Metadata-Version: 2.4
Name: choicellm
Version: 0.4.1
Summary: Using LLMs for rating items on a scale, comparative judgments, and multiple choice questions.
Author-email: Matthijs Westera <m.westera@hum.leidenuniv.nl>
Project-URL: Homepage, https://github.com/mwestera/choicellm
Project-URL: Bug Tracker, https://github.com/mwestera/choicellm/issues
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Text Processing :: Linguistic
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyyaml
Provides-Extra: local
Requires-Dist: torch; extra == "local"
Requires-Dist: transformers; extra == "local"
Requires-Dist: accelerate; extra == "local"
Requires-Dist: bitsandbytes; extra == "local"
Provides-Extra: openai
Requires-Dist: openai; extra == "openai"
Requires-Dist: tiktoken; extra == "openai"
Provides-Extra: all
Requires-Dist: torch; extra == "all"
Requires-Dist: transformers; extra == "all"
Requires-Dist: accelerate; extra == "all"
Requires-Dist: bitsandbytes; extra == "all"
Requires-Dist: openai; extra == "all"
Requires-Dist: tiktoken; extra == "all"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Dynamic: license-file

# ChoiceLLM: A Python package for ratings and multiple choice answers from LLMs 

## Purpose

This tool makes it easier to prompt an LLM for:

- 'scalar' judgments (e.g., "On a scale from 1 to 7, how abstract is this word?", "How suggestive is this question?").
- 'comparative' judgments (e.g., "Of these 4 words, which is the most emotional?")
- '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?").

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`).

The scores obtained are deterministic, obtained by accessing the underlying logits computed by the model (as opposed to sampling a concrete response).

## Installation

Pick the backend(s) you need via extras:

```bash
pip install "choicellm[local]"      # local Huggingface models (torch + transformers)
pip install "choicellm[openai]"     # models via an OpenAI-compatible API (OpenAI, llama.cpp, vLLM, ...)
pip install "choicellm[all]"        # everything
```

Installation makes available the main program `choicellm`, and helper programs `choicellm-template` and `choicellm-aggregate`. (`choicellm-template` and `choicellm-aggregate` need no extras.)

### Running local models on a GPU (PyTorch build)

For local (Huggingface transformers) models, `choicellm` uses your GPU automatically *if* PyTorch can see it. A common pitfall: `pip install` may pull a PyTorch build compiled for a newer CUDA than your NVIDIA driver supports, in which case PyTorch **silently falls back to CPU** (very slow) — no error, just slow runs. `choicellm` will print `Loading model on device: cpu` and a warning when this happens.

To avoid it, install the PyTorch build that matches your system *before* (or after) installing `choicellm`, following the official selector at <https://pytorch.org/get-started/locally/>. Check the maximum CUDA version your driver supports with `nvidia-smi` (top-right), and pick a matching build. For example, for a driver supporting CUDA 12.x:

```bash
pip install torch --index-url https://download.pytorch.org/whl/cu126
pip install "choicellm[local]"
```

**AMD GPUs (ROCm)** need PyTorch's ROCm build, from its own package index (pick the one matching your ROCm version on the selector page; `rocm7.2` below). `pip install choicellm` alone gets the NVIDIA build from PyPI, so install torch first:

```bash
pip install torch --index-url https://download.pytorch.org/whl/rocm7.2
pip install "choicellm[local]"
```

If you already installed `choicellm` (and with it the wrong torch), install the ROCm build over it (`--force-reinstall`, because pip would otherwise keep a torch of the same version; `--no-deps` leaves the rest alone):

```bash
pip install torch --index-url https://download.pytorch.org/whl/rocm7.2 --force-reinstall --no-deps
# or, if you installed choicellm with pipx:
pipx inject choicellm torch --index-url https://download.pytorch.org/whl/rocm7.2 --pip-args="--force-reinstall --no-deps"
```

(Python packages can't specify from which index a dependency comes, so this can't be automated in `choicellm`'s dependencies.)

You can confirm PyTorch sees the GPU with the following (for ROCm, `torch.version.hip` is set and `cuda.is_available()` is `True` too):

```bash
python -c "import torch; print(torch.cuda.is_available(), torch.version.cuda, torch.version.hip)"
```

(This only matters for local models; the OpenAI-compatible API backends don't use your local GPU.)

### Local transformers or llama.cpp?

- **Local transformers** (`[local]`) runs Huggingface models at full precision: about 2 bytes per parameter in bf16 (an 8B model needs ~16 GB). `choicellm` batches the items itself, and in float32 batched results equal unbatched ones exactly. Quantized formats (bitsandbytes, GPTQ, AWQ) work best on NVIDIA GPUs; support on AMD is patchy.
- **llama.cpp** (via `--base-url`) runs quantized GGUF models (Q8 about 1 byte per parameter, Q4 about 0.6) on NVIDIA, AMD (ROCm or Vulkan), Apple and CPUs: the practical choice for large models on limited memory or non-NVIDIA hardware. (Transformers can load GGUF files, but converts them to full size.)
- Results differ slightly between backends, quantizations, dtypes and batch sizes (rounding). For exactly reproducible numbers: float32 locally, or a single llama.cpp slot.

## First create a suitable prompt YAML file (`choicellm-template`)

When running `choicellm`, you need to provide it with a 'prompt template' file in YAML format, like `choicellm --prompt my_first_prompt.yaml`. 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).

To generate an example prompt template (which you can then modify to suit your needs), you can do, for instance:

```bash
choicellm-template --scalar > my_first_prompt.yaml
```

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.)

When modifying a prompt, the parts in curly braces, like `{scale}`, will be replaced by the program, according to the information you provide. You may also omit such parts (by removing `{scale}`), for instance if you think they are unnecessary or you manually include the information in the prompt.

The generated templates start with some explanatory comments. Templates are YAML (JSON files are read too). To convert an older `.json` prompt to YAML, or to combine several scalar `.json` prompts, one per category, into a single multi-label prompt set (see below): `choicellm-json-to-yaml old.json > new.yaml`, or `choicellm-json-to-yaml advice.json interest.json ... > prompt_set.yaml`.

## Basic usage

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:

```bash
choicellm items.txt --prompt my_first_prompt.yaml
```

Results are printed to the command-line. To save them, use `-o` (this also writes `results.csv.meta.json`, recording the settings, seed, versions and timing). Progress (items per second, time remaining) is shown every 5 minutes:

```bash
choicellm items.txt --prompt my_first_prompt.yaml -o results.csv
```

If a long run is interrupted, `--resume` continues it, skipping the items already in `results.csv`:

```bash
choicellm items.txt --prompt my_first_prompt.yaml -o results.csv --resume
```

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.

```bash
choicellm items.txt --model 'unsloth/llama-3-70b-bnb-4bit' --prompt my_first_prompt.yaml -o results.csv
```

To use a proprietary OpenAI model, first, you need to set the `OPENAI_API_KEY` environment variable to your secret key:

```bash
export OPENAI_API_KEY=yoursecretkey123
```

Then you can specify an OpenAI model (and include the `--openai` flag):

```bash
choicellm items.txt --model 'gpt-4o' --openai --prompt my_first_prompt.yaml -o results.csv
```

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`.

### Other OpenAI-compatible servers (llama.cpp, vLLM, Ollama, ...)

Any OpenAI-compatible server works via the `--base-url` option. For example, with a local [llama.cpp](https://github.com/ggml-org/llama.cpp) server (`llama-server -m model.gguf --port 8080`):

```bash
choicellm items.txt --model 'my-model' --base-url http://localhost:8080/v1 --prompt my_first_prompt.yaml -o results.csv
```

(You can also set the `OPENAI_BASE_URL` environment variable instead of passing `--base-url` each time.) Passing `--base-url` implies API mode, so `--openai` is not needed. Chat-style prompt templates go through the chat API (with 'thinking' disabled, for models that support it); plain-text templates go through the `/completions` endpoint, which lets you use base models served by llama.cpp or vLLM.

`choicellm` needs the model's tokenizer, to know how the labels are tokenized. It finds it automatically: via `tiktoken` for OpenAI models, and via the server's `/tokenize` endpoint for llama.cpp and vLLM (so a model alias like `--model my-model` is fine). Otherwise, pass the matching Huggingface tokenizer, e.g. `--tokenizer meta-llama/Llama-3.1-8B-Instruct`.

**Concurrency.** `--batch-size N` sends up to N requests at once, which the server processes in parallel. The default is 8 for OpenAI, the number of slots + 2 for llama.cpp (set with `-np`), and 1 for other servers. A server can compute concurrent requests wrongly (llama.cpp's ROCm build on an AMD iGPU; `--kv-unified` with 16+ slots shifts many results slightly), so check each new server setup once: the same command as for a run, plus `--check-server` (150 requests; `--check-server N` for N), compares concurrent results with one-at-a-time ones and reports whether they match. `--do-spot-checks` additionally recomputes a few items one at a time during a run (early, then rarely) and continues one request at a time if they differ much; it only catches gross errors. To measure a server's speed: `tests/runs/throughput.py`.

For llama.cpp on an AMD iGPU, the Vulkan build gave correct concurrent results where ROCm did not. With several shared prompt starts (e.g. one per category), llama.cpp sends each request to a slot whose cache matches, or restores the prompt start from its RAM cache. `CHOICELLM_PIN_SLOTS=1` instead pins each prompt start to its own slot(s). That only helps with separate KV caches per slot (`--no-kv-unified`): 10-15% faster on an AMD iGPU, best with `--cache-ram 0` (which also saves memory when the GPU shares system memory with the model). With `--kv-unified` it gains nothing, and together with the RAM cache it makes llama.cpp recompute prompt starts for nearly every request. The run stats report how many prompt tokens came from the server's cache (`prompt_tokens_cached`).

On the whole, while `choicellm` is probably not entirely model-agnostic in some unforeseen ways, it should work with Huggingface models and OpenAI-compatible APIs. 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. Quantized (e.g. bitsandbytes 4/8-bit) models are loaded via `device_map`; for unquantized models you can pick a smaller dtype with `--dtype` (e.g. `--dtype bfloat16`) to save memory.

## A bit more info about the three 'modes': scalar, comparative, categorical

First, `--scalar` prompts ask the LLM to give ratings on a numerical scale. The `results.csv` file contains the items, with additional columns `pred` (the model's choice), `prob` (the probability of this choice), `rating` (the average over the scale, weighted by the model's probabilities), and `probs` (the probabilities of all choices, separated by semicolons; they sum to 1.0).

Labels may be any strings, also several tokens long (e.g. `10`, `-1`, or `very concrete`): a label's probability is the product of its tokens' probabilities, and a label that is a token-prefix of another (`1` vs `10`) only counts if the answer stops there. Whether a label follows the prompt with or without a space (`' 3'` vs `'3'`) is worked out from the tokenizer. To see how a tokenizer handles your labels, and how many forward passes or requests they take: `tests/runs/probe_tokenizers.py`.

Next, `--categorical` prompts classify items into categories. By default (`exclusive: true`) the categories are mutually exclusive: one prompt lists them all, and the category probabilities sum to one. If the template has no `"labels"`, the model answers with the category names themselves (e.g. `abstract`); with `"labels": ["A", "B", "C"]`, with letters. For this mode, the `results.csv` file contains `pred` (the 'chosen' category), `prob` (its probability) and `probs` (probabilities for all categories, separated by semicolons).

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. With `"labels": "options"` in the template, the model answers with the option itself rather than a letter. (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):

```bash
choicellm-aggregate results.csv --scale 1,5 > results_aggregated.csv
```

With `exclusive: false`, the categories are **not** mutually exclusive (multi-label): each category gets its own prompt, rated on `scale`, and `results.csv` has one row per item with a rating (and probabilities) per category. All categories go in one YAML file, a *prompt set*: shared settings, per category its own `system_prompt`/`prompt_format` if needed, and the few-shot examples listed once, each with its target value (0-1) per category (categories not listed: 0) and optionally `include-in: [...]` or `exclude-from: [...]`:

```yaml
mode: categorical
exclusive: false
scale: [1, 2, 3, 4, 5]
system_prompt: "Rate how much this reply shows {category} ({description}), from {scale_min} to {scale_max}."
prompt_format: "{n}. {item}\nRating:"
categories:
  advice: giving advice
  interest: {description: showing interest, prompt_format: "{n}. {item}\nShows interest? (rating)"}
examples:
  - {item: "Try a walk.", advice: 1}
  - {item: "How did it go?", interest: 1, exclude-from: advice}
```

Generate an example with `choicellm-template --categorical --multi`, or see `examples/empathy/` (7 categories of empathy in replies to personal stories, with sample replies). Each category costs one prompt per item; to spread categories over machines, run `--categories-subset advice` on one and `--categories-subset interest` on another (the outputs share `target_id`).

