├── .github
└── workflows
│ └── mypy.yml
├── .gitignore
├── Dec-2023.filelist
├── Dec-2023.tar.gz
├── LICENSE
├── Nov-2023.filelist
├── Nov-2023.tar.gz
├── Oct-2023.filelist
├── Oct-2023.tar.gz
├── README.md
├── api_query_cache
├── Anthropic_Eval_claude-3-opus-20240229_temp=0.0_cot=False_fs=5.tar.gz
├── Anthropic_Eval_claude-3-opus-20240229_temp=0.0_cot=True_fs=0.tar.gz
├── Anthropic_Eval_claude-3-opus-20240229_temp=0.0_cot=True_fs=5.tar.gz
├── Mistral_Eval_mistral-large-2402_temp=0.0_cot=False_fs=5.tar.gz
├── Mistral_Eval_mistral-large-2402_temp=0.0_cot=True_fs=0.tar.gz
├── Mistral_Eval_mistral-large-2402_temp=0.0_cot=True_fs=5.tar.gz
├── Mistral_Eval_mistral-medium-2312_temp=0.0_cot=False_fs=5.tar.gz
├── Mistral_Eval_mistral-medium-2312_temp=0.0_cot=True_fs=0.tar.gz
├── Mistral_Eval_mistral-medium-2312_temp=0.0_cot=True_fs=5.tar.gz
├── OAI_Eval_gpt-3.5-turbo_temp=0.0_cot=False_fs=5.tar.gz
├── OAI_Eval_gpt-3.5-turbo_temp=0.0_cot=True_fs=0.tar.gz
├── OAI_Eval_gpt-3.5-turbo_temp=0.0_cot=True_fs=5.tar.gz
├── OAI_Eval_gpt-4_temp=0.0_cot=False_fs=5.tar.gz
├── OAI_Eval_gpt-4_temp=0.0_cot=True_fs=0.tar.gz
├── OAI_Eval_gpt-4_temp=0.0_cot=True_fs=5.tar.gz
├── Together_Eval_Open-Orca_Mistral-7B-OpenOrca_temp=0.0_cot=False_fs=5.tar.gz
├── Together_Eval_Open-Orca_Mistral-7B-OpenOrca_temp=0.0_cot=True_fs=0.tar.gz
├── Together_Eval_Open-Orca_Mistral-7B-OpenOrca_temp=0.0_cot=True_fs=5.tar.gz
├── Together_Eval_Qwen_Qwen1.5-72B_temp=0.0_cot=False_fs=5.tar.gz
├── Together_Eval_Qwen_Qwen1.5-72B_temp=0.0_cot=True_fs=0.tar.gz
├── Together_Eval_Qwen_Qwen1.5-72B_temp=0.0_cot=True_fs=5.tar.gz
├── Together_Eval_allenai_OLMo-7B-Instruct_temp=0.0_cot=False_fs=5.tar.gz
├── Together_Eval_allenai_OLMo-7B-Instruct_temp=0.0_cot=True_fs=0.tar.gz
├── Together_Eval_allenai_OLMo-7B-Instruct_temp=0.0_cot=True_fs=5.tar.gz
├── Together_Eval_google_gemma-7b_temp=0.0_cot=False_fs=5.tar.gz
├── Together_Eval_google_gemma-7b_temp=0.0_cot=True_fs=0.tar.gz
├── Together_Eval_google_gemma-7b_temp=0.0_cot=True_fs=5.tar.gz
├── Together_Eval_meta-llama_Llama-2-70b-hf_temp=0.0_cot=False_fs=5.tar.gz
├── Together_Eval_meta-llama_Llama-2-70b-hf_temp=0.0_cot=True_fs=0.tar.gz
├── Together_Eval_meta-llama_Llama-2-70b-hf_temp=0.0_cot=True_fs=5.tar.gz
├── Together_Eval_microsoft_phi-2_temp=0.0_cot=False_fs=5.tar.gz
├── Together_Eval_microsoft_phi-2_temp=0.0_cot=True_fs=0.tar.gz
├── Together_Eval_microsoft_phi-2_temp=0.0_cot=True_fs=5.tar.gz
├── Together_Eval_togethercomputer_StripedHyena-Nous-7B_temp=0.0_cot=False_fs=5.tar.gz
├── Together_Eval_togethercomputer_StripedHyena-Nous-7B_temp=0.0_cot=True_fs=0.tar.gz
├── Together_Eval_togethercomputer_StripedHyena-Nous-7B_temp=0.0_cot=True_fs=5.tar.gz
├── Together_Eval_zero-one-ai_Yi-34B_temp=0.0_cot=False_fs=5.tar.gz
├── Together_Eval_zero-one-ai_Yi-34B_temp=0.0_cot=True_fs=0.tar.gz
└── Together_Eval_zero-one-ai_Yi-34B_temp=0.0_cot=True_fs=5.tar.gz
├── chain_of_thought.py
├── eval
├── __init__.py
├── measure_math.py
└── runner.py
├── evaluate.py
├── evaluated_models.json
├── few_shot.py
├── fn_snapshot.py
├── helper_utils.py
├── loader.py
├── math_utils
├── README.md
├── __init__.py
├── math_equivalence.py
└── math_helpers.py
├── model_api
├── __init__.py
├── ant.py
├── claude.py
├── closed_api.py
├── file_api.py
├── gpt.py
├── mis.py
├── mistral.py
├── oai.py
├── offline.py
├── oss.py
└── tog.py
├── monthly_snapshots.json
├── monthly_snapshots_only_oct.json
├── persist.py
├── query_cache.py
├── report
├── .gitignore
├── Makefile
├── all-coverage.pdf
├── all-levels.pdf
├── all-reasoning-gap.pdf
├── all-static-vs-func-accuracy.pdf
├── all-subjects.pdf
├── data_files.tar.gz
├── gpt4-by-level.pdf
├── gpt4-by-subject.pdf
├── gpt4-k=3-suffices.pdf
├── gpt4-levels.pdf
├── gpt4-reasoning-needed.pdf
├── gpt4-subjects.pdf
├── gpt4-surprise.pdf
├── main.tex
├── oss-by-level.pdf
├── oss-by-subject.pdf
├── oss-k=3-suffices.pdf
├── oss-reasoning-needed.pdf
├── oss-surprise.pdf
└── refs.bib
├── requirements.txt
├── summarize_evals.py
└── unformatted_llm.py
/.github/workflows/mypy.yml:
--------------------------------------------------------------------------------
1 | name: Typecheck fneval
2 |
3 | on:
4 | push:
5 | branches: [main]
6 | paths:
7 | - "**"
8 | - ".github/workflows/mypy.yml"
9 | pull_request:
10 | paths:
11 | - "**"
12 | - ".github/workflows/mypy.yml"
13 |
14 | jobs:
15 | build:
16 | runs-on: ubuntu-22.04
17 | strategy:
18 | matrix:
19 | python-version: [3.9]
20 |
21 | steps:
22 | - uses: actions/checkout@v2
23 | - name: Set up Python ${{ matrix.python-version }}
24 | uses: actions/setup-python@v1
25 | with:
26 | python-version: ${{ matrix.python-version }}
27 | - name: Install dependencies
28 | run: |
29 | python3 -m pip install types-tqdm
30 | python -m pip install --upgrade pip
31 | pip install -r requirements.txt
32 | pip install mypy flake8
33 | - name: Check types
34 | run: |
35 | # flake8 . --ignore E501,W503,W504,W505,E266
36 | mypy --check-untyped-defs --pretty .
37 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # save your api keys to this file, for convenient . ./api_keys.sh export
2 | api_keys.sh
3 |
4 | # source static dataset
5 | MATH.tar
6 | MATH/
7 |
8 | # untarred monthly snapshots
9 | Dec-2023/
10 | Nov-2023/
11 | Oct-2023/
12 |
13 | # caches (the saved snapshots can be checked in as .tar.gz, but no need for the untarred dirs)
14 | # with CoT and Few Shot
15 | api_query_cache/Anthropic_Eval_claude-3-opus-20240229_temp=0.0_cot=False_fs=5
16 | api_query_cache/Anthropic_Eval_claude-3-opus-20240229_temp=0.0_cot=True_fs=0
17 | api_query_cache/Anthropic_Eval_claude-3-opus-20240229_temp=0.0_cot=True_fs=5
18 | api_query_cache/OAI_Eval_gpt-3.5-turbo_temp=0.0_cot=False_fs=5
19 | api_query_cache/OAI_Eval_gpt-3.5-turbo_temp=0.0_cot=True_fs=0
20 | api_query_cache/OAI_Eval_gpt-3.5-turbo_temp=0.0_cot=True_fs=5
21 | api_query_cache/OAI_Eval_gpt-4_temp=0.0_cot=False_fs=5
22 | api_query_cache/OAI_Eval_gpt-4_temp=0.0_cot=True_fs=0
23 | api_query_cache/OAI_Eval_gpt-4_temp=0.0_cot=True_fs=5
24 | api_query_cache/Together_Eval_togethercomputer_StripedHyena-Nous-7B_temp=0.0_cot=False_fs=5
25 | api_query_cache/Together_Eval_togethercomputer_StripedHyena-Nous-7B_temp=0.0_cot=True_fs=0
26 | api_query_cache/Together_Eval_togethercomputer_StripedHyena-Nous-7B_temp=0.0_cot=True_fs=5
27 | api_query_cache/Together_Eval_Open-Orca_Mistral-7B-OpenOrca_temp=0.0_cot=False_fs=5
28 | api_query_cache/Together_Eval_Open-Orca_Mistral-7B-OpenOrca_temp=0.0_cot=True_fs=0
29 | api_query_cache/Together_Eval_Open-Orca_Mistral-7B-OpenOrca_temp=0.0_cot=True_fs=5
30 | api_query_cache/Together_Eval_zero-one-ai_Yi-34B_temp=0.0_cot=False_fs=5
31 | api_query_cache/Together_Eval_zero-one-ai_Yi-34B_temp=0.0_cot=True_fs=0
32 | api_query_cache/Together_Eval_zero-one-ai_Yi-34B_temp=0.0_cot=True_fs=5
33 | api_query_cache/Together_Eval_Qwen_Qwen1.5-72B_temp=0.0_cot=False_fs=5
34 | api_query_cache/Together_Eval_Qwen_Qwen1.5-72B_temp=0.0_cot=True_fs=0
35 | api_query_cache/Together_Eval_Qwen_Qwen1.5-72B_temp=0.0_cot=True_fs=5
36 | api_query_cache/Together_Eval_allenai_OLMo-7B-Instruct_temp=0.0_cot=False_fs=5
37 | api_query_cache/Together_Eval_allenai_OLMo-7B-Instruct_temp=0.0_cot=True_fs=0
38 | api_query_cache/Together_Eval_allenai_OLMo-7B-Instruct_temp=0.0_cot=True_fs=5
39 | api_query_cache/Together_Eval_google_gemma-7b_temp=0.0_cot=False_fs=5
40 | api_query_cache/Together_Eval_google_gemma-7b_temp=0.0_cot=True_fs=0
41 | api_query_cache/Together_Eval_google_gemma-7b_temp=0.0_cot=True_fs=5
42 | api_query_cache/Together_Eval_meta-llama_Llama-2-70b-hf_temp=0.0_cot=False_fs=5
43 | api_query_cache/Together_Eval_meta-llama_Llama-2-70b-hf_temp=0.0_cot=True_fs=0
44 | api_query_cache/Together_Eval_meta-llama_Llama-2-70b-hf_temp=0.0_cot=True_fs=5
45 | api_query_cache/Together_Eval_microsoft_phi-2_temp=0.0_cot=False_fs=5
46 | api_query_cache/Together_Eval_microsoft_phi-2_temp=0.0_cot=True_fs=0
47 | api_query_cache/Together_Eval_microsoft_phi-2_temp=0.0_cot=True_fs=5
48 | api_query_cache/Mistral_Eval_mistral-large-2402_temp=0.0_cot=False_fs=5
49 | api_query_cache/Mistral_Eval_mistral-large-2402_temp=0.0_cot=True_fs=0
50 | api_query_cache/Mistral_Eval_mistral-large-2402_temp=0.0_cot=True_fs=5
51 | api_query_cache/Mistral_Eval_mistral-medium-2312_temp=0.0_cot=False_fs=5
52 | api_query_cache/Mistral_Eval_mistral-medium-2312_temp=0.0_cot=True_fs=5
53 | api_query_cache/Mistral_Eval_mistral-medium-2312_temp=0.0_cot=True_fs=0
54 |
55 | # OLD
56 | # api_query_cache/Anthropic_Eval_claude-2.1/
57 | # api_query_cache/Mistral_Eval_mistral-medium/
58 | # api_query_cache/OAI_Eval_davinci/
59 | # api_query_cache/OAI_Eval_gpt-3.5-turbo/
60 | # api_query_cache/OAI_Eval_gpt-4/
61 | # api_query_cache/Together_Eval_EleutherAI_llemma_7b/
62 | # api_query_cache/Together_Eval_WizardLM_WizardCoder-Python-34B-V1.0/
63 | # api_query_cache/Together_Eval_mistralai_Mixtral-8x7B-Instruct-v0.1/
64 | # api_query_cache/Together_Eval_mistralai_Mixtral-8x7B-v0.1/
65 | # api_query_cache/Together_Eval_togethercomputer_Qwen-7B/
66 | # api_query_cache/Together_Eval_togethercomputer_StripedHyena-Hessian-7B/
67 | # api_query_cache/Together_Eval_togethercomputer_StripedHyena-Nous-7B/
68 | # api_query_cache/Together_Eval_togethercomputer_llama-2-70b/
69 | # api_query_cache/Together_Eval_zero-one-ai_Yi-34B-Chat/
70 | # api_query_cache/Together_Eval_zero-one-ai_Yi-34B/
71 |
72 | # output of individual evals, intermediate from eval/measure_math.py
73 | intermediate
74 |
75 | # individual test results from model evals; output of evaluate.py
76 | *.json.pickle
77 |
78 | # output of summarize_evals.py
79 | *.json.pickle.*
80 |
81 | # mac
82 | .DS_Store
83 |
84 | # pycache
85 | __pycache__
86 |
87 | # vim swaps
88 | *.swp
89 |
--------------------------------------------------------------------------------
/Dec-2023.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/Dec-2023.tar.gz
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Nov-2023.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/Nov-2023.tar.gz
--------------------------------------------------------------------------------
/Oct-2023.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/Oct-2023.tar.gz
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Functional Benchmarks and Reasoning Gap
3 |
4 | This repository accompanies the paper
5 | [Functional Benchmarks for Robust Evaluation of Reasoning Performance,
6 | and the Reasoning Gap](https://arxiv.org/abs/2402.19450)
7 |
8 | Summary tweet threads:
9 | [Without CoT](https://twitter.com/_saurabh/status/1763626711407816930),
10 | and [with CoT](https://twitter.com/_saurabh/status/1769852207925805080).
11 |
12 | ---
13 |
14 | **Note (Feb'24): This repo and associated paper will not be finalized until the
15 | Q2'24 release. We are working to get 100% coverage over MATH and GSM8K. We are
16 | releasing the first version (Q1'24) for early access to the community.**
17 |
18 | # Overview
19 | We propose a way to evaluate reasoning capabilities of models that could have
20 | been trained on the entire (compressed on uncompressed) text of the internet,
21 | and possibly retrieval augmented.
22 |
23 | We rewrite each benchmark question, in parameterized functional form, such that
24 | the reasoning involved in solving each instance is identical, but the question
25 | and answer are textually distinct each time. We snapshot a new instance of the
26 | entire benchmark each month. A model has to solve the last K instances
27 | correctly to count as correctly reasoning through that question. We notate
28 | these functionalized versions of the benchmarks with "()", e.g., "MATH()" for
29 | the "MATH" benchmark.
30 |
31 | For each model the evaluation script tabulates:
32 | * Static accuracy: accuracy on the static benchmark (e.g., MATH).
33 | * Functional accuracy: accuracy over the last K instances of the functional benchmark
34 | (e.g., MATH()) and the static benchmark.
35 | * Reasoning Gap: Percent drop from static to functional.
36 | * Hallucination [0,100]: Percent times incorrect solution output, instead
37 | of stating no solution.
38 |
39 | # Run (with external API calls)
40 | Export the following keys:
41 | ```
42 | export OPENAI_ORG="org-..."
43 | export OPENAI_API_KEY="sk-..."
44 | export ANTHROPIC_API_KEY="sk-..."
45 | export TOGETHER_API_KEY="..."
46 | export MISTRAL_API_KEY="..."
47 | export HUGGING_FACE_HUB_TOKEN="hf_..."
48 | ```
49 |
50 | After exporting the API keys, run:
51 | ```
52 | python3 -m evaluate
53 |
54 | # compute accuracies for static/functional (or run with just --stat_fn to see all available stats)
55 | python3 -m summarize_evals --stat_fn stat_accuracy
56 | ```
57 |
58 | # Run (offline, with manual model completions)
59 | If you have an internal model that cannot be called via API, then it might be best to dump out all prompts to JSON, and complete them offline and bring them back into the harness. There is a fake api called `model_api/offline.py` that lets you do that.
60 |
61 | Create two model spec JSONs, one for writing prompts, and one for reading completions
62 |
63 | Writing prompts `evaluated_models_write_qs.json` should look like:
64 | ```
65 | [ { "name": "your-local-model", "script": "model_api/offline.py", "include": true, "CoT": false, "extra_params": "{\"write_qs\": true}" } ]
66 | ```
67 | Reading completions `evaluated_models.json` should look like:
68 | ```
69 | [ { "name": "your-local-model", "script": "model_api/offline.py", "include": true, "CoT": false } ]
70 | ```
71 |
72 | ```
73 | # dump prompts
74 | python -m evaluate --model_specs evaluated_models_write_qs.json
75 |
76 | # run your local model and complete each of the prompts in the output JSON
77 | # create a new JSON by adding the completions as a "completion" field in the prompts JSON
78 |
79 | # run completions
80 | python3 -m evaluate --model_specs evaluated_models.json # this step is not fully implemented in the code
81 |
82 | # compute accuracies for static/functional (or run with just --stat_fn to see all available stats)
83 | python3 -m summarize_evals --stat_fn stat_accuracy
84 | ```
85 |
86 | # FAQs
87 |
88 | 1. Why do the accuracy numbers differ from the best reported for the models?
89 | We have not optimized for getting the best reported accuracy for each model,
90 | and we likely will not do that. The best reported might need undisclosed
91 | prompting, or post-processing.
92 | We conjecture that the overall conclusions about reasoning gap presence
93 | will not change.
94 |
95 | 1. Open question: pass@k and maj@k increase topline performance, but do they
96 | increase or decrease the reasoning gap?
97 | Work-in-progress. Requires 100% MATH coverage.
98 |
99 | 1. Why is the GPT4 number not 78.2% as reported in the [Let's why step by
100 | step](https://arxiv.org/abs/2305.20050) paper?
101 | As mentioned in their repository section [MATH
102 | Splits](https://github.com/openai/prm800k#math-splits) and in the paper, their
103 | evaluation is non-standard: "In order to avoid the risk of over-fitting on the
104 | 7,500 MATH training problems, we expanded the training set to include 4,500
105 | MATH test split problems. We therefore evaluate our models only on the
106 | remaining 500 held-out problems. We selected these 500 test problems uniformly
107 | at random, and we believe they are representative of the test set as a whole."
108 | For the 500 representative problems they pick PRM, ORM, and Majority Voting get
109 | 78.2%, 72.4% and 69.6% when using best-of-1860 (Figure 3).
110 |
111 | # Known Issues
112 | * More liberal output math equivalence matching. E.g., `C(21,7)` instead of `116280`
113 | (Claude non-CoT); `9 choose 2 = 36` instead of `36` (Mixtral non-CoT).
114 | * Functional instantiations can sometimes result in problems or answers that
115 | are too long. E.g., in one of the instantiations in the `Dec-2023` snapshot a
116 | benchmark's output number has more than 40 digits.
117 |
118 | # Citation
119 |
120 | @misc{srivastava2024functional,
121 | title={Functional Benchmarks for Robust Evaluation of Reasoning Performance, and the Reasoning Gap},
122 | author={Saurabh Srivastava and Annarose M B and Anto P V au2 and Shashank Menon and Ajay Sukumar and Adwaith Samod T and Alan Philipose and Stevin Prince and Sooraj Thomas},
123 | year={2024},
124 | eprint={2402.19450},
125 | archivePrefix={arXiv},
126 | primaryClass={cs.AI}
127 | }
128 |
--------------------------------------------------------------------------------
/api_query_cache/Anthropic_Eval_claude-3-opus-20240229_temp=0.0_cot=False_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Anthropic_Eval_claude-3-opus-20240229_temp=0.0_cot=False_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Anthropic_Eval_claude-3-opus-20240229_temp=0.0_cot=True_fs=0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Anthropic_Eval_claude-3-opus-20240229_temp=0.0_cot=True_fs=0.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Anthropic_Eval_claude-3-opus-20240229_temp=0.0_cot=True_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Anthropic_Eval_claude-3-opus-20240229_temp=0.0_cot=True_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Mistral_Eval_mistral-large-2402_temp=0.0_cot=False_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Mistral_Eval_mistral-large-2402_temp=0.0_cot=False_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Mistral_Eval_mistral-large-2402_temp=0.0_cot=True_fs=0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Mistral_Eval_mistral-large-2402_temp=0.0_cot=True_fs=0.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Mistral_Eval_mistral-large-2402_temp=0.0_cot=True_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Mistral_Eval_mistral-large-2402_temp=0.0_cot=True_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Mistral_Eval_mistral-medium-2312_temp=0.0_cot=False_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Mistral_Eval_mistral-medium-2312_temp=0.0_cot=False_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Mistral_Eval_mistral-medium-2312_temp=0.0_cot=True_fs=0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Mistral_Eval_mistral-medium-2312_temp=0.0_cot=True_fs=0.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Mistral_Eval_mistral-medium-2312_temp=0.0_cot=True_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Mistral_Eval_mistral-medium-2312_temp=0.0_cot=True_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/OAI_Eval_gpt-3.5-turbo_temp=0.0_cot=False_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/OAI_Eval_gpt-3.5-turbo_temp=0.0_cot=False_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/OAI_Eval_gpt-3.5-turbo_temp=0.0_cot=True_fs=0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/OAI_Eval_gpt-3.5-turbo_temp=0.0_cot=True_fs=0.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/OAI_Eval_gpt-3.5-turbo_temp=0.0_cot=True_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/OAI_Eval_gpt-3.5-turbo_temp=0.0_cot=True_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/OAI_Eval_gpt-4_temp=0.0_cot=False_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/OAI_Eval_gpt-4_temp=0.0_cot=False_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/OAI_Eval_gpt-4_temp=0.0_cot=True_fs=0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/OAI_Eval_gpt-4_temp=0.0_cot=True_fs=0.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/OAI_Eval_gpt-4_temp=0.0_cot=True_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/OAI_Eval_gpt-4_temp=0.0_cot=True_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_Open-Orca_Mistral-7B-OpenOrca_temp=0.0_cot=False_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_Open-Orca_Mistral-7B-OpenOrca_temp=0.0_cot=False_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_Open-Orca_Mistral-7B-OpenOrca_temp=0.0_cot=True_fs=0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_Open-Orca_Mistral-7B-OpenOrca_temp=0.0_cot=True_fs=0.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_Open-Orca_Mistral-7B-OpenOrca_temp=0.0_cot=True_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_Open-Orca_Mistral-7B-OpenOrca_temp=0.0_cot=True_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_Qwen_Qwen1.5-72B_temp=0.0_cot=False_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_Qwen_Qwen1.5-72B_temp=0.0_cot=False_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_Qwen_Qwen1.5-72B_temp=0.0_cot=True_fs=0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_Qwen_Qwen1.5-72B_temp=0.0_cot=True_fs=0.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_Qwen_Qwen1.5-72B_temp=0.0_cot=True_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_Qwen_Qwen1.5-72B_temp=0.0_cot=True_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_allenai_OLMo-7B-Instruct_temp=0.0_cot=False_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_allenai_OLMo-7B-Instruct_temp=0.0_cot=False_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_allenai_OLMo-7B-Instruct_temp=0.0_cot=True_fs=0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_allenai_OLMo-7B-Instruct_temp=0.0_cot=True_fs=0.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_allenai_OLMo-7B-Instruct_temp=0.0_cot=True_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_allenai_OLMo-7B-Instruct_temp=0.0_cot=True_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_google_gemma-7b_temp=0.0_cot=False_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_google_gemma-7b_temp=0.0_cot=False_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_google_gemma-7b_temp=0.0_cot=True_fs=0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_google_gemma-7b_temp=0.0_cot=True_fs=0.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_google_gemma-7b_temp=0.0_cot=True_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_google_gemma-7b_temp=0.0_cot=True_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_meta-llama_Llama-2-70b-hf_temp=0.0_cot=False_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_meta-llama_Llama-2-70b-hf_temp=0.0_cot=False_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_meta-llama_Llama-2-70b-hf_temp=0.0_cot=True_fs=0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_meta-llama_Llama-2-70b-hf_temp=0.0_cot=True_fs=0.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_meta-llama_Llama-2-70b-hf_temp=0.0_cot=True_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_meta-llama_Llama-2-70b-hf_temp=0.0_cot=True_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_microsoft_phi-2_temp=0.0_cot=False_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_microsoft_phi-2_temp=0.0_cot=False_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_microsoft_phi-2_temp=0.0_cot=True_fs=0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_microsoft_phi-2_temp=0.0_cot=True_fs=0.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_microsoft_phi-2_temp=0.0_cot=True_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_microsoft_phi-2_temp=0.0_cot=True_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_togethercomputer_StripedHyena-Nous-7B_temp=0.0_cot=False_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_togethercomputer_StripedHyena-Nous-7B_temp=0.0_cot=False_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_togethercomputer_StripedHyena-Nous-7B_temp=0.0_cot=True_fs=0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_togethercomputer_StripedHyena-Nous-7B_temp=0.0_cot=True_fs=0.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_togethercomputer_StripedHyena-Nous-7B_temp=0.0_cot=True_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_togethercomputer_StripedHyena-Nous-7B_temp=0.0_cot=True_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_zero-one-ai_Yi-34B_temp=0.0_cot=False_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_zero-one-ai_Yi-34B_temp=0.0_cot=False_fs=5.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_zero-one-ai_Yi-34B_temp=0.0_cot=True_fs=0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_zero-one-ai_Yi-34B_temp=0.0_cot=True_fs=0.tar.gz
--------------------------------------------------------------------------------
/api_query_cache/Together_Eval_zero-one-ai_Yi-34B_temp=0.0_cot=True_fs=5.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/api_query_cache/Together_Eval_zero-one-ai_Yi-34B_temp=0.0_cot=True_fs=5.tar.gz
--------------------------------------------------------------------------------
/chain_of_thought.py:
--------------------------------------------------------------------------------
1 | # Ref: Chain-of-Thought Prompting Elicits Reasoning in Large Language Models https://arxiv.org/abs/2201.11903
2 | # TODO, v2 implement option to use different prompting:
3 | # Ref: Lewkowycz’ 2022 https://arxiv.org/pdf/2206.14858.pdf
4 | # Ref: Section 9.7.6 of the Gemini 1.5 whitepaper: https://arxiv.org/pdf/2403.05530.pdf
5 |
6 | from typing import Dict, List, Tuple
7 | from math_utils.math_helpers import rm_latex_math
8 | from few_shot import CoTFewShotAnswerSamples, FewShotBuilder
9 | from helper_utils import NO_SOLUTION_PREFIX
10 |
11 | PREAMBLE = "Answer the MATH query below. " \
12 | f"If the answer cannot be computed, or you are not confident, say {NO_SOLUTION_PREFIX}. "
13 | COT_PROMPT = "Think step by step. "
14 | ANSWER_TAG = "The answer is: "
15 | END_WITH_ANSWER = f"End the answer with \"{ANSWER_TAG} \" followed by only the answer you compute and no extra words.\n"
16 |
17 | COT_INSTRUCTION = PREAMBLE + COT_PROMPT + END_WITH_ANSWER
18 |
19 | class ChainOfThought(FewShotBuilder):
20 | def __init__(self):
21 | mk_io = lambda fs: (fs.prb, fs.sol + '\n' + ANSWER_TAG + rm_latex_math(fs.outcome))
22 | self.few_shot_io: List[Tuple[str, str]] = [ mk_io(fs) for fs in CoTFewShotAnswerSamples ]
23 |
24 | def few_shot_limited(self, count: int) -> Dict[str, str]:
25 | limited_samples = self.few_shot_io[:count] if count != -1 else self.few_shot_io
26 | return dict(limited_samples)
27 |
28 | def extract_answer(self, answer):
29 | # locate the first ANSWER_TAG
30 | ans_index = answer.find(ANSWER_TAG)
31 | extracted = answer[ans_index + len(ANSWER_TAG):] if ans_index != -1 else ''
32 |
33 | # expecting only a single line in the answer
34 | empty_line = extracted.find('\n')
35 | extracted = extracted[:empty_line] if empty_line != -1 else extracted
36 |
37 | # remove any whitespaces, and any ending periods
38 | extracted = extracted.strip()
39 | extracted = extracted[:-1] if extracted.endswith('.') else extracted
40 |
41 | # Most of time this processing works:
42 | # The answer is: $68/125$.
43 | # The answer is: $\frac{\pi}{4}$
44 | # The answer is: 165.
45 | # The answer is: 6
46 |
47 | # But then there are other models insists on outputting english; or other extraneous tokens:
48 | # The answer is: $n=5$.
49 | # The answer is: The probability that Phil and Sarah get the same number is $\frac{3}{10}$ or 0.3 or 30%.
50 | # The answer is: There are 28 ways for Mary to put the 6 identical basil plants on the 3 window sills
51 | # The answer is: 3/8 or approximately 0.375.
52 | # The answer is: 18/343
53 | # The answer is: The probability is approximately 0.2616 or about 26.16%.
54 | # The answer is: 1 slice has both pepperoni and mushrooms.
55 | # The answer is: 110 students take physics.
56 |
57 | verbose = False
58 | console_confirm = False
59 |
60 | if console_confirm:
61 | print(f'\n---------------\n')
62 | print(f'From:{answer}')
63 | print(f'\n---------------\n')
64 | print(f'Extracted: {extracted}')
65 | print(f'\n---------------\n')
66 | input('Continue? ')
67 | if verbose:
68 | if ' ' in extracted:
69 | print(f'Extracted: {extracted}')
70 | if not extracted:
71 | print(f'Missing extraction; no answer tag; likely exceeded token length.')
72 |
73 | return extracted
74 |
--------------------------------------------------------------------------------
/eval/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/eval/__init__.py
--------------------------------------------------------------------------------
/eval/measure_math.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | import os
3 | import csv
4 | import json
5 | from math_utils.math_helpers import clean_numbers, last_boxed_only # these are unused; why?
6 | from math_utils.math_helpers import last_boxed_only_string, remove_boxed
7 | from math_utils.math_equivalence import is_equiv
8 | from helper_utils import NO_SOLUTION_PREFIX
9 | import numpy as np
10 | from typing import Dict, Any, List, Tuple, Optional
11 | from pathlib import Path
12 | from fn_snapshot import FnSnapshot, root_test
13 | from tqdm import tqdm
14 |
15 | INTERMEDIATES_DIR = "intermediate"
16 | PREFIX_FN_SOLVED = os.path.join(INTERMEDIATES_DIR, "functionals_solved_")
17 | PREFIX_ANSWERS = os.path.join(INTERMEDIATES_DIR, "answers_")
18 | PREFIX_CORRECT = os.path.join(INTERMEDIATES_DIR, "correct_")
19 |
20 | if not os.path.exists(INTERMEDIATES_DIR):
21 | os.makedirs(INTERMEDIATES_DIR)
22 |
23 | # these should match functional-math/functional/regression/instantiate.py
24 | FN_SOLVED_STATIC_UNSOLVED = 'FN_SOLVED_STATIC_UNSOLVED'
25 | FN_SOLVED_STATIC_SOLVED = 'FN_SOLVED_STATIC_SOLVED'
26 |
27 | DELIM = "#" * 80 + "\n"
28 | SUBJECTS = [
29 | 'Prealgebra',
30 | 'Algebra',
31 | 'Number Theory',
32 | 'Counting & Probability',
33 | 'Geometry',
34 | 'Intermediate Algebra',
35 | 'Precalculus'
36 | ]
37 |
38 |
39 | class TestMetric:
40 | def __init__(self, correct, frac_correct, output, completion, answer, typ, level, is_static, fname):
41 | # evaluation output and result
42 | self.correct = correct
43 | self.fraction_correct = frac_correct
44 | self.output = output
45 | self.answer = answer
46 | self.raw_completion = completion
47 |
48 | # identification data
49 | self.type = typ
50 | self.level = level
51 | self.is_static = is_static
52 | self.fname = os.path.join(*Path(fname).parts[-2:]) # `subject/id.json`
53 |
54 | def __repr__(self):
55 | s = f"CORRECT: {self.correct} | TYPE: {self.type} | LEVEL: {self.level} | OUTPUT: {self.output} | ANSWER: {self.answer} | STATIC: {self.is_static} | FNAME: {self.fname}"
56 | return s
57 |
58 | def __repr_concise__(self):
59 | s = f'{self.correct} | {self.output} | GT: {self.answer} | STATIC: {self.is_static} | {self.fname}'
60 | return s
61 |
62 | @classmethod
63 | def consensus(cls, many: List[TestMetric]) -> TestMetric:
64 | first = many[0]
65 | agree = lambda field: all(field(first) == field(m) for m in many)
66 | assert agree(lambda x: x.type), f'Differs on `type`: {many}'
67 | assert agree(lambda x: x.level), f'Differs on `level`: {many}'
68 | assert agree(lambda x: x.is_static), f'Differs on `is_static`: {many}'
69 | assert agree(lambda x: x.fname), f'Differs on `fname`: {many}'
70 |
71 | t, l, s, f = first.type, first.level, first.is_static, first.fname
72 |
73 | # if all correct then doesn't matter, we'll default to the first of the many
74 | assign = lambda x: (x.output, x.raw_completion, x.answer)
75 | valid, o, c, a = True, *assign(first)
76 | for m in many:
77 | if not m.correct:
78 | valid, o, c, a = False, *assign(m)
79 | break
80 | frac_valid = [m.correct for m in many].count(True) / float(len(many))
81 | return TestMetric(valid, frac_valid, o, c, a, t, l, s, f)
82 |
83 |
84 | class Metrics:
85 | def __init__(self):
86 | self.individuals: List[TestMetric] = []
87 | self.name = None
88 |
89 | self.cors: Dict[Any, Any] = {}
90 | self.subject_cors: Dict[Any, Any] = {}
91 | self.level_cors: Dict[Any, Any] = {}
92 | self.correct = 0
93 | self.total = 0
94 | self.total_incorrect = 0
95 | self.hallucinated = 0
96 |
97 | def update_with(self, rslt: TestMetric):
98 | self.individuals.append(rslt)
99 | equiv = rslt.correct
100 | prob_level = rslt.level
101 | prob_type = rslt.type
102 |
103 | # update subject and level corrects
104 | if (prob_level, prob_type) in self.cors:
105 | self.cors[(prob_level, prob_type)].append(equiv)
106 | else:
107 | self.cors[(prob_level, prob_type)] = [equiv]
108 | if prob_level in self.level_cors:
109 | self.level_cors[prob_level].append(equiv)
110 | else:
111 | if prob_level is not None:
112 | self.level_cors[prob_level] = [equiv]
113 | if prob_type in self.subject_cors:
114 | self.subject_cors[prob_type].append(equiv)
115 | else:
116 | if prob_type is not None:
117 | self.subject_cors[prob_type] = [equiv]
118 |
119 | # update correct/total counts
120 | if equiv:
121 | self.correct += 1
122 | self.total += 1
123 |
124 | # update hallucinations count
125 | if not equiv:
126 | lowered_answer = rslt.output.lower().strip()
127 | no_soln_prefix = NO_SOLUTION_PREFIX.lower()
128 | says_dont_know = lowered_answer.startswith(no_soln_prefix)
129 | if not says_dont_know:
130 | self.hallucinated += 1
131 | self.total_incorrect += 1
132 |
133 | def accuracy(self):
134 | return self.correct, self.total
135 |
136 | def hallucinations(self):
137 | return self.hallucinated, self.total_incorrect
138 |
139 | def stats_legend(self):
140 | return "[A]ccuracy, [H]allucination"
141 |
142 | def stats(self):
143 | def stat_str(num: int, dim: int) -> str:
144 | pc = 100.0 * (num / float(dim) if dim else 0.0)
145 | return f'{num:04d}/{dim:04d} = {pc:5.2f}%'
146 |
147 | return f"A: {stat_str(*self.accuracy())}"\
148 | f" | H: {stat_str(*self.hallucinations())}"
149 |
150 | def save_and_log(self, tested_functionally: Dict[TestMetric, TestMetric], model_name: str, verbose):
151 | console = []
152 | filelog = []
153 |
154 | for s, f in tested_functionally.items():
155 | # default - functional unsolved; static solved; or both unsolved
156 | log: Optional[str] = None
157 | row: Optional[Any] = None
158 | if f.correct:
159 | if s.correct:
160 | log = f'[INFO] TOO SIMPLE? - functional solved: {s.fname} at Level {s.level}'
161 | row = [s.fname, FN_SOLVED_STATIC_SOLVED, s.level]
162 | else:
163 | log = f'[WARN] UNEXPECTED - functional solved; static unsolved: {s.fname}'
164 | row = [s.fname, FN_SOLVED_STATIC_UNSOLVED, s.level]
165 | console.append(log)
166 | filelog.append(row)
167 |
168 | solved_fns_file = f'{PREFIX_FN_SOLVED}{model_name}.csv'
169 | with open(solved_fns_file, 'w') as cf:
170 | csvwriter = csv.writer(cf)
171 | for l in filelog:
172 | if l is not None:
173 | csvwriter.writerow(l)
174 |
175 | if verbose:
176 | console_lines = "\n".join(c for c in console if c is not None)
177 | print(f'{console_lines}')
178 | print(f'written solved functionals to {solved_fns_file}')
179 |
180 | # print stats
181 | cases = [case for _, case, _ in [row for row in filelog if row]]
182 | s_f_correct = cases.count(FN_SOLVED_STATIC_SOLVED)
183 | s_incorrect_f_correct = cases.count(FN_SOLVED_STATIC_UNSOLVED)
184 | print(f'[STATS] tested functionally: {len(tested_functionally)}, correct f+s: {s_f_correct} (counts towards accuracy), correct f+!s: {s_incorrect_f_correct} (does not count)')
185 |
186 | def get_overriden(self, func: Metrics, verbose: bool) -> Dict[TestMetric, Optional[TestMetric]]:
187 | if verbose:
188 | statics = set(f.fname for f in func.individuals if f.is_static)
189 | print(f'[STATS] statics in the functional set: {len(statics)} (if 0 then snapshot might have been taken without include_static = True)')
190 |
191 | matching = lambda ident: [f for f in func.individuals if f.fname == ident and not f.is_static]
192 | overriden = {}
193 | for s in self.individuals:
194 | matches = matching(s.fname)
195 | if len(matches) > 1:
196 | print(f'More than one functional for {s.fname}. Picking first')
197 | overriden[s] = matches[0] if matches else None
198 | return overriden
199 |
200 | def with_functional(self, func: Metrics, model_name: str, verbose: bool) -> Tuple[Metrics, Metrics]:
201 | overriden: Dict[TestMetric, Optional[TestMetric]] = self.get_overriden(func, verbose)
202 | with_fn = Metrics()
203 | of_static_correct_fn_correct = Metrics()
204 | tested_functionally: Dict[TestMetric, TestMetric] = {}
205 | total_correct, functionalized_correct = 0, 0
206 | f_none_count_s_correct = 0
207 | for s, f in overriden.items():
208 |
209 | if f is None:
210 | # update accumulator: only static available, so keep that
211 | with_fn.update_with(s)
212 | if s.correct:
213 | f_none_count_s_correct += 1
214 |
215 | else:
216 | # update accumulator: both s & f available
217 | # - case: both correct or both false, storing s/f is identical
218 | # - case: one of them is false, keep the false one; since we want to be strict
219 | # summary: if s is incorrect store that, otherwise store whatever f's outcome was
220 | if not s.correct:
221 | with_fn.update_with(s)
222 | else:
223 | with_fn.update_with(f)
224 |
225 | # s is correct, and f is not None
226 | # store this as the functional test for when static correct
227 | of_static_correct_fn_correct.update_with(f)
228 |
229 | # for ones overriden, put them in tested_functionally, so we can log to console and file
230 | tested_functionally[s] = f
231 |
232 | if verbose:
233 | print(f'[STATS] statics correct, for which no functional: {f_none_count_s_correct} (counts towards accuracy)')
234 |
235 | with_fn.name = f'{self.name}\\{func.name}'
236 | self.save_and_log(tested_functionally, model_name, verbose)
237 |
238 | return with_fn, of_static_correct_fn_correct
239 |
240 | @classmethod
241 | def consensus(cls, many: List[Metrics]) -> Metrics:
242 | find = lambda fname, m: next(tm for tm in m.individuals if tm.fname == fname)
243 | idents = lambda i: set(tm.fname for tm in many[i].individuals)
244 | ref_idents = idents(0)
245 | assert all(ref_idents == idents(i) for i in range(1, len(many))), f'idents differ'
246 | by_name: Dict[str, List[TestMetric]] = { f: [find(f, m) for m in many] for f in ref_idents }
247 | cs: Dict[str, TestMetric] = { f: TestMetric.consensus(ltm) for f, ltm in by_name.items() }
248 |
249 | aggr = Metrics()
250 | aggr.name = "+".join([f'{m.name}' for m in many])
251 | for c in cs.values():
252 | aggr.update_with(c)
253 | return aggr
254 |
255 | class Eval:
256 | def __init__(self, solve_fn, fn_snapshots, model_name, verbose = False):
257 | self.verbose = verbose
258 | self.problems_tested = []
259 | self.static_metrics, self.func_metrics = self.get_metrics(solve_fn, fn_snapshots, model_name)
260 |
261 | # report combined metrics
262 | combined, _ = self.static_metrics.with_functional(self.func_metrics, model_name, verbose)
263 | self.report_stats(combined)
264 |
265 | if not os.path.exists(INTERMEDIATES_DIR):
266 | os.makedirs(INTERMEDIATES_DIR)
267 |
268 | def get_metrics(self, solve_fn, fn_snapshots, model_name) -> Tuple[Metrics, Metrics]:
269 | static_metrics = None
270 | multiple_func_metrics = []
271 | for snapshot in fn_snapshots:
272 | # download and setup directories `ROOT/test/subject/id.json`
273 | root = snapshot.ensure_dataset()
274 |
275 | # location
276 | test_dir = root_test(root)
277 | tag = snapshot.date
278 | out_answers_to = f'{PREFIX_ANSWERS}{model_name}-{tag}'
279 | correct_dir = f'{PREFIX_CORRECT}{model_name}-{tag}'
280 |
281 | # eval over snapshot
282 | metrics = self.run_eval(tag, test_dir, solve_fn, out_answers_to)
283 |
284 | # log to data dirs
285 | self.write_correct_completions(metrics, correct_dir)
286 |
287 | # keep static aside, and put all functionals into list
288 | if snapshot.is_static():
289 | static_metrics = metrics
290 | else:
291 | multiple_func_metrics.append(metrics)
292 |
293 | func_metrics = Metrics.consensus(multiple_func_metrics)
294 | assert static_metrics, f'No static metrics!'
295 | return static_metrics, func_metrics
296 |
297 | def get_solved(self, only_static: bool = False) -> List[str]:
298 | names = lambda mm: set(tm.fname for tm in mm.individuals if tm.correct)
299 | s, f = names(self.static_metrics), names(self.func_metrics)
300 | return list(s if only_static else s.intersection(f))
301 |
302 | def report_stats(self, m: Metrics):
303 | print(DELIM)
304 | print(f'Legend: {m.stats_legend()}')
305 | print(f'{m.name}: {m.stats()}')
306 | print(DELIM)
307 |
308 | def run_eval(self, name, root, solve_fn, out_answers_file):
309 | metrics = self.eval_test_files(root, solve_fn)
310 | metrics.name = name
311 | self.write_results_file(metrics, out_answers_file)
312 | return metrics
313 |
314 | def eval_test_files(self, root, solve_fn) -> Metrics:
315 | m = Metrics()
316 |
317 | for subdir, dirs, files in os.walk(root):
318 | enum_files = files if self.verbose else tqdm(files, desc = subdir)
319 | for file in enum_files: # type: ignore
320 |
321 | fname = os.path.join(subdir, file)
322 | with open(fname, 'r') as fp:
323 | self.eval_test_data(fname, fp, m, solve_fn)
324 | return m
325 |
326 | def compare_answer(self, ref, solns: List[Tuple[str, str]]) -> Tuple[bool, str, str]:
327 | def eq(t):
328 | try:
329 | return is_equiv(t, ref)
330 | except:
331 | return False
332 |
333 | def pick_best(many_solns: List[Tuple[bool, str, str]]) -> Tuple[bool, str, str]:
334 | return many_solns[0]
335 |
336 | equivs = [(eq(t), t, c) for t, c in solns]
337 | return pick_best(equivs)
338 |
339 | def eval_test_data(self, fname, fp, m, solve_fn) -> None:
340 | try:
341 | problem_data = json.load(fp)
342 | except Exception as e:
343 | print(f"Error loading JSON from {fname}", e)
344 | raise e
345 | prob_level = problem_data["level"]
346 | prob_type = problem_data["type"]
347 | try:
348 | prob_level = int(prob_level.split("Level ")[1])
349 | except:
350 | prob_level = None
351 | prb = problem_data["problem"]
352 | soln = problem_data["solution"]
353 | ref_answer = remove_boxed(last_boxed_only_string(soln))
354 | is_static = problem_data["is_static"] if "is_static" in problem_data else True
355 |
356 | # ask model to solve problem
357 | solns: List[Tuple[str, str]] = solve_fn(prb)
358 | equiv, text_answer, completion = self.compare_answer(ref_answer, solns)
359 | frac_correct = 1.0 if equiv else 0.0
360 |
361 | prb_tested = {
362 | 'problem': prb,
363 | 'reference solution': ref_answer,
364 | 'is_static': is_static,
365 | 'level': prob_level,
366 | 'type': prob_type,
367 | 'fname': fname,
368 | }
369 | self.problems_tested.append(prb_tested)
370 | rslt = TestMetric(
371 | correct = equiv,
372 | frac_correct = frac_correct,
373 | output = text_answer,
374 | completion = completion,
375 | answer = ref_answer,
376 | typ = prob_type,
377 | level = prob_level,
378 | is_static = is_static,
379 | fname = fname,
380 | )
381 | m.update_with(rslt)
382 |
383 | running = m.stats() # percentages accuracy/hallucinations
384 | test_summary = rslt.__repr_concise__()
385 | if self.verbose:
386 | print(f'{running} | {test_summary}')
387 |
388 | def out(self, f, line):
389 | f.write(line + "\n")
390 | if self.verbose:
391 | print(line)
392 |
393 | def write_each_test_results(self, m, f):
394 | for k, t in enumerate(m.individuals):
395 | line = f"{k} {t}"
396 | self.out(f, line)
397 |
398 | def pc(self, cors_list):
399 | return np.sum(cors_list), len(cors_list), 100.0 * np.mean(cors_list)
400 |
401 | def write_level_accuracies(self, m, f):
402 | self.out(f, DELIM)
403 | for level in sorted(m.level_cors):
404 | if level not in m.level_cors.keys():
405 | continue
406 | cors_list = m.level_cors[level]
407 | line = "Level {} Accuracy = {}/{} = {:5.2f}%".format(level, *self.pc(cors_list))
408 | self.out(f, line)
409 | self.out(f, DELIM)
410 |
411 | def write_subject_accuracies(self, m, f):
412 | self.out(f, DELIM)
413 | for subject in SUBJECTS:
414 | if subject not in m.subject_cors.keys():
415 | continue
416 | cors_list = m.subject_cors[subject]
417 | line = "{} Accuracy = {}/{} = {:5.2f}%".format(subject, *self.pc(cors_list))
418 | self.out(f, line)
419 | self.out(f, DELIM)
420 |
421 | def write_subject_level_accuracies(self, m, f):
422 | self.out(f, DELIM)
423 | for subject in SUBJECTS:
424 | for level in range(1, 6):
425 | key = (level, subject)
426 | if key not in m.cors.keys():
427 | continue
428 | cors_list = m.cors[key]
429 | line = "{} Level {} Accuracy = {}/{} = {:5.2f}%".format(subject, level, *self.pc(cors_list))
430 | self.out(f, line)
431 | self.out(f, DELIM)
432 |
433 | def write_correct_completions(self, m, dirpath: str):
434 | print(f'Writing {m.name} raw+correct completions to {dirpath}')
435 | # make directory if it doesn't exist
436 | if not os.path.exists(dirpath):
437 | os.makedirs(dirpath)
438 |
439 | # for each test outcome, if not correct continue,
440 | # if correct then write raw to file in dump directory
441 | for t in m.individuals:
442 | if not t.correct:
443 | continue
444 |
445 | ident, json = os.path.splitext(os.path.basename(t.fname))
446 | subject = os.path.split(t.fname)[0]
447 | loc = os.path.join(dirpath, subject)
448 | if not os.path.exists(loc):
449 | os.makedirs(loc)
450 | fname = os.path.join(loc, f'{ident}.txt')
451 | raw_completion = t.raw_completion
452 | with open(fname, 'w') as f:
453 | f.write(raw_completion)
454 |
455 | def write_results_file(self, m: Metrics, out_answers_file: str):
456 | with open(out_answers_file, "w+") as f:
457 | # write all the raw test results
458 | self.write_each_test_results(m, f)
459 |
460 | # write accuracies by subject/level
461 | self.write_subject_level_accuracies(m, f)
462 | self.write_level_accuracies(m, f)
463 | self.write_subject_accuracies(m, f)
464 |
465 | # write overall accuracy
466 | self.out(f, f'Overall {m.name}: {m.stats()}')
467 |
468 |
--------------------------------------------------------------------------------
/eval/runner.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | from typing import List, Optional, Tuple
3 | from eval.measure_math import Eval
4 | from helper_utils import NO_SOLUTION_BAD_FORMAT
5 | from fn_snapshot import FnSnapshot
6 |
7 | HR = "\n" + '-' * 80 + "\n"
8 | BENCHMARK = "MATH"
9 |
10 | class RunEval:
11 | def __init__(self):
12 | self.model_name = None
13 | self.snapshots = None
14 | self.verbose = True
15 |
16 | def do(self):
17 | return Eval(self.solve_fn,
18 | self.snapshots,
19 | self.model_name,
20 | verbose = self.verbose)
21 |
22 | def solve_fn(self, prb: str) -> List[Tuple[str, str]]:
23 | answers: List[Tuple[str, str]] = self.answers(prb)
24 | # If no answers return indicator that we got no answer section
25 | if not answers:
26 | return [(NO_SOLUTION_BAD_FORMAT, "")]
27 | return answers
28 |
29 | def answers(self, prb: str) -> List[Tuple[str, str]]: # type: ignore [empty-body]
30 | pass
31 |
32 | mk_dir_safe = lambda x: x.replace('/', '_')
33 |
34 | class EvalRunner(RunEval):
35 | def __init__(self, answerer, snapshots_specs, verbose):
36 | print(f'Reading specs from: {snapshots_specs}')
37 | self.answers = answerer.answers # type: ignore [method-assign]
38 | self.model_name = mk_dir_safe(answerer.model.name)
39 | self.snapshots = FnSnapshot.load(BENCHMARK, snapshots_specs)
40 | self.verbose = verbose
41 |
--------------------------------------------------------------------------------
/evaluate.py:
--------------------------------------------------------------------------------
1 | from loader import load_mod
2 | from eval.measure_math import Eval
3 | import json
4 | import argparse
5 | from typing import List, Dict, Any, Tuple
6 | from persist import Persist
7 |
8 |
9 | DEFAULT_MODEL_SPECS_FILE = 'evaluated_models.json'
10 | DEFAULT_SNAPSHOTS_FILE = 'monthly_snapshots.json'
11 | DEFAULT_EVAL_PICKLE_FILE = DEFAULT_MODEL_SPECS_FILE + '.pickle'
12 |
13 | DEFAULT_FEW_SHOT_NUM = 5
14 | DEFAULT_TEMPERATURE = 0.0
15 |
16 | SPEC_SCRIPT = 'script'
17 | SPEC_INCLUDE = 'include'
18 | SPEC_NAME = 'name'
19 | SPEC_COT = 'CoT'
20 | SPEC_FEW_SHOT = 'few shot'
21 | SPEC_TEMP = 'temperature'
22 | SPEC_EXTRA_PARAMS = 'extra_params'
23 | SPEC_EXTRA_PARAMS_MODE_WRITE_OFFLINE = 'write_qs'
24 |
25 |
26 | class ModelSpec:
27 | def __init__(self, spec):
28 | self.script = spec[SPEC_SCRIPT]
29 | self.model = spec[SPEC_NAME]
30 | self.chain_of_thought = spec[SPEC_COT]
31 | self.few_shot_num = spec[SPEC_FEW_SHOT] if SPEC_FEW_SHOT in spec else DEFAULT_FEW_SHOT_NUM
32 | self.temperature = spec[SPEC_TEMP] if SPEC_TEMP in spec else DEFAULT_TEMPERATURE
33 | self.extra_params = json.loads(spec[SPEC_EXTRA_PARAMS]) if SPEC_EXTRA_PARAMS in spec else {}
34 |
35 | def ident(self) -> str:
36 | cot_yn = 'yes' if self.chain_of_thought else 'no'
37 | return self.model + f'_cot={cot_yn}_fs={self.few_shot_num}_temp={self.temperature}'
38 |
39 | def __repr__(self) -> str:
40 | return self.ident()
41 |
42 | def spec_csv(self) -> Tuple[str,str]:
43 | hdr = f'model,cot,fewshot,temp'
44 | row = f'{self.model},{self.chain_of_thought},{self.few_shot_num},{self.temperature}'
45 | return hdr,row
46 |
47 | class ModelRunners:
48 | def __init__(self, spec_file: str, snapshots_specs: str, verbose: bool, save_snapshot: bool):
49 | self.verbose = verbose
50 | self.save_snapshot = save_snapshot
51 | self.snapshots_specs = snapshots_specs
52 |
53 | with open(spec_file, 'r') as f:
54 | js = json.load(f)
55 | script_names = set(spec[SPEC_SCRIPT] for spec in js if spec[SPEC_INCLUDE] )
56 | model_specs = [ ModelSpec(spec) for spec in js if spec[SPEC_INCLUDE] ]
57 |
58 | models_for = lambda sc: [ ms for ms in model_specs if ms.script == sc ]
59 |
60 | self.models: Dict[str, List[ModelSpec]] = { script: models_for(script) for script in script_names }
61 | self.scripts: Dict[str, Any] = { script: load_mod(script) for script in script_names }
62 |
63 | def run(self, ms: ModelSpec) -> Eval:
64 | self.banner(f"Evaluating {ms.ident()}")
65 | runner = self.scripts[ms.script].Answers.run
66 | return runner(ms.model,
67 | self.snapshots_specs,
68 | ms.chain_of_thought,
69 | ms.few_shot_num,
70 | ms.temperature,
71 | self.verbose,
72 | self.save_snapshot,
73 | ms.extra_params)
74 |
75 | def run_models_for(self, script: str) -> Dict[ModelSpec, Eval]:
76 | return { ms: self.run(ms) for ms in self.models[script] }
77 |
78 | def api_script_names(self) -> List[str]:
79 | return list(self.scripts.keys())
80 |
81 | def banner(self, msg):
82 | hr = '\n' + '*' * 80 + '\n'
83 | print(f'{hr}{msg}{hr}')
84 |
85 |
86 | class Evaluate:
87 | def __init__(self, spec_file: str, snapshots_specs: str, verbose: bool, save_snapshot: bool):
88 | self.model_runners = ModelRunners(spec_file, snapshots_specs, verbose, save_snapshot)
89 |
90 | def build_evals(self) -> Dict[ModelSpec, Eval]:
91 | api_scripts: List[str] = self.model_runners.api_script_names()
92 | evals: List[Dict[ModelSpec, Eval]] = list(map(self.rfn, api_scripts))
93 | return { ms: e for evd in evals for ms, e in evd.items() }
94 |
95 | def rfn(self, sc) -> Dict[ModelSpec, Eval]:
96 | return self.model_runners.run_models_for(sc)
97 |
98 |
99 | if __name__ == "__main__":
100 | parser = argparse.ArgumentParser()
101 | parser.add_argument("--model_specs", type=str, default=DEFAULT_MODEL_SPECS_FILE,
102 | help = f"JSON of model specs, name + run script + enabled")
103 | parser.add_argument("--snapshots_specs", type=str, default=DEFAULT_SNAPSHOTS_FILE,
104 | help = f"JSON of static and monthly snapshots")
105 | parser.add_argument("--verbose", action='store_true', default=False,
106 | help="Outcomes of each test, one per line, on console")
107 | parser.add_argument("--save_snapshot", action='store_true', default=False,
108 | help="Save API query snapshot as .tar.gz file")
109 | args = parser.parse_args()
110 |
111 | outfile = f'{args.model_specs}.pickle'
112 | e = Evaluate(args.model_specs, args.snapshots_specs, args.verbose, args.save_snapshot)
113 | evals: Dict[ModelSpec, Eval] = e.build_evals()
114 | Persist.save(evals, outfile, force_overwrite = True)
115 | ofile_msg = f'--in_file {outfile}' if outfile != DEFAULT_EVAL_PICKLE_FILE else ''
116 | print(f'Evals written. Run python3 -m summarize_evals {ofile_msg} to see summary.')
117 |
--------------------------------------------------------------------------------
/evaluated_models.json:
--------------------------------------------------------------------------------
1 | [
2 | { "name": "c3-opus", "script": "model_api/ant.py", "include": true, "CoT": false },
3 | { "name": "c3-opus", "script": "model_api/ant.py", "include": true, "CoT": true, "few shot": 0 },
4 | { "name": "c3-opus", "script": "model_api/ant.py", "include": true, "CoT": true, "few shot": 5 },
5 |
6 | { "name": "mistral-large", "script": "model_api/mis.py", "include": true, "CoT": false },
7 | { "name": "mistral-large", "script": "model_api/mis.py", "include": true, "CoT": true, "few shot": 0 },
8 | { "name": "mistral-large", "script": "model_api/mis.py", "include": true, "CoT": true, "few shot": 5 },
9 |
10 | { "name": "mistral-medium", "script": "model_api/mis.py", "include": true, "CoT": false },
11 | { "name": "mistral-medium", "script": "model_api/mis.py", "include": true, "CoT": true, "few shot": 5 },
12 | { "name": "mistral-medium", "script": "model_api/mis.py", "include": true, "CoT": true, "few shot": 0 },
13 |
14 | { "name": "gpt3", "script": "model_api/oai.py", "include": true, "CoT": false },
15 | { "name": "gpt3", "script": "model_api/oai.py", "include": true, "CoT": true, "few shot": 0 },
16 | { "name": "gpt3", "script": "model_api/oai.py", "include": true, "CoT": true, "few shot": 5 },
17 |
18 | { "name": "gpt4", "script": "model_api/oai.py", "include": true, "CoT": false },
19 | { "name": "gpt4", "script": "model_api/oai.py", "include": true, "CoT": true, "few shot": 0 },
20 | { "name": "gpt4", "script": "model_api/oai.py", "include": true, "CoT": true, "few shot": 5 },
21 |
22 | { "name": "togethercomputer/StripedHyena-Nous-7B", "script": "model_api/tog.py", "include": true, "CoT": false },
23 | { "name": "togethercomputer/StripedHyena-Nous-7B", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 0 },
24 | { "name": "togethercomputer/StripedHyena-Nous-7B", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 5 },
25 |
26 | { "name": "Open-Orca/Mistral-7B-OpenOrca", "script": "model_api/tog.py", "include": true, "CoT": false },
27 | { "name": "Open-Orca/Mistral-7B-OpenOrca", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 0 },
28 | { "name": "Open-Orca/Mistral-7B-OpenOrca", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 5 },
29 |
30 | { "name": "zero-one-ai/Yi-34B", "script": "model_api/tog.py", "include": true, "CoT": false },
31 | { "name": "zero-one-ai/Yi-34B", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 0 },
32 | { "name": "zero-one-ai/Yi-34B", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 5 },
33 |
34 | { "name": "Qwen/Qwen1.5-72B", "script": "model_api/tog.py", "include": true, "CoT": false },
35 | { "name": "Qwen/Qwen1.5-72B", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 0 },
36 | { "name": "Qwen/Qwen1.5-72B", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 5 },
37 |
38 | { "name": "allenai/OLMo-7B-Instruct", "script": "model_api/tog.py", "include": true, "CoT": false },
39 | { "name": "allenai/OLMo-7B-Instruct", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 0 },
40 | { "name": "allenai/OLMo-7B-Instruct", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 5 },
41 |
42 | { "name": "google/gemma-7b", "script": "model_api/tog.py", "include": true, "CoT": false },
43 | { "name": "google/gemma-7b", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 0 },
44 | { "name": "google/gemma-7b", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 5 },
45 |
46 | { "name": "meta-llama/Llama-2-70b-hf", "script": "model_api/tog.py", "include": true, "CoT": false },
47 | { "name": "meta-llama/Llama-2-70b-hf", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 0 },
48 | { "name": "meta-llama/Llama-2-70b-hf", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 5 },
49 |
50 | { "name": "microsoft/phi-2", "script": "model_api/tog.py", "include": true, "CoT": false },
51 | { "name": "microsoft/phi-2", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 0 },
52 | { "name": "microsoft/phi-2", "script": "model_api/tog.py", "include": true, "CoT": true, "few shot": 5 }
53 | ]
54 |
--------------------------------------------------------------------------------
/few_shot.py:
--------------------------------------------------------------------------------
1 | from typing import List, Dict, Optional
2 |
3 | class FewShot:
4 | def __init__(self, prb: str, outcome: str, sol: Optional[str] = None):
5 | self.prb = prb
6 | self.outcome = outcome
7 | self.sol = sol
8 |
9 |
10 | class FewShotBuilder:
11 | def few_shot_limited(self, count: int) -> Dict[str, str]: # type: ignore [empty-body]
12 | pass
13 |
14 |
15 | FewShotAnswerSamples = [
16 | FewShot(
17 | prb = "What is $\left(\\frac{7}{8}\\right)^3 \cdot \left(\\frac{7}{8}\\right)^{-3}$?",
18 | outcome = "$1$",
19 | ),
20 | FewShot(
21 | prb = "In how many ways can 4 books be selected from a shelf of 6 books if the order in which the books are selected does not matter?",
22 | outcome = "$15$",
23 | ),
24 | FewShot(
25 | prb = "Find the distance between the points $(2,1,-4)$ and $(5,8,-3).$",
26 | outcome = "$\sqrt{59}$",
27 | ),
28 | FewShot(
29 | prb = "The faces of an octahedral die are labeled with digits $1$ through $8$. What is the probability, expressed as a common fraction, of rolling a sum of $15$ with a pair of such octahedral dice?",
30 | outcome = "$\\frac{1}{32}$",
31 | ),
32 | FewShot(
33 | prb = "The first three terms of an arithmetic sequence are 1, 10 and 19, respectively. What is the value of the 21st term?",
34 | outcome = "$181$",
35 | ),
36 | FewShot(
37 | prb = "Calculate $6 \\cdot 8\\frac{1}{3}",
38 | outcome = "$16$",
39 | ),
40 | FewShot(
41 | prb = "When the binary number $100101110010_2$ is divided by 4, what is the remainder (give your answer in base 10)?",
42 | outcome = "$2$",
43 | ),
44 | FewShot(
45 | prb = "How many zeros are at the end of the product 25 $\\times$ 240?",
46 | outcome = "$3$",
47 | ),
48 | ]
49 |
50 | CoTFewShotAnswerSamples = [
51 | FewShot(
52 | prb = "What is $\left(\\frac{7}{8}\\right)^3 \cdot \left(\\frac{7}{8}\\right)^{-3}$?",
53 | outcome = "$1$",
54 | sol = "Let's think about this step by step. We have the left part of the product raised to the power of 3, and the right part raised to the power of -3. Raising x to a negative power is the same as the 1/x, so we have a product of x and 1/x, which equals 1.",
55 | ),
56 | FewShot(
57 | prb = "In how many ways can 4 books be selected from a shelf of 6 books if the order in which the books are selected does not matter?",
58 | outcome = "$15$",
59 | sol = "Let's think about this step by step. This is a simple combinations problem, and the choice is 6 choose 4, which equals 15.",
60 | ),
61 | FewShot(
62 | prb = "Find the distance between the points $(2,1,-4)$ and $(5,8,-3).$",
63 | outcome = "$\sqrt{59}$",
64 | sol = "Let's think about this step by step. We need to find the distance in 3D space, which is equal to the square of difference in each coordinate, summed, and then sqrt of that. In this case, that is sqrt of (3^2 + 7^2 + (-1)^2) which is sqrt of 9 + 49 + 1, which equals \sqrt{59}.",
65 | ),
66 | FewShot(
67 | prb = "The faces of an octahedral die are labeled with digits $1$ through $8$. What is the probability, expressed as a common fraction, of rolling a sum of $15$ with a pair of such octahedral dice?",
68 | outcome = "$\\frac{1}{32}$",
69 | sol = "Let's think about this step by step. 15 can be made using 7 and 8 rolled. There are 8 times 8 ways of rolling the dies of which only two end up with a 7 and 8 on the face. So the probability is 2/64 which is \frac{1}{32}.",
70 | ),
71 | FewShot(
72 | prb = "The first three terms of an arithmetic sequence are 1, 10 and 19, respectively. What is the value of the 21st term?",
73 | outcome = "$181$",
74 | sol = "Let's think about this step by step. This is an arithmetic sequence with difference 9, so its nth term is given by 1+9(n-1), so its 21st terms is 1+9x20 = 181.",
75 | ),
76 | FewShot(
77 | prb = "Calculate $6 \\cdot 8\\frac{1}{3}",
78 | outcome = "$16$",
79 | sol = "Let's think about this step by step. This equals 6 times 8 divided by 3, which is 2 times 8, or 16.",
80 | ),
81 | FewShot(
82 | prb = "When the binary number $100101110010_2$ is divided by 4, what is the remainder (give your answer in base 10)?",
83 | outcome = "$2$",
84 | sol = "Let's think about this step by step. None of the bits after the 3rd matter in this case, so the binary remainder is 10_2, which is 2 in decimal.",
85 | ),
86 | FewShot(
87 | prb = "How many zeros are at the end of the product 25 $\\times$ 240?",
88 | outcome = "$3$",
89 | sol = "Let's think about this step by step. 25 is 100 by 4, and 4 cleanly divides 24, so two zeros from 100 and one from the other number give us 3 zeros.",
90 | ),
91 | ]
92 |
--------------------------------------------------------------------------------
/fn_snapshot.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | import os
3 | from datetime import datetime
4 | from pathlib import Path
5 | from helper_utils import download_extract
6 | from typing import Dict, Any, List, Tuple, Optional
7 | import json
8 |
9 | DATE_FMT = '%b-%Y'
10 | STATIC_DATE_TAG = "Jan-1984"
11 |
12 | # MATH/test has the subject dirs within it
13 | root_test = lambda root: os.path.join(root, "test")
14 |
15 | class FnSnapshot:
16 | def __init__(self, date: str, url: str):
17 | self.date = date
18 | self.url = url
19 |
20 | def is_static(self) -> bool:
21 | return self.date == STATIC_DATE_TAG
22 |
23 | def ensure_dataset(self):
24 | # get root "MATH" from "https://people.eecs.berkeley.edu/~hendrycks/MATH.tar"
25 | # or "Dec-2023" from "Dec-2023.tar.gz"
26 | p = Path(self.url)
27 | root = p.name.removesuffix("".join(p.suffixes))
28 |
29 | downloaded_name = os.path.basename(self.url)
30 | is_gz = downloaded_name.endswith('gz')
31 | there = lambda d: os.path.exists(d)
32 | test_dir = root_test(root)
33 | if not there(root) or not there(test_dir):
34 | download_extract(self.url, root, downloaded_name, root, is_gz)
35 | assert there(root), f'Download/extract failed to create {root} from {self.url}'
36 | assert there(test_dir), f'Download/extract from {self.url} does not have {test_dir}'
37 | return root
38 |
39 | @classmethod
40 | def load(cls, benchmark: str, config: str) -> List[FnSnapshot]:
41 | def load_snaps(fixed_url, fns):
42 | snaps = [FnSnapshot(fn['date'], fn['url']) for fn in fns]
43 | snaps.append(FnSnapshot(STATIC_DATE_TAG, fixed_url))
44 | snaps.sort(key = lambda x: datetime.strptime(x.date, DATE_FMT))
45 | return snaps
46 |
47 | with open(config, 'r') as cf:
48 | benchmarks = json.load(cf)
49 | benchmark_meta = None
50 | for meta in benchmarks:
51 | if meta['benchmark'] == benchmark:
52 | benchmark_meta = meta
53 | assert benchmark_meta, f'Did not find {benchmark} in {benchmarks}'
54 | return load_snaps(benchmark_meta['fixed'], benchmark_meta['functionals'])
55 |
56 |
--------------------------------------------------------------------------------
/helper_utils.py:
--------------------------------------------------------------------------------
1 | import os
2 | import subprocess
3 | from typing import Tuple, Optional, List
4 |
5 | NO_SOLUTION_PREFIX = "NO_SOLUTION"
6 | NO_SOLUTION_BAD_FORMAT = f"{NO_SOLUTION_PREFIX} [BAD FORMAT]"
7 | NO_SOLUTION_DIMS = f"{NO_SOLUTION_PREFIX} [DIMS]"
8 | NO_SOLUTION_EXCEED_CONTEXT = f"{NO_SOLUTION_PREFIX} [EXCEED CONTEXT]"
9 |
10 | def download_extract(url: str, unzipped_dir: str, downloaded_targz: str, root: str, gz: bool = True):
11 | assert not os.path.exists(unzipped_dir), f'Cannot download extract to {unzipped_dir}. Directory already exists'
12 | tar_flags = '-zxvf' if gz else '-xvf'
13 | get = ['curl', url, '-o', downloaded_targz] if url.startswith("http") else ['cp', url, downloaded_targz]
14 | unzip = ['tar', tar_flags, downloaded_targz]
15 | mv = ['mv', unzipped_dir, f'{root}']
16 | for cmd in [get, unzip, mv]:
17 | print(f'Running: {cmd}')
18 | subprocess.call(cmd)
19 |
20 | def targz(dirname: str):
21 | tar_name = dirname + ".tar"
22 | targz_name = tar_name + ".gz"
23 | assert not os.path.exists(tar_name), f'Cannot tar to {tar_name}. File already exists'
24 | assert not os.path.exists(targz_name), f'Cannot gz to {targz_name}. File already exists'
25 | tar = ['tar', '-cvf', tar_name, dirname]
26 | gzip = ['gzip', tar_name]
27 | subprocess.call(tar)
28 | subprocess.call(gzip)
29 |
30 | def untargz(targz_name: str, dst: str):
31 | ext = ".tar.gz"
32 | assert targz_name.endswith(ext)
33 | extract_name = targz_name[:-len(ext)]
34 | assert not os.path.exists(extract_name), f'Cannot extract to {extract_name}. Directory already exists'
35 | tar_flags = '-zxvf'
36 | unzip = ['tar', tar_flags, targz_name]
37 | subprocess.call(unzip)
38 |
39 | if extract_name != dst:
40 | print(f'Moving {extract_name} to {dst}')
41 | assert not os.path.exists(dst), f'Cannot mv to {dst}. Directory already exists'
42 | mv = ['mv', extract_name, dst]
43 | subprocess.call(mv)
44 |
--------------------------------------------------------------------------------
/loader.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import importlib.util
3 |
4 | def load_mod(fname):
5 | nm = fname
6 | spec = importlib.util.spec_from_file_location(nm, fname)
7 | assert spec, f'Could not load from file: {fname}'
8 | mod = importlib.util.module_from_spec(spec)
9 | sys.modules[nm] = mod
10 | assert spec.loader, f'Spec does not have loader'
11 | spec.loader.exec_module(mod)
12 | return mod
13 |
--------------------------------------------------------------------------------
/math_utils/README.md:
--------------------------------------------------------------------------------
1 | original source code from hendrycks MATH: https://github.com/hendrycks/math/
2 |
--------------------------------------------------------------------------------
/math_utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/math_utils/__init__.py
--------------------------------------------------------------------------------
/math_utils/math_equivalence.py:
--------------------------------------------------------------------------------
1 | # This is a copy of the equivalence helper functions from the MATH repo:
2 | # https://github.com/hendrycks/math/blob/main/modeling/math_equivalence.py
3 |
4 | def _fix_fracs(string):
5 | substrs = string.split("\\frac")
6 | new_str = substrs[0]
7 | if len(substrs) > 1:
8 | substrs = substrs[1:]
9 | for substr in substrs:
10 | new_str += "\\frac"
11 | if substr[0] == "{":
12 | new_str += substr
13 | else:
14 | try:
15 | assert len(substr) >= 2
16 | except:
17 | return string
18 | a = substr[0]
19 | b = substr[1]
20 | if b != "{":
21 | if len(substr) > 2:
22 | post_substr = substr[2:]
23 | new_str += "{" + a + "}{" + b + "}" + post_substr
24 | else:
25 | new_str += "{" + a + "}{" + b + "}"
26 | else:
27 | if len(substr) > 2:
28 | post_substr = substr[2:]
29 | new_str += "{" + a + "}" + b + post_substr
30 | else:
31 | new_str += "{" + a + "}" + b
32 | string = new_str
33 | return string
34 |
35 | def _fix_a_slash_b(string):
36 | if len(string.split("/")) != 2:
37 | return string
38 | a = string.split("/")[0]
39 | b = string.split("/")[1]
40 | try:
41 | a = int(a)
42 | b = int(b)
43 | assert string == "{}/{}".format(a, b)
44 | new_string = "\\frac{" + str(a) + "}{" + str(b) + "}"
45 | return new_string
46 | except:
47 | return string
48 |
49 | def _remove_right_units(string):
50 | # "\\text{ " only ever occurs (at least in the val set) when describing units
51 | if "\\text{ " in string:
52 | splits = string.split("\\text{ ")
53 | assert len(splits) == 2
54 | return splits[0]
55 | else:
56 | return string
57 |
58 | def _fix_sqrt(string):
59 | if "\\sqrt" not in string:
60 | return string
61 | splits = string.split("\\sqrt")
62 | new_string = splits[0]
63 | for split in splits[1:]:
64 | if split[0] != "{":
65 | a = split[0]
66 | new_substr = "\\sqrt{" + a + "}" + split[1:]
67 | else:
68 | new_substr = "\\sqrt" + split
69 | new_string += new_substr
70 | return new_string
71 |
72 | def _strip_string(string):
73 | # linebreaks
74 | string = string.replace("\n", "")
75 | #print(string)
76 |
77 | # remove inverse spaces
78 | string = string.replace("\\!", "")
79 | #print(string)
80 |
81 | # replace \\ with \
82 | string = string.replace("\\\\", "\\")
83 | #print(string)
84 |
85 | # replace tfrac and dfrac with frac
86 | string = string.replace("tfrac", "frac")
87 | string = string.replace("dfrac", "frac")
88 | #print(string)
89 |
90 | # remove \left and \right
91 | string = string.replace("\\left", "")
92 | string = string.replace("\\right", "")
93 | #print(string)
94 |
95 | # Remove circ (degrees)
96 | string = string.replace("^{\\circ}", "")
97 | string = string.replace("^\\circ", "")
98 |
99 | # remove dollar signs
100 | string = string.replace("\\$", "")
101 |
102 | # remove units (on the right)
103 | string = _remove_right_units(string)
104 |
105 | # remove percentage
106 | string = string.replace("\\%", "")
107 | string = string.replace("\%", "")
108 |
109 | # " 0." equivalent to " ." and "{0." equivalent to "{." Alternatively, add "0" if "." is the start of the string
110 | string = string.replace(" .", " 0.")
111 | string = string.replace("{.", "{0.")
112 | # if empty, return empty string
113 | if len(string) == 0:
114 | return string
115 | if string[0] == ".":
116 | string = "0" + string
117 |
118 | # to consider: get rid of e.g. "k = " or "q = " at beginning
119 | if len(string.split("=")) == 2:
120 | if len(string.split("=")[0]) <= 2:
121 | string = string.split("=")[1]
122 |
123 | # fix sqrt3 --> sqrt{3}
124 | string = _fix_sqrt(string)
125 |
126 | # remove spaces
127 | string = string.replace(" ", "")
128 |
129 | # \frac1b or \frac12 --> \frac{1}{b} and \frac{1}{2}, etc. Even works with \frac1{72} (but not \frac{72}1). Also does a/b --> \\frac{a}{b}
130 | string = _fix_fracs(string)
131 |
132 | # manually change 0.5 --> \frac{1}{2}
133 | if string == "0.5":
134 | string = "\\frac{1}{2}"
135 |
136 | # NOTE: X/Y changed to \frac{X}{Y} in dataset, but in simple cases fix in case the model output is X/Y
137 | string = _fix_a_slash_b(string)
138 |
139 | return string
140 |
141 | def is_equiv(str1, str2, verbose=False):
142 | if str1 is None and str2 is None:
143 | print("WARNING: Both None")
144 | return True
145 | if str1 is None or str2 is None:
146 | return False
147 |
148 | try:
149 | ss1 = _strip_string(str1)
150 | ss2 = _strip_string(str2)
151 | if verbose:
152 | print(ss1, ss2)
153 | return ss1 == ss2
154 | except:
155 | return str1 == str2
156 |
--------------------------------------------------------------------------------
/math_utils/math_helpers.py:
--------------------------------------------------------------------------------
1 |
2 | def rm_latex_math(expr: str) -> str:
3 | def wrapped_latex_math(expr: str) -> bool:
4 | expr = expr.strip()
5 | return len(expr) >=2 and expr[0] == '$' and expr[-1] == '$'
6 |
7 | expr = expr.strip()
8 | return expr[1:-1] if wrapped_latex_math(expr) else expr
9 |
10 |
11 | # The below is a copy of the helper functions in the MATH repo:
12 | # https://github.com/hendrycks/math/blob/main/modeling/eval_math_gpt.py
13 |
14 | def remove_boxed(s):
15 | left = "\\boxed{"
16 | try:
17 | assert s[:len(left)] == left
18 | assert s[-1] == "}"
19 | return s[len(left):-1]
20 | except:
21 | return None
22 |
23 |
24 | # The below is a copy of the helper functions in the MATH repo:
25 | # https://github.com/hendrycks/math/blob/main/modeling/dataset/util.py
26 |
27 | def last_boxed_only(sample):
28 | """
29 | Given a (q,a) sample, filter the answers so that they only contain
30 | the last \boxed{...} or \fbox{...} element
31 | """
32 | q, a = sample
33 | a = last_boxed_only_string(a)
34 | if a == None:
35 | return None
36 | return (q, a)
37 |
38 | def last_boxed_only_string(string):
39 | idx = string.rfind("\\boxed")
40 | if idx < 0:
41 | idx = string.rfind("\\fbox")
42 | if idx < 0:
43 | return None
44 |
45 | i = idx
46 | right_brace_idx = None
47 | num_left_braces_open = 0
48 | while i < len(string):
49 | if string[i] == "{":
50 | num_left_braces_open += 1
51 | if string[i] == "}":
52 | num_left_braces_open -= 1
53 | if num_left_braces_open == 0:
54 | right_brace_idx = i
55 | break
56 | i += 1
57 |
58 | if right_brace_idx == None:
59 | retval = None
60 | else:
61 | assert right_brace_idx is not None
62 | retval = string[idx:right_brace_idx + 1]
63 |
64 | return retval
65 |
66 | def only_until_first_boxed_from_tokens(string, tokens):
67 | idx = string.find("\\boxed")
68 | if idx < 0:
69 | idx = string.find("\\fbox")
70 | if idx < 0:
71 | return None
72 |
73 | cum_length = 0
74 | for i, t in enumerate(tokens):
75 | cum_length += len(t)
76 | if cum_length >= idx:
77 | break
78 |
79 | return tokens[:i]
80 |
81 |
82 |
83 | def clean_numbers(sample):
84 | if not sample:
85 | return None
86 | new_sample = list()
87 | for s in sample:
88 | new_sample.append(_clean_numbers(s))
89 |
90 | return tuple(new_sample)
91 |
92 | def _clean_numbers(string):
93 | """
94 | Clean Numbers in the given string
95 |
96 | >>> _clean_numbers(None, "Hello 123")
97 | 'Hello 123'
98 | >>> _clean_numbers(None, "Hello 1234")
99 | 'Hello 1,234'
100 | >>> _clean_numbers(None, "Hello 1234324asdasd")
101 | 'Hello 1,234,324asdasd'
102 | """
103 | num_prev_digits = 0
104 | new_string = ""
105 | for i, c in enumerate(string):
106 | # isdigit() doesnt work here because of weird unicode chars.
107 | if c in {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}:
108 | num_prev_digits += 1
109 | else:
110 | if num_prev_digits > 3:
111 | # Some fixing
112 | string_number = new_string[-num_prev_digits:]
113 | new_string = new_string[:-num_prev_digits] + "{0:,}".format(int(string_number))
114 | num_prev_digits = 0
115 | new_string += c
116 |
117 | if num_prev_digits > 3:
118 | # Some fixing
119 | string_number = new_string[-num_prev_digits:]
120 | new_string = new_string[:-num_prev_digits] + "{0:,}".format(int(string_number))
121 |
122 | return new_string
123 |
--------------------------------------------------------------------------------
/model_api/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/model_api/__init__.py
--------------------------------------------------------------------------------
/model_api/ant.py:
--------------------------------------------------------------------------------
1 | from eval.runner import EvalRunner, mk_dir_safe
2 | import argparse
3 | import sys
4 | from typing import Dict, List, Tuple, Any
5 | from math_utils.math_helpers import rm_latex_math
6 | from unformatted_llm import UnformattedLLM
7 | from model_api.closed_api import KnownModel, ParameterizedModel, Runner
8 | from model_api.claude import Claude, ANTHROPIC_PARAMS
9 | from evaluate import DEFAULT_SNAPSHOTS_FILE, DEFAULT_FEW_SHOT_NUM, DEFAULT_TEMPERATURE
10 | from chain_of_thought import COT_INSTRUCTION, ChainOfThought
11 |
12 | class Answers(Runner):
13 | def __init__(self, model: KnownModel, use_cot: bool, few_shot_num: int, temperature: float):
14 | self.model = model
15 | self.use_cot = use_cot
16 | self.cot = ChainOfThought()
17 | unformatted = UnformattedLLM()
18 |
19 | few_shot_builder = self.cot if use_cot else unformatted
20 | instruction = COT_INSTRUCTION if use_cot else unformatted.INSTRUCTION
21 | few_shot: Dict[str, str] = few_shot_builder.few_shot_limited(few_shot_num)
22 | cache_infer_params = f'temp={temperature}_cot={use_cot}_fs={few_shot_num}'
23 | cache_model_name = mk_dir_safe(model.name)
24 | params = ParameterizedModel(
25 | temp = temperature,
26 | instruction = instruction,
27 | who_are_you = "",
28 | few_shot = few_shot,
29 | model = model,
30 | agent_name = f"Anthropic_Eval_{cache_model_name}_{cache_infer_params}",
31 | )
32 | self.claude = Claude(params)
33 |
34 | def answers(self, prb: str) -> List[Tuple[str, str]]:
35 | completion = self.claude.query([prb], rate_limited = False)[0]
36 | answer = self.claude.extract_answer(completion)
37 | if self.use_cot:
38 | answer = self.cot.extract_answer(answer)
39 | return [(answer, completion)]
40 |
41 | @classmethod
42 | def run(cls, name: str, snapshots_specs: str,
43 | cot: bool, few_shot_num: int, temperature: float,
44 | verbose: bool = False, save_snaphot: bool = False, extra_params: Dict[str, Any] = {}):
45 | known_model = ANTHROPIC_PARAMS.SHORT_NAMES[name]
46 | answerer = Answers(known_model, cot, few_shot_num, temperature)
47 | e = EvalRunner(answerer, snapshots_specs, verbose).do()
48 | if save_snaphot:
49 | answerer.claude.snapshot_api_query_cache()
50 | return e
51 |
52 |
53 | if __name__ == "__main__":
54 | parser = argparse.ArgumentParser()
55 | parser.add_argument("--model", required=True,
56 | help = f"Model has to be one of {list(ANTHROPIC_PARAMS.SHORT_NAMES.keys())}")
57 | parser.add_argument("--snapshots_specs", type=str, default=DEFAULT_SNAPSHOTS_FILE,
58 | help = f"JSON of static and monthly snapshots")
59 | parser.add_argument("--verbose", action='store_true',
60 | help="Outcomes of each test, one per line, on console")
61 | parser.add_argument("--use_chain_of_thought", action='store_true',
62 | help="Use chain of thought instruction and postprocessing")
63 | parser.add_argument("--few_shot_num", type=str, default=DEFAULT_FEW_SHOT_NUM,
64 | help=f"Default few shot count: {DEFAULT_FEW_SHOT_NUM}")
65 | parser.add_argument("--temperature", type=float, default=DEFAULT_TEMPERATURE,
66 | help=f"Default temperature: {DEFAULT_TEMPERATURE}")
67 | parser.add_argument("--save_snapshot", action='store_true',
68 | help="Save API query snapshot as .tar.gz file")
69 | args = parser.parse_args()
70 |
71 | Answers.run(args.model, args.snapshots_specs,
72 | args.use_chain_of_thought, args.few_shot_num, args.temperature,
73 | args.verbose, args.save_snapshot)
74 |
--------------------------------------------------------------------------------
/model_api/claude.py:
--------------------------------------------------------------------------------
1 | import os
2 | from model_api.closed_api import ClosedAPI, RateLimited, KnownModel, PERIODS_PER_MIN, ParameterizedModel
3 | from typing import Any, Awaitable, Dict, Optional
4 |
5 | from anthropic import AsyncAnthropic, HUMAN_PROMPT, AI_PROMPT
6 |
7 | CLAUDE_API_KEY = os.getenv("ANTHROPIC_API_KEY")
8 | END_TAG = "\n~~~\n"
9 | MAX_TOKENS = 1024
10 |
11 | mk_model = lambda name: KnownModel(
12 | name,
13 | is_chat = False,
14 | api_org = None,
15 | api_key = CLAUDE_API_KEY,
16 | api_base = "")
17 |
18 | class ANTHROPIC_PARAMS:
19 | NAMES = {
20 | 'c2-2.1': 'claude-2.1',
21 | 'c3-opus': 'claude-3-opus-20240229',
22 | 'c3-sonnet': 'claude-3-sonnet-20240229'
23 | }
24 | SHORT_NAMES = { short: mk_model(model) for short, model in NAMES.items() }
25 |
26 | class Claude(ClosedAPI):
27 | def __init__(self, params: ParameterizedModel):
28 | super().__init__(params)
29 |
30 | self.params = params
31 | self.prelude = self.few_shot_format(params.few_shot)
32 | self.anthropic = AsyncAnthropic(api_key = params.model.api_key)
33 |
34 | def deobject(self, message: Any) -> str:
35 | # message is a Message(
36 | # id = 'msg_..',
37 | # content = [ContentBlock(text='', type='text')],
38 | # model='claude-3-opus-20240229',
39 | # role='assistant',
40 | # stop_reason='end_turn',
41 | # stop_sequence=None,
42 | # type='message',
43 | # usage=Usage(input_tokens=84, output_tokens=409))
44 | content_list = message.content
45 |
46 | # From docs: https://docs.anthropic.com/claude/reference/messages_post
47 | # [{"type": "text", "text": "Hi, I'm Claude."}]
48 |
49 | # Actual output..
50 | # [ContentBlock(text='To solve this, we ca.......9647\n\nThe answer is: 0.9647', type='text')]
51 | assert len(content_list) == 1, f'Expecting a single content response, got: {content_list}'
52 | single_content = content_list[0]
53 | assert single_content.type == 'text', f'Only expecting text content, got: {single_content}'
54 | completion = single_content.text
55 |
56 | assert isinstance(completion, str), f'claude: model output is not str: {completion}'
57 | return completion
58 |
59 | def extract_answer(self, response) -> str:
60 | completion = response.lstrip()
61 | end = completion.find(END_TAG)
62 | answer = completion[:end] if end != -1 else completion
63 | answer = answer.strip()
64 | return answer
65 |
66 | def to_prompt_task(self, task: str) -> Any:
67 | return self.prelude + self.params.instruction + self.format(task, None)
68 |
69 | def reset_library(self, model: KnownModel) -> None:
70 | return
71 |
72 | def model_ask(self, prompt: str) -> Awaitable[Any]:
73 | # print(f'Sending query: {prompt}')
74 | message = self.anthropic.messages.create(
75 | model = self.params.model.name,
76 | max_tokens = MAX_TOKENS,
77 | temperature = self.params.temperature,
78 | system = "You are a MATH expert.",
79 | messages = [{
80 | 'role': 'user',
81 | 'content': prompt,
82 | }]
83 | )
84 | return message
85 |
86 | def spent(self, response) -> float:
87 | return 0.0
88 |
89 | def format(self, inp: str, out: Optional[str]) -> str:
90 | fmt = f"{HUMAN_PROMPT} {inp}{AI_PROMPT}"
91 | extra = out if out else ""
92 | return fmt + extra
93 |
94 | def few_shot_format(self, ios: Dict[str, str]) -> str:
95 | fs = ""
96 | for inp, out in ios.items():
97 | fs += self.format(inp, out) + END_TAG
98 | return fs
99 |
100 |
--------------------------------------------------------------------------------
/model_api/closed_api.py:
--------------------------------------------------------------------------------
1 | from typing import Dict, List, Tuple, Callable, Any, Awaitable, Optional
2 | import time
3 | import sys
4 | import os
5 | import asyncio
6 | import math
7 | import functools
8 | from codetiming import Timer # type: ignore
9 | from tqdm import tqdm # type: ignore
10 | from query_cache import QueryCache
11 | from persist import Persist
12 | from enum import Enum
13 |
14 | # temperature threshold under which we expect deterministic answers
15 | # the queries will be cached and we won't make API calls to OAI
16 | # If temp is above the threshold then every time we will API to OAI
17 | DETERMINISTIC_THRESHOLD = 1.0
18 |
19 | NOW_MS = lambda: round(time.time() * 1000)
20 | PERIODS_PER_MIN = 4
21 | ONE_PERIOD_MS = 1000 * 60 / PERIODS_PER_MIN
22 |
23 | # If ServiceUnavailableError, or Timeout etc
24 | BACKOFF_NUM_RETRIES = 3
25 | BACKOFF_TIME_SECONDS = 120
26 | hr = "=" * 100
27 | BACKOFF_MSG = lambda e: f'\n\n{hr}\nService unavailable.\nError = {e}\nPausing for {BACKOFF_TIME_SECONDS} seconds.\n{hr}\n\n'
28 | BACKOFF_ABORT_MSG = lambda e: f'\n\n{hr}\nService unavailable after {BACKOFF_NUM_RETRIES} attempts.\nError = {e}\n{hr}\nAborting!\n\n'
29 |
30 | OFFLINE_DEFER = "DEFERRED; MAGIC; NOTHING TO SEE HERE!"
31 |
32 | class KnownModel:
33 | def __init__(self,
34 | name: str,
35 | is_chat: bool,
36 | api_org: Optional[str],
37 | api_key: Optional[str],
38 | api_base: str,
39 | stops: Optional[List[str]] = None,
40 | prompt_format: Optional[str] = None,
41 | server_path: Optional[str] = None,
42 | batch_size: int = 200,
43 | num_parallel: int = 50,
44 | cps: float = 0.0,
45 | ):
46 | self.name = name
47 | self.is_chat = is_chat
48 | self.api_org = api_org
49 | self.api_key = api_key
50 | self.api_base = api_base
51 | self.server_path = server_path
52 |
53 | self.stops = stops
54 | self.prompt_format = prompt_format
55 |
56 | self.batch_size = batch_size
57 | self.num_parallel = num_parallel
58 | self.cost_per_token = cps
59 |
60 | def __hash__(self):
61 | hashes = [hash(v) for v in vars(self)]
62 | init = 42
63 | return functools.reduce(lambda a, b: a ^ b, hashes, init)
64 |
65 | def __eq__(self, other):
66 | eq_vars = vars(self) == vars(other)
67 | return (isinstance(other, self.__class__) and eq_vars)
68 |
69 | class QStat:
70 | def __init__(self, cost, time_ms):
71 | self.cost = cost
72 | self.time_ms = time_ms
73 | self.timestamp = NOW_MS()
74 |
75 | class QueryStats:
76 | def __init__(self):
77 | self.stats: List[QStat] = []
78 |
79 | def log_queries(self, qs: List[QStat]):
80 | self.stats += qs
81 |
82 | def __repr__(self) -> str:
83 | total = len(self.stats)
84 | per_query_spend = 0.0
85 | per_query_ms = 0.0
86 | queries_min = 0.0
87 |
88 | if total > 0:
89 | spend = sum(q.cost for q in self.stats)
90 | ms = sum(q.time_ms for q in self.stats)
91 | per_query_spend = float(spend) / total
92 | per_query_ms = float(ms) / total
93 |
94 | # estimate q/min
95 | max_ts = max(q.timestamp for q in self.stats)
96 | min_ts = min(q.timestamp for q in self.stats)
97 | minutes = (max_ts - min_ts) / (60 * 1000.0)
98 | ms_per_query = ( max_ts - min_ts ) / total
99 | queries_min = PERIODS_PER_MIN * ONE_PERIOD_MS / ms_per_query if ms_per_query else 0.0
100 |
101 | return f'{total} queries; {minutes:.2f} mins total time; per query = ${per_query_spend:.4f} {per_query_ms / 1000.0:.2f}s; rate = {queries_min:.0f}queries/min, 0 time/cost implies cache lookup]'
102 |
103 | ResponseStats = Tuple[str, QStat]
104 | WorkFn = Callable[[Any], Awaitable[Tuple[ResponseStats, bool]]]
105 |
106 | class Workers:
107 | def __init__(self, async_fn: WorkFn, num_parallel):
108 | self.async_fn = async_fn
109 | self.num_parallel = num_parallel
110 |
111 | def do(self, tasks) -> Tuple[List[ResponseStats], int]:
112 | return asyncio.run(self.parallel(tasks))
113 |
114 | async def work(self, worker_ident, in_q, out_q):
115 | while not in_q.empty():
116 | tid, task = await in_q.get()
117 | rslt, is_expensive = await self.async_fn(task)
118 | await out_q.put((tid, is_expensive, rslt))
119 |
120 | async def progress(self, out_q, sz):
121 | pbar = tqdm(total = sz)
122 | out_sz = 0
123 | while out_sz < sz:
124 | new_sz = out_q.qsize()
125 | update = new_sz - out_sz
126 | out_sz = new_sz
127 | pbar.update(update)
128 | await asyncio.sleep(0.5)
129 | pbar.close()
130 |
131 | async def parallel(self, tasks) -> Tuple[List[ResponseStats], int]:
132 | # Create the queue of work
133 | in_q: asyncio.Queue[Tuple[int, Any]] = asyncio.Queue()
134 | out_q: asyncio.Queue[Tuple[int, bool, Any]] = asyncio.Queue()
135 |
136 | # Put some work in the queue
137 | for tid, t in enumerate(tasks):
138 | await in_q.put((tid, t))
139 |
140 | # create the deferred workers
141 | create = lambda x: asyncio.create_task(self.work(x, in_q, out_q))
142 | workers = [create(i) for i in range(self.num_parallel)]
143 | workers.append(asyncio.create_task(self.progress(out_q, len(tasks))))
144 |
145 | # Run the tasks
146 | await asyncio.gather(*workers)
147 |
148 | results = []
149 | while not out_q.empty():
150 | results.append(await out_q.get())
151 | results.sort(key = lambda x: x[0])
152 | ids, expensive_flags, done = list(zip(*results))
153 | assert list(ids) == sorted(list(ids))
154 | expensed = expensive_flags.count(True)
155 | return list(done), expensed
156 |
157 | class LogLevel(Enum):
158 | ERROR = 3
159 | WARN = 2
160 | INFO = 1
161 |
162 | LOWEST = 1
163 |
164 | class RateLimited:
165 | def __init__(self, async_fn: WorkFn, batch_size: int, num_parallel: int, console_log_lvl: LogLevel):
166 | self.workers = Workers(async_fn, num_parallel)
167 | self.overall_stats = QueryStats()
168 | self.batch_size = batch_size
169 | self.console_log_lvl = console_log_lvl
170 |
171 | def do(self, tasks) -> List[str]:
172 | with Timer(text="Total elapsed time: {:.1f}"):
173 | chunks = self.chunks(tasks, self.batch_size)
174 | num_chunks = math.ceil(len(tasks) / self.batch_size)
175 | responses: List[ResponseStats] = self.do_one_per_period(chunks, num_chunks, self.workers.do)
176 | answers, stats = list(zip(*responses))
177 | self.overall_stats.log_queries(list(stats))
178 | self.console_log(LogLevel.INFO, f'stats: {self.overall_stats}')
179 | return list(answers)
180 |
181 | def do_one_per_period(self, per_period_chunks, num_chunks,
182 | per_period_fn: Callable[[Any], Tuple[List[ResponseStats], int]]) -> List[ResponseStats]:
183 | responses: List[ResponseStats] = []
184 | for count, chunk in enumerate(per_period_chunks):
185 | with Timer(text="Expected to spend 60s if API called. Elapsed: {:.1f}s. (< 60s ok, if cache lookup)"):
186 | self.console_log(LogLevel.INFO, f'Sending {len(chunk)} queries to OAI in parallel.')
187 | start = NOW_MS()
188 | resp_list, num_expensive = self.with_unavailable_backoff(per_period_fn, chunk)
189 | responses += resp_list
190 | elapsed = NOW_MS() - start
191 | frac_api = float(num_expensive) / len(chunk)
192 | frac_cache = float(len(chunk) - num_expensive) / len(chunk)
193 | self.console_log(LogLevel.INFO, f'Done {count + 1}/{num_chunks} ({frac_api * 100:.2f}% API calls, {frac_cache * 100:.2f}% cache lookup)')
194 |
195 | # sleep for 100ms more than what is needed to make it one min
196 | pause_ms = frac_api * (ONE_PERIOD_MS - elapsed + 100)
197 | if pause_ms > 0:
198 | self.console_log(LogLevel.WARN, f'Pausing for {pause_ms / 1000.0}s to stay within API rate budget')
199 | time.sleep(pause_ms / 1000.0)
200 | return responses
201 |
202 | def console_log(self, lvl: LogLevel, msg):
203 | if lvl.value >= self.console_log_lvl.value:
204 | return
205 | print(msg)
206 |
207 | def with_unavailable_backoff(self, per_period_fn, chunk):
208 | tries = 0
209 | while tries < BACKOFF_NUM_RETRIES:
210 | try:
211 | return per_period_fn(chunk)
212 | except Exception as e:
213 | self.console_log(LogLevel.WARN, BACKOFF_MSG(e))
214 | time.sleep(BACKOFF_TIME_SECONDS)
215 | ex = e
216 | tries += 1
217 | # if failed after enough tries, terminate process
218 | # restarting will pull any data already downloaded from cache
219 | # so no destructive loss. we just revert to user to manually restart
220 | self.console_log(LogLevel.WARN, BACKOFF_ABORT_MSG(ex))
221 | raise ex
222 |
223 | def chunks(self, lst, batch_size):
224 | for i in range(0, len(lst), batch_size):
225 | yield lst[i:i + batch_size]
226 |
227 |
228 | class ParameterizedModel:
229 | def __init__(self,
230 | temp: float,
231 | instruction: str,
232 | who_are_you: str,
233 | few_shot: Dict[str, str],
234 | model: KnownModel,
235 | agent_name: str,
236 | mk_tasks: bool = False,
237 | batch_sz: int = 200,
238 | num_parallel: int = 50,
239 | ):
240 | self.pull_from_cache = temp < DETERMINISTIC_THRESHOLD
241 |
242 | self.temperature = temp
243 | self.instruction = instruction
244 | self.who_are_you = who_are_you
245 | self.few_shot = few_shot
246 | self.model = model
247 |
248 | self.agent_name = agent_name
249 | self.batch_sz = batch_sz
250 | self.num_parallel = num_parallel
251 |
252 | self.mk_tasks = mk_tasks
253 |
254 | def __hash__(self):
255 | hashes = [hash(v) for v in vars(self)]
256 | init = 42
257 | return functools.reduce(lambda a, b: a ^ b, hashes, init)
258 |
259 | def __eq__(self, other):
260 | eq_vars = vars(self) == vars(other)
261 | return (isinstance(other, self.__class__) and eq_vars)
262 |
263 | def __repr__(self):
264 | return f'PM({self.model.name}, {self.agent_name}, task_maker = {self.mk_tasks})'
265 |
266 | class TasksForModel:
267 | def __init__(self, tasks: List[str], params: ParameterizedModel):
268 | self.tasks = tasks
269 | self.params = params
270 |
271 | class OracleTaskQ:
272 | TASKS_DIR = "oracle_task_queue"
273 | TASK_FILE_SUFFIX = ".pickle"
274 |
275 | @classmethod
276 | def write_tasks(cls, tasks: List[str], params: ParameterizedModel) -> None:
277 | cls.ensure_tq_dir_exists()
278 | existing: List[int] = cls.idents_in_task_dir()
279 | ident = max(existing) + 1 if existing else 0
280 | fname = cls.task_file(ident)
281 | tm = TasksForModel(tasks, params)
282 | Persist.save(tm, fname)
283 |
284 | @classmethod
285 | def task_file(cls, ident: int) -> str:
286 | cls.ensure_tq_dir_exists()
287 | return os.path.join(cls.TASKS_DIR, f"{ident}{cls.TASK_FILE_SUFFIX}")
288 |
289 | @classmethod
290 | def idents_in_task_dir(cls) -> List[int]:
291 | cls.ensure_tq_dir_exists()
292 | extract = lambda fname: int(fname[:-len(cls.TASK_FILE_SUFFIX)])
293 | return sorted([extract(f) for f in os.listdir(cls.TASKS_DIR)])
294 |
295 | @classmethod
296 | def purge_tasks(cls, idents: List[int]) -> None:
297 | cls.ensure_tq_dir_exists()
298 | for i in idents:
299 | fname = cls.task_file(i)
300 | os.remove(fname)
301 |
302 | @classmethod
303 | def ensure_tq_dir_exists(cls) -> None:
304 | if not os.path.exists(cls.TASKS_DIR):
305 | os.makedirs(cls.TASKS_DIR, exist_ok = True)
306 |
307 | class ClosedAPI:
308 | MAKER_PLACEHOLDER = "PLACEHOLDER_FILL_LATER"
309 |
310 | def __init__(self, params: ParameterizedModel, console_loglevel: LogLevel = LogLevel.LOWEST):
311 | self.params = params
312 | self.cacher = QueryCache(params.agent_name)
313 | self.rate_limited_runner = RateLimited(self.cached_api_call, params.batch_sz, params.num_parallel, console_loglevel)
314 | self.TASK_MAKER_MODE = params.mk_tasks
315 |
316 | # to be overriden
317 | def deobject(self, obj_resp: Any) -> str: # type: ignore [empty-body]
318 | pass
319 |
320 | # to be overriden
321 | def extract_answer(self, resp: str) -> str: # type: ignore [empty-body]
322 | pass
323 |
324 | # to be overriden
325 | def to_prompt_task(self, task: str) -> Any: # type: ignore [empty-body]
326 | pass
327 |
328 | # to be overriden
329 | def reset_library(self, model: KnownModel) -> None: # type: ignore [empty-body]
330 | pass
331 |
332 | # to be overriden
333 | def model_ask(self, prompt: str) -> Awaitable[Any]: # type: ignore [empty-body]
334 | pass
335 |
336 | # to be overriden
337 | def spent(self, response) -> float: # type: ignore [empty-body]
338 | pass
339 |
340 | def sync_solver(self, task: str):
341 | ans_stat, api_call_not_cache = asyncio.run(self.cached_api_call(task))
342 | ans, stat = ans_stat
343 | return ans
344 |
345 | def maker_placeholder(self, sz: int) -> List[str]:
346 | return [ ClosedAPI.MAKER_PLACEHOLDER ] * sz
347 |
348 | def make_tasks(self, tasks: List[str]) -> List[str]:
349 | OracleTaskQ.write_tasks(tasks, self.params)
350 | placeholders = self.maker_placeholder(len(tasks))
351 | return placeholders
352 |
353 | def query(self, tasks: List[str], rate_limited: bool = True) -> List[str]:
354 | if self.TASK_MAKER_MODE:
355 | return self.make_tasks(tasks)
356 |
357 | # actual solving mode, call API
358 | self.reset_library(self.params.model)
359 |
360 | if rate_limited:
361 | solved = self.rate_limited_runner.do(tasks)
362 | else:
363 | solved = [self.sync_solver(s) for s in tasks]
364 | return solved
365 |
366 | async def cached_api_call(self, task: str) -> Tuple[ResponseStats, bool]:
367 | # if in cache pull from cache
368 | if self.params.pull_from_cache:
369 | cached = self.cacher.get(task)
370 | if cached:
371 | return (cached, QStat(0, 0)), False
372 |
373 | # not cached, make api call
374 | answer, stat = await self.api_call(task)
375 |
376 | if answer != OFFLINE_DEFER:
377 | # write to cache even in the case when we don't pull from it
378 | self.cacher.put(task, answer)
379 |
380 | return (answer, stat), True
381 |
382 | async def api_call(self, task: str) -> ResponseStats:
383 |
384 | start_ms = NOW_MS()
385 | response = await self.model_ask(self.to_prompt_task(task))
386 | elapsed = NOW_MS() - start_ms
387 |
388 | if response == OFFLINE_DEFER:
389 | return OFFLINE_DEFER, QStat(0, 0)
390 |
391 | cost = self.spent(response)
392 | txt_response = self.deobject(response)
393 | return txt_response, QStat(cost, elapsed)
394 |
395 | def snapshot_api_query_cache(self):
396 | self.cacher.save_snapshot()
397 |
398 | class Runner:
399 | @classmethod
400 | def run(cls, name: str, snapshots_specs: str,
401 | cot: bool, few_shot_num: int, temperature: float,
402 | verbose: bool = False, save_snaphot: bool = False): # type: ignore [empty-body]
403 | pass
404 |
--------------------------------------------------------------------------------
/model_api/file_api.py:
--------------------------------------------------------------------------------
1 | import os
2 | from model_api.closed_api import ClosedAPI, RateLimited, KnownModel, PERIODS_PER_MIN, ParameterizedModel, OFFLINE_DEFER
3 | from typing import Any, Awaitable, List, Dict, Optional
4 |
5 | END_TAG = "\n~~~\n"
6 | MAX_TOKENS = 1024
7 | DEFAULT_PROMPT_FORMAT = "Problem:\n{prompt}\nSolution:\n{response}"
8 |
9 | mk_model = lambda name: KnownModel(
10 | name,
11 | is_chat = False,
12 | api_org = None,
13 | api_key = "",
14 | api_base = "",
15 | prompt_format = DEFAULT_PROMPT_FORMAT)
16 |
17 | class OFFLINE_PARAMS:
18 | NAMES = {
19 | 'gemini-ultra': 'gemini-ultra',
20 | 'gemini-pro': 'gemini-pro',
21 | 'gemini-nano': 'gemini-nano',
22 | }
23 | SHORT_NAMES = { short: mk_model(model) for short, model in NAMES.items() }
24 |
25 | class FileAPI(ClosedAPI):
26 | def __init__(self, params: ParameterizedModel, mode_write_questions: bool):
27 | super().__init__(params)
28 |
29 | self.params = params
30 | self.prelude = self.few_shot_format(params.few_shot)
31 |
32 | self.mode_write_questions = mode_write_questions
33 | self.offline_prompts: List[Dict[str, Any]] = []
34 | self.offline_answers = self.read_offline(params.model.name) if not mode_write_questions else None
35 |
36 | def read_offline(self, model_name: str) -> Dict[str, str]:
37 | assert False, f'unimplemented'
38 |
39 | def deobject(self, message: Any) -> str:
40 | completion = message
41 | assert isinstance(completion, str), f'model output is not str: {completion}'
42 | return completion
43 |
44 | def extract_answer(self, response) -> str:
45 | completion = response.lstrip()
46 | end = completion.find(END_TAG)
47 | answer = completion[:end] if end != -1 else completion
48 | answer = answer.strip()
49 | return answer
50 |
51 | def to_prompt_task(self, task: str) -> Any:
52 | return self.prelude + self.params.instruction + self.format(task, None)
53 |
54 | def reset_library(self, model: KnownModel) -> None:
55 | return
56 |
57 | def model_ask(self, prompt: str) -> Awaitable[Any]:
58 | if self.mode_write_questions:
59 | # question mode
60 | return self.async_write_prompt(prompt,
61 | model = self.params.model.name,
62 | max_tokens = MAX_TOKENS,
63 | temperature = self.params.temperature)
64 | else:
65 | # answer mode
66 | return self.async_read_response(prompt)
67 |
68 | async def async_write_prompt(self, prompt,
69 | model: str,
70 | max_tokens: int,
71 | temperature: float) -> str:
72 | prompt_json = {
73 | 'prompt': prompt,
74 | 'model': model,
75 | 'max_tokens': max_tokens,
76 | 'temperature': temperature
77 | }
78 | self.offline_prompts.append(prompt_json)
79 | return OFFLINE_DEFER
80 |
81 | async def async_read_response(self, prompt) -> str:
82 | assert self.offline_answers, f'No offline answers available'
83 | assert prompt in self.offline_answers, f'Prompt not completed: {prompt}'
84 | message = self.offline_answers[prompt]
85 | return message
86 |
87 | def spent(self, response) -> float:
88 | return 0.0
89 |
90 | def format(self, inp: str, out: Optional[str]) -> str:
91 | resp = out if out else ""
92 | assert self.params.model.prompt_format, f'prompt format not set'
93 | formatted = self.params.model.prompt_format.format(prompt = inp, response = resp)
94 | return formatted
95 |
96 | def few_shot_format(self, ios: Dict[str, str]) -> str:
97 | fs = ""
98 | for inp, out in ios.items():
99 | fs += self.format(inp, out) + END_TAG
100 | return fs
101 |
102 |
--------------------------------------------------------------------------------
/model_api/gpt.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 | from copy import deepcopy
4 | from typing import Dict, List, Tuple, Callable, Any, Awaitable, Optional
5 |
6 | import openai # type: ignore
7 |
8 | from model_api.closed_api import ClosedAPI, RateLimited, KnownModel, PERIODS_PER_MIN, ParameterizedModel
9 | from model_api.closed_api import OracleTaskQ
10 | from unformatted_llm import UnformattedLLM
11 | from persist import Persist
12 |
13 | # In debug mode will only make limited API queries
14 | DEBUG_MODE_NUM_LIMIT = None # 200 # or None for non-debug mode
15 |
16 | # end few shot instances with special tag
17 | END_TAG = "\n~~~\n"
18 |
19 | # how much buffer on being nice with API calls; e.g., if 100/min allowed then we do 50/min if factor = 2
20 | BATCH_SZ_FACTOR_PER_MIN = 8
21 | # extra nice on API calls, by reducing batch size "permitted" based on API rate, divided by this factor
22 | EXTRA_NICE = 4
23 |
24 | # find these keys at https://platform.openai.com/account/api-keys
25 | # ... org-... at url above Organization->Settings
26 | # ... sk- at url above User->API Keys
27 | API_ORG = os.getenv("OPENAI_ORG")
28 | API_KEY = os.getenv("OPENAI_API_KEY")
29 |
30 | def ensure_keys():
31 | if API_KEY and API_ORG:
32 | return
33 | print(f'OAI keys missing. export OPENAI_API_KEY and OPENAI_ORG. Aborting.')
34 | print(f'[WARN] You might have to purge the oracle task queue at {OracleTaskQ.TASKS_DIR}')
35 | print(f'[WARN] Some no-key tasks might have been written to queue')
36 | exit(-1)
37 |
38 | class OAI_PARAMS:
39 | # gpt rate limits: https://platform.openai.com/account/rate-limits
40 | QUERY_PER_MIN_LIMIT = {
41 | "gpt4": 200,
42 | "gpt3": 3500,
43 | }
44 | if isinstance(DEBUG_MODE_NUM_LIMIT, int):
45 | QUERY_PER_MIN_LIMIT = {
46 | "gpt4": min(200, DEBUG_MODE_NUM_LIMIT),
47 | "gpt3": min(3500, DEBUG_MODE_NUM_LIMIT),
48 | }
49 |
50 | # https://openai.com/pricing#language-models
51 | MODEL_COST_PER_TOKEN = {
52 | "gpt4": 0.03 / 1000,
53 | "gpt3": 0.0015 / 1000,
54 | }
55 |
56 | # Note, legacy text models, e.g., DAVINCI are being deprecated Jan 2024
57 | # https://platform.openai.com/docs/deprecations/base-gpt-models
58 | @classmethod
59 | def cps(cls, m):
60 | return cls.MODEL_COST_PER_TOKEN[m]
61 | @classmethod
62 | def bsz(cls, m):
63 | return int(cls.QUERY_PER_MIN_LIMIT[m] / (PERIODS_PER_MIN * BATCH_SZ_FACTOR_PER_MIN))
64 | @classmethod
65 | def np(cls, m):
66 | return int(cls.bsz(m) / EXTRA_NICE) if DEBUG_MODE_NUM_LIMIT is None else 10
67 | @classmethod
68 | def rates(cls, m):
69 | return { "batch_size": cls.bsz(m), "num_parallel": cls.np(m), "cps": cls.cps(m) }
70 | LOC = { "api_org": API_ORG, "api_key": API_KEY, "api_base": "https://api.openai.com/v1" }
71 |
72 | class OAI_MODELS:
73 | GPT4 = KnownModel("gpt-4", is_chat = True, **OAI_PARAMS.LOC, **OAI_PARAMS.rates("gpt4")) # type: ignore
74 | GPT3 = KnownModel("gpt-3.5-turbo", is_chat = True, **OAI_PARAMS.LOC, **OAI_PARAMS.rates("gpt3")) # type: ignore
75 |
76 | SHORT_NAMES = {"gpt4": GPT4, "gpt3": GPT3}
77 |
78 | DEFAULT_MODEL = GPT3
79 |
80 | class GPT(ClosedAPI):
81 | def __init__(self, params: ParameterizedModel):
82 | self.params = params
83 | super().__init__(params)
84 |
85 | a, t, c, p = GPT.model_fns(params.model, params.temperature, params.few_shot, params.instruction, params.who_are_you)
86 | self.model_ask = a # type: ignore [method-assign]
87 | self.to_prompt_task = t # type: ignore [method-assign]
88 | self.deobject = c # type: ignore [method-assign]
89 | self.prelude = p
90 |
91 | def extract_answer(self, response) -> str:
92 | completion = response.lstrip()
93 | end = completion.find(END_TAG)
94 | answer = completion[:end] if end != -1 else completion
95 | answer = answer.strip()
96 | return answer
97 |
98 | def reset_library(self, model_params):
99 | # reset openai library
100 | openai.organization = model_params.api_org
101 | openai.api_key = model_params.api_key
102 | openai.api_base = model_params.api_base
103 |
104 | def spent(self, response) -> float:
105 | return response['usage']['total_tokens'] * self.params.model.cost_per_token
106 |
107 | @classmethod
108 | def model_fns(cls, model, temp, few_shot, instruction, who_are_you) -> Tuple[Any, Any, Any, Any]:
109 | # note `acreate` instead of `create` for async
110 | # docs: https://github.com/openai/openai-python#async-api
111 |
112 | # chat ask, raw api query
113 | def chat_ask(msgs):
114 | # print(f'Sending query: {msgs}')
115 | return openai.ChatCompletion.acreate(
116 | model = model.name,
117 | messages = msgs,
118 | temperature = temp,
119 | )
120 | # prelude added to each query
121 | who = {"role": "system", "content": who_are_you}
122 | chat_prelude = [who]
123 | for inp, out in few_shot.items():
124 | que = {"role": "user", "content": instruction + inp}
125 | chat_prelude.append(que)
126 | ans = {"role": "assistant", "content": out + END_TAG}
127 | chat_prelude.append(ans)
128 | # extract
129 | chat_txt_from_obj = lambda response: response['choices'][0]['message']['content']
130 |
131 | def chat_task(task: str):
132 | messages = deepcopy(chat_prelude)
133 | que = {"role": "user", "content": instruction + task}
134 | messages.append(que)
135 | return messages
136 |
137 | # pick appropriate functions based on model type
138 | callfn = chat_ask
139 | promptfn = chat_task
140 | deobject = chat_txt_from_obj
141 | prelude = chat_prelude
142 | return callfn, promptfn, deobject, prelude
143 |
144 | def check_model_access(self):
145 | # check that we have access to this model
146 | self.reset_library(self.params.model)
147 | models = openai.Model.list()["data"]
148 | assert list(filter(lambda x: x["id"] == self.params.model.name, models)), "No access to {self.params.model.name}"
149 |
--------------------------------------------------------------------------------
/model_api/mis.py:
--------------------------------------------------------------------------------
1 | from eval.runner import EvalRunner, mk_dir_safe
2 | import argparse
3 | import sys
4 | from typing import Dict, List, Tuple, Any
5 | from math_utils.math_helpers import rm_latex_math
6 | from unformatted_llm import UnformattedLLM
7 | from model_api.closed_api import KnownModel, ParameterizedModel, Runner
8 | from model_api.mistral import Mistral, MISTRAL_PARAMS
9 | from evaluate import DEFAULT_SNAPSHOTS_FILE, DEFAULT_FEW_SHOT_NUM, DEFAULT_TEMPERATURE
10 | from chain_of_thought import COT_INSTRUCTION, ChainOfThought
11 |
12 | _MISTRAL = MISTRAL_PARAMS()
13 |
14 | class Answers(Runner):
15 | def __init__(self, model: KnownModel, use_cot: bool, few_shot_num: int, temperature: float):
16 | self.model = model
17 | self.use_cot = use_cot
18 | self.cot = ChainOfThought()
19 | unformatted = UnformattedLLM()
20 |
21 | few_shot_builder = self.cot if use_cot else unformatted
22 | instruction = COT_INSTRUCTION if use_cot else unformatted.INSTRUCTION
23 | few_shot: Dict[str, str] = few_shot_builder.few_shot_limited(few_shot_num)
24 | cache_infer_params = f'temp={temperature}_cot={use_cot}_fs={few_shot_num}'
25 | cache_model_name = mk_dir_safe(model.name)
26 | params = ParameterizedModel(
27 | temp = temperature,
28 | instruction = instruction,
29 | who_are_you = "",
30 | few_shot = few_shot,
31 | model = model,
32 | agent_name = f"Mistral_Eval_{cache_model_name}_{cache_infer_params}",
33 | )
34 | self.mistral = Mistral(params)
35 |
36 | def answers(self, prb: str) -> List[Tuple[str, str]]:
37 | completion = self.mistral.query([prb], rate_limited = False)[0]
38 | answer = self.mistral.extract_answer(completion)
39 | if self.use_cot:
40 | answer = self.cot.extract_answer(answer)
41 | return [(answer, completion)]
42 |
43 | @classmethod
44 | def run(cls, name: str, snapshots_specs: str,
45 | cot: bool, few_shot_num: int, temperature: float,
46 | verbose: bool = False, save_snaphot: bool = False, extra_params: Dict[str, Any] = {}):
47 | known_model = _MISTRAL.models[name]
48 | answerer = Answers(known_model, cot, few_shot_num, temperature)
49 | e = EvalRunner(answerer, snapshots_specs, verbose).do()
50 | if save_snaphot:
51 | answerer.mistral.snapshot_api_query_cache()
52 | return e
53 |
54 |
55 | if __name__ == "__main__":
56 | parser = argparse.ArgumentParser()
57 | parser.add_argument("--model", required=True,
58 | help = f"Model has to be one of {list(_MISTRAL.models.keys())}")
59 | parser.add_argument("--snapshots_specs", type=str, default=DEFAULT_SNAPSHOTS_FILE,
60 | help = f"JSON of static and monthly snapshots")
61 | parser.add_argument("--verbose", action='store_true',
62 | help="Outcomes of each test, one per line, on console")
63 | parser.add_argument("--use_chain_of_thought", action='store_true',
64 | help="Use chain of thought instruction and postprocessing")
65 | parser.add_argument("--few_shot_num", type=str, default=DEFAULT_FEW_SHOT_NUM,
66 | help=f"Default few shot count: {DEFAULT_FEW_SHOT_NUM}")
67 | parser.add_argument("--temperature", type=float, default=DEFAULT_TEMPERATURE,
68 | help=f"Default temperature: {DEFAULT_TEMPERATURE}")
69 | parser.add_argument("--save_snapshot", action='store_true',
70 | help="Save API query snapshot as .tar.gz file")
71 | args = parser.parse_args()
72 |
73 | Answers.run(args.model, args.snapshots_specs,
74 | args.use_chain_of_thought, args.few_shot_num, args.temperature,
75 | args.verbose, args.save_snapshot)
76 |
--------------------------------------------------------------------------------
/model_api/mistral.py:
--------------------------------------------------------------------------------
1 | from mistralai.client import MistralClient
2 | from mistralai.models.chat_completion import ChatMessage
3 | import os
4 | from model_api.closed_api import ClosedAPI, RateLimited, KnownModel, PERIODS_PER_MIN, ParameterizedModel
5 | from unformatted_llm import UnformattedLLM
6 | from typing import Any, Awaitable, Dict, Optional, List, Tuple
7 | from tqdm import tqdm # type: ignore
8 |
9 | MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY")
10 | END_TAG = "\n~~~\n"
11 | DEFAULT_END_TAGS = [END_TAG, '']
12 | DEFAULT_PROMPT_FORMAT = ": {prompt}\n: {response}"
13 | MAX_TOKENS = 1024
14 |
15 | class MISTRAL_PARAMS:
16 | def __init__(self):
17 | # https://docs.mistral.ai/platform/endpoints/
18 | # small = 8x7b
19 | # medium = unknown but 8x32b rumoured
20 | # large = unknown, but apparently does well on evals: https://mistral.ai/news/mistral-large/
21 | models_names: Dict[str, str] = {
22 | "mistral-small": "mistral-small-2402",
23 | "mistral-medium": "mistral-medium-2312",
24 | "mistral-large": "mistral-large-2402",
25 | }
26 | self.models: Dict[str, KnownModel] = { n: self.known_from_config(endpoint) for n, endpoint in models_names.items() }
27 |
28 | def known_from_config(self, name: str) -> KnownModel:
29 | is_chat = True
30 | stops: List[str] = DEFAULT_END_TAGS
31 | prompt_format: str = DEFAULT_PROMPT_FORMAT
32 |
33 | return KnownModel(name,
34 | is_chat,
35 | api_org = None,
36 | api_key = MISTRAL_API_KEY,
37 | api_base = "",
38 | stops = stops,
39 | prompt_format = prompt_format)
40 |
41 |
42 | class Mistral(ClosedAPI):
43 | def __init__(self, params: ParameterizedModel):
44 | super().__init__(params)
45 |
46 | self.params = params
47 | self.prelude = self.few_shot_format(params.few_shot)
48 | self.client = MistralClient(api_key = params.model.api_key)
49 |
50 | def deobject(self, obj_resp: Any) -> str:
51 | extract = lambda resp: resp.choices[0].message.content
52 | completion = obj_resp if isinstance(obj_resp, str) else extract(obj_resp)
53 | assert isinstance(completion, str), f'model output is not str: {obj_resp}'
54 | return completion
55 |
56 | def extract_answer(self, response) -> str:
57 | completion = response.lstrip()
58 | assert self.params.model.stops, f'stop tokens not set'
59 | ends = [completion.find(s) for s in self.params.model.stops if completion.find(s) != -1]
60 | answer = completion[:ends[0]] if ends else completion
61 | answer = answer.strip()
62 | return answer
63 |
64 | async def async_ask(self, prompt: str):
65 | # print(f'Sending query: {prompt}')
66 | return self.client.chat(
67 | model = self.params.model.name,
68 | messages = [
69 | ChatMessage(role="user", content=prompt)
70 | ],
71 | max_tokens = MAX_TOKENS,
72 | temperature = self.params.temperature,
73 | )
74 |
75 | def to_prompt_task(self, task: str) -> Any:
76 | return self.prelude + self.params.instruction + self.format(task, None)
77 |
78 | def reset_library(self, model: KnownModel) -> None:
79 | return
80 |
81 | def model_ask(self, prompt: str) -> Awaitable[Any]:
82 | return self.async_ask(prompt)
83 |
84 | def spent(self, response) -> float:
85 | return 0.0
86 |
87 | def format(self, inp: str, out: Optional[str]) -> str:
88 | resp = out if out else ""
89 | assert self.params.model.prompt_format, f'prompt format not set'
90 | formatted = self.params.model.prompt_format.format(prompt = inp, response = resp)
91 | return formatted
92 |
93 | def few_shot_format(self, ios: Dict[str, str]) -> str:
94 | fs = ""
95 | for inp, out in ios.items():
96 | assert self.params.model.stops, f'stop tokens not set'
97 | fs += self.format(inp, out) + self.params.model.stops[0]
98 | return fs
99 |
--------------------------------------------------------------------------------
/model_api/oai.py:
--------------------------------------------------------------------------------
1 | from eval.runner import EvalRunner, mk_dir_safe
2 | import argparse
3 | import sys
4 | from typing import Dict, List, Tuple, Any
5 | from math_utils.math_helpers import rm_latex_math
6 | from unformatted_llm import UnformattedLLM
7 | from model_api.gpt import GPT, OAI_MODELS
8 | from model_api.closed_api import KnownModel, ParameterizedModel, Runner
9 | from evaluate import DEFAULT_SNAPSHOTS_FILE, DEFAULT_FEW_SHOT_NUM, DEFAULT_TEMPERATURE
10 | from chain_of_thought import COT_INSTRUCTION, ChainOfThought
11 |
12 | WHO_ARE_YOU = "You are a expert in mathematics, logic, and formal reasoning. "
13 |
14 | class Answers(Runner):
15 | def __init__(self, model: KnownModel, use_cot: bool, few_shot_num: int, temperature: float):
16 | self.model = model
17 | self.use_cot = use_cot
18 | self.cot = ChainOfThought()
19 | unformatted = UnformattedLLM()
20 |
21 | few_shot_builder = self.cot if use_cot else unformatted
22 | instruction = COT_INSTRUCTION if use_cot else unformatted.INSTRUCTION
23 | few_shot: Dict[str, str] = few_shot_builder.few_shot_limited(few_shot_num)
24 | cache_infer_params = f'temp={temperature}_cot={use_cot}_fs={few_shot_num}'
25 | cache_model_name = mk_dir_safe(model.name)
26 | params = ParameterizedModel(
27 | temp = temperature,
28 | instruction = instruction,
29 | who_are_you = WHO_ARE_YOU,
30 | few_shot = few_shot,
31 | model = model,
32 | agent_name = f"OAI_Eval_{cache_model_name}_{cache_infer_params}",
33 | )
34 | self.gpt = GPT(params)
35 |
36 | def answers(self, prb: str) -> List[Tuple[str, str]]:
37 | try:
38 | completion = self.gpt.query([prb], rate_limited = False)[0]
39 | except Exception as e:
40 | if self.known_error(e):
41 | completion = ""
42 | else:
43 | raise e
44 | answer = self.gpt.extract_answer(completion)
45 | if self.use_cot:
46 | answer = self.cot.extract_answer(answer)
47 | return [(answer, completion)]
48 |
49 | def known_error(self, e) -> bool:
50 | KNOWN = [
51 | "Sorry! We've encountered an issue with repetitive patterns in your prompt. Please try again with a different prompt."
52 | ]
53 | print(f'API ERROR: {str(e)}')
54 | return str(e) in KNOWN
55 |
56 | @classmethod
57 | def run(cls, name: str, snapshots_specs: str,
58 | cot: bool, few_shot_num: int, temperature: float,
59 | verbose: bool = False, save_snaphot: bool = False, extra_params: Dict[str, Any] = {}):
60 | known_model = OAI_MODELS.SHORT_NAMES[name]
61 | answerer = Answers(known_model, cot, few_shot_num, temperature)
62 | e = EvalRunner(answerer, snapshots_specs, verbose).do()
63 | if save_snaphot:
64 | answerer.gpt.snapshot_api_query_cache()
65 | return e
66 |
67 |
68 | if __name__ == "__main__":
69 | parser = argparse.ArgumentParser()
70 | parser.add_argument("--model", required=True,
71 | help = f"Model has to be one of {list(OAI_MODELS.SHORT_NAMES.keys())}")
72 | parser.add_argument("--snapshots_specs", type=str, default=DEFAULT_SNAPSHOTS_FILE,
73 | help = f"JSON of static and monthly snapshots")
74 | parser.add_argument("--verbose", action='store_true',
75 | help="Outcomes of each test, one per line, on console")
76 | parser.add_argument("--use_chain_of_thought", action='store_true',
77 | help="Use chain of thought instruction and postprocessing")
78 | parser.add_argument("--few_shot_num", type=str, default=DEFAULT_FEW_SHOT_NUM,
79 | help=f"Default few shot count: {DEFAULT_FEW_SHOT_NUM}")
80 | parser.add_argument("--temperature", type=float, default=DEFAULT_TEMPERATURE,
81 | help=f"Default temperature: {DEFAULT_TEMPERATURE}")
82 | parser.add_argument("--save_snapshot", action='store_true',
83 | help="Save API query snapshot as .tar.gz file")
84 | args = parser.parse_args()
85 |
86 | Answers.run(args.model, args.snapshots_specs,
87 | args.use_chain_of_thought, args.few_shot_num, args.temperature,
88 | args.verbose, args.save_snapshot)
89 |
--------------------------------------------------------------------------------
/model_api/offline.py:
--------------------------------------------------------------------------------
1 | from eval.runner import EvalRunner, mk_dir_safe
2 | import argparse
3 | import sys
4 | import json
5 | from typing import Dict, List, Tuple, Optional, Any
6 | from math_utils.math_helpers import rm_latex_math
7 | from unformatted_llm import UnformattedLLM
8 | from model_api.closed_api import KnownModel, ParameterizedModel
9 | from model_api.file_api import FileAPI, OFFLINE_PARAMS
10 | from evaluate import DEFAULT_SNAPSHOTS_FILE, DEFAULT_FEW_SHOT_NUM, DEFAULT_TEMPERATURE, SPEC_EXTRA_PARAMS_MODE_WRITE_OFFLINE
11 | from chain_of_thought import COT_INSTRUCTION, ChainOfThought
12 |
13 | class Answers:
14 | def __init__(self, model: KnownModel, use_cot: bool, few_shot_num: int, temperature: float, mode_write_questions: bool):
15 | self.model = model
16 | self.use_cot = use_cot
17 | self.cot = ChainOfThought()
18 | unformatted = UnformattedLLM()
19 |
20 | few_shot_builder = self.cot if use_cot else unformatted
21 | instruction = COT_INSTRUCTION if use_cot else unformatted.INSTRUCTION
22 | few_shot: Dict[str, str] = few_shot_builder.few_shot_limited(few_shot_num)
23 | cache_infer_params = f'temp={temperature}_cot={use_cot}_fs={few_shot_num}'
24 | cache_model_name = mk_dir_safe(model.name)
25 | params = ParameterizedModel(
26 | temp = temperature,
27 | instruction = instruction,
28 | who_are_you = "",
29 | few_shot = few_shot,
30 | model = model,
31 | agent_name = f"Offline_Eval_{cache_model_name}_{cache_infer_params}",
32 | )
33 | self.file_api = FileAPI(params, mode_write_questions)
34 |
35 | def answers(self, prb: str) -> List[Tuple[str, str]]:
36 | completion = self.file_api.query([prb], rate_limited = False)[0]
37 | answer = self.file_api.extract_answer(completion)
38 | if self.use_cot:
39 | answer = self.cot.extract_answer(answer)
40 | return [(answer, completion)]
41 |
42 | def write_questions(self, e):
43 | def write(data):
44 | fname = self.file_api.params.agent_name + '.json'
45 | with open(fname, "w") as jfile:
46 | json.dump(data, jfile, indent=4)
47 |
48 | duplicates = 0
49 | for ref in e.problems_tested:
50 | matched = None
51 | for prompt in self.file_api.offline_prompts:
52 | if ref['problem'] in prompt['prompt']:
53 | if matched and not ref['is_static']:
54 | duplicates += 1
55 | matched = prompt
56 | assert matched, f'Failed to match: {prompt}'
57 | for k, v in matched.items():
58 | ref[k] = v
59 | print(f'Duplicates found: {duplicates}. Investigate!')
60 |
61 | write(e.problems_tested)
62 |
63 | @classmethod
64 | def run(cls, name: str, snapshots_specs: str,
65 | cot: bool, few_shot_num: int, temperature: float,
66 | verbose: bool = False, save_snaphot: bool = False, extra_params: Dict[str, Any] = {}):
67 | mode_write_questions = extra_params[SPEC_EXTRA_PARAMS_MODE_WRITE_OFFLINE] if SPEC_EXTRA_PARAMS_MODE_WRITE_OFFLINE in extra_params else False
68 | known_model = OFFLINE_PARAMS.SHORT_NAMES[name]
69 | answerer = Answers(known_model, cot, few_shot_num, temperature, mode_write_questions)
70 | e = EvalRunner(answerer, snapshots_specs, verbose).do()
71 | if mode_write_questions:
72 | answerer.write_questions(e)
73 | return None
74 | if save_snaphot:
75 | answerer.file_api.snapshot_api_query_cache()
76 | return e
77 |
78 |
79 | if __name__ == "__main__":
80 | parser = argparse.ArgumentParser()
81 | parser.add_argument("--model", required=True,
82 | help = f"Model has to be one of {list(OFFLINE_PARAMS.SHORT_NAMES.keys())}")
83 | parser.add_argument("--snapshots_specs", type=str, default=DEFAULT_SNAPSHOTS_FILE,
84 | help = f"JSON of static and monthly snapshots")
85 | parser.add_argument("--verbose", action='store_true',
86 | help="Outcomes of each test, one per line, on console")
87 | parser.add_argument("--use_chain_of_thought", action='store_true',
88 | help="Use chain of thought instruction and postprocessing")
89 | parser.add_argument("--few_shot_num", type=str, default=DEFAULT_FEW_SHOT_NUM,
90 | help=f"Default few shot count: {DEFAULT_FEW_SHOT_NUM}")
91 | parser.add_argument("--temperature", type=float, default=DEFAULT_TEMPERATURE,
92 | help=f"Default temperature: {DEFAULT_TEMPERATURE}")
93 | parser.add_argument("--save_snapshot", action='store_true',
94 | help="Save API query snapshot as .tar.gz file")
95 | parser.add_argument("--mode_write_questions", action='store_true',
96 | help="Write questions to output dump, to be solved offline")
97 | args = parser.parse_args()
98 |
99 | extra_params = { SPEC_EXTRA_PARAMS_MODE_WRITE_OFFLINE: args.mode_write_questions }
100 | Answers.run(args.model, args.snapshots_specs,
101 | args.use_chain_of_thought, args.few_shot_num, args.temperature,
102 | args.verbose, args.save_snapshot, extra_params)
103 |
--------------------------------------------------------------------------------
/model_api/oss.py:
--------------------------------------------------------------------------------
1 | import together # type: ignore
2 | import os
3 | from model_api.closed_api import ClosedAPI, RateLimited, KnownModel, PERIODS_PER_MIN, ParameterizedModel
4 | from unformatted_llm import UnformattedLLM
5 | from typing import Any, Awaitable, Dict, Optional, List, Tuple
6 | from tqdm import tqdm # type: ignore
7 |
8 | TOGETHER_API_KEY = os.getenv("TOGETHER_API_KEY")
9 | END_TAG = "\n~~~\n"
10 | DEFAULT_END_TAGS = [END_TAG, '']
11 | DEFAULT_PROMPT_FORMAT = ": {prompt}\n: {response}"
12 | MAX_TOKENS = 1024
13 |
14 | # Model list: https://docs.together.ai/docs/inference-models
15 | WORTH_IT_LANG = [
16 | "EleutherAI/llemma_7b",
17 | "zero-one-ai/Yi-34B",
18 | "Open-Orca/Mistral-7B-OpenOrca",
19 | "zero-one-ai/Yi-34B",
20 | "meta-llama/Llama-2-70b-hf",
21 | "Qwen/Qwen1.5-72B",
22 | "microsoft/phi-2",
23 | "google/gemma-7b",
24 | "togethercomputer/RedPajama-INCITE-7B-Instruct",
25 | "allenai/OLMo-7B-Instruct",
26 |
27 | "mistralai/Mixtral-8x7B-v0.1",
28 | "togethercomputer/StripedHyena-Hessian-7B",
29 | "WizardLM/WizardLM-70B-V1.0",
30 | ]
31 |
32 |
33 | WORTH_IT_CODE = [
34 | "togethercomputer/CodeLlama-34b-Python",
35 | "togethercomputer/CodeLlama-34b",
36 | "WizardLM/WizardCoder-Python-34B-V1.0",
37 | ]
38 |
39 | WORTH_IT_CHAT = [
40 | "zero-one-ai/Yi-34B-Chat",
41 | "togethercomputer/CodeLlama-34b-Instruct",
42 | "togethercomputer/llama-2-70b-chat",
43 | "mistralai/Mixtral-8x7B-Instruct-v0.1",
44 | "Open-Orca/Mistral-7B-OpenOrca",
45 | "togethercomputer/Pythia-Chat-Base-7B-v0.16",
46 | "togethercomputer/Qwen-7B-Chat",
47 | "togethercomputer/StripedHyena-Nous-7B",
48 | "lmsys/vicuna-13b-v1.5",
49 | "togethercomputer/CodeLlama-34b-Instruct",
50 | "upstage/SOLAR-0-70b-16bit",
51 | ]
52 |
53 | def worth_it_exclude(names: List[str]) -> Tuple[List[str], List[str]]:
54 | keep, exclude = [], []
55 | for n in names:
56 | if n in WORTH_IT_CHAT or n in WORTH_IT_LANG or n in WORTH_IT_CODE:
57 | keep.append(n)
58 | else:
59 | exclude.append(n)
60 | return keep, exclude
61 |
62 | class TOGETHER_PARAMS:
63 | def __init__(self):
64 | models_names: List[str] = [m['name'] for m in together.Models.list()]
65 | print(f'## Available models: {len(models_names)}\n')
66 |
67 | # keep the "excluded" print, it'll show whats available on together as new models get added
68 | worth_it, excluded = worth_it_exclude(models_names)
69 | print(f'## Worth trying: {worth_it}\n')
70 | print(f'## Excluded: {excluded}\n')
71 |
72 | self.models: Dict[str, KnownModel] = { n: self.known_from_config(n) for n in tqdm(worth_it, desc = 'Getting info for "worth it" models') }
73 |
74 | def known_from_config(self, name: str) -> KnownModel:
75 | info = together.Models.info(name)
76 |
77 | # https://docs.together.ai/docs
78 | # >>> together.Models.info(model='mistralai/Mixtral-8x7B-v0.1')
79 | # info: {'modelInstanceConfig': {'appearsIn': [], 'order': 0}, '_id': '6577bf1034e6c1e2bb5283d9', 'name': 'mistralai/Mixtral-8x7B-v0.1', 'display_name': 'Mixtral-8x7B', 'display_type': 'language', 'description': 'The Mixtral-8x7B Large Language Model (LLM) is a pretrained generative Sparse Mixture of Experts.', 'license': 'apache-2.0', 'link': 'https://huggingface.co/mistralai/Mixtral-8x7B-v0.1', 'creator_organization': 'mistralai', 'pricing_tier': 'Featured', 'access': 'open', 'num_parameters': '56000000000', 'show_in_playground': True, 'isFeaturedModel': True, 'context_length': 32768, 'pricing': {'input': 150, 'output': 150, 'hourly': 0}, 'created_at': '2023-12-12T02:01:52.674Z', 'update_at': '2023-12-12T02:01:52.674Z', 'instances': [{'avzone': 'us-east-1a', 'cluster': 'happypiglet'}], 'renamed': 'mistralai/mixtral-8x7b-32kseqlen', 'hardware_label': '', 'descriptionLink': '', 'depth': {'num_asks': 1, 'num_bids': 0, 'num_running': 0, 'qps': 0, 'throughput_in': 0, 'throughput_out': 0, 'error_rate': 0, 'retry_rate': 0, 'stats': [{'avzone': 'us-east-1a', 'cluster': 'happypiglet', 'capacity': 0, 'qps': 0, 'throughput_in': 0, 'throughput_out': 0, 'error_rate': 0, 'retry_rate': 0}]}}
80 |
81 | is_chat = info["display_type"] == 'chat'
82 |
83 | stops: List[str] = DEFAULT_END_TAGS
84 | prompt_format: str = DEFAULT_PROMPT_FORMAT
85 | # override the stops and prompt_format if they are specified (which is the case for chat models)
86 | if is_chat:
87 | # >>> together.Models.info(model='mistralai/Mixtral-8x7B-Instruct-v0.1')["config"]
88 | # {'stop': ['', '[INST]'], 'prompt_format': '[INST] {prompt} [/INST]', 'chat_template_name': 'llama'}
89 | stops = info["config"]["stop"]
90 | prompt_format = info["config"]["prompt_format"] + "{response}"
91 |
92 | return KnownModel(name,
93 | is_chat,
94 | api_org = None,
95 | api_key = TOGETHER_API_KEY,
96 | api_base = "https://api.together.xyz",
97 | stops = stops,
98 | prompt_format = prompt_format)
99 |
100 |
101 | class OSS(ClosedAPI):
102 | def __init__(self, params: ParameterizedModel):
103 | super().__init__(params)
104 |
105 | self.params = params
106 | self.prelude = self.few_shot_format(params.few_shot)
107 |
108 | def deobject(self, obj_resp: Any) -> str:
109 | extract = lambda output: output['output']['choices'][0]['text']
110 | completion = obj_resp if isinstance(obj_resp, str) else extract(obj_resp)
111 | assert isinstance(completion, str), f'model output is not str: {obj_resp}'
112 | return completion
113 |
114 | def extract_answer(self, response) -> str:
115 | completion = response.lstrip()
116 | assert self.params.model.stops, f'stop tokens not set'
117 | ends = [completion.find(s) for s in self.params.model.stops if completion.find(s) != -1]
118 | answer = completion[:ends[0]] if ends else completion
119 | answer = answer.strip()
120 | return answer
121 |
122 | def to_prompt_task(self, task: str) -> Any:
123 | return self.prelude + self.params.instruction + self.format(task, None)
124 |
125 | def reset_library(self, model: KnownModel) -> None:
126 | return
127 |
128 | def model_ask(self, prompt: str) -> Awaitable[Any]:
129 | return self.async_ask(prompt)
130 |
131 | async def async_ask(self, prompt: str):
132 | # print(f'Sending query: {prompt}')
133 | return together.Complete.create(
134 | model = self.params.model.name,
135 | max_tokens = MAX_TOKENS,
136 | temperature = self.params.temperature,
137 | prompt = prompt,
138 | stop = self.params.model.stops
139 | )
140 |
141 | def spent(self, response) -> float:
142 | return 0.0
143 |
144 | def format(self, inp: str, out: Optional[str]) -> str:
145 | resp = out if out else ""
146 | assert self.params.model.prompt_format, f'prompt format not set'
147 | formatted = self.params.model.prompt_format.format(prompt = inp, response = resp)
148 | return formatted
149 |
150 | def few_shot_format(self, ios: Dict[str, str]) -> str:
151 | fs = ""
152 | for inp, out in ios.items():
153 | assert self.params.model.stops, f'stop tokens not set'
154 | fs += self.format(inp, out) + '\n' + self.params.model.stops[0]
155 | return fs
156 |
157 |
--------------------------------------------------------------------------------
/model_api/tog.py:
--------------------------------------------------------------------------------
1 | from eval.runner import EvalRunner, mk_dir_safe
2 | import argparse
3 | import sys
4 | from typing import Dict, List, Tuple, Any
5 | from math_utils.math_helpers import rm_latex_math
6 | from unformatted_llm import UnformattedLLM
7 | from model_api.closed_api import KnownModel, ParameterizedModel
8 | from model_api.oss import OSS, TOGETHER_PARAMS
9 | from evaluate import DEFAULT_SNAPSHOTS_FILE, DEFAULT_FEW_SHOT_NUM, DEFAULT_TEMPERATURE
10 | from chain_of_thought import COT_INSTRUCTION, ChainOfThought
11 |
12 | _TOGETHER = TOGETHER_PARAMS()
13 |
14 | KNOWN_CRASH="400 Client Error: Bad Request for url: https://api.together.xyz/api/inference"
15 |
16 | class Answers:
17 | def __init__(self, model: KnownModel, use_cot: bool, few_shot_num: int, temperature: float):
18 | self.model = model
19 | self.use_cot = use_cot
20 | self.cot = ChainOfThought()
21 | unformatted = UnformattedLLM()
22 |
23 | few_shot_builder = self.cot if use_cot else unformatted
24 | instruction = COT_INSTRUCTION if use_cot else unformatted.INSTRUCTION
25 | few_shot: Dict[str, str] = few_shot_builder.few_shot_limited(few_shot_num)
26 | cache_infer_params = f'temp={temperature}_cot={use_cot}_fs={few_shot_num}'
27 | cache_model_name = mk_dir_safe(model.name)
28 | params = ParameterizedModel(
29 | temp = temperature,
30 | instruction = instruction,
31 | who_are_you = "",
32 | few_shot = few_shot,
33 | model = model,
34 | agent_name = f"Together_Eval_{cache_model_name}_{cache_infer_params}",
35 | )
36 | self.oss = OSS(params)
37 |
38 | def answers(self, prb: str) -> List[Tuple[str, str]]:
39 | try:
40 | completion = self.oss.query([prb], rate_limited = False)[0]
41 | except Exception as he:
42 | if f'{he}' == KNOWN_CRASH:
43 | # print(f'[WARN] CRASH on prb below\n-----\n{prb}\n-----\nIgnoring and Continue!')
44 | completion = ""
45 | else:
46 | raise he
47 | answer = self.oss.extract_answer(completion)
48 | if self.use_cot:
49 | answer = self.cot.extract_answer(answer)
50 | return [(answer, completion)]
51 |
52 | @classmethod
53 | def run(cls, name: str, snapshots_specs: str,
54 | cot: bool, few_shot_num: int, temperature: float,
55 | verbose: bool = False, save_snaphot: bool = False, extra_params: Dict[str, Any] = {}):
56 | known_model = _TOGETHER.models[name]
57 | answerer = Answers(known_model, cot, few_shot_num, temperature)
58 | e = EvalRunner(answerer, snapshots_specs, verbose).do()
59 | if save_snaphot:
60 | answerer.oss.snapshot_api_query_cache()
61 | return e
62 |
63 |
64 | if __name__ == "__main__":
65 | parser = argparse.ArgumentParser()
66 | parser.add_argument("--model", required=True,
67 | help = f"Model has to be one of {list(_TOGETHER.models.keys())}")
68 | parser.add_argument("--snapshots_specs", type=str, default=DEFAULT_SNAPSHOTS_FILE,
69 | help = f"JSON of static and monthly snapshots")
70 | parser.add_argument("--verbose", action='store_true',
71 | help="Outcomes of each test, one per line, on console")
72 | parser.add_argument("--use_chain_of_thought", action='store_true',
73 | help="Use chain of thought instruction and postprocessing")
74 | parser.add_argument("--few_shot_num", type=str, default=DEFAULT_FEW_SHOT_NUM,
75 | help=f"Default few shot count: {DEFAULT_FEW_SHOT_NUM}")
76 | parser.add_argument("--temperature", type=float, default=DEFAULT_TEMPERATURE,
77 | help=f"Default temperature: {DEFAULT_TEMPERATURE}")
78 | parser.add_argument("--save_snapshot", action='store_true',
79 | help="Save API query snapshot as .tar.gz file")
80 | args = parser.parse_args()
81 |
82 | Answers.run(args.model, args.snapshots_specs,
83 | args.use_chain_of_thought, args.few_shot_num, args.temperature,
84 | args.verbose, args.save_snapshot)
85 |
--------------------------------------------------------------------------------
/monthly_snapshots.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "benchmark": "MATH",
4 | "fixed": "https://people.eecs.berkeley.edu/~hendrycks/MATH.tar",
5 | "functionals": [
6 | {
7 | "date": "Dec-2023",
8 | "url": "Dec-2023.tar.gz"
9 | },
10 | {
11 | "date": "Nov-2023",
12 | "url": "Nov-2023.tar.gz"
13 | },
14 | {
15 | "date": "Oct-2023",
16 | "url": "Oct-2023.tar.gz"
17 | }
18 | ]
19 | },
20 | {
21 | "benchmark": "GSM8k",
22 | "static": "https://",
23 | "functionals": []
24 | }
25 | ]
26 |
--------------------------------------------------------------------------------
/monthly_snapshots_only_oct.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "benchmark": "MATH",
4 | "fixed": "https://people.eecs.berkeley.edu/~hendrycks/MATH.tar",
5 | "functionals": [
6 | {
7 | "date": "Oct-2023",
8 | "url": "Oct-2023.tar.gz"
9 | }
10 | ]
11 | },
12 | {
13 | "benchmark": "GSM8k",
14 | "static": "https://",
15 | "functionals": []
16 | }
17 | ]
18 |
--------------------------------------------------------------------------------
/persist.py:
--------------------------------------------------------------------------------
1 | import pickle
2 | import os
3 |
4 | class Persist:
5 | @classmethod
6 | def overwrite(cls, fname) -> bool:
7 | ask = lambda: input(f'{fname} exists. Overwrite? [y/n]')
8 | if os.path.exists(fname):
9 | yn = ask()
10 | while not (yn == 'y' or yn == 'n'):
11 | yn = ask()
12 | return yn == 'y'
13 | return True
14 |
15 | @classmethod
16 | def save(cls, obj, fname, force_overwrite = False):
17 | if not force_overwrite:
18 | # ask; if file already present and we need to overwrite
19 | if not Persist.overwrite(fname):
20 | print(f'Will not overwrite {fname}. Save failed!')
21 | return
22 | with open(fname, 'wb') as handle:
23 | pickle.dump(obj, handle, protocol=pickle.HIGHEST_PROTOCOL)
24 |
25 | @classmethod
26 | def load(cls, fname):
27 | with open(fname, 'rb') as handle:
28 | obj = pickle.load(handle)
29 | return obj
30 |
--------------------------------------------------------------------------------
/query_cache.py:
--------------------------------------------------------------------------------
1 | import uuid
2 | import os
3 | from typing import Optional, List
4 | import time
5 | from helper_utils import targz, untargz
6 |
7 | CACHE_LOC = "api_query_cache"
8 |
9 |
10 | class UniqId:
11 | def __init__(self, txt: List[str]):
12 | s = "\n".join(txt)
13 | # uuid3 does a MD5 hash; use uuid5 if you need SHA1
14 | self.uuid = uuid.uuid3(uuid.NAMESPACE_OID, s)
15 |
16 | def __repr__(self) -> str:
17 | return str(self.uuid)
18 |
19 |
20 | class QueryCache:
21 | def __init__(self, name):
22 | self.dir = os.path.join(CACHE_LOC, name)
23 | self.ensure_cache_dir()
24 |
25 | def ensure_cache_dir(self):
26 | self.ensure_exists(CACHE_LOC)
27 | self.load_snapshot_or_empty()
28 |
29 | def load_snapshot_or_empty(self):
30 | snapshot = self.snapshot_filename()
31 | if not os.path.exists(self.dir):
32 | if os.path.exists(snapshot) and self.confirm(f'Cache snapshot {snapshot} exists. Initialize from it (highly recommended)'):
33 | self.load_snapshot()
34 | else:
35 | self.ensure_exists(self.dir)
36 | return
37 |
38 | def save_snapshot(self):
39 | save_loc = self.snapshot_filename()
40 | do_save = self.confirm(f"Save query snapshot to {save_loc}")
41 | if not do_save:
42 | return
43 | targz(self.dir)
44 | assert os.path.exists(save_loc), f'Save should have created {save_loc}. Did not.'
45 |
46 | def load_snapshot(self):
47 | untargz(self.snapshot_filename(), self.dir)
48 | assert os.path.exists(self.dir), f'Load should have created {self.dir}. Did not.'
49 |
50 | def confirm(self, msg: str) -> bool:
51 | do = input(msg + "[y]/n? ")
52 | return do != "n"
53 |
54 | def snapshot_filename(self):
55 | return str(self.dir) + ".tar.gz"
56 |
57 | def ensure_exists(self, d):
58 | if not os.path.exists(d):
59 | os.mkdir(d)
60 |
61 | def put(self, q: str, a: str) -> bool:
62 | old = self.get(q)
63 | if old is not None and old != a:
64 | print(f'[WARN] Cache already has map for "{q[:20]}.." -> "{old[:20]}..", but asking to overwrite with different {a[:20]}.. Overwrite ignored!')
65 | return False
66 | uuid = UniqId([q])
67 | self.cache_write(uuid, a)
68 | return True
69 |
70 | def get(self, q: str) -> Optional[str]:
71 | uuid = UniqId([q])
72 | return self.cache_get(uuid) if self.cache_exists(uuid) else None
73 |
74 | def cache_get(self, uuid: UniqId) -> str:
75 | with open(self.fname(uuid), 'r') as f:
76 | return f.read()
77 |
78 | def cache_write(self, uuid: UniqId, val: str) -> None:
79 | with open(self.fname(uuid), 'w') as f:
80 | f.write(val)
81 |
82 | def cache_exists(self, uuid: UniqId) -> bool:
83 | return os.path.exists(self.fname(uuid))
84 |
85 | def fname(self, uuid: UniqId) -> str:
86 | return os.path.join(self.dir, f'{uuid}')
87 |
88 | def purge(self):
89 | for c in os.listdir(self.dir):
90 | cache_file = os.path.join(self.dir, c)
91 | print(f"Purging {cache_file}")
92 | time.sleep(1)
93 | os.remove(cache_file)
94 |
95 |
96 | def test_cache_write() -> None:
97 | q12 = "question 1 2"
98 | q23 = "question 2 3"
99 | a12 = "answer 1 2"
100 | a23 = "answer 2 3"
101 | cache = QueryCache("TEST")
102 |
103 | cache.purge()
104 |
105 | # empty cache
106 | assert cache.get(q12) == None
107 | assert cache.get(q23) == None
108 |
109 | # put a value and retrieve it
110 | assert cache.put(q12, a12) == True
111 | assert cache.get(q12) == a12
112 |
113 | # put new cache value, make sure old value did not change
114 | assert cache.put(q23, a23) == True
115 | assert cache.get(q23) == a23
116 | assert cache.get(q12) == a12
117 |
118 | # fail to overwrite
119 | assert cache.put(q23, a12) == False
120 | assert cache.get(q23) == a23
121 |
--------------------------------------------------------------------------------
/report/.gitignore:
--------------------------------------------------------------------------------
1 | *aux
2 | *blg
3 | *bbl
4 | *log
5 | main.pdf
6 |
--------------------------------------------------------------------------------
/report/Makefile:
--------------------------------------------------------------------------------
1 | main.pdf: main.tex refs.bib
2 | pdflatex main
3 | bibtex main
4 | pdflatex main
5 | bibtex main
6 | pdflatex main
7 |
8 | clean:
9 | rm main.pdf main.aux main.log main.bbl main.blg
10 | rm missfont.log
11 | rm texput.log
12 |
--------------------------------------------------------------------------------
/report/all-coverage.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/all-coverage.pdf
--------------------------------------------------------------------------------
/report/all-levels.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/all-levels.pdf
--------------------------------------------------------------------------------
/report/all-reasoning-gap.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/all-reasoning-gap.pdf
--------------------------------------------------------------------------------
/report/all-static-vs-func-accuracy.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/all-static-vs-func-accuracy.pdf
--------------------------------------------------------------------------------
/report/all-subjects.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/all-subjects.pdf
--------------------------------------------------------------------------------
/report/data_files.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/data_files.tar.gz
--------------------------------------------------------------------------------
/report/gpt4-by-level.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/gpt4-by-level.pdf
--------------------------------------------------------------------------------
/report/gpt4-by-subject.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/gpt4-by-subject.pdf
--------------------------------------------------------------------------------
/report/gpt4-k=3-suffices.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/gpt4-k=3-suffices.pdf
--------------------------------------------------------------------------------
/report/gpt4-levels.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/gpt4-levels.pdf
--------------------------------------------------------------------------------
/report/gpt4-reasoning-needed.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/gpt4-reasoning-needed.pdf
--------------------------------------------------------------------------------
/report/gpt4-subjects.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/gpt4-subjects.pdf
--------------------------------------------------------------------------------
/report/gpt4-surprise.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/gpt4-surprise.pdf
--------------------------------------------------------------------------------
/report/oss-by-level.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/oss-by-level.pdf
--------------------------------------------------------------------------------
/report/oss-by-subject.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/oss-by-subject.pdf
--------------------------------------------------------------------------------
/report/oss-k=3-suffices.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/oss-k=3-suffices.pdf
--------------------------------------------------------------------------------
/report/oss-reasoning-needed.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/oss-reasoning-needed.pdf
--------------------------------------------------------------------------------
/report/oss-surprise.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ConsequentAI/fneval/a89e561466dac1d0a376aaad9d84fa366a9f8e93/report/oss-surprise.pdf
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pytest>=7.3.1
2 | codetiming
3 | openai==0.28.1
4 | anthropic==0.18.1
5 | numpy
6 | together
7 | mistralai
8 |
--------------------------------------------------------------------------------
/summarize_evals.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import inspect
3 | import sys
4 | import os
5 | import json
6 | import shutil
7 | from persist import Persist
8 | from typing import List, Dict, Any, Set, Tuple
9 | from eval.measure_math import Eval, Metrics, SUBJECTS
10 | from eval.runner import mk_dir_safe
11 |
12 | from evaluate import DEFAULT_EVAL_PICKLE_FILE, ModelSpec
13 |
14 | COVERAGE_PC_TOO_LOW_IF_BELOW = 70
15 | PC = lambda num, dim: 100.0 * (num / float(dim) if dim else 0.0)
16 |
17 |
18 | def write_lines(lines: List[Any], prefix, ext = "txt"):
19 | frm = inspect.stack()[1][3]
20 | outfile = f"{prefix}.{frm}.{ext}"
21 | with open(outfile, 'w') as f:
22 | f.write("\n".join(lines))
23 | print(f'Written to {outfile}')
24 |
25 |
26 | def solved_by_models_across_snapshots(frac_models, es, prefix):
27 | model_solved: Dict[str, List[str]] = { model: e.get_solved(only_static = False) for model, e in es.items() }
28 | solved: List[List[str]] = [s for _, s in model_solved.items()]
29 |
30 | counts: Dict[str, int] = {}
31 | def incr(s, d):
32 | if s not in d:
33 | d[s] = 0
34 | d[s] += 1
35 | for solns in solved:
36 | for soln in solns:
37 | incr(soln, counts)
38 |
39 | threshold = len(es) * frac_models
40 | above_threshold = [s for s, times in counts.items() if times >= threshold]
41 |
42 | solved_solns = sorted(above_threshold)
43 | write_lines(solved_solns, prefix + f'_{frac_models}')
44 |
45 |
46 | def fraction_functionally_tested(static, func) -> Tuple[int, int]:
47 | static_correct = [tm.fname for tm in static.individuals if tm.correct]
48 | func_tested = [tm.fname for tm in func.individuals if tm.fname in static_correct]
49 | num, dim = len(func_tested), len(static_correct)
50 | return num, dim
51 |
52 |
53 | def reasoning_gap(static, combined) -> Tuple[int, int]:
54 | st = PC(*static.accuracy())
55 | cb = PC(*combined.accuracy())
56 | return st-cb, st
57 |
58 |
59 | def model_specs_to_str(evals_spec: Dict[ModelSpec, Eval]) -> Dict[str, Eval]:
60 | to_str = lambda ms: ms.spec_csv()[1]
61 | evals: Dict[str, Eval] = { to_str(ms): e for ms, e in evals_spec.items() }
62 | return evals
63 |
64 |
65 | def stat_solved_by_majority_models_across_snapshots(evaluations, prefix, extra):
66 | es = model_specs_to_str(evaluations)
67 | solved_by_models_across_snapshots(0.5, es, prefix)
68 |
69 |
70 | def stat_solved_by_all_models_across_snapshots(evaluations, prefix, extra):
71 | es = model_specs_to_str(evaluations)
72 | solved_by_models_across_snapshots(1.0, es, prefix)
73 |
74 |
75 | def stat_solved_statics(evaluations, prefix, extra):
76 | es = model_specs_to_str(evaluations)
77 | solved: Dict[str, List[str]] = { model: e.get_solved(only_static = True) for model, e in es.items() }
78 | solved_solns = sorted(list(set(s for _, solns in solved.items() for s in solns)))
79 | write_lines(solved_solns, prefix)
80 |
81 |
82 | def static_func_combined(model, evals) -> Tuple[Any, Any, Any, Any, str, str, bool]:
83 | static = evals.static_metrics
84 | func = evals.func_metrics
85 | verbose = False
86 | model_name = mk_dir_safe(model)
87 | combined, func_of_static = static.with_functional(func, model_name, verbose)
88 | gap = PC(*reasoning_gap(static, combined))
89 | gap_tag = f'{gap:.2f}%'
90 | pc_fn = PC(*fraction_functionally_tested(static, func))
91 | pc_fn_tag = f"{pc_fn:.2f}%"
92 | cover_too_low = pc_fn <= COVERAGE_PC_TOO_LOW_IF_BELOW
93 | warn_low_cover = pc_fn_tag + (" (too low)" if cover_too_low else "")
94 | return static, func, func_of_static, combined, gap_tag, warn_low_cover, cover_too_low
95 |
96 |
97 | def stat_accuracy(evaluations, prefix, extra):
98 | es = model_specs_to_str(evaluations)
99 | hr = '-' * 100
100 | accuracies: List[str] = []
101 | for model, evals in es.items():
102 | if not accuracies:
103 | legend = evals.static_metrics.stats_legend()
104 | accuracies.append(legend)
105 | static, func, func_sub_static, combined, gap, warn_low_cover, cover_too_low = static_func_combined(model, evals)
106 | if cover_too_low:
107 | print(f'Coverage too low ({warn_low_cover}) for {model}. Still writing raw data to file.')
108 | gap_warn = ' (please dont cite; coverage too low)' if cover_too_low else ''
109 | accuracies += [
110 | hr, model, hr,
111 | 'static:', static.stats(),
112 | 'functional:', func.stats(),
113 | 'functional correct amongst static correct:', func_sub_static.stats(),
114 | 'combined:', combined.stats(),
115 | 'reasoning gap:', gap + gap_warn,
116 | 'pc functionally tested:', warn_low_cover,
117 | 'coverage low:', str(cover_too_low),
118 | hr]
119 | write_lines(accuracies, prefix)
120 |
121 |
122 | class ModelAccuracies:
123 | def __init__(self, model, evals):
124 | static, func, func_sub_static, combined, gap, warn_low, cover_too_low = static_func_combined(model, evals)
125 | self.st = PC(*static.accuracy())
126 | self.fn = PC(*combined.accuracy())
127 | self.pc_fn = PC(*fraction_functionally_tested(static, func))
128 | self.st_h = PC(*static.hallucinations())
129 | self.fn_h = PC(*combined.hallucinations())
130 | self.fn_correct = PC(*func_sub_static.accuracy())
131 | self.gap = gap
132 | self.warn_low = warn_low
133 | self.cover_too_low = cover_too_low
134 |
135 | HDRS = 'Static,Func,Frac Func Tested,Static Hall,Func Hall,Gap,Fn Coverage,Correct Amongst Fn Tested'
136 |
137 | def __repr__(self):
138 | return f'{self.st:.2f}%,{self.fn:.2f}%,{self.pc_fn:.2f}%,{self.st_h:.2f}%,{self.fn_h:.2f}%,{self.gap},{self.warn_low},{self.fn_correct:.2f}%'
139 |
140 | def stat_csv_static_func(evaluations, prefix, extra):
141 | es = model_specs_to_str(evaluations)
142 | force_write_low_covers = 'FORCE_WRITE_LOW_COVERS' in extra
143 |
144 | model_spec = next(iter(evaluations)).spec_csv()[0]
145 | accuracies: List[str] = [f'{model_spec},{ModelAccuracies.HDRS}']
146 | some_skipped = False
147 |
148 | for model, evals in es.items():
149 | model_accs = ModelAccuracies(model, evals)
150 | if model_accs.cover_too_low:
151 | print(f'Coverage too low ({model_accs.warn_low}) for {model}.')
152 | if not force_write_low_covers:
153 | some_skipped = True
154 | continue
155 | accuracies.append(f'{model},{model_accs}')
156 |
157 | if some_skipped:
158 | print('Low coverage values skipped; add extra flag to include them: --extra \'{"FORCE_WRITE_LOW_COVERS": "True"}\'')
159 | write_lines(accuracies, prefix, ext = "csv")
160 |
161 |
162 | def stat_effect_of_cot(evaluations, prefix, extra):
163 | without_cot = {}
164 | with_cot = {}
165 | for model_spec, evals in evaluations.items():
166 | if model_spec.chain_of_thought:
167 | with_cot[model_spec] = evals
168 | else:
169 | without_cot[model_spec] = evals
170 |
171 | def find_with_cot(ms: ModelSpec):
172 | for ms_with, evals in with_cot.items():
173 | if ms_with.model == ms.model and \
174 | ms_with.few_shot_num == ms.few_shot_num and \
175 | ms_with.temperature == ms.temperature:
176 | return ms_with, evals
177 | return None, None
178 |
179 | to_str = lambda ms: ms.spec_csv()[1]
180 | hdrs = ModelAccuracies.HDRS
181 | with_and_without = [f'model,fs,temp,{hdrs},{hdrs}']
182 | for ms, evals in without_cot.items():
183 | with_ms, with_evals = find_with_cot(ms)
184 | if not with_ms:
185 | continue
186 |
187 | model_desc = f'{ms.model},{ms.few_shot_num},{ms.temperature}'
188 | with_nums = ModelAccuracies(to_str(with_ms), with_evals)
189 | without_nums = ModelAccuracies(to_str(ms), evals)
190 |
191 | line = f'{model_desc},{without_nums},{with_nums}'
192 | with_and_without.append(line)
193 |
194 | write_lines(with_and_without, prefix, ext = "csv")
195 |
196 |
197 | def stat_effect_of_fewshot(evaluations, prefix, extra):
198 | without_fs = {}
199 | with_fs = {}
200 | for model_spec, evals in evaluations.items():
201 | if model_spec.few_shot_num == 0:
202 | without_fs[model_spec] = evals
203 | else:
204 | with_fs[model_spec] = evals
205 |
206 | def find_with_fs(ms: ModelSpec):
207 | for ms_with, evals in with_fs.items():
208 | if ms_with.model == ms.model and \
209 | ms_with.chain_of_thought == ms.chain_of_thought and \
210 | ms_with.temperature == ms.temperature:
211 | return ms_with, evals
212 | return None, None
213 |
214 | to_str = lambda ms: ms.spec_csv()[1]
215 | hdrs = ModelAccuracies.HDRS
216 | with_and_without = [f'model,cot,temp,{hdrs},{hdrs}']
217 | for ms, evals in without_fs.items():
218 | with_ms, with_evals = find_with_fs(ms)
219 | if not with_ms:
220 | continue
221 |
222 | model_desc = f'{ms.model},{ms.chain_of_thought},{ms.temperature}'
223 | with_nums = ModelAccuracies(to_str(with_ms), with_evals)
224 | without_nums = ModelAccuracies(to_str(ms), evals)
225 |
226 | line = f'{model_desc},{without_nums},{with_nums}'
227 | with_and_without.append(line)
228 |
229 | write_lines(with_and_without, prefix, ext = "csv")
230 |
231 |
232 | def stat_csv_subject_level(evaluations, prefix, extra):
233 | es = model_specs_to_str(evaluations)
234 | # model -> typ (subject or level) -> (static, func)
235 | ModelTypStatFunc = Dict[str, Dict[Any, Tuple[float, float]]]
236 |
237 | def acc_fn(outcomes: List[bool]):
238 | return PC(outcomes.count(True), len(outcomes))
239 |
240 | def acc_s(m: Metrics, subject: str):
241 | return acc_fn(m.subject_cors[subject])
242 |
243 | def acc_l(m: Metrics, lvl: int):
244 | return acc_fn(m.level_cors[lvl])
245 |
246 | def collapse_models(metrics: ModelTypStatFunc, fn) -> ModelTypStatFunc:
247 | def collapse_tuple(l: List[Tuple[float, float]]) -> Tuple[float, float]:
248 | statics, funcs = list(zip(*l))
249 | return fn(statics), fn(funcs)
250 | models = list(m for m in metrics)
251 | types = list(t for t in metrics[models[0]])
252 | return { "all": { t: collapse_tuple(list(metrics[model][t] for model in models)) for t in types } }
253 |
254 |
255 | sub_accs: ModelTypStatFunc = {}
256 | lvl_accs: ModelTypStatFunc = {}
257 | for model, evals in es.items():
258 | static, _, _, comb, _, _, _ = static_func_combined(model, evals)
259 | s_accs = { sub: (acc_s(static, sub), acc_s(comb, sub)) for sub in SUBJECTS }
260 | l_accs = { lvl: (acc_l(static, lvl), acc_l(comb, lvl)) for lvl in range(1,6) }
261 | sub_accs[model] = s_accs
262 | lvl_accs[model] = l_accs
263 |
264 | def write(tag: str, accs: ModelTypStatFunc):
265 | lines: List[str] = [f"Model,{tag},Static,W Func,Delta"]
266 | for model, accuracies in accs.items():
267 | for typ, (stat, func) in accuracies.items():
268 | delta = PC(stat - func, stat)
269 | lines.append(f'{model},{typ},{stat:.2f}%,{func:.2f}%,{delta:.2f}%')
270 | write_lines(lines, prefix + f".{tag}", ext = "csv")
271 |
272 | write("Subject", sub_accs)
273 | write("Level", lvl_accs)
274 |
275 | avg = lambda xs: sum(xs)/len(xs)
276 | write("AllModels.Subject", collapse_models(sub_accs, avg))
277 | write("AllModels.Level", collapse_models(lvl_accs, avg))
278 |
279 |
280 | def stat_dropoff(evaluations, prefix, extra):
281 | es = model_specs_to_str(evaluations)
282 | tab = '\t'
283 | def summary_line(s, f):
284 | jsn = f'functional-math/prbs/{s.fname}'
285 | subject, base = s.fname.split('/')
286 | pyid = base[:-len('.json')]
287 | fnpy = f'functional-math/functional/benchmarks/{subject}/m{pyid}.py'
288 | lines = [
289 | s.answer,
290 | f.answer,
291 | f.output,
292 | f'{f.fraction_correct:.2f}',
293 | f'{s.level}',
294 | jsn,
295 | fnpy
296 | ]
297 | return tab.join(lines)
298 | hdr = tab.join([
299 | 'static got (= correct)',
300 | 'func correct ref',
301 | 'func got (incorrect)',
302 | 'fraction correct',
303 | 'level',
304 | 'json',
305 | 'functional'
306 | ])
307 |
308 | def get_static_for(f, static):
309 | return next(tm for tm in static.individuals if tm.fname == f.fname)
310 |
311 | for model, evals in es.items():
312 | static, func, _, _, _, _, _ = static_func_combined(model, evals)
313 | dropped = [hdr]
314 | for fn in func.individuals:
315 | if not fn.correct:
316 | assert fn.output != fn.answer, 'aggregation failure? some functional incorrect, but diff outs not captured?'
317 | st = get_static_for(fn, static)
318 | if st.correct:
319 | dropped.append(summary_line(st, fn))
320 | fname = f'dropped.{mk_dir_safe(model)}'
321 | write_lines(dropped, fname, ext = 'tsv')
322 |
323 |
324 | def stat_model_counts(evaluations, prefix, extra):
325 | es = model_specs_to_str(evaluations)
326 | corrects = {}
327 | for model, evals in es.items():
328 | static, func, _, _, _, _, _ = static_func_combined(model, evals)
329 | corrects[model] = [s.fname for s in static.individuals if s.correct]
330 | cummulative: Dict[str, List[str]] = {}
331 | for model in es:
332 | for c in corrects[model]:
333 | if c not in cummulative:
334 | cummulative[c] = []
335 | cummulative[c].append(model)
336 |
337 | exclusives = [f'Across all models: {len(cummulative)}']
338 | only_in_model = {}
339 | for model in es:
340 | only_here = [c for c in cummulative if cummulative[c] == [model]]
341 | only_in_model[model] = only_here
342 | exclusives += [f'Exclusive to {model}: {len(only_here)}']
343 | write_lines(exclusives, prefix + '.exclusives')
344 |
345 | overlaps = [f'{c},{len(cummulative[c])}' for c in cummulative]
346 | write_lines(overlaps, prefix + '.count_models', ext='csv')
347 |
348 |
349 | def stat_solved_statics_not_functionalized(evaluations, prefix, extra):
350 | es = model_specs_to_str(evaluations)
351 | # root of already functionalized problems
352 | prb_root = extra['ROOT_FUNCMATH_PRBS']
353 |
354 | def read_functional_math_prbs() -> List[str]:
355 | files = []
356 | subjects = os.listdir(prb_root)
357 | for s in subjects:
358 | d = os.path.join(prb_root, s)
359 | for f in os.listdir(d):
360 | files.append(os.path.join(s, f))
361 | return files
362 |
363 | def copy_from_MATH(ufn: str, root: str):
364 | subj, ident = ufn.split('/')
365 | src = os.path.join('MATH', 'test', subj, ident)
366 | dst_dir = os.path.join(root, subj)
367 | dst = os.path.join(dst_dir, ident)
368 | if not os.path.exists(dst_dir):
369 | os.makedirs(dst_dir)
370 | shutil.copyfile(src, dst)
371 |
372 | solved: Dict[str, List[str]] = { model: e.get_solved(only_static = True) for model, e in es.items() }
373 | solved_solns: List[str] = sorted(list(set(s for _, solns in solved.items() for s in solns)))
374 | prbs: List[str] = read_functional_math_prbs()
375 | unfunctionalized = [s for s in solved_solns if not s in prbs]
376 |
377 | # write output /prbs data to this directory
378 | outdir = prefix + '.not_yet_func'
379 | # read jsons and copy to directory structure with root of fn name
380 | ufn_root = os.path.join(outdir, 'prbs')
381 | if not os.path.exists(ufn_root):
382 | os.makedirs(ufn_root)
383 | for ufn in unfunctionalized:
384 | copy_from_MATH(ufn, ufn_root)
385 | print(f'Unfunctionalized MATH test jsons written to: {ufn_root}')
386 |
387 |
388 | if __name__ == "__main__":
389 | parser = argparse.ArgumentParser()
390 | parser.add_argument("--in_file",
391 | help = f"Read pickle file of [ model_name -> eval ]; default = {DEFAULT_EVAL_PICKLE_FILE}")
392 | parser.add_argument("--stat_fn",
393 | help = f"Name of stat fn to run")
394 | parser.add_argument("--extra",
395 | help = f"Opt dict of other parameters")
396 | args = parser.parse_args()
397 |
398 | if not args.stat_fn:
399 | stat_names = [s for s in dir(sys.modules[__name__]) if s.startswith('stat')]
400 | print(f'--stat_fn can take: {stat_names}')
401 | exit(1)
402 |
403 | infile = args.in_file if args.in_file else DEFAULT_EVAL_PICKLE_FILE
404 |
405 | evals: Dict[ModelSpec, Eval] = Persist.load(infile)
406 | print(f'Processing eval data from: {list(evals.keys())}')
407 | stat_fn = getattr(sys.modules[__name__], args.stat_fn)
408 | prefix = infile
409 | extra = json.loads(args.extra) if args.extra else {}
410 |
411 | # run the requested stat fn
412 | stat_fn(evals, prefix, extra)
413 |
--------------------------------------------------------------------------------
/unformatted_llm.py:
--------------------------------------------------------------------------------
1 | from typing import Dict, List, Tuple, Optional
2 | from few_shot import FewShotAnswerSamples, FewShotBuilder
3 | from math_utils.math_helpers import rm_latex_math
4 | from helper_utils import NO_SOLUTION_PREFIX
5 |
6 | HDR = "###"
7 | PRB_TAG = f"{HDR} Problem"
8 | ANS_TAG = f"{HDR} Answer"
9 | END_TAG = "\n\n"
10 |
11 | class UnformattedLLM(FewShotBuilder):
12 | INSTRUCTION = f"Given a mathematics problem, determine the answer. "\
13 | f"Simplify your answer as much as possible. "\
14 | f"If the answer cannot be computed, or you are not confident, say {NO_SOLUTION_PREFIX}. "
15 |
16 | def few_shot_dict(self, count: int = -1) -> Dict[str, str]:
17 | ios: Dict[str, str] = self.few_shot_limited(count)
18 | return ios
19 |
20 | def few_shot_format(self, ios: Dict[str, str]) -> str:
21 | return "".join([self.format(i, o) for i, o in ios.items()])
22 |
23 | def prompt_for(self, prb: str, solns: List[str] = []) -> str:
24 | assert solns == [], f'Unformatted does not format soln steps to model prompt'
25 | return self.format(prb)
26 |
27 | def extract_answer(self, completion: str) -> str:
28 | completion = completion.lstrip()
29 | end = completion.find(END_TAG)
30 | answer = completion[:end] if end != -1 else completion
31 | answer = answer.strip()
32 | return answer
33 |
34 | def __init__(self):
35 | mk_io = lambda fs: (fs.prb, rm_latex_math(fs.outcome))
36 | self.few_shot_io: List[Tuple[str, str]] = [ mk_io(fs) for fs in FewShotAnswerSamples ]
37 |
38 | def few_shot_limited(self, count: int) -> Dict[str, str]:
39 | limited_samples = self.few_shot_io[:count] if count != -1 else self.few_shot_io
40 | return dict(limited_samples)
41 |
42 | def format_fn(self, prb: str, solns: List[str], outcome: str, explain: Optional[List[str]]):
43 | assert solns == [] and explain == None
44 | return self.format(prb, outcome)
45 |
46 | def format(self, inp: str, out: Optional[str] = None) -> str:
47 | lines = [
48 | UnformattedLLM.INSTRUCTION,
49 | PRB_TAG,
50 | inp,
51 | ANS_TAG,
52 | ]
53 | if out:
54 | lines += [out, END_TAG]
55 | return "\n".join(lines)
56 |
57 |
58 |
--------------------------------------------------------------------------------