Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- lm-evaluation-harness/.github/workflows/new_tasks.yml +71 -0
- lm-evaluation-harness/.github/workflows/publish.yml +97 -0
- lm-evaluation-harness/Qwen2.5-7B_eval.log +0 -0
- lm-evaluation-harness/docs/CONTRIBUTING.md +83 -0
- lm-evaluation-harness/docs/README.md +11 -0
- lm-evaluation-harness/docs/decontamination.md +76 -0
- lm-evaluation-harness/docs/interface.md +170 -0
- lm-evaluation-harness/docs/model_guide.md +192 -0
- lm-evaluation-harness/docs/new_task_guide.md +521 -0
- lm-evaluation-harness/docs/task_guide.md +335 -0
- lm-evaluation-harness/eval_base_qwen2_5_32b.log +0 -0
- lm-evaluation-harness/examples/lm-eval-overview.ipynb +1240 -0
- lm-evaluation-harness/examples/transformer-lens.py +59 -0
- lm-evaluation-harness/examples/visualize-wandb.ipynb +172 -0
- lm-evaluation-harness/examples/visualize-zeno.ipynb +115 -0
- lm-evaluation-harness/lm_eval/__init__.py +7 -0
- lm-evaluation-harness/lm_eval/__pycache__/evaluator.cpython-310.pyc +0 -0
- lm-evaluation-harness/lm_eval/__pycache__/evaluator.cpython-311.pyc +0 -0
- lm-evaluation-harness/lm_eval/__pycache__/evaluator_utils.cpython-311.pyc +0 -0
- lm-evaluation-harness/lm_eval/__pycache__/utils.cpython-310.pyc +0 -0
- lm-evaluation-harness/lm_eval/__pycache__/utils.cpython-311.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__init__.py +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/__init__.cpython-310.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/__init__.cpython-311.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/filter.cpython-311.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/group.cpython-310.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/group.cpython-311.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/instance.cpython-310.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/instance.cpython-311.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/metrics.cpython-310.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/metrics.cpython-311.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/model.cpython-310.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/model.cpython-311.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/registry.cpython-310.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/registry.cpython-311.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/samplers.cpython-310.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/samplers.cpython-311.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/task.cpython-310.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/__pycache__/task.cpython-311.pyc +0 -0
- lm-evaluation-harness/lm_eval/api/group.py +115 -0
- lm-evaluation-harness/lm_eval/api/instance.py +38 -0
- lm-evaluation-harness/lm_eval/api/metrics.py +578 -0
- lm-evaluation-harness/lm_eval/api/registry.py +196 -0
- lm-evaluation-harness/lm_eval/api/samplers.py +232 -0
- lm-evaluation-harness/lm_eval/api/task.py +1879 -0
- lm-evaluation-harness/lm_eval/caching/__init__.py +0 -0
- lm-evaluation-harness/lm_eval/caching/__pycache__/__init__.cpython-310.pyc +0 -0
- lm-evaluation-harness/lm_eval/caching/__pycache__/__init__.cpython-311.pyc +0 -0
- lm-evaluation-harness/lm_eval/caching/__pycache__/cache.cpython-310.pyc +0 -0
- lm-evaluation-harness/lm_eval/caching/__pycache__/cache.cpython-311.pyc +0 -0
lm-evaluation-harness/.github/workflows/new_tasks.yml
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Tasks Modified
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches:
|
| 6 |
+
- 'main'
|
| 7 |
+
pull_request:
|
| 8 |
+
branches:
|
| 9 |
+
- 'main'
|
| 10 |
+
workflow_dispatch:
|
| 11 |
+
# comment/edit out the above to stop/change the triggers
|
| 12 |
+
jobs:
|
| 13 |
+
changed_files:
|
| 14 |
+
runs-on: ubuntu-latest # windows-latest || macos-latest
|
| 15 |
+
timeout-minutes: 120
|
| 16 |
+
name: Scan for changed tasks
|
| 17 |
+
steps:
|
| 18 |
+
- name: checkout
|
| 19 |
+
uses: actions/checkout@v4
|
| 20 |
+
with:
|
| 21 |
+
fetch-depth: 2 # OR "2" -> To retrieve the preceding commit.
|
| 22 |
+
|
| 23 |
+
# Uses the tj-actions/changed-files action to check for changes.
|
| 24 |
+
# The `files_yaml` input optionally takes a yaml string to specify filters,
|
| 25 |
+
# and prepends the filter name to the standard output names.
|
| 26 |
+
- name: Check task folders
|
| 27 |
+
id: changed-tasks
|
| 28 |
+
uses: tj-actions/changed-files@v46.0.5
|
| 29 |
+
with:
|
| 30 |
+
# tasks checks the tasks folder and api checks the api folder for changes
|
| 31 |
+
files_yaml: |
|
| 32 |
+
tasks:
|
| 33 |
+
- lm_eval/tasks/**
|
| 34 |
+
api:
|
| 35 |
+
- lm_eval/api/**
|
| 36 |
+
write_output_files: true
|
| 37 |
+
|
| 38 |
+
# The next step is optional; the files are written to the workspace by default (above).
|
| 39 |
+
# so it's just for debugging
|
| 40 |
+
- name: Run Tests
|
| 41 |
+
if: steps.changed-tasks.outputs.tasks_any_modified == 'true' || steps.changed-tasks.outputs.api_any_modified == 'true'
|
| 42 |
+
run: |
|
| 43 |
+
echo .github/outputs/tasks_all_changed_and_modified_files.txt >> 'GITHUB_ENV'
|
| 44 |
+
echo "One or more test file(s) has changed."
|
| 45 |
+
echo "List of all the files that have changed: ${{ steps.changed-tasks.outputs.tasks_all_modified_files }}"
|
| 46 |
+
|
| 47 |
+
- name: Set up Python 3.9
|
| 48 |
+
if: steps.changed-tasks.outputs.tasks_any_modified == 'true' || steps.changed-tasks.outputs.api_any_modified == 'true'
|
| 49 |
+
uses: actions/setup-python@v5
|
| 50 |
+
with:
|
| 51 |
+
python-version: 3.9
|
| 52 |
+
cache: 'pip'
|
| 53 |
+
cache-dependency-path: setup.py
|
| 54 |
+
- name: Install dependencies
|
| 55 |
+
if: steps.changed-tasks.outputs.tasks_any_modified == 'true' || steps.changed-tasks.outputs.api_any_modified == 'true'
|
| 56 |
+
run: |
|
| 57 |
+
python -m pip install --upgrade pip
|
| 58 |
+
pip install -e '.[dev,ifeval]' --extra-index-url https://download.pytorch.org/whl/cpu
|
| 59 |
+
# Install optional git dependencies
|
| 60 |
+
# pip install bleurt@https://github.com/google-research/bleurt/archive/b610120347ef22b494b6d69b4316e303f5932516.zip#egg=bleurt
|
| 61 |
+
# if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
|
| 62 |
+
- name: Test with pytest
|
| 63 |
+
# if new tasks are added, run tests on them
|
| 64 |
+
if: steps.changed-tasks.outputs.tasks_any_modified == 'true'
|
| 65 |
+
run: python -m pytest tests/test_tasks.py -s -vv
|
| 66 |
+
# if api is modified, run tests on it
|
| 67 |
+
- name: Test more tasks with pytest
|
| 68 |
+
env:
|
| 69 |
+
API: true
|
| 70 |
+
if: steps.changed-tasks.outputs.api_any_modified == 'true'
|
| 71 |
+
run: python -m pytest tests/test_tasks.py -s -vv
|
lm-evaluation-harness/.github/workflows/publish.yml
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Publish Python distribution to PyPI
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
tags:
|
| 6 |
+
- '*'
|
| 7 |
+
|
| 8 |
+
jobs:
|
| 9 |
+
build:
|
| 10 |
+
name: Build distribution
|
| 11 |
+
runs-on: ubuntu-latest
|
| 12 |
+
|
| 13 |
+
steps:
|
| 14 |
+
- uses: actions/checkout@v4
|
| 15 |
+
- name: Set up Python
|
| 16 |
+
uses: actions/setup-python@v5
|
| 17 |
+
with:
|
| 18 |
+
python-version: "3.x"
|
| 19 |
+
|
| 20 |
+
- name: Check version consistency
|
| 21 |
+
run: |
|
| 22 |
+
# Extract version from pyproject.toml
|
| 23 |
+
PYPROJECT_VERSION=$(grep 'version = ' pyproject.toml | head -1 | cut -d'"' -f2)
|
| 24 |
+
|
| 25 |
+
# Extract version from __init__.py
|
| 26 |
+
INIT_VERSION=$(grep '__version__ = ' lm_eval/__init__.py | head -1 | cut -d'"' -f2)
|
| 27 |
+
|
| 28 |
+
echo "Version in pyproject.toml: $PYPROJECT_VERSION"
|
| 29 |
+
echo "Version in __init__.py: $INIT_VERSION"
|
| 30 |
+
|
| 31 |
+
# Check if versions match
|
| 32 |
+
if [ "$PYPROJECT_VERSION" != "$INIT_VERSION" ]; then
|
| 33 |
+
echo "Error: Version mismatch between pyproject.toml ($PYPROJECT_VERSION) and __init__.py ($INIT_VERSION)"
|
| 34 |
+
exit 1
|
| 35 |
+
fi
|
| 36 |
+
|
| 37 |
+
echo "Version check passed: $PYPROJECT_VERSION"
|
| 38 |
+
|
| 39 |
+
- name: Install pypa/build
|
| 40 |
+
run: >-
|
| 41 |
+
python3 -m
|
| 42 |
+
pip install
|
| 43 |
+
build
|
| 44 |
+
--user
|
| 45 |
+
- name: Build a binary wheel and a source tarball
|
| 46 |
+
run: python3 -m build
|
| 47 |
+
- name: Store the distribution packages
|
| 48 |
+
uses: actions/upload-artifact@v4
|
| 49 |
+
with:
|
| 50 |
+
name: python-package-distributions
|
| 51 |
+
path: dist/
|
| 52 |
+
|
| 53 |
+
publish-to-pypi:
|
| 54 |
+
name: >-
|
| 55 |
+
Publish Python distribution to PyPI
|
| 56 |
+
if: startsWith(github.ref, 'refs/tags/') # only publish to PyPI on tag pushes
|
| 57 |
+
needs:
|
| 58 |
+
- build
|
| 59 |
+
runs-on: ubuntu-latest
|
| 60 |
+
environment:
|
| 61 |
+
name: pypi
|
| 62 |
+
url: https://pypi.org/p/lm_eval
|
| 63 |
+
permissions:
|
| 64 |
+
id-token: write # IMPORTANT: mandatory for trusted publishing
|
| 65 |
+
|
| 66 |
+
steps:
|
| 67 |
+
- name: Download all the dists
|
| 68 |
+
uses: actions/download-artifact@v4
|
| 69 |
+
with:
|
| 70 |
+
name: python-package-distributions
|
| 71 |
+
path: dist/
|
| 72 |
+
- name: Publish distribution to PyPI
|
| 73 |
+
uses: pypa/gh-action-pypi-publish@release/v1
|
| 74 |
+
|
| 75 |
+
publish-to-testpypi:
|
| 76 |
+
name: Publish Python distribution to TestPyPI
|
| 77 |
+
needs:
|
| 78 |
+
- build
|
| 79 |
+
runs-on: ubuntu-latest
|
| 80 |
+
|
| 81 |
+
environment:
|
| 82 |
+
name: testpypi
|
| 83 |
+
url: https://test.pypi.org/p/lm_eval
|
| 84 |
+
|
| 85 |
+
permissions:
|
| 86 |
+
id-token: write # IMPORTANT: mandatory for trusted publishing
|
| 87 |
+
|
| 88 |
+
steps:
|
| 89 |
+
- name: Download all the dists
|
| 90 |
+
uses: actions/download-artifact@v4
|
| 91 |
+
with:
|
| 92 |
+
name: python-package-distributions
|
| 93 |
+
path: dist/
|
| 94 |
+
- name: Publish distribution to TestPyPI
|
| 95 |
+
uses: pypa/gh-action-pypi-publish@release/v1
|
| 96 |
+
with:
|
| 97 |
+
repository-url: https://test.pypi.org/legacy/
|
lm-evaluation-harness/Qwen2.5-7B_eval.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
lm-evaluation-harness/docs/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contributing to LM Evaluation Harness
|
| 2 |
+
|
| 3 |
+
Welcome and thank you for your interest in the LM Evaluation Harness! We welcome contributions and feedback and appreciate your time spent with our library, and hope you find it useful!
|
| 4 |
+
|
| 5 |
+
## Important Resources
|
| 6 |
+
|
| 7 |
+
There are several places information about LM Evaluation Harness is located:
|
| 8 |
+
|
| 9 |
+
- Our [documentation pages](https://github.com/EleutherAI/lm-evaluation-harness/tree/main/docs)
|
| 10 |
+
- We occasionally use [GitHub Milestones](https://github.com/EleutherAI/lm-evaluation-harness/milestones) to track progress toward specific near-term version releases.
|
| 11 |
+
- We maintain a [Project Board](https://github.com/orgs/EleutherAI/projects/25) for tracking current work items and PRs, and for future roadmap items or feature requests.
|
| 12 |
+
- Further discussion and support conversations are located in the #lm-thunderdome channel of the [EleutherAI discord](https://discord.gg/eleutherai).
|
| 13 |
+
|
| 14 |
+
## Code Style
|
| 15 |
+
|
| 16 |
+
LM Evaluation Harness uses [ruff](https://github.com/astral-sh/ruff) for linting via [pre-commit](https://pre-commit.com/).
|
| 17 |
+
|
| 18 |
+
You can install linters and dev tools via
|
| 19 |
+
|
| 20 |
+
```pip install lm_eval[dev]``` or ```pip install -e ".[dev]"```
|
| 21 |
+
|
| 22 |
+
Then, run
|
| 23 |
+
|
| 24 |
+
```pre-commit install```
|
| 25 |
+
|
| 26 |
+
in order to ensure linters and other checks will be run upon committing.
|
| 27 |
+
|
| 28 |
+
## Testing
|
| 29 |
+
|
| 30 |
+
We use [pytest](https://docs.pytest.org/en/latest/) for running unit tests. All library unit tests can be run via:
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
python -m pytest --showlocals -s -vv -n=auto --ignore=tests/models/test_neuralmagic.py --ignore=tests/models/test_openvino.py
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
## Contributor License Agreement
|
| 37 |
+
|
| 38 |
+
We ask that new contributors agree to a Contributor License Agreement affirming that EleutherAI has the rights to use your contribution to our library.
|
| 39 |
+
First-time pull requests will have a reply added by @CLAassistant containing instructions for how to confirm this, and we require it before merging your PR.
|
| 40 |
+
|
| 41 |
+
## Contribution Best Practices
|
| 42 |
+
|
| 43 |
+
We recommend a few best practices to make your contributions or reported errors easier to assist with.
|
| 44 |
+
|
| 45 |
+
**For Pull Requests:**
|
| 46 |
+
|
| 47 |
+
- PRs should be titled descriptively, and be opened with a brief description of the scope and intent of the new contribution.
|
| 48 |
+
- New features should have appropriate documentation added alongside them.
|
| 49 |
+
- Aim for code maintainability, and minimize code copying.
|
| 50 |
+
- If opening a task, try to share test results on the task using a publicly-available model, and if any public results are available on the task, compare to them.
|
| 51 |
+
|
| 52 |
+
**For Feature Requests:**
|
| 53 |
+
|
| 54 |
+
- Provide a short paragraph's worth of description. What is the feature you are requesting? What is its motivation, and an example use case of it? How does this differ from what is currently supported?
|
| 55 |
+
|
| 56 |
+
**For Bug Reports**:
|
| 57 |
+
|
| 58 |
+
- Provide a short description of the bug.
|
| 59 |
+
- Provide a *reproducible example*--what is the command you run with our library that results in this error? Have you tried any other steps to resolve it?
|
| 60 |
+
- Provide a *full error traceback* of the error that occurs, if applicable. A one-line error message or small screenshot snippet is unhelpful without the surrounding context.
|
| 61 |
+
- Note what version of the codebase you are using, and any specifics of your environment and setup that may be relevant.
|
| 62 |
+
|
| 63 |
+
**For Requesting New Tasks**:
|
| 64 |
+
|
| 65 |
+
- Provide a 1-2 sentence description of what the task is and what it evaluates.
|
| 66 |
+
- Provide a link to the paper introducing the task.
|
| 67 |
+
- Provide a link to where the dataset can be found.
|
| 68 |
+
- Provide a link to a paper containing results on an open-source model on the task, for use in comparisons and implementation validation.
|
| 69 |
+
- If applicable, link to any codebase that has implemented the task (especially the original publication's codebase, if existent).
|
| 70 |
+
|
| 71 |
+
## How Can I Get Involved?
|
| 72 |
+
|
| 73 |
+
To quickly get started, we maintain a list of good first issues, which can be found [on our project board](https://github.com/orgs/EleutherAI/projects/25/views/8) or by [filtering GH Issues](https://github.com/EleutherAI/lm-evaluation-harness/issues?q=is%3Aopen+label%3A%22good+first+issue%22+label%3A%22help+wanted%22). These are typically smaller code changes or self-contained features which can be added without extensive familiarity with library internals, and we recommend new contributors consider taking a stab at one of these first if they are feeling uncertain where to begin.
|
| 74 |
+
|
| 75 |
+
There are a number of distinct ways to contribute to LM Evaluation Harness, and all are extremely helpful! A sampling of ways to contribute include:
|
| 76 |
+
|
| 77 |
+
- **Implementing and verifying new evaluation tasks**: Is there a task you'd like to see LM Evaluation Harness support? Consider opening an issue requesting it, or helping add it! Verifying and cross-checking task implementations with their original versions is also a very valuable form of assistance in ensuring standardized evaluation.
|
| 78 |
+
- **Improving documentation** - Improvements to the documentation, or noting pain points / gaps in documentation, are helpful in order for us to improve the user experience of the library and clarity + coverage of documentation.
|
| 79 |
+
- **Testing and devops** - We are very grateful for any assistance in adding tests for the library that can be run for new PRs, and other devops workflows.
|
| 80 |
+
- **Adding new modeling / inference library integrations** - We hope to support a broad range of commonly-used inference libraries popular among the community, and welcome PRs for new integrations, so long as they are documented properly and maintainable.
|
| 81 |
+
- **Proposing or Contributing New Features** - We want LM Evaluation Harness to support a broad range of evaluation usecases. If you have a feature that is not currently supported but desired, feel free to open an issue describing the feature and, if applicable, how you intend to implement it. We would be happy to give feedback on the cleanest way to implement new functionalities and are happy to coordinate with interested contributors via GH discussions or via discord.
|
| 82 |
+
|
| 83 |
+
We hope that this has been helpful, and appreciate your interest in contributing! Further questions can be directed to [our Discord](discord.gg/eleutherai).
|
lm-evaluation-harness/docs/README.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Eval Harness Documentation
|
| 2 |
+
|
| 3 |
+
Welcome to the docs for the LM Evaluation Harness!
|
| 4 |
+
|
| 5 |
+
## Table of Contents
|
| 6 |
+
|
| 7 |
+
* To learn about the public interface of the library, as well as how to evaluate via the command line or as integrated into an external library, see the [Interface](./interface.md).
|
| 8 |
+
* To learn how to add a new library, API, or model type to the library, as well as a quick explainer on the types of ways to evaluate an LM, see the [Model Guide](./model_guide.md).
|
| 9 |
+
* For an extended description of how to extend the library to new model classes served over an API, see the [API Guide](./API_guide.md).
|
| 10 |
+
* For a crash course on adding new tasks to the library, see our [New Task Guide](./new_task_guide.md).
|
| 11 |
+
* To learn more about pushing the limits of task configuration that the Eval Harness supports, see the [Task Configuration Guide](./task_guide.md).
|
lm-evaluation-harness/docs/decontamination.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Decontamination
|
| 2 |
+
|
| 3 |
+
## Usage
|
| 4 |
+
|
| 5 |
+
The provided directory should contain
|
| 6 |
+
the ngram files and info.json produced in "Pile Ngram Generation" further down.
|
| 7 |
+
|
| 8 |
+
```bash
|
| 9 |
+
python -m lm_eval \
|
| 10 |
+
--model gpt2 \
|
| 11 |
+
--device 0 \
|
| 12 |
+
--tasks sciq
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
## Background
|
| 16 |
+
|
| 17 |
+
Downstream evaluations test model generalization, and are less useful when test set data also exists in the training set, referred to as leakage or contamination.
|
| 18 |
+
|
| 19 |
+
Filtering your training set against the test set is a good first step, however this isn't always possible, as in the case of a new benchmark or one that wasn't considered prior to model training. When training set filtering isn't possible, it is useful to measure the impact of test set leakage by detecting the contaminated test examples and producing a clean version of the benchmark.
|
| 20 |
+
|
| 21 |
+
The basis for our decontamination procedure can be found in Appendix C of "Language Models are Few-Shot Learners". OpenAI defined a test document as contaminated if any N-gram overlap existed with any training document. They used a range of N values between 8 and 13 depending on dataset, while we just used 13 for simplicity.
|
| 22 |
+
|
| 23 |
+
## Implementation
|
| 24 |
+
|
| 25 |
+
Contamination detection can be found in `lm_eval/decontaminate.py` with supporting code in `lm_eval/decontamination/`.
|
| 26 |
+
|
| 27 |
+
decontaminate.py does the following:
|
| 28 |
+
|
| 29 |
+
1. Build dictionaries of all ngrams and their corresponding evaluation/document ids.
|
| 30 |
+
2. Scan through sorted files containing training set n-grams.
|
| 31 |
+
3. If a match is found, the corresponding evaluation/document combinations are marked as contaminated.
|
| 32 |
+
|
| 33 |
+
`lm_eval/evaluator.py` can then produce a clean version of the benchmark by excluding the results of contaminated documents. For each metric, a clean version will be shown in the results with a "decontaminate" suffix.
|
| 34 |
+
|
| 35 |
+
This is disabled by default for new tasks, to support decontamination on a task override the "should_decontaminate" and "doc_to_decontamination_query" methods. For more details see the [task guide](task_guide.md).
|
| 36 |
+
|
| 37 |
+
## Pile Ngram Generation
|
| 38 |
+
|
| 39 |
+
The relevant scripts can be found in `scripts/clean_training_data`, which also import from
|
| 40 |
+
`lm_eval/decontamination/`
|
| 41 |
+
|
| 42 |
+
1. git clone https://github.com/EleutherAI/lm-evaluation-harness.git
|
| 43 |
+
2. pip install -r requirements.txt
|
| 44 |
+
3. Download The Pile from [The Eye](https://the-eye.eu/public/AI/pile/train/)
|
| 45 |
+
4. Place pile files in "pile" directory under "lm-evaluation-harness" (or create a symlink)
|
| 46 |
+
5. Run generate_13_grams.
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
export PYTHONHASHSEED=0
|
| 50 |
+
python -m scripts/clean_training_data/generate_13_grams \
|
| 51 |
+
-dir path/to/working/directory \
|
| 52 |
+
-n 13 \
|
| 53 |
+
-buckets 500
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
Took approximately 4 days for us. We had the time to wait, but this could be scaled out by doing partial pile scans on multiple instances of this script and merging the relevant buckets. We fixed PYTHONHASHSEED to ensure reproducibility of bucket hashing in case you need to stop and start.
|
| 57 |
+
|
| 58 |
+
6. Sort the generated 13-grams.
|
| 59 |
+
|
| 60 |
+
```bash
|
| 61 |
+
python -m scripts/clean_training_data/sort_13_gram_buckets \
|
| 62 |
+
-dir path/to/working/directory/output
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
Took approximately 5 days for us. You could speed this up by spreading the files around to different machines and running the sort script before gathering them together.
|
| 66 |
+
|
| 67 |
+
7. Compress the sorted 13 grams files and place them together with info.json.
|
| 68 |
+
|
| 69 |
+
This step only takes a few hours.
|
| 70 |
+
|
| 71 |
+
```bash
|
| 72 |
+
python -m scripts/clean_training_data/compress_and_package \
|
| 73 |
+
-dir path/to/working/directory \
|
| 74 |
+
-output path/to/final/directory \
|
| 75 |
+
-procs 8
|
| 76 |
+
```
|
lm-evaluation-harness/docs/interface.md
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
## Command-line Interface
|
| 6 |
+
|
| 7 |
+
A majority of users run the library by cloning it from Github, installing the package as editable, and running the `python -m lm_eval` script.
|
| 8 |
+
|
| 9 |
+
Equivalently, running the library can be done via the `lm-eval` entrypoint at the command line.
|
| 10 |
+
|
| 11 |
+
This mode supports a number of command-line arguments, the details of which can also be seen via running with `-h` or `--help`:
|
| 12 |
+
|
| 13 |
+
- `--model` : Selects which model type or provider is evaluated. Must be a string corresponding to the name of the model type/provider being used. See [the main README](https://github.com/EleutherAI/lm-evaluation-harness/tree/main#model-apis-and-inference-servers) for a full list of enabled model names and supported libraries or APIs.
|
| 14 |
+
|
| 15 |
+
- `--model_args` : Controls parameters passed to the model constructor. Accepts a string containing comma-separated keyword arguments to the model class of the format `"arg1=val1,arg2=val2,..."`, such as, for example `--model_args pretrained=EleutherAI/pythia-160m,dtype=float32`. For a full list of what keyword arguments, see the initialization of the `lm_eval.api.model.LM` subclass, e.g. [`HFLM`](https://github.com/EleutherAI/lm-evaluation-harness/blob/365fcda9b85bbb6e0572d91976b8daf409164500/lm_eval/models/huggingface.py#L66)
|
| 16 |
+
|
| 17 |
+
- `--tasks` : Determines which tasks or task groups are evaluated. Accepts a comma-separated list of task names or task group names. Must be solely comprised of valid tasks/groups. A list of supported tasks can be viewed with `--tasks list`.
|
| 18 |
+
|
| 19 |
+
- `--num_fewshot` : Sets the number of few-shot examples to place in context. Must be an integer.
|
| 20 |
+
|
| 21 |
+
- `--gen_kwargs` : takes an arg string in same format as `--model_args` and creates a dictionary of keyword arguments. These will be passed to the models for all called `generate_until` (free-form or greedy generation task) tasks, to set options such as the sampling temperature or `top_p` / `top_k`. For a list of what args are supported for each model type, reference the respective library's documentation (for example, the documentation for `transformers.AutoModelForCausalLM.generate()`.) These kwargs will be applied to all `generate_until` tasks called--we do not currently support unique gen_kwargs or batch_size values per task in a single run of the library. To control these on a per-task level, set them in that task's YAML file.
|
| 22 |
+
|
| 23 |
+
- `--batch_size` : Sets the batch size used for evaluation. Can be a positive integer or `"auto"` to automatically select the largest batch size that will fit in memory, speeding up evaluation. One can pass `--batch_size auto:N` to re-select the maximum batch size `N` times during evaluation. This can help accelerate evaluation further, since `lm-eval` sorts documents in descending order of context length.
|
| 24 |
+
|
| 25 |
+
- `--max_batch_size` : Sets the maximum batch size to try to fit in memory, if `--batch_size auto` is passed.
|
| 26 |
+
|
| 27 |
+
- `--device` : Sets which device to place the model onto. Must be a string, for example, `"cuda", "cuda:0", "cpu", "mps"`. Defaults to "cuda", and can be ignored if running multi-GPU or running a non-local model type.
|
| 28 |
+
|
| 29 |
+
- `--output_path` : A string of the form `dir/file.jsonl` or `dir/`. Provides a path where high-level results will be saved, either into the file named or into the directory named. If `--log_samples` is passed as well, then per-document outputs and metrics will be saved into the directory as well.
|
| 30 |
+
|
| 31 |
+
- `--log_samples` : If this flag is passed, then the model's outputs, and the text fed into the model, will be saved at per-document granularity. Must be used with `--output_path`.
|
| 32 |
+
|
| 33 |
+
- `--limit` : Accepts an integer, or a float between 0.0 and 1.0 . If passed, will limit the number of documents to evaluate to the first X documents (if an integer) per task or first X% of documents per task. Useful for debugging, especially on costly API models.
|
| 34 |
+
|
| 35 |
+
- `--use_cache` : Should be a path where a sqlite db file can be written to. Takes a string of format `/path/to/sqlite_cache_` in order to create a cache db at `/path/to/sqlite_cache_rank{i}.db` for each process (0-NUM_GPUS). This allows results of prior runs to be cached, so that there is no need to re-run results in order to re-score or re-run a given (model, task) pair again.
|
| 36 |
+
|
| 37 |
+
- `--cache_requests` : Can be "true", "refresh", or "delete". "true" means that the cache should be used. "refresh" means that you wish to regenerate the cache, which you should run if you change your dataset configuration for a given task. "delete" will delete the cache. Cached files are stored under lm_eval/cache/.cache unless you specify a different path via the environment variable: `LM_HARNESS_CACHE_PATH`. e.g. `LM_HARNESS_CACHE_PATH=~/Documents/cache_for_lm_harness`.
|
| 38 |
+
|
| 39 |
+
- `--check_integrity` : If this flag is used, the library tests for each task selected are run to confirm task integrity.
|
| 40 |
+
|
| 41 |
+
- `--write_out` : Used for diagnostic purposes to observe the format of task documents passed to a model. If this flag is used, then prints the prompt and gold target string for the first document of each task.
|
| 42 |
+
|
| 43 |
+
- `--show_config` : If used, prints the full `lm_eval.api.task.TaskConfig` contents (non-default settings the task YAML file) for each task which was run, at the completion of an evaluation. Useful for when one is modifying a task's configuration YAML locally to transmit the exact configurations used for debugging or for reproducibility purposes.
|
| 44 |
+
|
| 45 |
+
- `--include_path` : Accepts a path to a folder. If passed, then all YAML files containing `lm-eval` compatible task configurations will be added to the task registry as available tasks. Used for when one is writing config files for their own task in a folder other than `lm_eval/tasks/`.
|
| 46 |
+
|
| 47 |
+
- `--system_instruction`: Specifies a system instruction string to prepend to the prompt.
|
| 48 |
+
|
| 49 |
+
- `--apply_chat_template` : This flag specifies whether to apply a chat template to the prompt. It can be used in the following ways:
|
| 50 |
+
- `--apply_chat_template` : When used without an argument, applies the only available chat template to the prompt. For Hugging Face models, if no dedicated chat template exists, the default chat template will be applied.
|
| 51 |
+
- `--apply_chat_template template_name` : If the model has multiple chat templates, apply the specified template to the prompt.
|
| 52 |
+
|
| 53 |
+
For Hugging Face models, the default chat template can be found in the [`default_chat_template`](https://github.com/huggingface/transformers/blob/fc35907f95459d7a6c5281dfadd680b6f7b620e3/src/transformers/tokenization_utils_base.py#L1912) property of the Transformers Tokenizer.
|
| 54 |
+
|
| 55 |
+
- `--fewshot_as_multiturn` : If this flag is on, the Fewshot examples are treated as a multi-turn conversation. Questions are provided as user content and answers are provided as assistant responses. Requires `--num_fewshot` to be set to be greater than 0, and `--apply_chat_template` to be on.
|
| 56 |
+
|
| 57 |
+
- `--predict_only`: Generates the model outputs without computing metrics. Use with `--log_samples` to retrieve decoded results.
|
| 58 |
+
|
| 59 |
+
- `--seed`: Set seed for python's random, numpy and torch. Accepts a comma-separated list of 3 values for python's random, numpy, and torch seeds, respectively, or a single integer to set the same seed for all three. The values are either an integer or 'None' to not set the seed. Default is `0,1234,1234` (for backward compatibility). E.g. `--seed 0,None,8` sets `random.seed(0)` and `torch.manual_seed(8)`. Here numpy's seed is not set since the second value is `None`. E.g, `--seed 42` sets all three seeds to 42.
|
| 60 |
+
|
| 61 |
+
- `--wandb_args`: Tracks logging to Weights and Biases for evaluation runs and includes args passed to `wandb.init`, such as `project` and `job_type`. Full list [here](https://docs.wandb.ai/ref/python/init). e.g., ```--wandb_args project=test-project,name=test-run```. Also allows for the passing of the step to log things at (passed to `wandb.run.log`), e.g., `--wandb_args step=123`.
|
| 62 |
+
|
| 63 |
+
- `--hf_hub_log_args` : Logs evaluation results to Hugging Face Hub. Accepts a string with the arguments separated by commas. Available arguments:
|
| 64 |
+
- `hub_results_org` - organization name on Hugging Face Hub, e.g., `EleutherAI`. If not provided, the results will be pushed to the owner of the Hugging Face token,
|
| 65 |
+
- `hub_repo_name` - repository name on Hugging Face Hub (deprecated, `details_repo_name` and `results_repo_name` should be used instead), e.g., `lm-eval-results`,
|
| 66 |
+
- `details_repo_name` - repository name on Hugging Face Hub to store details, e.g., `lm-eval-results`,
|
| 67 |
+
- `results_repo_name` - repository name on Hugging Face Hub to store results, e.g., `lm-eval-results`,
|
| 68 |
+
- `push_results_to_hub` - whether to push results to Hugging Face Hub, can be `True` or `False`,
|
| 69 |
+
- `push_samples_to_hub` - whether to push samples results to Hugging Face Hub, can be `True` or `False`. Requires `--log_samples` to be set,
|
| 70 |
+
- `public_repo` - whether the repository is public, can be `True` or `False`,
|
| 71 |
+
- `leaderboard_url` - URL to the leaderboard, e.g., `https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard`.
|
| 72 |
+
- `point_of_contact` - Point of contact for the results dataset, e.g., `yourname@example.com`.
|
| 73 |
+
- `gated` - whether to gate the details dataset, can be `True` or `False`.
|
| 74 |
+
|
| 75 |
+
- `--metadata`: JSON string to pass to TaskConfig. Used for some tasks which require additional metadata to be passed for processing. E.g., `--metadata '{"key": "value"}'`.
|
| 76 |
+
|
| 77 |
+
## External Library Usage
|
| 78 |
+
|
| 79 |
+
We also support using the library's external API for use within model training loops or other scripts.
|
| 80 |
+
|
| 81 |
+
`lm_eval` supplies two functions for external import and use: `lm_eval.evaluate()` and `lm_eval.simple_evaluate()`.
|
| 82 |
+
|
| 83 |
+
`simple_evaluate()` can be used by simply creating an `lm_eval.api.model.LM` subclass that implements the methods described in the [Model Guide](https://github.com/EleutherAI/lm-evaluation-harness/tree/main/docs/model_guide.md), and wrapping your custom model in that class as follows:
|
| 84 |
+
|
| 85 |
+
```python
|
| 86 |
+
import lm_eval
|
| 87 |
+
from lm_eval.utils import setup_logging
|
| 88 |
+
...
|
| 89 |
+
# initialize logging
|
| 90 |
+
setup_logging("DEBUG") # optional, but recommended; or you can set up logging yourself
|
| 91 |
+
my_model = initialize_my_model() # create your model (could be running finetuning with some custom modeling code)
|
| 92 |
+
...
|
| 93 |
+
# instantiate an LM subclass that takes your initialized model and can run
|
| 94 |
+
# - `Your_LM.loglikelihood()`
|
| 95 |
+
# - `Your_LM.loglikelihood_rolling()`
|
| 96 |
+
# - `Your_LM.generate_until()`
|
| 97 |
+
lm_obj = Your_LM(model=my_model, batch_size=16)
|
| 98 |
+
|
| 99 |
+
# indexes all tasks from the `lm_eval/tasks` subdirectory.
|
| 100 |
+
# Alternatively, you can set `TaskManager(include_path="path/to/my/custom/task/configs")`
|
| 101 |
+
# to include a set of tasks in a separate directory.
|
| 102 |
+
task_manager = lm_eval.tasks.TaskManager()
|
| 103 |
+
|
| 104 |
+
# Setting `task_manager` to the one above is optional and should generally be done
|
| 105 |
+
# if you want to include tasks from paths other than ones in `lm_eval/tasks`.
|
| 106 |
+
# `simple_evaluate` will instantiate its own task_manager if it is set to None here.
|
| 107 |
+
results = lm_eval.simple_evaluate( # call simple_evaluate
|
| 108 |
+
model=lm_obj,
|
| 109 |
+
tasks=["taskname1", "taskname2"],
|
| 110 |
+
num_fewshot=0,
|
| 111 |
+
task_manager=task_manager,
|
| 112 |
+
...
|
| 113 |
+
)
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
See the `simple_evaluate()` and `evaluate()` functions in [lm_eval/evaluator.py](../lm_eval/evaluator.py#:~:text=simple_evaluate) for a full description of all arguments available. All keyword arguments to simple_evaluate share the same role as the command-line flags described previously.
|
| 117 |
+
|
| 118 |
+
Additionally, the `evaluate()` function offers the core evaluation functionality provided by the library, but without some of the special handling and simplification + abstraction provided by `simple_evaluate()`.
|
| 119 |
+
|
| 120 |
+
As a brief example usage of `evaluate()`:
|
| 121 |
+
|
| 122 |
+
```python
|
| 123 |
+
import lm_eval
|
| 124 |
+
|
| 125 |
+
# suppose you've defined a custom lm_eval.api.Task subclass in your own external codebase
|
| 126 |
+
from my_tasks import MyTask1
|
| 127 |
+
...
|
| 128 |
+
|
| 129 |
+
# create your model (could be running finetuning with some custom modeling code)
|
| 130 |
+
my_model = initialize_my_model()
|
| 131 |
+
...
|
| 132 |
+
|
| 133 |
+
# instantiate an LM subclass that takes your initialized model and can run
|
| 134 |
+
# - `Your_LM.loglikelihood()`
|
| 135 |
+
# - `Your_LM.loglikelihood_rolling()`
|
| 136 |
+
# - `Your_LM.generate_until()`
|
| 137 |
+
lm_obj = Your_LM(model=my_model, batch_size=16)
|
| 138 |
+
|
| 139 |
+
# optional: the task_manager indexes tasks including ones
|
| 140 |
+
# specified by the user through `include_path`.
|
| 141 |
+
task_manager = lm_eval.tasks.TaskManager(
|
| 142 |
+
include_path="/path/to/custom/yaml"
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
# To get a task dict for `evaluate`
|
| 146 |
+
task_dict = lm_eval.tasks.get_task_dict(
|
| 147 |
+
[
|
| 148 |
+
"mmlu", # A stock task
|
| 149 |
+
"my_custom_task", # A custom task
|
| 150 |
+
{
|
| 151 |
+
"task": ..., # A dict that configures a task
|
| 152 |
+
"doc_to_text": ...,
|
| 153 |
+
},
|
| 154 |
+
MyTask1 # A task object from `lm_eval.task.Task`
|
| 155 |
+
],
|
| 156 |
+
task_manager # A task manager that allows lm_eval to
|
| 157 |
+
# load the task during evaluation.
|
| 158 |
+
# If none is provided, `get_task_dict`
|
| 159 |
+
# will instantiate one itself, but this
|
| 160 |
+
# only includes the stock tasks so users
|
| 161 |
+
# will need to set this if including
|
| 162 |
+
# custom paths is required.
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
results = evaluate(
|
| 166 |
+
lm=lm_obj,
|
| 167 |
+
task_dict=task_dict,
|
| 168 |
+
...
|
| 169 |
+
)
|
| 170 |
+
```
|
lm-evaluation-harness/docs/model_guide.md
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# New Model Guide
|
| 2 |
+
|
| 3 |
+
This guide may be of special interest to users who are using the library outside of the repository, via installing the library via pypi and calling `lm_eval.evaluator.evaluate()` to evaluate an existing model.
|
| 4 |
+
|
| 5 |
+
In order to properly evaluate a given LM, we require implementation of a wrapper class subclassing the `lm_eval.api.model.LM` class, that defines how the Evaluation Harness should interface with your model. This guide walks through how to write this `LM` subclass via adding it to the library!
|
| 6 |
+
|
| 7 |
+
## Setup
|
| 8 |
+
|
| 9 |
+
To get started contributing, go ahead and fork the main repo, clone it, create a branch with the name of your model, and install the project requirements in your environment:
|
| 10 |
+
|
| 11 |
+
```sh
|
| 12 |
+
# After forking...
|
| 13 |
+
git clone https://github.com/<YOUR-USERNAME>/lm-evaluation-harness.git
|
| 14 |
+
cd lm-evaluation-harness
|
| 15 |
+
git checkout -b <model-type>
|
| 16 |
+
pip install -e ".[dev]"
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
Now, we'll create a new file where we'll be adding our model:
|
| 20 |
+
|
| 21 |
+
```sh
|
| 22 |
+
touch lm_eval/models/<my_model_filename>.py
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
**Tip: this filename should not shadow package names! For example, naming your file `anthropic.py` is disallowed since the API's name on pypi is `anthropic`, but naming it `anthropic_llms.py` works with no problems.**
|
| 26 |
+
|
| 27 |
+
## Interface
|
| 28 |
+
|
| 29 |
+
All models must subclass the `lm_eval.api.model.LM` class.
|
| 30 |
+
|
| 31 |
+
The LM class enforces a common interface via which we can extract responses from a model:
|
| 32 |
+
|
| 33 |
+
```python
|
| 34 |
+
class MyCustomLM(LM):
|
| 35 |
+
#...
|
| 36 |
+
def loglikelihood(self, requests: list[Instance]) -> list[tuple[float, bool]]:
|
| 37 |
+
#...
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def loglikelihood_rolling(self, requests: list[Instance]) -> list[tuple[float, bool]]:
|
| 41 |
+
#...
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def generate_until(self, requests: list[Instance]) -> list[str]:
|
| 45 |
+
#...
|
| 46 |
+
#...
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
Where `Instance` is a dataclass defined in [`lm_eval.api.instance`](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/api/instance.py) with property `args` of request-dependent type signature described below.
|
| 50 |
+
|
| 51 |
+
We support three types of requests, consisting of different interactions / measurements with an autoregressive LM.
|
| 52 |
+
|
| 53 |
+
All three request types take as input `requests` of type `list[Instance]` that have a matching `Instance.request_type` to the method name.
|
| 54 |
+
|
| 55 |
+
- `generate_until`
|
| 56 |
+
- Each request contains `Instance.args : Tuple[str, dict]` containing 1. an input string to the LM and 2. a dictionary of keyword arguments used to control generation parameters.
|
| 57 |
+
- Using this input and these generation parameters, text will be sampled from the language model (typically until a maximum output length or specific stopping string sequences--for example, `{"until": ["\n\n", "."], "max_gen_toks": 128}`).
|
| 58 |
+
- The generated output text from the model will then be returned.
|
| 59 |
+
|
| 60 |
+
- `loglikelihood`
|
| 61 |
+
- Each request contains `Instance.args : Tuple[str, str]` containing 1. an input string to the LM and 2. a target string on which the loglikelihood of the LM producing this target, conditioned on the input, will be returned.
|
| 62 |
+
- Each request will have, as result, `(ll, is_greedy): Tuple[float, int]` returned, where `ll` is a floating point number representing the log probability of generating the target string conditioned on the input, and `is_greedy` being either the value `0` or `1`, with it being `1` if and only if the target string *would be generated by greedy sampling from the LM* (that is, if the target string is the *most likely* N-token string to be output by the LM given the input. )
|
| 63 |
+
|
| 64 |
+
- `loglikelihood_rolling`
|
| 65 |
+
- Each request contains `Instance.args : Tuple[str]`, which is an input string to the model whose *entire* loglikelihood, conditioned on purely the EOT token, will be calculated.
|
| 66 |
+
- This is used to evaluate *perplexity* on a data distribution.
|
| 67 |
+
- It should return `(ll,) : Tuple[float]` , a.k.a. solely the *loglikelihood* of producing each piece of text given no starting input.
|
| 68 |
+
|
| 69 |
+
To allow a model to be evaluated on all types of tasks, you will need to implement these three types of measurements (note that `loglikelihood_rolling` is a special case of `loglikelihood`). For a reference implementation, check out `lm_eval/models/huggingface.py` ! Additionally, check out `lm_eval.api.model.TemplateLM` for a class that abstracts away some commonly used functions across LM subclasses, or see if your model would lend itself well to subclassing the `lm_eval.models.huggingface.HFLM` class and overriding just the initialization or a couple methods!
|
| 70 |
+
|
| 71 |
+
**Tip: be careful of indexing in loglikelihood!**
|
| 72 |
+
|
| 73 |
+
LMs take in tokens in position `[0 1 2 ... N]` and output a probability distribution for token position `N+1`. We provide a simplified graphic here, excerpted from `huggingface.py`:
|
| 74 |
+
|
| 75 |
+
```text
|
| 76 |
+
# how this all works (illustrated on a causal decoder-only setup):
|
| 77 |
+
# CTX CONT
|
| 78 |
+
# inp 0 1 2 3|4 5 6 7 8 9 <- last token is deleted by inp[:, :-1]
|
| 79 |
+
# model \ \
|
| 80 |
+
# logits 1 2 3|4 5 6 7 8 9 <- the ctx half gets tossed out by the
|
| 81 |
+
# cont_toks 4 5 6 7 8 9 [:, -len(continuation_enc):, :self.vocab_size] slice
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
The final token of the target is not passed into the LM, because we want the LM's predictions *up to but not past* that final target token. For more information, check out https://github.com/EleutherAI/lm-evaluation-harness/issues/942 .
|
| 85 |
+
|
| 86 |
+
## Registration
|
| 87 |
+
|
| 88 |
+
Congrats on implementing your model! Now it's time to test it out.
|
| 89 |
+
|
| 90 |
+
To make your model usable via the command line interface to `lm-eval` using `python -m lm_eval`, you'll need to tell `lm-eval` what your model's name is.
|
| 91 |
+
|
| 92 |
+
This is done via a *decorator*, `lm_eval.api.registry.register_model`. Using `register_model()`, one can both tell the package what the model's name(s) to be used are when invoking it with `python -m lm_eval --model <name>` and alert `lm-eval` to the model's existence.
|
| 93 |
+
|
| 94 |
+
```python
|
| 95 |
+
from lm_eval.api.registry import register_model
|
| 96 |
+
|
| 97 |
+
@register_model("<name1>", "<name2>")
|
| 98 |
+
class MyCustomLM(LM):
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
Using this decorator results in the class being added to an accounting of the usable LM types maintained internally to the library at `lm_eval.api.registry.MODEL_REGISTRY`. See `lm_eval.api.registry` for more detail on what sorts of registries and decorators exist in the library!
|
| 102 |
+
|
| 103 |
+
**Tip: be sure to import your model in `lm_eval/models/__init__.py!`**
|
| 104 |
+
|
| 105 |
+
## Testing
|
| 106 |
+
|
| 107 |
+
We also recommend that new model contributions be accompanied by short tests of their 3 core functionalities, at minimum. To see an example of such tests, look at https://github.com/EleutherAI/lm-evaluation-harness/blob/35bdecd379c0cefad6897e67db892f4a6026a128/tests/test_ggml.py .
|
| 108 |
+
|
| 109 |
+
## Chat Templating
|
| 110 |
+
|
| 111 |
+
Many models are fine-tuned with a [Chat Template](https://huggingface.co/docs/transformers/main/en/chat_templating) in order to enable back-and-forth interaction between a "User"'s queries and the model (often called "Assistant")'s responses. It can be desirable to evaluate fine-tuned models on evaluation tasks while wrapped in the conversational format they expect.
|
| 112 |
+
|
| 113 |
+
In order to make your model optionally compatible with a chat format, three additional methods must be implemented:
|
| 114 |
+
|
| 115 |
+
```python
|
| 116 |
+
class MyCustomLM(LM):
|
| 117 |
+
#...
|
| 118 |
+
@property
|
| 119 |
+
def tokenizer_name(self) -> str:
|
| 120 |
+
"""
|
| 121 |
+
Return the name of the model's tokenizer and/or the accompanying chat template.
|
| 122 |
+
The returned string is used to cache requests.
|
| 123 |
+
|
| 124 |
+
Returns:
|
| 125 |
+
str: The name of the model's tokenizer and/or chat template.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
def chat_template(self, chat_template: Union[bool, str] = False) -> str:
|
| 129 |
+
"""
|
| 130 |
+
Get the appropriate chat template for the model based on the `chat_template` argument.
|
| 131 |
+
|
| 132 |
+
This method returns the chat template string to build the prompt from a chat history.
|
| 133 |
+
The chat template is saved in the evaluation results for reproducibility.
|
| 134 |
+
Boolean arguments should be used with models that have only one chat template,
|
| 135 |
+
while string arguments are used with models that have multiple chat templates.
|
| 136 |
+
For the reference implementation, see HFLM class in `lm_eval.models.huggingface`.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
chat_template (Union[bool, str]): Specifies whether to apply a chat template:
|
| 140 |
+
- If False: Do not apply any chat template.
|
| 141 |
+
- If True: Apply the default chat template.
|
| 142 |
+
- If str: Apply the specified chat template by name.
|
| 143 |
+
|
| 144 |
+
Returns:
|
| 145 |
+
str: The selected chat template in Jinja format.
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
def apply_chat_template(self, chat_history: List[Dict[str, str]]) -> str:
|
| 149 |
+
"""
|
| 150 |
+
Process a chat history to create a string that can be tokenized and input into the model.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
chat_history (List[Dict[str, str]]): A list of dictionaries representing the chat history,
|
| 154 |
+
where each dictionary has "role" and "content" keys.
|
| 155 |
+
|
| 156 |
+
Returns:
|
| 157 |
+
str: A string representing the chat history that can be tokenized and fed into the model.
|
| 158 |
+
"""
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
- `apply_chat_template`
|
| 162 |
+
- This method performs the bulk of the work required for chat-formatting.
|
| 163 |
+
- As input, a `chat_history: List[Dict[str, str]]` is passed in. This is a transcript of a conversation of a form similar to
|
| 164 |
+
|
| 165 |
+
```text
|
| 166 |
+
[
|
| 167 |
+
{"system": <user-provided system message such as "You are a helpful math-focused chatbot">},
|
| 168 |
+
{"user": <task example - a few-shot example 'input'>}
|
| 169 |
+
{"assistant": <correct response to the above example>},
|
| 170 |
+
# ... more few-shot examples, potentially
|
| 171 |
+
{"user": <test set query--response on which we will evaluate>},
|
| 172 |
+
]
|
| 173 |
+
```
|
| 174 |
+
|
| 175 |
+
which can then be converted into a string input.
|
| 176 |
+
- The output is a string representing this conversation that can be fed into the model.
|
| 177 |
+
- For example, this consists of simply calling `tokenizer.apply_chat_template` for HFLM--see the implementation there for reference.
|
| 178 |
+
- `tokenizer_name`
|
| 179 |
+
- LM Eval Harness supports [caching requests](https://github.com/EleutherAI/lm-evaluation-harness/blob/4902aaaf1f374682f95ac25fe2e13b23faddc91a/lm_eval/__main__.py#L140) that are sent to a model, for faster setup when repeating an already-performed evaluation.
|
| 180 |
+
- However, we don't want to use the cache of chat transcripts rendered using one chat template or system prompt to send to a model with a different template! So, we use this `lm.tokenizer_name` string to distinguish caches for a given model (and chat template) from one another.
|
| 181 |
+
- `chat_template`
|
| 182 |
+
- Chat templates are typically provided as a Jinja template string or a string formatted with str.format to include user and assistant messages in a single prompt. This template string is saved in the evaluation results to ensure reproducibility.
|
| 183 |
+
|
| 184 |
+
If not implemented for a given model type, the flags `--apply_chat_template` , `--fewshot_as_multiturn`, and `--system_instruction` cannot be used.
|
| 185 |
+
|
| 186 |
+
## Other
|
| 187 |
+
|
| 188 |
+
**Pro tip**: In order to make the Evaluation Harness overestimate total runtimes rather than underestimate it, HuggingFace models come in-built with the ability to provide responses on data points in *descending order by total input length* via `lm_eval.utils.Reorderer`. Take a look at `lm_eval.models.hf_causal.HFLM` to see how this is done, and see if you can implement it in your own model!
|
| 189 |
+
|
| 190 |
+
## Conclusion
|
| 191 |
+
|
| 192 |
+
After reading this guide, you should be able to add new model APIs or implementations to the Eval Harness library!
|
lm-evaluation-har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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# New Task Guide
|
| 2 |
+
|
| 3 |
+
`lm-evaluation-harness` is a framework that strives to support a wide range of zero- and few-shot evaluation tasks on autoregressive language models (LMs).
|
| 4 |
+
|
| 5 |
+
This documentation page provides a walkthrough to get started creating your own task, in `lm-eval` versions v0.4.0 and later.
|
| 6 |
+
|
| 7 |
+
A more interactive tutorial is available as a Jupyter notebook [here](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/examples/lm-eval-overview.ipynb).
|
| 8 |
+
|
| 9 |
+
## Setup
|
| 10 |
+
|
| 11 |
+
If you haven't already, go ahead and fork the main repo, clone it, create a branch with the name of your task, and install the project requirements in your environment:
|
| 12 |
+
|
| 13 |
+
```sh
|
| 14 |
+
# After forking...
|
| 15 |
+
git clone https://github.com/<YOUR-USERNAME>/lm-evaluation-harness.git
|
| 16 |
+
cd lm-evaluation-harness
|
| 17 |
+
git checkout -b <task-name>
|
| 18 |
+
pip install -e ".[dev]"
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
In this document, we'll walk through the basics of implementing a static benchmark evaluation in two formats: a *generative* task which requires sampling text from a model, such as [`gsm8k`](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/gsm8k/gsm8k.yaml), and a *discriminative*, or *multiple choice*, task where the model picks the most likely of several fixed answer choices, such as [`sciq`](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/sciq/sciq.yaml).
|
| 22 |
+
|
| 23 |
+
## Creating a YAML file
|
| 24 |
+
|
| 25 |
+
To implement a new standard task, we'll need to write a YAML file which configures our task logic. We start by making a new empty YAML file. This file can have any name, but we recommend placing it in a subfolder of `lm_eval/tasks` titled by the dataset or task's shorthand name: for example,
|
| 26 |
+
|
| 27 |
+
```sh
|
| 28 |
+
touch lm_eval/tasks/<dataset_name>/<my_new_task_name>.yaml
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
Or, copy the template subfolder we provide from `templates/new_yaml_task`:
|
| 32 |
+
|
| 33 |
+
```sh
|
| 34 |
+
cp -r templates/new_yaml_task lm_eval/tasks/
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
and rename the folders and YAML file(s) as desired.
|
| 38 |
+
|
| 39 |
+
### Selecting and configuring a dataset
|
| 40 |
+
|
| 41 |
+
All data downloading and management is handled through the HuggingFace (**HF**) [`datasets`](https://github.com/huggingface/datasets) API. So, the first thing you should do is check to see if your task's dataset is already provided in their catalog [here](https://huggingface.co/datasets). If it's not in there, please consider adding it to their Hub to make it accessible to a wider user base by following their [new dataset guide](https://github.com/huggingface/datasets/blob/main/ADD_NEW_DATASET.md)
|
| 42 |
+
.
|
| 43 |
+
> [!TIP]
|
| 44 |
+
> To test your task, we recommend using verbose logging using `export LOGLEVEL = DEBUG` in your shell before running the evaluation script. This will help you debug any issues that may arise.
|
| 45 |
+
Once you have a HuggingFace dataset prepared for your task, we want to assign our new YAML to use this dataset:
|
| 46 |
+
|
| 47 |
+
```yaml
|
| 48 |
+
dataset_path: ... # the name of the dataset on the HF Hub.
|
| 49 |
+
dataset_name: ... # the dataset configuration to use. Leave `null` if your dataset does not require a config to be passed. See https://huggingface.co/docs/datasets/load_hub#configurations for more info.
|
| 50 |
+
dataset_kwargs: null # any extra keyword arguments that should be passed to the dataset constructor, e.g. `data_dir`.
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
Next, we'd like to tell our task what the dataset's train, validation, and test splits are named, if they exist:
|
| 54 |
+
|
| 55 |
+
```yaml
|
| 56 |
+
training_split: <split name of training set, or `null`>
|
| 57 |
+
validation_split: <split name of val. set, or `null`>
|
| 58 |
+
test_split: <split name of test set, or `null`>
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
Tests will run on the `test_split` if it is available, and otherwise evaluate on the `validation_split`.
|
| 62 |
+
|
| 63 |
+
We can also specify from which split the task should retrieve few-shot examples via:
|
| 64 |
+
|
| 65 |
+
```yaml
|
| 66 |
+
fewshot_split: <split name to draw fewshot examples from, or `null`>
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
or by hardcoding them, either using the following in the yaml file:
|
| 70 |
+
|
| 71 |
+
```yaml
|
| 72 |
+
fewshot_config:
|
| 73 |
+
sampler: first_n
|
| 74 |
+
samples: [
|
| 75 |
+
{<sample 1>},
|
| 76 |
+
{<sample 2>},
|
| 77 |
+
]
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
or by adding the function `list_fewshot_samples` in the associated utils.py file:
|
| 81 |
+
|
| 82 |
+
```python
|
| 83 |
+
def list_fewshot_samples() -> list[dict]:
|
| 84 |
+
return [{<sample 1>}, {<sample 2>}]
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
See `lm_eval/tasks/minerva_math/minerva_math_algebra.yaml` for an example of the latter, and `lm_eval/tasks/gsm8k/gsm8k-cot.yaml` for an example of the former.
|
| 88 |
+
|
| 89 |
+
In this case, each sample must contain the same fields as the samples in the above sets--for example, if `doc_to_text` expects an `input` field when rendering input prompts, these provided samples must include an `input` key.
|
| 90 |
+
|
| 91 |
+
If neither above options are not set, we will default to train/validation/test sets, in that order.
|
| 92 |
+
|
| 93 |
+
Finally, our dataset may not be already in the exact format we want. Maybe we have to strip whitespace and special characters via a regex from our dataset's "question" field! Or maybe we just want to rename its columns to match a convention we'll be using for our prompts.
|
| 94 |
+
|
| 95 |
+
Let's create a python file in the directory where we're writing our YAML file:
|
| 96 |
+
|
| 97 |
+
```bash
|
| 98 |
+
touch lm_eval/tasks/<dataset_name>/utils.py
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
Now, in `utils.py` we'll write a function to process each split of our dataset (the following example is drawn from [the `hellaswag` task](../lm_eval/tasks/hellaswag/utils.py)):
|
| 102 |
+
|
| 103 |
+
```python
|
| 104 |
+
def process_docs(dataset: datasets.Dataset) -> datasets.Dataset:
|
| 105 |
+
def _process_doc(doc):
|
| 106 |
+
ctx = doc["ctx_a"] + " " + doc["ctx_b"].capitalize()
|
| 107 |
+
out_doc = {
|
| 108 |
+
"query": preprocess(doc["activity_label"] + ": " + ctx),
|
| 109 |
+
"choices": [preprocess(ending) for ending in doc["endings"]],
|
| 110 |
+
"gold": int(doc["label"]),
|
| 111 |
+
}
|
| 112 |
+
return out_doc
|
| 113 |
+
|
| 114 |
+
return dataset.map(_process_doc)
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
Now, in our YAML config file we'll use the `!function` constructor, and tell the config where our imported Python function will come from. At runtime, before doing anything else we will preprocess our dataset according to this function!
|
| 118 |
+
|
| 119 |
+
```yaml
|
| 120 |
+
process_docs: !function utils.process_docs
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
### Using Local Datasets
|
| 124 |
+
|
| 125 |
+
To load a local dataset for evaluation, you can specify data files in the `dataset_kwargs` field, such as the following for JSON files:
|
| 126 |
+
|
| 127 |
+
```yaml
|
| 128 |
+
dataset_path: json
|
| 129 |
+
dataset_name: null
|
| 130 |
+
dataset_kwargs:
|
| 131 |
+
data_files: /path/to/my/json
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
Or with files already split into separate directories:
|
| 135 |
+
|
| 136 |
+
```yaml
|
| 137 |
+
dataset_path: arrow
|
| 138 |
+
dataset_kwargs:
|
| 139 |
+
data_files:
|
| 140 |
+
train: /path/to/arrow/train/data-00000-of-00001.arrow
|
| 141 |
+
validation: /path/to/arrow/validation/data-00000-of-00001.arrow
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
Alternatively, if you have previously downloaded a dataset from huggingface hub (using `save_to_disk()`) and wish to use the local files, you will need to use `data_dir` under `dataset_kwargs` to point to where the directory is.
|
| 145 |
+
|
| 146 |
+
```yaml
|
| 147 |
+
dataset_path: hellaswag
|
| 148 |
+
dataset_kwargs:
|
| 149 |
+
data_dir: hellaswag_local/
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
You can also set `dataset_path` as a directory path in your local system. This will assume that there is a loading script with the same name as the directory. [See datasets docs](https://huggingface.co/docs/datasets/loading#local-loading-script).
|
| 153 |
+
|
| 154 |
+
## Writing a Prompt Template
|
| 155 |
+
|
| 156 |
+
The next thing we need to do is decide what format to use when presenting the data to the LM. This is our **prompt**, where we'll define both an input and output format.
|
| 157 |
+
|
| 158 |
+
To write a prompt, users will use `doc_to_text`, `doc_to_target`, and `doc_to_choice` (Optional when certain conditions are met).
|
| 159 |
+
|
| 160 |
+
`doc_to_text` defines the input string a model will be given while `doc_to_target` and `doc_to_choice` will be used to generate the target text. `doc_to_target` can be either a text string that refers to the target string or an integer that refers to the index of the correct label. When it is set as an index, `doc_to_choice` must also be set with the appropriate list of possible choice strings.
|
| 161 |
+
|
| 162 |
+
### Basic prompts
|
| 163 |
+
|
| 164 |
+
If a dataset is straightforward enough, users can enter the feature name directly. This assumes that no preprocessing is required. For example in [Swag](https://github.com/EleutherAI/lm-evaluation-harness/blob/1710b42d52d0f327cb0eb3cb1bfbbeca992836ca/lm_eval/tasks/swag/swag.yaml#L10-L11), `doc_to_text` and `doc_to_target` given the name of one of the feature each.
|
| 165 |
+
|
| 166 |
+
```yaml
|
| 167 |
+
doc_to_text: startphrase
|
| 168 |
+
doc_to_target: label
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
Hard-coding is also possible as is the case in [SciQ](https://github.com/EleutherAI/lm-evaluation-harness/blob/1710b42d52d0f327cb0eb3cb1bfbbeca992836ca/lm_eval/tasks/sciq/sciq.yaml#L11).
|
| 172 |
+
|
| 173 |
+
```yaml
|
| 174 |
+
doc_to_target: 3
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
`doc_to_choice` can be directly given a list of text as option (See [Toxigen](https://github.com/EleutherAI/lm-evaluation-harness/blob/1710b42d52d0f327cb0eb3cb1bfbbeca992836ca/lm_eval/tasks/toxigen/toxigen.yaml#L11))
|
| 178 |
+
|
| 179 |
+
```yaml
|
| 180 |
+
doc_to_choice: ['No', 'Yes']
|
| 181 |
+
```
|
| 182 |
+
|
| 183 |
+
if a dataset feature is already a list, you can set the name of the feature as `doc_to_choice` (See [Hellaswag](https://github.com/EleutherAI/lm-evaluation-harness/blob/e0eda4d3ffa10e5f65e0976161cd134bec61983a/lm_eval/tasks/hellaswag/hellaswag.yaml#L13))
|
| 184 |
+
|
| 185 |
+
```yaml
|
| 186 |
+
doc_to_choice: choices
|
| 187 |
+
```
|
| 188 |
+
|
| 189 |
+
### Writing a prompt with Jinja 2
|
| 190 |
+
|
| 191 |
+
We support the [Jinja 2](https://jinja.palletsprojects.com/en/3.1.x/) templating language for writing prompts. In practice, this means you can take your dataset's columns and do many basic string manipulations to place each document into prompted format.
|
| 192 |
+
|
| 193 |
+
Take for example the dataset `super_glue/boolq`. As input, we'd like to use the features `passage` and `question` and string them together so that for a sample line `doc`, the model sees something in the format of:
|
| 194 |
+
|
| 195 |
+
```text
|
| 196 |
+
doc["passage"]
|
| 197 |
+
Question: doc["question"]?
|
| 198 |
+
Answer:
|
| 199 |
+
```
|
| 200 |
+
|
| 201 |
+
We do this by [writing](https://github.com/EleutherAI/lm-evaluation-harness/blob/1710b42d52d0f327cb0eb3cb1bfbbeca992836ca/lm_eval/tasks/super_glue/boolq/default.yaml#L9C1-L9C61)
|
| 202 |
+
|
| 203 |
+
```yaml
|
| 204 |
+
doc_to_text: "{{passage}}\nQuestion: {{question}}?\nAnswer:"
|
| 205 |
+
```
|
| 206 |
+
|
| 207 |
+
Such that `{{passage}}` will be replaced by `doc["passage"]` and `{{question}}` with `doc["question"]` when rendering the prompt template.
|
| 208 |
+
|
| 209 |
+
Our intended output is for the model to predict a single whitespace, and then the answer to the question. We do this via:
|
| 210 |
+
|
| 211 |
+
```yaml
|
| 212 |
+
doc_to_target: "{{answer}}"
|
| 213 |
+
```
|
| 214 |
+
|
| 215 |
+
#### Multiple choice format
|
| 216 |
+
|
| 217 |
+
For tasks which are multiple choice (a fixed, finite set of label words per each document) and evaluated via comparing loglikelihoods of all label words (the `multiple_choice` task output type) we enforce a particular convention on prompt format.
|
| 218 |
+
|
| 219 |
+
> [!WARNING]
|
| 220 |
+
> We add `target_delimiter` between input and target which defaults to " ", such that the full input-output string is `doc_to_text(doc) + target_delimiter + doc_to_target(doc)`. `doc_to_text` and `doc_to_target` should not contain trailing right or left whitespace, respectively. For multiple choice the target will be each choice index concatenated with the delimiter.
|
| 221 |
+
|
| 222 |
+
An annotated example in the case of SciQ is as follows:
|
| 223 |
+
|
| 224 |
+
```yaml
|
| 225 |
+
doc_to_text: "{{support.lstrip()}}\nQuestion: {{question}}\nAnswer:" # This is the input portion of the prompt for this doc. It will have " {{choice}}" appended to it as target for each choice in answer_choices.
|
| 226 |
+
doc_to_target: 3 # this contains the index into the answer choice list of the correct answer.
|
| 227 |
+
doc_to_choice: "{{[distractor1, distractor2, distractor3, correct_answer]}}"
|
| 228 |
+
```
|
| 229 |
+
|
| 230 |
+
Task implementers are thus able to decide what the answer choices should be for a document, and what prompt format to use.
|
| 231 |
+
|
| 232 |
+
The label index can also be sourced from a feature directly. For example in `superglue/boolq`, the label index if defined in the feature `label`. We can set `doc_to_target` as simply `label`. The options or verbalizers can be written in the form of a list `["no", "yes"]` that will correspond to the label index.
|
| 233 |
+
|
| 234 |
+
```yaml
|
| 235 |
+
doc_to_text: "{{passage}}\nQuestion: {{question}}?\nAnswer:"
|
| 236 |
+
doc_to_target: label
|
| 237 |
+
doc_to_choice: ["no", "yes"]
|
| 238 |
+
```
|
| 239 |
+
|
| 240 |
+
### Using Python Functions for Prompts
|
| 241 |
+
|
| 242 |
+
There may be cases where the prompt we want to implement is easier expressed in Python instead of Jinja 2. For this, we can use Python helper functions that are defined in the YAML config. It should be noted that the function script must be in the same directory as the yaml.
|
| 243 |
+
|
| 244 |
+
A good example is WikiText that requires a lot of regex rules to clean the samples.
|
| 245 |
+
|
| 246 |
+
```python
|
| 247 |
+
def wikitext_detokenizer(doc):
|
| 248 |
+
string = doc["page"]
|
| 249 |
+
# contractions
|
| 250 |
+
string = string.replace("s '", "s'")
|
| 251 |
+
string = re.sub(r"/' [0-9]/", r"/'[0-9]/", string)
|
| 252 |
+
...
|
| 253 |
+
string = string.replace(" 's", "'s")
|
| 254 |
+
|
| 255 |
+
return string
|
| 256 |
+
```
|
| 257 |
+
|
| 258 |
+
We can load this function in `doc_to_target` by using a `!function` operator after `doc_to_target` and followed by `<file name>.<function name>`. In the file [wikitext.yaml](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/wikitext/wikitext.yaml) we write:
|
| 259 |
+
|
| 260 |
+
```yaml
|
| 261 |
+
doc_to_target: !function preprocess_wikitext.wikitext_detokenizer
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
### Importing a Prompt from Promptsource
|
| 265 |
+
|
| 266 |
+
[Promptsource](https://github.com/bigscience-workshop/promptsource/tree/main/promptsource) is a great repository for crowdsourced prompts for many datasets. We can load these prompts easily by using the `use_prompt` argument and filling it with the format `"promptsource:<name of prompt template>"`. To use this, `doc_to_text` and `doc_to_target` should be left undefined. This will fetch the template of the dataset defined in the YAML file.
|
| 267 |
+
|
| 268 |
+
For example, For Super Glue BoolQ, if we want to use the prompt template `GPT-3 Style` we can add this to the YAML file.
|
| 269 |
+
|
| 270 |
+
```yaml
|
| 271 |
+
use_prompt: "promptsource:GPT-3 Style"
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
If you would like to run evaluation on all prompt templates, you can simply call it this way.
|
| 275 |
+
|
| 276 |
+
```yaml
|
| 277 |
+
use_prompt: "promptsource:*"
|
| 278 |
+
```
|
| 279 |
+
|
| 280 |
+
### Setting metrics
|
| 281 |
+
|
| 282 |
+
You're almost done! Now we need to choose how to score our task.
|
| 283 |
+
|
| 284 |
+
- *If this is a multiple choice task:* do you just want to check your model's accuracy in choosing the correct answer choice?
|
| 285 |
+
- *If this is a generation task:* do you just want to check how often your model outputs *exactly the ground-truth output string provided*?
|
| 286 |
+
|
| 287 |
+
If the answer to the above is no: you'll need to record what scoring metrics to use! Metrics can be listed in the following format:
|
| 288 |
+
|
| 289 |
+
```yaml
|
| 290 |
+
metric_list:
|
| 291 |
+
- metric: <name of the metric here>
|
| 292 |
+
aggregation: <name of the aggregation fn here>
|
| 293 |
+
higher_is_better: <true or false>
|
| 294 |
+
- metric: !function script.function
|
| 295 |
+
aggregation: ...
|
| 296 |
+
higher_is_better: ...
|
| 297 |
+
```
|
| 298 |
+
|
| 299 |
+
`aggregation` and `higher_is_better` can optionally be left out to default to the manually-set defaults if using a natively supported metric, otherwise it must be defined explicitly (for example, when using a custom metric implemented as a function).
|
| 300 |
+
|
| 301 |
+
For a full list of natively supported metrics and aggregation functions see [`docs/task_guide.md`](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/task_guide.md). All metrics supported in [HuggingFace Evaluate](https://github.com/huggingface/evaluate/tree/main/metrics) can also be used, and will be loaded if a given metric name is not one natively supported in `lm-eval` or `hf_evaluate` is set to `true`.
|
| 302 |
+
|
| 303 |
+
### Optional, More Advanced Setup
|
| 304 |
+
|
| 305 |
+
Some tasks may require more advanced processing logic than is described in this guide.
|
| 306 |
+
|
| 307 |
+
As a heuristic check:
|
| 308 |
+
|
| 309 |
+
- Does your task require generating multiple free-form outputs per input document?
|
| 310 |
+
- Does your task require complex, multi-step post-processing of generated model outputs?
|
| 311 |
+
- Does your task require subsetting documents on the fly based on their content?
|
| 312 |
+
- Do you expect to compute metrics after applying multiple such processing steps on your model outputs?
|
| 313 |
+
- Does your task rely on metrics that need a custom implementation?
|
| 314 |
+
|
| 315 |
+
For more detail on the task system and advanced features, see [`docs/task_guide.md`](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/task_guide.md). If none of the above sounds like they apply to your task, it's time to continue onto checking your task performance!
|
| 316 |
+
|
| 317 |
+
### Task name + tags (registering a task)
|
| 318 |
+
|
| 319 |
+
To test a task conveniently, it helps to *register* the task--that is, to give it a name and make the `lm-eval` library aware it exists!
|
| 320 |
+
|
| 321 |
+
If you're writing your YAML file inside the `lm_eval/tasks` folder, you just need to give your task a name! You can do this inside your YAML file:
|
| 322 |
+
|
| 323 |
+
```yaml
|
| 324 |
+
task: <name of the task>
|
| 325 |
+
```
|
| 326 |
+
|
| 327 |
+
Including a task name is mandatory.
|
| 328 |
+
|
| 329 |
+
It is often also convenient to label your task with several `tag` values, though this field is optional:
|
| 330 |
+
|
| 331 |
+
```yaml
|
| 332 |
+
tag:
|
| 333 |
+
- tag1
|
| 334 |
+
- tag2
|
| 335 |
+
```
|
| 336 |
+
|
| 337 |
+
This will add your task to the `tag1` and `tag2` tags, enabling people to know how to categorize your task, and if desired run all tasks in one of these groups at once, your task along with them.
|
| 338 |
+
|
| 339 |
+
If your task is not in the `lm_eval/tasks` folder, you'll need to tell the Eval Harness where to look for YAML files.
|
| 340 |
+
|
| 341 |
+
You can do this via the `--include_path` argument in `__main__.py`. This command will be used to initialize the `TaskManager` object which you can also use for your custom scripts.
|
| 342 |
+
|
| 343 |
+
```python
|
| 344 |
+
task_manager = TaskManager(args.verbosity, include_path=args.include_path)
|
| 345 |
+
```
|
| 346 |
+
|
| 347 |
+
Passing `--tasks /path/to/yaml/file` is also accepted.
|
| 348 |
+
|
| 349 |
+
### Advanced Group Configs
|
| 350 |
+
|
| 351 |
+
While `tag` values are helpful when you want to be able to quickly and conveniently run a set of related tasks via `--tasks my_tag_name`, often, we wish to implement more complex logic. For example, the MMLU benchmark contains 57 *subtasks* that must all be *averaged* together in order to report a final 'MMLU score'.
|
| 352 |
+
|
| 353 |
+
Groupings of tasks might also use particular variants of a task--for example, we might want to default to evaluating a task as 5-shot when called as part of a given grouping, but not have a preference for number of shots when evaluating it as a standalone.
|
| 354 |
+
|
| 355 |
+
We implement this via **groups**, which are distinct from tags. Groups can be implemented via *group config* YAML files, which are laid out similarly but slightly differently to tasks' YAML configs.
|
| 356 |
+
|
| 357 |
+
The most basic form of group can be defined via a YAML config similar to the following:
|
| 358 |
+
|
| 359 |
+
```yaml
|
| 360 |
+
group: nli_tasks
|
| 361 |
+
task:
|
| 362 |
+
- cb
|
| 363 |
+
- anli_r1
|
| 364 |
+
- rte
|
| 365 |
+
metadata:
|
| 366 |
+
version: 1.0
|
| 367 |
+
```
|
| 368 |
+
|
| 369 |
+
This will behave almost identically to a `tag` that includes these 3 tasks, but with one key distinction: we'll print the `nli_tasks` group as a row (with no associated metrics) in our table of outputs, and visually show that these 3 tasks appear under its subheader.
|
| 370 |
+
|
| 371 |
+
Now, let's assume we actually want to report an aggregate score for `nli_tasks`. We would instead use a YAML config like the following:
|
| 372 |
+
|
| 373 |
+
```yaml
|
| 374 |
+
group: nli_tasks
|
| 375 |
+
task:
|
| 376 |
+
- cb
|
| 377 |
+
- anli_r1
|
| 378 |
+
- rte
|
| 379 |
+
aggregate_metric_list:
|
| 380 |
+
- metric: acc
|
| 381 |
+
aggregation: mean
|
| 382 |
+
weight_by_size: true # defaults to `true`. Set this to `false` to do a "macro" average (taking each subtask's average accuracy, and summing those accuracies and dividing by 3)--by default we do a "micro" average (retain all subtasks' per-document accuracies, and take the mean over all documents' accuracies to get our aggregate mean).
|
| 383 |
+
metadata:
|
| 384 |
+
version: 1.0
|
| 385 |
+
```
|
| 386 |
+
|
| 387 |
+
Similar to our `metric_list` for listing out the metrics we want to calculate for a given task, we use an `aggregate_metric_list` field to specify which metric name to aggregate across subtasks, what aggregation function to use, and whether we should micro- or macro- average these metrics. See [./task_guide.md](./task_guide.md) for a full list of related sub-keys.
|
| 388 |
+
|
| 389 |
+
**[!Tip]: currently, we predominantly only support the aggregation of group metrics that use `mean` (either micro- or macro- averaged) over their subtasks. If you require even more complex aggregation rules, you may want to perform aggregation offline.**
|
| 390 |
+
|
| 391 |
+
Group configs can be fairly complex! We can do various operations, such as defining new subtask(s) inline in our group YAML, overriding an existing task's specific config value, or nesting existing groups within our
|
| 392 |
+
|
| 393 |
+
For example, let's build a config for evaluating MMLU and a few natural language inference tasks. For MMLU, we can write the name for the benchmark as a subtask written under `task`. You can configure the parameters such as `num_fewshot`. If the task being configured is a group such as `mmlu` or `super_glue`, the parameter set will be applied to all of the subtasks.
|
| 394 |
+
|
| 395 |
+
```yaml
|
| 396 |
+
group: nli_and_mmlu
|
| 397 |
+
task:
|
| 398 |
+
- group: nli_tasks
|
| 399 |
+
task:
|
| 400 |
+
- cb
|
| 401 |
+
- anli_r1
|
| 402 |
+
- rte
|
| 403 |
+
aggregate_metric_list:
|
| 404 |
+
- metric: acc
|
| 405 |
+
aggregation: mean
|
| 406 |
+
higher_is_better: true
|
| 407 |
+
- task: mmlu
|
| 408 |
+
num_fewshot: 2
|
| 409 |
+
```
|
| 410 |
+
|
| 411 |
+
### Configuring python classes
|
| 412 |
+
|
| 413 |
+
There can be occasions when yaml-based tasks cannot accommodate how a task is handled. LM-Eval supports the manually implementing tasks as was previously done before `0.4.x`. To register the task, you can simply make a yaml with the name of the task in `task` and the class object in `class` using the `!function` prefix.
|
| 414 |
+
|
| 415 |
+
```yaml
|
| 416 |
+
task: squadv2
|
| 417 |
+
class: !function task.SQuAD2
|
| 418 |
+
```
|
| 419 |
+
|
| 420 |
+
This also applies to building group configurations with subtasks that are python classes.
|
| 421 |
+
|
| 422 |
+
```yaml
|
| 423 |
+
group: scrolls
|
| 424 |
+
task:
|
| 425 |
+
- task: scrolls_qasper
|
| 426 |
+
class: !function task.Qasper
|
| 427 |
+
- task: scrolls_quality
|
| 428 |
+
class: !function task.QuALITY
|
| 429 |
+
- task: scrolls_narrativeqa
|
| 430 |
+
class: !function task.NarrativeQA
|
| 431 |
+
...
|
| 432 |
+
```
|
| 433 |
+
|
| 434 |
+
You can also pass a custom argument to your class by accepting `config` in the custom class constructor.
|
| 435 |
+
Here's how to do it:
|
| 436 |
+
|
| 437 |
+
```yaml
|
| 438 |
+
task: 20_newsgroups
|
| 439 |
+
class: !function task.Unitxt
|
| 440 |
+
recipe: card=cards.20_newsgroups,template=templates.classification.multi_class.title
|
| 441 |
+
```
|
| 442 |
+
|
| 443 |
+
In this example, `recipe` is the custom argument for the `Unitxt` class.
|
| 444 |
+
|
| 445 |
+
## Beautifying Table Display
|
| 446 |
+
|
| 447 |
+
To avoid conflict, each task needs to be registered with a unique name. Because of this, slight variations of task are still counted as unique tasks and need to be named uniquely. This could be done by appending an additional naming that may refer to the variation such as in MMLU where the template used to evaluated for flan are differentiated from the default by the prefix `mmlu_flan_*`. Printing the full task names can easily clutter the results table at the end of the evaluation especially when you have a long list of tasks or are using a benchmark that comprises of many tasks. To make it more legible, you can use `task_alias` and `group_alias` to provide an alternative task name and group name that will be printed. For example in `mmlu_abstract_algebra.yaml` we set `task_alias` to `abstract_algebra`. In group configs, a `group_alias` for a group can also be set.
|
| 448 |
+
|
| 449 |
+
```yaml
|
| 450 |
+
"dataset_name": "abstract_algebra"
|
| 451 |
+
"description": "The following are multiple choice questions (with answers) about abstract\
|
| 452 |
+
\ algebra.\n\n"
|
| 453 |
+
"include": "_default_template_yaml"
|
| 454 |
+
"task": "mmlu_abstract_algebra"
|
| 455 |
+
"task_alias": "abstract_algebra"
|
| 456 |
+
```
|
| 457 |
+
|
| 458 |
+
## Checking validity
|
| 459 |
+
|
| 460 |
+
After registering your task, you can now check on your data downloading and verify that the few-shot samples look as intended. Run the following command with your desired args:
|
| 461 |
+
|
| 462 |
+
```bash
|
| 463 |
+
python -m scripts.write_out \
|
| 464 |
+
--output_base_path <path> \
|
| 465 |
+
--tasks <your-task-name> \
|
| 466 |
+
--sets <train | val | test> \
|
| 467 |
+
--num_fewshot K \
|
| 468 |
+
--num_examples N \
|
| 469 |
+
```
|
| 470 |
+
|
| 471 |
+
Open the file specified at the `--output_base_path <path>` and ensure it passes
|
| 472 |
+
a simple eye test.
|
| 473 |
+
|
| 474 |
+
## Versioning
|
| 475 |
+
|
| 476 |
+
One key feature in LM Evaluation Harness is the ability to version tasks and groups--that is, mark them with a specific version number that can be bumped whenever a breaking change is made.
|
| 477 |
+
|
| 478 |
+
This version info can be provided by adding the following to your new task or group config file:
|
| 479 |
+
|
| 480 |
+
```yaml
|
| 481 |
+
metadata:
|
| 482 |
+
version: 0
|
| 483 |
+
```
|
| 484 |
+
|
| 485 |
+
Now, whenever a change needs to be made to your task in the future, please increase the version number by 1 so that users can differentiate the different task iterations and versions.
|
| 486 |
+
|
| 487 |
+
If you are incrementing a task's version, please also consider adding a changelog to the task's README.md noting the date, PR number, what version you have updated to, and a one-liner describing the change.
|
| 488 |
+
|
| 489 |
+
for example,
|
| 490 |
+
|
| 491 |
+
- \[Dec 25, 2023\] (PR #999) Version 0.0 -> 1.0: Fixed a bug with answer extraction that led to underestimated performance.
|
| 492 |
+
|
| 493 |
+
## Checking performance + equivalence
|
| 494 |
+
|
| 495 |
+
It's now time to check models' performance on your task! In the evaluation harness, we intend to support a wide range of evaluation tasks and setups, but prioritize the inclusion of already-proven benchmarks following the precise evaluation setups in the literature where possible.
|
| 496 |
+
|
| 497 |
+
To enable this, we provide a checklist that should be completed when contributing a new task, to enable accurate book-keeping and to ensure that tasks added to the library are well-tested and, where applicable, precedented.
|
| 498 |
+
|
| 499 |
+
### Task Validity Checklist
|
| 500 |
+
|
| 501 |
+
The checklist is the following:
|
| 502 |
+
|
| 503 |
+
For adding novel benchmarks/datasets to the library:
|
| 504 |
+
|
| 505 |
+
- [ ] Is the task an existing benchmark in the literature?
|
| 506 |
+
- [ ] Have you referenced the original paper that introduced the task?
|
| 507 |
+
- [ ] If yes, does the original paper provide a reference implementation? If so, have you checked against the reference implementation and documented how to run such a test?
|
| 508 |
+
|
| 509 |
+
If other tasks on this dataset are already supported:
|
| 510 |
+
|
| 511 |
+
- [ ] Is the "Main" variant of this task clearly denoted?
|
| 512 |
+
- [ ] Have you provided a short sentence in a README on what each new variant adds / evaluates?
|
| 513 |
+
- [ ] Have you noted which, if any, published evaluation setups are matched by this variant?
|
| 514 |
+
|
| 515 |
+
It is recommended to include a filled-out copy of this checklist in the README.md for the subfolder you are creating, if you have created a new subfolder in `lm_eval/tasks`.
|
| 516 |
+
|
| 517 |
+
**Finally, please add a short description of your task(s), along with a link to its subfolder in lm_eval/tasks, to [`lm_eval/tasks/README.md`](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/README.md) so that users can discover your task in the library, and follow the link to your README for more information about the variants supported, their task names, and the original source of the dataset and/or evaluation setup.**
|
| 518 |
+
|
| 519 |
+
## Submitting your task
|
| 520 |
+
|
| 521 |
+
You're all set! Now push your work and make a pull request to the `main` branch! Thanks for the contribution :). If there are any questions, please leave a message in the `#lm-thunderdome` channel on the EAI discord!
|
lm-evaluation-harness/docs/task_guide.md
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Task Configuration
|
| 2 |
+
|
| 3 |
+
The `lm-evaluation-harness` is meant to be an extensible and flexible framework within which many different evaluation tasks can be defined. All tasks in the new version of the harness are built around a YAML configuration file format.
|
| 4 |
+
|
| 5 |
+
These YAML configuration files, along with the current codebase commit hash, are intended to be shareable such that providing the YAML config enables another researcher to precisely replicate the evaluation setup used by another, in the case that the prompt or setup differs from standard `lm-eval` task implementations.
|
| 6 |
+
|
| 7 |
+
While adding a standard evaluation task on a new dataset can be occasionally as simple as swapping out a Hugging Face dataset path in an existing file, more specialized evaluation setups also exist. Here we'll provide a crash course on the more advanced logic implementable in YAML form available to users.
|
| 8 |
+
|
| 9 |
+
If your intended task relies on features beyond what is described in this guide, we'd love to hear about it! Feel free to open an issue describing the scenario on Github, create a PR to the project with a proposed implementation, or ask in the `#lm-thunderdome` channel on the EleutherAI discord.
|
| 10 |
+
|
| 11 |
+
## Configurations
|
| 12 |
+
|
| 13 |
+
Tasks are configured via the `TaskConfig` object. Below, we describe all fields usable within the object, and their role in defining a task.
|
| 14 |
+
|
| 15 |
+
### Parameters
|
| 16 |
+
|
| 17 |
+
Task naming + registration:
|
| 18 |
+
|
| 19 |
+
- **task** (`str`, defaults to None) — name of the task.
|
| 20 |
+
- **task_alias** (`str`, defaults to None) - Alias of the task name that will be printed in the final table results.
|
| 21 |
+
- **tag** (`str`, *optional*) — name of the task tags(s) a task belongs to. Enables one to run all tasks with a specified tag name at once.
|
| 22 |
+
|
| 23 |
+
Dataset configuration options:
|
| 24 |
+
|
| 25 |
+
- **dataset_path** (`str`) — The name of the dataset as listed by HF in the datasets Hub.
|
| 26 |
+
- **dataset_name** (`str`, *optional*, defaults to None) — The name of what HF calls a “data instance” or sub-task of the benchmark. If your task does not contain any data instances, just leave this to default to None. (If you're familiar with the HF `datasets.load_dataset` function, these are just the first 2 arguments to it.)
|
| 27 |
+
- **dataset_kwargs** (`dict`, *optional*) — Auxiliary arguments that `datasets.load_dataset` accepts. This can be used to specify arguments such as `data_files` or `data_dir` if you want to use local datafiles such as json or csv.
|
| 28 |
+
- **custom_dataset** (`Callable`, *optional) - A function that returns a `dict[str, datasets.Dataset]` (<split_name>, dataset) object. This can be used to load a dataset from a custom source or to preprocess the dataset in a way that is not supported by the `datasets` library. Will have access to `metadata` field if defined (from config and passed to TaskManager), and `model_args` from runtime (if using `evaluate`).
|
| 29 |
+
- **training_split** (`str`, *optional*) — Split in the dataset to use as the training split.
|
| 30 |
+
- **validation_split** (`str`, *optional*) — Split in the dataset to use as the validation split.
|
| 31 |
+
- **test_split** (`str`, *optional*) — Split in the dataset to use as the test split.
|
| 32 |
+
- **fewshot_split** (`str`, *optional*) — Split in the dataset to draw few-shot exemplars from. assert that this not None if num_fewshot > 0.
|
| 33 |
+
- **process_docs** (`Callable`, *optional*) — Optionally define a function to apply to each HF dataset split, to preprocess all documents before being fed into prompt template rendering or other evaluation steps. Can be used to rename dataset columns, or to process documents into a format closer to the expected format expected by a prompt template.
|
| 34 |
+
|
| 35 |
+
Prompting / in-context formatting options:
|
| 36 |
+
|
| 37 |
+
- **use_prompt** (`str`, *optional*) — Name of prompt in promptsource to use. if defined, will overwrite doc_to_text, doc_to_target, and doc_to_choice.
|
| 38 |
+
- **description** (`str`, *optional*) — An optional prepended Jinja2 template or string which will be prepended to the few-shot examples passed into the model, often describing the task or providing instructions to a model, such as `"The following are questions (with answers) about {{subject}}.\n\n"`. No delimiters or spacing are inserted between the description and the first few-shot example.
|
| 39 |
+
- **doc_to_text** (`Union[Callable, str]`, *optional*) — Jinja2 template, string, or function to process a sample into the appropriate input for the model.
|
| 40 |
+
- **doc_to_target** (`Union[Callable, str]`, *optional*) — Jinja2 template, string, or function to process a sample into the appropriate target output for the model. For multiple choice tasks, this should return an index into the answer choice list of the correct answer.
|
| 41 |
+
- **doc_to_choice** (`Union[Callable, str]`, *optional*) — Jinja2 template, string, or function to process a sample into a list of possible string choices for `multiple_choice` tasks. Left undefined for `generate_until` tasks.
|
| 42 |
+
- **fewshot_delimiter** (`str`, *optional*, defaults to "\n\n") — String to insert between few-shot examples.
|
| 43 |
+
- **target_delimiter** (`str`, *optional*, defaults to `" "`) — String to insert between input and target output for the datapoint being tested.
|
| 44 |
+
- **gen_prefix** (`str`, *optional*) — String to append after the <|assistant|> token. For example, if the task is to generate a question, the gen_prefix could be "The answer is: " to prompt the model to generate an answer to the question. If not using a chat template then this string will be appended to the end of the prompt.
|
| 45 |
+
|
| 46 |
+
Runtime configuration options:
|
| 47 |
+
|
| 48 |
+
- **num_fewshot** (`int`, *optional*, defaults to 0) — Number of few-shot examples before the input.
|
| 49 |
+
- **batch_size** (`int`, *optional*, defaults to 1) — Batch size.
|
| 50 |
+
|
| 51 |
+
Scoring details:
|
| 52 |
+
|
| 53 |
+
- **metric_list** (`str`, *optional*, defaults to None) — A list of metrics to use for evaluation. See docs for expected format.
|
| 54 |
+
- **output_type** (`str`, *optional*, defaults to "generate_until") — Selects the type of model output for the given task. Options are `generate_until`, `loglikelihood`, `loglikelihood_rolling`, and `multiple_choice`.
|
| 55 |
+
- **generation_kwargs** (`dict`, *optional*) — Auxiliary arguments for the `generate` function from HF transformers library. Advanced keyword arguments may not be supported for non-HF LM classes.
|
| 56 |
+
- **repeats** (`int`, *optional*, defaults to 1) — Number of repeated runs through model for each sample. Can be used for cases such as self-consistency.
|
| 57 |
+
- **filter_list** (`Union[str, list]`, *optional*) — List of filters to postprocess model outputs. See below for further detail on the filter API.
|
| 58 |
+
- **should_decontaminate** (`bool`, *optional*, defaults to False) - Whether to decontaminate or not.
|
| 59 |
+
- **doc_to_decontamination_query** (`str`, *optional*) — Query for decontamination if `should_decontaminate` is True. If `should_decontaminate` is True but `doc_to_decontamination_query` is `None`, `doc_to_decontamination_query` will follow `doc_to_text`.
|
| 60 |
+
|
| 61 |
+
Other:
|
| 62 |
+
|
| 63 |
+
- **metadata** (`dict`, *optional*) — An optional field where arbitrary metadata can be passed. Most tasks should include a `version` key in this field that is used to denote the version of the yaml config. Other special metadata keys are: `num_fewshot`, to override the printed `n-shot` table column for a task. Will also be passed to the `custom_dataset` function if defined.
|
| 64 |
+
|
| 65 |
+
## Filters
|
| 66 |
+
|
| 67 |
+
A key component of the `lm-evaluation-harness` library is the `Filter` object. In a typical evaluation run of the harness, we take the formatted inputs and run them through our LM, with the appropriate output type (greedy or free-form generation, or loglikelihood-based comparative scoring).
|
| 68 |
+
|
| 69 |
+
After getting scores or output text from our LM on each `Instance` or document in the dataset, we then need to feed these responses into a metric or scoring function to return scores to a user.
|
| 70 |
+
|
| 71 |
+
However, certain tasks may require more complex behavior than directly turning over model outputs to a metric function. For example, we may want to post-process our output text by truncating it or extracting a model's answer, we may want to ensemble over multiple "takes" on a different document, et cetera.
|
| 72 |
+
|
| 73 |
+
**Detailed Aside**:
|
| 74 |
+
We do such post-processing by operating on *responses*, which are stored after running an LM on an `Instance` from the task in `Instance.resps`.
|
| 75 |
+
|
| 76 |
+
`resps` is a `List[str]` for each instance, and we pass a `List[List[<expected return type from model>]]` to our filters that is a list of `[instance.resps for instance in instances]`.
|
| 77 |
+
|
| 78 |
+
Our filters, after completing a pipeline, must return a `List[<expected return type from model>]` which we then unpack and store each element of in `Instance.filtered_resps` for the corresponding instance. Thus, we take as input a list of returns from our model for each doc, and must return a return from our model *without it being wrapped in a list* for each doc.
|
| 79 |
+
**End Aside**
|
| 80 |
+
|
| 81 |
+
A full list of supported filter operations can be found in `lm_eval/filters/__init__.py`. Contributions of new filter types are welcome!
|
| 82 |
+
|
| 83 |
+
### Multiple Filter Pipelines
|
| 84 |
+
|
| 85 |
+
Tasks need not be limited to a single filter pipeline. We enable users to run multiple, distinct, filter pipelines on *the same model outputs* generated in one run on a task.
|
| 86 |
+
|
| 87 |
+
As a case study, let's look at an implementation of solving the Gsm8k math word problem benchmark in `lm_eval/tasks/gsm8k/gsm8k-cot-self-consistency.yaml`. Here, we are emulating the setup used by [Self-Consistency Improves Chain of Thought Prompting](https://arxiv.org/abs/2203.11171), in which evaluation is performed by generating N chain-of-thought outputs from a model via temperature-based sampling, then selecting the answers output by the model at the end of the chains of thought, then majority voting across all those numeric answers.
|
| 88 |
+
|
| 89 |
+
Within our YAML file:
|
| 90 |
+
|
| 91 |
+
```yaml
|
| 92 |
+
...
|
| 93 |
+
repeats: 64
|
| 94 |
+
filter_list:
|
| 95 |
+
- name: "score-first"
|
| 96 |
+
filter:
|
| 97 |
+
- function: "regex"
|
| 98 |
+
regex_pattern: "The answer is (\\-?[0-9\\.\\,]*[0-9]+)"
|
| 99 |
+
- function: "take_first"
|
| 100 |
+
- name: "maj@64"
|
| 101 |
+
filter:
|
| 102 |
+
- function: "regex"
|
| 103 |
+
regex_pattern: "The answer is (\\-?[0-9\\.\\,]*[0-9]+)"
|
| 104 |
+
- function: "majority_vote"
|
| 105 |
+
- function: "take_first"
|
| 106 |
+
- name: "maj@8"
|
| 107 |
+
filter:
|
| 108 |
+
- function: "take_first_k"
|
| 109 |
+
k: 8
|
| 110 |
+
- function: "regex"
|
| 111 |
+
regex_pattern: "The answer is (\\-?[0-9\\.\\,]*[0-9]+)"
|
| 112 |
+
- function: "majority_vote"
|
| 113 |
+
- function: "take_first"
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
We are able to provide multiple different filter pipelines, each with their own name and list of filters to apply in sequence.
|
| 117 |
+
|
| 118 |
+
Our first filter pipeline implements
|
| 119 |
+
|
| 120 |
+
- applying a regex to the model generations (extracting the number within the phrase "The answer is (number)")
|
| 121 |
+
- selecting only the first out of the 64 model answers
|
| 122 |
+
|
| 123 |
+
Then scoring this single answer.
|
| 124 |
+
|
| 125 |
+
```yaml
|
| 126 |
+
- name: "score-first"
|
| 127 |
+
filter:
|
| 128 |
+
- function: "regex"
|
| 129 |
+
regex_pattern: "The answer is (\\-?[0-9\\.\\,]*[0-9]+)"
|
| 130 |
+
- function: "take_first"
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
Our second filter pipeline, "maj@64", does majority voting across all 64 answers via:
|
| 134 |
+
|
| 135 |
+
- applying the same regex to all responses, to get the numerical answer from the model for each of the 64 responses per problem
|
| 136 |
+
- applying majority voting to all responses, which then returns a length-1 `[<majority answer>]` list for each
|
| 137 |
+
- taking the first element of this length-1 list, to then score the sole response `<majority answer>` for each document.
|
| 138 |
+
|
| 139 |
+
```yaml
|
| 140 |
+
- name: "maj@64"
|
| 141 |
+
filter:
|
| 142 |
+
- function: "regex"
|
| 143 |
+
regex_pattern: "The answer is (\\-?[0-9\\.\\,]*[0-9]+)"
|
| 144 |
+
- function: "majority_vote"
|
| 145 |
+
- function: "take_first"
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
Our final filter pipeline, "maj@8", does majority voting across the first 8 of the model's responses per document via:
|
| 149 |
+
|
| 150 |
+
- subsetting the len-64 list of responses `[answer1, answer2, ..., answer64]` to `[answer1, answer2, ..., answer8]` for each document
|
| 151 |
+
- performing the same sequence of filters on these new sets of 8 responses, for each document.
|
| 152 |
+
|
| 153 |
+
```yaml
|
| 154 |
+
- name: "maj@8"
|
| 155 |
+
filter:
|
| 156 |
+
- function: "take_first_k"
|
| 157 |
+
k: 8
|
| 158 |
+
- function: "regex"
|
| 159 |
+
regex_pattern: "The answer is (\\-?[0-9\\.\\,]*[0-9]+)"
|
| 160 |
+
- function: "majority_vote"
|
| 161 |
+
- function: "take_first"
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
Thus, given the 64 responses from our LM on each document, we can report metrics on these responses in these 3 different ways, as defined by our filter pipelines.
|
| 165 |
+
|
| 166 |
+
### Adding a custom filter
|
| 167 |
+
|
| 168 |
+
Just like adding a custom model with `register_model` decorator one is able to do the same with filters, for example
|
| 169 |
+
|
| 170 |
+
```python
|
| 171 |
+
from lm_eval.api.filter import Filter
|
| 172 |
+
from lm_eval.api.registry import register_filter
|
| 173 |
+
|
| 174 |
+
@register_filter("new_filter")
|
| 175 |
+
class NewFilter(Filter)
|
| 176 |
+
...
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
## Embedded Python Code
|
| 180 |
+
|
| 181 |
+
Use can use python functions for certain arguments by using the `!function` operator after the argument name followed by `<filename>.<pythonfunctionname>`. This feature can be used for the following arguments:
|
| 182 |
+
|
| 183 |
+
1. `doc_to_text`
|
| 184 |
+
2. `doc_to_target`
|
| 185 |
+
3. `doc_to_choice`
|
| 186 |
+
4. `aggregation` for a `metric` in `metric_list`
|
| 187 |
+
|
| 188 |
+
## (No Longer Recommended) Direct `Task` Subclassing
|
| 189 |
+
|
| 190 |
+
The prior implementation method of new tasks was to subclass `Task`. While we intend to migrate all tasks to the new YAML implementation option going forward, it remains possible to subclass the Task class and implement custom logic. For more information, see `docs/task_guide.md` in v0.3.0 of the `lm-evaluation-harness`.
|
| 191 |
+
|
| 192 |
+
## Including a Base YAML
|
| 193 |
+
|
| 194 |
+
You can base a YAML on another YAML file as a template. This can be handy when you need to just change the prompt for `doc_to_text` but keep the rest the same or change `filters` to compare which is better. Simply use `include` in the YAML file and write the name of the template you want to base from. This assumes that the base template is in the same directory. Otherwise, You will need to define the full path.
|
| 195 |
+
|
| 196 |
+
```yaml
|
| 197 |
+
include: <YAML filename or with full path>
|
| 198 |
+
...
|
| 199 |
+
```
|
| 200 |
+
|
| 201 |
+
You can find an example of how to use this feature at [gsm8k-cot-self-consistency.yaml](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/gsm8k/gsm8k-cot-self-consistency.yaml) where it is based off [gsm8k-cot.yaml](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/gsm8k/gsm8k-cot.yaml)
|
| 202 |
+
|
| 203 |
+
## Passing Arguments to Metrics
|
| 204 |
+
|
| 205 |
+
Metrics can be defined in the `metric_list` argument when building the YAML config. Multiple metrics can be listed along with any auxiliary arguments. For example, setting the [`exact_match` metric](https://github.com/huggingface/evaluate/tree/main/metrics/exact_match), auxiliary arguments such as `ignore_case`, `ignore_punctuation`, `regexes_to_ignore` can be listed as well. They will be added to the metric function as `kwargs`. Some metrics have predefined values for `aggregation` and `higher_is_better` so listing the metric name only can be sufficient.
|
| 206 |
+
|
| 207 |
+
```yaml
|
| 208 |
+
metric_list:
|
| 209 |
+
- metric: acc
|
| 210 |
+
- metric: exact_match
|
| 211 |
+
aggregation: mean
|
| 212 |
+
higher_is_better: true
|
| 213 |
+
ignore_case: true
|
| 214 |
+
ignore_punctuation: false
|
| 215 |
+
regexes_to_ignore:
|
| 216 |
+
- ","
|
| 217 |
+
- "\\$"
|
| 218 |
+
```
|
| 219 |
+
|
| 220 |
+
### Natively Supported Metrics
|
| 221 |
+
|
| 222 |
+
Here we list all metrics currently supported natively in `lm-eval`:
|
| 223 |
+
|
| 224 |
+
Metrics:
|
| 225 |
+
|
| 226 |
+
- `acc` (accuracy)
|
| 227 |
+
- `acc_norm` (length-normalized accuracy)
|
| 228 |
+
- `acc_mutual_info` (baseline loglikelihood - normalized accuracy)
|
| 229 |
+
- `perplexity`
|
| 230 |
+
- `word_perplexity` (perplexity per word)
|
| 231 |
+
- `byte_perplexity` (perplexity per byte)
|
| 232 |
+
- `bits_per_byte`
|
| 233 |
+
- `matthews_corrcoef` (Matthews correlation coefficient)
|
| 234 |
+
- `f1` (F1 score)
|
| 235 |
+
- `bleu`
|
| 236 |
+
- `chrf`
|
| 237 |
+
- `ter`
|
| 238 |
+
|
| 239 |
+
Aggregation functions:
|
| 240 |
+
|
| 241 |
+
- `mean`
|
| 242 |
+
- `median`
|
| 243 |
+
- `perplexity`
|
| 244 |
+
- `weighted_perplexity`
|
| 245 |
+
- `bits_per_byte`
|
| 246 |
+
|
| 247 |
+
### Adding a Multiple Choice Metric
|
| 248 |
+
|
| 249 |
+
Adding a multiple choice metric has a few steps. To get it working you need to:
|
| 250 |
+
|
| 251 |
+
1. register a metric function
|
| 252 |
+
2. register an aggregation function
|
| 253 |
+
3. update the `Task` definition to make sure the correct arguments are passed
|
| 254 |
+
|
| 255 |
+
The default metric and aggregation functions are in `lm_eval/api/metrics.py`, and you can add a function there if it's for general use. The metrics are towards the bottom of the file and look like this:
|
| 256 |
+
|
| 257 |
+
```python
|
| 258 |
+
@register_metric(
|
| 259 |
+
metric="mcc",
|
| 260 |
+
higher_is_better=True,
|
| 261 |
+
output_type="multiple_choice",
|
| 262 |
+
aggregation="matthews_corrcoef",
|
| 263 |
+
)
|
| 264 |
+
def mcc_fn(items): # This is a passthrough function
|
| 265 |
+
return items
|
| 266 |
+
```
|
| 267 |
+
|
| 268 |
+
Note that many of these are passthrough functions, and for multiple choice (at least) this function is never actually called.
|
| 269 |
+
|
| 270 |
+
Aggregation functions are defined towards the top of the file, here's an example:
|
| 271 |
+
|
| 272 |
+
```python
|
| 273 |
+
@register_aggregation("matthews_corrcoef")
|
| 274 |
+
def matthews_corrcoef(items):
|
| 275 |
+
unzipped_list = list(zip(*items))
|
| 276 |
+
golds = unzipped_list[0]
|
| 277 |
+
preds = unzipped_list[1]
|
| 278 |
+
return sklearn.metrics.matthews_corrcoef(golds, preds)
|
| 279 |
+
```
|
| 280 |
+
|
| 281 |
+
This function returns a single numeric value. The input is defined in `Task.process_results` in `lm_eval/api/task.py`. There's a section that looks like this:
|
| 282 |
+
|
| 283 |
+
```python
|
| 284 |
+
result_dict = {
|
| 285 |
+
**({"acc": acc} if "acc" in use_metric else {}),
|
| 286 |
+
**({"f1": (gold, pred)} if "f1" in use_metric else {}),
|
| 287 |
+
**({"mcc": (gold, pred)} if "mcc" in use_metric else {}),
|
| 288 |
+
**({"acc_norm": acc_norm} if "acc_norm" in use_metric else {}),
|
| 289 |
+
**({"exact_match": exact_match} if "exact_match" in use_metric else {}),
|
| 290 |
+
}
|
| 291 |
+
```
|
| 292 |
+
|
| 293 |
+
The value here determines the input to the aggregation function, though the name used matches the metric function. These metrics all have simple needs and just need the accuracy or gold and predicted values, but immediately below this there are examples of metrics with more complicated needs you can use as reference.
|
| 294 |
+
|
| 295 |
+
## Good Reference Tasks
|
| 296 |
+
|
| 297 |
+
Contributing a new task can be daunting! Luckily, much of the work has often been done for you in a different, similarly evaluated task. Good examples of task implementations to study include:
|
| 298 |
+
|
| 299 |
+
Multiple choice tasks:
|
| 300 |
+
|
| 301 |
+
- SciQ (`lm_eval/tasks/sciq/sciq.yaml`)
|
| 302 |
+
|
| 303 |
+
Corpus perplexity evaluations:
|
| 304 |
+
|
| 305 |
+
- Wikitext (`lm_eval/tasks/wikitext/wikitext.yaml`)
|
| 306 |
+
|
| 307 |
+
Generative tasks:
|
| 308 |
+
|
| 309 |
+
- GSM8k (`lm_eval/tasks/gsm8k/gsm8k.yaml`)
|
| 310 |
+
|
| 311 |
+
Tasks using complex filtering:
|
| 312 |
+
|
| 313 |
+
- GSM8k with CoT (+ with Self-Consistency): (`lm_eval/tasks/gsm8k/gsm8k-cot.yaml` ; `lm_eval/tasks/gsm8k/gsm8k-cot-self-consistency.yaml`)
|
| 314 |
+
|
| 315 |
+
# Group Configuration
|
| 316 |
+
|
| 317 |
+
When evaluating a language model, it is not unusual to test across a number of tasks that may not be related to one another in order to assess a variety of capabilities. To this end, it may be cumbersome to have to list the set of tasks or add a new group name to each yaml of each individual task.
|
| 318 |
+
|
| 319 |
+
To solve this, we can create a **group** yaml config. This is a config that contains the names of the tasks that should be included in a particular group. The config consists of two main keys: a `group` key which denotes the name of the group (as it would be called from the command line, e.g. `mmlu`) and a `task` key which is where we can list the tasks. The tasks listed in `task` are the task names that have been registered. A good example of a group yaml config can be found at [../lm_eval/tasks/mmlu/default/_mmlu.yaml]. See also the [New Task Guide](./new_task_guide.md) for a more in-depth and tutorial-esque explanation of how to write complex GroupConfigs.
|
| 320 |
+
|
| 321 |
+
## Configurations
|
| 322 |
+
|
| 323 |
+
Groups are configured via the `GroupConfig` object. Below, we describe all fields usable within the object, and their role in defining a task.
|
| 324 |
+
|
| 325 |
+
### Parameters
|
| 326 |
+
|
| 327 |
+
- **group** (`str`, defaults to `None`) — name of the group. Used to invoke it from the command line.
|
| 328 |
+
- **group_alias** (`str`, defaults to `None`) - Alternative name for the group that will be printed in the table output.
|
| 329 |
+
- **task** (`Union[str, list]`, defaults to `None`) - List of tasks that constitute the group.
|
| 330 |
+
- **aggregate_metric_list** (`list`, defaults to `None`) - similar to `metric_list` in TaskConfigs, provide a list of configurations for metrics that should be aggregated across subtasks. Leaving empty will result in no aggregation being performed for this group. Keys for each list entry are:
|
| 331 |
+
- `metric: str` - the name of the metric to aggregate over (all subtasks must report a metric holding this name.)
|
| 332 |
+
- `aggregation: str` - what aggregation function to apply to aggregate these per-subtask metrics. **currently, only `mean` is supported.**
|
| 333 |
+
- `weight_by_size: bool = True` whether to perform micro- averaging (`True`) or macro- (`False`) averaging of subtasks' accuracy scores when reporting the group's metric. MMLU, for example, averages over per-document accuracies (the *micro average*), resulting in the same accuracy as if one simply concatenated all 57 subjects into a single dataset and evaluated accuracy on that dataset.
|
| 334 |
+
- `filter_list: Union[str, List[str]] = "none"` - what filter keys one should match on to aggregate results. For example, if trying to aggregate over the `exact_match` metric using `strict-match` filter for `bbh_cot_zeroshot`, then set this to be `filter_list: "strict-match"`.
|
| 335 |
+
- **metadata** (`dict`, *optional*) - As with TaskConfigs, a field where extra config metadata can be passed. set the `num_fewshot` key within this to override the printed n_shot value in a results table for your group, for example.
|
lm-evaluation-harness/eval_base_qwen2_5_32b.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
lm-evaluation-harness/examples/lm-eval-overview.ipynb
ADDED
|
@@ -0,0 +1,1240 @@
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {
|
| 6 |
+
"id": "Qw83KAePAhaS"
|
| 7 |
+
},
|
| 8 |
+
"source": [
|
| 9 |
+
"# Releasing LM-Evaluation-Harness v0.4.0"
|
| 10 |
+
]
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"cell_type": "markdown",
|
| 14 |
+
"metadata": {
|
| 15 |
+
"id": "Z7k2vq1iAdqr"
|
| 16 |
+
},
|
| 17 |
+
"source": [
|
| 18 |
+
"With the vast amount of work done in the field today, it helps to have a tool that people can use easily to share their results and use to check others to ensure reported numbers are valid. The LM Evaluation Harness is one such tool the community has used extensively. We want to continue to support the community and with that in mind, we’re excited to announce a major update on the LM Evaluation Harness to further our goal for open and accessible AI research."
|
| 19 |
+
]
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"cell_type": "markdown",
|
| 23 |
+
"metadata": {
|
| 24 |
+
"id": "0gDoM0AJAvEc"
|
| 25 |
+
},
|
| 26 |
+
"source": [
|
| 27 |
+
"Our refactor stems from our desires to make the following believed best practices easier to carry out. \n",
|
| 28 |
+
"\n",
|
| 29 |
+
"1. Never copy results from other papers\n",
|
| 30 |
+
"2. Always share your exact prompts\n",
|
| 31 |
+
"3. Always provide model outputs\n",
|
| 32 |
+
"4. Qualitatively review a small batch of outputs before running evaluation jobs at scale\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"We also wanted to make the library a better experience to use and to contribute or design evaluations within. New features in the new release that serve this purpose include:\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"1. Faster Evaluation Runtimes (accelerated data-parallel inference with HF Transformers + Accelerate, and commonly used or faster inference libraries such as vLLM and Llama-CPP)\n",
|
| 37 |
+
"2. Easier addition and sharing of new tasks (YAML-based task config formats, allowing single-file sharing of custom tasks)\n",
|
| 38 |
+
"3. More configurability, for more advanced workflows and easier operation with modifying prompts\n",
|
| 39 |
+
"4. Better logging of data at runtime and post-hoc"
|
| 40 |
+
]
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "markdown",
|
| 44 |
+
"metadata": {
|
| 45 |
+
"id": "nnwsOpjda_YW"
|
| 46 |
+
},
|
| 47 |
+
"source": [
|
| 48 |
+
"In this notebook we will be going through a short tutorial on how things work."
|
| 49 |
+
]
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "markdown",
|
| 53 |
+
"metadata": {
|
| 54 |
+
"id": "zAov81vTbL2K"
|
| 55 |
+
},
|
| 56 |
+
"source": [
|
| 57 |
+
"## Install LM-Eval"
|
| 58 |
+
]
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"execution_count": 1,
|
| 63 |
+
"metadata": {
|
| 64 |
+
"colab": {
|
| 65 |
+
"base_uri": "https://localhost:8080/"
|
| 66 |
+
},
|
| 67 |
+
"id": "8hiosGzq_qZg",
|
| 68 |
+
"outputId": "6ab73e5e-1f54-417e-a388-07e0d870b132"
|
| 69 |
+
},
|
| 70 |
+
"outputs": [
|
| 71 |
+
{
|
| 72 |
+
"name": "stdout",
|
| 73 |
+
"output_type": "stream",
|
| 74 |
+
"text": [
|
| 75 |
+
"Collecting git+https://github.com/EleutherAI/lm-evaluation-harness.git@big-refactor\n",
|
| 76 |
+
" Cloning https://github.com/EleutherAI/lm-evaluation-harness.git (to revision big-refactor) to /tmp/pip-req-build-tnssql5s\n",
|
| 77 |
+
" Running command git clone --filter=blob:none --quiet https://github.com/EleutherAI/lm-evaluation-harness.git /tmp/pip-req-build-tnssql5s\n",
|
| 78 |
+
" Running command git checkout -b big-refactor --track origin/big-refactor\n",
|
| 79 |
+
" Switched to a new branch 'big-refactor'\n",
|
| 80 |
+
" Branch 'big-refactor' set up to track remote branch 'big-refactor' from 'origin'.\n",
|
| 81 |
+
" Resolved https://github.com/EleutherAI/lm-evaluation-harness.git to commit 42f486ee49b65926a444cb0620870a39a5b4b0a8\n",
|
| 82 |
+
" Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n",
|
| 83 |
+
" Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n",
|
| 84 |
+
" Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
|
| 85 |
+
"Collecting accelerate>=0.21.0 (from lm-eval==1.0.0)\n",
|
| 86 |
+
" Downloading accelerate-0.24.1-py3-none-any.whl (261 kB)\n",
|
| 87 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m261.4/261.4 kB\u001b[0m \u001b[31m4.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 88 |
+
"\u001b[?25hCollecting evaluate (from lm-eval==1.0.0)\n",
|
| 89 |
+
" Downloading evaluate-0.4.1-py3-none-any.whl (84 kB)\n",
|
| 90 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m84.1/84.1 kB\u001b[0m \u001b[31m5.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 91 |
+
"\u001b[?25hCollecting datasets>=2.0.0 (from lm-eval==1.0.0)\n",
|
| 92 |
+
" Downloading datasets-2.15.0-py3-none-any.whl (521 kB)\n",
|
| 93 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m521.2/521.2 kB\u001b[0m \u001b[31m9.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 94 |
+
"\u001b[?25hCollecting jsonlines (from lm-eval==1.0.0)\n",
|
| 95 |
+
" Downloading jsonlines-4.0.0-py3-none-any.whl (8.7 kB)\n",
|
| 96 |
+
"Requirement already satisfied: numexpr in /usr/local/lib/python3.10/dist-packages (from lm-eval==1.0.0) (2.8.7)\n",
|
| 97 |
+
"Collecting peft>=0.2.0 (from lm-eval==1.0.0)\n",
|
| 98 |
+
" Downloading peft-0.6.2-py3-none-any.whl (174 kB)\n",
|
| 99 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m174.7/174.7 kB\u001b[0m \u001b[31m7.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 100 |
+
"\u001b[?25hCollecting pybind11>=2.6.2 (from lm-eval==1.0.0)\n",
|
| 101 |
+
" Downloading pybind11-2.11.1-py3-none-any.whl (227 kB)\n",
|
| 102 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m227.7/227.7 kB\u001b[0m \u001b[31m12.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 103 |
+
"\u001b[?25hCollecting pytablewriter (from lm-eval==1.0.0)\n",
|
| 104 |
+
" Downloading pytablewriter-1.2.0-py3-none-any.whl (111 kB)\n",
|
| 105 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m111.1/111.1 kB\u001b[0m \u001b[31m8.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 106 |
+
"\u001b[?25hCollecting rouge-score>=0.0.4 (from lm-eval==1.0.0)\n",
|
| 107 |
+
" Downloading rouge_score-0.1.2.tar.gz (17 kB)\n",
|
| 108 |
+
" Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
|
| 109 |
+
"Collecting sacrebleu>=1.5.0 (from lm-eval==1.0.0)\n",
|
| 110 |
+
" Downloading sacrebleu-2.3.2-py3-none-any.whl (119 kB)\n",
|
| 111 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m119.7/119.7 kB\u001b[0m \u001b[31m8.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 112 |
+
"\u001b[?25hRequirement already satisfied: scikit-learn>=0.24.1 in /usr/local/lib/python3.10/dist-packages (from lm-eval==1.0.0) (1.2.2)\n",
|
| 113 |
+
"Collecting sqlitedict (from lm-eval==1.0.0)\n",
|
| 114 |
+
" Downloading sqlitedict-2.1.0.tar.gz (21 kB)\n",
|
| 115 |
+
" Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
|
| 116 |
+
"Requirement already satisfied: torch>=1.8 in /usr/local/lib/python3.10/dist-packages (from lm-eval==1.0.0) (2.1.0+cu118)\n",
|
| 117 |
+
"Collecting tqdm-multiprocess (from lm-eval==1.0.0)\n",
|
| 118 |
+
" Downloading tqdm_multiprocess-0.0.11-py3-none-any.whl (9.8 kB)\n",
|
| 119 |
+
"Requirement already satisfied: transformers>=4.1 in /usr/local/lib/python3.10/dist-packages (from lm-eval==1.0.0) (4.35.2)\n",
|
| 120 |
+
"Collecting zstandard (from lm-eval==1.0.0)\n",
|
| 121 |
+
" Downloading zstandard-0.22.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (5.4 MB)\n",
|
| 122 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m5.4/5.4 MB\u001b[0m \u001b[31m29.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 123 |
+
"\u001b[?25hRequirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.10/dist-packages (from accelerate>=0.21.0->lm-eval==1.0.0) (1.23.5)\n",
|
| 124 |
+
"Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from accelerate>=0.21.0->lm-eval==1.0.0) (23.2)\n",
|
| 125 |
+
"Requirement already satisfied: psutil in /usr/local/lib/python3.10/dist-packages (from accelerate>=0.21.0->lm-eval==1.0.0) (5.9.5)\n",
|
| 126 |
+
"Requirement already satisfied: pyyaml in /usr/local/lib/python3.10/dist-packages (from accelerate>=0.21.0->lm-eval==1.0.0) (6.0.1)\n",
|
| 127 |
+
"Requirement already satisfied: huggingface-hub in /usr/local/lib/python3.10/dist-packages (from accelerate>=0.21.0->lm-eval==1.0.0) (0.19.4)\n",
|
| 128 |
+
"Requirement already satisfied: pyarrow>=8.0.0 in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (9.0.0)\n",
|
| 129 |
+
"Collecting pyarrow-hotfix (from datasets>=2.0.0->lm-eval==1.0.0)\n",
|
| 130 |
+
" Downloading pyarrow_hotfix-0.6-py3-none-any.whl (7.9 kB)\n",
|
| 131 |
+
"Collecting dill<0.3.8,>=0.3.0 (from datasets>=2.0.0->lm-eval==1.0.0)\n",
|
| 132 |
+
" Downloading dill-0.3.7-py3-none-any.whl (115 kB)\n",
|
| 133 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m115.3/115.3 kB\u001b[0m \u001b[31m14.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 134 |
+
"\u001b[?25hRequirement already satisfied: pandas in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (1.5.3)\n",
|
| 135 |
+
"Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (2.31.0)\n",
|
| 136 |
+
"Requirement already satisfied: tqdm>=4.62.1 in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (4.66.1)\n",
|
| 137 |
+
"Requirement already satisfied: xxhash in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (3.4.1)\n",
|
| 138 |
+
"Collecting multiprocess (from datasets>=2.0.0->lm-eval==1.0.0)\n",
|
| 139 |
+
" Downloading multiprocess-0.70.15-py310-none-any.whl (134 kB)\n",
|
| 140 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m134.8/134.8 kB\u001b[0m \u001b[31m19.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 141 |
+
"\u001b[?25hRequirement already satisfied: fsspec[http]<=2023.10.0,>=2023.1.0 in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (2023.6.0)\n",
|
| 142 |
+
"Requirement already satisfied: aiohttp in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (3.8.6)\n",
|
| 143 |
+
"Collecting responses<0.19 (from evaluate->lm-eval==1.0.0)\n",
|
| 144 |
+
" Downloading responses-0.18.0-py3-none-any.whl (38 kB)\n",
|
| 145 |
+
"Requirement already satisfied: safetensors in /usr/local/lib/python3.10/dist-packages (from peft>=0.2.0->lm-eval==1.0.0) (0.4.0)\n",
|
| 146 |
+
"Requirement already satisfied: absl-py in /usr/local/lib/python3.10/dist-packages (from rouge-score>=0.0.4->lm-eval==1.0.0) (1.4.0)\n",
|
| 147 |
+
"Requirement already satisfied: nltk in /usr/local/lib/python3.10/dist-packages (from rouge-score>=0.0.4->lm-eval==1.0.0) (3.8.1)\n",
|
| 148 |
+
"Requirement already satisfied: six>=1.14.0 in /usr/local/lib/python3.10/dist-packages (from rouge-score>=0.0.4->lm-eval==1.0.0) (1.16.0)\n",
|
| 149 |
+
"Collecting portalocker (from sacrebleu>=1.5.0->lm-eval==1.0.0)\n",
|
| 150 |
+
" Downloading portalocker-2.8.2-py3-none-any.whl (17 kB)\n",
|
| 151 |
+
"Requirement already satisfied: regex in /usr/local/lib/python3.10/dist-packages (from sacrebleu>=1.5.0->lm-eval==1.0.0) (2023.6.3)\n",
|
| 152 |
+
"Requirement already satisfied: tabulate>=0.8.9 in /usr/local/lib/python3.10/dist-packages (from sacrebleu>=1.5.0->lm-eval==1.0.0) (0.9.0)\n",
|
| 153 |
+
"Collecting colorama (from sacrebleu>=1.5.0->lm-eval==1.0.0)\n",
|
| 154 |
+
" Downloading colorama-0.4.6-py2.py3-none-any.whl (25 kB)\n",
|
| 155 |
+
"Requirement already satisfied: lxml in /usr/local/lib/python3.10/dist-packages (from sacrebleu>=1.5.0->lm-eval==1.0.0) (4.9.3)\n",
|
| 156 |
+
"Requirement already satisfied: scipy>=1.3.2 in /usr/local/lib/python3.10/dist-packages (from scikit-learn>=0.24.1->lm-eval==1.0.0) (1.11.3)\n",
|
| 157 |
+
"Requirement already satisfied: joblib>=1.1.1 in /usr/local/lib/python3.10/dist-packages (from scikit-learn>=0.24.1->lm-eval==1.0.0) (1.3.2)\n",
|
| 158 |
+
"Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.10/dist-packages (from scikit-learn>=0.24.1->lm-eval==1.0.0) (3.2.0)\n",
|
| 159 |
+
"Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from torch>=1.8->lm-eval==1.0.0) (3.13.1)\n",
|
| 160 |
+
"Requirement already satisfied: typing-extensions in /usr/local/lib/python3.10/dist-packages (from torch>=1.8->lm-eval==1.0.0) (4.5.0)\n",
|
| 161 |
+
"Requirement already satisfied: sympy in /usr/local/lib/python3.10/dist-packages (from torch>=1.8->lm-eval==1.0.0) (1.12)\n",
|
| 162 |
+
"Requirement already satisfied: networkx in /usr/local/lib/python3.10/dist-packages (from torch>=1.8->lm-eval==1.0.0) (3.2.1)\n",
|
| 163 |
+
"Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8->lm-eval==1.0.0) (3.1.2)\n",
|
| 164 |
+
"Requirement already satisfied: triton==2.1.0 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8->lm-eval==1.0.0) (2.1.0)\n",
|
| 165 |
+
"Requirement already satisfied: tokenizers<0.19,>=0.14 in /usr/local/lib/python3.10/dist-packages (from transformers>=4.1->lm-eval==1.0.0) (0.15.0)\n",
|
| 166 |
+
"Requirement already satisfied: attrs>=19.2.0 in /usr/local/lib/python3.10/dist-packages (from jsonlines->lm-eval==1.0.0) (23.1.0)\n",
|
| 167 |
+
"Requirement already satisfied: setuptools>=38.3.0 in /usr/local/lib/python3.10/dist-packages (from pytablewriter->lm-eval==1.0.0) (67.7.2)\n",
|
| 168 |
+
"Collecting DataProperty<2,>=1.0.1 (from pytablewriter->lm-eval==1.0.0)\n",
|
| 169 |
+
" Downloading DataProperty-1.0.1-py3-none-any.whl (27 kB)\n",
|
| 170 |
+
"Collecting mbstrdecoder<2,>=1.0.0 (from pytablewriter->lm-eval==1.0.0)\n",
|
| 171 |
+
" Downloading mbstrdecoder-1.1.3-py3-none-any.whl (7.8 kB)\n",
|
| 172 |
+
"Collecting pathvalidate<4,>=2.3.0 (from pytablewriter->lm-eval==1.0.0)\n",
|
| 173 |
+
" Downloading pathvalidate-3.2.0-py3-none-any.whl (23 kB)\n",
|
| 174 |
+
"Collecting tabledata<2,>=1.3.1 (from pytablewriter->lm-eval==1.0.0)\n",
|
| 175 |
+
" Downloading tabledata-1.3.3-py3-none-any.whl (11 kB)\n",
|
| 176 |
+
"Collecting tcolorpy<1,>=0.0.5 (from pytablewriter->lm-eval==1.0.0)\n",
|
| 177 |
+
" Downloading tcolorpy-0.1.4-py3-none-any.whl (7.9 kB)\n",
|
| 178 |
+
"Collecting typepy[datetime]<2,>=1.3.2 (from pytablewriter->lm-eval==1.0.0)\n",
|
| 179 |
+
" Downloading typepy-1.3.2-py3-none-any.whl (31 kB)\n",
|
| 180 |
+
"Requirement already satisfied: charset-normalizer<4.0,>=2.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets>=2.0.0->lm-eval==1.0.0) (3.3.2)\n",
|
| 181 |
+
"Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets>=2.0.0->lm-eval==1.0.0) (6.0.4)\n",
|
| 182 |
+
"Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets>=2.0.0->lm-eval==1.0.0) (4.0.3)\n",
|
| 183 |
+
"Requirement already satisfied: yarl<2.0,>=1.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets>=2.0.0->lm-eval==1.0.0) (1.9.2)\n",
|
| 184 |
+
"Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets>=2.0.0->lm-eval==1.0.0) (1.4.0)\n",
|
| 185 |
+
"Requirement already satisfied: aiosignal>=1.1.2 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets>=2.0.0->lm-eval==1.0.0) (1.3.1)\n",
|
| 186 |
+
"Requirement already satisfied: chardet<6,>=3.0.4 in /usr/local/lib/python3.10/dist-packages (from mbstrdecoder<2,>=1.0.0->pytablewriter->lm-eval==1.0.0) (5.2.0)\n",
|
| 187 |
+
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->datasets>=2.0.0->lm-eval==1.0.0) (3.4)\n",
|
| 188 |
+
"Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->datasets>=2.0.0->lm-eval==1.0.0) (2.0.7)\n",
|
| 189 |
+
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->datasets>=2.0.0->lm-eval==1.0.0) (2023.7.22)\n",
|
| 190 |
+
"Requirement already satisfied: python-dateutil<3.0.0,>=2.8.0 in /usr/local/lib/python3.10/dist-packages (from typepy[datetime]<2,>=1.3.2->pytablewriter->lm-eval==1.0.0) (2.8.2)\n",
|
| 191 |
+
"Requirement already satisfied: pytz>=2018.9 in /usr/local/lib/python3.10/dist-packages (from typepy[datetime]<2,>=1.3.2->pytablewriter->lm-eval==1.0.0) (2023.3.post1)\n",
|
| 192 |
+
"Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch>=1.8->lm-eval==1.0.0) (2.1.3)\n",
|
| 193 |
+
"Requirement already satisfied: click in /usr/local/lib/python3.10/dist-packages (from nltk->rouge-score>=0.0.4->lm-eval==1.0.0) (8.1.7)\n",
|
| 194 |
+
"Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.10/dist-packages (from sympy->torch>=1.8->lm-eval==1.0.0) (1.3.0)\n",
|
| 195 |
+
"Building wheels for collected packages: lm-eval, rouge-score, sqlitedict\n",
|
| 196 |
+
" Building wheel for lm-eval (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
|
| 197 |
+
" Created wheel for lm-eval: filename=lm_eval-1.0.0-py3-none-any.whl size=994254 sha256=88356155b19f2891981ecef948326ad6ce8ca40a6009378410ec20d0e225995a\n",
|
| 198 |
+
" Stored in directory: /tmp/pip-ephem-wheel-cache-9v6ye7h3/wheels/17/01/26/599c0779e9858a70a73fa8a306699b5b9a868f820c225457b0\n",
|
| 199 |
+
" Building wheel for rouge-score (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
|
| 200 |
+
" Created wheel for rouge-score: filename=rouge_score-0.1.2-py3-none-any.whl size=24933 sha256=6bb0d44e4881972c43ce194e7cb65233d309758cb15f0dec54590d3d2efcfc36\n",
|
| 201 |
+
" Stored in directory: /root/.cache/pip/wheels/5f/dd/89/461065a73be61a532ff8599a28e9beef17985c9e9c31e541b4\n",
|
| 202 |
+
" Building wheel for sqlitedict (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
|
| 203 |
+
" Created wheel for sqlitedict: filename=sqlitedict-2.1.0-py3-none-any.whl size=16863 sha256=5747f7dd73ddf3d8fbcebf51b5e4f718fabe1e94bccdf16d2f22a2e65ee7fdf4\n",
|
| 204 |
+
" Stored in directory: /root/.cache/pip/wheels/79/d6/e7/304e0e6cb2221022c26d8161f7c23cd4f259a9e41e8bbcfabd\n",
|
| 205 |
+
"Successfully built lm-eval rouge-score sqlitedict\n",
|
| 206 |
+
"Installing collected packages: sqlitedict, zstandard, tcolorpy, pybind11, pyarrow-hotfix, portalocker, pathvalidate, mbstrdecoder, jsonlines, dill, colorama, typepy, tqdm-multiprocess, sacrebleu, rouge-score, responses, multiprocess, accelerate, datasets, DataProperty, tabledata, peft, evaluate, pytablewriter, lm-eval\n",
|
| 207 |
+
"Successfully installed DataProperty-1.0.1 accelerate-0.24.1 colorama-0.4.6 datasets-2.15.0 dill-0.3.7 evaluate-0.4.1 jsonlines-4.0.0 lm-eval-1.0.0 mbstrdecoder-1.1.3 multiprocess-0.70.15 pathvalidate-3.2.0 peft-0.6.2 portalocker-2.8.2 pyarrow-hotfix-0.6 pybind11-2.11.1 pytablewriter-1.2.0 responses-0.18.0 rouge-score-0.1.2 sacrebleu-2.3.2 sqlitedict-2.1.0 tabledata-1.3.3 tcolorpy-0.1.4 tqdm-multiprocess-0.0.11 typepy-1.3.2 zstandard-0.22.0\n"
|
| 208 |
+
]
|
| 209 |
+
}
|
| 210 |
+
],
|
| 211 |
+
"source": [
|
| 212 |
+
"# Install LM-Eval\n",
|
| 213 |
+
"!pip install git+https://github.com/EleutherAI/lm-evaluation-harness.git"
|
| 214 |
+
]
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"cell_type": "code",
|
| 218 |
+
"execution_count": 2,
|
| 219 |
+
"metadata": {
|
| 220 |
+
"colab": {
|
| 221 |
+
"base_uri": "https://localhost:8080/",
|
| 222 |
+
"height": 0,
|
| 223 |
+
"referenced_widgets": [
|
| 224 |
+
"a1d3a8aa016544a78e8821c8f6199e06",
|
| 225 |
+
"f61ed33fad754146bdd2ac9db1ba1c48",
|
| 226 |
+
"bfa0af6aeff344c6845e1080a878e92e",
|
| 227 |
+
"fd1ad9e0367d4004aae853b91c3a7617",
|
| 228 |
+
"6b2d90209ec14230b3d58a74ac9b83bf",
|
| 229 |
+
"a73f357065d34d7baf0453ae4a8d75e2",
|
| 230 |
+
"46f521b73fd943c081c648fd873ebc0a",
|
| 231 |
+
"7c5689bc13684db8a22681f41863dddd",
|
| 232 |
+
"48763b6233374554ae76035c0483066f",
|
| 233 |
+
"4986a21eb560448fa79f4b25cde48951",
|
| 234 |
+
"aed3acd2f2d74003b44079c333a0698e"
|
| 235 |
+
]
|
| 236 |
+
},
|
| 237 |
+
"id": "uyO5MaKkZyah",
|
| 238 |
+
"outputId": "d46e8096-5086-4e49-967e-ea33d4a2a335"
|
| 239 |
+
},
|
| 240 |
+
"outputs": [
|
| 241 |
+
{
|
| 242 |
+
"data": {
|
| 243 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 244 |
+
"model_id": "a1d3a8aa016544a78e8821c8f6199e06",
|
| 245 |
+
"version_major": 2,
|
| 246 |
+
"version_minor": 0
|
| 247 |
+
},
|
| 248 |
+
"text/plain": [
|
| 249 |
+
"Downloading builder script: 0%| | 0.00/5.67k [00:00<?, ?B/s]"
|
| 250 |
+
]
|
| 251 |
+
},
|
| 252 |
+
"metadata": {},
|
| 253 |
+
"output_type": "display_data"
|
| 254 |
+
}
|
| 255 |
+
],
|
| 256 |
+
"source": []
|
| 257 |
+
},
|
| 258 |
+
{
|
| 259 |
+
"cell_type": "markdown",
|
| 260 |
+
"metadata": {
|
| 261 |
+
"id": "8rfUeX6n_wkK"
|
| 262 |
+
},
|
| 263 |
+
"source": [
|
| 264 |
+
"## Create new evaluation tasks with config-based tasks\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"Even within the same task, many works have reported numbers based on different choices of evaluation. Some report on the test sets, validation sets, or even subset of the training sets. Others have specialized prompts and verbalizers. We introduce YAMLs to allow users to easily make different variations. By leveraging the YAML configs to configure evaluations, the refactored LM-Eval takes the methods of the `Task` object and makes them configurable by setting the appropriate attributes in the config file. There, users can set the tasks they want by setting the name of the HF dataset (local tasks are also possible), the dataset splits used, and much more. Key configurations relating to prompting, such as `doc_to_text`, previously implemented as a method of the same name, are now configurable with jinja2 to allow high-level scripting to transform a HF dataset to text string as input to the model.\n",
|
| 267 |
+
"\n"
|
| 268 |
+
]
|
| 269 |
+
},
|
| 270 |
+
{
|
| 271 |
+
"cell_type": "markdown",
|
| 272 |
+
"metadata": {
|
| 273 |
+
"id": "HYFUhhfOSJKe"
|
| 274 |
+
},
|
| 275 |
+
"source": [
|
| 276 |
+
"A core-feature to LM-Eval is to configure tasks with YAML configs. With configs, you can fill preset fields to easily set up a task.\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"Here, we write a demo YAML config for a multiple-choice evaluation of BoolQ:"
|
| 279 |
+
]
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
"cell_type": "code",
|
| 283 |
+
"execution_count": 3,
|
| 284 |
+
"metadata": {
|
| 285 |
+
"id": "bg3dGROW-V39"
|
| 286 |
+
},
|
| 287 |
+
"outputs": [],
|
| 288 |
+
"source": [
|
| 289 |
+
"YAML_boolq_string = \"\"\"\n",
|
| 290 |
+
"task: demo_boolq\n",
|
| 291 |
+
"dataset_path: super_glue\n",
|
| 292 |
+
"dataset_name: boolq\n",
|
| 293 |
+
"output_type: multiple_choice\n",
|
| 294 |
+
"training_split: train\n",
|
| 295 |
+
"validation_split: validation\n",
|
| 296 |
+
"doc_to_text: \"{{passage}}\\nQuestion: {{question}}?\\nAnswer:\"\n",
|
| 297 |
+
"doc_to_target: label\n",
|
| 298 |
+
"doc_to_choice: [\"no\", \"yes\"]\n",
|
| 299 |
+
"should_decontaminate: true\n",
|
| 300 |
+
"doc_to_decontamination_query: passage\n",
|
| 301 |
+
"metric_list:\n",
|
| 302 |
+
" - metric: acc\n",
|
| 303 |
+
"\"\"\"\n",
|
| 304 |
+
"with open(\"boolq.yaml\", \"w\") as f:\n",
|
| 305 |
+
" f.write(YAML_boolq_string)"
|
| 306 |
+
]
|
| 307 |
+
},
|
| 308 |
+
{
|
| 309 |
+
"cell_type": "markdown",
|
| 310 |
+
"metadata": {},
|
| 311 |
+
"source": [
|
| 312 |
+
"And we can now run evaluation on this task, by pointing to the config file we've just created:"
|
| 313 |
+
]
|
| 314 |
+
},
|
| 315 |
+
{
|
| 316 |
+
"cell_type": "code",
|
| 317 |
+
"execution_count": 4,
|
| 318 |
+
"metadata": {
|
| 319 |
+
"id": "LOUHK7PtQfq4"
|
| 320 |
+
},
|
| 321 |
+
"outputs": [
|
| 322 |
+
{
|
| 323 |
+
"name": "stdout",
|
| 324 |
+
"output_type": "stream",
|
| 325 |
+
"text": [
|
| 326 |
+
"2023-11-29:11:54:55,156 INFO [utils.py:160] NumExpr defaulting to 2 threads.\n",
|
| 327 |
+
"2023-11-29 11:54:55.942051: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
|
| 328 |
+
"2023-11-29 11:54:55.942108: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
|
| 329 |
+
"2023-11-29 11:54:55.942142: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
|
| 330 |
+
"2023-11-29 11:54:57.066802: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
|
| 331 |
+
"2023-11-29:11:55:00,954 INFO [__main__.py:132] Verbosity set to INFO\n",
|
| 332 |
+
"2023-11-29:11:55:11,038 WARNING [__main__.py:138] --limit SHOULD ONLY BE USED FOR TESTING.REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.\n",
|
| 333 |
+
"2023-11-29:11:55:11,038 INFO [__main__.py:143] Including path: ./\n",
|
| 334 |
+
"2023-11-29:11:55:11,046 INFO [__main__.py:205] Selected Tasks: ['demo_boolq']\n",
|
| 335 |
+
"2023-11-29:11:55:11,047 WARNING [evaluator.py:93] generation_kwargs specified through cli, these settings will be used over set parameters in yaml tasks.\n",
|
| 336 |
+
"2023-11-29:11:55:11,110 INFO [huggingface.py:120] Using device 'cuda'\n",
|
| 337 |
+
"config.json: 100% 571/571 [00:00<00:00, 2.87MB/s]\n",
|
| 338 |
+
"model.safetensors: 100% 5.68G/5.68G [00:32<00:00, 173MB/s]\n",
|
| 339 |
+
"tokenizer_config.json: 100% 396/396 [00:00<00:00, 2.06MB/s]\n",
|
| 340 |
+
"tokenizer.json: 100% 2.11M/2.11M [00:00<00:00, 11.6MB/s]\n",
|
| 341 |
+
"special_tokens_map.json: 100% 99.0/99.0 [00:00<00:00, 555kB/s]\n",
|
| 342 |
+
"2023-11-29:11:56:18,658 WARNING [task.py:614] [Task: demo_boolq] metric acc is defined, but aggregation is not. using default aggregation=mean\n",
|
| 343 |
+
"2023-11-29:11:56:18,658 WARNING [task.py:626] [Task: demo_boolq] metric acc is defined, but higher_is_better is not. using default higher_is_better=True\n",
|
| 344 |
+
"Downloading builder script: 100% 30.7k/30.7k [00:00<00:00, 59.0MB/s]\n",
|
| 345 |
+
"Downloading metadata: 100% 38.7k/38.7k [00:00<00:00, 651kB/s]\n",
|
| 346 |
+
"Downloading readme: 100% 14.8k/14.8k [00:00<00:00, 37.3MB/s]\n",
|
| 347 |
+
"Downloading data: 100% 4.12M/4.12M [00:00<00:00, 55.1MB/s]\n",
|
| 348 |
+
"Generating train split: 100% 9427/9427 [00:00<00:00, 15630.89 examples/s]\n",
|
| 349 |
+
"Generating validation split: 100% 3270/3270 [00:00<00:00, 20002.56 examples/s]\n",
|
| 350 |
+
"Generating test split: 100% 3245/3245 [00:00<00:00, 20866.19 examples/s]\n",
|
| 351 |
+
"2023-11-29:11:56:22,315 INFO [task.py:355] Building contexts for task on rank 0...\n",
|
| 352 |
+
"2023-11-29:11:56:22,322 INFO [evaluator.py:319] Running loglikelihood requests\n",
|
| 353 |
+
"100% 20/20 [00:04<00:00, 4.37it/s]\n",
|
| 354 |
+
"fatal: not a git repository (or any of the parent directories): .git\n",
|
| 355 |
+
"hf (pretrained=EleutherAI/pythia-2.8b), gen_kwargs: (), limit: 10.0, num_fewshot: None, batch_size: 1\n",
|
| 356 |
+
"| Tasks |Version|Filter|n-shot|Metric|Value| |Stderr|\n",
|
| 357 |
+
"|----------|-------|------|-----:|------|----:|---|-----:|\n",
|
| 358 |
+
"|demo_boolq|Yaml |none | 0|acc | 1|± | 0|\n",
|
| 359 |
+
"\n"
|
| 360 |
+
]
|
| 361 |
+
}
|
| 362 |
+
],
|
| 363 |
+
"source": [
|
| 364 |
+
"%env LOGLEVEL=DEBUG\n",
|
| 365 |
+
"!lm_eval \\\n",
|
| 366 |
+
" --model hf \\\n",
|
| 367 |
+
" --model_args pretrained=EleutherAI/pythia-2.8b \\\n",
|
| 368 |
+
" --include_path ./ \\\n",
|
| 369 |
+
" --tasks demo_boolq \\\n",
|
| 370 |
+
" --limit 10"
|
| 371 |
+
]
|
| 372 |
+
},
|
| 373 |
+
{
|
| 374 |
+
"cell_type": "markdown",
|
| 375 |
+
"metadata": {
|
| 376 |
+
"id": "LOUHK7PtQfq4"
|
| 377 |
+
},
|
| 378 |
+
"source": [
|
| 379 |
+
"Often, tasks are part of a larger group used to measure different capabilities. The dynamism of the field today means new dimensions of evaluation can come about which would mix and match new and older tasks alike. In LM-Eval, We can also group tasks and call that the group name to evaluate on a set of tasks easily. In this instance, let's evaluate the tag `yes_or_no_tasks` which comprise of the tasks `demo_boolq` and `demo_cola`; tasks which are multiple choice tasks with options `yes` and `no` as the name suggests.\n",
|
| 380 |
+
"\n",
|
| 381 |
+
"<!-- making new groups is easier than ever, allowing user to work bottom-up by makiing individual tasks and linking them to a group or Top-Down, making a new group by listing existing tasks.\n",
|
| 382 |
+
"\n",
|
| 383 |
+
"We also show the aggregate across samples besides only showing the aggregation between subtasks. This may come in handy when certain groups want to be aggregated as a single task. -->\n",
|
| 384 |
+
"\n",
|
| 385 |
+
"\n"
|
| 386 |
+
]
|
| 387 |
+
},
|
| 388 |
+
{
|
| 389 |
+
"cell_type": "code",
|
| 390 |
+
"execution_count": 5,
|
| 391 |
+
"metadata": {
|
| 392 |
+
"id": "fthNg3ywO-kA"
|
| 393 |
+
},
|
| 394 |
+
"outputs": [],
|
| 395 |
+
"source": [
|
| 396 |
+
"YAML_cola_string = \"\"\"\n",
|
| 397 |
+
"tag: yes_or_no_tasks\n",
|
| 398 |
+
"task: demo_cola\n",
|
| 399 |
+
"dataset_path: glue\n",
|
| 400 |
+
"dataset_name: cola\n",
|
| 401 |
+
"output_type: multiple_choice\n",
|
| 402 |
+
"training_split: train\n",
|
| 403 |
+
"validation_split: validation\n",
|
| 404 |
+
"doc_to_text: \"{{sentence}}\\nQuestion: Does this sentence make sense?\\nAnswer:\"\n",
|
| 405 |
+
"doc_to_target: label\n",
|
| 406 |
+
"doc_to_choice: [\"no\", \"yes\"]\n",
|
| 407 |
+
"should_decontaminate: true\n",
|
| 408 |
+
"doc_to_decontamination_query: sentence\n",
|
| 409 |
+
"metric_list:\n",
|
| 410 |
+
" - metric: acc\n",
|
| 411 |
+
"\"\"\"\n",
|
| 412 |
+
"with open(\"cola.yaml\", \"w\") as f:\n",
|
| 413 |
+
" f.write(YAML_cola_string)"
|
| 414 |
+
]
|
| 415 |
+
},
|
| 416 |
+
{
|
| 417 |
+
"cell_type": "code",
|
| 418 |
+
"execution_count": 6,
|
| 419 |
+
"metadata": {
|
| 420 |
+
"id": "XceRKCuuDtbn"
|
| 421 |
+
},
|
| 422 |
+
"outputs": [
|
| 423 |
+
{
|
| 424 |
+
"name": "stdout",
|
| 425 |
+
"output_type": "stream",
|
| 426 |
+
"text": [
|
| 427 |
+
"2023-11-29:11:56:33,016 INFO [utils.py:160] NumExpr defaulting to 2 threads.\n",
|
| 428 |
+
"2023-11-29 11:56:33.852995: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
|
| 429 |
+
"2023-11-29 11:56:33.853050: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
|
| 430 |
+
"2023-11-29 11:56:33.853087: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
|
| 431 |
+
"2023-11-29 11:56:35.129047: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
|
| 432 |
+
"2023-11-29:11:56:38,546 INFO [__main__.py:132] Verbosity set to INFO\n",
|
| 433 |
+
"2023-11-29:11:56:47,509 WARNING [__main__.py:138] --limit SHOULD ONLY BE USED FOR TESTING.REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.\n",
|
| 434 |
+
"2023-11-29:11:56:47,509 INFO [__main__.py:143] Including path: ./\n",
|
| 435 |
+
"2023-11-29:11:56:47,517 INFO [__main__.py:205] Selected Tasks: ['yes_or_no_tasks']\n",
|
| 436 |
+
"2023-11-29:11:56:47,520 WARNING [evaluator.py:93] generation_kwargs specified through cli, these settings will be used over set parameters in yaml tasks.\n",
|
| 437 |
+
"2023-11-29:11:56:47,550 INFO [huggingface.py:120] Using device 'cuda'\n",
|
| 438 |
+
"2023-11-29:11:57:08,743 WARNING [task.py:614] [Task: demo_cola] metric acc is defined, but aggregation is not. using default aggregation=mean\n",
|
| 439 |
+
"2023-11-29:11:57:08,743 WARNING [task.py:626] [Task: demo_cola] metric acc is defined, but higher_is_better is not. using default higher_is_better=True\n",
|
| 440 |
+
"Downloading builder script: 100% 28.8k/28.8k [00:00<00:00, 52.7MB/s]\n",
|
| 441 |
+
"Downloading metadata: 100% 28.7k/28.7k [00:00<00:00, 51.9MB/s]\n",
|
| 442 |
+
"Downloading readme: 100% 27.9k/27.9k [00:00<00:00, 48.0MB/s]\n",
|
| 443 |
+
"Downloading data: 100% 377k/377k [00:00<00:00, 12.0MB/s]\n",
|
| 444 |
+
"Generating train split: 100% 8551/8551 [00:00<00:00, 19744.58 examples/s]\n",
|
| 445 |
+
"Generating validation split: 100% 1043/1043 [00:00<00:00, 27057.01 examples/s]\n",
|
| 446 |
+
"Generating test split: 100% 1063/1063 [00:00<00:00, 22705.17 examples/s]\n",
|
| 447 |
+
"2023-11-29:11:57:11,698 INFO [task.py:355] Building contexts for task on rank 0...\n",
|
| 448 |
+
"2023-11-29:11:57:11,704 INFO [evaluator.py:319] Running loglikelihood requests\n",
|
| 449 |
+
"100% 20/20 [00:03<00:00, 5.15it/s]\n",
|
| 450 |
+
"fatal: not a git repository (or any of the parent directories): .git\n",
|
| 451 |
+
"hf (pretrained=EleutherAI/pythia-2.8b), gen_kwargs: (), limit: 10.0, num_fewshot: None, batch_size: 1\n",
|
| 452 |
+
"| Tasks |Version|Filter|n-shot|Metric|Value| |Stderr|\n",
|
| 453 |
+
"|---------------|-------|------|-----:|------|----:|---|-----:|\n",
|
| 454 |
+
"|yes_or_no_tasks|N/A |none | 0|acc | 0.7|± |0.1528|\n",
|
| 455 |
+
"| - demo_cola |Yaml |none | 0|acc | 0.7|± |0.1528|\n",
|
| 456 |
+
"\n",
|
| 457 |
+
"| Groups |Version|Filter|n-shot|Metric|Value| |Stderr|\n",
|
| 458 |
+
"|---------------|-------|------|-----:|------|----:|---|-----:|\n",
|
| 459 |
+
"|yes_or_no_tasks|N/A |none | 0|acc | 0.7|± |0.1528|\n",
|
| 460 |
+
"\n"
|
| 461 |
+
]
|
| 462 |
+
}
|
| 463 |
+
],
|
| 464 |
+
"source": [
|
| 465 |
+
"# !accelerate launch --no_python\n",
|
| 466 |
+
"%env LOGLEVEL=DEBUG\n",
|
| 467 |
+
"!lm_eval \\\n",
|
| 468 |
+
" --model hf \\\n",
|
| 469 |
+
" --model_args pretrained=EleutherAI/pythia-2.8b \\\n",
|
| 470 |
+
" --include_path ./ \\\n",
|
| 471 |
+
" --tasks yes_or_no_tasks \\\n",
|
| 472 |
+
" --limit 10 \\\n",
|
| 473 |
+
" --output output/yes_or_no_tasks/ \\\n",
|
| 474 |
+
" --log_samples"
|
| 475 |
+
]
|
| 476 |
+
},
|
| 477 |
+
{
|
| 478 |
+
"cell_type": "markdown",
|
| 479 |
+
"metadata": {
|
| 480 |
+
"id": "XceRKCuuDtbn"
|
| 481 |
+
},
|
| 482 |
+
"source": [
|
| 483 |
+
"## Edit Prompt Templates Quickly\n",
|
| 484 |
+
"\n",
|
| 485 |
+
"The following is a yaml made to evaluate the specific subtask of `high_school_geography` from MMLU. It uses the standard prompt where the we choose the letters from the options with most likelihood as the model's prediction."
|
| 486 |
+
]
|
| 487 |
+
},
|
| 488 |
+
{
|
| 489 |
+
"cell_type": "code",
|
| 490 |
+
"execution_count": 7,
|
| 491 |
+
"metadata": {
|
| 492 |
+
"id": "GTFvdt9kSlBG"
|
| 493 |
+
},
|
| 494 |
+
"outputs": [],
|
| 495 |
+
"source": [
|
| 496 |
+
"YAML_mmlu_geo_string = \"\"\"\n",
|
| 497 |
+
"task: demo_mmlu_high_school_geography\n",
|
| 498 |
+
"dataset_path: cais/mmlu\n",
|
| 499 |
+
"dataset_name: high_school_geography\n",
|
| 500 |
+
"description: \"The following are multiple choice questions (with answers) about high school geography.\\n\\n\"\n",
|
| 501 |
+
"test_split: test\n",
|
| 502 |
+
"fewshot_split: dev\n",
|
| 503 |
+
"fewshot_config:\n",
|
| 504 |
+
" sampler: first_n\n",
|
| 505 |
+
"output_type: multiple_choice\n",
|
| 506 |
+
"doc_to_text: \"{{question.strip()}}\\nA. {{choices[0]}}\\nB. {{choices[1]}}\\nC. {{choices[2]}}\\nD. {{choices[3]}}\\nAnswer:\"\n",
|
| 507 |
+
"doc_to_choice: [\"A\", \"B\", \"C\", \"D\"]\n",
|
| 508 |
+
"doc_to_target: answer\n",
|
| 509 |
+
"metric_list:\n",
|
| 510 |
+
" - metric: acc\n",
|
| 511 |
+
" aggregation: mean\n",
|
| 512 |
+
" higher_is_better: true\n",
|
| 513 |
+
" - metric: acc_norm\n",
|
| 514 |
+
" aggregation: mean\n",
|
| 515 |
+
" higher_is_better: true\n",
|
| 516 |
+
"\"\"\"\n",
|
| 517 |
+
"with open(\"mmlu_high_school_geography.yaml\", \"w\") as f:\n",
|
| 518 |
+
" f.write(YAML_mmlu_geo_string)"
|
| 519 |
+
]
|
| 520 |
+
},
|
| 521 |
+
{
|
| 522 |
+
"cell_type": "code",
|
| 523 |
+
"execution_count": 8,
|
| 524 |
+
"metadata": {
|
| 525 |
+
"id": "jyKOfCsKb-xy"
|
| 526 |
+
},
|
| 527 |
+
"outputs": [
|
| 528 |
+
{
|
| 529 |
+
"name": "stdout",
|
| 530 |
+
"output_type": "stream",
|
| 531 |
+
"text": [
|
| 532 |
+
"2023-11-29:11:57:23,598 INFO [utils.py:160] NumExpr defaulting to 2 threads.\n",
|
| 533 |
+
"2023-11-29 11:57:24.719750: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
|
| 534 |
+
"2023-11-29 11:57:24.719806: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
|
| 535 |
+
"2023-11-29 11:57:24.719847: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
|
| 536 |
+
"2023-11-29 11:57:26.656125: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
|
| 537 |
+
"2023-11-29:11:57:31,563 INFO [__main__.py:132] Verbosity set to INFO\n",
|
| 538 |
+
"2023-11-29:11:57:40,541 WARNING [__main__.py:138] --limit SHOULD ONLY BE USED FOR TESTING.REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.\n",
|
| 539 |
+
"2023-11-29:11:57:40,541 INFO [__main__.py:143] Including path: ./\n",
|
| 540 |
+
"2023-11-29:11:57:40,558 INFO [__main__.py:205] Selected Tasks: ['demo_mmlu_high_school_geography']\n",
|
| 541 |
+
"2023-11-29:11:57:40,559 WARNING [evaluator.py:93] generation_kwargs specified through cli, these settings will be used over set parameters in yaml tasks.\n",
|
| 542 |
+
"2023-11-29:11:57:40,589 INFO [huggingface.py:120] Using device 'cuda'\n",
|
| 543 |
+
"Downloading builder script: 100% 5.84k/5.84k [00:00<00:00, 17.7MB/s]\n",
|
| 544 |
+
"Downloading metadata: 100% 106k/106k [00:00<00:00, 892kB/s] \n",
|
| 545 |
+
"Downloading readme: 100% 39.7k/39.7k [00:00<00:00, 631kB/s]\n",
|
| 546 |
+
"Downloading data: 100% 166M/166M [00:01<00:00, 89.0MB/s]\n",
|
| 547 |
+
"Generating auxiliary_train split: 100% 99842/99842 [00:07<00:00, 12536.83 examples/s]\n",
|
| 548 |
+
"Generating test split: 100% 198/198 [00:00<00:00, 1439.20 examples/s]\n",
|
| 549 |
+
"Generating validation split: 100% 22/22 [00:00<00:00, 4181.76 examples/s]\n",
|
| 550 |
+
"Generating dev split: 100% 5/5 [00:00<00:00, 36.25 examples/s]\n",
|
| 551 |
+
"2023-11-29:11:58:09,798 INFO [task.py:355] Building contexts for task on rank 0...\n",
|
| 552 |
+
"2023-11-29:11:58:09,822 INFO [evaluator.py:319] Running loglikelihood requests\n",
|
| 553 |
+
"100% 40/40 [00:05<00:00, 7.86it/s]\n",
|
| 554 |
+
"fatal: not a git repository (or any of the parent directories): .git\n",
|
| 555 |
+
"hf (pretrained=EleutherAI/pythia-2.8b), gen_kwargs: (), limit: 10.0, num_fewshot: None, batch_size: 1\n",
|
| 556 |
+
"| Tasks |Version|Filter|n-shot| Metric |Value| |Stderr|\n",
|
| 557 |
+
"|-------------------------------|-------|------|-----:|--------|----:|---|-----:|\n",
|
| 558 |
+
"|demo_mmlu_high_school_geography|Yaml |none | 0|acc | 0.3|± |0.1528|\n",
|
| 559 |
+
"| | |none | 0|acc_norm| 0.3|± |0.1528|\n",
|
| 560 |
+
"\n"
|
| 561 |
+
]
|
| 562 |
+
}
|
| 563 |
+
],
|
| 564 |
+
"source": [
|
| 565 |
+
"# !accelerate launch --no_python\n",
|
| 566 |
+
"%env LOGLEVEL=DEBUG\n",
|
| 567 |
+
"!lm_eval \\\n",
|
| 568 |
+
" --model hf \\\n",
|
| 569 |
+
" --model_args pretrained=EleutherAI/pythia-2.8b \\\n",
|
| 570 |
+
" --include_path ./ \\\n",
|
| 571 |
+
" --tasks demo_mmlu_high_school_geography \\\n",
|
| 572 |
+
" --limit 10 \\\n",
|
| 573 |
+
" --output output/mmlu_high_school_geography/ \\\n",
|
| 574 |
+
" --log_samples"
|
| 575 |
+
]
|
| 576 |
+
},
|
| 577 |
+
{
|
| 578 |
+
"cell_type": "markdown",
|
| 579 |
+
"metadata": {
|
| 580 |
+
"id": "jyKOfCsKb-xy"
|
| 581 |
+
},
|
| 582 |
+
"source": [
|
| 583 |
+
"We could also evaluate this task in a different way. For example, instead of observing the loglikelihood of the letters, we can instead evaluate on the choices themselves as the continuation. This is done by simply changing `doc_to_choice` from a list of letters to the corresponding `choices` field from the HF dataset. We write `\"{{choices}}\"` so that the string field is interpreted as jinja string that acquires the list from the HF dataset directly.\n",
|
| 584 |
+
"\n",
|
| 585 |
+
"Another convenient feature here is since we're only modifying the `doc_to_choice` and the rest of config is the same as the task above, we can use the above configuration as a template by using `include: mmlu_high_school_geography.yaml` to load the config from that file. We'll need to add a unique task name as to not colide with the existing yaml config we're including. For this case we'll simply name this one `mmlu_high_school_geography_continuation`. `doc_to_text` is added here just for sake of clarity."
|
| 586 |
+
]
|
| 587 |
+
},
|
| 588 |
+
{
|
| 589 |
+
"cell_type": "code",
|
| 590 |
+
"execution_count": 9,
|
| 591 |
+
"metadata": {
|
| 592 |
+
"id": "lqElwU54TaK-"
|
| 593 |
+
},
|
| 594 |
+
"outputs": [],
|
| 595 |
+
"source": [
|
| 596 |
+
"YAML_mmlu_geo_string = \"\"\"\n",
|
| 597 |
+
"include: mmlu_high_school_geography.yaml\n",
|
| 598 |
+
"task: demo_mmlu_high_school_geography_continuation\n",
|
| 599 |
+
"doc_to_text: \"{{question.strip()}}\\nA. {{choices[0]}}\\nB. {{choices[1]}}\\nC. {{choices[2]}}\\nD. {{choices[3]}}\\nAnswer:\"\n",
|
| 600 |
+
"doc_to_choice: \"{{choices}}\"\n",
|
| 601 |
+
"\"\"\"\n",
|
| 602 |
+
"with open(\"mmlu_high_school_geography_continuation.yaml\", \"w\") as f:\n",
|
| 603 |
+
" f.write(YAML_mmlu_geo_string)"
|
| 604 |
+
]
|
| 605 |
+
},
|
| 606 |
+
{
|
| 607 |
+
"cell_type": "code",
|
| 608 |
+
"execution_count": 10,
|
| 609 |
+
"metadata": {
|
| 610 |
+
"id": "-_CVnDirdy7j"
|
| 611 |
+
},
|
| 612 |
+
"outputs": [
|
| 613 |
+
{
|
| 614 |
+
"name": "stdout",
|
| 615 |
+
"output_type": "stream",
|
| 616 |
+
"text": [
|
| 617 |
+
"2023-11-29:11:58:21,284 INFO [utils.py:160] NumExpr defaulting to 2 threads.\n",
|
| 618 |
+
"2023-11-29 11:58:22.850159: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
|
| 619 |
+
"2023-11-29 11:58:22.850219: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
|
| 620 |
+
"2023-11-29 11:58:22.850254: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
|
| 621 |
+
"2023-11-29 11:58:24.948103: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
|
| 622 |
+
"2023-11-29:11:58:28,460 INFO [__main__.py:132] Verbosity set to INFO\n",
|
| 623 |
+
"2023-11-29:11:58:37,935 WARNING [__main__.py:138] --limit SHOULD ONLY BE USED FOR TESTING.REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.\n",
|
| 624 |
+
"2023-11-29:11:58:37,935 INFO [__main__.py:143] Including path: ./\n",
|
| 625 |
+
"2023-11-29:11:58:37,969 INFO [__main__.py:205] Selected Tasks: ['demo_mmlu_high_school_geography_continuation']\n",
|
| 626 |
+
"2023-11-29:11:58:37,972 WARNING [evaluator.py:93] generation_kwargs specified through cli, these settings will be used over set parameters in yaml tasks.\n",
|
| 627 |
+
"2023-11-29:11:58:38,008 INFO [huggingface.py:120] Using device 'cuda'\n",
|
| 628 |
+
"2023-11-29:11:58:59,758 INFO [task.py:355] Building contexts for task on rank 0...\n",
|
| 629 |
+
"2023-11-29:11:58:59,777 INFO [evaluator.py:319] Running loglikelihood requests\n",
|
| 630 |
+
"100% 40/40 [00:02<00:00, 16.23it/s]\n",
|
| 631 |
+
"fatal: not a git repository (or any of the parent directories): .git\n",
|
| 632 |
+
"hf (pretrained=EleutherAI/pythia-2.8b), gen_kwargs: (), limit: 10.0, num_fewshot: None, batch_size: 1\n",
|
| 633 |
+
"| Tasks |Version|Filter|n-shot| Metric |Value| |Stderr|\n",
|
| 634 |
+
"|--------------------------------------------|-------|------|-----:|--------|----:|---|-----:|\n",
|
| 635 |
+
"|demo_mmlu_high_school_geography_continuation|Yaml |none | 0|acc | 0.1|± |0.1000|\n",
|
| 636 |
+
"| | |none | 0|acc_norm| 0.2|± |0.1333|\n",
|
| 637 |
+
"\n"
|
| 638 |
+
]
|
| 639 |
+
}
|
| 640 |
+
],
|
| 641 |
+
"source": [
|
| 642 |
+
"# !accelerate launch --no_python\n",
|
| 643 |
+
"%env LOGLEVEL=DEBUG\n",
|
| 644 |
+
"!lm_eval \\\n",
|
| 645 |
+
" --model hf \\\n",
|
| 646 |
+
" --model_args pretrained=EleutherAI/pythia-2.8b \\\n",
|
| 647 |
+
" --include_path ./ \\\n",
|
| 648 |
+
" --tasks demo_mmlu_high_school_geography_continuation \\\n",
|
| 649 |
+
" --limit 10 \\\n",
|
| 650 |
+
" --output output/mmlu_high_school_geography_continuation/ \\\n",
|
| 651 |
+
" --log_samples"
|
| 652 |
+
]
|
| 653 |
+
},
|
| 654 |
+
{
|
| 655 |
+
"cell_type": "markdown",
|
| 656 |
+
"metadata": {
|
| 657 |
+
"id": "-_CVnDirdy7j"
|
| 658 |
+
},
|
| 659 |
+
"source": [
|
| 660 |
+
"If we take a look at the samples, we can see that it is in fact evaluating the continuation based on the choices rather than the letters."
|
| 661 |
+
]
|
| 662 |
+
},
|
| 663 |
+
{
|
| 664 |
+
"cell_type": "code",
|
| 665 |
+
"execution_count": 11,
|
| 666 |
+
"metadata": {
|
| 667 |
+
"id": "duBDqC6PAdjL"
|
| 668 |
+
},
|
| 669 |
+
"outputs": [
|
| 670 |
+
{
|
| 671 |
+
"data": {
|
| 672 |
+
"application/javascript": "\n ((filepath) => {{\n if (!google.colab.kernel.accessAllowed) {{\n return;\n }}\n google.colab.files.view(filepath);\n }})(\"/content/output/mmlu_high_school_geography_continuation/pretrained__EleutherAI__pythia-2.8b_demo_mmlu_high_school_geography_continuation.jsonl\")",
|
| 673 |
+
"text/plain": [
|
| 674 |
+
"<IPython.core.display.Javascript object>"
|
| 675 |
+
]
|
| 676 |
+
},
|
| 677 |
+
"metadata": {},
|
| 678 |
+
"output_type": "display_data"
|
| 679 |
+
}
|
| 680 |
+
],
|
| 681 |
+
"source": [
|
| 682 |
+
"from google.colab import files\n",
|
| 683 |
+
"\n",
|
| 684 |
+
"\n",
|
| 685 |
+
"files.view(\n",
|
| 686 |
+
" \"output/mmlu_high_school_geography_continuation/pretrained__EleutherAI__pythia-2.8b_demo_mmlu_high_school_geography_continuation.jsonl\"\n",
|
| 687 |
+
")"
|
| 688 |
+
]
|
| 689 |
+
},
|
| 690 |
+
{
|
| 691 |
+
"cell_type": "markdown",
|
| 692 |
+
"metadata": {
|
| 693 |
+
"id": "6p0-KPwAgK5j"
|
| 694 |
+
},
|
| 695 |
+
"source": [
|
| 696 |
+
"## Closer Look at YAML Fields\n",
|
| 697 |
+
"\n",
|
| 698 |
+
"To prepare a task we can simply fill in a YAML config with the relevant information.\n",
|
| 699 |
+
"\n",
|
| 700 |
+
"`output_type`\n",
|
| 701 |
+
"The current provided evaluation types comprise of the following:\n",
|
| 702 |
+
"1. `loglikelihood`: Evaluates the loglikelihood of a continuation, conditioned on some input string.\n",
|
| 703 |
+
"2. `loglikelihood_rolling`: evaluate the loglikelihood of producing a string, conditioned on the empty string. (Used for perplexity evaluations)\n",
|
| 704 |
+
"3. `multiple_choice`: Evaluates loglikelihood among the a number of choices predicted by the model.\n",
|
| 705 |
+
"4. `greedy_until`: Model outputs greedy generation (can be configured to to use beam search and other generation-related parameters)\n",
|
| 706 |
+
"\n",
|
| 707 |
+
"The core prompt revolves around 3 fields.\n",
|
| 708 |
+
"1. `doc_to_text`: Denotes the prompt template that will be used as input to the model.\n",
|
| 709 |
+
"2. `doc_to_choice`: Available choices that will be used as continuation for the model. This is used when the `output_type` is `multiple_choice`, and otherwise can be left as `None`.\n",
|
| 710 |
+
"3. `doc_to_target`: When `output_type` is `multiple_choice`, this can be an index that corresponds to the correct answer, or the answer string itself (must be a subset of `doc_to_choice`). For other tasks, this is expected to be a string. You can fill this field with a feature name from the HF dataset so long as the resulting feature follows the conditioned described.\n",
|
| 711 |
+
"\n",
|
| 712 |
+
"These three fields can be expressed as strings, column names from the source dataset, or as Jinja2 templates that can use fields from the source dataset as variables.\n"
|
| 713 |
+
]
|
| 714 |
+
},
|
| 715 |
+
{
|
| 716 |
+
"cell_type": "markdown",
|
| 717 |
+
"metadata": {
|
| 718 |
+
"id": "6p0-KPwAgK5j"
|
| 719 |
+
},
|
| 720 |
+
"source": [
|
| 721 |
+
"## What if Jinja is not Sufficient?\n",
|
| 722 |
+
"\n",
|
| 723 |
+
"There can be times where the Jinja2 templating language is not enough to make the prompt we had in mind. There are a few ways to circumvent this limitation:\n",
|
| 724 |
+
"\n",
|
| 725 |
+
"1. Use `!function` operator for the prompt-related fields to pass a python function that takes as input the dataset row, and will output the prompt template component.\n",
|
| 726 |
+
"2. Perform a transformation on the dataset beforehand."
|
| 727 |
+
]
|
| 728 |
+
},
|
| 729 |
+
{
|
| 730 |
+
"cell_type": "markdown",
|
| 731 |
+
"metadata": {},
|
| 732 |
+
"source": [
|
| 733 |
+
"Below, we show an example of using `!function` to create `doc_to_text` from a python function:"
|
| 734 |
+
]
|
| 735 |
+
},
|
| 736 |
+
{
|
| 737 |
+
"cell_type": "code",
|
| 738 |
+
"execution_count": 12,
|
| 739 |
+
"metadata": {
|
| 740 |
+
"colab": {
|
| 741 |
+
"base_uri": "https://localhost:8080/"
|
| 742 |
+
},
|
| 743 |
+
"id": "DYZ5c0JhR1lJ",
|
| 744 |
+
"outputId": "ca945235-fb9e-4f17-8bfa-78e7d6ec1490"
|
| 745 |
+
},
|
| 746 |
+
"outputs": [
|
| 747 |
+
{
|
| 748 |
+
"name": "stdout",
|
| 749 |
+
"output_type": "stream",
|
| 750 |
+
"text": [
|
| 751 |
+
"2023-11-29:11:59:08,312 INFO [utils.py:160] NumExpr defaulting to 2 threads.\n",
|
| 752 |
+
"2023-11-29 11:59:09.348327: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
|
| 753 |
+
"2023-11-29 11:59:09.348387: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
|
| 754 |
+
"2023-11-29 11:59:09.348421: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
|
| 755 |
+
"2023-11-29 11:59:10.573752: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
|
| 756 |
+
"2023-11-29:11:59:14,044 INFO [__main__.py:132] Verbosity set to INFO\n",
|
| 757 |
+
"2023-11-29:11:59:23,654 WARNING [__main__.py:138] --limit SHOULD ONLY BE USED FOR TESTING.REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.\n",
|
| 758 |
+
"2023-11-29:11:59:23,654 INFO [__main__.py:143] Including path: ./\n",
|
| 759 |
+
"2023-11-29:11:59:23,678 INFO [__main__.py:205] Selected Tasks: ['demo_mmlu_high_school_geography_function_prompt']\n",
|
| 760 |
+
"2023-11-29:11:59:23,679 WARNING [evaluator.py:93] generation_kwargs specified through cli, these settings will be used over set parameters in yaml tasks.\n",
|
| 761 |
+
"2023-11-29:11:59:23,708 INFO [huggingface.py:120] Using device 'cuda'\n",
|
| 762 |
+
"2023-11-29:11:59:44,516 INFO [task.py:355] Building contexts for task on rank 0...\n",
|
| 763 |
+
"2023-11-29:11:59:44,524 INFO [evaluator.py:319] Running loglikelihood requests\n",
|
| 764 |
+
"100% 40/40 [00:02<00:00, 15.41it/s]\n",
|
| 765 |
+
"fatal: not a git repository (or any of the parent directories): .git\n",
|
| 766 |
+
"hf (pretrained=EleutherAI/pythia-2.8b), gen_kwargs: (), limit: 10.0, num_fewshot: None, batch_size: 1\n",
|
| 767 |
+
"| Tasks |Version|Filter|n-shot| Metric |Value| |Stderr|\n",
|
| 768 |
+
"|-----------------------------------------------|-------|------|-----:|--------|----:|---|-----:|\n",
|
| 769 |
+
"|demo_mmlu_high_school_geography_function_prompt|Yaml |none | 0|acc | 0.1|± |0.1000|\n",
|
| 770 |
+
"| | |none | 0|acc_norm| 0.2|± |0.1333|\n",
|
| 771 |
+
"\n"
|
| 772 |
+
]
|
| 773 |
+
}
|
| 774 |
+
],
|
| 775 |
+
"source": [
|
| 776 |
+
"YAML_mmlu_geo_string = \"\"\"\n",
|
| 777 |
+
"include: mmlu_high_school_geography.yaml\n",
|
| 778 |
+
"task: demo_mmlu_high_school_geography_function_prompt\n",
|
| 779 |
+
"doc_to_text: !function utils.doc_to_text\n",
|
| 780 |
+
"doc_to_choice: \"{{choices}}\"\n",
|
| 781 |
+
"\"\"\"\n",
|
| 782 |
+
"with open(\"demo_mmlu_high_school_geography_function_prompt.yaml\", \"w\") as f:\n",
|
| 783 |
+
" f.write(YAML_mmlu_geo_string)\n",
|
| 784 |
+
"\n",
|
| 785 |
+
"DOC_TO_TEXT = \"\"\"\n",
|
| 786 |
+
"def doc_to_text(x):\n",
|
| 787 |
+
" question = x[\"question\"].strip()\n",
|
| 788 |
+
" choices = x[\"choices\"]\n",
|
| 789 |
+
" option_a = choices[0]\n",
|
| 790 |
+
" option_b = choices[1]\n",
|
| 791 |
+
" option_c = choices[2]\n",
|
| 792 |
+
" option_d = choices[3]\n",
|
| 793 |
+
" return f\"{question}\\\\nA. {option_a}\\\\nB. {option_b}\\\\nC. {option_c}\\\\nD. {option_d}\\\\nAnswer:\"\n",
|
| 794 |
+
"\"\"\"\n",
|
| 795 |
+
"with open(\"utils.py\", \"w\") as f:\n",
|
| 796 |
+
" f.write(DOC_TO_TEXT)\n",
|
| 797 |
+
"\n",
|
| 798 |
+
"!lm_eval \\\n",
|
| 799 |
+
" --model hf \\\n",
|
| 800 |
+
" --model_args pretrained=EleutherAI/pythia-2.8b \\\n",
|
| 801 |
+
" --include_path ./ \\\n",
|
| 802 |
+
" --tasks demo_mmlu_high_school_geography_function_prompt \\\n",
|
| 803 |
+
" --limit 10 \\\n",
|
| 804 |
+
" --output output/demo_mmlu_high_school_geography_function_prompt/ \\\n",
|
| 805 |
+
" --log_samples"
|
| 806 |
+
]
|
| 807 |
+
},
|
| 808 |
+
{
|
| 809 |
+
"cell_type": "markdown",
|
| 810 |
+
"metadata": {},
|
| 811 |
+
"source": [
|
| 812 |
+
"Next, we'll also show how to do this via preprocessing the dataset as necessary using the `process_docs` config field:\n",
|
| 813 |
+
"\n",
|
| 814 |
+
"We will write a function that will modify each document in our evaluation dataset's split to add a field that is suitable for us to use in `doc_to_text`."
|
| 815 |
+
]
|
| 816 |
+
},
|
| 817 |
+
{
|
| 818 |
+
"cell_type": "code",
|
| 819 |
+
"execution_count": null,
|
| 820 |
+
"metadata": {},
|
| 821 |
+
"outputs": [],
|
| 822 |
+
"source": [
|
| 823 |
+
"YAML_mmlu_geo_string = \"\"\"\n",
|
| 824 |
+
"include: mmlu_high_school_geography.yaml\n",
|
| 825 |
+
"task: demo_mmlu_high_school_geography_function_prompt_2\n",
|
| 826 |
+
"process_docs: !function utils_process_docs.process_docs\n",
|
| 827 |
+
"doc_to_text: \"{{input}}\"\n",
|
| 828 |
+
"doc_to_choice: \"{{choices}}\"\n",
|
| 829 |
+
"\"\"\"\n",
|
| 830 |
+
"with open(\"demo_mmlu_high_school_geography_process_docs.yaml\", \"w\") as f:\n",
|
| 831 |
+
" f.write(YAML_mmlu_geo_string)\n",
|
| 832 |
+
"\n",
|
| 833 |
+
"DOC_TO_TEXT = \"\"\"\n",
|
| 834 |
+
"def process_docs(dataset):\n",
|
| 835 |
+
" def _process_doc(x):\n",
|
| 836 |
+
" question = x[\"question\"].strip()\n",
|
| 837 |
+
" choices = x[\"choices\"]\n",
|
| 838 |
+
" option_a = choices[0]\n",
|
| 839 |
+
" option_b = choices[1]\n",
|
| 840 |
+
" option_c = choices[2]\n",
|
| 841 |
+
" option_d = choices[3]\n",
|
| 842 |
+
" doc[\"input\"] = f\"{question}\\\\nA. {option_a}\\\\nB. {option_b}\\\\nC. {option_c}\\\\nD. {option_d}\\\\nAnswer:\"\n",
|
| 843 |
+
" return out_doc\n",
|
| 844 |
+
"\n",
|
| 845 |
+
" return dataset.map(_process_doc)\n",
|
| 846 |
+
"\"\"\"\n",
|
| 847 |
+
"\n",
|
| 848 |
+
"with open(\"utils_process_docs.py\", \"w\") as f:\n",
|
| 849 |
+
" f.write(DOC_TO_TEXT)\n",
|
| 850 |
+
"\n",
|
| 851 |
+
"!lm_eval \\\n",
|
| 852 |
+
" --model hf \\\n",
|
| 853 |
+
" --model_args pretrained=EleutherAI/pythia-2.8b \\\n",
|
| 854 |
+
" --include_path ./ \\\n",
|
| 855 |
+
" --tasks demo_mmlu_high_school_geography_function_prompt_2 \\\n",
|
| 856 |
+
" --limit 10 \\\n",
|
| 857 |
+
" --output output/demo_mmlu_high_school_geography_function_prompt_2/ \\\n",
|
| 858 |
+
" --log_samples"
|
| 859 |
+
]
|
| 860 |
+
},
|
| 861 |
+
{
|
| 862 |
+
"cell_type": "markdown",
|
| 863 |
+
"metadata": {},
|
| 864 |
+
"source": [
|
| 865 |
+
"We hope that this explainer gives you a sense of what can be done with and how to work with LM-Evaluation-Harnes v0.4.0 ! \n",
|
| 866 |
+
"\n",
|
| 867 |
+
"For more information, check out our documentation pages in the `docs/` folder, and if you have questions, please raise them in GitHub issues, or in #lm-thunderdome or #release-discussion on the EleutherAI discord server."
|
| 868 |
+
]
|
| 869 |
+
}
|
| 870 |
+
],
|
| 871 |
+
"metadata": {
|
| 872 |
+
"accelerator": "GPU",
|
| 873 |
+
"colab": {
|
| 874 |
+
"collapsed_sections": [
|
| 875 |
+
"zAov81vTbL2K"
|
| 876 |
+
],
|
| 877 |
+
"gpuType": "T4",
|
| 878 |
+
"provenance": []
|
| 879 |
+
},
|
| 880 |
+
"kernelspec": {
|
| 881 |
+
"display_name": "Python 3",
|
| 882 |
+
"name": "python3"
|
| 883 |
+
},
|
| 884 |
+
"language_info": {
|
| 885 |
+
"name": "python"
|
| 886 |
+
},
|
| 887 |
+
"widgets": {
|
| 888 |
+
"application/vnd.jupyter.widget-state+json": {
|
| 889 |
+
"state": {
|
| 890 |
+
"46f521b73fd943c081c648fd873ebc0a": {
|
| 891 |
+
"model_module": "@jupyter-widgets/controls",
|
| 892 |
+
"model_module_version": "1.5.0",
|
| 893 |
+
"model_name": "DescriptionStyleModel",
|
| 894 |
+
"state": {
|
| 895 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 896 |
+
"_model_module_version": "1.5.0",
|
| 897 |
+
"_model_name": "DescriptionStyleModel",
|
| 898 |
+
"_view_count": null,
|
| 899 |
+
"_view_module": "@jupyter-widgets/base",
|
| 900 |
+
"_view_module_version": "1.2.0",
|
| 901 |
+
"_view_name": "StyleView",
|
| 902 |
+
"description_width": ""
|
| 903 |
+
}
|
| 904 |
+
},
|
| 905 |
+
"48763b6233374554ae76035c0483066f": {
|
| 906 |
+
"model_module": "@jupyter-widgets/controls",
|
| 907 |
+
"model_module_version": "1.5.0",
|
| 908 |
+
"model_name": "ProgressStyleModel",
|
| 909 |
+
"state": {
|
| 910 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 911 |
+
"_model_module_version": "1.5.0",
|
| 912 |
+
"_model_name": "ProgressStyleModel",
|
| 913 |
+
"_view_count": null,
|
| 914 |
+
"_view_module": "@jupyter-widgets/base",
|
| 915 |
+
"_view_module_version": "1.2.0",
|
| 916 |
+
"_view_name": "StyleView",
|
| 917 |
+
"bar_color": null,
|
| 918 |
+
"description_width": ""
|
| 919 |
+
}
|
| 920 |
+
},
|
| 921 |
+
"4986a21eb560448fa79f4b25cde48951": {
|
| 922 |
+
"model_module": "@jupyter-widgets/base",
|
| 923 |
+
"model_module_version": "1.2.0",
|
| 924 |
+
"model_name": "LayoutModel",
|
| 925 |
+
"state": {
|
| 926 |
+
"_model_module": "@jupyter-widgets/base",
|
| 927 |
+
"_model_module_version": "1.2.0",
|
| 928 |
+
"_model_name": "LayoutModel",
|
| 929 |
+
"_view_count": null,
|
| 930 |
+
"_view_module": "@jupyter-widgets/base",
|
| 931 |
+
"_view_module_version": "1.2.0",
|
| 932 |
+
"_view_name": "LayoutView",
|
| 933 |
+
"align_content": null,
|
| 934 |
+
"align_items": null,
|
| 935 |
+
"align_self": null,
|
| 936 |
+
"border": null,
|
| 937 |
+
"bottom": null,
|
| 938 |
+
"display": null,
|
| 939 |
+
"flex": null,
|
| 940 |
+
"flex_flow": null,
|
| 941 |
+
"grid_area": null,
|
| 942 |
+
"grid_auto_columns": null,
|
| 943 |
+
"grid_auto_flow": null,
|
| 944 |
+
"grid_auto_rows": null,
|
| 945 |
+
"grid_column": null,
|
| 946 |
+
"grid_gap": null,
|
| 947 |
+
"grid_row": null,
|
| 948 |
+
"grid_template_areas": null,
|
| 949 |
+
"grid_template_columns": null,
|
| 950 |
+
"grid_template_rows": null,
|
| 951 |
+
"height": null,
|
| 952 |
+
"justify_content": null,
|
| 953 |
+
"justify_items": null,
|
| 954 |
+
"left": null,
|
| 955 |
+
"margin": null,
|
| 956 |
+
"max_height": null,
|
| 957 |
+
"max_width": null,
|
| 958 |
+
"min_height": null,
|
| 959 |
+
"min_width": null,
|
| 960 |
+
"object_fit": null,
|
| 961 |
+
"object_position": null,
|
| 962 |
+
"order": null,
|
| 963 |
+
"overflow": null,
|
| 964 |
+
"overflow_x": null,
|
| 965 |
+
"overflow_y": null,
|
| 966 |
+
"padding": null,
|
| 967 |
+
"right": null,
|
| 968 |
+
"top": null,
|
| 969 |
+
"visibility": null,
|
| 970 |
+
"width": null
|
| 971 |
+
}
|
| 972 |
+
},
|
| 973 |
+
"6b2d90209ec14230b3d58a74ac9b83bf": {
|
| 974 |
+
"model_module": "@jupyter-widgets/base",
|
| 975 |
+
"model_module_version": "1.2.0",
|
| 976 |
+
"model_name": "LayoutModel",
|
| 977 |
+
"state": {
|
| 978 |
+
"_model_module": "@jupyter-widgets/base",
|
| 979 |
+
"_model_module_version": "1.2.0",
|
| 980 |
+
"_model_name": "LayoutModel",
|
| 981 |
+
"_view_count": null,
|
| 982 |
+
"_view_module": "@jupyter-widgets/base",
|
| 983 |
+
"_view_module_version": "1.2.0",
|
| 984 |
+
"_view_name": "LayoutView",
|
| 985 |
+
"align_content": null,
|
| 986 |
+
"align_items": null,
|
| 987 |
+
"align_self": null,
|
| 988 |
+
"border": null,
|
| 989 |
+
"bottom": null,
|
| 990 |
+
"display": null,
|
| 991 |
+
"flex": null,
|
| 992 |
+
"flex_flow": null,
|
| 993 |
+
"grid_area": null,
|
| 994 |
+
"grid_auto_columns": null,
|
| 995 |
+
"grid_auto_flow": null,
|
| 996 |
+
"grid_auto_rows": null,
|
| 997 |
+
"grid_column": null,
|
| 998 |
+
"grid_gap": null,
|
| 999 |
+
"grid_row": null,
|
| 1000 |
+
"grid_template_areas": null,
|
| 1001 |
+
"grid_template_columns": null,
|
| 1002 |
+
"grid_template_rows": null,
|
| 1003 |
+
"height": null,
|
| 1004 |
+
"justify_content": null,
|
| 1005 |
+
"justify_items": null,
|
| 1006 |
+
"left": null,
|
| 1007 |
+
"margin": null,
|
| 1008 |
+
"max_height": null,
|
| 1009 |
+
"max_width": null,
|
| 1010 |
+
"min_height": null,
|
| 1011 |
+
"min_width": null,
|
| 1012 |
+
"object_fit": null,
|
| 1013 |
+
"object_position": null,
|
| 1014 |
+
"order": null,
|
| 1015 |
+
"overflow": null,
|
| 1016 |
+
"overflow_x": null,
|
| 1017 |
+
"overflow_y": null,
|
| 1018 |
+
"padding": null,
|
| 1019 |
+
"right": null,
|
| 1020 |
+
"top": null,
|
| 1021 |
+
"visibility": null,
|
| 1022 |
+
"width": null
|
| 1023 |
+
}
|
| 1024 |
+
},
|
| 1025 |
+
"7c5689bc13684db8a22681f41863dddd": {
|
| 1026 |
+
"model_module": "@jupyter-widgets/base",
|
| 1027 |
+
"model_module_version": "1.2.0",
|
| 1028 |
+
"model_name": "LayoutModel",
|
| 1029 |
+
"state": {
|
| 1030 |
+
"_model_module": "@jupyter-widgets/base",
|
| 1031 |
+
"_model_module_version": "1.2.0",
|
| 1032 |
+
"_model_name": "LayoutModel",
|
| 1033 |
+
"_view_count": null,
|
| 1034 |
+
"_view_module": "@jupyter-widgets/base",
|
| 1035 |
+
"_view_module_version": "1.2.0",
|
| 1036 |
+
"_view_name": "LayoutView",
|
| 1037 |
+
"align_content": null,
|
| 1038 |
+
"align_items": null,
|
| 1039 |
+
"align_self": null,
|
| 1040 |
+
"border": null,
|
| 1041 |
+
"bottom": null,
|
| 1042 |
+
"display": null,
|
| 1043 |
+
"flex": null,
|
| 1044 |
+
"flex_flow": null,
|
| 1045 |
+
"grid_area": null,
|
| 1046 |
+
"grid_auto_columns": null,
|
| 1047 |
+
"grid_auto_flow": null,
|
| 1048 |
+
"grid_auto_rows": null,
|
| 1049 |
+
"grid_column": null,
|
| 1050 |
+
"grid_gap": null,
|
| 1051 |
+
"grid_row": null,
|
| 1052 |
+
"grid_template_areas": null,
|
| 1053 |
+
"grid_template_columns": null,
|
| 1054 |
+
"grid_template_rows": null,
|
| 1055 |
+
"height": null,
|
| 1056 |
+
"justify_content": null,
|
| 1057 |
+
"justify_items": null,
|
| 1058 |
+
"left": null,
|
| 1059 |
+
"margin": null,
|
| 1060 |
+
"max_height": null,
|
| 1061 |
+
"max_width": null,
|
| 1062 |
+
"min_height": null,
|
| 1063 |
+
"min_width": null,
|
| 1064 |
+
"object_fit": null,
|
| 1065 |
+
"object_position": null,
|
| 1066 |
+
"order": null,
|
| 1067 |
+
"overflow": null,
|
| 1068 |
+
"overflow_x": null,
|
| 1069 |
+
"overflow_y": null,
|
| 1070 |
+
"padding": null,
|
| 1071 |
+
"right": null,
|
| 1072 |
+
"top": null,
|
| 1073 |
+
"visibility": null,
|
| 1074 |
+
"width": null
|
| 1075 |
+
}
|
| 1076 |
+
},
|
| 1077 |
+
"a1d3a8aa016544a78e8821c8f6199e06": {
|
| 1078 |
+
"model_module": "@jupyter-widgets/controls",
|
| 1079 |
+
"model_module_version": "1.5.0",
|
| 1080 |
+
"model_name": "HBoxModel",
|
| 1081 |
+
"state": {
|
| 1082 |
+
"_dom_classes": [],
|
| 1083 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 1084 |
+
"_model_module_version": "1.5.0",
|
| 1085 |
+
"_model_name": "HBoxModel",
|
| 1086 |
+
"_view_count": null,
|
| 1087 |
+
"_view_module": "@jupyter-widgets/controls",
|
| 1088 |
+
"_view_module_version": "1.5.0",
|
| 1089 |
+
"_view_name": "HBoxView",
|
| 1090 |
+
"box_style": "",
|
| 1091 |
+
"children": [
|
| 1092 |
+
"IPY_MODEL_f61ed33fad754146bdd2ac9db1ba1c48",
|
| 1093 |
+
"IPY_MODEL_bfa0af6aeff344c6845e1080a878e92e",
|
| 1094 |
+
"IPY_MODEL_fd1ad9e0367d4004aae853b91c3a7617"
|
| 1095 |
+
],
|
| 1096 |
+
"layout": "IPY_MODEL_6b2d90209ec14230b3d58a74ac9b83bf"
|
| 1097 |
+
}
|
| 1098 |
+
},
|
| 1099 |
+
"a73f357065d34d7baf0453ae4a8d75e2": {
|
| 1100 |
+
"model_module": "@jupyter-widgets/base",
|
| 1101 |
+
"model_module_version": "1.2.0",
|
| 1102 |
+
"model_name": "LayoutModel",
|
| 1103 |
+
"state": {
|
| 1104 |
+
"_model_module": "@jupyter-widgets/base",
|
| 1105 |
+
"_model_module_version": "1.2.0",
|
| 1106 |
+
"_model_name": "LayoutModel",
|
| 1107 |
+
"_view_count": null,
|
| 1108 |
+
"_view_module": "@jupyter-widgets/base",
|
| 1109 |
+
"_view_module_version": "1.2.0",
|
| 1110 |
+
"_view_name": "LayoutView",
|
| 1111 |
+
"align_content": null,
|
| 1112 |
+
"align_items": null,
|
| 1113 |
+
"align_self": null,
|
| 1114 |
+
"border": null,
|
| 1115 |
+
"bottom": null,
|
| 1116 |
+
"display": null,
|
| 1117 |
+
"flex": null,
|
| 1118 |
+
"flex_flow": null,
|
| 1119 |
+
"grid_area": null,
|
| 1120 |
+
"grid_auto_columns": null,
|
| 1121 |
+
"grid_auto_flow": null,
|
| 1122 |
+
"grid_auto_rows": null,
|
| 1123 |
+
"grid_column": null,
|
| 1124 |
+
"grid_gap": null,
|
| 1125 |
+
"grid_row": null,
|
| 1126 |
+
"grid_template_areas": null,
|
| 1127 |
+
"grid_template_columns": null,
|
| 1128 |
+
"grid_template_rows": null,
|
| 1129 |
+
"height": null,
|
| 1130 |
+
"justify_content": null,
|
| 1131 |
+
"justify_items": null,
|
| 1132 |
+
"left": null,
|
| 1133 |
+
"margin": null,
|
| 1134 |
+
"max_height": null,
|
| 1135 |
+
"max_width": null,
|
| 1136 |
+
"min_height": null,
|
| 1137 |
+
"min_width": null,
|
| 1138 |
+
"object_fit": null,
|
| 1139 |
+
"object_position": null,
|
| 1140 |
+
"order": null,
|
| 1141 |
+
"overflow": null,
|
| 1142 |
+
"overflow_x": null,
|
| 1143 |
+
"overflow_y": null,
|
| 1144 |
+
"padding": null,
|
| 1145 |
+
"right": null,
|
| 1146 |
+
"top": null,
|
| 1147 |
+
"visibility": null,
|
| 1148 |
+
"width": null
|
| 1149 |
+
}
|
| 1150 |
+
},
|
| 1151 |
+
"aed3acd2f2d74003b44079c333a0698e": {
|
| 1152 |
+
"model_module": "@jupyter-widgets/controls",
|
| 1153 |
+
"model_module_version": "1.5.0",
|
| 1154 |
+
"model_name": "DescriptionStyleModel",
|
| 1155 |
+
"state": {
|
| 1156 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 1157 |
+
"_model_module_version": "1.5.0",
|
| 1158 |
+
"_model_name": "DescriptionStyleModel",
|
| 1159 |
+
"_view_count": null,
|
| 1160 |
+
"_view_module": "@jupyter-widgets/base",
|
| 1161 |
+
"_view_module_version": "1.2.0",
|
| 1162 |
+
"_view_name": "StyleView",
|
| 1163 |
+
"description_width": ""
|
| 1164 |
+
}
|
| 1165 |
+
},
|
| 1166 |
+
"bfa0af6aeff344c6845e1080a878e92e": {
|
| 1167 |
+
"model_module": "@jupyter-widgets/controls",
|
| 1168 |
+
"model_module_version": "1.5.0",
|
| 1169 |
+
"model_name": "FloatProgressModel",
|
| 1170 |
+
"state": {
|
| 1171 |
+
"_dom_classes": [],
|
| 1172 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 1173 |
+
"_model_module_version": "1.5.0",
|
| 1174 |
+
"_model_name": "FloatProgressModel",
|
| 1175 |
+
"_view_count": null,
|
| 1176 |
+
"_view_module": "@jupyter-widgets/controls",
|
| 1177 |
+
"_view_module_version": "1.5.0",
|
| 1178 |
+
"_view_name": "ProgressView",
|
| 1179 |
+
"bar_style": "success",
|
| 1180 |
+
"description": "",
|
| 1181 |
+
"description_tooltip": null,
|
| 1182 |
+
"layout": "IPY_MODEL_7c5689bc13684db8a22681f41863dddd",
|
| 1183 |
+
"max": 5669,
|
| 1184 |
+
"min": 0,
|
| 1185 |
+
"orientation": "horizontal",
|
| 1186 |
+
"style": "IPY_MODEL_48763b6233374554ae76035c0483066f",
|
| 1187 |
+
"value": 5669
|
| 1188 |
+
}
|
| 1189 |
+
},
|
| 1190 |
+
"f61ed33fad754146bdd2ac9db1ba1c48": {
|
| 1191 |
+
"model_module": "@jupyter-widgets/controls",
|
| 1192 |
+
"model_module_version": "1.5.0",
|
| 1193 |
+
"model_name": "HTMLModel",
|
| 1194 |
+
"state": {
|
| 1195 |
+
"_dom_classes": [],
|
| 1196 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 1197 |
+
"_model_module_version": "1.5.0",
|
| 1198 |
+
"_model_name": "HTMLModel",
|
| 1199 |
+
"_view_count": null,
|
| 1200 |
+
"_view_module": "@jupyter-widgets/controls",
|
| 1201 |
+
"_view_module_version": "1.5.0",
|
| 1202 |
+
"_view_name": "HTMLView",
|
| 1203 |
+
"description": "",
|
| 1204 |
+
"description_tooltip": null,
|
| 1205 |
+
"layout": "IPY_MODEL_a73f357065d34d7baf0453ae4a8d75e2",
|
| 1206 |
+
"placeholder": "",
|
| 1207 |
+
"style": "IPY_MODEL_46f521b73fd943c081c648fd873ebc0a",
|
| 1208 |
+
"value": "Downloading builder script: 100%"
|
| 1209 |
+
}
|
| 1210 |
+
},
|
| 1211 |
+
"fd1ad9e0367d4004aae853b91c3a7617": {
|
| 1212 |
+
"model_module": "@jupyter-widgets/controls",
|
| 1213 |
+
"model_module_version": "1.5.0",
|
| 1214 |
+
"model_name": "HTMLModel",
|
| 1215 |
+
"state": {
|
| 1216 |
+
"_dom_classes": [],
|
| 1217 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 1218 |
+
"_model_module_version": "1.5.0",
|
| 1219 |
+
"_model_name": "HTMLModel",
|
| 1220 |
+
"_view_count": null,
|
| 1221 |
+
"_view_module": "@jupyter-widgets/controls",
|
| 1222 |
+
"_view_module_version": "1.5.0",
|
| 1223 |
+
"_view_name": "HTMLView",
|
| 1224 |
+
"description": "",
|
| 1225 |
+
"description_tooltip": null,
|
| 1226 |
+
"layout": "IPY_MODEL_4986a21eb560448fa79f4b25cde48951",
|
| 1227 |
+
"placeholder": "",
|
| 1228 |
+
"style": "IPY_MODEL_aed3acd2f2d74003b44079c333a0698e",
|
| 1229 |
+
"value": " 5.67k/5.67k [00:00<00:00, 205kB/s]"
|
| 1230 |
+
}
|
| 1231 |
+
}
|
| 1232 |
+
},
|
| 1233 |
+
"version_major": 2,
|
| 1234 |
+
"version_minor": 0
|
| 1235 |
+
}
|
| 1236 |
+
}
|
| 1237 |
+
},
|
| 1238 |
+
"nbformat": 4,
|
| 1239 |
+
"nbformat_minor": 0
|
| 1240 |
+
}
|
lm-evaluation-harness/examples/transformer-lens.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from transformer_lens import HookedTransformer
|
| 6 |
+
from transformers import AutoConfig
|
| 7 |
+
|
| 8 |
+
from lm_eval import evaluator
|
| 9 |
+
from lm_eval.models.huggingface import HFLM
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def evaluate_lm_eval(lens_model: HookedTransformer, tasks: list[str], **kwargs):
|
| 13 |
+
class HFLikeModelAdapter(nn.Module):
|
| 14 |
+
"""Adapts HookedTransformer to match the HuggingFace interface expected by lm-eval"""
|
| 15 |
+
|
| 16 |
+
def __init__(self, model: HookedTransformer):
|
| 17 |
+
super().__init__()
|
| 18 |
+
self.model = model
|
| 19 |
+
self.tokenizer = model.tokenizer
|
| 20 |
+
self.config = AutoConfig.from_pretrained(model.cfg.tokenizer_name)
|
| 21 |
+
self.device = model.cfg.device
|
| 22 |
+
self.tie_weights = lambda: self
|
| 23 |
+
|
| 24 |
+
def forward(self, input_ids=None, attention_mask=None, **kwargs):
|
| 25 |
+
output = self.model(input_ids, attention_mask=attention_mask, **kwargs)
|
| 26 |
+
# Make sure output has the expected .logits attribute
|
| 27 |
+
if not hasattr(output, "logits"):
|
| 28 |
+
if isinstance(output, torch.Tensor):
|
| 29 |
+
output.logits = output
|
| 30 |
+
return output
|
| 31 |
+
|
| 32 |
+
# Only delegate specific attributes we know we need
|
| 33 |
+
def to(self, *args, **kwargs):
|
| 34 |
+
return self.model.to(*args, **kwargs)
|
| 35 |
+
|
| 36 |
+
def eval(self):
|
| 37 |
+
self.model.eval()
|
| 38 |
+
return self
|
| 39 |
+
|
| 40 |
+
def train(self, mode=True):
|
| 41 |
+
self.model.train(mode)
|
| 42 |
+
return self
|
| 43 |
+
|
| 44 |
+
model = HFLikeModelAdapter(lens_model)
|
| 45 |
+
warnings.filterwarnings("ignore", message="Failed to get model SHA for")
|
| 46 |
+
results = evaluator.simple_evaluate(
|
| 47 |
+
model=HFLM(pretrained=model, tokenizer=model.tokenizer),
|
| 48 |
+
tasks=tasks,
|
| 49 |
+
verbosity="WARNING",
|
| 50 |
+
**kwargs,
|
| 51 |
+
)
|
| 52 |
+
return results
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
# Load base model
|
| 57 |
+
model = HookedTransformer.from_pretrained("pythia-70m")
|
| 58 |
+
res = evaluate_lm_eval(model, tasks=["arc_easy"])
|
| 59 |
+
print(res["results"])
|
lm-evaluation-harness/examples/visualize-wandb.ipynb
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"id": "fc477b96-adee-4829-a9d7-a5eb990df358",
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"source": [
|
| 8 |
+
"# Visualizing Results in Weights and Biases\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"With the Weights and Biases integration, you can now spend more time extracting deeper insights into your evaluation results. The integration is designed to streamline the process of logging and visualizing experiment results using the Weights & Biases (W&B) platform.\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"The integration provide functionalities\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"- to automatically log the evaluation results,\n",
|
| 15 |
+
"- log the samples as W&B Tables for easy visualization,\n",
|
| 16 |
+
"- log the `results.json` file as an artifact for version control,\n",
|
| 17 |
+
"- log the `<task_name>_eval_samples.json` file if the samples are logged,\n",
|
| 18 |
+
"- generate a comprehensive report for analysis and visualization with all the important metric,\n",
|
| 19 |
+
"- log task and cli configs,\n",
|
| 20 |
+
"- and more out of the box like the command used to run the evaluation, GPU/CPU counts, timestamp, etc.\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"The integration is super easy to use with the eval harness. Let's see how!"
|
| 23 |
+
]
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"cell_type": "code",
|
| 27 |
+
"execution_count": null,
|
| 28 |
+
"id": "3851439a-bff4-41f2-bf21-1b3d8704913b",
|
| 29 |
+
"metadata": {
|
| 30 |
+
"scrolled": true
|
| 31 |
+
},
|
| 32 |
+
"outputs": [],
|
| 33 |
+
"source": [
|
| 34 |
+
"# Install this project if you did not already have it.\n",
|
| 35 |
+
"# This is all that is needed to be installed to start using Weights and Biases\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"!pip -qq install -e ..[wandb]"
|
| 38 |
+
]
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "markdown",
|
| 42 |
+
"id": "8507fd7e-3b99-4a92-89fa-9eaada74ba91",
|
| 43 |
+
"metadata": {},
|
| 44 |
+
"source": [
|
| 45 |
+
"# Run the Eval Harness\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"Run the eval harness as usual with a `wandb_args` flag. This flag is used to provide arguments for initializing a wandb run ([wandb.init](https://docs.wandb.ai/ref/python/init)) as comma separated string arguments.\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"If `wandb_args` flag is used, the metrics and all other goodness will be automatically logged to Weights and Biases. In the stdout, you will find the link to the W&B run page as well as link to the generated report."
|
| 50 |
+
]
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "markdown",
|
| 54 |
+
"id": "eec5866e-f01e-42f8-8803-9d77472ef991",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"## Set your API Key\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"Before you can use W&B, you need to authenticate your machine with an authentication key. Visit https://wandb.ai/authorize to get one."
|
| 60 |
+
]
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"cell_type": "code",
|
| 64 |
+
"execution_count": null,
|
| 65 |
+
"id": "d824d163-71a9-4313-935d-f1d56397841c",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"outputs": [],
|
| 68 |
+
"source": [
|
| 69 |
+
"import wandb\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"\n",
|
| 72 |
+
"wandb.login()"
|
| 73 |
+
]
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "markdown",
|
| 77 |
+
"id": "124e4a34-1547-4bed-bc09-db012bacbda6",
|
| 78 |
+
"metadata": {},
|
| 79 |
+
"source": [
|
| 80 |
+
"> Note that if you are using command line you can simply authenticate your machine by doing `wandb login` in your terminal. For more info check out the [documentation](https://docs.wandb.ai/quickstart#2-log-in-to-wb)."
|
| 81 |
+
]
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "markdown",
|
| 85 |
+
"id": "abc6f6b6-179a-4aff-ada9-f380fb74df6e",
|
| 86 |
+
"metadata": {},
|
| 87 |
+
"source": [
|
| 88 |
+
"## Run and log to W&B"
|
| 89 |
+
]
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"cell_type": "code",
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"id": "bd0a8130-a97b-451a-acd2-3f9885b88643",
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"outputs": [],
|
| 97 |
+
"source": [
|
| 98 |
+
"!lm_eval \\\n",
|
| 99 |
+
" --model hf \\\n",
|
| 100 |
+
" --model_args pretrained=microsoft/phi-2,trust_remote_code=True \\\n",
|
| 101 |
+
" --tasks hellaswag,mmlu_abstract_algebra \\\n",
|
| 102 |
+
" --device cuda:0 \\\n",
|
| 103 |
+
" --batch_size 8 \\\n",
|
| 104 |
+
" --output_path output/phi-2 \\\n",
|
| 105 |
+
" --limit 10 \\\n",
|
| 106 |
+
" --wandb_args project=lm-eval-harness-integration \\\n",
|
| 107 |
+
" --log_samples"
|
| 108 |
+
]
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "markdown",
|
| 112 |
+
"id": "e974cabdbe70b667",
|
| 113 |
+
"metadata": {},
|
| 114 |
+
"source": []
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"cell_type": "markdown",
|
| 118 |
+
"id": "5178ca9445b844e4",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"W&B can also be initialized programmatically for use outside the CLI to parse and log the results."
|
| 122 |
+
]
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "code",
|
| 126 |
+
"execution_count": null,
|
| 127 |
+
"id": "c6a421b2cf3ddac5",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"outputs": [],
|
| 130 |
+
"source": [
|
| 131 |
+
"import lm_eval\n",
|
| 132 |
+
"from lm_eval.loggers import WandbLogger\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"results = lm_eval.simple_evaluate(\n",
|
| 136 |
+
" model=\"hf\",\n",
|
| 137 |
+
" model_args=\"pretrained=microsoft/phi-2,trust_remote_code=True\",\n",
|
| 138 |
+
" tasks=\"hellaswag,mmlu_abstract_algebra\",\n",
|
| 139 |
+
" log_samples=True,\n",
|
| 140 |
+
")\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"wandb_logger = WandbLogger(\n",
|
| 143 |
+
" project=\"lm-eval-harness-integration\", job_type=\"eval\"\n",
|
| 144 |
+
") # or empty if wandb.init(...) already called before\n",
|
| 145 |
+
"wandb_logger.post_init(results)\n",
|
| 146 |
+
"wandb_logger.log_eval_result()\n",
|
| 147 |
+
"wandb_logger.log_eval_samples(results[\"samples\"]) # if log_samples"
|
| 148 |
+
]
|
| 149 |
+
}
|
| 150 |
+
],
|
| 151 |
+
"metadata": {
|
| 152 |
+
"kernelspec": {
|
| 153 |
+
"display_name": "Python 3 (ipykernel)",
|
| 154 |
+
"language": "python",
|
| 155 |
+
"name": "python3"
|
| 156 |
+
},
|
| 157 |
+
"language_info": {
|
| 158 |
+
"codemirror_mode": {
|
| 159 |
+
"name": "ipython",
|
| 160 |
+
"version": 3
|
| 161 |
+
},
|
| 162 |
+
"file_extension": ".py",
|
| 163 |
+
"mimetype": "text/x-python",
|
| 164 |
+
"name": "python",
|
| 165 |
+
"nbconvert_exporter": "python",
|
| 166 |
+
"pygments_lexer": "ipython3",
|
| 167 |
+
"version": "3.10.12"
|
| 168 |
+
}
|
| 169 |
+
},
|
| 170 |
+
"nbformat": 4,
|
| 171 |
+
"nbformat_minor": 5
|
| 172 |
+
}
|
lm-evaluation-harness/examples/visualize-zeno.ipynb
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"# Visualizing Results in Zeno\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"Benchmarking your models is the first step towards making sure your model performs well.\n",
|
| 10 |
+
"However, looking at the data behind the benchmark, slicing the data into subsets, and comparing models on individual instances can help you even more in evaluating and quantifying the behavior of your AI system.\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"All of this can be done in [Zeno](https://zenoml.com)!\n",
|
| 13 |
+
"Zeno is super easy to use with the eval harness, let's explore how you can easily upload and visualize your eval results.\n"
|
| 14 |
+
]
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"cell_type": "code",
|
| 18 |
+
"execution_count": null,
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"outputs": [],
|
| 21 |
+
"source": [
|
| 22 |
+
"# Install this project if you did not already do that. This is all that needs to be installed for you to be able to visualize your data in Zeno!\n",
|
| 23 |
+
"!pip install -e ..\n",
|
| 24 |
+
"!pip install -e ..[zeno]"
|
| 25 |
+
]
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"cell_type": "markdown",
|
| 29 |
+
"metadata": {},
|
| 30 |
+
"source": [
|
| 31 |
+
"# Run the Eval Harness\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"To visualize the results, run the eval harness with the `log_samples` and `output_path` flags. We expect `output_path` to contain multiple folders that represent individual model names. You can thus run your evaluation on any number of tasks and models and upload all of the results as projects on Zeno.\n"
|
| 34 |
+
]
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"cell_type": "code",
|
| 38 |
+
"execution_count": null,
|
| 39 |
+
"metadata": {},
|
| 40 |
+
"outputs": [],
|
| 41 |
+
"source": [
|
| 42 |
+
"!lm_eval \\\n",
|
| 43 |
+
" --model hf \\\n",
|
| 44 |
+
" --model_args pretrained=EleutherAI/gpt-neo-2.7B \\\n",
|
| 45 |
+
" --tasks hellaswag,wikitext \\\n",
|
| 46 |
+
" --batch_size 8 \\\n",
|
| 47 |
+
" --device mps \\\n",
|
| 48 |
+
" --log_samples \\\n",
|
| 49 |
+
" --output_path output/gpt-neo-2.7B \\\n",
|
| 50 |
+
" --limit 10"
|
| 51 |
+
]
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "markdown",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"# Set your API Key\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"This is so you can be authenticated with Zeno.\n",
|
| 60 |
+
"If you don't already have a Zeno account, first create an account on [Zeno Hub](https://hub.zenoml.com).\n",
|
| 61 |
+
"After logging in to Zeno Hub, generate your API key by clicking on your profile at the bottom left to navigate to your account page.\n"
|
| 62 |
+
]
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"execution_count": null,
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"outputs": [],
|
| 69 |
+
"source": [
|
| 70 |
+
"%env ZENO_API_KEY=YOUR_API_KEY"
|
| 71 |
+
]
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "markdown",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# Visualize Eval Results\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"You can now use the `zeno_visualize` script to upload the results to Zeno.\n",
|
| 80 |
+
"\n",
|
| 81 |
+
"This will use all subfolders in `data_path` as different models and upload all tasks within these model folders to Zeno. If you run the eval harness on multiple tasks, the `project_name` will be used as a prefix and one project will be created per task.\n"
|
| 82 |
+
]
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"cell_type": "code",
|
| 86 |
+
"execution_count": null,
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"outputs": [],
|
| 89 |
+
"source": [
|
| 90 |
+
"!python ../scripts/zeno_visualize.py --data_path output --project_name \"Zeno Upload Test\""
|
| 91 |
+
]
|
| 92 |
+
}
|
| 93 |
+
],
|
| 94 |
+
"metadata": {
|
| 95 |
+
"kernelspec": {
|
| 96 |
+
"display_name": "zeno_projects",
|
| 97 |
+
"language": "python",
|
| 98 |
+
"name": "python3"
|
| 99 |
+
},
|
| 100 |
+
"language_info": {
|
| 101 |
+
"codemirror_mode": {
|
| 102 |
+
"name": "ipython",
|
| 103 |
+
"version": 3
|
| 104 |
+
},
|
| 105 |
+
"file_extension": ".py",
|
| 106 |
+
"mimetype": "text/x-python",
|
| 107 |
+
"name": "python",
|
| 108 |
+
"nbconvert_exporter": "python",
|
| 109 |
+
"pygments_lexer": "ipython3",
|
| 110 |
+
"version": "3.10.11"
|
| 111 |
+
}
|
| 112 |
+
},
|
| 113 |
+
"nbformat": 4,
|
| 114 |
+
"nbformat_minor": 2
|
| 115 |
+
}
|
lm-evaluation-harness/lm_eval/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
from .evaluator import evaluate, simple_evaluate
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__version__ = "0.4.8"
|
lm-evaluation-harness/lm_eval/__pycache__/evaluator.cpython-310.pyc
ADDED
|
Binary file (19.2 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/__pycache__/evaluator.cpython-311.pyc
ADDED
|
Binary file (32.7 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/__pycache__/evaluator_utils.cpython-311.pyc
ADDED
|
Binary file (24.8 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (17.1 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/__pycache__/utils.cpython-311.pyc
ADDED
|
Binary file (28.4 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__init__.py
ADDED
|
File without changes
|
lm-evaluation-harness/lm_eval/api/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (179 Bytes). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (195 Bytes). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/filter.cpython-311.pyc
ADDED
|
Binary file (3.6 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/group.cpython-310.pyc
ADDED
|
Binary file (4.62 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/group.cpython-311.pyc
ADDED
|
Binary file (6.97 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/instance.cpython-310.pyc
ADDED
|
Binary file (1.53 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/instance.cpython-311.pyc
ADDED
|
Binary file (2.24 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/metrics.cpython-310.pyc
ADDED
|
Binary file (13.4 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/metrics.cpython-311.pyc
ADDED
|
Binary file (24.1 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/model.cpython-310.pyc
ADDED
|
Binary file (18 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/model.cpython-311.pyc
ADDED
|
Binary file (24.7 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/registry.cpython-310.pyc
ADDED
|
Binary file (5.24 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/registry.cpython-311.pyc
ADDED
|
Binary file (8.62 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/samplers.cpython-310.pyc
ADDED
|
Binary file (5.67 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/samplers.cpython-311.pyc
ADDED
|
Binary file (10.4 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/task.cpython-310.pyc
ADDED
|
Binary file (47.4 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/__pycache__/task.cpython-311.pyc
ADDED
|
Binary file (83 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/api/group.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
from dataclasses import asdict, dataclass
|
| 3 |
+
from inspect import getsource
|
| 4 |
+
from typing import Any, Callable, List, Optional, Union
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@dataclass
|
| 8 |
+
class AggMetricConfig(dict):
|
| 9 |
+
metric: Optional[str] = None
|
| 10 |
+
aggregation: Optional[str] = "mean"
|
| 11 |
+
weight_by_size: Optional[str] = False
|
| 12 |
+
# list of filter names which should be incorporated into the aggregated metric.
|
| 13 |
+
filter_list: Optional[Union[str, list]] = "none"
|
| 14 |
+
|
| 15 |
+
def __post_init__(self):
|
| 16 |
+
if self.aggregation != "mean" and not callable(self.aggregation):
|
| 17 |
+
raise ValueError(
|
| 18 |
+
f"Currently, 'mean' is the only pre-defined aggregation across groups' subtasks. Got '{self.aggregation}'."
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
if isinstance(self.filter_list, str):
|
| 22 |
+
self.filter_list = [self.filter_list]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass
|
| 26 |
+
class GroupConfig(dict):
|
| 27 |
+
group: Optional[str] = None
|
| 28 |
+
group_alias: Optional[str] = None
|
| 29 |
+
task: Optional[Union[str, list]] = None
|
| 30 |
+
aggregate_metric_list: Optional[
|
| 31 |
+
Union[List[AggMetricConfig], AggMetricConfig, dict]
|
| 32 |
+
] = None
|
| 33 |
+
metadata: Optional[dict] = (
|
| 34 |
+
None # by default, not used in the code. allows for users to pass arbitrary info to tasks
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
def __getitem__(self, item):
|
| 38 |
+
return getattr(self, item)
|
| 39 |
+
|
| 40 |
+
def __setitem__(self, item, value):
|
| 41 |
+
return setattr(self, item, value)
|
| 42 |
+
|
| 43 |
+
def __post_init__(self):
|
| 44 |
+
if self.aggregate_metric_list is not None:
|
| 45 |
+
if isinstance(self.aggregate_metric_list, dict):
|
| 46 |
+
self.aggregate_metric_list = [self.aggregate_metric_list]
|
| 47 |
+
|
| 48 |
+
self.aggregate_metric_list = [
|
| 49 |
+
AggMetricConfig(**item) if isinstance(item, dict) else item
|
| 50 |
+
for item in self.aggregate_metric_list
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
def to_dict(self, keep_callable: bool = False) -> dict:
|
| 54 |
+
"""dumps the current config as a dictionary object, as a printable format.
|
| 55 |
+
null fields will not be printed.
|
| 56 |
+
Used for dumping results alongside full task configuration
|
| 57 |
+
|
| 58 |
+
:return: dict
|
| 59 |
+
A printable dictionary version of the TaskConfig object.
|
| 60 |
+
|
| 61 |
+
# TODO: should any default value in the TaskConfig not be printed?
|
| 62 |
+
"""
|
| 63 |
+
cfg_dict = asdict(self)
|
| 64 |
+
# remove values that are `None`
|
| 65 |
+
for k, v in list(cfg_dict.items()):
|
| 66 |
+
if callable(v):
|
| 67 |
+
cfg_dict[k] = self.serialize_function(v, keep_callable=keep_callable)
|
| 68 |
+
return cfg_dict
|
| 69 |
+
|
| 70 |
+
def serialize_function(
|
| 71 |
+
self, value: Union[Callable, str], keep_callable=False
|
| 72 |
+
) -> Union[Callable, str]:
|
| 73 |
+
"""Serializes a given function or string.
|
| 74 |
+
|
| 75 |
+
If 'keep_callable' is True, the original callable is returned.
|
| 76 |
+
Otherwise, attempts to return the source code of the callable using 'getsource'.
|
| 77 |
+
"""
|
| 78 |
+
if keep_callable:
|
| 79 |
+
return value
|
| 80 |
+
else:
|
| 81 |
+
try:
|
| 82 |
+
return getsource(value)
|
| 83 |
+
except (TypeError, OSError):
|
| 84 |
+
return str(value)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class ConfigurableGroup(abc.ABC):
|
| 88 |
+
def __init__(
|
| 89 |
+
self,
|
| 90 |
+
config: Optional[dict] = None,
|
| 91 |
+
) -> None:
|
| 92 |
+
self._config = GroupConfig(**config)
|
| 93 |
+
|
| 94 |
+
@property
|
| 95 |
+
def group(self):
|
| 96 |
+
return self._config.group
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def group_alias(self):
|
| 100 |
+
return self._config.group_alias
|
| 101 |
+
|
| 102 |
+
@property
|
| 103 |
+
def version(self):
|
| 104 |
+
return self._config.version
|
| 105 |
+
|
| 106 |
+
@property
|
| 107 |
+
def config(self):
|
| 108 |
+
return self._config.to_dict()
|
| 109 |
+
|
| 110 |
+
@property
|
| 111 |
+
def group_name(self) -> Any:
|
| 112 |
+
return self._config.group
|
| 113 |
+
|
| 114 |
+
def __repr__(self):
|
| 115 |
+
return f"ConfigurableGroup(group={self.group},group_alias={self.group_alias})"
|
lm-evaluation-harness/lm_eval/api/instance.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, field
|
| 2 |
+
from typing import Literal, Optional, Tuple
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
OutputType = Literal[
|
| 6 |
+
"loglikelihood", "loglikelihood_rolling", "generate_until", "multiple_choice"
|
| 7 |
+
]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class Instance:
|
| 12 |
+
request_type: OutputType
|
| 13 |
+
doc: dict
|
| 14 |
+
arguments: tuple
|
| 15 |
+
idx: int
|
| 16 |
+
metadata: Tuple[Optional[str], Optional[int], Optional[int]] = field(
|
| 17 |
+
default_factory=lambda: (None, None, None)
|
| 18 |
+
)
|
| 19 |
+
resps: list = field(default_factory=list)
|
| 20 |
+
filtered_resps: dict = field(default_factory=dict)
|
| 21 |
+
|
| 22 |
+
# initialized after init
|
| 23 |
+
task_name: Optional[str] = None
|
| 24 |
+
doc_id: Optional[int] = None
|
| 25 |
+
repeats: Optional[int] = None
|
| 26 |
+
|
| 27 |
+
def __post_init__(self) -> None:
|
| 28 |
+
# unpack metadata field
|
| 29 |
+
self.task_name, self.doc_id, self.repeats = self.metadata
|
| 30 |
+
|
| 31 |
+
@property
|
| 32 |
+
def args(self):
|
| 33 |
+
"""
|
| 34 |
+
Returns (string,) where `string` is the string to calculate loglikelihood over
|
| 35 |
+
"""
|
| 36 |
+
return (
|
| 37 |
+
self.arguments if isinstance(self.arguments, tuple) else (self.arguments,)
|
| 38 |
+
)
|
lm-evaluation-harness/lm_eval/api/metrics.py
ADDED
|
@@ -0,0 +1,578 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import math
|
| 3 |
+
import random
|
| 4 |
+
import re
|
| 5 |
+
import string
|
| 6 |
+
from collections.abc import Iterable
|
| 7 |
+
from typing import List
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import sacrebleu
|
| 11 |
+
|
| 12 |
+
from lm_eval.api.registry import register_aggregation, register_metric
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
eval_logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# Register Aggregations First
|
| 19 |
+
@register_aggregation("bypass")
|
| 20 |
+
def bypass_agg(arr):
|
| 21 |
+
return 999
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@register_aggregation("nanmean")
|
| 25 |
+
def nanmean(arr):
|
| 26 |
+
if len(arr) == 0 or all(np.isnan(arr)):
|
| 27 |
+
return np.nan
|
| 28 |
+
return np.nanmean(arr)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@register_aggregation("mean")
|
| 32 |
+
def mean(arr):
|
| 33 |
+
return sum(arr) / len(arr)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@register_aggregation("median")
|
| 37 |
+
def median(arr):
|
| 38 |
+
return arr[len(arr) // 2]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# Certain metrics must be calculated across all documents in a benchmark.
|
| 42 |
+
# We use them as aggregation metrics, paired with no-op passthrough metric fns.
|
| 43 |
+
@register_aggregation("perplexity")
|
| 44 |
+
def perplexity(items):
|
| 45 |
+
return math.exp(-mean(items))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@register_aggregation("weighted_perplexity")
|
| 49 |
+
def weighted_perplexity(items):
|
| 50 |
+
return math.exp(-weighted_mean(items))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@register_aggregation("bits_per_byte")
|
| 54 |
+
def bits_per_byte(items):
|
| 55 |
+
return -weighted_mean(items) / math.log(2)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@register_aggregation("f1")
|
| 59 |
+
def f1_score(items):
|
| 60 |
+
from sklearn.metrics import f1_score
|
| 61 |
+
|
| 62 |
+
unzipped_list = list(zip(*items))
|
| 63 |
+
golds = unzipped_list[0]
|
| 64 |
+
preds = unzipped_list[1]
|
| 65 |
+
fscore = f1_score(golds, preds)
|
| 66 |
+
|
| 67 |
+
return np.max(fscore)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@register_aggregation("matthews_corrcoef")
|
| 71 |
+
def matthews_corrcoef(items):
|
| 72 |
+
from sklearn.metrics import matthews_corrcoef
|
| 73 |
+
|
| 74 |
+
unzipped_list = list(zip(*items))
|
| 75 |
+
golds = unzipped_list[0]
|
| 76 |
+
preds = unzipped_list[1]
|
| 77 |
+
return matthews_corrcoef(golds, preds)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@register_aggregation("bleu")
|
| 81 |
+
def bleu(items):
|
| 82 |
+
"""The Bilingual Evaluation Understudy Score, or BLEU for short, is a metric
|
| 83 |
+
for evaluating a generated sentence to a reference sentence. It counts matching
|
| 84 |
+
n-grams in the candidate translation to n-grams in the reference text, where
|
| 85 |
+
1-gram or unigram would be each token and a bigram comparison would be each
|
| 86 |
+
word pair. The comparison is made regardless of word order
|
| 87 |
+
Source: https://machinelearningmastery.com/calculate-bleu-score-for-text-python/
|
| 88 |
+
Paper: https://www.aclweb.org/anthology/P02-1040/
|
| 89 |
+
|
| 90 |
+
Higher is better
|
| 91 |
+
"""
|
| 92 |
+
refs = list(zip(*items))[0]
|
| 93 |
+
preds = list(zip(*items))[1]
|
| 94 |
+
refs, preds = _sacreformat(refs, preds)
|
| 95 |
+
return sacrebleu.corpus_bleu(preds, refs).score
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@register_aggregation("chrf")
|
| 99 |
+
def chrf(items):
|
| 100 |
+
"""chrF++ is a tool for automatic evaluation of machine translation output
|
| 101 |
+
based on character n-gram precision and recall enhanced with word n-grams.
|
| 102 |
+
Source: https://github.com/m-popovic/chrF
|
| 103 |
+
Paper: https://www.aclweb.org/anthology/W15-3049.pdf
|
| 104 |
+
|
| 105 |
+
Higher is better # TODO I think
|
| 106 |
+
"""
|
| 107 |
+
refs = list(zip(*items))[0]
|
| 108 |
+
preds = list(zip(*items))[1]
|
| 109 |
+
refs, preds = _sacreformat(refs, preds)
|
| 110 |
+
return sacrebleu.corpus_chrf(preds, refs).score
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@register_aggregation("ter")
|
| 114 |
+
def ter(items):
|
| 115 |
+
"""Translation Error Rate is an error metric for machine translation that
|
| 116 |
+
measures the number of edits required to change a system output into one
|
| 117 |
+
of the references
|
| 118 |
+
Source: http://www.cs.umd.edu/~snover/tercom/
|
| 119 |
+
Paper: http://mt-archive.info/AMTA-2006-Snover.pdf
|
| 120 |
+
|
| 121 |
+
Lower is better
|
| 122 |
+
"""
|
| 123 |
+
refs = list(zip(*items))[0]
|
| 124 |
+
preds = list(zip(*items))[1]
|
| 125 |
+
refs, preds = _sacreformat(refs, preds)
|
| 126 |
+
return sacrebleu.corpus_ter(preds, refs).score
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@register_aggregation("brier_score")
|
| 130 |
+
def brier_score(items): # This is a passthrough function
|
| 131 |
+
gold, predictions = list(zip(*items))
|
| 132 |
+
bs, num_class = np.array(predictions).shape
|
| 133 |
+
|
| 134 |
+
gold = list(gold)
|
| 135 |
+
gold_one_hot = np.eye(num_class)[gold]
|
| 136 |
+
return np.mean(np.sum((predictions - gold_one_hot) ** 2, axis=1))
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@register_metric(
|
| 140 |
+
metric="brier_score",
|
| 141 |
+
higher_is_better=False,
|
| 142 |
+
output_type=["multiple_choice"],
|
| 143 |
+
aggregation="brier_score",
|
| 144 |
+
)
|
| 145 |
+
def brier_score_fn(items): # This is a passthrough function
|
| 146 |
+
return items
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
@register_metric(
|
| 150 |
+
metric="acc",
|
| 151 |
+
higher_is_better=True,
|
| 152 |
+
output_type=["loglikelihood", "multiple_choice"],
|
| 153 |
+
aggregation="mean",
|
| 154 |
+
)
|
| 155 |
+
def acc_fn(items): # This is a passthrough function
|
| 156 |
+
return items
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@register_metric(
|
| 160 |
+
metric="acc_norm",
|
| 161 |
+
higher_is_better=True,
|
| 162 |
+
output_type=["loglikelihood", "multiple_choice"],
|
| 163 |
+
aggregation="mean",
|
| 164 |
+
)
|
| 165 |
+
def acc_norm_fn(items): # This is a passthrough function
|
| 166 |
+
return items
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@register_metric(
|
| 170 |
+
metric="acc_mutual_info",
|
| 171 |
+
higher_is_better=True,
|
| 172 |
+
output_type="multiple_choice",
|
| 173 |
+
aggregation="mean",
|
| 174 |
+
)
|
| 175 |
+
def acc_mutual_info_fn(items): # This is a passthrough function
|
| 176 |
+
return items
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
### the code used in the `exact_match_hf_evaluate` function is ported from
|
| 180 |
+
### https://github.com/huggingface/evaluate/blob/main/metrics/exact_match/exact_match.py
|
| 181 |
+
### which is under the apache license.
|
| 182 |
+
|
| 183 |
+
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
|
| 184 |
+
|
| 185 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 186 |
+
# you may not use this file except in compliance with the License.
|
| 187 |
+
# You may obtain a copy of the License at
|
| 188 |
+
|
| 189 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 193 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 194 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 195 |
+
# See the License for the specific language governing permissions and
|
| 196 |
+
# limitations under the License.
|
| 197 |
+
def exact_match_hf_evaluate(
|
| 198 |
+
predictions,
|
| 199 |
+
references,
|
| 200 |
+
regexes_to_ignore=None,
|
| 201 |
+
ignore_case=False,
|
| 202 |
+
ignore_punctuation=False,
|
| 203 |
+
ignore_numbers=False,
|
| 204 |
+
):
|
| 205 |
+
if regexes_to_ignore is not None:
|
| 206 |
+
for s in regexes_to_ignore:
|
| 207 |
+
predictions = np.array([re.sub(s, "", x) for x in predictions])
|
| 208 |
+
references = np.array([re.sub(s, "", x) for x in references])
|
| 209 |
+
else:
|
| 210 |
+
predictions = np.asarray(predictions)
|
| 211 |
+
references = np.asarray(references)
|
| 212 |
+
|
| 213 |
+
if ignore_case:
|
| 214 |
+
predictions = np.char.lower(predictions)
|
| 215 |
+
references = np.char.lower(references)
|
| 216 |
+
|
| 217 |
+
if ignore_punctuation:
|
| 218 |
+
repl_table = string.punctuation.maketrans("", "", string.punctuation)
|
| 219 |
+
predictions = np.char.translate(predictions, table=repl_table)
|
| 220 |
+
references = np.char.translate(references, table=repl_table)
|
| 221 |
+
|
| 222 |
+
if ignore_numbers:
|
| 223 |
+
repl_table = string.digits.maketrans("", "", string.digits)
|
| 224 |
+
predictions = np.char.translate(predictions, table=repl_table)
|
| 225 |
+
references = np.char.translate(references, table=repl_table)
|
| 226 |
+
|
| 227 |
+
score_list = predictions == references
|
| 228 |
+
|
| 229 |
+
return {"exact_match": np.mean(score_list)}
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
###
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@register_metric(
|
| 236 |
+
metric="exact_match",
|
| 237 |
+
higher_is_better=True,
|
| 238 |
+
output_type="generate_until",
|
| 239 |
+
aggregation="mean",
|
| 240 |
+
)
|
| 241 |
+
def exact_match_fn(**kwargs):
|
| 242 |
+
return exact_match_hf_evaluate(**kwargs)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@register_metric(
|
| 246 |
+
metric="perplexity",
|
| 247 |
+
higher_is_better=False,
|
| 248 |
+
output_type="loglikelihood",
|
| 249 |
+
aggregation="perplexity",
|
| 250 |
+
)
|
| 251 |
+
def perplexity_fn(items): # This is a passthrough function
|
| 252 |
+
return items
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
@register_metric(
|
| 256 |
+
metric="word_perplexity",
|
| 257 |
+
higher_is_better=False,
|
| 258 |
+
output_type="loglikelihood_rolling",
|
| 259 |
+
aggregation="weighted_perplexity",
|
| 260 |
+
)
|
| 261 |
+
def word_perplexity_fn(items): # This is a passthrough function
|
| 262 |
+
return items
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@register_metric(
|
| 266 |
+
metric="byte_perplexity",
|
| 267 |
+
higher_is_better=False,
|
| 268 |
+
output_type="loglikelihood_rolling",
|
| 269 |
+
aggregation="weighted_perplexity",
|
| 270 |
+
)
|
| 271 |
+
def byte_perplexity_fn(items): # This is a passthrough function
|
| 272 |
+
return items
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
@register_metric(
|
| 276 |
+
metric="bits_per_byte",
|
| 277 |
+
higher_is_better=False,
|
| 278 |
+
output_type="loglikelihood_rolling",
|
| 279 |
+
aggregation="bits_per_byte",
|
| 280 |
+
)
|
| 281 |
+
def bits_per_byte_fn(items): # This is a passthrough function
|
| 282 |
+
return items
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def pop_stddev(arr):
|
| 286 |
+
mu = mean(arr)
|
| 287 |
+
return math.sqrt(sum([(x - mu) ** 2 for x in arr]) / len(arr))
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def sample_stddev(arr):
|
| 291 |
+
mu = mean(arr)
|
| 292 |
+
return math.sqrt(sum([(x - mu) ** 2 for x in arr]) / (len(arr) - 1))
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def mean_stderr(arr):
|
| 296 |
+
return sample_stddev(arr) / math.sqrt(len(arr))
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
@register_metric(
|
| 300 |
+
metric="bypass",
|
| 301 |
+
higher_is_better=True,
|
| 302 |
+
output_type=["loglikelihood", "multiple_choice", "generate_until"],
|
| 303 |
+
aggregation="bypass",
|
| 304 |
+
)
|
| 305 |
+
def bypass(items):
|
| 306 |
+
return None
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
@register_metric(
|
| 310 |
+
metric="mcc",
|
| 311 |
+
higher_is_better=True,
|
| 312 |
+
output_type="multiple_choice",
|
| 313 |
+
aggregation="matthews_corrcoef",
|
| 314 |
+
)
|
| 315 |
+
def mcc_fn(items): # This is a passthrough function
|
| 316 |
+
return items
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@register_metric(
|
| 320 |
+
metric="f1",
|
| 321 |
+
higher_is_better=True,
|
| 322 |
+
output_type="multiple_choice",
|
| 323 |
+
aggregation="f1",
|
| 324 |
+
)
|
| 325 |
+
def f1_fn(items): # This is a passthrough function
|
| 326 |
+
return items
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
@register_metric(
|
| 330 |
+
metric="bleu",
|
| 331 |
+
higher_is_better=True,
|
| 332 |
+
output_type="generate_until",
|
| 333 |
+
aggregation="bleu",
|
| 334 |
+
)
|
| 335 |
+
def bleu_fn(items): # This is a passthrough function
|
| 336 |
+
return items
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@register_metric(
|
| 340 |
+
metric="chrf",
|
| 341 |
+
higher_is_better=True,
|
| 342 |
+
output_type="generate_until",
|
| 343 |
+
aggregation="chrf",
|
| 344 |
+
)
|
| 345 |
+
def chrf_fn(items): # This is a passthrough function
|
| 346 |
+
return items
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
@register_metric(
|
| 350 |
+
metric="ter",
|
| 351 |
+
higher_is_better=True,
|
| 352 |
+
output_type="generate_until",
|
| 353 |
+
aggregation="ter",
|
| 354 |
+
)
|
| 355 |
+
def ter_fn(items): # This is a passthrough function
|
| 356 |
+
return items
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
@register_metric(
|
| 360 |
+
metric="acc_all",
|
| 361 |
+
higher_is_better=True,
|
| 362 |
+
output_type="loglikelihood",
|
| 363 |
+
aggregation="mean",
|
| 364 |
+
)
|
| 365 |
+
def acc_all(items):
|
| 366 |
+
# Only count as correct if all answers are labeled correctly for each question
|
| 367 |
+
question_scoring_dict = {}
|
| 368 |
+
preds = list(zip(*items))[0]
|
| 369 |
+
docs = list(zip(*items))[1]
|
| 370 |
+
|
| 371 |
+
for doc, pred in zip(docs, preds):
|
| 372 |
+
paragraph_id = doc["idx"]["paragraph"]
|
| 373 |
+
question_id = doc["idx"]["question"]
|
| 374 |
+
if (paragraph_id, question_id) not in question_scoring_dict:
|
| 375 |
+
question_scoring_dict[(paragraph_id, question_id)] = []
|
| 376 |
+
|
| 377 |
+
gold_label = doc["label"] == 1
|
| 378 |
+
|
| 379 |
+
question_scoring_dict[(paragraph_id, question_id)].append(gold_label == pred)
|
| 380 |
+
acc = np.mean([int(all(x)) for x in question_scoring_dict.values()])
|
| 381 |
+
return acc
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def acc_all_stderr(items):
|
| 385 |
+
# Only count as correct if all answers are labeled correctly for each question
|
| 386 |
+
question_scoring_dict = {}
|
| 387 |
+
preds = list(zip(*items))[0]
|
| 388 |
+
docs = list(zip(*items))[1]
|
| 389 |
+
|
| 390 |
+
for doc, pred in zip(docs, preds):
|
| 391 |
+
question_id = doc["idx"]["question"]
|
| 392 |
+
if question_id not in question_scoring_dict:
|
| 393 |
+
question_scoring_dict[question_id] = []
|
| 394 |
+
|
| 395 |
+
gold_label = doc["label"] == 1
|
| 396 |
+
question_scoring_dict[question_id].append(gold_label == pred)
|
| 397 |
+
|
| 398 |
+
acc = mean_stderr([int(all(x)) for x in question_scoring_dict.values()])
|
| 399 |
+
return acc
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
|
| 403 |
+
"""Compute max metric between prediction and each ground truth."""
|
| 404 |
+
scores_for_ground_truths = []
|
| 405 |
+
for ground_truth in ground_truths:
|
| 406 |
+
score = metric_fn(prediction, ground_truth)
|
| 407 |
+
scores_for_ground_truths.append(score)
|
| 408 |
+
return max(scores_for_ground_truths)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def weighted_mean(items):
|
| 412 |
+
a, b = zip(*items)
|
| 413 |
+
return sum(a) / sum(b)
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def is_non_str_iterable(obj):
|
| 417 |
+
return isinstance(obj, Iterable) and not isinstance(obj, str)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def _sacreformat(refs, preds):
|
| 421 |
+
"""Format refs and preds for sacrebleu corpus calculation. It is very particular"""
|
| 422 |
+
# Sacrebleu expects (List[str], List[List[str])
|
| 423 |
+
# e.g. sacrebleu.corpus_bleu([pred_t], [[ref1_stream], [ref2_stream], ...])
|
| 424 |
+
|
| 425 |
+
# Note [ref1_stream] is the first reference for each pred.
|
| 426 |
+
# So lists are size N and (M, N) for N preds and M possible refs for each pred
|
| 427 |
+
# This is a different order of dimensions that I would expect
|
| 428 |
+
|
| 429 |
+
# We expect refs to be List[str] or List[List[str]], the outer list corresponding to preds
|
| 430 |
+
# Must become List[List[str]] with the inner list corresponding to preds
|
| 431 |
+
if not is_non_str_iterable(refs):
|
| 432 |
+
refs = list(refs)
|
| 433 |
+
if not is_non_str_iterable(refs[0]):
|
| 434 |
+
refs = [[ref] for ref in refs]
|
| 435 |
+
refs = list(zip(*refs))
|
| 436 |
+
# Note the number of refs in each ref list much match the number of preds
|
| 437 |
+
|
| 438 |
+
# We expect preds to be List[str] or List[List[str]]. Must become List[str]
|
| 439 |
+
if not is_non_str_iterable(preds):
|
| 440 |
+
preds = list(preds)
|
| 441 |
+
if is_non_str_iterable(preds[0]):
|
| 442 |
+
assert len(preds[0]) == 1, f"Pred must be a str, was {preds[0]}"
|
| 443 |
+
preds = [pred[0] for pred in preds]
|
| 444 |
+
|
| 445 |
+
return refs, preds
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
# stderr stuff
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
class _bootstrap_internal:
|
| 452 |
+
def __init__(self, f, n) -> None:
|
| 453 |
+
self.f = f
|
| 454 |
+
self.n = n
|
| 455 |
+
|
| 456 |
+
def __call__(self, v):
|
| 457 |
+
i, xs = v
|
| 458 |
+
rnd = random.Random()
|
| 459 |
+
rnd.seed(i)
|
| 460 |
+
res = []
|
| 461 |
+
for _ in range(self.n):
|
| 462 |
+
res.append(self.f(rnd.choices(xs, k=len(xs))))
|
| 463 |
+
return res
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def bootstrap_stderr(f, xs, iters):
|
| 467 |
+
import multiprocessing as mp
|
| 468 |
+
|
| 469 |
+
pool = mp.Pool(mp.cpu_count())
|
| 470 |
+
# this gives a biased estimate of the stderr (i.e w/ the mean, it gives something
|
| 471 |
+
# equivalent to stderr calculated without Bessel's correction in the stddev.
|
| 472 |
+
# Unfortunately, I haven't been able to figure out what the right correction is
|
| 473 |
+
# to make the bootstrap unbiased - i considered multiplying by sqrt(n/(n-1)) but
|
| 474 |
+
# that would be ad-hoc and I can't prove that that would actually be an unbiased estimator)
|
| 475 |
+
# Thankfully, shouldn't matter because our samples are pretty big usually anyways
|
| 476 |
+
res = []
|
| 477 |
+
chunk_size = min(1000, iters)
|
| 478 |
+
from tqdm import tqdm
|
| 479 |
+
|
| 480 |
+
print("bootstrapping for stddev:", f.__name__)
|
| 481 |
+
for bootstrap in tqdm(
|
| 482 |
+
pool.imap(
|
| 483 |
+
_bootstrap_internal(f, chunk_size),
|
| 484 |
+
[(i, xs) for i in range(iters // chunk_size)],
|
| 485 |
+
),
|
| 486 |
+
total=iters // chunk_size,
|
| 487 |
+
):
|
| 488 |
+
# sample w replacement
|
| 489 |
+
res.extend(bootstrap)
|
| 490 |
+
|
| 491 |
+
pool.close()
|
| 492 |
+
return sample_stddev(res)
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def stderr_for_metric(metric, bootstrap_iters: int):
|
| 496 |
+
if bootstrap_iters <= 0:
|
| 497 |
+
# return no function (don't compute stderr) if bootstrap iters = 0
|
| 498 |
+
return None
|
| 499 |
+
|
| 500 |
+
bootstrappable = [
|
| 501 |
+
median,
|
| 502 |
+
matthews_corrcoef,
|
| 503 |
+
f1_score,
|
| 504 |
+
perplexity,
|
| 505 |
+
bleu,
|
| 506 |
+
chrf,
|
| 507 |
+
ter,
|
| 508 |
+
nanmean,
|
| 509 |
+
]
|
| 510 |
+
|
| 511 |
+
if metric in bootstrappable:
|
| 512 |
+
return lambda x: bootstrap_stderr(metric, x, iters=bootstrap_iters)
|
| 513 |
+
|
| 514 |
+
stderr = {mean: mean_stderr, acc_all: acc_all_stderr}
|
| 515 |
+
|
| 516 |
+
return stderr.get(metric, None)
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def pooled_sample_stderr(stderrs: List[float], sizes: List[int]):
|
| 520 |
+
# Used to aggregate bootstrapped stderrs across subtasks in a group,
|
| 521 |
+
# when we are weighting by the size of each subtask.
|
| 522 |
+
#
|
| 523 |
+
|
| 524 |
+
assert len(stderrs) == len(sizes)
|
| 525 |
+
|
| 526 |
+
# formula source: https://en.wikipedia.org/wiki/Pooled_variance
|
| 527 |
+
# and: https://stats.stackexchange.com/a/4841331
|
| 528 |
+
# this empirically seems to match running `stderr_for_metric` on all instances
|
| 529 |
+
# from the subtasks concatenated with each other.
|
| 530 |
+
pooled_sample_var = (
|
| 531 |
+
sum([(size - 1) * stderr**2 * size for size, stderr in zip(sizes, stderrs)])
|
| 532 |
+
) / (sum(sizes) - len(sizes))
|
| 533 |
+
|
| 534 |
+
return np.sqrt(pooled_sample_var / sum(sizes))
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def combined_sample_stderr(stderrs: List[float], sizes: List[int], metrics=None):
|
| 538 |
+
assert metrics is not None, (
|
| 539 |
+
"Need to pass a list of each subtask's metric for this stderr aggregation"
|
| 540 |
+
)
|
| 541 |
+
assert len(stderrs) == len(sizes) and len(sizes) == len(metrics)
|
| 542 |
+
|
| 543 |
+
# See https://github.com/EleutherAI/lm-evaluation-harness/pull/1390 for more documentation.
|
| 544 |
+
# This formula depends on sample means.
|
| 545 |
+
# removed because it seems to give erroneously huge stderrs for groupings of tasks
|
| 546 |
+
# and does not seem to match up with bootstrap-calculated stderrs for groups.
|
| 547 |
+
|
| 548 |
+
### don't use this unless a statistician has told you it's the right thing to do ###
|
| 549 |
+
|
| 550 |
+
# accumulators: we'll aggregate pairwise N - 1 times
|
| 551 |
+
variance = stderrs[0] ** 2
|
| 552 |
+
curr_size = sizes[0]
|
| 553 |
+
curr_score = metrics[0]
|
| 554 |
+
|
| 555 |
+
for stderr, size, score in zip(stderrs[1:], sizes[1:], metrics[1:]):
|
| 556 |
+
curr_score = ((curr_score * curr_size) + (score * size)) / (
|
| 557 |
+
curr_size + size
|
| 558 |
+
) # NOTE: this assumes our aggregation fn is "mean"
|
| 559 |
+
|
| 560 |
+
variance = ((curr_size - 1) * variance + (size - 1) * (stderr**2)) / (
|
| 561 |
+
curr_size + size - 1
|
| 562 |
+
) + curr_size * size / ((curr_size + size) * (curr_size + size - 1)) * (
|
| 563 |
+
curr_score - score
|
| 564 |
+
) ** 2
|
| 565 |
+
|
| 566 |
+
return np.sqrt(variance)
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def aggregate_subtask_metrics(metrics, sizes, weight_by_size=True):
|
| 570 |
+
# A helper function that is used to aggregate
|
| 571 |
+
# subtask scores cross-task.
|
| 572 |
+
# TODO: does not hold for non-mean aggregations
|
| 573 |
+
if not weight_by_size:
|
| 574 |
+
sizes = [1] * len(sizes)
|
| 575 |
+
|
| 576 |
+
assert len(metrics) == len(sizes)
|
| 577 |
+
|
| 578 |
+
return sum([metric * size for metric, size in zip(metrics, sizes)]) / sum(sizes)
|
lm-evaluation-harness/lm_eval/api/registry.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from typing import Callable, Dict, Union
|
| 3 |
+
|
| 4 |
+
import evaluate as hf_evaluate
|
| 5 |
+
|
| 6 |
+
from lm_eval.api.model import LM
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
eval_logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
MODEL_REGISTRY = {}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def register_model(*names):
|
| 15 |
+
# either pass a list or a single alias.
|
| 16 |
+
# function receives them as a tuple of strings
|
| 17 |
+
|
| 18 |
+
def decorate(cls):
|
| 19 |
+
for name in names:
|
| 20 |
+
assert issubclass(cls, LM), (
|
| 21 |
+
f"Model '{name}' ({cls.__name__}) must extend LM class"
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
assert name not in MODEL_REGISTRY, (
|
| 25 |
+
f"Model named '{name}' conflicts with existing model! Please register with a non-conflicting alias instead."
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
MODEL_REGISTRY[name] = cls
|
| 29 |
+
return cls
|
| 30 |
+
|
| 31 |
+
return decorate
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def get_model(model_name):
|
| 35 |
+
try:
|
| 36 |
+
return MODEL_REGISTRY[model_name]
|
| 37 |
+
except KeyError:
|
| 38 |
+
raise ValueError(
|
| 39 |
+
f"Attempted to load model '{model_name}', but no model for this name found! Supported model names: {', '.join(MODEL_REGISTRY.keys())}"
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
TASK_REGISTRY = {}
|
| 44 |
+
GROUP_REGISTRY = {}
|
| 45 |
+
ALL_TASKS = set()
|
| 46 |
+
func2task_index = {}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def register_task(name):
|
| 50 |
+
def decorate(fn):
|
| 51 |
+
assert name not in TASK_REGISTRY, (
|
| 52 |
+
f"task named '{name}' conflicts with existing registered task!"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
TASK_REGISTRY[name] = fn
|
| 56 |
+
ALL_TASKS.add(name)
|
| 57 |
+
func2task_index[fn.__name__] = name
|
| 58 |
+
return fn
|
| 59 |
+
|
| 60 |
+
return decorate
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def register_group(name):
|
| 64 |
+
def decorate(fn):
|
| 65 |
+
func_name = func2task_index[fn.__name__]
|
| 66 |
+
if name in GROUP_REGISTRY:
|
| 67 |
+
GROUP_REGISTRY[name].append(func_name)
|
| 68 |
+
else:
|
| 69 |
+
GROUP_REGISTRY[name] = [func_name]
|
| 70 |
+
ALL_TASKS.add(name)
|
| 71 |
+
return fn
|
| 72 |
+
|
| 73 |
+
return decorate
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
OUTPUT_TYPE_REGISTRY = {}
|
| 77 |
+
METRIC_REGISTRY = {}
|
| 78 |
+
METRIC_AGGREGATION_REGISTRY = {}
|
| 79 |
+
AGGREGATION_REGISTRY: Dict[str, Callable[[], Dict[str, Callable]]] = {}
|
| 80 |
+
HIGHER_IS_BETTER_REGISTRY = {}
|
| 81 |
+
FILTER_REGISTRY = {}
|
| 82 |
+
|
| 83 |
+
DEFAULT_METRIC_REGISTRY = {
|
| 84 |
+
"loglikelihood": [
|
| 85 |
+
"perplexity",
|
| 86 |
+
"acc",
|
| 87 |
+
],
|
| 88 |
+
"loglikelihood_rolling": ["word_perplexity", "byte_perplexity", "bits_per_byte"],
|
| 89 |
+
"multiple_choice": ["acc", "acc_norm"],
|
| 90 |
+
"generate_until": ["exact_match"],
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def register_metric(**args):
|
| 95 |
+
# TODO: do we want to enforce a certain interface to registered metrics?
|
| 96 |
+
def decorate(fn):
|
| 97 |
+
assert "metric" in args
|
| 98 |
+
name = args["metric"]
|
| 99 |
+
|
| 100 |
+
for key, registry in [
|
| 101 |
+
("metric", METRIC_REGISTRY),
|
| 102 |
+
("higher_is_better", HIGHER_IS_BETTER_REGISTRY),
|
| 103 |
+
("aggregation", METRIC_AGGREGATION_REGISTRY),
|
| 104 |
+
]:
|
| 105 |
+
if key in args:
|
| 106 |
+
value = args[key]
|
| 107 |
+
assert value not in registry, (
|
| 108 |
+
f"{key} named '{value}' conflicts with existing registered {key}!"
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
if key == "metric":
|
| 112 |
+
registry[name] = fn
|
| 113 |
+
elif key == "aggregation":
|
| 114 |
+
registry[name] = AGGREGATION_REGISTRY[value]
|
| 115 |
+
else:
|
| 116 |
+
registry[name] = value
|
| 117 |
+
|
| 118 |
+
return fn
|
| 119 |
+
|
| 120 |
+
return decorate
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def get_metric(name: str, hf_evaluate_metric=False) -> Callable:
|
| 124 |
+
if not hf_evaluate_metric:
|
| 125 |
+
if name in METRIC_REGISTRY:
|
| 126 |
+
return METRIC_REGISTRY[name]
|
| 127 |
+
else:
|
| 128 |
+
eval_logger.warning(
|
| 129 |
+
f"Could not find registered metric '{name}' in lm-eval, searching in HF Evaluate library..."
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
try:
|
| 133 |
+
metric_object = hf_evaluate.load(name)
|
| 134 |
+
return metric_object.compute
|
| 135 |
+
except Exception:
|
| 136 |
+
eval_logger.error(
|
| 137 |
+
f"{name} not found in the evaluate library! Please check https://huggingface.co/evaluate-metric",
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def register_aggregation(name: str):
|
| 142 |
+
def decorate(fn):
|
| 143 |
+
assert name not in AGGREGATION_REGISTRY, (
|
| 144 |
+
f"aggregation named '{name}' conflicts with existing registered aggregation!"
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
AGGREGATION_REGISTRY[name] = fn
|
| 148 |
+
return fn
|
| 149 |
+
|
| 150 |
+
return decorate
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def get_aggregation(name: str) -> Callable[[], Dict[str, Callable]]:
|
| 154 |
+
try:
|
| 155 |
+
return AGGREGATION_REGISTRY[name]
|
| 156 |
+
except KeyError:
|
| 157 |
+
eval_logger.warning(f"{name} not a registered aggregation metric!")
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def get_metric_aggregation(name: str) -> Callable[[], Dict[str, Callable]]:
|
| 161 |
+
try:
|
| 162 |
+
return METRIC_AGGREGATION_REGISTRY[name]
|
| 163 |
+
except KeyError:
|
| 164 |
+
eval_logger.warning(f"{name} metric is not assigned a default aggregation!")
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def is_higher_better(metric_name) -> bool:
|
| 168 |
+
try:
|
| 169 |
+
return HIGHER_IS_BETTER_REGISTRY[metric_name]
|
| 170 |
+
except KeyError:
|
| 171 |
+
eval_logger.warning(
|
| 172 |
+
f"higher_is_better not specified for metric '{metric_name}'!"
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def register_filter(name):
|
| 177 |
+
def decorate(cls):
|
| 178 |
+
if name in FILTER_REGISTRY:
|
| 179 |
+
eval_logger.info(
|
| 180 |
+
f"Registering filter `{name}` that is already in Registry {FILTER_REGISTRY}"
|
| 181 |
+
)
|
| 182 |
+
FILTER_REGISTRY[name] = cls
|
| 183 |
+
return cls
|
| 184 |
+
|
| 185 |
+
return decorate
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def get_filter(filter_name: Union[str, Callable]) -> Callable:
|
| 189 |
+
try:
|
| 190 |
+
return FILTER_REGISTRY[filter_name]
|
| 191 |
+
except KeyError as e:
|
| 192 |
+
if callable(filter_name):
|
| 193 |
+
return filter_name
|
| 194 |
+
else:
|
| 195 |
+
eval_logger.warning(f"filter `{filter_name}` is not registered!")
|
| 196 |
+
raise e
|
lm-evaluation-harness/lm_eval/api/samplers.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 5 |
+
|
| 6 |
+
import datasets
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
from random import Random
|
| 11 |
+
|
| 12 |
+
from lm_eval.api.task import ConfigurableTask, Task
|
| 13 |
+
|
| 14 |
+
eval_logger = logging.getLogger("lm-eval")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class ContextSampler:
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
docs: list[dict],
|
| 21 |
+
task: Union["Task", "ConfigurableTask"],
|
| 22 |
+
fewshot_indices: Optional[Iterable] = None,
|
| 23 |
+
rnd: Optional["Random"] = None,
|
| 24 |
+
) -> None:
|
| 25 |
+
self.rnd = rnd
|
| 26 |
+
if not self.rnd:
|
| 27 |
+
raise ValueError(
|
| 28 |
+
"A `random.Random` generator argument must be provided to `rnd` of FewShotSampler!"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
self.task = task
|
| 32 |
+
self.config = task._config
|
| 33 |
+
|
| 34 |
+
self.target_delimiter = self.config.target_delimiter
|
| 35 |
+
self.fewshot_delimiter = self.config.fewshot_delimiter
|
| 36 |
+
|
| 37 |
+
if (
|
| 38 |
+
self.config.fewshot_config is not None
|
| 39 |
+
and self.config.fewshot_config.get("doc_to_text", None) is not None
|
| 40 |
+
):
|
| 41 |
+
self.doc_to_text = partial(
|
| 42 |
+
self.task.doc_to_text,
|
| 43 |
+
doc_to_text=self.config.fewshot_config.get("doc_to_text", None),
|
| 44 |
+
)
|
| 45 |
+
else:
|
| 46 |
+
self.doc_to_text = self.task.doc_to_text
|
| 47 |
+
|
| 48 |
+
if (
|
| 49 |
+
self.config.fewshot_config is not None
|
| 50 |
+
and self.config.fewshot_config.get("doc_to_target", None) is not None
|
| 51 |
+
):
|
| 52 |
+
self.doc_to_target = partial(
|
| 53 |
+
self.task.doc_to_target,
|
| 54 |
+
doc_to_target=self.config.fewshot_config.get("doc_to_target", None),
|
| 55 |
+
)
|
| 56 |
+
else:
|
| 57 |
+
self.doc_to_target = self.task.doc_to_target
|
| 58 |
+
|
| 59 |
+
if (
|
| 60 |
+
self.config.fewshot_config is not None
|
| 61 |
+
and self.config.fewshot_config.get("doc_to_choice", None) is not None
|
| 62 |
+
):
|
| 63 |
+
self.doc_to_choice = partial(
|
| 64 |
+
self.task.doc_to_choice,
|
| 65 |
+
doc_to_choice=self.config.fewshot_config.get("doc_to_choice", None),
|
| 66 |
+
)
|
| 67 |
+
else:
|
| 68 |
+
self.doc_to_choice = self.task.doc_to_choice
|
| 69 |
+
|
| 70 |
+
self.docs = docs # HF dataset split, provided by task._fewshot_docs()
|
| 71 |
+
if fewshot_indices: # subset few-shot docs from
|
| 72 |
+
if not isinstance(self.docs, datasets.Dataset):
|
| 73 |
+
raise ValueError(
|
| 74 |
+
"Got `fewshot_indices` but fewshot_docs are not a HF dataset. Don't use both `fewshot_indices` and a user-defined few-shot sample list simultaneously"
|
| 75 |
+
)
|
| 76 |
+
self.docs = self.docs.select(fewshot_indices)
|
| 77 |
+
|
| 78 |
+
def get_context(self, doc: dict, num_fewshot: int, gen_prefix: str = None):
|
| 79 |
+
# draw an extra fewshot sample if using same split as evaluating on
|
| 80 |
+
prefix = gen_prefix + " " if gen_prefix else ""
|
| 81 |
+
n_samples = (
|
| 82 |
+
num_fewshot + 1
|
| 83 |
+
if self.config.fewshot_split == self.config.test_split
|
| 84 |
+
else num_fewshot
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
# draw `n_samples` docs from fewshot_docs
|
| 88 |
+
fewshotex = self.sample(n_samples)
|
| 89 |
+
|
| 90 |
+
# get rid of the doc that's the one we're evaluating, if it's in the fewshot
|
| 91 |
+
# TODO: should we just stop people from using fewshot from same split as evaluating?
|
| 92 |
+
selected_docs = [x for x in fewshotex if x != doc][:num_fewshot]
|
| 93 |
+
|
| 94 |
+
labeled_examples = ""
|
| 95 |
+
for doc in selected_docs:
|
| 96 |
+
doc_content = self.doc_to_text(doc)
|
| 97 |
+
doc_target = self.doc_to_target(doc)
|
| 98 |
+
if self.config.doc_to_choice is None or isinstance(doc_content, str):
|
| 99 |
+
labeled_examples += doc_content
|
| 100 |
+
else:
|
| 101 |
+
labeled_examples += self.doc_to_choice(doc)[doc_content]
|
| 102 |
+
|
| 103 |
+
if doc_target != "":
|
| 104 |
+
if self.target_delimiter.isspace() and str(doc_target)[0].isspace():
|
| 105 |
+
# TODO: add logger warn once here.
|
| 106 |
+
warnings.warn(
|
| 107 |
+
"Both target_delimiter and target start with a space. This may cause issues.",
|
| 108 |
+
Warning,
|
| 109 |
+
stacklevel=2,
|
| 110 |
+
)
|
| 111 |
+
labeled_examples += self.target_delimiter
|
| 112 |
+
labeled_examples += prefix
|
| 113 |
+
labeled_examples += (
|
| 114 |
+
str(doc_target[0])
|
| 115 |
+
if isinstance(doc_target, list)
|
| 116 |
+
else doc_target
|
| 117 |
+
if self.config.doc_to_choice is None or isinstance(doc_target, str)
|
| 118 |
+
else str(self.doc_to_choice(doc)[doc_target])
|
| 119 |
+
)
|
| 120 |
+
labeled_examples += self.fewshot_delimiter
|
| 121 |
+
|
| 122 |
+
return labeled_examples
|
| 123 |
+
|
| 124 |
+
def get_chat_context(
|
| 125 |
+
self,
|
| 126 |
+
doc: dict,
|
| 127 |
+
num_fewshot: int,
|
| 128 |
+
fewshot_as_multiturn: bool = False,
|
| 129 |
+
gen_prefix: Optional[str] = None,
|
| 130 |
+
):
|
| 131 |
+
# TODO: Do we need any other delimiter
|
| 132 |
+
prefix = gen_prefix + " " if gen_prefix else ""
|
| 133 |
+
chat_history = []
|
| 134 |
+
# draw an extra fewshot sample if using same split as evaluating on
|
| 135 |
+
n_samples = (
|
| 136 |
+
num_fewshot + 1
|
| 137 |
+
if self.config.fewshot_split == self.config.test_split
|
| 138 |
+
else num_fewshot
|
| 139 |
+
)
|
| 140 |
+
# draw `n_samples` docs from fewshot_docs
|
| 141 |
+
fewshotex = self.sample(n_samples)
|
| 142 |
+
|
| 143 |
+
# get rid of the doc that's the one we're evaluating, if it's in the fewshot
|
| 144 |
+
# TODO: should we just stop people from using fewshot from same split as evaluating?
|
| 145 |
+
selected_docs = [x for x in fewshotex if x != doc][:num_fewshot]
|
| 146 |
+
|
| 147 |
+
if fewshot_as_multiturn:
|
| 148 |
+
for doc in selected_docs:
|
| 149 |
+
doc_content = self.doc_to_text(doc)
|
| 150 |
+
doc_target = self.doc_to_target(doc)
|
| 151 |
+
chat_history.append(
|
| 152 |
+
{
|
| 153 |
+
"role": "user",
|
| 154 |
+
"content": doc_content
|
| 155 |
+
if self.config.doc_to_choice is None
|
| 156 |
+
or isinstance(doc_content, str)
|
| 157 |
+
else self.doc_to_choice(doc)[doc_content],
|
| 158 |
+
}
|
| 159 |
+
)
|
| 160 |
+
chat_history.append(
|
| 161 |
+
{
|
| 162 |
+
"role": "assistant",
|
| 163 |
+
"content": prefix + str(doc_target[0])
|
| 164 |
+
if isinstance(doc_target, list)
|
| 165 |
+
else prefix + doc_target
|
| 166 |
+
if self.config.doc_to_choice is None
|
| 167 |
+
or isinstance(doc_target, str)
|
| 168 |
+
else prefix + str(self.doc_to_choice(doc)[doc_target]),
|
| 169 |
+
}
|
| 170 |
+
)
|
| 171 |
+
else:
|
| 172 |
+
# get fewshot context as one user turn
|
| 173 |
+
chat_history.append(
|
| 174 |
+
{
|
| 175 |
+
"role": "user",
|
| 176 |
+
"content": self.get_context(
|
| 177 |
+
doc, num_fewshot, gen_prefix=gen_prefix
|
| 178 |
+
),
|
| 179 |
+
}
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
return chat_history
|
| 183 |
+
|
| 184 |
+
def sample(self, n: int):
|
| 185 |
+
"""
|
| 186 |
+
Draw `n` samples from our fewshot docs. This method should be overridden by subclasses.
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
return self.rnd.sample(self.docs, n)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class FirstNSampler(ContextSampler):
|
| 193 |
+
def sample(self, n: int) -> None:
|
| 194 |
+
"""
|
| 195 |
+
Draw the first `n` samples in order from the specified split.
|
| 196 |
+
Used for tasks with "canonical" ordered fewshot examples, such as MMLU and CMMLU.
|
| 197 |
+
"""
|
| 198 |
+
assert n <= len(self.docs), (
|
| 199 |
+
f"Error: number of fewshot samples requested exceeds the {len(self.docs)} that are available."
|
| 200 |
+
)
|
| 201 |
+
return self.docs[:n]
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class BalancedSampler(ContextSampler):
|
| 205 |
+
def sample(self, n: int) -> None:
|
| 206 |
+
"""
|
| 207 |
+
TODO: this should return approximately class-balanced samples from our fewshot examples.
|
| 208 |
+
TODO: what order should they be in? maybe random?
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
pass
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class ManualSampler(ContextSampler):
|
| 215 |
+
def sample(self, n: int) -> None:
|
| 216 |
+
""" """
|
| 217 |
+
pass
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
SAMPLER_REGISTRY = {
|
| 221 |
+
"default": ContextSampler,
|
| 222 |
+
"first_n": FirstNSampler,
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def get_sampler(name: str):
|
| 227 |
+
try:
|
| 228 |
+
return SAMPLER_REGISTRY[name]
|
| 229 |
+
except KeyError:
|
| 230 |
+
raise ValueError(
|
| 231 |
+
f"Attempted to use contextsampler '{name}', but no sampling strategy for this name found! Supported model names: {', '.join(SAMPLER_REGISTRY.keys())}"
|
| 232 |
+
)
|
lm-evaluation-harness/lm_eval/api/task.py
ADDED
|
@@ -0,0 +1,1879 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
import ast
|
| 3 |
+
import logging
|
| 4 |
+
import random
|
| 5 |
+
import re
|
| 6 |
+
from collections.abc import Callable
|
| 7 |
+
from copy import deepcopy
|
| 8 |
+
from dataclasses import asdict, dataclass
|
| 9 |
+
from inspect import getsource
|
| 10 |
+
from typing import (
|
| 11 |
+
Any,
|
| 12 |
+
Dict,
|
| 13 |
+
Iterable,
|
| 14 |
+
Iterator,
|
| 15 |
+
List,
|
| 16 |
+
Literal,
|
| 17 |
+
Mapping,
|
| 18 |
+
Optional,
|
| 19 |
+
Tuple,
|
| 20 |
+
Union,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
import datasets
|
| 24 |
+
import numpy as np
|
| 25 |
+
from tqdm import tqdm
|
| 26 |
+
|
| 27 |
+
from lm_eval import utils
|
| 28 |
+
from lm_eval.api import samplers
|
| 29 |
+
from lm_eval.api.instance import Instance, OutputType
|
| 30 |
+
from lm_eval.api.metrics import bits_per_byte, mean, weighted_perplexity
|
| 31 |
+
from lm_eval.api.registry import (
|
| 32 |
+
AGGREGATION_REGISTRY,
|
| 33 |
+
DEFAULT_METRIC_REGISTRY,
|
| 34 |
+
get_aggregation,
|
| 35 |
+
get_metric,
|
| 36 |
+
get_metric_aggregation,
|
| 37 |
+
is_higher_better,
|
| 38 |
+
)
|
| 39 |
+
from lm_eval.caching.cache import load_from_cache, save_to_cache
|
| 40 |
+
from lm_eval.filters import build_filter_ensemble
|
| 41 |
+
from lm_eval.prompts import get_prompt
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
ALL_OUTPUT_TYPES = [
|
| 45 |
+
"loglikelihood",
|
| 46 |
+
"multiple_choice",
|
| 47 |
+
"loglikelihood_rolling",
|
| 48 |
+
"generate_until",
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
eval_logger = logging.getLogger(__name__)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@dataclass
|
| 55 |
+
class TaskConfig(dict):
|
| 56 |
+
# task naming/registry
|
| 57 |
+
task: Optional[str] = None
|
| 58 |
+
task_alias: Optional[str] = None
|
| 59 |
+
tag: Optional[Union[str, list]] = None
|
| 60 |
+
# HF dataset options.
|
| 61 |
+
# which dataset to use,
|
| 62 |
+
# and what splits for what purpose
|
| 63 |
+
custom_dataset: Optional[Callable] = None
|
| 64 |
+
dataset_path: Optional[str] = None
|
| 65 |
+
dataset_name: Optional[str] = None
|
| 66 |
+
dataset_kwargs: Optional[dict] = None
|
| 67 |
+
training_split: Optional[str] = None
|
| 68 |
+
validation_split: Optional[str] = None
|
| 69 |
+
test_split: Optional[str] = None
|
| 70 |
+
fewshot_split: Optional[str] = (
|
| 71 |
+
None # TODO: assert that this not None if num_fewshot > 0. (?) assert if this is same split as one evaluating (?)
|
| 72 |
+
)
|
| 73 |
+
# formatting / prompting options.
|
| 74 |
+
# see docs/advanced_task_guide.md for more info
|
| 75 |
+
process_docs: Optional[Callable] = None
|
| 76 |
+
doc_to_text: Optional[Union[Callable, str]] = None
|
| 77 |
+
doc_to_target: Optional[Union[Callable, str]] = None
|
| 78 |
+
doc_to_image: Union[Callable, str] = None
|
| 79 |
+
doc_to_audio: Union[Callable, str] = None
|
| 80 |
+
unsafe_code: bool = False
|
| 81 |
+
doc_to_choice: Optional[Union[Callable, str, dict, list]] = None
|
| 82 |
+
process_results: Optional[Union[Callable, str]] = None
|
| 83 |
+
use_prompt: Optional[str] = None
|
| 84 |
+
description: str = ""
|
| 85 |
+
target_delimiter: str = " "
|
| 86 |
+
fewshot_delimiter: str = "\n\n"
|
| 87 |
+
fewshot_config: Optional[dict] = None
|
| 88 |
+
# runtime configuration options
|
| 89 |
+
num_fewshot: Optional[int] = None
|
| 90 |
+
# scoring options
|
| 91 |
+
metric_list: Optional[list] = None
|
| 92 |
+
output_type: OutputType = "generate_until"
|
| 93 |
+
generation_kwargs: Optional[dict] = None
|
| 94 |
+
repeats: int = 1
|
| 95 |
+
filter_list: Optional[Union[str, list]] = None
|
| 96 |
+
should_decontaminate: bool = False
|
| 97 |
+
doc_to_decontamination_query: Optional[str] = None
|
| 98 |
+
gen_prefix: Optional[str] = None
|
| 99 |
+
metadata: Optional[dict] = (
|
| 100 |
+
None # by default, not used in the code. allows for users to pass arbitrary info to tasks
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
def __post_init__(self) -> None:
|
| 104 |
+
if self.generation_kwargs is not None:
|
| 105 |
+
if self.output_type != "generate_until":
|
| 106 |
+
eval_logger.warning(
|
| 107 |
+
f"[{self.task}] passed `generation_kwargs`, but not using `output_type: generate_until`!"
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
if "temperature" in self.generation_kwargs:
|
| 111 |
+
self.generation_kwargs["temperature"] = float(
|
| 112 |
+
self.generation_kwargs["temperature"]
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
if "until" not in self.generation_kwargs:
|
| 116 |
+
eval_logger.warning(
|
| 117 |
+
f"{self.task}: No `until` specified in `generation_kwargs`! Defaulting to the fewshot_delimiter={repr(self.fewshot_delimiter)}"
|
| 118 |
+
)
|
| 119 |
+
self.generation_kwargs["until"] = [self.fewshot_delimiter]
|
| 120 |
+
else:
|
| 121 |
+
if self.output_type == "generate_until":
|
| 122 |
+
# ensure that we greedily generate in absence of explicit arguments otherwise
|
| 123 |
+
self.generation_kwargs = {
|
| 124 |
+
"until": (
|
| 125 |
+
None
|
| 126 |
+
if self.fewshot_delimiter is None
|
| 127 |
+
else [self.fewshot_delimiter]
|
| 128 |
+
),
|
| 129 |
+
"do_sample": False,
|
| 130 |
+
"temperature": 0,
|
| 131 |
+
}
|
| 132 |
+
eval_logger.warning(
|
| 133 |
+
f"{self.task}: No `generation_kwargs` specified in task config, defaulting to {self.generation_kwargs}"
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
def __getitem__(self, item):
|
| 137 |
+
return getattr(self, item)
|
| 138 |
+
|
| 139 |
+
def __setitem__(self, item, value):
|
| 140 |
+
return setattr(self, item, value)
|
| 141 |
+
|
| 142 |
+
def to_dict(self, keep_callable: bool = False) -> dict:
|
| 143 |
+
"""dumps the current config as a dictionary object, as a printable format.
|
| 144 |
+
null fields will not be printed.
|
| 145 |
+
Used for dumping results alongside full task configuration
|
| 146 |
+
|
| 147 |
+
:return: dict
|
| 148 |
+
A printable dictionary version of the TaskConfig object.
|
| 149 |
+
|
| 150 |
+
# TODO: should any default value in the TaskConfig not be printed?
|
| 151 |
+
"""
|
| 152 |
+
cfg_dict = asdict(self)
|
| 153 |
+
# remove values that are `None`
|
| 154 |
+
for k, v in list(cfg_dict.items()):
|
| 155 |
+
if v is None:
|
| 156 |
+
cfg_dict.pop(k)
|
| 157 |
+
elif k == "metric_list":
|
| 158 |
+
for metric_dict in v:
|
| 159 |
+
for metric_key, metric_value in metric_dict.items():
|
| 160 |
+
if callable(metric_value):
|
| 161 |
+
metric_dict[metric_key] = self.serialize_function(
|
| 162 |
+
metric_value, keep_callable=keep_callable
|
| 163 |
+
)
|
| 164 |
+
cfg_dict[k] = v
|
| 165 |
+
elif callable(v):
|
| 166 |
+
cfg_dict[k] = self.serialize_function(v, keep_callable=keep_callable)
|
| 167 |
+
return cfg_dict
|
| 168 |
+
|
| 169 |
+
def serialize_function(
|
| 170 |
+
self, value: Union[Callable, str], keep_callable=False
|
| 171 |
+
) -> Union[Callable, str]:
|
| 172 |
+
"""Serializes a given function or string.
|
| 173 |
+
|
| 174 |
+
If 'keep_callable' is True, the original callable is returned.
|
| 175 |
+
Otherwise, attempts to return the source code of the callable using 'getsource'.
|
| 176 |
+
"""
|
| 177 |
+
if keep_callable:
|
| 178 |
+
return value
|
| 179 |
+
else:
|
| 180 |
+
try:
|
| 181 |
+
return getsource(value)
|
| 182 |
+
except (TypeError, OSError):
|
| 183 |
+
return str(value)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class Task(abc.ABC):
|
| 187 |
+
"""A task represents an entire benchmark including its dataset, problems,
|
| 188 |
+
answers, and evaluation methods. See BoolQ for a simple example implementation
|
| 189 |
+
|
| 190 |
+
A `doc` can be any python object which represents one instance of evaluation.
|
| 191 |
+
This is usually a dictionary e.g.
|
| 192 |
+
{"question": ..., "answer": ...} or
|
| 193 |
+
{"question": ..., question, answer)
|
| 194 |
+
"""
|
| 195 |
+
|
| 196 |
+
VERSION: Optional[Union[int, str]] = None
|
| 197 |
+
|
| 198 |
+
# The name of the `Task` benchmark as denoted in the HuggingFace datasets Hub
|
| 199 |
+
# or a path to a custom `datasets` loading script.
|
| 200 |
+
DATASET_PATH: Optional[str] = None
|
| 201 |
+
|
| 202 |
+
# The name of a subset within `DATASET_PATH`.
|
| 203 |
+
DATASET_NAME: Optional[str] = None
|
| 204 |
+
|
| 205 |
+
OUTPUT_TYPE: Optional[OutputType] = None
|
| 206 |
+
|
| 207 |
+
def __init__(
|
| 208 |
+
self,
|
| 209 |
+
data_dir: Optional[str] = None,
|
| 210 |
+
cache_dir: Optional[str] = None,
|
| 211 |
+
download_mode: Optional[datasets.DownloadMode] = None,
|
| 212 |
+
config: Optional[Mapping] = None, # Union[dict, TaskConfig]
|
| 213 |
+
) -> None:
|
| 214 |
+
"""
|
| 215 |
+
:param data_dir: str
|
| 216 |
+
Stores the path to a local folder containing the `Task`'s data files.
|
| 217 |
+
Use this to specify the path to manually downloaded data (usually when
|
| 218 |
+
the dataset is not publicly accessible).
|
| 219 |
+
:param cache_dir: str
|
| 220 |
+
The directory to read/write the `Task` dataset. This follows the
|
| 221 |
+
HuggingFace `datasets` API with the default cache directory located at:
|
| 222 |
+
`~/.cache/huggingface/datasets`
|
| 223 |
+
NOTE: You can change the cache location globally for a given process
|
| 224 |
+
to another directory:
|
| 225 |
+
`export HF_DATASETS_CACHE="/path/to/another/directory"`
|
| 226 |
+
:param download_mode: datasets.DownloadMode
|
| 227 |
+
How to treat pre-existing `Task` downloads and data.
|
| 228 |
+
- `datasets.DownloadMode.REUSE_DATASET_IF_EXISTS`
|
| 229 |
+
Reuse download and reuse dataset.
|
| 230 |
+
- `datasets.DownloadMode.REUSE_CACHE_IF_EXISTS`
|
| 231 |
+
Reuse download with fresh dataset.
|
| 232 |
+
- `datasets.DownloadMode.FORCE_REDOWNLOAD`
|
| 233 |
+
Fresh download and fresh dataset.
|
| 234 |
+
"""
|
| 235 |
+
self.download(data_dir, cache_dir, download_mode)
|
| 236 |
+
self._training_docs: Optional[list] = None
|
| 237 |
+
self._fewshot_docs: Optional[list] = None
|
| 238 |
+
self._instances: Optional[List[Instance]] = None
|
| 239 |
+
|
| 240 |
+
self._config: TaskConfig = TaskConfig({**config}) if config else TaskConfig()
|
| 241 |
+
|
| 242 |
+
self._filters = [build_filter_ensemble("none", [["take_first", None]])]
|
| 243 |
+
self.fewshot_rnd: Optional[random.Random] = (
|
| 244 |
+
None # purposely induce errors in case of improper usage
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
def download(
|
| 248 |
+
self,
|
| 249 |
+
data_dir: Optional[str] = None,
|
| 250 |
+
cache_dir: Optional[str] = None,
|
| 251 |
+
download_mode=None,
|
| 252 |
+
) -> None:
|
| 253 |
+
"""Downloads and returns the task dataset.
|
| 254 |
+
Override this method to download the dataset from a custom API.
|
| 255 |
+
|
| 256 |
+
:param data_dir: str
|
| 257 |
+
Stores the path to a local folder containing the `Task`'s data files.
|
| 258 |
+
Use this to specify the path to manually downloaded data (usually when
|
| 259 |
+
the dataset is not publicly accessible).
|
| 260 |
+
:param cache_dir: str
|
| 261 |
+
The directory to read/write the `Task` dataset. This follows the
|
| 262 |
+
HuggingFace `datasets` API with the default cache directory located at:
|
| 263 |
+
`~/.cache/huggingface/datasets`
|
| 264 |
+
NOTE: You can change the cache location globally for a given process
|
| 265 |
+
by setting the shell environment variable, `HF_DATASETS_CACHE`,
|
| 266 |
+
to another directory:
|
| 267 |
+
`export HF_DATASETS_CACHE="/path/to/another/directory"`
|
| 268 |
+
:param download_mode: datasets.DownloadMode
|
| 269 |
+
How to treat pre-existing `Task` downloads and data.
|
| 270 |
+
- `datasets.DownloadMode.REUSE_DATASET_IF_EXISTS`
|
| 271 |
+
Reuse download and reuse dataset.
|
| 272 |
+
- `datasets.DownloadMode.REUSE_CACHE_IF_EXISTS`
|
| 273 |
+
Reuse download with fresh dataset.
|
| 274 |
+
- `datasets.DownloadMode.FORCE_REDOWNLOAD`
|
| 275 |
+
Fresh download and fresh dataset.
|
| 276 |
+
"""
|
| 277 |
+
self.dataset = datasets.load_dataset(
|
| 278 |
+
path=self.DATASET_PATH,
|
| 279 |
+
name=self.DATASET_NAME,
|
| 280 |
+
data_dir=data_dir,
|
| 281 |
+
cache_dir=cache_dir,
|
| 282 |
+
download_mode=download_mode,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
@property
|
| 286 |
+
def config(self) -> TaskConfig:
|
| 287 |
+
"""Returns the TaskConfig associated with this class."""
|
| 288 |
+
return self._config
|
| 289 |
+
|
| 290 |
+
@abc.abstractmethod
|
| 291 |
+
def has_training_docs(self):
|
| 292 |
+
"""Whether the task has a training set"""
|
| 293 |
+
pass
|
| 294 |
+
|
| 295 |
+
@abc.abstractmethod
|
| 296 |
+
def has_validation_docs(self):
|
| 297 |
+
"""Whether the task has a validation set"""
|
| 298 |
+
pass
|
| 299 |
+
|
| 300 |
+
@abc.abstractmethod
|
| 301 |
+
def has_test_docs(self):
|
| 302 |
+
"""Whether the task has a test set"""
|
| 303 |
+
pass
|
| 304 |
+
|
| 305 |
+
def training_docs(self) -> Iterable:
|
| 306 |
+
"""
|
| 307 |
+
:return: Iterable[obj]
|
| 308 |
+
A iterable of any object, that doc_to_text can handle
|
| 309 |
+
"""
|
| 310 |
+
return []
|
| 311 |
+
|
| 312 |
+
def validation_docs(self) -> Iterable:
|
| 313 |
+
"""
|
| 314 |
+
:return: Iterable[obj]
|
| 315 |
+
A iterable of any object, that doc_to_text can handle
|
| 316 |
+
"""
|
| 317 |
+
return []
|
| 318 |
+
|
| 319 |
+
def test_docs(self) -> Iterable:
|
| 320 |
+
"""
|
| 321 |
+
:return: Iterable[obj]
|
| 322 |
+
A iterable of any object, that doc_to_text can handle
|
| 323 |
+
"""
|
| 324 |
+
return []
|
| 325 |
+
|
| 326 |
+
def fewshot_docs(self) -> Iterable:
|
| 327 |
+
"""
|
| 328 |
+
:return: Iterable[obj]
|
| 329 |
+
A iterable of any object, that doc_to_text can handle
|
| 330 |
+
"""
|
| 331 |
+
if self.has_training_docs():
|
| 332 |
+
return self.training_docs()
|
| 333 |
+
elif self.has_validation_docs():
|
| 334 |
+
return self.validation_docs()
|
| 335 |
+
else:
|
| 336 |
+
if self.config.get("num_fewshot", 0) > 0:
|
| 337 |
+
eval_logger.warning(
|
| 338 |
+
f"[Task: {self.config.task}] has_training_docs and has_validation_docs are False"
|
| 339 |
+
", using test_docs as fewshot_docs but this is not recommended."
|
| 340 |
+
)
|
| 341 |
+
return self.test_docs()
|
| 342 |
+
|
| 343 |
+
def _process_doc(self, doc: dict) -> dict:
|
| 344 |
+
"""
|
| 345 |
+
Override this to process (detokenize, strip, replace, etc.) individual
|
| 346 |
+
documents. This can be used in a map over documents of a data split.
|
| 347 |
+
E.g. `map(self._process_doc, self.dataset["validation"])`
|
| 348 |
+
|
| 349 |
+
:return: dict
|
| 350 |
+
The processed version of the specified `doc`.
|
| 351 |
+
"""
|
| 352 |
+
return doc
|
| 353 |
+
|
| 354 |
+
@property
|
| 355 |
+
def instances(self) -> List[Instance]:
|
| 356 |
+
"""After calling `task.build_all_requests()`, tasks
|
| 357 |
+
maintain a list of the dataset instances which will be evaluated.
|
| 358 |
+
"""
|
| 359 |
+
return self._instances
|
| 360 |
+
|
| 361 |
+
def fewshot_examples(self, k, rnd):
|
| 362 |
+
if self._training_docs is None:
|
| 363 |
+
self._training_docs = list(self.training_docs())
|
| 364 |
+
|
| 365 |
+
return rnd.sample(self._training_docs, k)
|
| 366 |
+
|
| 367 |
+
def doc_to_decontamination_query(self, doc):
|
| 368 |
+
raise NotImplementedError(
|
| 369 |
+
"Override doc_to_decontamination_query with document specific decontamination query."
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
@abc.abstractmethod
|
| 373 |
+
def doc_to_text(self, doc):
|
| 374 |
+
pass
|
| 375 |
+
|
| 376 |
+
@abc.abstractmethod
|
| 377 |
+
def doc_to_target(self, doc):
|
| 378 |
+
pass
|
| 379 |
+
|
| 380 |
+
# not an abstractmethod because not every language-only task has to implement this
|
| 381 |
+
def doc_to_image(self, doc):
|
| 382 |
+
raise NotImplementedError
|
| 383 |
+
|
| 384 |
+
def doc_to_audio(self, doc):
|
| 385 |
+
raise NotImplementedError
|
| 386 |
+
|
| 387 |
+
def doc_to_prefix(self, doc):
|
| 388 |
+
return ""
|
| 389 |
+
|
| 390 |
+
def build_all_requests(
|
| 391 |
+
self,
|
| 392 |
+
*,
|
| 393 |
+
limit: Union[int, None] = None,
|
| 394 |
+
samples: Optional[List[int]] = None,
|
| 395 |
+
rank: int = 0,
|
| 396 |
+
world_size: int = 1,
|
| 397 |
+
cache_requests: bool = False,
|
| 398 |
+
rewrite_requests_cache: bool = False,
|
| 399 |
+
system_instruction: Optional[str] = None,
|
| 400 |
+
apply_chat_template: bool = False,
|
| 401 |
+
fewshot_as_multiturn: bool = False,
|
| 402 |
+
chat_template: Optional[Callable] = None,
|
| 403 |
+
tokenizer_name: str = "",
|
| 404 |
+
) -> None:
|
| 405 |
+
"""Build a set of Instances for a task, and store them in task.instances"""
|
| 406 |
+
|
| 407 |
+
# used with caching
|
| 408 |
+
og_limit = limit
|
| 409 |
+
|
| 410 |
+
cache_key = f"requests-{self._config.task}-{self.config.num_fewshot}shot-rank{rank}-world_size{world_size}"
|
| 411 |
+
cache_key += "-chat_template" if apply_chat_template else ""
|
| 412 |
+
cache_key += "-fewshot_as_multiturn" if fewshot_as_multiturn else ""
|
| 413 |
+
cache_key += (
|
| 414 |
+
f"-system_prompt_hash{utils.hash_string(system_instruction)}"
|
| 415 |
+
if system_instruction is not None
|
| 416 |
+
else ""
|
| 417 |
+
)
|
| 418 |
+
cache_key += f"-tokenizer{tokenizer_name}"
|
| 419 |
+
|
| 420 |
+
cached_instances = load_from_cache(file_name=cache_key, cache=cache_requests)
|
| 421 |
+
|
| 422 |
+
if cache_requests and cached_instances and not rewrite_requests_cache:
|
| 423 |
+
cached_instances = cached_instances[:limit]
|
| 424 |
+
|
| 425 |
+
flattened_instances = [
|
| 426 |
+
instance
|
| 427 |
+
for instance_group in cached_instances
|
| 428 |
+
for instance in instance_group
|
| 429 |
+
]
|
| 430 |
+
|
| 431 |
+
self._instances = flattened_instances
|
| 432 |
+
return
|
| 433 |
+
|
| 434 |
+
eval_logger.info(f"Building contexts for {self.config.task} on rank {rank}...")
|
| 435 |
+
|
| 436 |
+
instances = []
|
| 437 |
+
|
| 438 |
+
# process all documents when caching is specified for simplicity
|
| 439 |
+
if (
|
| 440 |
+
cache_requests
|
| 441 |
+
and (not cached_instances or rewrite_requests_cache)
|
| 442 |
+
and limit is not None
|
| 443 |
+
):
|
| 444 |
+
limit = None
|
| 445 |
+
|
| 446 |
+
doc_id_docs = list(
|
| 447 |
+
self.doc_iterator(
|
| 448 |
+
rank=rank, limit=limit, samples=samples, world_size=world_size
|
| 449 |
+
)
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
num_docs = len(doc_id_docs)
|
| 453 |
+
|
| 454 |
+
for doc_id, doc in tqdm(
|
| 455 |
+
doc_id_docs,
|
| 456 |
+
total=num_docs,
|
| 457 |
+
):
|
| 458 |
+
# sample fewshot context #TODO: need to offset doc_id by rank now!
|
| 459 |
+
fewshot_ctx = self.fewshot_context(
|
| 460 |
+
doc,
|
| 461 |
+
0 if self.config.num_fewshot is None else self.config.num_fewshot,
|
| 462 |
+
system_instruction,
|
| 463 |
+
apply_chat_template,
|
| 464 |
+
fewshot_as_multiturn,
|
| 465 |
+
chat_template,
|
| 466 |
+
gen_prefix=self.doc_to_prefix(doc),
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
# TODO: we should override self.config.repeats if doing greedy gen so users don't waste time+compute
|
| 470 |
+
inst = self.construct_requests(
|
| 471 |
+
doc=doc,
|
| 472 |
+
ctx=fewshot_ctx,
|
| 473 |
+
metadata=(self.config["task"], doc_id, self.config.repeats),
|
| 474 |
+
apply_chat_template=apply_chat_template,
|
| 475 |
+
chat_template=chat_template,
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
if not isinstance(inst, list):
|
| 479 |
+
inst = [inst]
|
| 480 |
+
|
| 481 |
+
instances.append(inst)
|
| 482 |
+
|
| 483 |
+
# now flatten, this is to allow slicing to work with pickles
|
| 484 |
+
|
| 485 |
+
sliced_instances = instances[:og_limit]
|
| 486 |
+
|
| 487 |
+
flattened_instances = [
|
| 488 |
+
instance
|
| 489 |
+
for instance_group in sliced_instances
|
| 490 |
+
for instance in instance_group
|
| 491 |
+
]
|
| 492 |
+
|
| 493 |
+
self._instances = flattened_instances
|
| 494 |
+
|
| 495 |
+
if len(self._instances) == 0:
|
| 496 |
+
raise ValueError("task.build_requests() did not find any docs!")
|
| 497 |
+
|
| 498 |
+
if cache_requests and (not cached_instances or rewrite_requests_cache):
|
| 499 |
+
save_to_cache(file_name=cache_key, obj=instances)
|
| 500 |
+
|
| 501 |
+
@abc.abstractmethod
|
| 502 |
+
def construct_requests(self, doc, ctx, **kwargs):
|
| 503 |
+
"""Uses RequestFactory to construct Requests and returns an iterable of
|
| 504 |
+
Requests which will be sent to the LM.
|
| 505 |
+
|
| 506 |
+
:param doc:
|
| 507 |
+
The document as returned from training_docs, validation_docs, or test_docs.
|
| 508 |
+
:param ctx: str
|
| 509 |
+
The context string, generated by fewshot_context. This includes the natural
|
| 510 |
+
language description, as well as the few shot examples, and the question
|
| 511 |
+
part of the document for `doc`.
|
| 512 |
+
:param doc_idx: int
|
| 513 |
+
The index of a document within `self.test_docs()` or `self.validation_docs()`,
|
| 514 |
+
whichever is the main split used.
|
| 515 |
+
:param repeats: int
|
| 516 |
+
TODO: update this docstring
|
| 517 |
+
The number of times each instance in a dataset is inferred on. Defaults to 1,
|
| 518 |
+
can be increased for techniques like majority voting.
|
| 519 |
+
"""
|
| 520 |
+
pass
|
| 521 |
+
|
| 522 |
+
@abc.abstractmethod
|
| 523 |
+
def process_results(self, doc, results):
|
| 524 |
+
"""Take a single document and the LM results and evaluates, returning a
|
| 525 |
+
dict where keys are the names of submetrics and values are the values of
|
| 526 |
+
the metric for that one document
|
| 527 |
+
|
| 528 |
+
:param doc:
|
| 529 |
+
The document as returned from training_docs, validation_docs, or test_docs.
|
| 530 |
+
:param results:
|
| 531 |
+
The results of the requests created in construct_requests.
|
| 532 |
+
"""
|
| 533 |
+
pass
|
| 534 |
+
|
| 535 |
+
@abc.abstractmethod
|
| 536 |
+
def aggregation(self):
|
| 537 |
+
"""
|
| 538 |
+
:returns: {str: [metric_score] -> float}
|
| 539 |
+
A dictionary where keys are the names of submetrics and values are
|
| 540 |
+
functions that aggregate a list of metric scores
|
| 541 |
+
"""
|
| 542 |
+
pass
|
| 543 |
+
|
| 544 |
+
@abc.abstractmethod
|
| 545 |
+
def higher_is_better(self):
|
| 546 |
+
"""
|
| 547 |
+
:returns: {str: bool}
|
| 548 |
+
A dictionary where keys are the names of submetrics and values are
|
| 549 |
+
whether a higher value of the submetric is better
|
| 550 |
+
"""
|
| 551 |
+
pass
|
| 552 |
+
|
| 553 |
+
def get_config(self, key: str) -> Any:
|
| 554 |
+
return getattr(self._config, key, None)
|
| 555 |
+
|
| 556 |
+
@classmethod
|
| 557 |
+
def count_bytes(cls, doc):
|
| 558 |
+
"""Used for byte-level perplexity metrics in rolling loglikelihood"""
|
| 559 |
+
return len(doc.encode("utf-8"))
|
| 560 |
+
|
| 561 |
+
@classmethod
|
| 562 |
+
def count_words(cls, doc):
|
| 563 |
+
"""Downstream loglikelihood_rolling perplexity tasks with custom word boundaries should override this!"""
|
| 564 |
+
return len(re.split(r"\s+", doc))
|
| 565 |
+
|
| 566 |
+
@utils.positional_deprecated
|
| 567 |
+
def fewshot_context(self, doc, num_fewshot, rnd=None, description=None, **kwargs):
|
| 568 |
+
"""Returns a fewshot context string that is made up of a prepended description
|
| 569 |
+
(if provided), the `num_fewshot` number of examples, and an appended prompt example.
|
| 570 |
+
|
| 571 |
+
:param doc: str
|
| 572 |
+
The document as returned from training_docs, validation_docs, or test_docs.
|
| 573 |
+
:param num_fewshot: int
|
| 574 |
+
The number of fewshot examples to provide in the returned context string.
|
| 575 |
+
:param rnd: random.Random
|
| 576 |
+
The pseudo-random number generator used to randomly sample examples.
|
| 577 |
+
WARNING: This is currently a required arg although it's optionalized with a default `None`.
|
| 578 |
+
:param description: str
|
| 579 |
+
The task's description that will be prepended to the fewshot examples.
|
| 580 |
+
:returns: str
|
| 581 |
+
The fewshot context.
|
| 582 |
+
"""
|
| 583 |
+
if rnd is None:
|
| 584 |
+
if self.fewshot_rnd is not None:
|
| 585 |
+
rnd = self.fewshot_rnd
|
| 586 |
+
else:
|
| 587 |
+
raise ValueError(
|
| 588 |
+
"A `random.Random` generator argument must be provided to `rnd`"
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
description = description if description else ""
|
| 592 |
+
|
| 593 |
+
if num_fewshot == 0:
|
| 594 |
+
labeled_examples = ""
|
| 595 |
+
else:
|
| 596 |
+
# for sets with no training docs, draw from other set *but ensure no overlap with current doc*
|
| 597 |
+
if self.has_training_docs():
|
| 598 |
+
fewshotex = self.fewshot_examples(k=num_fewshot, rnd=rnd)
|
| 599 |
+
else:
|
| 600 |
+
if self._fewshot_docs is None:
|
| 601 |
+
self._fewshot_docs = list(
|
| 602 |
+
self.validation_docs()
|
| 603 |
+
if self.has_validation_docs()
|
| 604 |
+
else self.test_docs()
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
fewshotex = rnd.sample(self._fewshot_docs, num_fewshot + 1)
|
| 608 |
+
|
| 609 |
+
# get rid of the doc that's the one we're evaluating, if it's in the fewshot
|
| 610 |
+
fewshotex = [x for x in fewshotex if x != doc][:num_fewshot]
|
| 611 |
+
|
| 612 |
+
labeled_examples = (
|
| 613 |
+
"\n\n".join(
|
| 614 |
+
[
|
| 615 |
+
self.doc_to_text(doc) + self.doc_to_target(doc)
|
| 616 |
+
for doc in fewshotex
|
| 617 |
+
]
|
| 618 |
+
)
|
| 619 |
+
+ "\n\n"
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
example = self.doc_to_text(doc)
|
| 623 |
+
return description + labeled_examples + example
|
| 624 |
+
|
| 625 |
+
def apply_filters(self) -> Optional[List[Instance]]:
|
| 626 |
+
"""Iterates over FilterEnsembles and applies them to instances"""
|
| 627 |
+
if hasattr(self, "_filters"):
|
| 628 |
+
for f in self._filters:
|
| 629 |
+
f.apply(self._instances)
|
| 630 |
+
else:
|
| 631 |
+
eval_logger.warning("No filter defined, passing through instances")
|
| 632 |
+
return self._instances
|
| 633 |
+
|
| 634 |
+
def dump_config(self) -> dict:
|
| 635 |
+
"""Returns the config as a dictionary."""
|
| 636 |
+
# TODO: this should only return the overrides applied to a non-YAML task's configuration.
|
| 637 |
+
# (num_fewshot)
|
| 638 |
+
return self.config.to_dict()
|
| 639 |
+
|
| 640 |
+
def set_config(self, key: str, value: Any, update: bool = False) -> None:
|
| 641 |
+
"""Set or update the configuration for a given key."""
|
| 642 |
+
if key is None:
|
| 643 |
+
raise ValueError("Key must be provided.")
|
| 644 |
+
|
| 645 |
+
if update:
|
| 646 |
+
current_value = getattr(self._config, key, {})
|
| 647 |
+
if not isinstance(current_value, dict):
|
| 648 |
+
raise TypeError(
|
| 649 |
+
f"Expected a dict for key '{key}', got {type(current_value).__name__} instead."
|
| 650 |
+
)
|
| 651 |
+
current_value.update(value)
|
| 652 |
+
else:
|
| 653 |
+
setattr(self._config, key, value)
|
| 654 |
+
|
| 655 |
+
def override_metric(self, metric_name: str) -> None:
|
| 656 |
+
"""
|
| 657 |
+
Override the default metrics used for evaluation with custom metrics.
|
| 658 |
+
|
| 659 |
+
Parameters:
|
| 660 |
+
- metric_name (str): The name of the custom metric to override. Should be registered in api.metrics.
|
| 661 |
+
"""
|
| 662 |
+
(
|
| 663 |
+
self._metric_fn_list,
|
| 664 |
+
self._aggregation_list,
|
| 665 |
+
self._metric_fn_kwargs,
|
| 666 |
+
self._higher_is_better,
|
| 667 |
+
) = ({}, {}, {}, {})
|
| 668 |
+
self._metric_fn_list[metric_name] = get_metric(metric_name)
|
| 669 |
+
self._aggregation_list[metric_name] = get_metric_aggregation(metric_name)
|
| 670 |
+
self._higher_is_better[metric_name] = is_higher_better(metric_name)
|
| 671 |
+
self._metric_fn_kwargs[metric_name] = {}
|
| 672 |
+
if not isinstance(self, ConfigurableTask):
|
| 673 |
+
self.process_results = lambda x, y: {metric_name: get_metric(metric_name)}
|
| 674 |
+
self.aggregation = lambda: {
|
| 675 |
+
metric_name: get_metric_aggregation(metric_name)
|
| 676 |
+
}
|
| 677 |
+
setattr(self._config, "metric_list", [{"metric": metric_name}])
|
| 678 |
+
setattr(self._config, "process_results", None)
|
| 679 |
+
|
| 680 |
+
def set_fewshot_seed(self, seed: Optional[int] = None) -> None:
|
| 681 |
+
self.fewshot_rnd = random.Random(seed)
|
| 682 |
+
if hasattr(self, "sampler"):
|
| 683 |
+
self.sampler.rnd = self.fewshot_rnd
|
| 684 |
+
|
| 685 |
+
@property
|
| 686 |
+
def eval_docs(self) -> Union[datasets.Dataset, List[dict]]:
|
| 687 |
+
if self.has_test_docs():
|
| 688 |
+
return self.test_docs()
|
| 689 |
+
elif self.has_validation_docs():
|
| 690 |
+
return self.validation_docs()
|
| 691 |
+
else:
|
| 692 |
+
raise ValueError(
|
| 693 |
+
f"Task dataset (path={self.DATASET_PATH}, name={self.DATASET_NAME}) must have valid or test docs!"
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
def doc_iterator(
|
| 697 |
+
self,
|
| 698 |
+
*,
|
| 699 |
+
rank: int = 0,
|
| 700 |
+
limit: Union[int, None] = None,
|
| 701 |
+
world_size: int = 1,
|
| 702 |
+
samples: Optional[List[int]] = None,
|
| 703 |
+
) -> Iterator[Tuple[int, Any]]:
|
| 704 |
+
if samples:
|
| 705 |
+
n = len(self.eval_docs)
|
| 706 |
+
assert all([e < n for e in samples]), (
|
| 707 |
+
f"Elements of --samples should be in the interval [0,k-1] where k is the number of total examples. In this case, k={n}."
|
| 708 |
+
)
|
| 709 |
+
eval_logger.info(
|
| 710 |
+
f"{self.config.task}: Evaluating on {len(samples)} examples"
|
| 711 |
+
)
|
| 712 |
+
doc_iterator = utils.create_iterator(
|
| 713 |
+
enumerate(x for i, x in enumerate(self.eval_docs) if i in samples),
|
| 714 |
+
rank=int(rank),
|
| 715 |
+
limit=None, # limit does not matter here since we are selecting samples directly
|
| 716 |
+
world_size=int(world_size),
|
| 717 |
+
)
|
| 718 |
+
else:
|
| 719 |
+
limit = int(limit) if limit else None
|
| 720 |
+
doc_iterator = utils.create_iterator(
|
| 721 |
+
enumerate(self.eval_docs),
|
| 722 |
+
rank=int(rank),
|
| 723 |
+
limit=limit,
|
| 724 |
+
world_size=int(world_size),
|
| 725 |
+
)
|
| 726 |
+
return doc_iterator
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
class ConfigurableTask(Task):
|
| 730 |
+
VERSION = "Yaml"
|
| 731 |
+
OUTPUT_TYPE = None
|
| 732 |
+
CONFIG = None
|
| 733 |
+
|
| 734 |
+
def __init__(
|
| 735 |
+
self,
|
| 736 |
+
data_dir=None,
|
| 737 |
+
cache_dir=None,
|
| 738 |
+
download_mode=None,
|
| 739 |
+
config: Optional[dict] = None,
|
| 740 |
+
) -> None: # TODO no super() call here
|
| 741 |
+
# Get pre-configured attributes
|
| 742 |
+
self._config = self.CONFIG
|
| 743 |
+
|
| 744 |
+
# Use new configurations if there was no preconfiguration
|
| 745 |
+
if self.config is None:
|
| 746 |
+
self._config = TaskConfig(**config)
|
| 747 |
+
# Overwrite configs
|
| 748 |
+
else:
|
| 749 |
+
if config is not None:
|
| 750 |
+
self._config.__dict__.update(config)
|
| 751 |
+
|
| 752 |
+
if self.config is None:
|
| 753 |
+
raise ValueError(
|
| 754 |
+
"Must pass a config to ConfigurableTask, either in cls.CONFIG or `config` kwarg"
|
| 755 |
+
)
|
| 756 |
+
|
| 757 |
+
if isinstance(self.config.metadata, dict):
|
| 758 |
+
if "version" in self.config.metadata:
|
| 759 |
+
self.VERSION = self.config.metadata["version"]
|
| 760 |
+
|
| 761 |
+
if self.config.output_type is not None:
|
| 762 |
+
if self.config.output_type not in ALL_OUTPUT_TYPES:
|
| 763 |
+
raise ValueError(
|
| 764 |
+
f"Got invalid output_type '{self.config.output_type}', must be in '{','.join(ALL_OUTPUT_TYPES)}'"
|
| 765 |
+
)
|
| 766 |
+
self.OUTPUT_TYPE = self.config.output_type
|
| 767 |
+
|
| 768 |
+
if self.config.doc_to_image is not None:
|
| 769 |
+
# mark the task as requiring multimodality.
|
| 770 |
+
self.MULTIMODAL = True
|
| 771 |
+
|
| 772 |
+
if self.config.doc_to_audio:
|
| 773 |
+
# mark the task as requiring multimodality.
|
| 774 |
+
self.MULTIMODAL = True
|
| 775 |
+
|
| 776 |
+
if self.config.unsafe_code is not False:
|
| 777 |
+
self.UNSAFE_CODE = True
|
| 778 |
+
|
| 779 |
+
if self.config.dataset_path is not None:
|
| 780 |
+
self.DATASET_PATH = self.config.dataset_path
|
| 781 |
+
|
| 782 |
+
if self.config.dataset_name is not None:
|
| 783 |
+
self.DATASET_NAME = self.config.dataset_name
|
| 784 |
+
|
| 785 |
+
self._metric_fn_list = {}
|
| 786 |
+
self._metric_fn_kwargs = {}
|
| 787 |
+
self._aggregation_list = {}
|
| 788 |
+
self._higher_is_better = {}
|
| 789 |
+
|
| 790 |
+
if self.config.metric_list is None:
|
| 791 |
+
# TODO: handle this in TaskConfig.__post_init__ ?
|
| 792 |
+
_metric_list = DEFAULT_METRIC_REGISTRY[self.config.output_type]
|
| 793 |
+
|
| 794 |
+
for metric_name in _metric_list:
|
| 795 |
+
self._metric_fn_list[metric_name] = get_metric(metric_name)
|
| 796 |
+
self._metric_fn_kwargs[metric_name] = {}
|
| 797 |
+
self._aggregation_list[metric_name] = get_metric_aggregation(
|
| 798 |
+
metric_name
|
| 799 |
+
)
|
| 800 |
+
self._higher_is_better[metric_name] = is_higher_better(metric_name)
|
| 801 |
+
else:
|
| 802 |
+
for metric_config in self.config.metric_list:
|
| 803 |
+
if "metric" not in metric_config:
|
| 804 |
+
raise ValueError(
|
| 805 |
+
"'metric' key not provided for an entry in 'metric_list', must be specified!"
|
| 806 |
+
)
|
| 807 |
+
metric_name = metric_config["metric"]
|
| 808 |
+
kwargs = {
|
| 809 |
+
key: metric_config[key]
|
| 810 |
+
for key in metric_config
|
| 811 |
+
if key
|
| 812 |
+
not in ["metric", "aggregation", "higher_is_better", "hf_evaluate"]
|
| 813 |
+
}
|
| 814 |
+
hf_evaluate_metric = (
|
| 815 |
+
"hf_evaluate" in metric_config
|
| 816 |
+
and metric_config["hf_evaluate"] is True
|
| 817 |
+
)
|
| 818 |
+
|
| 819 |
+
if self.config.process_results is not None:
|
| 820 |
+
self._metric_fn_list[metric_name] = None
|
| 821 |
+
self._metric_fn_kwargs[metric_name] = {}
|
| 822 |
+
elif callable(metric_name):
|
| 823 |
+
metric_fn = metric_name.__call__
|
| 824 |
+
metric_name = metric_name.__name__
|
| 825 |
+
self._metric_fn_list[metric_name] = metric_fn
|
| 826 |
+
self._metric_fn_kwargs[metric_name] = kwargs
|
| 827 |
+
else:
|
| 828 |
+
self._metric_fn_list[metric_name] = get_metric(
|
| 829 |
+
metric_name, hf_evaluate_metric
|
| 830 |
+
)
|
| 831 |
+
self._metric_fn_kwargs[metric_name] = kwargs
|
| 832 |
+
|
| 833 |
+
if "aggregation" in metric_config:
|
| 834 |
+
agg_name = metric_config["aggregation"]
|
| 835 |
+
if isinstance(agg_name, str):
|
| 836 |
+
self._aggregation_list[metric_name] = get_aggregation(agg_name)
|
| 837 |
+
elif callable(agg_name): # noqa: E721
|
| 838 |
+
self._aggregation_list[metric_name] = metric_config[
|
| 839 |
+
"aggregation"
|
| 840 |
+
]
|
| 841 |
+
else:
|
| 842 |
+
INV_AGG_REGISTRY = {v: k for k, v in AGGREGATION_REGISTRY.items()}
|
| 843 |
+
metric_agg = get_metric_aggregation(metric_name)
|
| 844 |
+
eval_logger.warning(
|
| 845 |
+
f"[Task: {self.config.task}] metric {metric_name} is defined, but aggregation is not. "
|
| 846 |
+
f"using default "
|
| 847 |
+
f"aggregation={INV_AGG_REGISTRY[metric_agg]}"
|
| 848 |
+
)
|
| 849 |
+
self._aggregation_list[metric_name] = metric_agg
|
| 850 |
+
|
| 851 |
+
if "higher_is_better" in metric_config:
|
| 852 |
+
self._higher_is_better[metric_name] = metric_config[
|
| 853 |
+
"higher_is_better"
|
| 854 |
+
]
|
| 855 |
+
else:
|
| 856 |
+
eval_logger.warning(
|
| 857 |
+
f"[Task: {self.config.task}] metric {metric_name} is defined, but higher_is_better is not. "
|
| 858 |
+
f"using default "
|
| 859 |
+
f"higher_is_better={is_higher_better(metric_name)}"
|
| 860 |
+
)
|
| 861 |
+
self._higher_is_better[metric_name] = is_higher_better(metric_name)
|
| 862 |
+
|
| 863 |
+
self.download(self.config.dataset_kwargs)
|
| 864 |
+
self._training_docs = None
|
| 865 |
+
self._fewshot_docs = None
|
| 866 |
+
|
| 867 |
+
if self.config.filter_list is not None:
|
| 868 |
+
self._filters = []
|
| 869 |
+
for filter_config in self.config.filter_list:
|
| 870 |
+
filter_name = filter_config["name"]
|
| 871 |
+
filter_functions = filter_config["filter"]
|
| 872 |
+
components = []
|
| 873 |
+
for function in filter_functions:
|
| 874 |
+
kwargs = {
|
| 875 |
+
key: function[key] for key in function if key != "function"
|
| 876 |
+
}
|
| 877 |
+
components.append([function["function"], kwargs])
|
| 878 |
+
filter_pipeline = build_filter_ensemble(filter_name, components)
|
| 879 |
+
self._filters.append(filter_pipeline)
|
| 880 |
+
else:
|
| 881 |
+
# TODO: handle repeats in a more general way rather than just discarding
|
| 882 |
+
eval_logger.debug(
|
| 883 |
+
"No custom filters defined. Using default 'take_first' filter for handling repeats."
|
| 884 |
+
)
|
| 885 |
+
self._filters = [build_filter_ensemble("none", [["take_first", None]])]
|
| 886 |
+
|
| 887 |
+
if self.config.use_prompt is not None:
|
| 888 |
+
eval_logger.info(f"loading prompt {self.config.use_prompt}")
|
| 889 |
+
self.prompt = get_prompt(
|
| 890 |
+
self.config.use_prompt, self.DATASET_PATH, self.DATASET_NAME
|
| 891 |
+
)
|
| 892 |
+
else:
|
| 893 |
+
self.prompt = None
|
| 894 |
+
|
| 895 |
+
if self.fewshot_docs() is not None:
|
| 896 |
+
self.fewshot_rnd = (
|
| 897 |
+
random.Random()
|
| 898 |
+
) # setting with no seed, to be overridden at a later time
|
| 899 |
+
config_sampler: Union[str, Callable] = (
|
| 900 |
+
self.config.fewshot_config.get("sampler", "default")
|
| 901 |
+
if self.config.fewshot_config
|
| 902 |
+
else "default"
|
| 903 |
+
)
|
| 904 |
+
if isinstance(config_sampler, str):
|
| 905 |
+
self.sampler = samplers.get_sampler(config_sampler)(
|
| 906 |
+
list(self.fewshot_docs()), self, rnd=self.fewshot_rnd
|
| 907 |
+
)
|
| 908 |
+
elif callable(config_sampler) and issubclass(
|
| 909 |
+
config_sampler, samplers.ContextSampler
|
| 910 |
+
):
|
| 911 |
+
self.sampler = config_sampler(
|
| 912 |
+
docs=list(self.fewshot_docs()), task=self, rnd=self.fewshot_rnd
|
| 913 |
+
)
|
| 914 |
+
else:
|
| 915 |
+
raise TypeError(
|
| 916 |
+
f"fewshot_config.sampler should be a string or callable of ContextSampler type, "
|
| 917 |
+
f"not {type(config_sampler)}"
|
| 918 |
+
)
|
| 919 |
+
|
| 920 |
+
self.task_docs = self.eval_docs
|
| 921 |
+
|
| 922 |
+
# Test One Doc
|
| 923 |
+
self.features = list(self.task_docs.features.keys())
|
| 924 |
+
self.multiple_input = 0
|
| 925 |
+
self.multiple_target = 0
|
| 926 |
+
test_doc = self.task_docs[0]
|
| 927 |
+
test_text = self.doc_to_text(test_doc)
|
| 928 |
+
test_target = self.doc_to_target(test_doc)
|
| 929 |
+
|
| 930 |
+
if self.config.doc_to_choice is not None:
|
| 931 |
+
test_choice = self.doc_to_choice(test_doc)
|
| 932 |
+
if not isinstance(test_choice, list):
|
| 933 |
+
eval_logger.error("doc_to_choice must return list")
|
| 934 |
+
else:
|
| 935 |
+
num_choice = len(test_choice)
|
| 936 |
+
|
| 937 |
+
if isinstance(test_text, int):
|
| 938 |
+
eval_logger.debug(
|
| 939 |
+
"doc_to_text returned an int. Assuming multiple inputs."
|
| 940 |
+
)
|
| 941 |
+
self.multiple_input = num_choice
|
| 942 |
+
else:
|
| 943 |
+
test_choice = None
|
| 944 |
+
|
| 945 |
+
if isinstance(test_target, list):
|
| 946 |
+
eval_logger.debug(
|
| 947 |
+
"doc_to_target returned a list. Assuming multiple targets."
|
| 948 |
+
)
|
| 949 |
+
self.multiple_target = len(test_target)
|
| 950 |
+
else:
|
| 951 |
+
if (isinstance(test_target, int)) and (test_choice is not None):
|
| 952 |
+
test_target = test_choice[test_target]
|
| 953 |
+
else:
|
| 954 |
+
test_target = str(test_target)
|
| 955 |
+
|
| 956 |
+
if test_choice is not None:
|
| 957 |
+
check_choices = test_choice
|
| 958 |
+
else:
|
| 959 |
+
check_choices = [test_target]
|
| 960 |
+
if self.config.doc_to_choice is not None:
|
| 961 |
+
for choice in check_choices:
|
| 962 |
+
choice_has_whitespace = True if choice[0].isspace() else False
|
| 963 |
+
delimiter_has_whitespace = (
|
| 964 |
+
True
|
| 965 |
+
if self.config.target_delimiter.rstrip()
|
| 966 |
+
!= self.config.target_delimiter
|
| 967 |
+
else False
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
if delimiter_has_whitespace and choice_has_whitespace:
|
| 971 |
+
eval_logger.debug(
|
| 972 |
+
f'Both target_delimiter "{self.config.target_delimiter}" and target choice: "{choice}" have whitespace'
|
| 973 |
+
)
|
| 974 |
+
elif (not delimiter_has_whitespace) and (not choice_has_whitespace):
|
| 975 |
+
eval_logger.debug(
|
| 976 |
+
f'Both target_delimiter "{self.config.target_delimiter}" and target choice: "{choice}" do not have whitespace, ignore if the language you are evaluating on does not require/use whitespace'
|
| 977 |
+
)
|
| 978 |
+
|
| 979 |
+
def download(
|
| 980 |
+
self, dataset_kwargs: Optional[Dict[str, Any]] = None, **kwargs
|
| 981 |
+
) -> None:
|
| 982 |
+
if isinstance(self.config.custom_dataset, Callable):
|
| 983 |
+
eval_logger.warning(
|
| 984 |
+
f"{self.config.task}: Custom kwargs can be passed to `--metadata` in console (as json string) or to the TaskManager."
|
| 985 |
+
+ "\nFor example --metadata='{\"max_seq_lengths\":[4096, 8192]}'. For details see task Readme."
|
| 986 |
+
)
|
| 987 |
+
self.dataset = self.config.custom_dataset(
|
| 988 |
+
**(self.config.metadata or {}), **(self.config.dataset_kwargs or {})
|
| 989 |
+
)
|
| 990 |
+
else:
|
| 991 |
+
self.dataset = datasets.load_dataset(
|
| 992 |
+
path=self.DATASET_PATH,
|
| 993 |
+
name=self.DATASET_NAME,
|
| 994 |
+
**dataset_kwargs if dataset_kwargs is not None else {},
|
| 995 |
+
)
|
| 996 |
+
|
| 997 |
+
def has_training_docs(self) -> bool:
|
| 998 |
+
if self.config.training_split is not None:
|
| 999 |
+
return True
|
| 1000 |
+
else:
|
| 1001 |
+
return False
|
| 1002 |
+
|
| 1003 |
+
def has_validation_docs(self) -> bool:
|
| 1004 |
+
if self.config.validation_split is not None:
|
| 1005 |
+
return True
|
| 1006 |
+
else:
|
| 1007 |
+
return False
|
| 1008 |
+
|
| 1009 |
+
def has_test_docs(self) -> bool:
|
| 1010 |
+
if self.config.test_split is not None:
|
| 1011 |
+
return True
|
| 1012 |
+
else:
|
| 1013 |
+
return False
|
| 1014 |
+
|
| 1015 |
+
def training_docs(self) -> datasets.Dataset:
|
| 1016 |
+
if self.has_training_docs():
|
| 1017 |
+
if self.config.process_docs is not None:
|
| 1018 |
+
return self.config.process_docs(
|
| 1019 |
+
self.dataset[self.config.training_split]
|
| 1020 |
+
)
|
| 1021 |
+
return self.dataset[self.config.training_split]
|
| 1022 |
+
|
| 1023 |
+
def validation_docs(self) -> datasets.Dataset:
|
| 1024 |
+
if self.has_validation_docs():
|
| 1025 |
+
if self.config.process_docs is not None:
|
| 1026 |
+
return self.config.process_docs(
|
| 1027 |
+
self.dataset[self.config.validation_split]
|
| 1028 |
+
)
|
| 1029 |
+
return self.dataset[self.config.validation_split]
|
| 1030 |
+
|
| 1031 |
+
def test_docs(self) -> datasets.Dataset:
|
| 1032 |
+
if self.has_test_docs():
|
| 1033 |
+
if self.config.process_docs is not None:
|
| 1034 |
+
return self.config.process_docs(self.dataset[self.config.test_split])
|
| 1035 |
+
return self.dataset[self.config.test_split]
|
| 1036 |
+
|
| 1037 |
+
def fewshot_docs(self):
|
| 1038 |
+
if self.config.fewshot_split is not None:
|
| 1039 |
+
if self.config.process_docs is not None:
|
| 1040 |
+
return self.config.process_docs(self.dataset[self.config.fewshot_split])
|
| 1041 |
+
return self.dataset[self.config.fewshot_split]
|
| 1042 |
+
elif (
|
| 1043 |
+
self.config.fewshot_config is not None
|
| 1044 |
+
and self.config.fewshot_config.get("samples", None) is not None
|
| 1045 |
+
):
|
| 1046 |
+
if isinstance(self.config.fewshot_config["samples"], list):
|
| 1047 |
+
return self.config.fewshot_config["samples"]
|
| 1048 |
+
elif callable(self.config.fewshot_config["samples"]):
|
| 1049 |
+
return self.config.fewshot_config["samples"]()
|
| 1050 |
+
else:
|
| 1051 |
+
raise Exception(
|
| 1052 |
+
"`fewshot_config['samples']` was incorrectly defined in the configuration. It should be either a list of samples as a dict, or function returning this list."
|
| 1053 |
+
)
|
| 1054 |
+
else:
|
| 1055 |
+
if (self.config.num_fewshot is not None) and (self.config.num_fewshot > 0):
|
| 1056 |
+
eval_logger.warning(
|
| 1057 |
+
f"[Task: {self.config.task}] "
|
| 1058 |
+
"num_fewshot > 0 but fewshot_split is None. "
|
| 1059 |
+
"using preconfigured rule."
|
| 1060 |
+
)
|
| 1061 |
+
return super().fewshot_docs()
|
| 1062 |
+
|
| 1063 |
+
@staticmethod
|
| 1064 |
+
def append_target_question(
|
| 1065 |
+
labeled_examples: List[Dict[str, str]],
|
| 1066 |
+
question: str,
|
| 1067 |
+
fewshot_as_multiturn: bool = False,
|
| 1068 |
+
gen_prefix: Optional[str] = None,
|
| 1069 |
+
) -> None:
|
| 1070 |
+
"""Adds a target question to the labeled examples list.
|
| 1071 |
+
If fewshot_as_multiturn is True, or labeled_examples is empty, or the last entry is a system turn, appends the question as a new user entry.
|
| 1072 |
+
Otherwise, it is appended to the last user entry, ensuring that the conversation alternates between the user and the assistant.
|
| 1073 |
+
"""
|
| 1074 |
+
if not fewshot_as_multiturn:
|
| 1075 |
+
# if no messages or last message is system, append as new user entry
|
| 1076 |
+
if len(labeled_examples) == 0 or labeled_examples[-1]["role"] == "system":
|
| 1077 |
+
labeled_examples.append({"role": "user", "content": question})
|
| 1078 |
+
# if last message is user, append to it to avoid two user messages in a row
|
| 1079 |
+
else:
|
| 1080 |
+
labeled_examples[-1]["content"] += question
|
| 1081 |
+
else:
|
| 1082 |
+
# if fewshot_as_multiturn is True, append as next user entry (last is always assistant)
|
| 1083 |
+
labeled_examples.append({"role": "user", "content": question})
|
| 1084 |
+
if gen_prefix:
|
| 1085 |
+
labeled_examples.append({"role": "assistant", "content": gen_prefix})
|
| 1086 |
+
|
| 1087 |
+
@utils.positional_deprecated
|
| 1088 |
+
def fewshot_context(
|
| 1089 |
+
self,
|
| 1090 |
+
doc: dict,
|
| 1091 |
+
num_fewshot: int,
|
| 1092 |
+
system_instruction: Optional[str] = None,
|
| 1093 |
+
apply_chat_template: bool = False,
|
| 1094 |
+
fewshot_as_multiturn: bool = False,
|
| 1095 |
+
chat_template: Optional[Callable] = None,
|
| 1096 |
+
gen_prefix: Optional[str] = None,
|
| 1097 |
+
) -> Union[str, List[str]]:
|
| 1098 |
+
"""Returns a fewshot context string that is made up of a prepended description
|
| 1099 |
+
(if provided), the `num_fewshot` number of examples, and an appended prompt example.
|
| 1100 |
+
|
| 1101 |
+
:param doc: str
|
| 1102 |
+
The document as returned from training_docs, validation_docs, or test_docs.
|
| 1103 |
+
:param num_fewshot: int
|
| 1104 |
+
The number of fewshot examples to provide in the returned context string.
|
| 1105 |
+
:param system_instruction: str
|
| 1106 |
+
System instruction to be applied to the prompt.
|
| 1107 |
+
:param apply_chat_template: bool
|
| 1108 |
+
Whether to apply the chat template to the fewshot context.
|
| 1109 |
+
:param fewshot_as_multiturn: bool
|
| 1110 |
+
Whether to provide the fewshot examples as a multiturn conversation or a single user turn.
|
| 1111 |
+
:param chat_template:
|
| 1112 |
+
callable (from lm.apply_chat_template) that takes in a list[Dict] chat transcript and renders it into a string.
|
| 1113 |
+
:param gen_prefix:
|
| 1114 |
+
String to append after the <|assistant|> token.
|
| 1115 |
+
:returns: str
|
| 1116 |
+
The fewshot context.
|
| 1117 |
+
"""
|
| 1118 |
+
if apply_chat_template:
|
| 1119 |
+
labeled_examples = []
|
| 1120 |
+
else:
|
| 1121 |
+
labeled_examples = ""
|
| 1122 |
+
|
| 1123 |
+
# get task description
|
| 1124 |
+
if description := self.config.description:
|
| 1125 |
+
description = utils.apply_template(self.config.description, doc)
|
| 1126 |
+
|
| 1127 |
+
# create system prompt based on the provided system instruction and description
|
| 1128 |
+
if system_instruction is not None and description:
|
| 1129 |
+
system_prompt = (
|
| 1130 |
+
f"{system_instruction}{self.sampler.fewshot_delimiter}{description}"
|
| 1131 |
+
)
|
| 1132 |
+
elif system_instruction is not None:
|
| 1133 |
+
system_prompt = system_instruction
|
| 1134 |
+
elif description:
|
| 1135 |
+
system_prompt = description
|
| 1136 |
+
else:
|
| 1137 |
+
system_prompt = ""
|
| 1138 |
+
|
| 1139 |
+
# add system prompt if specified
|
| 1140 |
+
if system_prompt:
|
| 1141 |
+
if apply_chat_template:
|
| 1142 |
+
labeled_examples.append({"role": "system", "content": system_prompt})
|
| 1143 |
+
else:
|
| 1144 |
+
labeled_examples = system_prompt
|
| 1145 |
+
# if few-shot - append examples after the system prompt
|
| 1146 |
+
if num_fewshot > 0:
|
| 1147 |
+
if apply_chat_template:
|
| 1148 |
+
labeled_examples.extend(
|
| 1149 |
+
self.sampler.get_chat_context(
|
| 1150 |
+
doc,
|
| 1151 |
+
num_fewshot,
|
| 1152 |
+
fewshot_as_multiturn,
|
| 1153 |
+
gen_prefix=gen_prefix,
|
| 1154 |
+
)
|
| 1155 |
+
)
|
| 1156 |
+
else:
|
| 1157 |
+
labeled_examples += self.sampler.get_context(
|
| 1158 |
+
doc, num_fewshot, gen_prefix=gen_prefix
|
| 1159 |
+
)
|
| 1160 |
+
|
| 1161 |
+
example = self.doc_to_text(doc)
|
| 1162 |
+
if apply_chat_template:
|
| 1163 |
+
if self.multiple_input:
|
| 1164 |
+
# TODO: append prefill?
|
| 1165 |
+
if not labeled_examples:
|
| 1166 |
+
return ""
|
| 1167 |
+
return chat_template(labeled_examples)
|
| 1168 |
+
if isinstance(example, str):
|
| 1169 |
+
self.append_target_question(
|
| 1170 |
+
labeled_examples,
|
| 1171 |
+
example,
|
| 1172 |
+
fewshot_as_multiturn,
|
| 1173 |
+
gen_prefix=gen_prefix,
|
| 1174 |
+
)
|
| 1175 |
+
# for loglikelihood create a list of questions with appended choices
|
| 1176 |
+
elif isinstance(example, list):
|
| 1177 |
+
labeled_examples_list = []
|
| 1178 |
+
# copy chat history for each example and append the answer
|
| 1179 |
+
for ex in example:
|
| 1180 |
+
chat = deepcopy(labeled_examples)
|
| 1181 |
+
self.append_target_question(
|
| 1182 |
+
chat,
|
| 1183 |
+
ex,
|
| 1184 |
+
fewshot_as_multiturn,
|
| 1185 |
+
gen_prefix=gen_prefix,
|
| 1186 |
+
)
|
| 1187 |
+
# TODO: append prefill?
|
| 1188 |
+
labeled_examples_list.append(
|
| 1189 |
+
chat_template(
|
| 1190 |
+
chat,
|
| 1191 |
+
add_generation_prompt=False if gen_prefix else True,
|
| 1192 |
+
)
|
| 1193 |
+
)
|
| 1194 |
+
return labeled_examples_list
|
| 1195 |
+
# if example is an integer, append the choice or convert to string
|
| 1196 |
+
elif isinstance(example, int):
|
| 1197 |
+
if self.config.doc_to_choice is not None:
|
| 1198 |
+
choices = self.doc_to_choice(doc)
|
| 1199 |
+
self.append_target_question(
|
| 1200 |
+
labeled_examples,
|
| 1201 |
+
choices[example],
|
| 1202 |
+
fewshot_as_multiturn,
|
| 1203 |
+
gen_prefix=gen_prefix,
|
| 1204 |
+
)
|
| 1205 |
+
else:
|
| 1206 |
+
self.append_target_question(
|
| 1207 |
+
labeled_examples,
|
| 1208 |
+
str(example),
|
| 1209 |
+
fewshot_as_multiturn,
|
| 1210 |
+
gen_prefix=gen_prefix,
|
| 1211 |
+
)
|
| 1212 |
+
# return lm.apply_chat_template(labeled_examples)
|
| 1213 |
+
return chat_template(
|
| 1214 |
+
labeled_examples,
|
| 1215 |
+
add_generation_prompt=False if gen_prefix else True,
|
| 1216 |
+
)
|
| 1217 |
+
else:
|
| 1218 |
+
prefix = (
|
| 1219 |
+
self.config.target_delimiter + gen_prefix
|
| 1220 |
+
if gen_prefix is not None
|
| 1221 |
+
else ""
|
| 1222 |
+
)
|
| 1223 |
+
if self.multiple_input:
|
| 1224 |
+
return labeled_examples
|
| 1225 |
+
if isinstance(example, str):
|
| 1226 |
+
return labeled_examples + example + prefix
|
| 1227 |
+
elif isinstance(example, list):
|
| 1228 |
+
return [labeled_examples + ex + prefix for ex in example]
|
| 1229 |
+
elif isinstance(example, int):
|
| 1230 |
+
if self.config.doc_to_choice is not None:
|
| 1231 |
+
choices = self.doc_to_choice(doc)
|
| 1232 |
+
return labeled_examples + choices[example] + prefix
|
| 1233 |
+
else:
|
| 1234 |
+
return labeled_examples + str(example) + prefix
|
| 1235 |
+
|
| 1236 |
+
def apply_filters(self) -> Optional[List[Instance]]:
|
| 1237 |
+
"""Iterates over FilterEnsembles and applies them to instances"""
|
| 1238 |
+
if hasattr(self, "_filters"):
|
| 1239 |
+
for f in self._filters:
|
| 1240 |
+
f.apply(self._instances)
|
| 1241 |
+
else:
|
| 1242 |
+
eval_logger.warning("No filter defined, passing through instances")
|
| 1243 |
+
return self._instances
|
| 1244 |
+
|
| 1245 |
+
def should_decontaminate(self):
|
| 1246 |
+
return self.config.should_decontaminate
|
| 1247 |
+
|
| 1248 |
+
def doc_to_decontamination_query(self, doc: dict):
|
| 1249 |
+
if self.config.should_decontaminate:
|
| 1250 |
+
if self.config.doc_to_decontamination_query is None:
|
| 1251 |
+
return self.doc_to_text(doc)
|
| 1252 |
+
else:
|
| 1253 |
+
doc_to_decontamination_query = self.config.doc_to_decontamination_query
|
| 1254 |
+
if doc_to_decontamination_query in self.features:
|
| 1255 |
+
return doc[doc_to_decontamination_query]
|
| 1256 |
+
elif callable(doc_to_decontamination_query):
|
| 1257 |
+
return doc_to_decontamination_query(doc)
|
| 1258 |
+
else:
|
| 1259 |
+
return ast.literal_eval(
|
| 1260 |
+
utils.apply_template(
|
| 1261 |
+
self.config.doc_to_decontamination_query, doc
|
| 1262 |
+
)
|
| 1263 |
+
)
|
| 1264 |
+
|
| 1265 |
+
def _process_doc(self, doc: dict) -> dict:
|
| 1266 |
+
"""
|
| 1267 |
+
Override this to process (detokenize, strip, replace, etc.) individual
|
| 1268 |
+
documents. This can be used in a map over documents of a data split.
|
| 1269 |
+
E.g. `map(self._process_doc, self.dataset["validation"])`
|
| 1270 |
+
|
| 1271 |
+
:return: dict
|
| 1272 |
+
The processed version of the specified `doc`.
|
| 1273 |
+
"""
|
| 1274 |
+
return doc
|
| 1275 |
+
|
| 1276 |
+
def doc_to_text(self, doc, doc_to_text=None):
|
| 1277 |
+
if self.prompt is not None:
|
| 1278 |
+
doc_to_text = self.prompt
|
| 1279 |
+
elif doc_to_text is not None:
|
| 1280 |
+
doc_to_text = doc_to_text
|
| 1281 |
+
else:
|
| 1282 |
+
doc_to_text = self.config.doc_to_text
|
| 1283 |
+
|
| 1284 |
+
if isinstance(doc_to_text, int):
|
| 1285 |
+
return doc_to_text
|
| 1286 |
+
elif isinstance(doc_to_text, str):
|
| 1287 |
+
if doc_to_text in self.features:
|
| 1288 |
+
# if self.config.doc_to_choice is not None:
|
| 1289 |
+
# return self.doc_to_choice(doc)[doc[doc_to_text]]
|
| 1290 |
+
# else:
|
| 1291 |
+
return doc[doc_to_text]
|
| 1292 |
+
else:
|
| 1293 |
+
text_string = utils.apply_template(doc_to_text, doc)
|
| 1294 |
+
if text_string.isdigit() and self._config.doc_to_choice is not None:
|
| 1295 |
+
return ast.literal_eval(text_string)
|
| 1296 |
+
else:
|
| 1297 |
+
return text_string
|
| 1298 |
+
elif callable(doc_to_text):
|
| 1299 |
+
return doc_to_text(doc)
|
| 1300 |
+
# Used when applying a Promptsource template
|
| 1301 |
+
elif hasattr(doc_to_text, "apply"):
|
| 1302 |
+
applied_prompt = doc_to_text.apply(doc)
|
| 1303 |
+
if len(applied_prompt) == 2:
|
| 1304 |
+
return applied_prompt[0]
|
| 1305 |
+
else:
|
| 1306 |
+
eval_logger.warning("Applied prompt returns empty string")
|
| 1307 |
+
return self.config.fewshot_delimiter
|
| 1308 |
+
else:
|
| 1309 |
+
print(type(doc_to_text))
|
| 1310 |
+
raise TypeError
|
| 1311 |
+
|
| 1312 |
+
def doc_to_target(self, doc: Mapping, doc_to_target=None) -> Union[int, str, list]:
|
| 1313 |
+
if self.prompt is not None:
|
| 1314 |
+
doc_to_target = self.prompt
|
| 1315 |
+
elif doc_to_target is not None:
|
| 1316 |
+
doc_to_target = doc_to_target
|
| 1317 |
+
else:
|
| 1318 |
+
doc_to_target = self.config.doc_to_target
|
| 1319 |
+
|
| 1320 |
+
if isinstance(doc_to_target, int):
|
| 1321 |
+
return doc_to_target
|
| 1322 |
+
elif isinstance(doc_to_target, str):
|
| 1323 |
+
if doc_to_target in self.features:
|
| 1324 |
+
# if self.config.doc_to_choice is not None:
|
| 1325 |
+
# return self.doc_to_choice(doc)[doc[doc_to_target]]
|
| 1326 |
+
# else:
|
| 1327 |
+
return doc[doc_to_target]
|
| 1328 |
+
else:
|
| 1329 |
+
target_string = utils.apply_template(doc_to_target, doc)
|
| 1330 |
+
if target_string.isdigit() and self._config.doc_to_choice is not None:
|
| 1331 |
+
return ast.literal_eval(target_string)
|
| 1332 |
+
elif (
|
| 1333 |
+
len(target_string) >= 2
|
| 1334 |
+
and (target_string[0] == "[")
|
| 1335 |
+
and (target_string[-1] == "]")
|
| 1336 |
+
):
|
| 1337 |
+
try:
|
| 1338 |
+
return ast.literal_eval(target_string)
|
| 1339 |
+
except (SyntaxError, ValueError):
|
| 1340 |
+
return target_string
|
| 1341 |
+
else:
|
| 1342 |
+
return target_string
|
| 1343 |
+
elif isinstance(doc_to_target, list):
|
| 1344 |
+
return doc_to_target
|
| 1345 |
+
elif callable(doc_to_target):
|
| 1346 |
+
return doc_to_target(doc)
|
| 1347 |
+
# Used when applying a Promptsource template
|
| 1348 |
+
elif hasattr(doc_to_target, "apply"):
|
| 1349 |
+
applied_prompt = doc_to_target.apply(doc)
|
| 1350 |
+
if len(applied_prompt) == 2:
|
| 1351 |
+
return applied_prompt[1]
|
| 1352 |
+
else:
|
| 1353 |
+
eval_logger.warning("Applied prompt returns empty string")
|
| 1354 |
+
return self.config.fewshot_delimiter
|
| 1355 |
+
else:
|
| 1356 |
+
raise TypeError
|
| 1357 |
+
|
| 1358 |
+
def doc_to_choice(self, doc: Any, doc_to_choice=None) -> List[str]:
|
| 1359 |
+
if self.prompt is not None:
|
| 1360 |
+
doc_to_choice = self.prompt
|
| 1361 |
+
elif doc_to_choice is not None:
|
| 1362 |
+
doc_to_choice = doc_to_choice
|
| 1363 |
+
elif self.config.doc_to_choice is None:
|
| 1364 |
+
eval_logger.error("doc_to_choice was called but not set in config")
|
| 1365 |
+
else:
|
| 1366 |
+
doc_to_choice = self.config.doc_to_choice
|
| 1367 |
+
|
| 1368 |
+
if isinstance(doc_to_choice, str):
|
| 1369 |
+
if doc_to_choice in self.features:
|
| 1370 |
+
return doc[doc_to_choice]
|
| 1371 |
+
else:
|
| 1372 |
+
return ast.literal_eval(utils.apply_template(doc_to_choice, doc))
|
| 1373 |
+
elif isinstance(doc_to_choice, list):
|
| 1374 |
+
return doc_to_choice
|
| 1375 |
+
elif isinstance(doc_to_choice, dict):
|
| 1376 |
+
return list(doc_to_choice.values())
|
| 1377 |
+
elif callable(doc_to_choice):
|
| 1378 |
+
return doc_to_choice(doc)
|
| 1379 |
+
elif hasattr(doc_to_choice, "get_answer_choices_list"):
|
| 1380 |
+
return doc_to_choice.get_answer_choices_list(doc)
|
| 1381 |
+
else:
|
| 1382 |
+
raise TypeError
|
| 1383 |
+
|
| 1384 |
+
def doc_to_image(self, doc: Any, doc_to_image=None) -> Union[int, str, list]:
|
| 1385 |
+
if doc_to_image is not None:
|
| 1386 |
+
doc_to_image = doc_to_image
|
| 1387 |
+
elif self.config.doc_to_image is not None:
|
| 1388 |
+
doc_to_image = self.config.doc_to_image
|
| 1389 |
+
else:
|
| 1390 |
+
return None
|
| 1391 |
+
|
| 1392 |
+
if isinstance(doc_to_image, list):
|
| 1393 |
+
image_feature = [
|
| 1394 |
+
self.doc_to_image(doc, feature) for feature in doc_to_image
|
| 1395 |
+
]
|
| 1396 |
+
return [feature for feature in image_feature if feature is not None]
|
| 1397 |
+
elif isinstance(doc_to_image, str):
|
| 1398 |
+
if doc_to_image in self.features:
|
| 1399 |
+
return doc[doc_to_image]
|
| 1400 |
+
else:
|
| 1401 |
+
return ast.literal_eval(utils.apply_template(doc_to_image, doc))
|
| 1402 |
+
elif callable(doc_to_image):
|
| 1403 |
+
return doc_to_image(doc)
|
| 1404 |
+
else:
|
| 1405 |
+
return None
|
| 1406 |
+
|
| 1407 |
+
def doc_to_audio(self, doc: Any, doc_to_audio=None) -> Union[int, str, list]:
|
| 1408 |
+
if doc_to_audio is not None:
|
| 1409 |
+
doc_to_audio = doc_to_audio
|
| 1410 |
+
elif self.config.doc_to_audio is not None:
|
| 1411 |
+
doc_to_audio = self.config.doc_to_audio
|
| 1412 |
+
else:
|
| 1413 |
+
return None
|
| 1414 |
+
|
| 1415 |
+
if isinstance(doc_to_audio, list):
|
| 1416 |
+
audio_feature = [
|
| 1417 |
+
self.doc_to_audio(doc, feature) for feature in doc_to_audio
|
| 1418 |
+
]
|
| 1419 |
+
return [feature for feature in audio_feature if feature is not None]
|
| 1420 |
+
elif isinstance(doc_to_audio, str):
|
| 1421 |
+
if doc_to_audio in self.features:
|
| 1422 |
+
return doc[doc_to_audio]
|
| 1423 |
+
else:
|
| 1424 |
+
return ast.literal_eval(utils.apply_template(doc_to_audio, doc))
|
| 1425 |
+
elif callable(doc_to_audio):
|
| 1426 |
+
return doc_to_audio(doc)
|
| 1427 |
+
else:
|
| 1428 |
+
return None
|
| 1429 |
+
|
| 1430 |
+
def doc_to_prefix(self, doc):
|
| 1431 |
+
if (gen_prefix := self.config.gen_prefix) is not None:
|
| 1432 |
+
if gen_prefix in self.features:
|
| 1433 |
+
return doc[gen_prefix]
|
| 1434 |
+
else:
|
| 1435 |
+
return utils.apply_template(gen_prefix, doc)
|
| 1436 |
+
return None
|
| 1437 |
+
|
| 1438 |
+
def construct_requests(
|
| 1439 |
+
self, doc: dict, ctx: str, **kwargs
|
| 1440 |
+
) -> Union[List[Instance], Instance]:
|
| 1441 |
+
apply_chat_template = kwargs.pop("apply_chat_template", False)
|
| 1442 |
+
chat_template: Callable | None = kwargs.pop("chat_template", None)
|
| 1443 |
+
|
| 1444 |
+
aux_arguments = None
|
| 1445 |
+
|
| 1446 |
+
if self.OUTPUT_TYPE == "loglikelihood":
|
| 1447 |
+
arguments = (ctx, self.doc_to_target(doc))
|
| 1448 |
+
elif self.OUTPUT_TYPE == "loglikelihood_rolling":
|
| 1449 |
+
arguments = (self.doc_to_target(doc),)
|
| 1450 |
+
elif self.OUTPUT_TYPE == "multiple_choice":
|
| 1451 |
+
choices = self.doc_to_choice(doc)
|
| 1452 |
+
target_delimiter = self.config.target_delimiter
|
| 1453 |
+
if apply_chat_template:
|
| 1454 |
+
target_delimiter = ""
|
| 1455 |
+
if self.multiple_input:
|
| 1456 |
+
# If there are multiple inputs, choices are placed in the ctx
|
| 1457 |
+
# apply chat_template to choices if apply_chat_template
|
| 1458 |
+
cont = self.doc_to_target(doc)
|
| 1459 |
+
|
| 1460 |
+
arguments = [
|
| 1461 |
+
(
|
| 1462 |
+
ctx
|
| 1463 |
+
+ (
|
| 1464 |
+
chat_template([{"role": "user", "content": choice}])
|
| 1465 |
+
if apply_chat_template
|
| 1466 |
+
else choice
|
| 1467 |
+
),
|
| 1468 |
+
f"{target_delimiter}{cont}",
|
| 1469 |
+
)
|
| 1470 |
+
for choice in choices
|
| 1471 |
+
]
|
| 1472 |
+
else:
|
| 1473 |
+
# Otherwise they are placed in the continuation
|
| 1474 |
+
arguments = [(ctx, f"{target_delimiter}{cont}") for cont in choices]
|
| 1475 |
+
|
| 1476 |
+
# TODO: we should raise a warning telling users this will at most ~2x runtime.
|
| 1477 |
+
if "acc_mutual_info" in self._metric_fn_list.keys():
|
| 1478 |
+
# if we are calculating multiple choice accuracy
|
| 1479 |
+
# using mutual information instead of raw loglikelihood as metric, need unconditional lls.
|
| 1480 |
+
|
| 1481 |
+
# here mutual info refers to calculating
|
| 1482 |
+
# log(P(choice|ctx) / P(choice)) = log(P(choice|ctx)) - log(P(choice))
|
| 1483 |
+
# in other words normalizing by subtracting the unconditional logprob of each choice.
|
| 1484 |
+
# TODO: should these be strided? will have to modify the processing in process_results if so
|
| 1485 |
+
aux_arguments = [
|
| 1486 |
+
("", f"{target_delimiter}{choice}") for choice in choices
|
| 1487 |
+
]
|
| 1488 |
+
|
| 1489 |
+
arguments.extend(aux_arguments)
|
| 1490 |
+
|
| 1491 |
+
elif self.OUTPUT_TYPE == "generate_until":
|
| 1492 |
+
arguments = (ctx, deepcopy(self.config.generation_kwargs))
|
| 1493 |
+
|
| 1494 |
+
multimodal_arg = {}
|
| 1495 |
+
if (
|
| 1496 |
+
self.config.doc_to_image
|
| 1497 |
+
): # TODO: ensure that non-multimodal tasks aren't getting visual args
|
| 1498 |
+
multimodal_arg = {
|
| 1499 |
+
**multimodal_arg,
|
| 1500 |
+
**{"visual": self.doc_to_image(doc)},
|
| 1501 |
+
}
|
| 1502 |
+
|
| 1503 |
+
if (
|
| 1504 |
+
self.config.doc_to_audio
|
| 1505 |
+
): # TODO: ensure that non-multimodal tasks aren't getting audio args
|
| 1506 |
+
multimodal_arg = {
|
| 1507 |
+
**multimodal_arg,
|
| 1508 |
+
**{"audio": self.doc_to_audio(doc)},
|
| 1509 |
+
}
|
| 1510 |
+
|
| 1511 |
+
if bool(multimodal_arg):
|
| 1512 |
+
if isinstance(arguments, list):
|
| 1513 |
+
arguments = [arg + (multimodal_arg,) for arg in arguments]
|
| 1514 |
+
else:
|
| 1515 |
+
arguments = arguments + (multimodal_arg,)
|
| 1516 |
+
|
| 1517 |
+
if self.OUTPUT_TYPE == "multiple_choice":
|
| 1518 |
+
request_list = [
|
| 1519 |
+
Instance(
|
| 1520 |
+
request_type="loglikelihood",
|
| 1521 |
+
doc=doc,
|
| 1522 |
+
arguments=arg,
|
| 1523 |
+
idx=i,
|
| 1524 |
+
**kwargs,
|
| 1525 |
+
)
|
| 1526 |
+
for i, arg in enumerate(arguments)
|
| 1527 |
+
]
|
| 1528 |
+
|
| 1529 |
+
return request_list
|
| 1530 |
+
|
| 1531 |
+
return Instance(
|
| 1532 |
+
request_type=self.OUTPUT_TYPE,
|
| 1533 |
+
doc=doc,
|
| 1534 |
+
arguments=arguments,
|
| 1535 |
+
idx=0,
|
| 1536 |
+
**kwargs,
|
| 1537 |
+
)
|
| 1538 |
+
|
| 1539 |
+
def process_results(self, doc, results):
|
| 1540 |
+
if callable(self.config.process_results):
|
| 1541 |
+
return self.config.process_results(doc, results)
|
| 1542 |
+
|
| 1543 |
+
result_dict = {}
|
| 1544 |
+
use_metric = list(self._metric_fn_list.keys())
|
| 1545 |
+
if self.OUTPUT_TYPE == "loglikelihood":
|
| 1546 |
+
results = results[0]
|
| 1547 |
+
ll, is_greedy = results
|
| 1548 |
+
return {
|
| 1549 |
+
**({"perplexity": ll} if "perplexity" in use_metric else {}),
|
| 1550 |
+
**({"acc": int(is_greedy)} if "acc" in use_metric else {}),
|
| 1551 |
+
}
|
| 1552 |
+
elif self.OUTPUT_TYPE == "loglikelihood_rolling":
|
| 1553 |
+
(loglikelihood,) = results
|
| 1554 |
+
_words = self.count_words(self.doc_to_target(doc))
|
| 1555 |
+
_bytes = self.count_bytes(self.doc_to_target(doc))
|
| 1556 |
+
return {
|
| 1557 |
+
**(
|
| 1558 |
+
{"word_perplexity": (loglikelihood, _words)}
|
| 1559 |
+
if "word_perplexity" in use_metric
|
| 1560 |
+
else {}
|
| 1561 |
+
),
|
| 1562 |
+
**(
|
| 1563 |
+
{"byte_perplexity": (loglikelihood, _bytes)}
|
| 1564 |
+
if "byte_perplexity" in use_metric
|
| 1565 |
+
else {}
|
| 1566 |
+
),
|
| 1567 |
+
**(
|
| 1568 |
+
{"bits_per_byte": (loglikelihood, _bytes)}
|
| 1569 |
+
if "bits_per_byte" in use_metric
|
| 1570 |
+
else {}
|
| 1571 |
+
),
|
| 1572 |
+
}
|
| 1573 |
+
elif self.OUTPUT_TYPE == "multiple_choice":
|
| 1574 |
+
lls, is_greedy = zip(*results)
|
| 1575 |
+
|
| 1576 |
+
# retrieve choices in List[str] form, to compute choice lengths, etc.
|
| 1577 |
+
choices = self.doc_to_choice(doc)
|
| 1578 |
+
completion_len = np.array([float(len(i)) for i in choices])
|
| 1579 |
+
|
| 1580 |
+
if (
|
| 1581 |
+
2 * len(choices) == len(lls)
|
| 1582 |
+
and "acc_mutual_info" in self._metric_fn_list.keys()
|
| 1583 |
+
):
|
| 1584 |
+
# then we are doing mutual info.
|
| 1585 |
+
# this stores the "dryrun" / unconditional answer loglikelihoods
|
| 1586 |
+
# as we extend the args list with unconditional ("", continuation) pairs
|
| 1587 |
+
lls_unconditional = lls[len(choices) :]
|
| 1588 |
+
if len(lls_unconditional) != len(choices):
|
| 1589 |
+
raise ValueError
|
| 1590 |
+
# and this stores our "regular" conditional loglikelihoods
|
| 1591 |
+
lls = lls[: len(choices)]
|
| 1592 |
+
|
| 1593 |
+
pred = np.argmax(lls)
|
| 1594 |
+
pred_norm = np.argmax(lls / completion_len)
|
| 1595 |
+
|
| 1596 |
+
if self.multiple_input:
|
| 1597 |
+
gold = self.doc_to_text(doc)
|
| 1598 |
+
else:
|
| 1599 |
+
gold = self.doc_to_target(doc)
|
| 1600 |
+
|
| 1601 |
+
gold_index_error = False
|
| 1602 |
+
if isinstance(gold, list):
|
| 1603 |
+
gold = [i if i < len(choices) else -100 for i in gold]
|
| 1604 |
+
if -100 in gold:
|
| 1605 |
+
gold_index_error = True
|
| 1606 |
+
else:
|
| 1607 |
+
if isinstance(gold, int):
|
| 1608 |
+
gold = gold if gold < len(choices) else -100
|
| 1609 |
+
elif isinstance(gold, str):
|
| 1610 |
+
gold = choices.index(gold) if gold in choices else -100
|
| 1611 |
+
|
| 1612 |
+
if gold == -100:
|
| 1613 |
+
gold_index_error = True
|
| 1614 |
+
|
| 1615 |
+
if gold_index_error:
|
| 1616 |
+
eval_logger.warning(
|
| 1617 |
+
f"Label index was not in within range of available choices,"
|
| 1618 |
+
f"Sample:\n\n{doc}\n\n"
|
| 1619 |
+
)
|
| 1620 |
+
|
| 1621 |
+
if self.multiple_target:
|
| 1622 |
+
acc = 1.0 if pred in gold else 0.0
|
| 1623 |
+
acc_norm = 1.0 if pred_norm in gold else 0.0
|
| 1624 |
+
exact_match = int(any([is_greedy[i] if i != -100 else 0 for i in gold]))
|
| 1625 |
+
else:
|
| 1626 |
+
acc = 1.0 if pred == gold else 0.0
|
| 1627 |
+
acc_norm = 1.0 if pred_norm == gold else 0.0
|
| 1628 |
+
# TODO: this gets score of 0 on arc_challenge for pythia-70m. need to test that this works properly
|
| 1629 |
+
exact_match = int(is_greedy[gold]) if gold != -100 else 0
|
| 1630 |
+
|
| 1631 |
+
prob_norm = utils.softmax(lls)
|
| 1632 |
+
|
| 1633 |
+
# TODO use keyword arguments to the metric?
|
| 1634 |
+
# gold, pred, norm stuff, the original lls,
|
| 1635 |
+
result_dict = {
|
| 1636 |
+
**({"acc": acc} if "acc" in use_metric else {}),
|
| 1637 |
+
**({"f1": (gold, pred)} if "f1" in use_metric else {}),
|
| 1638 |
+
**({"mcc": (gold, pred)} if "mcc" in use_metric else {}),
|
| 1639 |
+
**({"acc_norm": acc_norm} if "acc_norm" in use_metric else {}),
|
| 1640 |
+
**({"exact_match": exact_match} if "exact_match" in use_metric else {}),
|
| 1641 |
+
**(
|
| 1642 |
+
{"brier_score": (gold, prob_norm)}
|
| 1643 |
+
if "brier_score" in use_metric
|
| 1644 |
+
else {}
|
| 1645 |
+
),
|
| 1646 |
+
}
|
| 1647 |
+
|
| 1648 |
+
if "acc_mutual_info" in use_metric:
|
| 1649 |
+
lls_mutual_info = [
|
| 1650 |
+
ll_c - ll_u for ll_c, ll_u in zip(lls, lls_unconditional)
|
| 1651 |
+
]
|
| 1652 |
+
acc_mutual_info = 1.0 if np.argmax(lls_mutual_info) == gold else 0.0
|
| 1653 |
+
result_dict["acc_mutual_info"] = acc_mutual_info
|
| 1654 |
+
|
| 1655 |
+
elif self.OUTPUT_TYPE == "generate_until":
|
| 1656 |
+
gold = self.doc_to_target(doc)
|
| 1657 |
+
result = results[0]
|
| 1658 |
+
if self.config.doc_to_choice is not None:
|
| 1659 |
+
# If you set doc_to_choice,
|
| 1660 |
+
# it assumes that doc_to_target returns a number.
|
| 1661 |
+
choices = self.doc_to_choice(doc)
|
| 1662 |
+
gold = choices[gold]
|
| 1663 |
+
# we expect multiple_targets to be a list.
|
| 1664 |
+
elif self.multiple_target:
|
| 1665 |
+
gold = list(gold)
|
| 1666 |
+
# TODO: handle this better
|
| 1667 |
+
elif type(gold) is not type(result) and not (
|
| 1668 |
+
"bypass" in self._metric_fn_list.keys() or isinstance(result, list)
|
| 1669 |
+
):
|
| 1670 |
+
# cast gold to the same type as result
|
| 1671 |
+
gold = type(result)(gold)
|
| 1672 |
+
|
| 1673 |
+
for metric in self._metric_fn_list.keys():
|
| 1674 |
+
if self.multiple_target:
|
| 1675 |
+
# in the case where we have multiple targets,
|
| 1676 |
+
# return true if any are true
|
| 1677 |
+
# TODO: this may break for multipLe_target, non zero-or-1 metrics
|
| 1678 |
+
scores = []
|
| 1679 |
+
if not isinstance(gold, list):
|
| 1680 |
+
# sometimes, a multiple_target dataset has exceptions where one doc has only one string answer
|
| 1681 |
+
# print(gold)
|
| 1682 |
+
gold = [gold]
|
| 1683 |
+
if metric == "exact_match":
|
| 1684 |
+
result = [result for _ in range(len(gold))]
|
| 1685 |
+
scores = self._metric_fn_list[metric](
|
| 1686 |
+
references=gold,
|
| 1687 |
+
predictions=result,
|
| 1688 |
+
**self._metric_fn_kwargs[metric],
|
| 1689 |
+
)[metric]
|
| 1690 |
+
result_score = 1.0 if scores > 0.0 else 0.0
|
| 1691 |
+
else:
|
| 1692 |
+
for gold_option in gold:
|
| 1693 |
+
try:
|
| 1694 |
+
result_score = self._metric_fn_list[metric](
|
| 1695 |
+
references=[gold_option],
|
| 1696 |
+
predictions=[result],
|
| 1697 |
+
**self._metric_fn_kwargs[metric],
|
| 1698 |
+
)
|
| 1699 |
+
except (
|
| 1700 |
+
TypeError
|
| 1701 |
+
): # TODO: this is hacky and I don't want to do it
|
| 1702 |
+
result_score = self._metric_fn_list[metric](
|
| 1703 |
+
[gold_option, result]
|
| 1704 |
+
)
|
| 1705 |
+
if isinstance(result_score, dict):
|
| 1706 |
+
# TODO: this handles the case where HF evaluate returns a dict.
|
| 1707 |
+
result_score = result_score[metric]
|
| 1708 |
+
scores.append(result_score)
|
| 1709 |
+
if any(scores):
|
| 1710 |
+
result_score = 1.0
|
| 1711 |
+
else:
|
| 1712 |
+
result_score = 0.0
|
| 1713 |
+
else:
|
| 1714 |
+
try:
|
| 1715 |
+
result_score = self._metric_fn_list[metric](
|
| 1716 |
+
references=[gold],
|
| 1717 |
+
predictions=[result],
|
| 1718 |
+
**self._metric_fn_kwargs[metric],
|
| 1719 |
+
)
|
| 1720 |
+
except TypeError: # needed for now in order to use a different interface between our own metrics and HF Evaluate metrics
|
| 1721 |
+
result_score = self._metric_fn_list[metric]([gold, result])
|
| 1722 |
+
if isinstance(result_score, dict):
|
| 1723 |
+
# TODO: this handles the case where HF evaluate returns a dict.
|
| 1724 |
+
# This allows for multiple metrics to be returned from the same function
|
| 1725 |
+
for k, v in result_score.items():
|
| 1726 |
+
result_dict[k] = v
|
| 1727 |
+
else:
|
| 1728 |
+
result_dict[metric] = result_score
|
| 1729 |
+
else:
|
| 1730 |
+
raise ValueError(
|
| 1731 |
+
f"Passed invalid output_type '{self.OUTPUT_TYPE}' ! Please use one of ",
|
| 1732 |
+
"'loglikelihood', 'loglikelihood_rolling', 'generate_until' or 'multiple_choice'",
|
| 1733 |
+
)
|
| 1734 |
+
|
| 1735 |
+
return result_dict
|
| 1736 |
+
|
| 1737 |
+
def aggregation(self) -> dict:
|
| 1738 |
+
return self._aggregation_list
|
| 1739 |
+
|
| 1740 |
+
def higher_is_better(self) -> dict:
|
| 1741 |
+
return self._higher_is_better
|
| 1742 |
+
|
| 1743 |
+
def get_config(self, key: str) -> Any:
|
| 1744 |
+
return getattr(self._config, key, None)
|
| 1745 |
+
|
| 1746 |
+
@property
|
| 1747 |
+
def task_name(self) -> Any:
|
| 1748 |
+
return getattr(self.config, "task", None)
|
| 1749 |
+
|
| 1750 |
+
def __repr__(self):
|
| 1751 |
+
return (
|
| 1752 |
+
f"ConfigurableTask(task_name={getattr(self.config, 'task', None)},"
|
| 1753 |
+
f"output_type={self.OUTPUT_TYPE},"
|
| 1754 |
+
f"num_fewshot={getattr(self.config, 'num_fewshot', None)},"
|
| 1755 |
+
f"num_samples={len(self.eval_docs)})"
|
| 1756 |
+
)
|
| 1757 |
+
|
| 1758 |
+
|
| 1759 |
+
class MultipleChoiceTask(Task):
|
| 1760 |
+
OUTPUT_TYPE = "loglikelihood"
|
| 1761 |
+
|
| 1762 |
+
def doc_to_target(self, doc: dict) -> str:
|
| 1763 |
+
return " " + doc["choices"][doc["gold"]]
|
| 1764 |
+
|
| 1765 |
+
def construct_requests(self, doc: dict, ctx: str, **kwargs) -> List[Instance]:
|
| 1766 |
+
# TODO: add mutual info here?
|
| 1767 |
+
return [
|
| 1768 |
+
Instance(
|
| 1769 |
+
request_type="loglikelihood",
|
| 1770 |
+
doc=doc,
|
| 1771 |
+
arguments=(ctx, " {}".format(choice)),
|
| 1772 |
+
idx=i,
|
| 1773 |
+
**kwargs,
|
| 1774 |
+
)
|
| 1775 |
+
for i, choice in enumerate(doc["choices"])
|
| 1776 |
+
]
|
| 1777 |
+
|
| 1778 |
+
def process_results(self, doc: dict, results: Iterable[Tuple[float, bool]]) -> dict:
|
| 1779 |
+
results = [
|
| 1780 |
+
res[0] for res in results
|
| 1781 |
+
] # only retain loglikelihoods, discard is_greedy TODO: do we need is_greedy anywhere?
|
| 1782 |
+
gold = doc["gold"]
|
| 1783 |
+
|
| 1784 |
+
acc = 1.0 if np.argmax(results) == gold else 0.0
|
| 1785 |
+
completion_len = np.array([float(len(i)) for i in doc["choices"]])
|
| 1786 |
+
acc_norm = 1.0 if np.argmax(results / completion_len) == gold else 0.0
|
| 1787 |
+
|
| 1788 |
+
return {
|
| 1789 |
+
"acc": acc,
|
| 1790 |
+
"acc_norm": acc_norm,
|
| 1791 |
+
}
|
| 1792 |
+
|
| 1793 |
+
def higher_is_better(self) -> dict:
|
| 1794 |
+
return {
|
| 1795 |
+
"acc": True,
|
| 1796 |
+
"acc_norm": True,
|
| 1797 |
+
}
|
| 1798 |
+
|
| 1799 |
+
def aggregation(self) -> dict:
|
| 1800 |
+
return {
|
| 1801 |
+
"acc": mean,
|
| 1802 |
+
"acc_norm": mean,
|
| 1803 |
+
}
|
| 1804 |
+
|
| 1805 |
+
|
| 1806 |
+
class PerplexityTask(Task):
|
| 1807 |
+
OUTPUT_TYPE = "loglikelihood_rolling"
|
| 1808 |
+
|
| 1809 |
+
def has_training_docs(self) -> bool:
|
| 1810 |
+
return False
|
| 1811 |
+
|
| 1812 |
+
def fewshot_examples(self, k: int, rnd) -> List:
|
| 1813 |
+
if k != 0:
|
| 1814 |
+
raise ValueError(
|
| 1815 |
+
"The number of fewshot examples must be 0 for perplexity tasks."
|
| 1816 |
+
)
|
| 1817 |
+
return []
|
| 1818 |
+
|
| 1819 |
+
def fewshot_context(self, doc: dict, num_fewshot: int) -> Literal[""]:
|
| 1820 |
+
if num_fewshot != 0:
|
| 1821 |
+
raise ValueError(
|
| 1822 |
+
"The number of fewshot examples must be 0 for perplexity tasks."
|
| 1823 |
+
)
|
| 1824 |
+
|
| 1825 |
+
return ""
|
| 1826 |
+
|
| 1827 |
+
def higher_is_better(self) -> dict:
|
| 1828 |
+
return {
|
| 1829 |
+
"word_perplexity": False,
|
| 1830 |
+
"byte_perplexity": False,
|
| 1831 |
+
"bits_per_byte": False,
|
| 1832 |
+
}
|
| 1833 |
+
|
| 1834 |
+
def doc_to_decontamination_query(self, doc):
|
| 1835 |
+
return doc
|
| 1836 |
+
|
| 1837 |
+
def doc_to_text(self, doc) -> str:
|
| 1838 |
+
return ""
|
| 1839 |
+
|
| 1840 |
+
def doc_to_target(self, doc):
|
| 1841 |
+
return doc
|
| 1842 |
+
|
| 1843 |
+
def construct_requests(self, doc: dict, ctx: Optional[str], **kwargs):
|
| 1844 |
+
if bool(ctx):
|
| 1845 |
+
raise ValueError
|
| 1846 |
+
|
| 1847 |
+
return Instance(
|
| 1848 |
+
request_type=self.OUTPUT_TYPE,
|
| 1849 |
+
doc=doc,
|
| 1850 |
+
arguments=(self.doc_to_target(doc),),
|
| 1851 |
+
idx=0,
|
| 1852 |
+
**kwargs,
|
| 1853 |
+
)
|
| 1854 |
+
|
| 1855 |
+
def process_results(self, doc: dict, results: Tuple[float]) -> dict:
|
| 1856 |
+
(loglikelihood,) = results
|
| 1857 |
+
words = self.count_words(self.doc_to_target(doc))
|
| 1858 |
+
bytes_ = self.count_bytes(self.doc_to_target(doc))
|
| 1859 |
+
return {
|
| 1860 |
+
"word_perplexity": (loglikelihood, words),
|
| 1861 |
+
"byte_perplexity": (loglikelihood, bytes_),
|
| 1862 |
+
"bits_per_byte": (loglikelihood, bytes_),
|
| 1863 |
+
}
|
| 1864 |
+
|
| 1865 |
+
def aggregation(self) -> dict:
|
| 1866 |
+
return {
|
| 1867 |
+
"word_perplexity": weighted_perplexity,
|
| 1868 |
+
"byte_perplexity": weighted_perplexity,
|
| 1869 |
+
"bits_per_byte": bits_per_byte,
|
| 1870 |
+
}
|
| 1871 |
+
|
| 1872 |
+
@classmethod
|
| 1873 |
+
def count_bytes(cls, doc) -> int:
|
| 1874 |
+
return len(doc.encode("utf-8"))
|
| 1875 |
+
|
| 1876 |
+
@classmethod
|
| 1877 |
+
def count_words(cls, doc) -> int:
|
| 1878 |
+
"""Downstream tasks with custom word boundaries should override this!"""
|
| 1879 |
+
return len(re.split(r"\s+", doc))
|
lm-evaluation-harness/lm_eval/caching/__init__.py
ADDED
|
File without changes
|
lm-evaluation-harness/lm_eval/caching/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (183 Bytes). View file
|
|
|
lm-evaluation-harness/lm_eval/caching/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (199 Bytes). View file
|
|
|
lm-evaluation-harness/lm_eval/caching/__pycache__/cache.cpython-310.pyc
ADDED
|
Binary file (1.69 kB). View file
|
|
|
lm-evaluation-harness/lm_eval/caching/__pycache__/cache.cpython-311.pyc
ADDED
|
Binary file (3.38 kB). View file
|
|
|