diff --git a/testbed/EleutherAI__lm-evaluation-harness/.coveragerc b/testbed/EleutherAI__lm-evaluation-harness/.coveragerc new file mode 100644 index 0000000000000000000000000000000000000000..1248476304d3d43662439148724428792f150585 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/.coveragerc @@ -0,0 +1,28 @@ +[run] + +# tasks that aren't wired up. +omit = + lm_eval/tasks/quac.py + lm_eval/tasks/storycloze.py + lm_eval/tasks/cbt.py + lm_eval/tasks/sat.py + lm_eval/tasks/triviaqa.py + lm_eval/tasks/naturalqs.py + lm_eval/models/dummy.py + +[report] +exclude_lines = + # Skip any pass lines such as may be used for @abstractmethod + pass + + # Have to re-enable the standard pragma + pragma: no cover + + # Don't complain about missing debug-only code: + def __repr__ + if self\.debug + + # Don't complain if tests don't hit defensive assertion code: + raise AssertionError + raise NotImplementedError + return NotImplemented diff --git a/testbed/EleutherAI__lm-evaluation-harness/.flake8 b/testbed/EleutherAI__lm-evaluation-harness/.flake8 new file mode 100644 index 0000000000000000000000000000000000000000..73f6455d132003fce0034f41d72eeb901b68f039 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/.flake8 @@ -0,0 +1,5 @@ +[flake8] +ignore = E203, E266, E501, W503, F403, F401, C901 +max-line-length = 127 +max-complexity = 10 +select = B,C,E,F,W,T4,B9 diff --git a/testbed/EleutherAI__lm-evaluation-harness/.gitignore b/testbed/EleutherAI__lm-evaluation-harness/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c9278761b0ce9499b0c20afe0151b89121443512 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/.gitignore @@ -0,0 +1,24 @@ +env +*.pyc +output/ +data/ +lm_cache +.idea +build +dist +*.egg-info +venv +.vscode/ +temp +__pycache__ +.ipynb_checkpoints +temp +test_logs/ +# IPython +profile_default/ +ipython_config.py +# don't track (the default location of) the cached requests +lm_eval/caching/.cache +# don't track files created by wandb +wandb +examples/wandb diff --git a/testbed/EleutherAI__lm-evaluation-harness/.pre-commit-config.yaml b/testbed/EleutherAI__lm-evaluation-harness/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d066cd9e6b4b174a267155a2b8e558a3b946dac1 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/.pre-commit-config.yaml @@ -0,0 +1,54 @@ +# Ignore test linting to avoid conflicting changes to version stability. +exclude: ^tests/testdata/ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 + hooks: + - id: check-added-large-files + - id: check-ast + - id: check-byte-order-marker + - id: check-case-conflict + - id: check-json + - id: check-merge-conflict + args: [--assume-in-merge] + - id: check-symlinks + - id: check-yaml + args: ["--unsafe"] + - id: destroyed-symlinks + - id: detect-private-key + - id: end-of-file-fixer + - id: no-commit-to-branch + always_run: false + - id: requirements-txt-fixer + - id: trailing-whitespace + args: [--markdown-linebreak-ext=md] + - id: fix-byte-order-marker + exclude: docs/CNAME + - id: fix-encoding-pragma + args: [--remove] + - id: mixed-line-ending + args: [--fix=lf] + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.4.8 + hooks: + # Run the linter. + - id: ruff + args: + - --fix + # Run the formatter. + - id: ruff-format + - repo: https://github.com/codespell-project/codespell + rev: v2.3.0 + hooks: + - id: codespell + exclude: > + (?x)^( + .*\.json|ignore.txt|lm_eval/tasks/.*|.*yaml|.*\.ipynb + )$ + args: [--check-filenames, --check-hidden, --ignore-words=ignore.txt] +# - repo: https://github.com/pre-commit/mirrors-mypy +# rev: v1.5.1 +# hooks: +# - id: mypy +# additional_dependencies: [".[sentencepiece,multilingual,promptsource,gptq]", "types-PyYAML", "types-requests"] +# exclude: ^tests/.*$ diff --git a/testbed/EleutherAI__lm-evaluation-harness/CITATION.bib b/testbed/EleutherAI__lm-evaluation-harness/CITATION.bib new file mode 100644 index 0000000000000000000000000000000000000000..4ec33f139693aad74d2cb89c5edb2a578a315dd2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/CITATION.bib @@ -0,0 +1,10 @@ +@misc{eval-harness, + author = {Gao, Leo and Tow, Jonathan and Abbasi, Baber and Biderman, Stella and Black, Sid and DiPofi, Anthony and Foster, Charles and Golding, Laurence and Hsu, Jeffrey and Le Noac'h, Alain and Li, Haonan and McDonell, Kyle and Muennighoff, Niklas and Ociepa, Chris and Phang, Jason and Reynolds, Laria and Schoelkopf, Hailey and Skowron, Aviya and Sutawika, Lintang and Tang, Eric and Thite, Anish and Wang, Ben and Wang, Kevin and Zou, Andy}, + title = {A framework for few-shot language model evaluation}, + month = 12, + year = 2023, + publisher = {Zenodo}, + version = {v0.4.0}, + doi = {10.5281/zenodo.10256836}, + url = {https://zenodo.org/records/10256836} +} diff --git a/testbed/EleutherAI__lm-evaluation-harness/LICENSE.md b/testbed/EleutherAI__lm-evaluation-harness/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..12e6063183935e876e232db276568baf4954b492 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 EleutherAI + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/testbed/EleutherAI__lm-evaluation-harness/README.md b/testbed/EleutherAI__lm-evaluation-harness/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e973cdb7e895152b889f93cd22ab071c2c37c0e7 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/README.md @@ -0,0 +1,497 @@ +# Language Model Evaluation Harness + +[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.10256836.svg)](https://doi.org/10.5281/zenodo.10256836) + +--- + +*Latest News 📣* + +- [2024/07] [API model](docs/API_guide.md) support has been updated and refactored, introducing support for batched and async requests, and making it significantly easier to customize and use for your own purposes. **To run Llama 405B, we recommend using VLLM's OpenAI-compliant API to host the model, and use the `local-completions` model type to evaluate the model.** +- [2024/07] New Open LLM Leaderboard tasks have been added ! You can find them under the [leaderboard](lm_eval/tasks/leaderboard/README.md) task group. + +--- + +## Announcement +**A new v0.4.0 release of lm-evaluation-harness is available** ! + +New updates and features include: + +- **New Open LLM Leaderboard tasks have been added ! You can find them under the [leaderboard](lm_eval/tasks/leaderboard/README.md) task group.** +- Internal refactoring +- Config-based task creation and configuration +- Easier import and sharing of externally-defined task config YAMLs +- Support for Jinja2 prompt design, easy modification of prompts + prompt imports from Promptsource +- More advanced configuration options, including output post-processing, answer extraction, and multiple LM generations per document, configurable fewshot settings, and more +- Speedups and new modeling libraries supported, including: faster data-parallel HF model usage, vLLM support, MPS support with HuggingFace, and more +- Logging and usability changes +- New tasks including CoT BIG-Bench-Hard, Belebele, user-defined task groupings, and more + +Please see our updated documentation pages in `docs/` for more details. + +Development will be continuing on the `main` branch, and we encourage you to give us feedback on what features are desired and how to improve the library further, or ask questions, either in issues or PRs on GitHub, or in the [EleutherAI discord](https://discord.gg/eleutherai)! + +--- + +## Overview + +This project provides a unified framework to test generative language models on a large number of different evaluation tasks. + +**Features:** +- Over 60 standard academic benchmarks for LLMs, with hundreds of subtasks and variants implemented. +- Support for models loaded via [transformers](https://github.com/huggingface/transformers/) (including quantization via [AutoGPTQ](https://github.com/PanQiWei/AutoGPTQ)), [GPT-NeoX](https://github.com/EleutherAI/gpt-neox), and [Megatron-DeepSpeed](https://github.com/microsoft/Megatron-DeepSpeed/), with a flexible tokenization-agnostic interface. +- Support for fast and memory-efficient inference with [vLLM](https://github.com/vllm-project/vllm). +- Support for commercial APIs including [OpenAI](https://openai.com), and [TextSynth](https://textsynth.com/). +- Support for evaluation on adapters (e.g. LoRA) supported in [HuggingFace's PEFT library](https://github.com/huggingface/peft). +- Support for local models and benchmarks. +- Evaluation with publicly available prompts ensures reproducibility and comparability between papers. +- Easy support for custom prompts and evaluation metrics. + +The Language Model Evaluation Harness is the backend for 🤗 Hugging Face's popular [Open LLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard), has been used in [hundreds of papers](https://scholar.google.com/scholar?oi=bibs&hl=en&authuser=2&cites=15052937328817631261,4097184744846514103,1520777361382155671,17476825572045927382,18443729326628441434,14801318227356878622,7890865700763267262,12854182577605049984,15641002901115500560,5104500764547628290), and is used internally by dozens of organizations including NVIDIA, Cohere, BigScience, BigCode, Nous Research, and Mosaic ML. + +## Install + +To install the `lm-eval` package from the github repository, run: + +```bash +git clone https://github.com/EleutherAI/lm-evaluation-harness +cd lm-evaluation-harness +pip install -e . +``` + +We also provide a number of optional dependencies for extended functionality. A detailed table is available at the end of this document. + +## Basic Usage +### User Guide + +A user guide detailing the full list of supported arguments is provided [here](./docs/interface.md), and on the terminal by calling `lm_eval -h`. Alternatively, you can use `lm-eval` instead of `lm_eval`. + +A list of supported tasks (or groupings of tasks) can be viewed with `lm-eval --tasks list`. Task descriptions and links to corresponding subfolders are provided [here](./lm_eval/tasks/README.md). + +### Hugging Face `transformers` + +To evaluate a model hosted on the [HuggingFace Hub](https://huggingface.co/models) (e.g. GPT-J-6B) on `hellaswag` you can use the following command (this assumes you are using a CUDA-compatible GPU): + +```bash +lm_eval --model hf \ + --model_args pretrained=EleutherAI/gpt-j-6B \ + --tasks hellaswag \ + --device cuda:0 \ + --batch_size 8 +``` + +Additional arguments can be provided to the model constructor using the `--model_args` flag. Most notably, this supports the common practice of using the `revisions` feature on the Hub to store partially trained checkpoints, or to specify the datatype for running a model: + +```bash +lm_eval --model hf \ + --model_args pretrained=EleutherAI/pythia-160m,revision=step100000,dtype="float" \ + --tasks lambada_openai,hellaswag \ + --device cuda:0 \ + --batch_size 8 +``` + +Models that are loaded via both `transformers.AutoModelForCausalLM` (autoregressive, decoder-only GPT style models) and `transformers.AutoModelForSeq2SeqLM` (such as encoder-decoder models like T5) in Huggingface are supported. + +Batch size selection can be automated by setting the ```--batch_size``` flag to ```auto```. This will perform automatic detection of the largest batch size that will fit on your device. On tasks where there is a large difference between the longest and shortest example, it can be helpful to periodically recompute the largest batch size, to gain a further speedup. To do this, append ```:N``` to above flag to automatically recompute the largest batch size ```N``` times. For example, to recompute the batch size 4 times, the command would be: + +```bash +lm_eval --model hf \ + --model_args pretrained=EleutherAI/pythia-160m,revision=step100000,dtype="float" \ + --tasks lambada_openai,hellaswag \ + --device cuda:0 \ + --batch_size auto:4 +``` + +> [!Note] +> Just like you can provide a local path to `transformers.AutoModel`, you can also provide a local path to `lm_eval` via `--model_args pretrained=/path/to/model` + +#### Multi-GPU Evaluation with Hugging Face `accelerate` + +We support three main ways of using Hugging Face's [accelerate 🚀](https://github.com/huggingface/accelerate) library for multi-GPU evaluation. + +To perform *data-parallel evaluation* (where each GPU loads a **separate full copy** of the model), we leverage the `accelerate` launcher as follows: + +``` +accelerate launch -m lm_eval --model hf \ + --tasks lambada_openai,arc_easy \ + --batch_size 16 +``` +(or via `accelerate launch --no-python lm_eval`). + +For cases where your model can fit on a single GPU, this allows you to evaluate on K GPUs K times faster than on one. + +**WARNING**: This setup does not work with FSDP model sharding, so in `accelerate config` FSDP must be disabled, or the NO_SHARD FSDP option must be used. + +The second way of using `accelerate` for multi-GPU evaluation is when your model is *too large to fit on a single GPU.* + +In this setting, run the library *outside the `accelerate` launcher*, but passing `parallelize=True` to `--model_args` as follows: + +``` +lm_eval --model hf \ + --tasks lambada_openai,arc_easy \ + --model_args parallelize=True \ + --batch_size 16 +``` + +This means that your model's weights will be split across all available GPUs. + +For more advanced users or even larger models, we allow for the following arguments when `parallelize=True` as well: +- `device_map_option`: How to split model weights across available GPUs. defaults to "auto". +- `max_memory_per_gpu`: the max GPU memory to use per GPU in loading the model. +- `max_cpu_memory`: the max amount of CPU memory to use when offloading the model weights to RAM. +- `offload_folder`: a folder where model weights will be offloaded to disk if needed. + +The third option is to use both at the same time. This will allow you to take advantage of both data parallelism and model sharding, and is especially useful for models that are too large to fit on a single GPU. + +``` +accelerate launch --multi_gpu --num_processes {nb_of_copies_of_your_model} \ + -m lm_eval --model hf \ + --tasks lambada_openai,arc_easy \ + --model_args parallelize=True \ + --batch_size 16 +``` + +To learn more about model parallelism and how to use it with the `accelerate` library, see the [accelerate documentation](https://huggingface.co/docs/transformers/v4.15.0/en/parallelism) + +**Warning: We do not natively support multi-node evaluation using the `hf` model type! Please reference [our GPT-NeoX library integration](https://github.com/EleutherAI/gpt-neox/blob/main/eval.py) for an example of code in which a custom multi-machine evaluation script is written.** + +**Note: we do not currently support multi-node evaluations natively, and advise using either an externally hosted server to run inference requests against, or creating a custom integration with your distributed framework [as is done for the GPT-NeoX library](https://github.com/EleutherAI/gpt-neox/blob/main/eval_tasks/eval_adapter.py).** + +### NVIDIA `nemo` models + +[NVIDIA NeMo Framework](https://github.com/NVIDIA/NeMo) is a generative AI framework built for researchers and pytorch developers working on language models. + +To evaluate a `nemo` model, start by installing NeMo following [the documentation](https://github.com/NVIDIA/NeMo?tab=readme-ov-file#installation). We highly recommended to use the NVIDIA PyTorch or NeMo container, especially if having issues installing Apex or any other dependencies (see [latest released containers](https://github.com/NVIDIA/NeMo/releases)). Please also install the lm evaluation harness library following the instructions in [the Install section](https://github.com/EleutherAI/lm-evaluation-harness/tree/main?tab=readme-ov-file#install). + +NeMo models can be obtained through [NVIDIA NGC Catalog](https://catalog.ngc.nvidia.com/models) or in [NVIDIA's Hugging Face page](https://huggingface.co/nvidia). In [NVIDIA NeMo Framework](https://github.com/NVIDIA/NeMo/tree/main/scripts/nlp_language_modeling) there are conversion scripts to convert the `hf` checkpoints of popular models like llama, falcon, mixtral or mpt to `nemo`. + +Run a `nemo` model on one GPU: +```bash +lm_eval --model nemo_lm \ + --model_args path= \ + --tasks hellaswag \ + --batch_size 32 +``` + +It is recommended to unpack the `nemo` model to avoid the unpacking inside the docker container - it may overflow disk space. For that you can run: + +``` +mkdir MY_MODEL +tar -xvf MY_MODEL.nemo -c MY_MODEL +``` + +#### Multi-GPU evaluation with NVIDIA `nemo` models + +By default, only one GPU is used. But we do support either data replication or tensor/pipeline parallelism during evaluation, on one node. + +1) To enable data replication, set the `model_args` of `devices` to the number of data replicas to run. For example, the command to run 8 data replicas over 8 GPUs is: +```bash +torchrun --nproc-per-node=8 --no-python lm_eval \ + --model nemo_lm \ + --model_args path=,devices=8 \ + --tasks hellaswag \ + --batch_size 32 +``` + +2) To enable tensor and/or pipeline parallelism, set the `model_args` of `tensor_model_parallel_size` and/or `pipeline_model_parallel_size`. In addition, you also have to set up `devices` to be equal to the product of `tensor_model_parallel_size` and/or `pipeline_model_parallel_size`. For example, the command to use one node of 4 GPUs with tensor parallelism of 2 and pipeline parallelism of 2 is: +```bash +torchrun --nproc-per-node=4 --no-python lm_eval \ + --model nemo_lm \ + --model_args path=,devices=4,tensor_model_parallel_size=2,pipeline_model_parallel_size=2 \ + --tasks hellaswag \ + --batch_size 32 +``` +Note that it is recommended to substitute the `python` command by `torchrun --nproc-per-node= --no-python` to facilitate loading the model into the GPUs. This is especially important for large checkpoints loaded into multiple GPUs. + +Not supported yet: multi-node evaluation and combinations of data replication with tensor or pipeline parallelism. + +### Tensor + Data Parallel and Optimized Inference with `vLLM` + +We also support vLLM for faster inference on [supported model types](https://docs.vllm.ai/en/latest/models/supported_models.html), especially faster when splitting a model across multiple GPUs. For single-GPU or multi-GPU — tensor parallel, data parallel, or a combination of both — inference, for example: + +```bash +lm_eval --model vllm \ + --model_args pretrained={model_name},tensor_parallel_size={GPUs_per_model},dtype=auto,gpu_memory_utilization=0.8,data_parallel_size={model_replicas} \ + --tasks lambada_openai \ + --batch_size auto +``` +To use vllm, do `pip install lm_eval[vllm]`. For a full list of supported vLLM configurations, please reference our [vLLM integration](https://github.com/EleutherAI/lm-evaluation-harness/blob/e74ec966556253fbe3d8ecba9de675c77c075bce/lm_eval/models/vllm_causallms.py) and the vLLM documentation. + +vLLM occasionally differs in output from Huggingface. We treat Huggingface as the reference implementation, and provide a [script](./scripts/model_comparator.py) for checking the validity of vllm results against HF. + +> [!Tip] +> For fastest performance, we recommend using `--batch_size auto` for vLLM whenever possible, to leverage its continuous batching functionality! + +> [!Tip] +> Passing `max_model_len=4096` or some other reasonable default to vLLM through model args may cause speedups or prevent out-of-memory errors when trying to use auto batch size, such as for Mistral-7B-v0.1 which defaults to a maximum length of 32k. + +### Model APIs and Inference Servers + +Our library also supports the evaluation of models served via several commercial APIs, and we hope to implement support for the most commonly used performant local/self-hosted inference servers. + +To call a hosted model, use: + +```bash +export OPENAI_API_KEY=YOUR_KEY_HERE +lm_eval --model openai-completions \ + --model_args model=davinci \ + --tasks lambada_openai,hellaswag +``` + +We also support using your own local inference server with servers that mirror the OpenAI Completions and ChatCompletions APIs. + +```bash +lm_eval --model local-completions --tasks gsm8k --model_args model=facebook/opt-125m,base_url=http://{yourip}:8000/v1/completions,num_concurrent=1,max_retries=3,tokenized_requests=False,batch_size=16 +``` +Note that for externally hosted models, configs such as `--device` which relate to where to place a local model should not be used and do not function. Just like you can use `--model_args` to pass arbitrary arguments to the model constructor for local models, you can use it to pass arbitrary arguments to the model API for hosted models. See the documentation of the hosting service for information on what arguments they support. + +| API or Inference Server | Implemented? | `--model ` name | Models supported: | Request Types: | +|---------------------------------------------------------------------------------------------------------------------------|---------------------------------|-----------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------| +| OpenAI Completions | :heavy_check_mark: | `openai-completions`, `local-completions` | All OpenAI Completions API models | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | +| OpenAI ChatCompletions | :heavy_check_mark: | `openai-chat-completions`, `local-chat-completions` | [All ChatCompletions API models](https://platform.openai.com/docs/guides/gpt) | `generate_until` (no logprobs) | +| Anthropic | :heavy_check_mark: | `anthropic` | [Supported Anthropic Engines](https://docs.anthropic.com/claude/reference/selecting-a-model) | `generate_until` (no logprobs) | +| Anthropic Chat | :heavy_check_mark: | `anthropic-chat`, `anthropic-chat-completions` | [Supported Anthropic Engines](https://docs.anthropic.com/claude/docs/models-overview) | `generate_until` (no logprobs) | +| Textsynth | :heavy_check_mark: | `textsynth` | [All supported engines](https://textsynth.com/documentation.html#engines) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | +| Cohere | [:hourglass: - blocked on Cohere API bug](https://github.com/EleutherAI/lm-evaluation-harness/pull/395) | N/A | [All `cohere.generate()` engines](https://docs.cohere.com/docs/models) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | +| [Llama.cpp](https://github.com/ggerganov/llama.cpp) (via [llama-cpp-python](https://github.com/abetlen/llama-cpp-python)) | :heavy_check_mark: | `gguf`, `ggml` | [All models supported by llama.cpp](https://github.com/ggerganov/llama.cpp) | `generate_until`, `loglikelihood`, (perplexity evaluation not yet implemented) | +| vLLM | :heavy_check_mark: | `vllm` | [Most HF Causal Language Models](https://docs.vllm.ai/en/latest/models/supported_models.html) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | +| Mamba | :heavy_check_mark: | `mamba_ssm` | [Mamba architecture Language Models via the `mamba_ssm` package](https://huggingface.co/state-spaces) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | +| Huggingface Optimum (Causal LMs) | ✔️ | `openvino` | Any decoder-only AutoModelForCausalLM converted with Huggingface Optimum into OpenVINO™ Intermediate Representation (IR) format | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | ... | +| Neuron via AWS Inf2 (Causal LMs) | ✔️ | `neuronx` | Any decoder-only AutoModelForCausalLM supported to run on [huggingface-ami image for inferentia2](https://aws.amazon.com/marketplace/pp/prodview-gr3e6yiscria2) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | ... | +| [Neural Magic DeepSparse](https://github.com/neuralmagic/deepsparse) | ✔️ | `deepsparse` | Any LM from [SparseZoo](https://sparsezoo.neuralmagic.com/) or on [HF Hub with the "deepsparse" tag](https://huggingface.co/models?other=deepsparse) | `generate_until`, `loglikelihood` | ... | +| [Neural Magic SparseML](https://github.com/neuralmagic/sparseml) | ✔️ | `sparseml` | Any decoder-only AutoModelForCausalLM from [SparseZoo](https://sparsezoo.neuralmagic.com/) or on [HF Hub](https://huggingface.co/neuralmagic). Especially useful for models with quantization like [`zoo:llama2-7b-gsm8k_llama2_pretrain-pruned60_quantized`](https://sparsezoo.neuralmagic.com/models/llama2-7b-gsm8k_llama2_pretrain-pruned60_quantized) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | ... | +| Your local inference server! | :heavy_check_mark: | `local-completions` or `local-chat-completions` | Support for OpenAI API-compatible servers, with easy customization for other APIs. | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | | ... | + +Models which do not supply logits or logprobs can be used with tasks of type `generate_until` only, while local models, or APIs that supply logprobs/logits of their prompts, can be run on all task types: `generate_until`, `loglikelihood`, `loglikelihood_rolling`, and `multiple_choice`. + +For more information on the different task `output_types` and model request types, see [our documentation](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/model_guide.md#interface). + +> [!Note] +> For best performance with closed chat model APIs such as Anthropic Claude 3 and GPT-4, we recommend carefully looking at a few sample outputs using `--limit 10` first to confirm answer extraction and scoring on generative tasks is performing as expected. providing `system=""` within `--model_args` for anthropic-chat-completions, to instruct the model what format to respond in, may be useful. + + +### Other Frameworks + +A number of other libraries contain scripts for calling the eval harness through their library. These include [GPT-NeoX](https://github.com/EleutherAI/gpt-neox/blob/main/eval_tasks/eval_adapter.py), [Megatron-DeepSpeed](https://github.com/microsoft/Megatron-DeepSpeed/blob/main/examples/MoE/readme_evalharness.md), and [mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/blob/master/eval_harness.py). + +To create your own custom integration you can follow instructions from [this tutorial](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/interface.md#external-library-usage). + +### Additional Features +> [!Note] +> For tasks unsuitable for direct evaluation — either due risks associated with executing untrusted code or complexities in the evaluation process — the `--predict_only` flag is available to obtain decoded generations for post-hoc evaluation. + +If you have a Metal compatible Mac, you can run the eval harness using the MPS back-end by replacing `--device cuda:0` with `--device mps` (requires PyTorch version 2.1 or higher). **Note that the PyTorch MPS backend is still in early stages of development, so correctness issues or unsupported operations may exist. If you observe oddities in model performance on the MPS back-end, we recommend first checking that a forward pass of your model on `--device cpu` and `--device mps` match.** + +> [!Note] +> You can inspect what the LM inputs look like by running the following command: +> ```bash +> python write_out.py \ +> --tasks \ +> --num_fewshot 5 \ +> --num_examples 10 \ +> --output_base_path /path/to/output/folder +> ``` +> This will write out one text file for each task. + +To verify the data integrity of the tasks you're performing in addition to running the tasks themselves, you can use the `--check_integrity` flag: + +```bash +lm_eval --model openai \ + --model_args engine=davinci \ + --tasks lambada_openai,hellaswag \ + --check_integrity +``` + +## Advanced Usage Tips + +For models loaded with the HuggingFace `transformers` library, any arguments provided via `--model_args` get passed to the relevant constructor directly. This means that anything you can do with `AutoModel` can be done with our library. For example, you can pass a local path via `pretrained=` or use models finetuned with [PEFT](https://github.com/huggingface/peft) by taking the call you would run to evaluate the base model and add `,peft=PATH` to the `model_args` argument: +```bash +lm_eval --model hf \ + --model_args pretrained=EleutherAI/gpt-j-6b,parallelize=True,load_in_4bit=True,peft=nomic-ai/gpt4all-j-lora \ + --tasks openbookqa,arc_easy,winogrande,hellaswag,arc_challenge,piqa,boolq \ + --device cuda:0 +``` + +Models provided as delta weights can be easily loaded using the Hugging Face transformers library. Within --model_args, set the delta argument to specify the delta weights, and use the pretrained argument to designate the relative base model to which they will be applied: +```bash +lm_eval --model hf \ + --model_args pretrained=Ejafa/llama_7B,delta=lmsys/vicuna-7b-delta-v1.1 \ + --tasks hellaswag +``` + +[GPTQ](https://github.com/PanQiWei/AutoGPTQ) quantized models can be loaded by specifying their file names in `,autogptq=NAME` (or `,autogptq=True` for default names) in the `model_args` argument: + +```bash +lm_eval --model hf \ + --model_args pretrained=model-name-or-path,autogptq=model.safetensors,gptq_use_triton=True \ + --tasks hellaswag +``` + +We support wildcards in task names, for example you can run all of the machine-translated lambada tasks via `--task lambada_openai_mt_*`. + +## Saving Results + +To save evaluation results provide an `--output_path`. We also support logging model responses with the `--log_samples` flag for post-hoc analysis. + +Additionally, one can provide a directory with `--use_cache` to cache the results of prior runs. This allows you to avoid repeated execution of the same (model, task) pairs for re-scoring. + +To push results and samples to the Hugging Face Hub, first ensure an access token with write access is set in the `HF_TOKEN` environment variable. Then, use the `--hf_hub_log_args` flag to specify the organization, repository name, repository visibility, and whether to push results and samples to the Hub - [example dataset on the HF Hub](https://huggingface.co/datasets/KonradSzafer/lm-eval-results-demo). For instance: + +```bash +lm_eval --model hf \ + --model_args pretrained=model-name-or-path,autogptq=model.safetensors,gptq_use_triton=True \ + --tasks hellaswag \ + --log_samples \ + --output_path results \ + --hf_hub_log_args hub_results_org=EleutherAI,hub_repo_name=lm-eval-results,push_results_to_hub=True,push_samples_to_hub=True,public_repo=False \ +``` + +This allows you to easily download the results and samples from the Hub, using: +```python +from datasets import load_dataset + +load_dataset("EleutherAI/lm-eval-results-private", "hellaswag", "latest") +``` + +For a full list of supported arguments, check out the [interface](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/interface.md) guide in our documentation! + +## Visualizing Results + +You can seamlessly visualize and analyze the results of your evaluation harness runs using both Weights & Biases (W&B) and Zeno. + +### Zeno + +You can use [Zeno](https://zenoml.com) to visualize the results of your eval harness runs. + +First, head to [hub.zenoml.com](https://hub.zenoml.com) to create an account and get an API key [on your account page](https://hub.zenoml.com/account). +Add this key as an environment variable: + +```bash +export ZENO_API_KEY=[your api key] +``` + +You'll also need to install the `lm_eval[zeno]` package extra. + +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. + +```bash +lm_eval \ + --model hf \ + --model_args pretrained=EleutherAI/gpt-j-6B \ + --tasks hellaswag \ + --device cuda:0 \ + --batch_size 8 \ + --log_samples \ + --output_path output/gpt-j-6B +``` + +Then, you can upload the resulting data using the `zeno_visualize` script: + +```bash +python scripts/zeno_visualize.py \ + --data_path output \ + --project_name "Eleuther Project" +``` + +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. + +You can find an example of this workflow in [examples/visualize-zeno.ipynb](examples/visualize-zeno.ipynb). + +### Weights and Biases + +With the [Weights and Biases](https://wandb.ai/site) 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. + +The integration provide functionalities + +- to automatically log the evaluation results, +- log the samples as W&B Tables for easy visualization, +- log the `results.json` file as an artifact for version control, +- log the `_eval_samples.json` file if the samples are logged, +- generate a comprehensive report for analysis and visualization with all the important metric, +- log task and cli specific configs, +- and more out of the box like the command used to run the evaluation, GPU/CPU counts, timestamp, etc. + +First you'll need to install the lm_eval[wandb] package extra. Do `pip install lm_eval[wandb]`. + +Authenticate your machine with an your unique W&B token. Visit https://wandb.ai/authorize to get one. Do `wandb login` in your command line terminal. + +Run eval harness as usual with a `wandb_args` flag. Use this flag to provide arguments for initializing a wandb run ([wandb.init](https://docs.wandb.ai/ref/python/init)) as comma separated string arguments. + +```bash +lm_eval \ + --model hf \ + --model_args pretrained=microsoft/phi-2,trust_remote_code=True \ + --tasks hellaswag,mmlu_abstract_algebra \ + --device cuda:0 \ + --batch_size 8 \ + --output_path output/phi-2 \ + --limit 10 \ + --wandb_args project=lm-eval-harness-integration \ + --log_samples +``` + +In the stdout, you will find the link to the W&B run page as well as link to the generated report. You can find an example of this workflow in [examples/visualize-wandb.ipynb](examples/visualize-wandb.ipynb), and an example of how to integrate it beyond the CLI. + +## How to Contribute or Learn More? + +For more information on the library and how everything fits together, check out all of our [documentation pages](https://github.com/EleutherAI/lm-evaluation-harness/tree/main/docs)! We plan to post a larger roadmap of desired + planned library improvements soon, with more information on how contributors can help. + +### Implementing new tasks + +To implement a new task in the eval harness, see [this guide](./docs/new_task_guide.md). + +In general, we follow this priority list for addressing concerns about prompting and other eval details: +1. If there is widespread agreement among people who train LLMs, use the agreed upon procedure. +2. If there is a clear and unambiguous official implementation, use that procedure. +3. If there is widespread agreement among people who evaluate LLMs, use the agreed upon procedure. +4. If there are multiple common implementations but not universal or widespread agreement, use our preferred option among the common implementations. As before, prioritize choosing from among the implementations found in LLM training papers. + +These are guidelines and not rules, and can be overruled in special circumstances. + +We try to prioritize agreement with the procedures used by other groups to decrease the harm when people inevitably compare runs across different papers despite our discouragement of the practice. Historically, we also prioritized the implementation from [Language Models are Few Shot Learners](https://arxiv.org/abs/2005.14165) as our original goal was specifically to compare results with that paper. + +### Support + +The best way to get support is to open an issue on this repo or join the [EleutherAI Discord server](https://discord.gg/eleutherai). The `#lm-thunderdome` channel is dedicated to developing this project and the `#release-discussion` channel is for receiving support for our releases. If you've used the library and have had a positive (or negative) experience, we'd love to hear from you! + +## Optional Extras +Extras dependencies can be installed via `pip install -e ".[NAME]"` + +| Name | Use | +|-----------------|----------------------------------------------| +| api | For using api models (Anthropic, OpenAI API) | +| deepsparse | For running NM's DeepSparse models | +| dev | For linting PRs and contributions | +| gptq | For loading models with GPTQ | +| hf_transfer | For speeding up HF Hub file downloads | +| ifeval | For running the IFEval task | +| neuronx | For running on AWS inf2 instances | +| mamba | For loading Mamba SSM models | +| math | For running math task answer checking | +| multilingual | For multilingual tokenizers | +| optimum | For running Intel OpenVINO models | +| promptsource | For using PromptSource prompts | +| sentencepiece | For using the sentencepiece tokenizer | +| sparseml | For using NM's SparseML models | +| testing | For running library test suite | +| vllm | For loading models with vLLM | +| zeno | For visualizing results with Zeno | +| --------------- | --------------------------------------- | +| all | Loads all extras (not recommended) | + +## Cite as + +``` +@misc{eval-harness, + author = {Gao, Leo and Tow, Jonathan and Abbasi, Baber and Biderman, Stella and Black, Sid and DiPofi, Anthony and Foster, Charles and Golding, Laurence and Hsu, Jeffrey and Le Noac'h, Alain and Li, Haonan and McDonell, Kyle and Muennighoff, Niklas and Ociepa, Chris and Phang, Jason and Reynolds, Laria and Schoelkopf, Hailey and Skowron, Aviya and Sutawika, Lintang and Tang, Eric and Thite, Anish and Wang, Ben and Wang, Kevin and Zou, Andy}, + title = {A framework for few-shot language model evaluation}, + month = 07, + year = 2024, + publisher = {Zenodo}, + version = {v0.4.3}, + doi = {10.5281/zenodo.12608602}, + url = {https://zenodo.org/records/12608602} +} +``` diff --git a/testbed/EleutherAI__lm-evaluation-harness/ignore.txt b/testbed/EleutherAI__lm-evaluation-harness/ignore.txt new file mode 100644 index 0000000000000000000000000000000000000000..de10b539b98c9e500d2d838ed3eb9bece95c00e2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/ignore.txt @@ -0,0 +1,8 @@ +ROUGE +rouge +nin +maka +mor +te +ond +extraversion diff --git a/testbed/EleutherAI__lm-evaluation-harness/mypy.ini b/testbed/EleutherAI__lm-evaluation-harness/mypy.ini new file mode 100644 index 0000000000000000000000000000000000000000..76a0c86452e1943edb6680b9a1fdc9627e2f7593 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/mypy.ini @@ -0,0 +1,29 @@ +[mypy] +python_version = 3.8 +show_traceback = True +check_untyped_defs = True +no_implicit_reexport = True +warn_unreachable = True +warn_unused_configs = True +warn_unused_ignores = True +warn_redundant_casts = True + +# We ignore errors everywhere to gradually add type annotations + +[mypy-lm_eval.*] +ignore_errors = True + +[mypy-lm_eval.api.*] +ignore_errors = True + +[mypy-lm_eval.prompts.*] +ignore_errors = True + +[mypy-lm_eval.models.*] +ignore_errors = True + +[mypy-scripts.*] +ignore_errors = True + +[mypy-main] +ignore_errors = True diff --git a/testbed/EleutherAI__lm-evaluation-harness/pile_statistics.json b/testbed/EleutherAI__lm-evaluation-harness/pile_statistics.json new file mode 100644 index 0000000000000000000000000000000000000000..116f0eb976d735bdf92cf06341f2483e69b67e36 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/pile_statistics.json @@ -0,0 +1,37 @@ +{ + "Data": "Pile statistics", + "Document Count": 210607728, + "Total Pile Characters": 421215456, + "File Start Offsets": [ + 0, + 7021438, + 14042822, + 21066113, + 28086515, + 35106072, + 42123306, + 49145091, + 56165817, + 63185587, + 70211208, + 77234322, + 84249267, + 91267634, + 98285983, + 105305110, + 112322489, + 119342491, + 126367373, + 133389153, + 140412039, + 147432373, + 154452516, + 161470190, + 168492733, + 175512521, + 182526939, + 189547478, + 196565318, + 203583306 + ] +} diff --git a/testbed/EleutherAI__lm-evaluation-harness/requirements.txt b/testbed/EleutherAI__lm-evaluation-harness/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..d6e1198b1ab1f5a7f19c6f1fc2ba7338438cf718 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/requirements.txt @@ -0,0 +1 @@ +-e . diff --git a/testbed/EleutherAI__lm-evaluation-harness/setup.py b/testbed/EleutherAI__lm-evaluation-harness/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..b5d8fabb8630f2b4c1e00465e4d22d60e8aa00c3 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/setup.py @@ -0,0 +1,5 @@ +import setuptools + + +# This is to make sure that the package supports editable installs +setuptools.setup() diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/__init__.py b/testbed/EleutherAI__lm-evaluation-harness/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/test_cli.py b/testbed/EleutherAI__lm-evaluation-harness/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..feaa7340d6a36da7c98f3c44128702fc33f0e770 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/test_cli.py @@ -0,0 +1,43 @@ +import argparse + +import pytest + +import lm_eval.__main__ + + +def test_cli_parse_error(): + """ + Assert error raised if cli args argument doesn't have type + """ + with pytest.raises(ValueError): + parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) + parser.add_argument( + "--model", "-m", type=str, default="hf", help="Name of model e.g. `hf`" + ) + parser.add_argument( + "--tasks", + "-t", + default=None, + metavar="task1,task2", + help="To get full list of tasks, use the command lm-eval --tasks list", + ) + lm_eval.__main__.check_argument_types(parser) + + +def test_cli_parse_no_error(): + """ + Assert typed arguments are parsed correctly + """ + parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) + parser.add_argument( + "--model", "-m", type=str, default="hf", help="Name of model e.g. `hf`" + ) + parser.add_argument( + "--tasks", + "-t", + type=str, + default=None, + metavar="task1,task2", + help="To get full list of tasks, use the command lm-eval --tasks list", + ) + lm_eval.__main__.check_argument_types(parser) diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/test_evaluator.py b/testbed/EleutherAI__lm-evaluation-harness/tests/test_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..cc5f70fa73edf6a9dbd4d8d325dc3cc868eace6c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/test_evaluator.py @@ -0,0 +1,151 @@ +import os +import re +from typing import List + +import pytest + +import lm_eval.api as api +import lm_eval.evaluator as evaluator +from lm_eval import tasks +from lm_eval.utils import make_table + + +os.environ["TOKENIZERS_PARALLELISM"] = "false" +# TODO: more fine grained unit tests rather than this big honking integration +# test once we break evaluator into smaller, more manageable pieces + + +@pytest.mark.parametrize( + "task_name,limit,model,model_args,bootstrap_iters", + [ + ( + ["arc_easy"], + 10, + "hf", + "pretrained=EleutherAI/pythia-160m,dtype=float32,device=cpu", + 0, + ), + ( + ["mmlu_abstract_algebra"], + None, + "hf", + "pretrained=EleutherAI/pythia-160m,dtype=float32,device=cpu", + 10000, + ), + ], + ids=lambda d: f"{d}", +) +def test_evaluator( + task_name: List[str], limit: int, model: str, model_args: str, bootstrap_iters: int +): + e1 = evaluator.simple_evaluate( + model=model, + tasks=task_name, + limit=limit, + model_args=model_args, + bootstrap_iters=bootstrap_iters, + ) + assert e1 is not None + + lm = api.registry.get_model(model).create_from_arg_string( + model_args, + { + "batch_size": None, + "max_batch_size": None, + "device": None, + }, + ) + task_manager = tasks.TaskManager() + task_dict = tasks.get_task_dict(task_name, task_manager) + + e2 = evaluator.evaluate( + lm=lm, + task_dict=task_dict, + limit=limit, + bootstrap_iters=bootstrap_iters, + ) + + assert e2 is not None + # check that caching is working + + def r(x): + if "arc_easy" in x["results"]: + return x["results"]["arc_easy"] + else: + return x["results"]["mmlu_abstract_algebra"] + + assert all( + x == y + for x, y in zip([y for _, y in r(e1).items()], [y for _, y in r(e2).items()]) + ) + + +@pytest.mark.parametrize( + "task_name,limit,model,model_args", + [ + ( + ["ai2_arc"], + 10, + "hf", + "pretrained=EleutherAI/pythia-14m,dtype=float32,device=cpu", + ), + ( + ["mmlu_stem"], + 10, + "hf", + "pretrained=EleutherAI/pythia-14m,dtype=float32,device=cpu", + ), + ( + ["lambada_openai"], + 10, + "hf", + "pretrained=EleutherAI/pythia-14m,dtype=float32,device=cpu", + ), + ( + ["wikitext"], + 10, + "hf", + "pretrained=EleutherAI/pythia-14m,dtype=float32,device=cpu", + ), + ], + ids=lambda d: f"{d}", +) +def test_printed_results(task_name: List[str], limit: int, model: str, model_args: str): + results = evaluator.simple_evaluate( + model=model, + tasks=task_name, + limit=limit, + model_args=model_args, + bootstrap_iters=0, + random_seed=0, + numpy_random_seed=0, + torch_random_seed=0, + fewshot_random_seed=0, + ) + + filename = "_".join( + ( + "-".join(task_name), + str(limit), + str(model), + re.sub(r"[^a-zA-Z0-9_\-\.]", "-", model_args), + ) + ) + filepath = f"./tests/testdata/{filename}.txt" + with open(filepath, "r") as f: + t1 = f.read().strip() + + t2 = make_table(results).strip() + + t1_lines, t2_lines = t1.splitlines(), t2.splitlines() + assert len(t1_lines) == len(t2_lines) + for t1_line, t2_line in zip(t1_lines, t2_lines): + t1_items, t2_items = t1_line.split("|"), t2_line.split("|") + assert len(t1_items) == len(t2_items) + for t1_item, t2_item in zip(t1_items, t2_items): + try: + t1_item = float(t1_item) + t2_item = float(t2_item) + assert abs(t1_item - t2_item) < 0.3 + except ValueError: + assert t1_item == t2_item diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/test_include_path.py b/testbed/EleutherAI__lm-evaluation-harness/tests/test_include_path.py new file mode 100644 index 0000000000000000000000000000000000000000..debbdaf46436a74155542b91ea7762bf8c63cd3d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/test_include_path.py @@ -0,0 +1,93 @@ +import os + +import pytest + +import lm_eval.api as api +import lm_eval.evaluator as evaluator +from lm_eval import tasks + + +@pytest.mark.parametrize( + "limit,model,model_args", + [ + ( + 10, + "hf", + "pretrained=EleutherAI/pythia-160m,dtype=float32,device=cpu", + ), + ], +) +def test_include_correctness(limit: int, model: str, model_args: str): + task_name = ["arc_easy"] + + task_manager = tasks.TaskManager() + task_dict = tasks.get_task_dict(task_name, task_manager) + + e1 = evaluator.simple_evaluate( + model=model, + tasks=task_name, + limit=limit, + model_args=model_args, + ) + assert e1 is not None + + # run with evaluate() and "arc_easy" test config (included from ./testconfigs path) + lm = api.registry.get_model(model).create_from_arg_string( + model_args, + { + "batch_size": None, + "max_batch_size": None, + "device": None, + }, + ) + + task_name = ["arc_easy"] + + task_manager = tasks.TaskManager( + include_path=os.path.dirname(os.path.abspath(__file__)) + "/testconfigs", + include_defaults=False, + ) + task_dict = tasks.get_task_dict(task_name, task_manager) + + e2 = evaluator.evaluate( + lm=lm, + task_dict=task_dict, + limit=limit, + ) + + assert e2 is not None + # check that caching is working + + def r(x): + return x["results"]["arc_easy"] + + assert all( + x == y + for x, y in zip([y for _, y in r(e1).items()], [y for _, y in r(e2).items()]) + ) + + +# test that setting include_defaults = False works as expected and that include_path works +def test_no_include_defaults(): + task_name = ["arc_easy"] + + task_manager = tasks.TaskManager( + include_path=os.path.dirname(os.path.abspath(__file__)) + "/testconfigs", + include_defaults=False, + ) + # should succeed, because we've included an 'arc_easy' task from this dir + task_dict = tasks.get_task_dict(task_name, task_manager) + + # should fail, since ./testconfigs has no arc_challenge task + task_name = ["arc_challenge"] + with pytest.raises(KeyError): + task_dict = tasks.get_task_dict(task_name, task_manager) # noqa: F841 + + +# test that include_path containing a task shadowing another task's name fails +# def test_shadowed_name_fails(): + +# task_name = ["arc_easy"] + +# task_manager = tasks.TaskManager(include_path=os.path.dirname(os.path.abspath(__file__)) + "/testconfigs") +# task_dict = tasks.get_task_dict(task_name, task_manager) diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/test_janitor.py b/testbed/EleutherAI__lm-evaluation-harness/tests/test_janitor.py new file mode 100644 index 0000000000000000000000000000000000000000..e0ed7525a72fe938d80e03f1b9078ca454915ac2 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/test_janitor.py @@ -0,0 +1,446 @@ +import os +from collections import defaultdict + +from lm_eval.decontamination.janitor import ( + Janitor, + form_ngrams, + split_indices, + word_ngrams, + word_ngrams_indices, +) + + +os.environ["TOKENIZERS_PARALLELISM"] = "false" +TEST_SEQUENCE = ( + "Hello my name is Bob, I like eating pizza, chicken, chips and ice cream. Maybe I should eat some" + " more salad but it's so booooring. I just... like eating pizza, chicken, chips and ice cream so much." +) + +JANITOR_EXPECTED = ( + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing " + " characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " +) + +JANITOR_FILTH1 = "filth lots of dirty filthy filth" +JANITOR_FILTH2 = "filth lots of filthy dirty filth" + + +def simple_ngram(sequence, n): + ngrams = list() + ngram = [] + for x in sequence: + ngram.extend([x]) + if len(ngram) == n: + ngrams.extend([tuple(ngram)]) + ngram = ngram[1:] + + return ngrams + + +def test_form_ngrams(): + sequence = TEST_SEQUENCE + + n_values = [1, 2, 3, 5, 13] + for n in n_values: + comparison = simple_ngram(sequence, n) + result_to_test = list(form_ngrams(iter(sequence), n)) + assert len(comparison) == len(result_to_test) + assert comparison == result_to_test + + +def test_word_ngrams(): + sequence = TEST_SEQUENCE + + words = sequence.split() + + n_values = [1, 2, 3, 5, 13] + for n in n_values: + comparison = simple_ngram(words, n) + comparison = [" ".join(ngram) for ngram in comparison] + result_to_test = list(word_ngrams(sequence, n)) + assert len(comparison) == len(result_to_test) + assert result_to_test == comparison + + +def test_split_indices(): + sequence = TEST_SEQUENCE + + comparison = [] + current_word = "" + for i, c in enumerate(sequence): + if c != " ": + current_word += c + else: + if current_word: + comparison.extend([(current_word, (i - len(current_word), i - 1))]) + current_word = "" + + if current_word: + len_sequence = len(sequence) + comparison.extend( + [ + ( + current_word, + (len_sequence - len(current_word), len_sequence - 1), + ) + ] + ) + current_word = "" + + result_to_test = list(split_indices(sequence)) + assert len(comparison) == len(result_to_test) + assert comparison == result_to_test + + +def test_word_ngrams_indices(): + sequence = TEST_SEQUENCE + + n_values = [1, 2, 3, 5, 13] + + for n in n_values: + ngrams = [" ".join(ngram) for ngram in simple_ngram(sequence.split(), n)] + tracker = defaultdict(int) + comparison = [] + for ngram in ngrams: + while True: + start = sequence.find(ngram, tracker[ngram]) + assert start != -1 # testing the test + + end = start + len(ngram) - 1 + tracker[ngram] = end + 1 + + # ignore partial word matches + if not ( + (start != 0 and sequence[start - 1] != " ") + or (end != len(sequence) - 1 and sequence[end + 1] != " ") + ): + break + + comparison.extend([(ngram, (start, end))]) + + result_to_test = list(word_ngrams_indices(sequence, n)) + assert len(result_to_test) == len(comparison) + assert result_to_test == comparison + + +# Assumptions from GPT3 Paper: +# the 200 characters to remove include punctuation and is actually a half-window + + +# All tests below initially test without any registered contaminants, expecting the same sequence back. +def test_janitor1(): + # First test using a 1gram and expected the first block before the filth to have some remaining + # characters, but the second block should be completely removed. + + sequence = ( + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "FILTH. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + ) + + filth = "filth" + + expected_result = ( + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing " + ) + + janitor = Janitor( + ngram_n=1, window_to_remove=200, too_dirty_cutoff=10, minimum_slice_length=200 + ) + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == sequence + + janitor.register_contaminant(filth) + assert janitor.dirt_ngrams == {filth} + + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == expected_result + + +def test_janitor2(): + # Second test using a 1gram and expected the first block before the filth to have some remaining + # characters, and the second block is longer then 200 characters so should also have some remaining. + + sequence = ( + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "FILTH. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + ) + + filth = "filth" + + janitor = Janitor( + ngram_n=1, window_to_remove=200, too_dirty_cutoff=10, minimum_slice_length=200 + ) + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == sequence + + janitor.register_contaminant(filth) + assert janitor.dirt_ngrams == {filth} + + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == JANITOR_EXPECTED + + +def test_janitor3(): + # Same test as above but with a 6gram. + + sequence = ( + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "FILTH. lots of dirty filtHy FIlTh " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + ) + + janitor = Janitor( + ngram_n=6, window_to_remove=200, too_dirty_cutoff=10, minimum_slice_length=200 + ) + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == sequence + + janitor.register_contaminant(JANITOR_FILTH1) + assert janitor.dirt_ngrams == {JANITOR_FILTH1} + + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == JANITOR_EXPECTED + + +def test_janitor4(): + # This test adds another block to that from the previous. The middle block should be entirely + # removed as the 200 characters are removed from each side. + + sequence = ( + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "FILTH. lots of dirty filtHy FIlTh " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "FILTH. lots of dirty filtHy FIlTh " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + ) + + janitor = Janitor( + ngram_n=6, window_to_remove=200, too_dirty_cutoff=10, minimum_slice_length=200 + ) + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == sequence + + janitor.register_contaminant(JANITOR_FILTH1) + assert janitor.dirt_ngrams == {JANITOR_FILTH1} + + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == JANITOR_EXPECTED + + +def test_janitor5(): + # Same as above but using multiple different filth 6grams. + + sequence = ( + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "FILTH. lots of dirty filtHy FIlTh " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "FILTH. lots of filtHy dirty FIlTh " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + ) + + filths = [JANITOR_FILTH1, JANITOR_FILTH2] + + janitor = Janitor( + ngram_n=6, window_to_remove=200, too_dirty_cutoff=10, minimum_slice_length=200 + ) + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == sequence + + for filth in filths: + janitor.register_contaminant(filth) + assert janitor.dirt_ngrams == set(filths) + + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == JANITOR_EXPECTED + + +def test_janitor6(): + # Same as above but now we add 10 filths and expect the same result, the following test does 11. + + sequence = ( + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "FILTH. lots of filtHy dirty FIlTh " + "FILTH. lots of filtHy dirty FIlTh " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + ) + + filths = [JANITOR_FILTH1, JANITOR_FILTH2] + + janitor = Janitor( + ngram_n=6, window_to_remove=200, too_dirty_cutoff=10, minimum_slice_length=200 + ) + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == sequence + + for filth in filths: + janitor.register_contaminant(filth) + assert janitor.dirt_ngrams == set(filths) + + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == JANITOR_EXPECTED + + +def test_janitor7(): + # Same as above but now we add 9 filths and expect the same result, the following test does 10. + + sequence = ( + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "FILTH. lots of dirty filtHy FIlTh " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "FILTH. lots of filtHy dirty FIlTh " + "FILTH. lots of filtHy dirty FIlTh " + "FILTH. lots of filtHy dirty FIlTh " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + "This is a @line #containing a certain number of characters, 76 to be exact. " + ) + + filths = [JANITOR_FILTH1, JANITOR_FILTH2] + + expected_result = "" + + janitor = Janitor( + ngram_n=6, window_to_remove=200, too_dirty_cutoff=10, minimum_slice_length=200 + ) + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == sequence + + for filth in filths: + janitor.register_contaminant(filth) + assert janitor.dirt_ngrams == set(filths) + + result = janitor.clean_python(sequence) + result = "".join(result) + assert result == expected_result + + +def test_janitor8(): + # This will test the save and load contams + pass diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/test_misc.py b/testbed/EleutherAI__lm-evaluation-harness/tests/test_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..30267f63d0a518a41ae5681088878edcacc1c729 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/test_misc.py @@ -0,0 +1,14 @@ +import random + +import pytest + +import lm_eval.api.metrics as metrics + + +def test_bootstrapping(): + random.seed(42) + arr = [random.random() for _ in range(1000)] + expected = metrics.mean_stderr(arr) + bootstrapped = metrics.bootstrap_stderr(metrics.mean, arr, iters=100000) + + assert bootstrapped == pytest.approx(expected, abs=1e-4) diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/test_prompt.py b/testbed/EleutherAI__lm-evaluation-harness/tests/test_prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..d1e5deb06507aaf85c1d17d88d6237ff0f042875 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/test_prompt.py @@ -0,0 +1,119 @@ +import random +from typing import List + +import numpy as np +import pytest + +from lm_eval import tasks +from lm_eval.tasks import TaskManager +from lm_eval.utils import join_iters + + +MMLU_ANATOMY_ZERO_SHOT = """The following are multiple choice questions (with answers) about anatomy. + +A lesion causing compression of the facial nerve at the stylomastoid foramen will cause ipsilateral +A. paralysis of the facial muscles. +B. paralysis of the facial muscles and loss of taste. +C. paralysis of the facial muscles, loss of taste and lacrimation. +D. paralysis of the facial muscles, loss of taste, lacrimation and decreased salivation. +Answer:""" + +MMLU_ANATOMY_FIVE_SHOT = """The following are multiple choice questions (with answers) about anatomy. + +What is the embryological origin of the hyoid bone? +A. The first pharyngeal arch +B. The first and second pharyngeal arches +C. The second pharyngeal arch +D. The second and third pharyngeal arches +Answer: D + +Which of these branches of the trigeminal nerve contain somatic motor processes? +A. The supraorbital nerve +B. The infraorbital nerve +C. The mental nerve +D. None of the above +Answer: D + +The pleura +A. have no sensory innervation. +B. are separated by a 2 mm space. +C. extend into the neck. +D. are composed of respiratory epithelium. +Answer: C + +In Angle's Class II Div 2 occlusion there is +A. excess overbite of the upper lateral incisors. +B. negative overjet of the upper central incisors. +C. excess overjet of the upper lateral incisors. +D. excess overjet of the upper central incisors. +Answer: C + +Which of the following is the body cavity that contains the pituitary gland? +A. Abdominal +B. Cranial +C. Pleural +D. Spinal +Answer: B + +A lesion causing compression of the facial nerve at the stylomastoid foramen will cause ipsilateral +A. paralysis of the facial muscles. +B. paralysis of the facial muscles and loss of taste. +C. paralysis of the facial muscles, loss of taste and lacrimation. +D. paralysis of the facial muscles, loss of taste, lacrimation and decreased salivation. +Answer:""" + + +@pytest.mark.parametrize( + "task_names,sets,num_fewshot,seed,num_examples,expected_prompt", + [ + (["mmlu_anatomy"], "test", 0, 42, 1, MMLU_ANATOMY_ZERO_SHOT), + (["mmlu_anatomy"], "test", 5, 42, 1, MMLU_ANATOMY_FIVE_SHOT), + ], +) +def test_mmlu_prompt_rendering( + task_names: List[str], + sets: str, + num_fewshot: int, + seed: int, + num_examples: int, + expected_prompt: str, +): + np.random.seed(seed) + + task_manager = TaskManager() + task_dict = tasks.get_task_dict(task_names, task_manager) + + for task_name, task in task_dict.items(): + if isinstance(task, tuple): + _, task = task + + rnd = random.Random() + rnd.seed(seed) + + iters = [] + + for set in sets.split(","): + docs = None + if set == "train" and task.has_training_docs(): + docs = task.training_docs() + if set == "val" and task.has_validation_docs(): + docs = task.validation_docs() + if set == "test" and task.has_test_docs(): + docs = task.test_docs() + if docs is not None: + iters.append(docs) + + if len(iters) == 0: + raise ValueError + + docs = join_iters(iters) + + for i, doc in ( + zip(range(num_examples), docs) if num_examples > 0 else enumerate(docs) + ): + ctx = task.fewshot_context( + doc=doc, + num_fewshot=num_fewshot, + ) + + assert ctx == expected_prompt diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/test_requests_caching.py b/testbed/EleutherAI__lm-evaluation-harness/tests/test_requests_caching.py new file mode 100644 index 0000000000000000000000000000000000000000..fc520454b92f16e8333ada7a5ad58153199c5e78 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/test_requests_caching.py @@ -0,0 +1,122 @@ +import importlib +import os +import sys +from datetime import datetime +from typing import List, Optional, Tuple + +import pytest +import torch + +from lm_eval.caching.cache import PATH + + +MODULE_DIR = os.path.dirname(os.path.realpath(__file__)) + +# NOTE the script this loads uses simple evaluate +# TODO potentially test both the helper script and the normal script +sys.path.append(f"{MODULE_DIR}/../scripts") +model_loader = importlib.import_module("requests_caching") +run_model_for_task_caching = model_loader.run_model_for_task_caching + +os.environ["HF_DATASETS_TRUST_REMOTE_CODE"] = "1" +DEFAULT_TASKS = ["lambada_openai", "sciq"] + + +@pytest.fixture(autouse=True) +def setup_and_teardown(): + # Setup + torch.use_deterministic_algorithms(False) + clear_cache() + # Yields control back to the test function + yield + # Cleanup here + + +def clear_cache(): + if os.path.exists(PATH): + cache_files = os.listdir(PATH) + for file in cache_files: + file_path = f"{PATH}/{file}" + os.unlink(file_path) + + +# leaving tasks here to allow for the option to select specific task files +def get_cache_files(tasks: Optional[List[str]] = None) -> Tuple[List[str], List[str]]: + cache_files = os.listdir(PATH) + + file_task_names = [] + + for file in cache_files: + file_without_prefix = file.split("-")[1] + file_without_prefix_and_suffix = file_without_prefix.split(".")[0] + file_task_names.extend([file_without_prefix_and_suffix]) + + return cache_files, file_task_names + + +def assert_created(tasks: List[str], file_task_names: List[str]): + tasks.sort() + file_task_names.sort() + + assert tasks == file_task_names + + +@pytest.mark.parametrize("tasks", [DEFAULT_TASKS]) +def requests_caching_true(tasks: List[str]): + run_model_for_task_caching(tasks=tasks, cache_requests="true") + + cache_files, file_task_names = get_cache_files() + print(file_task_names) + assert_created(tasks=tasks, file_task_names=file_task_names) + + +@pytest.mark.parametrize("tasks", [DEFAULT_TASKS]) +def requests_caching_refresh(tasks: List[str]): + run_model_for_task_caching(tasks=tasks, cache_requests="true") + + timestamp_before_test = datetime.now().timestamp() + + run_model_for_task_caching(tasks=tasks, cache_requests="refresh") + + cache_files, file_task_names = get_cache_files() + + for file in cache_files: + modification_time = os.path.getmtime(f"{PATH}/{file}") + assert modification_time > timestamp_before_test + + tasks.sort() + file_task_names.sort() + + assert tasks == file_task_names + + +@pytest.mark.parametrize("tasks", [DEFAULT_TASKS]) +def requests_caching_delete(tasks: List[str]): + # populate the data first, rerun this test within this test for additional confidence + # test_requests_caching_true(tasks=tasks) + + run_model_for_task_caching(tasks=tasks, cache_requests="delete") + + cache_files, file_task_names = get_cache_files() + + assert len(cache_files) == 0 + + +# useful for locally running tests through the debugger +if __name__ == "__main__": + + def run_tests(): + tests = [ + # test_requests_caching_true, + # test_requests_caching_refresh, + # test_requests_caching_delete, + ] + # Lookups of global names within a loop is inefficient, so copy to a local variable outside of the loop first + default_tasks = DEFAULT_TASKS + for test_func in tests: + clear_cache() + test_func(tasks=default_tasks) + + print("Tests pass") + + run_tests() diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/test_tasks.py b/testbed/EleutherAI__lm-evaluation-harness/tests/test_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..c9453d54973ea9f094d9bfcaec1b30f8eeb4047d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/test_tasks.py @@ -0,0 +1,119 @@ +import os +from itertools import islice + +import pytest + +import lm_eval.tasks as tasks +from lm_eval.api.task import ConfigurableTask + +from .utils import new_tasks + + +os.environ["TOKENIZERS_PARALLELISM"] = "false" +task_manager = tasks.TaskManager() +# Default Task +TASKS = ["arc_easy"] + + +def task_class(): + global TASKS + # CI: new_tasks checks if any modifications have been made + task_classes = new_tasks() + # Check if task_classes is empty + if task_classes: + return list(task_manager.load_task_or_group(task_classes).values()) + else: + return list(task_manager.load_task_or_group(TASKS).values()) + + +@pytest.fixture() +def limit() -> int: + return 10 + + +# Tests +@pytest.mark.parametrize("task_class", task_class(), ids=lambda x: f"{x.config.task}") +class TestNewTasks: + def test_download(self, task_class: ConfigurableTask): + task_class.download() + assert task_class.dataset is not None + + def test_has_training_docs(self, task_class: ConfigurableTask): + assert task_class.has_training_docs() in [True, False] + + def test_check_training_docs(self, task_class: ConfigurableTask): + if task_class.has_training_docs(): + assert task_class._config["training_split"] is not None + + def test_has_validation_docs(self, task_class): + assert task_class.has_validation_docs() in [True, False] + + def test_check_validation_docs(self, task_class): + if task_class.has_validation_docs(): + assert task_class._config["validation_split"] is not None + + def test_has_test_docs(self, task_class): + assert task_class.has_test_docs() in [True, False] + + def test_check_test_docs(self, task_class): + task = task_class + if task.has_test_docs(): + assert task._config["test_split"] is not None + + def test_should_decontaminate(self, task_class): + task = task_class + assert task.should_decontaminate() in [True, False] + if task.should_decontaminate(): + assert task._config["doc_to_decontamination_query"] is not None + + def test_doc_to_text(self, task_class, limit): + task = task_class + arr = ( + list(islice(task.test_docs(), limit)) + if task.has_test_docs() + else list(islice(task.validation_docs(), limit)) + ) + _array = [task.doc_to_text(doc) for doc in arr] + # space convention; allow txt to have length 0 for perplexity-like tasks since the model tacks an <|endoftext|> on + assert all( + isinstance(x, str) and (x[-1] != " " if len(x) != 0 else True) + for x in _array + ) + + def test_create_choices(self, task_class, limit): + task = task_class + arr = ( + list(islice(task.test_docs(), limit)) + if task.has_test_docs() + else list(islice(task.validation_docs(), limit)) + ) + if "multiple_choice" in task._config.output_type: + _array = [task.doc_to_choice(doc) for doc in arr] + assert all(isinstance(x, list) for x in _array) + assert all(isinstance(x[0], str) for x in _array) + + def test_doc_to_target(self, task_class, limit): + task = task_class + arr = ( + list(islice(task.test_docs(), limit)) + if task.has_test_docs() + else list(islice(task.validation_docs(), limit)) + ) + _array_target = [task.doc_to_target(doc) for doc in arr] + if task._config.output_type == "multiple_choice": + assert all(isinstance(label, int) for label in _array_target) + + def test_build_all_requests(self, task_class, limit): + task_class.build_all_requests(rank=1, limit=limit, world_size=1) + assert task_class.instances is not None + + # ToDO: Add proper testing + def test_construct_requests(self, task_class, limit): + task = task_class + arr = ( + list(islice(task.test_docs(), limit)) + if task.has_test_docs() + else list(islice(task.validation_docs(), limit)) + ) + requests = [task.construct_requests(doc, task.doc_to_text(doc)) for doc in arr] + assert len(requests) == limit if limit else True diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testconfigs/arc_test.yaml b/testbed/EleutherAI__lm-evaluation-harness/tests/testconfigs/arc_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c9052dc80d6d6c3cd26944feec21cfb673330b41 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testconfigs/arc_test.yaml @@ -0,0 +1,21 @@ +task: arc_easy +dataset_path: allenai/ai2_arc +dataset_name: ARC-Easy +output_type: multiple_choice +training_split: train +validation_split: validation +test_split: test +doc_to_text: "Question: {{question}}\nAnswer:" +doc_to_target: "{{choices.label.index(answerKey)}}" +doc_to_choice: "{{choices.text}}" +should_decontaminate: true +doc_to_decontamination_query: "Question: {{question}}\nAnswer:" +metric_list: + - metric: acc + aggregation: mean + higher_is_better: true + - metric: acc_norm + aggregation: mean + higher_is_better: true +metadata: + version: 1.0 diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ai2_arc_10_hf_pretrained-EleutherAI-pythia-14m-dtype-float32-device-cpu.txt b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ai2_arc_10_hf_pretrained-EleutherAI-pythia-14m-dtype-float32-device-cpu.txt new file mode 100644 index 0000000000000000000000000000000000000000..6ba01f21d5711e90b22bafd9979f7a517b98b0ef --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/ai2_arc_10_hf_pretrained-EleutherAI-pythia-14m-dtype-float32-device-cpu.txt @@ -0,0 +1,6 @@ +| Tasks |Version|Filter|n-shot| Metric | |Value| |Stderr| +|-------------|------:|------|-----:|--------|---|----:|---|------| +|arc_challenge| 1|none | 0|acc |↑ | 0.0|± | N/A| +| | |none | 0|acc_norm|↑ | 0.0|± | N/A| +|arc_easy | 1|none | 0|acc |↑ | 0.3|± | N/A| +| | |none | 0|acc_norm|↑ | 0.1|± | N/A| \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_10_hf_pretrained-EleutherAI-pythia-14m-dtype-float32-device-cpu.txt b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_10_hf_pretrained-EleutherAI-pythia-14m-dtype-float32-device-cpu.txt new file mode 100644 index 0000000000000000000000000000000000000000..a3ea263b794b561212250ea3d962d1ba8eb89bde --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/lambada_openai_10_hf_pretrained-EleutherAI-pythia-14m-dtype-float32-device-cpu.txt @@ -0,0 +1,4 @@ +| Tasks |Version|Filter|n-shot| Metric | | Value | |Stderr| +|--------------|------:|------|-----:|----------|---|-------:|---|------| +|lambada_openai| 1|none | 0|acc |↑ | 0.1000|± | N/A| +| | |none | 0|perplexity|↓ |605.3866|± | N/A| \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mmlu_stem_10_hf_pretrained-EleutherAI-pythia-14m-dtype-float32-device-cpu.txt b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mmlu_stem_10_hf_pretrained-EleutherAI-pythia-14m-dtype-float32-device-cpu.txt new file mode 100644 index 0000000000000000000000000000000000000000..8c6c56c1261f69f89dff5ac169fd75d16a5a9f43 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/mmlu_stem_10_hf_pretrained-EleutherAI-pythia-14m-dtype-float32-device-cpu.txt @@ -0,0 +1,22 @@ +| Tasks |Version|Filter|n-shot|Metric| |Value | |Stderr| +|-------------------------------|------:|------|-----:|------|---|-----:|---|------| +|stem | 2|none | |acc |↑ |0.2474|± | N/A| +| - abstract_algebra | 1|none | 0|acc |↑ |0.2000|± | N/A| +| - anatomy | 1|none | 0|acc |↑ |0.3000|± | N/A| +| - astronomy | 1|none | 0|acc |↑ |0.1000|± | N/A| +| - college_biology | 1|none | 0|acc |↑ |0.3000|± | N/A| +| - college_chemistry | 1|none | 0|acc |↑ |0.1000|± | N/A| +| - college_computer_science | 1|none | 0|acc |↑ |0.2000|± | N/A| +| - college_mathematics | 1|none | 0|acc |↑ |0.2000|± | N/A| +| - college_physics | 1|none | 0|acc |↑ |0.3000|± | N/A| +| - computer_security | 1|none | 0|acc |↑ |0.5000|± | N/A| +| - conceptual_physics | 1|none | 0|acc |↑ |0.3000|± | N/A| +| - electrical_engineering | 1|none | 0|acc |↑ |0.4000|± | N/A| +| - elementary_mathematics | 1|none | 0|acc |↑ |0.0000|± | N/A| +| - high_school_biology | 1|none | 0|acc |↑ |0.3000|± | N/A| +| - high_school_chemistry | 1|none | 0|acc |↑ |0.4000|± | N/A| +| - high_school_computer_science| 1|none | 0|acc |↑ |0.3000|± | N/A| +| - high_school_mathematics | 1|none | 0|acc |↑ |0.2000|± | N/A| +| - high_school_physics | 1|none | 0|acc |↑ |0.3000|± | N/A| +| - high_school_statistics | 1|none | 0|acc |↑ |0.0000|± | N/A| +| - machine_learning | 1|none | 0|acc |↑ |0.3000|± | N/A| \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext_10_hf_pretrained-EleutherAI-pythia-14m-dtype-float32-device-cpu.txt b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext_10_hf_pretrained-EleutherAI-pythia-14m-dtype-float32-device-cpu.txt new file mode 100644 index 0000000000000000000000000000000000000000..654e63ee7cb083d729d9be56e0d9d71ef1805928 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wikitext_10_hf_pretrained-EleutherAI-pythia-14m-dtype-float32-device-cpu.txt @@ -0,0 +1,5 @@ +| Tasks |Version|Filter|n-shot| Metric | | Value | |Stderr| +|--------|------:|------|-----:|---------------|---|-------:|---|------| +|wikitext| 2|none | 0|bits_per_byte |↓ | 1.3394|± | N/A| +| | |none | 0|byte_perplexity|↓ | 2.5304|± | N/A| +| | |none | 0|word_perplexity|↓ |130.4801|± | N/A| \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-de-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-de-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..183e66270a61dcb463076306b2768dde7995162f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-de-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-en-de": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.007148103038872972, "chrf_stderr": 9.594096858911254e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-en-de": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ja-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ja-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..9777002c79830918a3939ec6978d606ae967ffe6 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ja-v0-greedy_until @@ -0,0 +1 @@ +7fe61f5847a51e93e97c84b39f4420978727754e4b6cf636a27851c615857530 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ja-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ja-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..57bad300d7f05b7eb0908ad655b0fc90a2bb9c26 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ja-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-en-ja": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 4.1308658294778584e-05, "chrf_stderr": 2.0456539027807417e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-en-ja": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ps-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ps-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..77b600c49afa12cf988280e337a9d4747195f95f --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ps-v0-greedy_until @@ -0,0 +1 @@ +8411c2cb73114cbd0c6e0f17eab2625d486cc3a601105deb0ea1338a401df689 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ru-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ru-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..af339eda5d3d76e00e3e0f3c800353bb2b7fb696 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ru-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-en-ru": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.0007327811114614671, "chrf_stderr": 4.43155903515048e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-en-ru": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ta-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ta-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..1b40263f154461098d6ee820bc0d003c03a6962c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ta-v0-greedy_until @@ -0,0 +1 @@ +5fc556fa90bca7f1b1396e97e392eac8080b0ad53488358799b8fc0b21a94cb1 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ta-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ta-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..b04f968d76055c494762ec6cd2a84327c8351742 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-ta-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-en-ta": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.0, "chrf_stderr": 0.0, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-en-ta": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-zh-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-zh-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..db79b7f03fcfc8f7720f1344339e7d94d8a01ebf --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-zh-v0-greedy_until @@ -0,0 +1 @@ +67f0333ddbcb07d7a9ac12919129a18fe4fea24e4826a11bbdde4fd5ed5ed83f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-zh-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-zh-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..24db35e62fd176b0454ff426ab749787da805897 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-zh-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-en-zh": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.00014170297316825535, "chrf_stderr": 6.590669847391838e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-en-zh": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-zh-v1-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-zh-v1-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..db79b7f03fcfc8f7720f1344339e7d94d8a01ebf --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-zh-v1-greedy_until @@ -0,0 +1 @@ +67f0333ddbcb07d7a9ac12919129a18fe4fea24e4826a11bbdde4fd5ed5ed83f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-zh-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-zh-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..a7a56daf0e793acf229c9b16a751383473bd5e26 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-en-zh-v1-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-en-zh": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.00014170297316825535, "chrf_stderr": 6.590669847391838e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-en-zh": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-fr-de-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-fr-de-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..d5d06a02a30635ad57907b32ae66ccb9ba5a7e23 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-fr-de-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-fr-de": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.01143193767396364, "chrf_stderr": 0.00012555271954563658, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-fr-de": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-iu-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-iu-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..87a1981e79e0558366487aa2476cc751ad3857dc --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-iu-en-v0-greedy_until @@ -0,0 +1 @@ +97bf664a8efa54b5366b8341f77b418106dd0cb26169d5b2d0144e4d3d2bc5c9 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ja-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ja-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..3a89d7fcdfb76bc3912a930cf592da0270ba440c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ja-en-v0-greedy_until @@ -0,0 +1 @@ +1fd846f3c0104e794eb380dae7f648592092ab8bf59234c26d0a671bbbc28df1 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ja-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ja-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..4344b7cd8a1a9bfb8cd60e2aa0ece17f530f7d3d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ja-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-ja-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.010703148854351403, "chrf_stderr": 0.00022242113108130186, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-ja-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-km-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-km-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..a6f148661093f5f97c85e96ab2c01da6e40c1547 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-km-en-v0-greedy_until @@ -0,0 +1 @@ +fb4ec81bb89c70df7e21b43e0e882915b7b71a2a85bb8d4b59e0c7938baaa4c2 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-pl-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-pl-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..899ce01919910ab80fc95b99371bf334a7c7c37a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-pl-en-v0-greedy_until @@ -0,0 +1 @@ +89274499d84176b1ffe4eaec06f2c89ca807342384dc946c2e348d00116aaade \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-pl-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-pl-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..a2f5cb31be388a5ca081567e72d16e42774aa008 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-pl-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-pl-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.01353367757716276, "chrf_stderr": 0.00018386199249976465, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-pl-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ps-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ps-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..00c9c742e4d34830628a52aa34cfd7faaa86516c --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ps-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-ps-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.015192865365105723, "chrf_stderr": 0.00011334541381539086, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-ps-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ru-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ru-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..27c60fb72194325e51647ce0fe137710df6dff86 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ru-en-v0-greedy_until @@ -0,0 +1 @@ +1477ab6542c26bd0222cc1aded174f33bf8d04d1cf6a1c0959aeca4ff3779adc \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ru-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ru-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..b6d0c71ad7c140790040022c51970dea075ab0b1 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ru-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-ru-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.013344639906399232, "chrf_stderr": 7.583552652374546e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-ru-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ta-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ta-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..f0f65972451ff666399f7b2c81194c4b892ac783 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ta-en-v0-greedy_until @@ -0,0 +1 @@ +111ea3efdc08f1cf536631b9426c3a20e482c575d009d2a8c71f59c027578eec \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ta-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ta-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..a2ad506bf94188b54a0f3b7ee6f5d787d34e68ff --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-ta-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-ta-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.013841110664859798, "chrf_stderr": 0.00018476696850880766, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-ta-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-zh-en-v0-greedy_until b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-zh-en-v0-greedy_until new file mode 100644 index 0000000000000000000000000000000000000000..41a1e91515b30a2acdc6363c36af1cdf43f477a9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-zh-en-v0-greedy_until @@ -0,0 +1 @@ +07dbadfd6f2b2b9462ab6187dbfaabae6e5192ab89a8e4ede9237834b9364dd1 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-zh-en-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-zh-en-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..11b8df7f8739d9e4a459636640af6ebb2b7b868a --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wmt20-zh-en-v0-res.json @@ -0,0 +1 @@ +{"results": {"wmt20-zh-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.008438201290981157, "chrf_stderr": 0.0001109053964076822, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt20-zh-en": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wnli-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wnli-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..0c5c0b8ceb64a158bd57294d432b2186f3a0fdf9 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wnli-v0-loglikelihood @@ -0,0 +1 @@ +2ffd304d6096416eb29607e2e7642b1d6043163624967bcf4c4fc00fddc6c721 \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wnli-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wnli-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..8841cb74d16977645c1c7399d8b58de094bafef1 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wnli-v0-res.json @@ -0,0 +1 @@ +{"results": {"wnli": {"acc": 0.3380281690140845, "acc_stderr": 0.05653887739133514}}, "versions": {"wnli": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wnli-v1-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wnli-v1-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..cbf4ad3777eebbcee7c1ccf1c4a4cac64829ad2b --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wnli-v1-loglikelihood @@ -0,0 +1 @@ +8a0f81661d2ab2334bbc8031fac31c0c8882f1d9271dd51599d21dfdbb726dea \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wnli-v1-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wnli-v1-res.json new file mode 100644 index 0000000000000000000000000000000000000000..d12348e0aeb8d7feec272059e08eb30cbb1d918d --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wnli-v1-res.json @@ -0,0 +1 @@ +{"results": {"wnli": {"acc": 0.5633802816901409, "acc_stderr": 0.0592793555841297}}, "versions": {"wnli": 1}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wsc-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wsc-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..d0d2963fe90b29dbbf2527e9a3b559cf9b9c23c7 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wsc-v0-loglikelihood @@ -0,0 +1 @@ +45865468eff5ca31e6a050947a6b3310d9d5ed19d0f2e578a32ecaf1c768600f \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wsc-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wsc-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..84be59624161779e494896d2618dbcf0f1f4b4b0 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wsc-v0-res.json @@ -0,0 +1 @@ +{"results": {"wsc": {"acc": 0.5480769230769231, "acc_stderr": 0.049038186969314335}}, "versions": {"wsc": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wsc273-v0-loglikelihood b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wsc273-v0-loglikelihood new file mode 100644 index 0000000000000000000000000000000000000000..9d592917bd96783c290237446891eef56083a693 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wsc273-v0-loglikelihood @@ -0,0 +1 @@ +26450d414c4581feb51a09882080e7a9b95882e7eab47b1751a4a6024b5a60ee \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wsc273-v0-res.json b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wsc273-v0-res.json new file mode 100644 index 0000000000000000000000000000000000000000..8f023b422a7003d2984e35e58045d8866954a4c4 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testdata/wsc273-v0-res.json @@ -0,0 +1 @@ +{"results": {"wsc273": {"acc": 0.5164835164835165, "acc_stderr": 0.0303004740355766}}, "versions": {"wsc273": 0}} \ No newline at end of file diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/testyamls/test-01.yaml b/testbed/EleutherAI__lm-evaluation-harness/tests/testyamls/test-01.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4e4367eeb3651bd49540009949fc080b9dba0a59 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/testyamls/test-01.yaml @@ -0,0 +1,45 @@ +group: test-1 +group_alias: test 1 +task: + - piqa # string task + - ai2_arc # string tag + - task: super-glue-lm-eval-v1 # Should this be spread out? + num_fewshot: 3 + - task: swag # dict registered task + num_fewshot: 2 + - task: mmlu + num_fewshot: 5 + - group: nli-tasks # dict group + task: + - anli + - boolq + - sglue_rte + num_fewshot: 4 + metric_list: + - metric: brier_score + - task: sciq # dict registered task duplicate + task_alias: sciq 2-shot + num_fewshot: 2 + - task: sciq # dict registered task duplicate + task_alias: sciq 4-shot + num_fewshot: 4 + - task: sciq # dict registered task duplicate + task_alias: sciq 6-shot + num_fewshot: 6 + - task: siqa_custom # dict task + dataset_path: social_i_qa + dataset_name: null + output_type: multiple_choice + training_split: train + validation_split: validation + doc_to_text: "Question: {{context}} {{question}}\nAnswer:" + target_delimiter: " " + doc_to_choice: + - "{{answerA}}" + - "{{answerB}}" + - "{{answerC}}" + doc_to_target: "{{ (label|int) - 1 }}" + metric_list: + - metric: acc + aggregation: mean + higher_is_better: true diff --git a/testbed/EleutherAI__lm-evaluation-harness/tests/utils.py b/testbed/EleutherAI__lm-evaluation-harness/tests/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0c0398029a58f968bdb1c89d6faee3c9a52144b4 --- /dev/null +++ b/testbed/EleutherAI__lm-evaluation-harness/tests/utils.py @@ -0,0 +1,48 @@ +import os +from typing import List, Union + +from lm_eval.utils import load_yaml_config + + +# {{{CI}}} +# This is the path where the output for the changed files for the tasks folder is stored +# FILE_PATH = file_path = ".github/outputs/tasks_all_changed_and_modified_files.txt" + + +# reads a text file and returns a list of words +# used to read the output of the changed txt from tj-actions/changed-files +def load_changed_files(file_path: str) -> List[str]: + with open(file_path, "r", encoding="utf-8") as f: + content = f.read() + words_list = list(content.split()) + return words_list + + +# checks the txt file for list of changed files. +# if file ends with .yaml then check yaml and load the config. +# if the config task is a string, it's a task config. +# if the config task is a list, it's a group config. +def parser(full_path: List[str]) -> List[str]: + _output = set() + for x in full_path: + if x.endswith(".yaml") and os.path.exists(x): + config = load_yaml_config(x, mode="simple") + if isinstance(config["task"], str): + _output.add(config["task"]) + elif isinstance(config["task"], list): + _output.add(config["group"]) + return list(_output) + + +def new_tasks() -> Union[List[str], None]: + FILENAME = ".github/outputs/tasks_all_changed_and_modified_files.txt" + if os.path.exists(FILENAME): + # If tasks folder has changed then we get the list of files from FILENAME + # and parse the yaml files to get the task names. + return parser(load_changed_files(FILENAME)) + if os.getenv("API") is not None: + # Or if API has changed then we set the ENV variable API to True + # and run given tasks. + return ["arc_easy", "hellaswag", "piqa", "wikitext"] + # if both not true just do arc_easy + return None diff --git a/testbed/Project-MONAI__MONAI/.github/codecov.yml b/testbed/Project-MONAI__MONAI/.github/codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..91ab3ab5fd12df45031377ebab5180bf5f062021 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/.github/codecov.yml @@ -0,0 +1,32 @@ +coverage: + status: + project: + default: + target: 70% + threshold: 10 + base: parent + if_no_uploads: error + if_not_found: success + if_ci_failed: error + only_pulls: false + flags: null + paths: null + patch: + default: + target: auto + # Allows PRs without tests, overall stats count + threshold: 100 + base: auto + if_no_uploads: error + if_not_found: success + if_ci_failed: error + only_pulls: false + flags: null + paths: null + +# Disable comments on PR +comment: false + +ignore: + - "versioneer.py" + - "monai/_version.py" diff --git a/testbed/Project-MONAI__MONAI/.github/pull_request_template.md b/testbed/Project-MONAI__MONAI/.github/pull_request_template.md new file mode 100644 index 0000000000000000000000000000000000000000..f1003ec7997bdd7c3f7af51f83d16bde8809a4b1 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/.github/pull_request_template.md @@ -0,0 +1,16 @@ +Fixes # . + +### Description +A few sentences describing the changes proposed in this pull request. + +### Status +**Ready/Work in progress/Hold** + +### Types of changes + +- [x] Non-breaking change (fix or new feature that would not break existing functionality). +- [ ] Breaking change (fix or new feature that would cause existing functionality to change). +- [ ] New tests added to cover the changes. +- [ ] Integration tests passed locally by running `./runtests.sh --codeformat --coverage`. +- [ ] In-line docstrings updated. +- [ ] Documentation updated, tested `make html` command in the `docs/` folder. diff --git a/testbed/Project-MONAI__MONAI/.github/workflows/cron.yml b/testbed/Project-MONAI__MONAI/.github/workflows/cron.yml new file mode 100644 index 0000000000000000000000000000000000000000..f9ffe4d8387cc726ec9fa44097766ed95da5eef9 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/.github/workflows/cron.yml @@ -0,0 +1,67 @@ +name: crons + +on: + schedule: + - cron: "0 2 * * *" # at 02:00 UTC + +jobs: + cron-gpu: + container: + image: nvcr.io/nvidia/pytorch:20.03-py3 + options: "--gpus all" + runs-on: [self-hosted, linux, x64] + strategy: + matrix: + pytorch-version: [1.4.0, latest] + steps: + - uses: actions/checkout@v2 + - name: Install the dependencies + run: | + which python + python -m pip install --upgrade pip wheel + python -m pip uninstall -y torch torchvision + if [ ${{ matrix.pytorch-version }} == "latest" ]; then + python -m pip install torch torchvision + else + python -m pip install torch==${{ matrix.pytorch-version }} + python -m pip install torchvision==0.5.0 + fi + python -m pip install -r requirements-dev.txt + python -m pip list + - name: Run tests report coverage + run: | + nvidia-smi + export CUDA_VISIBLE_DEVICES=$(python -m tests.utils) + echo $CUDA_VISIBLE_DEVICES + python -c "import torch; print(torch.__version__); print('{} of GPUs available'.format(torch.cuda.device_count()))" + python -c 'import torch; print(torch.rand(5,3, device=torch.device("cuda:0")))' + ./runtests.sh --coverage + coverage xml + - name: Upload coverage + uses: codecov/codecov-action@v1 + with: + fail_ci_if_error: false + file: ./coverage.xml + + cron-docker: + container: + image: docker://projectmonai/monai:latest + options: "--gpus all" + runs-on: [self-hosted, linux, x64] + steps: + - name: Run tests report coverage + run: | + cd /opt/monai + nvidia-smi + export CUDA_VISIBLE_DEVICES=$(python -m tests.utils) + echo $CUDA_VISIBLE_DEVICES + python -c "import torch; print(torch.__version__); print('{} of GPUs available'.format(torch.cuda.device_count()))" + python -c 'import torch; print(torch.rand(5,3, device=torch.device("cuda:0")))' + ngc --version + ./runtests.sh --coverage --pytype + coverage xml + - name: Upload coverage + uses: codecov/codecov-action@v1 + with: + fail_ci_if_error: false + file: ./coverage.xml diff --git a/testbed/Project-MONAI__MONAI/.github/workflows/format.yml b/testbed/Project-MONAI__MONAI/.github/workflows/format.yml new file mode 100644 index 0000000000000000000000000000000000000000..10ac5aae52461f883256e81c8054ad678e5faebe --- /dev/null +++ b/testbed/Project-MONAI__MONAI/.github/workflows/format.yml @@ -0,0 +1,26 @@ +name: chatops + +# currently dispatches /black command to project-monai/monai-code-formatter +on: + issue_comment: + types: [created, edited] +jobs: + dispatch_command: + runs-on: ubuntu-latest + steps: + - name: dispatch + uses: peter-evans/slash-command-dispatch@v1.1.3 + with: + token: ${{ secrets.PR_MAINTAIN }} + reaction-token: ${{ secrets.GITHUB_TOKEN }} + reactions: false + config: > + [ + { + "command": "black", + "permission": "none", + "issue_type": "pull-request", + "allow_edits": true, + "repository": "project-monai/monai-code-formatter" + } + ] diff --git a/testbed/Project-MONAI__MONAI/docs/images/favicon.ico b/testbed/Project-MONAI__MONAI/docs/images/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..dd19d06d64b9677190d8b04e6f6a7020961bc502 Binary files /dev/null and b/testbed/Project-MONAI__MONAI/docs/images/favicon.ico differ diff --git a/testbed/Project-MONAI__MONAI/tests/test_normalize_intensity.py b/testbed/Project-MONAI__MONAI/tests/test_normalize_intensity.py new file mode 100644 index 0000000000000000000000000000000000000000..0947734601286c96993d785f86c33f6d17cba269 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_normalize_intensity.py @@ -0,0 +1,51 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +from parameterized import parameterized + +from monai.transforms import NormalizeIntensity +from tests.utils import NumpyImageTestCase2D + +TEST_CASE_1 = [{"nonzero": True}, np.array([0.0, 3.0, 0.0, 4.0]), np.array([0.0, -1.0, 0.0, 1.0])] + +TEST_CASE_2 = [ + {"subtrahend": np.array([3.5, 3.5, 3.5, 3.5]), "divisor": np.array([0.5, 0.5, 0.5, 0.5]), "nonzero": True}, + np.array([0.0, 3.0, 0.0, 4.0]), + np.array([0.0, -1.0, 0.0, 1.0]), +] + +TEST_CASE_3 = [{"nonzero": True}, np.array([0.0, 0.0, 0.0, 0.0]), np.array([0.0, 0.0, 0.0, 0.0])] + + +class TestNormalizeIntensity(NumpyImageTestCase2D): + def test_default(self): + normalizer = NormalizeIntensity() + normalized = normalizer(self.imt) + expected = (self.imt - np.mean(self.imt)) / np.std(self.imt) + np.testing.assert_allclose(normalized, expected, rtol=1e-6) + + @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3]) + def test_nonzero(self, input_param, input_data, expected_data): + normalizer = NormalizeIntensity(**input_param) + np.testing.assert_allclose(expected_data, normalizer(input_data)) + + def test_channel_wise(self): + normalizer = NormalizeIntensity(nonzero=True, channel_wise=True) + input_data = np.array([[0.0, 3.0, 0.0, 4.0], [0.0, 4.0, 0.0, 5.0]]) + expected = np.array([[0.0, -1.0, 0.0, 1.0], [0.0, -1.0, 0.0, 1.0]]) + np.testing.assert_allclose(expected, normalizer(input_data)) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_parallel_execution.py b/testbed/Project-MONAI__MONAI/tests/test_parallel_execution.py new file mode 100644 index 0000000000000000000000000000000000000000..e6abcc641c67a531d1d8b3b467251e65f051aff1 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_parallel_execution.py @@ -0,0 +1,58 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest +import warnings + +import torch + +from monai.engines import create_multigpu_supervised_trainer +from tests.utils import expect_failure_if_no_gpu + + +def fake_loss(y_pred, y): + return (y_pred[0] + y).sum() + + +def fake_data_stream(): + while True: + yield torch.rand((10, 1, 64, 64)), torch.rand((10, 1, 64, 64)) + + +class TestParallelExecution(unittest.TestCase): + """ + Tests single GPU, multi GPU, and CPU execution with the Ignite supervised trainer. + """ + + @expect_failure_if_no_gpu + def test_single_gpu(self): + net = torch.nn.Conv2d(1, 1, 3, padding=1) + opt = torch.optim.Adam(net.parameters(), 1e-3) + trainer = create_multigpu_supervised_trainer(net, opt, fake_loss, [torch.device("cuda:0")]) + trainer.run(fake_data_stream(), 2, 2) + + @expect_failure_if_no_gpu + def test_multi_gpu(self): + net = torch.nn.Conv2d(1, 1, 3, padding=1) + opt = torch.optim.Adam(net.parameters(), 1e-3) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") # ignore warnings about imbalanced GPU memory + + trainer = create_multigpu_supervised_trainer(net, opt, fake_loss, None) + + trainer.run(fake_data_stream(), 2, 2) + + def test_cpu(self): + net = torch.nn.Conv2d(1, 1, 3, padding=1) + opt = torch.optim.Adam(net.parameters(), 1e-3) + trainer = create_multigpu_supervised_trainer(net, opt, fake_loss, []) + trainer.run(fake_data_stream(), 2, 2) diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_affine.py b/testbed/Project-MONAI__MONAI/tests/test_rand_affine.py new file mode 100644 index 0000000000000000000000000000000000000000..3d4a3c94634670960e596ff0d5299abc5e293fca --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_affine.py @@ -0,0 +1,85 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +import torch +from parameterized import parameterized + +from monai.transforms import RandAffine + +TEST_CASES = [ + [ + dict(as_tensor_output=False, device=None), + {"img": torch.arange(27).reshape((3, 3, 3))}, + np.arange(27).reshape((3, 3, 3)), + ], + [ + dict(as_tensor_output=False, device=None, spatial_size=-1), + {"img": torch.arange(27).reshape((3, 3, 3))}, + np.arange(27).reshape((3, 3, 3)), + ], + [ + dict(as_tensor_output=False, device=None), + {"img": torch.arange(27).reshape((3, 3, 3)), "spatial_size": (2, 2)}, + np.array([[[2.0, 3.0], [5.0, 6.0]], [[11.0, 12.0], [14.0, 15.0]], [[20.0, 21.0], [23.0, 24.0]]]), + ], + [ + dict(as_tensor_output=True, device=None), + {"img": torch.ones((1, 3, 3, 3)), "spatial_size": (2, 2, 2)}, + torch.ones((1, 2, 2, 2)), + ], + [ + dict( + prob=0.9, + rotate_range=(np.pi / 2,), + shear_range=[1, 2], + translate_range=[2, 1], + as_tensor_output=True, + padding_mode="zeros", + spatial_size=(2, 2, 2), + device=None, + ), + {"img": torch.ones((1, 3, 3, 3)), "mode": "bilinear"}, + torch.tensor([[[[0.3658, 1.0000], [1.0000, 1.0000]], [[1.0000, 1.0000], [1.0000, 0.9333]]]]), + ], + [ + dict( + prob=0.9, + rotate_range=(np.pi / 2,), + shear_range=[1, 2], + translate_range=[2, 1], + scale_range=[0.1, 0.2], + as_tensor_output=True, + device=None, + ), + {"img": torch.arange(64).reshape((1, 8, 8)), "spatial_size": (3, 3)}, + torch.tensor([[[18.7362, 15.5820, 12.4278], [27.3988, 24.2446, 21.0904], [36.0614, 32.9072, 29.7530]]]), + ], +] + + +class TestRandAffine(unittest.TestCase): + @parameterized.expand(TEST_CASES) + def test_rand_affine(self, input_param, input_data, expected_val): + g = RandAffine(**input_param) + g.set_random_state(123) + result = g(**input_data) + self.assertEqual(torch.is_tensor(result), torch.is_tensor(expected_val)) + if torch.is_tensor(result): + np.testing.assert_allclose(result.cpu().numpy(), expected_val.cpu().numpy(), rtol=1e-4, atol=1e-4) + else: + np.testing.assert_allclose(result, expected_val, rtol=1e-4, atol=1e-4) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_crop_by_pos_neg_label.py b/testbed/Project-MONAI__MONAI/tests/test_rand_crop_by_pos_neg_label.py new file mode 100644 index 0000000000000000000000000000000000000000..5b85f212616af4b3c7b70f54e5339f27539db5ef --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_crop_by_pos_neg_label.py @@ -0,0 +1,78 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +from parameterized import parameterized + +from monai.transforms import RandCropByPosNegLabel + +TEST_CASE_0 = [ + { + "label": np.random.randint(0, 2, size=[3, 3, 3, 3]), + "spatial_size": [2, 2, -1], + "pos": 1, + "neg": 1, + "num_samples": 2, + "image": np.random.randint(0, 2, size=[3, 3, 3, 3]), + "image_threshold": 0, + }, + {"img": np.random.randint(0, 2, size=[3, 3, 3, 3])}, + list, + (3, 2, 2, 3), +] + +TEST_CASE_1 = [ + { + "label": np.random.randint(0, 2, size=[3, 3, 3, 3]), + "spatial_size": [2, 2, 2], + "pos": 1, + "neg": 1, + "num_samples": 2, + "image": np.random.randint(0, 2, size=[3, 3, 3, 3]), + "image_threshold": 0, + }, + {"img": np.random.randint(0, 2, size=[3, 3, 3, 3])}, + list, + (3, 2, 2, 2), +] + +TEST_CASE_2 = [ + { + "label": None, + "spatial_size": [2, 2, 2], + "pos": 1, + "neg": 1, + "num_samples": 2, + "image": np.random.randint(0, 2, size=[3, 3, 3, 3]), + "image_threshold": 0, + }, + { + "img": np.random.randint(0, 2, size=[3, 3, 3, 3]), + "label": np.random.randint(0, 2, size=[3, 3, 3, 3]), + "image": np.random.randint(0, 2, size=[3, 3, 3, 3]), + }, + list, + (3, 2, 2, 2), +] + + +class TestRandCropByPosNegLabel(unittest.TestCase): + @parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2]) + def test_type_shape(self, input_param, input_data, expected_type, expected_shape): + result = RandCropByPosNegLabel(**input_param)(**input_data) + self.assertIsInstance(result, expected_type) + self.assertTupleEqual(result[0].shape, expected_shape) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_crop_by_pos_neg_labeld.py b/testbed/Project-MONAI__MONAI/tests/test_rand_crop_by_pos_neg_labeld.py new file mode 100644 index 0000000000000000000000000000000000000000..a79eab2ae98292bcf94f211ecc3ce89e20cd8ec0 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_crop_by_pos_neg_labeld.py @@ -0,0 +1,97 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +from parameterized import parameterized + +from monai.transforms import RandCropByPosNegLabeld + +TEST_CASE_0 = [ + { + "keys": ["image", "extral", "label"], + "label_key": "label", + "spatial_size": [-1, 2, 2], + "pos": 1, + "neg": 1, + "num_samples": 2, + "image_key": None, + "image_threshold": 0, + }, + { + "image": np.random.randint(0, 2, size=[3, 3, 3, 3]), + "extral": np.random.randint(0, 2, size=[3, 3, 3, 3]), + "label": np.random.randint(0, 2, size=[3, 3, 3, 3]), + "affine": np.eye(3), + "shape": "CHWD", + }, + list, + (3, 3, 2, 2), +] + +TEST_CASE_1 = [ + { + "keys": ["image", "extral", "label"], + "label_key": "label", + "spatial_size": [2, 2, 2], + "pos": 1, + "neg": 1, + "num_samples": 2, + "image_key": None, + "image_threshold": 0, + }, + { + "image": np.random.randint(0, 2, size=[3, 3, 3, 3]), + "extral": np.random.randint(0, 2, size=[3, 3, 3, 3]), + "label": np.random.randint(0, 2, size=[3, 3, 3, 3]), + "affine": np.eye(3), + "shape": "CHWD", + }, + list, + (3, 2, 2, 2), +] + +TEST_CASE_2 = [ + { + "keys": ["image", "extral", "label"], + "label_key": "label", + "spatial_size": [2, 2, 2], + "pos": 1, + "neg": 1, + "num_samples": 2, + "image_key": None, + "image_threshold": 0, + }, + { + "image": np.zeros([3, 3, 3, 3]) - 1, + "extral": np.zeros([3, 3, 3, 3]), + "label": np.ones([3, 3, 3, 3]), + "affine": np.eye(3), + "shape": "CHWD", + }, + list, + (3, 2, 2, 2), +] + + +class TestRandCropByPosNegLabeld(unittest.TestCase): + @parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2]) + def test_type_shape(self, input_param, input_data, expected_type, expected_shape): + result = RandCropByPosNegLabeld(**input_param)(input_data) + self.assertIsInstance(result, expected_type) + self.assertTupleEqual(result[0]["image"].shape, expected_shape) + self.assertTupleEqual(result[0]["extral"].shape, expected_shape) + self.assertTupleEqual(result[0]["label"].shape, expected_shape) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_elastic_2d.py b/testbed/Project-MONAI__MONAI/tests/test_rand_elastic_2d.py new file mode 100644 index 0000000000000000000000000000000000000000..fc4eac33eb5f3775cb4d7997d824c9cfbf8a6a67 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_elastic_2d.py @@ -0,0 +1,106 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +import torch +from parameterized import parameterized + +from monai.transforms import Rand2DElastic + +TEST_CASES = [ + [ + {"spacing": (0.3, 0.3), "magnitude_range": (1.0, 2.0), "prob": 0.0, "as_tensor_output": False, "device": None}, + {"img": torch.ones((3, 3, 3)), "spatial_size": (2, 2)}, + np.ones((3, 2, 2)), + ], + [ + {"spacing": (0.3, 0.3), "magnitude_range": (1.0, 2.0), "prob": 0.0, "as_tensor_output": False, "device": None}, + {"img": torch.arange(27).reshape((3, 3, 3))}, + np.arange(27).reshape((3, 3, 3)), + ], + [ + { + "spacing": (0.3, 0.3), + "magnitude_range": (1.0, 2.0), + "prob": 0.9, + "as_tensor_output": False, + "device": None, + "padding_mode": "zeros", + }, + {"img": torch.ones((3, 3, 3)), "spatial_size": (2, 2), "mode": "bilinear"}, + np.array( + [ + [[0.45531988, 0.0], [0.0, 0.71558857]], + [[0.45531988, 0.0], [0.0, 0.71558857]], + [[0.45531988, 0.0], [0.0, 0.71558857]], + ] + ), + ], + [ + { + "spacing": (1.0, 1.0), + "magnitude_range": (1.0, 1.0), + "scale_range": [1.2, 2.2], + "prob": 0.9, + "padding_mode": "border", + "as_tensor_output": True, + "device": None, + "spatial_size": (2, 2), + }, + {"img": torch.arange(27).reshape((3, 3, 3))}, + torch.tensor( + [ + [[3.0793, 2.6141], [4.0568, 5.9978]], + [[12.0793, 11.6141], [13.0568, 14.9978]], + [[21.0793, 20.6141], [22.0568, 23.9978]], + ] + ), + ], + [ + { + "spacing": (0.3, 0.3), + "magnitude_range": (0.1, 0.2), + "translate_range": [-0.01, 0.01], + "scale_range": [0.01, 0.02], + "prob": 0.9, + "as_tensor_output": False, + "device": None, + "spatial_size": (2, 2), + }, + {"img": torch.arange(27).reshape((3, 3, 3))}, + np.array( + [ + [[1.3584113, 1.9251312], [5.626623, 6.642721]], + [[10.358411, 10.925131], [14.626623, 15.642721]], + [[19.358412, 19.92513], [23.626623, 24.642721]], + ] + ), + ], +] + + +class TestRand2DElastic(unittest.TestCase): + @parameterized.expand(TEST_CASES) + def test_rand_2d_elastic(self, input_param, input_data, expected_val): + g = Rand2DElastic(**input_param) + g.set_random_state(123) + result = g(**input_data) + self.assertEqual(torch.is_tensor(result), torch.is_tensor(expected_val)) + if torch.is_tensor(result): + np.testing.assert_allclose(result.cpu().numpy(), expected_val.cpu().numpy(), rtol=1e-4, atol=1e-4) + else: + np.testing.assert_allclose(result, expected_val, rtol=1e-4, atol=1e-4) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_elastic_3d.py b/testbed/Project-MONAI__MONAI/tests/test_rand_elastic_3d.py new file mode 100644 index 0000000000000000000000000000000000000000..30aaf802de5cbed9e605da261bceced16acaaff2 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_elastic_3d.py @@ -0,0 +1,85 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +import torch +from parameterized import parameterized + +from monai.transforms import Rand3DElastic + +TEST_CASES = [ + [ + { + "magnitude_range": (0.3, 2.3), + "sigma_range": (1.0, 20.0), + "prob": 0.0, + "as_tensor_output": False, + "device": None, + "spatial_size": -1, + }, + {"img": torch.arange(72).reshape((2, 3, 3, 4))}, + np.arange(72).reshape((2, 3, 3, 4)), + ], + [ + { + "magnitude_range": (0.3, 2.3), + "sigma_range": (1.0, 20.0), + "prob": 0.0, + "as_tensor_output": False, + "device": None, + }, + {"img": torch.ones((2, 3, 3, 3)), "spatial_size": (2, 2, 2)}, + np.ones((2, 2, 2, 2)), + ], + [ + { + "magnitude_range": (0.3, 0.3), + "sigma_range": (1.0, 2.0), + "prob": 0.9, + "as_tensor_output": False, + "device": None, + }, + {"img": torch.arange(27).reshape((1, 3, 3, 3)), "spatial_size": (2, 2, 2)}, + np.array([[[[6.492354, 7.5022864], [9.519528, 10.524366]], [[15.51277, 16.525297], [18.533852, 19.539217]]]]), + ], + [ + { + "magnitude_range": (0.3, 0.3), + "sigma_range": (1.0, 2.0), + "prob": 0.9, + "rotate_range": [1, 1, 1], + "as_tensor_output": False, + "device": None, + "spatial_size": (2, 2, 2), + }, + {"img": torch.arange(27).reshape((1, 3, 3, 3)), "mode": "bilinear"}, + np.array([[[[5.005563, 9.463698], [9.289501, 13.741863]], [[12.320587, 16.779654], [16.597677, 21.049414]]]]), + ], +] + + +class TestRand3DElastic(unittest.TestCase): + @parameterized.expand(TEST_CASES) + def test_rand_3d_elastic(self, input_param, input_data, expected_val): + g = Rand3DElastic(**input_param) + g.set_random_state(123) + result = g(**input_data) + self.assertEqual(torch.is_tensor(result), torch.is_tensor(expected_val)) + if torch.is_tensor(result): + np.testing.assert_allclose(result.cpu().numpy(), expected_val.cpu().numpy(), rtol=1e-4, atol=1e-4) + else: + np.testing.assert_allclose(result, expected_val, rtol=1e-4, atol=1e-4) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_flipd.py b/testbed/Project-MONAI__MONAI/tests/test_rand_flipd.py new file mode 100644 index 0000000000000000000000000000000000000000..5e55f629db531bdce3c8b9f5792c91d44bfb2a18 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_flipd.py @@ -0,0 +1,36 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +from parameterized import parameterized + +from monai.transforms import RandFlipd +from tests.utils import NumpyImageTestCase2D + +VALID_CASES = [("no_axis", None), ("one_axis", 1), ("many_axis", [0, 1])] + + +class TestRandFlipd(NumpyImageTestCase2D): + @parameterized.expand(VALID_CASES) + def test_correct_results(self, _, spatial_axis): + flip = RandFlipd(keys="img", prob=1.0, spatial_axis=spatial_axis) + res = flip({"img": self.imt[0]}) + expected = list() + for channel in self.imt[0]: + expected.append(np.flip(channel, spatial_axis)) + expected = np.stack(expected) + self.assertTrue(np.allclose(expected, res["img"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_gaussian_noised.py b/testbed/Project-MONAI__MONAI/tests/test_rand_gaussian_noised.py new file mode 100644 index 0000000000000000000000000000000000000000..c72dd2b29b314e5227ead47a87817e0642fe0b7d --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_gaussian_noised.py @@ -0,0 +1,35 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +from parameterized import parameterized + +from monai.transforms import RandGaussianNoised +from tests.utils import NumpyImageTestCase2D + + +class TestRandGaussianNoised(NumpyImageTestCase2D): + @parameterized.expand([("test_zero_mean", ["img"], 0, 0.1), ("test_non_zero_mean", ["img"], 1, 0.5)]) + def test_correct_results(self, _, keys, mean, std): + seed = 0 + gaussian_fn = RandGaussianNoised(keys=keys, prob=1.0, mean=mean, std=std) + gaussian_fn.set_random_state(seed) + noised = gaussian_fn({"img": self.imt}) + np.random.seed(seed) + np.random.random() + expected = self.imt + np.random.normal(mean, np.random.uniform(0, std), size=self.imt.shape) + np.testing.assert_allclose(expected, noised["img"], atol=1e-5, rtol=1e-5) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_gaussian_smooth.py b/testbed/Project-MONAI__MONAI/tests/test_rand_gaussian_smooth.py new file mode 100644 index 0000000000000000000000000000000000000000..672ce4ccb0bf0ab1f67f80818c7fe3fd3d8cba31 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_gaussian_smooth.py @@ -0,0 +1,52 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +from parameterized import parameterized + +from monai.transforms import RandGaussianSmooth + +TEST_CASE_1 = [ + {"sigma_x": (0.5, 1.5), "prob": 1.0}, + np.array([[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4, 4], [5, 5, 5], [6, 6, 6]]]), + np.array( + [ + [[0.7291442, 0.9260285, 0.7291442], [1.1054044, 1.4038869, 1.1054044], [1.0672514, 1.3554319, 1.0672514]], + [[2.076441, 2.6371238, 2.076441], [2.763511, 3.5097172, 2.763511], [2.4145484, 3.0665274, 2.4145484]], + ] + ), +] + +TEST_CASE_2 = [ + {"sigma_x": (0.5, 1.5), "sigma_y": (0.5, 1.0), "prob": 1.0}, + np.array([[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4, 4], [5, 5, 5], [6, 6, 6]]]), + np.array( + [ + [[0.78625894, 1.0031066, 0.78625894], [1.1919919, 1.5207394, 1.191992], [1.1508504, 1.4682512, 1.1508505]], + [[2.239091, 2.8566248, 2.239091], [2.97998, 3.8018486, 2.97998], [2.6036828, 3.3217697, 2.6036828]], + ] + ), +] + + +class TestRandGaussianSmooth(unittest.TestCase): + @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) + def test_value(self, argments, image, expected_data): + converter = RandGaussianSmooth(**argments) + converter.set_random_state(seed=0) + result = converter(image) + np.testing.assert_allclose(result, expected_data, rtol=1e-4) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_rotate.py b/testbed/Project-MONAI__MONAI/tests/test_rand_rotate.py new file mode 100644 index 0000000000000000000000000000000000000000..921764f3cf835dd4a4a6276aec05c40cc138c794 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_rotate.py @@ -0,0 +1,84 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +import scipy.ndimage +from parameterized import parameterized + +from monai.transforms import RandRotate +from tests.utils import NumpyImageTestCase2D, NumpyImageTestCase3D + + +class TestRandRotate2D(NumpyImageTestCase2D): + @parameterized.expand( + [ + (90, True, "bilinear", "border", False), + (45, True, "nearest", "border", False), + (180, False, "nearest", "zeros", True), + ((-45, 0), False, "nearest", "zeros", True), + ] + ) + def test_correct_results(self, degrees, keep_size, mode, padding_mode, align_corners): + rotate_fn = RandRotate( + range_x=degrees, + prob=1.0, + keep_size=keep_size, + mode=mode, + padding_mode=padding_mode, + align_corners=align_corners, + ) + rotate_fn.set_random_state(243) + rotated = rotate_fn(self.imt[0]) + + _order = 0 if mode == "nearest" else 1 + if mode == "border": + _mode = "nearest" + elif mode == "reflection": + _mode = "reflect" + else: + _mode = "constant" + angle = rotate_fn.x + expected = scipy.ndimage.rotate( + self.imt[0, 0], -angle, (0, 1), not keep_size, order=_order, mode=_mode, prefilter=False + ) + expected = np.stack(expected).astype(np.float32) + np.testing.assert_allclose(expected, rotated[0]) + + +class TestRandRotate3D(NumpyImageTestCase3D): + @parameterized.expand( + [ + (90, -30, (0.0, 180), False, "bilinear", "border", False, (1, 87, 104, 109)), + (45, (-20, 40), (20, 30), False, "nearest", "border", True, (1, 89, 105, 104)), + (0.0, (360, 370), (-1, 1), True, "nearest", "zeros", True, (1, 48, 64, 80)), + ((-45, 0), 0, 0, False, "nearest", "zeros", False, (1, 48, 77, 90)), + ] + ) + def test_correct_results(self, x, y, z, keep_size, mode, padding_mode, align_corners, expected): + rotate_fn = RandRotate( + range_x=x, + range_y=y, + range_z=z, + prob=1.0, + keep_size=keep_size, + mode=mode, + padding_mode=padding_mode, + align_corners=align_corners, + ) + rotate_fn.set_random_state(243) + rotated = rotate_fn(self.imt[0]) + np.testing.assert_allclose(rotated.shape, expected) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_rotate90.py b/testbed/Project-MONAI__MONAI/tests/test_rand_rotate90.py new file mode 100644 index 0000000000000000000000000000000000000000..20e171f9e8a93db54312c7abeaf0fe05e38d1b6e --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_rotate90.py @@ -0,0 +1,63 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np + +from monai.transforms import RandRotate90 +from tests.utils import NumpyImageTestCase2D + + +class TestRandRotate90(NumpyImageTestCase2D): + def test_default(self): + rotate = RandRotate90() + rotate.set_random_state(123) + rotated = rotate(self.imt[0]) + expected = list() + for channel in self.imt[0]: + expected.append(np.rot90(channel, 0, (0, 1))) + expected = np.stack(expected) + self.assertTrue(np.allclose(rotated, expected)) + + def test_k(self): + rotate = RandRotate90(max_k=2) + rotate.set_random_state(234) + rotated = rotate(self.imt[0]) + expected = list() + for channel in self.imt[0]: + expected.append(np.rot90(channel, 0, (0, 1))) + expected = np.stack(expected) + self.assertTrue(np.allclose(rotated, expected)) + + def test_spatial_axes(self): + rotate = RandRotate90(spatial_axes=(0, 1)) + rotate.set_random_state(234) + rotated = rotate(self.imt[0]) + expected = list() + for channel in self.imt[0]: + expected.append(np.rot90(channel, 0, (0, 1))) + expected = np.stack(expected) + self.assertTrue(np.allclose(rotated, expected)) + + def test_prob_k_spatial_axes(self): + rotate = RandRotate90(prob=1.0, max_k=2, spatial_axes=(0, 1)) + rotate.set_random_state(234) + rotated = rotate(self.imt[0]) + expected = list() + for channel in self.imt[0]: + expected.append(np.rot90(channel, 1, (0, 1))) + expected = np.stack(expected) + self.assertTrue(np.allclose(rotated, expected)) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_rotate90d.py b/testbed/Project-MONAI__MONAI/tests/test_rand_rotate90d.py new file mode 100644 index 0000000000000000000000000000000000000000..cd55ff5e3a47c5b882b4c1d72dc30b416487afe0 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_rotate90d.py @@ -0,0 +1,73 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np + +from monai.transforms import RandRotate90d +from tests.utils import NumpyImageTestCase2D + + +class TestRandRotate90d(NumpyImageTestCase2D): + def test_default(self): + key = None + rotate = RandRotate90d(keys=key) + rotate.set_random_state(123) + rotated = rotate({key: self.imt[0]}) + expected = list() + for channel in self.imt[0]: + expected.append(np.rot90(channel, 0, (0, 1))) + expected = np.stack(expected) + self.assertTrue(np.allclose(rotated[key], expected)) + + def test_k(self): + key = "test" + rotate = RandRotate90d(keys=key, max_k=2) + rotate.set_random_state(234) + rotated = rotate({key: self.imt[0]}) + expected = list() + for channel in self.imt[0]: + expected.append(np.rot90(channel, 0, (0, 1))) + expected = np.stack(expected) + self.assertTrue(np.allclose(rotated[key], expected)) + + def test_spatial_axes(self): + key = "test" + rotate = RandRotate90d(keys=key, spatial_axes=(0, 1)) + rotate.set_random_state(234) + rotated = rotate({key: self.imt[0]}) + expected = list() + for channel in self.imt[0]: + expected.append(np.rot90(channel, 0, (0, 1))) + expected = np.stack(expected) + self.assertTrue(np.allclose(rotated[key], expected)) + + def test_prob_k_spatial_axes(self): + key = "test" + rotate = RandRotate90d(keys=key, prob=1.0, max_k=2, spatial_axes=(0, 1)) + rotate.set_random_state(234) + rotated = rotate({key: self.imt[0]}) + expected = list() + for channel in self.imt[0]: + expected.append(np.rot90(channel, 1, (0, 1))) + expected = np.stack(expected) + self.assertTrue(np.allclose(rotated[key], expected)) + + def test_no_key(self): + key = "unknown" + rotate = RandRotate90d(keys=key, prob=1.0, max_k=2, spatial_axes=(0, 1)) + with self.assertRaisesRegex(KeyError, ""): + rotated = rotate({"test": self.imt[0]}) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_rotated.py b/testbed/Project-MONAI__MONAI/tests/test_rand_rotated.py new file mode 100644 index 0000000000000000000000000000000000000000..a68c98f384c17d1d876d9bdb60571cb7c41ec96a --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_rotated.py @@ -0,0 +1,91 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +import scipy.ndimage +from parameterized import parameterized + +from monai.transforms import RandRotated +from monai.utils import GridSampleMode, GridSamplePadMode +from tests.utils import NumpyImageTestCase2D, NumpyImageTestCase3D + + +class TestRandRotated2D(NumpyImageTestCase2D): + @parameterized.expand( + [ + (90, True, "bilinear", "border", False), + (45, True, "nearest", "border", False), + (180, False, "nearest", "zeros", True), + ((-45, 0), False, "nearest", "zeros", True), + ] + ) + def test_correct_results(self, degrees, keep_size, mode, padding_mode, align_corners): + rotate_fn = RandRotated( + "img", + range_x=degrees, + prob=1.0, + keep_size=keep_size, + mode=mode, + padding_mode=padding_mode, + align_corners=align_corners, + ) + rotate_fn.set_random_state(243) + rotated = rotate_fn({"img": self.imt[0], "seg": self.segn[0]}) + + _order = 0 if mode == "nearest" else 1 + if padding_mode == "border": + _mode = "nearest" + elif padding_mode == "reflection": + _mode = "reflect" + else: + _mode = "constant" + angle = rotate_fn.x + expected = scipy.ndimage.rotate( + self.imt[0, 0], -angle, (0, 1), not keep_size, order=_order, mode=_mode, prefilter=False + ) + expected = np.stack(expected).astype(np.float32) + self.assertTrue(np.allclose(expected, rotated["img"][0])) + + +class TestRandRotated3D(NumpyImageTestCase3D): + @parameterized.expand( + [ + (90, -30, (0.0, 180), False, "bilinear", "border", False, (1, 87, 104, 109)), + (90, -30, (0.0, 180), False, GridSampleMode.NEAREST, GridSamplePadMode.BORDER, False, (1, 87, 104, 109)), + (45, (-20, 40), (20, 30), False, "nearest", "border", True, (1, 89, 105, 104)), + (45, (-20, 40), (20, 30), False, GridSampleMode.NEAREST, GridSamplePadMode.BORDER, True, (1, 89, 105, 104)), + (0.0, (360, 370), (-1, 1), True, "nearest", "zeros", True, (1, 48, 64, 80)), + (0.0, (360, 370), (-1, 1), True, GridSampleMode.NEAREST, GridSamplePadMode.ZEROS, True, (1, 48, 64, 80)), + ((-45, 0), 0, 0, False, "nearest", "zeros", False, (1, 48, 77, 90)), + ((-45, 0), 0, 0, False, GridSampleMode.NEAREST, GridSamplePadMode.ZEROS, False, (1, 48, 77, 90)), + ] + ) + def test_correct_shapes(self, x, y, z, keep_size, mode, padding_mode, align_corners, expected): + rotate_fn = RandRotated( + "img", + range_x=x, + range_y=y, + range_z=z, + prob=1.0, + keep_size=keep_size, + mode=mode, + padding_mode=padding_mode, + align_corners=align_corners, + ) + rotate_fn.set_random_state(243) + rotated = rotate_fn({"img": self.imt[0], "seg": self.segn[0]}) + np.testing.assert_allclose(rotated["img"].shape, expected) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_shift_intensity.py b/testbed/Project-MONAI__MONAI/tests/test_rand_shift_intensity.py new file mode 100644 index 0000000000000000000000000000000000000000..a8beb9b1e38e26a83567f93cc34d98079c459506 --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_shift_intensity.py @@ -0,0 +1,31 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np + +from monai.transforms import RandShiftIntensity +from tests.utils import NumpyImageTestCase2D + + +class TestRandShiftIntensity(NumpyImageTestCase2D): + def test_value(self): + shifter = RandShiftIntensity(offsets=1.0, prob=1.0) + shifter.set_random_state(seed=0) + result = shifter(self.imt) + np.random.seed(0) + expected = self.imt + np.random.uniform(low=-1.0, high=1.0) + np.testing.assert_allclose(result, expected) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_shift_intensityd.py b/testbed/Project-MONAI__MONAI/tests/test_rand_shift_intensityd.py new file mode 100644 index 0000000000000000000000000000000000000000..2a4c1952351aa3e86e756ace23f2d45fa1bc98ac --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_shift_intensityd.py @@ -0,0 +1,32 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np + +from monai.transforms import RandShiftIntensityd +from tests.utils import NumpyImageTestCase2D + + +class TestRandShiftIntensityd(NumpyImageTestCase2D): + def test_value(self): + key = "img" + shifter = RandShiftIntensityd(keys=[key], offsets=1.0, prob=1.0) + shifter.set_random_state(seed=0) + result = shifter({key: self.imt}) + np.random.seed(0) + expected = self.imt + np.random.uniform(low=-1.0, high=1.0) + np.testing.assert_allclose(result[key], expected) + + +if __name__ == "__main__": + unittest.main() diff --git a/testbed/Project-MONAI__MONAI/tests/test_rand_spatial_crop_samplesd.py b/testbed/Project-MONAI__MONAI/tests/test_rand_spatial_crop_samplesd.py new file mode 100644 index 0000000000000000000000000000000000000000..51bf50f16a6422a3fbb53960058466f1b60aa54e --- /dev/null +++ b/testbed/Project-MONAI__MONAI/tests/test_rand_spatial_crop_samplesd.py @@ -0,0 +1,42 @@ +# Copyright 2020 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +from parameterized import parameterized + +from monai.transforms import RandSpatialCropSamplesd + +TEST_CASE_1 = [ + {"keys": ["img", "seg"], "num_samples": 4, "roi_size": [3, 3, 3], "random_center": True}, + {"img": np.random.randint(0, 2, size=[3, 3, 3, 3]), "seg": np.random.randint(0, 2, size=[3, 3, 3, 3])}, + (3, 3, 3, 3), +] + +TEST_CASE_2 = [ + {"keys": ["img", "seg"], "num_samples": 8, "roi_size": [3, 3, 3], "random_center": False}, + {"img": np.random.randint(0, 2, size=[3, 3, 3, 3]), "seg": np.random.randint(0, 2, size=[3, 3, 3, 3])}, + (3, 3, 3, 3), +] + + +class TestRandSpatialCropSamplesd(unittest.TestCase): + @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) + def test_shape(self, input_param, input_data, expected_shape): + result = RandSpatialCropSamplesd(**input_param)(input_data) + for item in result: + self.assertTupleEqual(item["img"].shape, expected_shape) + self.assertTupleEqual(item["seg"].shape, expected_shape) + + +if __name__ == "__main__": + unittest.main()