Stage Harbor release files 43501-44000
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/README.md +120 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/test_4bit.py +870 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/test_mixed_int8.py +1017 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/test_compressed_models.py +232 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/test_compressed_tensors.py +87 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/eetq_integration/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/eetq_integration/test_eetq.py +171 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fbgemm_fp8/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fbgemm_fp8/test_fbgemm_fp8.py +301 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/finegrained_fp8/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/finegrained_fp8/test_fp8.py +287 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fp_quant_integration/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fp_quant_integration/test_fp_quant.py +227 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/ggml/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/ggml/test_ggml.py +991 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/gptq/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/gptq/test_gptq.py +499 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/higgs/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/higgs/test_higgs.py +197 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/hqq/test_hqq.py +314 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/mxfp4/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/mxfp4/test_mxfp4.py +481 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quanto_integration/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quanto_integration/test_quanto.py +472 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quark_integration/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quark_integration/test_quark.py +153 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/spqr_integration/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/spqr_integration/test_spqr.py +246 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/torchao_integration/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/torchao_integration/test_torchao.py +592 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/vptq_integration/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/vptq_integration/test_vptq.py +194 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/modular/test_conversion_order.py +74 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_check_copies.py +454 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_check_docstrings.py +98 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_get_test_info.py +108 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_tests_fetcher.py +788 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/README.md +148 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/__init__.py +5 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/conftest.py +64 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/requirements.txt +2 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/run_ddp.py +52 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/run_glue_model_parallelism.py +540 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/tensorflow/requirements.txt +1 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/tensorflow/run_tf.py +104 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_multi_node_data_parallel.py +109 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_multi_node_model_parallel.py +122 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_single_node_gpu.py +95 -0
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/README.md
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Testing mixed int8 quantization
|
| 2 |
+
|
| 3 |
+

|
| 4 |
+
|
| 5 |
+
The following is the recipe on how to effectively debug `bitsandbytes` integration on Hugging Face `transformers`.
|
| 6 |
+
|
| 7 |
+
## Library requirements
|
| 8 |
+
|
| 9 |
+
+ `transformers>=4.22.0`
|
| 10 |
+
+ `accelerate>=0.12.0`
|
| 11 |
+
+ `bitsandbytes>=0.31.5`.
|
| 12 |
+
## Hardware requirements
|
| 13 |
+
|
| 14 |
+
The following instructions are tested with 2 NVIDIA-Tesla T4 GPUs. To run successfully `bitsandbytes` you would need a 8-bit core tensor supported GPU. Note that Turing, Ampere or newer architectures - e.g. T4, RTX20s RTX30s, A40-A100, A6000 should be supported.
|
| 15 |
+
|
| 16 |
+
## Virtual envs
|
| 17 |
+
|
| 18 |
+
```bash
|
| 19 |
+
conda create --name int8-testing python==3.8
|
| 20 |
+
pip install bitsandbytes>=0.31.5
|
| 21 |
+
pip install accelerate>=0.12.0
|
| 22 |
+
pip install transformers>=4.23.0
|
| 23 |
+
```
|
| 24 |
+
if `transformers>=4.23.0` is not released yet, then use:
|
| 25 |
+
```bash
|
| 26 |
+
pip install git+https://github.com/huggingface/transformers.git
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
## Troubleshooting
|
| 30 |
+
|
| 31 |
+
A list of common errors:
|
| 32 |
+
|
| 33 |
+
### Torch does not correctly do the operations on GPU
|
| 34 |
+
|
| 35 |
+
First check that:
|
| 36 |
+
|
| 37 |
+
```py
|
| 38 |
+
import torch
|
| 39 |
+
|
| 40 |
+
vec = torch.randn(1, 2, 3).to(0)
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
Works without any error. If not, install torch using `conda` like:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
conda create --name int8-testing python==3.8
|
| 47 |
+
conda install pytorch torchvision torchaudio cudatoolkit=11.6 -c pytorch -c conda-forge
|
| 48 |
+
pip install bitsandbytes>=0.31.5
|
| 49 |
+
pip install accelerate>=0.12.0
|
| 50 |
+
pip install transformers>=4.23.0
|
| 51 |
+
```
|
| 52 |
+
For the latest pytorch instructions please see [this](https://pytorch.org/get-started/locally/)
|
| 53 |
+
|
| 54 |
+
and the snippet above should work.
|
| 55 |
+
|
| 56 |
+
### ` bitsandbytes operations are not supported under CPU!`
|
| 57 |
+
|
| 58 |
+
This happens when some Linear weights are set to the CPU when using `accelerate`. Please check carefully `model.hf_device_map` and make sure that there is no `Linear` module that is assigned to CPU. It is fine to have the last module (usually the Lm_head) set on CPU.
|
| 59 |
+
|
| 60 |
+
### `To use the type as a Parameter, please correct the detach() semantics defined by __torch_dispatch__() implementation.`
|
| 61 |
+
|
| 62 |
+
Use the latest version of `accelerate` with a command such as: `pip install -U accelerate` and the problem should be solved.
|
| 63 |
+
|
| 64 |
+
### `Parameter has no attribute .CB`
|
| 65 |
+
|
| 66 |
+
Same solution as above.
|
| 67 |
+
|
| 68 |
+
### `RuntimeError: CUDA error: an illegal memory access was encountered ... consider passing CUDA_LAUNCH_BLOCKING=1`
|
| 69 |
+
|
| 70 |
+
Run your script by prepending `CUDA_LAUNCH_BLOCKING=1` and you should observe an error as described in the next section.
|
| 71 |
+
|
| 72 |
+
### `CUDA illegal memory error: an illegal memory access at line...`:
|
| 73 |
+
|
| 74 |
+
Check the CUDA versions with:
|
| 75 |
+
```bash
|
| 76 |
+
nvcc --version
|
| 77 |
+
```
|
| 78 |
+
and confirm it is the same version as the one detected by `bitsandbytes`. If not, run:
|
| 79 |
+
```bash
|
| 80 |
+
ls -l $CONDA_PREFIX/lib/libcudart.so
|
| 81 |
+
```
|
| 82 |
+
or
|
| 83 |
+
```bash
|
| 84 |
+
ls -l $LD_LIBRARY_PATH
|
| 85 |
+
```
|
| 86 |
+
Check if `libcudart.so` has a correct symlink that is set. Sometimes `nvcc` detects the correct CUDA version but `bitsandbytes` doesn't. You have to make sure that the symlink that is set for the file `libcudart.so` is redirected to the correct CUDA file.
|
| 87 |
+
|
| 88 |
+
Here is an example of a badly configured CUDA installation:
|
| 89 |
+
|
| 90 |
+
`nvcc --version` gives:
|
| 91 |
+
|
| 92 |
+

|
| 93 |
+
|
| 94 |
+
which means that the detected CUDA version is 11.3 but `bitsandbytes` outputs:
|
| 95 |
+
|
| 96 |
+

|
| 97 |
+
|
| 98 |
+
First check:
|
| 99 |
+
|
| 100 |
+
```bash
|
| 101 |
+
echo $LD_LIBRARY_PATH
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
If this contains multiple paths separated by `:`. Then you have to make sure that the correct CUDA version is set. By doing:
|
| 105 |
+
|
| 106 |
+
```bash
|
| 107 |
+
ls -l $path/libcudart.so
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
On each path (`$path`) separated by `:`.
|
| 111 |
+
If not, simply run
|
| 112 |
+
```bash
|
| 113 |
+
ls -l $LD_LIBRARY_PATH/libcudart.so
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
and you can see
|
| 117 |
+
|
| 118 |
+

|
| 119 |
+
|
| 120 |
+
If you see that the file is linked to the wrong CUDA version (here 10.2), find the correct location for `libcudart.so` (`find --name libcudart.so`) and replace the environment variable `LD_LIBRARY_PATH` with the one containing the correct `libcudart.so` file.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/test_4bit.py
ADDED
|
@@ -0,0 +1,870 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team Inc.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a clone of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import gc
|
| 15 |
+
import importlib.metadata
|
| 16 |
+
import tempfile
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import pytest
|
| 20 |
+
from packaging import version
|
| 21 |
+
|
| 22 |
+
from transformers import (
|
| 23 |
+
AutoConfig,
|
| 24 |
+
AutoModel,
|
| 25 |
+
AutoModelForCausalLM,
|
| 26 |
+
AutoModelForSeq2SeqLM,
|
| 27 |
+
AutoModelForSequenceClassification,
|
| 28 |
+
AutoTokenizer,
|
| 29 |
+
BitsAndBytesConfig,
|
| 30 |
+
pipeline,
|
| 31 |
+
set_seed,
|
| 32 |
+
)
|
| 33 |
+
from transformers.models.opt.modeling_opt import OPTAttention
|
| 34 |
+
from transformers.testing_utils import (
|
| 35 |
+
apply_skip_if_not_implemented,
|
| 36 |
+
backend_empty_cache,
|
| 37 |
+
backend_torch_accelerator_module,
|
| 38 |
+
is_bitsandbytes_available,
|
| 39 |
+
is_torch_available,
|
| 40 |
+
require_accelerate,
|
| 41 |
+
require_bitsandbytes,
|
| 42 |
+
require_torch,
|
| 43 |
+
require_torch_gpu_if_bnb_not_multi_backend_enabled,
|
| 44 |
+
require_torch_multi_accelerator,
|
| 45 |
+
slow,
|
| 46 |
+
torch_device,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_some_linear_layer(model):
|
| 51 |
+
if model.config.model_type == "gpt2":
|
| 52 |
+
return model.transformer.h[0].mlp.c_fc
|
| 53 |
+
elif model.config.model_type == "opt":
|
| 54 |
+
try:
|
| 55 |
+
return model.decoder.layers[0].fc1
|
| 56 |
+
except AttributeError:
|
| 57 |
+
# for AutoModelforCausalLM
|
| 58 |
+
return model.model.decoder.layers[0].fc1
|
| 59 |
+
elif model.config.model_type == "llama":
|
| 60 |
+
return model.model.layers[0].mlp.gate_proj
|
| 61 |
+
else:
|
| 62 |
+
return model.transformer.h[0].mlp.dense_4h_to_h
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
if is_torch_available():
|
| 66 |
+
import torch
|
| 67 |
+
import torch.nn as nn
|
| 68 |
+
|
| 69 |
+
class LoRALayer(nn.Module):
|
| 70 |
+
"""Wraps a linear layer with LoRA-like adapter - Used for testing purposes only"""
|
| 71 |
+
|
| 72 |
+
def __init__(self, module: nn.Module, rank: int):
|
| 73 |
+
super().__init__()
|
| 74 |
+
self.module = module
|
| 75 |
+
self.adapter = nn.Sequential(
|
| 76 |
+
nn.Linear(module.in_features, rank, bias=False),
|
| 77 |
+
nn.Linear(rank, module.out_features, bias=False),
|
| 78 |
+
)
|
| 79 |
+
small_std = (2.0 / (5 * min(module.in_features, module.out_features))) ** 0.5
|
| 80 |
+
nn.init.normal_(self.adapter[0].weight, std=small_std)
|
| 81 |
+
nn.init.zeros_(self.adapter[1].weight)
|
| 82 |
+
self.adapter.to(module.weight.device)
|
| 83 |
+
|
| 84 |
+
def forward(self, input, *args, **kwargs):
|
| 85 |
+
return self.module(input, *args, **kwargs) + self.adapter(input)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if is_bitsandbytes_available():
|
| 89 |
+
import bitsandbytes as bnb
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@require_bitsandbytes
|
| 93 |
+
@require_accelerate
|
| 94 |
+
@require_torch
|
| 95 |
+
@require_torch_gpu_if_bnb_not_multi_backend_enabled
|
| 96 |
+
@slow
|
| 97 |
+
class Base4bitTest(unittest.TestCase):
|
| 98 |
+
# We keep the constants inside the init function and model loading inside setUp function
|
| 99 |
+
|
| 100 |
+
# We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
|
| 101 |
+
# Therefore here we use only bloom-1b3 to test our module
|
| 102 |
+
model_name = "bigscience/bloom-1b7"
|
| 103 |
+
|
| 104 |
+
# Constant values
|
| 105 |
+
EXPECTED_RELATIVE_DIFFERENCE = (
|
| 106 |
+
2.109659552692574 # This was obtained on a RTX Titan so the number might slightly change
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
input_text = "Hello my name is"
|
| 110 |
+
EXPECTED_OUTPUTS = set()
|
| 111 |
+
EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I")
|
| 112 |
+
EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n")
|
| 113 |
+
EXPECTED_OUTPUTS.add("Hello my name is John Doe, I am a student at the University")
|
| 114 |
+
EXPECTED_OUTPUTS.add("Hello my name is John and I am 25 years old.")
|
| 115 |
+
EXPECTED_OUTPUTS.add("Hello my name is John and I am a student at the University of")
|
| 116 |
+
# Expected values on Intel XPU and NV A100
|
| 117 |
+
EXPECTED_OUTPUTS.add("Hello my name is Alina. I have been working as a professional")
|
| 118 |
+
MAX_NEW_TOKENS = 10
|
| 119 |
+
|
| 120 |
+
def setUp(self):
|
| 121 |
+
# Models and tokenizer
|
| 122 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@apply_skip_if_not_implemented
|
| 126 |
+
class Bnb4BitTest(Base4bitTest):
|
| 127 |
+
def setUp(self):
|
| 128 |
+
super().setUp()
|
| 129 |
+
|
| 130 |
+
# Models and tokenizer
|
| 131 |
+
self.model_fp16 = AutoModelForCausalLM.from_pretrained(
|
| 132 |
+
self.model_name, torch_dtype=torch.float16, device_map="auto"
|
| 133 |
+
)
|
| 134 |
+
self.model_4bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto")
|
| 135 |
+
|
| 136 |
+
def tearDown(self):
|
| 137 |
+
r"""
|
| 138 |
+
TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
|
| 139 |
+
avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
|
| 140 |
+
"""
|
| 141 |
+
del self.model_fp16
|
| 142 |
+
del self.model_4bit
|
| 143 |
+
|
| 144 |
+
gc.collect()
|
| 145 |
+
backend_empty_cache(torch_device)
|
| 146 |
+
|
| 147 |
+
def test_quantization_num_parameters(self):
|
| 148 |
+
r"""
|
| 149 |
+
Test if the number of returned parameters is correct
|
| 150 |
+
|
| 151 |
+
See: https://github.com/huggingface/transformers/issues/25978
|
| 152 |
+
"""
|
| 153 |
+
num_params_4bit = self.model_4bit.num_parameters()
|
| 154 |
+
num_params_fp16 = self.model_fp16.num_parameters()
|
| 155 |
+
|
| 156 |
+
self.assertEqual(num_params_4bit, num_params_fp16)
|
| 157 |
+
|
| 158 |
+
def test_quantization_config_json_serialization(self):
|
| 159 |
+
r"""
|
| 160 |
+
A simple test to check if the quantization config is correctly serialized and deserialized
|
| 161 |
+
"""
|
| 162 |
+
config = self.model_4bit.config
|
| 163 |
+
|
| 164 |
+
self.assertTrue(hasattr(config, "quantization_config"))
|
| 165 |
+
|
| 166 |
+
_ = config.to_dict()
|
| 167 |
+
_ = config.to_diff_dict()
|
| 168 |
+
|
| 169 |
+
_ = config.to_json_string()
|
| 170 |
+
|
| 171 |
+
def test_memory_footprint(self):
|
| 172 |
+
r"""
|
| 173 |
+
A simple test to check if the model conversion has been done correctly by checking on the
|
| 174 |
+
memory footprint of the converted model and the class type of the linear layers of the converted models
|
| 175 |
+
"""
|
| 176 |
+
from bitsandbytes.nn import Params4bit
|
| 177 |
+
|
| 178 |
+
mem_fp16 = self.model_fp16.get_memory_footprint()
|
| 179 |
+
mem_4bit = self.model_4bit.get_memory_footprint()
|
| 180 |
+
|
| 181 |
+
self.assertAlmostEqual(mem_fp16 / mem_4bit, self.EXPECTED_RELATIVE_DIFFERENCE, delta=1e-5)
|
| 182 |
+
linear = get_some_linear_layer(self.model_4bit)
|
| 183 |
+
self.assertTrue(linear.weight.__class__ == Params4bit)
|
| 184 |
+
|
| 185 |
+
def test_original_dtype(self):
|
| 186 |
+
r"""
|
| 187 |
+
A simple test to check if the model successfully stores the original dtype
|
| 188 |
+
"""
|
| 189 |
+
self.assertTrue(hasattr(self.model_4bit.config, "_pre_quantization_dtype"))
|
| 190 |
+
self.assertFalse(hasattr(self.model_fp16.config, "_pre_quantization_dtype"))
|
| 191 |
+
self.assertTrue(self.model_4bit.config._pre_quantization_dtype == torch.float16)
|
| 192 |
+
|
| 193 |
+
def test_linear_are_4bit(self):
|
| 194 |
+
r"""
|
| 195 |
+
A simple test to check if the model conversion has been done correctly by checking on the
|
| 196 |
+
memory footprint of the converted model and the class type of the linear layers of the converted models
|
| 197 |
+
"""
|
| 198 |
+
from transformers import T5PreTrainedModel
|
| 199 |
+
|
| 200 |
+
self.model_fp16.get_memory_footprint()
|
| 201 |
+
self.model_4bit.get_memory_footprint()
|
| 202 |
+
|
| 203 |
+
for name, module in self.model_4bit.named_modules():
|
| 204 |
+
if isinstance(module, torch.nn.Linear):
|
| 205 |
+
if name not in ["lm_head"] + T5PreTrainedModel._keep_in_fp32_modules:
|
| 206 |
+
# 4-bit parameters are packed in uint8 variables
|
| 207 |
+
self.assertTrue(module.weight.dtype == torch.uint8)
|
| 208 |
+
|
| 209 |
+
def test_rwkv_4bit(self):
|
| 210 |
+
r"""
|
| 211 |
+
A simple test to check if 4-bit RWKV inference works as expected.
|
| 212 |
+
"""
|
| 213 |
+
model_id = "RWKV/rwkv-4-169m-pile"
|
| 214 |
+
|
| 215 |
+
quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_use_double_quant=True)
|
| 216 |
+
|
| 217 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=quantization_config)
|
| 218 |
+
tok = AutoTokenizer.from_pretrained(model_id)
|
| 219 |
+
|
| 220 |
+
text = "Hello my name is"
|
| 221 |
+
input_ids = tok.encode(text, return_tensors="pt").to(torch_device)
|
| 222 |
+
|
| 223 |
+
_ = model.generate(input_ids, max_new_tokens=30)
|
| 224 |
+
|
| 225 |
+
def test_generate_quality(self):
|
| 226 |
+
r"""
|
| 227 |
+
Test the generation quality of the quantized model and see that we are matching the expected output.
|
| 228 |
+
Given that we are operating on small numbers + the testing model is relatively small, we might not get
|
| 229 |
+
the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
|
| 230 |
+
"""
|
| 231 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 232 |
+
output_sequences = self.model_4bit.generate(
|
| 233 |
+
input_ids=encoded_input["input_ids"].to(self.model_4bit.device), max_new_tokens=10
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 237 |
+
|
| 238 |
+
def test_generate_quality_config(self):
|
| 239 |
+
r"""
|
| 240 |
+
Test that loading the model with the config is equivalent
|
| 241 |
+
"""
|
| 242 |
+
bnb_config = BitsAndBytesConfig()
|
| 243 |
+
bnb_config.load_in_4bit = True
|
| 244 |
+
|
| 245 |
+
model_4bit_from_config = AutoModelForCausalLM.from_pretrained(
|
| 246 |
+
self.model_name, quantization_config=bnb_config, device_map="auto"
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 250 |
+
output_sequences = model_4bit_from_config.generate(
|
| 251 |
+
input_ids=encoded_input["input_ids"].to(model_4bit_from_config.device), max_new_tokens=10
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 255 |
+
|
| 256 |
+
def test_generate_quality_dequantize(self):
|
| 257 |
+
r"""
|
| 258 |
+
Test that loading the model and unquantize it produce correct results
|
| 259 |
+
"""
|
| 260 |
+
bnb_config = BitsAndBytesConfig(load_in_4bit=True)
|
| 261 |
+
|
| 262 |
+
model_4bit = AutoModelForCausalLM.from_pretrained(
|
| 263 |
+
self.model_name, quantization_config=bnb_config, device_map="auto"
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
model_4bit.dequantize()
|
| 267 |
+
|
| 268 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 269 |
+
output_sequences = model_4bit.generate(
|
| 270 |
+
input_ids=encoded_input["input_ids"].to(model_4bit.device), max_new_tokens=10
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 274 |
+
|
| 275 |
+
def test_clear_quantization_trace(self):
|
| 276 |
+
r"""
|
| 277 |
+
Test that dequantizing the model won't leave any attribute relative to quantization in the model's configuration
|
| 278 |
+
"""
|
| 279 |
+
bnb_config = BitsAndBytesConfig(load_in_4bit=True)
|
| 280 |
+
model_4bit = AutoModelForCausalLM.from_pretrained(
|
| 281 |
+
self.model_name, quantization_config=bnb_config, device_map="auto"
|
| 282 |
+
)
|
| 283 |
+
model_4bit.dequantize()
|
| 284 |
+
|
| 285 |
+
self.assertFalse(hasattr(model_4bit, "hf_quantizer"))
|
| 286 |
+
self.assertFalse(hasattr(model_4bit.config, "quantization_config"))
|
| 287 |
+
self.assertFalse(hasattr(model_4bit.config, "_pre_quantization_dtype"))
|
| 288 |
+
self.assertFalse(hasattr(model_4bit, "quantization_method"))
|
| 289 |
+
self.assertFalse(model_4bit.is_quantized)
|
| 290 |
+
|
| 291 |
+
def test_to_device_dequantized(self):
|
| 292 |
+
r"""
|
| 293 |
+
Test that dequantizing the model won't prevent converting it to a different dtype
|
| 294 |
+
"""
|
| 295 |
+
bnb_config = BitsAndBytesConfig(load_in_4bit=True)
|
| 296 |
+
model_4bit = AutoModelForCausalLM.from_pretrained(
|
| 297 |
+
self.model_name, quantization_config=bnb_config, device_map="auto"
|
| 298 |
+
)
|
| 299 |
+
model_4bit.dequantize()
|
| 300 |
+
model_4bit.to(dtype=torch.float16)
|
| 301 |
+
|
| 302 |
+
def test_device_assignment(self):
|
| 303 |
+
if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.43.2"):
|
| 304 |
+
self.skipTest(reason="This test requires bitsandbytes >= 0.43.2")
|
| 305 |
+
|
| 306 |
+
mem_before = self.model_4bit.get_memory_footprint()
|
| 307 |
+
|
| 308 |
+
# Move to CPU
|
| 309 |
+
self.model_4bit.to("cpu")
|
| 310 |
+
self.assertEqual(self.model_4bit.device.type, "cpu")
|
| 311 |
+
self.assertAlmostEqual(self.model_4bit.get_memory_footprint(), mem_before)
|
| 312 |
+
|
| 313 |
+
if torch_device in ["cuda", "xpu"]:
|
| 314 |
+
# Move back to CUDA device
|
| 315 |
+
self.model_4bit.to(torch_device)
|
| 316 |
+
self.assertEqual(self.model_4bit.device.type, torch_device)
|
| 317 |
+
self.assertAlmostEqual(self.model_4bit.get_memory_footprint(), mem_before)
|
| 318 |
+
|
| 319 |
+
def test_device_and_dtype_assignment(self):
|
| 320 |
+
r"""
|
| 321 |
+
Test whether attempting to change the device or cast the dtype of a model
|
| 322 |
+
after converting it to 4-bit precision will raise an appropriate error.
|
| 323 |
+
The test ensures that such operations are prohibited on 4-bit models
|
| 324 |
+
to prevent invalid conversions.
|
| 325 |
+
"""
|
| 326 |
+
|
| 327 |
+
# Moving with `to` or `cuda` is not supported with versions < 0.43.2.
|
| 328 |
+
if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.43.2"):
|
| 329 |
+
with self.assertRaises(ValueError):
|
| 330 |
+
# Tries with `str`
|
| 331 |
+
self.model_4bit.to("cpu")
|
| 332 |
+
|
| 333 |
+
with self.assertRaises(ValueError):
|
| 334 |
+
# Tries with a `device`
|
| 335 |
+
self.model_4bit.to(torch.device("cuda:0"))
|
| 336 |
+
|
| 337 |
+
with self.assertRaises(ValueError):
|
| 338 |
+
# Tries with `cuda`
|
| 339 |
+
self.model_4bit.cuda()
|
| 340 |
+
|
| 341 |
+
with self.assertRaises(ValueError):
|
| 342 |
+
# Tries with a `dtype`
|
| 343 |
+
self.model_4bit.to(torch.float16)
|
| 344 |
+
|
| 345 |
+
with self.assertRaises(ValueError):
|
| 346 |
+
# Tries to cast the 4-bit model to float32 using `float()`
|
| 347 |
+
self.model_4bit.float()
|
| 348 |
+
|
| 349 |
+
with self.assertRaises(ValueError):
|
| 350 |
+
# Tries to cast the 4-bit model to float16 using `half()`
|
| 351 |
+
self.model_4bit.half()
|
| 352 |
+
|
| 353 |
+
# Test if we did not break anything
|
| 354 |
+
self.model_4bit.to(torch.device(torch_device))
|
| 355 |
+
|
| 356 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 357 |
+
|
| 358 |
+
self.model_fp16 = self.model_fp16.to(torch.float32)
|
| 359 |
+
_ = self.model_fp16.generate(
|
| 360 |
+
input_ids=encoded_input["input_ids"].to(self.model_fp16.device), max_new_tokens=10
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
if torch_device in ["cuda", "xpu"]:
|
| 364 |
+
# Check that this does not throw an error
|
| 365 |
+
_ = self.model_fp16.to(torch_device)
|
| 366 |
+
|
| 367 |
+
# Check this does not throw an error
|
| 368 |
+
_ = self.model_fp16.to("cpu")
|
| 369 |
+
|
| 370 |
+
# Check this does not throw an error
|
| 371 |
+
_ = self.model_fp16.half()
|
| 372 |
+
|
| 373 |
+
# Check this does not throw an error
|
| 374 |
+
_ = self.model_fp16.float()
|
| 375 |
+
|
| 376 |
+
def test_fp32_4bit_conversion(self):
|
| 377 |
+
r"""
|
| 378 |
+
Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly.
|
| 379 |
+
"""
|
| 380 |
+
model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small", load_in_4bit=True, device_map="auto")
|
| 381 |
+
self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32)
|
| 382 |
+
|
| 383 |
+
def test_bnb_4bit_wrong_config(self):
|
| 384 |
+
r"""
|
| 385 |
+
Test whether creating a bnb config with unsupported values leads to errors.
|
| 386 |
+
"""
|
| 387 |
+
with self.assertRaises(ValueError):
|
| 388 |
+
_ = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_storage="add")
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
@require_bitsandbytes
|
| 392 |
+
@require_accelerate
|
| 393 |
+
@require_torch
|
| 394 |
+
@require_torch_gpu_if_bnb_not_multi_backend_enabled
|
| 395 |
+
@slow
|
| 396 |
+
@apply_skip_if_not_implemented
|
| 397 |
+
class Bnb4BitT5Test(unittest.TestCase):
|
| 398 |
+
@classmethod
|
| 399 |
+
def setUpClass(cls):
|
| 400 |
+
cls.model_name = "google-t5/t5-small"
|
| 401 |
+
cls.dense_act_model_name = "google/flan-t5-small" # flan-t5 uses dense-act instead of dense-relu-dense
|
| 402 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name)
|
| 403 |
+
cls.input_text = "Translate in German: Hello, my dog is cute"
|
| 404 |
+
|
| 405 |
+
def tearDown(self):
|
| 406 |
+
r"""
|
| 407 |
+
TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
|
| 408 |
+
avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
|
| 409 |
+
"""
|
| 410 |
+
gc.collect()
|
| 411 |
+
backend_empty_cache(torch_device)
|
| 412 |
+
|
| 413 |
+
def test_inference_without_keep_in_fp32(self):
|
| 414 |
+
r"""
|
| 415 |
+
Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly.
|
| 416 |
+
`flan-t5-small` uses `T5DenseGatedActDense` whereas `google-t5/t5-small` uses `T5DenseReluDense`. We need to test
|
| 417 |
+
both cases.
|
| 418 |
+
"""
|
| 419 |
+
from transformers import T5ForConditionalGeneration
|
| 420 |
+
|
| 421 |
+
modules = T5ForConditionalGeneration._keep_in_fp32_modules
|
| 422 |
+
T5ForConditionalGeneration._keep_in_fp32_modules = None
|
| 423 |
+
|
| 424 |
+
# test with `google-t5/t5-small`
|
| 425 |
+
model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto")
|
| 426 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device)
|
| 427 |
+
_ = model.generate(**encoded_input)
|
| 428 |
+
|
| 429 |
+
# test with `flan-t5-small`
|
| 430 |
+
model = T5ForConditionalGeneration.from_pretrained(
|
| 431 |
+
self.dense_act_model_name, load_in_4bit=True, device_map="auto"
|
| 432 |
+
)
|
| 433 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device)
|
| 434 |
+
_ = model.generate(**encoded_input)
|
| 435 |
+
T5ForConditionalGeneration._keep_in_fp32_modules = modules
|
| 436 |
+
|
| 437 |
+
def test_inference_with_keep_in_fp32(self):
|
| 438 |
+
r"""
|
| 439 |
+
Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly.
|
| 440 |
+
`flan-t5-small` uses `T5DenseGatedActDense` whereas `google-t5/t5-small` uses `T5DenseReluDense`. We need to test
|
| 441 |
+
both cases.
|
| 442 |
+
"""
|
| 443 |
+
from transformers import T5ForConditionalGeneration
|
| 444 |
+
|
| 445 |
+
# test with `google-t5/t5-small`
|
| 446 |
+
model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto")
|
| 447 |
+
|
| 448 |
+
# there was a bug with decoders - this test checks that it is fixed
|
| 449 |
+
self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q, bnb.nn.Linear4bit))
|
| 450 |
+
|
| 451 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device)
|
| 452 |
+
_ = model.generate(**encoded_input)
|
| 453 |
+
|
| 454 |
+
# test with `flan-t5-small`
|
| 455 |
+
model = T5ForConditionalGeneration.from_pretrained(
|
| 456 |
+
self.dense_act_model_name, load_in_4bit=True, device_map="auto"
|
| 457 |
+
)
|
| 458 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device)
|
| 459 |
+
_ = model.generate(**encoded_input)
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
@apply_skip_if_not_implemented
|
| 463 |
+
class Classes4BitModelTest(Base4bitTest):
|
| 464 |
+
def setUp(self):
|
| 465 |
+
super().setUp()
|
| 466 |
+
# model_name
|
| 467 |
+
self.model_name = "bigscience/bloom-560m"
|
| 468 |
+
self.seq_to_seq_name = "google-t5/t5-small"
|
| 469 |
+
|
| 470 |
+
# Different types of model
|
| 471 |
+
|
| 472 |
+
self.base_model = AutoModel.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto")
|
| 473 |
+
# Sequence classification model
|
| 474 |
+
self.sequence_model = AutoModelForSequenceClassification.from_pretrained(
|
| 475 |
+
self.model_name, load_in_4bit=True, device_map="auto"
|
| 476 |
+
)
|
| 477 |
+
# CausalLM model
|
| 478 |
+
self.model_4bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto")
|
| 479 |
+
# Seq2seq model
|
| 480 |
+
self.seq_to_seq_model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 481 |
+
self.seq_to_seq_name, load_in_4bit=True, device_map="auto"
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
def tearDown(self):
|
| 485 |
+
r"""
|
| 486 |
+
TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
|
| 487 |
+
avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
|
| 488 |
+
"""
|
| 489 |
+
del self.base_model
|
| 490 |
+
del self.sequence_model
|
| 491 |
+
del self.model_4bit
|
| 492 |
+
del self.seq_to_seq_model
|
| 493 |
+
|
| 494 |
+
gc.collect()
|
| 495 |
+
backend_empty_cache(torch_device)
|
| 496 |
+
|
| 497 |
+
def test_correct_head_class(self):
|
| 498 |
+
r"""
|
| 499 |
+
A simple test to check if the last modules for some classes (AutoModelForCausalLM or SequenceClassification)
|
| 500 |
+
are kept in their native class.
|
| 501 |
+
"""
|
| 502 |
+
from bitsandbytes.nn import Params4bit
|
| 503 |
+
|
| 504 |
+
self.assertTrue(self.base_model.h[-1].mlp.dense_4h_to_h.weight.__class__ == Params4bit)
|
| 505 |
+
|
| 506 |
+
# Other heads should be nn.Parameter
|
| 507 |
+
self.assertTrue(self.model_4bit.lm_head.weight.__class__ == torch.nn.Parameter)
|
| 508 |
+
self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter)
|
| 509 |
+
self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
@apply_skip_if_not_implemented
|
| 513 |
+
class Pipeline4BitTest(Base4bitTest):
|
| 514 |
+
def setUp(self):
|
| 515 |
+
super().setUp()
|
| 516 |
+
|
| 517 |
+
def tearDown(self):
|
| 518 |
+
r"""
|
| 519 |
+
TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
|
| 520 |
+
avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
|
| 521 |
+
"""
|
| 522 |
+
if hasattr(self, "pipe"):
|
| 523 |
+
del self.pipe
|
| 524 |
+
|
| 525 |
+
gc.collect()
|
| 526 |
+
backend_empty_cache(torch_device)
|
| 527 |
+
|
| 528 |
+
def test_pipeline(self):
|
| 529 |
+
r"""
|
| 530 |
+
The aim of this test is to verify that the mixed 4bit is compatible with `pipeline` from transformers. Since
|
| 531 |
+
we used pipeline for inference speed benchmarking we want to make sure that this feature does not break anything
|
| 532 |
+
on pipeline.
|
| 533 |
+
"""
|
| 534 |
+
# self._clear_cuda_cache()
|
| 535 |
+
self.pipe = pipeline(
|
| 536 |
+
"text-generation",
|
| 537 |
+
model=self.model_name,
|
| 538 |
+
model_kwargs={
|
| 539 |
+
"device_map": "auto",
|
| 540 |
+
"load_in_4bit": True,
|
| 541 |
+
# float16 isn't supported on CPU, use bfloat16 instead
|
| 542 |
+
"torch_dtype": torch.bfloat16 if torch_device == "cpu" else torch.float16,
|
| 543 |
+
},
|
| 544 |
+
max_new_tokens=self.MAX_NEW_TOKENS,
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
# Avoid sampling different outputs
|
| 548 |
+
set_seed(42)
|
| 549 |
+
# Real second forward pass
|
| 550 |
+
pipeline_output = self.pipe(self.input_text)
|
| 551 |
+
self.assertIn(pipeline_output[0]["generated_text"], self.EXPECTED_OUTPUTS)
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
@require_torch_multi_accelerator
|
| 555 |
+
@apply_skip_if_not_implemented
|
| 556 |
+
class Bnb4bitTestMultiAccelerator(Base4bitTest):
|
| 557 |
+
def setUp(self):
|
| 558 |
+
super().setUp()
|
| 559 |
+
|
| 560 |
+
def test_multi_accelerator_loading(self):
|
| 561 |
+
r"""
|
| 562 |
+
This tests that the model has been loaded and can be used correctly on a multi-accelerator setup.
|
| 563 |
+
Let's just try to load a model on 2 accelerators and see if it works. The model we test has ~2GB of total, 3GB should suffice
|
| 564 |
+
"""
|
| 565 |
+
device_map = {
|
| 566 |
+
"transformer.word_embeddings": 0,
|
| 567 |
+
"transformer.word_embeddings_layernorm": 0,
|
| 568 |
+
"lm_head": 0,
|
| 569 |
+
"transformer.h.0": 0,
|
| 570 |
+
"transformer.h.1": 0,
|
| 571 |
+
"transformer.h.2": 0,
|
| 572 |
+
"transformer.h.3": 0,
|
| 573 |
+
"transformer.h.4": 0,
|
| 574 |
+
"transformer.h.5": 0,
|
| 575 |
+
"transformer.h.6": 0,
|
| 576 |
+
"transformer.h.7": 0,
|
| 577 |
+
"transformer.h.8": 0,
|
| 578 |
+
"transformer.h.9": 0,
|
| 579 |
+
"transformer.h.10": 1,
|
| 580 |
+
"transformer.h.11": 1,
|
| 581 |
+
"transformer.h.12": 1,
|
| 582 |
+
"transformer.h.13": 1,
|
| 583 |
+
"transformer.h.14": 1,
|
| 584 |
+
"transformer.h.15": 1,
|
| 585 |
+
"transformer.h.16": 1,
|
| 586 |
+
"transformer.h.17": 0,
|
| 587 |
+
"transformer.h.18": 0,
|
| 588 |
+
"transformer.h.19": 0,
|
| 589 |
+
"transformer.h.20": 0,
|
| 590 |
+
"transformer.h.21": 0,
|
| 591 |
+
"transformer.h.22": 0,
|
| 592 |
+
"transformer.h.23": 1,
|
| 593 |
+
"transformer.ln_f": 0,
|
| 594 |
+
}
|
| 595 |
+
|
| 596 |
+
model_parallel = AutoModelForCausalLM.from_pretrained(
|
| 597 |
+
self.model_name, load_in_4bit=True, device_map=device_map
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
# Check correct device map
|
| 601 |
+
self.assertEqual(set(model_parallel.hf_device_map.values()), {0, 1})
|
| 602 |
+
|
| 603 |
+
# Check that inference pass works on the model
|
| 604 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 605 |
+
|
| 606 |
+
# Second real batch
|
| 607 |
+
output_parallel = model_parallel.generate(
|
| 608 |
+
input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10
|
| 609 |
+
)
|
| 610 |
+
self.assertIn(self.tokenizer.decode(output_parallel[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
@apply_skip_if_not_implemented
|
| 614 |
+
class Bnb4BitTestTraining(Base4bitTest):
|
| 615 |
+
def setUp(self):
|
| 616 |
+
self.model_name = "facebook/opt-350m"
|
| 617 |
+
super().setUp()
|
| 618 |
+
|
| 619 |
+
def test_training(self):
|
| 620 |
+
if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.37.0"):
|
| 621 |
+
self.skipTest(reason="This test requires bitsandbytes >= 0.37.0")
|
| 622 |
+
|
| 623 |
+
# Step 1: freeze all parameters
|
| 624 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_4bit=True)
|
| 625 |
+
|
| 626 |
+
if torch_device in ["cuda", "xpu"]:
|
| 627 |
+
self.assertEqual(
|
| 628 |
+
set(model.hf_device_map.values()), {backend_torch_accelerator_module(torch_device).current_device()}
|
| 629 |
+
)
|
| 630 |
+
else:
|
| 631 |
+
self.assertTrue(all(param.device.type == "cpu" for param in model.parameters()))
|
| 632 |
+
|
| 633 |
+
for param in model.parameters():
|
| 634 |
+
param.requires_grad = False # freeze the model - train adapters later
|
| 635 |
+
if param.ndim == 1:
|
| 636 |
+
# cast the small parameters (e.g. layernorm) to fp32 for stability
|
| 637 |
+
param.data = param.data.to(torch.float32)
|
| 638 |
+
|
| 639 |
+
# Step 2: add adapters
|
| 640 |
+
for _, module in model.named_modules():
|
| 641 |
+
if isinstance(module, OPTAttention):
|
| 642 |
+
module.q_proj = LoRALayer(module.q_proj, rank=16)
|
| 643 |
+
module.k_proj = LoRALayer(module.k_proj, rank=16)
|
| 644 |
+
module.v_proj = LoRALayer(module.v_proj, rank=16)
|
| 645 |
+
|
| 646 |
+
# Step 3: dummy batch
|
| 647 |
+
batch = self.tokenizer("Test batch ", return_tensors="pt").to(torch_device)
|
| 648 |
+
|
| 649 |
+
# Step 4: Check if the gradient is not None
|
| 650 |
+
with torch.autocast(torch_device):
|
| 651 |
+
out = model.forward(**batch)
|
| 652 |
+
out.logits.norm().backward()
|
| 653 |
+
|
| 654 |
+
for module in model.modules():
|
| 655 |
+
if isinstance(module, LoRALayer):
|
| 656 |
+
self.assertTrue(module.adapter[1].weight.grad is not None)
|
| 657 |
+
self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0)
|
| 658 |
+
elif isinstance(module, nn.Embedding):
|
| 659 |
+
self.assertTrue(module.weight.grad is None)
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
@apply_skip_if_not_implemented
|
| 663 |
+
class Bnb4BitGPT2Test(Bnb4BitTest):
|
| 664 |
+
model_name = "openai-community/gpt2-xl"
|
| 665 |
+
EXPECTED_RELATIVE_DIFFERENCE = 3.3191854854152187
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
@apply_skip_if_not_implemented
|
| 669 |
+
class Bnb4BitLlamaTest(Bnb4BitTest):
|
| 670 |
+
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
| 671 |
+
EXPECTED_RELATIVE_DIFFERENCE = 2.9461410686392764
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
@require_bitsandbytes
|
| 675 |
+
@require_accelerate
|
| 676 |
+
@require_torch
|
| 677 |
+
@require_torch_gpu_if_bnb_not_multi_backend_enabled
|
| 678 |
+
@slow
|
| 679 |
+
@apply_skip_if_not_implemented
|
| 680 |
+
class BaseSerializationTest(unittest.TestCase):
|
| 681 |
+
model_name = "facebook/opt-125m"
|
| 682 |
+
input_text = "Mars colonists' favorite meals are"
|
| 683 |
+
|
| 684 |
+
def tearDown(self):
|
| 685 |
+
gc.collect()
|
| 686 |
+
backend_empty_cache(torch_device)
|
| 687 |
+
|
| 688 |
+
def test_serialization(self, quant_type="nf4", double_quant=True, safe_serialization=True):
|
| 689 |
+
r"""
|
| 690 |
+
Test whether it is possible to serialize a model in 4-bit. Uses most typical params as default.
|
| 691 |
+
See ExtendedSerializationTest class for more params combinations.
|
| 692 |
+
"""
|
| 693 |
+
|
| 694 |
+
tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 695 |
+
|
| 696 |
+
self.quantization_config = BitsAndBytesConfig(
|
| 697 |
+
load_in_4bit=True,
|
| 698 |
+
bnb_4bit_quant_type=quant_type,
|
| 699 |
+
bnb_4bit_use_double_quant=double_quant,
|
| 700 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 701 |
+
)
|
| 702 |
+
model_0 = AutoModelForCausalLM.from_pretrained(
|
| 703 |
+
self.model_name,
|
| 704 |
+
quantization_config=self.quantization_config,
|
| 705 |
+
device_map=torch_device,
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 709 |
+
model_0.save_pretrained(tmpdirname, safe_serialization=safe_serialization)
|
| 710 |
+
|
| 711 |
+
config = AutoConfig.from_pretrained(tmpdirname)
|
| 712 |
+
self.assertTrue(hasattr(config, "quantization_config"))
|
| 713 |
+
|
| 714 |
+
model_1 = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=torch_device)
|
| 715 |
+
|
| 716 |
+
# checking quantized linear module weight
|
| 717 |
+
linear = get_some_linear_layer(model_1)
|
| 718 |
+
self.assertTrue(linear.weight.__class__ == bnb.nn.Params4bit)
|
| 719 |
+
self.assertTrue(hasattr(linear.weight, "quant_state"))
|
| 720 |
+
self.assertTrue(linear.weight.quant_state.__class__ == bnb.functional.QuantState)
|
| 721 |
+
|
| 722 |
+
# checking memory footpring
|
| 723 |
+
self.assertAlmostEqual(model_0.get_memory_footprint() / model_1.get_memory_footprint(), 1, places=2)
|
| 724 |
+
|
| 725 |
+
# Matching all parameters and their quant_state items:
|
| 726 |
+
d0 = dict(model_0.named_parameters())
|
| 727 |
+
d1 = dict(model_1.named_parameters())
|
| 728 |
+
self.assertTrue(d0.keys() == d1.keys())
|
| 729 |
+
|
| 730 |
+
for k in d0:
|
| 731 |
+
self.assertTrue(d0[k].shape == d1[k].shape)
|
| 732 |
+
self.assertTrue(d0[k].device.type == d1[k].device.type)
|
| 733 |
+
self.assertTrue(d0[k].device == d1[k].device)
|
| 734 |
+
self.assertTrue(d0[k].dtype == d1[k].dtype)
|
| 735 |
+
self.assertTrue(torch.equal(d0[k], d1[k].to(d0[k].device)))
|
| 736 |
+
|
| 737 |
+
if isinstance(d0[k], bnb.nn.modules.Params4bit):
|
| 738 |
+
for v0, v1 in zip(
|
| 739 |
+
d0[k].quant_state.as_dict().values(),
|
| 740 |
+
d1[k].quant_state.as_dict().values(),
|
| 741 |
+
):
|
| 742 |
+
if isinstance(v0, torch.Tensor):
|
| 743 |
+
# The absmax will not be saved in the quant_state when using NF4 in CPU
|
| 744 |
+
if v0.numel() != 0:
|
| 745 |
+
self.assertTrue(torch.equal(v0, v1.to(v0.device)))
|
| 746 |
+
else:
|
| 747 |
+
self.assertTrue(v0 == v1)
|
| 748 |
+
|
| 749 |
+
# comparing forward() outputs
|
| 750 |
+
encoded_input = tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 751 |
+
out_0 = model_0(**encoded_input)
|
| 752 |
+
out_1 = model_1(**encoded_input)
|
| 753 |
+
torch.testing.assert_close(out_0["logits"], out_1["logits"], rtol=0.05, atol=0.05)
|
| 754 |
+
|
| 755 |
+
# comparing generate() outputs
|
| 756 |
+
encoded_input = tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 757 |
+
output_sequences_0 = model_0.generate(**encoded_input, max_new_tokens=10)
|
| 758 |
+
output_sequences_1 = model_1.generate(**encoded_input, max_new_tokens=10)
|
| 759 |
+
|
| 760 |
+
def _decode(token):
|
| 761 |
+
return tokenizer.decode(token, skip_special_tokens=True)
|
| 762 |
+
|
| 763 |
+
self.assertEqual(
|
| 764 |
+
[_decode(x) for x in output_sequences_0],
|
| 765 |
+
[_decode(x) for x in output_sequences_1],
|
| 766 |
+
)
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
@apply_skip_if_not_implemented
|
| 770 |
+
class ExtendedSerializationTest(BaseSerializationTest):
|
| 771 |
+
"""
|
| 772 |
+
tests more combinations of parameters
|
| 773 |
+
"""
|
| 774 |
+
|
| 775 |
+
def test_nf4_single_unsafe(self):
|
| 776 |
+
self.test_serialization(quant_type="nf4", double_quant=False, safe_serialization=False)
|
| 777 |
+
|
| 778 |
+
def test_nf4_single_safe(self):
|
| 779 |
+
self.test_serialization(quant_type="nf4", double_quant=False, safe_serialization=True)
|
| 780 |
+
|
| 781 |
+
def test_nf4_double_unsafe(self):
|
| 782 |
+
self.test_serialization(quant_type="nf4", double_quant=True, safe_serialization=False)
|
| 783 |
+
|
| 784 |
+
# nf4 double safetensors quantization is tested in test_serialization() method from the parent class
|
| 785 |
+
|
| 786 |
+
def test_fp4_single_unsafe(self):
|
| 787 |
+
self.test_serialization(quant_type="fp4", double_quant=False, safe_serialization=False)
|
| 788 |
+
|
| 789 |
+
def test_fp4_single_safe(self):
|
| 790 |
+
self.test_serialization(quant_type="fp4", double_quant=False, safe_serialization=True)
|
| 791 |
+
|
| 792 |
+
def test_fp4_double_unsafe(self):
|
| 793 |
+
self.test_serialization(quant_type="fp4", double_quant=True, safe_serialization=False)
|
| 794 |
+
|
| 795 |
+
def test_fp4_double_safe(self):
|
| 796 |
+
self.test_serialization(quant_type="fp4", double_quant=True, safe_serialization=True)
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
class BloomSerializationTest(BaseSerializationTest):
|
| 800 |
+
"""
|
| 801 |
+
default BaseSerializationTest config tested with Bloom family model
|
| 802 |
+
"""
|
| 803 |
+
|
| 804 |
+
model_name = "bigscience/bloom-560m"
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
class GPTSerializationTest(BaseSerializationTest):
|
| 808 |
+
"""
|
| 809 |
+
default BaseSerializationTest config tested with GPT family model
|
| 810 |
+
"""
|
| 811 |
+
|
| 812 |
+
model_name = "openai-community/gpt2-xl"
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
class LlamaSerializationTest(BaseSerializationTest):
|
| 816 |
+
"""
|
| 817 |
+
default BaseSerializationTest config tested with Llama family model
|
| 818 |
+
"""
|
| 819 |
+
|
| 820 |
+
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
@require_bitsandbytes
|
| 824 |
+
@require_accelerate
|
| 825 |
+
@require_torch_gpu_if_bnb_not_multi_backend_enabled
|
| 826 |
+
@slow
|
| 827 |
+
@apply_skip_if_not_implemented
|
| 828 |
+
class Bnb4BitTestBasicConfigTest(unittest.TestCase):
|
| 829 |
+
def test_load_in_4_and_8_bit_fails(self):
|
| 830 |
+
with self.assertRaisesRegex(ValueError, "load_in_4bit and load_in_8bit are both True"):
|
| 831 |
+
AutoModelForCausalLM.from_pretrained("facebook/opt-125m", load_in_4bit=True, load_in_8bit=True)
|
| 832 |
+
|
| 833 |
+
def test_set_load_in_8_bit(self):
|
| 834 |
+
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
|
| 835 |
+
with self.assertRaisesRegex(ValueError, "load_in_4bit and load_in_8bit are both True"):
|
| 836 |
+
quantization_config.load_in_8bit = True
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
@require_bitsandbytes
|
| 840 |
+
@require_accelerate
|
| 841 |
+
@require_torch_gpu_if_bnb_not_multi_backend_enabled
|
| 842 |
+
@slow
|
| 843 |
+
@apply_skip_if_not_implemented
|
| 844 |
+
class Bnb4bitCompile(unittest.TestCase):
|
| 845 |
+
model_name = "hf-internal-testing/tiny-random-LlamaForCausalLM"
|
| 846 |
+
input_text = "Hello my name is"
|
| 847 |
+
|
| 848 |
+
def setUp(self):
|
| 849 |
+
# Models and tokenizer
|
| 850 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 851 |
+
self.model_4bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_4bit=True)
|
| 852 |
+
|
| 853 |
+
@pytest.mark.torch_compile_test
|
| 854 |
+
def test_generate_compile(self):
|
| 855 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 856 |
+
|
| 857 |
+
# if nothing is set, compile will be disabled for bnb
|
| 858 |
+
self.model_4bit.generate(
|
| 859 |
+
input_ids=encoded_input["input_ids"].to(self.model_4bit.device),
|
| 860 |
+
max_new_tokens=10,
|
| 861 |
+
cache_implementation="static",
|
| 862 |
+
)
|
| 863 |
+
with self.assertRaises(Exception):
|
| 864 |
+
# overwrite property
|
| 865 |
+
object.__setattr__(self.model_4bit.hf_quantizer, "is_compileable", True)
|
| 866 |
+
self.model_4bit.generate(
|
| 867 |
+
input_ids=encoded_input["input_ids"].to(self.model_4bit.device),
|
| 868 |
+
max_new_tokens=10,
|
| 869 |
+
cache_implementation="static",
|
| 870 |
+
)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/test_mixed_int8.py
ADDED
|
@@ -0,0 +1,1017 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team Inc.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a clone of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import gc
|
| 15 |
+
import importlib.metadata
|
| 16 |
+
import tempfile
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import pytest
|
| 20 |
+
from packaging import version
|
| 21 |
+
|
| 22 |
+
from transformers import (
|
| 23 |
+
AutoConfig,
|
| 24 |
+
AutoModel,
|
| 25 |
+
AutoModelForCausalLM,
|
| 26 |
+
AutoModelForSeq2SeqLM,
|
| 27 |
+
AutoModelForSequenceClassification,
|
| 28 |
+
AutoTokenizer,
|
| 29 |
+
BitsAndBytesConfig,
|
| 30 |
+
pipeline,
|
| 31 |
+
set_seed,
|
| 32 |
+
)
|
| 33 |
+
from transformers.models.opt.modeling_opt import OPTAttention
|
| 34 |
+
from transformers.testing_utils import (
|
| 35 |
+
apply_skip_if_not_implemented,
|
| 36 |
+
backend_empty_cache,
|
| 37 |
+
backend_torch_accelerator_module,
|
| 38 |
+
is_accelerate_available,
|
| 39 |
+
is_bitsandbytes_available,
|
| 40 |
+
is_torch_available,
|
| 41 |
+
require_accelerate,
|
| 42 |
+
require_bitsandbytes,
|
| 43 |
+
require_torch,
|
| 44 |
+
require_torch_gpu_if_bnb_not_multi_backend_enabled,
|
| 45 |
+
require_torch_multi_accelerator,
|
| 46 |
+
slow,
|
| 47 |
+
torch_device,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_some_linear_layer(model):
|
| 52 |
+
if model.config.model_type == "gpt2":
|
| 53 |
+
return model.transformer.h[0].mlp.c_fc
|
| 54 |
+
elif model.config.model_type == "llama":
|
| 55 |
+
return model.model.layers[0].mlp.gate_proj
|
| 56 |
+
return model.transformer.h[0].mlp.dense_4h_to_h
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
if is_accelerate_available():
|
| 60 |
+
from accelerate import PartialState
|
| 61 |
+
from accelerate.logging import get_logger
|
| 62 |
+
|
| 63 |
+
logger = get_logger(__name__)
|
| 64 |
+
_ = PartialState()
|
| 65 |
+
|
| 66 |
+
if is_torch_available():
|
| 67 |
+
import torch
|
| 68 |
+
import torch.nn as nn
|
| 69 |
+
|
| 70 |
+
class LoRALayer(nn.Module):
|
| 71 |
+
"""Wraps a linear layer with LoRA-like adapter - Used for testing purposes only"""
|
| 72 |
+
|
| 73 |
+
def __init__(self, module: nn.Module, rank: int, dtype: torch.dtype):
|
| 74 |
+
super().__init__()
|
| 75 |
+
self.module = module
|
| 76 |
+
self.adapter = nn.Sequential(
|
| 77 |
+
nn.Linear(module.in_features, rank, bias=False, dtype=dtype),
|
| 78 |
+
nn.Linear(rank, module.out_features, bias=False, dtype=dtype),
|
| 79 |
+
)
|
| 80 |
+
small_std = (2.0 / (5 * min(module.in_features, module.out_features))) ** 0.5
|
| 81 |
+
nn.init.normal_(self.adapter[0].weight, std=small_std)
|
| 82 |
+
nn.init.zeros_(self.adapter[1].weight)
|
| 83 |
+
self.adapter.to(module.weight.device)
|
| 84 |
+
|
| 85 |
+
def forward(self, input, *args, **kwargs):
|
| 86 |
+
return self.module(input, *args, **kwargs) + self.adapter(input)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
if is_bitsandbytes_available():
|
| 90 |
+
import bitsandbytes as bnb
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@require_bitsandbytes
|
| 94 |
+
@require_accelerate
|
| 95 |
+
@require_torch
|
| 96 |
+
@require_torch_gpu_if_bnb_not_multi_backend_enabled
|
| 97 |
+
@slow
|
| 98 |
+
class BaseMixedInt8Test(unittest.TestCase):
|
| 99 |
+
# We keep the constants inside the init function and model loading inside setUp function
|
| 100 |
+
|
| 101 |
+
# We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
|
| 102 |
+
# Therefore here we use only bloom-1b3 to test our module
|
| 103 |
+
model_name = "bigscience/bloom-1b7"
|
| 104 |
+
|
| 105 |
+
# Constant values
|
| 106 |
+
EXPECTED_RELATIVE_DIFFERENCE = (
|
| 107 |
+
1.540025 # This was obtained on a Quadro RTX 8000 so the number might slightly change
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
input_text = "Hello my name is"
|
| 111 |
+
EXPECTED_OUTPUTS = set()
|
| 112 |
+
EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of the family.\n")
|
| 113 |
+
# Expected values on a A10
|
| 114 |
+
EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n")
|
| 115 |
+
MAX_NEW_TOKENS = 10
|
| 116 |
+
# Expected values with offload
|
| 117 |
+
EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer based in")
|
| 118 |
+
# Expected values on Intel XPU and NV A100
|
| 119 |
+
EXPECTED_OUTPUTS.add("Hello my name is Alina. I have been working as a professional")
|
| 120 |
+
|
| 121 |
+
def setUp(self):
|
| 122 |
+
# Models and tokenizer
|
| 123 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@apply_skip_if_not_implemented
|
| 127 |
+
class MixedInt8Test(BaseMixedInt8Test):
|
| 128 |
+
def setUp(self):
|
| 129 |
+
super().setUp()
|
| 130 |
+
|
| 131 |
+
# Models and tokenizer
|
| 132 |
+
self.model_fp16 = AutoModelForCausalLM.from_pretrained(
|
| 133 |
+
self.model_name, torch_dtype=torch.float16, device_map="auto"
|
| 134 |
+
)
|
| 135 |
+
self.model_8bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto")
|
| 136 |
+
|
| 137 |
+
def tearDown(self):
|
| 138 |
+
r"""
|
| 139 |
+
TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
|
| 140 |
+
avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
|
| 141 |
+
"""
|
| 142 |
+
del self.model_fp16
|
| 143 |
+
del self.model_8bit
|
| 144 |
+
|
| 145 |
+
gc.collect()
|
| 146 |
+
backend_empty_cache(torch_device)
|
| 147 |
+
|
| 148 |
+
def test_get_keys_to_not_convert(self):
|
| 149 |
+
r"""
|
| 150 |
+
Test the `get_keys_to_not_convert` function.
|
| 151 |
+
"""
|
| 152 |
+
from accelerate import init_empty_weights
|
| 153 |
+
|
| 154 |
+
from transformers import AutoModelForMaskedLM, Blip2ForConditionalGeneration, MptForCausalLM, OPTForCausalLM
|
| 155 |
+
from transformers.integrations.bitsandbytes import get_keys_to_not_convert
|
| 156 |
+
|
| 157 |
+
model_id = "mosaicml/mpt-7b"
|
| 158 |
+
config = AutoConfig.from_pretrained(model_id, revision="72e5f594ce36f9cabfa2a9fd8f58b491eb467ee7")
|
| 159 |
+
with init_empty_weights():
|
| 160 |
+
model = MptForCausalLM(config)
|
| 161 |
+
# The order of the keys does not matter, so we sort them before comparing, same for the other tests.
|
| 162 |
+
self.assertEqual(get_keys_to_not_convert(model).sort(), ["lm_head", "transformer.wte"].sort())
|
| 163 |
+
|
| 164 |
+
model_id = "Salesforce/blip2-opt-2.7b"
|
| 165 |
+
config = AutoConfig.from_pretrained(model_id, revision="1ef7f63a8f0a144c13fdca8103eb7b4691c74cec")
|
| 166 |
+
with init_empty_weights():
|
| 167 |
+
model = Blip2ForConditionalGeneration(config)
|
| 168 |
+
self.assertEqual(
|
| 169 |
+
get_keys_to_not_convert(model).sort(),
|
| 170 |
+
["language_model.lm_head", "language_model.model.decoder.embed_tokens"].sort(),
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
model_id = "facebook/opt-350m"
|
| 174 |
+
config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5")
|
| 175 |
+
with init_empty_weights():
|
| 176 |
+
model = OPTForCausalLM(config)
|
| 177 |
+
self.assertEqual(get_keys_to_not_convert(model).sort(), ["lm_head", "model.decoder.embed_tokens"].sort())
|
| 178 |
+
|
| 179 |
+
model_id = "FacebookAI/roberta-large"
|
| 180 |
+
config = AutoConfig.from_pretrained(model_id, revision="716877d372b884cad6d419d828bac6c85b3b18d9")
|
| 181 |
+
with init_empty_weights():
|
| 182 |
+
model = AutoModelForMaskedLM.from_config(config)
|
| 183 |
+
self.assertEqual(
|
| 184 |
+
get_keys_to_not_convert(model).sort(),
|
| 185 |
+
["'roberta.embeddings.word_embeddings', 'lm_head', 'lm_head.decoder"].sort(),
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def test_quantization_config_json_serialization(self):
|
| 189 |
+
r"""
|
| 190 |
+
A simple test to check if the quantization config is correctly serialized and deserialized
|
| 191 |
+
"""
|
| 192 |
+
config = self.model_8bit.config
|
| 193 |
+
|
| 194 |
+
self.assertTrue(hasattr(config, "quantization_config"))
|
| 195 |
+
|
| 196 |
+
_ = config.to_dict()
|
| 197 |
+
_ = config.to_diff_dict()
|
| 198 |
+
|
| 199 |
+
_ = config.to_json_string()
|
| 200 |
+
|
| 201 |
+
def test_original_dtype(self):
|
| 202 |
+
r"""
|
| 203 |
+
A simple test to check if the model successfully stores the original dtype
|
| 204 |
+
"""
|
| 205 |
+
self.assertTrue(hasattr(self.model_8bit.config, "_pre_quantization_dtype"))
|
| 206 |
+
self.assertFalse(hasattr(self.model_fp16.config, "_pre_quantization_dtype"))
|
| 207 |
+
self.assertTrue(self.model_8bit.config._pre_quantization_dtype == torch.float16)
|
| 208 |
+
|
| 209 |
+
def test_memory_footprint(self):
|
| 210 |
+
r"""
|
| 211 |
+
A simple test to check if the model conversion has been done correctly by checking on the
|
| 212 |
+
memory footprint of the converted model and the class type of the linear layers of the converted models
|
| 213 |
+
"""
|
| 214 |
+
from bitsandbytes.nn import Int8Params
|
| 215 |
+
|
| 216 |
+
mem_fp16 = self.model_fp16.get_memory_footprint()
|
| 217 |
+
mem_8bit = self.model_8bit.get_memory_footprint()
|
| 218 |
+
|
| 219 |
+
self.assertAlmostEqual(mem_fp16 / mem_8bit, self.EXPECTED_RELATIVE_DIFFERENCE, delta=1e-5)
|
| 220 |
+
self.assertTrue(get_some_linear_layer(self.model_8bit).weight.__class__ == Int8Params)
|
| 221 |
+
|
| 222 |
+
def test_linear_are_8bit(self):
|
| 223 |
+
r"""
|
| 224 |
+
A simple test to check if the model conversion has been done correctly by checking on the
|
| 225 |
+
memory footprint of the converted model and the class type of the linear layers of the converted models
|
| 226 |
+
"""
|
| 227 |
+
from transformers import T5PreTrainedModel
|
| 228 |
+
|
| 229 |
+
self.model_fp16.get_memory_footprint()
|
| 230 |
+
self.model_8bit.get_memory_footprint()
|
| 231 |
+
|
| 232 |
+
for name, module in self.model_8bit.named_modules():
|
| 233 |
+
if isinstance(module, torch.nn.Linear):
|
| 234 |
+
if name not in ["lm_head"] + T5PreTrainedModel._keep_in_fp32_modules:
|
| 235 |
+
self.assertTrue(module.weight.dtype == torch.int8)
|
| 236 |
+
|
| 237 |
+
def test_llm_skip(self):
|
| 238 |
+
r"""
|
| 239 |
+
A simple test to check if `llm_int8_skip_modules` works as expected
|
| 240 |
+
"""
|
| 241 |
+
|
| 242 |
+
quantization_config = BitsAndBytesConfig(load_in_8bit=True, llm_int8_skip_modules=["classifier"])
|
| 243 |
+
seq_classification_model = AutoModelForSequenceClassification.from_pretrained(
|
| 244 |
+
"FacebookAI/roberta-large-mnli", quantization_config=quantization_config
|
| 245 |
+
)
|
| 246 |
+
self.assertTrue(seq_classification_model.roberta.encoder.layer[0].output.dense.weight.dtype == torch.int8)
|
| 247 |
+
self.assertTrue(
|
| 248 |
+
isinstance(seq_classification_model.roberta.encoder.layer[0].output.dense, bnb.nn.Linear8bitLt)
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
self.assertTrue(isinstance(seq_classification_model.classifier.dense, nn.Linear))
|
| 252 |
+
self.assertTrue(seq_classification_model.classifier.dense.weight.dtype != torch.int8)
|
| 253 |
+
self.assertTrue(isinstance(seq_classification_model.classifier.out_proj, nn.Linear))
|
| 254 |
+
self.assertTrue(seq_classification_model.classifier.out_proj != torch.int8)
|
| 255 |
+
|
| 256 |
+
def test_generate_quality(self):
|
| 257 |
+
r"""
|
| 258 |
+
Test the generation quality of the quantized model and see that we are matching the expected output.
|
| 259 |
+
Given that we are operating on small numbers + the testing model is relatively small, we might not get
|
| 260 |
+
the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
|
| 261 |
+
"""
|
| 262 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 263 |
+
output_sequences = self.model_8bit.generate(
|
| 264 |
+
input_ids=encoded_input["input_ids"].to(self.model_8bit.device), max_new_tokens=10
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 268 |
+
|
| 269 |
+
def test_generate_quality_config(self):
|
| 270 |
+
r"""
|
| 271 |
+
Test that loading the model with the config is equivalent
|
| 272 |
+
"""
|
| 273 |
+
bnb_config = BitsAndBytesConfig()
|
| 274 |
+
bnb_config.load_in_8bit = True
|
| 275 |
+
|
| 276 |
+
model_8bit_from_config = AutoModelForCausalLM.from_pretrained(
|
| 277 |
+
self.model_name, quantization_config=bnb_config, device_map="auto"
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 281 |
+
output_sequences = model_8bit_from_config.generate(
|
| 282 |
+
input_ids=encoded_input["input_ids"].to(model_8bit_from_config.device), max_new_tokens=10
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 286 |
+
|
| 287 |
+
def test_generate_quality_dequantize(self):
|
| 288 |
+
r"""
|
| 289 |
+
Test that loading the model and dequantizing it produce correct results
|
| 290 |
+
"""
|
| 291 |
+
bnb_config = BitsAndBytesConfig(load_in_8bit=True)
|
| 292 |
+
|
| 293 |
+
model_8bit = AutoModelForCausalLM.from_pretrained(
|
| 294 |
+
self.model_name, quantization_config=bnb_config, device_map="auto"
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
model_8bit.dequantize()
|
| 298 |
+
|
| 299 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 300 |
+
output_sequences = model_8bit.generate(
|
| 301 |
+
input_ids=encoded_input["input_ids"].to(model_8bit.device), max_new_tokens=10
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 305 |
+
|
| 306 |
+
def test_raise_if_config_and_load_in_8bit(self):
|
| 307 |
+
r"""
|
| 308 |
+
Test that loading the model with the config and `load_in_8bit` raises an error
|
| 309 |
+
"""
|
| 310 |
+
bnb_config = BitsAndBytesConfig()
|
| 311 |
+
|
| 312 |
+
with self.assertRaises(ValueError):
|
| 313 |
+
_ = AutoModelForCausalLM.from_pretrained(
|
| 314 |
+
self.model_name,
|
| 315 |
+
quantization_config=bnb_config,
|
| 316 |
+
load_in_8bit=True,
|
| 317 |
+
device_map="auto",
|
| 318 |
+
llm_int8_enable_fp32_cpu_offload=True,
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
def test_device_and_dtype_assignment(self):
|
| 322 |
+
r"""
|
| 323 |
+
Test whether attempting to change the device or cast the dtype of a model
|
| 324 |
+
after converting it to 8-bit precision will raise an appropriate error.
|
| 325 |
+
The test ensures that such operations are prohibited on 8-bit models
|
| 326 |
+
to prevent invalid conversions.
|
| 327 |
+
"""
|
| 328 |
+
with self.assertRaises(ValueError):
|
| 329 |
+
# Tries with `str`
|
| 330 |
+
self.model_8bit.to("cpu")
|
| 331 |
+
|
| 332 |
+
with self.assertRaises(ValueError):
|
| 333 |
+
# Tries with a `dtype``
|
| 334 |
+
self.model_8bit.to(torch.float16)
|
| 335 |
+
|
| 336 |
+
with self.assertRaises(ValueError):
|
| 337 |
+
# Tries with a `device`
|
| 338 |
+
self.model_8bit.to(torch.device(torch_device))
|
| 339 |
+
|
| 340 |
+
with self.assertRaises(ValueError):
|
| 341 |
+
# Tries to cast the 8-bit model to float32 using `float()`
|
| 342 |
+
self.model_8bit.float()
|
| 343 |
+
|
| 344 |
+
with self.assertRaises(ValueError):
|
| 345 |
+
# Tries to cast the 4-bit model to float16 using `half()`
|
| 346 |
+
self.model_8bit.half()
|
| 347 |
+
|
| 348 |
+
# Test if we did not break anything
|
| 349 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 350 |
+
|
| 351 |
+
self.model_fp16 = self.model_fp16.to(torch.float32)
|
| 352 |
+
_ = self.model_fp16.generate(
|
| 353 |
+
input_ids=encoded_input["input_ids"].to(self.model_fp16.device), max_new_tokens=10
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
# Check this does not throw an error
|
| 357 |
+
_ = self.model_fp16.to("cpu")
|
| 358 |
+
|
| 359 |
+
# Check this does not throw an error
|
| 360 |
+
_ = self.model_fp16.half()
|
| 361 |
+
|
| 362 |
+
# Check this does not throw an error
|
| 363 |
+
_ = self.model_fp16.float()
|
| 364 |
+
|
| 365 |
+
def test_fp32_int8_conversion(self):
|
| 366 |
+
r"""
|
| 367 |
+
Test whether it is possible to mix both `int8` and `fp32` weights when using `keep_in_fp32_modules` correctly.
|
| 368 |
+
"""
|
| 369 |
+
model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small", load_in_8bit=True, device_map="auto")
|
| 370 |
+
self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32)
|
| 371 |
+
|
| 372 |
+
def test_int8_serialization(self):
|
| 373 |
+
r"""
|
| 374 |
+
Test whether it is possible to serialize a model in 8-bit.
|
| 375 |
+
"""
|
| 376 |
+
from bitsandbytes.nn import Int8Params
|
| 377 |
+
|
| 378 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 379 |
+
self.model_8bit.save_pretrained(tmpdirname)
|
| 380 |
+
|
| 381 |
+
# check that the file `quantization_config` is present
|
| 382 |
+
config = AutoConfig.from_pretrained(tmpdirname)
|
| 383 |
+
self.assertTrue(hasattr(config, "quantization_config"))
|
| 384 |
+
|
| 385 |
+
model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname, load_in_8bit=True, device_map="auto")
|
| 386 |
+
|
| 387 |
+
linear = get_some_linear_layer(model_from_saved)
|
| 388 |
+
self.assertTrue(linear.weight.__class__ == Int8Params)
|
| 389 |
+
self.assertTrue(hasattr(linear.weight, "SCB"))
|
| 390 |
+
|
| 391 |
+
# generate
|
| 392 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 393 |
+
output_sequences = model_from_saved.generate(
|
| 394 |
+
input_ids=encoded_input["input_ids"].to(model_from_saved.device), max_new_tokens=10
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 398 |
+
|
| 399 |
+
def test_int8_serialization_regression(self):
|
| 400 |
+
r"""
|
| 401 |
+
Test whether it is possible to serialize a model in 8-bit - using not safetensors
|
| 402 |
+
"""
|
| 403 |
+
from bitsandbytes.nn import Int8Params
|
| 404 |
+
|
| 405 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 406 |
+
self.model_8bit.save_pretrained(tmpdirname, safe_serialization=False)
|
| 407 |
+
|
| 408 |
+
# check that the file `quantization_config` is present
|
| 409 |
+
config = AutoConfig.from_pretrained(tmpdirname)
|
| 410 |
+
self.assertTrue(hasattr(config, "quantization_config"))
|
| 411 |
+
|
| 412 |
+
model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname, load_in_8bit=True, device_map="auto")
|
| 413 |
+
|
| 414 |
+
linear = get_some_linear_layer(model_from_saved)
|
| 415 |
+
self.assertTrue(linear.weight.__class__ == Int8Params)
|
| 416 |
+
self.assertTrue(hasattr(linear.weight, "SCB"))
|
| 417 |
+
|
| 418 |
+
# generate
|
| 419 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 420 |
+
output_sequences = model_from_saved.generate(
|
| 421 |
+
input_ids=encoded_input["input_ids"].to(model_from_saved.device), max_new_tokens=10
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 425 |
+
|
| 426 |
+
def test_int8_serialization_sharded(self):
|
| 427 |
+
r"""
|
| 428 |
+
Test whether it is possible to serialize a model in 8-bit - sharded version.
|
| 429 |
+
"""
|
| 430 |
+
from bitsandbytes.nn import Int8Params
|
| 431 |
+
|
| 432 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 433 |
+
self.model_8bit.save_pretrained(tmpdirname, max_shard_size="200MB")
|
| 434 |
+
|
| 435 |
+
# check that the file `quantization_config` is present
|
| 436 |
+
config = AutoConfig.from_pretrained(tmpdirname)
|
| 437 |
+
self.assertTrue(hasattr(config, "quantization_config"))
|
| 438 |
+
|
| 439 |
+
model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname)
|
| 440 |
+
|
| 441 |
+
linear = get_some_linear_layer(model_from_saved)
|
| 442 |
+
self.assertTrue(linear.weight.__class__ == Int8Params)
|
| 443 |
+
self.assertTrue(hasattr(linear.weight, "SCB"))
|
| 444 |
+
|
| 445 |
+
# generate
|
| 446 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 447 |
+
output_sequences = model_from_saved.generate(
|
| 448 |
+
input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 452 |
+
|
| 453 |
+
def test_int8_from_pretrained(self):
|
| 454 |
+
r"""
|
| 455 |
+
Test whether loading a 8bit model from the Hub works as expected
|
| 456 |
+
"""
|
| 457 |
+
from bitsandbytes.nn import Int8Params
|
| 458 |
+
|
| 459 |
+
model_id = "ybelkada/bloom-1b7-8bit"
|
| 460 |
+
|
| 461 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 462 |
+
|
| 463 |
+
linear = get_some_linear_layer(model)
|
| 464 |
+
self.assertTrue(linear.weight.__class__ == Int8Params)
|
| 465 |
+
self.assertTrue(hasattr(linear.weight, "SCB"))
|
| 466 |
+
|
| 467 |
+
# generate
|
| 468 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 469 |
+
output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10)
|
| 470 |
+
|
| 471 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
@require_bitsandbytes
|
| 475 |
+
@require_accelerate
|
| 476 |
+
@require_torch
|
| 477 |
+
@require_torch_gpu_if_bnb_not_multi_backend_enabled
|
| 478 |
+
@slow
|
| 479 |
+
class MixedInt8T5Test(unittest.TestCase):
|
| 480 |
+
@classmethod
|
| 481 |
+
def setUpClass(cls):
|
| 482 |
+
cls.model_name = "google-t5/t5-small"
|
| 483 |
+
cls.dense_act_model_name = "google/flan-t5-small" # flan-t5 uses dense-act instead of dense-relu-dense
|
| 484 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name)
|
| 485 |
+
cls.input_text = "Translate in German: Hello, my dog is cute"
|
| 486 |
+
|
| 487 |
+
def tearDown(self):
|
| 488 |
+
r"""
|
| 489 |
+
TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
|
| 490 |
+
avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
|
| 491 |
+
"""
|
| 492 |
+
gc.collect()
|
| 493 |
+
backend_empty_cache(torch_device)
|
| 494 |
+
|
| 495 |
+
def test_inference_without_keep_in_fp32(self):
|
| 496 |
+
r"""
|
| 497 |
+
Test whether it is possible to mix both `int8` and `fp32` weights when using `keep_in_fp32_modules` correctly.
|
| 498 |
+
`flan-t5-small` uses `T5DenseGatedActDense` whereas `google-t5/t5-small` uses `T5DenseReluDense`. We need to test
|
| 499 |
+
both cases.
|
| 500 |
+
"""
|
| 501 |
+
from transformers import T5ForConditionalGeneration
|
| 502 |
+
|
| 503 |
+
modules = T5ForConditionalGeneration._keep_in_fp32_modules
|
| 504 |
+
T5ForConditionalGeneration._keep_in_fp32_modules = None
|
| 505 |
+
|
| 506 |
+
# test with `google-t5/t5-small`
|
| 507 |
+
model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto")
|
| 508 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device)
|
| 509 |
+
_ = model.generate(**encoded_input)
|
| 510 |
+
|
| 511 |
+
# test with `flan-t5-small`
|
| 512 |
+
model = T5ForConditionalGeneration.from_pretrained(
|
| 513 |
+
self.dense_act_model_name, load_in_8bit=True, device_map="auto"
|
| 514 |
+
)
|
| 515 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device)
|
| 516 |
+
_ = model.generate(**encoded_input)
|
| 517 |
+
T5ForConditionalGeneration._keep_in_fp32_modules = modules
|
| 518 |
+
|
| 519 |
+
def test_inference_with_keep_in_fp32(self):
|
| 520 |
+
r"""
|
| 521 |
+
Test whether it is possible to mix both `int8` and `fp32` weights when using `keep_in_fp32_modules` correctly.
|
| 522 |
+
`flan-t5-small` uses `T5DenseGatedActDense` whereas `google-t5/t5-small` uses `T5DenseReluDense`. We need to test
|
| 523 |
+
both cases.
|
| 524 |
+
"""
|
| 525 |
+
|
| 526 |
+
from transformers import T5ForConditionalGeneration
|
| 527 |
+
|
| 528 |
+
# test with `google-t5/t5-small`
|
| 529 |
+
model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto")
|
| 530 |
+
|
| 531 |
+
# there was a bug with decoders - this test checks that it is fixed
|
| 532 |
+
self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q, bnb.nn.Linear8bitLt))
|
| 533 |
+
|
| 534 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device)
|
| 535 |
+
_ = model.generate(**encoded_input)
|
| 536 |
+
|
| 537 |
+
# test with `flan-t5-small`
|
| 538 |
+
model = T5ForConditionalGeneration.from_pretrained(
|
| 539 |
+
self.dense_act_model_name, load_in_8bit=True, device_map="auto"
|
| 540 |
+
)
|
| 541 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device)
|
| 542 |
+
_ = model.generate(**encoded_input)
|
| 543 |
+
|
| 544 |
+
def test_inference_with_keep_in_fp32_serialized(self):
|
| 545 |
+
r"""
|
| 546 |
+
Test whether it is possible to mix both `int8` and `fp32` weights when using `keep_in_fp32_modules` correctly on
|
| 547 |
+
a serialized model.
|
| 548 |
+
`flan-t5-small` uses `T5DenseGatedActDense` whereas `google-t5/t5-small` uses `T5DenseReluDense`. We need to test
|
| 549 |
+
both cases.
|
| 550 |
+
"""
|
| 551 |
+
|
| 552 |
+
from transformers import T5ForConditionalGeneration
|
| 553 |
+
|
| 554 |
+
# test with `google-t5/t5-small`
|
| 555 |
+
model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto")
|
| 556 |
+
|
| 557 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 558 |
+
model.save_pretrained(tmp_dir)
|
| 559 |
+
|
| 560 |
+
model = T5ForConditionalGeneration.from_pretrained(tmp_dir)
|
| 561 |
+
|
| 562 |
+
# there was a bug with decoders - this test checks that it is fixed
|
| 563 |
+
self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q, bnb.nn.Linear8bitLt))
|
| 564 |
+
|
| 565 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device)
|
| 566 |
+
_ = model.generate(**encoded_input)
|
| 567 |
+
|
| 568 |
+
# test with `flan-t5-small`
|
| 569 |
+
model = T5ForConditionalGeneration.from_pretrained(
|
| 570 |
+
self.dense_act_model_name, load_in_8bit=True, device_map="auto"
|
| 571 |
+
)
|
| 572 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device)
|
| 573 |
+
_ = model.generate(**encoded_input)
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
class MixedInt8ModelClassesTest(BaseMixedInt8Test):
|
| 577 |
+
def setUp(self):
|
| 578 |
+
super().setUp()
|
| 579 |
+
# model_name
|
| 580 |
+
self.model_name = "bigscience/bloom-560m"
|
| 581 |
+
self.seq_to_seq_name = "google-t5/t5-small"
|
| 582 |
+
|
| 583 |
+
# Different types of model
|
| 584 |
+
|
| 585 |
+
self.base_model = AutoModel.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto")
|
| 586 |
+
# Sequence classification model
|
| 587 |
+
self.sequence_model = AutoModelForSequenceClassification.from_pretrained(
|
| 588 |
+
self.model_name, load_in_8bit=True, device_map="auto"
|
| 589 |
+
)
|
| 590 |
+
# CausalLM model
|
| 591 |
+
self.model_8bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto")
|
| 592 |
+
# Seq2seq model
|
| 593 |
+
self.seq_to_seq_model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 594 |
+
self.seq_to_seq_name, load_in_8bit=True, device_map="auto"
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
def tearDown(self):
|
| 598 |
+
r"""
|
| 599 |
+
TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
|
| 600 |
+
avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
|
| 601 |
+
"""
|
| 602 |
+
del self.base_model
|
| 603 |
+
del self.sequence_model
|
| 604 |
+
del self.model_8bit
|
| 605 |
+
del self.seq_to_seq_model
|
| 606 |
+
|
| 607 |
+
gc.collect()
|
| 608 |
+
backend_empty_cache(torch_device)
|
| 609 |
+
|
| 610 |
+
def test_correct_head_class(self):
|
| 611 |
+
r"""
|
| 612 |
+
A simple test to check if the last modules for some classes (AutoModelForCausalLM or SequenceClassification)
|
| 613 |
+
are kept in their native class.
|
| 614 |
+
"""
|
| 615 |
+
from bitsandbytes.nn import Int8Params
|
| 616 |
+
|
| 617 |
+
# last param of a base model should be a linear8bit module
|
| 618 |
+
self.assertTrue(self.base_model.h[-1].mlp.dense_4h_to_h.weight.__class__ == Int8Params)
|
| 619 |
+
|
| 620 |
+
# Other heads should be nn.Parameter
|
| 621 |
+
self.assertTrue(self.model_8bit.lm_head.weight.__class__ == torch.nn.Parameter)
|
| 622 |
+
self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter)
|
| 623 |
+
self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter)
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
@apply_skip_if_not_implemented
|
| 627 |
+
class MixedInt8TestPipeline(BaseMixedInt8Test):
|
| 628 |
+
def setUp(self):
|
| 629 |
+
super().setUp()
|
| 630 |
+
|
| 631 |
+
def tearDown(self):
|
| 632 |
+
r"""
|
| 633 |
+
TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
|
| 634 |
+
avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
|
| 635 |
+
"""
|
| 636 |
+
if hasattr(self, "pipe"):
|
| 637 |
+
del self.pipe
|
| 638 |
+
|
| 639 |
+
gc.collect()
|
| 640 |
+
backend_empty_cache(torch_device)
|
| 641 |
+
|
| 642 |
+
def test_pipeline(self):
|
| 643 |
+
r"""
|
| 644 |
+
The aim of this test is to verify that the mixed int8 is compatible with `pipeline` from transformers. Since
|
| 645 |
+
we used pipeline for inference speed benchmarking we want to make sure that this feature does not break anything
|
| 646 |
+
on pipeline.
|
| 647 |
+
"""
|
| 648 |
+
# self._clear_cuda_cache()
|
| 649 |
+
self.pipe = pipeline(
|
| 650 |
+
"text-generation",
|
| 651 |
+
model=self.model_name,
|
| 652 |
+
model_kwargs={"device_map": "auto", "load_in_8bit": True},
|
| 653 |
+
max_new_tokens=self.MAX_NEW_TOKENS,
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
# Avoid sampling different outputs
|
| 657 |
+
set_seed(42)
|
| 658 |
+
# Real second forward pass
|
| 659 |
+
pipeline_output = self.pipe(self.input_text)
|
| 660 |
+
self.assertIn(pipeline_output[0]["generated_text"], self.EXPECTED_OUTPUTS)
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
@require_torch_multi_accelerator
|
| 664 |
+
@apply_skip_if_not_implemented
|
| 665 |
+
class MixedInt8TestMultiGpu(BaseMixedInt8Test):
|
| 666 |
+
def setUp(self):
|
| 667 |
+
super().setUp()
|
| 668 |
+
|
| 669 |
+
def test_multi_gpu_loading(self):
|
| 670 |
+
r"""
|
| 671 |
+
This tests that the model has been loaded and can be used correctly on a multi-GPU setup.
|
| 672 |
+
Let's just try to load a model on 2 GPUs and see if it works. The model we test has ~2GB of total, 3GB should suffice
|
| 673 |
+
"""
|
| 674 |
+
device_map = {
|
| 675 |
+
"transformer.word_embeddings": 0,
|
| 676 |
+
"transformer.word_embeddings_layernorm": 0,
|
| 677 |
+
"lm_head": 0,
|
| 678 |
+
"transformer.h.0": 0,
|
| 679 |
+
"transformer.h.1": 0,
|
| 680 |
+
"transformer.h.2": 0,
|
| 681 |
+
"transformer.h.3": 0,
|
| 682 |
+
"transformer.h.4": 0,
|
| 683 |
+
"transformer.h.5": 0,
|
| 684 |
+
"transformer.h.6": 0,
|
| 685 |
+
"transformer.h.7": 0,
|
| 686 |
+
"transformer.h.8": 0,
|
| 687 |
+
"transformer.h.9": 0,
|
| 688 |
+
"transformer.h.10": 1,
|
| 689 |
+
"transformer.h.11": 1,
|
| 690 |
+
"transformer.h.12": 1,
|
| 691 |
+
"transformer.h.13": 1,
|
| 692 |
+
"transformer.h.14": 1,
|
| 693 |
+
"transformer.h.15": 1,
|
| 694 |
+
"transformer.h.16": 1,
|
| 695 |
+
"transformer.h.17": 0,
|
| 696 |
+
"transformer.h.18": 0,
|
| 697 |
+
"transformer.h.19": 0,
|
| 698 |
+
"transformer.h.20": 0,
|
| 699 |
+
"transformer.h.21": 0,
|
| 700 |
+
"transformer.h.22": 0,
|
| 701 |
+
"transformer.h.23": 1,
|
| 702 |
+
"transformer.ln_f": 0,
|
| 703 |
+
}
|
| 704 |
+
|
| 705 |
+
model_parallel = AutoModelForCausalLM.from_pretrained(
|
| 706 |
+
self.model_name, load_in_8bit=True, device_map=device_map
|
| 707 |
+
)
|
| 708 |
+
|
| 709 |
+
# Check correct device map
|
| 710 |
+
self.assertEqual(set(model_parallel.hf_device_map.values()), {0, 1})
|
| 711 |
+
|
| 712 |
+
# Check that inference pass works on the model
|
| 713 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 714 |
+
|
| 715 |
+
# Second real batch
|
| 716 |
+
output_parallel = model_parallel.generate(
|
| 717 |
+
input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10
|
| 718 |
+
)
|
| 719 |
+
self.assertIn(self.tokenizer.decode(output_parallel[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
@require_torch_multi_accelerator
|
| 723 |
+
@apply_skip_if_not_implemented
|
| 724 |
+
class MixedInt8TestCpuGpu(BaseMixedInt8Test):
|
| 725 |
+
def setUp(self):
|
| 726 |
+
super().setUp()
|
| 727 |
+
|
| 728 |
+
def check_inference_correctness(self, model):
|
| 729 |
+
# Check that inference pass works on the model
|
| 730 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 731 |
+
|
| 732 |
+
# Check the exactness of the results
|
| 733 |
+
output_parallel = model.generate(input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10)
|
| 734 |
+
|
| 735 |
+
# Get the generation
|
| 736 |
+
output_text = self.tokenizer.decode(output_parallel[0], skip_special_tokens=True)
|
| 737 |
+
self.assertIn(output_text, self.EXPECTED_OUTPUTS)
|
| 738 |
+
|
| 739 |
+
def test_cpu_accelerator_loading_random_device_map(self):
|
| 740 |
+
r"""
|
| 741 |
+
A test to check is dispatching a model on cpu & gpu works correctly using a random `device_map`.
|
| 742 |
+
"""
|
| 743 |
+
device_map = {
|
| 744 |
+
"transformer.word_embeddings": 0,
|
| 745 |
+
"transformer.word_embeddings_layernorm": 0,
|
| 746 |
+
"lm_head": 0,
|
| 747 |
+
"transformer.h.0": "cpu",
|
| 748 |
+
"transformer.h.1": "cpu",
|
| 749 |
+
"transformer.h.2": 0,
|
| 750 |
+
"transformer.h.3": 0,
|
| 751 |
+
"transformer.h.4": 0,
|
| 752 |
+
"transformer.h.5": 0,
|
| 753 |
+
"transformer.h.6": 0,
|
| 754 |
+
"transformer.h.7": 0,
|
| 755 |
+
"transformer.h.8": 0,
|
| 756 |
+
"transformer.h.9": 1,
|
| 757 |
+
"transformer.h.10": 0,
|
| 758 |
+
"transformer.h.11": 1,
|
| 759 |
+
"transformer.h.12": 0,
|
| 760 |
+
"transformer.h.13": 0,
|
| 761 |
+
"transformer.h.14": 1,
|
| 762 |
+
"transformer.h.15": 0,
|
| 763 |
+
"transformer.h.16": 0,
|
| 764 |
+
"transformer.h.17": 1,
|
| 765 |
+
"transformer.h.18": 1,
|
| 766 |
+
"transformer.h.19": 0,
|
| 767 |
+
"transformer.h.20": 1,
|
| 768 |
+
"transformer.h.21": 1,
|
| 769 |
+
"transformer.h.22": 0,
|
| 770 |
+
"transformer.h.23": 0,
|
| 771 |
+
"transformer.ln_f": 1,
|
| 772 |
+
}
|
| 773 |
+
|
| 774 |
+
bnb_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True, load_in_8bit=True)
|
| 775 |
+
|
| 776 |
+
model_8bit = AutoModelForCausalLM.from_pretrained(
|
| 777 |
+
self.model_name,
|
| 778 |
+
device_map=device_map,
|
| 779 |
+
quantization_config=bnb_config,
|
| 780 |
+
)
|
| 781 |
+
|
| 782 |
+
# Check that the model has been correctly set on device 0, 1, and `cpu`.
|
| 783 |
+
self.assertEqual(set(model_8bit.hf_device_map.values()), {0, 1, "cpu"})
|
| 784 |
+
|
| 785 |
+
self.check_inference_correctness(model_8bit)
|
| 786 |
+
|
| 787 |
+
def test_cpu_accelerator_loading_custom_device_map(self):
|
| 788 |
+
r"""
|
| 789 |
+
A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`.
|
| 790 |
+
This time the device map is more organized than the test above and uses the abstraction
|
| 791 |
+
`transformer.h` to encapsulate all the decoder layers.
|
| 792 |
+
"""
|
| 793 |
+
device_map = {
|
| 794 |
+
"transformer.word_embeddings": "cpu",
|
| 795 |
+
"transformer.word_embeddings_layernorm": "cpu",
|
| 796 |
+
"lm_head": "cpu",
|
| 797 |
+
"transformer.h": 0,
|
| 798 |
+
"transformer.ln_f": 1,
|
| 799 |
+
}
|
| 800 |
+
bnb_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True, load_in_8bit=True)
|
| 801 |
+
|
| 802 |
+
# Load model
|
| 803 |
+
model_8bit = AutoModelForCausalLM.from_pretrained(
|
| 804 |
+
self.model_name,
|
| 805 |
+
device_map=device_map,
|
| 806 |
+
quantization_config=bnb_config,
|
| 807 |
+
)
|
| 808 |
+
|
| 809 |
+
# Check that the model has been correctly set on device 0, 1, and `cpu`.
|
| 810 |
+
self.assertEqual(set(model_8bit.hf_device_map.values()), {0, 1, "cpu"})
|
| 811 |
+
|
| 812 |
+
self.check_inference_correctness(model_8bit)
|
| 813 |
+
|
| 814 |
+
def test_cpu_accelerator_disk_loading_custom_device_map(self):
|
| 815 |
+
r"""
|
| 816 |
+
A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`.
|
| 817 |
+
This time we also add `disk` on the device_map.
|
| 818 |
+
"""
|
| 819 |
+
device_map = {
|
| 820 |
+
"transformer.word_embeddings": 0,
|
| 821 |
+
"transformer.word_embeddings_layernorm": "cpu",
|
| 822 |
+
"lm_head": 0,
|
| 823 |
+
"transformer.h": 1,
|
| 824 |
+
"transformer.ln_f": "disk",
|
| 825 |
+
}
|
| 826 |
+
bnb_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True, load_in_8bit=True)
|
| 827 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 828 |
+
# Load model
|
| 829 |
+
model_8bit = AutoModelForCausalLM.from_pretrained(
|
| 830 |
+
self.model_name,
|
| 831 |
+
device_map=device_map,
|
| 832 |
+
quantization_config=bnb_config,
|
| 833 |
+
offload_folder=tmpdirname,
|
| 834 |
+
)
|
| 835 |
+
|
| 836 |
+
# Check that the model has been correctly set on device 0, 1, and `cpu`.
|
| 837 |
+
self.assertEqual(set(model_8bit.hf_device_map.values()), {0, 1, "cpu", "disk"})
|
| 838 |
+
|
| 839 |
+
self.check_inference_correctness(model_8bit)
|
| 840 |
+
|
| 841 |
+
def test_cpu_accelerator_disk_loading_custom_device_map_kwargs(self):
|
| 842 |
+
r"""
|
| 843 |
+
A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`.
|
| 844 |
+
This time we also add `disk` on the device_map - using the kwargs directly instead of the quantization config
|
| 845 |
+
"""
|
| 846 |
+
device_map = {
|
| 847 |
+
"transformer.word_embeddings": 0,
|
| 848 |
+
"transformer.word_embeddings_layernorm": "cpu",
|
| 849 |
+
"lm_head": 0,
|
| 850 |
+
"transformer.h": 1,
|
| 851 |
+
"transformer.ln_f": "disk",
|
| 852 |
+
}
|
| 853 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 854 |
+
# Load model
|
| 855 |
+
model_8bit = AutoModelForCausalLM.from_pretrained(
|
| 856 |
+
self.model_name,
|
| 857 |
+
device_map=device_map,
|
| 858 |
+
load_in_8bit=True,
|
| 859 |
+
llm_int8_enable_fp32_cpu_offload=True,
|
| 860 |
+
offload_folder=tmpdirname,
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
# Check that the model has been correctly set on device 0, 1, and `cpu`.
|
| 864 |
+
self.assertEqual(set(model_8bit.hf_device_map.values()), {0, 1, "cpu", "disk"})
|
| 865 |
+
|
| 866 |
+
self.check_inference_correctness(model_8bit)
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
@apply_skip_if_not_implemented
|
| 870 |
+
class MixedInt8TestTraining(BaseMixedInt8Test):
|
| 871 |
+
def setUp(self):
|
| 872 |
+
self.model_name = "facebook/opt-350m"
|
| 873 |
+
super().setUp()
|
| 874 |
+
|
| 875 |
+
def test_training(self):
|
| 876 |
+
if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.37.0"):
|
| 877 |
+
self.skipTest(reason="This test requires bitsandbytes>=0.37.0")
|
| 878 |
+
|
| 879 |
+
# Step 1: freeze all parameters
|
| 880 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_8bit=True)
|
| 881 |
+
model.train()
|
| 882 |
+
|
| 883 |
+
if torch_device in ["cuda", "xpu"]:
|
| 884 |
+
self.assertEqual(
|
| 885 |
+
set(model.hf_device_map.values()), {backend_torch_accelerator_module(torch_device).current_device()}
|
| 886 |
+
)
|
| 887 |
+
else:
|
| 888 |
+
self.assertTrue(all(param.device.type == "cpu" for param in model.parameters()))
|
| 889 |
+
|
| 890 |
+
for param in model.parameters():
|
| 891 |
+
param.requires_grad = False # freeze the model - train adapters later
|
| 892 |
+
# cast all non INT8 parameters to fp32
|
| 893 |
+
if param.dtype in (torch.float16, torch.bfloat16) and param.__class__.__name__ != "Params4bit":
|
| 894 |
+
param.data = param.data.to(torch.float32)
|
| 895 |
+
|
| 896 |
+
# Step 2: add adapters
|
| 897 |
+
for _, module in model.named_modules():
|
| 898 |
+
if isinstance(module, OPTAttention):
|
| 899 |
+
module.q_proj = LoRALayer(module.q_proj, rank=16, dtype=model.dtype)
|
| 900 |
+
module.k_proj = LoRALayer(module.k_proj, rank=16, dtype=model.dtype)
|
| 901 |
+
module.v_proj = LoRALayer(module.v_proj, rank=16, dtype=model.dtype)
|
| 902 |
+
|
| 903 |
+
# Step 3: dummy batch
|
| 904 |
+
batch = self.tokenizer("Test batch ", return_tensors="pt").to(torch_device)
|
| 905 |
+
|
| 906 |
+
# Step 4: Check if the gradient is not None
|
| 907 |
+
with torch.autocast(torch_device):
|
| 908 |
+
out = model.forward(**batch)
|
| 909 |
+
out.logits.norm().backward()
|
| 910 |
+
|
| 911 |
+
for module in model.modules():
|
| 912 |
+
if isinstance(module, LoRALayer):
|
| 913 |
+
self.assertTrue(module.adapter[1].weight.grad is not None)
|
| 914 |
+
self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0)
|
| 915 |
+
elif isinstance(module, nn.Embedding):
|
| 916 |
+
self.assertTrue(module.weight.grad is None)
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
@apply_skip_if_not_implemented
|
| 920 |
+
class MixedInt8GPT2Test(MixedInt8Test):
|
| 921 |
+
model_name = "openai-community/gpt2-xl"
|
| 922 |
+
EXPECTED_RELATIVE_DIFFERENCE = 1.8720077507258357
|
| 923 |
+
EXPECTED_OUTPUTS = set()
|
| 924 |
+
EXPECTED_OUTPUTS.add("Hello my name is John Doe, and I'm a big fan of")
|
| 925 |
+
EXPECTED_OUTPUTS.add("Hello my name is John Doe, and I'm a fan of the")
|
| 926 |
+
# Expected values on a A10
|
| 927 |
+
EXPECTED_OUTPUTS.add("Hello my name is John Doe, and I am a member of the")
|
| 928 |
+
# Expected values on Intel CPU
|
| 929 |
+
EXPECTED_OUTPUTS.add("Hello my name is John Doe. I am a man. I am")
|
| 930 |
+
EXPECTED_OUTPUTS.add("Hello my name is John, and I'm a writer. I'm")
|
| 931 |
+
|
| 932 |
+
def test_int8_from_pretrained(self):
|
| 933 |
+
r"""
|
| 934 |
+
Test whether loading a 8bit model from the Hub works as expected
|
| 935 |
+
"""
|
| 936 |
+
from bitsandbytes.nn import Int8Params
|
| 937 |
+
|
| 938 |
+
model_id = "ybelkada/gpt2-xl-8bit"
|
| 939 |
+
|
| 940 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 941 |
+
|
| 942 |
+
linear = get_some_linear_layer(model)
|
| 943 |
+
self.assertTrue(linear.weight.__class__ == Int8Params)
|
| 944 |
+
self.assertTrue(hasattr(linear.weight, "SCB"))
|
| 945 |
+
|
| 946 |
+
# generate
|
| 947 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 948 |
+
output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10)
|
| 949 |
+
|
| 950 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
class MixedInt8LlamaTest(MixedInt8Test):
|
| 954 |
+
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
| 955 |
+
EXPECTED_RELATIVE_DIFFERENCE = 1.7869331026479096
|
| 956 |
+
EXPECTED_OUTPUTS = set()
|
| 957 |
+
|
| 958 |
+
# Expected on Intel XPU
|
| 959 |
+
EXPECTED_OUTPUTS.add("Hello my name is John Smith and I am a software engineer. I")
|
| 960 |
+
|
| 961 |
+
# Expected on NVIDIA T4
|
| 962 |
+
EXPECTED_OUTPUTS.add("Hello my name is John and I am a software engineer. I have")
|
| 963 |
+
|
| 964 |
+
def test_int8_from_pretrained(self):
|
| 965 |
+
r"""
|
| 966 |
+
Test whether loading a 8bit model from the Hub works as expected
|
| 967 |
+
"""
|
| 968 |
+
from bitsandbytes.nn import Int8Params
|
| 969 |
+
|
| 970 |
+
model_id = "Jiqing/TinyLlama-1.1B-Chat-v1.0-bnb-8bit"
|
| 971 |
+
|
| 972 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 973 |
+
|
| 974 |
+
linear = get_some_linear_layer(model)
|
| 975 |
+
self.assertTrue(linear.weight.__class__ == Int8Params)
|
| 976 |
+
self.assertTrue(hasattr(linear.weight, "SCB"))
|
| 977 |
+
|
| 978 |
+
# generate
|
| 979 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 980 |
+
output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10)
|
| 981 |
+
|
| 982 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
@require_bitsandbytes
|
| 986 |
+
@require_accelerate
|
| 987 |
+
@require_torch
|
| 988 |
+
@require_torch_gpu_if_bnb_not_multi_backend_enabled
|
| 989 |
+
@slow
|
| 990 |
+
@apply_skip_if_not_implemented
|
| 991 |
+
class Bnb8bitCompile(unittest.TestCase):
|
| 992 |
+
model_name = "hf-internal-testing/tiny-random-LlamaForCausalLM"
|
| 993 |
+
input_text = "Hello my name is"
|
| 994 |
+
|
| 995 |
+
def setUp(self):
|
| 996 |
+
# Models and tokenizer
|
| 997 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 998 |
+
self.model_8bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_8bit=True)
|
| 999 |
+
|
| 1000 |
+
@pytest.mark.torch_compile_test
|
| 1001 |
+
def test_generate_compile(self):
|
| 1002 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 1003 |
+
|
| 1004 |
+
# if nothing is set, compile will be disabled for bnb
|
| 1005 |
+
self.model_8bit.generate(
|
| 1006 |
+
input_ids=encoded_input["input_ids"].to(self.model_8bit.device),
|
| 1007 |
+
max_new_tokens=10,
|
| 1008 |
+
cache_implementation="static",
|
| 1009 |
+
)
|
| 1010 |
+
|
| 1011 |
+
with self.assertRaises(Exception):
|
| 1012 |
+
object.__setattr__(self.model_8bit.hf_quantizer, "is_compileable", True)
|
| 1013 |
+
self.model_8bit.generate(
|
| 1014 |
+
input_ids=encoded_input["input_ids"].to(self.model_8bit.device),
|
| 1015 |
+
max_new_tokens=10,
|
| 1016 |
+
cache_implementation="static",
|
| 1017 |
+
)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/test_compressed_models.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
import unittest
|
| 3 |
+
import warnings
|
| 4 |
+
|
| 5 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 6 |
+
from transformers.testing_utils import backend_empty_cache, require_compressed_tensors, require_torch, torch_device
|
| 7 |
+
from transformers.utils import is_torch_available
|
| 8 |
+
from transformers.utils.quantization_config import CompressedTensorsConfig
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if is_torch_available():
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@require_compressed_tensors
|
| 16 |
+
@require_torch
|
| 17 |
+
class StackCompressedModelTest(unittest.TestCase):
|
| 18 |
+
# Define stubs as class attributes
|
| 19 |
+
compressed_uncompressed_model_stubs = [
|
| 20 |
+
(
|
| 21 |
+
"nm-testing/llama2.c-stories42M-gsm8k-quantized-only-compressed",
|
| 22 |
+
"nm-testing/llama2.c-stories42M-gsm8k-quantized-only-uncompressed",
|
| 23 |
+
),
|
| 24 |
+
(
|
| 25 |
+
"nm-testing/llama2.c-stories42M-gsm8k-sparse-only-compressed",
|
| 26 |
+
"nm-testing/llama2.c-stories42M-gsm8k-sparse-only-uncompressed",
|
| 27 |
+
),
|
| 28 |
+
(
|
| 29 |
+
"nm-testing/llama2.c-stories42M-gsm8k-stacked-compressed",
|
| 30 |
+
"nm-testing/llama2.c-stories42M-gsm8k-stacked-uncompressed",
|
| 31 |
+
),
|
| 32 |
+
]
|
| 33 |
+
# Flatten the list for tests that require a single list of stubs.
|
| 34 |
+
model_stubs = [stub for pair in compressed_uncompressed_model_stubs for stub in pair]
|
| 35 |
+
|
| 36 |
+
# For the outputs matching test, use the sparse-only pair.
|
| 37 |
+
sparse_compressed_model = "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-compressed"
|
| 38 |
+
sparse_uncompressed_model = "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-uncompressed"
|
| 39 |
+
|
| 40 |
+
prompt = "Paris is the capital of which country?"
|
| 41 |
+
|
| 42 |
+
def tearDown(self):
|
| 43 |
+
gc.collect()
|
| 44 |
+
backend_empty_cache(torch_device)
|
| 45 |
+
gc.collect()
|
| 46 |
+
|
| 47 |
+
def test_compressed_uncompressed_model_shapes(self):
|
| 48 |
+
"""
|
| 49 |
+
Verify that the weights of an uncompressed model and its decompressed compressed counterpart match.
|
| 50 |
+
Note: Weights for sparsely compressed models may differ due to packing.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def _has_nested_attr(obj, attr_path):
|
| 54 |
+
attrs = attr_path.split(".")
|
| 55 |
+
for attr in attrs:
|
| 56 |
+
if not hasattr(obj, attr):
|
| 57 |
+
return None
|
| 58 |
+
obj = getattr(obj, attr)
|
| 59 |
+
return obj
|
| 60 |
+
|
| 61 |
+
from compressed_tensors.quantization.utils import iter_named_leaf_modules
|
| 62 |
+
|
| 63 |
+
for compressed_model, uncompressed_model in self.compressed_uncompressed_model_stubs:
|
| 64 |
+
with self.subTest(compressed_model=compressed_model, uncompressed_model=uncompressed_model):
|
| 65 |
+
uncompressed = AutoModelForCausalLM.from_pretrained(
|
| 66 |
+
uncompressed_model,
|
| 67 |
+
device_map="auto",
|
| 68 |
+
torch_dtype="auto",
|
| 69 |
+
quantization_config=CompressedTensorsConfig(run_compressed=False),
|
| 70 |
+
)
|
| 71 |
+
compressed_decompressed = AutoModelForCausalLM.from_pretrained(
|
| 72 |
+
compressed_model,
|
| 73 |
+
device_map="auto",
|
| 74 |
+
torch_dtype="auto",
|
| 75 |
+
quantization_config=CompressedTensorsConfig(run_compressed=False),
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
for name, submodule in iter_named_leaf_modules(uncompressed):
|
| 79 |
+
comp_decomp_obj = _has_nested_attr(compressed_decompressed, name)
|
| 80 |
+
if comp_decomp_obj is not None and hasattr(submodule, "weight"):
|
| 81 |
+
if "sparse-only" in uncompressed_model:
|
| 82 |
+
self.assertTrue(
|
| 83 |
+
torch.equal(submodule.weight, comp_decomp_obj.weight),
|
| 84 |
+
f"Weight mismatch for module '{name}' in sparse-only model.",
|
| 85 |
+
)
|
| 86 |
+
else:
|
| 87 |
+
self.assertTrue(
|
| 88 |
+
torch.allclose(submodule.weight, comp_decomp_obj.weight, atol=0.2),
|
| 89 |
+
f"Weight mismatch for module '{name}' in quantized-only or stacked model.",
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
def test_outputs_match(self):
|
| 93 |
+
"""
|
| 94 |
+
Ensure that the generated outputs match between the uncompressed model
|
| 95 |
+
and its decompressed compressed counterpart.
|
| 96 |
+
"""
|
| 97 |
+
tokenizer = AutoTokenizer.from_pretrained(self.sparse_uncompressed_model)
|
| 98 |
+
input_ids = tokenizer(self.prompt, return_tensors="pt").input_ids
|
| 99 |
+
|
| 100 |
+
uncompressed = AutoModelForCausalLM.from_pretrained(
|
| 101 |
+
self.sparse_uncompressed_model,
|
| 102 |
+
device_map="auto",
|
| 103 |
+
torch_dtype="auto",
|
| 104 |
+
quantization_config=CompressedTensorsConfig(run_compressed=False),
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
output_uncompressed = uncompressed.generate(input_ids.to(uncompressed.device), max_new_tokens=100)
|
| 108 |
+
|
| 109 |
+
decompressed = AutoModelForCausalLM.from_pretrained(
|
| 110 |
+
self.sparse_compressed_model,
|
| 111 |
+
device_map="auto",
|
| 112 |
+
torch_dtype="auto",
|
| 113 |
+
quantization_config=CompressedTensorsConfig(run_compressed=False),
|
| 114 |
+
)
|
| 115 |
+
output_decompressed = decompressed.generate(input_ids.to(decompressed.device), max_new_tokens=100)
|
| 116 |
+
|
| 117 |
+
self.assertEqual(
|
| 118 |
+
tokenizer.decode(output_uncompressed[0]),
|
| 119 |
+
tokenizer.decode(output_decompressed[0]),
|
| 120 |
+
"Generated outputs do not match between compressed and uncompressed models.",
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
def test_no_warnings_for_all_models(self):
|
| 124 |
+
"""
|
| 125 |
+
Confirm that loading any model using compressed tensors does not trigger
|
| 126 |
+
warnings about missing or unexpected keys.
|
| 127 |
+
"""
|
| 128 |
+
for model_stub in self.model_stubs:
|
| 129 |
+
with self.subTest(model_stub=model_stub):
|
| 130 |
+
with warnings.catch_warnings(record=True) as caught_warnings:
|
| 131 |
+
warnings.simplefilter("always")
|
| 132 |
+
AutoModelForCausalLM.from_pretrained(
|
| 133 |
+
model_stub,
|
| 134 |
+
device_map="auto",
|
| 135 |
+
torch_dtype="auto",
|
| 136 |
+
quantization_config=CompressedTensorsConfig(run_compressed=False),
|
| 137 |
+
)
|
| 138 |
+
for warning in caught_warnings:
|
| 139 |
+
self.assertNotIn(
|
| 140 |
+
"missing keys",
|
| 141 |
+
str(warning.message).lower(),
|
| 142 |
+
f"'missing keys' found in warnings for model {model_stub}",
|
| 143 |
+
)
|
| 144 |
+
self.assertNotIn(
|
| 145 |
+
"unexpected keys",
|
| 146 |
+
str(warning.message).lower(),
|
| 147 |
+
f"'unexpected keys' found in warnings for model {model_stub}",
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@require_compressed_tensors
|
| 152 |
+
@require_torch
|
| 153 |
+
class RunCompressedTest(unittest.TestCase):
|
| 154 |
+
tinyllama_w4a16 = "nm-testing/tinyllama-w4a16-compressed-hf-quantizer"
|
| 155 |
+
tinyllama_w8a8 = "nm-testing/tinyllama-w8a8-compressed-hf-quantizer"
|
| 156 |
+
|
| 157 |
+
prompt = "Paris is the capital of which country?"
|
| 158 |
+
|
| 159 |
+
stubs = [tinyllama_w4a16, tinyllama_w8a8]
|
| 160 |
+
|
| 161 |
+
def tearDown(self):
|
| 162 |
+
gc.collect()
|
| 163 |
+
backend_empty_cache(torch_device)
|
| 164 |
+
gc.collect()
|
| 165 |
+
|
| 166 |
+
def test_default_run_compressed__True(self):
|
| 167 |
+
from compressed_tensors.linear.compressed_linear import CompressedLinear
|
| 168 |
+
from compressed_tensors.quantization.utils import iter_named_leaf_modules
|
| 169 |
+
|
| 170 |
+
for stub in self.stubs:
|
| 171 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 172 |
+
stub,
|
| 173 |
+
)
|
| 174 |
+
compressed_linear_counts = 0
|
| 175 |
+
|
| 176 |
+
for _, submodule in iter_named_leaf_modules(
|
| 177 |
+
model,
|
| 178 |
+
):
|
| 179 |
+
if isinstance(submodule, CompressedLinear):
|
| 180 |
+
compressed_linear_counts += 1
|
| 181 |
+
|
| 182 |
+
# some linear models are not compressed - ex. lm_head
|
| 183 |
+
assert compressed_linear_counts > 0
|
| 184 |
+
|
| 185 |
+
def test_default_run_compressed__False(self):
|
| 186 |
+
from compressed_tensors.linear.compressed_linear import CompressedLinear
|
| 187 |
+
from compressed_tensors.quantization.utils import iter_named_leaf_modules
|
| 188 |
+
|
| 189 |
+
from transformers.utils.quantization_config import CompressedTensorsConfig
|
| 190 |
+
|
| 191 |
+
quantization_config = CompressedTensorsConfig(run_compressed=False)
|
| 192 |
+
|
| 193 |
+
for stub in self.stubs:
|
| 194 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 195 |
+
stub,
|
| 196 |
+
quantization_config=quantization_config,
|
| 197 |
+
)
|
| 198 |
+
compressed_linear_counts = 0
|
| 199 |
+
|
| 200 |
+
for _, submodule in iter_named_leaf_modules(
|
| 201 |
+
model,
|
| 202 |
+
):
|
| 203 |
+
if isinstance(submodule, CompressedLinear):
|
| 204 |
+
compressed_linear_counts += 1
|
| 205 |
+
|
| 206 |
+
# No modules should be CompressedLinear
|
| 207 |
+
assert compressed_linear_counts == 0
|
| 208 |
+
|
| 209 |
+
def test_run_compressed_outputs_match(self):
|
| 210 |
+
"""Check that run_compressed=True/False output are the same"""
|
| 211 |
+
|
| 212 |
+
from transformers import AutoTokenizer
|
| 213 |
+
from transformers.utils.quantization_config import CompressedTensorsConfig
|
| 214 |
+
|
| 215 |
+
quantization_config = CompressedTensorsConfig(run_compressed=False)
|
| 216 |
+
|
| 217 |
+
for stub in self.stubs:
|
| 218 |
+
tokenizer = AutoTokenizer.from_pretrained(stub)
|
| 219 |
+
input_ids = tokenizer(self.prompt, return_tensors="pt").input_ids
|
| 220 |
+
|
| 221 |
+
model_run_compressed__True = AutoModelForCausalLM.from_pretrained(
|
| 222 |
+
stub,
|
| 223 |
+
)
|
| 224 |
+
output_rc_true = model_run_compressed__True.generate(input_ids, max_new_tokens=100)
|
| 225 |
+
|
| 226 |
+
model_run_compressed__False = AutoModelForCausalLM.from_pretrained(
|
| 227 |
+
stub,
|
| 228 |
+
quantization_config=quantization_config,
|
| 229 |
+
)
|
| 230 |
+
output_rc_false = model_run_compressed__False.generate(input_ids, max_new_tokens=100)
|
| 231 |
+
|
| 232 |
+
assert tokenizer.decode(output_rc_true[0]) == tokenizer.decode(output_rc_false[0])
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/test_compressed_tensors.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, CompressedTensorsConfig
|
| 5 |
+
from transformers.testing_utils import backend_empty_cache, require_compressed_tensors, require_torch, torch_device
|
| 6 |
+
from transformers.utils import is_torch_available
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
if is_torch_available():
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@require_compressed_tensors
|
| 14 |
+
@require_torch
|
| 15 |
+
class CompressedTensorsTest(unittest.TestCase):
|
| 16 |
+
tinyllama_w8a16 = "nm-testing/tinyllama-w8a16-dense-hf-quantizer"
|
| 17 |
+
tinyllama_w4a16 = "nm-testing/tinyllama-w4a16-compressed-hf-quantizer"
|
| 18 |
+
tinyllama_w8a8 = "nm-testing/tinyllama-w8a8-compressed-hf-quantizer"
|
| 19 |
+
llama3_8b_fp8 = "nm-testing/Meta-Llama-3-8B-Instruct-fp8-hf_compat"
|
| 20 |
+
|
| 21 |
+
prompt = "Paris is the capital of which country?"
|
| 22 |
+
|
| 23 |
+
def tearDown(self):
|
| 24 |
+
gc.collect()
|
| 25 |
+
backend_empty_cache(torch_device)
|
| 26 |
+
gc.collect()
|
| 27 |
+
|
| 28 |
+
def test_config_args(self):
|
| 29 |
+
with self.assertRaises(ValueError):
|
| 30 |
+
# passing quant scheme directly is not allowed
|
| 31 |
+
CompressedTensorsConfig(config_groups={"weights": {"num_bits": 8}})
|
| 32 |
+
CompressedTensorsConfig(
|
| 33 |
+
config_groups={"FP8": ["Linear"]},
|
| 34 |
+
ignore=["lm_head"],
|
| 35 |
+
quantization_status="frozen",
|
| 36 |
+
sparsity_config={"format": "dense"},
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
def test_config_to_from_dict(self):
|
| 40 |
+
config = CompressedTensorsConfig(config_groups={"FP8": ["Linear"]}, sparsity_config={"format": "dense"})
|
| 41 |
+
config_dict = config.to_dict()
|
| 42 |
+
config_from_dict = CompressedTensorsConfig.from_dict(config_dict)
|
| 43 |
+
|
| 44 |
+
from compressed_tensors import QuantizationConfig, SparsityCompressionConfig
|
| 45 |
+
|
| 46 |
+
self.assertIsInstance(config_from_dict.quantization_config, QuantizationConfig)
|
| 47 |
+
self.assertIsInstance(config_from_dict.sparsity_config, SparsityCompressionConfig)
|
| 48 |
+
|
| 49 |
+
def test_tinyllama_w8a8(self):
|
| 50 |
+
expected_out = "<s> Paris is the capital of which country?\n\n 1. Paris is the capital of which country?\n\n 1. Paris is the capital of which country?\n\n 1. Paris is the capital of which country?\n\n"
|
| 51 |
+
self._test_quantized_model(self.tinyllama_w8a8, expected_out)
|
| 52 |
+
|
| 53 |
+
def test_tinyllama_w4a16(self):
|
| 54 |
+
expected_out = "<s> Paris is the capital of which country?\nAnswer: Paris is the capital of France.\nQuestion: Which country is the capital of which city?\nAnswer: The capital of the city of New York is New York.\nQuestion: Which"
|
| 55 |
+
self._test_quantized_model(self.tinyllama_w4a16, expected_out)
|
| 56 |
+
|
| 57 |
+
def test_tinyllama_w8a16(self):
|
| 58 |
+
expected_out = "<s> Paris is the capital of which country?\nA. France\nB. Germany\nC. Spain\nD. Italy\nE. Switzerland\nQ10. Which of the following is not a country in the European Union?\nA."
|
| 59 |
+
self._test_quantized_model(self.tinyllama_w8a16, expected_out)
|
| 60 |
+
|
| 61 |
+
def test_llama_8b_fp8(self):
|
| 62 |
+
expected_out = "<|begin_of_text|>Paris is the capital of which country? France\nWhat is the name of the famous museum in Paris that is home to the Mona Lisa? The Louvre\nWhat is the name of the famous bridge in Paris that is often associated with the city"
|
| 63 |
+
self._test_quantized_model(self.llama3_8b_fp8, expected_out)
|
| 64 |
+
|
| 65 |
+
def _test_quantized_model(self, model_name: str, expected_output: str):
|
| 66 |
+
"""Carry out generation"""
|
| 67 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto")
|
| 68 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 69 |
+
device = quantized_model.device
|
| 70 |
+
self.assertIsNotNone(
|
| 71 |
+
quantized_model.config.quantization_config,
|
| 72 |
+
"quantization_config should not be None",
|
| 73 |
+
)
|
| 74 |
+
self.assertTrue(
|
| 75 |
+
any(
|
| 76 |
+
key
|
| 77 |
+
for key, tensor in quantized_model.state_dict().items()
|
| 78 |
+
if "scale" in key and not torch.all(tensor == 1.0)
|
| 79 |
+
),
|
| 80 |
+
"quantized model should load a non-trivial scale into the state dict",
|
| 81 |
+
)
|
| 82 |
+
inputs = tokenizer(self.prompt, return_tensors="pt").to(device)
|
| 83 |
+
generated_ids = quantized_model.generate(**inputs, max_length=50, do_sample=False)
|
| 84 |
+
outputs = tokenizer.batch_decode(generated_ids)
|
| 85 |
+
|
| 86 |
+
self.assertIsNotNone(outputs)
|
| 87 |
+
self.assertEqual(outputs[0], expected_output)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/eetq_integration/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/eetq_integration/test_eetq.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import tempfile
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, EetqConfig, OPTForCausalLM
|
| 20 |
+
from transformers.testing_utils import (
|
| 21 |
+
backend_empty_cache,
|
| 22 |
+
require_accelerate,
|
| 23 |
+
require_eetq,
|
| 24 |
+
require_torch_gpu,
|
| 25 |
+
require_torch_multi_gpu,
|
| 26 |
+
slow,
|
| 27 |
+
torch_device,
|
| 28 |
+
)
|
| 29 |
+
from transformers.utils import is_accelerate_available, is_torch_available
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if is_torch_available():
|
| 33 |
+
import torch
|
| 34 |
+
|
| 35 |
+
if is_accelerate_available():
|
| 36 |
+
from accelerate import init_empty_weights
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@require_torch_gpu
|
| 40 |
+
class EetqConfigTest(unittest.TestCase):
|
| 41 |
+
def test_to_dict(self):
|
| 42 |
+
"""
|
| 43 |
+
Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object
|
| 44 |
+
"""
|
| 45 |
+
quantization_config = EetqConfig()
|
| 46 |
+
config_to_dict = quantization_config.to_dict()
|
| 47 |
+
|
| 48 |
+
for key in config_to_dict:
|
| 49 |
+
self.assertEqual(getattr(quantization_config, key), config_to_dict[key])
|
| 50 |
+
|
| 51 |
+
def test_from_dict(self):
|
| 52 |
+
"""
|
| 53 |
+
Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict
|
| 54 |
+
"""
|
| 55 |
+
dict = {"modules_to_not_convert": ["lm_head.weight"], "quant_method": "eetq", "weights": "int8"}
|
| 56 |
+
quantization_config = EetqConfig.from_dict(dict)
|
| 57 |
+
|
| 58 |
+
self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert)
|
| 59 |
+
self.assertEqual(dict["quant_method"], quantization_config.quant_method)
|
| 60 |
+
self.assertEqual(dict["weights"], quantization_config.weights)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@slow
|
| 64 |
+
@require_torch_gpu
|
| 65 |
+
@require_eetq
|
| 66 |
+
@require_accelerate
|
| 67 |
+
class EetqTest(unittest.TestCase):
|
| 68 |
+
model_name = "facebook/opt-350m"
|
| 69 |
+
|
| 70 |
+
input_text = "What are we having for dinner?"
|
| 71 |
+
max_new_tokens = 9
|
| 72 |
+
|
| 73 |
+
EXPECTED_OUTPUT = "What are we having for dinner?\nI'm having a steak and a salad"
|
| 74 |
+
|
| 75 |
+
device_map = "cuda"
|
| 76 |
+
|
| 77 |
+
# called only once for all test in this class
|
| 78 |
+
@classmethod
|
| 79 |
+
def setUpClass(cls):
|
| 80 |
+
"""
|
| 81 |
+
Setup quantized model
|
| 82 |
+
"""
|
| 83 |
+
quantization_config = EetqConfig(weights="int8")
|
| 84 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name)
|
| 85 |
+
cls.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 86 |
+
cls.model_name, device_map=cls.device_map, quantization_config=quantization_config
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
def tearDown(self):
|
| 90 |
+
gc.collect()
|
| 91 |
+
backend_empty_cache(torch_device)
|
| 92 |
+
gc.collect()
|
| 93 |
+
|
| 94 |
+
def test_quantized_model_conversion(self):
|
| 95 |
+
"""
|
| 96 |
+
Simple test that checks if the quantized model has been converted properly
|
| 97 |
+
"""
|
| 98 |
+
from eetq import EetqLinear
|
| 99 |
+
|
| 100 |
+
from transformers.integrations import replace_with_eetq_linear
|
| 101 |
+
|
| 102 |
+
model_id = "facebook/opt-350m"
|
| 103 |
+
config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5")
|
| 104 |
+
quantization_config = EetqConfig(weights="int8")
|
| 105 |
+
|
| 106 |
+
with init_empty_weights():
|
| 107 |
+
model = OPTForCausalLM(config)
|
| 108 |
+
|
| 109 |
+
nb_linears = 0
|
| 110 |
+
for module in model.modules():
|
| 111 |
+
if isinstance(module, torch.nn.Linear):
|
| 112 |
+
nb_linears += 1
|
| 113 |
+
|
| 114 |
+
model = replace_with_eetq_linear(model, quantization_config=quantization_config)
|
| 115 |
+
nb_eetq_linear = 0
|
| 116 |
+
for module in model.modules():
|
| 117 |
+
if isinstance(module, EetqLinear):
|
| 118 |
+
nb_eetq_linear += 1
|
| 119 |
+
|
| 120 |
+
self.assertEqual(nb_linears - 1, nb_eetq_linear)
|
| 121 |
+
|
| 122 |
+
# Try with `modules_to_not_convert`
|
| 123 |
+
with init_empty_weights():
|
| 124 |
+
model = OPTForCausalLM(config)
|
| 125 |
+
quantization_config = EetqConfig(modules_to_not_convert=["fc1"])
|
| 126 |
+
model = replace_with_eetq_linear(model, quantization_config=quantization_config)
|
| 127 |
+
nb_eetq_linear = 0
|
| 128 |
+
for module in model.modules():
|
| 129 |
+
if isinstance(module, EetqLinear):
|
| 130 |
+
nb_eetq_linear += 1
|
| 131 |
+
# 25 corresponds to the lm_head along with 24 fc1 layers.
|
| 132 |
+
self.assertEqual(nb_linears - 25, nb_eetq_linear)
|
| 133 |
+
|
| 134 |
+
def test_quantized_model(self):
|
| 135 |
+
"""
|
| 136 |
+
Simple test that checks if the quantized model is working properly
|
| 137 |
+
"""
|
| 138 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 139 |
+
|
| 140 |
+
output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 141 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 142 |
+
|
| 143 |
+
def test_save_pretrained(self):
|
| 144 |
+
"""
|
| 145 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 146 |
+
"""
|
| 147 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 148 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 149 |
+
|
| 150 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map)
|
| 151 |
+
|
| 152 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 153 |
+
|
| 154 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 155 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 156 |
+
|
| 157 |
+
@require_torch_multi_gpu
|
| 158 |
+
def test_quantized_model_multi_gpu(self):
|
| 159 |
+
"""
|
| 160 |
+
Simple test that checks if the quantized model is working properly with multiple GPUs
|
| 161 |
+
set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs
|
| 162 |
+
"""
|
| 163 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 164 |
+
quantization_config = EetqConfig()
|
| 165 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 166 |
+
self.model_name, device_map="auto", quantization_config=quantization_config
|
| 167 |
+
)
|
| 168 |
+
self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1})
|
| 169 |
+
|
| 170 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 171 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fbgemm_fp8/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fbgemm_fp8/test_fbgemm_fp8.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import tempfile
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, FbgemmFp8Config, OPTForCausalLM
|
| 20 |
+
from transformers.testing_utils import (
|
| 21 |
+
backend_empty_cache,
|
| 22 |
+
require_accelerate,
|
| 23 |
+
require_fbgemm_gpu,
|
| 24 |
+
require_read_token,
|
| 25 |
+
require_torch_gpu,
|
| 26 |
+
require_torch_multi_gpu,
|
| 27 |
+
slow,
|
| 28 |
+
torch_device,
|
| 29 |
+
)
|
| 30 |
+
from transformers.utils import is_accelerate_available, is_torch_available
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if is_torch_available():
|
| 34 |
+
import torch
|
| 35 |
+
|
| 36 |
+
if is_accelerate_available():
|
| 37 |
+
from accelerate import init_empty_weights
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@require_torch_gpu
|
| 41 |
+
class FbgemmFp8ConfigTest(unittest.TestCase):
|
| 42 |
+
def test_to_dict(self):
|
| 43 |
+
"""
|
| 44 |
+
Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object
|
| 45 |
+
"""
|
| 46 |
+
quantization_config = FbgemmFp8Config()
|
| 47 |
+
config_to_dict = quantization_config.to_dict()
|
| 48 |
+
|
| 49 |
+
for key in config_to_dict:
|
| 50 |
+
self.assertEqual(getattr(quantization_config, key), config_to_dict[key])
|
| 51 |
+
|
| 52 |
+
def test_from_dict(self):
|
| 53 |
+
"""
|
| 54 |
+
Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict
|
| 55 |
+
"""
|
| 56 |
+
dict = {"modules_to_not_convert": ["lm_head.weight"], "quant_method": "fbgemm_fp8"}
|
| 57 |
+
quantization_config = FbgemmFp8Config.from_dict(dict)
|
| 58 |
+
|
| 59 |
+
self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert)
|
| 60 |
+
self.assertEqual(dict["quant_method"], quantization_config.quant_method)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@slow
|
| 64 |
+
@require_torch_gpu
|
| 65 |
+
@require_fbgemm_gpu
|
| 66 |
+
@require_accelerate
|
| 67 |
+
@require_read_token
|
| 68 |
+
class FbgemmFp8Test(unittest.TestCase):
|
| 69 |
+
model_name = "meta-llama/Meta-Llama-3-8B"
|
| 70 |
+
|
| 71 |
+
input_text = "What are we having for dinner?"
|
| 72 |
+
max_new_tokens = 9
|
| 73 |
+
|
| 74 |
+
EXPECTED_OUTPUT = "What are we having for dinner?\nI'm having a steak and a salad"
|
| 75 |
+
|
| 76 |
+
device_map = "cuda"
|
| 77 |
+
|
| 78 |
+
offload_device_map = {
|
| 79 |
+
"model.embed_tokens": 0,
|
| 80 |
+
"model.layers.0": 0,
|
| 81 |
+
"model.layers.1": 0,
|
| 82 |
+
"model.layers.2": 0,
|
| 83 |
+
"model.layers.3": 0,
|
| 84 |
+
"model.layers.4": 0,
|
| 85 |
+
"model.layers.5": 0,
|
| 86 |
+
"model.layers.6": 0,
|
| 87 |
+
"model.layers.7": 0,
|
| 88 |
+
"model.layers.8": 0,
|
| 89 |
+
"model.layers.9": 0,
|
| 90 |
+
"model.layers.10": 0,
|
| 91 |
+
"model.layers.11": 0,
|
| 92 |
+
"model.layers.12": 0,
|
| 93 |
+
"model.layers.13": 0,
|
| 94 |
+
"model.layers.14": 0,
|
| 95 |
+
"model.layers.15": 0,
|
| 96 |
+
"model.layers.16": "cpu",
|
| 97 |
+
"model.layers.17": "cpu",
|
| 98 |
+
"model.layers.18": "cpu",
|
| 99 |
+
"model.layers.19": "cpu",
|
| 100 |
+
"model.layers.20": "disk",
|
| 101 |
+
"model.layers.21": "disk",
|
| 102 |
+
"model.layers.22": "disk",
|
| 103 |
+
"model.layers.23": "disk",
|
| 104 |
+
"model.layers.24": "disk",
|
| 105 |
+
"model.layers.25": "disk",
|
| 106 |
+
"model.layers.26": "disk",
|
| 107 |
+
"model.layers.27": "disk",
|
| 108 |
+
"model.layers.28": "disk",
|
| 109 |
+
"model.layers.29": "disk",
|
| 110 |
+
"model.layers.30": "disk",
|
| 111 |
+
"model.layers.31": "disk",
|
| 112 |
+
"model.norm": "disk",
|
| 113 |
+
"lm_head": "disk",
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
# called only once for all test in this class
|
| 117 |
+
@classmethod
|
| 118 |
+
def setUpClass(cls):
|
| 119 |
+
"""
|
| 120 |
+
Setup quantized model
|
| 121 |
+
"""
|
| 122 |
+
quantization_config = FbgemmFp8Config()
|
| 123 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name)
|
| 124 |
+
cls.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 125 |
+
cls.model_name, device_map=cls.device_map, quantization_config=quantization_config
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
def tearDown(self):
|
| 129 |
+
gc.collect()
|
| 130 |
+
backend_empty_cache(torch_device)
|
| 131 |
+
gc.collect()
|
| 132 |
+
|
| 133 |
+
def test_quantized_model_conversion(self):
|
| 134 |
+
"""
|
| 135 |
+
Simple test that checks if the quantized model has been converted properly
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
from transformers.integrations import FbgemmFp8Linear, replace_with_fbgemm_fp8_linear
|
| 139 |
+
|
| 140 |
+
model_id = "facebook/opt-350m"
|
| 141 |
+
config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5")
|
| 142 |
+
quantization_config = FbgemmFp8Config()
|
| 143 |
+
|
| 144 |
+
with init_empty_weights():
|
| 145 |
+
model = OPTForCausalLM(config)
|
| 146 |
+
|
| 147 |
+
nb_linears = 0
|
| 148 |
+
for module in model.modules():
|
| 149 |
+
if isinstance(module, torch.nn.Linear):
|
| 150 |
+
nb_linears += 1
|
| 151 |
+
|
| 152 |
+
model = replace_with_fbgemm_fp8_linear(model, quantization_config=quantization_config)
|
| 153 |
+
nb_fbgemm_linear = 0
|
| 154 |
+
for module in model.modules():
|
| 155 |
+
if isinstance(module, FbgemmFp8Linear):
|
| 156 |
+
nb_fbgemm_linear += 1
|
| 157 |
+
|
| 158 |
+
self.assertEqual(nb_linears - 1, nb_fbgemm_linear)
|
| 159 |
+
|
| 160 |
+
with init_empty_weights():
|
| 161 |
+
model = OPTForCausalLM(config)
|
| 162 |
+
quantization_config = FbgemmFp8Config(modules_to_not_convert=["fc1"])
|
| 163 |
+
model = replace_with_fbgemm_fp8_linear(model, quantization_config=quantization_config)
|
| 164 |
+
nb_fbgemm_linear = 0
|
| 165 |
+
for module in model.modules():
|
| 166 |
+
if isinstance(module, FbgemmFp8Linear):
|
| 167 |
+
nb_fbgemm_linear += 1
|
| 168 |
+
|
| 169 |
+
self.assertEqual(nb_linears - 25, nb_fbgemm_linear)
|
| 170 |
+
|
| 171 |
+
def test_quantized_model(self):
|
| 172 |
+
"""
|
| 173 |
+
Simple test that checks if the quantized model is working properly
|
| 174 |
+
"""
|
| 175 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 176 |
+
|
| 177 |
+
output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 178 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 179 |
+
|
| 180 |
+
def test_save_pretrained(self):
|
| 181 |
+
"""
|
| 182 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 183 |
+
"""
|
| 184 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 185 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 186 |
+
|
| 187 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map)
|
| 188 |
+
|
| 189 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 190 |
+
|
| 191 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 192 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 193 |
+
|
| 194 |
+
def test_change_loading_attributes(self):
|
| 195 |
+
"""
|
| 196 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 197 |
+
"""
|
| 198 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 199 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 200 |
+
|
| 201 |
+
quantization_config = FbgemmFp8Config(activation_scale_ub=1000.0)
|
| 202 |
+
|
| 203 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 204 |
+
tmpdirname, device_map=self.device_map, quantization_config=quantization_config
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
self.assertEqual(model.model.layers[1].mlp.down_proj.input_scale_ub.item(), 1000.0)
|
| 208 |
+
|
| 209 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 210 |
+
|
| 211 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 212 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 213 |
+
|
| 214 |
+
@require_torch_multi_gpu
|
| 215 |
+
def test_quantized_model_multi_gpu(self):
|
| 216 |
+
"""
|
| 217 |
+
Simple test that checks if the quantized model is working properly with multiple GPUs
|
| 218 |
+
set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs
|
| 219 |
+
"""
|
| 220 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 221 |
+
quantization_config = FbgemmFp8Config()
|
| 222 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 223 |
+
self.model_name, device_map="auto", quantization_config=quantization_config
|
| 224 |
+
)
|
| 225 |
+
self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1})
|
| 226 |
+
|
| 227 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 228 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 229 |
+
|
| 230 |
+
def test_quantized_model_offload(self):
|
| 231 |
+
"""
|
| 232 |
+
Simple test that checks if the quantized model returns an error when loading with cpu/disk offloaded
|
| 233 |
+
"""
|
| 234 |
+
quantization_config = FbgemmFp8Config()
|
| 235 |
+
|
| 236 |
+
with self.assertRaisesRegex(
|
| 237 |
+
ValueError, "You are attempting to load an FP8 model with a device_map that contains a CPU or disk device."
|
| 238 |
+
):
|
| 239 |
+
AutoModelForCausalLM.from_pretrained(
|
| 240 |
+
self.model_name, device_map=self.offload_device_map, quantization_config=quantization_config
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
def test_save_pretrained_offload(self):
|
| 244 |
+
"""
|
| 245 |
+
Simple test that checks if the saved quantized model is working properly cpu/disk offload
|
| 246 |
+
"""
|
| 247 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 248 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 249 |
+
|
| 250 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 251 |
+
|
| 252 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.offload_device_map)
|
| 253 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 254 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 255 |
+
|
| 256 |
+
@require_torch_multi_gpu
|
| 257 |
+
def test_save_pretrained_multi_gpu(self):
|
| 258 |
+
"""
|
| 259 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 260 |
+
"""
|
| 261 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 262 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 263 |
+
|
| 264 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="auto")
|
| 265 |
+
self.assertTrue(set(model.hf_device_map.values()) == {0, 1})
|
| 266 |
+
|
| 267 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 268 |
+
|
| 269 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 270 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
@require_torch_gpu
|
| 274 |
+
@require_accelerate
|
| 275 |
+
@require_fbgemm_gpu
|
| 276 |
+
class FbgemmFp8LinearTest(unittest.TestCase):
|
| 277 |
+
def test_linear_preserves_shape(self):
|
| 278 |
+
"""
|
| 279 |
+
Test that FbgemmFp8Linear preserves shape when in_features == out_features.
|
| 280 |
+
"""
|
| 281 |
+
from transformers.integrations import FbgemmFp8Linear
|
| 282 |
+
|
| 283 |
+
with init_empty_weights(include_buffers=True):
|
| 284 |
+
linear = FbgemmFp8Linear(1024, 1024, True)
|
| 285 |
+
x = torch.rand((17, 23, 1024))
|
| 286 |
+
|
| 287 |
+
x_ = linear(x)
|
| 288 |
+
self.assertEqual(x_.shape, x.shape)
|
| 289 |
+
|
| 290 |
+
def test_linear_with_diff_feature_size_preserves_shape(self):
|
| 291 |
+
"""
|
| 292 |
+
Test that FbgemmFp8Linear generates the correct shape when in_features != out_features.
|
| 293 |
+
"""
|
| 294 |
+
from transformers.integrations import FbgemmFp8Linear
|
| 295 |
+
|
| 296 |
+
with init_empty_weights(include_buffers=True):
|
| 297 |
+
linear = FbgemmFp8Linear(1024, 2048, True)
|
| 298 |
+
x = torch.rand((17, 23, 1024))
|
| 299 |
+
|
| 300 |
+
x_ = linear(x)
|
| 301 |
+
self.assertEqual(x_.shape, (17, 23, 2048))
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/finegrained_fp8/__init__.py
ADDED
|
File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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import tempfile
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, FineGrainedFP8Config, OPTForCausalLM
|
| 20 |
+
from transformers.testing_utils import (
|
| 21 |
+
backend_empty_cache,
|
| 22 |
+
get_device_properties,
|
| 23 |
+
require_accelerate,
|
| 24 |
+
require_read_token,
|
| 25 |
+
require_torch_accelerator,
|
| 26 |
+
require_torch_multi_accelerator,
|
| 27 |
+
slow,
|
| 28 |
+
torch_device,
|
| 29 |
+
)
|
| 30 |
+
from transformers.utils import is_accelerate_available, is_torch_available
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if is_torch_available():
|
| 34 |
+
import torch
|
| 35 |
+
|
| 36 |
+
if is_accelerate_available():
|
| 37 |
+
from accelerate import init_empty_weights
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@require_torch_accelerator
|
| 41 |
+
class FineGrainedFP8ConfigTest(unittest.TestCase):
|
| 42 |
+
def test_to_dict(self):
|
| 43 |
+
"""
|
| 44 |
+
Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object
|
| 45 |
+
"""
|
| 46 |
+
quantization_config = FineGrainedFP8Config()
|
| 47 |
+
config_to_dict = quantization_config.to_dict()
|
| 48 |
+
|
| 49 |
+
for key in config_to_dict:
|
| 50 |
+
self.assertEqual(getattr(quantization_config, key), config_to_dict[key])
|
| 51 |
+
|
| 52 |
+
def test_from_dict(self):
|
| 53 |
+
"""
|
| 54 |
+
Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict
|
| 55 |
+
"""
|
| 56 |
+
dict = {"modules_to_not_convert": ["lm_head.weight"], "quant_method": "fp8"}
|
| 57 |
+
quantization_config = FineGrainedFP8Config.from_dict(dict)
|
| 58 |
+
|
| 59 |
+
self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert)
|
| 60 |
+
self.assertEqual(dict["quant_method"], quantization_config.quant_method)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@slow
|
| 64 |
+
@require_accelerate
|
| 65 |
+
@require_read_token
|
| 66 |
+
@require_torch_accelerator
|
| 67 |
+
class FP8QuantizerTest(unittest.TestCase):
|
| 68 |
+
model_name = "meta-llama/Llama-3.2-1B"
|
| 69 |
+
input_text = "Once upon a time"
|
| 70 |
+
max_new_tokens = 10
|
| 71 |
+
EXPECTED_OUTPUT = "Once upon a time, there was a man who was very rich."
|
| 72 |
+
device_map = torch_device
|
| 73 |
+
offload_device_map = {
|
| 74 |
+
"model.embed_tokens": 0,
|
| 75 |
+
"model.layers.0": 0,
|
| 76 |
+
"model.layers.1": 0,
|
| 77 |
+
"model.layers.2": 0,
|
| 78 |
+
"model.layers.3": 0,
|
| 79 |
+
"model.layers.4": 0,
|
| 80 |
+
"model.layers.5": 0,
|
| 81 |
+
"model.layers.6": 0,
|
| 82 |
+
"model.layers.7": "cpu",
|
| 83 |
+
"model.layers.8": "cpu",
|
| 84 |
+
"model.layers.9": "cpu",
|
| 85 |
+
"model.layers.10": "cpu",
|
| 86 |
+
"model.layers.11": "cpu",
|
| 87 |
+
"model.layers.12": "cpu",
|
| 88 |
+
"model.layers.13": "cpu",
|
| 89 |
+
"model.layers.14": "cpu",
|
| 90 |
+
"model.layers.15": "cpu",
|
| 91 |
+
"model.rotary_emb": "disk",
|
| 92 |
+
"model.norm": "disk",
|
| 93 |
+
"lm_head": 0,
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
@classmethod
|
| 97 |
+
def setUpClass(cls):
|
| 98 |
+
"""
|
| 99 |
+
Setup quantized model
|
| 100 |
+
"""
|
| 101 |
+
cls.quantization_config = FineGrainedFP8Config()
|
| 102 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name)
|
| 103 |
+
cls.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 104 |
+
cls.model_name, device_map=cls.device_map, quantization_config=cls.quantization_config
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
def tearDown(self):
|
| 108 |
+
gc.collect()
|
| 109 |
+
backend_empty_cache(torch_device)
|
| 110 |
+
gc.collect()
|
| 111 |
+
|
| 112 |
+
def test_quantized_model_conversion(self):
|
| 113 |
+
"""
|
| 114 |
+
Simple test that checks if the quantized model has been converted properly
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
from transformers.integrations import FP8Linear, replace_with_fp8_linear
|
| 118 |
+
|
| 119 |
+
model_id = "facebook/opt-350m"
|
| 120 |
+
config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5")
|
| 121 |
+
quantization_config = FineGrainedFP8Config()
|
| 122 |
+
|
| 123 |
+
with init_empty_weights():
|
| 124 |
+
model = OPTForCausalLM(config)
|
| 125 |
+
|
| 126 |
+
nb_linears = 0
|
| 127 |
+
for module in model.modules():
|
| 128 |
+
if isinstance(module, torch.nn.Linear):
|
| 129 |
+
nb_linears += 1
|
| 130 |
+
|
| 131 |
+
model = replace_with_fp8_linear(model, quantization_config=quantization_config)
|
| 132 |
+
nb_fp8_linear = 0
|
| 133 |
+
for module in model.modules():
|
| 134 |
+
if isinstance(module, FP8Linear):
|
| 135 |
+
nb_fp8_linear += 1
|
| 136 |
+
|
| 137 |
+
self.assertEqual(nb_linears - 1, nb_fp8_linear)
|
| 138 |
+
|
| 139 |
+
with init_empty_weights():
|
| 140 |
+
model = OPTForCausalLM(config)
|
| 141 |
+
quantization_config = FineGrainedFP8Config(modules_to_not_convert=["fc1"])
|
| 142 |
+
model = replace_with_fp8_linear(model, quantization_config=quantization_config)
|
| 143 |
+
nb_fp8_linear = 0
|
| 144 |
+
for module in model.modules():
|
| 145 |
+
if isinstance(module, FP8Linear):
|
| 146 |
+
nb_fp8_linear += 1
|
| 147 |
+
|
| 148 |
+
self.assertEqual(nb_linears - 25, nb_fp8_linear)
|
| 149 |
+
|
| 150 |
+
def test_quantized_model(self):
|
| 151 |
+
"""
|
| 152 |
+
Simple test that checks if the quantized model is working properly
|
| 153 |
+
"""
|
| 154 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device_map)
|
| 155 |
+
|
| 156 |
+
output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False)
|
| 157 |
+
output_tokens = self.tokenizer.decode(output[0], skip_special_tokens=True)
|
| 158 |
+
self.assertEqual(output_tokens, self.EXPECTED_OUTPUT)
|
| 159 |
+
|
| 160 |
+
def test_save_pretrained(self):
|
| 161 |
+
"""
|
| 162 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 163 |
+
"""
|
| 164 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 165 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 166 |
+
|
| 167 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map)
|
| 168 |
+
|
| 169 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device_map)
|
| 170 |
+
|
| 171 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False)
|
| 172 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 173 |
+
|
| 174 |
+
def test_weight_and_weight_scale_inv(self):
|
| 175 |
+
"""
|
| 176 |
+
Simple test that checks if the weight and weight_scale_inv are working properly
|
| 177 |
+
"""
|
| 178 |
+
weight = self.quantized_model.model.layers[0].self_attn.q_proj.weight
|
| 179 |
+
weight_scale_inv = self.quantized_model.model.layers[0].self_attn.q_proj.weight_scale_inv
|
| 180 |
+
self.assertEqual(weight.dtype, torch.float8_e4m3fn)
|
| 181 |
+
self.assertEqual(weight_scale_inv.dtype, torch.float32)
|
| 182 |
+
self.assertEqual(weight.shape, (weight_scale_inv.shape[0] * 128, weight_scale_inv.shape[1] * 128))
|
| 183 |
+
|
| 184 |
+
def test_block_size(self):
|
| 185 |
+
"""
|
| 186 |
+
Simple test that checks if the block size is working properly
|
| 187 |
+
"""
|
| 188 |
+
self.assertEqual(self.quantized_model.config.quantization_config.weight_block_size, (128, 128))
|
| 189 |
+
quantization_config = FineGrainedFP8Config(weight_block_size=(32, 32))
|
| 190 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 191 |
+
self.model_name, device_map=self.device_map, quantization_config=quantization_config
|
| 192 |
+
)
|
| 193 |
+
self.assertEqual(quantized_model.config.quantization_config.weight_block_size, (32, 32))
|
| 194 |
+
|
| 195 |
+
@require_torch_multi_accelerator
|
| 196 |
+
def test_quantized_model_multi_accelerator(self):
|
| 197 |
+
"""
|
| 198 |
+
Simple test that checks if the quantized model is working properly with multiple accelerators
|
| 199 |
+
set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs; or set ZE_AFFINITY_MASK=0,1 if you
|
| 200 |
+
have more than 2 XPUs.
|
| 201 |
+
"""
|
| 202 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device_map)
|
| 203 |
+
quantization_config = FineGrainedFP8Config()
|
| 204 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 205 |
+
self.model_name, device_map="auto", quantization_config=quantization_config
|
| 206 |
+
)
|
| 207 |
+
self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1})
|
| 208 |
+
|
| 209 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False)
|
| 210 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 211 |
+
|
| 212 |
+
@require_torch_multi_accelerator
|
| 213 |
+
def test_save_pretrained_multi_accelerators(self):
|
| 214 |
+
"""
|
| 215 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 216 |
+
"""
|
| 217 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 218 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 219 |
+
|
| 220 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="auto")
|
| 221 |
+
self.assertTrue(set(model.hf_device_map.values()) == {0, 1})
|
| 222 |
+
|
| 223 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device_map)
|
| 224 |
+
|
| 225 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False)
|
| 226 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 227 |
+
|
| 228 |
+
def test_quantized_model_offload(self):
|
| 229 |
+
"""
|
| 230 |
+
Simple test that checks if the quantized model returns an error when loading with cpu/disk offloaded
|
| 231 |
+
"""
|
| 232 |
+
with self.assertRaisesRegex(
|
| 233 |
+
ValueError, "You are attempting to load an FP8 model with a device_map that contains a cpu/disk device."
|
| 234 |
+
):
|
| 235 |
+
AutoModelForCausalLM.from_pretrained(
|
| 236 |
+
self.model_name, device_map=self.offload_device_map, quantization_config=self.quantization_config
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
def test_save_pretrained_offload(self):
|
| 240 |
+
"""
|
| 241 |
+
Simple test that checks if the saved quantized model is working properly cpu/disk offload
|
| 242 |
+
"""
|
| 243 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 244 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 245 |
+
|
| 246 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device_map)
|
| 247 |
+
|
| 248 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.offload_device_map)
|
| 249 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False)
|
| 250 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
@require_torch_accelerator
|
| 254 |
+
class FP8LinearTest(unittest.TestCase):
|
| 255 |
+
device = torch_device
|
| 256 |
+
|
| 257 |
+
@unittest.skipIf(
|
| 258 |
+
get_device_properties()[0] == "cuda" and get_device_properties()[1] < 9,
|
| 259 |
+
"Skipping FP8LinearTest because it is not supported on GPU with capability < 9.0",
|
| 260 |
+
)
|
| 261 |
+
def test_linear_preserves_shape(self):
|
| 262 |
+
"""
|
| 263 |
+
Test that FP8Linear preserves shape when in_features == out_features.
|
| 264 |
+
"""
|
| 265 |
+
from transformers.integrations import FP8Linear
|
| 266 |
+
|
| 267 |
+
linear = FP8Linear(256, 256, block_size=(128, 128), device=self.device)
|
| 268 |
+
x = torch.rand((1, 5, 256)).to(self.device)
|
| 269 |
+
|
| 270 |
+
x_ = linear(x)
|
| 271 |
+
self.assertEqual(x_.shape, x.shape)
|
| 272 |
+
|
| 273 |
+
@unittest.skipIf(
|
| 274 |
+
get_device_properties()[0] == "cuda" and get_device_properties()[1] < 9,
|
| 275 |
+
"Skipping FP8LinearTest because it is not supported on GPU with capability < 9.0",
|
| 276 |
+
)
|
| 277 |
+
def test_linear_with_diff_feature_size_preserves_shape(self):
|
| 278 |
+
"""
|
| 279 |
+
Test that FP8Linear generates the correct shape when in_features != out_features.
|
| 280 |
+
"""
|
| 281 |
+
from transformers.integrations import FP8Linear
|
| 282 |
+
|
| 283 |
+
linear = FP8Linear(128, 256, block_size=(128, 128), device=self.device)
|
| 284 |
+
x = torch.rand((1, 5, 128)).to(self.device)
|
| 285 |
+
|
| 286 |
+
x_ = linear(x)
|
| 287 |
+
self.assertEqual(x_.shape, (1, 5, 256))
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fp_quant_integration/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fp_quant_integration/test_fp_quant.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import tempfile
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, FPQuantConfig
|
| 20 |
+
from transformers.testing_utils import (
|
| 21 |
+
backend_empty_cache,
|
| 22 |
+
require_accelerate,
|
| 23 |
+
require_fp_quant,
|
| 24 |
+
require_qutlass,
|
| 25 |
+
require_torch_gpu,
|
| 26 |
+
require_torch_multi_gpu,
|
| 27 |
+
slow,
|
| 28 |
+
torch_device,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@require_torch_gpu
|
| 33 |
+
class FPQuantConfigTest(unittest.TestCase):
|
| 34 |
+
def test_to_dict(self):
|
| 35 |
+
"""
|
| 36 |
+
Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object
|
| 37 |
+
"""
|
| 38 |
+
quantization_config = FPQuantConfig()
|
| 39 |
+
config_to_dict = quantization_config.to_dict()
|
| 40 |
+
|
| 41 |
+
for key in config_to_dict:
|
| 42 |
+
self.assertEqual(getattr(quantization_config, key), config_to_dict[key])
|
| 43 |
+
|
| 44 |
+
def test_from_dict(self):
|
| 45 |
+
"""
|
| 46 |
+
Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict
|
| 47 |
+
"""
|
| 48 |
+
dict = {"modules_to_not_convert": ["embed_tokens", "lm_head"], "quant_method": "fp_quant"}
|
| 49 |
+
quantization_config = FPQuantConfig.from_dict(dict)
|
| 50 |
+
|
| 51 |
+
self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert)
|
| 52 |
+
self.assertEqual(dict["quant_method"], quantization_config.quant_method)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@slow
|
| 56 |
+
@require_torch_gpu
|
| 57 |
+
@require_fp_quant
|
| 58 |
+
@require_qutlass
|
| 59 |
+
@require_accelerate
|
| 60 |
+
class FPQuantTest(unittest.TestCase):
|
| 61 |
+
model_name = "unsloth/Llama-3.2-1B"
|
| 62 |
+
|
| 63 |
+
input_text = "1 2 3 4"
|
| 64 |
+
max_new_tokens = 4
|
| 65 |
+
|
| 66 |
+
EXPECTED_OUTPUT = "1 2 3 4 5 6"
|
| 67 |
+
|
| 68 |
+
device_map = "cuda"
|
| 69 |
+
|
| 70 |
+
# called only once for all test in this class
|
| 71 |
+
@classmethod
|
| 72 |
+
def setUpClass(cls):
|
| 73 |
+
"""
|
| 74 |
+
Setup quantized model
|
| 75 |
+
"""
|
| 76 |
+
quantization_config = FPQuantConfig(pseudoquantization=False)
|
| 77 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name)
|
| 78 |
+
cls.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 79 |
+
cls.model_name, device_map=cls.device_map, quantization_config=quantization_config
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
def tearDown(self):
|
| 83 |
+
gc.collect()
|
| 84 |
+
backend_empty_cache(torch_device)
|
| 85 |
+
gc.collect()
|
| 86 |
+
|
| 87 |
+
def test_quantized_model(self):
|
| 88 |
+
"""
|
| 89 |
+
Simple test that checks if the quantized model is working properly
|
| 90 |
+
"""
|
| 91 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 92 |
+
|
| 93 |
+
output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 94 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 95 |
+
|
| 96 |
+
def test_save_pretrained(self):
|
| 97 |
+
"""
|
| 98 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 99 |
+
"""
|
| 100 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 101 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 102 |
+
|
| 103 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map)
|
| 104 |
+
|
| 105 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 106 |
+
|
| 107 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 108 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 109 |
+
|
| 110 |
+
@require_torch_multi_gpu
|
| 111 |
+
def test_quantized_model_multi_gpu(self):
|
| 112 |
+
"""
|
| 113 |
+
Simple test that checks if the quantized model is working properly with multiple GPUs
|
| 114 |
+
set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs
|
| 115 |
+
"""
|
| 116 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 117 |
+
quantization_config = FPQuantConfig()
|
| 118 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 119 |
+
self.model_name, device_map="auto", quantization_config=quantization_config
|
| 120 |
+
)
|
| 121 |
+
self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1})
|
| 122 |
+
|
| 123 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 124 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 125 |
+
|
| 126 |
+
@require_torch_multi_gpu
|
| 127 |
+
def test_save_pretrained_multi_gpu(self):
|
| 128 |
+
"""
|
| 129 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 130 |
+
"""
|
| 131 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 132 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 133 |
+
|
| 134 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="auto")
|
| 135 |
+
self.assertTrue(set(model.hf_device_map.values()) == {0, 1})
|
| 136 |
+
|
| 137 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 138 |
+
|
| 139 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 140 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@slow
|
| 144 |
+
@require_torch_gpu
|
| 145 |
+
@require_fp_quant
|
| 146 |
+
@require_accelerate
|
| 147 |
+
class FPQuantPseudoquantTest(unittest.TestCase):
|
| 148 |
+
model_name = "unsloth/Llama-3.2-1B"
|
| 149 |
+
|
| 150 |
+
input_text = "1 2 3 4"
|
| 151 |
+
max_new_tokens = 4
|
| 152 |
+
|
| 153 |
+
EXPECTED_OUTPUT = "1 2 3 4 5 6"
|
| 154 |
+
|
| 155 |
+
device_map = "cuda"
|
| 156 |
+
|
| 157 |
+
# called only once for all test in this class
|
| 158 |
+
@classmethod
|
| 159 |
+
def setUpClass(cls):
|
| 160 |
+
"""
|
| 161 |
+
Setup quantized model
|
| 162 |
+
"""
|
| 163 |
+
quantization_config = FPQuantConfig(pseudoquantization=True)
|
| 164 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name)
|
| 165 |
+
cls.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 166 |
+
cls.model_name, device_map=cls.device_map, quantization_config=quantization_config
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
def tearDown(self):
|
| 170 |
+
gc.collect()
|
| 171 |
+
backend_empty_cache(torch_device)
|
| 172 |
+
gc.collect()
|
| 173 |
+
|
| 174 |
+
def test_quantized_model(self):
|
| 175 |
+
"""
|
| 176 |
+
Simple test that checks if the quantized model is working properly
|
| 177 |
+
"""
|
| 178 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 179 |
+
|
| 180 |
+
output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 181 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 182 |
+
|
| 183 |
+
def test_save_pretrained(self):
|
| 184 |
+
"""
|
| 185 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 186 |
+
"""
|
| 187 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 188 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 189 |
+
|
| 190 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map)
|
| 191 |
+
|
| 192 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 193 |
+
|
| 194 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 195 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 196 |
+
|
| 197 |
+
@require_torch_multi_gpu
|
| 198 |
+
def test_quantized_model_multi_gpu(self):
|
| 199 |
+
"""
|
| 200 |
+
Simple test that checks if the quantized model is working properly with multiple GPUs
|
| 201 |
+
set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs
|
| 202 |
+
"""
|
| 203 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 204 |
+
quantization_config = FPQuantConfig(pseudoquantization=True)
|
| 205 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 206 |
+
self.model_name, device_map="auto", quantization_config=quantization_config
|
| 207 |
+
)
|
| 208 |
+
self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1})
|
| 209 |
+
|
| 210 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 211 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 212 |
+
|
| 213 |
+
@require_torch_multi_gpu
|
| 214 |
+
def test_save_pretrained_multi_gpu(self):
|
| 215 |
+
"""
|
| 216 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 217 |
+
"""
|
| 218 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 219 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 220 |
+
|
| 221 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="auto")
|
| 222 |
+
self.assertTrue(set(model.hf_device_map.values()) == {0, 1})
|
| 223 |
+
|
| 224 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 225 |
+
|
| 226 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 227 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/ggml/__init__.py
ADDED
|
File without changes
|
tasks/tasksm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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import tempfile
|
| 15 |
+
import unittest
|
| 16 |
+
|
| 17 |
+
from parameterized import parameterized
|
| 18 |
+
|
| 19 |
+
from transformers import AddedToken, AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer
|
| 20 |
+
from transformers.testing_utils import (
|
| 21 |
+
require_gguf,
|
| 22 |
+
require_read_token,
|
| 23 |
+
require_torch_accelerator,
|
| 24 |
+
slow,
|
| 25 |
+
torch_device,
|
| 26 |
+
)
|
| 27 |
+
from transformers.utils import is_gguf_available, is_torch_available
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_torch_available():
|
| 31 |
+
import torch
|
| 32 |
+
|
| 33 |
+
if is_gguf_available():
|
| 34 |
+
from gguf import GGMLQuantizationType as QuantType
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@require_gguf
|
| 38 |
+
@require_torch_accelerator
|
| 39 |
+
@slow
|
| 40 |
+
class GgufQuantizationTests(unittest.TestCase):
|
| 41 |
+
"""
|
| 42 |
+
Test cases for weights dequantization with GGUF models.
|
| 43 |
+
Note: The quantization names should keep aligned with `GGMLQuantizationType` in gguf-py:
|
| 44 |
+
https://github.com/ggerganov/llama.cpp/blob/4b0c638b9a68f577cb2066b638c9f622d91ee661/gguf-py/gguf/constants.py#L1545-L1576
|
| 45 |
+
So quantization like Q4_K_M or Q4_K_S shouldn't be added to this tests.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
example_text = "Hello"
|
| 49 |
+
|
| 50 |
+
def run_gguf_model(self, gguf_model_id: str, gguf_filename: str, expected_text: str):
|
| 51 |
+
tokenizer = AutoTokenizer.from_pretrained(gguf_model_id, gguf_file=gguf_filename)
|
| 52 |
+
model = AutoModelForCausalLM.from_pretrained(gguf_model_id, gguf_file=gguf_filename).to(torch_device)
|
| 53 |
+
|
| 54 |
+
text = tokenizer(self.example_text, return_tensors="pt").to(torch_device)
|
| 55 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 56 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), expected_text)
|
| 57 |
+
|
| 58 |
+
@parameterized.expand(
|
| 59 |
+
[
|
| 60 |
+
# standard quants
|
| 61 |
+
("Q4_0", "Hello, World!\n\nStep 3: Add"),
|
| 62 |
+
("Q5_0", "Hello, World!\n\n5. Use a library"),
|
| 63 |
+
("Q8_0", "Hello, World!\n\n5. Use a library"),
|
| 64 |
+
],
|
| 65 |
+
)
|
| 66 |
+
def test_standard_quants(self, quant_type: str, expected_text: str):
|
| 67 |
+
gguf_model_id = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF"
|
| 68 |
+
filename_format = "tinyllama-1.1b-chat-v1.0.{quant_type}.gguf"
|
| 69 |
+
gguf_filename = filename_format.format(quant_type=quant_type)
|
| 70 |
+
self.run_gguf_model(gguf_model_id, gguf_filename, expected_text)
|
| 71 |
+
|
| 72 |
+
# k-quants
|
| 73 |
+
@parameterized.expand(
|
| 74 |
+
[
|
| 75 |
+
("Q2_K", "Hello, I'm a 22 year old female"),
|
| 76 |
+
("Q3_K", "Hello\n\nI am trying to create a simple program that"),
|
| 77 |
+
("Q4_K", "Hello\n\nI am trying to create a simple program that"),
|
| 78 |
+
("Q5_K", "Helloveda is a 1999 Indian"),
|
| 79 |
+
("Q6_K", "Hello\n\nI am trying to create a simple program that"),
|
| 80 |
+
],
|
| 81 |
+
)
|
| 82 |
+
def test_k_quants(self, quant_type: str, expected_text: str):
|
| 83 |
+
gguf_model_id = "legraphista/Qwen2.5-0.5B-Instruct-IMat-GGUF"
|
| 84 |
+
filename_format = "Qwen2.5-0.5B-Instruct.{quant_type}.gguf"
|
| 85 |
+
gguf_filename = filename_format.format(quant_type=quant_type)
|
| 86 |
+
self.run_gguf_model(gguf_model_id, gguf_filename, expected_text)
|
| 87 |
+
|
| 88 |
+
@parameterized.expand(
|
| 89 |
+
[
|
| 90 |
+
# i-matrix
|
| 91 |
+
("IQ1_S", "Hello, I'm a friend of mine, I"),
|
| 92 |
+
("IQ1_M", "Hello, I am interested in purching a copy of"),
|
| 93 |
+
("IQ2_XXS", "Hello, I'm a software engineer. I'"),
|
| 94 |
+
("IQ2_XS", "Hello World!\n\n```\n<|user|"),
|
| 95 |
+
("IQ2_S", "Hello World!\n\n```\n<|user|"),
|
| 96 |
+
("IQ3_XXS", "Hello, I am interested in your product. Can you"),
|
| 97 |
+
("IQ4_XS", "Hello, world!\n\n5. Using a loop"),
|
| 98 |
+
("IQ3_S", "Hello, World!\n\n5. Python:\n"),
|
| 99 |
+
("IQ4_NL", "Hello, world!\n\n5. Using a loop"),
|
| 100 |
+
],
|
| 101 |
+
)
|
| 102 |
+
def test_imatrix_quants(self, quant_type: str, expected_text: str):
|
| 103 |
+
gguf_model_id = "duyntnet/TinyLlama-1.1B-Chat-v1.0-imatrix-GGUF"
|
| 104 |
+
filename_format = "TinyLlama-1.1B-Chat-v1.0-{quant_type}.gguf"
|
| 105 |
+
gguf_filename = filename_format.format(quant_type=quant_type)
|
| 106 |
+
self.run_gguf_model(gguf_model_id, gguf_filename, expected_text)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@require_gguf
|
| 110 |
+
@require_torch_accelerator
|
| 111 |
+
@slow
|
| 112 |
+
class GgufIntegrationTests(unittest.TestCase):
|
| 113 |
+
"""
|
| 114 |
+
Test cases for basic interoperability with GGUF models:
|
| 115 |
+
- Tokenization
|
| 116 |
+
- Model dtype casting and serialization
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
example_text = "Hello"
|
| 120 |
+
original_model_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
| 121 |
+
gguf_model_id = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF"
|
| 122 |
+
gguf_filename = "tinyllama-1.1b-chat-v1.0.{quant_type}.gguf"
|
| 123 |
+
|
| 124 |
+
def test_tokenization_xnli(self):
|
| 125 |
+
import tqdm
|
| 126 |
+
from datasets import load_dataset
|
| 127 |
+
|
| 128 |
+
q8_0_gguf_model_id = self.gguf_filename.format(quant_type=QuantType.Q8_0.name)
|
| 129 |
+
gguf_tokenizer = AutoTokenizer.from_pretrained(self.gguf_model_id, gguf_file=q8_0_gguf_model_id)
|
| 130 |
+
original_tokenizer = AutoTokenizer.from_pretrained(self.original_model_id)
|
| 131 |
+
|
| 132 |
+
dataset = load_dataset("google/code_x_glue_ct_code_to_text", "go")
|
| 133 |
+
for item in tqdm.tqdm(dataset["validation"]):
|
| 134 |
+
string = item["code"]
|
| 135 |
+
encoded1 = gguf_tokenizer.encode(string)
|
| 136 |
+
encoded2 = original_tokenizer.encode(string)
|
| 137 |
+
|
| 138 |
+
self.assertEqual(encoded1, encoded2)
|
| 139 |
+
|
| 140 |
+
decoded1 = gguf_tokenizer.decode(encoded1, skip_special_tokens=True)
|
| 141 |
+
decoded2 = original_tokenizer.decode(encoded2, skip_special_tokens=True)
|
| 142 |
+
|
| 143 |
+
self.assertEqual(decoded1, decoded2)
|
| 144 |
+
|
| 145 |
+
dataset = load_dataset("facebook/xnli", "all_languages")
|
| 146 |
+
|
| 147 |
+
for i, item in enumerate(tqdm.tqdm(dataset["train"].select(range(100)))):
|
| 148 |
+
for string in item["premise"].values():
|
| 149 |
+
encoded1 = gguf_tokenizer.encode(string)
|
| 150 |
+
encoded2 = original_tokenizer.encode(string)
|
| 151 |
+
|
| 152 |
+
self.assertEqual(encoded1, encoded2)
|
| 153 |
+
|
| 154 |
+
decoded1 = gguf_tokenizer.decode(encoded1, skip_special_tokens=True)
|
| 155 |
+
decoded2 = original_tokenizer.decode(encoded2, skip_special_tokens=True)
|
| 156 |
+
|
| 157 |
+
self.assertEqual(decoded1, decoded2)
|
| 158 |
+
|
| 159 |
+
# With special tokens
|
| 160 |
+
gguf_tokenizer = AutoTokenizer.from_pretrained(self.gguf_model_id, gguf_file=q8_0_gguf_model_id)
|
| 161 |
+
original_tokenizer = AutoTokenizer.from_pretrained(self.original_model_id)
|
| 162 |
+
|
| 163 |
+
gguf_tokenizer.add_special_tokens(
|
| 164 |
+
{"additional_special_tokens": [AddedToken("<token>", rstrip=False, lstrip=False)]}
|
| 165 |
+
)
|
| 166 |
+
original_tokenizer.add_special_tokens(
|
| 167 |
+
{"additional_special_tokens": [AddedToken("<token>", rstrip=False, lstrip=False)]}
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
text = "Hello <token>. <token> Hello"
|
| 171 |
+
|
| 172 |
+
encoded1 = gguf_tokenizer.encode(text)
|
| 173 |
+
encoded2 = original_tokenizer.encode(text)
|
| 174 |
+
|
| 175 |
+
self.assertEqual(encoded1, encoded2)
|
| 176 |
+
|
| 177 |
+
decoded1 = gguf_tokenizer.decode(encoded1, skip_special_tokens=True)
|
| 178 |
+
decoded2 = original_tokenizer.decode(encoded2, skip_special_tokens=True)
|
| 179 |
+
|
| 180 |
+
self.assertEqual(decoded1, decoded2)
|
| 181 |
+
|
| 182 |
+
def test_q2_k_serialization(self):
|
| 183 |
+
q2_k_gguf_model_id = self.gguf_filename.format(quant_type=QuantType.Q2_K.name)
|
| 184 |
+
EXPECTED_TEXT = "Hello, World!\n\n[10:0"
|
| 185 |
+
|
| 186 |
+
tokenizer = AutoTokenizer.from_pretrained(self.gguf_model_id, gguf_file=q2_k_gguf_model_id)
|
| 187 |
+
model = AutoModelForCausalLM.from_pretrained(self.gguf_model_id, gguf_file=q2_k_gguf_model_id).to(torch_device)
|
| 188 |
+
|
| 189 |
+
orig_text = tokenizer(self.example_text, return_tensors="pt").to(torch_device)
|
| 190 |
+
orig_out = model.generate(**orig_text, max_new_tokens=10)
|
| 191 |
+
self.assertEqual(tokenizer.decode(orig_out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 192 |
+
|
| 193 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 194 |
+
model.save_pretrained(tmpdirname)
|
| 195 |
+
tokenizer.save_pretrained(tmpdirname)
|
| 196 |
+
|
| 197 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname).to(torch_device)
|
| 198 |
+
tokenizer = AutoTokenizer.from_pretrained(tmpdirname)
|
| 199 |
+
|
| 200 |
+
text = tokenizer(self.example_text, return_tensors="pt").to(torch_device)
|
| 201 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 202 |
+
|
| 203 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 204 |
+
|
| 205 |
+
def test_q6_k_fp16(self):
|
| 206 |
+
q6_k_gguf_model_id = self.gguf_filename.format(quant_type=QuantType.Q6_K.name)
|
| 207 |
+
|
| 208 |
+
tokenizer = AutoTokenizer.from_pretrained(self.gguf_model_id, gguf_file=q6_k_gguf_model_id)
|
| 209 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 210 |
+
self.gguf_model_id, gguf_file=q6_k_gguf_model_id, torch_dtype=torch.float16
|
| 211 |
+
).to(torch_device)
|
| 212 |
+
|
| 213 |
+
self.assertTrue(model.lm_head.weight.dtype == torch.float16)
|
| 214 |
+
|
| 215 |
+
text = tokenizer(self.example_text, return_tensors="pt").to(torch_device)
|
| 216 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 217 |
+
|
| 218 |
+
EXPECTED_TEXT = "Hello, World!\n\nStep 3: Add"
|
| 219 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 220 |
+
|
| 221 |
+
def test_gguf_errors_disk_offload(self):
|
| 222 |
+
from collections import OrderedDict
|
| 223 |
+
|
| 224 |
+
q2_k_gguf_model_id = self.gguf_filename.format(quant_type=QuantType.Q2_K.name)
|
| 225 |
+
with self.assertRaises(RuntimeError):
|
| 226 |
+
AutoModelForCausalLM.from_pretrained(
|
| 227 |
+
self.gguf_model_id,
|
| 228 |
+
device_map=OrderedDict(
|
| 229 |
+
[
|
| 230 |
+
("model.embed_tokens", "cpu"),
|
| 231 |
+
("lm_head", "cpu"),
|
| 232 |
+
("model.layers.0", "cpu"),
|
| 233 |
+
("model.layers.1", "cpu"),
|
| 234 |
+
("model.layers.2", "cpu"),
|
| 235 |
+
("model.layers.3", "cpu"),
|
| 236 |
+
("model.layers.4", "cpu"),
|
| 237 |
+
("model.layers.5", "cpu"),
|
| 238 |
+
("model.layers.6", "cpu"),
|
| 239 |
+
("model.layers.7", "cpu"),
|
| 240 |
+
("model.layers.8", "cpu"),
|
| 241 |
+
("model.layers.9", "cpu"),
|
| 242 |
+
("model.layers.10", "disk"),
|
| 243 |
+
("model.layers.11", "disk"),
|
| 244 |
+
("model.layers.12", "disk"),
|
| 245 |
+
("model.layers.13", "disk"),
|
| 246 |
+
("model.layers.14", "disk"),
|
| 247 |
+
("model.layers.15", "disk"),
|
| 248 |
+
("model.layers.16", "disk"),
|
| 249 |
+
("model.layers.17", "disk"),
|
| 250 |
+
("model.layers.18", "disk"),
|
| 251 |
+
("model.layers.19", "disk"),
|
| 252 |
+
("model.layers.20", "disk"),
|
| 253 |
+
("model.layers.21", "disk"),
|
| 254 |
+
("model.layers.22", "disk"),
|
| 255 |
+
("model.norm", "disk"),
|
| 256 |
+
("model.rotary_emb", "disk"),
|
| 257 |
+
]
|
| 258 |
+
),
|
| 259 |
+
gguf_file=q2_k_gguf_model_id,
|
| 260 |
+
offload_folder="offload",
|
| 261 |
+
offload_state_dict=True,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@require_gguf
|
| 266 |
+
@require_torch_accelerator
|
| 267 |
+
@slow
|
| 268 |
+
class GgufModelTests(unittest.TestCase):
|
| 269 |
+
mistral_model_id = "TheBloke/Mistral-7B-Instruct-v0.2-GGUF"
|
| 270 |
+
qwen2_model_id = "Qwen/Qwen1.5-0.5B-Chat-GGUF"
|
| 271 |
+
qwen2moe_model_id = "gdax/Qwen1.5-MoE-A2.7B_gguf"
|
| 272 |
+
qwen2moe_original_model_id = "Qwen/Qwen1.5-MoE-A2.7B"
|
| 273 |
+
llama3_model_id = "NousResearch/Meta-Llama-3-8B-GGUF"
|
| 274 |
+
tinyllama_model_id = "PenutChen/TinyLlama-1.1B-Chat-v1.0-GGUF"
|
| 275 |
+
phi3_model_id = "microsoft/Phi-3-mini-4k-instruct-gguf"
|
| 276 |
+
bloom_model_id = "afrideva/bloom-560m-GGUF"
|
| 277 |
+
original_bloom_model_id = "bigscience/bloom-560m"
|
| 278 |
+
falcon7b_model_id_q2 = "xaviviro/falcon-7b-quantized-gguf"
|
| 279 |
+
falcon7b_model_id_fp16 = "medmekk/falcon-7b-gguf"
|
| 280 |
+
falcon40b_model_id = "maddes8cht/tiiuae-falcon-40b-gguf"
|
| 281 |
+
original_flacon7b_model_id = "tiiuae/falcon-7b"
|
| 282 |
+
t5_model_id = "repetitio/flan-t5-small"
|
| 283 |
+
original_t5_model_id = "google/flan-t5-small"
|
| 284 |
+
stablelm_model_id = "afrideva/stablelm-3b-4e1t-GGUF"
|
| 285 |
+
stablelm2_model_id = "afrideva/stablelm-2-1_6b-GGUF"
|
| 286 |
+
original_stablelm2_model_id = "stabilityai/stablelm-2-1_6b"
|
| 287 |
+
gpt2_model_id = "mradermacher/gpt2-GGUF"
|
| 288 |
+
gpt2_original_model_id = "openai-community/gpt2"
|
| 289 |
+
gpt2_xl_model_id = "RichardErkhov/openai-community_-_gpt2-xl-gguf"
|
| 290 |
+
starcoder2_model_id = "QuantFactory/starcoder2-3b-GGUF"
|
| 291 |
+
starcoder2_fp16_model_id = "brittlewis12/starcoder2-3b-GGUF"
|
| 292 |
+
starcoder2_original_model_id = "bigcode/starcoder2-3b"
|
| 293 |
+
mamba_original_model_id = "state-spaces/mamba-2.8b-hf"
|
| 294 |
+
mamba_model_id = "jpodivin/mamba-2.8b-hf-GGUF"
|
| 295 |
+
nemotron_original_model_id = "nvidia/Nemotron-Mini-4B-Instruct"
|
| 296 |
+
nemotron_model_id = "bartowski/Nemotron-Mini-4B-Instruct-GGUF"
|
| 297 |
+
original_gemma2_model_id = "google/gemma-2-2b-it"
|
| 298 |
+
gemma2_model_id = "bartowski/gemma-2-2b-it-GGUF"
|
| 299 |
+
original_gemma3_text_model_id = "google/gemma-3-1b-it"
|
| 300 |
+
original_gemma3_vision_model_id = "google/gemma-3-4b-it"
|
| 301 |
+
gemma3_qat_model_id = "google/gemma-3-1b-it-qat-q4_0-gguf"
|
| 302 |
+
gemma3_text_model_id = "unsloth/gemma-3-1b-it-GGUF"
|
| 303 |
+
gemma3_vision_model_id = "unsloth/gemma-3-4b-it-GGUF"
|
| 304 |
+
qwen3_model_id = "Qwen/Qwen3-0.6B-GGUF"
|
| 305 |
+
qwen3moe_model_id = "Qwen/Qwen3-30B-A3B-GGUF"
|
| 306 |
+
|
| 307 |
+
q4_0_phi3_model_id = "Phi-3-mini-4k-instruct-q4.gguf"
|
| 308 |
+
q4_0_mistral_model_id = "mistral-7b-instruct-v0.2.Q4_0.gguf"
|
| 309 |
+
q4_0_qwen2_model_id = "qwen1_5-0_5b-chat-q4_0.gguf"
|
| 310 |
+
q8_qwen2moe_model_id = "Qwen1.5-MoE-A2.7B_Q8_0.gguf"
|
| 311 |
+
q4_llama3_model_id = "Meta-Llama-3-8B-Q4_K_M.gguf"
|
| 312 |
+
fp16_bloom_model_id = "bloom-560m.fp16.gguf"
|
| 313 |
+
q4_k_m_stablelm_model_id = "stablelm-3b-4e1t.q4_k_m.gguf"
|
| 314 |
+
fp16_stablelm2_model_id = "stablelm-2-1_6b.fp16.gguf"
|
| 315 |
+
q8_bloom_model_id = "bloom-560m.q8_0.gguf"
|
| 316 |
+
f16_tinyllama_model_id = "TinyLlama-1.1B-Chat-v1.0.FP16.gguf"
|
| 317 |
+
q2_k_falcon7b_model_id = "falcon-7b-q2_k.gguf"
|
| 318 |
+
fp16_falcon7b_model_id = "falcon-7b-fp16.gguf"
|
| 319 |
+
q2_k_falcon40b_model_id = "tiiuae-falcon-40b-Q2_K.gguf"
|
| 320 |
+
fp16_t5_model_id = "flan-t5-small-f16.gguf"
|
| 321 |
+
q8_0_t5_model_id = "flan-t5-small-q8_0.gguf"
|
| 322 |
+
fp16_qwen2moe_model_id = "Qwen1.5-MoE-A2.7B.gguf"
|
| 323 |
+
fp16_gpt2_model_id = "gpt2.f16.gguf"
|
| 324 |
+
q8_gpt2_model_id = "gpt2.Q8_0.gguf"
|
| 325 |
+
q6_k_gpt2_xl_model_id = "gpt2-xl.Q6_K.gguf"
|
| 326 |
+
q6_k_starcoder2_model_id = "starcoder2-3b.Q6_K.gguf"
|
| 327 |
+
fp16_starcoder2_gguf_model_id = "starcoder2-3b.fp16.gguf"
|
| 328 |
+
q6_k_mamba_model_id = "ggml-model-Q6_K.gguf"
|
| 329 |
+
fp16_mamba_model_id = "ggml-model-f16.gguf"
|
| 330 |
+
q6_k_nemotron_model_id = "Nemotron-Mini-4B-Instruct-Q6_K.gguf"
|
| 331 |
+
fp16_nemotron_model_id = "Nemotron-Mini-4B-Instruct-f16.gguf"
|
| 332 |
+
q3_k_gemma2_model_id = "gemma-2-2b-it-Q3_K_L.gguf"
|
| 333 |
+
q8_0_gemma2_model_id = "gemma-2-2b-it-Q8_0.gguf"
|
| 334 |
+
fp32_gemma2_model_id = "gemma-2-2b-it-f32.gguf"
|
| 335 |
+
q4_0_gemma3_qat_model_id = "gemma-3-1b-it-q4_0.gguf"
|
| 336 |
+
bf16_gemma3_text_model_id = "gemma-3-1b-it-BF16.gguf"
|
| 337 |
+
bf16_gemma3_vision_model_id = "gemma-3-4b-it-BF16.gguf"
|
| 338 |
+
q8_0_qwen3_model_id = "Qwen3-0.6B-Q8_0.gguf"
|
| 339 |
+
q4_k_m_qwen3moe_model_id = "Qwen3-30B-A3B-Q4_K_M.gguf"
|
| 340 |
+
|
| 341 |
+
example_text = "Hello"
|
| 342 |
+
|
| 343 |
+
def test_mistral_q4_0(self):
|
| 344 |
+
tokenizer = AutoTokenizer.from_pretrained(self.mistral_model_id, gguf_file=self.q4_0_mistral_model_id)
|
| 345 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 346 |
+
self.mistral_model_id,
|
| 347 |
+
gguf_file=self.q4_0_mistral_model_id,
|
| 348 |
+
device_map="auto",
|
| 349 |
+
torch_dtype=torch.float16,
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
text = tokenizer(self.example_text, return_tensors="pt").to(torch_device)
|
| 353 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 354 |
+
|
| 355 |
+
EXPECTED_TEXT = "Hello,\n\nI'm trying to create a"
|
| 356 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 357 |
+
|
| 358 |
+
def test_qwen2_q4_0(self):
|
| 359 |
+
tokenizer = AutoTokenizer.from_pretrained(self.qwen2_model_id, gguf_file=self.q4_0_qwen2_model_id)
|
| 360 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 361 |
+
self.qwen2_model_id,
|
| 362 |
+
gguf_file=self.q4_0_qwen2_model_id,
|
| 363 |
+
device_map="auto",
|
| 364 |
+
torch_dtype=torch.float16,
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
text = tokenizer(self.example_text, return_tensors="pt").to(torch_device)
|
| 368 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 369 |
+
|
| 370 |
+
EXPECTED_TEXT = "Hello.jsoup\n\nI am a beginner"
|
| 371 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 372 |
+
|
| 373 |
+
def test_qwen2moe_q8(self):
|
| 374 |
+
tokenizer = AutoTokenizer.from_pretrained(self.qwen2moe_model_id, gguf_file=self.q8_qwen2moe_model_id)
|
| 375 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 376 |
+
self.qwen2moe_model_id,
|
| 377 |
+
gguf_file=self.q8_qwen2moe_model_id,
|
| 378 |
+
torch_dtype=torch.float16,
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
text = tokenizer(self.example_text, return_tensors="pt")
|
| 382 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 383 |
+
|
| 384 |
+
EXPECTED_TEXT = "Hello, I am a 20 year old male"
|
| 385 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 386 |
+
|
| 387 |
+
def test_qwen2moe_weights_conversion_fp16(self):
|
| 388 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 389 |
+
self.qwen2moe_model_id,
|
| 390 |
+
gguf_file=self.fp16_qwen2moe_model_id,
|
| 391 |
+
torch_dtype=torch.float16,
|
| 392 |
+
)
|
| 393 |
+
original_model = AutoModelForCausalLM.from_pretrained(
|
| 394 |
+
self.qwen2moe_original_model_id,
|
| 395 |
+
torch_dtype=torch.float16,
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
quantized_state_dict = quantized_model.state_dict()
|
| 399 |
+
original_state_dict = original_model.state_dict()
|
| 400 |
+
|
| 401 |
+
for layer_name, original_params in original_state_dict.items():
|
| 402 |
+
if layer_name in quantized_state_dict:
|
| 403 |
+
self.assertTrue(original_params.shape == quantized_state_dict[layer_name].shape)
|
| 404 |
+
torch.testing.assert_close(original_params, quantized_state_dict[layer_name])
|
| 405 |
+
|
| 406 |
+
def test_phi3_q4_0(self):
|
| 407 |
+
tokenizer = AutoTokenizer.from_pretrained(self.phi3_model_id, gguf_file=self.q4_0_phi3_model_id)
|
| 408 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 409 |
+
self.phi3_model_id, gguf_file=self.q4_0_phi3_model_id, device_map="auto", torch_dtype=torch.float16
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
text = tokenizer(self.example_text, return_tensors="pt").to(torch_device)
|
| 413 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 414 |
+
|
| 415 |
+
EXPECTED_TEXT = "Hello, I've been reading about the impact of"
|
| 416 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 417 |
+
|
| 418 |
+
def test_llama3_q4_0_tokenizer(self):
|
| 419 |
+
tokenizer = AutoTokenizer.from_pretrained(self.llama3_model_id, gguf_file=self.q4_llama3_model_id)
|
| 420 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 421 |
+
tokenizer.save_pretrained(tmpdirname)
|
| 422 |
+
tokenizer = AutoTokenizer.from_pretrained(tmpdirname)
|
| 423 |
+
special_sentence = "สวัสดี"
|
| 424 |
+
predicted_text = tokenizer.decode(tokenizer.encode(special_sentence, return_tensors="pt")[0])
|
| 425 |
+
self.assertEqual(predicted_text, "<|begin_of_text|>" + special_sentence)
|
| 426 |
+
|
| 427 |
+
def test_llama3_q4_0(self):
|
| 428 |
+
tokenizer = AutoTokenizer.from_pretrained(self.llama3_model_id, gguf_file=self.q4_llama3_model_id)
|
| 429 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 430 |
+
self.llama3_model_id,
|
| 431 |
+
gguf_file=self.q4_llama3_model_id,
|
| 432 |
+
device_map="auto",
|
| 433 |
+
torch_dtype=torch.float16,
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
text = tokenizer(self.example_text, return_tensors="pt").to(torch_device)
|
| 437 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 438 |
+
|
| 439 |
+
EXPECTED_TEXT = "Hello, I am interested in [The Park]\nThe"
|
| 440 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 441 |
+
|
| 442 |
+
def test_bloom_fp16(self):
|
| 443 |
+
tokenizer = AutoTokenizer.from_pretrained(self.bloom_model_id, gguf_file=self.fp16_bloom_model_id)
|
| 444 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 445 |
+
self.bloom_model_id,
|
| 446 |
+
gguf_file=self.fp16_bloom_model_id,
|
| 447 |
+
device_map="auto",
|
| 448 |
+
torch_dtype=torch.float16,
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
text = tokenizer(self.example_text, return_tensors="pt").to(torch_device)
|
| 452 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 453 |
+
|
| 454 |
+
EXPECTED_TEXT = "Hello, I just want to say that I am very"
|
| 455 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 456 |
+
|
| 457 |
+
def test_bloom_q8_0(self):
|
| 458 |
+
tokenizer = AutoTokenizer.from_pretrained(self.bloom_model_id, gguf_file=self.q8_bloom_model_id)
|
| 459 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 460 |
+
self.bloom_model_id,
|
| 461 |
+
gguf_file=self.q8_bloom_model_id,
|
| 462 |
+
device_map="auto",
|
| 463 |
+
torch_dtype=torch.float16,
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
text = tokenizer(self.example_text, return_tensors="pt").to(torch_device)
|
| 467 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 468 |
+
|
| 469 |
+
EXPECTED_TEXT = "Hello, I just want to say that I am just"
|
| 470 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 471 |
+
|
| 472 |
+
def test_bloom_weights_conversion_fp16(self):
|
| 473 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 474 |
+
self.bloom_model_id,
|
| 475 |
+
gguf_file=self.fp16_bloom_model_id,
|
| 476 |
+
device_map="auto",
|
| 477 |
+
torch_dtype=torch.float16,
|
| 478 |
+
)
|
| 479 |
+
original_model = AutoModelForCausalLM.from_pretrained(
|
| 480 |
+
self.original_bloom_model_id,
|
| 481 |
+
device_map="auto",
|
| 482 |
+
torch_dtype=torch.float16,
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
quantized_state_dict = quantized_model.state_dict()
|
| 486 |
+
original_state_dict = original_model.state_dict()
|
| 487 |
+
|
| 488 |
+
for (quantized_name, quantized_param), (original_name, original_param) in zip(
|
| 489 |
+
quantized_state_dict.items(), original_state_dict.items()
|
| 490 |
+
):
|
| 491 |
+
if (
|
| 492 |
+
"self_attention.query_key_value" in quantized_name
|
| 493 |
+
and "self_attention.query_key_value" in original_name
|
| 494 |
+
):
|
| 495 |
+
self.assertTrue(quantized_param.shape == original_param.shape)
|
| 496 |
+
torch.testing.assert_close(quantized_param, original_param)
|
| 497 |
+
|
| 498 |
+
def test_t5_f16(self):
|
| 499 |
+
tokenizer = AutoTokenizer.from_pretrained(self.t5_model_id, gguf_file=self.fp16_t5_model_id)
|
| 500 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 501 |
+
self.t5_model_id, gguf_file=self.fp16_t5_model_id, device_map="auto", torch_dtype=torch.float16
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
T5_EXAMPLE_TEXT = "translate English to German: How old are you?"
|
| 505 |
+
|
| 506 |
+
text = tokenizer(T5_EXAMPLE_TEXT, return_tensors="pt").to(torch_device)
|
| 507 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 508 |
+
|
| 509 |
+
EXPECTED_TEXT = "Wie ich er?"
|
| 510 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 511 |
+
|
| 512 |
+
def test_t5_q8_0(self):
|
| 513 |
+
tokenizer = AutoTokenizer.from_pretrained(self.t5_model_id, gguf_file=self.q8_0_t5_model_id)
|
| 514 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 515 |
+
self.t5_model_id, gguf_file=self.q8_0_t5_model_id, device_map="auto", torch_dtype=torch.float16
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
T5_EXAMPLE_TEXT = "translate English to German: How old are you?"
|
| 519 |
+
|
| 520 |
+
text = tokenizer(T5_EXAMPLE_TEXT, return_tensors="pt").to(torch_device)
|
| 521 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 522 |
+
|
| 523 |
+
EXPECTED_TEXT = "Wie ich er?"
|
| 524 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 525 |
+
|
| 526 |
+
def test_t5_weights_conversion_fp16(self):
|
| 527 |
+
quantized_model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 528 |
+
self.t5_model_id,
|
| 529 |
+
gguf_file=self.fp16_t5_model_id,
|
| 530 |
+
device_map="auto",
|
| 531 |
+
torch_dtype=torch.float16,
|
| 532 |
+
)
|
| 533 |
+
original_model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 534 |
+
self.original_t5_model_id,
|
| 535 |
+
device_map="auto",
|
| 536 |
+
torch_dtype=torch.float16,
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
quantized_state_dict = quantized_model.state_dict()
|
| 540 |
+
original_state_dict = original_model.state_dict()
|
| 541 |
+
|
| 542 |
+
for (quantized_name, quantized_param), (original_name, original_param) in zip(
|
| 543 |
+
quantized_state_dict.items(), original_state_dict.items()
|
| 544 |
+
):
|
| 545 |
+
self.assertTrue(quantized_param.shape == original_param.shape)
|
| 546 |
+
torch.testing.assert_close(quantized_param, original_param, rtol=5e-04, atol=5e-04)
|
| 547 |
+
|
| 548 |
+
def test_gpt2_q8(self):
|
| 549 |
+
tokenizer = AutoTokenizer.from_pretrained(self.gpt2_model_id, gguf_file=self.q8_gpt2_model_id)
|
| 550 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 551 |
+
self.gpt2_model_id,
|
| 552 |
+
gguf_file=self.q8_gpt2_model_id,
|
| 553 |
+
torch_dtype=torch.float16,
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
text = tokenizer(self.example_text, return_tensors="pt")
|
| 557 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 558 |
+
|
| 559 |
+
EXPECTED_TEXT = "Hello, I'm sorry. I'm sorry. I"
|
| 560 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 561 |
+
|
| 562 |
+
def test_gpt2_weights_conversion_fp16(self):
|
| 563 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 564 |
+
self.gpt2_model_id,
|
| 565 |
+
gguf_file=self.fp16_gpt2_model_id,
|
| 566 |
+
torch_dtype=torch.float16,
|
| 567 |
+
)
|
| 568 |
+
original_model = AutoModelForCausalLM.from_pretrained(
|
| 569 |
+
self.gpt2_original_model_id,
|
| 570 |
+
torch_dtype=torch.float16,
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
quantized_state_dict = quantized_model.state_dict()
|
| 574 |
+
original_state_dict = original_model.state_dict()
|
| 575 |
+
|
| 576 |
+
for layer_name, original_params in original_state_dict.items():
|
| 577 |
+
if layer_name in quantized_state_dict:
|
| 578 |
+
self.assertTrue(original_params.shape == quantized_state_dict[layer_name].shape)
|
| 579 |
+
torch.testing.assert_close(original_params, quantized_state_dict[layer_name])
|
| 580 |
+
else:
|
| 581 |
+
raise ValueError(f"Layer {layer_name} is not presented in GGUF model")
|
| 582 |
+
|
| 583 |
+
def test_gpt2_xl_Q6_K(self):
|
| 584 |
+
tokenizer = AutoTokenizer.from_pretrained(self.gpt2_xl_model_id, gguf_file=self.q6_k_gpt2_xl_model_id)
|
| 585 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 586 |
+
self.gpt2_xl_model_id,
|
| 587 |
+
gguf_file=self.q6_k_gpt2_xl_model_id,
|
| 588 |
+
torch_dtype=torch.float16,
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
text = tokenizer(self.example_text, return_tensors="pt")
|
| 592 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 593 |
+
|
| 594 |
+
EXPECTED_TEXT = "Hello, I'm a newbie to the world of"
|
| 595 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 596 |
+
|
| 597 |
+
@unittest.skip(reason="Heavy memory")
|
| 598 |
+
def test_falcon40b_q2_k(self):
|
| 599 |
+
tokenizer = AutoTokenizer.from_pretrained(self.falcon40b_model_id, gguf_file=self.q2_k_falcon40b_model_id)
|
| 600 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 601 |
+
self.falcon40b_model_id,
|
| 602 |
+
gguf_file=self.q2_k_falcon40b_model_id,
|
| 603 |
+
device_map="auto",
|
| 604 |
+
torch_dtype=torch.float16,
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
text = tokenizer(self.example_text, return_tensors="pt").to(torch_device)
|
| 608 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 609 |
+
|
| 610 |
+
EXPECTED_TEXT = "Hello All,\nI am new to this forum."
|
| 611 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 612 |
+
|
| 613 |
+
def test_falcon7b_q2_k(self):
|
| 614 |
+
tokenizer = AutoTokenizer.from_pretrained(self.falcon7b_model_id_q2, gguf_file=self.q2_k_falcon7b_model_id)
|
| 615 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 616 |
+
self.falcon7b_model_id_q2,
|
| 617 |
+
gguf_file=self.q2_k_falcon7b_model_id,
|
| 618 |
+
device_map="auto",
|
| 619 |
+
torch_dtype=torch.float16,
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
text = tokenizer(self.example_text, return_tensors="pt")["input_ids"].to(torch_device)
|
| 623 |
+
out = model.generate(text, max_new_tokens=16)
|
| 624 |
+
|
| 625 |
+
EXPECTED_TEXT = "Hello All,\nI am new to this forum.\nI am using the "
|
| 626 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 627 |
+
|
| 628 |
+
@unittest.skip("The test causes a torch.OutOfMemoryError on the CI but it passes with enough memory")
|
| 629 |
+
def test_falcon7b_weights_conversion_fp16(self):
|
| 630 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 631 |
+
self.falcon7b_model_id_fp16,
|
| 632 |
+
gguf_file=self.fp16_falcon7b_model_id,
|
| 633 |
+
device_map="auto",
|
| 634 |
+
torch_dtype=torch.float16,
|
| 635 |
+
)
|
| 636 |
+
original_model = AutoModelForCausalLM.from_pretrained(
|
| 637 |
+
self.original_flacon7b_model_id,
|
| 638 |
+
device_map="auto",
|
| 639 |
+
torch_dtype=torch.float16,
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
quantized_state_dict = quantized_model.state_dict()
|
| 643 |
+
original_state_dict = original_model.state_dict()
|
| 644 |
+
|
| 645 |
+
for layer_name, original_params in original_state_dict.items():
|
| 646 |
+
if layer_name in quantized_state_dict:
|
| 647 |
+
self.assertTrue(original_params.shape == quantized_state_dict[layer_name].shape)
|
| 648 |
+
torch.testing.assert_close(original_params, quantized_state_dict[layer_name])
|
| 649 |
+
else:
|
| 650 |
+
raise ValueError(f"Layer {layer_name} is not presented in GGUF model")
|
| 651 |
+
|
| 652 |
+
def test_stablelm_q4_k_m(self):
|
| 653 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 654 |
+
self.stablelm_model_id,
|
| 655 |
+
gguf_file=self.q4_k_m_stablelm_model_id,
|
| 656 |
+
device_map="auto",
|
| 657 |
+
torch_dtype=torch.float16,
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
tokenizer = AutoTokenizer.from_pretrained(self.stablelm_model_id, gguf_file=self.q4_k_m_stablelm_model_id)
|
| 661 |
+
text = tokenizer(self.example_text, return_tensors="pt").to(torch_device)
|
| 662 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 663 |
+
|
| 664 |
+
EXPECTED_TEXT = "Hello-\nI am trying to create a new user"
|
| 665 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 666 |
+
|
| 667 |
+
def test_stablelm_fp16(self):
|
| 668 |
+
original_model = AutoModelForCausalLM.from_pretrained(
|
| 669 |
+
self.original_stablelm2_model_id,
|
| 670 |
+
torch_dtype=torch.float16,
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
converted_model = AutoModelForCausalLM.from_pretrained(
|
| 674 |
+
self.stablelm2_model_id,
|
| 675 |
+
gguf_file=self.fp16_stablelm2_model_id,
|
| 676 |
+
torch_dtype=torch.float16,
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
tokenizer = AutoTokenizer.from_pretrained(self.stablelm2_model_id, gguf_file=self.fp16_stablelm2_model_id)
|
| 680 |
+
text = tokenizer(self.example_text, return_tensors="pt")
|
| 681 |
+
original_out = original_model.generate(**text, max_new_tokens=10)
|
| 682 |
+
converted_out = converted_model.generate(**text, max_new_tokens=10)
|
| 683 |
+
|
| 684 |
+
EXPECTED_TEXT = "Hello, I am a 20 year old male"
|
| 685 |
+
self.assertEqual(tokenizer.decode(converted_out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 686 |
+
self.assertEqual(
|
| 687 |
+
tokenizer.decode(converted_out[0], skip_special_tokens=True),
|
| 688 |
+
tokenizer.decode(original_out[0], skip_special_tokens=True),
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
+
def test_stablelm_weights_conversion_fp16(self):
|
| 692 |
+
original_model = AutoModelForCausalLM.from_pretrained(
|
| 693 |
+
self.original_stablelm2_model_id,
|
| 694 |
+
device_map="auto",
|
| 695 |
+
torch_dtype=torch.float16,
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
converted_model = AutoModelForCausalLM.from_pretrained(
|
| 699 |
+
self.stablelm2_model_id,
|
| 700 |
+
gguf_file=self.fp16_stablelm2_model_id,
|
| 701 |
+
device_map="auto",
|
| 702 |
+
torch_dtype=torch.float16,
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
converted_state_dict = converted_model.state_dict()
|
| 706 |
+
original_state_dict = original_model.state_dict()
|
| 707 |
+
|
| 708 |
+
for layer_name, original_params in original_state_dict.items():
|
| 709 |
+
if layer_name in converted_state_dict:
|
| 710 |
+
self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape)
|
| 711 |
+
torch.testing.assert_close(original_params, converted_state_dict[layer_name])
|
| 712 |
+
else:
|
| 713 |
+
raise ValueError(f"Layer {layer_name} is not presented in GGUF model")
|
| 714 |
+
|
| 715 |
+
def test_starcoder2_weights_conversion_fp16(self):
|
| 716 |
+
original_model = AutoModelForCausalLM.from_pretrained(
|
| 717 |
+
self.starcoder2_original_model_id,
|
| 718 |
+
device_map="auto",
|
| 719 |
+
torch_dtype=torch.float16,
|
| 720 |
+
)
|
| 721 |
+
|
| 722 |
+
converted_model = AutoModelForCausalLM.from_pretrained(
|
| 723 |
+
self.starcoder2_fp16_model_id,
|
| 724 |
+
gguf_file=self.fp16_starcoder2_gguf_model_id,
|
| 725 |
+
device_map="auto",
|
| 726 |
+
torch_dtype=torch.float16,
|
| 727 |
+
)
|
| 728 |
+
|
| 729 |
+
converted_state_dict = converted_model.state_dict()
|
| 730 |
+
original_state_dict = original_model.state_dict()
|
| 731 |
+
|
| 732 |
+
for layer_name, original_params in original_state_dict.items():
|
| 733 |
+
if layer_name in converted_state_dict:
|
| 734 |
+
self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape)
|
| 735 |
+
torch.testing.assert_close(original_params, converted_state_dict[layer_name])
|
| 736 |
+
else:
|
| 737 |
+
raise ValueError(f"Layer {layer_name} is not presented in GGUF model")
|
| 738 |
+
|
| 739 |
+
def test_starcoder2_q6_k(self):
|
| 740 |
+
example_function_text = "def print_hello_world():"
|
| 741 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 742 |
+
self.starcoder2_model_id,
|
| 743 |
+
gguf_file=self.q6_k_starcoder2_model_id,
|
| 744 |
+
device_map="auto",
|
| 745 |
+
torch_dtype=torch.float16,
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
+
tokenizer = AutoTokenizer.from_pretrained(self.starcoder2_model_id, gguf_file=self.q6_k_starcoder2_model_id)
|
| 749 |
+
text = tokenizer(example_function_text, return_tensors="pt").to(torch_device)
|
| 750 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 751 |
+
|
| 752 |
+
EXPECTED_TEXT = 'def print_hello_world():\n print("Hello World")\n\ndef print'
|
| 753 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 754 |
+
|
| 755 |
+
def test_mamba_weights_conversion_fp16(self):
|
| 756 |
+
original_model = AutoModelForCausalLM.from_pretrained(
|
| 757 |
+
self.mamba_original_model_id,
|
| 758 |
+
torch_dtype=torch.float16,
|
| 759 |
+
)
|
| 760 |
+
|
| 761 |
+
converted_model = AutoModelForCausalLM.from_pretrained(
|
| 762 |
+
self.mamba_model_id,
|
| 763 |
+
gguf_file=self.fp16_mamba_model_id,
|
| 764 |
+
torch_dtype=torch.float16,
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
converted_state_dict = converted_model.state_dict()
|
| 768 |
+
original_state_dict = original_model.state_dict()
|
| 769 |
+
|
| 770 |
+
for layer_name, original_params in original_state_dict.items():
|
| 771 |
+
if layer_name in converted_state_dict:
|
| 772 |
+
self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape)
|
| 773 |
+
if "mixer.A_log" in layer_name:
|
| 774 |
+
# we should increase tolerance after exponential reversing
|
| 775 |
+
# and performing np.log(-weights) operation as numbers are slightly different
|
| 776 |
+
torch.testing.assert_close(original_params, converted_state_dict[layer_name], rtol=1e-3, atol=1e-3)
|
| 777 |
+
else:
|
| 778 |
+
torch.testing.assert_close(original_params, converted_state_dict[layer_name])
|
| 779 |
+
else:
|
| 780 |
+
raise ValueError(f"Layer {layer_name} is not presented in GGUF model")
|
| 781 |
+
|
| 782 |
+
def test_mamba_q6_k(self):
|
| 783 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 784 |
+
self.mamba_model_id,
|
| 785 |
+
gguf_file=self.q6_k_mamba_model_id,
|
| 786 |
+
torch_dtype=torch.float16,
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
tokenizer = AutoTokenizer.from_pretrained(self.mamba_model_id, gguf_file=self.q6_k_mamba_model_id)
|
| 790 |
+
text = tokenizer(self.example_text, return_tensors="pt")["input_ids"]
|
| 791 |
+
out = model.generate(text, max_new_tokens=10)
|
| 792 |
+
|
| 793 |
+
EXPECTED_TEXT = "Hello,I answerthe question.\n\nA"
|
| 794 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 795 |
+
|
| 796 |
+
def test_nemotron_weights_conversion_fp16(self):
|
| 797 |
+
original_model = AutoModelForCausalLM.from_pretrained(
|
| 798 |
+
self.nemotron_original_model_id,
|
| 799 |
+
torch_dtype=torch.float16,
|
| 800 |
+
)
|
| 801 |
+
|
| 802 |
+
converted_model = AutoModelForCausalLM.from_pretrained(
|
| 803 |
+
self.nemotron_model_id,
|
| 804 |
+
gguf_file=self.fp16_nemotron_model_id,
|
| 805 |
+
torch_dtype=torch.float16,
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
converted_state_dict = converted_model.state_dict()
|
| 809 |
+
original_state_dict = original_model.state_dict()
|
| 810 |
+
|
| 811 |
+
for layer_name, original_params in original_state_dict.items():
|
| 812 |
+
if layer_name in converted_state_dict:
|
| 813 |
+
self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape)
|
| 814 |
+
torch.testing.assert_close(original_params, converted_state_dict[layer_name])
|
| 815 |
+
else:
|
| 816 |
+
raise ValueError(f"Layer {layer_name} is not presented in GGUF model")
|
| 817 |
+
|
| 818 |
+
def test_nemotron_q6_k(self):
|
| 819 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 820 |
+
self.nemotron_model_id,
|
| 821 |
+
gguf_file=self.q6_k_nemotron_model_id,
|
| 822 |
+
torch_dtype=torch.float16,
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
tokenizer = AutoTokenizer.from_pretrained(self.nemotron_model_id, gguf_file=self.q6_k_nemotron_model_id)
|
| 826 |
+
text = tokenizer(self.example_text, return_tensors="pt")["input_ids"]
|
| 827 |
+
out = model.generate(text, max_new_tokens=16)
|
| 828 |
+
|
| 829 |
+
EXPECTED_TEXT = "Hello.▁hotmail.com</s>"
|
| 830 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 831 |
+
|
| 832 |
+
def test_gemma2_q3_k(self):
|
| 833 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 834 |
+
self.gemma2_model_id,
|
| 835 |
+
gguf_file=self.q3_k_gemma2_model_id,
|
| 836 |
+
torch_dtype=torch.float16,
|
| 837 |
+
)
|
| 838 |
+
|
| 839 |
+
tokenizer = AutoTokenizer.from_pretrained(self.gemma2_model_id, gguf_file=self.q3_k_gemma2_model_id)
|
| 840 |
+
text = tokenizer(self.example_text, return_tensors="pt")["input_ids"]
|
| 841 |
+
out = model.generate(text, max_new_tokens=10)
|
| 842 |
+
|
| 843 |
+
EXPECTED_TEXT = "Hello! 👋\n\nI'm trying to create a"
|
| 844 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 845 |
+
|
| 846 |
+
def test_gemma2_q8_0(self):
|
| 847 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 848 |
+
self.gemma2_model_id,
|
| 849 |
+
gguf_file=self.q8_0_gemma2_model_id,
|
| 850 |
+
torch_dtype=torch.float16,
|
| 851 |
+
)
|
| 852 |
+
|
| 853 |
+
tokenizer = AutoTokenizer.from_pretrained(self.gemma2_model_id, gguf_file=self.q8_0_gemma2_model_id)
|
| 854 |
+
text = tokenizer(self.example_text, return_tensors="pt")["input_ids"]
|
| 855 |
+
out = model.generate(text, max_new_tokens=10)
|
| 856 |
+
|
| 857 |
+
EXPECTED_TEXT = "Hello! 👋\n\nI'm a large language model"
|
| 858 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 859 |
+
|
| 860 |
+
def test_gemma2_fp32(self):
|
| 861 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 862 |
+
self.gemma2_model_id,
|
| 863 |
+
gguf_file=self.fp32_gemma2_model_id,
|
| 864 |
+
torch_dtype=torch.float16,
|
| 865 |
+
)
|
| 866 |
+
|
| 867 |
+
tokenizer = AutoTokenizer.from_pretrained(self.gemma2_model_id, gguf_file=self.fp32_gemma2_model_id)
|
| 868 |
+
text = tokenizer(self.example_text, return_tensors="pt")["input_ids"]
|
| 869 |
+
out = model.generate(text, max_new_tokens=10)
|
| 870 |
+
|
| 871 |
+
EXPECTED_TEXT = "Hello! 👋\n\nI'm a large language model"
|
| 872 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 873 |
+
|
| 874 |
+
@require_read_token
|
| 875 |
+
def test_gemma2_weights_conversion_fp32(self):
|
| 876 |
+
original_model = AutoModelForCausalLM.from_pretrained(
|
| 877 |
+
self.original_gemma2_model_id,
|
| 878 |
+
torch_dtype=torch.float16,
|
| 879 |
+
)
|
| 880 |
+
|
| 881 |
+
converted_model = AutoModelForCausalLM.from_pretrained(
|
| 882 |
+
self.gemma2_model_id,
|
| 883 |
+
gguf_file=self.fp32_gemma2_model_id,
|
| 884 |
+
torch_dtype=torch.float16,
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
converted_state_dict = converted_model.state_dict()
|
| 888 |
+
original_state_dict = original_model.state_dict()
|
| 889 |
+
|
| 890 |
+
for layer_name, original_params in original_state_dict.items():
|
| 891 |
+
if layer_name in converted_state_dict:
|
| 892 |
+
self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape)
|
| 893 |
+
torch.testing.assert_close(original_params, converted_state_dict[layer_name])
|
| 894 |
+
else:
|
| 895 |
+
raise ValueError(f"Layer {layer_name} is not presented in GGUF model")
|
| 896 |
+
|
| 897 |
+
@require_read_token
|
| 898 |
+
@unittest.skipUnless(is_gguf_available("0.16.0"), "test requires gguf version >= 0.16.0")
|
| 899 |
+
def test_gemma3_qat_q4_0(self):
|
| 900 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 901 |
+
self.gemma3_qat_model_id,
|
| 902 |
+
gguf_file=self.q4_0_gemma3_qat_model_id,
|
| 903 |
+
torch_dtype=torch.float16,
|
| 904 |
+
)
|
| 905 |
+
|
| 906 |
+
tokenizer = AutoTokenizer.from_pretrained(self.gemma3_qat_model_id, gguf_file=self.q4_0_gemma3_qat_model_id)
|
| 907 |
+
text = tokenizer(self.example_text, return_tensors="pt")["input_ids"]
|
| 908 |
+
out = model.generate(text, max_new_tokens=10)
|
| 909 |
+
|
| 910 |
+
EXPECTED_TEXT = 'Hello with the prompt, "What is the best way'
|
| 911 |
+
|
| 912 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 913 |
+
|
| 914 |
+
@require_read_token
|
| 915 |
+
@unittest.skipUnless(is_gguf_available("0.16.0"), "test requires gguf version >= 0.16.0")
|
| 916 |
+
def test_gemma3_text_weights_conversion_bf16(self):
|
| 917 |
+
original_model = AutoModelForCausalLM.from_pretrained(
|
| 918 |
+
self.original_gemma3_text_model_id,
|
| 919 |
+
torch_dtype=torch.float16,
|
| 920 |
+
)
|
| 921 |
+
|
| 922 |
+
converted_model = AutoModelForCausalLM.from_pretrained(
|
| 923 |
+
self.gemma3_text_model_id,
|
| 924 |
+
gguf_file=self.bf16_gemma3_text_model_id,
|
| 925 |
+
torch_dtype=torch.float16,
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
converted_state_dict = converted_model.state_dict()
|
| 929 |
+
original_state_dict = original_model.state_dict()
|
| 930 |
+
|
| 931 |
+
for layer_name, original_params in original_state_dict.items():
|
| 932 |
+
if layer_name in converted_state_dict:
|
| 933 |
+
self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape)
|
| 934 |
+
torch.testing.assert_close(original_params, converted_state_dict[layer_name])
|
| 935 |
+
else:
|
| 936 |
+
raise ValueError(f"Layer {layer_name} is not presented in GGUF model")
|
| 937 |
+
|
| 938 |
+
# Test text backbone conversion for gemma3 vision models
|
| 939 |
+
@require_read_token
|
| 940 |
+
@unittest.skipUnless(is_gguf_available("0.16.0"), "test requires gguf version >= 0.16.0")
|
| 941 |
+
def test_gemma3_vision_weights_conversion_bf16(self):
|
| 942 |
+
original_model = AutoModelForCausalLM.from_pretrained(
|
| 943 |
+
self.original_gemma3_vision_model_id,
|
| 944 |
+
torch_dtype=torch.float16,
|
| 945 |
+
).language_model
|
| 946 |
+
|
| 947 |
+
converted_model = AutoModelForCausalLM.from_pretrained(
|
| 948 |
+
self.gemma3_vision_model_id,
|
| 949 |
+
gguf_file=self.bf16_gemma3_vision_model_id,
|
| 950 |
+
torch_dtype=torch.float16,
|
| 951 |
+
)
|
| 952 |
+
|
| 953 |
+
converted_state_dict = converted_model.state_dict()
|
| 954 |
+
original_state_dict = original_model.state_dict()
|
| 955 |
+
|
| 956 |
+
for layer_name, original_params in original_state_dict.items():
|
| 957 |
+
if layer_name in converted_state_dict:
|
| 958 |
+
self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape)
|
| 959 |
+
torch.testing.assert_close(original_params, converted_state_dict[layer_name])
|
| 960 |
+
else:
|
| 961 |
+
raise ValueError(f"Layer {layer_name} is not presented in GGUF model")
|
| 962 |
+
|
| 963 |
+
@require_read_token
|
| 964 |
+
@unittest.skipUnless(is_gguf_available("0.16.0"), "test requires gguf version >= 0.16.0")
|
| 965 |
+
def test_qwen3_q8_0(self):
|
| 966 |
+
tokenizer = AutoTokenizer.from_pretrained(self.qwen3_model_id, gguf_file=self.q8_0_qwen3_model_id)
|
| 967 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 968 |
+
self.qwen3_model_id,
|
| 969 |
+
gguf_file=self.q8_0_qwen3_model_id,
|
| 970 |
+
torch_dtype=torch.float16,
|
| 971 |
+
)
|
| 972 |
+
|
| 973 |
+
text = tokenizer(self.example_text, return_tensors="pt")["input_ids"]
|
| 974 |
+
out = model.generate(text, max_new_tokens=10)
|
| 975 |
+
|
| 976 |
+
EXPECTED_TEXT = "HelloED\nI need to find the value of the"
|
| 977 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
| 978 |
+
|
| 979 |
+
def test_qwen3moe_q4_k_m(self):
|
| 980 |
+
tokenizer = AutoTokenizer.from_pretrained(self.qwen3moe_model_id, gguf_file=self.q4_k_m_qwen3moe_model_id)
|
| 981 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 982 |
+
self.qwen3moe_model_id,
|
| 983 |
+
gguf_file=self.q4_k_m_qwen3moe_model_id,
|
| 984 |
+
torch_dtype=torch.float16,
|
| 985 |
+
)
|
| 986 |
+
|
| 987 |
+
text = tokenizer(self.example_text, return_tensors="pt")
|
| 988 |
+
out = model.generate(**text, max_new_tokens=10)
|
| 989 |
+
|
| 990 |
+
EXPECTED_TEXT = "Hello, I am a 20 year old male"
|
| 991 |
+
self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/gptq/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/gptq/test_gptq.py
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import tempfile
|
| 16 |
+
import unittest
|
| 17 |
+
|
| 18 |
+
import pytest
|
| 19 |
+
|
| 20 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GPTQConfig
|
| 21 |
+
from transformers.testing_utils import (
|
| 22 |
+
is_torch_available,
|
| 23 |
+
require_accelerate,
|
| 24 |
+
require_gptq,
|
| 25 |
+
require_optimum,
|
| 26 |
+
require_torch_gpu,
|
| 27 |
+
require_torch_multi_gpu,
|
| 28 |
+
slow,
|
| 29 |
+
)
|
| 30 |
+
from transformers.utils import is_auto_gptq_available, is_gptqmodel_available, is_ipex_available
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if is_torch_available():
|
| 34 |
+
import torch
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class GPTQConfigTest(unittest.TestCase):
|
| 38 |
+
def test_bits(self):
|
| 39 |
+
with self.assertRaises(ValueError):
|
| 40 |
+
GPTQConfig(bits="")
|
| 41 |
+
GPTQConfig(bits=1)
|
| 42 |
+
GPTQConfig(bits=2)
|
| 43 |
+
GPTQConfig(bits=4)
|
| 44 |
+
|
| 45 |
+
def test_dataset(self):
|
| 46 |
+
with self.assertRaises(ValueError):
|
| 47 |
+
GPTQConfig(bits=2, dataset="auto_gpt")
|
| 48 |
+
GPTQConfig(bits=2, dataset="c4")
|
| 49 |
+
|
| 50 |
+
def test_damp_percent(self):
|
| 51 |
+
with self.assertRaises(ValueError):
|
| 52 |
+
GPTQConfig(bits=2, damp_percent=10)
|
| 53 |
+
GPTQConfig(bits=2, damp_percent=-1)
|
| 54 |
+
GPTQConfig(bits=2, damp_percent="0")
|
| 55 |
+
GPTQConfig(bits=2, damp_percent=0.01)
|
| 56 |
+
|
| 57 |
+
def test_to_dict(self):
|
| 58 |
+
quantization_config = GPTQConfig(bits=2)
|
| 59 |
+
quantization_config.to_dict()
|
| 60 |
+
|
| 61 |
+
def test_from_dict(self):
|
| 62 |
+
dict = {"bits": 2}
|
| 63 |
+
quantization_config = GPTQConfig.from_dict(dict)
|
| 64 |
+
self.assertEqual(dict["bits"], quantization_config.bits)
|
| 65 |
+
|
| 66 |
+
@require_optimum
|
| 67 |
+
def test_optimum_config(self):
|
| 68 |
+
from optimum.gptq import GPTQQuantizer
|
| 69 |
+
|
| 70 |
+
config = GPTQConfig(bits=2)
|
| 71 |
+
optimum_config = GPTQQuantizer.from_dict(config.to_dict_optimum())
|
| 72 |
+
self.assertEqual(optimum_config.bits, config.bits)
|
| 73 |
+
new_config = GPTQConfig.from_dict_optimum(optimum_config.to_dict())
|
| 74 |
+
self.assertEqual(optimum_config.bits, new_config.bits)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@slow
|
| 78 |
+
@require_optimum
|
| 79 |
+
@require_gptq
|
| 80 |
+
class GPTQTest(unittest.TestCase):
|
| 81 |
+
model_name = "bigscience/bloom-560m"
|
| 82 |
+
|
| 83 |
+
input_text = "Hello my name is"
|
| 84 |
+
|
| 85 |
+
EXPECTED_OUTPUTS = set()
|
| 86 |
+
# flaky test: gptqmodel and auto-gptq are not output equivalent nor is string compare deterministic even between transformer/torch versions
|
| 87 |
+
EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I")
|
| 88 |
+
EXPECTED_OUTPUTS.add("Hello my name is John, I am a professional photographer and I")
|
| 89 |
+
EXPECTED_OUTPUTS.add("Hello my name is John, I am a student in the University of")
|
| 90 |
+
EXPECTED_OUTPUTS.add("Hello my name is John and I am a very good looking man.")
|
| 91 |
+
EXPECTED_OUTPUTS.add("Hello my name is Alyson, I am a student in the")
|
| 92 |
+
EXPECTED_OUTPUTS.add("Hello my name is Alyson and I am a very sweet,")
|
| 93 |
+
EXPECTED_OUTPUTS.add("Hello my name is Aiden, I am a student at the University")
|
| 94 |
+
EXPECTED_OUTPUTS.add("Hello my name is Nate and I am a member of the N")
|
| 95 |
+
EXPECTED_OUTPUTS.add("Hello my name is Nellie and I am a student at the")
|
| 96 |
+
EXPECTED_OUTPUTS.add("Hello my name is Nate and I am a new member of the")
|
| 97 |
+
|
| 98 |
+
# this seems a little small considering that we are doing 4bit quant but we have a small model and ww don't quantize the embeddings
|
| 99 |
+
EXPECTED_RELATIVE_DIFFERENCE = 1.664253062
|
| 100 |
+
|
| 101 |
+
bits = 4
|
| 102 |
+
sym = True
|
| 103 |
+
group_size = 128
|
| 104 |
+
desc_act = False
|
| 105 |
+
use_exllama = False
|
| 106 |
+
|
| 107 |
+
dataset = [
|
| 108 |
+
"auto-gptq is an easy-to-use model quantization library with user-friendly apis, based on GPTQ algorithm."
|
| 109 |
+
]
|
| 110 |
+
|
| 111 |
+
device_map = "cpu" if is_gptqmodel_available() else None
|
| 112 |
+
|
| 113 |
+
# called only once for all test in this class
|
| 114 |
+
@classmethod
|
| 115 |
+
def setUpClass(cls):
|
| 116 |
+
"""
|
| 117 |
+
Setup quantized model
|
| 118 |
+
"""
|
| 119 |
+
cls.model_fp16 = AutoModelForCausalLM.from_pretrained(
|
| 120 |
+
cls.model_name, torch_dtype=torch.float16, device_map=cls.device_map
|
| 121 |
+
)
|
| 122 |
+
cls.mem_fp16 = cls.model_fp16.get_memory_footprint()
|
| 123 |
+
|
| 124 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name, use_fast=True)
|
| 125 |
+
cls.config = AutoConfig.from_pretrained(cls.model_name)
|
| 126 |
+
|
| 127 |
+
cls.quantization_config = GPTQConfig(
|
| 128 |
+
bits=cls.bits,
|
| 129 |
+
dataset=cls.dataset,
|
| 130 |
+
tokenizer=cls.tokenizer,
|
| 131 |
+
group_size=cls.group_size,
|
| 132 |
+
desc_act=cls.desc_act,
|
| 133 |
+
sym=cls.sym,
|
| 134 |
+
use_exllama=cls.use_exllama,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
cls.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 138 |
+
cls.model_name,
|
| 139 |
+
torch_dtype=torch.float16,
|
| 140 |
+
device_map=cls.device_map,
|
| 141 |
+
quantization_config=cls.quantization_config,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
def test_memory_footprint(self):
|
| 145 |
+
r"""
|
| 146 |
+
A simple test to check if the model conversion has been done correctly by checking on the
|
| 147 |
+
memory footprint of the converted model
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
mem_quantized = self.quantized_model.get_memory_footprint()
|
| 151 |
+
|
| 152 |
+
self.assertAlmostEqual(self.mem_fp16 / mem_quantized, self.EXPECTED_RELATIVE_DIFFERENCE, places=4)
|
| 153 |
+
|
| 154 |
+
def test_device_and_dtype_assignment(self):
|
| 155 |
+
r"""
|
| 156 |
+
Test whether trying to cast (or assigning a device to) a model after quantization will throw an error.
|
| 157 |
+
Checks also if other models are casted correctly.
|
| 158 |
+
"""
|
| 159 |
+
# This should work
|
| 160 |
+
if self.device_map in (None, "cpu"):
|
| 161 |
+
_ = self.quantized_model.to(0)
|
| 162 |
+
|
| 163 |
+
with self.assertRaises(ValueError):
|
| 164 |
+
# Tries with a `dtype``
|
| 165 |
+
self.quantized_model.to(torch.float16)
|
| 166 |
+
|
| 167 |
+
def test_original_dtype(self):
|
| 168 |
+
r"""
|
| 169 |
+
A simple test to check if the model successfully stores the original dtype
|
| 170 |
+
"""
|
| 171 |
+
self.assertTrue(hasattr(self.quantized_model.config, "_pre_quantization_dtype"))
|
| 172 |
+
self.assertFalse(hasattr(self.model_fp16.config, "_pre_quantization_dtype"))
|
| 173 |
+
self.assertTrue(self.quantized_model.config._pre_quantization_dtype == torch.float16)
|
| 174 |
+
|
| 175 |
+
def test_quantized_layers_class(self):
|
| 176 |
+
"""
|
| 177 |
+
Simple test to check if the model conversion has been done correctly by checking on
|
| 178 |
+
the class type of the linear layers of the converted models
|
| 179 |
+
"""
|
| 180 |
+
if is_gptqmodel_available():
|
| 181 |
+
from gptqmodel.utils.importer import hf_select_quant_linear
|
| 182 |
+
|
| 183 |
+
if hasattr(self.config, "quantization_config"):
|
| 184 |
+
checkpoint_format = self.config.quantization_config.get("checkpoint_format")
|
| 185 |
+
meta = self.config.quantization_config.get("meta")
|
| 186 |
+
else:
|
| 187 |
+
checkpoint_format = "gptq"
|
| 188 |
+
meta = None
|
| 189 |
+
QuantLinear = hf_select_quant_linear(
|
| 190 |
+
bits=self.bits,
|
| 191 |
+
group_size=self.group_size,
|
| 192 |
+
desc_act=self.desc_act,
|
| 193 |
+
sym=self.sym,
|
| 194 |
+
device_map=self.device_map,
|
| 195 |
+
checkpoint_format=checkpoint_format,
|
| 196 |
+
meta=meta,
|
| 197 |
+
backend=self.quantization_config.backend,
|
| 198 |
+
)
|
| 199 |
+
elif is_auto_gptq_available():
|
| 200 |
+
from auto_gptq.utils.import_utils import dynamically_import_QuantLinear as hf_select_quant_linear
|
| 201 |
+
|
| 202 |
+
QuantLinear = hf_select_quant_linear(
|
| 203 |
+
use_triton=False,
|
| 204 |
+
desc_act=self.desc_act,
|
| 205 |
+
group_size=self.group_size,
|
| 206 |
+
bits=self.bits,
|
| 207 |
+
disable_exllama=not self.use_exllama,
|
| 208 |
+
disable_exllamav2=True,
|
| 209 |
+
)
|
| 210 |
+
self.assertTrue(self.quantized_model.transformer.h[0].mlp.dense_4h_to_h.__class__ == QuantLinear)
|
| 211 |
+
|
| 212 |
+
def check_inference_correctness(self, model):
|
| 213 |
+
r"""
|
| 214 |
+
Test the generation quality of the quantized model and see that we are matching the expected output.
|
| 215 |
+
Given that we are operating on small numbers + the testing model is relatively small, we might not get
|
| 216 |
+
the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
|
| 217 |
+
"""
|
| 218 |
+
# Check that inference pass works on the model
|
| 219 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 220 |
+
|
| 221 |
+
# Check the exactness of the results
|
| 222 |
+
output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(model.device), max_new_tokens=10)
|
| 223 |
+
|
| 224 |
+
# Get the generation
|
| 225 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 226 |
+
|
| 227 |
+
def check_quantized_layers_type(self, model, value):
|
| 228 |
+
self.assertTrue(model.transformer.h[0].mlp.dense_4h_to_h.QUANT_TYPE == value)
|
| 229 |
+
|
| 230 |
+
def test_generate_quality(self):
|
| 231 |
+
"""
|
| 232 |
+
Simple test to check the quality of the model by comparing the generated tokens with the expected tokens
|
| 233 |
+
"""
|
| 234 |
+
if self.device_map is None:
|
| 235 |
+
self.check_inference_correctness(self.quantized_model.to(0))
|
| 236 |
+
else:
|
| 237 |
+
if self.device_map == "cpu" and self.quantized_model.device.type != "cpu":
|
| 238 |
+
self.quantized_model.to("cpu")
|
| 239 |
+
self.check_inference_correctness(self.quantized_model)
|
| 240 |
+
|
| 241 |
+
def test_serialization(self):
|
| 242 |
+
"""
|
| 243 |
+
Test the serialization of the model and the loading of the quantized weights works
|
| 244 |
+
"""
|
| 245 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 246 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 247 |
+
if is_auto_gptq_available() and not is_gptqmodel_available():
|
| 248 |
+
quant_type = "cuda-old" if not self.use_exllama else "exllama"
|
| 249 |
+
if not self.use_exllama:
|
| 250 |
+
quantized_model_from_saved = AutoModelForCausalLM.from_pretrained(
|
| 251 |
+
tmpdirname, quantization_config=GPTQConfig(use_exllama=False, bits=4)
|
| 252 |
+
)
|
| 253 |
+
if self.device_map != "cpu":
|
| 254 |
+
quantized_model_from_saved = quantized_model_from_saved.to(0)
|
| 255 |
+
else:
|
| 256 |
+
quantized_model_from_saved = AutoModelForCausalLM.from_pretrained(
|
| 257 |
+
tmpdirname, device_map=self.device_map
|
| 258 |
+
)
|
| 259 |
+
else:
|
| 260 |
+
if self.device_map == "cpu":
|
| 261 |
+
quant_type = "ipex" if is_ipex_available() else "torch"
|
| 262 |
+
else:
|
| 263 |
+
# We expect tritonv2 to be used here, because exllama backend doesn't support packing https://github.com/ModelCloud/GPTQModel/issues/1354
|
| 264 |
+
# TODO: Remove this once GPTQModel exllama kernels supports packing
|
| 265 |
+
quant_type = "tritonv2"
|
| 266 |
+
quantized_model_from_saved = AutoModelForCausalLM.from_pretrained(
|
| 267 |
+
tmpdirname, device_map=self.device_map
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
self.check_quantized_layers_type(quantized_model_from_saved, quant_type)
|
| 271 |
+
self.check_inference_correctness(quantized_model_from_saved)
|
| 272 |
+
|
| 273 |
+
@require_accelerate
|
| 274 |
+
def test_serialization_big_model_inference(self):
|
| 275 |
+
"""
|
| 276 |
+
Test the serialization of the model and the loading of the quantized weights with big model inference
|
| 277 |
+
"""
|
| 278 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 279 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 280 |
+
device_map = self.device_map or "auto"
|
| 281 |
+
quantized_model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=device_map)
|
| 282 |
+
self.check_inference_correctness(quantized_model_from_saved)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
@require_torch_gpu
|
| 286 |
+
class GPTQTestCUDA(GPTQTest):
|
| 287 |
+
device_map = {"": 0}
|
| 288 |
+
|
| 289 |
+
def test_change_loading_attributes(self):
|
| 290 |
+
"""
|
| 291 |
+
Test the serialization of the model and the loading of the quantized weights works with another config file
|
| 292 |
+
"""
|
| 293 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 294 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 295 |
+
if is_auto_gptq_available() and not is_gptqmodel_available() and not self.use_exllama:
|
| 296 |
+
self.check_quantized_layers_type(self.quantized_model, "cuda-old")
|
| 297 |
+
# we need to put it directly to the gpu. Otherwise, we won't be able to initialize the exllama kernel
|
| 298 |
+
quantized_model_from_saved = AutoModelForCausalLM.from_pretrained(
|
| 299 |
+
tmpdirname, quantization_config=GPTQConfig(use_exllama=True, bits=4), device_map=self.device_map
|
| 300 |
+
)
|
| 301 |
+
self.assertEqual(quantized_model_from_saved.config.quantization_config.bits, self.bits)
|
| 302 |
+
self.check_quantized_layers_type(quantized_model_from_saved, "exllama")
|
| 303 |
+
self.check_inference_correctness(quantized_model_from_saved)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
@require_accelerate
|
| 307 |
+
@require_torch_multi_gpu
|
| 308 |
+
class GPTQTestDeviceMap(GPTQTestCUDA):
|
| 309 |
+
device_map = "auto"
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
@require_accelerate
|
| 313 |
+
@require_torch_multi_gpu
|
| 314 |
+
class GPTQTestDeviceMapExllama(GPTQTestCUDA):
|
| 315 |
+
device_map = "auto"
|
| 316 |
+
use_exllama = True
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@slow
|
| 320 |
+
@require_optimum
|
| 321 |
+
@require_gptq
|
| 322 |
+
@require_torch_gpu
|
| 323 |
+
@require_accelerate
|
| 324 |
+
class GPTQTestActOrderExllama(unittest.TestCase):
|
| 325 |
+
"""
|
| 326 |
+
Test GPTQ model with exllama kernel and desc_act=True (also known as act-order).
|
| 327 |
+
More information on those arguments here:
|
| 328 |
+
https://huggingface.co/docs/transformers/main_classes/quantization#transformers.GPTQConfig
|
| 329 |
+
"""
|
| 330 |
+
|
| 331 |
+
EXPECTED_OUTPUTS = set()
|
| 332 |
+
# flaky test: gptqmodel and auto-gptq are not output equivalent nor is string compare deterministic even between transformer/torch versions
|
| 333 |
+
EXPECTED_OUTPUTS.add("Hello, how are you ? I'm doing good, thanks for asking.")
|
| 334 |
+
# 4bit + act_order + 128g
|
| 335 |
+
model_name = "hf-internal-testing/TinyLlama-1.1B-Chat-v0.3-GPTQ"
|
| 336 |
+
input_text = "Hello, how are you ?"
|
| 337 |
+
|
| 338 |
+
@classmethod
|
| 339 |
+
def setUpClass(cls):
|
| 340 |
+
"""
|
| 341 |
+
Setup quantized model
|
| 342 |
+
"""
|
| 343 |
+
cls.quantization_config = GPTQConfig(bits=4, max_input_length=4028)
|
| 344 |
+
cls.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 345 |
+
cls.model_name,
|
| 346 |
+
torch_dtype=torch.float16,
|
| 347 |
+
device_map={"": 0},
|
| 348 |
+
quantization_config=cls.quantization_config,
|
| 349 |
+
)
|
| 350 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name, use_fast=True)
|
| 351 |
+
|
| 352 |
+
def check_inference_correctness(self, model):
|
| 353 |
+
"""
|
| 354 |
+
Test the generation quality of the quantized model and see that we are matching the expected output.
|
| 355 |
+
Given that we are operating on small numbers + the testing model is relatively small, we might not get
|
| 356 |
+
the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
|
| 357 |
+
"""
|
| 358 |
+
|
| 359 |
+
# Check that inference pass works on the model
|
| 360 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 361 |
+
|
| 362 |
+
# Check the exactness of the results
|
| 363 |
+
output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10)
|
| 364 |
+
|
| 365 |
+
# Get the generation
|
| 366 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 367 |
+
|
| 368 |
+
def test_quantized_layers_type(self):
|
| 369 |
+
self.assertTrue(self.quantized_model.model.layers[0].self_attn.k_proj.QUANT_TYPE == "exllama")
|
| 370 |
+
|
| 371 |
+
def test_generate_quality(self):
|
| 372 |
+
"""
|
| 373 |
+
Simple test to check the quality of the model by comparing the generated tokens with the expected tokens
|
| 374 |
+
"""
|
| 375 |
+
self.check_inference_correctness(self.quantized_model)
|
| 376 |
+
|
| 377 |
+
def test_max_input_length(self):
|
| 378 |
+
"""
|
| 379 |
+
Test if the max_input_length works. It modifies the maximum input length that of the model that runs with exllama backend.
|
| 380 |
+
"""
|
| 381 |
+
|
| 382 |
+
prompt = "I am in Paris and" * 1000
|
| 383 |
+
inp = self.tokenizer(prompt, return_tensors="pt").to(0)
|
| 384 |
+
self.assertTrue(inp["input_ids"].shape[1] > 4028)
|
| 385 |
+
with self.assertRaises(RuntimeError) as cm:
|
| 386 |
+
self.quantized_model.generate(**inp, num_beams=1, min_new_tokens=3, max_new_tokens=3)
|
| 387 |
+
self.assertTrue("temp_state buffer is too small" in str(cm.exception))
|
| 388 |
+
|
| 389 |
+
prompt = "I am in Paris and"
|
| 390 |
+
inp = self.tokenizer(prompt, return_tensors="pt").to(0)
|
| 391 |
+
self.assertTrue(inp["input_ids"].shape[1] < 4028)
|
| 392 |
+
self.quantized_model.generate(**inp, num_beams=1, min_new_tokens=3, max_new_tokens=3)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
@slow
|
| 396 |
+
@require_optimum
|
| 397 |
+
@require_gptq
|
| 398 |
+
@require_torch_gpu
|
| 399 |
+
@require_accelerate
|
| 400 |
+
class GPTQTestExllamaV2(unittest.TestCase):
|
| 401 |
+
"""
|
| 402 |
+
Test GPTQ model with exllamav2 kernel and desc_act=True (also known as act-order).
|
| 403 |
+
More information on those arguments here:
|
| 404 |
+
https://huggingface.co/docs/transformers/main_classes/quantization#transformers.GPTQConfig
|
| 405 |
+
"""
|
| 406 |
+
|
| 407 |
+
EXPECTED_OUTPUTS = set()
|
| 408 |
+
# flaky test: gptqmodel and auto-gptq are not output equivalent nor is string compare deterministic even between transformer/torch versions
|
| 409 |
+
EXPECTED_OUTPUTS.add("Hello, how are you ? I'm doing good, thanks for asking.")
|
| 410 |
+
# 4bit + act_order + 128g
|
| 411 |
+
model_name = "hf-internal-testing/TinyLlama-1.1B-Chat-v0.3-GPTQ"
|
| 412 |
+
input_text = "Hello, how are you ?"
|
| 413 |
+
|
| 414 |
+
@classmethod
|
| 415 |
+
def setUpClass(cls):
|
| 416 |
+
"""
|
| 417 |
+
Setup quantized model
|
| 418 |
+
"""
|
| 419 |
+
cls.quantization_config = GPTQConfig(bits=4, exllama_config={"version": 2})
|
| 420 |
+
cls.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 421 |
+
cls.model_name,
|
| 422 |
+
torch_dtype=torch.float16,
|
| 423 |
+
device_map={"": 0},
|
| 424 |
+
quantization_config=cls.quantization_config,
|
| 425 |
+
)
|
| 426 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name, use_fast=True)
|
| 427 |
+
|
| 428 |
+
def test_quantized_layers_type(self):
|
| 429 |
+
if is_auto_gptq_available() and not is_gptqmodel_available():
|
| 430 |
+
self.assertEqual(
|
| 431 |
+
self.quantized_model.model.layers[0].self_attn.k_proj.QUANT_TYPE,
|
| 432 |
+
"exllamav2",
|
| 433 |
+
)
|
| 434 |
+
else:
|
| 435 |
+
# We expect tritonv2 to be used here, because exllama backend doesn't support packing https://github.com/ModelCloud/GPTQModel/issues/1354
|
| 436 |
+
# TODO: Remove this once GPTQModel exllama kernels supports packing
|
| 437 |
+
self.assertEqual(
|
| 438 |
+
self.quantized_model.model.layers[0].self_attn.k_proj.QUANT_TYPE,
|
| 439 |
+
"tritonv2",
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
def check_inference_correctness(self, model):
|
| 443 |
+
"""
|
| 444 |
+
Test the generation quality of the quantized model and see that we are matching the expected output.
|
| 445 |
+
Given that we are operating on small numbers + the testing model is relatively small, we might not get
|
| 446 |
+
the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
|
| 447 |
+
"""
|
| 448 |
+
|
| 449 |
+
# Check that inference pass works on the model
|
| 450 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 451 |
+
|
| 452 |
+
# Check the exactness of the results
|
| 453 |
+
output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10)
|
| 454 |
+
|
| 455 |
+
# Get the generation
|
| 456 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 457 |
+
|
| 458 |
+
def test_generate_quality(self):
|
| 459 |
+
"""
|
| 460 |
+
Simple test to check the quality of the model by comparing the generated tokens with the expected tokens
|
| 461 |
+
"""
|
| 462 |
+
self.check_inference_correctness(self.quantized_model)
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
# fail when run all together
|
| 466 |
+
@pytest.mark.skip
|
| 467 |
+
@require_accelerate
|
| 468 |
+
@require_torch_multi_gpu
|
| 469 |
+
class GPTQTestDeviceMapCPUOffload(GPTQTest):
|
| 470 |
+
device_map = {
|
| 471 |
+
"transformer.word_embeddings": 0,
|
| 472 |
+
"transformer.word_embeddings_layernorm": 0,
|
| 473 |
+
"lm_head": 0,
|
| 474 |
+
"transformer.h.0": 0,
|
| 475 |
+
"transformer.h.1": 0,
|
| 476 |
+
"transformer.h.2": 0,
|
| 477 |
+
"transformer.h.3": 0,
|
| 478 |
+
"transformer.h.4": 0,
|
| 479 |
+
"transformer.h.5": 0,
|
| 480 |
+
"transformer.h.6": 0,
|
| 481 |
+
"transformer.h.7": 0,
|
| 482 |
+
"transformer.h.8": 0,
|
| 483 |
+
"transformer.h.9": 0,
|
| 484 |
+
"transformer.h.10": 1,
|
| 485 |
+
"transformer.h.11": 1,
|
| 486 |
+
"transformer.h.12": 1,
|
| 487 |
+
"transformer.h.13": 1,
|
| 488 |
+
"transformer.h.14": 1,
|
| 489 |
+
"transformer.h.15": 1,
|
| 490 |
+
"transformer.h.16": 1,
|
| 491 |
+
"transformer.h.17": 0,
|
| 492 |
+
"transformer.h.18": "cpu",
|
| 493 |
+
"transformer.h.19": "cpu",
|
| 494 |
+
"transformer.h.20": "cpu",
|
| 495 |
+
"transformer.h.21": "cpu",
|
| 496 |
+
"transformer.h.22": "cpu",
|
| 497 |
+
"transformer.h.23": 1,
|
| 498 |
+
"transformer.ln_f": 0,
|
| 499 |
+
}
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/higgs/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/higgs/test_higgs.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import tempfile
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HiggsConfig, OPTForCausalLM
|
| 20 |
+
from transformers.testing_utils import (
|
| 21 |
+
backend_empty_cache,
|
| 22 |
+
require_accelerate,
|
| 23 |
+
require_flute_hadamard,
|
| 24 |
+
require_torch_gpu,
|
| 25 |
+
require_torch_multi_gpu,
|
| 26 |
+
slow,
|
| 27 |
+
torch_device,
|
| 28 |
+
)
|
| 29 |
+
from transformers.utils import is_accelerate_available, is_torch_available
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if is_torch_available():
|
| 33 |
+
import torch
|
| 34 |
+
|
| 35 |
+
if is_accelerate_available():
|
| 36 |
+
from accelerate import init_empty_weights
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@require_torch_gpu
|
| 40 |
+
class HiggsConfigTest(unittest.TestCase):
|
| 41 |
+
def test_to_dict(self):
|
| 42 |
+
"""
|
| 43 |
+
Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object
|
| 44 |
+
"""
|
| 45 |
+
quantization_config = HiggsConfig()
|
| 46 |
+
config_to_dict = quantization_config.to_dict()
|
| 47 |
+
|
| 48 |
+
for key in config_to_dict:
|
| 49 |
+
self.assertEqual(getattr(quantization_config, key), config_to_dict[key])
|
| 50 |
+
|
| 51 |
+
def test_from_dict(self):
|
| 52 |
+
"""
|
| 53 |
+
Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict
|
| 54 |
+
"""
|
| 55 |
+
dict = {"modules_to_not_convert": ["embed_tokens", "lm_head"], "quant_method": "higgs"}
|
| 56 |
+
quantization_config = HiggsConfig.from_dict(dict)
|
| 57 |
+
|
| 58 |
+
self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert)
|
| 59 |
+
self.assertEqual(dict["quant_method"], quantization_config.quant_method)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@slow
|
| 63 |
+
@require_torch_gpu
|
| 64 |
+
@require_flute_hadamard
|
| 65 |
+
@require_accelerate
|
| 66 |
+
# @require_read_token
|
| 67 |
+
class HiggsTest(unittest.TestCase):
|
| 68 |
+
model_name = "unsloth/Llama-3.2-1B"
|
| 69 |
+
|
| 70 |
+
input_text = "Font test: A quick brown fox jumps over the"
|
| 71 |
+
max_new_tokens = 2
|
| 72 |
+
|
| 73 |
+
EXPECTED_OUTPUT = "Font test: A quick brown fox jumps over the lazy dog"
|
| 74 |
+
|
| 75 |
+
device_map = "cuda"
|
| 76 |
+
|
| 77 |
+
# called only once for all test in this class
|
| 78 |
+
@classmethod
|
| 79 |
+
def setUpClass(cls):
|
| 80 |
+
"""
|
| 81 |
+
Setup quantized model
|
| 82 |
+
"""
|
| 83 |
+
quantization_config = HiggsConfig()
|
| 84 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name)
|
| 85 |
+
cls.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 86 |
+
cls.model_name, device_map=cls.device_map, quantization_config=quantization_config
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
def tearDown(self):
|
| 90 |
+
gc.collect()
|
| 91 |
+
backend_empty_cache(torch_device)
|
| 92 |
+
gc.collect()
|
| 93 |
+
|
| 94 |
+
def test_quantized_model_conversion(self):
|
| 95 |
+
"""
|
| 96 |
+
Simple test that checks if the quantized model has been converted properly
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
from transformers.integrations import HiggsLinear, replace_with_higgs_linear
|
| 100 |
+
|
| 101 |
+
model_id = "facebook/opt-350m"
|
| 102 |
+
config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5")
|
| 103 |
+
quantization_config = HiggsConfig()
|
| 104 |
+
|
| 105 |
+
with init_empty_weights():
|
| 106 |
+
model = OPTForCausalLM(config)
|
| 107 |
+
|
| 108 |
+
nb_linears = 0
|
| 109 |
+
for module in model.modules():
|
| 110 |
+
if isinstance(module, torch.nn.Linear):
|
| 111 |
+
nb_linears += 1
|
| 112 |
+
|
| 113 |
+
model, _ = replace_with_higgs_linear(model, quantization_config=quantization_config)
|
| 114 |
+
nb_higgs_linear = 0
|
| 115 |
+
for module in model.modules():
|
| 116 |
+
if isinstance(module, HiggsLinear):
|
| 117 |
+
nb_higgs_linear += 1
|
| 118 |
+
|
| 119 |
+
self.assertEqual(nb_linears - 1, nb_higgs_linear)
|
| 120 |
+
|
| 121 |
+
with init_empty_weights():
|
| 122 |
+
model = OPTForCausalLM(config)
|
| 123 |
+
quantization_config = HiggsConfig(modules_to_not_convert=["fc1"])
|
| 124 |
+
model, _ = replace_with_higgs_linear(model, quantization_config=quantization_config)
|
| 125 |
+
nb_higgs_linear = 0
|
| 126 |
+
for module in model.modules():
|
| 127 |
+
if isinstance(module, HiggsLinear):
|
| 128 |
+
nb_higgs_linear += 1
|
| 129 |
+
|
| 130 |
+
self.assertEqual(nb_linears - 24, nb_higgs_linear)
|
| 131 |
+
|
| 132 |
+
def test_quantized_model(self):
|
| 133 |
+
"""
|
| 134 |
+
Simple test that checks if the quantized model is working properly
|
| 135 |
+
"""
|
| 136 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 137 |
+
|
| 138 |
+
output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 139 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 140 |
+
|
| 141 |
+
def test_save_pretrained(self):
|
| 142 |
+
"""
|
| 143 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 144 |
+
"""
|
| 145 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 146 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 147 |
+
|
| 148 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map)
|
| 149 |
+
|
| 150 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 151 |
+
|
| 152 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 153 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 154 |
+
|
| 155 |
+
@require_torch_multi_gpu
|
| 156 |
+
def test_quantized_model_multi_gpu(self):
|
| 157 |
+
"""
|
| 158 |
+
Simple test that checks if the quantized model is working properly with multiple GPUs
|
| 159 |
+
set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs
|
| 160 |
+
"""
|
| 161 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 162 |
+
quantization_config = HiggsConfig()
|
| 163 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 164 |
+
self.model_name, device_map="auto", quantization_config=quantization_config
|
| 165 |
+
)
|
| 166 |
+
self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1})
|
| 167 |
+
|
| 168 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 169 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 170 |
+
|
| 171 |
+
@require_torch_multi_gpu
|
| 172 |
+
def test_save_pretrained_multi_gpu(self):
|
| 173 |
+
"""
|
| 174 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 175 |
+
"""
|
| 176 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 177 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 178 |
+
|
| 179 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="auto")
|
| 180 |
+
self.assertTrue(set(model.hf_device_map.values()) == {0, 1})
|
| 181 |
+
|
| 182 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 183 |
+
|
| 184 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 185 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 186 |
+
|
| 187 |
+
@unittest.skip("This will almost surely OOM. Enable when switched to a smaller model")
|
| 188 |
+
def test_dequantize(self):
|
| 189 |
+
"""
|
| 190 |
+
Test the ability to dequantize a model
|
| 191 |
+
"""
|
| 192 |
+
self.quantized_model.dequantize()
|
| 193 |
+
|
| 194 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 195 |
+
|
| 196 |
+
output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 197 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/hqq/test_hqq.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import unittest
|
| 17 |
+
|
| 18 |
+
import accelerate
|
| 19 |
+
|
| 20 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, HqqConfig
|
| 21 |
+
from transformers.testing_utils import (
|
| 22 |
+
backend_empty_cache,
|
| 23 |
+
require_accelerate,
|
| 24 |
+
require_deterministic_for_xpu,
|
| 25 |
+
require_hqq,
|
| 26 |
+
require_torch_accelerator,
|
| 27 |
+
require_torch_multi_accelerator,
|
| 28 |
+
slow,
|
| 29 |
+
torch_device,
|
| 30 |
+
)
|
| 31 |
+
from transformers.utils import is_hqq_available, is_torch_available
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if is_torch_available():
|
| 35 |
+
import torch
|
| 36 |
+
|
| 37 |
+
if is_hqq_available():
|
| 38 |
+
from hqq.core.quantize import HQQBackend, HQQLinear
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class HQQLLMRunner:
|
| 42 |
+
def __init__(self, model_id, quant_config, compute_dtype, device, cache_dir=None):
|
| 43 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 44 |
+
model_id,
|
| 45 |
+
torch_dtype=compute_dtype,
|
| 46 |
+
device_map=device,
|
| 47 |
+
quantization_config=quant_config,
|
| 48 |
+
cache_dir=cache_dir,
|
| 49 |
+
)
|
| 50 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_id, cache_dir=cache_dir)
|
| 51 |
+
self.device = self.model.device
|
| 52 |
+
HQQLinear.set_backend(HQQBackend.PYTORCH)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def cleanup():
|
| 56 |
+
backend_empty_cache(torch_device)
|
| 57 |
+
gc.collect()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def check_hqqlayer(test_module, hqq_layer, batch_size=1, context_size=1024):
|
| 61 |
+
# Test HQQ layer
|
| 62 |
+
W_dequant = hqq_layer.dequantize() # Reconstructed weights
|
| 63 |
+
inputs = (
|
| 64 |
+
torch.randn(
|
| 65 |
+
(batch_size, context_size, hqq_layer.meta["shape"][1]),
|
| 66 |
+
device=hqq_layer.device,
|
| 67 |
+
dtype=hqq_layer.compute_dtype,
|
| 68 |
+
)
|
| 69 |
+
/ 10.0
|
| 70 |
+
)
|
| 71 |
+
with torch.no_grad():
|
| 72 |
+
outputs = hqq_layer(inputs)
|
| 73 |
+
test_module.assertEqual(outputs.shape[-1], W_dequant.shape[0])
|
| 74 |
+
test_module.assertEqual(outputs.dtype, hqq_layer.compute_dtype)
|
| 75 |
+
del W_dequant, inputs, outputs
|
| 76 |
+
cleanup()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def check_forward(test_module, model, batch_size=1, context_size=1024):
|
| 80 |
+
# Test forward pass
|
| 81 |
+
with torch.no_grad():
|
| 82 |
+
out = model(torch.zeros([batch_size, context_size], device=model.device, dtype=torch.int32)).logits
|
| 83 |
+
test_module.assertEqual(out.shape[0], batch_size)
|
| 84 |
+
test_module.assertEqual(out.shape[1], context_size)
|
| 85 |
+
cleanup()
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
MODEL_ID = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@require_torch_accelerator
|
| 92 |
+
@require_hqq
|
| 93 |
+
class HqqConfigTest(unittest.TestCase):
|
| 94 |
+
def test_to_dict(self):
|
| 95 |
+
"""
|
| 96 |
+
Makes sure the config format is properly set
|
| 97 |
+
"""
|
| 98 |
+
quantization_config = HqqConfig()
|
| 99 |
+
hqq_orig_config = quantization_config.to_dict()
|
| 100 |
+
|
| 101 |
+
self.assertEqual(quantization_config.quant_config, hqq_orig_config["quant_config"])
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@slow
|
| 105 |
+
@require_torch_accelerator
|
| 106 |
+
@require_accelerate
|
| 107 |
+
@require_hqq
|
| 108 |
+
class HQQTest(unittest.TestCase):
|
| 109 |
+
def tearDown(self):
|
| 110 |
+
cleanup()
|
| 111 |
+
|
| 112 |
+
def test_fp16_quantized_model(self):
|
| 113 |
+
"""
|
| 114 |
+
Simple LLM model testing fp16
|
| 115 |
+
"""
|
| 116 |
+
quant_config = HqqConfig(nbits=8, group_size=64)
|
| 117 |
+
|
| 118 |
+
hqq_runner = HQQLLMRunner(
|
| 119 |
+
model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj)
|
| 123 |
+
check_forward(self, hqq_runner.model)
|
| 124 |
+
|
| 125 |
+
def test_quantized_model_to_new_device_and_new_dtype(self):
|
| 126 |
+
"""
|
| 127 |
+
Simple LLM model testing different devices and dtypes
|
| 128 |
+
"""
|
| 129 |
+
quant_config = HqqConfig(nbits=8, group_size=64)
|
| 130 |
+
|
| 131 |
+
hqq_runner = HQQLLMRunner(
|
| 132 |
+
model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj)
|
| 136 |
+
check_forward(self, hqq_runner.model)
|
| 137 |
+
|
| 138 |
+
# Remove `accelerate` hooks to enable move the model to a new device
|
| 139 |
+
accelerate.hooks.remove_hook_from_module(hqq_runner.model, recurse=True)
|
| 140 |
+
|
| 141 |
+
hqq_runner.model.to("cpu", torch.bfloat16)
|
| 142 |
+
check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj)
|
| 143 |
+
check_forward(self, hqq_runner.model)
|
| 144 |
+
|
| 145 |
+
hqq_runner.model.to(torch_device)
|
| 146 |
+
check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj)
|
| 147 |
+
check_forward(self, hqq_runner.model)
|
| 148 |
+
|
| 149 |
+
def test_quantized_model_fake_weight_dtype(self):
|
| 150 |
+
quant_config = HqqConfig(nbits=8, group_size=64)
|
| 151 |
+
|
| 152 |
+
hqq_runner = HQQLLMRunner(
|
| 153 |
+
model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
# We use a hack to inject a fake weight to HQQLinear. Check that it works
|
| 157 |
+
self.assertEqual(hqq_runner.model.model.layers[0].self_attn.v_proj.weight.dtype, torch.float16)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@slow
|
| 161 |
+
@require_torch_accelerator
|
| 162 |
+
@require_torch_multi_accelerator
|
| 163 |
+
@require_accelerate
|
| 164 |
+
@require_hqq
|
| 165 |
+
class HQQTestMultiGPU(unittest.TestCase):
|
| 166 |
+
def tearDown(self):
|
| 167 |
+
cleanup()
|
| 168 |
+
|
| 169 |
+
def test_fp16_quantized_model_multipgpu(self):
|
| 170 |
+
"""
|
| 171 |
+
Simple LLM model testing fp16 with multi-gpu
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
quant_config = HqqConfig(nbits=8, group_size=64)
|
| 175 |
+
|
| 176 |
+
hqq_runner = HQQLLMRunner(
|
| 177 |
+
model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device="auto"
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj)
|
| 181 |
+
check_forward(self, hqq_runner.model)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@slow
|
| 185 |
+
@require_torch_accelerator
|
| 186 |
+
@require_accelerate
|
| 187 |
+
@require_hqq
|
| 188 |
+
class HQQTestBias(unittest.TestCase):
|
| 189 |
+
def tearDown(self):
|
| 190 |
+
cleanup()
|
| 191 |
+
|
| 192 |
+
def test_fp16_quantized_model(self):
|
| 193 |
+
"""
|
| 194 |
+
Simple LLM model testing fp16 with bias
|
| 195 |
+
"""
|
| 196 |
+
quant_config = HqqConfig(nbits=8, group_size=64)
|
| 197 |
+
|
| 198 |
+
hqq_runner = HQQLLMRunner(
|
| 199 |
+
model_id="facebook/opt-125m", quant_config=quant_config, compute_dtype=torch.float16, device=torch_device
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
check_hqqlayer(self, hqq_runner.model.model.decoder.layers[0].self_attn.v_proj)
|
| 203 |
+
check_forward(self, hqq_runner.model)
|
| 204 |
+
|
| 205 |
+
@require_deterministic_for_xpu
|
| 206 |
+
def test_save_and_load_quantized_model(self):
|
| 207 |
+
"""
|
| 208 |
+
Test saving and loading a quantized model with bias
|
| 209 |
+
"""
|
| 210 |
+
import tempfile
|
| 211 |
+
|
| 212 |
+
quant_config = HqqConfig(nbits=8, group_size=64)
|
| 213 |
+
|
| 214 |
+
hqq_runner = HQQLLMRunner(
|
| 215 |
+
model_id="facebook/opt-125m", quant_config=quant_config, compute_dtype=torch.float16, device=torch_device
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
input_tensor = torch.zeros((1, 8), dtype=torch.int32, device=torch_device)
|
| 219 |
+
|
| 220 |
+
# Get reference logits
|
| 221 |
+
with torch.no_grad():
|
| 222 |
+
logits_ref = hqq_runner.model.forward(input_tensor).logits
|
| 223 |
+
|
| 224 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 225 |
+
hqq_runner.model.save_pretrained(tmpdirname)
|
| 226 |
+
|
| 227 |
+
del hqq_runner.model
|
| 228 |
+
backend_empty_cache(torch_device)
|
| 229 |
+
|
| 230 |
+
model_loaded = AutoModelForCausalLM.from_pretrained(
|
| 231 |
+
tmpdirname, torch_dtype=torch.float16, device_map=torch_device
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
with torch.no_grad():
|
| 235 |
+
logits_loaded = model_loaded.forward(input_tensor).logits
|
| 236 |
+
|
| 237 |
+
self.assertEqual((logits_loaded - logits_ref).abs().mean().item(), 0)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
@slow
|
| 241 |
+
@require_torch_accelerator
|
| 242 |
+
@require_accelerate
|
| 243 |
+
@require_hqq
|
| 244 |
+
class HQQSerializationTest(unittest.TestCase):
|
| 245 |
+
def tearDown(self):
|
| 246 |
+
cleanup()
|
| 247 |
+
|
| 248 |
+
def test_model_serialization(self):
|
| 249 |
+
"""
|
| 250 |
+
Simple HQQ LLM save/load test
|
| 251 |
+
"""
|
| 252 |
+
quant_config = HqqConfig(nbits=4, group_size=64)
|
| 253 |
+
|
| 254 |
+
hqq_runner = HQQLLMRunner(
|
| 255 |
+
model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
input_tensor = torch.zeros((1, 8), dtype=torch.int32, device=torch_device)
|
| 259 |
+
|
| 260 |
+
with torch.no_grad():
|
| 261 |
+
logits_ref = hqq_runner.model.forward(input_tensor).logits
|
| 262 |
+
|
| 263 |
+
# Save
|
| 264 |
+
saved_model_id = "quant_model"
|
| 265 |
+
hqq_runner.model.save_pretrained(saved_model_id)
|
| 266 |
+
|
| 267 |
+
# Remove old model
|
| 268 |
+
del hqq_runner.model
|
| 269 |
+
backend_empty_cache(torch_device)
|
| 270 |
+
|
| 271 |
+
# Load and check if the logits match
|
| 272 |
+
model_loaded = AutoModelForCausalLM.from_pretrained(
|
| 273 |
+
"quant_model",
|
| 274 |
+
torch_dtype=torch.float16,
|
| 275 |
+
device_map=torch_device,
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
with torch.no_grad():
|
| 279 |
+
logits_loaded = model_loaded.forward(input_tensor).logits
|
| 280 |
+
|
| 281 |
+
self.assertEqual((logits_loaded - logits_ref).abs().mean().item(), 0)
|
| 282 |
+
|
| 283 |
+
def test_model_serialization_dynamic_quant_with_skip(self):
|
| 284 |
+
"""
|
| 285 |
+
Simple HQQ LLM save/load test with dynamic quant
|
| 286 |
+
"""
|
| 287 |
+
q4_config = {"nbits": 4, "group_size": 64}
|
| 288 |
+
q3_config = {"nbits": 3, "group_size": 64}
|
| 289 |
+
|
| 290 |
+
quant_config = HqqConfig(
|
| 291 |
+
dynamic_config={
|
| 292 |
+
"self_attn.q_proj": q4_config,
|
| 293 |
+
"self_attn.k_proj": q4_config,
|
| 294 |
+
"self_attn.v_proj": q4_config,
|
| 295 |
+
"self_attn.o_proj": q4_config,
|
| 296 |
+
"mlp.gate_proj": q3_config,
|
| 297 |
+
"mlp.up_proj": q3_config,
|
| 298 |
+
},
|
| 299 |
+
skip_modules=["lm_head", "down_proj"],
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
hqq_runner = HQQLLMRunner(
|
| 303 |
+
model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
model = hqq_runner.model
|
| 307 |
+
|
| 308 |
+
input_tensor = torch.zeros((1, 8), dtype=torch.int32, device=torch_device)
|
| 309 |
+
with torch.no_grad():
|
| 310 |
+
model.forward(input_tensor).logits
|
| 311 |
+
|
| 312 |
+
self.assertEqual(isinstance(model.model.layers[1].mlp.down_proj, torch.nn.Linear), True)
|
| 313 |
+
self.assertEqual(model.model.layers[1].self_attn.v_proj.quant_config["weight_quant_params"]["nbits"], 4)
|
| 314 |
+
self.assertEqual(model.model.layers[1].mlp.gate_proj.quant_config["weight_quant_params"]["nbits"], 3)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/mxfp4/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/mxfp4/test_mxfp4.py
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import unittest
|
| 17 |
+
from unittest.mock import patch
|
| 18 |
+
|
| 19 |
+
from transformers import AutoTokenizer, GptOssForCausalLM, Mxfp4Config
|
| 20 |
+
from transformers.testing_utils import (
|
| 21 |
+
require_kernels,
|
| 22 |
+
require_torch,
|
| 23 |
+
require_torch_gpu,
|
| 24 |
+
require_torch_large_gpu,
|
| 25 |
+
require_triton,
|
| 26 |
+
slow,
|
| 27 |
+
)
|
| 28 |
+
from transformers.utils import (
|
| 29 |
+
is_torch_available,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if is_torch_available():
|
| 34 |
+
import torch
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class Mxfp4ConfigTest(unittest.TestCase):
|
| 38 |
+
def test_basic_config_creation(self):
|
| 39 |
+
"""Test basic configuration creation with default values"""
|
| 40 |
+
config = Mxfp4Config()
|
| 41 |
+
self.assertEqual(config.quant_method.value, "mxfp4")
|
| 42 |
+
self.assertIsNone(config.modules_to_not_convert)
|
| 43 |
+
self.assertFalse(config.dequantize)
|
| 44 |
+
|
| 45 |
+
def test_config_with_modules_to_not_convert(self):
|
| 46 |
+
"""Test configuration with modules to not convert"""
|
| 47 |
+
modules = ["model.layers.*.self_attn", "lm_head"]
|
| 48 |
+
config = Mxfp4Config(modules_to_not_convert=modules)
|
| 49 |
+
self.assertEqual(config.modules_to_not_convert, modules)
|
| 50 |
+
|
| 51 |
+
def test_config_with_dequantize(self):
|
| 52 |
+
"""Test configuration with dequantize enabled"""
|
| 53 |
+
config = Mxfp4Config(dequantize=True)
|
| 54 |
+
self.assertTrue(config.dequantize)
|
| 55 |
+
|
| 56 |
+
def test_get_loading_attributes(self):
|
| 57 |
+
"""Test get_loading_attributes method"""
|
| 58 |
+
config = Mxfp4Config(dequantize=True)
|
| 59 |
+
attrs = config.get_loading_attributes()
|
| 60 |
+
self.assertEqual(attrs, {"dequantize": True})
|
| 61 |
+
|
| 62 |
+
def test_to_dict(self):
|
| 63 |
+
"""Test configuration serialization to dict"""
|
| 64 |
+
config = Mxfp4Config(modules_to_not_convert=["lm_head"], dequantize=True)
|
| 65 |
+
config_dict = config.to_dict()
|
| 66 |
+
self.assertEqual(config_dict["quant_method"], "mxfp4")
|
| 67 |
+
self.assertEqual(config_dict["modules_to_not_convert"], ["lm_head"])
|
| 68 |
+
self.assertTrue(config_dict["dequantize"])
|
| 69 |
+
|
| 70 |
+
def test_from_dict(self):
|
| 71 |
+
"""Test configuration creation from dict"""
|
| 72 |
+
config_dict = {"quant_method": "mxfp4", "modules_to_not_convert": ["lm_head"], "dequantize": True}
|
| 73 |
+
config = Mxfp4Config.from_dict(config_dict)
|
| 74 |
+
self.assertEqual(config.modules_to_not_convert, ["lm_head"])
|
| 75 |
+
self.assertTrue(config.dequantize)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class Mxfp4QuantizerTest(unittest.TestCase):
|
| 79 |
+
"""Test the Mxfp4HfQuantizer class"""
|
| 80 |
+
|
| 81 |
+
def setUp(self):
|
| 82 |
+
gc.collect()
|
| 83 |
+
if torch.cuda.is_available():
|
| 84 |
+
torch.cuda.empty_cache()
|
| 85 |
+
|
| 86 |
+
def test_quantizer_validation_no_torch(self):
|
| 87 |
+
"""Test quantizer validation when torch is not available"""
|
| 88 |
+
with patch("transformers.quantizers.quantizer_mxfp4.is_torch_available", return_value=False):
|
| 89 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 90 |
+
|
| 91 |
+
config = Mxfp4Config()
|
| 92 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 93 |
+
|
| 94 |
+
with self.assertRaises(ImportError):
|
| 95 |
+
quantizer.validate_environment()
|
| 96 |
+
|
| 97 |
+
def test_quantizer_validation_no_cuda(self):
|
| 98 |
+
"""Test quantizer validation when CUDA is not available"""
|
| 99 |
+
with patch("torch.cuda.is_available", return_value=False):
|
| 100 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 101 |
+
|
| 102 |
+
config = Mxfp4Config()
|
| 103 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 104 |
+
|
| 105 |
+
with self.assertRaises(RuntimeError):
|
| 106 |
+
quantizer.validate_environment()
|
| 107 |
+
|
| 108 |
+
def test_quantizer_validation_low_compute_capability(self):
|
| 109 |
+
"""Test quantizer validation with low compute capability"""
|
| 110 |
+
with patch("torch.cuda.get_device_capability", return_value=(7, 0)):
|
| 111 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 112 |
+
|
| 113 |
+
config = Mxfp4Config()
|
| 114 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 115 |
+
quantizer.pre_quantized = False
|
| 116 |
+
|
| 117 |
+
with self.assertRaises(ValueError):
|
| 118 |
+
quantizer.validate_environment()
|
| 119 |
+
|
| 120 |
+
def test_quantizer_validation_low_compute_capability_with_prequantized(self):
|
| 121 |
+
"""Test quantizer validation with low compute capability"""
|
| 122 |
+
with patch("torch.cuda.get_device_capability", return_value=(7, 0)):
|
| 123 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 124 |
+
|
| 125 |
+
config = Mxfp4Config()
|
| 126 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 127 |
+
|
| 128 |
+
# Should automatically set dequantize=True and warn
|
| 129 |
+
quantizer.validate_environment()
|
| 130 |
+
self.assertTrue(quantizer.quantization_config.dequantize)
|
| 131 |
+
|
| 132 |
+
def test_quantizer_validation_low_compute_capability_with_dequantize(self):
|
| 133 |
+
"""Test quantizer validation with low compute capability but dequantize enabled"""
|
| 134 |
+
with patch("torch.cuda.get_device_capability", return_value=(7, 0)):
|
| 135 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 136 |
+
|
| 137 |
+
config = Mxfp4Config(dequantize=True)
|
| 138 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 139 |
+
|
| 140 |
+
# Should not raise error with dequantize=True
|
| 141 |
+
try:
|
| 142 |
+
quantizer.validate_environment()
|
| 143 |
+
except ValueError as e:
|
| 144 |
+
if "compute capability" in str(e):
|
| 145 |
+
self.fail("Should not raise compute capability error when dequantize=True")
|
| 146 |
+
|
| 147 |
+
def test_quantizer_validation_dequantize_on_cpu(self):
|
| 148 |
+
"""Test quantizer validation with dequantize enabled on CPU-only environment"""
|
| 149 |
+
with patch("torch.cuda.is_available", return_value=False):
|
| 150 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 151 |
+
|
| 152 |
+
config = Mxfp4Config(dequantize=True)
|
| 153 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 154 |
+
|
| 155 |
+
# Should not raise error when dequantize=True even without CUDA
|
| 156 |
+
try:
|
| 157 |
+
quantizer.validate_environment()
|
| 158 |
+
except RuntimeError as e:
|
| 159 |
+
if "requires a GPU" in str(e):
|
| 160 |
+
self.fail("Should not raise GPU requirement error when dequantize=True on CPU")
|
| 161 |
+
|
| 162 |
+
def test_quantizer_validation_order_dequantize_before_cuda_check(self):
|
| 163 |
+
"""Test that dequantize check happens before CUDA availability check"""
|
| 164 |
+
# Mock both torch.cuda.is_available and is_accelerate_available to return False
|
| 165 |
+
with (
|
| 166 |
+
patch("torch.cuda.is_available", return_value=False),
|
| 167 |
+
patch(
|
| 168 |
+
"transformers.quantizers.quantizer_mxfp4.is_accelerate_available",
|
| 169 |
+
return_value=False,
|
| 170 |
+
),
|
| 171 |
+
):
|
| 172 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 173 |
+
|
| 174 |
+
# Test with dequantize=True - should pass even without CUDA and accelerate
|
| 175 |
+
config = Mxfp4Config(dequantize=True)
|
| 176 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 177 |
+
|
| 178 |
+
# This should not raise any error because dequantize check comes first
|
| 179 |
+
try:
|
| 180 |
+
quantizer.validate_environment()
|
| 181 |
+
except (RuntimeError, ImportError) as e:
|
| 182 |
+
if "requires a GPU" in str(e) or "requires Accelerate" in str(e):
|
| 183 |
+
self.fail(f"Should not raise error when dequantize=True: {e}")
|
| 184 |
+
|
| 185 |
+
# Test with dequantize=False - should still fail due to missing CUDA
|
| 186 |
+
config = Mxfp4Config(dequantize=False)
|
| 187 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 188 |
+
|
| 189 |
+
with self.assertRaises(RuntimeError) as context:
|
| 190 |
+
quantizer.validate_environment()
|
| 191 |
+
self.assertIn("requires a GPU", str(context.exception))
|
| 192 |
+
|
| 193 |
+
def test_quantizer_validation_missing_triton(self):
|
| 194 |
+
"""Test quantizer validation when triton is not available"""
|
| 195 |
+
with (
|
| 196 |
+
patch("transformers.quantizers.quantizer_mxfp4.is_triton_available", return_value=False),
|
| 197 |
+
patch("transformers.quantizers.quantizer_mxfp4.is_kernels_availalble", return_value=False),
|
| 198 |
+
):
|
| 199 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 200 |
+
|
| 201 |
+
config = Mxfp4Config()
|
| 202 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 203 |
+
quantizer.pre_quantized = False
|
| 204 |
+
with self.assertRaises(ValueError):
|
| 205 |
+
quantizer.validate_environment()
|
| 206 |
+
|
| 207 |
+
def test_quantizer_validation_missing_triton_pre_quantized_no_dequantize(self):
|
| 208 |
+
"""Test quantizer validation when triton is not available but model is pre-quantized and dequantize is False"""
|
| 209 |
+
with (
|
| 210 |
+
patch("transformers.quantizers.quantizer_mxfp4.is_triton_available", return_value=False),
|
| 211 |
+
patch("transformers.quantizers.quantizer_mxfp4.is_kernels_availalble", return_value=False),
|
| 212 |
+
):
|
| 213 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 214 |
+
|
| 215 |
+
config = Mxfp4Config()
|
| 216 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 217 |
+
quantizer.pre_quantized = True
|
| 218 |
+
|
| 219 |
+
# Should automatically set dequantize=True and warn
|
| 220 |
+
quantizer.validate_environment()
|
| 221 |
+
self.assertTrue(quantizer.quantization_config.dequantize)
|
| 222 |
+
|
| 223 |
+
def test_update_torch_dtype(self):
|
| 224 |
+
"""Test torch dtype updating"""
|
| 225 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 226 |
+
|
| 227 |
+
config = Mxfp4Config()
|
| 228 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 229 |
+
|
| 230 |
+
# Should default to bfloat16
|
| 231 |
+
result_dtype = quantizer.update_torch_dtype(None)
|
| 232 |
+
self.assertEqual(result_dtype, torch.bfloat16)
|
| 233 |
+
|
| 234 |
+
# Should preserve existing dtype
|
| 235 |
+
result_dtype = quantizer.update_torch_dtype(torch.float32)
|
| 236 |
+
self.assertEqual(result_dtype, torch.float32)
|
| 237 |
+
|
| 238 |
+
def test_update_expected_keys(self):
|
| 239 |
+
"""Test expected keys updating for quantized models"""
|
| 240 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 241 |
+
|
| 242 |
+
config = Mxfp4Config()
|
| 243 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 244 |
+
|
| 245 |
+
expected_keys = [
|
| 246 |
+
"model.layers.0.mlp.experts.gate_up_proj",
|
| 247 |
+
"model.layers.0.mlp.experts.down_proj",
|
| 248 |
+
"model.embed_tokens.weight",
|
| 249 |
+
]
|
| 250 |
+
|
| 251 |
+
updated_keys = quantizer.update_expected_keys(None, expected_keys, [])
|
| 252 |
+
|
| 253 |
+
expected_updated = [
|
| 254 |
+
"model.layers.0.mlp.experts.gate_up_proj_blocks",
|
| 255 |
+
"model.layers.0.mlp.experts.gate_up_proj_scales",
|
| 256 |
+
"model.layers.0.mlp.experts.down_proj_blocks",
|
| 257 |
+
"model.layers.0.mlp.experts.down_proj_scales",
|
| 258 |
+
"model.embed_tokens.weight",
|
| 259 |
+
]
|
| 260 |
+
|
| 261 |
+
self.assertEqual(set(updated_keys), set(expected_updated))
|
| 262 |
+
|
| 263 |
+
def test_update_param_name_dequantize(self):
|
| 264 |
+
"""Test parameter name updating when dequantizing"""
|
| 265 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 266 |
+
|
| 267 |
+
config = Mxfp4Config(dequantize=True)
|
| 268 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 269 |
+
|
| 270 |
+
# Should remove _blocks suffix
|
| 271 |
+
param_name = "model.layers.0.mlp.experts.gate_up_proj_blocks"
|
| 272 |
+
updated_name = quantizer.update_param_name(param_name)
|
| 273 |
+
self.assertEqual(updated_name, "model.layers.0.mlp.experts.gate_up_proj")
|
| 274 |
+
|
| 275 |
+
# Should remove _scales suffix
|
| 276 |
+
param_name = "model.layers.0.mlp.experts.down_proj_scales"
|
| 277 |
+
updated_name = quantizer.update_param_name(param_name)
|
| 278 |
+
self.assertEqual(updated_name, "model.layers.0.mlp.experts.down_proj")
|
| 279 |
+
|
| 280 |
+
# Should not change other names
|
| 281 |
+
param_name = "model.embed_tokens.weight"
|
| 282 |
+
updated_name = quantizer.update_param_name(param_name)
|
| 283 |
+
self.assertEqual(updated_name, "model.embed_tokens.weight")
|
| 284 |
+
|
| 285 |
+
def test_update_param_name_no_dequantize(self):
|
| 286 |
+
"""Test parameter name updating when not dequantizing"""
|
| 287 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 288 |
+
|
| 289 |
+
config = Mxfp4Config(dequantize=False)
|
| 290 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 291 |
+
|
| 292 |
+
param_name = "model.layers.0.mlp.experts.gate_up_proj_blocks"
|
| 293 |
+
updated_name = quantizer.update_param_name(param_name)
|
| 294 |
+
self.assertEqual(updated_name, param_name)
|
| 295 |
+
|
| 296 |
+
def test_is_serializable(self):
|
| 297 |
+
"""Test serialization capability"""
|
| 298 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 299 |
+
|
| 300 |
+
config = Mxfp4Config()
|
| 301 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 302 |
+
|
| 303 |
+
# MXFP4 is not serializable with safetensors
|
| 304 |
+
self.assertFalse(quantizer.is_serializable())
|
| 305 |
+
|
| 306 |
+
def test_is_trainable(self):
|
| 307 |
+
"""Test trainability"""
|
| 308 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 309 |
+
|
| 310 |
+
config = Mxfp4Config()
|
| 311 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 312 |
+
|
| 313 |
+
# MXFP4 is not trainable
|
| 314 |
+
self.assertFalse(quantizer.is_trainable)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
class Mxfp4IntegrationTest(unittest.TestCase):
|
| 318 |
+
"""Test mxfp4 integration functions"""
|
| 319 |
+
|
| 320 |
+
def test_should_convert_module(self):
|
| 321 |
+
"""Test module conversion decision logic"""
|
| 322 |
+
from transformers.integrations.mxfp4 import should_convert_module
|
| 323 |
+
|
| 324 |
+
# Should convert by default
|
| 325 |
+
self.assertTrue(should_convert_module(["model", "layers", "0", "mlp"], []))
|
| 326 |
+
|
| 327 |
+
# Should not convert if in exclusion list
|
| 328 |
+
patterns = ["model.layers.*.self_attn", "lm_head"]
|
| 329 |
+
self.assertFalse(should_convert_module(["model", "layers", "0", "self_attn"], patterns))
|
| 330 |
+
self.assertFalse(should_convert_module(["lm_head"], patterns))
|
| 331 |
+
|
| 332 |
+
# Should convert if not in exclusion list
|
| 333 |
+
self.assertTrue(should_convert_module(["model", "layers", "0", "mlp", "experts"], patterns))
|
| 334 |
+
|
| 335 |
+
@require_torch
|
| 336 |
+
def test_convert_moe_packed_tensors(self):
|
| 337 |
+
"""Test unpacking of quantized tensors"""
|
| 338 |
+
from transformers.integrations.mxfp4 import convert_moe_packed_tensors
|
| 339 |
+
|
| 340 |
+
# Create dummy packed tensors
|
| 341 |
+
blocks = torch.randint(0, 255, (2, 4, 8), dtype=torch.uint8)
|
| 342 |
+
scales = torch.randint(100, 150, (2, 4), dtype=torch.uint8)
|
| 343 |
+
|
| 344 |
+
result = convert_moe_packed_tensors(blocks, scales, dtype=torch.bfloat16)
|
| 345 |
+
|
| 346 |
+
# Check output shape - should be [2, 4, 16] (8 * 2 for unpacking)
|
| 347 |
+
self.assertEqual(result.shape, (2, 4 * 16))
|
| 348 |
+
self.assertEqual(result.dtype, torch.bfloat16)
|
| 349 |
+
|
| 350 |
+
@require_triton(min_version="3.4.0")
|
| 351 |
+
@require_kernels
|
| 352 |
+
@require_torch_gpu
|
| 353 |
+
@require_torch
|
| 354 |
+
def test_quantize_to_mxfp4(self):
|
| 355 |
+
"""Test quantization function"""
|
| 356 |
+
from transformers.integrations.mxfp4 import quantize_to_mxfp4
|
| 357 |
+
|
| 358 |
+
# Create dummy weight tensor
|
| 359 |
+
w = torch.randn(32, 64, 128, dtype=torch.bfloat16, device=torch.device("cuda"))
|
| 360 |
+
|
| 361 |
+
quantized_w, flex_data, mx_ctx = quantize_to_mxfp4(w, None, None)
|
| 362 |
+
|
| 363 |
+
# Check that shapes are reasonable
|
| 364 |
+
self.assertEqual(quantized_w.dtype, torch.uint8)
|
| 365 |
+
self.assertIsNotNone(flex_data)
|
| 366 |
+
self.assertIsNotNone(mx_ctx)
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
@require_torch
|
| 370 |
+
@require_torch_large_gpu
|
| 371 |
+
@require_triton(min_version="3.4.0")
|
| 372 |
+
@require_kernels
|
| 373 |
+
@slow
|
| 374 |
+
class Mxfp4ModelTest(unittest.TestCase):
|
| 375 |
+
"""Test mxfp4 with actual models (requires specific model and hardware)"""
|
| 376 |
+
|
| 377 |
+
# These should be paths to real OpenAI MoE models for proper testing
|
| 378 |
+
model_name = "openai/gpt-oss-20b"
|
| 379 |
+
|
| 380 |
+
input_text = "Once upon a time"
|
| 381 |
+
|
| 382 |
+
# Expected outputs for generation tests
|
| 383 |
+
EXPECTED_OUTPUTS = set()
|
| 384 |
+
EXPECTED_OUTPUTS.add("Once upon a time, in a small village, there lived a young")
|
| 385 |
+
|
| 386 |
+
def setUp(self):
|
| 387 |
+
gc.collect()
|
| 388 |
+
if torch.cuda.is_available():
|
| 389 |
+
torch.cuda.empty_cache()
|
| 390 |
+
|
| 391 |
+
def tearDown(self):
|
| 392 |
+
gc.collect()
|
| 393 |
+
if torch.cuda.is_available():
|
| 394 |
+
torch.cuda.empty_cache()
|
| 395 |
+
|
| 396 |
+
def check_inference_correctness_quantized(self, model, tokenizer):
|
| 397 |
+
# Check that inference pass works on the model
|
| 398 |
+
encoded_input = tokenizer(self.input_text, return_tensors="pt").to(model.device)
|
| 399 |
+
|
| 400 |
+
# Set pad token if not set
|
| 401 |
+
if tokenizer.pad_token is None:
|
| 402 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 403 |
+
|
| 404 |
+
with torch.no_grad():
|
| 405 |
+
output_sequences = model.generate(
|
| 406 |
+
**encoded_input,
|
| 407 |
+
max_new_tokens=10,
|
| 408 |
+
do_sample=False,
|
| 409 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 410 |
+
use_cache=False,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
generated_text = tokenizer.decode(output_sequences[0], skip_special_tokens=True)
|
| 414 |
+
|
| 415 |
+
self.assertIn(generated_text, self.EXPECTED_OUTPUTS)
|
| 416 |
+
|
| 417 |
+
def test_gpt_oss_model_loading_quantized_with_device_map(self):
|
| 418 |
+
"""Test loading OpenAI MoE model with mxfp4 quantization and device_map"""
|
| 419 |
+
|
| 420 |
+
quantization_config = Mxfp4Config(dequantize=False)
|
| 421 |
+
|
| 422 |
+
# Test that config is properly set up
|
| 423 |
+
self.assertFalse(quantization_config.dequantize)
|
| 424 |
+
|
| 425 |
+
model = GptOssForCausalLM.from_pretrained(
|
| 426 |
+
self.model_name,
|
| 427 |
+
quantization_config=quantization_config,
|
| 428 |
+
torch_dtype=torch.bfloat16,
|
| 429 |
+
device_map="auto",
|
| 430 |
+
)
|
| 431 |
+
tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 432 |
+
self.check_inference_correctness_quantized(model, tokenizer)
|
| 433 |
+
|
| 434 |
+
def test_gpt_oss_model_loading_dequantized_with_device_map(self):
|
| 435 |
+
"""Test loading OpenAI MoE model with mxfp4 dequantization and device_map"""
|
| 436 |
+
|
| 437 |
+
quantization_config = Mxfp4Config(dequantize=True)
|
| 438 |
+
|
| 439 |
+
# Test that config is properly set up
|
| 440 |
+
self.assertTrue(quantization_config.dequantize)
|
| 441 |
+
|
| 442 |
+
model = GptOssForCausalLM.from_pretrained(
|
| 443 |
+
self.model_name,
|
| 444 |
+
quantization_config=quantization_config,
|
| 445 |
+
torch_dtype=torch.bfloat16,
|
| 446 |
+
device_map="auto",
|
| 447 |
+
)
|
| 448 |
+
tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 449 |
+
self.check_inference_correctness_quantized(model, tokenizer)
|
| 450 |
+
|
| 451 |
+
def test_model_device_map_validation(self):
|
| 452 |
+
"""Test device map validation"""
|
| 453 |
+
from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer
|
| 454 |
+
|
| 455 |
+
config = Mxfp4Config()
|
| 456 |
+
quantizer = Mxfp4HfQuantizer(config)
|
| 457 |
+
quantizer.pre_quantized = False
|
| 458 |
+
|
| 459 |
+
# Test with CPU in device map (should raise error for non-pre-quantized)
|
| 460 |
+
with self.assertRaises(ValueError):
|
| 461 |
+
quantizer.validate_environment(device_map={"": "cpu"})
|
| 462 |
+
|
| 463 |
+
def test_memory_footprint_comparison(self):
|
| 464 |
+
"""Test memory footprint differences between quantized and unquantized models"""
|
| 465 |
+
|
| 466 |
+
# Expected: quantized < dequantized < unquantized memory usage
|
| 467 |
+
quantization_config = Mxfp4Config(dequantize=True)
|
| 468 |
+
quantized_model = GptOssForCausalLM.from_pretrained(
|
| 469 |
+
self.model_name,
|
| 470 |
+
torch_dtype=torch.bfloat16,
|
| 471 |
+
device_map="auto",
|
| 472 |
+
)
|
| 473 |
+
dequantized_model = GptOssForCausalLM.from_pretrained(
|
| 474 |
+
self.model_name,
|
| 475 |
+
torch_dtype=torch.bfloat16,
|
| 476 |
+
device_map="auto",
|
| 477 |
+
quantization_config=quantization_config,
|
| 478 |
+
)
|
| 479 |
+
quantized_mem = quantized_model.get_memory_footprint()
|
| 480 |
+
dequantized_mem = dequantized_model.get_memory_footprint()
|
| 481 |
+
self.assertLess(quantized_mem, dequantized_mem)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quanto_integration/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quanto_integration/test_quanto.py
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import tempfile
|
| 16 |
+
import unittest
|
| 17 |
+
|
| 18 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, QuantoConfig
|
| 19 |
+
from transformers.testing_utils import (
|
| 20 |
+
require_accelerate,
|
| 21 |
+
require_optimum_quanto,
|
| 22 |
+
require_read_token,
|
| 23 |
+
require_torch_accelerator,
|
| 24 |
+
slow,
|
| 25 |
+
torch_device,
|
| 26 |
+
)
|
| 27 |
+
from transformers.utils import is_accelerate_available, is_optimum_quanto_available, is_torch_available
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_torch_available():
|
| 31 |
+
import torch
|
| 32 |
+
|
| 33 |
+
from transformers import LlamaForCausalLM
|
| 34 |
+
|
| 35 |
+
if is_accelerate_available():
|
| 36 |
+
from accelerate import init_empty_weights
|
| 37 |
+
|
| 38 |
+
if is_optimum_quanto_available():
|
| 39 |
+
from optimum.quanto import QLayerNorm, QLinear
|
| 40 |
+
|
| 41 |
+
from transformers.integrations.quanto import replace_with_quanto_layers
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class QuantoConfigTest(unittest.TestCase):
|
| 45 |
+
def test_attributes(self):
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@require_optimum_quanto
|
| 50 |
+
@require_accelerate
|
| 51 |
+
class QuantoTestIntegration(unittest.TestCase):
|
| 52 |
+
model_id = "facebook/opt-350m"
|
| 53 |
+
|
| 54 |
+
def setUp(self):
|
| 55 |
+
config = AutoConfig.from_pretrained(self.model_id)
|
| 56 |
+
with init_empty_weights():
|
| 57 |
+
self.model = AutoModelForCausalLM.from_config(config)
|
| 58 |
+
self.nb_linear = 0
|
| 59 |
+
self.nb_layernorm = 0
|
| 60 |
+
for module in self.model.modules():
|
| 61 |
+
if isinstance(module, torch.nn.Linear):
|
| 62 |
+
self.nb_linear += 1
|
| 63 |
+
elif isinstance(module, torch.nn.LayerNorm):
|
| 64 |
+
self.nb_layernorm += 1
|
| 65 |
+
|
| 66 |
+
def test_weight_only_quantization_conversion(self):
|
| 67 |
+
"""
|
| 68 |
+
Simple test that checks if the quantized model has been converted properly when using weight only quantization
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
# Try with weight only quantization
|
| 72 |
+
quantization_config = QuantoConfig(weights="int8", activations=None)
|
| 73 |
+
self.model, _ = replace_with_quanto_layers(self.model, quantization_config=quantization_config)
|
| 74 |
+
|
| 75 |
+
nb_qlinear = 0
|
| 76 |
+
for module in self.model.modules():
|
| 77 |
+
if isinstance(module, QLinear):
|
| 78 |
+
nb_qlinear += 1
|
| 79 |
+
|
| 80 |
+
self.assertEqual(self.nb_linear, nb_qlinear)
|
| 81 |
+
|
| 82 |
+
def test_weight_and_activation_quantization_conversion(self):
|
| 83 |
+
"""
|
| 84 |
+
Simple test that checks if the quantized model has been converted properly when using weight + activation quantization
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
# Try with weight + activation quantization
|
| 88 |
+
quantization_config = QuantoConfig(weights="int8", activations="int8")
|
| 89 |
+
self.model, _ = replace_with_quanto_layers(self.model, quantization_config=quantization_config)
|
| 90 |
+
|
| 91 |
+
nb_qlinear = 0
|
| 92 |
+
nb_qlayernorm = 0
|
| 93 |
+
for module in self.model.modules():
|
| 94 |
+
if isinstance(module, QLinear):
|
| 95 |
+
nb_qlinear += 1
|
| 96 |
+
if isinstance(module, QLayerNorm):
|
| 97 |
+
nb_qlayernorm += 1
|
| 98 |
+
|
| 99 |
+
self.assertEqual(self.nb_linear, nb_qlinear)
|
| 100 |
+
self.assertEqual(self.nb_layernorm, nb_qlayernorm)
|
| 101 |
+
|
| 102 |
+
def test_conversion_with_modules_to_not_convert(self):
|
| 103 |
+
"""
|
| 104 |
+
Simple test that checks if the quantized model has been converted properly when specifying modules_to_not_convert argument
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
# Try with weight + activatioin quantization
|
| 108 |
+
quantization_config = QuantoConfig(weights="int8", activations="int8")
|
| 109 |
+
self.model, _ = replace_with_quanto_layers(
|
| 110 |
+
self.model, quantization_config=quantization_config, modules_to_not_convert=["lm_head"]
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
nb_qlinear = 0
|
| 114 |
+
nb_qlayernorm = 0
|
| 115 |
+
for module in self.model.modules():
|
| 116 |
+
if isinstance(module, QLinear):
|
| 117 |
+
nb_qlinear += 1
|
| 118 |
+
if isinstance(module, QLayerNorm):
|
| 119 |
+
nb_qlayernorm += 1
|
| 120 |
+
|
| 121 |
+
self.assertEqual(self.nb_linear - 1, nb_qlinear)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@slow
|
| 125 |
+
@require_torch_accelerator
|
| 126 |
+
@require_optimum_quanto
|
| 127 |
+
@require_accelerate
|
| 128 |
+
class QuantoQuantizationTest(unittest.TestCase):
|
| 129 |
+
"""
|
| 130 |
+
Test 8-bit weights only quantization
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
model_name = "bigscience/bloom-560m"
|
| 134 |
+
|
| 135 |
+
weights = "int8"
|
| 136 |
+
activations = None
|
| 137 |
+
device_map = "cpu"
|
| 138 |
+
|
| 139 |
+
input_text = "Hello my name is"
|
| 140 |
+
EXPECTED_OUTPUTS = "Hello my name is John, I am a professional photographer and I"
|
| 141 |
+
|
| 142 |
+
def setUp(self):
|
| 143 |
+
"""
|
| 144 |
+
Setup quantized model
|
| 145 |
+
"""
|
| 146 |
+
quantization_config = QuantoConfig(
|
| 147 |
+
weights=self.weights,
|
| 148 |
+
activations=self.activations,
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
self.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 152 |
+
self.model_name,
|
| 153 |
+
device_map=self.device_map,
|
| 154 |
+
quantization_config=quantization_config,
|
| 155 |
+
torch_dtype=torch.float32,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 159 |
+
|
| 160 |
+
self.have_accelerate_hooks = (
|
| 161 |
+
getattr(self.quantized_model, "hf_device_map", False) and len(self.quantized_model.hf_device_map) > 1
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
def check_inference_correctness(self, model, device):
|
| 165 |
+
r"""
|
| 166 |
+
Test the generation quality of the quantized model and see that we are matching the expected output.
|
| 167 |
+
Given that we are operating on small numbers + the testing model is relatively small, we might not get
|
| 168 |
+
the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
|
| 169 |
+
"""
|
| 170 |
+
if not self.have_accelerate_hooks:
|
| 171 |
+
model.to(device)
|
| 172 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 173 |
+
output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(device), max_new_tokens=10)
|
| 174 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 175 |
+
|
| 176 |
+
def test_generate_quality_cpu(self):
|
| 177 |
+
"""
|
| 178 |
+
Simple test to check the quality of the model on cpu by comparing the generated tokens with the expected tokens
|
| 179 |
+
"""
|
| 180 |
+
self.check_inference_correctness(self.quantized_model, "cpu")
|
| 181 |
+
|
| 182 |
+
def test_generate_quality_accelerator(self):
|
| 183 |
+
"""
|
| 184 |
+
Simple test to check the quality of the model on accelerators by comparing the generated tokens with the expected tokens
|
| 185 |
+
"""
|
| 186 |
+
self.check_inference_correctness(self.quantized_model, torch_device)
|
| 187 |
+
|
| 188 |
+
def test_quantized_model_layers(self):
|
| 189 |
+
from optimum.quanto import QBitsTensor, QModuleMixin, QTensor
|
| 190 |
+
|
| 191 |
+
"""
|
| 192 |
+
Suite of simple test to check if the layers are quantized and are working properly
|
| 193 |
+
"""
|
| 194 |
+
# Test the type of the quantized layer
|
| 195 |
+
self.assertTrue(isinstance(self.quantized_model.transformer.h[0].self_attention.query_key_value, QModuleMixin))
|
| 196 |
+
self.assertTrue(
|
| 197 |
+
isinstance(self.quantized_model.transformer.h[0].self_attention.query_key_value.weight, QTensor)
|
| 198 |
+
)
|
| 199 |
+
if self.weights == "int4":
|
| 200 |
+
self.assertTrue(
|
| 201 |
+
isinstance(self.quantized_model.transformer.h[0].self_attention.query_key_value.weight, QBitsTensor)
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# check that the lm_head was indeed not quantized, just like bnb
|
| 205 |
+
self.assertTrue(
|
| 206 |
+
isinstance(self.quantized_model.lm_head, torch.nn.Linear)
|
| 207 |
+
and not isinstance(self.quantized_model.lm_head, QModuleMixin)
|
| 208 |
+
)
|
| 209 |
+
if self.device_map in ["cpu", "cuda"]:
|
| 210 |
+
self.assertEqual(
|
| 211 |
+
self.quantized_model.transformer.h[0].self_attention.query_key_value.weight._data.device.type,
|
| 212 |
+
self.device_map,
|
| 213 |
+
)
|
| 214 |
+
self.quantized_model.to(0)
|
| 215 |
+
self.assertEqual(
|
| 216 |
+
self.quantized_model.transformer.h[0].self_attention.query_key_value.weight._data.device.type, torch_device
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
def test_serialization_bin(self):
|
| 220 |
+
"""
|
| 221 |
+
Test the serialization, the loading and the inference of the quantized weights
|
| 222 |
+
"""
|
| 223 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 224 |
+
with self.assertRaises(ValueError) as e:
|
| 225 |
+
self.quantized_model.save_pretrained(tmpdirname, safe_serialization=False)
|
| 226 |
+
self.assertIn(
|
| 227 |
+
"The model is quantized with QuantizationMethod.QUANTO and is not serializable", str(e.exception)
|
| 228 |
+
)
|
| 229 |
+
# TODO: replace by the following when it works
|
| 230 |
+
# quantized_model_from_saved = AutoModelForCausalLM.from_pretrained(
|
| 231 |
+
# tmpdirname, torch_dtype=torch.float32, device_map="cpu"
|
| 232 |
+
# )
|
| 233 |
+
# self.check_inference_correctness(quantized_model_from_saved, device="cuda")
|
| 234 |
+
|
| 235 |
+
def test_serialization_safetensors(self):
|
| 236 |
+
"""
|
| 237 |
+
Test the serialization, the loading and the inference of the quantized weights
|
| 238 |
+
"""
|
| 239 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 240 |
+
with self.assertRaises(ValueError) as e:
|
| 241 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 242 |
+
self.assertIn(
|
| 243 |
+
"The model is quantized with QuantizationMethod.QUANTO and is not serializable", str(e.exception)
|
| 244 |
+
)
|
| 245 |
+
# quantized_model_from_saved = AutoModelForCausalLM.from_pretrained(
|
| 246 |
+
# tmpdirname, torch_dtype=torch.float32, device_map="cpu"
|
| 247 |
+
# )
|
| 248 |
+
# self.check_inference_correctness(quantized_model_from_saved, device="cuda")
|
| 249 |
+
|
| 250 |
+
def check_same_model(self, model1, model2):
|
| 251 |
+
d0 = dict(model1.named_parameters())
|
| 252 |
+
d1 = dict(model2.named_parameters())
|
| 253 |
+
self.assertTrue(d0.keys() == d1.keys())
|
| 254 |
+
for k in d0:
|
| 255 |
+
self.assertTrue(d0[k].shape == d1[k].shape)
|
| 256 |
+
self.assertTrue(d0[k].device.type == d1[k].device.type)
|
| 257 |
+
self.assertTrue(d0[k].device == d1[k].device)
|
| 258 |
+
self.assertTrue(d0[k].dtype == d1[k].dtype)
|
| 259 |
+
self.assertTrue(torch.equal(d0[k], d1[k].to(d0[k].device)))
|
| 260 |
+
|
| 261 |
+
def test_compare_with_quanto(self):
|
| 262 |
+
from optimum.quanto import freeze, qint4, qint8, quantize
|
| 263 |
+
|
| 264 |
+
w_mapping = {"int8": qint8, "int4": qint4}
|
| 265 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 266 |
+
self.model_name,
|
| 267 |
+
device_map=self.device_map,
|
| 268 |
+
torch_dtype=torch.float32,
|
| 269 |
+
)
|
| 270 |
+
# we do not quantize the lm_head since we don't do that in transformers
|
| 271 |
+
quantize(model.transformer, weights=w_mapping[self.weights])
|
| 272 |
+
freeze(model.transformer)
|
| 273 |
+
self.check_same_model(model, self.quantized_model)
|
| 274 |
+
self.check_inference_correctness(model, device=torch_device)
|
| 275 |
+
|
| 276 |
+
@unittest.skip
|
| 277 |
+
def test_load_from_quanto_saved(self):
|
| 278 |
+
from optimum.quanto import freeze, qint4, qint8, quantize
|
| 279 |
+
|
| 280 |
+
from transformers import QuantoConfig
|
| 281 |
+
|
| 282 |
+
w_mapping = {"int8": qint8, "int4": qint4}
|
| 283 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 284 |
+
self.model_name,
|
| 285 |
+
device_map=self.device_map,
|
| 286 |
+
torch_dtype=torch.float32,
|
| 287 |
+
)
|
| 288 |
+
# we do not quantize the lm_head since we don't do that in transformers
|
| 289 |
+
quantize(model.transformer, weights=w_mapping[self.weights])
|
| 290 |
+
freeze(model.transformer)
|
| 291 |
+
|
| 292 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 293 |
+
model.config.quantization_config = QuantoConfig(
|
| 294 |
+
weights=self.weights, activations=self.activations, modules_to_not_convert=["lm_head"]
|
| 295 |
+
)
|
| 296 |
+
model.save_pretrained(tmpdirname, safe_serialization=False)
|
| 297 |
+
quantized_model_from_saved = AutoModelForCausalLM.from_pretrained(
|
| 298 |
+
tmpdirname,
|
| 299 |
+
device_map=self.device_map,
|
| 300 |
+
torch_dtype=torch.float32,
|
| 301 |
+
)
|
| 302 |
+
self.check_same_model(model, quantized_model_from_saved)
|
| 303 |
+
self.check_inference_correctness(quantized_model_from_saved, device="cuda")
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
class QuantoQuantizationOffloadTest(QuantoQuantizationTest):
|
| 307 |
+
device_map = {
|
| 308 |
+
"transformer.word_embeddings": 0,
|
| 309 |
+
"transformer.word_embeddings_layernorm": 0,
|
| 310 |
+
"transformer.ln_f": 0,
|
| 311 |
+
"transformer.h.0": 0,
|
| 312 |
+
"transformer.h.1": 0,
|
| 313 |
+
"transformer.h.2": 0,
|
| 314 |
+
"transformer.h.3": 0,
|
| 315 |
+
"transformer.h.4": 0,
|
| 316 |
+
"transformer.h.5": 0,
|
| 317 |
+
"transformer.h.6": 0,
|
| 318 |
+
"transformer.h.7": 0,
|
| 319 |
+
"transformer.h.8": 0,
|
| 320 |
+
"transformer.h.9": 0,
|
| 321 |
+
"transformer.h.10": 0,
|
| 322 |
+
"transformer.h.11": 0,
|
| 323 |
+
"transformer.h.12": 0,
|
| 324 |
+
"transformer.h.13": 0,
|
| 325 |
+
"transformer.h.14": 0,
|
| 326 |
+
"transformer.h.15": 0,
|
| 327 |
+
"transformer.h.16": 0,
|
| 328 |
+
"transformer.h.17": 0,
|
| 329 |
+
"transformer.h.18": 0,
|
| 330 |
+
"transformer.h.19": 0,
|
| 331 |
+
"transformer.h.20": 0,
|
| 332 |
+
"transformer.h.21": 0,
|
| 333 |
+
"transformer.h.22": "cpu",
|
| 334 |
+
"transformer.h.23": "disk",
|
| 335 |
+
"lm_head": 0,
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
@unittest.skip(reason="The execution device is a gpu")
|
| 339 |
+
def test_generate_quality_cpu(self):
|
| 340 |
+
pass
|
| 341 |
+
|
| 342 |
+
@unittest.skip(reason="We can't save offloaded values")
|
| 343 |
+
def test_serialization_bin(self):
|
| 344 |
+
pass
|
| 345 |
+
|
| 346 |
+
@unittest.skip
|
| 347 |
+
def test_serialization_safetensors(self):
|
| 348 |
+
pass
|
| 349 |
+
|
| 350 |
+
@unittest.skip
|
| 351 |
+
def test_compare_with_quanto(self):
|
| 352 |
+
pass
|
| 353 |
+
|
| 354 |
+
@unittest.skip
|
| 355 |
+
def test_load_from_quanto_saved(self):
|
| 356 |
+
pass
|
| 357 |
+
|
| 358 |
+
def test_check_offload_quantized(self):
|
| 359 |
+
"""
|
| 360 |
+
We check that we have unquantized value in the cpu and in the disk
|
| 361 |
+
"""
|
| 362 |
+
from optimum.quanto import QBitsTensor, QTensor
|
| 363 |
+
|
| 364 |
+
cpu_weights = self.quantized_model.transformer.h[22].self_attention.query_key_value._hf_hook.weights_map[
|
| 365 |
+
"weight"
|
| 366 |
+
]
|
| 367 |
+
disk_weights = self.quantized_model.transformer.h[23].self_attention.query_key_value._hf_hook.weights_map[
|
| 368 |
+
"weight"
|
| 369 |
+
]
|
| 370 |
+
self.assertTrue(isinstance(cpu_weights, torch.Tensor) and not isinstance(cpu_weights, QTensor))
|
| 371 |
+
self.assertTrue(isinstance(disk_weights, torch.Tensor) and not isinstance(disk_weights, QTensor))
|
| 372 |
+
if self.weights == "int4":
|
| 373 |
+
self.assertTrue(isinstance(cpu_weights, torch.Tensor) and not isinstance(disk_weights, QBitsTensor))
|
| 374 |
+
self.assertTrue(isinstance(disk_weights, torch.Tensor) and not isinstance(disk_weights, QBitsTensor))
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@unittest.skip(reason="Skipping test class because serialization is not supported yet")
|
| 378 |
+
class QuantoQuantizationSerializationTest(QuantoQuantizationTest):
|
| 379 |
+
"""
|
| 380 |
+
Perform the same tests as in QuantoQuantizationTest but with a serialized model.
|
| 381 |
+
"""
|
| 382 |
+
|
| 383 |
+
def setUp(self):
|
| 384 |
+
"""
|
| 385 |
+
Setup quantized model
|
| 386 |
+
"""
|
| 387 |
+
quantization_config = QuantoConfig(
|
| 388 |
+
weights=self.weights,
|
| 389 |
+
activations=self.activations,
|
| 390 |
+
)
|
| 391 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 392 |
+
self.model_name,
|
| 393 |
+
device_map=self.device_map,
|
| 394 |
+
quantization_config=quantization_config,
|
| 395 |
+
torch_dtype=torch.float32,
|
| 396 |
+
)
|
| 397 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 398 |
+
quantized_model.save_pretrained(tmpdirname, safe_serialization=False)
|
| 399 |
+
self.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 400 |
+
tmpdirname, torch_dtype=torch.float32, device_map=self.device_map
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 404 |
+
|
| 405 |
+
self.have_accelerate_hooks = (
|
| 406 |
+
getattr(self.quantized_model, "hf_device_map", False) and len(self.quantized_model.hf_device_map) > 1
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
@unittest.skip(reason="Skipping test class because serialization is not supported yet")
|
| 411 |
+
class QuantoQuantizationSerializationCudaTest(QuantoQuantizationTest):
|
| 412 |
+
"""
|
| 413 |
+
Perform the same tests as in QuantoQuantizationTest but with model on cuda
|
| 414 |
+
"""
|
| 415 |
+
|
| 416 |
+
device_map = "cuda:0"
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
class QuantoQuantizationQBitsTensorTest(QuantoQuantizationTest):
|
| 420 |
+
EXPECTED_OUTPUTS = "Hello my name is John, I am a professional photographer, I"
|
| 421 |
+
weights = "int4"
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
class QuantoQuantizationQBitsTensorOffloadTest(QuantoQuantizationOffloadTest):
|
| 425 |
+
EXPECTED_OUTPUTS = "Hello my name is John, I am a professional photographer, I"
|
| 426 |
+
weights = "int4"
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
@unittest.skip(reason="Skipping test class because serialization is not supported yet")
|
| 430 |
+
class QuantoQuantizationQBitsTensorSerializationTest(QuantoQuantizationSerializationTest):
|
| 431 |
+
EXPECTED_OUTPUTS = "Hello my name is John, I am a professional photographer, I"
|
| 432 |
+
weights = "int4"
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
@require_torch_accelerator
|
| 436 |
+
class QuantoQuantizationActivationTest(unittest.TestCase):
|
| 437 |
+
def test_quantize_activation(self):
|
| 438 |
+
quantization_config = QuantoConfig(
|
| 439 |
+
weights="int8",
|
| 440 |
+
activations="int8",
|
| 441 |
+
)
|
| 442 |
+
with self.assertRaises(ValueError) as e:
|
| 443 |
+
AutoModelForCausalLM.from_pretrained("bigscience/bloom-560m", quantization_config=quantization_config)
|
| 444 |
+
self.assertIn("We don't support quantizing the activations with transformers library", str(e.exception))
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
@require_optimum_quanto
|
| 448 |
+
@require_torch_accelerator
|
| 449 |
+
class QuantoKVCacheQuantizationTest(unittest.TestCase):
|
| 450 |
+
@slow
|
| 451 |
+
@require_read_token
|
| 452 |
+
def test_quantized_cache(self):
|
| 453 |
+
EXPECTED_TEXT_COMPLETION = [
|
| 454 |
+
"Simply put, the theory of relativity states that 1) time and space are not absolute, but are relative to the observer, and 2) the laws of physics are the same everywhere in the universe. This means that the speed of light is",
|
| 455 |
+
"My favorite all time favorite condiment is ketchup. I love how it adds a sweet and tangy flavor to my food. I also enjoy using it as a dip for fries, burgers, and grilled meats. It's a classic condiment that never",
|
| 456 |
+
]
|
| 457 |
+
|
| 458 |
+
prompts = [
|
| 459 |
+
"Simply put, the theory of relativity states that ",
|
| 460 |
+
"My favorite all time favorite condiment is ketchup.",
|
| 461 |
+
]
|
| 462 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 463 |
+
"unsloth/Llama-3.2-1B-Instruct", pad_token="</s>", padding_side="left"
|
| 464 |
+
)
|
| 465 |
+
model = LlamaForCausalLM.from_pretrained(
|
| 466 |
+
"unsloth/Llama-3.2-1B-Instruct", device_map="sequential", torch_dtype=torch.float16
|
| 467 |
+
)
|
| 468 |
+
inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(torch_device)
|
| 469 |
+
|
| 470 |
+
generated_ids = model.generate(**inputs, max_new_tokens=40, do_sample=False, cache_implementation="quantized")
|
| 471 |
+
text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
|
| 472 |
+
self.assertEqual(EXPECTED_TEXT_COMPLETION, text)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quark_integration/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quark_integration/test_quark.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 Advanced Micro Devices, Inc. and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import unittest
|
| 15 |
+
|
| 16 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, QuarkConfig
|
| 17 |
+
from transformers.testing_utils import (
|
| 18 |
+
cleanup,
|
| 19 |
+
is_torch_available,
|
| 20 |
+
require_accelerate,
|
| 21 |
+
require_quark,
|
| 22 |
+
require_torch_gpu,
|
| 23 |
+
require_torch_multi_gpu,
|
| 24 |
+
slow,
|
| 25 |
+
torch_device,
|
| 26 |
+
)
|
| 27 |
+
from transformers.utils.import_utils import is_quark_available
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_torch_available():
|
| 31 |
+
import torch
|
| 32 |
+
|
| 33 |
+
if is_quark_available():
|
| 34 |
+
from quark.torch.export.nn.modules.qparamslinear import QParamsLinear
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@require_quark
|
| 38 |
+
class QuarkConfigTest(unittest.TestCase):
|
| 39 |
+
def test_commmon_args(self):
|
| 40 |
+
config = AutoConfig.from_pretrained("amd/Llama-3.1-8B-Instruct-w-int8-a-int8-sym-test")
|
| 41 |
+
QuarkConfig(**config.quantization_config)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@slow
|
| 45 |
+
@require_quark
|
| 46 |
+
@require_torch_gpu
|
| 47 |
+
class QuarkTest(unittest.TestCase):
|
| 48 |
+
reference_model_name = "unsloth/Meta-Llama-3.1-8B-Instruct"
|
| 49 |
+
quantized_model_name = "amd/Llama-3.1-8B-Instruct-w-int8-a-int8-sym-test"
|
| 50 |
+
|
| 51 |
+
input_text = "Today I am in Paris and"
|
| 52 |
+
|
| 53 |
+
EXPECTED_OUTPUTS = set()
|
| 54 |
+
EXPECTED_OUTPUTS.add("Today I am in Paris and I am not in Paris, France\nToday I am in Paris, Illinois")
|
| 55 |
+
EXPECTED_OUTPUTS.add("Today I am in Paris and I am enjoying the city of light. I am not just any ordinary Paris")
|
| 56 |
+
EXPECTED_OUTPUTS.add("Today I am in Paris and I am enjoying my day off! The sun is shining, the birds are")
|
| 57 |
+
EXPECTED_OUTPUTS.add("Today I am in Paris and I'm here to tell you about it. It's a beautiful day,")
|
| 58 |
+
EXPECTED_OUTPUTS.add("Today I am in Paris and I am not in Paris at all! I am not in Paris, but")
|
| 59 |
+
|
| 60 |
+
EXPECTED_RELATIVE_DIFFERENCE = 1.66
|
| 61 |
+
device_map = None
|
| 62 |
+
|
| 63 |
+
@classmethod
|
| 64 |
+
def setUpClass(cls):
|
| 65 |
+
"""
|
| 66 |
+
Setup reference & quantized model
|
| 67 |
+
"""
|
| 68 |
+
cls.model_fp16 = AutoModelForCausalLM.from_pretrained(
|
| 69 |
+
cls.reference_model_name, torch_dtype=torch.float16, device_map=cls.device_map
|
| 70 |
+
)
|
| 71 |
+
cls.mem_fp16 = cls.model_fp16.get_memory_footprint()
|
| 72 |
+
|
| 73 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.reference_model_name, use_fast=True)
|
| 74 |
+
|
| 75 |
+
cls.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 76 |
+
cls.quantized_model_name,
|
| 77 |
+
torch_dtype=torch.float16,
|
| 78 |
+
device_map=cls.device_map,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
def tearDown(self):
|
| 82 |
+
r"""
|
| 83 |
+
TearDown function needs to be called at the end of each test to free the accelerator memory and cache, also to
|
| 84 |
+
avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
|
| 85 |
+
"""
|
| 86 |
+
cleanup(torch_device, gc_collect=True)
|
| 87 |
+
|
| 88 |
+
def test_memory_footprint(self):
|
| 89 |
+
mem_quantized = self.quantized_model.get_memory_footprint()
|
| 90 |
+
|
| 91 |
+
self.assertTrue(self.mem_fp16 / mem_quantized > self.EXPECTED_RELATIVE_DIFFERENCE)
|
| 92 |
+
|
| 93 |
+
def test_device_and_dtype_assignment(self):
|
| 94 |
+
r"""
|
| 95 |
+
Test whether trying to cast (or assigning a device to) a model after quantization will throw an error.
|
| 96 |
+
Checks also if other models are casted correctly .
|
| 97 |
+
"""
|
| 98 |
+
# This should work
|
| 99 |
+
if self.device_map is None:
|
| 100 |
+
_ = self.quantized_model.to(0)
|
| 101 |
+
|
| 102 |
+
with self.assertRaises(ValueError):
|
| 103 |
+
# Tries with a `dtype``
|
| 104 |
+
self.quantized_model.to(torch.float16)
|
| 105 |
+
|
| 106 |
+
def test_original_dtype(self):
|
| 107 |
+
r"""
|
| 108 |
+
A simple test to check if the model successfully stores the original dtype
|
| 109 |
+
"""
|
| 110 |
+
self.assertTrue(hasattr(self.quantized_model.config, "_pre_quantization_dtype"))
|
| 111 |
+
self.assertFalse(hasattr(self.model_fp16.config, "_pre_quantization_dtype"))
|
| 112 |
+
self.assertTrue(self.quantized_model.config._pre_quantization_dtype == torch.float16)
|
| 113 |
+
|
| 114 |
+
self.assertTrue(isinstance(self.quantized_model.model.layers[0].mlp.gate_proj, QParamsLinear))
|
| 115 |
+
|
| 116 |
+
def check_inference_correctness(self, model):
|
| 117 |
+
r"""
|
| 118 |
+
Test the generation quality of the quantized model and see that we are matching the expected output.
|
| 119 |
+
Given that we are operating on small numbers + the testing model is relatively small, we might not get
|
| 120 |
+
the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
|
| 121 |
+
"""
|
| 122 |
+
# Check that inference pass works on the model
|
| 123 |
+
encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
|
| 124 |
+
|
| 125 |
+
gen_config = GenerationConfig(
|
| 126 |
+
max_new_tokens=15,
|
| 127 |
+
min_new_tokens=15,
|
| 128 |
+
use_cache=True,
|
| 129 |
+
num_beams=1,
|
| 130 |
+
do_sample=False,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
# Check the exactness of the results
|
| 134 |
+
output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), generation_config=gen_config)
|
| 135 |
+
|
| 136 |
+
# Get the generation
|
| 137 |
+
self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS)
|
| 138 |
+
|
| 139 |
+
def test_generate_quality(self):
|
| 140 |
+
"""
|
| 141 |
+
Simple test to check the quality of the model by comparing the generated tokens with the expected tokens
|
| 142 |
+
"""
|
| 143 |
+
if self.device_map is None:
|
| 144 |
+
self.check_inference_correctness(self.quantized_model.to(0))
|
| 145 |
+
else:
|
| 146 |
+
self.check_inference_correctness(self.quantized_model)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
@require_accelerate
|
| 150 |
+
@require_torch_multi_gpu
|
| 151 |
+
@require_quark
|
| 152 |
+
class QuarkTestDeviceMap(QuarkTest):
|
| 153 |
+
device_map = "auto"
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/spqr_integration/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/spqr_integration/test_spqr.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import tempfile
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import pytest
|
| 20 |
+
|
| 21 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, SpQRConfig, StaticCache
|
| 22 |
+
from transformers.testing_utils import (
|
| 23 |
+
backend_empty_cache,
|
| 24 |
+
require_accelerate,
|
| 25 |
+
require_spqr,
|
| 26 |
+
require_torch_gpu,
|
| 27 |
+
require_torch_multi_gpu,
|
| 28 |
+
slow,
|
| 29 |
+
torch_device,
|
| 30 |
+
)
|
| 31 |
+
from transformers.utils import is_accelerate_available, is_torch_available
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if is_torch_available():
|
| 35 |
+
import torch
|
| 36 |
+
|
| 37 |
+
if is_accelerate_available():
|
| 38 |
+
from accelerate import init_empty_weights
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@require_torch_gpu
|
| 42 |
+
class SpQRConfigTest(unittest.TestCase):
|
| 43 |
+
def test_to_dict(self):
|
| 44 |
+
"""
|
| 45 |
+
Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object
|
| 46 |
+
"""
|
| 47 |
+
quantization_config = SpQRConfig()
|
| 48 |
+
config_to_dict = quantization_config.to_dict()
|
| 49 |
+
|
| 50 |
+
for key in config_to_dict:
|
| 51 |
+
self.assertEqual(getattr(quantization_config, key), config_to_dict[key])
|
| 52 |
+
|
| 53 |
+
def test_from_dict(self):
|
| 54 |
+
"""
|
| 55 |
+
Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict
|
| 56 |
+
"""
|
| 57 |
+
dict = {
|
| 58 |
+
"beta1": 16,
|
| 59 |
+
"beta2": 16,
|
| 60 |
+
"bits": 3,
|
| 61 |
+
"modules_to_not_convert": ["lm_head.weight"],
|
| 62 |
+
"shapes": {"model.layers.0.self_attn.q_proj.dense_weights.shape": 16},
|
| 63 |
+
}
|
| 64 |
+
quantization_config = SpQRConfig.from_dict(dict)
|
| 65 |
+
|
| 66 |
+
self.assertEqual(dict["beta1"], quantization_config.beta1)
|
| 67 |
+
self.assertEqual(dict["beta2"], quantization_config.beta2)
|
| 68 |
+
self.assertEqual(dict["bits"], quantization_config.bits)
|
| 69 |
+
self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert)
|
| 70 |
+
self.assertEqual(dict["shapes"], quantization_config.shapes)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@slow
|
| 74 |
+
@require_torch_gpu
|
| 75 |
+
@require_spqr
|
| 76 |
+
@require_accelerate
|
| 77 |
+
class SpQRTest(unittest.TestCase):
|
| 78 |
+
model_name = "elvircrn/Llama-2-7b-SPQR-3Bit-16x16-red_pajama-hf"
|
| 79 |
+
|
| 80 |
+
input_text = "Hello my name is"
|
| 81 |
+
max_new_tokens = 32
|
| 82 |
+
|
| 83 |
+
EXPECTED_OUTPUT = (
|
| 84 |
+
"Hello my name is Jesse. (I'm also known as Jesse) I'm a 25 year old male from United States. I'm looking for"
|
| 85 |
+
)
|
| 86 |
+
EXPECTED_OUTPUT_COMPILE = "Hello my name is Jake and I am a 20 year old student at the University of North Texas. (Go Mean Green!) I am a huge fan of the Dallas"
|
| 87 |
+
|
| 88 |
+
# called only once for all test in this class
|
| 89 |
+
@classmethod
|
| 90 |
+
def setUpClass(cls):
|
| 91 |
+
"""
|
| 92 |
+
Setup quantized model
|
| 93 |
+
"""
|
| 94 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name)
|
| 95 |
+
cls.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 96 |
+
cls.model_name,
|
| 97 |
+
device_map=torch_device,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
def tearDown(self):
|
| 101 |
+
gc.collect()
|
| 102 |
+
backend_empty_cache(torch_device)
|
| 103 |
+
gc.collect()
|
| 104 |
+
|
| 105 |
+
def test_quantized_model_conversion(self):
|
| 106 |
+
"""
|
| 107 |
+
Simple test that checks if the quantized model has been converted properly
|
| 108 |
+
"""
|
| 109 |
+
from spqr_quant import QuantizedLinear
|
| 110 |
+
|
| 111 |
+
from transformers.integrations import replace_with_spqr_linear
|
| 112 |
+
|
| 113 |
+
model_id = "meta-llama/Llama-2-7b-hf"
|
| 114 |
+
config = AutoConfig.from_pretrained(model_id)
|
| 115 |
+
quantization_config = AutoConfig.from_pretrained(self.model_name, return_dict=False).quantization_config
|
| 116 |
+
quantization_config = SpQRConfig.from_dict(quantization_config)
|
| 117 |
+
|
| 118 |
+
with init_empty_weights():
|
| 119 |
+
model = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path=model_id, config=config)
|
| 120 |
+
|
| 121 |
+
nb_linears = 0
|
| 122 |
+
for module in model.modules():
|
| 123 |
+
if isinstance(module, torch.nn.Linear):
|
| 124 |
+
nb_linears += 1
|
| 125 |
+
|
| 126 |
+
model, _ = replace_with_spqr_linear(
|
| 127 |
+
model,
|
| 128 |
+
quantization_config=quantization_config,
|
| 129 |
+
modules_to_not_convert=quantization_config.modules_to_not_convert,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
nb_spqr_linear = 0
|
| 133 |
+
for module in model.modules():
|
| 134 |
+
if isinstance(module, QuantizedLinear):
|
| 135 |
+
nb_spqr_linear += 1
|
| 136 |
+
|
| 137 |
+
self.assertEqual(nb_linears - 1, nb_spqr_linear)
|
| 138 |
+
|
| 139 |
+
def test_quantized_model(self):
|
| 140 |
+
"""
|
| 141 |
+
Simple test that checks if the quantized model is working properly
|
| 142 |
+
"""
|
| 143 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 144 |
+
|
| 145 |
+
output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 146 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 147 |
+
|
| 148 |
+
def test_raise_if_non_quantized(self):
|
| 149 |
+
model_id = "meta-llama/Llama-2-7b-hf"
|
| 150 |
+
quantization_config = SpQRConfig()
|
| 151 |
+
|
| 152 |
+
with self.assertRaises(ValueError):
|
| 153 |
+
_ = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=quantization_config)
|
| 154 |
+
|
| 155 |
+
@unittest.skip
|
| 156 |
+
def test_save_pretrained(self):
|
| 157 |
+
"""
|
| 158 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 159 |
+
"""
|
| 160 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 161 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 162 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=torch_device)
|
| 163 |
+
|
| 164 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 165 |
+
|
| 166 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 167 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 168 |
+
|
| 169 |
+
@require_torch_multi_gpu
|
| 170 |
+
def test_quantized_model_multi_gpu(self):
|
| 171 |
+
"""
|
| 172 |
+
Simple test that checks if the quantized model is working properly with multiple GPUs
|
| 173 |
+
"""
|
| 174 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 175 |
+
|
| 176 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(self.model_name, device_map="auto")
|
| 177 |
+
|
| 178 |
+
self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1})
|
| 179 |
+
|
| 180 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 181 |
+
|
| 182 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 183 |
+
|
| 184 |
+
@pytest.mark.torch_compile_test
|
| 185 |
+
def test_quantized_model_compile(self):
|
| 186 |
+
"""
|
| 187 |
+
Simple test that checks if the quantized model is working properly
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
# Sample tokens greedily
|
| 191 |
+
def decode_one_tokens(model, cur_token, input_pos, cache_position, past_key_values):
|
| 192 |
+
logits = model(
|
| 193 |
+
cur_token,
|
| 194 |
+
position_ids=input_pos,
|
| 195 |
+
cache_position=cache_position,
|
| 196 |
+
past_key_values=past_key_values,
|
| 197 |
+
return_dict=False,
|
| 198 |
+
use_cache=True,
|
| 199 |
+
)[0]
|
| 200 |
+
new_token = torch.argmax(logits[:, [-1]], dim=-1).to(torch.int)
|
| 201 |
+
|
| 202 |
+
return new_token
|
| 203 |
+
|
| 204 |
+
# Tokenize the test input
|
| 205 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)["input_ids"]
|
| 206 |
+
seq_length = input_ids.shape[1]
|
| 207 |
+
|
| 208 |
+
# Setup static KV cache for generation
|
| 209 |
+
past_key_values = StaticCache(
|
| 210 |
+
config=self.quantized_model.config, max_cache_len=seq_length + self.max_new_tokens + 1
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
# Allocate token ids to be generated and copy prefix ids
|
| 214 |
+
cache_position = torch.arange(seq_length, device=torch_device)
|
| 215 |
+
generated_ids = torch.zeros(1, seq_length + self.max_new_tokens, dtype=torch.int, device=torch_device)
|
| 216 |
+
generated_ids[:, cache_position] = input_ids.to(torch_device).to(torch.int)
|
| 217 |
+
|
| 218 |
+
# Do a forward pass to fill the prefix cache and compile the kernels if necessary
|
| 219 |
+
logits = self.quantized_model(
|
| 220 |
+
input_ids,
|
| 221 |
+
cache_position=cache_position,
|
| 222 |
+
past_key_values=past_key_values,
|
| 223 |
+
return_dict=False,
|
| 224 |
+
use_cache=True,
|
| 225 |
+
)[0]
|
| 226 |
+
next_token = torch.argmax(logits[:, [-1]], dim=-1).to(torch.int)
|
| 227 |
+
generated_ids[:, [seq_length]] = next_token
|
| 228 |
+
|
| 229 |
+
with torch.no_grad():
|
| 230 |
+
# Compile the CUDA graph
|
| 231 |
+
decode_one_tokens = torch.compile(decode_one_tokens, mode="default", backend="inductor", fullgraph=True)
|
| 232 |
+
|
| 233 |
+
# Generate tokens one by one
|
| 234 |
+
cache_position = torch.tensor([seq_length + 1], device=torch_device)
|
| 235 |
+
for _ in range(1, self.max_new_tokens):
|
| 236 |
+
with torch.backends.cuda.sdp_kernel(enable_flash=False, enable_mem_efficient=False, enable_math=True):
|
| 237 |
+
next_token = decode_one_tokens(
|
| 238 |
+
self.quantized_model, next_token.clone(), None, cache_position, past_key_values
|
| 239 |
+
)
|
| 240 |
+
generated_ids.index_copy_(1, cache_position, next_token)
|
| 241 |
+
cache_position += 1
|
| 242 |
+
|
| 243 |
+
# Check generated text
|
| 244 |
+
self.assertEqual(
|
| 245 |
+
self.tokenizer.decode(generated_ids[0], skip_special_tokens=True), self.EXPECTED_OUTPUT_COMPILE
|
| 246 |
+
)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/torchao_integration/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/torchao_integration/test_torchao.py
ADDED
|
@@ -0,0 +1,592 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import importlib.metadata
|
| 17 |
+
import tempfile
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
from packaging import version
|
| 21 |
+
|
| 22 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
|
| 23 |
+
from transformers.testing_utils import (
|
| 24 |
+
Expectations,
|
| 25 |
+
backend_empty_cache,
|
| 26 |
+
get_device_properties,
|
| 27 |
+
require_torch_accelerator,
|
| 28 |
+
require_torch_multi_accelerator,
|
| 29 |
+
require_torchao,
|
| 30 |
+
require_torchao_version_greater_or_equal,
|
| 31 |
+
torch_device,
|
| 32 |
+
)
|
| 33 |
+
from transformers.utils import is_torch_available, is_torchao_available
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if is_torch_available():
|
| 37 |
+
import torch
|
| 38 |
+
|
| 39 |
+
if is_torchao_available():
|
| 40 |
+
# renamed in torchao 0.7.0, please install the latest torchao
|
| 41 |
+
from torchao.dtypes import (
|
| 42 |
+
AffineQuantizedTensor,
|
| 43 |
+
TensorCoreTiledLayout,
|
| 44 |
+
)
|
| 45 |
+
from torchao.quantization import (
|
| 46 |
+
Int8WeightOnlyConfig,
|
| 47 |
+
IntxWeightOnlyConfig,
|
| 48 |
+
MappingType,
|
| 49 |
+
ModuleFqnToConfig,
|
| 50 |
+
PerAxis,
|
| 51 |
+
)
|
| 52 |
+
from torchao.quantization.autoquant import AQMixin
|
| 53 |
+
|
| 54 |
+
if version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0"):
|
| 55 |
+
from torchao.dtypes import Int4CPULayout
|
| 56 |
+
if version.parse(importlib.metadata.version("torchao")) >= version.parse("0.11.0"):
|
| 57 |
+
from torchao.dtypes import Int4XPULayout
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def check_torchao_int4_wo_quantized(test_module, qlayer):
|
| 61 |
+
weight = qlayer.weight
|
| 62 |
+
test_module.assertEqual(weight.quant_min, 0)
|
| 63 |
+
test_module.assertEqual(weight.quant_max, 15)
|
| 64 |
+
test_module.assertTrue(isinstance(weight, AffineQuantizedTensor))
|
| 65 |
+
layout = None
|
| 66 |
+
if weight.device.type == "cpu":
|
| 67 |
+
layout = Int4CPULayout
|
| 68 |
+
elif weight.device.type == "xpu":
|
| 69 |
+
layout = Int4XPULayout
|
| 70 |
+
elif weight.device.type == "cuda":
|
| 71 |
+
layout = TensorCoreTiledLayout
|
| 72 |
+
test_module.assertTrue(isinstance(weight.tensor_impl._layout, layout))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def check_autoquantized(test_module, qlayer):
|
| 76 |
+
weight = qlayer.weight
|
| 77 |
+
test_module.assertTrue(isinstance(weight, AQMixin))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def check_forward(test_module, model, batch_size=1, context_size=1024):
|
| 81 |
+
# Test forward pass
|
| 82 |
+
with torch.no_grad():
|
| 83 |
+
out = model(torch.zeros([batch_size, context_size], device=model.device, dtype=torch.int32)).logits
|
| 84 |
+
test_module.assertEqual(out.shape[0], batch_size)
|
| 85 |
+
test_module.assertEqual(out.shape[1], context_size)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@require_torchao
|
| 89 |
+
@require_torchao_version_greater_or_equal("0.8.0")
|
| 90 |
+
class TorchAoConfigTest(unittest.TestCase):
|
| 91 |
+
def test_to_dict(self):
|
| 92 |
+
"""
|
| 93 |
+
Makes sure the config format is properly set
|
| 94 |
+
"""
|
| 95 |
+
quantization_config = TorchAoConfig("int4_weight_only")
|
| 96 |
+
torchao_orig_config = quantization_config.to_dict()
|
| 97 |
+
|
| 98 |
+
for key in torchao_orig_config:
|
| 99 |
+
self.assertEqual(getattr(quantization_config, key), torchao_orig_config[key])
|
| 100 |
+
|
| 101 |
+
def test_post_init_check(self):
|
| 102 |
+
"""
|
| 103 |
+
Test kwargs validations in TorchAoConfig
|
| 104 |
+
"""
|
| 105 |
+
_ = TorchAoConfig("int4_weight_only")
|
| 106 |
+
with self.assertRaisesRegex(ValueError, "Unsupported string quantization type"):
|
| 107 |
+
_ = TorchAoConfig("fp6")
|
| 108 |
+
|
| 109 |
+
with self.assertRaisesRegex(ValueError, "Unexpected keyword arg"):
|
| 110 |
+
_ = TorchAoConfig("int4_weight_only", group_size1=32)
|
| 111 |
+
|
| 112 |
+
def test_repr(self):
|
| 113 |
+
"""
|
| 114 |
+
Check that there is no error in the repr
|
| 115 |
+
"""
|
| 116 |
+
quantization_config = TorchAoConfig("int4_weight_only", modules_to_not_convert=["conv"], group_size=8)
|
| 117 |
+
repr(quantization_config)
|
| 118 |
+
|
| 119 |
+
def test_json_serializable(self):
|
| 120 |
+
"""
|
| 121 |
+
Check that the config dict can be JSON serialized.
|
| 122 |
+
"""
|
| 123 |
+
quantization_config = TorchAoConfig("int4_weight_only", group_size=32, layout=TensorCoreTiledLayout())
|
| 124 |
+
d = quantization_config.to_dict()
|
| 125 |
+
self.assertIsInstance(d["quant_type_kwargs"]["layout"], list)
|
| 126 |
+
self.assertTrue("inner_k_tiles" in d["quant_type_kwargs"]["layout"][1])
|
| 127 |
+
quantization_config.to_json_string(use_diff=False)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@require_torchao
|
| 131 |
+
@require_torchao_version_greater_or_equal("0.8.0")
|
| 132 |
+
class TorchAoTest(unittest.TestCase):
|
| 133 |
+
input_text = "What are we having for dinner?"
|
| 134 |
+
max_new_tokens = 10
|
| 135 |
+
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
| 136 |
+
device = "cpu"
|
| 137 |
+
quant_scheme_kwargs = (
|
| 138 |
+
{"group_size": 32, "layout": Int4CPULayout()}
|
| 139 |
+
if is_torchao_available() and version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0")
|
| 140 |
+
else {"group_size": 32}
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
# called only once for all test in this class
|
| 144 |
+
@classmethod
|
| 145 |
+
def setUpClass(cls):
|
| 146 |
+
cls.EXPECTED_OUTPUT = "What are we having for dinner?\n- 1. What is the temperature outside"
|
| 147 |
+
|
| 148 |
+
def tearDown(self):
|
| 149 |
+
gc.collect()
|
| 150 |
+
backend_empty_cache(torch_device)
|
| 151 |
+
gc.collect()
|
| 152 |
+
|
| 153 |
+
def test_int4wo_quant(self):
|
| 154 |
+
"""
|
| 155 |
+
Simple LLM model testing int4 weight only quantization
|
| 156 |
+
"""
|
| 157 |
+
quant_config = TorchAoConfig("int4_weight_only", **self.quant_scheme_kwargs)
|
| 158 |
+
|
| 159 |
+
# Note: we quantize the bfloat16 model on the fly to int4
|
| 160 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 161 |
+
self.model_name,
|
| 162 |
+
torch_dtype=torch.bfloat16,
|
| 163 |
+
device_map=self.device,
|
| 164 |
+
quantization_config=quant_config,
|
| 165 |
+
)
|
| 166 |
+
tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 167 |
+
|
| 168 |
+
check_torchao_int4_wo_quantized(self, quantized_model.model.layers[0].self_attn.v_proj)
|
| 169 |
+
|
| 170 |
+
input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device)
|
| 171 |
+
|
| 172 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 173 |
+
self.assertEqual(tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 174 |
+
|
| 175 |
+
def test_int4wo_quant_bfloat16_conversion(self):
|
| 176 |
+
"""
|
| 177 |
+
Testing the dtype of model will be modified to be bfloat16 for int4 weight only quantization
|
| 178 |
+
"""
|
| 179 |
+
quant_config = TorchAoConfig("int4_weight_only", **self.quant_scheme_kwargs)
|
| 180 |
+
|
| 181 |
+
# Note: we quantize the bfloat16 model on the fly to int4
|
| 182 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 183 |
+
self.model_name,
|
| 184 |
+
torch_dtype=torch.bfloat16,
|
| 185 |
+
device_map=self.device,
|
| 186 |
+
quantization_config=quant_config,
|
| 187 |
+
)
|
| 188 |
+
tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 189 |
+
|
| 190 |
+
check_torchao_int4_wo_quantized(self, quantized_model.model.layers[0].self_attn.v_proj)
|
| 191 |
+
|
| 192 |
+
input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device)
|
| 193 |
+
|
| 194 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 195 |
+
self.assertEqual(tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 196 |
+
|
| 197 |
+
def test_int8_dynamic_activation_int8_weight_quant(self):
|
| 198 |
+
"""
|
| 199 |
+
Simple LLM model testing int8_dynamic_activation_int8_weight
|
| 200 |
+
"""
|
| 201 |
+
quant_config = TorchAoConfig("int8_dynamic_activation_int8_weight")
|
| 202 |
+
|
| 203 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 204 |
+
self.model_name,
|
| 205 |
+
device_map=self.device,
|
| 206 |
+
quantization_config=quant_config,
|
| 207 |
+
)
|
| 208 |
+
tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 209 |
+
|
| 210 |
+
input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device)
|
| 211 |
+
|
| 212 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 213 |
+
EXPECTED_OUTPUT = [
|
| 214 |
+
"What are we having for dinner?\n\nJessica: (smiling)",
|
| 215 |
+
"What are we having for dinner?\n\nJess: (smiling) I",
|
| 216 |
+
]
|
| 217 |
+
self.assertTrue(tokenizer.decode(output[0], skip_special_tokens=True) in EXPECTED_OUTPUT)
|
| 218 |
+
|
| 219 |
+
@require_torchao_version_greater_or_equal("0.11.0")
|
| 220 |
+
def test_include_input_output_embeddings(self):
|
| 221 |
+
weight_dtype = torch.int8
|
| 222 |
+
granularity = PerAxis(0)
|
| 223 |
+
mapping_type = MappingType.ASYMMETRIC
|
| 224 |
+
embedding_config = IntxWeightOnlyConfig(
|
| 225 |
+
weight_dtype=weight_dtype,
|
| 226 |
+
granularity=granularity,
|
| 227 |
+
mapping_type=mapping_type,
|
| 228 |
+
)
|
| 229 |
+
config = ModuleFqnToConfig(
|
| 230 |
+
{"_default": None, "model.embed_tokens": embedding_config, "lm_head": embedding_config}
|
| 231 |
+
)
|
| 232 |
+
# need set `include_input_output_embeddings` to True
|
| 233 |
+
quant_config = TorchAoConfig(quant_type=config, include_input_output_embeddings=True)
|
| 234 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 235 |
+
self.model_name,
|
| 236 |
+
device_map=self.device,
|
| 237 |
+
quantization_config=quant_config,
|
| 238 |
+
)
|
| 239 |
+
# making sure embedding is quantized
|
| 240 |
+
self.assertTrue(isinstance(quantized_model.model.embed_tokens.weight, AffineQuantizedTensor))
|
| 241 |
+
self.assertTrue(isinstance(quantized_model.lm_head.weight, AffineQuantizedTensor))
|
| 242 |
+
tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 243 |
+
|
| 244 |
+
input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device)
|
| 245 |
+
|
| 246 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 247 |
+
EXPECTED_OUTPUT = [
|
| 248 |
+
"What are we having for dinner?\n\nJessica: (smiling)",
|
| 249 |
+
"What are we having for dinner?\n\nJess: (smiling) I",
|
| 250 |
+
]
|
| 251 |
+
self.assertTrue(tokenizer.decode(output[0], skip_special_tokens=True) in EXPECTED_OUTPUT)
|
| 252 |
+
|
| 253 |
+
@require_torchao_version_greater_or_equal("0.11.0")
|
| 254 |
+
def test_per_module_config_skip(self):
|
| 255 |
+
linear_config = Int8WeightOnlyConfig()
|
| 256 |
+
config = ModuleFqnToConfig({"_default": linear_config, "model.layers.0.self_attn.q_proj": None})
|
| 257 |
+
quant_config = TorchAoConfig(quant_type=config)
|
| 258 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 259 |
+
self.model_name,
|
| 260 |
+
device_map=self.device,
|
| 261 |
+
quantization_config=quant_config,
|
| 262 |
+
)
|
| 263 |
+
# making sure `model.layers.0.self_attn.q_proj` is skipped
|
| 264 |
+
self.assertTrue(not isinstance(quantized_model.model.layers[0].self_attn.q_proj.weight, AffineQuantizedTensor))
|
| 265 |
+
tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 266 |
+
|
| 267 |
+
input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device)
|
| 268 |
+
|
| 269 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 270 |
+
EXPECTED_OUTPUT = [
|
| 271 |
+
"What are we having for dinner?\n\nJessica: (smiling)",
|
| 272 |
+
"What are we having for dinner?\n\nJess: (smiling) I",
|
| 273 |
+
]
|
| 274 |
+
self.assertTrue(tokenizer.decode(output[0], skip_special_tokens=True) in EXPECTED_OUTPUT)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@require_torch_accelerator
|
| 278 |
+
class TorchAoAcceleratorTest(TorchAoTest):
|
| 279 |
+
device = torch_device
|
| 280 |
+
quant_scheme_kwargs = {"group_size": 32}
|
| 281 |
+
|
| 282 |
+
# called only once for all test in this class
|
| 283 |
+
@classmethod
|
| 284 |
+
def setUpClass(cls):
|
| 285 |
+
super().setUpClass()
|
| 286 |
+
# fmt: off
|
| 287 |
+
EXPECTED_OUTPUTS = Expectations(
|
| 288 |
+
{
|
| 289 |
+
("xpu", 3): "What are we having for dinner?\n\nJessica: (smiling)",
|
| 290 |
+
("cuda", 7): "What are we having for dinner?\n- 1. What is the temperature outside",
|
| 291 |
+
}
|
| 292 |
+
)
|
| 293 |
+
# fmt: on
|
| 294 |
+
cls.EXPECTED_OUTPUT = EXPECTED_OUTPUTS.get_expectation()
|
| 295 |
+
|
| 296 |
+
def test_int4wo_offload(self):
|
| 297 |
+
"""
|
| 298 |
+
Simple test that checks if the quantized model int4 weight only is working properly with cpu/disk offload
|
| 299 |
+
"""
|
| 300 |
+
|
| 301 |
+
device_map_offload = {
|
| 302 |
+
"model.embed_tokens": 0,
|
| 303 |
+
"model.layers.0": 0,
|
| 304 |
+
"model.layers.1": 0,
|
| 305 |
+
"model.layers.2": 0,
|
| 306 |
+
"model.layers.3": 0,
|
| 307 |
+
"model.layers.4": 0,
|
| 308 |
+
"model.layers.5": 0,
|
| 309 |
+
"model.layers.6": 0,
|
| 310 |
+
"model.layers.7": 0,
|
| 311 |
+
"model.layers.8": 0,
|
| 312 |
+
"model.layers.9": 0,
|
| 313 |
+
"model.layers.10": 0,
|
| 314 |
+
"model.layers.11": 0,
|
| 315 |
+
"model.layers.12": 0,
|
| 316 |
+
"model.layers.13": 0,
|
| 317 |
+
"model.layers.14": 0,
|
| 318 |
+
"model.layers.15": 0,
|
| 319 |
+
"model.layers.16": 0,
|
| 320 |
+
"model.layers.17": 0,
|
| 321 |
+
"model.layers.18": 0,
|
| 322 |
+
"model.layers.19": "cpu",
|
| 323 |
+
"model.layers.20": "cpu",
|
| 324 |
+
"model.layers.21": "disk",
|
| 325 |
+
"model.norm": 0,
|
| 326 |
+
"model.rotary_emb": 0,
|
| 327 |
+
"lm_head": 0,
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
quant_config = TorchAoConfig("int4_weight_only", group_size=32)
|
| 331 |
+
|
| 332 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 333 |
+
self.model_name,
|
| 334 |
+
torch_dtype=torch.bfloat16,
|
| 335 |
+
device_map=device_map_offload,
|
| 336 |
+
quantization_config=quant_config,
|
| 337 |
+
)
|
| 338 |
+
tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 339 |
+
|
| 340 |
+
input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device)
|
| 341 |
+
|
| 342 |
+
# fmt: off
|
| 343 |
+
EXPECTED_OUTPUTS = Expectations(
|
| 344 |
+
{
|
| 345 |
+
("xpu", 3): "What are we having for dinner?\n\nJessica: (smiling)",
|
| 346 |
+
("cuda", 7): "What are we having for dinner?\n- 2. What is the temperature outside",
|
| 347 |
+
}
|
| 348 |
+
)
|
| 349 |
+
# fmt: on
|
| 350 |
+
EXPECTED_OUTPUT = EXPECTED_OUTPUTS.get_expectation()
|
| 351 |
+
|
| 352 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 353 |
+
generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 354 |
+
|
| 355 |
+
self.assertEqual(generated_text, EXPECTED_OUTPUT)
|
| 356 |
+
|
| 357 |
+
@require_torch_multi_accelerator
|
| 358 |
+
def test_int4wo_quant_multi_accelerator(self):
|
| 359 |
+
"""
|
| 360 |
+
Simple test that checks if the quantized model int4 weight only is working properly with multiple accelerators
|
| 361 |
+
set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 CUDA GPUs
|
| 362 |
+
set ZE_AFFINITY_MASK=0,1 if you have more than 2 Intel XPUs
|
| 363 |
+
"""
|
| 364 |
+
|
| 365 |
+
quant_config = TorchAoConfig("int4_weight_only", **self.quant_scheme_kwargs)
|
| 366 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 367 |
+
self.model_name,
|
| 368 |
+
torch_dtype=torch.bfloat16,
|
| 369 |
+
device_map="auto",
|
| 370 |
+
quantization_config=quant_config,
|
| 371 |
+
)
|
| 372 |
+
tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 373 |
+
|
| 374 |
+
self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1})
|
| 375 |
+
|
| 376 |
+
input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device)
|
| 377 |
+
|
| 378 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 379 |
+
self.assertEqual(tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 380 |
+
|
| 381 |
+
def test_autoquant(self):
|
| 382 |
+
"""
|
| 383 |
+
Simple LLM model testing autoquant
|
| 384 |
+
"""
|
| 385 |
+
quant_config = TorchAoConfig("autoquant")
|
| 386 |
+
|
| 387 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 388 |
+
self.model_name,
|
| 389 |
+
torch_dtype="auto",
|
| 390 |
+
device_map=self.device,
|
| 391 |
+
quantization_config=quant_config,
|
| 392 |
+
)
|
| 393 |
+
tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 394 |
+
input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device)
|
| 395 |
+
output = quantized_model.generate(
|
| 396 |
+
**input_ids, max_new_tokens=self.max_new_tokens, cache_implementation="static"
|
| 397 |
+
)
|
| 398 |
+
quantized_model.finalize_autoquant()
|
| 399 |
+
|
| 400 |
+
check_autoquantized(self, quantized_model.model.layers[0].self_attn.v_proj)
|
| 401 |
+
|
| 402 |
+
EXPECTED_OUTPUT = "What are we having for dinner?\n\nJane: (sighs)"
|
| 403 |
+
output = quantized_model.generate(
|
| 404 |
+
**input_ids, max_new_tokens=self.max_new_tokens, cache_implementation="static"
|
| 405 |
+
)
|
| 406 |
+
self.assertEqual(tokenizer.decode(output[0], skip_special_tokens=True), EXPECTED_OUTPUT)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@require_torchao
|
| 410 |
+
@require_torchao_version_greater_or_equal("0.8.0")
|
| 411 |
+
class TorchAoSerializationTest(unittest.TestCase):
|
| 412 |
+
input_text = "What are we having for dinner?"
|
| 413 |
+
max_new_tokens = 10
|
| 414 |
+
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
| 415 |
+
quant_scheme = "int4_weight_only"
|
| 416 |
+
quant_scheme_kwargs = (
|
| 417 |
+
{"group_size": 32, "layout": Int4CPULayout()}
|
| 418 |
+
if is_torchao_available() and version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0")
|
| 419 |
+
else {"group_size": 32}
|
| 420 |
+
)
|
| 421 |
+
device = "cpu"
|
| 422 |
+
|
| 423 |
+
# called only once for all test in this class
|
| 424 |
+
@classmethod
|
| 425 |
+
def setUpClass(cls):
|
| 426 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name)
|
| 427 |
+
cls.EXPECTED_OUTPUT = "What are we having for dinner?\n- 1. What is the temperature outside"
|
| 428 |
+
|
| 429 |
+
def setUp(self):
|
| 430 |
+
self.quant_config = TorchAoConfig(self.quant_scheme, **self.quant_scheme_kwargs)
|
| 431 |
+
torch_dtype = torch.bfloat16 if self.quant_scheme == "int4_weight_only" else "auto"
|
| 432 |
+
self.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 433 |
+
self.model_name,
|
| 434 |
+
torch_dtype=torch_dtype,
|
| 435 |
+
device_map=self.device,
|
| 436 |
+
quantization_config=self.quant_config,
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
def tearDown(self):
|
| 440 |
+
gc.collect()
|
| 441 |
+
backend_empty_cache(torch_device)
|
| 442 |
+
gc.collect()
|
| 443 |
+
|
| 444 |
+
def test_original_model_expected_output(self):
|
| 445 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device)
|
| 446 |
+
output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 447 |
+
|
| 448 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 449 |
+
|
| 450 |
+
def check_serialization_expected_output(self, device, expected_output):
|
| 451 |
+
"""
|
| 452 |
+
Test if we can serialize and load/infer the model again on the same device
|
| 453 |
+
"""
|
| 454 |
+
torch_dtype = torch.bfloat16 if self.quant_scheme == "int4_weight_only" else "auto"
|
| 455 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 456 |
+
self.quantized_model.save_pretrained(tmpdirname, safe_serialization=False)
|
| 457 |
+
loaded_quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 458 |
+
tmpdirname, torch_dtype=torch_dtype, device_map=device
|
| 459 |
+
)
|
| 460 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(device)
|
| 461 |
+
|
| 462 |
+
output = loaded_quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
|
| 463 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), expected_output)
|
| 464 |
+
|
| 465 |
+
def test_serialization_expected_output(self):
|
| 466 |
+
self.check_serialization_expected_output(self.device, self.EXPECTED_OUTPUT)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
class TorchAoSerializationW8A8CPUTest(TorchAoSerializationTest):
|
| 470 |
+
quant_scheme, quant_scheme_kwargs = "int8_dynamic_activation_int8_weight", {}
|
| 471 |
+
|
| 472 |
+
# called only once for all test in this class
|
| 473 |
+
@classmethod
|
| 474 |
+
def setUpClass(cls):
|
| 475 |
+
super().setUpClass()
|
| 476 |
+
cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)"
|
| 477 |
+
|
| 478 |
+
@require_torch_accelerator
|
| 479 |
+
def test_serialization_expected_output_on_accelerator(self):
|
| 480 |
+
"""
|
| 481 |
+
Test if we can serialize on device (cpu) and load/infer the model on accelerator
|
| 482 |
+
"""
|
| 483 |
+
self.check_serialization_expected_output(torch_device, self.EXPECTED_OUTPUT)
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
class TorchAoSerializationW8CPUTest(TorchAoSerializationTest):
|
| 487 |
+
quant_scheme, quant_scheme_kwargs = "int8_weight_only", {}
|
| 488 |
+
|
| 489 |
+
# called only once for all test in this class
|
| 490 |
+
@classmethod
|
| 491 |
+
def setUpClass(cls):
|
| 492 |
+
super().setUpClass()
|
| 493 |
+
cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)"
|
| 494 |
+
|
| 495 |
+
@require_torch_accelerator
|
| 496 |
+
def test_serialization_expected_output_on_accelerator(self):
|
| 497 |
+
"""
|
| 498 |
+
Test if we can serialize on device (cpu) and load/infer the model on accelerator
|
| 499 |
+
"""
|
| 500 |
+
self.check_serialization_expected_output(torch_device, self.EXPECTED_OUTPUT)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
@require_torch_accelerator
|
| 504 |
+
class TorchAoSerializationAcceleratorTest(TorchAoSerializationTest):
|
| 505 |
+
quant_scheme, quant_scheme_kwargs = "int4_weight_only", {"group_size": 32}
|
| 506 |
+
device = f"{torch_device}:0"
|
| 507 |
+
|
| 508 |
+
# called only once for all test in this class
|
| 509 |
+
@classmethod
|
| 510 |
+
def setUpClass(cls):
|
| 511 |
+
super().setUpClass()
|
| 512 |
+
# fmt: off
|
| 513 |
+
EXPECTED_OUTPUTS = Expectations(
|
| 514 |
+
{
|
| 515 |
+
("xpu", 3): "What are we having for dinner?\n\nJessica: (smiling)",
|
| 516 |
+
("cuda", 7): "What are we having for dinner?\n- 1. What is the temperature outside",
|
| 517 |
+
}
|
| 518 |
+
)
|
| 519 |
+
# fmt: on
|
| 520 |
+
cls.EXPECTED_OUTPUT = EXPECTED_OUTPUTS.get_expectation()
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
@require_torch_accelerator
|
| 524 |
+
class TorchAoSerializationW8A8AcceleratorTest(TorchAoSerializationTest):
|
| 525 |
+
quant_scheme, quant_scheme_kwargs = "int8_dynamic_activation_int8_weight", {}
|
| 526 |
+
device = f"{torch_device}:0"
|
| 527 |
+
|
| 528 |
+
# called only once for all test in this class
|
| 529 |
+
@classmethod
|
| 530 |
+
def setUpClass(cls):
|
| 531 |
+
super().setUpClass()
|
| 532 |
+
cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)"
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
@require_torch_accelerator
|
| 536 |
+
class TorchAoSerializationW8AcceleratorTest(TorchAoSerializationTest):
|
| 537 |
+
quant_scheme, quant_scheme_kwargs = "int8_weight_only", {}
|
| 538 |
+
device = f"{torch_device}:0"
|
| 539 |
+
|
| 540 |
+
# called only once for all test in this class
|
| 541 |
+
@classmethod
|
| 542 |
+
def setUpClass(cls):
|
| 543 |
+
super().setUpClass()
|
| 544 |
+
cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)"
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
@require_torch_accelerator
|
| 548 |
+
@require_torchao_version_greater_or_equal("0.10.0")
|
| 549 |
+
class TorchAoSerializationFP8AcceleratorTest(TorchAoSerializationTest):
|
| 550 |
+
device = f"{torch_device}:0"
|
| 551 |
+
|
| 552 |
+
# called only once for all test in this class
|
| 553 |
+
@classmethod
|
| 554 |
+
def setUpClass(cls):
|
| 555 |
+
device_type, major, minor = get_device_properties()
|
| 556 |
+
if device_type == "cuda" and major < 9:
|
| 557 |
+
raise unittest.SkipTest("CUDA compute capability 9.0 or higher required for FP8 tests")
|
| 558 |
+
|
| 559 |
+
from torchao.quantization import Float8WeightOnlyConfig
|
| 560 |
+
|
| 561 |
+
cls.quant_scheme = Float8WeightOnlyConfig()
|
| 562 |
+
cls.quant_scheme_kwargs = {}
|
| 563 |
+
|
| 564 |
+
super().setUpClass()
|
| 565 |
+
|
| 566 |
+
cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)"
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
@require_torch_accelerator
|
| 570 |
+
@require_torchao_version_greater_or_equal("0.10.0")
|
| 571 |
+
class TorchAoSerializationA8W4Test(TorchAoSerializationTest):
|
| 572 |
+
device = f"{torch_device}:0"
|
| 573 |
+
|
| 574 |
+
# called only once for all test in this class
|
| 575 |
+
@classmethod
|
| 576 |
+
def setUpClass(cls):
|
| 577 |
+
device_type, major, minor = get_device_properties()
|
| 578 |
+
if device_type == "cuda" and major < 9:
|
| 579 |
+
raise unittest.SkipTest("CUDA compute capability 9.0 or higher required for FP8 tests")
|
| 580 |
+
|
| 581 |
+
from torchao.quantization import Int8DynamicActivationInt4WeightConfig
|
| 582 |
+
|
| 583 |
+
cls.quant_scheme = Int8DynamicActivationInt4WeightConfig()
|
| 584 |
+
cls.quant_scheme_kwargs = {}
|
| 585 |
+
|
| 586 |
+
super().setUpClass()
|
| 587 |
+
|
| 588 |
+
cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)"
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
if __name__ == "__main__":
|
| 592 |
+
unittest.main()
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/vptq_integration/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/vptq_integration/test_vptq.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import tempfile
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, VptqConfig
|
| 20 |
+
from transformers.testing_utils import (
|
| 21 |
+
backend_empty_cache,
|
| 22 |
+
require_accelerate,
|
| 23 |
+
require_torch_gpu,
|
| 24 |
+
require_torch_multi_gpu,
|
| 25 |
+
require_vptq,
|
| 26 |
+
slow,
|
| 27 |
+
torch_device,
|
| 28 |
+
)
|
| 29 |
+
from transformers.utils import is_accelerate_available, is_torch_available
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if is_torch_available():
|
| 33 |
+
import torch
|
| 34 |
+
|
| 35 |
+
if is_accelerate_available():
|
| 36 |
+
from accelerate import init_empty_weights
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class VptqConfigTest(unittest.TestCase):
|
| 40 |
+
def test_to_dict(self):
|
| 41 |
+
"""
|
| 42 |
+
Makes sure the config format is properly set
|
| 43 |
+
"""
|
| 44 |
+
quantization_config = VptqConfig()
|
| 45 |
+
vptq_orig_config = quantization_config.to_dict()
|
| 46 |
+
|
| 47 |
+
self.assertEqual(vptq_orig_config["quant_method"], quantization_config.quant_method)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@slow
|
| 51 |
+
@require_torch_gpu
|
| 52 |
+
@require_vptq
|
| 53 |
+
@require_accelerate
|
| 54 |
+
class VptqTest(unittest.TestCase):
|
| 55 |
+
model_name = "VPTQ-community/Meta-Llama-3.1-8B-Instruct-v12-k65536-4096-woft"
|
| 56 |
+
|
| 57 |
+
input_text = "Hello my name is"
|
| 58 |
+
max_new_tokens = 32
|
| 59 |
+
|
| 60 |
+
EXPECTED_OUTPUT = "Hello my name is Sarah and I am a 25 year old woman from the United States. I am a college graduate and I am currently working as a marketing specialist for a small"
|
| 61 |
+
|
| 62 |
+
device_map = "cuda"
|
| 63 |
+
|
| 64 |
+
# called only once for all test in this class
|
| 65 |
+
@classmethod
|
| 66 |
+
def setUpClass(cls):
|
| 67 |
+
"""
|
| 68 |
+
Setup quantized model
|
| 69 |
+
"""
|
| 70 |
+
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name)
|
| 71 |
+
cls.quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 72 |
+
cls.model_name,
|
| 73 |
+
device_map=cls.device_map,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
def tearDown(self):
|
| 77 |
+
gc.collect()
|
| 78 |
+
backend_empty_cache(torch_device)
|
| 79 |
+
gc.collect()
|
| 80 |
+
|
| 81 |
+
def test_quantized_model(self):
|
| 82 |
+
"""
|
| 83 |
+
Simple test that checks if the quantized model is working properly
|
| 84 |
+
"""
|
| 85 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 86 |
+
|
| 87 |
+
output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False)
|
| 88 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 89 |
+
|
| 90 |
+
def test_raise_if_non_quantized(self):
|
| 91 |
+
model_id = "facebook/opt-125m"
|
| 92 |
+
quantization_config = VptqConfig()
|
| 93 |
+
|
| 94 |
+
with self.assertRaises(ValueError):
|
| 95 |
+
_ = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=quantization_config)
|
| 96 |
+
|
| 97 |
+
def test_save_pretrained(self):
|
| 98 |
+
"""
|
| 99 |
+
Simple test that checks if the quantized model is working properly after being saved and loaded
|
| 100 |
+
"""
|
| 101 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 102 |
+
self.quantized_model.save_pretrained(tmpdirname)
|
| 103 |
+
model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map)
|
| 104 |
+
|
| 105 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 106 |
+
|
| 107 |
+
output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False)
|
| 108 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 109 |
+
|
| 110 |
+
@require_torch_multi_gpu
|
| 111 |
+
def test_quantized_model_multi_gpu(self):
|
| 112 |
+
"""
|
| 113 |
+
Simple test that checks if the quantized model is working properly with multiple GPUs
|
| 114 |
+
"""
|
| 115 |
+
input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
|
| 116 |
+
|
| 117 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(self.model_name, device_map="auto")
|
| 118 |
+
|
| 119 |
+
self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1})
|
| 120 |
+
|
| 121 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False)
|
| 122 |
+
|
| 123 |
+
self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
|
| 124 |
+
|
| 125 |
+
def test_quantized_model_conversion(self):
|
| 126 |
+
"""
|
| 127 |
+
Simple test that checks if the quantized model has been converted properly
|
| 128 |
+
"""
|
| 129 |
+
from vptq import VQuantLinear
|
| 130 |
+
|
| 131 |
+
from transformers.integrations import replace_with_vptq_linear
|
| 132 |
+
|
| 133 |
+
model_id = "facebook/opt-350m"
|
| 134 |
+
config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5")
|
| 135 |
+
modules_to_not_convert = ["lm_head"]
|
| 136 |
+
names = [
|
| 137 |
+
"q_proj",
|
| 138 |
+
"k_proj",
|
| 139 |
+
"v_proj",
|
| 140 |
+
"out_proj",
|
| 141 |
+
"fc1",
|
| 142 |
+
"fc2",
|
| 143 |
+
]
|
| 144 |
+
value = {
|
| 145 |
+
"enable_norm": True,
|
| 146 |
+
"enable_perm": True,
|
| 147 |
+
"group_num": 1,
|
| 148 |
+
"group_size": 128,
|
| 149 |
+
"indices_as_float": False,
|
| 150 |
+
"num_centroids": [-1, 128],
|
| 151 |
+
"num_res_centroids": [-1, 128],
|
| 152 |
+
"outlier_size": 0,
|
| 153 |
+
"vector_lens": [-1, 12],
|
| 154 |
+
}
|
| 155 |
+
shared_layer_config = {}
|
| 156 |
+
for name in names:
|
| 157 |
+
shared_layer_config[name] = value
|
| 158 |
+
for i in range(24):
|
| 159 |
+
modules_to_not_convert.append(f"model.decoder.layers.{i}.fc1")
|
| 160 |
+
layer_configs = {}
|
| 161 |
+
layer_configs["model.decoder.project_out"] = value
|
| 162 |
+
layer_configs["model.decoder.project_in"] = value
|
| 163 |
+
quantization_config = VptqConfig(config_for_layers=layer_configs, shared_layer_config=shared_layer_config)
|
| 164 |
+
|
| 165 |
+
with init_empty_weights():
|
| 166 |
+
model = AutoModelForCausalLM.from_config(config)
|
| 167 |
+
|
| 168 |
+
nb_linears = 0
|
| 169 |
+
for module in model.modules():
|
| 170 |
+
if isinstance(module, torch.nn.Linear):
|
| 171 |
+
nb_linears += 1
|
| 172 |
+
|
| 173 |
+
model, _ = replace_with_vptq_linear(model, quantization_config=quantization_config)
|
| 174 |
+
nb_vptq_linear = 0
|
| 175 |
+
for module in model.modules():
|
| 176 |
+
if isinstance(module, VQuantLinear):
|
| 177 |
+
nb_vptq_linear += 1
|
| 178 |
+
|
| 179 |
+
self.assertEqual(nb_linears - 1, nb_vptq_linear)
|
| 180 |
+
|
| 181 |
+
# Try with `linear_weights_not_to_quantize`
|
| 182 |
+
with init_empty_weights():
|
| 183 |
+
model = AutoModelForCausalLM.from_config(config)
|
| 184 |
+
quantization_config = VptqConfig(config_for_layers=layer_configs, shared_layer_config=shared_layer_config)
|
| 185 |
+
model, _ = replace_with_vptq_linear(
|
| 186 |
+
model, quantization_config=quantization_config, modules_to_not_convert=modules_to_not_convert
|
| 187 |
+
)
|
| 188 |
+
nb_vptq_linear = 0
|
| 189 |
+
for module in model.modules():
|
| 190 |
+
if isinstance(module, VQuantLinear):
|
| 191 |
+
nb_vptq_linear += 1
|
| 192 |
+
# 25 comes from 24 decoder.layers.{layer_idx}.fc1
|
| 193 |
+
# and the last lm_head
|
| 194 |
+
self.assertEqual(nb_linears - 25, nb_vptq_linear)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/modular/test_conversion_order.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import unittest
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
|
| 7 |
+
sys.path.append(os.path.join(ROOT_DIR, "utils"))
|
| 8 |
+
|
| 9 |
+
import create_dependency_mapping # noqa: E402
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# This is equivalent to `all` in the current library state (as of 09/01/2025)
|
| 13 |
+
MODEL_ROOT = os.path.join("src", "transformers", "models")
|
| 14 |
+
FILES_TO_PARSE = [
|
| 15 |
+
os.path.join(MODEL_ROOT, "starcoder2", "modular_starcoder2.py"),
|
| 16 |
+
os.path.join(MODEL_ROOT, "gemma", "modular_gemma.py"),
|
| 17 |
+
os.path.join(MODEL_ROOT, "olmo2", "modular_olmo2.py"),
|
| 18 |
+
os.path.join(MODEL_ROOT, "diffllama", "modular_diffllama.py"),
|
| 19 |
+
os.path.join(MODEL_ROOT, "granite", "modular_granite.py"),
|
| 20 |
+
os.path.join(MODEL_ROOT, "gemma2", "modular_gemma2.py"),
|
| 21 |
+
os.path.join(MODEL_ROOT, "mixtral", "modular_mixtral.py"),
|
| 22 |
+
os.path.join(MODEL_ROOT, "olmo", "modular_olmo.py"),
|
| 23 |
+
os.path.join(MODEL_ROOT, "rt_detr", "modular_rt_detr.py"),
|
| 24 |
+
os.path.join(MODEL_ROOT, "qwen2", "modular_qwen2.py"),
|
| 25 |
+
os.path.join(MODEL_ROOT, "qwen3", "modular_qwen3.py"),
|
| 26 |
+
os.path.join(MODEL_ROOT, "llava_next_video", "modular_llava_next_video.py"),
|
| 27 |
+
os.path.join(MODEL_ROOT, "cohere2", "modular_cohere2.py"),
|
| 28 |
+
os.path.join(MODEL_ROOT, "modernbert", "modular_modernbert.py"),
|
| 29 |
+
os.path.join(MODEL_ROOT, "colpali", "modular_colpali.py"),
|
| 30 |
+
os.path.join(MODEL_ROOT, "deformable_detr", "modular_deformable_detr.py"),
|
| 31 |
+
os.path.join(MODEL_ROOT, "aria", "modular_aria.py"),
|
| 32 |
+
os.path.join(MODEL_ROOT, "ijepa", "modular_ijepa.py"),
|
| 33 |
+
os.path.join(MODEL_ROOT, "bamba", "modular_bamba.py"),
|
| 34 |
+
os.path.join(MODEL_ROOT, "dinov2_with_registers", "modular_dinov2_with_registers.py"),
|
| 35 |
+
os.path.join(MODEL_ROOT, "instructblipvideo", "modular_instructblipvideo.py"),
|
| 36 |
+
os.path.join(MODEL_ROOT, "glm", "modular_glm.py"),
|
| 37 |
+
os.path.join(MODEL_ROOT, "phi", "modular_phi.py"),
|
| 38 |
+
os.path.join(MODEL_ROOT, "mistral", "modular_mistral.py"),
|
| 39 |
+
os.path.join(MODEL_ROOT, "phi3", "modular_phi3.py"),
|
| 40 |
+
os.path.join(MODEL_ROOT, "cohere", "modular_cohere.py"),
|
| 41 |
+
os.path.join(MODEL_ROOT, "glm4", "modular_glm4.py"),
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def appear_after(model1: str, model2: str, priority_list: list[list[str]]) -> bool:
|
| 46 |
+
"""Return True if `model1` appear after `model2` in `priority_list`."""
|
| 47 |
+
model1_index, model2_index = None, None
|
| 48 |
+
for i, level in enumerate(priority_list):
|
| 49 |
+
if model1 in level:
|
| 50 |
+
model1_index = i
|
| 51 |
+
if model2 in level:
|
| 52 |
+
model2_index = i
|
| 53 |
+
if model1_index is None or model2_index is None:
|
| 54 |
+
raise ValueError(f"Model {model1} or {model2} not found in {priority_list}")
|
| 55 |
+
return model1_index > model2_index
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class ConversionOrderTest(unittest.TestCase):
|
| 59 |
+
def test_conversion_order(self):
|
| 60 |
+
# Find the order
|
| 61 |
+
priority_list, _ = create_dependency_mapping.find_priority_list(FILES_TO_PARSE)
|
| 62 |
+
# Extract just the model names (list of lists)
|
| 63 |
+
model_priority_list = [[file.split("/")[-2] for file in level] for level in priority_list]
|
| 64 |
+
|
| 65 |
+
# These are based on what the current library order should be (as of 09/01/2025)
|
| 66 |
+
self.assertTrue(appear_after("mixtral", "mistral", model_priority_list))
|
| 67 |
+
self.assertTrue(appear_after("gemma2", "gemma", model_priority_list))
|
| 68 |
+
self.assertTrue(appear_after("starcoder2", "mistral", model_priority_list))
|
| 69 |
+
self.assertTrue(appear_after("olmo2", "olmo", model_priority_list))
|
| 70 |
+
self.assertTrue(appear_after("diffllama", "mistral", model_priority_list))
|
| 71 |
+
self.assertTrue(appear_after("cohere2", "gemma2", model_priority_list))
|
| 72 |
+
self.assertTrue(appear_after("cohere2", "cohere", model_priority_list))
|
| 73 |
+
self.assertTrue(appear_after("phi3", "mistral", model_priority_list))
|
| 74 |
+
self.assertTrue(appear_after("glm4", "glm", model_priority_list))
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_check_copies.py
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import shutil
|
| 17 |
+
import sys
|
| 18 |
+
import tempfile
|
| 19 |
+
import unittest
|
| 20 |
+
from contextlib import contextmanager
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
|
| 25 |
+
sys.path.append(os.path.join(git_repo_path, "utils"))
|
| 26 |
+
|
| 27 |
+
import check_copies # noqa: E402
|
| 28 |
+
from check_copies import convert_to_localized_md, find_code_in_transformers, is_copy_consistent # noqa: E402
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# This is the reference code that will be used in the tests.
|
| 32 |
+
# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.
|
| 33 |
+
REFERENCE_CODE = """ def __init__(self, config):
|
| 34 |
+
super().__init__()
|
| 35 |
+
self.transform = BertPredictionHeadTransform(config)
|
| 36 |
+
|
| 37 |
+
# The output weights are the same as the input embeddings, but there is
|
| 38 |
+
# an output-only bias for each token.
|
| 39 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 40 |
+
|
| 41 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 42 |
+
|
| 43 |
+
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
|
| 44 |
+
self.decoder.bias = self.bias
|
| 45 |
+
|
| 46 |
+
def forward(self, hidden_states):
|
| 47 |
+
hidden_states = self.transform(hidden_states)
|
| 48 |
+
hidden_states = self.decoder(hidden_states)
|
| 49 |
+
return hidden_states
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
MOCK_BERT_CODE = """from ...modeling_utils import PreTrainedModel
|
| 53 |
+
|
| 54 |
+
def bert_function(x):
|
| 55 |
+
return x
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class BertAttention(nn.Module):
|
| 59 |
+
def __init__(self, config):
|
| 60 |
+
super().__init__()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class BertModel(BertPreTrainedModel):
|
| 64 |
+
def __init__(self, config):
|
| 65 |
+
super().__init__()
|
| 66 |
+
self.bert = BertEncoder(config)
|
| 67 |
+
|
| 68 |
+
@add_docstring(BERT_DOCSTRING)
|
| 69 |
+
def forward(self, x):
|
| 70 |
+
return self.bert(x)
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
MOCK_BERT_COPY_CODE = """from ...modeling_utils import PreTrainedModel
|
| 74 |
+
|
| 75 |
+
# Copied from transformers.models.bert.modeling_bert.bert_function
|
| 76 |
+
def bert_copy_function(x):
|
| 77 |
+
return x
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# Copied from transformers.models.bert.modeling_bert.BertAttention
|
| 81 |
+
class BertCopyAttention(nn.Module):
|
| 82 |
+
def __init__(self, config):
|
| 83 |
+
super().__init__()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# Copied from transformers.models.bert.modeling_bert.BertModel with Bert->BertCopy all-casing
|
| 87 |
+
class BertCopyModel(BertCopyPreTrainedModel):
|
| 88 |
+
def __init__(self, config):
|
| 89 |
+
super().__init__()
|
| 90 |
+
self.bertcopy = BertCopyEncoder(config)
|
| 91 |
+
|
| 92 |
+
@add_docstring(BERTCOPY_DOCSTRING)
|
| 93 |
+
def forward(self, x):
|
| 94 |
+
return self.bertcopy(x)
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
MOCK_DUMMY_BERT_CODE_MATCH = """
|
| 99 |
+
class BertDummyModel:
|
| 100 |
+
attr_1 = 1
|
| 101 |
+
attr_2 = 2
|
| 102 |
+
|
| 103 |
+
def __init__(self, a=1, b=2):
|
| 104 |
+
self.a = a
|
| 105 |
+
self.b = b
|
| 106 |
+
|
| 107 |
+
# Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward
|
| 108 |
+
def forward(self, c):
|
| 109 |
+
return 1
|
| 110 |
+
|
| 111 |
+
def existing_common(self, c):
|
| 112 |
+
return 4
|
| 113 |
+
|
| 114 |
+
def existing_diff_to_be_ignored(self, c):
|
| 115 |
+
return 9
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
MOCK_DUMMY_ROBERTA_CODE_MATCH = """
|
| 120 |
+
# Copied from transformers.models.dummy_bert_match.modeling_dummy_bert_match.BertDummyModel with BertDummy->RobertaBertDummy
|
| 121 |
+
class RobertaBertDummyModel:
|
| 122 |
+
|
| 123 |
+
attr_1 = 1
|
| 124 |
+
attr_2 = 2
|
| 125 |
+
|
| 126 |
+
def __init__(self, a=1, b=2):
|
| 127 |
+
self.a = a
|
| 128 |
+
self.b = b
|
| 129 |
+
|
| 130 |
+
# Ignore copy
|
| 131 |
+
def only_in_roberta_to_be_ignored(self, c):
|
| 132 |
+
return 3
|
| 133 |
+
|
| 134 |
+
# Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward
|
| 135 |
+
def forward(self, c):
|
| 136 |
+
return 1
|
| 137 |
+
|
| 138 |
+
def existing_common(self, c):
|
| 139 |
+
return 4
|
| 140 |
+
|
| 141 |
+
# Ignore copy
|
| 142 |
+
def existing_diff_to_be_ignored(self, c):
|
| 143 |
+
return 6
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
MOCK_DUMMY_BERT_CODE_NO_MATCH = """
|
| 148 |
+
class BertDummyModel:
|
| 149 |
+
attr_1 = 1
|
| 150 |
+
attr_2 = 2
|
| 151 |
+
|
| 152 |
+
def __init__(self, a=1, b=2):
|
| 153 |
+
self.a = a
|
| 154 |
+
self.b = b
|
| 155 |
+
|
| 156 |
+
# Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward
|
| 157 |
+
def forward(self, c):
|
| 158 |
+
return 1
|
| 159 |
+
|
| 160 |
+
def only_in_bert(self, c):
|
| 161 |
+
return 7
|
| 162 |
+
|
| 163 |
+
def existing_common(self, c):
|
| 164 |
+
return 4
|
| 165 |
+
|
| 166 |
+
def existing_diff_not_ignored(self, c):
|
| 167 |
+
return 8
|
| 168 |
+
|
| 169 |
+
def existing_diff_to_be_ignored(self, c):
|
| 170 |
+
return 9
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
MOCK_DUMMY_ROBERTA_CODE_NO_MATCH = """
|
| 175 |
+
# Copied from transformers.models.dummy_bert_no_match.modeling_dummy_bert_no_match.BertDummyModel with BertDummy->RobertaBertDummy
|
| 176 |
+
class RobertaBertDummyModel:
|
| 177 |
+
|
| 178 |
+
attr_1 = 1
|
| 179 |
+
attr_2 = 3
|
| 180 |
+
|
| 181 |
+
def __init__(self, a=1, b=2):
|
| 182 |
+
self.a = a
|
| 183 |
+
self.b = b
|
| 184 |
+
|
| 185 |
+
# Ignore copy
|
| 186 |
+
def only_in_roberta_to_be_ignored(self, c):
|
| 187 |
+
return 3
|
| 188 |
+
|
| 189 |
+
# Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward
|
| 190 |
+
def forward(self, c):
|
| 191 |
+
return 1
|
| 192 |
+
|
| 193 |
+
def only_in_roberta_not_ignored(self, c):
|
| 194 |
+
return 2
|
| 195 |
+
|
| 196 |
+
def existing_common(self, c):
|
| 197 |
+
return 4
|
| 198 |
+
|
| 199 |
+
def existing_diff_not_ignored(self, c):
|
| 200 |
+
return 5
|
| 201 |
+
|
| 202 |
+
# Ignore copy
|
| 203 |
+
def existing_diff_to_be_ignored(self, c):
|
| 204 |
+
return 6
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
EXPECTED_REPLACED_CODE = """
|
| 209 |
+
# Copied from transformers.models.dummy_bert_no_match.modeling_dummy_bert_no_match.BertDummyModel with BertDummy->RobertaBertDummy
|
| 210 |
+
class RobertaBertDummyModel:
|
| 211 |
+
attr_1 = 1
|
| 212 |
+
attr_2 = 2
|
| 213 |
+
|
| 214 |
+
def __init__(self, a=1, b=2):
|
| 215 |
+
self.a = a
|
| 216 |
+
self.b = b
|
| 217 |
+
|
| 218 |
+
# Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward
|
| 219 |
+
def forward(self, c):
|
| 220 |
+
return 1
|
| 221 |
+
|
| 222 |
+
def only_in_bert(self, c):
|
| 223 |
+
return 7
|
| 224 |
+
|
| 225 |
+
def existing_common(self, c):
|
| 226 |
+
return 4
|
| 227 |
+
|
| 228 |
+
def existing_diff_not_ignored(self, c):
|
| 229 |
+
return 8
|
| 230 |
+
|
| 231 |
+
# Ignore copy
|
| 232 |
+
def existing_diff_to_be_ignored(self, c):
|
| 233 |
+
return 6
|
| 234 |
+
|
| 235 |
+
# Ignore copy
|
| 236 |
+
def only_in_roberta_to_be_ignored(self, c):
|
| 237 |
+
return 3
|
| 238 |
+
"""
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def replace_in_file(filename, old, new):
|
| 242 |
+
with open(filename, encoding="utf-8") as f:
|
| 243 |
+
content = f.read()
|
| 244 |
+
|
| 245 |
+
content = content.replace(old, new)
|
| 246 |
+
|
| 247 |
+
with open(filename, "w", encoding="utf-8", newline="\n") as f:
|
| 248 |
+
f.write(content)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def create_tmp_repo(tmp_dir):
|
| 252 |
+
"""
|
| 253 |
+
Creates a mock repository in a temporary folder for testing.
|
| 254 |
+
"""
|
| 255 |
+
tmp_dir = Path(tmp_dir)
|
| 256 |
+
if tmp_dir.exists():
|
| 257 |
+
shutil.rmtree(tmp_dir)
|
| 258 |
+
tmp_dir.mkdir(exist_ok=True)
|
| 259 |
+
|
| 260 |
+
model_dir = tmp_dir / "src" / "transformers" / "models"
|
| 261 |
+
model_dir.mkdir(parents=True, exist_ok=True)
|
| 262 |
+
|
| 263 |
+
models = {
|
| 264 |
+
"bert": MOCK_BERT_CODE,
|
| 265 |
+
"bertcopy": MOCK_BERT_COPY_CODE,
|
| 266 |
+
"dummy_bert_match": MOCK_DUMMY_BERT_CODE_MATCH,
|
| 267 |
+
"dummy_roberta_match": MOCK_DUMMY_ROBERTA_CODE_MATCH,
|
| 268 |
+
"dummy_bert_no_match": MOCK_DUMMY_BERT_CODE_NO_MATCH,
|
| 269 |
+
"dummy_roberta_no_match": MOCK_DUMMY_ROBERTA_CODE_NO_MATCH,
|
| 270 |
+
}
|
| 271 |
+
for model, code in models.items():
|
| 272 |
+
model_subdir = model_dir / model
|
| 273 |
+
model_subdir.mkdir(exist_ok=True)
|
| 274 |
+
with open(model_subdir / f"modeling_{model}.py", "w", encoding="utf-8", newline="\n") as f:
|
| 275 |
+
f.write(code)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
@contextmanager
|
| 279 |
+
def patch_transformer_repo_path(new_folder):
|
| 280 |
+
"""
|
| 281 |
+
Temporarily patches the variables defines in `check_copies` to use a different location for the repo.
|
| 282 |
+
"""
|
| 283 |
+
old_repo_path = check_copies.REPO_PATH
|
| 284 |
+
old_doc_path = check_copies.PATH_TO_DOCS
|
| 285 |
+
old_transformer_path = check_copies.TRANSFORMERS_PATH
|
| 286 |
+
repo_path = Path(new_folder).resolve()
|
| 287 |
+
check_copies.REPO_PATH = str(repo_path)
|
| 288 |
+
check_copies.PATH_TO_DOCS = str(repo_path / "docs" / "source" / "en")
|
| 289 |
+
check_copies.TRANSFORMERS_PATH = str(repo_path / "src" / "transformers")
|
| 290 |
+
try:
|
| 291 |
+
yield
|
| 292 |
+
finally:
|
| 293 |
+
check_copies.REPO_PATH = old_repo_path
|
| 294 |
+
check_copies.PATH_TO_DOCS = old_doc_path
|
| 295 |
+
check_copies.TRANSFORMERS_PATH = old_transformer_path
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class CopyCheckTester(unittest.TestCase):
|
| 299 |
+
def test_find_code_in_transformers(self):
|
| 300 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 301 |
+
create_tmp_repo(tmp_folder)
|
| 302 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 303 |
+
code = find_code_in_transformers("models.bert.modeling_bert.BertAttention")
|
| 304 |
+
|
| 305 |
+
reference_code = (
|
| 306 |
+
"class BertAttention(nn.Module):\n def __init__(self, config):\n super().__init__()\n"
|
| 307 |
+
)
|
| 308 |
+
self.assertEqual(code, reference_code)
|
| 309 |
+
|
| 310 |
+
def test_is_copy_consistent(self):
|
| 311 |
+
path_to_check = ["src", "transformers", "models", "bertcopy", "modeling_bertcopy.py"]
|
| 312 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 313 |
+
# Base check
|
| 314 |
+
create_tmp_repo(tmp_folder)
|
| 315 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 316 |
+
file_to_check = os.path.join(tmp_folder, *path_to_check)
|
| 317 |
+
diffs = is_copy_consistent(file_to_check)
|
| 318 |
+
self.assertEqual(diffs, [])
|
| 319 |
+
|
| 320 |
+
# Base check with an inconsistency
|
| 321 |
+
create_tmp_repo(tmp_folder)
|
| 322 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 323 |
+
file_to_check = os.path.join(tmp_folder, *path_to_check)
|
| 324 |
+
|
| 325 |
+
replace_in_file(file_to_check, "self.bertcopy(x)", "self.bert(x)")
|
| 326 |
+
diffs = is_copy_consistent(file_to_check)
|
| 327 |
+
self.assertEqual(diffs, [["models.bert.modeling_bert.BertModel", 22]])
|
| 328 |
+
|
| 329 |
+
_ = is_copy_consistent(file_to_check, overwrite=True)
|
| 330 |
+
|
| 331 |
+
with open(file_to_check, encoding="utf-8") as f:
|
| 332 |
+
self.assertEqual(f.read(), MOCK_BERT_COPY_CODE)
|
| 333 |
+
|
| 334 |
+
def test_is_copy_consistent_with_ignored_match(self):
|
| 335 |
+
path_to_check = ["src", "transformers", "models", "dummy_roberta_match", "modeling_dummy_roberta_match.py"]
|
| 336 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 337 |
+
# Base check
|
| 338 |
+
create_tmp_repo(tmp_folder)
|
| 339 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 340 |
+
file_to_check = os.path.join(tmp_folder, *path_to_check)
|
| 341 |
+
diffs = is_copy_consistent(file_to_check)
|
| 342 |
+
self.assertEqual(diffs, [])
|
| 343 |
+
|
| 344 |
+
def test_is_copy_consistent_with_ignored_no_match(self):
|
| 345 |
+
path_to_check = [
|
| 346 |
+
"src",
|
| 347 |
+
"transformers",
|
| 348 |
+
"models",
|
| 349 |
+
"dummy_roberta_no_match",
|
| 350 |
+
"modeling_dummy_roberta_no_match.py",
|
| 351 |
+
]
|
| 352 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 353 |
+
# Base check with an inconsistency
|
| 354 |
+
create_tmp_repo(tmp_folder)
|
| 355 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 356 |
+
file_to_check = os.path.join(tmp_folder, *path_to_check)
|
| 357 |
+
|
| 358 |
+
diffs = is_copy_consistent(file_to_check)
|
| 359 |
+
# line 6: `attr_2 = 3` in `MOCK_DUMMY_ROBERTA_CODE_NO_MATCH`.
|
| 360 |
+
# (which has a leading `\n`.)
|
| 361 |
+
self.assertEqual(
|
| 362 |
+
diffs, [["models.dummy_bert_no_match.modeling_dummy_bert_no_match.BertDummyModel", 6]]
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
_ = is_copy_consistent(file_to_check, overwrite=True)
|
| 366 |
+
|
| 367 |
+
with open(file_to_check, encoding="utf-8") as f:
|
| 368 |
+
self.assertEqual(f.read(), EXPECTED_REPLACED_CODE)
|
| 369 |
+
|
| 370 |
+
def test_convert_to_localized_md(self):
|
| 371 |
+
localized_readme = check_copies.LOCALIZED_READMES["README_zh-hans.md"]
|
| 372 |
+
|
| 373 |
+
md_list = (
|
| 374 |
+
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"
|
| 375 |
+
" Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"
|
| 376 |
+
" Self-supervised Learning of Language Representations](https://huggingface.co/papers/1909.11942), by Zhenzhong"
|
| 377 |
+
" Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1."
|
| 378 |
+
" **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),"
|
| 379 |
+
" released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"
|
| 380 |
+
" lighter](https://huggingface.co/papers/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same"
|
| 381 |
+
" method has been applied to compress GPT2 into"
|
| 382 |
+
" [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"
|
| 383 |
+
" [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"
|
| 384 |
+
" Multilingual BERT into"
|
| 385 |
+
" [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"
|
| 386 |
+
" version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**"
|
| 387 |
+
" (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders"
|
| 388 |
+
" as discriminators rather than generators](https://huggingface.co/papers/2003.10555) by Kevin Clark, Minh-Thang"
|
| 389 |
+
" Luong, Quoc V. Le, Christopher D. Manning."
|
| 390 |
+
)
|
| 391 |
+
localized_md_list = (
|
| 392 |
+
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
|
| 393 |
+
" Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
|
| 394 |
+
" Language Representations](https://huggingface.co/papers/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
|
| 395 |
+
" Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
|
| 396 |
+
)
|
| 397 |
+
converted_md_list_sample = (
|
| 398 |
+
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
|
| 399 |
+
" Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
|
| 400 |
+
" Language Representations](https://huggingface.co/papers/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
|
| 401 |
+
" Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1."
|
| 402 |
+
" **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文"
|
| 403 |
+
" [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"
|
| 404 |
+
" lighter](https://huggingface.co/papers/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same"
|
| 405 |
+
" method has been applied to compress GPT2 into"
|
| 406 |
+
" [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"
|
| 407 |
+
" [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"
|
| 408 |
+
" Multilingual BERT into"
|
| 409 |
+
" [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"
|
| 410 |
+
" version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自"
|
| 411 |
+
" Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather"
|
| 412 |
+
" than generators](https://huggingface.co/papers/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,"
|
| 413 |
+
" Christopher D. Manning 发布。\n"
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
num_models_equal, converted_md_list = convert_to_localized_md(
|
| 417 |
+
md_list, localized_md_list, localized_readme["format_model_list"]
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
self.assertFalse(num_models_equal)
|
| 421 |
+
self.assertEqual(converted_md_list, converted_md_list_sample)
|
| 422 |
+
|
| 423 |
+
num_models_equal, converted_md_list = convert_to_localized_md(
|
| 424 |
+
md_list, converted_md_list, localized_readme["format_model_list"]
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
# Check whether the number of models is equal to README.md after conversion.
|
| 428 |
+
self.assertTrue(num_models_equal)
|
| 429 |
+
|
| 430 |
+
link_changed_md_list = (
|
| 431 |
+
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"
|
| 432 |
+
" Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"
|
| 433 |
+
" Self-supervised Learning of Language Representations](https://huggingface.co/papers/1909.11942), by Zhenzhong"
|
| 434 |
+
" Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut."
|
| 435 |
+
)
|
| 436 |
+
link_unchanged_md_list = (
|
| 437 |
+
"1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and"
|
| 438 |
+
" the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
|
| 439 |
+
" Language Representations](https://huggingface.co/papers/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
|
| 440 |
+
" Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
|
| 441 |
+
)
|
| 442 |
+
converted_md_list_sample = (
|
| 443 |
+
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
|
| 444 |
+
" Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
|
| 445 |
+
" Language Representations](https://huggingface.co/papers/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
|
| 446 |
+
" Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
num_models_equal, converted_md_list = convert_to_localized_md(
|
| 450 |
+
link_changed_md_list, link_unchanged_md_list, localized_readme["format_model_list"]
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
# Check if the model link is synchronized.
|
| 454 |
+
self.assertEqual(converted_md_list, converted_md_list_sample)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_check_docstrings.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
|
| 22 |
+
sys.path.append(os.path.join(git_repo_path, "utils"))
|
| 23 |
+
|
| 24 |
+
from check_docstrings import get_default_description, replace_default_in_arg_description # noqa: E402
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class CheckDostringsTested(unittest.TestCase):
|
| 28 |
+
def test_replace_default_in_arg_description(self):
|
| 29 |
+
# Standard docstring with default.
|
| 30 |
+
desc_with_default = "`float`, *optional*, defaults to 2.0"
|
| 31 |
+
self.assertEqual(
|
| 32 |
+
replace_default_in_arg_description(desc_with_default, 2.0), "`float`, *optional*, defaults to 2.0"
|
| 33 |
+
)
|
| 34 |
+
self.assertEqual(
|
| 35 |
+
replace_default_in_arg_description(desc_with_default, 1.0), "`float`, *optional*, defaults to 1.0"
|
| 36 |
+
)
|
| 37 |
+
self.assertEqual(replace_default_in_arg_description(desc_with_default, inspect._empty), "`float`")
|
| 38 |
+
|
| 39 |
+
# Standard docstring with default but optional is not using the stars.
|
| 40 |
+
desc_with_default_typo = "`float`, `optional`, defaults to 2.0"
|
| 41 |
+
self.assertEqual(
|
| 42 |
+
replace_default_in_arg_description(desc_with_default_typo, 2.0), "`float`, *optional*, defaults to 2.0"
|
| 43 |
+
)
|
| 44 |
+
self.assertEqual(
|
| 45 |
+
replace_default_in_arg_description(desc_with_default_typo, 1.0), "`float`, *optional*, defaults to 1.0"
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# If the default is None we do not erase the value in the docstring.
|
| 49 |
+
self.assertEqual(
|
| 50 |
+
replace_default_in_arg_description(desc_with_default, None), "`float`, *optional*, defaults to 2.0"
|
| 51 |
+
)
|
| 52 |
+
# If the default is None (and set as such in the docstring), we do not include it.
|
| 53 |
+
desc_with_default = "`float`, *optional*, defaults to None"
|
| 54 |
+
self.assertEqual(replace_default_in_arg_description(desc_with_default, None), "`float`, *optional*")
|
| 55 |
+
desc_with_default = "`float`, *optional*, defaults to `None`"
|
| 56 |
+
self.assertEqual(replace_default_in_arg_description(desc_with_default, None), "`float`, *optional*")
|
| 57 |
+
|
| 58 |
+
# Operations are not replaced, but put in backtiks.
|
| 59 |
+
desc_with_default = "`float`, *optional*, defaults to 1/255"
|
| 60 |
+
self.assertEqual(
|
| 61 |
+
replace_default_in_arg_description(desc_with_default, 1 / 255), "`float`, *optional*, defaults to `1/255`"
|
| 62 |
+
)
|
| 63 |
+
desc_with_default = "`float`, *optional*, defaults to `1/255`"
|
| 64 |
+
self.assertEqual(
|
| 65 |
+
replace_default_in_arg_description(desc_with_default, 1 / 255), "`float`, *optional*, defaults to `1/255`"
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
desc_with_optional = "`float`, *optional*"
|
| 69 |
+
self.assertEqual(
|
| 70 |
+
replace_default_in_arg_description(desc_with_optional, 2.0), "`float`, *optional*, defaults to 2.0"
|
| 71 |
+
)
|
| 72 |
+
self.assertEqual(
|
| 73 |
+
replace_default_in_arg_description(desc_with_optional, 1.0), "`float`, *optional*, defaults to 1.0"
|
| 74 |
+
)
|
| 75 |
+
self.assertEqual(replace_default_in_arg_description(desc_with_optional, None), "`float`, *optional*")
|
| 76 |
+
self.assertEqual(replace_default_in_arg_description(desc_with_optional, inspect._empty), "`float`")
|
| 77 |
+
|
| 78 |
+
desc_with_no_optional = "`float`"
|
| 79 |
+
self.assertEqual(
|
| 80 |
+
replace_default_in_arg_description(desc_with_no_optional, 2.0), "`float`, *optional*, defaults to 2.0"
|
| 81 |
+
)
|
| 82 |
+
self.assertEqual(
|
| 83 |
+
replace_default_in_arg_description(desc_with_no_optional, 1.0), "`float`, *optional*, defaults to 1.0"
|
| 84 |
+
)
|
| 85 |
+
self.assertEqual(replace_default_in_arg_description(desc_with_no_optional, None), "`float`, *optional*")
|
| 86 |
+
self.assertEqual(replace_default_in_arg_description(desc_with_no_optional, inspect._empty), "`float`")
|
| 87 |
+
|
| 88 |
+
def test_get_default_description(self):
|
| 89 |
+
# Fake function to have arguments to test.
|
| 90 |
+
def _fake_function(a, b: int, c=1, d: float = 2.0, e: str = "blob"):
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
params = inspect.signature(_fake_function).parameters
|
| 94 |
+
assert get_default_description(params["a"]) == "`<fill_type>`"
|
| 95 |
+
assert get_default_description(params["b"]) == "`int`"
|
| 96 |
+
assert get_default_description(params["c"]) == "`<fill_type>`, *optional*, defaults to 1"
|
| 97 |
+
assert get_default_description(params["d"]) == "`float`, *optional*, defaults to 2.0"
|
| 98 |
+
assert get_default_description(params["e"]) == '`str`, *optional*, defaults to `"blob"`'
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_get_test_info.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
|
| 21 |
+
sys.path.append(os.path.join(git_repo_path, "utils"))
|
| 22 |
+
|
| 23 |
+
import get_test_info # noqa: E402
|
| 24 |
+
from get_test_info import ( # noqa: E402
|
| 25 |
+
get_model_to_test_mapping,
|
| 26 |
+
get_model_to_tester_mapping,
|
| 27 |
+
get_test_to_tester_mapping,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
BERT_TEST_FILE = os.path.join("tests", "models", "bert", "test_modeling_bert.py")
|
| 32 |
+
BLIP_TEST_FILE = os.path.join("tests", "models", "blip", "test_modeling_blip.py")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class GetTestInfoTester(unittest.TestCase):
|
| 36 |
+
def test_get_test_to_tester_mapping(self):
|
| 37 |
+
bert_test_tester_mapping = get_test_to_tester_mapping(BERT_TEST_FILE)
|
| 38 |
+
blip_test_tester_mapping = get_test_to_tester_mapping(BLIP_TEST_FILE)
|
| 39 |
+
|
| 40 |
+
EXPECTED_BERT_MAPPING = {"BertModelTest": "BertModelTester"}
|
| 41 |
+
|
| 42 |
+
EXPECTED_BLIP_MAPPING = {
|
| 43 |
+
"BlipModelTest": "BlipModelTester",
|
| 44 |
+
"BlipTextImageModelTest": "BlipTextImageModelsModelTester",
|
| 45 |
+
"BlipTextModelTest": "BlipTextModelTester",
|
| 46 |
+
"BlipTextRetrievalModelTest": "BlipTextRetrievalModelTester",
|
| 47 |
+
"BlipVQAModelTest": "BlipVQAModelTester",
|
| 48 |
+
"BlipVisionModelTest": "BlipVisionModelTester",
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
self.assertEqual(get_test_info.to_json(bert_test_tester_mapping), EXPECTED_BERT_MAPPING)
|
| 52 |
+
self.assertEqual(get_test_info.to_json(blip_test_tester_mapping), EXPECTED_BLIP_MAPPING)
|
| 53 |
+
|
| 54 |
+
def test_get_model_to_test_mapping(self):
|
| 55 |
+
bert_model_test_mapping = get_model_to_test_mapping(BERT_TEST_FILE)
|
| 56 |
+
blip_model_test_mapping = get_model_to_test_mapping(BLIP_TEST_FILE)
|
| 57 |
+
|
| 58 |
+
EXPECTED_BERT_MAPPING = {
|
| 59 |
+
"BertForMaskedLM": ["BertModelTest"],
|
| 60 |
+
"BertForMultipleChoice": ["BertModelTest"],
|
| 61 |
+
"BertForNextSentencePrediction": ["BertModelTest"],
|
| 62 |
+
"BertForPreTraining": ["BertModelTest"],
|
| 63 |
+
"BertForQuestionAnswering": ["BertModelTest"],
|
| 64 |
+
"BertForSequenceClassification": ["BertModelTest"],
|
| 65 |
+
"BertForTokenClassification": ["BertModelTest"],
|
| 66 |
+
"BertLMHeadModel": ["BertModelTest"],
|
| 67 |
+
"BertModel": ["BertModelTest"],
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
EXPECTED_BLIP_MAPPING = {
|
| 71 |
+
"BlipForConditionalGeneration": ["BlipTextImageModelTest"],
|
| 72 |
+
"BlipForImageTextRetrieval": ["BlipTextRetrievalModelTest"],
|
| 73 |
+
"BlipForQuestionAnswering": ["BlipVQAModelTest"],
|
| 74 |
+
"BlipModel": ["BlipModelTest"],
|
| 75 |
+
"BlipTextModel": ["BlipTextModelTest"],
|
| 76 |
+
"BlipVisionModel": ["BlipVisionModelTest"],
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
self.assertEqual(get_test_info.to_json(bert_model_test_mapping), EXPECTED_BERT_MAPPING)
|
| 80 |
+
self.assertEqual(get_test_info.to_json(blip_model_test_mapping), EXPECTED_BLIP_MAPPING)
|
| 81 |
+
|
| 82 |
+
def test_get_model_to_tester_mapping(self):
|
| 83 |
+
bert_model_tester_mapping = get_model_to_tester_mapping(BERT_TEST_FILE)
|
| 84 |
+
blip_model_tester_mapping = get_model_to_tester_mapping(BLIP_TEST_FILE)
|
| 85 |
+
|
| 86 |
+
EXPECTED_BERT_MAPPING = {
|
| 87 |
+
"BertForMaskedLM": ["BertModelTester"],
|
| 88 |
+
"BertForMultipleChoice": ["BertModelTester"],
|
| 89 |
+
"BertForNextSentencePrediction": ["BertModelTester"],
|
| 90 |
+
"BertForPreTraining": ["BertModelTester"],
|
| 91 |
+
"BertForQuestionAnswering": ["BertModelTester"],
|
| 92 |
+
"BertForSequenceClassification": ["BertModelTester"],
|
| 93 |
+
"BertForTokenClassification": ["BertModelTester"],
|
| 94 |
+
"BertLMHeadModel": ["BertModelTester"],
|
| 95 |
+
"BertModel": ["BertModelTester"],
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
EXPECTED_BLIP_MAPPING = {
|
| 99 |
+
"BlipForConditionalGeneration": ["BlipTextImageModelsModelTester"],
|
| 100 |
+
"BlipForImageTextRetrieval": ["BlipTextRetrievalModelTester"],
|
| 101 |
+
"BlipForQuestionAnswering": ["BlipVQAModelTester"],
|
| 102 |
+
"BlipModel": ["BlipModelTester"],
|
| 103 |
+
"BlipTextModel": ["BlipTextModelTester"],
|
| 104 |
+
"BlipVisionModel": ["BlipVisionModelTester"],
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
self.assertEqual(get_test_info.to_json(bert_model_tester_mapping), EXPECTED_BERT_MAPPING)
|
| 108 |
+
self.assertEqual(get_test_info.to_json(blip_model_tester_mapping), EXPECTED_BLIP_MAPPING)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_tests_fetcher.py
ADDED
|
@@ -0,0 +1,788 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import shutil
|
| 17 |
+
import sys
|
| 18 |
+
import tempfile
|
| 19 |
+
import unittest
|
| 20 |
+
from contextlib import contextmanager
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
from git import Repo
|
| 24 |
+
|
| 25 |
+
from transformers.testing_utils import CaptureStdout
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
REPO_PATH = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
|
| 29 |
+
sys.path.append(os.path.join(REPO_PATH, "utils"))
|
| 30 |
+
|
| 31 |
+
import tests_fetcher # noqa: E402
|
| 32 |
+
from tests_fetcher import ( # noqa: E402
|
| 33 |
+
checkout_commit,
|
| 34 |
+
clean_code,
|
| 35 |
+
create_reverse_dependency_map,
|
| 36 |
+
create_reverse_dependency_tree,
|
| 37 |
+
diff_is_docstring_only,
|
| 38 |
+
extract_imports,
|
| 39 |
+
get_all_tests,
|
| 40 |
+
get_diff,
|
| 41 |
+
get_module_dependencies,
|
| 42 |
+
get_tree_starting_at,
|
| 43 |
+
infer_tests_to_run,
|
| 44 |
+
init_test_examples_dependencies,
|
| 45 |
+
parse_commit_message,
|
| 46 |
+
print_tree_deps_of,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
BERT_MODELING_FILE = "src/transformers/models/bert/modeling_bert.py"
|
| 51 |
+
BERT_MODEL_FILE = """from ...modeling_utils import PreTrainedModel
|
| 52 |
+
from ...utils import is_torch_available
|
| 53 |
+
from .configuration_bert import BertConfig
|
| 54 |
+
|
| 55 |
+
class BertModel:
|
| 56 |
+
'''
|
| 57 |
+
This is the docstring.
|
| 58 |
+
'''
|
| 59 |
+
This is the code
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
BERT_MODEL_FILE_NEW_DOCSTRING = """from ...modeling_utils import PreTrainedModel
|
| 63 |
+
from ...utils import is_torch_available
|
| 64 |
+
from .configuration_bert import BertConfig
|
| 65 |
+
|
| 66 |
+
class BertModel:
|
| 67 |
+
'''
|
| 68 |
+
This is the docstring. It has been updated.
|
| 69 |
+
'''
|
| 70 |
+
This is the code
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
BERT_MODEL_FILE_NEW_CODE = """from ...modeling_utils import PreTrainedModel
|
| 74 |
+
from ...utils import is_torch_available
|
| 75 |
+
from .configuration_bert import BertConfig
|
| 76 |
+
|
| 77 |
+
class BertModel:
|
| 78 |
+
'''
|
| 79 |
+
This is the docstring.
|
| 80 |
+
'''
|
| 81 |
+
This is the code. It has been updated
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def create_tmp_repo(tmp_dir, models=None):
|
| 86 |
+
"""
|
| 87 |
+
Creates a repository in a temporary directory mimicking the structure of Transformers. Uses the list of models
|
| 88 |
+
provided (which defaults to just `["bert"]`).
|
| 89 |
+
"""
|
| 90 |
+
tmp_dir = Path(tmp_dir)
|
| 91 |
+
if tmp_dir.exists():
|
| 92 |
+
shutil.rmtree(tmp_dir)
|
| 93 |
+
tmp_dir.mkdir(exist_ok=True)
|
| 94 |
+
repo = Repo.init(tmp_dir)
|
| 95 |
+
|
| 96 |
+
if models is None:
|
| 97 |
+
models = ["bert"]
|
| 98 |
+
class_names = [model[0].upper() + model[1:] for model in models]
|
| 99 |
+
|
| 100 |
+
transformers_dir = tmp_dir / "src" / "transformers"
|
| 101 |
+
transformers_dir.mkdir(parents=True, exist_ok=True)
|
| 102 |
+
with open(transformers_dir / "__init__.py", "w") as f:
|
| 103 |
+
init_lines = ["from .utils import cached_file, is_torch_available"]
|
| 104 |
+
init_lines.extend(
|
| 105 |
+
[f"from .models.{model} import {cls}Config, {cls}Model" for model, cls in zip(models, class_names)]
|
| 106 |
+
)
|
| 107 |
+
f.write("\n".join(init_lines) + "\n")
|
| 108 |
+
with open(transformers_dir / "configuration_utils.py", "w") as f:
|
| 109 |
+
f.write("from .utils import cached_file\n\ncode")
|
| 110 |
+
with open(transformers_dir / "modeling_utils.py", "w") as f:
|
| 111 |
+
f.write("from .utils import cached_file\n\ncode")
|
| 112 |
+
|
| 113 |
+
utils_dir = tmp_dir / "src" / "transformers" / "utils"
|
| 114 |
+
utils_dir.mkdir(exist_ok=True)
|
| 115 |
+
with open(utils_dir / "__init__.py", "w") as f:
|
| 116 |
+
f.write("from .hub import cached_file\nfrom .imports import is_torch_available\n")
|
| 117 |
+
with open(utils_dir / "hub.py", "w") as f:
|
| 118 |
+
f.write("import huggingface_hub\n\ncode")
|
| 119 |
+
with open(utils_dir / "imports.py", "w") as f:
|
| 120 |
+
f.write("code")
|
| 121 |
+
|
| 122 |
+
model_dir = tmp_dir / "src" / "transformers" / "models"
|
| 123 |
+
model_dir.mkdir(parents=True, exist_ok=True)
|
| 124 |
+
with open(model_dir / "__init__.py", "w") as f:
|
| 125 |
+
f.write("\n".join([f"import {model}" for model in models]))
|
| 126 |
+
|
| 127 |
+
for model, cls in zip(models, class_names):
|
| 128 |
+
model_dir = tmp_dir / "src" / "transformers" / "models" / model
|
| 129 |
+
model_dir.mkdir(parents=True, exist_ok=True)
|
| 130 |
+
with open(model_dir / "__init__.py", "w") as f:
|
| 131 |
+
f.write(f"from .configuration_{model} import {cls}Config\nfrom .modeling_{model} import {cls}Model\n")
|
| 132 |
+
with open(model_dir / f"configuration_{model}.py", "w") as f:
|
| 133 |
+
f.write("from ...configuration_utils import PretrainedConfig\ncode")
|
| 134 |
+
with open(model_dir / f"modeling_{model}.py", "w") as f:
|
| 135 |
+
modeling_code = BERT_MODEL_FILE.replace("bert", model).replace("Bert", cls)
|
| 136 |
+
f.write(modeling_code)
|
| 137 |
+
|
| 138 |
+
test_dir = tmp_dir / "tests"
|
| 139 |
+
test_dir.mkdir(exist_ok=True)
|
| 140 |
+
with open(test_dir / "test_modeling_common.py", "w") as f:
|
| 141 |
+
f.write("from transformers.modeling_utils import PreTrainedModel\ncode")
|
| 142 |
+
|
| 143 |
+
for model, cls in zip(models, class_names):
|
| 144 |
+
test_model_dir = test_dir / "models" / model
|
| 145 |
+
test_model_dir.mkdir(parents=True, exist_ok=True)
|
| 146 |
+
(test_model_dir / "__init__.py").touch()
|
| 147 |
+
with open(test_model_dir / f"test_modeling_{model}.py", "w") as f:
|
| 148 |
+
f.write(
|
| 149 |
+
f"from transformers import {cls}Config, {cls}Model\nfrom ...test_modeling_common import ModelTesterMixin\n\ncode"
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
example_dir = tmp_dir / "examples"
|
| 153 |
+
example_dir.mkdir(exist_ok=True)
|
| 154 |
+
for framework in ["flax", "pytorch", "tensorflow"]:
|
| 155 |
+
framework_dir = example_dir / framework
|
| 156 |
+
framework_dir.mkdir(exist_ok=True)
|
| 157 |
+
with open(framework_dir / f"test_{framework}_examples.py", "w") as f:
|
| 158 |
+
f.write("""test_args = "run_glue.py"\n""")
|
| 159 |
+
glue_dir = framework_dir / "text-classification"
|
| 160 |
+
glue_dir.mkdir(exist_ok=True)
|
| 161 |
+
with open(glue_dir / "run_glue.py", "w") as f:
|
| 162 |
+
f.write("from transformers import BertModel\n\ncode")
|
| 163 |
+
|
| 164 |
+
repo.index.add(["examples", "src", "tests"])
|
| 165 |
+
repo.index.commit("Initial commit")
|
| 166 |
+
repo.create_head("main")
|
| 167 |
+
repo.head.reference = repo.refs.main
|
| 168 |
+
repo.delete_head("master")
|
| 169 |
+
return repo
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@contextmanager
|
| 173 |
+
def patch_transformer_repo_path(new_folder):
|
| 174 |
+
"""
|
| 175 |
+
Temporarily patches the variables defines in `tests_fetcher` to use a different location for the repo.
|
| 176 |
+
"""
|
| 177 |
+
old_repo_path = tests_fetcher.PATH_TO_REPO
|
| 178 |
+
tests_fetcher.PATH_TO_REPO = Path(new_folder).resolve()
|
| 179 |
+
tests_fetcher.PATH_TO_EXAMPLES = tests_fetcher.PATH_TO_REPO / "examples"
|
| 180 |
+
tests_fetcher.PATH_TO_TRANFORMERS = tests_fetcher.PATH_TO_REPO / "src/transformers"
|
| 181 |
+
tests_fetcher.PATH_TO_TESTS = tests_fetcher.PATH_TO_REPO / "tests"
|
| 182 |
+
try:
|
| 183 |
+
yield
|
| 184 |
+
finally:
|
| 185 |
+
tests_fetcher.PATH_TO_REPO = old_repo_path
|
| 186 |
+
tests_fetcher.PATH_TO_EXAMPLES = tests_fetcher.PATH_TO_REPO / "examples"
|
| 187 |
+
tests_fetcher.PATH_TO_TRANFORMERS = tests_fetcher.PATH_TO_REPO / "src/transformers"
|
| 188 |
+
tests_fetcher.PATH_TO_TESTS = tests_fetcher.PATH_TO_REPO / "tests"
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def commit_changes(filenames, contents, repo, commit_message="Commit"):
|
| 192 |
+
"""
|
| 193 |
+
Commit new `contents` to `filenames` inside a given `repo`.
|
| 194 |
+
"""
|
| 195 |
+
if not isinstance(filenames, list):
|
| 196 |
+
filenames = [filenames]
|
| 197 |
+
if not isinstance(contents, list):
|
| 198 |
+
contents = [contents]
|
| 199 |
+
|
| 200 |
+
folder = Path(repo.working_dir)
|
| 201 |
+
for filename, content in zip(filenames, contents):
|
| 202 |
+
with open(folder / filename, "w") as f:
|
| 203 |
+
f.write(content)
|
| 204 |
+
repo.index.add(filenames)
|
| 205 |
+
commit = repo.index.commit(commit_message)
|
| 206 |
+
return commit.hexsha
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class TestFetcherTester(unittest.TestCase):
|
| 210 |
+
def test_checkout_commit(self):
|
| 211 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 212 |
+
tmp_folder = Path(tmp_folder)
|
| 213 |
+
repo = create_tmp_repo(tmp_folder)
|
| 214 |
+
initial_sha = repo.head.commit.hexsha
|
| 215 |
+
new_sha = commit_changes(BERT_MODELING_FILE, BERT_MODEL_FILE_NEW_DOCSTRING, repo)
|
| 216 |
+
|
| 217 |
+
assert repo.head.commit.hexsha == new_sha
|
| 218 |
+
with checkout_commit(repo, initial_sha):
|
| 219 |
+
assert repo.head.commit.hexsha == initial_sha
|
| 220 |
+
with open(tmp_folder / BERT_MODELING_FILE) as f:
|
| 221 |
+
assert f.read() == BERT_MODEL_FILE
|
| 222 |
+
|
| 223 |
+
assert repo.head.commit.hexsha == new_sha
|
| 224 |
+
with open(tmp_folder / BERT_MODELING_FILE) as f:
|
| 225 |
+
assert f.read() == BERT_MODEL_FILE_NEW_DOCSTRING
|
| 226 |
+
|
| 227 |
+
def test_clean_code(self):
|
| 228 |
+
# Clean code removes all strings in triple quotes
|
| 229 |
+
assert clean_code('"""\nDocstring\n"""\ncode\n"""Long string"""\ncode\n') == "code\ncode"
|
| 230 |
+
assert clean_code("'''\nDocstring\n'''\ncode\n'''Long string'''\ncode\n'''") == "code\ncode"
|
| 231 |
+
|
| 232 |
+
# Clean code removes all comments
|
| 233 |
+
assert clean_code("code\n# Comment\ncode") == "code\ncode"
|
| 234 |
+
assert clean_code("code # inline comment\ncode") == "code \ncode"
|
| 235 |
+
|
| 236 |
+
def test_get_all_tests(self):
|
| 237 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 238 |
+
tmp_folder = Path(tmp_folder)
|
| 239 |
+
create_tmp_repo(tmp_folder)
|
| 240 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 241 |
+
assert get_all_tests() == ["tests/models/bert", "tests/test_modeling_common.py"]
|
| 242 |
+
|
| 243 |
+
def test_get_all_tests_on_full_repo(self):
|
| 244 |
+
all_tests = get_all_tests()
|
| 245 |
+
assert "tests/models/albert" in all_tests
|
| 246 |
+
assert "tests/models/bert" in all_tests
|
| 247 |
+
assert "tests/repo_utils" in all_tests
|
| 248 |
+
assert "tests/test_pipeline_mixin.py" in all_tests
|
| 249 |
+
assert "tests/models" not in all_tests
|
| 250 |
+
assert "tests/__pycache__" not in all_tests
|
| 251 |
+
assert "tests/models/albert/test_modeling_albert.py" not in all_tests
|
| 252 |
+
assert "tests/repo_utils/test_tests_fetcher.py" not in all_tests
|
| 253 |
+
|
| 254 |
+
def test_diff_is_docstring_only(self):
|
| 255 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 256 |
+
tmp_folder = Path(tmp_folder)
|
| 257 |
+
repo = create_tmp_repo(tmp_folder)
|
| 258 |
+
|
| 259 |
+
branching_point = repo.refs.main.commit
|
| 260 |
+
bert_file = BERT_MODELING_FILE
|
| 261 |
+
commit_changes(bert_file, BERT_MODEL_FILE_NEW_DOCSTRING, repo)
|
| 262 |
+
assert diff_is_docstring_only(repo, branching_point, bert_file)
|
| 263 |
+
|
| 264 |
+
commit_changes(bert_file, BERT_MODEL_FILE_NEW_CODE, repo)
|
| 265 |
+
assert not diff_is_docstring_only(repo, branching_point, bert_file)
|
| 266 |
+
|
| 267 |
+
def test_get_diff(self):
|
| 268 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 269 |
+
tmp_folder = Path(tmp_folder)
|
| 270 |
+
repo = create_tmp_repo(tmp_folder)
|
| 271 |
+
|
| 272 |
+
initial_commit = repo.refs.main.commit
|
| 273 |
+
bert_file = BERT_MODELING_FILE
|
| 274 |
+
commit_changes(bert_file, BERT_MODEL_FILE_NEW_DOCSTRING, repo)
|
| 275 |
+
assert get_diff(repo, repo.head.commit, repo.head.commit.parents) == []
|
| 276 |
+
|
| 277 |
+
commit_changes(bert_file, BERT_MODEL_FILE_NEW_DOCSTRING + "\n# Adding a comment\n", repo)
|
| 278 |
+
assert get_diff(repo, repo.head.commit, repo.head.commit.parents) == []
|
| 279 |
+
|
| 280 |
+
commit_changes(bert_file, BERT_MODEL_FILE_NEW_CODE, repo)
|
| 281 |
+
assert get_diff(repo, repo.head.commit, repo.head.commit.parents) == [
|
| 282 |
+
"src/transformers/models/bert/modeling_bert.py"
|
| 283 |
+
]
|
| 284 |
+
|
| 285 |
+
commit_changes("src/transformers/utils/hub.py", "import huggingface_hub\n\nnew code", repo)
|
| 286 |
+
assert get_diff(repo, repo.head.commit, repo.head.commit.parents) == ["src/transformers/utils/hub.py"]
|
| 287 |
+
assert get_diff(repo, repo.head.commit, [initial_commit]) == [
|
| 288 |
+
"src/transformers/models/bert/modeling_bert.py",
|
| 289 |
+
"src/transformers/utils/hub.py",
|
| 290 |
+
]
|
| 291 |
+
|
| 292 |
+
def test_extract_imports_relative(self):
|
| 293 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 294 |
+
tmp_folder = Path(tmp_folder)
|
| 295 |
+
create_tmp_repo(tmp_folder)
|
| 296 |
+
|
| 297 |
+
expected_bert_imports = [
|
| 298 |
+
("src/transformers/modeling_utils.py", ["PreTrainedModel"]),
|
| 299 |
+
("src/transformers/utils/__init__.py", ["is_torch_available"]),
|
| 300 |
+
("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]),
|
| 301 |
+
]
|
| 302 |
+
expected_utils_imports = [
|
| 303 |
+
("src/transformers/utils/hub.py", ["cached_file"]),
|
| 304 |
+
("src/transformers/utils/imports.py", ["is_torch_available"]),
|
| 305 |
+
]
|
| 306 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 307 |
+
assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports
|
| 308 |
+
assert extract_imports("src/transformers/utils/__init__.py") == expected_utils_imports
|
| 309 |
+
|
| 310 |
+
with open(tmp_folder / BERT_MODELING_FILE, "w") as f:
|
| 311 |
+
f.write(
|
| 312 |
+
"from ...utils import cached_file, is_torch_available\nfrom .configuration_bert import BertConfig\n"
|
| 313 |
+
)
|
| 314 |
+
expected_bert_imports = [
|
| 315 |
+
("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]),
|
| 316 |
+
("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]),
|
| 317 |
+
]
|
| 318 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 319 |
+
assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports
|
| 320 |
+
|
| 321 |
+
# Test with multi-line imports
|
| 322 |
+
with open(tmp_folder / BERT_MODELING_FILE, "w") as f:
|
| 323 |
+
f.write(
|
| 324 |
+
"from ...utils import (\n cached_file,\n is_torch_available\n)\nfrom .configuration_bert import BertConfig\n"
|
| 325 |
+
)
|
| 326 |
+
expected_bert_imports = [
|
| 327 |
+
("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]),
|
| 328 |
+
("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]),
|
| 329 |
+
]
|
| 330 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 331 |
+
assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports
|
| 332 |
+
|
| 333 |
+
def test_extract_imports_absolute(self):
|
| 334 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 335 |
+
tmp_folder = Path(tmp_folder)
|
| 336 |
+
create_tmp_repo(tmp_folder)
|
| 337 |
+
|
| 338 |
+
with open(tmp_folder / BERT_MODELING_FILE, "w") as f:
|
| 339 |
+
f.write(
|
| 340 |
+
"from transformers.utils import cached_file, is_torch_available\nfrom transformers.models.bert.configuration_bert import BertConfig\n"
|
| 341 |
+
)
|
| 342 |
+
expected_bert_imports = [
|
| 343 |
+
("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]),
|
| 344 |
+
("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]),
|
| 345 |
+
]
|
| 346 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 347 |
+
assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports
|
| 348 |
+
|
| 349 |
+
# Test with multi-line imports
|
| 350 |
+
with open(tmp_folder / BERT_MODELING_FILE, "w") as f:
|
| 351 |
+
f.write(
|
| 352 |
+
"from transformers.utils import (\n cached_file,\n is_torch_available\n)\nfrom transformers.models.bert.configuration_bert import BertConfig\n"
|
| 353 |
+
)
|
| 354 |
+
expected_bert_imports = [
|
| 355 |
+
("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]),
|
| 356 |
+
("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]),
|
| 357 |
+
]
|
| 358 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 359 |
+
assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports
|
| 360 |
+
|
| 361 |
+
# Test with base imports
|
| 362 |
+
with open(tmp_folder / BERT_MODELING_FILE, "w") as f:
|
| 363 |
+
f.write(
|
| 364 |
+
"from transformers.utils import (\n cached_file,\n is_torch_available\n)\nfrom transformers import BertConfig\n"
|
| 365 |
+
)
|
| 366 |
+
expected_bert_imports = [
|
| 367 |
+
("src/transformers/__init__.py", ["BertConfig"]),
|
| 368 |
+
("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]),
|
| 369 |
+
]
|
| 370 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 371 |
+
assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports
|
| 372 |
+
|
| 373 |
+
def test_get_module_dependencies(self):
|
| 374 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 375 |
+
tmp_folder = Path(tmp_folder)
|
| 376 |
+
create_tmp_repo(tmp_folder)
|
| 377 |
+
|
| 378 |
+
expected_bert_dependencies = [
|
| 379 |
+
"src/transformers/modeling_utils.py",
|
| 380 |
+
"src/transformers/models/bert/configuration_bert.py",
|
| 381 |
+
"src/transformers/utils/imports.py",
|
| 382 |
+
]
|
| 383 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 384 |
+
assert get_module_dependencies(BERT_MODELING_FILE) == expected_bert_dependencies
|
| 385 |
+
|
| 386 |
+
expected_test_bert_dependencies = [
|
| 387 |
+
"tests/test_modeling_common.py",
|
| 388 |
+
"src/transformers/models/bert/configuration_bert.py",
|
| 389 |
+
"src/transformers/models/bert/modeling_bert.py",
|
| 390 |
+
]
|
| 391 |
+
|
| 392 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 393 |
+
assert (
|
| 394 |
+
get_module_dependencies("tests/models/bert/test_modeling_bert.py")
|
| 395 |
+
== expected_test_bert_dependencies
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
# Test with a submodule
|
| 399 |
+
(tmp_folder / "src/transformers/utils/logging.py").touch()
|
| 400 |
+
with open(tmp_folder / BERT_MODELING_FILE, "a") as f:
|
| 401 |
+
f.write("from ...utils import logging\n")
|
| 402 |
+
|
| 403 |
+
expected_bert_dependencies = [
|
| 404 |
+
"src/transformers/modeling_utils.py",
|
| 405 |
+
"src/transformers/models/bert/configuration_bert.py",
|
| 406 |
+
"src/transformers/utils/logging.py",
|
| 407 |
+
"src/transformers/utils/imports.py",
|
| 408 |
+
]
|
| 409 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 410 |
+
assert get_module_dependencies(BERT_MODELING_FILE) == expected_bert_dependencies
|
| 411 |
+
|
| 412 |
+
# Test with an object non-imported in the init
|
| 413 |
+
create_tmp_repo(tmp_folder)
|
| 414 |
+
with open(tmp_folder / BERT_MODELING_FILE, "a") as f:
|
| 415 |
+
f.write("from ...utils import CONSTANT\n")
|
| 416 |
+
|
| 417 |
+
expected_bert_dependencies = [
|
| 418 |
+
"src/transformers/modeling_utils.py",
|
| 419 |
+
"src/transformers/models/bert/configuration_bert.py",
|
| 420 |
+
"src/transformers/utils/__init__.py",
|
| 421 |
+
"src/transformers/utils/imports.py",
|
| 422 |
+
]
|
| 423 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 424 |
+
assert get_module_dependencies(BERT_MODELING_FILE) == expected_bert_dependencies
|
| 425 |
+
|
| 426 |
+
# Test with an example
|
| 427 |
+
create_tmp_repo(tmp_folder)
|
| 428 |
+
|
| 429 |
+
expected_example_dependencies = ["src/transformers/models/bert/modeling_bert.py"]
|
| 430 |
+
|
| 431 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 432 |
+
assert (
|
| 433 |
+
get_module_dependencies("examples/pytorch/text-classification/run_glue.py")
|
| 434 |
+
== expected_example_dependencies
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
def test_create_reverse_dependency_tree(self):
|
| 438 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 439 |
+
tmp_folder = Path(tmp_folder)
|
| 440 |
+
create_tmp_repo(tmp_folder)
|
| 441 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 442 |
+
tree = create_reverse_dependency_tree()
|
| 443 |
+
|
| 444 |
+
init_edges = [
|
| 445 |
+
"src/transformers/utils/hub.py",
|
| 446 |
+
"src/transformers/utils/imports.py",
|
| 447 |
+
"src/transformers/models/bert/configuration_bert.py",
|
| 448 |
+
"src/transformers/models/bert/modeling_bert.py",
|
| 449 |
+
]
|
| 450 |
+
assert {f for f, g in tree if g == "src/transformers/__init__.py"} == set(init_edges)
|
| 451 |
+
|
| 452 |
+
bert_edges = [
|
| 453 |
+
"src/transformers/modeling_utils.py",
|
| 454 |
+
"src/transformers/utils/imports.py",
|
| 455 |
+
"src/transformers/models/bert/configuration_bert.py",
|
| 456 |
+
]
|
| 457 |
+
assert {f for f, g in tree if g == "src/transformers/models/bert/modeling_bert.py"} == set(bert_edges)
|
| 458 |
+
|
| 459 |
+
test_bert_edges = [
|
| 460 |
+
"tests/test_modeling_common.py",
|
| 461 |
+
"src/transformers/models/bert/configuration_bert.py",
|
| 462 |
+
"src/transformers/models/bert/modeling_bert.py",
|
| 463 |
+
]
|
| 464 |
+
assert {f for f, g in tree if g == "tests/models/bert/test_modeling_bert.py"} == set(test_bert_edges)
|
| 465 |
+
|
| 466 |
+
def test_get_tree_starting_at(self):
|
| 467 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 468 |
+
tmp_folder = Path(tmp_folder)
|
| 469 |
+
create_tmp_repo(tmp_folder)
|
| 470 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 471 |
+
edges = create_reverse_dependency_tree()
|
| 472 |
+
|
| 473 |
+
bert_tree = get_tree_starting_at("src/transformers/models/bert/modeling_bert.py", edges)
|
| 474 |
+
config_utils_tree = get_tree_starting_at("src/transformers/configuration_utils.py", edges)
|
| 475 |
+
|
| 476 |
+
expected_bert_tree = [
|
| 477 |
+
"src/transformers/models/bert/modeling_bert.py",
|
| 478 |
+
[("src/transformers/models/bert/modeling_bert.py", "tests/models/bert/test_modeling_bert.py")],
|
| 479 |
+
]
|
| 480 |
+
assert bert_tree == expected_bert_tree
|
| 481 |
+
|
| 482 |
+
expected_config_tree = [
|
| 483 |
+
"src/transformers/configuration_utils.py",
|
| 484 |
+
[("src/transformers/configuration_utils.py", "src/transformers/models/bert/configuration_bert.py")],
|
| 485 |
+
[
|
| 486 |
+
("src/transformers/models/bert/configuration_bert.py", "tests/models/bert/test_modeling_bert.py"),
|
| 487 |
+
(
|
| 488 |
+
"src/transformers/models/bert/configuration_bert.py",
|
| 489 |
+
"src/transformers/models/bert/modeling_bert.py",
|
| 490 |
+
),
|
| 491 |
+
],
|
| 492 |
+
]
|
| 493 |
+
# Order of the edges is random
|
| 494 |
+
assert [set(v) for v in config_utils_tree] == [set(v) for v in expected_config_tree]
|
| 495 |
+
|
| 496 |
+
def test_print_tree_deps_of(self):
|
| 497 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 498 |
+
tmp_folder = Path(tmp_folder)
|
| 499 |
+
create_tmp_repo(tmp_folder)
|
| 500 |
+
|
| 501 |
+
# There are two possible outputs since the order of the last two lines is non-deterministic.
|
| 502 |
+
expected_std_out = """src/transformers/models/bert/modeling_bert.py
|
| 503 |
+
tests/models/bert/test_modeling_bert.py
|
| 504 |
+
src/transformers/configuration_utils.py
|
| 505 |
+
src/transformers/models/bert/configuration_bert.py
|
| 506 |
+
src/transformers/models/bert/modeling_bert.py
|
| 507 |
+
tests/models/bert/test_modeling_bert.py"""
|
| 508 |
+
|
| 509 |
+
expected_std_out_2 = """src/transformers/models/bert/modeling_bert.py
|
| 510 |
+
tests/models/bert/test_modeling_bert.py
|
| 511 |
+
src/transformers/configuration_utils.py
|
| 512 |
+
src/transformers/models/bert/configuration_bert.py
|
| 513 |
+
tests/models/bert/test_modeling_bert.py
|
| 514 |
+
src/transformers/models/bert/modeling_bert.py"""
|
| 515 |
+
|
| 516 |
+
with patch_transformer_repo_path(tmp_folder), CaptureStdout() as cs:
|
| 517 |
+
print_tree_deps_of("src/transformers/models/bert/modeling_bert.py")
|
| 518 |
+
print_tree_deps_of("src/transformers/configuration_utils.py")
|
| 519 |
+
|
| 520 |
+
assert cs.out.strip() in [expected_std_out, expected_std_out_2]
|
| 521 |
+
|
| 522 |
+
def test_init_test_examples_dependencies(self):
|
| 523 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 524 |
+
tmp_folder = Path(tmp_folder)
|
| 525 |
+
create_tmp_repo(tmp_folder)
|
| 526 |
+
|
| 527 |
+
expected_example_deps = {
|
| 528 |
+
"examples/flax/test_flax_examples.py": [
|
| 529 |
+
"examples/flax/text-classification/run_glue.py",
|
| 530 |
+
"examples/flax/test_flax_examples.py",
|
| 531 |
+
],
|
| 532 |
+
"examples/pytorch/test_pytorch_examples.py": [
|
| 533 |
+
"examples/pytorch/text-classification/run_glue.py",
|
| 534 |
+
"examples/pytorch/test_pytorch_examples.py",
|
| 535 |
+
],
|
| 536 |
+
"examples/tensorflow/test_tensorflow_examples.py": [
|
| 537 |
+
"examples/tensorflow/text-classification/run_glue.py",
|
| 538 |
+
"examples/tensorflow/test_tensorflow_examples.py",
|
| 539 |
+
],
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
expected_examples = {
|
| 543 |
+
"examples/flax/test_flax_examples.py",
|
| 544 |
+
"examples/flax/text-classification/run_glue.py",
|
| 545 |
+
"examples/pytorch/test_pytorch_examples.py",
|
| 546 |
+
"examples/pytorch/text-classification/run_glue.py",
|
| 547 |
+
"examples/tensorflow/test_tensorflow_examples.py",
|
| 548 |
+
"examples/tensorflow/text-classification/run_glue.py",
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 552 |
+
example_deps, all_examples = init_test_examples_dependencies()
|
| 553 |
+
assert example_deps == expected_example_deps
|
| 554 |
+
assert {str(f.relative_to(tmp_folder)) for f in all_examples} == expected_examples
|
| 555 |
+
|
| 556 |
+
def test_create_reverse_dependency_map(self):
|
| 557 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 558 |
+
tmp_folder = Path(tmp_folder)
|
| 559 |
+
create_tmp_repo(tmp_folder)
|
| 560 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 561 |
+
reverse_map = create_reverse_dependency_map()
|
| 562 |
+
|
| 563 |
+
# impact of BERT modeling file (note that we stop at the inits and don't go down further)
|
| 564 |
+
expected_bert_deps = {
|
| 565 |
+
"src/transformers/__init__.py",
|
| 566 |
+
"src/transformers/models/bert/__init__.py",
|
| 567 |
+
"tests/models/bert/test_modeling_bert.py",
|
| 568 |
+
"examples/flax/test_flax_examples.py",
|
| 569 |
+
"examples/flax/text-classification/run_glue.py",
|
| 570 |
+
"examples/pytorch/test_pytorch_examples.py",
|
| 571 |
+
"examples/pytorch/text-classification/run_glue.py",
|
| 572 |
+
"examples/tensorflow/test_tensorflow_examples.py",
|
| 573 |
+
"examples/tensorflow/text-classification/run_glue.py",
|
| 574 |
+
}
|
| 575 |
+
assert set(reverse_map["src/transformers/models/bert/modeling_bert.py"]) == expected_bert_deps
|
| 576 |
+
|
| 577 |
+
# init gets the direct deps (and their recursive deps)
|
| 578 |
+
expected_init_deps = {
|
| 579 |
+
"src/transformers/utils/__init__.py",
|
| 580 |
+
"src/transformers/utils/hub.py",
|
| 581 |
+
"src/transformers/utils/imports.py",
|
| 582 |
+
"src/transformers/models/bert/__init__.py",
|
| 583 |
+
"src/transformers/models/bert/configuration_bert.py",
|
| 584 |
+
"src/transformers/models/bert/modeling_bert.py",
|
| 585 |
+
"src/transformers/configuration_utils.py",
|
| 586 |
+
"src/transformers/modeling_utils.py",
|
| 587 |
+
"tests/test_modeling_common.py",
|
| 588 |
+
"tests/models/bert/test_modeling_bert.py",
|
| 589 |
+
"examples/flax/test_flax_examples.py",
|
| 590 |
+
"examples/flax/text-classification/run_glue.py",
|
| 591 |
+
"examples/pytorch/test_pytorch_examples.py",
|
| 592 |
+
"examples/pytorch/text-classification/run_glue.py",
|
| 593 |
+
"examples/tensorflow/test_tensorflow_examples.py",
|
| 594 |
+
"examples/tensorflow/text-classification/run_glue.py",
|
| 595 |
+
}
|
| 596 |
+
assert set(reverse_map["src/transformers/__init__.py"]) == expected_init_deps
|
| 597 |
+
|
| 598 |
+
expected_init_deps = {
|
| 599 |
+
"src/transformers/__init__.py",
|
| 600 |
+
"src/transformers/models/bert/configuration_bert.py",
|
| 601 |
+
"src/transformers/models/bert/modeling_bert.py",
|
| 602 |
+
"tests/models/bert/test_modeling_bert.py",
|
| 603 |
+
"examples/flax/test_flax_examples.py",
|
| 604 |
+
"examples/flax/text-classification/run_glue.py",
|
| 605 |
+
"examples/pytorch/test_pytorch_examples.py",
|
| 606 |
+
"examples/pytorch/text-classification/run_glue.py",
|
| 607 |
+
"examples/tensorflow/test_tensorflow_examples.py",
|
| 608 |
+
"examples/tensorflow/text-classification/run_glue.py",
|
| 609 |
+
}
|
| 610 |
+
assert set(reverse_map["src/transformers/models/bert/__init__.py"]) == expected_init_deps
|
| 611 |
+
|
| 612 |
+
# Test that with more models init of bert only gets deps to bert.
|
| 613 |
+
create_tmp_repo(tmp_folder, models=["bert", "gpt2"])
|
| 614 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 615 |
+
reverse_map = create_reverse_dependency_map()
|
| 616 |
+
|
| 617 |
+
# init gets the direct deps (and their recursive deps)
|
| 618 |
+
expected_init_deps = {
|
| 619 |
+
"src/transformers/__init__.py",
|
| 620 |
+
"src/transformers/models/bert/configuration_bert.py",
|
| 621 |
+
"src/transformers/models/bert/modeling_bert.py",
|
| 622 |
+
"tests/models/bert/test_modeling_bert.py",
|
| 623 |
+
"examples/flax/test_flax_examples.py",
|
| 624 |
+
"examples/flax/text-classification/run_glue.py",
|
| 625 |
+
"examples/pytorch/test_pytorch_examples.py",
|
| 626 |
+
"examples/pytorch/text-classification/run_glue.py",
|
| 627 |
+
"examples/tensorflow/test_tensorflow_examples.py",
|
| 628 |
+
"examples/tensorflow/text-classification/run_glue.py",
|
| 629 |
+
}
|
| 630 |
+
assert set(reverse_map["src/transformers/models/bert/__init__.py"]) == expected_init_deps
|
| 631 |
+
|
| 632 |
+
@unittest.skip("Broken for now TODO @ArthurZucker")
|
| 633 |
+
def test_infer_tests_to_run(self):
|
| 634 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 635 |
+
tmp_folder = Path(tmp_folder)
|
| 636 |
+
models = ["bert", "gpt2"] + [f"bert{i}" for i in range(10)]
|
| 637 |
+
repo = create_tmp_repo(tmp_folder, models=models)
|
| 638 |
+
|
| 639 |
+
commit_changes("src/transformers/models/bert/modeling_bert.py", BERT_MODEL_FILE_NEW_CODE, repo)
|
| 640 |
+
|
| 641 |
+
example_tests = {
|
| 642 |
+
"examples/flax/test_flax_examples.py",
|
| 643 |
+
"examples/pytorch/test_pytorch_examples.py",
|
| 644 |
+
"examples/tensorflow/test_tensorflow_examples.py",
|
| 645 |
+
}
|
| 646 |
+
|
| 647 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 648 |
+
infer_tests_to_run(tmp_folder / "test-output.txt", diff_with_last_commit=True)
|
| 649 |
+
with open(tmp_folder / "test-output.txt") as f:
|
| 650 |
+
tests_to_run = f.read()
|
| 651 |
+
with open(tmp_folder / "examples_test_list.txt") as f:
|
| 652 |
+
example_tests_to_run = f.read()
|
| 653 |
+
|
| 654 |
+
assert tests_to_run == "tests/models/bert/test_modeling_bert.py"
|
| 655 |
+
assert set(example_tests_to_run.split(" ")) == example_tests
|
| 656 |
+
|
| 657 |
+
# Fake a new model addition
|
| 658 |
+
repo = create_tmp_repo(tmp_folder, models=models)
|
| 659 |
+
|
| 660 |
+
branch = repo.create_head("new_model")
|
| 661 |
+
branch.checkout()
|
| 662 |
+
|
| 663 |
+
with open(tmp_folder / "src/transformers/__init__.py", "a") as f:
|
| 664 |
+
f.write("from .models.t5 import T5Config, T5Model\n")
|
| 665 |
+
|
| 666 |
+
model_dir = tmp_folder / "src/transformers/models/t5"
|
| 667 |
+
model_dir.mkdir(exist_ok=True)
|
| 668 |
+
|
| 669 |
+
with open(model_dir / "__init__.py", "w") as f:
|
| 670 |
+
f.write("from .configuration_t5 import T5Config\nfrom .modeling_t5 import T5Model\n")
|
| 671 |
+
with open(model_dir / "configuration_t5.py", "w") as f:
|
| 672 |
+
f.write("from ...configuration_utils import PretrainedConfig\ncode")
|
| 673 |
+
with open(model_dir / "modeling_t5.py", "w") as f:
|
| 674 |
+
modeling_code = BERT_MODEL_FILE.replace("bert", "t5").replace("Bert", "T5")
|
| 675 |
+
f.write(modeling_code)
|
| 676 |
+
|
| 677 |
+
test_dir = tmp_folder / "tests/models/t5"
|
| 678 |
+
test_dir.mkdir(exist_ok=True)
|
| 679 |
+
(test_dir / "__init__.py").touch()
|
| 680 |
+
with open(test_dir / "test_modeling_t5.py", "w") as f:
|
| 681 |
+
f.write(
|
| 682 |
+
"from transformers import T5Config, T5Model\nfrom ...test_modeling_common import ModelTesterMixin\n\ncode"
|
| 683 |
+
)
|
| 684 |
+
|
| 685 |
+
repo.index.add(["src", "tests"])
|
| 686 |
+
repo.index.commit("Add T5 model")
|
| 687 |
+
|
| 688 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 689 |
+
infer_tests_to_run(tmp_folder / "test-output.txt")
|
| 690 |
+
with open(tmp_folder / "test-output.txt") as f:
|
| 691 |
+
tests_to_run = f.read()
|
| 692 |
+
with open(tmp_folder / "examples_test_list.txt") as f:
|
| 693 |
+
example_tests_to_run = f.read()
|
| 694 |
+
|
| 695 |
+
expected_tests = {
|
| 696 |
+
"tests/models/bert/test_modeling_bert.py",
|
| 697 |
+
"tests/models/gpt2/test_modeling_gpt2.py",
|
| 698 |
+
"tests/models/t5/test_modeling_t5.py",
|
| 699 |
+
"tests/test_modeling_common.py",
|
| 700 |
+
}
|
| 701 |
+
assert set(tests_to_run.split(" ")) == expected_tests
|
| 702 |
+
assert set(example_tests_to_run.split(" ")) == example_tests
|
| 703 |
+
|
| 704 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 705 |
+
infer_tests_to_run(tmp_folder / "test-output.txt", filter_models=False)
|
| 706 |
+
with open(tmp_folder / "test-output.txt") as f:
|
| 707 |
+
tests_to_run = f.read()
|
| 708 |
+
with open(tmp_folder / "examples_test_list.txt") as f:
|
| 709 |
+
example_tests_to_run = f.read()
|
| 710 |
+
|
| 711 |
+
expected_tests = [f"tests/models/{name}/test_modeling_{name}.py" for name in models + ["t5"]]
|
| 712 |
+
expected_tests = set(expected_tests + ["tests/test_modeling_common.py"])
|
| 713 |
+
assert set(tests_to_run.split(" ")) == expected_tests
|
| 714 |
+
assert set(example_tests_to_run.split(" ")) == example_tests
|
| 715 |
+
|
| 716 |
+
@unittest.skip("Broken for now TODO @ArthurZucker")
|
| 717 |
+
def test_infer_tests_to_run_with_test_modifs(self):
|
| 718 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 719 |
+
tmp_folder = Path(tmp_folder)
|
| 720 |
+
models = ["bert", "gpt2"] + [f"bert{i}" for i in range(10)]
|
| 721 |
+
repo = create_tmp_repo(tmp_folder, models=models)
|
| 722 |
+
|
| 723 |
+
commit_changes(
|
| 724 |
+
"tests/models/bert/test_modeling_bert.py",
|
| 725 |
+
"from transformers import BertConfig, BertModel\nfrom ...test_modeling_common import ModelTesterMixin\n\ncode1",
|
| 726 |
+
repo,
|
| 727 |
+
)
|
| 728 |
+
|
| 729 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 730 |
+
infer_tests_to_run(tmp_folder / "test-output.txt", diff_with_last_commit=True)
|
| 731 |
+
with open(tmp_folder / "test-output.txt") as f:
|
| 732 |
+
tests_to_run = f.read()
|
| 733 |
+
|
| 734 |
+
assert tests_to_run == "tests/models/bert/test_modeling_bert.py"
|
| 735 |
+
|
| 736 |
+
@unittest.skip("Broken for now TODO @ArthurZucker")
|
| 737 |
+
def test_infer_tests_to_run_with_examples_modifs(self):
|
| 738 |
+
with tempfile.TemporaryDirectory() as tmp_folder:
|
| 739 |
+
tmp_folder = Path(tmp_folder)
|
| 740 |
+
models = ["bert", "gpt2"]
|
| 741 |
+
repo = create_tmp_repo(tmp_folder, models=models)
|
| 742 |
+
|
| 743 |
+
# Modification in one example trigger the corresponding test
|
| 744 |
+
commit_changes(
|
| 745 |
+
"examples/pytorch/text-classification/run_glue.py",
|
| 746 |
+
"from transformers import BertModeln\n\ncode1",
|
| 747 |
+
repo,
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 751 |
+
infer_tests_to_run(tmp_folder / "test-output.txt", diff_with_last_commit=True)
|
| 752 |
+
with open(tmp_folder / "examples_test_list.txt") as f:
|
| 753 |
+
example_tests_to_run = f.read()
|
| 754 |
+
|
| 755 |
+
assert example_tests_to_run == "examples/pytorch/test_pytorch_examples.py"
|
| 756 |
+
|
| 757 |
+
# Modification in one test example file trigger that test
|
| 758 |
+
repo = create_tmp_repo(tmp_folder, models=models)
|
| 759 |
+
commit_changes(
|
| 760 |
+
"examples/pytorch/test_pytorch_examples.py",
|
| 761 |
+
"""test_args = "run_glue.py"\nmore_code""",
|
| 762 |
+
repo,
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
with patch_transformer_repo_path(tmp_folder):
|
| 766 |
+
infer_tests_to_run(tmp_folder / "test-output.txt", diff_with_last_commit=True)
|
| 767 |
+
with open(tmp_folder / "examples_test_list.txt") as f:
|
| 768 |
+
example_tests_to_run = f.read()
|
| 769 |
+
|
| 770 |
+
assert example_tests_to_run == "examples/pytorch/test_pytorch_examples.py"
|
| 771 |
+
|
| 772 |
+
def test_parse_commit_message(self):
|
| 773 |
+
assert parse_commit_message("Normal commit") == {"skip": False, "no_filter": False, "test_all": False}
|
| 774 |
+
|
| 775 |
+
assert parse_commit_message("[skip ci] commit") == {"skip": True, "no_filter": False, "test_all": False}
|
| 776 |
+
assert parse_commit_message("[ci skip] commit") == {"skip": True, "no_filter": False, "test_all": False}
|
| 777 |
+
assert parse_commit_message("[skip-ci] commit") == {"skip": True, "no_filter": False, "test_all": False}
|
| 778 |
+
assert parse_commit_message("[skip_ci] commit") == {"skip": True, "no_filter": False, "test_all": False}
|
| 779 |
+
|
| 780 |
+
assert parse_commit_message("[no filter] commit") == {"skip": False, "no_filter": True, "test_all": False}
|
| 781 |
+
assert parse_commit_message("[no-filter] commit") == {"skip": False, "no_filter": True, "test_all": False}
|
| 782 |
+
assert parse_commit_message("[no_filter] commit") == {"skip": False, "no_filter": True, "test_all": False}
|
| 783 |
+
assert parse_commit_message("[filter-no] commit") == {"skip": False, "no_filter": True, "test_all": False}
|
| 784 |
+
|
| 785 |
+
assert parse_commit_message("[test all] commit") == {"skip": False, "no_filter": False, "test_all": True}
|
| 786 |
+
assert parse_commit_message("[all test] commit") == {"skip": False, "no_filter": False, "test_all": True}
|
| 787 |
+
assert parse_commit_message("[test-all] commit") == {"skip": False, "no_filter": False, "test_all": True}
|
| 788 |
+
assert parse_commit_message("[all_test] commit") == {"skip": False, "no_filter": False, "test_all": True}
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/README.md
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Testing new Hugging Face Deep Learning Container.
|
| 2 |
+
|
| 3 |
+
This document explains the testing strategy for releasing the new Hugging Face Deep Learning Container. AWS maintains 14 days of currency with framework releases. Besides framework releases, AWS release train is bi-weekly on Monday. Code cutoff date for any changes is the Wednesday before release-Monday.
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
## Test Case 1: Releasing a New Version (Minor/Major) of 🤗 Transformers
|
| 7 |
+
|
| 8 |
+
### Requirements: Test should run on Release Candidate for new `transformers` release to validate the new release is compatible with the DLCs. To run these tests you need credentials for the HF SageMaker AWS Account. You can ask @philschmid or @n1t0 to get access.
|
| 9 |
+
|
| 10 |
+
### Run Tests:
|
| 11 |
+
|
| 12 |
+
Before we can run the tests we need to adjust the `requirements.txt` for PyTorch under `/tests/sagemaker/scripts/pytorch` and for TensorFlow under `/tests/sagemaker/scripts/pytorch`. We adjust the branch to the new RC-tag.
|
| 13 |
+
|
| 14 |
+
```
|
| 15 |
+
git+https://github.com/huggingface/transformers.git@v4.5.0.rc0 # install main or adjust ist with vX.X.X for installing version specific-transforms
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
After we adjusted the `requirements.txt` we can run Amazon SageMaker tests with:
|
| 19 |
+
|
| 20 |
+
```bash
|
| 21 |
+
AWS_PROFILE=<enter-your-profile> make test-sagemaker
|
| 22 |
+
```
|
| 23 |
+
These tests take around 10-15 minutes to finish. Preferably make a screenshot of the successfully ran tests.
|
| 24 |
+
|
| 25 |
+
### After Transformers Release:
|
| 26 |
+
|
| 27 |
+
After we have released the Release Candidate we need to create a PR at the [Deep Learning Container Repository](https://github.com/aws/deep-learning-containers).
|
| 28 |
+
|
| 29 |
+
**Creating the update PR:**
|
| 30 |
+
|
| 31 |
+
1. Update the two latest `buildspec.yaml` config for [PyTorch](https://github.com/aws/deep-learning-containers/tree/master/huggingface/pytorch) and [TensorFlow](https://github.com/aws/deep-learning-containers/tree/master/huggingface/tensorflow). The two latest `buildspec.yaml` are the `buildspec.yaml` without a version tag and the one with the highest framework version, e.g. `buildspec-1-7-1.yml` and not `buildspec-1-6.yml`.
|
| 32 |
+
|
| 33 |
+
To update the `buildspec.yaml` we need to adjust either the `transformers_version` or the `datasets_version` or both. Example for upgrading to `transformers 4.5.0` and `datasets 1.6.0`.
|
| 34 |
+
```yaml
|
| 35 |
+
account_id: &ACCOUNT_ID <set-$ACCOUNT_ID-in-environment>
|
| 36 |
+
region: ®ION <set-$REGION-in-environment>
|
| 37 |
+
base_framework: &BASE_FRAMEWORK pytorch
|
| 38 |
+
framework: &FRAMEWORK !join [ "huggingface_", *BASE_FRAMEWORK]
|
| 39 |
+
version: &VERSION 1.6.0
|
| 40 |
+
short_version: &SHORT_VERSION 1.6
|
| 41 |
+
|
| 42 |
+
repository_info:
|
| 43 |
+
training_repository: &TRAINING_REPOSITORY
|
| 44 |
+
image_type: &TRAINING_IMAGE_TYPE training
|
| 45 |
+
root: !join [ "huggingface/", *BASE_FRAMEWORK, "/", *TRAINING_IMAGE_TYPE ]
|
| 46 |
+
repository_name: &REPOSITORY_NAME !join ["pr", "-", "huggingface", "-", *BASE_FRAMEWORK, "-", *TRAINING_IMAGE_TYPE]
|
| 47 |
+
repository: &REPOSITORY !join [ *ACCOUNT_ID, .dkr.ecr., *REGION, .amazonaws.com/,
|
| 48 |
+
*REPOSITORY_NAME ]
|
| 49 |
+
|
| 50 |
+
images:
|
| 51 |
+
BuildHuggingFacePytorchGpuPy37Cu110TrainingDockerImage:
|
| 52 |
+
<<: *TRAINING_REPOSITORY
|
| 53 |
+
build: &HUGGINGFACE_PYTORCH_GPU_TRAINING_PY3 false
|
| 54 |
+
image_size_baseline: &IMAGE_SIZE_BASELINE 15000
|
| 55 |
+
device_type: &DEVICE_TYPE gpu
|
| 56 |
+
python_version: &DOCKER_PYTHON_VERSION py3
|
| 57 |
+
tag_python_version: &TAG_PYTHON_VERSION py36
|
| 58 |
+
cuda_version: &CUDA_VERSION cu110
|
| 59 |
+
os_version: &OS_VERSION ubuntu18.04
|
| 60 |
+
transformers_version: &TRANSFORMERS_VERSION 4.5.0 # this was adjusted from 4.4.2 to 4.5.0
|
| 61 |
+
datasets_version: &DATASETS_VERSION 1.6.0 # this was adjusted from 1.5.0 to 1.6.0
|
| 62 |
+
tag: !join [ *VERSION, '-', 'transformers', *TRANSFORMERS_VERSION, '-', *DEVICE_TYPE, '-', *TAG_PYTHON_VERSION, '-',
|
| 63 |
+
*CUDA_VERSION, '-', *OS_VERSION ]
|
| 64 |
+
docker_file: !join [ docker/, *SHORT_VERSION, /, *DOCKER_PYTHON_VERSION, /,
|
| 65 |
+
*CUDA_VERSION, /Dockerfile., *DEVICE_TYPE ]
|
| 66 |
+
```
|
| 67 |
+
2. In the PR comment describe what test, we ran and with which package versions. Here you can copy the table from [Current Tests](#current-tests).
|
| 68 |
+
|
| 69 |
+
2. In the PR comment describe what test we ran and with which framework versions. Here you can copy the table from [Current Tests](#current-tests). You can take a look at this [PR](https://github.com/aws/deep-learning-containers/pull/1016), which information are needed.
|
| 70 |
+
## Test Case 2: Releasing a New AWS Framework DLC
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
## Execute Tests
|
| 74 |
+
|
| 75 |
+
### Requirements:
|
| 76 |
+
AWS is going to release new DLCs for PyTorch and/or TensorFlow. The Tests should run on the new framework versions with current `transformers` release to validate the new framework release is compatible with the `transformers` version. To run these tests you need credentials for the HF SageMaker AWS Account. You can ask @philschmid or @n1t0 to get access. AWS will notify us with a new issue in the repository pointing to their framework upgrade PR.
|
| 77 |
+
|
| 78 |
+
### Run Tests:
|
| 79 |
+
|
| 80 |
+
Before we can run the tests we need to adjust the `requirements.txt` for Pytorch under `/tests/sagemaker/scripts/pytorch` and for Tensorflow under `/tests/sagemaker/scripts/pytorch`. We add the new framework version to it.
|
| 81 |
+
|
| 82 |
+
```
|
| 83 |
+
torch==1.8.1 # for pytorch
|
| 84 |
+
tensorflow-gpu==2.5.0 # for tensorflow
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
After we adjusted the `requirements.txt` we can run Amazon SageMaker tests with.
|
| 88 |
+
|
| 89 |
+
```bash
|
| 90 |
+
AWS_PROFILE=<enter-your-profile> make test-sagemaker
|
| 91 |
+
```
|
| 92 |
+
These tests take around 10-15 minutes to finish. Preferably make a screenshot of the successfully ran tests.
|
| 93 |
+
|
| 94 |
+
### After successful Tests:
|
| 95 |
+
|
| 96 |
+
After we have successfully run tests for the new framework version we need to create a PR at the [Deep Learning Container Repository](https://github.com/aws/deep-learning-containers).
|
| 97 |
+
|
| 98 |
+
**Creating the update PR:**
|
| 99 |
+
|
| 100 |
+
1. Create a new `buildspec.yaml` config for [PyTorch](https://github.com/aws/deep-learning-containers/tree/master/huggingface/pytorch) and [TensorFlow](https://github.com/aws/deep-learning-containers/tree/master/huggingface/tensorflow) and rename the old `buildspec.yaml` to `buildespec-x.x.x`, where `x.x.x` is the base framework version, e.g. if pytorch 1.6.0 is the latest version in `buildspec.yaml` the file should be renamed to `buildspec-yaml-1-6.yaml`.
|
| 101 |
+
|
| 102 |
+
To create the new `buildspec.yaml` we need to adjust the `version` and the `short_version`. Example for upgrading to `pytorch 1.7.1`.
|
| 103 |
+
|
| 104 |
+
```yaml
|
| 105 |
+
account_id: &ACCOUNT_ID <set-$ACCOUNT_ID-in-environment>
|
| 106 |
+
region: ®ION <set-$REGION-in-environment>
|
| 107 |
+
base_framework: &BASE_FRAMEWORK pytorch
|
| 108 |
+
framework: &FRAMEWORK !join [ "huggingface_", *BASE_FRAMEWORK]
|
| 109 |
+
version: &VERSION 1.7.1 # this was adjusted from 1.6.0 to 1.7.1
|
| 110 |
+
short_version: &SHORT_VERSION 1.7 # this was adjusted from 1.6 to 1.7
|
| 111 |
+
|
| 112 |
+
repository_info:
|
| 113 |
+
training_repository: &TRAINING_REPOSITORY
|
| 114 |
+
image_type: &TRAINING_IMAGE_TYPE training
|
| 115 |
+
root: !join [ "huggingface/", *BASE_FRAMEWORK, "/", *TRAINING_IMAGE_TYPE ]
|
| 116 |
+
repository_name: &REPOSITORY_NAME !join ["pr", "-", "huggingface", "-", *BASE_FRAMEWORK, "-", *TRAINING_IMAGE_TYPE]
|
| 117 |
+
repository: &REPOSITORY !join [ *ACCOUNT_ID, .dkr.ecr., *REGION, .amazonaws.com/,
|
| 118 |
+
*REPOSITORY_NAME ]
|
| 119 |
+
|
| 120 |
+
images:
|
| 121 |
+
BuildHuggingFacePytorchGpuPy37Cu110TrainingDockerImage:
|
| 122 |
+
<<: *TRAINING_REPOSITORY
|
| 123 |
+
build: &HUGGINGFACE_PYTORCH_GPU_TRAINING_PY3 false
|
| 124 |
+
image_size_baseline: &IMAGE_SIZE_BASELINE 15000
|
| 125 |
+
device_type: &DEVICE_TYPE gpu
|
| 126 |
+
python_version: &DOCKER_PYTHON_VERSION py3
|
| 127 |
+
tag_python_version: &TAG_PYTHON_VERSION py36
|
| 128 |
+
cuda_version: &CUDA_VERSION cu110
|
| 129 |
+
os_version: &OS_VERSION ubuntu18.04
|
| 130 |
+
transformers_version: &TRANSFORMERS_VERSION 4.4.2
|
| 131 |
+
datasets_version: &DATASETS_VERSION 1.5.0
|
| 132 |
+
tag: !join [ *VERSION, '-', 'transformers', *TRANSFORMERS_VERSION, '-', *DEVICE_TYPE, '-', *TAG_PYTHON_VERSION, '-',
|
| 133 |
+
*CUDA_VERSION, '-', *OS_VERSION ]
|
| 134 |
+
docker_file: !join [ docker/, *SHORT_VERSION, /, *DOCKER_PYTHON_VERSION, /,
|
| 135 |
+
*CUDA_VERSION, /Dockerfile., *DEVICE_TYPE ]
|
| 136 |
+
```
|
| 137 |
+
2. In the PR comment describe what test we ran and with which framework versions. Here you can copy the table from [Current Tests](#current-tests). You can take a look at this [PR](https://github.com/aws/deep-learning-containers/pull/1025), which information are needed.
|
| 138 |
+
|
| 139 |
+
## Current Tests
|
| 140 |
+
|
| 141 |
+
| ID | Description | Platform | #GPUs | Collected & evaluated metrics |
|
| 142 |
+
|-------------------------------------|-------------------------------------------------------------------|-----------------------------|-------|------------------------------------------|
|
| 143 |
+
| pytorch-transfromers-test-single | test bert finetuning using BERT fromtransformerlib+PT | SageMaker createTrainingJob | 1 | train_runtime, eval_accuracy & eval_loss |
|
| 144 |
+
| pytorch-transfromers-test-2-ddp | test bert finetuning using BERT from transformer lib+ PT DPP | SageMaker createTrainingJob | 16 | train_runtime, eval_accuracy & eval_loss |
|
| 145 |
+
| pytorch-transfromers-test-2-smd | test bert finetuning using BERT from transformer lib+ PT SM DDP | SageMaker createTrainingJob | 16 | train_runtime, eval_accuracy & eval_loss |
|
| 146 |
+
| pytorch-transfromers-test-1-smp | test roberta finetuning using BERT from transformer lib+ PT SM MP | SageMaker createTrainingJob | 8 | train_runtime, eval_accuracy & eval_loss |
|
| 147 |
+
| tensorflow-transfromers-test-single | Test bert finetuning using BERT from transformer lib+TF | SageMaker createTrainingJob | 1 | train_runtime, eval_accuracy & eval_loss |
|
| 148 |
+
| tensorflow-transfromers-test-2-smd | test bert finetuning using BERT from transformer lib+ TF SM DDP | SageMaker createTrainingJob | 16 | train_runtime, eval_accuracy & eval_loss |
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def is_sagemaker_available():
|
| 5 |
+
return importlib.util.find_spec("sagemaker") is not None
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/conftest.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# we define a fixture function below and it will be "used" by
|
| 2 |
+
# referencing its name from tests
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
from attr import dataclass
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
os.environ["AWS_DEFAULT_REGION"] = "us-east-1" # defaults region
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass
|
| 14 |
+
class SageMakerTestEnvironment:
|
| 15 |
+
framework: str
|
| 16 |
+
role = "arn:aws:iam::558105141721:role/sagemaker_execution_role"
|
| 17 |
+
hyperparameters = {
|
| 18 |
+
"task_name": "mnli",
|
| 19 |
+
"per_device_train_batch_size": 16,
|
| 20 |
+
"per_device_eval_batch_size": 16,
|
| 21 |
+
"do_train": True,
|
| 22 |
+
"do_eval": True,
|
| 23 |
+
"do_predict": True,
|
| 24 |
+
"output_dir": "/opt/ml/model",
|
| 25 |
+
"overwrite_output_dir": True,
|
| 26 |
+
"max_steps": 500,
|
| 27 |
+
"save_steps": 5500,
|
| 28 |
+
}
|
| 29 |
+
distributed_hyperparameters = {**hyperparameters, "max_steps": 1000}
|
| 30 |
+
|
| 31 |
+
@property
|
| 32 |
+
def metric_definitions(self) -> str:
|
| 33 |
+
if self.framework == "pytorch":
|
| 34 |
+
return [
|
| 35 |
+
{"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"},
|
| 36 |
+
{"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"},
|
| 37 |
+
{"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"},
|
| 38 |
+
]
|
| 39 |
+
else:
|
| 40 |
+
return [
|
| 41 |
+
{"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"},
|
| 42 |
+
{"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"},
|
| 43 |
+
{"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"},
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
@property
|
| 47 |
+
def base_job_name(self) -> str:
|
| 48 |
+
return f"{self.framework}-transfromers-test"
|
| 49 |
+
|
| 50 |
+
@property
|
| 51 |
+
def test_path(self) -> str:
|
| 52 |
+
return f"./tests/sagemaker/scripts/{self.framework}"
|
| 53 |
+
|
| 54 |
+
@property
|
| 55 |
+
def image_uri(self) -> str:
|
| 56 |
+
if self.framework == "pytorch":
|
| 57 |
+
return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04"
|
| 58 |
+
else:
|
| 59 |
+
return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@pytest.fixture(scope="class")
|
| 63 |
+
def sm_env(request):
|
| 64 |
+
request.cls.env = SageMakerTestEnvironment(framework=request.cls.framework)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
git+https://github.com/huggingface/transformers.git@main # install main or adjust it with vX.X.X for installing version specific transforms
|
| 2 |
+
datasets==1.8.0
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/run_ddp.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import subprocess
|
| 5 |
+
from argparse import ArgumentParser
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def parse_args():
|
| 12 |
+
parser = ArgumentParser()
|
| 13 |
+
parsed, unknown = parser.parse_known_args()
|
| 14 |
+
for arg in unknown:
|
| 15 |
+
if arg.startswith(("-", "--")):
|
| 16 |
+
parser.add_argument(arg.split("=")[0])
|
| 17 |
+
|
| 18 |
+
return parser.parse_args()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def main():
|
| 22 |
+
args = parse_args()
|
| 23 |
+
port = 8888
|
| 24 |
+
num_gpus = int(os.environ["SM_NUM_GPUS"])
|
| 25 |
+
hosts = json.loads(os.environ["SM_HOSTS"])
|
| 26 |
+
num_nodes = len(hosts)
|
| 27 |
+
current_host = os.environ["SM_CURRENT_HOST"]
|
| 28 |
+
rank = hosts.index(current_host)
|
| 29 |
+
os.environ["NCCL_DEBUG"] = "INFO"
|
| 30 |
+
|
| 31 |
+
if num_nodes > 1:
|
| 32 |
+
cmd = f"""python -m torch.distributed.launch \
|
| 33 |
+
--nnodes={num_nodes} \
|
| 34 |
+
--node_rank={rank} \
|
| 35 |
+
--nproc_per_node={num_gpus} \
|
| 36 |
+
--master_addr={hosts[0]} \
|
| 37 |
+
--master_port={port} \
|
| 38 |
+
./run_glue.py \
|
| 39 |
+
{"".join([f" --{parameter} {value}" for parameter, value in args.__dict__.items()])}"""
|
| 40 |
+
else:
|
| 41 |
+
cmd = f"""python -m torch.distributed.launch \
|
| 42 |
+
--nproc_per_node={num_gpus} \
|
| 43 |
+
./run_glue.py \
|
| 44 |
+
{"".join([f" --{parameter} {value}" for parameter, value in args.__dict__.items()])}"""
|
| 45 |
+
try:
|
| 46 |
+
subprocess.run(cmd, shell=True)
|
| 47 |
+
except Exception as e:
|
| 48 |
+
logger.info(e)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
main()
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/run_glue_model_parallelism.py
ADDED
|
@@ -0,0 +1,540 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Finetuning the library models for sequence classification on GLUE."""
|
| 16 |
+
# You can also adapt this script on your own text classification task. Pointers for this are left as comments.
|
| 17 |
+
|
| 18 |
+
import logging
|
| 19 |
+
import os
|
| 20 |
+
import random
|
| 21 |
+
import sys
|
| 22 |
+
from dataclasses import dataclass, field
|
| 23 |
+
from typing import Optional
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
from datasets import load_dataset, load_metric
|
| 27 |
+
|
| 28 |
+
import transformers
|
| 29 |
+
from transformers import ( # Trainer,; TrainingArguments,
|
| 30 |
+
AutoConfig,
|
| 31 |
+
AutoModelForSequenceClassification,
|
| 32 |
+
AutoTokenizer,
|
| 33 |
+
DataCollatorWithPadding,
|
| 34 |
+
EvalPrediction,
|
| 35 |
+
HfArgumentParser,
|
| 36 |
+
PretrainedConfig,
|
| 37 |
+
default_data_collator,
|
| 38 |
+
set_seed,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# Will import SageMaker Model parallelism specific Trainer
|
| 42 |
+
from transformers.sagemaker import SageMakerTrainer as Trainer
|
| 43 |
+
from transformers.sagemaker import SageMakerTrainingArguments as TrainingArguments
|
| 44 |
+
from transformers.trainer_utils import get_last_checkpoint
|
| 45 |
+
from transformers.utils import check_min_version
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
|
| 49 |
+
check_min_version("4.4.2")
|
| 50 |
+
|
| 51 |
+
task_to_keys = {
|
| 52 |
+
"cola": ("sentence", None),
|
| 53 |
+
"mnli": ("premise", "hypothesis"),
|
| 54 |
+
"mrpc": ("sentence1", "sentence2"),
|
| 55 |
+
"qnli": ("question", "sentence"),
|
| 56 |
+
"qqp": ("question1", "question2"),
|
| 57 |
+
"rte": ("sentence1", "sentence2"),
|
| 58 |
+
"sst2": ("sentence", None),
|
| 59 |
+
"stsb": ("sentence1", "sentence2"),
|
| 60 |
+
"wnli": ("sentence1", "sentence2"),
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
logger = logging.getLogger(__name__)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@dataclass
|
| 67 |
+
class DataTrainingArguments:
|
| 68 |
+
"""
|
| 69 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
| 70 |
+
|
| 71 |
+
Using `HfArgumentParser` we can turn this class
|
| 72 |
+
into argparse arguments to be able to specify them on
|
| 73 |
+
the command line.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
task_name: Optional[str] = field(
|
| 77 |
+
default=None,
|
| 78 |
+
metadata={"help": "The name of the task to train on: " + ", ".join(task_to_keys.keys())},
|
| 79 |
+
)
|
| 80 |
+
max_seq_length: int = field(
|
| 81 |
+
default=128,
|
| 82 |
+
metadata={
|
| 83 |
+
"help": (
|
| 84 |
+
"The maximum total input sequence length after tokenization. Sequences longer "
|
| 85 |
+
"than this will be truncated, sequences shorter will be padded."
|
| 86 |
+
)
|
| 87 |
+
},
|
| 88 |
+
)
|
| 89 |
+
overwrite_cache: bool = field(
|
| 90 |
+
default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
|
| 91 |
+
)
|
| 92 |
+
pad_to_max_length: bool = field(
|
| 93 |
+
default=True,
|
| 94 |
+
metadata={
|
| 95 |
+
"help": (
|
| 96 |
+
"Whether to pad all samples to `max_seq_length`. "
|
| 97 |
+
"If False, will pad the samples dynamically when batching to the maximum length in the batch."
|
| 98 |
+
)
|
| 99 |
+
},
|
| 100 |
+
)
|
| 101 |
+
max_train_samples: Optional[int] = field(
|
| 102 |
+
default=None,
|
| 103 |
+
metadata={
|
| 104 |
+
"help": (
|
| 105 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
| 106 |
+
"value if set."
|
| 107 |
+
)
|
| 108 |
+
},
|
| 109 |
+
)
|
| 110 |
+
max_val_samples: Optional[int] = field(
|
| 111 |
+
default=None,
|
| 112 |
+
metadata={
|
| 113 |
+
"help": (
|
| 114 |
+
"For debugging purposes or quicker training, truncate the number of validation examples to this "
|
| 115 |
+
"value if set."
|
| 116 |
+
)
|
| 117 |
+
},
|
| 118 |
+
)
|
| 119 |
+
max_test_samples: Optional[int] = field(
|
| 120 |
+
default=None,
|
| 121 |
+
metadata={
|
| 122 |
+
"help": (
|
| 123 |
+
"For debugging purposes or quicker training, truncate the number of test examples to this "
|
| 124 |
+
"value if set."
|
| 125 |
+
)
|
| 126 |
+
},
|
| 127 |
+
)
|
| 128 |
+
train_file: Optional[str] = field(
|
| 129 |
+
default=None, metadata={"help": "A csv or a json file containing the training data."}
|
| 130 |
+
)
|
| 131 |
+
validation_file: Optional[str] = field(
|
| 132 |
+
default=None, metadata={"help": "A csv or a json file containing the validation data."}
|
| 133 |
+
)
|
| 134 |
+
test_file: Optional[str] = field(default=None, metadata={"help": "A csv or a json file containing the test data."})
|
| 135 |
+
|
| 136 |
+
def __post_init__(self):
|
| 137 |
+
if self.task_name is not None:
|
| 138 |
+
self.task_name = self.task_name.lower()
|
| 139 |
+
if self.task_name not in task_to_keys:
|
| 140 |
+
raise ValueError("Unknown task, you should pick one in " + ",".join(task_to_keys.keys()))
|
| 141 |
+
elif self.train_file is None or self.validation_file is None:
|
| 142 |
+
raise ValueError("Need either a GLUE task or a training/validation file.")
|
| 143 |
+
else:
|
| 144 |
+
train_extension = self.train_file.split(".")[-1]
|
| 145 |
+
assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file."
|
| 146 |
+
validation_extension = self.validation_file.split(".")[-1]
|
| 147 |
+
assert validation_extension == train_extension, (
|
| 148 |
+
"`validation_file` should have the same extension (csv or json) as `train_file`."
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@dataclass
|
| 153 |
+
class ModelArguments:
|
| 154 |
+
"""
|
| 155 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
|
| 156 |
+
"""
|
| 157 |
+
|
| 158 |
+
model_name_or_path: str = field(
|
| 159 |
+
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
|
| 160 |
+
)
|
| 161 |
+
config_name: Optional[str] = field(
|
| 162 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
| 163 |
+
)
|
| 164 |
+
tokenizer_name: Optional[str] = field(
|
| 165 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
| 166 |
+
)
|
| 167 |
+
cache_dir: Optional[str] = field(
|
| 168 |
+
default=None,
|
| 169 |
+
metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
|
| 170 |
+
)
|
| 171 |
+
use_fast_tokenizer: bool = field(
|
| 172 |
+
default=True,
|
| 173 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
| 174 |
+
)
|
| 175 |
+
model_revision: str = field(
|
| 176 |
+
default="main",
|
| 177 |
+
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
|
| 178 |
+
)
|
| 179 |
+
use_auth_token: bool = field(
|
| 180 |
+
default=False,
|
| 181 |
+
metadata={
|
| 182 |
+
"help": (
|
| 183 |
+
"Will use the token generated when running `hf auth login` (necessary to use this script "
|
| 184 |
+
"with private models)."
|
| 185 |
+
)
|
| 186 |
+
},
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def main():
|
| 191 |
+
# See all possible arguments in src/transformers/training_args.py
|
| 192 |
+
# or by passing the --help flag to this script.
|
| 193 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
| 194 |
+
|
| 195 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
|
| 196 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
| 197 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
| 198 |
+
# let's parse it to get our arguments.
|
| 199 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
| 200 |
+
else:
|
| 201 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
| 202 |
+
|
| 203 |
+
# Detecting last checkpoint.
|
| 204 |
+
last_checkpoint = None
|
| 205 |
+
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
| 206 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
| 207 |
+
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
|
| 208 |
+
raise ValueError(
|
| 209 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
|
| 210 |
+
"Use --overwrite_output_dir to overcome."
|
| 211 |
+
)
|
| 212 |
+
elif last_checkpoint is not None:
|
| 213 |
+
logger.info(
|
| 214 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
| 215 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
# Setup logging
|
| 219 |
+
logging.basicConfig(
|
| 220 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 221 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 222 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
| 223 |
+
)
|
| 224 |
+
logger.setLevel(logging.INFO if training_args.should_log else logging.WARN)
|
| 225 |
+
|
| 226 |
+
# Log on each process the small summary:
|
| 227 |
+
logger.warning(
|
| 228 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
| 229 |
+
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
| 230 |
+
)
|
| 231 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
| 232 |
+
if training_args.should_log:
|
| 233 |
+
transformers.utils.logging.set_verbosity_info()
|
| 234 |
+
transformers.utils.logging.enable_default_handler()
|
| 235 |
+
transformers.utils.logging.enable_explicit_format()
|
| 236 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
| 237 |
+
|
| 238 |
+
# Set seed before initializing model.
|
| 239 |
+
set_seed(training_args.seed)
|
| 240 |
+
|
| 241 |
+
# Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
|
| 242 |
+
# or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub).
|
| 243 |
+
#
|
| 244 |
+
# For CSV/JSON files, this script will use as labels the column called 'label' and as pair of sentences the
|
| 245 |
+
# sentences in columns called 'sentence1' and 'sentence2' if such column exists or the first two columns not named
|
| 246 |
+
# label if at least two columns are provided.
|
| 247 |
+
#
|
| 248 |
+
# If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this
|
| 249 |
+
# single column. You can easily tweak this behavior (see below)
|
| 250 |
+
#
|
| 251 |
+
# In distributed training, the load_dataset function guarantee that only one local process can concurrently
|
| 252 |
+
# download the dataset.
|
| 253 |
+
if data_args.task_name is not None:
|
| 254 |
+
# Downloading and loading a dataset from the hub.
|
| 255 |
+
datasets = load_dataset("nyu-mll/glue", data_args.task_name)
|
| 256 |
+
else:
|
| 257 |
+
# Loading a dataset from your local files.
|
| 258 |
+
# CSV/JSON training and evaluation files are needed.
|
| 259 |
+
data_files = {"train": data_args.train_file, "validation": data_args.validation_file}
|
| 260 |
+
|
| 261 |
+
# Get the test dataset: you can provide your own CSV/JSON test file (see below)
|
| 262 |
+
# when you use `do_predict` without specifying a GLUE benchmark task.
|
| 263 |
+
if training_args.do_predict:
|
| 264 |
+
if data_args.test_file is not None:
|
| 265 |
+
train_extension = data_args.train_file.split(".")[-1]
|
| 266 |
+
test_extension = data_args.test_file.split(".")[-1]
|
| 267 |
+
assert test_extension == train_extension, (
|
| 268 |
+
"`test_file` should have the same extension (csv or json) as `train_file`."
|
| 269 |
+
)
|
| 270 |
+
data_files["test"] = data_args.test_file
|
| 271 |
+
else:
|
| 272 |
+
raise ValueError("Need either a GLUE task or a test file for `do_predict`.")
|
| 273 |
+
|
| 274 |
+
for key in data_files:
|
| 275 |
+
logger.info(f"load a local file for {key}: {data_files[key]}")
|
| 276 |
+
|
| 277 |
+
if data_args.train_file.endswith(".csv"):
|
| 278 |
+
# Loading a dataset from local csv files
|
| 279 |
+
datasets = load_dataset("csv", data_files=data_files)
|
| 280 |
+
else:
|
| 281 |
+
# Loading a dataset from local json files
|
| 282 |
+
datasets = load_dataset("json", data_files=data_files)
|
| 283 |
+
# See more about loading any type of standard or custom dataset at
|
| 284 |
+
# https://huggingface.co/docs/datasets/loading_datasets.
|
| 285 |
+
|
| 286 |
+
# Labels
|
| 287 |
+
if data_args.task_name is not None:
|
| 288 |
+
is_regression = data_args.task_name == "stsb"
|
| 289 |
+
if not is_regression:
|
| 290 |
+
label_list = datasets["train"].features["label"].names
|
| 291 |
+
num_labels = len(label_list)
|
| 292 |
+
else:
|
| 293 |
+
num_labels = 1
|
| 294 |
+
else:
|
| 295 |
+
# Trying to have good defaults here, don't hesitate to tweak to your needs.
|
| 296 |
+
is_regression = datasets["train"].features["label"].dtype in ["float32", "float64"]
|
| 297 |
+
if is_regression:
|
| 298 |
+
num_labels = 1
|
| 299 |
+
else:
|
| 300 |
+
# A useful fast method:
|
| 301 |
+
# https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.unique
|
| 302 |
+
label_list = datasets["train"].unique("label")
|
| 303 |
+
label_list.sort() # Let's sort it for determinism
|
| 304 |
+
num_labels = len(label_list)
|
| 305 |
+
|
| 306 |
+
# Load pretrained model and tokenizer
|
| 307 |
+
#
|
| 308 |
+
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
|
| 309 |
+
# download model & vocab.
|
| 310 |
+
config = AutoConfig.from_pretrained(
|
| 311 |
+
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
|
| 312 |
+
num_labels=num_labels,
|
| 313 |
+
finetuning_task=data_args.task_name,
|
| 314 |
+
cache_dir=model_args.cache_dir,
|
| 315 |
+
revision=model_args.model_revision,
|
| 316 |
+
token=True if model_args.use_auth_token else None,
|
| 317 |
+
)
|
| 318 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 319 |
+
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
|
| 320 |
+
cache_dir=model_args.cache_dir,
|
| 321 |
+
use_fast=model_args.use_fast_tokenizer,
|
| 322 |
+
revision=model_args.model_revision,
|
| 323 |
+
token=True if model_args.use_auth_token else None,
|
| 324 |
+
)
|
| 325 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 326 |
+
model_args.model_name_or_path,
|
| 327 |
+
from_tf=bool(".ckpt" in model_args.model_name_or_path),
|
| 328 |
+
config=config,
|
| 329 |
+
cache_dir=model_args.cache_dir,
|
| 330 |
+
revision=model_args.model_revision,
|
| 331 |
+
token=True if model_args.use_auth_token else None,
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
# Preprocessing the datasets
|
| 335 |
+
if data_args.task_name is not None:
|
| 336 |
+
sentence1_key, sentence2_key = task_to_keys[data_args.task_name]
|
| 337 |
+
else:
|
| 338 |
+
# Again, we try to have some nice defaults but don't hesitate to tweak to your use case.
|
| 339 |
+
non_label_column_names = [name for name in datasets["train"].column_names if name != "label"]
|
| 340 |
+
if "sentence1" in non_label_column_names and "sentence2" in non_label_column_names:
|
| 341 |
+
sentence1_key, sentence2_key = "sentence1", "sentence2"
|
| 342 |
+
else:
|
| 343 |
+
if len(non_label_column_names) >= 2:
|
| 344 |
+
sentence1_key, sentence2_key = non_label_column_names[:2]
|
| 345 |
+
else:
|
| 346 |
+
sentence1_key, sentence2_key = non_label_column_names[0], None
|
| 347 |
+
|
| 348 |
+
# Padding strategy
|
| 349 |
+
if data_args.pad_to_max_length:
|
| 350 |
+
padding = "max_length"
|
| 351 |
+
else:
|
| 352 |
+
# We will pad later, dynamically at batch creation, to the max sequence length in each batch
|
| 353 |
+
padding = False
|
| 354 |
+
|
| 355 |
+
# Some models have set the order of the labels to use, so let's make sure we do use it.
|
| 356 |
+
label_to_id = None
|
| 357 |
+
if (
|
| 358 |
+
model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id
|
| 359 |
+
and data_args.task_name is not None
|
| 360 |
+
and not is_regression
|
| 361 |
+
):
|
| 362 |
+
# Some have all caps in their config, some don't.
|
| 363 |
+
label_name_to_id = {k.lower(): v for k, v in model.config.label2id.items()}
|
| 364 |
+
if sorted(label_name_to_id.keys()) == sorted(label_list):
|
| 365 |
+
label_to_id = {i: int(label_name_to_id[label_list[i]]) for i in range(num_labels)}
|
| 366 |
+
else:
|
| 367 |
+
logger.warning(
|
| 368 |
+
"Your model seems to have been trained with labels, but they don't match the dataset: "
|
| 369 |
+
f"model labels: {sorted(label_name_to_id.keys())}, dataset labels: {sorted(label_list)}."
|
| 370 |
+
"\nIgnoring the model labels as a result.",
|
| 371 |
+
)
|
| 372 |
+
elif data_args.task_name is None and not is_regression:
|
| 373 |
+
label_to_id = {v: i for i, v in enumerate(label_list)}
|
| 374 |
+
|
| 375 |
+
if data_args.max_seq_length > tokenizer.model_max_length:
|
| 376 |
+
logger.warning(
|
| 377 |
+
f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the "
|
| 378 |
+
f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
|
| 379 |
+
)
|
| 380 |
+
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
|
| 381 |
+
|
| 382 |
+
def preprocess_function(examples):
|
| 383 |
+
# Tokenize the texts
|
| 384 |
+
args = (
|
| 385 |
+
(examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key])
|
| 386 |
+
)
|
| 387 |
+
result = tokenizer(*args, padding=padding, max_length=max_seq_length, truncation=True)
|
| 388 |
+
|
| 389 |
+
# Map labels to IDs (not necessary for GLUE tasks)
|
| 390 |
+
if label_to_id is not None and "label" in examples:
|
| 391 |
+
result["label"] = [(label_to_id[l] if l != -1 else -1) for l in examples["label"]]
|
| 392 |
+
return result
|
| 393 |
+
|
| 394 |
+
datasets = datasets.map(preprocess_function, batched=True, load_from_cache_file=not data_args.overwrite_cache)
|
| 395 |
+
if training_args.do_train:
|
| 396 |
+
if "train" not in datasets:
|
| 397 |
+
raise ValueError("--do_train requires a train dataset")
|
| 398 |
+
train_dataset = datasets["train"]
|
| 399 |
+
if data_args.max_train_samples is not None:
|
| 400 |
+
train_dataset = train_dataset.select(range(data_args.max_train_samples))
|
| 401 |
+
|
| 402 |
+
if training_args.do_eval:
|
| 403 |
+
if "validation" not in datasets and "validation_matched" not in datasets:
|
| 404 |
+
raise ValueError("--do_eval requires a validation dataset")
|
| 405 |
+
eval_dataset = datasets["validation_matched" if data_args.task_name == "mnli" else "validation"]
|
| 406 |
+
if data_args.max_val_samples is not None:
|
| 407 |
+
eval_dataset = eval_dataset.select(range(data_args.max_val_samples))
|
| 408 |
+
|
| 409 |
+
if training_args.do_predict or data_args.task_name is not None or data_args.test_file is not None:
|
| 410 |
+
if "test" not in datasets and "test_matched" not in datasets:
|
| 411 |
+
raise ValueError("--do_predict requires a test dataset")
|
| 412 |
+
test_dataset = datasets["test_matched" if data_args.task_name == "mnli" else "test"]
|
| 413 |
+
if data_args.max_test_samples is not None:
|
| 414 |
+
test_dataset = test_dataset.select(range(data_args.max_test_samples))
|
| 415 |
+
|
| 416 |
+
# Log a few random samples from the training set:
|
| 417 |
+
if training_args.do_train:
|
| 418 |
+
for index in random.sample(range(len(train_dataset)), 3):
|
| 419 |
+
logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
|
| 420 |
+
|
| 421 |
+
# Get the metric function
|
| 422 |
+
if data_args.task_name is not None:
|
| 423 |
+
metric = load_metric("glue", data_args.task_name)
|
| 424 |
+
# TODO: When datasets metrics include regular accuracy, make an else here and remove special branch from
|
| 425 |
+
# compute_metrics
|
| 426 |
+
|
| 427 |
+
# You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
|
| 428 |
+
# predictions and label_ids field) and has to return a dictionary string to float.
|
| 429 |
+
def compute_metrics(p: EvalPrediction):
|
| 430 |
+
preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
|
| 431 |
+
preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1)
|
| 432 |
+
if data_args.task_name is not None:
|
| 433 |
+
result = metric.compute(predictions=preds, references=p.label_ids)
|
| 434 |
+
if len(result) > 1:
|
| 435 |
+
result["combined_score"] = np.mean(list(result.values())).item()
|
| 436 |
+
return result
|
| 437 |
+
elif is_regression:
|
| 438 |
+
return {"mse": ((preds - p.label_ids) ** 2).mean().item()}
|
| 439 |
+
else:
|
| 440 |
+
return {"accuracy": (preds == p.label_ids).astype(np.float32).mean().item()}
|
| 441 |
+
|
| 442 |
+
# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
|
| 443 |
+
if data_args.pad_to_max_length:
|
| 444 |
+
data_collator = default_data_collator
|
| 445 |
+
elif training_args.fp16:
|
| 446 |
+
data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8)
|
| 447 |
+
else:
|
| 448 |
+
data_collator = None
|
| 449 |
+
|
| 450 |
+
# Initialize our Trainer
|
| 451 |
+
trainer = Trainer(
|
| 452 |
+
model=model,
|
| 453 |
+
args=training_args,
|
| 454 |
+
train_dataset=train_dataset if training_args.do_train else None,
|
| 455 |
+
eval_dataset=eval_dataset if training_args.do_eval else None,
|
| 456 |
+
compute_metrics=compute_metrics,
|
| 457 |
+
processing_class=tokenizer,
|
| 458 |
+
data_collator=data_collator,
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
# Training
|
| 462 |
+
if training_args.do_train:
|
| 463 |
+
checkpoint = None
|
| 464 |
+
if last_checkpoint is not None:
|
| 465 |
+
checkpoint = last_checkpoint
|
| 466 |
+
elif os.path.isdir(model_args.model_name_or_path):
|
| 467 |
+
# Check the config from that potential checkpoint has the right number of labels before using it as a
|
| 468 |
+
# checkpoint.
|
| 469 |
+
if AutoConfig.from_pretrained(model_args.model_name_or_path).num_labels == num_labels:
|
| 470 |
+
checkpoint = model_args.model_name_or_path
|
| 471 |
+
|
| 472 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
| 473 |
+
metrics = train_result.metrics
|
| 474 |
+
max_train_samples = (
|
| 475 |
+
data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
|
| 476 |
+
)
|
| 477 |
+
metrics["train_samples"] = min(max_train_samples, len(train_dataset))
|
| 478 |
+
|
| 479 |
+
trainer.save_model() # Saves the tokenizer too for easy upload
|
| 480 |
+
|
| 481 |
+
trainer.log_metrics("train", metrics)
|
| 482 |
+
trainer.save_metrics("train", metrics)
|
| 483 |
+
trainer.save_state()
|
| 484 |
+
|
| 485 |
+
# Evaluation
|
| 486 |
+
if training_args.do_eval:
|
| 487 |
+
logger.info("*** Evaluate ***")
|
| 488 |
+
|
| 489 |
+
# Loop to handle MNLI double evaluation (matched, mis-matched)
|
| 490 |
+
tasks = [data_args.task_name]
|
| 491 |
+
eval_datasets = [eval_dataset]
|
| 492 |
+
if data_args.task_name == "mnli":
|
| 493 |
+
tasks.append("mnli-mm")
|
| 494 |
+
eval_datasets.append(datasets["validation_mismatched"])
|
| 495 |
+
|
| 496 |
+
for eval_dataset, task in zip(eval_datasets, tasks):
|
| 497 |
+
metrics = trainer.evaluate(eval_dataset=eval_dataset)
|
| 498 |
+
|
| 499 |
+
max_val_samples = data_args.max_val_samples if data_args.max_val_samples is not None else len(eval_dataset)
|
| 500 |
+
metrics["eval_samples"] = min(max_val_samples, len(eval_dataset))
|
| 501 |
+
|
| 502 |
+
trainer.log_metrics("eval", metrics)
|
| 503 |
+
trainer.save_metrics("eval", metrics)
|
| 504 |
+
|
| 505 |
+
if training_args.do_predict:
|
| 506 |
+
logger.info("*** Test ***")
|
| 507 |
+
|
| 508 |
+
# Loop to handle MNLI double evaluation (matched, mis-matched)
|
| 509 |
+
tasks = [data_args.task_name]
|
| 510 |
+
test_datasets = [test_dataset]
|
| 511 |
+
if data_args.task_name == "mnli":
|
| 512 |
+
tasks.append("mnli-mm")
|
| 513 |
+
test_datasets.append(datasets["test_mismatched"])
|
| 514 |
+
|
| 515 |
+
for test_dataset, task in zip(test_datasets, tasks):
|
| 516 |
+
# Removing the `label` columns because it contains -1 and Trainer won't like that.
|
| 517 |
+
test_dataset = test_dataset.remove_columns("label")
|
| 518 |
+
predictions = trainer.predict(test_dataset=test_dataset).predictions
|
| 519 |
+
predictions = np.squeeze(predictions) if is_regression else np.argmax(predictions, axis=1)
|
| 520 |
+
|
| 521 |
+
output_test_file = os.path.join(training_args.output_dir, f"test_results_{task}.txt")
|
| 522 |
+
if trainer.is_world_process_zero():
|
| 523 |
+
with open(output_test_file, "w") as writer:
|
| 524 |
+
logger.info(f"***** Test results {task} *****")
|
| 525 |
+
writer.write("index\tprediction\n")
|
| 526 |
+
for index, item in enumerate(predictions):
|
| 527 |
+
if is_regression:
|
| 528 |
+
writer.write(f"{index}\t{item:3.3f}\n")
|
| 529 |
+
else:
|
| 530 |
+
item = label_list[item]
|
| 531 |
+
writer.write(f"{index}\t{item}\n")
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def _mp_fn(index):
|
| 535 |
+
# For xla_spawn (TPUs)
|
| 536 |
+
main()
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
if __name__ == "__main__":
|
| 540 |
+
main()
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/tensorflow/requirements.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
git+https://github.com/huggingface/transformers.git@main # install main or adjust ist with vX.X.X for installing version specific transforms
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/tensorflow/run_tf.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import logging
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import tensorflow as tf
|
| 7 |
+
from datasets import load_dataset
|
| 8 |
+
from packaging.version import parse
|
| 9 |
+
|
| 10 |
+
from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
import tf_keras as keras
|
| 15 |
+
except (ModuleNotFoundError, ImportError):
|
| 16 |
+
import keras
|
| 17 |
+
|
| 18 |
+
if parse(keras.__version__).major > 2:
|
| 19 |
+
raise ValueError(
|
| 20 |
+
"Your currently installed version of Keras is Keras 3, but this is not yet supported in "
|
| 21 |
+
"Transformers. Please install the backwards-compatible tf-keras package with "
|
| 22 |
+
"`pip install tf-keras`."
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if __name__ == "__main__":
|
| 27 |
+
parser = argparse.ArgumentParser()
|
| 28 |
+
|
| 29 |
+
# Hyperparameters sent by the client are passed as command-line arguments to the script.
|
| 30 |
+
parser.add_argument("--epochs", type=int, default=1)
|
| 31 |
+
parser.add_argument("--per_device_train_batch_size", type=int, default=16)
|
| 32 |
+
parser.add_argument("--per_device_eval_batch_size", type=int, default=8)
|
| 33 |
+
parser.add_argument("--model_name_or_path", type=str)
|
| 34 |
+
parser.add_argument("--learning_rate", type=str, default=5e-5)
|
| 35 |
+
parser.add_argument("--do_train", type=bool, default=True)
|
| 36 |
+
parser.add_argument("--do_eval", type=bool, default=True)
|
| 37 |
+
parser.add_argument("--output_dir", type=str)
|
| 38 |
+
|
| 39 |
+
args, _ = parser.parse_known_args()
|
| 40 |
+
|
| 41 |
+
# overwrite batch size until we have tf_glue.py
|
| 42 |
+
args.per_device_train_batch_size = 16
|
| 43 |
+
args.per_device_eval_batch_size = 16
|
| 44 |
+
|
| 45 |
+
# Set up logging
|
| 46 |
+
logger = logging.getLogger(__name__)
|
| 47 |
+
|
| 48 |
+
logging.basicConfig(
|
| 49 |
+
level=logging.getLevelName("INFO"),
|
| 50 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
| 51 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# Load model and tokenizer
|
| 55 |
+
model = TFAutoModelForSequenceClassification.from_pretrained(args.model_name_or_path)
|
| 56 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
|
| 57 |
+
|
| 58 |
+
# Load dataset
|
| 59 |
+
train_dataset, test_dataset = load_dataset("stanfordnlp/imdb", split=["train", "test"])
|
| 60 |
+
train_dataset = train_dataset.shuffle().select(range(5000)) # smaller the size for train dataset to 5k
|
| 61 |
+
test_dataset = test_dataset.shuffle().select(range(500)) # smaller the size for test dataset to 500
|
| 62 |
+
|
| 63 |
+
# Preprocess train dataset
|
| 64 |
+
train_dataset = train_dataset.map(
|
| 65 |
+
lambda e: tokenizer(e["text"], truncation=True, padding="max_length"), batched=True
|
| 66 |
+
)
|
| 67 |
+
train_dataset.set_format(type="tensorflow", columns=["input_ids", "attention_mask", "label"])
|
| 68 |
+
|
| 69 |
+
train_features = {
|
| 70 |
+
x: train_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length])
|
| 71 |
+
for x in ["input_ids", "attention_mask"]
|
| 72 |
+
}
|
| 73 |
+
tf_train_dataset = tf.data.Dataset.from_tensor_slices((train_features, train_dataset["label"])).batch(
|
| 74 |
+
args.per_device_train_batch_size
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
# Preprocess test dataset
|
| 78 |
+
test_dataset = test_dataset.map(
|
| 79 |
+
lambda e: tokenizer(e["text"], truncation=True, padding="max_length"), batched=True
|
| 80 |
+
)
|
| 81 |
+
test_dataset.set_format(type="tensorflow", columns=["input_ids", "attention_mask", "label"])
|
| 82 |
+
|
| 83 |
+
test_features = {
|
| 84 |
+
x: test_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length])
|
| 85 |
+
for x in ["input_ids", "attention_mask"]
|
| 86 |
+
}
|
| 87 |
+
tf_test_dataset = tf.data.Dataset.from_tensor_slices((test_features, test_dataset["label"])).batch(
|
| 88 |
+
args.per_device_eval_batch_size
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
# fine optimizer and loss
|
| 92 |
+
optimizer = keras.optimizers.Adam(learning_rate=args.learning_rate)
|
| 93 |
+
loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True)
|
| 94 |
+
metrics = [keras.metrics.SparseCategoricalAccuracy()]
|
| 95 |
+
model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
|
| 96 |
+
|
| 97 |
+
start_train_time = time.time()
|
| 98 |
+
train_results = model.fit(tf_train_dataset, epochs=args.epochs, batch_size=args.per_device_train_batch_size)
|
| 99 |
+
end_train_time = time.time() - start_train_time
|
| 100 |
+
|
| 101 |
+
logger.info("*** Train ***")
|
| 102 |
+
logger.info(f"train_runtime = {end_train_time}")
|
| 103 |
+
for key, value in train_results.history.items():
|
| 104 |
+
logger.info(f" {key} = {value}")
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_multi_node_data_parallel.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import subprocess
|
| 4 |
+
import unittest
|
| 5 |
+
from ast import literal_eval
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
from parameterized import parameterized, parameterized_class
|
| 9 |
+
|
| 10 |
+
from . import is_sagemaker_available
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
if is_sagemaker_available():
|
| 14 |
+
from sagemaker import Session, TrainingJobAnalytics
|
| 15 |
+
from sagemaker.huggingface import HuggingFace
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.mark.skipif(
|
| 19 |
+
literal_eval(os.getenv("TEST_SAGEMAKER", "False")) is not True,
|
| 20 |
+
reason="Skipping test because should only be run when releasing minor transformers version",
|
| 21 |
+
)
|
| 22 |
+
@pytest.mark.usefixtures("sm_env")
|
| 23 |
+
@parameterized_class(
|
| 24 |
+
[
|
| 25 |
+
{
|
| 26 |
+
"framework": "pytorch",
|
| 27 |
+
"script": "run_glue.py",
|
| 28 |
+
"model_name_or_path": "distilbert/distilbert-base-cased",
|
| 29 |
+
"instance_type": "ml.p3.16xlarge",
|
| 30 |
+
"results": {"train_runtime": 650, "eval_accuracy": 0.7, "eval_loss": 0.6},
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"framework": "pytorch",
|
| 34 |
+
"script": "run_ddp.py",
|
| 35 |
+
"model_name_or_path": "distilbert/distilbert-base-cased",
|
| 36 |
+
"instance_type": "ml.p3.16xlarge",
|
| 37 |
+
"results": {"train_runtime": 600, "eval_accuracy": 0.7, "eval_loss": 0.6},
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"framework": "tensorflow",
|
| 41 |
+
"script": "run_tf_dist.py",
|
| 42 |
+
"model_name_or_path": "distilbert/distilbert-base-cased",
|
| 43 |
+
"instance_type": "ml.p3.16xlarge",
|
| 44 |
+
"results": {"train_runtime": 600, "eval_accuracy": 0.6, "eval_loss": 0.7},
|
| 45 |
+
},
|
| 46 |
+
]
|
| 47 |
+
)
|
| 48 |
+
class MultiNodeTest(unittest.TestCase):
|
| 49 |
+
def setUp(self):
|
| 50 |
+
if self.framework == "pytorch":
|
| 51 |
+
subprocess.run(
|
| 52 |
+
f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split(),
|
| 53 |
+
encoding="utf-8",
|
| 54 |
+
check=True,
|
| 55 |
+
)
|
| 56 |
+
assert hasattr(self, "env")
|
| 57 |
+
|
| 58 |
+
def create_estimator(self, instance_count):
|
| 59 |
+
job_name = f"{self.env.base_job_name}-{instance_count}-{'ddp' if 'ddp' in self.script else 'smd'}"
|
| 60 |
+
# distributed data settings
|
| 61 |
+
distribution = {"smdistributed": {"dataparallel": {"enabled": True}}} if self.script != "run_ddp.py" else None
|
| 62 |
+
|
| 63 |
+
# creates estimator
|
| 64 |
+
return HuggingFace(
|
| 65 |
+
entry_point=self.script,
|
| 66 |
+
source_dir=self.env.test_path,
|
| 67 |
+
role=self.env.role,
|
| 68 |
+
image_uri=self.env.image_uri,
|
| 69 |
+
base_job_name=job_name,
|
| 70 |
+
instance_count=instance_count,
|
| 71 |
+
instance_type=self.instance_type,
|
| 72 |
+
debugger_hook_config=False,
|
| 73 |
+
hyperparameters={**self.env.distributed_hyperparameters, "model_name_or_path": self.model_name_or_path},
|
| 74 |
+
metric_definitions=self.env.metric_definitions,
|
| 75 |
+
distribution=distribution,
|
| 76 |
+
py_version="py36",
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
def save_results_as_csv(self, job_name):
|
| 80 |
+
TrainingJobAnalytics(job_name).export_csv(f"{self.env.test_path}/{job_name}_metrics.csv")
|
| 81 |
+
|
| 82 |
+
# @parameterized.expand([(2,), (4,),])
|
| 83 |
+
@parameterized.expand([(2,)])
|
| 84 |
+
def test_script(self, instance_count):
|
| 85 |
+
# create estimator
|
| 86 |
+
estimator = self.create_estimator(instance_count)
|
| 87 |
+
|
| 88 |
+
# run training
|
| 89 |
+
estimator.fit()
|
| 90 |
+
|
| 91 |
+
# result dataframe
|
| 92 |
+
result_metrics_df = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe()
|
| 93 |
+
|
| 94 |
+
# extract kpis
|
| 95 |
+
eval_accuracy = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"])
|
| 96 |
+
eval_loss = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"])
|
| 97 |
+
# get train time from SageMaker job, this includes starting, preprocessing, stopping
|
| 98 |
+
train_runtime = (
|
| 99 |
+
Session().describe_training_job(estimator.latest_training_job.name).get("TrainingTimeInSeconds", 999999)
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# assert kpis
|
| 103 |
+
assert train_runtime <= self.results["train_runtime"]
|
| 104 |
+
assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy)
|
| 105 |
+
assert all(t <= self.results["eval_loss"] for t in eval_loss)
|
| 106 |
+
|
| 107 |
+
# dump tests result into json file to share in PR
|
| 108 |
+
with open(f"{estimator.latest_training_job.name}.json", "w") as outfile:
|
| 109 |
+
json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}, outfile)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_multi_node_model_parallel.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import subprocess
|
| 4 |
+
import unittest
|
| 5 |
+
from ast import literal_eval
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
from parameterized import parameterized, parameterized_class
|
| 9 |
+
|
| 10 |
+
from . import is_sagemaker_available
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
if is_sagemaker_available():
|
| 14 |
+
from sagemaker import Session, TrainingJobAnalytics
|
| 15 |
+
from sagemaker.huggingface import HuggingFace
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.mark.skipif(
|
| 19 |
+
literal_eval(os.getenv("TEST_SAGEMAKER", "False")) is not True,
|
| 20 |
+
reason="Skipping test because should only be run when releasing minor transformers version",
|
| 21 |
+
)
|
| 22 |
+
@pytest.mark.usefixtures("sm_env")
|
| 23 |
+
@parameterized_class(
|
| 24 |
+
[
|
| 25 |
+
{
|
| 26 |
+
"framework": "pytorch",
|
| 27 |
+
"script": "run_glue_model_parallelism.py",
|
| 28 |
+
"model_name_or_path": "FacebookAI/roberta-large",
|
| 29 |
+
"instance_type": "ml.p3dn.24xlarge",
|
| 30 |
+
"results": {"train_runtime": 1600, "eval_accuracy": 0.3, "eval_loss": 1.2},
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"framework": "pytorch",
|
| 34 |
+
"script": "run_glue.py",
|
| 35 |
+
"model_name_or_path": "FacebookAI/roberta-large",
|
| 36 |
+
"instance_type": "ml.p3dn.24xlarge",
|
| 37 |
+
"results": {"train_runtime": 1600, "eval_accuracy": 0.3, "eval_loss": 1.2},
|
| 38 |
+
},
|
| 39 |
+
]
|
| 40 |
+
)
|
| 41 |
+
class MultiNodeTest(unittest.TestCase):
|
| 42 |
+
def setUp(self):
|
| 43 |
+
if self.framework == "pytorch":
|
| 44 |
+
subprocess.run(
|
| 45 |
+
f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split(),
|
| 46 |
+
encoding="utf-8",
|
| 47 |
+
check=True,
|
| 48 |
+
)
|
| 49 |
+
assert hasattr(self, "env")
|
| 50 |
+
|
| 51 |
+
def create_estimator(self, instance_count):
|
| 52 |
+
# configuration for running training on smdistributed Model Parallel
|
| 53 |
+
mpi_options = {
|
| 54 |
+
"enabled": True,
|
| 55 |
+
"processes_per_host": 8,
|
| 56 |
+
}
|
| 57 |
+
smp_options = {
|
| 58 |
+
"enabled": True,
|
| 59 |
+
"parameters": {
|
| 60 |
+
"microbatches": 4,
|
| 61 |
+
"placement_strategy": "spread",
|
| 62 |
+
"pipeline": "interleaved",
|
| 63 |
+
"optimize": "speed",
|
| 64 |
+
"partitions": 4,
|
| 65 |
+
"ddp": True,
|
| 66 |
+
},
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
distribution = {"smdistributed": {"modelparallel": smp_options}, "mpi": mpi_options}
|
| 70 |
+
|
| 71 |
+
name_extension = "trainer" if self.script == "run_glue.py" else "smtrainer"
|
| 72 |
+
# creates estimator
|
| 73 |
+
return HuggingFace(
|
| 74 |
+
entry_point=self.script,
|
| 75 |
+
source_dir=self.env.test_path,
|
| 76 |
+
role=self.env.role,
|
| 77 |
+
image_uri=self.env.image_uri,
|
| 78 |
+
base_job_name=f"{self.env.base_job_name}-{instance_count}-smp-{name_extension}",
|
| 79 |
+
instance_count=instance_count,
|
| 80 |
+
instance_type=self.instance_type,
|
| 81 |
+
debugger_hook_config=False,
|
| 82 |
+
hyperparameters={
|
| 83 |
+
**self.env.hyperparameters,
|
| 84 |
+
"model_name_or_path": self.model_name_or_path,
|
| 85 |
+
"max_steps": 500,
|
| 86 |
+
},
|
| 87 |
+
metric_definitions=self.env.metric_definitions,
|
| 88 |
+
distribution=distribution,
|
| 89 |
+
py_version="py36",
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
def save_results_as_csv(self, job_name):
|
| 93 |
+
TrainingJobAnalytics(job_name).export_csv(f"{self.env.test_path}/{job_name}_metrics.csv")
|
| 94 |
+
|
| 95 |
+
# @parameterized.expand([(2,), (4,),])
|
| 96 |
+
@parameterized.expand([(1,)])
|
| 97 |
+
def test_scripz(self, instance_count):
|
| 98 |
+
# create estimator
|
| 99 |
+
estimator = self.create_estimator(instance_count)
|
| 100 |
+
|
| 101 |
+
# run training
|
| 102 |
+
estimator.fit()
|
| 103 |
+
|
| 104 |
+
# result dataframe
|
| 105 |
+
result_metrics_df = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe()
|
| 106 |
+
|
| 107 |
+
# extract kpis
|
| 108 |
+
eval_accuracy = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"])
|
| 109 |
+
eval_loss = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"])
|
| 110 |
+
# get train time from SageMaker job, this includes starting, preprocessing, stopping
|
| 111 |
+
train_runtime = (
|
| 112 |
+
Session().describe_training_job(estimator.latest_training_job.name).get("TrainingTimeInSeconds", 999999)
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# assert kpis
|
| 116 |
+
assert train_runtime <= self.results["train_runtime"]
|
| 117 |
+
assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy)
|
| 118 |
+
assert all(t <= self.results["eval_loss"] for t in eval_loss)
|
| 119 |
+
|
| 120 |
+
# dump tests result into json file to share in PR
|
| 121 |
+
with open(f"{estimator.latest_training_job.name}.json", "w") as outfile:
|
| 122 |
+
json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}, outfile)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_single_node_gpu.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import subprocess
|
| 4 |
+
import unittest
|
| 5 |
+
from ast import literal_eval
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
from parameterized import parameterized_class
|
| 9 |
+
|
| 10 |
+
from . import is_sagemaker_available
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
if is_sagemaker_available():
|
| 14 |
+
from sagemaker import Session, TrainingJobAnalytics
|
| 15 |
+
from sagemaker.huggingface import HuggingFace
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.mark.skipif(
|
| 19 |
+
literal_eval(os.getenv("TEST_SAGEMAKER", "False")) is not True,
|
| 20 |
+
reason="Skipping test because should only be run when releasing minor transformers version",
|
| 21 |
+
)
|
| 22 |
+
@pytest.mark.usefixtures("sm_env")
|
| 23 |
+
@parameterized_class(
|
| 24 |
+
[
|
| 25 |
+
{
|
| 26 |
+
"framework": "pytorch",
|
| 27 |
+
"script": "run_glue.py",
|
| 28 |
+
"model_name_or_path": "distilbert/distilbert-base-cased",
|
| 29 |
+
"instance_type": "ml.g4dn.xlarge",
|
| 30 |
+
"results": {"train_runtime": 650, "eval_accuracy": 0.6, "eval_loss": 0.9},
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"framework": "tensorflow",
|
| 34 |
+
"script": "run_tf.py",
|
| 35 |
+
"model_name_or_path": "distilbert/distilbert-base-cased",
|
| 36 |
+
"instance_type": "ml.g4dn.xlarge",
|
| 37 |
+
"results": {"train_runtime": 600, "eval_accuracy": 0.3, "eval_loss": 0.9},
|
| 38 |
+
},
|
| 39 |
+
]
|
| 40 |
+
)
|
| 41 |
+
class SingleNodeTest(unittest.TestCase):
|
| 42 |
+
def setUp(self):
|
| 43 |
+
if self.framework == "pytorch":
|
| 44 |
+
subprocess.run(
|
| 45 |
+
f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split(),
|
| 46 |
+
encoding="utf-8",
|
| 47 |
+
check=True,
|
| 48 |
+
)
|
| 49 |
+
assert hasattr(self, "env")
|
| 50 |
+
|
| 51 |
+
def create_estimator(self, instance_count=1):
|
| 52 |
+
# creates estimator
|
| 53 |
+
return HuggingFace(
|
| 54 |
+
entry_point=self.script,
|
| 55 |
+
source_dir=self.env.test_path,
|
| 56 |
+
role=self.env.role,
|
| 57 |
+
image_uri=self.env.image_uri,
|
| 58 |
+
base_job_name=f"{self.env.base_job_name}-single",
|
| 59 |
+
instance_count=instance_count,
|
| 60 |
+
instance_type=self.instance_type,
|
| 61 |
+
debugger_hook_config=False,
|
| 62 |
+
hyperparameters={**self.env.hyperparameters, "model_name_or_path": self.model_name_or_path},
|
| 63 |
+
metric_definitions=self.env.metric_definitions,
|
| 64 |
+
py_version="py36",
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
def save_results_as_csv(self, job_name):
|
| 68 |
+
TrainingJobAnalytics(job_name).export_csv(f"{self.env.test_path}/{job_name}_metrics.csv")
|
| 69 |
+
|
| 70 |
+
def test_glue(self):
|
| 71 |
+
# create estimator
|
| 72 |
+
estimator = self.create_estimator()
|
| 73 |
+
|
| 74 |
+
# run training
|
| 75 |
+
estimator.fit()
|
| 76 |
+
|
| 77 |
+
# result dataframe
|
| 78 |
+
result_metrics_df = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe()
|
| 79 |
+
|
| 80 |
+
# extract kpis
|
| 81 |
+
eval_accuracy = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"])
|
| 82 |
+
eval_loss = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"])
|
| 83 |
+
# get train time from SageMaker job, this includes starting, preprocessing, stopping
|
| 84 |
+
train_runtime = (
|
| 85 |
+
Session().describe_training_job(estimator.latest_training_job.name).get("TrainingTimeInSeconds", 999999)
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# assert kpis
|
| 89 |
+
assert train_runtime <= self.results["train_runtime"]
|
| 90 |
+
assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy)
|
| 91 |
+
assert all(t <= self.results["eval_loss"] for t in eval_loss)
|
| 92 |
+
|
| 93 |
+
# dump tests result into json file to share in PR
|
| 94 |
+
with open(f"{estimator.latest_training_job.name}.json", "w") as outfile:
|
| 95 |
+
json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}, outfile)
|