choicellm 0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
__init__.py ADDED
File without changes
aggregate.py ADDED
@@ -0,0 +1,72 @@
1
+ import pandas
2
+ import sys
3
+ import argparse
4
+ import logging
5
+
6
+ import math
7
+
8
+ import random
9
+ import numpy as np
10
+ from choicellm import N_DECIMALS
11
+
12
+ """
13
+ From the comparative results:
14
+
15
+ target_id,comparison_id,position,target,score,choices,scores
16
+
17
+ to:
18
+
19
+ target_id,target,score,entropy,method
20
+
21
+ """
22
+
23
+ def main():
24
+
25
+ logging.basicConfig(level=logging.INFO, format='')
26
+ argparser = argparse.ArgumentParser()
27
+ argparser.add_argument('file', nargs='?', default=sys.stdin)
28
+ argparser.add_argument('--onlyscore', action='store_true', help='whether to output only the scores; otherwise full csv.') # TODO: re-implement
29
+ argparser.add_argument('--n_positions', required=False, type=int, default=None, help='In case comparison data contains all positions, randomly sample one position per comparison')
30
+ argparser.add_argument('--n_comparisons', required=False, type=int, default=None, help='Randomly sample only this many comparisons per word.')
31
+ argparser.add_argument('--scale', required=False, type=str, help='start,end of the scale, to which to map the scores', default='1,5')
32
+ argparser.add_argument('--seed', required=False, type=int, default=None, help='seed, for sampling --n_comparisons or --n_positions only')
33
+
34
+ args = argparser.parse_args()
35
+ scale_start, scale_end = (int(i) for i in args.scale.split(','))
36
+
37
+ converters = {
38
+ 'choices': lambda x: tuple(x.split(';')),
39
+ 'probs': lambda x: tuple(float(s) for s in x.split(';')),
40
+ }
41
+
42
+ df = pandas.read_csv(args.file, index_col=None, converters=converters)
43
+
44
+ n_choices = len(df.iloc[0]['choices']) # hmmm, expose as command line arg?
45
+
46
+ if args.n_positions is not None or args.n_comparisons is not None:
47
+ args.seed = args.seed or random.randint(0, 999999)
48
+ logging.info(f'Seed: {args.seed}')
49
+ np.random.seed(args.seed)
50
+
51
+ if args.n_positions is not None:
52
+ df = df.groupby(['target_id', 'comparison_id']).sample(n=args.n_positions)
53
+
54
+ if args.n_comparisons is not None:
55
+ df = df.set_index(['target_id', 'comparison_id']).pivot(columns=['position']).groupby('target_id').sample(args.n_comparisons).stack(level=1).reset_index()
56
+
57
+ df['entropy'] = [-sum(prob * math.log2(max(prob, 0.00000001)) for prob in scores) for scores in df['probs']] # Hmmmmm
58
+
59
+ df_agg_per_word = df.groupby(['target_id', 'target']).agg({'prob': 'mean', 'entropy': 'mean'})
60
+
61
+ df_agg_per_word['rating'] = (df_agg_per_word['prob'] ** (1 / (n_choices - 1))) * (scale_end - scale_start) + scale_start
62
+ # rating based on normalized prob: if prob(winning 1 vs 3) = 0.25 = prob(winning 1 vs 1)**3, so prob(winning 1 vs 1) = 0.25 ** (1/3)
63
+
64
+ df_agg_per_word['rating'] = df_agg_per_word['rating'].round(N_DECIMALS)
65
+ df_agg_per_word['entropy'] = df_agg_per_word['entropy'].round(N_DECIMALS)
66
+
67
+ df_agg_per_word.reset_index()[['target_id', 'target', 'rating', 'entropy']].to_csv(sys.stdout, index=None)
68
+
69
+
70
+
71
+ if __name__ == '__main__':
72
+ main()
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.4
2
+ Name: choicellm
3
+ Version: 0.2
4
+ Summary: Using LLMs for rating items on a scale, comparative judgments, and multiple choice questions.
5
+ Author-email: Matthijs Westera <m.westera@hum.leidenuniv.nl>
6
+ Project-URL: Homepage, https://github.com/mwestera/choicellm
7
+ Project-URL: Bug Tracker, https://github.com/mwestera/choicellm/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
+ Classifier: Topic :: Text Processing :: Linguistic
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: transformers
18
+ Requires-Dist: torch
19
+ Requires-Dist: accelerate
20
+ Requires-Dist: optimum
21
+ Requires-Dist: auto_gptq
22
+ Requires-Dist: bitsandbytes
23
+ Requires-Dist: openai
24
+ Requires-Dist: tiktoken
25
+ Requires-Dist: pandas
26
+ Dynamic: license-file
27
+
28
+ # ChoiceLLM: A Python package for ratings and multiple choice answers from LLMs
29
+
30
+ ## Purpose
31
+
32
+ This tool makes it easier to prompt an LLM for:
33
+
34
+ - 'scalar' judgments (e.g., "On a scale from 1 to 7, how abstract is this word?", "How suggestive is this question?").
35
+ - 'comparative' judgments (e.g., "Of these 4 words, which is the most emotional?")
36
+ - 'categorical' judgments, i.e., to classify words, phrases or paragraphs into a number of fixed, predetermined categories (e.g., "What type of speech act is this utterance?").
37
+
38
+ and to do so for a large amount of 'stimuli', and using different LLMs (both locally running LLMs, and models via the OpenAI API, if you have an `OPENAI_API_KEY`).
39
+
40
+ The scores obtained are deterministic, obtained by accessing the underlying logits computed by the model (as opposed to sampling a concrete response).
41
+
42
+ ## Installation
43
+
44
+ From PyPI:
45
+
46
+ ```bash
47
+ pip install choicellm
48
+ ```
49
+
50
+ Installation makes available the main program `choicellm`, and helper programs `choicellm-template` and `choicellm-aggregate`.
51
+
52
+ ## First create a suitable prompt JSON file (`choicellm-template`)
53
+
54
+ When running `choicellm`, you need to provide it with a 'prompt template' file in JSON format, like `choicellm --prompt my_first_prompt.json`. The exact format of this file will depend on what you want to use `choicellm` for, i.e., for scalar judgments (and if so, on what kind of scale), for multiple-choice questions, or for comparing items, and whether you plan to use a 'base' model (i.e., plain language generation) or an 'instruct' model (i.e., chatbot like GPT).
55
+
56
+ To generate an example prompt template (which you can then modify to suit your needs), you can do, for instance:
57
+
58
+ ```bash
59
+ choicellm-template --scalar > my_first_prompt.json
60
+ ```
61
+
62
+ Alternative modes are `--comparative` and `--categorical` (see below for some explanation, but you'll understand most from the generated prompt templates themselves). If you want to use an 'instruct' model, additionally specify `--chat`. (Note that the examples were written for a study on concreteness vs. abstractness; you can of course modify all of this.)
63
+
64
+ When modifying a prompt, make sure to use all the parts in curly braces, like `{scale}`. These will be replaced by the program, according to the information you provide.
65
+
66
+ The prompt templates contain some additional comments under the JSON key `_comments`.
67
+
68
+ ## Basic usage
69
+
70
+ Now, assuming you have some items (words, phrases) to be categorized (or whatever) in a plain text file `items.txt`, one on each line, you can now do:
71
+
72
+ ```bash
73
+ choicellm items.txt --prompt my_first_prompt.json
74
+ ```
75
+
76
+ Results will simply be printed to the command-line (along with some logging info). To save them, use output redirection:
77
+
78
+ ```bash
79
+ choicellm items.txt --prompt my_first_prompt.json > results.csv
80
+ ```
81
+
82
+ The default model won't be very big, or very good. If you have a more powerful computer, you could try something larger with the `--model` option, accepting any model identifier from the Huggingface hub.
83
+
84
+ ```bash
85
+ choicellm items.txt --model 'unsloth/llama-3-70b-bnb-4bit' --prompt my_first_prompt.json > results.csv
86
+ ```
87
+
88
+ To use a proprietary OpenAI model, first, you need to set the `OPENAI_API_KEY` environment variable to your secret key:
89
+
90
+ ```bash
91
+ export OPENAI_API_KEY=yoursecretkey123
92
+ ```
93
+
94
+ Then you can specify an OpenAI model (and include the `--openai` flag):
95
+
96
+ ```bash
97
+ choicellm items.txt --model 'gpt-4o' --openai --my_first_prompt.json > results.csv
98
+ ```
99
+
100
+ Since GPT-4o is an 'instruct' (i.e., chat) model, make sure you use it with a prompt template created with the `--chat` option, e.g., `choicellm-template --scalar --chat`.
101
+
102
+ On the whole, while `choicellm` is probably not entirely model-agnostic in some unforeseen ways, it should work with Huggingface models and OpenAI models. Reasonable local options that fit in a 48GB GPU: `unsloth/llama-3-70b-bnb-4bit` or `unsloth/Llama-3.3-70B-Instruct-bnb-4bit`. Since the latter is an 'instruct' model, again make sure to use a prompt template generated with the `--chat` option.
103
+
104
+ ## A bit more info about the three 'modes': scalar, comparative, categorical
105
+
106
+ First, `--scalar` prompts ask the LLM to give ratings on a numerical scale. Beware that negative scale values (like a scale -1, 0, 1, which could make sense for sentiment) are currently supported only for local models with `transformers`, not through the OpenAI client. (This applies more generally to labels that do not map onto single token ids for the given tokenizer.) The `results.csv` file contains the items, with additional columns `pred` (the model's choice), `prob` (the probability the model assigned to this choice, i.e., the softmaxed logits), `rating` (a weighted sum taking the model's probabilities for all choices into account), `probs` (the probabilities for all choices, separated by semicolons; these sum to 1.0).
107
+
108
+ Next, `--categorical` prompts are most suited for single-label categorization: the category probabilities sum to one (under the hood, the LLM is not given the option of listing several categories). (For multi-label categorization, see below.) For this mode, the `results.csv` file contains `pred` (the 'chosen' category), `prob` (its probability) and `probs` (probabilities for all categories, separated by semicolons).
109
+
110
+ Third, `--comparative` prompts ask the model to compare each item to a large number of random other items, which can result in more reliable per-item scores (once aggregated over all comparisons). Applying `choicellm` to such a prompt comes with some additional options, see `choicellm --help` for that. (Publication with more explanation pending.) Note that, for a `--comparative` prompt, the `results.csv` file will not contain a single score per item, but rather a separate row for each of the many comparisons it did. The auxiliary command `choicellm-aggregate` may be used to aggregate these comparisons into a single score per item (in this case resulting in values on the scale 1,5):
111
+
112
+ ```bash
113
+ choicellm-aggregate results.csv --scale 1,5 > results_aggregated.csv
114
+ ```
115
+
116
+ Lastly, to achieve _multi-label_ classification (where the same instance may fit several categories at once), the recommended approach is to implement this as multiple, separate `--scalar` (or `--comparative`) prompts, one for each category, and fed separately into `choicellm`. After creating separate prompt files (each named as `<category>.json`), feeding them into `choicellm` can be easily done in Bash by looping over the prompt files as follows (e.g.):
117
+
118
+ ```bash
119
+ for category in games movies music sports; do
120
+ choicellm items.txt --model 'unsloth/Meta-Llama-3.1-70B-Instruct-bnb-4bit' --prompt "$category.json" > "$category.csv"
121
+ done
122
+ ```
123
+
124
+ Having a separate prompt template per category (with designated system prompt and few-shot examples for each category) is probably a good idea regardless, as it encourages fine-tuning and evaluating the system for each category separately. The `.csv` results files (one per category) need to be merged afterward, which is fairly straightforward using (for instance) the `pandas` library.
125
+
@@ -0,0 +1,11 @@
1
+ __init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ aggregate.py,sha256=VWHeUIhLnZJ6d8XL2qpSgwi2TPWOpCu0L1altTojJSU,2950
3
+ choicellm.py,sha256=hKn1_Su06NlM5lcUG9LSa4LZGtnDD7fliNuU-jUSass,12331
4
+ multichoicemodel.py,sha256=hNwZYSHcblpDMI_Kvm-lKI-Y8IRgygQovRbVkysjUkk,8962
5
+ prompttemplate.py,sha256=lmC3rR5I8EED8gd7wCSwSQAVWMvCQ3ihtl5gTlVbA_E,14028
6
+ choicellm-0.2.dist-info/licenses/LICENSE,sha256=RpvAZSjULHvoTR_esTlucJ08-zdQydnoqQLbqOh9Ub8,13826
7
+ choicellm-0.2.dist-info/METADATA,sha256=o_un65JYv-73vKjqt1S38SFBQZgszjnomqVkXExiUbU,8067
8
+ choicellm-0.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ choicellm-0.2.dist-info/entry_points.txt,sha256=cx6jpyWH6FefLhBa_WUbRQB0P_MhU0LDMpmTYnWYUCU,123
10
+ choicellm-0.2.dist-info/top_level.txt,sha256=OeaZvTv52UE1vjHKB5TxOWuOwWLdxpBG5AYOU70WI2c,61
11
+ choicellm-0.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,4 @@
1
+ [console_scripts]
2
+ choicellm = choicellm:main
3
+ choicellm-aggregate = aggregate:main
4
+ choicellm-template = prompttemplate:main
@@ -0,0 +1,287 @@
1
+ EUROPEAN UNION PUBLIC LICENCE v. 1.2
2
+ EUPL © the European Union 2007, 2016
3
+
4
+ This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined
5
+ below) which is provided under the terms of this Licence. Any use of the Work,
6
+ other than as authorised under this Licence is prohibited (to the extent such
7
+ use is covered by a right of the copyright holder of the Work).
8
+
9
+ The Work is provided under the terms of this Licence when the Licensor (as
10
+ defined below) has placed the following notice immediately following the
11
+ copyright notice for the Work:
12
+
13
+ Licensed under the EUPL
14
+
15
+ or has expressed by any other means his willingness to license under the EUPL.
16
+
17
+ 1. Definitions
18
+
19
+ In this Licence, the following terms have the following meaning:
20
+
21
+ - ‘The Licence’: this Licence.
22
+
23
+ - ‘The Original Work’: the work or software distributed or communicated by the
24
+ Licensor under this Licence, available as Source Code and also as Executable
25
+ Code as the case may be.
26
+
27
+ - ‘Derivative Works’: the works or software that could be created by the
28
+ Licensee, based upon the Original Work or modifications thereof. This Licence
29
+ does not define the extent of modification or dependence on the Original Work
30
+ required in order to classify a work as a Derivative Work; this extent is
31
+ determined by copyright law applicable in the country mentioned in Article 15.
32
+
33
+ - ‘The Work’: the Original Work or its Derivative Works.
34
+
35
+ - ‘The Source Code’: the human-readable form of the Work which is the most
36
+ convenient for people to study and modify.
37
+
38
+ - ‘The Executable Code’: any code which has generally been compiled and which is
39
+ meant to be interpreted by a computer as a program.
40
+
41
+ - ‘The Licensor’: the natural or legal person that distributes or communicates
42
+ the Work under the Licence.
43
+
44
+ - ‘Contributor(s)’: any natural or legal person who modifies the Work under the
45
+ Licence, or otherwise contributes to the creation of a Derivative Work.
46
+
47
+ - ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of
48
+ the Work under the terms of the Licence.
49
+
50
+ - ‘Distribution’ or ‘Communication’: any act of selling, giving, lending,
51
+ renting, distributing, communicating, transmitting, or otherwise making
52
+ available, online or offline, copies of the Work or providing access to its
53
+ essential functionalities at the disposal of any other natural or legal
54
+ person.
55
+
56
+ 2. Scope of the rights granted by the Licence
57
+
58
+ The Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
59
+ sublicensable licence to do the following, for the duration of copyright vested
60
+ in the Original Work:
61
+
62
+ - use the Work in any circumstance and for all usage,
63
+ - reproduce the Work,
64
+ - modify the Work, and make Derivative Works based upon the Work,
65
+ - communicate to the public, including the right to make available or display
66
+ the Work or copies thereof to the public and perform publicly, as the case may
67
+ be, the Work,
68
+ - distribute the Work or copies thereof,
69
+ - lend and rent the Work or copies thereof,
70
+ - sublicense rights in the Work or copies thereof.
71
+
72
+ Those rights can be exercised on any media, supports and formats, whether now
73
+ known or later invented, as far as the applicable law permits so.
74
+
75
+ In the countries where moral rights apply, the Licensor waives his right to
76
+ exercise his moral right to the extent allowed by law in order to make effective
77
+ the licence of the economic rights here above listed.
78
+
79
+ The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to
80
+ any patents held by the Licensor, to the extent necessary to make use of the
81
+ rights granted on the Work under this Licence.
82
+
83
+ 3. Communication of the Source Code
84
+
85
+ The Licensor may provide the Work either in its Source Code form, or as
86
+ Executable Code. If the Work is provided as Executable Code, the Licensor
87
+ provides in addition a machine-readable copy of the Source Code of the Work
88
+ along with each copy of the Work that the Licensor distributes or indicates, in
89
+ a notice following the copyright notice attached to the Work, a repository where
90
+ the Source Code is easily and freely accessible for as long as the Licensor
91
+ continues to distribute or communicate the Work.
92
+
93
+ 4. Limitations on copyright
94
+
95
+ Nothing in this Licence is intended to deprive the Licensee of the benefits from
96
+ any exception or limitation to the exclusive rights of the rights owners in the
97
+ Work, of the exhaustion of those rights or of other applicable limitations
98
+ thereto.
99
+
100
+ 5. Obligations of the Licensee
101
+
102
+ The grant of the rights mentioned above is subject to some restrictions and
103
+ obligations imposed on the Licensee. Those obligations are the following:
104
+
105
+ Attribution right: The Licensee shall keep intact all copyright, patent or
106
+ trademarks notices and all notices that refer to the Licence and to the
107
+ disclaimer of warranties. The Licensee must include a copy of such notices and a
108
+ copy of the Licence with every copy of the Work he/she distributes or
109
+ communicates. The Licensee must cause any Derivative Work to carry prominent
110
+ notices stating that the Work has been modified and the date of modification.
111
+
112
+ Copyleft clause: If the Licensee distributes or communicates copies of the
113
+ Original Works or Derivative Works, this Distribution or Communication will be
114
+ done under the terms of this Licence or of a later version of this Licence
115
+ unless the Original Work is expressly distributed only under this version of the
116
+ Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee
117
+ (becoming Licensor) cannot offer or impose any additional terms or conditions on
118
+ the Work or Derivative Work that alter or restrict the terms of the Licence.
119
+
120
+ Compatibility clause: If the Licensee Distributes or Communicates Derivative
121
+ Works or copies thereof based upon both the Work and another work licensed under
122
+ a Compatible Licence, this Distribution or Communication can be done under the
123
+ terms of this Compatible Licence. For the sake of this clause, ‘Compatible
124
+ Licence’ refers to the licences listed in the appendix attached to this Licence.
125
+ Should the Licensee's obligations under the Compatible Licence conflict with
126
+ his/her obligations under this Licence, the obligations of the Compatible
127
+ Licence shall prevail.
128
+
129
+ Provision of Source Code: When distributing or communicating copies of the Work,
130
+ the Licensee will provide a machine-readable copy of the Source Code or indicate
131
+ a repository where this Source will be easily and freely available for as long
132
+ as the Licensee continues to distribute or communicate the Work.
133
+
134
+ Legal Protection: This Licence does not grant permission to use the trade names,
135
+ trademarks, service marks, or names of the Licensor, except as required for
136
+ reasonable and customary use in describing the origin of the Work and
137
+ reproducing the content of the copyright notice.
138
+
139
+ 6. Chain of Authorship
140
+
141
+ The original Licensor warrants that the copyright in the Original Work granted
142
+ hereunder is owned by him/her or licensed to him/her and that he/she has the
143
+ power and authority to grant the Licence.
144
+
145
+ Each Contributor warrants that the copyright in the modifications he/she brings
146
+ to the Work are owned by him/her or licensed to him/her and that he/she has the
147
+ power and authority to grant the Licence.
148
+
149
+ Each time You accept the Licence, the original Licensor and subsequent
150
+ Contributors grant You a licence to their contributions to the Work, under the
151
+ terms of this Licence.
152
+
153
+ 7. Disclaimer of Warranty
154
+
155
+ The Work is a work in progress, which is continuously improved by numerous
156
+ Contributors. It is not a finished work and may therefore contain defects or
157
+ ‘bugs’ inherent to this type of development.
158
+
159
+ For the above reason, the Work is provided under the Licence on an ‘as is’ basis
160
+ and without warranties of any kind concerning the Work, including without
161
+ limitation merchantability, fitness for a particular purpose, absence of defects
162
+ or errors, accuracy, non-infringement of intellectual property rights other than
163
+ copyright as stated in Article 6 of this Licence.
164
+
165
+ This disclaimer of warranty is an essential part of the Licence and a condition
166
+ for the grant of any rights to the Work.
167
+
168
+ 8. Disclaimer of Liability
169
+
170
+ Except in the cases of wilful misconduct or damages directly caused to natural
171
+ persons, the Licensor will in no event be liable for any direct or indirect,
172
+ material or moral, damages of any kind, arising out of the Licence or of the use
173
+ of the Work, including without limitation, damages for loss of goodwill, work
174
+ stoppage, computer failure or malfunction, loss of data or any commercial
175
+ damage, even if the Licensor has been advised of the possibility of such damage.
176
+ However, the Licensor will be liable under statutory product liability laws as
177
+ far such laws apply to the Work.
178
+
179
+ 9. Additional agreements
180
+
181
+ While distributing the Work, You may choose to conclude an additional agreement,
182
+ defining obligations or services consistent with this Licence. However, if
183
+ accepting obligations, You may act only on your own behalf and on your sole
184
+ responsibility, not on behalf of the original Licensor or any other Contributor,
185
+ and only if You agree to indemnify, defend, and hold each Contributor harmless
186
+ for any liability incurred by, or claims asserted against such Contributor by
187
+ the fact You have accepted any warranty or additional liability.
188
+
189
+ 10. Acceptance of the Licence
190
+
191
+ The provisions of this Licence can be accepted by clicking on an icon ‘I agree’
192
+ placed under the bottom of a window displaying the text of this Licence or by
193
+ affirming consent in any other similar way, in accordance with the rules of
194
+ applicable law. Clicking on that icon indicates your clear and irrevocable
195
+ acceptance of this Licence and all of its terms and conditions.
196
+
197
+ Similarly, you irrevocably accept this Licence and all of its terms and
198
+ conditions by exercising any rights granted to You by Article 2 of this Licence,
199
+ such as the use of the Work, the creation by You of a Derivative Work or the
200
+ Distribution or Communication by You of the Work or copies thereof.
201
+
202
+ 11. Information to the public
203
+
204
+ In case of any Distribution or Communication of the Work by means of electronic
205
+ communication by You (for example, by offering to download the Work from a
206
+ remote location) the distribution channel or media (for example, a website) must
207
+ at least provide to the public the information requested by the applicable law
208
+ regarding the Licensor, the Licence and the way it may be accessible, concluded,
209
+ stored and reproduced by the Licensee.
210
+
211
+ 12. Termination of the Licence
212
+
213
+ The Licence and the rights granted hereunder will terminate automatically upon
214
+ any breach by the Licensee of the terms of the Licence.
215
+
216
+ Such a termination will not terminate the licences of any person who has
217
+ received the Work from the Licensee under the Licence, provided such persons
218
+ remain in full compliance with the Licence.
219
+
220
+ 13. Miscellaneous
221
+
222
+ Without prejudice of Article 9 above, the Licence represents the complete
223
+ agreement between the Parties as to the Work.
224
+
225
+ If any provision of the Licence is invalid or unenforceable under applicable
226
+ law, this will not affect the validity or enforceability of the Licence as a
227
+ whole. Such provision will be construed or reformed so as necessary to make it
228
+ valid and enforceable.
229
+
230
+ The European Commission may publish other linguistic versions or new versions of
231
+ this Licence or updated versions of the Appendix, so far this is required and
232
+ reasonable, without reducing the scope of the rights granted by the Licence. New
233
+ versions of the Licence will be published with a unique version number.
234
+
235
+ All linguistic versions of this Licence, approved by the European Commission,
236
+ have identical value. Parties can take advantage of the linguistic version of
237
+ their choice.
238
+
239
+ 14. Jurisdiction
240
+
241
+ Without prejudice to specific agreement between parties,
242
+
243
+ - any litigation resulting from the interpretation of this License, arising
244
+ between the European Union institutions, bodies, offices or agencies, as a
245
+ Licensor, and any Licensee, will be subject to the jurisdiction of the Court
246
+ of Justice of the European Union, as laid down in article 272 of the Treaty on
247
+ the Functioning of the European Union,
248
+
249
+ - any litigation arising between other parties and resulting from the
250
+ interpretation of this License, will be subject to the exclusive jurisdiction
251
+ of the competent court where the Licensor resides or conducts its primary
252
+ business.
253
+
254
+ 15. Applicable Law
255
+
256
+ Without prejudice to specific agreement between parties,
257
+
258
+ - this Licence shall be governed by the law of the European Union Member State
259
+ where the Licensor has his seat, resides or has his registered office,
260
+
261
+ - this licence shall be governed by Belgian law if the Licensor has no seat,
262
+ residence or registered office inside a European Union Member State.
263
+
264
+ Appendix
265
+
266
+ ‘Compatible Licences’ according to Article 5 EUPL are:
267
+
268
+ - GNU General Public License (GPL) v. 2, v. 3
269
+ - GNU Affero General Public License (AGPL) v. 3
270
+ - Open Software License (OSL) v. 2.1, v. 3.0
271
+ - Eclipse Public License (EPL) v. 1.0
272
+ - CeCILL v. 2.0, v. 2.1
273
+ - Mozilla Public Licence (MPL) v. 2
274
+ - GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
275
+ - Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for
276
+ works other than software
277
+ - European Union Public Licence (EUPL) v. 1.1, v. 1.2
278
+ - Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong
279
+ Reciprocity (LiLiQ-R+).
280
+
281
+ The European Commission may update this Appendix to later versions of the above
282
+ licences without producing a new version of the EUPL, as long as they provide
283
+ the rights granted in Article 2 of this Licence and protect the covered Source
284
+ Code from exclusive appropriation.
285
+
286
+ All other changes or additions to this Appendix require the production of a new
287
+ EUPL version.
@@ -0,0 +1,5 @@
1
+ __init__
2
+ aggregate
3
+ choicellm
4
+ multichoicemodel
5
+ prompttemplate
choicellm.py ADDED
@@ -0,0 +1,247 @@
1
+ import argparse
2
+ import csv
3
+ import sys
4
+ import itertools
5
+ import random
6
+ import logging
7
+ from typing import Generator, Union, Iterable
8
+ import os
9
+ from openai import OpenAI
10
+ import functools
11
+ import io
12
+
13
+ from prompttemplate import PromptTemplate
14
+ from multichoicemodel import MultipleChoiceModel
15
+
16
+
17
+ N_DECIMALS = 6
18
+
19
+
20
+ def main():
21
+
22
+ argparser = argparse.ArgumentParser()
23
+ argparser.add_argument('file', nargs='?', type=argparse.FileType('r'), default=sys.stdin,
24
+ help='Plaintext file with one word/phrase per line. '
25
+ 'Set the --newlines flag to allow the inclusion of "\\n" to indicate newlines within items. '
26
+ 'Set the --csv flag to allow inputs in .csv format with one column and no header. '
27
+ 'For comparative mode, the csv input can also have n_choices columns.')
28
+
29
+ argparser.add_argument('--prompt', required=True, type=argparse.FileType('r'), default=None, help='.json file containing the prompt template, few-shot examples, etc. To generate a suitable template, first use the auxiliary command choicellm-template and adapt the template to your needs.')
30
+ argparser.add_argument('--model', required=False, type=str, default="unsloth/Llama-3.2-1B", help='Currently supports base models via transformers, and chat models through OpenAI (specify --openai in that case).')
31
+ argparser.add_argument('--openai', action='store_true', help='Set this flag for models through the OpenAI API; otherwise --model is assumed to be a local model via huggingface transformers.')
32
+
33
+ input_options = argparser.add_argument_group('flags to change input format')
34
+ input_options_excl = input_options.add_mutually_exclusive_group()
35
+ input_options_excl.add_argument('--csv', action='store_true', help='Set this flag if your input file is in .csv format, either a single column to allow newlines etc., or multiple columns (optionally) for comparative mode.')
36
+ input_options_excl.add_argument('--newlines', action='store_true', help='If you want your input file to include newlines, either use full, proper .csv format (and the --csv flag), or use this flag to simply replace occurrences of "\\n" in the input file by proper newlines.')
37
+
38
+ # TODO low-priority implement this, maybe replacing --all_positions
39
+ # argparser.add_argument('--n_orders', type=int, help='[not implemented yet] Whether to randomize the order of the categories, and if so, how often; -1 means all orders.', default=None)
40
+
41
+ # If --mode comparative:
42
+ comparative_group = argparser.add_argument_group('options for comparative mode (only if comparisons not predetermined in .csv input)')
43
+ comparative_group.add_argument('--compare_to', required=False, type=argparse.FileType('r'), default=None, help='File containing the words to compare against. Default is the main file argument itself. If --csv, then --compare_to must be a csv file as well.')
44
+ comparative_group.add_argument('--compare_deterministic', required=False, action='store_true', help='To make selection of alternatives deterministic; if --compare_to is given (and no overlap with items), this will result in the exact same comparisons per item.')
45
+ comparative_group.add_argument('--n_comparisons', required=False, type=int, default=100, help='Comparisons per stimulus.')
46
+ comparative_group.add_argument('--all_positions', action='store_true', help='Whether to average over all positions; only if comparative.')
47
+ comparative_group.add_argument('--seed', required=False, type=int, default=None, help='Seed to use for shuffling/sampling of comparisons. By default a random seed is picked. If --compare_deterministic, this seed is reused for each item\'s comparisons.')
48
+
49
+ args = argparser.parse_args()
50
+
51
+ logging.basicConfig(level=logging.INFO, format='')
52
+ if args.seed is None:
53
+ args.seed = random.randint(0, 99999)
54
+ random.seed(args.seed)
55
+ logging.info(f'{args.seed=}')
56
+
57
+ inputs, is_multicolumn = read_inputs(args.file, args.csv, args.newlines)
58
+
59
+ prompt_template = PromptTemplate.from_json(args.prompt)
60
+
61
+ if is_multicolumn and prompt_template.mode != 'comparative':
62
+ raise ValueError('Input .csv appears to have multiple columns, which is an option only for \'comparative\' mode.')
63
+ if args.model == argparser.get_default('model'):
64
+ logging.warning(f'WARNING: Using default model {args.model}, which is quite small and may not yield very accurate results; use --model to override it.')
65
+ if not args.openai and 'gpt4' in args.model:
66
+ logging.warning('WARNING: If you meant to use a model available through the OpenAI API, include --openai.')
67
+ if args.openai and not prompt_template.is_chat:
68
+ logging.warning('WARNING: Given --openai, you\'re advised to use a chat-style prompt.')
69
+ if 'instruct' in args.model.lower() and not prompt_template.is_chat:
70
+ logging.warning('WARNING: Given "instruct" model, you\'re advised to use a chat-style prompt.')
71
+
72
+ model = MultipleChoiceModel(
73
+ model_name=args.model,
74
+ labels=prompt_template.labels_for_logits,
75
+ prompt_start_for_cache=prompt_template.prompt_start_for_cache,
76
+ openai_client=OpenAI(api_key=os.environ.get('OPENAI_API_KEY')) if args.openai else None
77
+ )
78
+
79
+ match prompt_template.mode:
80
+ case 'comparative':
81
+ if is_multicolumn:
82
+ if args.compare_to:
83
+ logging.warning('WARNING: --compare_to is ignored, because input file is multi-column csv.')
84
+ items = ({'choices': choices, 'prompt': prompt_template.format(*choices)} for choices in inputs)
85
+ else:
86
+ if args.compare_to:
87
+ compare_to, is_multicolumn2 = read_inputs(args.compare_to, args.csv, args.newlines)
88
+ if is_multicolumn2:
89
+ raise ValueError('The --compare_to file appears to contain multiple .csv columns, which is not allowed.')
90
+ compare_to = list(compare_to)
91
+ else:
92
+ compare_to = inputs = list(inputs)
93
+ items = iter_items_comparison(inputs, args.n_comparisons, args.all_positions, prompt_template,
94
+ compare_to=compare_to, seed_per_item=args.seed if args.compare_deterministic else None)
95
+ add_results_to_dict = add_results_comparative
96
+ case 'categorical':
97
+ items = iter_items_basic(inputs, prompt_template)
98
+ add_results_to_dict = functools.partial(add_results_categorical, category_names=list(prompt_template.categories))
99
+ case 'scalar':
100
+ items = iter_items_basic(inputs, prompt_template)
101
+ add_results_to_dict = functools.partial(add_results_scalar, scale=prompt_template.scale)
102
+
103
+ logging.info(f'-------\n{prompt_template}\n-------')
104
+
105
+ csv_writer = DictWriterAutoHeader(sys.stdout)
106
+ for item in items:
107
+ probs = model.get_probs(item['prompt'])
108
+ add_results_to_dict(item, probs)
109
+ del item['prompt']
110
+ csv_writer.writerow(item)
111
+
112
+
113
+ def read_inputs(file, is_csv, escaped_newlines) -> tuple[Generator[Union[str, list[str]], None, None], bool]:
114
+ is_multicolumn = False
115
+ if is_csv:
116
+ rows = csv.reader(file)
117
+ first_item = next(rows)
118
+ if len(first_item) > 1:
119
+ is_multicolumn = True
120
+ items = itertools.chain([first_item], rows)
121
+ else:
122
+ items = itertools.chain([first_item[0]], (l[0] for l in rows))
123
+ elif escaped_newlines:
124
+ items = (line.strip().replace('\\n', '\n') for line in file)
125
+ else:
126
+ items = (line.strip() for line in file)
127
+ return items, is_multicolumn
128
+
129
+
130
+ def add_results_scalar(item: dict, probs: list[float], scale: list[int | float]):
131
+ max_index = max(range(len(probs)), key=lambda x: probs[x])
132
+ probs = [round(s, N_DECIMALS) for s in probs]
133
+ item['pred'] = scale[max_index]
134
+ item['prob'] = probs[max_index]
135
+ item['rating'] = round(sum(s * n for s, n in zip(probs, scale)), N_DECIMALS)
136
+ item['probs'] = make_csv_string(probs, delimiter=';')
137
+
138
+
139
+ def add_results_comparative(item: dict, probs: list[float]):
140
+ max_index = max(range(len(probs)), key=lambda x: probs[x])
141
+ probs = [round(s, N_DECIMALS) for s in probs]
142
+ item['pred'] = item['choices'][max_index]
143
+ if 'position' in item:
144
+ item['prob'] = probs[item['position']]
145
+ item['probs'] = make_csv_string(probs, delimiter=';')
146
+ item['choices'] = make_csv_string(item['choices'], delimiter=';')
147
+
148
+
149
+ def add_results_categorical(item: dict, probs: list[float], category_names: list[str]):
150
+ max_index = max(range(len(probs)), key=lambda x: probs[x])
151
+ probs = [round(s, N_DECIMALS) for s in probs]
152
+ item['pred'] = category_names[max_index]
153
+ item['prob'] = probs[max_index]
154
+ item['probs'] = make_csv_string(probs, delimiter=';')
155
+
156
+
157
+ def iter_items_basic(lines: Iterable[str], prompt_template: Union[str, PromptTemplate]) -> Generator[dict, None, None]:
158
+ for n, line in enumerate(lines):
159
+ prompt = prompt_template.format(line)
160
+ yield {'target_id': n, 'target': line, 'prompt': prompt}
161
+
162
+
163
+ def iter_items_comparison(items: Iterable[str], n_comparisons: int, all_positions: bool,
164
+ prompt_template: Union[str, PromptTemplate], compare_to: list[str],
165
+ seed_per_item: int) -> Generator[dict, None, None]:
166
+
167
+ n_choices = prompt_template.n_choices
168
+ n_alternatives = n_choices - 1
169
+
170
+ logging.info(f'Will do {n_comparisons * (n_choices if all_positions else 1)} comparisons per input line.')
171
+
172
+ for item_id, item in enumerate(items):
173
+
174
+ if seed_per_item is not None:
175
+ random.seed(seed_per_item)
176
+
177
+ all_alternatives = random_sample_not_containing(compare_to, n_comparisons * n_alternatives, item_to_exclude=item)
178
+
179
+ for comp_id, alternatives in enumerate(batched(all_alternatives, n_alternatives)):
180
+ positions = range(n_choices) if all_positions else [random.randint(0, n_alternatives)]
181
+ for pos in positions:
182
+ choices = alternatives[:pos] + [item] + alternatives[pos:]
183
+ prompt = prompt_template.format(*choices)
184
+ yield {'target_id': item_id, 'comparison_id': comp_id, 'position': pos, 'target': item, 'choices': choices, 'prompt': prompt}
185
+
186
+
187
+ def random_sample_not_containing(items: list, k: int, item_to_exclude) -> list:
188
+ """
189
+ Like random.sample(items, k), but excluding a specific element from the original. Original order not maintained.
190
+ """
191
+ sample = random.sample(items, k=min(k + 1, len(items))) # one more if possible just in case item is among them
192
+ try:
193
+ sample.remove(item_to_exclude)
194
+ except ValueError: # if item not found
195
+ if len(sample) > k:
196
+ sample.pop()
197
+
198
+ if len(sample) < k:
199
+ raise ValueError(
200
+ f'Not enough comparison items for n_choices × n_comparisons comparisons per item. '
201
+ f'Decrease n_choices or --n_comparisons, or provide a longer list of items to compare '
202
+ f'to (--compare_to).')
203
+
204
+ return sample
205
+
206
+
207
+ def batched(iterable, n, *, strict=False) -> Generator[list, None, None]:
208
+ """
209
+ Was added to itertools only in Python 3.12, so included here.
210
+ >>> batched('ABCDEFG', 3)
211
+ ['A', 'B', 'C'], ['D', 'E', 'F'], ['G']
212
+ """
213
+ if n < 1:
214
+ raise ValueError('n must be at least one')
215
+ iterator = iter(iterable)
216
+ while batch := list(itertools.islice(iterator, n)):
217
+ if strict and len(batch) != n:
218
+ raise ValueError('batched(): incomplete batch')
219
+ yield batch
220
+
221
+
222
+ class DictWriterAutoHeader(csv.DictWriter):
223
+ """
224
+ A csv.DictWriter wrapper that lazily sets the fieldnames and writes the header automatically based
225
+ on the first writerow call.
226
+ """
227
+
228
+ def __init__(self, f):
229
+ super().__init__(f, fieldnames=[])
230
+
231
+ def writerow(self, rowdict):
232
+ if not self.fieldnames:
233
+ self.fieldnames.extend(rowdict.keys())
234
+ self.writeheader()
235
+ super().writerow(rowdict)
236
+
237
+
238
+ def make_csv_string(row: list, delimiter=','):
239
+ output = io.StringIO()
240
+ writer = csv.writer(output, delimiter=delimiter)
241
+ writer.writerow(row)
242
+ csv_string = output.getvalue().strip()
243
+ return csv_string
244
+
245
+
246
+ if __name__ == '__main__':
247
+ main()
multichoicemodel.py ADDED
@@ -0,0 +1,181 @@
1
+ import torch
2
+ import copy
3
+ import logging
4
+ import transformers
5
+ import functools
6
+ from typing import Union
7
+ import tiktoken
8
+
9
+ DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
10
+
11
+
12
+ class MultipleChoiceModel:
13
+ """
14
+ Wrapper around huggingface base LLMS and openai chat models for multiple-choice prompting, implementing a `get_scores` method.
15
+
16
+ Its main role is to extract the computed logits to obtain probabilities for the multiple choices.
17
+ """
18
+
19
+ def __init__(self, model_name, labels, prompt_start_for_cache=None, openai_client=None):
20
+
21
+ if openai_client:
22
+ tokenizer = tiktoken.encoding_for_model(model_name) # for o1, mind https://github.com/openai/tiktoken/issues/367
23
+ labels = [l.strip() for l in labels] # Hmmmm strip spaces
24
+ labels_tokenized = [tokenizer.encode(label) for label in labels]
25
+ label_ids = [label_tokenized[0] for label_tokenized in labels_tokenized]
26
+ # TODO: For o1 model, logprobs not supported; so consider disabling the logprobs and just getting the output directly?
27
+ self.get_probs = functools.partial(self.get_multiple_choice_prob_openai, model_name=model_name, client=openai_client, labels=labels, label_ids=label_ids)
28
+
29
+ problematic_labels = [label for label, label_tokenized in zip(labels, labels_tokenized) if len(label_tokenized) != 1]
30
+ if problematic_labels:
31
+ raise ValueError(f'Some of the choice labels do not map onto single tokens for your selected model: {", ".join(problematic_labels)}')
32
+ logging.info(f'Using label ids: {label_ids}')
33
+
34
+ else: # assuming local transformers model
35
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_name, clean_up_tokenization_spaces=False)
36
+ labels_tokenized = [tokenizer.encode(label, add_special_tokens=False) for label in labels]
37
+ model = transformers.AutoModelForCausalLM.from_pretrained(model_name).to(DEVICE)
38
+ model.eval()
39
+
40
+ cached_common_start = create_cache(model, tokenizer, prompt_start_for_cache) if prompt_start_for_cache else None
41
+ self.get_probs = functools.partial(self.get_multiple_choice_prob,
42
+ model=model,
43
+ tokenizer=tokenizer,
44
+ labels_tokenized=labels_tokenized,
45
+ cache=cached_common_start)
46
+
47
+
48
+ def get_scores(self, prompt: Union[str, list[str]]) -> list[float]:
49
+ pass # Hmmm... Overwritten by init.
50
+
51
+ @staticmethod
52
+ def get_multiple_choice_prob(prompt: Union[str, list[dict]], model, tokenizer, labels_tokenized: list[int], cache=None) -> list[float]:
53
+ """
54
+ Feeds prompt into a local transformers model, and obtains the probabilities of the different multiple-choice
55
+ labels.
56
+
57
+ Because the labels can in principle be multi-token, it takes a bit of work to get their probabilities, with iterative
58
+ prompting based on growing prefixes, and multiplying the resulting conditional probabilities.
59
+
60
+ When labels are single tokens, this function simply applies the model once and get the logits directly.
61
+ """
62
+
63
+ # TODO: Generalize and expose this function, maybe in a more general LLM utils module?
64
+
65
+ if isinstance(prompt, str):
66
+ prompt_encoded = tokenizer(prompt, return_tensors='pt').to(DEVICE)
67
+ else: # openai-style messages
68
+ prompt_encoded = tokenizer.apply_chat_template(prompt, return_tensors="pt", add_generation_prompt=True, return_dict=True).to(DEVICE)
69
+
70
+ choice_probabilities = [1 for _ in labels_tokenized] # to be iteratively multiplied (conditional probabilities)
71
+ for prefix, label_ids, next_token_ids in get_label_prefixes(tuple(tuple(t) for t in labels_tokenized)):
72
+ prompt_encoded_plus_prefix = torch.cat(
73
+ (prompt_encoded['input_ids'], torch.tensor([prefix], dtype=int).to(DEVICE)),
74
+ dim=-1
75
+ )
76
+ attention_mask_plus_prefix = torch.cat(
77
+ (prompt_encoded['attention_mask'], torch.tensor([[1] * len(prefix)], dtype=int).to(DEVICE)),
78
+ dim=-1
79
+ )
80
+ model_output = model.generate(
81
+ input_ids=prompt_encoded_plus_prefix,
82
+ attention_mask=attention_mask_plus_prefix, # only to avoid a warning
83
+ pad_token_id=tokenizer.eos_token_id,
84
+ output_logits=True,
85
+ return_dict_in_generate=True,
86
+ do_sample=False,
87
+ max_new_tokens=1,
88
+ past_key_values=copy.deepcopy(cache) if cache else None,
89
+ temperature=None, # only to avoid a warning
90
+ top_p=None
91
+ )
92
+
93
+ next_token_ids_unique = list(set(next_token_ids))
94
+ logits = model_output.logits[0] # [0] is first (and only) generated token
95
+ logits_to_use = logits[:, next_token_ids_unique]
96
+ probs_to_use = torch.nn.functional.softmax(logits_to_use, dim=-1)[0].tolist() # [0] is first (and only) batch
97
+ token_id_to_prob = dict(zip(next_token_ids_unique, probs_to_use))
98
+
99
+ for label_id, next_token_id in zip(label_ids, next_token_ids):
100
+ choice_probabilities[label_id] *= token_id_to_prob[next_token_id]
101
+
102
+ return choice_probabilities
103
+
104
+
105
+ @staticmethod
106
+ def get_multiple_choice_prob_openai(prompt: list[dict], client, model_name, labels, label_ids: list[int]) -> list[float]:
107
+
108
+ LOGIT_BIAS = 10
109
+
110
+ completion = client.chat.completions.create(
111
+ model=model_name,
112
+ messages=prompt,
113
+ logprobs=True,
114
+ top_logprobs=10,
115
+ logit_bias={l: LOGIT_BIAS for l in label_ids},
116
+ max_completion_tokens=10,
117
+ )
118
+
119
+ label_logprobs = {}
120
+ for logprob_dict in completion.choices[0].logprobs.content[0].top_logprobs:
121
+ token, logprob = logprob_dict.token, logprob_dict.logprob
122
+ if token in labels:
123
+ label_logprobs[token] = logprob - LOGIT_BIAS
124
+
125
+ newline = "\n"
126
+ logging.info(f'{prompt[-1]["content"].replace(newline, "/")} -> {completion.choices[0].message.content}')
127
+
128
+ label_logprobs_tensor = torch.tensor([label_logprobs.get(label, -90) - LOGIT_BIAS for label in labels])
129
+ probs = torch.nn.functional.softmax(label_logprobs_tensor, dim=-1)
130
+ return probs.tolist()
131
+
132
+
133
+ def create_cache(model, tokenizer, common_start: str) -> transformers.DynamicCache:
134
+ with torch.no_grad():
135
+ if isinstance(common_start, str):
136
+ inputs = tokenizer(common_start, return_tensors="pt").to(DEVICE)
137
+ else:
138
+ inputs = tokenizer.apply_chat_template(common_start, return_tensors="pt", return_dict=True).to(DEVICE)
139
+
140
+ ## In case multiple beams/sequences, also expand the cache (https://github.com/huggingface/transformers/pull/27576)
141
+ # inputs = inputs.expand(num_beams, *inputs.shape[1:])
142
+
143
+ cache = model(input_ids=inputs['input_ids'],
144
+ attention_mask=inputs['attention_mask'], # only to avoid a warning
145
+ past_key_values=transformers.DynamicCache(),
146
+ pad_token_id=tokenizer.eos_token_id).past_key_values
147
+ return cache
148
+
149
+
150
+ @functools.cache
151
+ def get_label_prefixes(labels_tokenized: tuple[tuple[int]]) -> list[tuple[tuple[int], list[int], list[int]]]:
152
+ """
153
+ # TODO: Generalize.
154
+
155
+ For computing probabilities of multi-token labels (e.g., the two-token string '-1' for negative sentiment),
156
+ beam search isn't quite suitable. So we manually implement beam search, but specifically one beam for each
157
+ possible prefix. To that end, this helper function computes all 'shared prefixes' and their next tokens
158
+ (and index of the corresponding labels).
159
+
160
+ Yields 3-tuples for each (shared) prefix and a list of the label_ids that share it, and their respective next_token_ids.
161
+
162
+ >>> get_label_prefixes(((2, ), (3, )))
163
+ [((), (0, 1), (2, 3))]
164
+ >>> get_label_prefixes(((1, 2), (1, 3)))
165
+ [((1), (0, 1), (2, 3)), ((), (0, 1), (1, 1)]
166
+ >>> get_label_prefixes(((1, 2, 3), (1, 4, 5), (0, 2), (1, 5)))
167
+ [((1, 2), [0], [3]), ((1, 5), [], []), ((1, 4), [1], [5]), ((1,), [0, 1, 3], [2, 4, 5]), ((0, 2), [], []), ((0,), [2], [2]), ((), [0, 1, 2, 3], [1, 1, 0, 1])]
168
+ """
169
+
170
+ max_length = max(len(t) for t in labels_tokenized)
171
+ unique_prefixes = {l[:n] for n in range(max_length) for l in labels_tokenized}
172
+ result = []
173
+ for prefix in unique_prefixes:
174
+ label_ids = []
175
+ next_token_ids = []
176
+ for i, l in enumerate(labels_tokenized):
177
+ if l[:len(prefix)] == prefix and len(l) > len(prefix):
178
+ label_ids.append(i)
179
+ next_token_ids.append(l[len(prefix)])
180
+ result.append((prefix, label_ids, next_token_ids))
181
+ return result
prompttemplate.py ADDED
@@ -0,0 +1,290 @@
1
+ import random
2
+ from typing import Literal, Union, Optional
3
+ import itertools
4
+ import copy
5
+ import json
6
+ import logging
7
+ import argparse
8
+
9
+
10
+ # TODO: Drastic refactoring needed
11
+ # TODO: Make fields in prompt template optional, i.e., not used if not present;
12
+ # TODO: Add optional 'mid point' field to prompt template.
13
+
14
+ class PromptTemplate:
15
+
16
+ """
17
+ Wrapper around plain string prompt templates, and openai-style message lists, both exposing the method `format`.
18
+
19
+ Justification:
20
+ - Instantiating prompt templates from prompt info (e.g., .json file) is slightly different in case of scalar, comparative and categorical prompting.
21
+ - I want openai-style 'messages' (list of dicts) to behave the same, on the outside, as a formatable string.
22
+ """
23
+
24
+ def __init__(self, mode: Literal['scalar', 'comparative', 'categorical'], is_chat: bool, *args, n_choices: int = None, **kwargs):
25
+
26
+ self.mode = mode
27
+ self.is_chat = is_chat
28
+ if n_choices:
29
+ self.n_choices = n_choices # meh
30
+ kwargs['n_choices'] = n_choices # meh
31
+
32
+ # TODO: Call the following in load_from_json:
33
+ system_prompt, examples, prompt = (
34
+ self.init_for_scalar if mode == 'scalar'
35
+ else self.init_for_comparative if mode == 'comparative'
36
+ else self.init_for_categorical
37
+ )(*args, **kwargs)
38
+
39
+ if mode == 'comparative':
40
+ self.labels_for_logits = kwargs['labels'][:kwargs['n_choices']] # TODO labels_for_logits is the model's business...
41
+ elif mode == 'categorical':
42
+ self.labels_for_logits = kwargs['labels'][:len(kwargs['categories'])]
43
+ self.categories = kwargs['categories']
44
+ else:
45
+ self.scale = kwargs['scale']
46
+ self.labels_for_logits = [str(i) for i in kwargs['scale']]
47
+ if not self.is_chat: # meh...
48
+ self.labels_for_logits = [' ' + l for l in self.labels_for_logits]
49
+
50
+ if is_chat:
51
+ self.prompt_format = [
52
+ {"role": "developer", "content": system_prompt},
53
+ *itertools.chain(*([{"role": "user", "content": example}, {"role": "assistant", "content": response}] for example, response in examples)),
54
+ {"role": "user", "content": prompt}
55
+ ]
56
+ def format(*args, **kwargs):
57
+ messages = copy.deepcopy(self.prompt_format)
58
+ messages[-1]['content'] = messages[-1]['content'].format(*args, **kwargs)
59
+ return messages
60
+ self.prompt_start_for_cache = self.prompt_format[:-1]
61
+ self.format = format
62
+ else:
63
+ prompt_parts = [system_prompt] + [x + ' ' + r for x, r in examples] + [prompt]
64
+ self.prompt_start_for_cache = '\n\n'.join(prompt_parts[:-1])
65
+ self.prompt_format = '\n\n'.join(prompt_parts)
66
+ self.format = self.prompt_format.format
67
+
68
+ def format(self, *args, **kwargs) -> Union[str, list[dict]]:
69
+ pass # to be overwritten by init; is that 'normal'?
70
+
71
+ def __str__(self):
72
+ if isinstance(self.prompt_format, str):
73
+ return self.prompt_format
74
+ else:
75
+ return json.dumps(self.prompt_format, indent=2)
76
+
77
+ @classmethod
78
+ def from_json(cls, file):
79
+
80
+ prompt_info = json.load(file) # TODO: JSON validation, incl. labels for categorical/comparative must be strings
81
+ prompt_info.pop('_comment', None)
82
+
83
+ if "chat" not in prompt_info:
84
+ logging.warning(
85
+ f'WARNING: The prompt .json file does not specify whether to use chat-style prompting; assuming "chat": false')
86
+ prompt_kwargs['chat'] = False
87
+
88
+ prompt_info['is_chat'] = prompt_info.pop('chat')
89
+
90
+ mode = prompt_info['mode']
91
+ is_chat = prompt_info['mode']
92
+
93
+ if mode in ('categorical', 'comparative') and 'labels' not in prompt_info:
94
+ # TODO: In future, allow using categories/items themselves as labels; for now, just ABCD...
95
+ prompt_info['labels'] = list(string.ascii_uppercase)
96
+
97
+ return cls(**prompt_info)
98
+
99
+
100
+ @staticmethod
101
+ def init_for_scalar(system_prompt: str, prompt_format: str, examples: list[dict], scale: list[int | float]) -> tuple[str, list[tuple[str, str]], str]:
102
+
103
+ if all(isinstance(n, int) for n in scale):
104
+ rating_as_int = True
105
+ else:
106
+ scale = [float(n) for n in scale]
107
+
108
+ labels = [str(number) for number in scale]
109
+ scale_min, scale_max = scale[0], scale[-1]
110
+ system_prompt = system_prompt.format(scale=', '.join(labels), scale_min=scale_min, scale_max=scale_max)
111
+ label_hint = f' (on scale {scale_min}-{scale_max})'
112
+
113
+ examples_list = []
114
+ n = 0 # in case no examples
115
+ for n, example in enumerate(examples, start=1):
116
+ rating_scaled = example['target_value'] * (scale_max - scale_min) + scale_min
117
+ rating_scaled = int(rating_scaled) if rating_as_int else float(rating_scaled)
118
+ examples_list.append((
119
+ prompt_format.format(n=n, item=example['item'], label_hint=label_hint),
120
+ str(rating_scaled),
121
+ ))
122
+ prompt = prompt_format.format(n=n+1, item='{}', label_hint=label_hint)
123
+
124
+ return system_prompt, examples_list, prompt
125
+
126
+ @staticmethod
127
+ def init_for_categorical(system_prompt: str, prompt_format: str, examples: list[dict], categories: dict, labels: Optional[list[str]] = None) -> tuple[str, list[tuple[str, str]], str]:
128
+ if labels:
129
+ categories_full = '\n'.join(f'{l}. {c}: {d}' for l, (c, d) in zip(labels, categories.items()))
130
+ else:
131
+ categories_full = '\n'.join(f'- {c}: {d}' for c, d in categories.items())
132
+ category_names = list(categories.keys())
133
+ system_prompt = system_prompt.format(categories=categories_full)
134
+ examples_list = []
135
+ n = 0
136
+
137
+ label_hint = f' (choose from {"/".join(labels)})' if labels else ''
138
+
139
+ for n, example in enumerate(examples, start=1):
140
+ examples_list.append((
141
+ prompt_format.format(n=n, item=example['item'], label_hint=label_hint),
142
+ f"{labels[example['target_index']]} ({category_names[example['target_index']]})"
143
+ ))
144
+
145
+ prompt = prompt_format.format(n=n+1, item='{}', label_hint=label_hint)
146
+
147
+ return system_prompt, examples_list, prompt
148
+
149
+ @staticmethod
150
+ def init_for_comparative(system_prompt: str, prompt_format: str, n_choices: int, examples: list[dict], labels: list[str] = None) -> tuple[str, list[tuple[str, str]], str]:
151
+
152
+ if labels:
153
+ labels = labels[:n_choices]
154
+
155
+ def make_choices_str(choices: list[str], labels: Optional[list[str]] = None) -> str:
156
+ if labels:
157
+ return '\n'.join((f'{label}. {choice}' for label, choice in zip(labels, choices)))
158
+ else:
159
+ return '\n'.join(f'- {choice}' for choice in choices)
160
+
161
+ label_hint = f' (choose from {"/".join(labels)})' if labels else ''
162
+ system_prompt = system_prompt
163
+ n = 0
164
+ examples_list = []
165
+ for n, example in enumerate(examples, start=1):
166
+
167
+ if example['target_index'] >= n_choices:
168
+ target = example['options'][example['target_index']]
169
+ example['target_index'] = random.randint(0, n_choices-1)
170
+ example['options'][example['target_index']] = target
171
+ example['options'] = example['options'][:n_choices]
172
+
173
+ examples_list.append((
174
+ prompt_format.format(n=n, choices=make_choices_str(example['options'], labels), label_hint=label_hint),
175
+ labels[example['target_index']]
176
+ ))
177
+ prompt = prompt_format.format(n=n+1, choices=make_choices_str(['{}'] * n_choices, labels), label_hint=label_hint)
178
+ return system_prompt, examples_list, prompt
179
+
180
+
181
+ TEMPLATE_SCALAR = {
182
+ "mode": "scalar",
183
+ "chat": False,
184
+ "system_prompt": "# Concrete vs. abstract\n\nSome words and phrases are more concrete, some are more abstract. "
185
+ "We can indicate how concrete a given word or phrase is, as a rating on a scale {scale}, "
186
+ "with {scale_min} very abstract, and {scale_max} very concrete.",
187
+ "prompt_format": "## Example {n}.\n\nWord/phrase: {item}\n\nConcreteness rating{label_hint}:",
188
+ "scale": [1, 2, 3, 4, 5],
189
+ "examples": [
190
+ {"item": "essentialness", "target_value": 0.0},
191
+ {"item": "frangipane", "target_value": 1.0},
192
+ {"item": "although", "target_value": 0.0},
193
+ {"item": "blackbird", "target_value": 1.0},
194
+ {"item": "bat", "target_value": 1.0},
195
+ {"item": "hope", "target_value": 0.0},
196
+ ],
197
+ "_comment": "In the examples, \"target_value\" is the target rating as a float between [0, 1]. This will be automatically mapped to whichever scale is used. This facilitates trying different scales with the same examples."
198
+ }
199
+
200
+ TEMPLATE_SCALAR_CHAT = TEMPLATE_SCALAR.copy()
201
+ TEMPLATE_SCALAR_CHAT.update({
202
+ 'chat': True,
203
+ 'system_prompt': 'Some words and phrases are more concrete, some are more abstract. You are a helpful assistant, '
204
+ 'who is an expert on rating how *concrete* a given word or phrase is, as a rating on a scale '
205
+ '{scale}, with {scale_min} very abstract, and {scale_max} very concrete.',
206
+ 'prompt_format': '## Question {n}.\n\nWord/phrase: {item}\n\nHow concrete is this {label_hint}?',
207
+ })
208
+
209
+ TEMPLATE_COMPARATIVE = {
210
+ "mode": "comparative",
211
+ "chat": False,
212
+ "system_prompt": "# Concrete vs. abstract\n\nSome words and phrases are more concrete, some are more abstract. "
213
+ "We can often tell which word or phrase, from a given set, is the _most concrete_ one.",
214
+ "prompt_format": "## Example {n}.\n\n{choices}\n\nThe most concrete is{label_hint}:", # TODO: Insert "choose from labels" only if choices are not single words?
215
+ "n_choices": 4,
216
+ "labels": ["A", "B", "C", "D"],
217
+ "examples": [
218
+ {"options": ["essentialness", "simulation", "bat", "living"], "target_index": 2},
219
+ {"options": ["blackbird", "high", "cause", "although"], "target_index": 0},
220
+ {"options": ["signature", "frangipane", "hope", "simulation"], "target_index": 1},
221
+ ],
222
+ "_comment": "If \"labels\" is omitted, will use the options themselves as responses (recommended only if the options are single words). Under \"examples\", \"target_index\" is always the integer index of the correct choice in the list, 0-based."
223
+ }
224
+
225
+ TEMPLATE_COMPARATIVE_CHAT = TEMPLATE_COMPARATIVE.copy()
226
+ TEMPLATE_COMPARATIVE_CHAT.update({
227
+ 'chat': True,
228
+ 'system_prompt': 'Some words and phrases are more concrete, some are more abstract. You are a helpful assistant, '
229
+ 'who is an expert on deciding which of several words or phrases is the _most concrete_.',
230
+ 'prompt_format': '## Question {n}.\n\n{choices}\n\nWhich of these is the most concrete{label_hint}?',
231
+ })
232
+
233
+ TEMPLATE_CATEGORICAL = {
234
+ "mode": "categorical",
235
+ "chat": False,
236
+ "system_prompt": "# Concrete vs. abstract\n\nSome words and phrases are more concrete, some are more abstract. "
237
+ "We distinguish the following categories:\n\n{categories}",
238
+ "prompt_format": "## Example {n}.\n\nWord/phrase: {item}\n\nThis word/phrase fits best in category{label_hint}:",
239
+ "labels": ["A", "B", "C"],
240
+ "categories": {
241
+ "concrete": "the word refers to something actual, concrete, empirical",
242
+ "neutral": "the word is neither abstract nor concrete",
243
+ "abstract": "the word refers to something conceptual, intangible, theoretical or vague"
244
+ },
245
+ "examples": [
246
+ {"item": "essentialness", "target_index": 0},
247
+ {"item": "frangipane", "target_index": 2},
248
+ {"item": "although", "target_index": 0},
249
+ {"item": "blackbird", "target_index": 2},
250
+ {"item": "bat", "target_index": 2},
251
+ {"item": "hope", "target_index": 0}
252
+ ],
253
+ "_comment": "If \"labels\" is omitted, will use the options themselves as responses (recommended only if the category names are single words). Under \"examples\", \"target_index\" is always the integer index of the correct choice in the list, 0-based."
254
+ }
255
+
256
+ TEMPLATE_CATEGORICAL_CHAT = TEMPLATE_CATEGORICAL.copy()
257
+ TEMPLATE_CATEGORICAL_CHAT.update({
258
+ 'chat': True,
259
+ 'system_prompt': 'Some words and phrases are more concrete, some are more abstract. You are a helpful assistant, '
260
+ 'who is an expert on categorizing words and phrases into one of three categories:\n\n{categories}',
261
+ 'prompt_format': '## Question {n}.\n\n{item}\n\nIn which category does this word/phrase fit best{label_hint}?',
262
+ })
263
+
264
+
265
+ def main():
266
+
267
+ argparser = argparse.ArgumentParser('Auxiliary command to generate prompt template .json files.')
268
+ argparser.add_argument('--chat', action='store_true', help='Whether to prompt the model like a chat/instruct model; otherwise plain text generation.')
269
+ group = argparser.add_mutually_exclusive_group(required=True)
270
+ group.add_argument('--comparative', action='store_true', help='Generate a prompt template for choicellm --mode comparative.')
271
+ group.add_argument('--scalar', action='store_true', help='Generate a prompt template for choicellm --mode scalar.')
272
+ group.add_argument('--categorical', action='store_true', help='Generate a prompt template for choicellm --mode categorical.')
273
+
274
+ args = argparser.parse_args()
275
+
276
+ logging.basicConfig(level=logging.INFO, format='')
277
+
278
+ mode = 'comparative' if args.comparative else 'scalar' if args.scalar else 'categorical'
279
+
280
+ template = globals()[f'TEMPLATE_{mode.upper()}{"_CHAT" if args.chat else ""}']
281
+ template_as_json = json.dumps(template, indent=2)
282
+
283
+ logging.info(f'Creating a JSON-format prompt template for {mode}, {"chat-style" if args.chat else "plain text generation"} prompting. '
284
+ f'Save this to a .json file, and modify to suit your needs.')
285
+
286
+ print(template_as_json)
287
+
288
+
289
+ if __name__ == '__main__':
290
+ main()