Stage Harbor release files 46501-47000
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/image_segmentation.py +220 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/image_text_to_text.py +432 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/image_to_image.py +136 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/image_to_text.py +216 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/mask_generation.py +287 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/object_detection.py +191 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/pt_utils.py +321 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/question_answering.py +682 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/table_question_answering.py +436 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/text2text_generation.py +376 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/text_classification.py +236 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/text_generation.py +436 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/text_to_audio.py +214 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/token_classification.py +576 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/video_classification.py +184 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/visual_question_answering.py +192 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/zero_shot_audio_classification.py +164 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/zero_shot_classification.py +268 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/zero_shot_image_classification.py +193 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/zero_shot_object_detection.py +235 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/processing_utils.py +1212 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pytorch_utils.py +357 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/__init__.py +15 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/auto.py +197 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/base.py +245 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_aqlm.py +97 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_awq.py +148 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_bitnet.py +115 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_bnb_4bit.py +362 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_bnb_8bit.py +310 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_compressed_tensors.py +124 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_eetq.py +183 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_fbgemm_fp8.py +204 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_gptq.py +94 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_higgs.py +232 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_hqq.py +296 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_quanto.py +208 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_torchao.py +231 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_vptq.py +98 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizers_utils.py +26 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/safetensors_conversion.py +105 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/sagemaker/__init__.py +16 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/sagemaker/trainer_sm.py +30 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/sagemaker/training_args_sm.py +136 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/testing_utils.py +0 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/tf_utils.py +294 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/time_series_utils.py +226 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/tokenization_utils.py +1134 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/tokenization_utils_base.py +0 -0
- tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/tokenization_utils_fast.py +895 -0
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/image_segmentation.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ging, requires_backends
|
| 6 |
+
from .base import Pipeline, build_pipeline_init_args
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
if is_vision_available():
|
| 10 |
+
from PIL import Image
|
| 11 |
+
|
| 12 |
+
from ..image_utils import load_image
|
| 13 |
+
|
| 14 |
+
if is_torch_available():
|
| 15 |
+
from ..models.auto.modeling_auto import (
|
| 16 |
+
MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES,
|
| 17 |
+
MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES,
|
| 18 |
+
MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES,
|
| 19 |
+
MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
Prediction = Dict[str, Any]
|
| 27 |
+
Predictions = List[Prediction]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
|
| 31 |
+
class ImageSegmentationPipeline(Pipeline):
|
| 32 |
+
"""
|
| 33 |
+
Image segmentation pipeline using any `AutoModelForXXXSegmentation`. This pipeline predicts masks of objects and
|
| 34 |
+
their classes.
|
| 35 |
+
|
| 36 |
+
Example:
|
| 37 |
+
|
| 38 |
+
```python
|
| 39 |
+
>>> from transformers import pipeline
|
| 40 |
+
|
| 41 |
+
>>> segmenter = pipeline(model="facebook/detr-resnet-50-panoptic")
|
| 42 |
+
>>> segments = segmenter("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
|
| 43 |
+
>>> len(segments)
|
| 44 |
+
2
|
| 45 |
+
|
| 46 |
+
>>> segments[0]["label"]
|
| 47 |
+
'bird'
|
| 48 |
+
|
| 49 |
+
>>> segments[1]["label"]
|
| 50 |
+
'bird'
|
| 51 |
+
|
| 52 |
+
>>> type(segments[0]["mask"]) # This is a black and white mask showing where is the bird on the original image.
|
| 53 |
+
<class 'PIL.Image.Image'>
|
| 54 |
+
|
| 55 |
+
>>> segments[0]["mask"].size
|
| 56 |
+
(768, 512)
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
This image segmentation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 61 |
+
`"image-segmentation"`.
|
| 62 |
+
|
| 63 |
+
See the list of available models on
|
| 64 |
+
[huggingface.co/models](https://huggingface.co/models?filter=image-segmentation).
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def __init__(self, *args, **kwargs):
|
| 68 |
+
super().__init__(*args, **kwargs)
|
| 69 |
+
|
| 70 |
+
if self.framework == "tf":
|
| 71 |
+
raise ValueError(f"The {self.__class__} is only available in PyTorch.")
|
| 72 |
+
|
| 73 |
+
requires_backends(self, "vision")
|
| 74 |
+
mapping = MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES.copy()
|
| 75 |
+
mapping.update(MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES)
|
| 76 |
+
mapping.update(MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES)
|
| 77 |
+
mapping.update(MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES)
|
| 78 |
+
self.check_model_type(mapping)
|
| 79 |
+
|
| 80 |
+
def _sanitize_parameters(self, **kwargs):
|
| 81 |
+
preprocess_kwargs = {}
|
| 82 |
+
postprocess_kwargs = {}
|
| 83 |
+
if "subtask" in kwargs:
|
| 84 |
+
postprocess_kwargs["subtask"] = kwargs["subtask"]
|
| 85 |
+
preprocess_kwargs["subtask"] = kwargs["subtask"]
|
| 86 |
+
if "threshold" in kwargs:
|
| 87 |
+
postprocess_kwargs["threshold"] = kwargs["threshold"]
|
| 88 |
+
if "mask_threshold" in kwargs:
|
| 89 |
+
postprocess_kwargs["mask_threshold"] = kwargs["mask_threshold"]
|
| 90 |
+
if "overlap_mask_area_threshold" in kwargs:
|
| 91 |
+
postprocess_kwargs["overlap_mask_area_threshold"] = kwargs["overlap_mask_area_threshold"]
|
| 92 |
+
if "timeout" in kwargs:
|
| 93 |
+
preprocess_kwargs["timeout"] = kwargs["timeout"]
|
| 94 |
+
|
| 95 |
+
return preprocess_kwargs, {}, postprocess_kwargs
|
| 96 |
+
|
| 97 |
+
def __call__(self, inputs=None, **kwargs) -> Union[Predictions, List[Prediction]]:
|
| 98 |
+
"""
|
| 99 |
+
Perform segmentation (detect masks & classes) in the image(s) passed as inputs.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
|
| 103 |
+
The pipeline handles three types of images:
|
| 104 |
+
|
| 105 |
+
- A string containing an HTTP(S) link pointing to an image
|
| 106 |
+
- A string containing a local path to an image
|
| 107 |
+
- An image loaded in PIL directly
|
| 108 |
+
|
| 109 |
+
The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the
|
| 110 |
+
same format: all as HTTP(S) links, all as local paths, or all as PIL images.
|
| 111 |
+
subtask (`str`, *optional*):
|
| 112 |
+
Segmentation task to be performed, choose [`semantic`, `instance` and `panoptic`] depending on model
|
| 113 |
+
capabilities. If not set, the pipeline will attempt tp resolve in the following order:
|
| 114 |
+
`panoptic`, `instance`, `semantic`.
|
| 115 |
+
threshold (`float`, *optional*, defaults to 0.9):
|
| 116 |
+
Probability threshold to filter out predicted masks.
|
| 117 |
+
mask_threshold (`float`, *optional*, defaults to 0.5):
|
| 118 |
+
Threshold to use when turning the predicted masks into binary values.
|
| 119 |
+
overlap_mask_area_threshold (`float`, *optional*, defaults to 0.5):
|
| 120 |
+
Mask overlap threshold to eliminate small, disconnected segments.
|
| 121 |
+
timeout (`float`, *optional*, defaults to None):
|
| 122 |
+
The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
|
| 123 |
+
the call may block forever.
|
| 124 |
+
|
| 125 |
+
Return:
|
| 126 |
+
A dictionary or a list of dictionaries containing the result. If the input is a single image, will return a
|
| 127 |
+
list of dictionaries, if the input is a list of several images, will return a list of list of dictionaries
|
| 128 |
+
corresponding to each image.
|
| 129 |
+
|
| 130 |
+
The dictionaries contain the mask, label and score (where applicable) of each detected object and contains
|
| 131 |
+
the following keys:
|
| 132 |
+
|
| 133 |
+
- **label** (`str`) -- The class label identified by the model.
|
| 134 |
+
- **mask** (`PIL.Image`) -- A binary mask of the detected object as a Pil Image of shape (width, height) of
|
| 135 |
+
the original image. Returns a mask filled with zeros if no object is found.
|
| 136 |
+
- **score** (*optional* `float`) -- Optionally, when the model is capable of estimating a confidence of the
|
| 137 |
+
"object" described by the label and the mask.
|
| 138 |
+
"""
|
| 139 |
+
# After deprecation of this is completed, remove the default `None` value for `images`
|
| 140 |
+
if "images" in kwargs:
|
| 141 |
+
inputs = kwargs.pop("images")
|
| 142 |
+
if inputs is None:
|
| 143 |
+
raise ValueError("Cannot call the image-classification pipeline without an inputs argument!")
|
| 144 |
+
return super().__call__(inputs, **kwargs)
|
| 145 |
+
|
| 146 |
+
def preprocess(self, image, subtask=None, timeout=None):
|
| 147 |
+
image = load_image(image, timeout=timeout)
|
| 148 |
+
target_size = [(image.height, image.width)]
|
| 149 |
+
if self.model.config.__class__.__name__ == "OneFormerConfig":
|
| 150 |
+
if subtask is None:
|
| 151 |
+
kwargs = {}
|
| 152 |
+
else:
|
| 153 |
+
kwargs = {"task_inputs": [subtask]}
|
| 154 |
+
inputs = self.image_processor(images=[image], return_tensors="pt", **kwargs)
|
| 155 |
+
if self.framework == "pt":
|
| 156 |
+
inputs = inputs.to(self.torch_dtype)
|
| 157 |
+
inputs["task_inputs"] = self.tokenizer(
|
| 158 |
+
inputs["task_inputs"],
|
| 159 |
+
padding="max_length",
|
| 160 |
+
max_length=self.model.config.task_seq_len,
|
| 161 |
+
return_tensors=self.framework,
|
| 162 |
+
)["input_ids"]
|
| 163 |
+
else:
|
| 164 |
+
inputs = self.image_processor(images=[image], return_tensors="pt")
|
| 165 |
+
if self.framework == "pt":
|
| 166 |
+
inputs = inputs.to(self.torch_dtype)
|
| 167 |
+
inputs["target_size"] = target_size
|
| 168 |
+
return inputs
|
| 169 |
+
|
| 170 |
+
def _forward(self, model_inputs):
|
| 171 |
+
target_size = model_inputs.pop("target_size")
|
| 172 |
+
model_outputs = self.model(**model_inputs)
|
| 173 |
+
model_outputs["target_size"] = target_size
|
| 174 |
+
return model_outputs
|
| 175 |
+
|
| 176 |
+
def postprocess(
|
| 177 |
+
self, model_outputs, subtask=None, threshold=0.9, mask_threshold=0.5, overlap_mask_area_threshold=0.5
|
| 178 |
+
):
|
| 179 |
+
fn = None
|
| 180 |
+
if subtask in {"panoptic", None} and hasattr(self.image_processor, "post_process_panoptic_segmentation"):
|
| 181 |
+
fn = self.image_processor.post_process_panoptic_segmentation
|
| 182 |
+
elif subtask in {"instance", None} and hasattr(self.image_processor, "post_process_instance_segmentation"):
|
| 183 |
+
fn = self.image_processor.post_process_instance_segmentation
|
| 184 |
+
|
| 185 |
+
if fn is not None:
|
| 186 |
+
outputs = fn(
|
| 187 |
+
model_outputs,
|
| 188 |
+
threshold=threshold,
|
| 189 |
+
mask_threshold=mask_threshold,
|
| 190 |
+
overlap_mask_area_threshold=overlap_mask_area_threshold,
|
| 191 |
+
target_sizes=model_outputs["target_size"],
|
| 192 |
+
)[0]
|
| 193 |
+
|
| 194 |
+
annotation = []
|
| 195 |
+
segmentation = outputs["segmentation"]
|
| 196 |
+
|
| 197 |
+
for segment in outputs["segments_info"]:
|
| 198 |
+
mask = (segmentation == segment["id"]) * 255
|
| 199 |
+
mask = Image.fromarray(mask.numpy().astype(np.uint8), mode="L")
|
| 200 |
+
label = self.model.config.id2label[segment["label_id"]]
|
| 201 |
+
score = segment["score"]
|
| 202 |
+
annotation.append({"score": score, "label": label, "mask": mask})
|
| 203 |
+
|
| 204 |
+
elif subtask in {"semantic", None} and hasattr(self.image_processor, "post_process_semantic_segmentation"):
|
| 205 |
+
outputs = self.image_processor.post_process_semantic_segmentation(
|
| 206 |
+
model_outputs, target_sizes=model_outputs["target_size"]
|
| 207 |
+
)[0]
|
| 208 |
+
|
| 209 |
+
annotation = []
|
| 210 |
+
segmentation = outputs.numpy()
|
| 211 |
+
labels = np.unique(segmentation)
|
| 212 |
+
|
| 213 |
+
for label in labels:
|
| 214 |
+
mask = (segmentation == label) * 255
|
| 215 |
+
mask = Image.fromarray(mask.astype(np.uint8), mode="L")
|
| 216 |
+
label = self.model.config.id2label[label]
|
| 217 |
+
annotation.append({"score": None, "label": label, "mask": mask})
|
| 218 |
+
else:
|
| 219 |
+
raise ValueError(f"Subtask {subtask} is not supported for model {type(self.model)}")
|
| 220 |
+
return annotation
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/image_text_to_text.py
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
|
| 16 |
+
import enum
|
| 17 |
+
from typing import Dict, List, Optional, Union
|
| 18 |
+
|
| 19 |
+
from ..processing_utils import ProcessingKwargs, Unpack
|
| 20 |
+
from ..utils import (
|
| 21 |
+
add_end_docstrings,
|
| 22 |
+
is_torch_available,
|
| 23 |
+
is_vision_available,
|
| 24 |
+
logging,
|
| 25 |
+
requires_backends,
|
| 26 |
+
)
|
| 27 |
+
from .base import Pipeline, build_pipeline_init_args
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_vision_available():
|
| 31 |
+
from PIL import Image
|
| 32 |
+
|
| 33 |
+
from ..image_utils import load_images, valid_images
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if is_torch_available():
|
| 37 |
+
from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES
|
| 38 |
+
from .pt_utils import KeyDataset
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
IMAGE_TOKEN = "<image>"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class ReturnType(enum.Enum):
|
| 46 |
+
TENSORS = 0
|
| 47 |
+
NEW_TEXT = 1
|
| 48 |
+
FULL_TEXT = 2
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class Chat:
|
| 52 |
+
"""This class is intended to just be used internally in this pipeline and not exposed to users. We convert chats
|
| 53 |
+
to this format because the rest of the pipeline code tends to assume that lists of messages are
|
| 54 |
+
actually a batch of samples rather than messages in the same conversation."""
|
| 55 |
+
|
| 56 |
+
def __init__(self, messages: Dict, images: Union[str, List[str], "Image.Image", List["Image.Image"]]):
|
| 57 |
+
for message in messages:
|
| 58 |
+
if not ("role" in message and "content" in message):
|
| 59 |
+
raise ValueError("When passing chat dicts as input, each dict must have a 'role' and 'content' key.")
|
| 60 |
+
images = retrieve_images_in_messages(messages, images)
|
| 61 |
+
|
| 62 |
+
self.messages = messages
|
| 63 |
+
self.images = images
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def retrieve_images_in_messages(
|
| 67 |
+
messages: dict, images: Optional[Union[str, List[str], "Image.Image", List["Image.Image"]]]
|
| 68 |
+
):
|
| 69 |
+
"""
|
| 70 |
+
Retrieve and combine images from the chat and the images passed as input.
|
| 71 |
+
"""
|
| 72 |
+
if images is None:
|
| 73 |
+
images = []
|
| 74 |
+
idx_images = 0
|
| 75 |
+
retrieved_images = []
|
| 76 |
+
for message in messages:
|
| 77 |
+
for content in message["content"]:
|
| 78 |
+
if isinstance(content, dict):
|
| 79 |
+
if content.get("type") == "image":
|
| 80 |
+
for key in ["image", "url", "path", "base64"]:
|
| 81 |
+
if key in content:
|
| 82 |
+
retrieved_images.append(content[key])
|
| 83 |
+
break
|
| 84 |
+
else:
|
| 85 |
+
if idx_images < len(images):
|
| 86 |
+
retrieved_images.append(images[idx_images])
|
| 87 |
+
idx_images += 1
|
| 88 |
+
else:
|
| 89 |
+
raise ValueError(
|
| 90 |
+
"The number of images in the chat messages should be the same as the number of images passed to the pipeline."
|
| 91 |
+
)
|
| 92 |
+
# Add support for OpenAI/TGI chat format
|
| 93 |
+
elif content.get("type") == "image_url":
|
| 94 |
+
if isinstance(content.get("image_url"), dict) and "url" in content["image_url"]:
|
| 95 |
+
retrieved_images.append(content["image_url"]["url"])
|
| 96 |
+
# Rewrite content to be in the Transformers chat format
|
| 97 |
+
content["type"] = "image"
|
| 98 |
+
content["image"] = content["image_url"]["url"]
|
| 99 |
+
del content["image_url"]
|
| 100 |
+
else:
|
| 101 |
+
raise ValueError(
|
| 102 |
+
"Wrong format for 'image_url' content type. The content should have an 'image_url' dict with a 'url' key."
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
# The number of images passed should be consistent with the number of images in the chat without an image key
|
| 106 |
+
if idx_images != len(images):
|
| 107 |
+
raise ValueError(
|
| 108 |
+
"The number of images in the chat messages should be the same as the number of images passed to the pipeline."
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
return retrieved_images
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@add_end_docstrings(build_pipeline_init_args(has_processor=True))
|
| 115 |
+
class ImageTextToTextPipeline(Pipeline):
|
| 116 |
+
"""
|
| 117 |
+
Image-text-to-text pipeline using an `AutoModelForImageTextToText`. This pipeline generates text given an image and text.
|
| 118 |
+
When the underlying model is a conversational model, it can also accept one or more chats,
|
| 119 |
+
in which case the pipeline will operate in chat mode and will continue the chat(s) by adding its response(s).
|
| 120 |
+
Each chat takes the form of a list of dicts, where each dict contains "role" and "content" keys.
|
| 121 |
+
|
| 122 |
+
Example:
|
| 123 |
+
|
| 124 |
+
```python
|
| 125 |
+
>>> from transformers import pipeline
|
| 126 |
+
|
| 127 |
+
>>> pipe = pipeline(task="image-text-to-text", model="Salesforce/blip-image-captioning-base")
|
| 128 |
+
>>> pipe("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", text="A photo of")
|
| 129 |
+
[{'generated_text': 'a photo of two birds'}]
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
```python
|
| 133 |
+
>>> from transformers import pipeline
|
| 134 |
+
|
| 135 |
+
>>> pipe = pipeline("image-text-to-text", model="llava-hf/llava-interleave-qwen-0.5b-hf")
|
| 136 |
+
>>> messages = [
|
| 137 |
+
>>> {
|
| 138 |
+
>>> "role": "user",
|
| 139 |
+
>>> "content": [
|
| 140 |
+
>>> {
|
| 141 |
+
>>> "type": "image",
|
| 142 |
+
>>> "url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
|
| 143 |
+
>>> },
|
| 144 |
+
>>> {"type": "text", "text": "Describe this image."},
|
| 145 |
+
>>> ],
|
| 146 |
+
>>> },
|
| 147 |
+
>>> {
|
| 148 |
+
>>> "role": "assistant",
|
| 149 |
+
>>> "content": [
|
| 150 |
+
>>> {"type": "text", "text": "There is a dog and"},
|
| 151 |
+
>>> ],
|
| 152 |
+
>>> },
|
| 153 |
+
>>> ]
|
| 154 |
+
>>> pipe(text=messages, max_new_tokens=20, return_full_text=False)
|
| 155 |
+
[{'input_text': [{'role': 'user',
|
| 156 |
+
'content': [{'type': 'image',
|
| 157 |
+
'url': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'},
|
| 158 |
+
{'type': 'text', 'text': 'Describe this image.'}]},
|
| 159 |
+
{'role': 'assistant',
|
| 160 |
+
'content': [{'type': 'text', 'text': 'There is a dog and'}]}],
|
| 161 |
+
'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}]
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
| 165 |
+
|
| 166 |
+
This image-text to text pipeline can currently be loaded from pipeline() using the following task identifier:
|
| 167 |
+
"image-text-to-text".
|
| 168 |
+
|
| 169 |
+
See the list of available models on
|
| 170 |
+
[huggingface.co/models](https://huggingface.co/models?pipeline_tag=image-text-to-text).
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
_load_processor = True
|
| 174 |
+
_load_image_processor = False
|
| 175 |
+
_load_feature_extractor = False
|
| 176 |
+
_load_tokenizer = False
|
| 177 |
+
|
| 178 |
+
def __init__(self, *args, **kwargs):
|
| 179 |
+
super().__init__(*args, **kwargs)
|
| 180 |
+
requires_backends(self, "vision")
|
| 181 |
+
self.check_model_type(MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES)
|
| 182 |
+
|
| 183 |
+
def _sanitize_parameters(
|
| 184 |
+
self,
|
| 185 |
+
max_new_tokens=None,
|
| 186 |
+
generate_kwargs=None,
|
| 187 |
+
timeout=None,
|
| 188 |
+
return_full_text=None,
|
| 189 |
+
return_tensors=None,
|
| 190 |
+
return_type=None,
|
| 191 |
+
continue_final_message=None,
|
| 192 |
+
**kwargs: Unpack[ProcessingKwargs],
|
| 193 |
+
):
|
| 194 |
+
forward_kwargs = {}
|
| 195 |
+
preprocess_params = {}
|
| 196 |
+
postprocess_params = {}
|
| 197 |
+
|
| 198 |
+
preprocess_params["processing_kwargs"] = kwargs
|
| 199 |
+
|
| 200 |
+
if timeout is not None:
|
| 201 |
+
preprocess_params["timeout"] = timeout
|
| 202 |
+
|
| 203 |
+
if continue_final_message is not None:
|
| 204 |
+
preprocess_params["continue_final_message"] = continue_final_message
|
| 205 |
+
|
| 206 |
+
if generate_kwargs is not None:
|
| 207 |
+
forward_kwargs["generate_kwargs"] = generate_kwargs
|
| 208 |
+
|
| 209 |
+
if max_new_tokens is not None:
|
| 210 |
+
if "generate_kwargs" not in forward_kwargs:
|
| 211 |
+
forward_kwargs["generate_kwargs"] = {}
|
| 212 |
+
if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
|
| 213 |
+
raise ValueError(
|
| 214 |
+
"'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,"
|
| 215 |
+
" please use only one"
|
| 216 |
+
)
|
| 217 |
+
forward_kwargs["generate_kwargs"]["max_new_tokens"] = max_new_tokens
|
| 218 |
+
|
| 219 |
+
if return_full_text is not None and return_type is None:
|
| 220 |
+
if return_tensors is not None:
|
| 221 |
+
raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`")
|
| 222 |
+
return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
|
| 223 |
+
if return_tensors is not None and return_type is None:
|
| 224 |
+
return_type = ReturnType.TENSORS
|
| 225 |
+
if return_type is not None:
|
| 226 |
+
postprocess_params["return_type"] = return_type
|
| 227 |
+
if continue_final_message is not None:
|
| 228 |
+
postprocess_params["continue_final_message"] = continue_final_message
|
| 229 |
+
|
| 230 |
+
return preprocess_params, forward_kwargs, postprocess_params
|
| 231 |
+
|
| 232 |
+
def __call__(
|
| 233 |
+
self,
|
| 234 |
+
images: Optional[
|
| 235 |
+
Union[str, List[str], List[List[str]], "Image.Image", List["Image.Image"], List[List["Image.Image"]]]
|
| 236 |
+
] = None,
|
| 237 |
+
text: Optional[Union[str, List[str], List[dict]]] = None,
|
| 238 |
+
**kwargs,
|
| 239 |
+
):
|
| 240 |
+
"""
|
| 241 |
+
Generate a text given text and the image(s) passed as inputs.
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
images (`str`, `List[str]`, `PIL.Image or `List[PIL.Image]`):
|
| 245 |
+
The pipeline handles three types of images:
|
| 246 |
+
|
| 247 |
+
- A string containing a HTTP(s) link pointing to an image
|
| 248 |
+
- A string containing a local path to an image
|
| 249 |
+
- An image loaded in PIL directly
|
| 250 |
+
|
| 251 |
+
The pipeline accepts either a single image or a batch of images.
|
| 252 |
+
text (str, List[str], `List[Dict[str, Union[str, PIL.Image]]]`):
|
| 253 |
+
The text to be used for generation. If a list of strings is passed, the length of the list should be the
|
| 254 |
+
same as the number of images. Text can also follow the chat format: a list of dictionaries where each
|
| 255 |
+
dictionary represents a message in a conversation. Each dictionary should have two keys: 'role' and
|
| 256 |
+
'content'. 'role' should be one of 'user', 'system' or 'assistant'. 'content' should be a list of dictionary
|
| 257 |
+
containing the text of the message and the type of the message. The type of the message can be either
|
| 258 |
+
'text' or 'image'. If the type is 'image', no text is needed.
|
| 259 |
+
return_tensors (`bool`, *optional*, defaults to `False`):
|
| 260 |
+
Returns the tensors of predictions (as token indices) in the outputs. If set to
|
| 261 |
+
`True`, the decoded text is not returned.
|
| 262 |
+
return_text (`bool`, *optional*):
|
| 263 |
+
Returns the decoded texts in the outputs.
|
| 264 |
+
return_full_text (`bool`, *optional*, defaults to `True`):
|
| 265 |
+
If set to `False` only added text is returned, otherwise the full text is returned. Cannot be
|
| 266 |
+
specified at the same time as `return_text`.
|
| 267 |
+
continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the
|
| 268 |
+
last message in the input chat rather than starting a new one, allowing you to "prefill" its response.
|
| 269 |
+
By default this is `True` when the final message in the input chat has the `assistant` role and
|
| 270 |
+
`False` otherwise, but you can manually override that behaviour by setting this flag.
|
| 271 |
+
|
| 272 |
+
Return:
|
| 273 |
+
A list or a list of list of `dict`: Each result comes as a dictionary with the following key (cannot return a combination
|
| 274 |
+
of both `generated_text` and `generated_token_ids`):
|
| 275 |
+
|
| 276 |
+
- **generated_text** (`str`, present when `return_text=True`) -- The generated text.
|
| 277 |
+
- **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True`) -- The token
|
| 278 |
+
ids of the generated text.
|
| 279 |
+
- **input_text** (`str`) -- The input text.
|
| 280 |
+
"""
|
| 281 |
+
if images is None and text is None:
|
| 282 |
+
raise ValueError("You must at least provide either text or images.")
|
| 283 |
+
if images is not None and text is None and not valid_images(images):
|
| 284 |
+
"""
|
| 285 |
+
Supports the following format
|
| 286 |
+
- {"image": image, "text": text}
|
| 287 |
+
- [{"image": image, "text": text}]
|
| 288 |
+
- Generator and datasets
|
| 289 |
+
This is a common pattern in other multimodal pipelines, so we support it here as well.
|
| 290 |
+
"""
|
| 291 |
+
return super().__call__(images, **kwargs)
|
| 292 |
+
|
| 293 |
+
if isinstance(text, (list, tuple, KeyDataset)) and isinstance(text[0], (list, tuple, dict)):
|
| 294 |
+
# We have one or more prompts in list-of-dicts format, so this is chat mode
|
| 295 |
+
if isinstance(text[0], dict):
|
| 296 |
+
return super().__call__(Chat(text, images), **kwargs)
|
| 297 |
+
else:
|
| 298 |
+
if images is None:
|
| 299 |
+
images = [None] * len(text)
|
| 300 |
+
chats = [Chat(chat, image) for chat, image in zip(text, images)] # 🐈 🐈 🐈
|
| 301 |
+
return super().__call__(chats, **kwargs)
|
| 302 |
+
|
| 303 |
+
# encourage the user to use the chat format if supported
|
| 304 |
+
if getattr(self.processor, "chat_template", None) is not None:
|
| 305 |
+
logger.warning_once(
|
| 306 |
+
"The input data was not formatted as a chat with dicts containing 'role' and 'content' keys, even though this model supports chat. "
|
| 307 |
+
"Consider using the chat format for better results. For more information, see https://huggingface.co/docs/transformers/en/chat_templating"
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
# support text only generation
|
| 311 |
+
if images is None:
|
| 312 |
+
return super().__call__(text, **kwargs)
|
| 313 |
+
if text is None:
|
| 314 |
+
raise ValueError("You must provide text for this pipeline.")
|
| 315 |
+
|
| 316 |
+
return super().__call__({"images": images, "text": text}, **kwargs)
|
| 317 |
+
|
| 318 |
+
def preprocess(self, inputs=None, timeout=None, continue_final_message=None, processing_kwargs=None):
|
| 319 |
+
# In case we only have text inputs
|
| 320 |
+
if isinstance(inputs, (list, tuple, str)):
|
| 321 |
+
images = None
|
| 322 |
+
text = inputs
|
| 323 |
+
inputs_text = inputs
|
| 324 |
+
else:
|
| 325 |
+
if isinstance(inputs, Chat):
|
| 326 |
+
# If the user passes a chat that ends in an assistant message, we treat it as a prefill by default
|
| 327 |
+
# because very few models support multiple separate, consecutive assistant messages
|
| 328 |
+
if continue_final_message is None:
|
| 329 |
+
continue_final_message = inputs.messages[-1]["role"] == "assistant"
|
| 330 |
+
text = self.processor.apply_chat_template(
|
| 331 |
+
inputs.messages,
|
| 332 |
+
add_generation_prompt=not continue_final_message,
|
| 333 |
+
continue_final_message=continue_final_message,
|
| 334 |
+
return_tensors=self.framework,
|
| 335 |
+
)
|
| 336 |
+
inputs_text = inputs
|
| 337 |
+
images = inputs.images
|
| 338 |
+
else:
|
| 339 |
+
text = inputs["text"]
|
| 340 |
+
inputs_text = inputs["text"]
|
| 341 |
+
images = inputs["images"]
|
| 342 |
+
|
| 343 |
+
images = load_images(images)
|
| 344 |
+
|
| 345 |
+
# if batched text inputs, we set padding to True unless specified otherwise
|
| 346 |
+
if isinstance(text, (list, tuple)) and len(text) > 1:
|
| 347 |
+
processing_kwargs.setdefault("padding", True)
|
| 348 |
+
model_inputs = self.processor(
|
| 349 |
+
images=images, text=text, return_tensors=self.framework, legacy=False, **processing_kwargs
|
| 350 |
+
).to(dtype=self.torch_dtype)
|
| 351 |
+
|
| 352 |
+
model_inputs["text"] = inputs_text
|
| 353 |
+
|
| 354 |
+
return model_inputs
|
| 355 |
+
|
| 356 |
+
def _forward(self, model_inputs, generate_kwargs=None):
|
| 357 |
+
generate_kwargs = {} if generate_kwargs is None else generate_kwargs
|
| 358 |
+
prompt_text = model_inputs.pop("text")
|
| 359 |
+
input_ids = (
|
| 360 |
+
model_inputs["input_ids"] if "input_ids" in model_inputs else model_inputs["decoder_input_ids"]
|
| 361 |
+
) # for decoder-only models
|
| 362 |
+
generated_sequence = self.model.generate(**model_inputs, **generate_kwargs)
|
| 363 |
+
|
| 364 |
+
return {"generated_sequence": generated_sequence, "prompt_text": prompt_text, "input_ids": input_ids}
|
| 365 |
+
|
| 366 |
+
def postprocess(self, model_outputs, return_type=ReturnType.FULL_TEXT, continue_final_message=None):
|
| 367 |
+
input_texts = model_outputs["prompt_text"]
|
| 368 |
+
input_texts = [input_texts] if isinstance(input_texts, (str, Chat)) else input_texts
|
| 369 |
+
generated_sequence = model_outputs["generated_sequence"]
|
| 370 |
+
input_ids = model_outputs["input_ids"]
|
| 371 |
+
if return_type == ReturnType.TENSORS:
|
| 372 |
+
return [
|
| 373 |
+
{"input_text": input_texts[i], "generated_token_ids": generated_sequence[i]}
|
| 374 |
+
for i in range(len(input_texts))
|
| 375 |
+
]
|
| 376 |
+
|
| 377 |
+
# Decode inputs and outputs the same way to remove input text from generated text if present
|
| 378 |
+
generated_texts = self.processor.post_process_image_text_to_text(generated_sequence)
|
| 379 |
+
decoded_inputs = self.processor.post_process_image_text_to_text(input_ids)
|
| 380 |
+
|
| 381 |
+
# Force consistent behavior for including the input text in the output
|
| 382 |
+
if return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
|
| 383 |
+
# Remove the input text from the generated text if the generated text starts with the input text
|
| 384 |
+
# (accounting for the possibility of a space between the input and generated text)
|
| 385 |
+
new_generated_texts = []
|
| 386 |
+
for text_generated, decoded_input in zip(generated_texts, decoded_inputs):
|
| 387 |
+
# There can be added characters before the input text, so we need to find the beginning of the input text in the generated text
|
| 388 |
+
index_input_text = text_generated.find(decoded_input)
|
| 389 |
+
# Limit the search to 2 residual characters, like spaces or new lines, to avoid removing a large part of the answer
|
| 390 |
+
if 0 <= index_input_text <= 2:
|
| 391 |
+
# If the input text is found, we remove it
|
| 392 |
+
new_generated_texts.append(text_generated[index_input_text + len(decoded_input) :])
|
| 393 |
+
else:
|
| 394 |
+
new_generated_texts.append(text_generated)
|
| 395 |
+
generated_texts = new_generated_texts
|
| 396 |
+
if return_type == ReturnType.FULL_TEXT:
|
| 397 |
+
full_texts = []
|
| 398 |
+
for prompt_text, generated_text in zip(input_texts, generated_texts):
|
| 399 |
+
if isinstance(prompt_text, str):
|
| 400 |
+
generated_text = prompt_text + generated_text
|
| 401 |
+
elif isinstance(prompt_text, Chat):
|
| 402 |
+
if continue_final_message is None:
|
| 403 |
+
# If the user passes a chat ending in an assistant message, we treat it as a prefill by
|
| 404 |
+
# default because very few models support multiple separate, consecutive assistant messages
|
| 405 |
+
continue_final_message = prompt_text.messages[-1]["role"] == "assistant"
|
| 406 |
+
if continue_final_message:
|
| 407 |
+
# With assistant prefill, concat onto the end of the last message
|
| 408 |
+
new_text = dict(prompt_text.messages[-1]["content"][-1].items())
|
| 409 |
+
new_text["text"] += generated_text
|
| 410 |
+
generated_text = list(prompt_text.messages)[:-1] + [
|
| 411 |
+
{
|
| 412 |
+
"role": prompt_text.messages[-1]["role"],
|
| 413 |
+
"content": prompt_text.messages[-1]["content"][:-1] + [new_text],
|
| 414 |
+
}
|
| 415 |
+
]
|
| 416 |
+
else:
|
| 417 |
+
# When we're not starting from a prefill, the output is a new assistant message
|
| 418 |
+
generated_text = list(prompt_text.messages) + [
|
| 419 |
+
{"role": "assistant", "content": generated_text}
|
| 420 |
+
]
|
| 421 |
+
full_texts.append(generated_text)
|
| 422 |
+
generated_texts = full_texts
|
| 423 |
+
|
| 424 |
+
records = [
|
| 425 |
+
{
|
| 426 |
+
"input_text": input_text.messages if isinstance(input_text, Chat) else input_text,
|
| 427 |
+
"generated_text": generated_text,
|
| 428 |
+
}
|
| 429 |
+
for input_text, generated_text in zip(input_texts, generated_texts)
|
| 430 |
+
]
|
| 431 |
+
|
| 432 |
+
return records
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/image_to_image.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from typing import List, Union
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
from ..utils import (
|
| 19 |
+
add_end_docstrings,
|
| 20 |
+
is_torch_available,
|
| 21 |
+
is_vision_available,
|
| 22 |
+
logging,
|
| 23 |
+
requires_backends,
|
| 24 |
+
)
|
| 25 |
+
from .base import Pipeline, build_pipeline_init_args
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_vision_available():
|
| 29 |
+
from PIL import Image
|
| 30 |
+
|
| 31 |
+
from ..image_utils import load_image
|
| 32 |
+
|
| 33 |
+
if is_torch_available():
|
| 34 |
+
from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES
|
| 35 |
+
|
| 36 |
+
logger = logging.get_logger(__name__)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
|
| 40 |
+
class ImageToImagePipeline(Pipeline):
|
| 41 |
+
"""
|
| 42 |
+
Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous
|
| 43 |
+
image input.
|
| 44 |
+
|
| 45 |
+
Example:
|
| 46 |
+
|
| 47 |
+
```python
|
| 48 |
+
>>> from PIL import Image
|
| 49 |
+
>>> import requests
|
| 50 |
+
|
| 51 |
+
>>> from transformers import pipeline
|
| 52 |
+
|
| 53 |
+
>>> upscaler = pipeline("image-to-image", model="caidas/swin2SR-classical-sr-x2-64")
|
| 54 |
+
>>> img = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)
|
| 55 |
+
>>> img = img.resize((64, 64))
|
| 56 |
+
>>> upscaled_img = upscaler(img)
|
| 57 |
+
>>> img.size
|
| 58 |
+
(64, 64)
|
| 59 |
+
|
| 60 |
+
>>> upscaled_img.size
|
| 61 |
+
(144, 144)
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
This image to image pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 65 |
+
`"image-to-image"`.
|
| 66 |
+
|
| 67 |
+
See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=image-to-image).
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def __init__(self, *args, **kwargs):
|
| 71 |
+
super().__init__(*args, **kwargs)
|
| 72 |
+
requires_backends(self, "vision")
|
| 73 |
+
self.check_model_type(MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES)
|
| 74 |
+
|
| 75 |
+
def _sanitize_parameters(self, **kwargs):
|
| 76 |
+
preprocess_params = {}
|
| 77 |
+
postprocess_params = {}
|
| 78 |
+
forward_params = {}
|
| 79 |
+
|
| 80 |
+
if "timeout" in kwargs:
|
| 81 |
+
preprocess_params["timeout"] = kwargs["timeout"]
|
| 82 |
+
if "head_mask" in kwargs:
|
| 83 |
+
forward_params["head_mask"] = kwargs["head_mask"]
|
| 84 |
+
|
| 85 |
+
return preprocess_params, forward_params, postprocess_params
|
| 86 |
+
|
| 87 |
+
def __call__(
|
| 88 |
+
self, images: Union[str, List[str], "Image.Image", List["Image.Image"]], **kwargs
|
| 89 |
+
) -> Union["Image.Image", List["Image.Image"]]:
|
| 90 |
+
"""
|
| 91 |
+
Transform the image(s) passed as inputs.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
images (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
|
| 95 |
+
The pipeline handles three types of images:
|
| 96 |
+
|
| 97 |
+
- A string containing a http link pointing to an image
|
| 98 |
+
- A string containing a local path to an image
|
| 99 |
+
- An image loaded in PIL directly
|
| 100 |
+
|
| 101 |
+
The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
|
| 102 |
+
Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
|
| 103 |
+
images.
|
| 104 |
+
timeout (`float`, *optional*, defaults to None):
|
| 105 |
+
The maximum time in seconds to wait for fetching images from the web. If None, no timeout is used and
|
| 106 |
+
the call may block forever.
|
| 107 |
+
|
| 108 |
+
Return:
|
| 109 |
+
An image (Image.Image) or a list of images (List["Image.Image"]) containing result(s). If the input is a
|
| 110 |
+
single image, the return will be also a single image, if the input is a list of several images, it will
|
| 111 |
+
return a list of transformed images.
|
| 112 |
+
"""
|
| 113 |
+
return super().__call__(images, **kwargs)
|
| 114 |
+
|
| 115 |
+
def _forward(self, model_inputs):
|
| 116 |
+
model_outputs = self.model(**model_inputs)
|
| 117 |
+
return model_outputs
|
| 118 |
+
|
| 119 |
+
def preprocess(self, image, timeout=None):
|
| 120 |
+
image = load_image(image, timeout=timeout)
|
| 121 |
+
inputs = self.image_processor(images=[image], return_tensors="pt")
|
| 122 |
+
if self.framework == "pt":
|
| 123 |
+
inputs = inputs.to(self.torch_dtype)
|
| 124 |
+
return inputs
|
| 125 |
+
|
| 126 |
+
def postprocess(self, model_outputs):
|
| 127 |
+
images = []
|
| 128 |
+
if "reconstruction" in model_outputs.keys():
|
| 129 |
+
outputs = model_outputs.reconstruction
|
| 130 |
+
for output in outputs:
|
| 131 |
+
output = output.data.squeeze().float().cpu().clamp_(0, 1).numpy()
|
| 132 |
+
output = np.moveaxis(output, source=0, destination=-1)
|
| 133 |
+
output = (output * 255.0).round().astype(np.uint8) # float32 to uint8
|
| 134 |
+
images.append(Image.fromarray(output))
|
| 135 |
+
|
| 136 |
+
return images if len(images) > 1 else images[0]
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/image_to_text.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 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 |
+
|
| 16 |
+
from typing import List, Union
|
| 17 |
+
|
| 18 |
+
from ..utils import (
|
| 19 |
+
add_end_docstrings,
|
| 20 |
+
is_tf_available,
|
| 21 |
+
is_torch_available,
|
| 22 |
+
is_vision_available,
|
| 23 |
+
logging,
|
| 24 |
+
requires_backends,
|
| 25 |
+
)
|
| 26 |
+
from .base import Pipeline, build_pipeline_init_args
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_vision_available():
|
| 30 |
+
from PIL import Image
|
| 31 |
+
|
| 32 |
+
from ..image_utils import load_image
|
| 33 |
+
|
| 34 |
+
if is_tf_available():
|
| 35 |
+
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES
|
| 36 |
+
|
| 37 |
+
if is_torch_available():
|
| 38 |
+
import torch
|
| 39 |
+
|
| 40 |
+
from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True, has_image_processor=True))
|
| 46 |
+
class ImageToTextPipeline(Pipeline):
|
| 47 |
+
"""
|
| 48 |
+
Image To Text pipeline using a `AutoModelForVision2Seq`. This pipeline predicts a caption for a given image.
|
| 49 |
+
|
| 50 |
+
Example:
|
| 51 |
+
|
| 52 |
+
```python
|
| 53 |
+
>>> from transformers import pipeline
|
| 54 |
+
|
| 55 |
+
>>> captioner = pipeline(model="ydshieh/vit-gpt2-coco-en")
|
| 56 |
+
>>> captioner("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
|
| 57 |
+
[{'generated_text': 'two birds are standing next to each other '}]
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
| 61 |
+
|
| 62 |
+
This image to text pipeline can currently be loaded from pipeline() using the following task identifier:
|
| 63 |
+
"image-to-text".
|
| 64 |
+
|
| 65 |
+
See the list of available models on
|
| 66 |
+
[huggingface.co/models](https://huggingface.co/models?pipeline_tag=image-to-text).
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def __init__(self, *args, **kwargs):
|
| 70 |
+
super().__init__(*args, **kwargs)
|
| 71 |
+
requires_backends(self, "vision")
|
| 72 |
+
self.check_model_type(
|
| 73 |
+
TF_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES if self.framework == "tf" else MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
def _sanitize_parameters(self, max_new_tokens=None, generate_kwargs=None, prompt=None, timeout=None):
|
| 77 |
+
forward_params = {}
|
| 78 |
+
preprocess_params = {}
|
| 79 |
+
|
| 80 |
+
if prompt is not None:
|
| 81 |
+
preprocess_params["prompt"] = prompt
|
| 82 |
+
if timeout is not None:
|
| 83 |
+
preprocess_params["timeout"] = timeout
|
| 84 |
+
|
| 85 |
+
if max_new_tokens is not None:
|
| 86 |
+
forward_params["max_new_tokens"] = max_new_tokens
|
| 87 |
+
if generate_kwargs is not None:
|
| 88 |
+
if max_new_tokens is not None and "max_new_tokens" in generate_kwargs:
|
| 89 |
+
raise ValueError(
|
| 90 |
+
"`max_new_tokens` is defined both as an argument and inside `generate_kwargs` argument, please use"
|
| 91 |
+
" only 1 version"
|
| 92 |
+
)
|
| 93 |
+
forward_params.update(generate_kwargs)
|
| 94 |
+
|
| 95 |
+
return preprocess_params, forward_params, {}
|
| 96 |
+
|
| 97 |
+
def __call__(self, inputs: Union[str, List[str], "Image.Image", List["Image.Image"]] = None, **kwargs):
|
| 98 |
+
"""
|
| 99 |
+
Assign labels to the image(s) passed as inputs.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
|
| 103 |
+
The pipeline handles three types of images:
|
| 104 |
+
|
| 105 |
+
- A string containing a HTTP(s) link pointing to an image
|
| 106 |
+
- A string containing a local path to an image
|
| 107 |
+
- An image loaded in PIL directly
|
| 108 |
+
|
| 109 |
+
The pipeline accepts either a single image or a batch of images.
|
| 110 |
+
|
| 111 |
+
max_new_tokens (`int`, *optional*):
|
| 112 |
+
The amount of maximum tokens to generate. By default it will use `generate` default.
|
| 113 |
+
|
| 114 |
+
generate_kwargs (`Dict`, *optional*):
|
| 115 |
+
Pass it to send all of these arguments directly to `generate` allowing full control of this function.
|
| 116 |
+
|
| 117 |
+
timeout (`float`, *optional*, defaults to None):
|
| 118 |
+
The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
|
| 119 |
+
the call may block forever.
|
| 120 |
+
|
| 121 |
+
Return:
|
| 122 |
+
A list or a list of list of `dict`: Each result comes as a dictionary with the following key:
|
| 123 |
+
|
| 124 |
+
- **generated_text** (`str`) -- The generated text.
|
| 125 |
+
"""
|
| 126 |
+
# After deprecation of this is completed, remove the default `None` value for `images`
|
| 127 |
+
if "images" in kwargs:
|
| 128 |
+
inputs = kwargs.pop("images")
|
| 129 |
+
if inputs is None:
|
| 130 |
+
raise ValueError("Cannot call the image-to-text pipeline without an inputs argument!")
|
| 131 |
+
return super().__call__(inputs, **kwargs)
|
| 132 |
+
|
| 133 |
+
def preprocess(self, image, prompt=None, timeout=None):
|
| 134 |
+
image = load_image(image, timeout=timeout)
|
| 135 |
+
|
| 136 |
+
if prompt is not None:
|
| 137 |
+
logger.warning_once(
|
| 138 |
+
"Passing `prompt` to the `image-to-text` pipeline is deprecated and will be removed in version 4.48"
|
| 139 |
+
" of 🤗 Transformers. Use the `image-text-to-text` pipeline instead",
|
| 140 |
+
)
|
| 141 |
+
if not isinstance(prompt, str):
|
| 142 |
+
raise ValueError(
|
| 143 |
+
f"Received an invalid text input, got - {type(prompt)} - but expected a single string. "
|
| 144 |
+
"Note also that one single text can be provided for conditional image to text generation."
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
model_type = self.model.config.model_type
|
| 148 |
+
|
| 149 |
+
if model_type == "git":
|
| 150 |
+
model_inputs = self.image_processor(images=image, return_tensors=self.framework)
|
| 151 |
+
if self.framework == "pt":
|
| 152 |
+
model_inputs = model_inputs.to(self.torch_dtype)
|
| 153 |
+
input_ids = self.tokenizer(text=prompt, add_special_tokens=False).input_ids
|
| 154 |
+
input_ids = [self.tokenizer.cls_token_id] + input_ids
|
| 155 |
+
input_ids = torch.tensor(input_ids).unsqueeze(0)
|
| 156 |
+
model_inputs.update({"input_ids": input_ids})
|
| 157 |
+
|
| 158 |
+
elif model_type == "pix2struct":
|
| 159 |
+
model_inputs = self.image_processor(images=image, header_text=prompt, return_tensors=self.framework)
|
| 160 |
+
if self.framework == "pt":
|
| 161 |
+
model_inputs = model_inputs.to(self.torch_dtype)
|
| 162 |
+
|
| 163 |
+
elif model_type != "vision-encoder-decoder":
|
| 164 |
+
# vision-encoder-decoder does not support conditional generation
|
| 165 |
+
model_inputs = self.image_processor(images=image, return_tensors=self.framework)
|
| 166 |
+
if self.framework == "pt":
|
| 167 |
+
model_inputs = model_inputs.to(self.torch_dtype)
|
| 168 |
+
text_inputs = self.tokenizer(prompt, return_tensors=self.framework)
|
| 169 |
+
model_inputs.update(text_inputs)
|
| 170 |
+
|
| 171 |
+
else:
|
| 172 |
+
raise ValueError(f"Model type {model_type} does not support conditional text generation")
|
| 173 |
+
|
| 174 |
+
else:
|
| 175 |
+
model_inputs = self.image_processor(images=image, return_tensors=self.framework)
|
| 176 |
+
if self.framework == "pt":
|
| 177 |
+
model_inputs = model_inputs.to(self.torch_dtype)
|
| 178 |
+
|
| 179 |
+
if self.model.config.model_type == "git" and prompt is None:
|
| 180 |
+
model_inputs["input_ids"] = None
|
| 181 |
+
|
| 182 |
+
return model_inputs
|
| 183 |
+
|
| 184 |
+
def _forward(self, model_inputs, **generate_kwargs):
|
| 185 |
+
# Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the
|
| 186 |
+
# pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first.
|
| 187 |
+
if (
|
| 188 |
+
"input_ids" in model_inputs
|
| 189 |
+
and isinstance(model_inputs["input_ids"], list)
|
| 190 |
+
and all(x is None for x in model_inputs["input_ids"])
|
| 191 |
+
):
|
| 192 |
+
model_inputs["input_ids"] = None
|
| 193 |
+
|
| 194 |
+
# User-defined `generation_config` passed to the pipeline call take precedence
|
| 195 |
+
if "generation_config" not in generate_kwargs:
|
| 196 |
+
generate_kwargs["generation_config"] = self.generation_config
|
| 197 |
+
|
| 198 |
+
# FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py`
|
| 199 |
+
# parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas
|
| 200 |
+
# the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name`
|
| 201 |
+
# in the `_prepare_model_inputs` method.
|
| 202 |
+
inputs = model_inputs.pop(self.model.main_input_name)
|
| 203 |
+
model_outputs = self.model.generate(inputs, **model_inputs, **generate_kwargs)
|
| 204 |
+
return model_outputs
|
| 205 |
+
|
| 206 |
+
def postprocess(self, model_outputs):
|
| 207 |
+
records = []
|
| 208 |
+
for output_ids in model_outputs:
|
| 209 |
+
record = {
|
| 210 |
+
"generated_text": self.tokenizer.decode(
|
| 211 |
+
output_ids,
|
| 212 |
+
skip_special_tokens=True,
|
| 213 |
+
)
|
| 214 |
+
}
|
| 215 |
+
records.append(record)
|
| 216 |
+
return records
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/mask_generation.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
from ..image_utils import load_image
|
| 5 |
+
from ..utils import (
|
| 6 |
+
add_end_docstrings,
|
| 7 |
+
is_torch_available,
|
| 8 |
+
logging,
|
| 9 |
+
requires_backends,
|
| 10 |
+
)
|
| 11 |
+
from .base import ChunkPipeline, build_pipeline_init_args
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
if is_torch_available():
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING_NAMES
|
| 18 |
+
|
| 19 |
+
logger = logging.get_logger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@add_end_docstrings(
|
| 23 |
+
build_pipeline_init_args(has_image_processor=True),
|
| 24 |
+
r"""
|
| 25 |
+
points_per_batch (*optional*, int, default to 64):
|
| 26 |
+
Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU
|
| 27 |
+
memory.
|
| 28 |
+
output_bboxes_mask (`bool`, *optional*, default to `False`):
|
| 29 |
+
Whether or not to output the bounding box predictions.
|
| 30 |
+
output_rle_masks (`bool`, *optional*, default to `False`):
|
| 31 |
+
Whether or not to output the masks in `RLE` format""",
|
| 32 |
+
)
|
| 33 |
+
class MaskGenerationPipeline(ChunkPipeline):
|
| 34 |
+
"""
|
| 35 |
+
Automatic mask generation for images using `SamForMaskGeneration`. This pipeline predicts binary masks for an
|
| 36 |
+
image, given an image. It is a `ChunkPipeline` because you can seperate the points in a mini-batch in order to
|
| 37 |
+
avoid OOM issues. Use the `points_per_batch` argument to control the number of points that will be processed at the
|
| 38 |
+
same time. Default is `64`.
|
| 39 |
+
|
| 40 |
+
The pipeline works in 3 steps:
|
| 41 |
+
1. `preprocess`: A grid of 1024 points evenly separated is generated along with bounding boxes and point
|
| 42 |
+
labels.
|
| 43 |
+
For more details on how the points and bounding boxes are created, check the `_generate_crop_boxes`
|
| 44 |
+
function. The image is also preprocessed using the `image_processor`. This function `yields` a minibatch of
|
| 45 |
+
`points_per_batch`.
|
| 46 |
+
|
| 47 |
+
2. `forward`: feeds the outputs of `preprocess` to the model. The image embedding is computed only once.
|
| 48 |
+
Calls both `self.model.get_image_embeddings` and makes sure that the gradients are not computed, and the
|
| 49 |
+
tensors and models are on the same device.
|
| 50 |
+
|
| 51 |
+
3. `postprocess`: The most important part of the automatic mask generation happens here. Three steps
|
| 52 |
+
are induced:
|
| 53 |
+
- image_processor.postprocess_masks (run on each minibatch loop): takes in the raw output masks,
|
| 54 |
+
resizes them according
|
| 55 |
+
to the image size, and transforms there to binary masks.
|
| 56 |
+
- image_processor.filter_masks (on each minibatch loop): uses both `pred_iou_thresh` and
|
| 57 |
+
`stability_scores`. Also
|
| 58 |
+
applies a variety of filters based on non maximum suppression to remove bad masks.
|
| 59 |
+
- image_processor.postprocess_masks_for_amg applies the NSM on the mask to only keep relevant ones.
|
| 60 |
+
|
| 61 |
+
Example:
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
>>> from transformers import pipeline
|
| 65 |
+
|
| 66 |
+
>>> generator = pipeline(model="facebook/sam-vit-base", task="mask-generation")
|
| 67 |
+
>>> outputs = generator(
|
| 68 |
+
... "http://images.cocodataset.org/val2017/000000039769.jpg",
|
| 69 |
+
... )
|
| 70 |
+
|
| 71 |
+
>>> outputs = generator(
|
| 72 |
+
... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", points_per_batch=128
|
| 73 |
+
... )
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
| 77 |
+
|
| 78 |
+
This segmentation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 79 |
+
`"mask-generation"`.
|
| 80 |
+
|
| 81 |
+
See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=mask-generation).
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
def __init__(self, **kwargs):
|
| 85 |
+
super().__init__(**kwargs)
|
| 86 |
+
requires_backends(self, "vision")
|
| 87 |
+
requires_backends(self, "torch")
|
| 88 |
+
|
| 89 |
+
if self.framework != "pt":
|
| 90 |
+
raise ValueError(f"The {self.__class__} is only available in PyTorch.")
|
| 91 |
+
|
| 92 |
+
self.check_model_type(MODEL_FOR_MASK_GENERATION_MAPPING_NAMES)
|
| 93 |
+
|
| 94 |
+
def _sanitize_parameters(self, **kwargs):
|
| 95 |
+
preprocess_kwargs = {}
|
| 96 |
+
postprocess_kwargs = {}
|
| 97 |
+
forward_params = {}
|
| 98 |
+
# preprocess args
|
| 99 |
+
if "points_per_batch" in kwargs:
|
| 100 |
+
preprocess_kwargs["points_per_batch"] = kwargs["points_per_batch"]
|
| 101 |
+
if "points_per_crop" in kwargs:
|
| 102 |
+
preprocess_kwargs["points_per_crop"] = kwargs["points_per_crop"]
|
| 103 |
+
if "crops_n_layers" in kwargs:
|
| 104 |
+
preprocess_kwargs["crops_n_layers"] = kwargs["crops_n_layers"]
|
| 105 |
+
if "crop_overlap_ratio" in kwargs:
|
| 106 |
+
preprocess_kwargs["crop_overlap_ratio"] = kwargs["crop_overlap_ratio"]
|
| 107 |
+
if "crop_n_points_downscale_factor" in kwargs:
|
| 108 |
+
preprocess_kwargs["crop_n_points_downscale_factor"] = kwargs["crop_n_points_downscale_factor"]
|
| 109 |
+
if "timeout" in kwargs:
|
| 110 |
+
preprocess_kwargs["timeout"] = kwargs["timeout"]
|
| 111 |
+
# postprocess args
|
| 112 |
+
if "pred_iou_thresh" in kwargs:
|
| 113 |
+
forward_params["pred_iou_thresh"] = kwargs["pred_iou_thresh"]
|
| 114 |
+
if "stability_score_offset" in kwargs:
|
| 115 |
+
forward_params["stability_score_offset"] = kwargs["stability_score_offset"]
|
| 116 |
+
if "mask_threshold" in kwargs:
|
| 117 |
+
forward_params["mask_threshold"] = kwargs["mask_threshold"]
|
| 118 |
+
if "stability_score_thresh" in kwargs:
|
| 119 |
+
forward_params["stability_score_thresh"] = kwargs["stability_score_thresh"]
|
| 120 |
+
if "crops_nms_thresh" in kwargs:
|
| 121 |
+
postprocess_kwargs["crops_nms_thresh"] = kwargs["crops_nms_thresh"]
|
| 122 |
+
if "output_rle_mask" in kwargs:
|
| 123 |
+
postprocess_kwargs["output_rle_mask"] = kwargs["output_rle_mask"]
|
| 124 |
+
if "output_bboxes_mask" in kwargs:
|
| 125 |
+
postprocess_kwargs["output_bboxes_mask"] = kwargs["output_bboxes_mask"]
|
| 126 |
+
return preprocess_kwargs, forward_params, postprocess_kwargs
|
| 127 |
+
|
| 128 |
+
def __call__(self, image, *args, num_workers=None, batch_size=None, **kwargs):
|
| 129 |
+
"""
|
| 130 |
+
Generates binary segmentation masks
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
inputs (`np.ndarray` or `bytes` or `str` or `dict`):
|
| 134 |
+
Image or list of images.
|
| 135 |
+
mask_threshold (`float`, *optional*, defaults to 0.0):
|
| 136 |
+
Threshold to use when turning the predicted masks into binary values.
|
| 137 |
+
pred_iou_thresh (`float`, *optional*, defaults to 0.88):
|
| 138 |
+
A filtering threshold in `[0,1]` applied on the model's predicted mask quality.
|
| 139 |
+
stability_score_thresh (`float`, *optional*, defaults to 0.95):
|
| 140 |
+
A filtering threshold in `[0,1]`, using the stability of the mask under changes to the cutoff used to
|
| 141 |
+
binarize the model's mask predictions.
|
| 142 |
+
stability_score_offset (`int`, *optional*, defaults to 1):
|
| 143 |
+
The amount to shift the cutoff when calculated the stability score.
|
| 144 |
+
crops_nms_thresh (`float`, *optional*, defaults to 0.7):
|
| 145 |
+
The box IoU cutoff used by non-maximal suppression to filter duplicate masks.
|
| 146 |
+
crops_n_layers (`int`, *optional*, defaults to 0):
|
| 147 |
+
If `crops_n_layers>0`, mask prediction will be run again on crops of the image. Sets the number of
|
| 148 |
+
layers to run, where each layer has 2**i_layer number of image crops.
|
| 149 |
+
crop_overlap_ratio (`float`, *optional*, defaults to `512 / 1500`):
|
| 150 |
+
Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of
|
| 151 |
+
the image length. Later layers with more crops scale down this overlap.
|
| 152 |
+
crop_n_points_downscale_factor (`int`, *optional*, defaults to `1`):
|
| 153 |
+
The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
|
| 154 |
+
timeout (`float`, *optional*, defaults to None):
|
| 155 |
+
The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
|
| 156 |
+
the call may block forever.
|
| 157 |
+
|
| 158 |
+
Return:
|
| 159 |
+
`Dict`: A dictionary with the following keys:
|
| 160 |
+
- **mask** (`PIL.Image`) -- A binary mask of the detected object as a PIL Image of shape `(width,
|
| 161 |
+
height)` of the original image. Returns a mask filled with zeros if no object is found.
|
| 162 |
+
- **score** (*optional* `float`) -- Optionally, when the model is capable of estimating a confidence of
|
| 163 |
+
the "object" described by the label and the mask.
|
| 164 |
+
|
| 165 |
+
"""
|
| 166 |
+
return super().__call__(image, *args, num_workers=num_workers, batch_size=batch_size, **kwargs)
|
| 167 |
+
|
| 168 |
+
def preprocess(
|
| 169 |
+
self,
|
| 170 |
+
image,
|
| 171 |
+
points_per_batch=64,
|
| 172 |
+
crops_n_layers: int = 0,
|
| 173 |
+
crop_overlap_ratio: float = 512 / 1500,
|
| 174 |
+
points_per_crop: Optional[int] = 32,
|
| 175 |
+
crop_n_points_downscale_factor: Optional[int] = 1,
|
| 176 |
+
timeout: Optional[float] = None,
|
| 177 |
+
):
|
| 178 |
+
image = load_image(image, timeout=timeout)
|
| 179 |
+
target_size = self.image_processor.size["longest_edge"]
|
| 180 |
+
crop_boxes, grid_points, cropped_images, input_labels = self.image_processor.generate_crop_boxes(
|
| 181 |
+
image, target_size, crops_n_layers, crop_overlap_ratio, points_per_crop, crop_n_points_downscale_factor
|
| 182 |
+
)
|
| 183 |
+
model_inputs = self.image_processor(images=cropped_images, return_tensors="pt")
|
| 184 |
+
if self.framework == "pt":
|
| 185 |
+
model_inputs = model_inputs.to(self.torch_dtype)
|
| 186 |
+
|
| 187 |
+
with self.device_placement():
|
| 188 |
+
if self.framework == "pt":
|
| 189 |
+
inference_context = self.get_inference_context()
|
| 190 |
+
with inference_context():
|
| 191 |
+
model_inputs = self._ensure_tensor_on_device(model_inputs, device=self.device)
|
| 192 |
+
image_embeddings = self.model.get_image_embeddings(model_inputs.pop("pixel_values"))
|
| 193 |
+
model_inputs["image_embeddings"] = image_embeddings
|
| 194 |
+
|
| 195 |
+
n_points = grid_points.shape[1]
|
| 196 |
+
points_per_batch = points_per_batch if points_per_batch is not None else n_points
|
| 197 |
+
|
| 198 |
+
if points_per_batch <= 0:
|
| 199 |
+
raise ValueError(
|
| 200 |
+
"Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. "
|
| 201 |
+
"To return all points at once, set points_per_batch to None"
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
for i in range(0, n_points, points_per_batch):
|
| 205 |
+
batched_points = grid_points[:, i : i + points_per_batch, :, :]
|
| 206 |
+
labels = input_labels[:, i : i + points_per_batch]
|
| 207 |
+
is_last = i == n_points - points_per_batch
|
| 208 |
+
yield {
|
| 209 |
+
"input_points": batched_points,
|
| 210 |
+
"input_labels": labels,
|
| 211 |
+
"input_boxes": crop_boxes,
|
| 212 |
+
"is_last": is_last,
|
| 213 |
+
**model_inputs,
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
def _forward(
|
| 217 |
+
self,
|
| 218 |
+
model_inputs,
|
| 219 |
+
pred_iou_thresh=0.88,
|
| 220 |
+
stability_score_thresh=0.95,
|
| 221 |
+
mask_threshold=0,
|
| 222 |
+
stability_score_offset=1,
|
| 223 |
+
):
|
| 224 |
+
input_boxes = model_inputs.pop("input_boxes")
|
| 225 |
+
is_last = model_inputs.pop("is_last")
|
| 226 |
+
original_sizes = model_inputs.pop("original_sizes").tolist()
|
| 227 |
+
reshaped_input_sizes = model_inputs.pop("reshaped_input_sizes").tolist()
|
| 228 |
+
|
| 229 |
+
model_outputs = self.model(**model_inputs)
|
| 230 |
+
|
| 231 |
+
# post processing happens here in order to avoid CPU GPU copies of ALL the masks
|
| 232 |
+
low_resolution_masks = model_outputs["pred_masks"]
|
| 233 |
+
masks = self.image_processor.post_process_masks(
|
| 234 |
+
low_resolution_masks, original_sizes, reshaped_input_sizes, mask_threshold, binarize=False
|
| 235 |
+
)
|
| 236 |
+
iou_scores = model_outputs["iou_scores"]
|
| 237 |
+
masks, iou_scores, boxes = self.image_processor.filter_masks(
|
| 238 |
+
masks[0],
|
| 239 |
+
iou_scores[0],
|
| 240 |
+
original_sizes[0],
|
| 241 |
+
input_boxes[0],
|
| 242 |
+
pred_iou_thresh,
|
| 243 |
+
stability_score_thresh,
|
| 244 |
+
mask_threshold,
|
| 245 |
+
stability_score_offset,
|
| 246 |
+
)
|
| 247 |
+
return {
|
| 248 |
+
"masks": masks,
|
| 249 |
+
"is_last": is_last,
|
| 250 |
+
"boxes": boxes,
|
| 251 |
+
"iou_scores": iou_scores,
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
def postprocess(
|
| 255 |
+
self,
|
| 256 |
+
model_outputs,
|
| 257 |
+
output_rle_mask=False,
|
| 258 |
+
output_bboxes_mask=False,
|
| 259 |
+
crops_nms_thresh=0.7,
|
| 260 |
+
):
|
| 261 |
+
all_scores = []
|
| 262 |
+
all_masks = []
|
| 263 |
+
all_boxes = []
|
| 264 |
+
for model_output in model_outputs:
|
| 265 |
+
all_scores.append(model_output.pop("iou_scores"))
|
| 266 |
+
all_masks.extend(model_output.pop("masks"))
|
| 267 |
+
all_boxes.append(model_output.pop("boxes"))
|
| 268 |
+
|
| 269 |
+
all_scores = torch.cat(all_scores)
|
| 270 |
+
all_boxes = torch.cat(all_boxes)
|
| 271 |
+
output_masks, iou_scores, rle_mask, bounding_boxes = self.image_processor.post_process_for_mask_generation(
|
| 272 |
+
all_masks, all_scores, all_boxes, crops_nms_thresh
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
extra = defaultdict(list)
|
| 276 |
+
for output in model_outputs:
|
| 277 |
+
for k, v in output.items():
|
| 278 |
+
extra[k].append(v)
|
| 279 |
+
|
| 280 |
+
optional = {}
|
| 281 |
+
if output_rle_mask:
|
| 282 |
+
optional["rle_mask"] = rle_mask
|
| 283 |
+
|
| 284 |
+
if output_bboxes_mask:
|
| 285 |
+
optional["bounding_boxes"] = bounding_boxes
|
| 286 |
+
|
| 287 |
+
return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/object_detection.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Union
|
| 2 |
+
|
| 3 |
+
from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
|
| 4 |
+
from .base import Pipeline, build_pipeline_init_args
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
if is_vision_available():
|
| 8 |
+
from ..image_utils import load_image
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if is_torch_available():
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
from ..models.auto.modeling_auto import (
|
| 15 |
+
MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES,
|
| 16 |
+
MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
logger = logging.get_logger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
Prediction = Dict[str, Any]
|
| 23 |
+
Predictions = List[Prediction]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
|
| 27 |
+
class ObjectDetectionPipeline(Pipeline):
|
| 28 |
+
"""
|
| 29 |
+
Object detection pipeline using any `AutoModelForObjectDetection`. This pipeline predicts bounding boxes of objects
|
| 30 |
+
and their classes.
|
| 31 |
+
|
| 32 |
+
Example:
|
| 33 |
+
|
| 34 |
+
```python
|
| 35 |
+
>>> from transformers import pipeline
|
| 36 |
+
|
| 37 |
+
>>> detector = pipeline(model="facebook/detr-resnet-50")
|
| 38 |
+
>>> detector("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
|
| 39 |
+
[{'score': 0.997, 'label': 'bird', 'box': {'xmin': 69, 'ymin': 171, 'xmax': 396, 'ymax': 507}}, {'score': 0.999, 'label': 'bird', 'box': {'xmin': 398, 'ymin': 105, 'xmax': 767, 'ymax': 507}}]
|
| 40 |
+
|
| 41 |
+
>>> # x, y are expressed relative to the top left hand corner.
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
| 45 |
+
|
| 46 |
+
This object detection pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 47 |
+
`"object-detection"`.
|
| 48 |
+
|
| 49 |
+
See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=object-detection).
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(self, *args, **kwargs):
|
| 53 |
+
super().__init__(*args, **kwargs)
|
| 54 |
+
|
| 55 |
+
if self.framework == "tf":
|
| 56 |
+
raise ValueError(f"The {self.__class__} is only available in PyTorch.")
|
| 57 |
+
|
| 58 |
+
requires_backends(self, "vision")
|
| 59 |
+
mapping = MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES.copy()
|
| 60 |
+
mapping.update(MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES)
|
| 61 |
+
self.check_model_type(mapping)
|
| 62 |
+
|
| 63 |
+
def _sanitize_parameters(self, **kwargs):
|
| 64 |
+
preprocess_params = {}
|
| 65 |
+
if "timeout" in kwargs:
|
| 66 |
+
preprocess_params["timeout"] = kwargs["timeout"]
|
| 67 |
+
postprocess_kwargs = {}
|
| 68 |
+
if "threshold" in kwargs:
|
| 69 |
+
postprocess_kwargs["threshold"] = kwargs["threshold"]
|
| 70 |
+
return preprocess_params, {}, postprocess_kwargs
|
| 71 |
+
|
| 72 |
+
def __call__(self, *args, **kwargs) -> Union[Predictions, List[Prediction]]:
|
| 73 |
+
"""
|
| 74 |
+
Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
|
| 78 |
+
The pipeline handles three types of images:
|
| 79 |
+
|
| 80 |
+
- A string containing an HTTP(S) link pointing to an image
|
| 81 |
+
- A string containing a local path to an image
|
| 82 |
+
- An image loaded in PIL directly
|
| 83 |
+
|
| 84 |
+
The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the
|
| 85 |
+
same format: all as HTTP(S) links, all as local paths, or all as PIL images.
|
| 86 |
+
threshold (`float`, *optional*, defaults to 0.5):
|
| 87 |
+
The probability necessary to make a prediction.
|
| 88 |
+
timeout (`float`, *optional*, defaults to None):
|
| 89 |
+
The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
|
| 90 |
+
the call may block forever.
|
| 91 |
+
|
| 92 |
+
Return:
|
| 93 |
+
A list of dictionaries or a list of list of dictionaries containing the result. If the input is a single
|
| 94 |
+
image, will return a list of dictionaries, if the input is a list of several images, will return a list of
|
| 95 |
+
list of dictionaries corresponding to each image.
|
| 96 |
+
|
| 97 |
+
The dictionaries contain the following keys:
|
| 98 |
+
|
| 99 |
+
- **label** (`str`) -- The class label identified by the model.
|
| 100 |
+
- **score** (`float`) -- The score attributed by the model for that label.
|
| 101 |
+
- **box** (`List[Dict[str, int]]`) -- The bounding box of detected object in image's original size.
|
| 102 |
+
"""
|
| 103 |
+
# After deprecation of this is completed, remove the default `None` value for `images`
|
| 104 |
+
if "images" in kwargs and "inputs" not in kwargs:
|
| 105 |
+
kwargs["inputs"] = kwargs.pop("images")
|
| 106 |
+
return super().__call__(*args, **kwargs)
|
| 107 |
+
|
| 108 |
+
def preprocess(self, image, timeout=None):
|
| 109 |
+
image = load_image(image, timeout=timeout)
|
| 110 |
+
target_size = torch.IntTensor([[image.height, image.width]])
|
| 111 |
+
inputs = self.image_processor(images=[image], return_tensors="pt")
|
| 112 |
+
if self.framework == "pt":
|
| 113 |
+
inputs = inputs.to(self.torch_dtype)
|
| 114 |
+
if self.tokenizer is not None:
|
| 115 |
+
inputs = self.tokenizer(text=inputs["words"], boxes=inputs["boxes"], return_tensors="pt")
|
| 116 |
+
inputs["target_size"] = target_size
|
| 117 |
+
return inputs
|
| 118 |
+
|
| 119 |
+
def _forward(self, model_inputs):
|
| 120 |
+
target_size = model_inputs.pop("target_size")
|
| 121 |
+
outputs = self.model(**model_inputs)
|
| 122 |
+
model_outputs = outputs.__class__({"target_size": target_size, **outputs})
|
| 123 |
+
if self.tokenizer is not None:
|
| 124 |
+
model_outputs["bbox"] = model_inputs["bbox"]
|
| 125 |
+
return model_outputs
|
| 126 |
+
|
| 127 |
+
def postprocess(self, model_outputs, threshold=0.5):
|
| 128 |
+
target_size = model_outputs["target_size"]
|
| 129 |
+
if self.tokenizer is not None:
|
| 130 |
+
# This is a LayoutLMForTokenClassification variant.
|
| 131 |
+
# The OCR got the boxes and the model classified the words.
|
| 132 |
+
height, width = target_size[0].tolist()
|
| 133 |
+
|
| 134 |
+
def unnormalize(bbox):
|
| 135 |
+
return self._get_bounding_box(
|
| 136 |
+
torch.Tensor(
|
| 137 |
+
[
|
| 138 |
+
(width * bbox[0] / 1000),
|
| 139 |
+
(height * bbox[1] / 1000),
|
| 140 |
+
(width * bbox[2] / 1000),
|
| 141 |
+
(height * bbox[3] / 1000),
|
| 142 |
+
]
|
| 143 |
+
)
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
scores, classes = model_outputs["logits"].squeeze(0).softmax(dim=-1).max(dim=-1)
|
| 147 |
+
labels = [self.model.config.id2label[prediction] for prediction in classes.tolist()]
|
| 148 |
+
boxes = [unnormalize(bbox) for bbox in model_outputs["bbox"].squeeze(0)]
|
| 149 |
+
keys = ["score", "label", "box"]
|
| 150 |
+
annotation = [dict(zip(keys, vals)) for vals in zip(scores.tolist(), labels, boxes) if vals[0] > threshold]
|
| 151 |
+
else:
|
| 152 |
+
# This is a regular ForObjectDetectionModel
|
| 153 |
+
raw_annotations = self.image_processor.post_process_object_detection(model_outputs, threshold, target_size)
|
| 154 |
+
raw_annotation = raw_annotations[0]
|
| 155 |
+
scores = raw_annotation["scores"]
|
| 156 |
+
labels = raw_annotation["labels"]
|
| 157 |
+
boxes = raw_annotation["boxes"]
|
| 158 |
+
|
| 159 |
+
raw_annotation["scores"] = scores.tolist()
|
| 160 |
+
raw_annotation["labels"] = [self.model.config.id2label[label.item()] for label in labels]
|
| 161 |
+
raw_annotation["boxes"] = [self._get_bounding_box(box) for box in boxes]
|
| 162 |
+
|
| 163 |
+
# {"scores": [...], ...} --> [{"score":x, ...}, ...]
|
| 164 |
+
keys = ["score", "label", "box"]
|
| 165 |
+
annotation = [
|
| 166 |
+
dict(zip(keys, vals))
|
| 167 |
+
for vals in zip(raw_annotation["scores"], raw_annotation["labels"], raw_annotation["boxes"])
|
| 168 |
+
]
|
| 169 |
+
|
| 170 |
+
return annotation
|
| 171 |
+
|
| 172 |
+
def _get_bounding_box(self, box: "torch.Tensor") -> Dict[str, int]:
|
| 173 |
+
"""
|
| 174 |
+
Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... }
|
| 175 |
+
|
| 176 |
+
Args:
|
| 177 |
+
box (`torch.Tensor`): Tensor containing the coordinates in corners format.
|
| 178 |
+
|
| 179 |
+
Returns:
|
| 180 |
+
bbox (`Dict[str, int]`): Dict containing the coordinates in corners format.
|
| 181 |
+
"""
|
| 182 |
+
if self.framework != "pt":
|
| 183 |
+
raise ValueError("The ObjectDetectionPipeline is only available in PyTorch.")
|
| 184 |
+
xmin, ymin, xmax, ymax = box.int().tolist()
|
| 185 |
+
bbox = {
|
| 186 |
+
"xmin": xmin,
|
| 187 |
+
"ymin": ymin,
|
| 188 |
+
"xmax": xmax,
|
| 189 |
+
"ymax": ymax,
|
| 190 |
+
}
|
| 191 |
+
return bbox
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/pt_utils.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
from torch.utils.data import Dataset, IterableDataset
|
| 4 |
+
|
| 5 |
+
from ..utils.generic import ModelOutput
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class PipelineDataset(Dataset):
|
| 9 |
+
def __init__(self, dataset, process, params):
|
| 10 |
+
self.dataset = dataset
|
| 11 |
+
self.process = process
|
| 12 |
+
self.params = params
|
| 13 |
+
|
| 14 |
+
def __len__(self):
|
| 15 |
+
return len(self.dataset)
|
| 16 |
+
|
| 17 |
+
def __getitem__(self, i):
|
| 18 |
+
item = self.dataset[i]
|
| 19 |
+
processed = self.process(item, **self.params)
|
| 20 |
+
return processed
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class PipelineIterator(IterableDataset):
|
| 24 |
+
def __init__(self, loader, infer, params, loader_batch_size=None):
|
| 25 |
+
"""
|
| 26 |
+
Roughly equivalent to
|
| 27 |
+
|
| 28 |
+
```
|
| 29 |
+
for item in loader:
|
| 30 |
+
yield infer(item, **params)
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Arguments:
|
| 34 |
+
loader (`torch.utils.data.DataLoader` or `Iterable`):
|
| 35 |
+
The iterator that will be used to apply `infer` on.
|
| 36 |
+
infer (any function):
|
| 37 |
+
The function to apply of each element of `loader`.
|
| 38 |
+
params (`dict`):
|
| 39 |
+
The parameters passed to `infer` along with every item
|
| 40 |
+
loader_batch_size (`int`, *optional*):
|
| 41 |
+
If specified, the items of `loader` are supposed to come as batch, and are loader_batched here
|
| 42 |
+
making it roughly behave as
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
```
|
| 46 |
+
for items in loader:
|
| 47 |
+
for i in loader_batch_size:
|
| 48 |
+
item = items[i]
|
| 49 |
+
yield infer(item, **params)
|
| 50 |
+
```"""
|
| 51 |
+
self.loader = loader
|
| 52 |
+
self.infer = infer
|
| 53 |
+
self.params = params
|
| 54 |
+
if loader_batch_size == 1:
|
| 55 |
+
# Let's spare some time by deactivating altogether
|
| 56 |
+
loader_batch_size = None
|
| 57 |
+
self.loader_batch_size = loader_batch_size
|
| 58 |
+
|
| 59 |
+
# Internal bookkeeping
|
| 60 |
+
self._loader_batch_index = None
|
| 61 |
+
self._loader_batch_data = None
|
| 62 |
+
|
| 63 |
+
def __len__(self):
|
| 64 |
+
return len(self.loader)
|
| 65 |
+
|
| 66 |
+
def __iter__(self):
|
| 67 |
+
self.iterator = iter(self.loader)
|
| 68 |
+
return self
|
| 69 |
+
|
| 70 |
+
def loader_batch_item(self):
|
| 71 |
+
"""
|
| 72 |
+
Return item located at `loader_batch_index` within the current `loader_batch_data`.
|
| 73 |
+
"""
|
| 74 |
+
if isinstance(self._loader_batch_data, torch.Tensor):
|
| 75 |
+
# Batch data is simple tensor, just fetch the slice
|
| 76 |
+
result = self._loader_batch_data[self._loader_batch_index].unsqueeze(0)
|
| 77 |
+
else:
|
| 78 |
+
# Batch data is assumed to be BaseModelOutput (or dict)
|
| 79 |
+
loader_batched = {}
|
| 80 |
+
for k, element in self._loader_batch_data.items():
|
| 81 |
+
if isinstance(element, ModelOutput):
|
| 82 |
+
# Convert ModelOutput to tuple first
|
| 83 |
+
element = element.to_tuple()
|
| 84 |
+
if isinstance(element[0], torch.Tensor):
|
| 85 |
+
loader_batched[k] = tuple(el[self._loader_batch_index].unsqueeze(0) for el in element)
|
| 86 |
+
elif isinstance(element[0], np.ndarray):
|
| 87 |
+
loader_batched[k] = tuple(np.expand_dims(el[self._loader_batch_index], 0) for el in element)
|
| 88 |
+
continue
|
| 89 |
+
if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(element, tuple):
|
| 90 |
+
# Those are stored as lists of tensors so need specific unbatching.
|
| 91 |
+
if isinstance(element[0], torch.Tensor):
|
| 92 |
+
loader_batched[k] = tuple(el[self._loader_batch_index].unsqueeze(0) for el in element)
|
| 93 |
+
elif isinstance(element[0], np.ndarray):
|
| 94 |
+
loader_batched[k] = tuple(np.expand_dims(el[self._loader_batch_index], 0) for el in element)
|
| 95 |
+
continue
|
| 96 |
+
if element is None:
|
| 97 |
+
# This can happen for optional data that get passed around
|
| 98 |
+
loader_batched[k] = None
|
| 99 |
+
elif isinstance(element[self._loader_batch_index], torch.Tensor):
|
| 100 |
+
# Take correct batch data, but make it looked like batch_size=1
|
| 101 |
+
# For compatibility with other methods within transformers
|
| 102 |
+
|
| 103 |
+
loader_batched[k] = element[self._loader_batch_index].unsqueeze(0)
|
| 104 |
+
elif isinstance(element[self._loader_batch_index], np.ndarray):
|
| 105 |
+
# Take correct batch data, but make it looked like batch_size=1
|
| 106 |
+
# For compatibility with other methods within transformers
|
| 107 |
+
loader_batched[k] = np.expand_dims(element[self._loader_batch_index], 0)
|
| 108 |
+
else:
|
| 109 |
+
# This is typically a list, so no need to `unsqueeze`.
|
| 110 |
+
loader_batched[k] = element[self._loader_batch_index]
|
| 111 |
+
# Recreate the element by reusing the original class to make it look
|
| 112 |
+
# batch_size=1
|
| 113 |
+
result = self._loader_batch_data.__class__(loader_batched)
|
| 114 |
+
self._loader_batch_index += 1
|
| 115 |
+
return result
|
| 116 |
+
|
| 117 |
+
def __next__(self):
|
| 118 |
+
if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
|
| 119 |
+
# We are currently unrolling a batch so we just need to return
|
| 120 |
+
# the current item within a batch
|
| 121 |
+
return self.loader_batch_item()
|
| 122 |
+
|
| 123 |
+
# We're out of items within a batch
|
| 124 |
+
item = next(self.iterator)
|
| 125 |
+
processed = self.infer(item, **self.params)
|
| 126 |
+
# We now have a batch of "inferred things".
|
| 127 |
+
if self.loader_batch_size is not None:
|
| 128 |
+
# Try to infer the size of the batch
|
| 129 |
+
if isinstance(processed, torch.Tensor):
|
| 130 |
+
first_tensor = processed
|
| 131 |
+
elif isinstance(processed, tuple):
|
| 132 |
+
first_tensor = processed[0]
|
| 133 |
+
else:
|
| 134 |
+
key = list(processed.keys())[0]
|
| 135 |
+
first_tensor = processed[key]
|
| 136 |
+
|
| 137 |
+
if isinstance(first_tensor, list):
|
| 138 |
+
observed_batch_size = len(first_tensor)
|
| 139 |
+
else:
|
| 140 |
+
observed_batch_size = first_tensor.shape[0]
|
| 141 |
+
if 0 < observed_batch_size < self.loader_batch_size:
|
| 142 |
+
# could be last batch so we can't unroll as many
|
| 143 |
+
# elements.
|
| 144 |
+
self.loader_batch_size = observed_batch_size
|
| 145 |
+
# Setting internal index to unwrap the batch
|
| 146 |
+
self._loader_batch_data = processed[0] if isinstance(processed, tuple) else processed
|
| 147 |
+
self._loader_batch_index = 0
|
| 148 |
+
return self.loader_batch_item()
|
| 149 |
+
else:
|
| 150 |
+
# We're not unrolling batches
|
| 151 |
+
return processed
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class PipelineChunkIterator(PipelineIterator):
|
| 155 |
+
def __init__(self, loader, infer, params, loader_batch_size=None):
|
| 156 |
+
"""
|
| 157 |
+
Roughly equivalent to
|
| 158 |
+
|
| 159 |
+
```
|
| 160 |
+
for iterator in loader:
|
| 161 |
+
for item in iterator:
|
| 162 |
+
yield infer(item, **params)
|
| 163 |
+
```
|
| 164 |
+
|
| 165 |
+
Arguments:
|
| 166 |
+
loader (`torch.utils.data.DataLoader` or `Iterable`):
|
| 167 |
+
The iterator that will be used to apply `infer` on.
|
| 168 |
+
infer (any function):
|
| 169 |
+
The function to apply of each element of `loader`.
|
| 170 |
+
params (`dict`):
|
| 171 |
+
The parameters passed to `infer` along with every item
|
| 172 |
+
"""
|
| 173 |
+
super().__init__(loader, infer, params)
|
| 174 |
+
|
| 175 |
+
def __iter__(self):
|
| 176 |
+
self.iterator = iter(self.loader)
|
| 177 |
+
self.subiterator = None
|
| 178 |
+
return self
|
| 179 |
+
|
| 180 |
+
def __next__(self):
|
| 181 |
+
if self.subiterator is None:
|
| 182 |
+
"Subiterator None means we haven't started a `preprocess` iterator. so start it"
|
| 183 |
+
self.subiterator = self.infer(next(self.iterator), **self.params)
|
| 184 |
+
try:
|
| 185 |
+
# Try to return next item
|
| 186 |
+
processed = next(self.subiterator)
|
| 187 |
+
except StopIteration:
|
| 188 |
+
# When a preprocess iterator ends, we can start lookig at the next item
|
| 189 |
+
# ChunkIterator will keep feeding until ALL elements of iterator
|
| 190 |
+
# all have created their subiterator and have been iterating against.
|
| 191 |
+
#
|
| 192 |
+
# Another way to look at it, is we're basically flattening lists of lists
|
| 193 |
+
# into a single list, but with generators
|
| 194 |
+
self.subiterator = self.infer(next(self.iterator), **self.params)
|
| 195 |
+
processed = next(self.subiterator)
|
| 196 |
+
return processed
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class PipelinePackIterator(PipelineIterator):
|
| 200 |
+
"""
|
| 201 |
+
Roughly equivalent to
|
| 202 |
+
|
| 203 |
+
```
|
| 204 |
+
packed = []
|
| 205 |
+
for item in loader:
|
| 206 |
+
packed.append(item)
|
| 207 |
+
if item["is_last"]:
|
| 208 |
+
yield packed
|
| 209 |
+
packed = []
|
| 210 |
+
```
|
| 211 |
+
|
| 212 |
+
but it also handles cases where `item` are batched (meaning it's a dict of Tensor with first dimension > 1. In
|
| 213 |
+
that case it does
|
| 214 |
+
|
| 215 |
+
```
|
| 216 |
+
packed = []
|
| 217 |
+
for batch in loader:
|
| 218 |
+
# item is batched
|
| 219 |
+
for item in batch:
|
| 220 |
+
packed.append(item)
|
| 221 |
+
if item["is_last"]:
|
| 222 |
+
yield packed
|
| 223 |
+
packed = []
|
| 224 |
+
```
|
| 225 |
+
|
| 226 |
+
Arguments:
|
| 227 |
+
loader (`torch.utils.data.DataLoader` or `Iterable`):
|
| 228 |
+
The iterator that will be used to apply `infer` on.
|
| 229 |
+
infer (any function):
|
| 230 |
+
The function to apply of each element of `loader`.
|
| 231 |
+
params (`dict`):
|
| 232 |
+
The parameters passed to `infer` along with every item
|
| 233 |
+
loader_batch_size (`int`, *optional*):
|
| 234 |
+
If specified, the items of `loader` are supposed to come as batch, and are loader_batched here making
|
| 235 |
+
it roughly behave as
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
```
|
| 239 |
+
for items in loader:
|
| 240 |
+
for i in loader_batch_size:
|
| 241 |
+
item = items[i]
|
| 242 |
+
yield infer(item, **params)
|
| 243 |
+
```"""
|
| 244 |
+
|
| 245 |
+
def __iter__(self):
|
| 246 |
+
self.iterator = iter(self.loader)
|
| 247 |
+
return self
|
| 248 |
+
|
| 249 |
+
def __next__(self):
|
| 250 |
+
# Extremely similar to PipelineIterator in its unpacking mechanism
|
| 251 |
+
# BUT, we have an extra required item which is the presence of `is_last`
|
| 252 |
+
# That is because everything is flattened by `PipelineChunkIterator` we
|
| 253 |
+
# need to keep track of how to regroup here in the original `process`
|
| 254 |
+
# boundaries so that `process` and `postprocess` see the same data.
|
| 255 |
+
|
| 256 |
+
# This iterator accumulates items (possibly while unbatching) until it
|
| 257 |
+
# its a `is_last` and then just passes it on to the caller.
|
| 258 |
+
is_last = False
|
| 259 |
+
accumulator = []
|
| 260 |
+
if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
|
| 261 |
+
while self._loader_batch_index < self.loader_batch_size:
|
| 262 |
+
item = self.loader_batch_item()
|
| 263 |
+
is_last = item.pop("is_last")
|
| 264 |
+
accumulator.append(item)
|
| 265 |
+
if is_last:
|
| 266 |
+
return accumulator
|
| 267 |
+
|
| 268 |
+
while not is_last:
|
| 269 |
+
processed = self.infer(next(self.iterator), **self.params)
|
| 270 |
+
if self.loader_batch_size is not None:
|
| 271 |
+
if isinstance(processed, torch.Tensor):
|
| 272 |
+
first_tensor = processed
|
| 273 |
+
else:
|
| 274 |
+
key = list(processed.keys())[0]
|
| 275 |
+
first_tensor = processed[key]
|
| 276 |
+
if isinstance(first_tensor, list):
|
| 277 |
+
observed_batch_size = len(first_tensor)
|
| 278 |
+
else:
|
| 279 |
+
observed_batch_size = first_tensor.shape[0]
|
| 280 |
+
if 0 < observed_batch_size < self.loader_batch_size:
|
| 281 |
+
# could be last batch so we can't unroll as many
|
| 282 |
+
# elements.
|
| 283 |
+
self.loader_batch_size = observed_batch_size
|
| 284 |
+
self._loader_batch_data = processed
|
| 285 |
+
self._loader_batch_index = 0
|
| 286 |
+
while self._loader_batch_index < self.loader_batch_size:
|
| 287 |
+
item = self.loader_batch_item()
|
| 288 |
+
is_last = item.pop("is_last")
|
| 289 |
+
accumulator.append(item)
|
| 290 |
+
if is_last:
|
| 291 |
+
return accumulator
|
| 292 |
+
else:
|
| 293 |
+
item = processed
|
| 294 |
+
is_last = item.pop("is_last")
|
| 295 |
+
accumulator.append(item)
|
| 296 |
+
return accumulator
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class KeyDataset(Dataset):
|
| 300 |
+
def __init__(self, dataset: Dataset, key: str):
|
| 301 |
+
self.dataset = dataset
|
| 302 |
+
self.key = key
|
| 303 |
+
|
| 304 |
+
def __len__(self):
|
| 305 |
+
return len(self.dataset)
|
| 306 |
+
|
| 307 |
+
def __getitem__(self, i):
|
| 308 |
+
return self.dataset[i][self.key]
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class KeyPairDataset(Dataset):
|
| 312 |
+
def __init__(self, dataset: Dataset, key1: str, key2: str):
|
| 313 |
+
self.dataset = dataset
|
| 314 |
+
self.key1 = key1
|
| 315 |
+
self.key2 = key2
|
| 316 |
+
|
| 317 |
+
def __len__(self):
|
| 318 |
+
return len(self.dataset)
|
| 319 |
+
|
| 320 |
+
def __getitem__(self, i):
|
| 321 |
+
return {"text": self.dataset[i][self.key1], "text_pair": self.dataset[i][self.key2]}
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/question_answering.py
ADDED
|
@@ -0,0 +1,682 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import types
|
| 3 |
+
import warnings
|
| 4 |
+
from collections.abc import Iterable
|
| 5 |
+
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
from ..data import SquadExample, SquadFeatures, squad_convert_examples_to_features
|
| 10 |
+
from ..modelcard import ModelCard
|
| 11 |
+
from ..tokenization_utils import PreTrainedTokenizer
|
| 12 |
+
from ..utils import (
|
| 13 |
+
PaddingStrategy,
|
| 14 |
+
add_end_docstrings,
|
| 15 |
+
is_tf_available,
|
| 16 |
+
is_tokenizers_available,
|
| 17 |
+
is_torch_available,
|
| 18 |
+
logging,
|
| 19 |
+
)
|
| 20 |
+
from .base import ArgumentHandler, ChunkPipeline, build_pipeline_init_args
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
from ..modeling_tf_utils import TFPreTrainedModel
|
| 27 |
+
from ..modeling_utils import PreTrainedModel
|
| 28 |
+
|
| 29 |
+
if is_tokenizers_available():
|
| 30 |
+
import tokenizers
|
| 31 |
+
|
| 32 |
+
if is_tf_available():
|
| 33 |
+
import tensorflow as tf
|
| 34 |
+
|
| 35 |
+
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
|
| 36 |
+
|
| 37 |
+
Dataset = None
|
| 38 |
+
|
| 39 |
+
if is_torch_available():
|
| 40 |
+
import torch
|
| 41 |
+
from torch.utils.data import Dataset
|
| 42 |
+
|
| 43 |
+
from ..models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def decode_spans(
|
| 47 |
+
start: np.ndarray, end: np.ndarray, topk: int, max_answer_len: int, undesired_tokens: np.ndarray
|
| 48 |
+
) -> Tuple:
|
| 49 |
+
"""
|
| 50 |
+
Take the output of any `ModelForQuestionAnswering` and will generate probabilities for each span to be the actual
|
| 51 |
+
answer.
|
| 52 |
+
|
| 53 |
+
In addition, it filters out some unwanted/impossible cases like answer len being greater than max_answer_len or
|
| 54 |
+
answer end position being before the starting position. The method supports output the k-best answer through the
|
| 55 |
+
topk argument.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
start (`np.ndarray`): Individual start probabilities for each token.
|
| 59 |
+
end (`np.ndarray`): Individual end probabilities for each token.
|
| 60 |
+
topk (`int`): Indicates how many possible answer span(s) to extract from the model output.
|
| 61 |
+
max_answer_len (`int`): Maximum size of the answer to extract from the model's output.
|
| 62 |
+
undesired_tokens (`np.ndarray`): Mask determining tokens that can be part of the answer
|
| 63 |
+
"""
|
| 64 |
+
# Ensure we have batch axis
|
| 65 |
+
if start.ndim == 1:
|
| 66 |
+
start = start[None]
|
| 67 |
+
|
| 68 |
+
if end.ndim == 1:
|
| 69 |
+
end = end[None]
|
| 70 |
+
|
| 71 |
+
# Compute the score of each tuple(start, end) to be the real answer
|
| 72 |
+
outer = np.matmul(np.expand_dims(start, -1), np.expand_dims(end, 1))
|
| 73 |
+
|
| 74 |
+
# Remove candidate with end < start and end - start > max_answer_len
|
| 75 |
+
candidates = np.tril(np.triu(outer), max_answer_len - 1)
|
| 76 |
+
|
| 77 |
+
# Inspired by Chen & al. (https://github.com/facebookresearch/DrQA)
|
| 78 |
+
scores_flat = candidates.flatten()
|
| 79 |
+
if topk == 1:
|
| 80 |
+
idx_sort = [np.argmax(scores_flat)]
|
| 81 |
+
elif len(scores_flat) < topk:
|
| 82 |
+
idx_sort = np.argsort(-scores_flat)
|
| 83 |
+
else:
|
| 84 |
+
idx = np.argpartition(-scores_flat, topk)[0:topk]
|
| 85 |
+
idx_sort = idx[np.argsort(-scores_flat[idx])]
|
| 86 |
+
|
| 87 |
+
starts, ends = np.unravel_index(idx_sort, candidates.shape)[1:]
|
| 88 |
+
desired_spans = np.isin(starts, undesired_tokens.nonzero()) & np.isin(ends, undesired_tokens.nonzero())
|
| 89 |
+
starts = starts[desired_spans]
|
| 90 |
+
ends = ends[desired_spans]
|
| 91 |
+
scores = candidates[0, starts, ends]
|
| 92 |
+
|
| 93 |
+
return starts, ends, scores
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def select_starts_ends(
|
| 97 |
+
start,
|
| 98 |
+
end,
|
| 99 |
+
p_mask,
|
| 100 |
+
attention_mask,
|
| 101 |
+
min_null_score=1000000,
|
| 102 |
+
top_k=1,
|
| 103 |
+
handle_impossible_answer=False,
|
| 104 |
+
max_answer_len=15,
|
| 105 |
+
):
|
| 106 |
+
"""
|
| 107 |
+
Takes the raw output of any `ModelForQuestionAnswering` and first normalizes its outputs and then uses
|
| 108 |
+
`decode_spans()` to generate probabilities for each span to be the actual answer.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
start (`np.ndarray`): Individual start logits for each token.
|
| 112 |
+
end (`np.ndarray`): Individual end logits for each token.
|
| 113 |
+
p_mask (`np.ndarray`): A mask with 1 for values that cannot be in the answer
|
| 114 |
+
attention_mask (`np.ndarray`): The attention mask generated by the tokenizer
|
| 115 |
+
min_null_score(`float`): The minimum null (empty) answer score seen so far.
|
| 116 |
+
topk (`int`): Indicates how many possible answer span(s) to extract from the model output.
|
| 117 |
+
handle_impossible_answer(`bool`): Whether to allow null (empty) answers
|
| 118 |
+
max_answer_len (`int`): Maximum size of the answer to extract from the model's output.
|
| 119 |
+
"""
|
| 120 |
+
# Ensure padded tokens & question tokens cannot belong to the set of candidate answers.
|
| 121 |
+
undesired_tokens = np.abs(np.array(p_mask) - 1)
|
| 122 |
+
|
| 123 |
+
if attention_mask is not None:
|
| 124 |
+
undesired_tokens = undesired_tokens & attention_mask
|
| 125 |
+
|
| 126 |
+
# Generate mask
|
| 127 |
+
undesired_tokens_mask = undesired_tokens == 0.0
|
| 128 |
+
|
| 129 |
+
# Make sure non-context indexes in the tensor cannot contribute to the softmax
|
| 130 |
+
start = np.where(undesired_tokens_mask, -10000.0, start)
|
| 131 |
+
end = np.where(undesired_tokens_mask, -10000.0, end)
|
| 132 |
+
|
| 133 |
+
# Normalize logits and spans to retrieve the answer
|
| 134 |
+
start = np.exp(start - start.max(axis=-1, keepdims=True))
|
| 135 |
+
start = start / start.sum()
|
| 136 |
+
|
| 137 |
+
end = np.exp(end - end.max(axis=-1, keepdims=True))
|
| 138 |
+
end = end / end.sum()
|
| 139 |
+
|
| 140 |
+
if handle_impossible_answer:
|
| 141 |
+
min_null_score = min(min_null_score, (start[0, 0] * end[0, 0]).item())
|
| 142 |
+
|
| 143 |
+
# Mask CLS
|
| 144 |
+
start[0, 0] = end[0, 0] = 0.0
|
| 145 |
+
|
| 146 |
+
starts, ends, scores = decode_spans(start, end, top_k, max_answer_len, undesired_tokens)
|
| 147 |
+
return starts, ends, scores, min_null_score
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class QuestionAnsweringArgumentHandler(ArgumentHandler):
|
| 151 |
+
"""
|
| 152 |
+
QuestionAnsweringPipeline requires the user to provide multiple arguments (i.e. question & context) to be mapped to
|
| 153 |
+
internal [`SquadExample`].
|
| 154 |
+
|
| 155 |
+
QuestionAnsweringArgumentHandler manages all the possible to create a [`SquadExample`] from the command-line
|
| 156 |
+
supplied arguments.
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
def normalize(self, item):
|
| 160 |
+
if isinstance(item, SquadExample):
|
| 161 |
+
return item
|
| 162 |
+
elif isinstance(item, dict):
|
| 163 |
+
for k in ["question", "context"]:
|
| 164 |
+
if k not in item:
|
| 165 |
+
raise KeyError("You need to provide a dictionary with keys {question:..., context:...}")
|
| 166 |
+
elif item[k] is None:
|
| 167 |
+
raise ValueError(f"`{k}` cannot be None")
|
| 168 |
+
elif isinstance(item[k], str) and len(item[k]) == 0:
|
| 169 |
+
raise ValueError(f"`{k}` cannot be empty")
|
| 170 |
+
|
| 171 |
+
return QuestionAnsweringPipeline.create_sample(**item)
|
| 172 |
+
raise ValueError(f"{item} argument needs to be of type (SquadExample, dict)")
|
| 173 |
+
|
| 174 |
+
def __call__(self, *args, **kwargs):
|
| 175 |
+
# Detect where the actual inputs are
|
| 176 |
+
if args is not None and len(args) > 0:
|
| 177 |
+
if len(args) == 1:
|
| 178 |
+
inputs = args[0]
|
| 179 |
+
elif len(args) == 2 and {type(el) for el in args} == {str}:
|
| 180 |
+
inputs = [{"question": args[0], "context": args[1]}]
|
| 181 |
+
else:
|
| 182 |
+
inputs = list(args)
|
| 183 |
+
# Generic compatibility with sklearn and Keras
|
| 184 |
+
# Batched data
|
| 185 |
+
elif "X" in kwargs:
|
| 186 |
+
warnings.warn(
|
| 187 |
+
"Passing the `X` argument to the pipeline is deprecated and will be removed in v5. Inputs should be passed using the `question` and `context` keyword arguments instead.",
|
| 188 |
+
FutureWarning,
|
| 189 |
+
)
|
| 190 |
+
inputs = kwargs["X"]
|
| 191 |
+
elif "data" in kwargs:
|
| 192 |
+
warnings.warn(
|
| 193 |
+
"Passing the `data` argument to the pipeline is deprecated and will be removed in v5. Inputs should be passed using the `question` and `context` keyword arguments instead.",
|
| 194 |
+
FutureWarning,
|
| 195 |
+
)
|
| 196 |
+
inputs = kwargs["data"]
|
| 197 |
+
elif "question" in kwargs and "context" in kwargs:
|
| 198 |
+
if isinstance(kwargs["question"], list) and isinstance(kwargs["context"], str):
|
| 199 |
+
inputs = [{"question": Q, "context": kwargs["context"]} for Q in kwargs["question"]]
|
| 200 |
+
elif isinstance(kwargs["question"], list) and isinstance(kwargs["context"], list):
|
| 201 |
+
if len(kwargs["question"]) != len(kwargs["context"]):
|
| 202 |
+
raise ValueError("Questions and contexts don't have the same lengths")
|
| 203 |
+
|
| 204 |
+
inputs = [{"question": Q, "context": C} for Q, C in zip(kwargs["question"], kwargs["context"])]
|
| 205 |
+
elif isinstance(kwargs["question"], str) and isinstance(kwargs["context"], str):
|
| 206 |
+
inputs = [{"question": kwargs["question"], "context": kwargs["context"]}]
|
| 207 |
+
else:
|
| 208 |
+
raise ValueError("Arguments can't be understood")
|
| 209 |
+
else:
|
| 210 |
+
raise ValueError(f"Unknown arguments {kwargs}")
|
| 211 |
+
|
| 212 |
+
# When user is sending a generator we need to trust it's a valid example
|
| 213 |
+
generator_types = (types.GeneratorType, Dataset) if Dataset is not None else (types.GeneratorType,)
|
| 214 |
+
if isinstance(inputs, generator_types):
|
| 215 |
+
return inputs
|
| 216 |
+
|
| 217 |
+
# Normalize inputs
|
| 218 |
+
if isinstance(inputs, dict):
|
| 219 |
+
inputs = [inputs]
|
| 220 |
+
elif isinstance(inputs, Iterable):
|
| 221 |
+
# Copy to avoid overriding arguments
|
| 222 |
+
inputs = list(inputs)
|
| 223 |
+
else:
|
| 224 |
+
raise ValueError(f"Invalid arguments {kwargs}")
|
| 225 |
+
|
| 226 |
+
for i, item in enumerate(inputs):
|
| 227 |
+
inputs[i] = self.normalize(item)
|
| 228 |
+
|
| 229 |
+
return inputs
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
|
| 233 |
+
class QuestionAnsweringPipeline(ChunkPipeline):
|
| 234 |
+
"""
|
| 235 |
+
Question Answering pipeline using any `ModelForQuestionAnswering`. See the [question answering
|
| 236 |
+
examples](../task_summary#question-answering) for more information.
|
| 237 |
+
|
| 238 |
+
Example:
|
| 239 |
+
|
| 240 |
+
```python
|
| 241 |
+
>>> from transformers import pipeline
|
| 242 |
+
|
| 243 |
+
>>> oracle = pipeline(model="deepset/roberta-base-squad2")
|
| 244 |
+
>>> oracle(question="Where do I live?", context="My name is Wolfgang and I live in Berlin")
|
| 245 |
+
{'score': 0.9191, 'start': 34, 'end': 40, 'answer': 'Berlin'}
|
| 246 |
+
```
|
| 247 |
+
|
| 248 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
| 249 |
+
|
| 250 |
+
This question answering pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 251 |
+
`"question-answering"`.
|
| 252 |
+
|
| 253 |
+
The models that this pipeline can use are models that have been fine-tuned on a question answering task. See the
|
| 254 |
+
up-to-date list of available models on
|
| 255 |
+
[huggingface.co/models](https://huggingface.co/models?filter=question-answering).
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
default_input_names = "question,context"
|
| 259 |
+
handle_impossible_answer = False
|
| 260 |
+
|
| 261 |
+
def __init__(
|
| 262 |
+
self,
|
| 263 |
+
model: Union["PreTrainedModel", "TFPreTrainedModel"],
|
| 264 |
+
tokenizer: PreTrainedTokenizer,
|
| 265 |
+
modelcard: Optional[ModelCard] = None,
|
| 266 |
+
framework: Optional[str] = None,
|
| 267 |
+
task: str = "",
|
| 268 |
+
**kwargs,
|
| 269 |
+
):
|
| 270 |
+
super().__init__(
|
| 271 |
+
model=model,
|
| 272 |
+
tokenizer=tokenizer,
|
| 273 |
+
modelcard=modelcard,
|
| 274 |
+
framework=framework,
|
| 275 |
+
task=task,
|
| 276 |
+
**kwargs,
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
self._args_parser = QuestionAnsweringArgumentHandler()
|
| 280 |
+
self.check_model_type(
|
| 281 |
+
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
|
| 282 |
+
if self.framework == "tf"
|
| 283 |
+
else MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
@staticmethod
|
| 287 |
+
def create_sample(
|
| 288 |
+
question: Union[str, List[str]], context: Union[str, List[str]]
|
| 289 |
+
) -> Union[SquadExample, List[SquadExample]]:
|
| 290 |
+
"""
|
| 291 |
+
QuestionAnsweringPipeline leverages the [`SquadExample`] internally. This helper method encapsulate all the
|
| 292 |
+
logic for converting question(s) and context(s) to [`SquadExample`].
|
| 293 |
+
|
| 294 |
+
We currently support extractive question answering.
|
| 295 |
+
|
| 296 |
+
Arguments:
|
| 297 |
+
question (`str` or `List[str]`): The question(s) asked.
|
| 298 |
+
context (`str` or `List[str]`): The context(s) in which we will look for the answer.
|
| 299 |
+
|
| 300 |
+
Returns:
|
| 301 |
+
One or a list of [`SquadExample`]: The corresponding [`SquadExample`] grouping question and context.
|
| 302 |
+
"""
|
| 303 |
+
if isinstance(question, list):
|
| 304 |
+
return [SquadExample(None, q, c, None, None, None) for q, c in zip(question, context)]
|
| 305 |
+
else:
|
| 306 |
+
return SquadExample(None, question, context, None, None, None)
|
| 307 |
+
|
| 308 |
+
def _sanitize_parameters(
|
| 309 |
+
self,
|
| 310 |
+
padding=None,
|
| 311 |
+
topk=None,
|
| 312 |
+
top_k=None,
|
| 313 |
+
doc_stride=None,
|
| 314 |
+
max_answer_len=None,
|
| 315 |
+
max_seq_len=None,
|
| 316 |
+
max_question_len=None,
|
| 317 |
+
handle_impossible_answer=None,
|
| 318 |
+
align_to_words=None,
|
| 319 |
+
**kwargs,
|
| 320 |
+
):
|
| 321 |
+
# Set defaults values
|
| 322 |
+
preprocess_params = {}
|
| 323 |
+
if padding is not None:
|
| 324 |
+
preprocess_params["padding"] = padding
|
| 325 |
+
if doc_stride is not None:
|
| 326 |
+
preprocess_params["doc_stride"] = doc_stride
|
| 327 |
+
if max_question_len is not None:
|
| 328 |
+
preprocess_params["max_question_len"] = max_question_len
|
| 329 |
+
if max_seq_len is not None:
|
| 330 |
+
preprocess_params["max_seq_len"] = max_seq_len
|
| 331 |
+
|
| 332 |
+
postprocess_params = {}
|
| 333 |
+
if topk is not None and top_k is None:
|
| 334 |
+
warnings.warn("topk parameter is deprecated, use top_k instead", UserWarning)
|
| 335 |
+
top_k = topk
|
| 336 |
+
if top_k is not None:
|
| 337 |
+
if top_k < 1:
|
| 338 |
+
raise ValueError(f"top_k parameter should be >= 1 (got {top_k})")
|
| 339 |
+
postprocess_params["top_k"] = top_k
|
| 340 |
+
if max_answer_len is not None:
|
| 341 |
+
if max_answer_len < 1:
|
| 342 |
+
raise ValueError(f"max_answer_len parameter should be >= 1 (got {max_answer_len}")
|
| 343 |
+
if max_answer_len is not None:
|
| 344 |
+
postprocess_params["max_answer_len"] = max_answer_len
|
| 345 |
+
if handle_impossible_answer is not None:
|
| 346 |
+
postprocess_params["handle_impossible_answer"] = handle_impossible_answer
|
| 347 |
+
if align_to_words is not None:
|
| 348 |
+
postprocess_params["align_to_words"] = align_to_words
|
| 349 |
+
return preprocess_params, {}, postprocess_params
|
| 350 |
+
|
| 351 |
+
def __call__(self, *args, **kwargs):
|
| 352 |
+
"""
|
| 353 |
+
Answer the question(s) given as inputs by using the context(s).
|
| 354 |
+
|
| 355 |
+
Args:
|
| 356 |
+
question (`str` or `List[str]`):
|
| 357 |
+
One or several question(s) (must be used in conjunction with the `context` argument).
|
| 358 |
+
context (`str` or `List[str]`):
|
| 359 |
+
One or several context(s) associated with the question(s) (must be used in conjunction with the
|
| 360 |
+
`question` argument).
|
| 361 |
+
top_k (`int`, *optional*, defaults to 1):
|
| 362 |
+
The number of answers to return (will be chosen by order of likelihood). Note that we return less than
|
| 363 |
+
top_k answers if there are not enough options available within the context.
|
| 364 |
+
doc_stride (`int`, *optional*, defaults to 128):
|
| 365 |
+
If the context is too long to fit with the question for the model, it will be split in several chunks
|
| 366 |
+
with some overlap. This argument controls the size of that overlap.
|
| 367 |
+
max_answer_len (`int`, *optional*, defaults to 15):
|
| 368 |
+
The maximum length of predicted answers (e.g., only answers with a shorter length are considered).
|
| 369 |
+
max_seq_len (`int`, *optional*, defaults to 384):
|
| 370 |
+
The maximum length of the total sentence (context + question) in tokens of each chunk passed to the
|
| 371 |
+
model. The context will be split in several chunks (using `doc_stride` as overlap) if needed.
|
| 372 |
+
max_question_len (`int`, *optional*, defaults to 64):
|
| 373 |
+
The maximum length of the question after tokenization. It will be truncated if needed.
|
| 374 |
+
handle_impossible_answer (`bool`, *optional*, defaults to `False`):
|
| 375 |
+
Whether or not we accept impossible as an answer.
|
| 376 |
+
align_to_words (`bool`, *optional*, defaults to `True`):
|
| 377 |
+
Attempts to align the answer to real words. Improves quality on space separated languages. Might hurt on
|
| 378 |
+
non-space-separated languages (like Japanese or Chinese)
|
| 379 |
+
|
| 380 |
+
Return:
|
| 381 |
+
A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys:
|
| 382 |
+
|
| 383 |
+
- **score** (`float`) -- The probability associated to the answer.
|
| 384 |
+
- **start** (`int`) -- The character start index of the answer (in the tokenized version of the input).
|
| 385 |
+
- **end** (`int`) -- The character end index of the answer (in the tokenized version of the input).
|
| 386 |
+
- **answer** (`str`) -- The answer to the question.
|
| 387 |
+
"""
|
| 388 |
+
|
| 389 |
+
# Convert inputs to features
|
| 390 |
+
if args:
|
| 391 |
+
warnings.warn(
|
| 392 |
+
"Passing a list of SQuAD examples to the pipeline is deprecated and will be removed in v5. Inputs should be passed using the `question` and `context` keyword arguments instead.",
|
| 393 |
+
FutureWarning,
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
examples = self._args_parser(*args, **kwargs)
|
| 397 |
+
if isinstance(examples, (list, tuple)) and len(examples) == 1:
|
| 398 |
+
return super().__call__(examples[0], **kwargs)
|
| 399 |
+
return super().__call__(examples, **kwargs)
|
| 400 |
+
|
| 401 |
+
def preprocess(self, example, padding="do_not_pad", doc_stride=None, max_question_len=64, max_seq_len=None):
|
| 402 |
+
# XXX: This is specal, args_parser will not handle anything generator or dataset like
|
| 403 |
+
# For those we expect user to send a simple valid example either directly as a SquadExample or simple dict.
|
| 404 |
+
# So we still need a little sanitation here.
|
| 405 |
+
if isinstance(example, dict):
|
| 406 |
+
example = SquadExample(None, example["question"], example["context"], None, None, None)
|
| 407 |
+
|
| 408 |
+
if max_seq_len is None:
|
| 409 |
+
max_seq_len = min(self.tokenizer.model_max_length, 384)
|
| 410 |
+
if doc_stride is None:
|
| 411 |
+
doc_stride = min(max_seq_len // 2, 128)
|
| 412 |
+
|
| 413 |
+
if doc_stride > max_seq_len:
|
| 414 |
+
raise ValueError(f"`doc_stride` ({doc_stride}) is larger than `max_seq_len` ({max_seq_len})")
|
| 415 |
+
|
| 416 |
+
if not self.tokenizer.is_fast:
|
| 417 |
+
features = squad_convert_examples_to_features(
|
| 418 |
+
examples=[example],
|
| 419 |
+
tokenizer=self.tokenizer,
|
| 420 |
+
max_seq_length=max_seq_len,
|
| 421 |
+
doc_stride=doc_stride,
|
| 422 |
+
max_query_length=max_question_len,
|
| 423 |
+
padding_strategy=PaddingStrategy.MAX_LENGTH,
|
| 424 |
+
is_training=False,
|
| 425 |
+
tqdm_enabled=False,
|
| 426 |
+
)
|
| 427 |
+
else:
|
| 428 |
+
# Define the side we want to truncate / pad and the text/pair sorting
|
| 429 |
+
question_first = self.tokenizer.padding_side == "right"
|
| 430 |
+
|
| 431 |
+
encoded_inputs = self.tokenizer(
|
| 432 |
+
text=example.question_text if question_first else example.context_text,
|
| 433 |
+
text_pair=example.context_text if question_first else example.question_text,
|
| 434 |
+
padding=padding,
|
| 435 |
+
truncation="only_second" if question_first else "only_first",
|
| 436 |
+
max_length=max_seq_len,
|
| 437 |
+
stride=doc_stride,
|
| 438 |
+
return_token_type_ids=True,
|
| 439 |
+
return_overflowing_tokens=True,
|
| 440 |
+
return_offsets_mapping=True,
|
| 441 |
+
return_special_tokens_mask=True,
|
| 442 |
+
)
|
| 443 |
+
# When the input is too long, it's converted in a batch of inputs with overflowing tokens
|
| 444 |
+
# and a stride of overlap between the inputs. If a batch of inputs is given, a special output
|
| 445 |
+
# "overflow_to_sample_mapping" indicate which member of the encoded batch belong to which original batch sample.
|
| 446 |
+
# Here we tokenize examples one-by-one so we don't need to use "overflow_to_sample_mapping".
|
| 447 |
+
# "num_span" is the number of output samples generated from the overflowing tokens.
|
| 448 |
+
num_spans = len(encoded_inputs["input_ids"])
|
| 449 |
+
|
| 450 |
+
# p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer)
|
| 451 |
+
# We put 0 on the tokens from the context and 1 everywhere else (question and special tokens)
|
| 452 |
+
p_mask = [
|
| 453 |
+
[tok != 1 if question_first else 0 for tok in encoded_inputs.sequence_ids(span_id)]
|
| 454 |
+
for span_id in range(num_spans)
|
| 455 |
+
]
|
| 456 |
+
|
| 457 |
+
features = []
|
| 458 |
+
for span_idx in range(num_spans):
|
| 459 |
+
input_ids_span_idx = encoded_inputs["input_ids"][span_idx]
|
| 460 |
+
attention_mask_span_idx = (
|
| 461 |
+
encoded_inputs["attention_mask"][span_idx] if "attention_mask" in encoded_inputs else None
|
| 462 |
+
)
|
| 463 |
+
token_type_ids_span_idx = (
|
| 464 |
+
encoded_inputs["token_type_ids"][span_idx] if "token_type_ids" in encoded_inputs else None
|
| 465 |
+
)
|
| 466 |
+
# keep the cls_token unmasked (some models use it to indicate unanswerable questions)
|
| 467 |
+
if self.tokenizer.cls_token_id is not None:
|
| 468 |
+
cls_indices = np.nonzero(np.array(input_ids_span_idx) == self.tokenizer.cls_token_id)[0]
|
| 469 |
+
for cls_index in cls_indices:
|
| 470 |
+
p_mask[span_idx][cls_index] = 0
|
| 471 |
+
submask = p_mask[span_idx]
|
| 472 |
+
features.append(
|
| 473 |
+
SquadFeatures(
|
| 474 |
+
input_ids=input_ids_span_idx,
|
| 475 |
+
attention_mask=attention_mask_span_idx,
|
| 476 |
+
token_type_ids=token_type_ids_span_idx,
|
| 477 |
+
p_mask=submask,
|
| 478 |
+
encoding=encoded_inputs[span_idx],
|
| 479 |
+
# We don't use the rest of the values - and actually
|
| 480 |
+
# for Fast tokenizer we could totally avoid using SquadFeatures and SquadExample
|
| 481 |
+
cls_index=None,
|
| 482 |
+
token_to_orig_map={},
|
| 483 |
+
example_index=0,
|
| 484 |
+
unique_id=0,
|
| 485 |
+
paragraph_len=0,
|
| 486 |
+
token_is_max_context=0,
|
| 487 |
+
tokens=[],
|
| 488 |
+
start_position=0,
|
| 489 |
+
end_position=0,
|
| 490 |
+
is_impossible=False,
|
| 491 |
+
qas_id=None,
|
| 492 |
+
)
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
for i, feature in enumerate(features):
|
| 496 |
+
fw_args = {}
|
| 497 |
+
others = {}
|
| 498 |
+
model_input_names = self.tokenizer.model_input_names + ["p_mask", "token_type_ids"]
|
| 499 |
+
|
| 500 |
+
for k, v in feature.__dict__.items():
|
| 501 |
+
if k in model_input_names:
|
| 502 |
+
if self.framework == "tf":
|
| 503 |
+
tensor = tf.constant(v)
|
| 504 |
+
if tensor.dtype == tf.int64:
|
| 505 |
+
tensor = tf.cast(tensor, tf.int32)
|
| 506 |
+
fw_args[k] = tf.expand_dims(tensor, 0)
|
| 507 |
+
elif self.framework == "pt":
|
| 508 |
+
tensor = torch.tensor(v)
|
| 509 |
+
if tensor.dtype == torch.int32:
|
| 510 |
+
tensor = tensor.long()
|
| 511 |
+
fw_args[k] = tensor.unsqueeze(0)
|
| 512 |
+
else:
|
| 513 |
+
others[k] = v
|
| 514 |
+
|
| 515 |
+
is_last = i == len(features) - 1
|
| 516 |
+
yield {"example": example, "is_last": is_last, **fw_args, **others}
|
| 517 |
+
|
| 518 |
+
def _forward(self, inputs):
|
| 519 |
+
example = inputs["example"]
|
| 520 |
+
model_inputs = {k: inputs[k] for k in self.tokenizer.model_input_names}
|
| 521 |
+
# `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported
|
| 522 |
+
model_forward = self.model.forward if self.framework == "pt" else self.model.call
|
| 523 |
+
if "use_cache" in inspect.signature(model_forward).parameters.keys():
|
| 524 |
+
model_inputs["use_cache"] = False
|
| 525 |
+
output = self.model(**model_inputs)
|
| 526 |
+
if isinstance(output, dict):
|
| 527 |
+
return {"start": output["start_logits"], "end": output["end_logits"], "example": example, **inputs}
|
| 528 |
+
else:
|
| 529 |
+
start, end = output[:2]
|
| 530 |
+
return {"start": start, "end": end, "example": example, **inputs}
|
| 531 |
+
|
| 532 |
+
def postprocess(
|
| 533 |
+
self,
|
| 534 |
+
model_outputs,
|
| 535 |
+
top_k=1,
|
| 536 |
+
handle_impossible_answer=False,
|
| 537 |
+
max_answer_len=15,
|
| 538 |
+
align_to_words=True,
|
| 539 |
+
):
|
| 540 |
+
min_null_score = 1000000 # large and positive
|
| 541 |
+
answers = []
|
| 542 |
+
for output in model_outputs:
|
| 543 |
+
if self.framework == "pt" and output["start"].dtype == torch.bfloat16:
|
| 544 |
+
start_ = output["start"].to(torch.float32)
|
| 545 |
+
else:
|
| 546 |
+
start_ = output["start"]
|
| 547 |
+
if self.framework == "pt" and output["start"].dtype == torch.bfloat16:
|
| 548 |
+
end_ = output["end"].to(torch.float32)
|
| 549 |
+
else:
|
| 550 |
+
end_ = output["end"]
|
| 551 |
+
example = output["example"]
|
| 552 |
+
p_mask = output["p_mask"]
|
| 553 |
+
attention_mask = (
|
| 554 |
+
output["attention_mask"].numpy() if output.get("attention_mask", None) is not None else None
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
starts, ends, scores, min_null_score = select_starts_ends(
|
| 558 |
+
start_, end_, p_mask, attention_mask, min_null_score, top_k, handle_impossible_answer, max_answer_len
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
if not self.tokenizer.is_fast:
|
| 562 |
+
char_to_word = np.array(example.char_to_word_offset)
|
| 563 |
+
|
| 564 |
+
# Convert the answer (tokens) back to the original text
|
| 565 |
+
# Score: score from the model
|
| 566 |
+
# Start: Index of the first character of the answer in the context string
|
| 567 |
+
# End: Index of the character following the last character of the answer in the context string
|
| 568 |
+
# Answer: Plain text of the answer
|
| 569 |
+
for s, e, score in zip(starts, ends, scores):
|
| 570 |
+
token_to_orig_map = output["token_to_orig_map"]
|
| 571 |
+
answers.append(
|
| 572 |
+
{
|
| 573 |
+
"score": score.item(),
|
| 574 |
+
"start": np.where(char_to_word == token_to_orig_map[s])[0][0].item(),
|
| 575 |
+
"end": np.where(char_to_word == token_to_orig_map[e])[0][-1].item(),
|
| 576 |
+
"answer": " ".join(example.doc_tokens[token_to_orig_map[s] : token_to_orig_map[e] + 1]),
|
| 577 |
+
}
|
| 578 |
+
)
|
| 579 |
+
else:
|
| 580 |
+
# Convert the answer (tokens) back to the original text
|
| 581 |
+
# Score: score from the model
|
| 582 |
+
# Start: Index of the first character of the answer in the context string
|
| 583 |
+
# End: Index of the character following the last character of the answer in the context string
|
| 584 |
+
# Answer: Plain text of the answer
|
| 585 |
+
question_first = bool(self.tokenizer.padding_side == "right")
|
| 586 |
+
enc = output["encoding"]
|
| 587 |
+
|
| 588 |
+
# Encoding was *not* padded, input_ids *might*.
|
| 589 |
+
# It doesn't make a difference unless we're padding on
|
| 590 |
+
# the left hand side, since now we have different offsets
|
| 591 |
+
# everywhere.
|
| 592 |
+
if self.tokenizer.padding_side == "left":
|
| 593 |
+
offset = (output["input_ids"] == self.tokenizer.pad_token_id).numpy().sum()
|
| 594 |
+
else:
|
| 595 |
+
offset = 0
|
| 596 |
+
|
| 597 |
+
# Sometimes the max probability token is in the middle of a word so:
|
| 598 |
+
# - we start by finding the right word containing the token with `token_to_word`
|
| 599 |
+
# - then we convert this word in a character span with `word_to_chars`
|
| 600 |
+
sequence_index = 1 if question_first else 0
|
| 601 |
+
for s, e, score in zip(starts, ends, scores):
|
| 602 |
+
s = s - offset
|
| 603 |
+
e = e - offset
|
| 604 |
+
|
| 605 |
+
start_index, end_index = self.get_indices(enc, s, e, sequence_index, align_to_words)
|
| 606 |
+
|
| 607 |
+
answers.append(
|
| 608 |
+
{
|
| 609 |
+
"score": score.item(),
|
| 610 |
+
"start": start_index,
|
| 611 |
+
"end": end_index,
|
| 612 |
+
"answer": example.context_text[start_index:end_index],
|
| 613 |
+
}
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
if handle_impossible_answer:
|
| 617 |
+
answers.append({"score": min_null_score, "start": 0, "end": 0, "answer": ""})
|
| 618 |
+
answers = sorted(answers, key=lambda x: x["score"], reverse=True)[:top_k]
|
| 619 |
+
if len(answers) == 1:
|
| 620 |
+
return answers[0]
|
| 621 |
+
return answers
|
| 622 |
+
|
| 623 |
+
def get_indices(
|
| 624 |
+
self, enc: "tokenizers.Encoding", s: int, e: int, sequence_index: int, align_to_words: bool
|
| 625 |
+
) -> Tuple[int, int]:
|
| 626 |
+
if align_to_words:
|
| 627 |
+
try:
|
| 628 |
+
start_word = enc.token_to_word(s)
|
| 629 |
+
end_word = enc.token_to_word(e)
|
| 630 |
+
start_index = enc.word_to_chars(start_word, sequence_index=sequence_index)[0]
|
| 631 |
+
end_index = enc.word_to_chars(end_word, sequence_index=sequence_index)[1]
|
| 632 |
+
except Exception:
|
| 633 |
+
# Some tokenizers don't really handle words. Keep to offsets then.
|
| 634 |
+
start_index = enc.offsets[s][0]
|
| 635 |
+
end_index = enc.offsets[e][1]
|
| 636 |
+
else:
|
| 637 |
+
start_index = enc.offsets[s][0]
|
| 638 |
+
end_index = enc.offsets[e][1]
|
| 639 |
+
return start_index, end_index
|
| 640 |
+
|
| 641 |
+
def span_to_answer(self, text: str, start: int, end: int) -> Dict[str, Union[str, int]]:
|
| 642 |
+
"""
|
| 643 |
+
When decoding from token probabilities, this method maps token indexes to actual word in the initial context.
|
| 644 |
+
|
| 645 |
+
Args:
|
| 646 |
+
text (`str`): The actual context to extract the answer from.
|
| 647 |
+
start (`int`): The answer starting token index.
|
| 648 |
+
end (`int`): The answer end token index.
|
| 649 |
+
|
| 650 |
+
Returns:
|
| 651 |
+
Dictionary like `{'answer': str, 'start': int, 'end': int}`
|
| 652 |
+
"""
|
| 653 |
+
words = []
|
| 654 |
+
token_idx = char_start_idx = char_end_idx = chars_idx = 0
|
| 655 |
+
|
| 656 |
+
for i, word in enumerate(text.split(" ")):
|
| 657 |
+
token = self.tokenizer.tokenize(word)
|
| 658 |
+
|
| 659 |
+
# Append words if they are in the span
|
| 660 |
+
if start <= token_idx <= end:
|
| 661 |
+
if token_idx == start:
|
| 662 |
+
char_start_idx = chars_idx
|
| 663 |
+
|
| 664 |
+
if token_idx == end:
|
| 665 |
+
char_end_idx = chars_idx + len(word)
|
| 666 |
+
|
| 667 |
+
words += [word]
|
| 668 |
+
|
| 669 |
+
# Stop if we went over the end of the answer
|
| 670 |
+
if token_idx > end:
|
| 671 |
+
break
|
| 672 |
+
|
| 673 |
+
# Append the subtokenization length to the running index
|
| 674 |
+
token_idx += len(token)
|
| 675 |
+
chars_idx += len(word) + 1
|
| 676 |
+
|
| 677 |
+
# Join text with spaces
|
| 678 |
+
return {
|
| 679 |
+
"answer": " ".join(words),
|
| 680 |
+
"start": max(0, char_start_idx),
|
| 681 |
+
"end": min(len(text), char_end_idx),
|
| 682 |
+
}
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/table_question_answering.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
import types
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from ..utils import (
|
| 7 |
+
add_end_docstrings,
|
| 8 |
+
is_tf_available,
|
| 9 |
+
is_torch_available,
|
| 10 |
+
requires_backends,
|
| 11 |
+
)
|
| 12 |
+
from .base import ArgumentHandler, Dataset, Pipeline, PipelineException, build_pipeline_init_args
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
if is_torch_available():
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
from ..models.auto.modeling_auto import (
|
| 19 |
+
MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
|
| 20 |
+
MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
if is_tf_available():
|
| 24 |
+
import tensorflow as tf
|
| 25 |
+
|
| 26 |
+
from ..models.auto.modeling_tf_auto import (
|
| 27 |
+
TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
|
| 28 |
+
TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TableQuestionAnsweringArgumentHandler(ArgumentHandler):
|
| 33 |
+
"""
|
| 34 |
+
Handles arguments for the TableQuestionAnsweringPipeline
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __call__(self, table=None, query=None, **kwargs):
|
| 38 |
+
# Returns tqa_pipeline_inputs of shape:
|
| 39 |
+
# [
|
| 40 |
+
# {"table": pd.DataFrame, "query": List[str]},
|
| 41 |
+
# ...,
|
| 42 |
+
# {"table": pd.DataFrame, "query" : List[str]}
|
| 43 |
+
# ]
|
| 44 |
+
requires_backends(self, "pandas")
|
| 45 |
+
import pandas as pd
|
| 46 |
+
|
| 47 |
+
if table is None:
|
| 48 |
+
raise ValueError("Keyword argument `table` cannot be None.")
|
| 49 |
+
elif query is None:
|
| 50 |
+
if isinstance(table, dict) and table.get("query") is not None and table.get("table") is not None:
|
| 51 |
+
tqa_pipeline_inputs = [table]
|
| 52 |
+
elif isinstance(table, list) and len(table) > 0:
|
| 53 |
+
if not all(isinstance(d, dict) for d in table):
|
| 54 |
+
raise ValueError(
|
| 55 |
+
f"Keyword argument `table` should be a list of dict, but is {(type(d) for d in table)}"
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
if table[0].get("query") is not None and table[0].get("table") is not None:
|
| 59 |
+
tqa_pipeline_inputs = table
|
| 60 |
+
else:
|
| 61 |
+
raise ValueError(
|
| 62 |
+
"If keyword argument `table` is a list of dictionaries, each dictionary should have a `table`"
|
| 63 |
+
f" and `query` key, but only dictionary has keys {table[0].keys()} `table` and `query` keys."
|
| 64 |
+
)
|
| 65 |
+
elif Dataset is not None and isinstance(table, Dataset) or isinstance(table, types.GeneratorType):
|
| 66 |
+
return table
|
| 67 |
+
else:
|
| 68 |
+
raise ValueError(
|
| 69 |
+
"Invalid input. Keyword argument `table` should be either of type `dict` or `list`, but "
|
| 70 |
+
f"is {type(table)})"
|
| 71 |
+
)
|
| 72 |
+
else:
|
| 73 |
+
tqa_pipeline_inputs = [{"table": table, "query": query}]
|
| 74 |
+
|
| 75 |
+
for tqa_pipeline_input in tqa_pipeline_inputs:
|
| 76 |
+
if not isinstance(tqa_pipeline_input["table"], pd.DataFrame):
|
| 77 |
+
if tqa_pipeline_input["table"] is None:
|
| 78 |
+
raise ValueError("Table cannot be None.")
|
| 79 |
+
|
| 80 |
+
tqa_pipeline_input["table"] = pd.DataFrame(tqa_pipeline_input["table"])
|
| 81 |
+
|
| 82 |
+
return tqa_pipeline_inputs
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
|
| 86 |
+
class TableQuestionAnsweringPipeline(Pipeline):
|
| 87 |
+
"""
|
| 88 |
+
Table Question Answering pipeline using a `ModelForTableQuestionAnswering`. This pipeline is only available in
|
| 89 |
+
PyTorch.
|
| 90 |
+
|
| 91 |
+
Example:
|
| 92 |
+
|
| 93 |
+
```python
|
| 94 |
+
>>> from transformers import pipeline
|
| 95 |
+
|
| 96 |
+
>>> oracle = pipeline(model="google/tapas-base-finetuned-wtq")
|
| 97 |
+
>>> table = {
|
| 98 |
+
... "Repository": ["Transformers", "Datasets", "Tokenizers"],
|
| 99 |
+
... "Stars": ["36542", "4512", "3934"],
|
| 100 |
+
... "Contributors": ["651", "77", "34"],
|
| 101 |
+
... "Programming language": ["Python", "Python", "Rust, Python and NodeJS"],
|
| 102 |
+
... }
|
| 103 |
+
>>> oracle(query="How many stars does the transformers repository have?", table=table)
|
| 104 |
+
{'answer': 'AVERAGE > 36542', 'coordinates': [(0, 1)], 'cells': ['36542'], 'aggregator': 'AVERAGE'}
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
| 108 |
+
|
| 109 |
+
This tabular question answering pipeline can currently be loaded from [`pipeline`] using the following task
|
| 110 |
+
identifier: `"table-question-answering"`.
|
| 111 |
+
|
| 112 |
+
The models that this pipeline can use are models that have been fine-tuned on a tabular question answering task.
|
| 113 |
+
See the up-to-date list of available models on
|
| 114 |
+
[huggingface.co/models](https://huggingface.co/models?filter=table-question-answering).
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
default_input_names = "table,query"
|
| 118 |
+
|
| 119 |
+
def __init__(self, args_parser=TableQuestionAnsweringArgumentHandler(), *args, **kwargs):
|
| 120 |
+
super().__init__(*args, **kwargs)
|
| 121 |
+
self._args_parser = args_parser
|
| 122 |
+
|
| 123 |
+
if self.framework == "tf":
|
| 124 |
+
mapping = TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES.copy()
|
| 125 |
+
mapping.update(TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES)
|
| 126 |
+
else:
|
| 127 |
+
mapping = MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES.copy()
|
| 128 |
+
mapping.update(MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES)
|
| 129 |
+
self.check_model_type(mapping)
|
| 130 |
+
|
| 131 |
+
self.aggregate = bool(getattr(self.model.config, "aggregation_labels", None)) and bool(
|
| 132 |
+
getattr(self.model.config, "num_aggregation_labels", None)
|
| 133 |
+
)
|
| 134 |
+
self.type = "tapas" if hasattr(self.model.config, "aggregation_labels") else None
|
| 135 |
+
|
| 136 |
+
def batch_inference(self, **inputs):
|
| 137 |
+
return self.model(**inputs)
|
| 138 |
+
|
| 139 |
+
def sequential_inference(self, **inputs):
|
| 140 |
+
"""
|
| 141 |
+
Inference used for models that need to process sequences in a sequential fashion, like the SQA models which
|
| 142 |
+
handle conversational query related to a table.
|
| 143 |
+
"""
|
| 144 |
+
if self.framework == "pt":
|
| 145 |
+
all_logits = []
|
| 146 |
+
all_aggregations = []
|
| 147 |
+
prev_answers = None
|
| 148 |
+
batch_size = inputs["input_ids"].shape[0]
|
| 149 |
+
|
| 150 |
+
input_ids = inputs["input_ids"].to(self.device)
|
| 151 |
+
attention_mask = inputs["attention_mask"].to(self.device)
|
| 152 |
+
token_type_ids = inputs["token_type_ids"].to(self.device)
|
| 153 |
+
token_type_ids_example = None
|
| 154 |
+
|
| 155 |
+
for index in range(batch_size):
|
| 156 |
+
# If sequences have already been processed, the token type IDs will be created according to the previous
|
| 157 |
+
# answer.
|
| 158 |
+
if prev_answers is not None:
|
| 159 |
+
prev_labels_example = token_type_ids_example[:, 3] # shape (seq_len,)
|
| 160 |
+
model_labels = np.zeros_like(prev_labels_example.cpu().numpy()) # shape (seq_len,)
|
| 161 |
+
|
| 162 |
+
token_type_ids_example = token_type_ids[index] # shape (seq_len, 7)
|
| 163 |
+
for i in range(model_labels.shape[0]):
|
| 164 |
+
segment_id = token_type_ids_example[:, 0].tolist()[i]
|
| 165 |
+
col_id = token_type_ids_example[:, 1].tolist()[i] - 1
|
| 166 |
+
row_id = token_type_ids_example[:, 2].tolist()[i] - 1
|
| 167 |
+
|
| 168 |
+
if row_id >= 0 and col_id >= 0 and segment_id == 1:
|
| 169 |
+
model_labels[i] = int(prev_answers[(col_id, row_id)])
|
| 170 |
+
|
| 171 |
+
token_type_ids_example[:, 3] = torch.from_numpy(model_labels).type(torch.long).to(self.device)
|
| 172 |
+
|
| 173 |
+
input_ids_example = input_ids[index]
|
| 174 |
+
attention_mask_example = attention_mask[index] # shape (seq_len,)
|
| 175 |
+
token_type_ids_example = token_type_ids[index] # shape (seq_len, 7)
|
| 176 |
+
outputs = self.model(
|
| 177 |
+
input_ids=input_ids_example.unsqueeze(0),
|
| 178 |
+
attention_mask=attention_mask_example.unsqueeze(0),
|
| 179 |
+
token_type_ids=token_type_ids_example.unsqueeze(0),
|
| 180 |
+
)
|
| 181 |
+
logits = outputs.logits
|
| 182 |
+
|
| 183 |
+
if self.aggregate:
|
| 184 |
+
all_aggregations.append(outputs.logits_aggregation)
|
| 185 |
+
|
| 186 |
+
all_logits.append(logits)
|
| 187 |
+
|
| 188 |
+
dist_per_token = torch.distributions.Bernoulli(logits=logits)
|
| 189 |
+
probabilities = dist_per_token.probs * attention_mask_example.type(torch.float32).to(
|
| 190 |
+
dist_per_token.probs.device
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
coords_to_probs = collections.defaultdict(list)
|
| 194 |
+
for i, p in enumerate(probabilities.squeeze().tolist()):
|
| 195 |
+
segment_id = token_type_ids_example[:, 0].tolist()[i]
|
| 196 |
+
col = token_type_ids_example[:, 1].tolist()[i] - 1
|
| 197 |
+
row = token_type_ids_example[:, 2].tolist()[i] - 1
|
| 198 |
+
if col >= 0 and row >= 0 and segment_id == 1:
|
| 199 |
+
coords_to_probs[(col, row)].append(p)
|
| 200 |
+
|
| 201 |
+
prev_answers = {key: np.array(coords_to_probs[key]).mean() > 0.5 for key in coords_to_probs}
|
| 202 |
+
|
| 203 |
+
logits_batch = torch.cat(tuple(all_logits), 0)
|
| 204 |
+
|
| 205 |
+
return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(all_aggregations), 0))
|
| 206 |
+
else:
|
| 207 |
+
all_logits = []
|
| 208 |
+
all_aggregations = []
|
| 209 |
+
prev_answers = None
|
| 210 |
+
batch_size = inputs["input_ids"].shape[0]
|
| 211 |
+
|
| 212 |
+
input_ids = inputs["input_ids"]
|
| 213 |
+
attention_mask = inputs["attention_mask"]
|
| 214 |
+
token_type_ids = inputs["token_type_ids"].numpy()
|
| 215 |
+
token_type_ids_example = None
|
| 216 |
+
|
| 217 |
+
for index in range(batch_size):
|
| 218 |
+
# If sequences have already been processed, the token type IDs will be created according to the previous
|
| 219 |
+
# answer.
|
| 220 |
+
if prev_answers is not None:
|
| 221 |
+
prev_labels_example = token_type_ids_example[:, 3] # shape (seq_len,)
|
| 222 |
+
model_labels = np.zeros_like(prev_labels_example, dtype=np.int32) # shape (seq_len,)
|
| 223 |
+
|
| 224 |
+
token_type_ids_example = token_type_ids[index] # shape (seq_len, 7)
|
| 225 |
+
for i in range(model_labels.shape[0]):
|
| 226 |
+
segment_id = token_type_ids_example[:, 0].tolist()[i]
|
| 227 |
+
col_id = token_type_ids_example[:, 1].tolist()[i] - 1
|
| 228 |
+
row_id = token_type_ids_example[:, 2].tolist()[i] - 1
|
| 229 |
+
|
| 230 |
+
if row_id >= 0 and col_id >= 0 and segment_id == 1:
|
| 231 |
+
model_labels[i] = int(prev_answers[(col_id, row_id)])
|
| 232 |
+
|
| 233 |
+
token_type_ids_example[:, 3] = model_labels
|
| 234 |
+
|
| 235 |
+
input_ids_example = input_ids[index]
|
| 236 |
+
attention_mask_example = attention_mask[index] # shape (seq_len,)
|
| 237 |
+
token_type_ids_example = token_type_ids[index] # shape (seq_len, 7)
|
| 238 |
+
outputs = self.model(
|
| 239 |
+
input_ids=np.expand_dims(input_ids_example, axis=0),
|
| 240 |
+
attention_mask=np.expand_dims(attention_mask_example, axis=0),
|
| 241 |
+
token_type_ids=np.expand_dims(token_type_ids_example, axis=0),
|
| 242 |
+
)
|
| 243 |
+
logits = outputs.logits
|
| 244 |
+
|
| 245 |
+
if self.aggregate:
|
| 246 |
+
all_aggregations.append(outputs.logits_aggregation)
|
| 247 |
+
|
| 248 |
+
all_logits.append(logits)
|
| 249 |
+
|
| 250 |
+
probabilities = tf.math.sigmoid(tf.cast(logits, tf.float32)) * tf.cast(
|
| 251 |
+
attention_mask_example, tf.float32
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
coords_to_probs = collections.defaultdict(list)
|
| 255 |
+
token_type_ids_example = token_type_ids_example
|
| 256 |
+
for i, p in enumerate(tf.squeeze(probabilities).numpy().tolist()):
|
| 257 |
+
segment_id = token_type_ids_example[:, 0].tolist()[i]
|
| 258 |
+
col = token_type_ids_example[:, 1].tolist()[i] - 1
|
| 259 |
+
row = token_type_ids_example[:, 2].tolist()[i] - 1
|
| 260 |
+
if col >= 0 and row >= 0 and segment_id == 1:
|
| 261 |
+
coords_to_probs[(col, row)].append(p)
|
| 262 |
+
|
| 263 |
+
prev_answers = {key: np.array(coords_to_probs[key]).mean() > 0.5 for key in coords_to_probs}
|
| 264 |
+
|
| 265 |
+
logits_batch = tf.concat(tuple(all_logits), 0)
|
| 266 |
+
|
| 267 |
+
return (logits_batch,) if not self.aggregate else (logits_batch, tf.concat(tuple(all_aggregations), 0))
|
| 268 |
+
|
| 269 |
+
def __call__(self, *args, **kwargs):
|
| 270 |
+
r"""
|
| 271 |
+
Answers queries according to a table. The pipeline accepts several types of inputs which are detailed below:
|
| 272 |
+
|
| 273 |
+
- `pipeline(table, query)`
|
| 274 |
+
- `pipeline(table, [query])`
|
| 275 |
+
- `pipeline(table=table, query=query)`
|
| 276 |
+
- `pipeline(table=table, query=[query])`
|
| 277 |
+
- `pipeline({"table": table, "query": query})`
|
| 278 |
+
- `pipeline({"table": table, "query": [query]})`
|
| 279 |
+
- `pipeline([{"table": table, "query": query}, {"table": table, "query": query}])`
|
| 280 |
+
|
| 281 |
+
The `table` argument should be a dict or a DataFrame built from that dict, containing the whole table:
|
| 282 |
+
|
| 283 |
+
Example:
|
| 284 |
+
|
| 285 |
+
```python
|
| 286 |
+
data = {
|
| 287 |
+
"actors": ["brad pitt", "leonardo di caprio", "george clooney"],
|
| 288 |
+
"age": ["56", "45", "59"],
|
| 289 |
+
"number of movies": ["87", "53", "69"],
|
| 290 |
+
"date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"],
|
| 291 |
+
}
|
| 292 |
+
```
|
| 293 |
+
|
| 294 |
+
This dictionary can be passed in as such, or can be converted to a pandas DataFrame:
|
| 295 |
+
|
| 296 |
+
Example:
|
| 297 |
+
|
| 298 |
+
```python
|
| 299 |
+
import pandas as pd
|
| 300 |
+
|
| 301 |
+
table = pd.DataFrame.from_dict(data)
|
| 302 |
+
```
|
| 303 |
+
|
| 304 |
+
Args:
|
| 305 |
+
table (`pd.DataFrame` or `Dict`):
|
| 306 |
+
Pandas DataFrame or dictionary that will be converted to a DataFrame containing all the table values.
|
| 307 |
+
See above for an example of dictionary.
|
| 308 |
+
query (`str` or `List[str]`):
|
| 309 |
+
Query or list of queries that will be sent to the model alongside the table.
|
| 310 |
+
sequential (`bool`, *optional*, defaults to `False`):
|
| 311 |
+
Whether to do inference sequentially or as a batch. Batching is faster, but models like SQA require the
|
| 312 |
+
inference to be done sequentially to extract relations within sequences, given their conversational
|
| 313 |
+
nature.
|
| 314 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
|
| 315 |
+
Activates and controls padding. Accepts the following values:
|
| 316 |
+
|
| 317 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
| 318 |
+
sequence if provided).
|
| 319 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 320 |
+
acceptable input length for the model if that argument is not provided.
|
| 321 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 322 |
+
lengths).
|
| 323 |
+
|
| 324 |
+
truncation (`bool`, `str` or [`TapasTruncationStrategy`], *optional*, defaults to `False`):
|
| 325 |
+
Activates and controls truncation. Accepts the following values:
|
| 326 |
+
|
| 327 |
+
- `True` or `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length`
|
| 328 |
+
or to the maximum acceptable input length for the model if that argument is not provided. This will
|
| 329 |
+
truncate row by row, removing rows from the table.
|
| 330 |
+
- `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
|
| 331 |
+
greater than the model maximum admissible input size).
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
Return:
|
| 335 |
+
A dictionary or a list of dictionaries containing results: Each result is a dictionary with the following
|
| 336 |
+
keys:
|
| 337 |
+
|
| 338 |
+
- **answer** (`str`) -- The answer of the query given the table. If there is an aggregator, the answer will
|
| 339 |
+
be preceded by `AGGREGATOR >`.
|
| 340 |
+
- **coordinates** (`List[Tuple[int, int]]`) -- Coordinates of the cells of the answers.
|
| 341 |
+
- **cells** (`List[str]`) -- List of strings made up of the answer cell values.
|
| 342 |
+
- **aggregator** (`str`) -- If the model has an aggregator, this returns the aggregator.
|
| 343 |
+
"""
|
| 344 |
+
pipeline_inputs = self._args_parser(*args, **kwargs)
|
| 345 |
+
|
| 346 |
+
results = super().__call__(pipeline_inputs, **kwargs)
|
| 347 |
+
if len(results) == 1:
|
| 348 |
+
return results[0]
|
| 349 |
+
return results
|
| 350 |
+
|
| 351 |
+
def _sanitize_parameters(self, sequential=None, padding=None, truncation=None, **kwargs):
|
| 352 |
+
preprocess_params = {}
|
| 353 |
+
if padding is not None:
|
| 354 |
+
preprocess_params["padding"] = padding
|
| 355 |
+
if truncation is not None:
|
| 356 |
+
preprocess_params["truncation"] = truncation
|
| 357 |
+
|
| 358 |
+
forward_params = {}
|
| 359 |
+
if sequential is not None:
|
| 360 |
+
forward_params["sequential"] = sequential
|
| 361 |
+
return preprocess_params, forward_params, {}
|
| 362 |
+
|
| 363 |
+
def preprocess(self, pipeline_input, sequential=None, padding=True, truncation=None):
|
| 364 |
+
if truncation is None:
|
| 365 |
+
if self.type == "tapas":
|
| 366 |
+
truncation = "drop_rows_to_fit"
|
| 367 |
+
else:
|
| 368 |
+
truncation = "do_not_truncate"
|
| 369 |
+
|
| 370 |
+
table, query = pipeline_input["table"], pipeline_input["query"]
|
| 371 |
+
if table.empty:
|
| 372 |
+
raise ValueError("table is empty")
|
| 373 |
+
if query is None or query == "":
|
| 374 |
+
raise ValueError("query is empty")
|
| 375 |
+
inputs = self.tokenizer(table, query, return_tensors=self.framework, truncation=truncation, padding=padding)
|
| 376 |
+
inputs["table"] = table
|
| 377 |
+
return inputs
|
| 378 |
+
|
| 379 |
+
def _forward(self, model_inputs, sequential=False, **generate_kwargs):
|
| 380 |
+
table = model_inputs.pop("table")
|
| 381 |
+
|
| 382 |
+
if self.type == "tapas":
|
| 383 |
+
if sequential:
|
| 384 |
+
outputs = self.sequential_inference(**model_inputs)
|
| 385 |
+
else:
|
| 386 |
+
outputs = self.batch_inference(**model_inputs)
|
| 387 |
+
else:
|
| 388 |
+
# User-defined `generation_config` passed to the pipeline call take precedence
|
| 389 |
+
if "generation_config" not in generate_kwargs:
|
| 390 |
+
generate_kwargs["generation_config"] = self.generation_config
|
| 391 |
+
|
| 392 |
+
outputs = self.model.generate(**model_inputs, **generate_kwargs)
|
| 393 |
+
model_outputs = {"model_inputs": model_inputs, "table": table, "outputs": outputs}
|
| 394 |
+
return model_outputs
|
| 395 |
+
|
| 396 |
+
def postprocess(self, model_outputs):
|
| 397 |
+
inputs = model_outputs["model_inputs"]
|
| 398 |
+
table = model_outputs["table"]
|
| 399 |
+
outputs = model_outputs["outputs"]
|
| 400 |
+
if self.type == "tapas":
|
| 401 |
+
if self.aggregate:
|
| 402 |
+
logits, logits_agg = outputs[:2]
|
| 403 |
+
predictions = self.tokenizer.convert_logits_to_predictions(inputs, logits, logits_agg)
|
| 404 |
+
answer_coordinates_batch, agg_predictions = predictions
|
| 405 |
+
aggregators = {i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(agg_predictions)}
|
| 406 |
+
|
| 407 |
+
no_agg_label_index = self.model.config.no_aggregation_label_index
|
| 408 |
+
aggregators_prefix = {
|
| 409 |
+
i: aggregators[i] + " > " for i, pred in enumerate(agg_predictions) if pred != no_agg_label_index
|
| 410 |
+
}
|
| 411 |
+
else:
|
| 412 |
+
logits = outputs[0]
|
| 413 |
+
predictions = self.tokenizer.convert_logits_to_predictions(inputs, logits)
|
| 414 |
+
answer_coordinates_batch = predictions[0]
|
| 415 |
+
aggregators = {}
|
| 416 |
+
aggregators_prefix = {}
|
| 417 |
+
answers = []
|
| 418 |
+
for index, coordinates in enumerate(answer_coordinates_batch):
|
| 419 |
+
cells = [table.iat[coordinate] for coordinate in coordinates]
|
| 420 |
+
aggregator = aggregators.get(index, "")
|
| 421 |
+
aggregator_prefix = aggregators_prefix.get(index, "")
|
| 422 |
+
answer = {
|
| 423 |
+
"answer": aggregator_prefix + ", ".join(cells),
|
| 424 |
+
"coordinates": coordinates,
|
| 425 |
+
"cells": [table.iat[coordinate] for coordinate in coordinates],
|
| 426 |
+
}
|
| 427 |
+
if aggregator:
|
| 428 |
+
answer["aggregator"] = aggregator
|
| 429 |
+
|
| 430 |
+
answers.append(answer)
|
| 431 |
+
if len(answer) == 0:
|
| 432 |
+
raise PipelineException("Empty answer")
|
| 433 |
+
else:
|
| 434 |
+
answers = [{"answer": answer} for answer in self.tokenizer.batch_decode(outputs, skip_special_tokens=True)]
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import enum
|
| 2 |
+
import warnings
|
| 3 |
+
|
| 4 |
+
from ..tokenization_utils import TruncationStrategy
|
| 5 |
+
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
|
| 6 |
+
from .base import Pipeline, build_pipeline_init_args
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
if is_tf_available():
|
| 10 |
+
import tensorflow as tf
|
| 11 |
+
|
| 12 |
+
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
|
| 13 |
+
|
| 14 |
+
if is_torch_available():
|
| 15 |
+
from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
|
| 16 |
+
|
| 17 |
+
logger = logging.get_logger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ReturnType(enum.Enum):
|
| 21 |
+
TENSORS = 0
|
| 22 |
+
TEXT = 1
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
|
| 26 |
+
class Text2TextGenerationPipeline(Pipeline):
|
| 27 |
+
"""
|
| 28 |
+
Pipeline for text to text generation using seq2seq models.
|
| 29 |
+
|
| 30 |
+
Example:
|
| 31 |
+
|
| 32 |
+
```python
|
| 33 |
+
>>> from transformers import pipeline
|
| 34 |
+
|
| 35 |
+
>>> generator = pipeline(model="mrm8488/t5-base-finetuned-question-generation-ap")
|
| 36 |
+
>>> generator(
|
| 37 |
+
... "answer: Manuel context: Manuel has created RuPERTa-base with the support of HF-Transformers and Google"
|
| 38 |
+
... )
|
| 39 |
+
[{'generated_text': 'question: Who created the RuPERTa-base?'}]
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial). You can pass text
|
| 43 |
+
generation parameters to this pipeline to control stopping criteria, decoding strategy, and more. Learn more about
|
| 44 |
+
text generation parameters in [Text generation strategies](../generation_strategies) and [Text
|
| 45 |
+
generation](text_generation).
|
| 46 |
+
|
| 47 |
+
This Text2TextGenerationPipeline pipeline can currently be loaded from [`pipeline`] using the following task
|
| 48 |
+
identifier: `"text2text-generation"`.
|
| 49 |
+
|
| 50 |
+
The models that this pipeline can use are models that have been fine-tuned on a translation task. See the
|
| 51 |
+
up-to-date list of available models on
|
| 52 |
+
[huggingface.co/models](https://huggingface.co/models?filter=text2text-generation). For a list of available
|
| 53 |
+
parameters, see the [following
|
| 54 |
+
documentation](https://huggingface.co/docs/transformers/en/main_classes/text_generation#transformers.generation.GenerationMixin.generate)
|
| 55 |
+
|
| 56 |
+
Usage:
|
| 57 |
+
|
| 58 |
+
```python
|
| 59 |
+
text2text_generator = pipeline("text2text-generation")
|
| 60 |
+
text2text_generator("question: What is 42 ? context: 42 is the answer to life, the universe and everything")
|
| 61 |
+
```"""
|
| 62 |
+
|
| 63 |
+
# Used in the return key of the pipeline.
|
| 64 |
+
return_name = "generated"
|
| 65 |
+
|
| 66 |
+
def __init__(self, *args, **kwargs):
|
| 67 |
+
super().__init__(*args, **kwargs)
|
| 68 |
+
|
| 69 |
+
self.check_model_type(
|
| 70 |
+
TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
|
| 71 |
+
if self.framework == "tf"
|
| 72 |
+
else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
def _sanitize_parameters(
|
| 76 |
+
self,
|
| 77 |
+
return_tensors=None,
|
| 78 |
+
return_text=None,
|
| 79 |
+
return_type=None,
|
| 80 |
+
clean_up_tokenization_spaces=None,
|
| 81 |
+
truncation=None,
|
| 82 |
+
stop_sequence=None,
|
| 83 |
+
**generate_kwargs,
|
| 84 |
+
):
|
| 85 |
+
preprocess_params = {}
|
| 86 |
+
if truncation is not None:
|
| 87 |
+
preprocess_params["truncation"] = truncation
|
| 88 |
+
|
| 89 |
+
forward_params = generate_kwargs
|
| 90 |
+
|
| 91 |
+
postprocess_params = {}
|
| 92 |
+
if return_tensors is not None and return_type is None:
|
| 93 |
+
return_type = ReturnType.TENSORS if return_tensors else ReturnType.TEXT
|
| 94 |
+
if return_type is not None:
|
| 95 |
+
postprocess_params["return_type"] = return_type
|
| 96 |
+
|
| 97 |
+
if clean_up_tokenization_spaces is not None:
|
| 98 |
+
postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces
|
| 99 |
+
|
| 100 |
+
if stop_sequence is not None:
|
| 101 |
+
stop_sequence_ids = self.tokenizer.encode(stop_sequence, add_special_tokens=False)
|
| 102 |
+
if len(stop_sequence_ids) > 1:
|
| 103 |
+
warnings.warn(
|
| 104 |
+
"Stopping on a multiple token sequence is not yet supported on transformers. The first token of"
|
| 105 |
+
" the stop sequence will be used as the stop sequence string in the interim."
|
| 106 |
+
)
|
| 107 |
+
generate_kwargs["eos_token_id"] = stop_sequence_ids[0]
|
| 108 |
+
|
| 109 |
+
return preprocess_params, forward_params, postprocess_params
|
| 110 |
+
|
| 111 |
+
def check_inputs(self, input_length: int, min_length: int, max_length: int):
|
| 112 |
+
"""
|
| 113 |
+
Checks whether there might be something wrong with given input with regard to the model.
|
| 114 |
+
"""
|
| 115 |
+
return True
|
| 116 |
+
|
| 117 |
+
def _parse_and_tokenize(self, *args, truncation):
|
| 118 |
+
prefix = self.prefix if self.prefix is not None else ""
|
| 119 |
+
if isinstance(args[0], list):
|
| 120 |
+
if self.tokenizer.pad_token_id is None:
|
| 121 |
+
raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input")
|
| 122 |
+
args = ([prefix + arg for arg in args[0]],)
|
| 123 |
+
padding = True
|
| 124 |
+
|
| 125 |
+
elif isinstance(args[0], str):
|
| 126 |
+
args = (prefix + args[0],)
|
| 127 |
+
padding = False
|
| 128 |
+
else:
|
| 129 |
+
raise ValueError(
|
| 130 |
+
f" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`"
|
| 131 |
+
)
|
| 132 |
+
inputs = self.tokenizer(*args, padding=padding, truncation=truncation, return_tensors=self.framework)
|
| 133 |
+
# This is produced by tokenizers but is an invalid generate kwargs
|
| 134 |
+
if "token_type_ids" in inputs:
|
| 135 |
+
del inputs["token_type_ids"]
|
| 136 |
+
return inputs
|
| 137 |
+
|
| 138 |
+
def __call__(self, *args, **kwargs):
|
| 139 |
+
r"""
|
| 140 |
+
Generate the output text(s) using text(s) given as inputs.
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
args (`str` or `List[str]`):
|
| 144 |
+
Input text for the encoder.
|
| 145 |
+
return_tensors (`bool`, *optional*, defaults to `False`):
|
| 146 |
+
Whether or not to include the tensors of predictions (as token indices) in the outputs.
|
| 147 |
+
return_text (`bool`, *optional*, defaults to `True`):
|
| 148 |
+
Whether or not to include the decoded texts in the outputs.
|
| 149 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
|
| 150 |
+
Whether or not to clean up the potential extra spaces in the text output.
|
| 151 |
+
truncation (`TruncationStrategy`, *optional*, defaults to `TruncationStrategy.DO_NOT_TRUNCATE`):
|
| 152 |
+
The truncation strategy for the tokenization within the pipeline. `TruncationStrategy.DO_NOT_TRUNCATE`
|
| 153 |
+
(default) will never truncate, but it is sometimes desirable to truncate the input to fit the model's
|
| 154 |
+
max_length instead of throwing an error down the line.
|
| 155 |
+
generate_kwargs:
|
| 156 |
+
Additional keyword arguments to pass along to the generate method of the model (see the generate method
|
| 157 |
+
corresponding to your framework [here](./text_generation)).
|
| 158 |
+
|
| 159 |
+
Return:
|
| 160 |
+
A list or a list of list of `dict`: Each result comes as a dictionary with the following keys:
|
| 161 |
+
|
| 162 |
+
- **generated_text** (`str`, present when `return_text=True`) -- The generated text.
|
| 163 |
+
- **generated_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The token
|
| 164 |
+
ids of the generated text.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
result = super().__call__(*args, **kwargs)
|
| 168 |
+
if (
|
| 169 |
+
isinstance(args[0], list)
|
| 170 |
+
and all(isinstance(el, str) for el in args[0])
|
| 171 |
+
and all(len(res) == 1 for res in result)
|
| 172 |
+
):
|
| 173 |
+
return [res[0] for res in result]
|
| 174 |
+
return result
|
| 175 |
+
|
| 176 |
+
def preprocess(self, inputs, truncation=TruncationStrategy.DO_NOT_TRUNCATE, **kwargs):
|
| 177 |
+
inputs = self._parse_and_tokenize(inputs, truncation=truncation, **kwargs)
|
| 178 |
+
return inputs
|
| 179 |
+
|
| 180 |
+
def _forward(self, model_inputs, **generate_kwargs):
|
| 181 |
+
if self.framework == "pt":
|
| 182 |
+
in_b, input_length = model_inputs["input_ids"].shape
|
| 183 |
+
elif self.framework == "tf":
|
| 184 |
+
in_b, input_length = tf.shape(model_inputs["input_ids"]).numpy()
|
| 185 |
+
|
| 186 |
+
self.check_inputs(
|
| 187 |
+
input_length,
|
| 188 |
+
generate_kwargs.get("min_length", self.generation_config.min_length),
|
| 189 |
+
generate_kwargs.get("max_length", self.generation_config.max_length),
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
# User-defined `generation_config` passed to the pipeline call take precedence
|
| 193 |
+
if "generation_config" not in generate_kwargs:
|
| 194 |
+
generate_kwargs["generation_config"] = self.generation_config
|
| 195 |
+
|
| 196 |
+
output_ids = self.model.generate(**model_inputs, **generate_kwargs)
|
| 197 |
+
out_b = output_ids.shape[0]
|
| 198 |
+
if self.framework == "pt":
|
| 199 |
+
output_ids = output_ids.reshape(in_b, out_b // in_b, *output_ids.shape[1:])
|
| 200 |
+
elif self.framework == "tf":
|
| 201 |
+
output_ids = tf.reshape(output_ids, (in_b, out_b // in_b, *output_ids.shape[1:]))
|
| 202 |
+
return {"output_ids": output_ids}
|
| 203 |
+
|
| 204 |
+
def postprocess(self, model_outputs, return_type=ReturnType.TEXT, clean_up_tokenization_spaces=False):
|
| 205 |
+
records = []
|
| 206 |
+
for output_ids in model_outputs["output_ids"][0]:
|
| 207 |
+
if return_type == ReturnType.TENSORS:
|
| 208 |
+
record = {f"{self.return_name}_token_ids": output_ids}
|
| 209 |
+
elif return_type == ReturnType.TEXT:
|
| 210 |
+
record = {
|
| 211 |
+
f"{self.return_name}_text": self.tokenizer.decode(
|
| 212 |
+
output_ids,
|
| 213 |
+
skip_special_tokens=True,
|
| 214 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 215 |
+
)
|
| 216 |
+
}
|
| 217 |
+
records.append(record)
|
| 218 |
+
return records
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
|
| 222 |
+
class SummarizationPipeline(Text2TextGenerationPipeline):
|
| 223 |
+
"""
|
| 224 |
+
Summarize news articles and other documents.
|
| 225 |
+
|
| 226 |
+
This summarizing pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 227 |
+
`"summarization"`.
|
| 228 |
+
|
| 229 |
+
The models that this pipeline can use are models that have been fine-tuned on a summarization task, which is
|
| 230 |
+
currently, '*bart-large-cnn*', '*google-t5/t5-small*', '*google-t5/t5-base*', '*google-t5/t5-large*', '*google-t5/t5-3b*', '*google-t5/t5-11b*'. See the up-to-date
|
| 231 |
+
list of available models on [huggingface.co/models](https://huggingface.co/models?filter=summarization). For a list
|
| 232 |
+
of available parameters, see the [following
|
| 233 |
+
documentation](https://huggingface.co/docs/transformers/en/main_classes/text_generation#transformers.generation.GenerationMixin.generate)
|
| 234 |
+
|
| 235 |
+
Usage:
|
| 236 |
+
|
| 237 |
+
```python
|
| 238 |
+
# use bart in pytorch
|
| 239 |
+
summarizer = pipeline("summarization")
|
| 240 |
+
summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20)
|
| 241 |
+
|
| 242 |
+
# use t5 in tf
|
| 243 |
+
summarizer = pipeline("summarization", model="google-t5/t5-base", tokenizer="google-t5/t5-base", framework="tf")
|
| 244 |
+
summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20)
|
| 245 |
+
```"""
|
| 246 |
+
|
| 247 |
+
# Used in the return key of the pipeline.
|
| 248 |
+
return_name = "summary"
|
| 249 |
+
|
| 250 |
+
def __call__(self, *args, **kwargs):
|
| 251 |
+
r"""
|
| 252 |
+
Summarize the text(s) given as inputs.
|
| 253 |
+
|
| 254 |
+
Args:
|
| 255 |
+
documents (*str* or `List[str]`):
|
| 256 |
+
One or several articles (or one list of articles) to summarize.
|
| 257 |
+
return_text (`bool`, *optional*, defaults to `True`):
|
| 258 |
+
Whether or not to include the decoded texts in the outputs
|
| 259 |
+
return_tensors (`bool`, *optional*, defaults to `False`):
|
| 260 |
+
Whether or not to include the tensors of predictions (as token indices) in the outputs.
|
| 261 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
|
| 262 |
+
Whether or not to clean up the potential extra spaces in the text output.
|
| 263 |
+
generate_kwargs:
|
| 264 |
+
Additional keyword arguments to pass along to the generate method of the model (see the generate method
|
| 265 |
+
corresponding to your framework [here](./text_generation)).
|
| 266 |
+
|
| 267 |
+
Return:
|
| 268 |
+
A list or a list of list of `dict`: Each result comes as a dictionary with the following keys:
|
| 269 |
+
|
| 270 |
+
- **summary_text** (`str`, present when `return_text=True`) -- The summary of the corresponding input.
|
| 271 |
+
- **summary_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The token
|
| 272 |
+
ids of the summary.
|
| 273 |
+
"""
|
| 274 |
+
return super().__call__(*args, **kwargs)
|
| 275 |
+
|
| 276 |
+
def check_inputs(self, input_length: int, min_length: int, max_length: int) -> bool:
|
| 277 |
+
"""
|
| 278 |
+
Checks whether there might be something wrong with given input with regard to the model.
|
| 279 |
+
"""
|
| 280 |
+
if max_length < min_length:
|
| 281 |
+
logger.warning(f"Your min_length={min_length} must be inferior than your max_length={max_length}.")
|
| 282 |
+
|
| 283 |
+
if input_length < max_length:
|
| 284 |
+
logger.warning(
|
| 285 |
+
f"Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is "
|
| 286 |
+
"a summarization task, where outputs shorter than the input are typically wanted, you might "
|
| 287 |
+
f"consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})"
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
|
| 292 |
+
class TranslationPipeline(Text2TextGenerationPipeline):
|
| 293 |
+
"""
|
| 294 |
+
Translates from one language to another.
|
| 295 |
+
|
| 296 |
+
This translation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 297 |
+
`"translation_xx_to_yy"`.
|
| 298 |
+
|
| 299 |
+
The models that this pipeline can use are models that have been fine-tuned on a translation task. See the
|
| 300 |
+
up-to-date list of available models on [huggingface.co/models](https://huggingface.co/models?filter=translation).
|
| 301 |
+
For a list of available parameters, see the [following
|
| 302 |
+
documentation](https://huggingface.co/docs/transformers/en/main_classes/text_generation#transformers.generation.GenerationMixin.generate)
|
| 303 |
+
|
| 304 |
+
Usage:
|
| 305 |
+
|
| 306 |
+
```python
|
| 307 |
+
en_fr_translator = pipeline("translation_en_to_fr")
|
| 308 |
+
en_fr_translator("How old are you?")
|
| 309 |
+
```"""
|
| 310 |
+
|
| 311 |
+
# Used in the return key of the pipeline.
|
| 312 |
+
return_name = "translation"
|
| 313 |
+
|
| 314 |
+
def check_inputs(self, input_length: int, min_length: int, max_length: int):
|
| 315 |
+
if input_length > 0.9 * max_length:
|
| 316 |
+
logger.warning(
|
| 317 |
+
f"Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider "
|
| 318 |
+
"increasing your max_length manually, e.g. translator('...', max_length=400)"
|
| 319 |
+
)
|
| 320 |
+
return True
|
| 321 |
+
|
| 322 |
+
def preprocess(self, *args, truncation=TruncationStrategy.DO_NOT_TRUNCATE, src_lang=None, tgt_lang=None):
|
| 323 |
+
if getattr(self.tokenizer, "_build_translation_inputs", None):
|
| 324 |
+
return self.tokenizer._build_translation_inputs(
|
| 325 |
+
*args, return_tensors=self.framework, truncation=truncation, src_lang=src_lang, tgt_lang=tgt_lang
|
| 326 |
+
)
|
| 327 |
+
else:
|
| 328 |
+
return super()._parse_and_tokenize(*args, truncation=truncation)
|
| 329 |
+
|
| 330 |
+
def _sanitize_parameters(self, src_lang=None, tgt_lang=None, **kwargs):
|
| 331 |
+
preprocess_params, forward_params, postprocess_params = super()._sanitize_parameters(**kwargs)
|
| 332 |
+
if src_lang is not None:
|
| 333 |
+
preprocess_params["src_lang"] = src_lang
|
| 334 |
+
if tgt_lang is not None:
|
| 335 |
+
preprocess_params["tgt_lang"] = tgt_lang
|
| 336 |
+
if src_lang is None and tgt_lang is None:
|
| 337 |
+
# Backward compatibility, direct arguments use is preferred.
|
| 338 |
+
task = kwargs.get("task", self.task)
|
| 339 |
+
items = task.split("_")
|
| 340 |
+
if task and len(items) == 4:
|
| 341 |
+
# translation, XX, to YY
|
| 342 |
+
preprocess_params["src_lang"] = items[1]
|
| 343 |
+
preprocess_params["tgt_lang"] = items[3]
|
| 344 |
+
return preprocess_params, forward_params, postprocess_params
|
| 345 |
+
|
| 346 |
+
def __call__(self, *args, **kwargs):
|
| 347 |
+
r"""
|
| 348 |
+
Translate the text(s) given as inputs.
|
| 349 |
+
|
| 350 |
+
Args:
|
| 351 |
+
args (`str` or `List[str]`):
|
| 352 |
+
Texts to be translated.
|
| 353 |
+
return_tensors (`bool`, *optional*, defaults to `False`):
|
| 354 |
+
Whether or not to include the tensors of predictions (as token indices) in the outputs.
|
| 355 |
+
return_text (`bool`, *optional*, defaults to `True`):
|
| 356 |
+
Whether or not to include the decoded texts in the outputs.
|
| 357 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
|
| 358 |
+
Whether or not to clean up the potential extra spaces in the text output.
|
| 359 |
+
src_lang (`str`, *optional*):
|
| 360 |
+
The language of the input. Might be required for multilingual models. Will not have any effect for
|
| 361 |
+
single pair translation models
|
| 362 |
+
tgt_lang (`str`, *optional*):
|
| 363 |
+
The language of the desired output. Might be required for multilingual models. Will not have any effect
|
| 364 |
+
for single pair translation models
|
| 365 |
+
generate_kwargs:
|
| 366 |
+
Additional keyword arguments to pass along to the generate method of the model (see the generate method
|
| 367 |
+
corresponding to your framework [here](./text_generation)).
|
| 368 |
+
|
| 369 |
+
Return:
|
| 370 |
+
A list or a list of list of `dict`: Each result comes as a dictionary with the following keys:
|
| 371 |
+
|
| 372 |
+
- **translation_text** (`str`, present when `return_text=True`) -- The translation.
|
| 373 |
+
- **translation_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The
|
| 374 |
+
token ids of the translation.
|
| 375 |
+
"""
|
| 376 |
+
return super().__call__(*args, **kwargs)
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/text_classification.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import warnings
|
| 3 |
+
from typing import Dict
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
|
| 8 |
+
from .base import GenericTensor, Pipeline, build_pipeline_init_args
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if is_tf_available():
|
| 12 |
+
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
|
| 13 |
+
|
| 14 |
+
if is_torch_available():
|
| 15 |
+
from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def sigmoid(_outputs):
|
| 19 |
+
return 1.0 / (1.0 + np.exp(-_outputs))
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def softmax(_outputs):
|
| 23 |
+
maxes = np.max(_outputs, axis=-1, keepdims=True)
|
| 24 |
+
shifted_exp = np.exp(_outputs - maxes)
|
| 25 |
+
return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class ClassificationFunction(ExplicitEnum):
|
| 29 |
+
SIGMOID = "sigmoid"
|
| 30 |
+
SOFTMAX = "softmax"
|
| 31 |
+
NONE = "none"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@add_end_docstrings(
|
| 35 |
+
build_pipeline_init_args(has_tokenizer=True),
|
| 36 |
+
r"""
|
| 37 |
+
return_all_scores (`bool`, *optional*, defaults to `False`):
|
| 38 |
+
Whether to return all prediction scores or just the one of the predicted class.
|
| 39 |
+
function_to_apply (`str`, *optional*, defaults to `"default"`):
|
| 40 |
+
The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:
|
| 41 |
+
|
| 42 |
+
- `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
|
| 43 |
+
has several labels, will apply the softmax function on the output. In case of regression tasks, will not
|
| 44 |
+
apply any function on the output.
|
| 45 |
+
- `"sigmoid"`: Applies the sigmoid function on the output.
|
| 46 |
+
- `"softmax"`: Applies the softmax function on the output.
|
| 47 |
+
- `"none"`: Does not apply any function on the output.""",
|
| 48 |
+
)
|
| 49 |
+
class TextClassificationPipeline(Pipeline):
|
| 50 |
+
"""
|
| 51 |
+
Text classification pipeline using any `ModelForSequenceClassification`. See the [sequence classification
|
| 52 |
+
examples](../task_summary#sequence-classification) for more information.
|
| 53 |
+
|
| 54 |
+
Example:
|
| 55 |
+
|
| 56 |
+
```python
|
| 57 |
+
>>> from transformers import pipeline
|
| 58 |
+
|
| 59 |
+
>>> classifier = pipeline(model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
|
| 60 |
+
>>> classifier("This movie is disgustingly good !")
|
| 61 |
+
[{'label': 'POSITIVE', 'score': 1.0}]
|
| 62 |
+
|
| 63 |
+
>>> classifier("Director tried too much.")
|
| 64 |
+
[{'label': 'NEGATIVE', 'score': 0.996}]
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
| 68 |
+
|
| 69 |
+
This text classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 70 |
+
`"sentiment-analysis"` (for classifying sequences according to positive or negative sentiments).
|
| 71 |
+
|
| 72 |
+
If multiple classification labels are available (`model.config.num_labels >= 2`), the pipeline will run a softmax
|
| 73 |
+
over the results. If there is a single label, the pipeline will run a sigmoid over the result. In case of regression
|
| 74 |
+
tasks (`model.config.problem_type == "regression"`), will not apply any function on the output.
|
| 75 |
+
|
| 76 |
+
The models that this pipeline can use are models that have been fine-tuned on a sequence classification task. See
|
| 77 |
+
the up-to-date list of available models on
|
| 78 |
+
[huggingface.co/models](https://huggingface.co/models?filter=text-classification).
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
return_all_scores = False
|
| 82 |
+
function_to_apply = ClassificationFunction.NONE
|
| 83 |
+
|
| 84 |
+
def __init__(self, **kwargs):
|
| 85 |
+
super().__init__(**kwargs)
|
| 86 |
+
|
| 87 |
+
self.check_model_type(
|
| 88 |
+
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
|
| 89 |
+
if self.framework == "tf"
|
| 90 |
+
else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
def _sanitize_parameters(self, return_all_scores=None, function_to_apply=None, top_k="", **tokenizer_kwargs):
|
| 94 |
+
# Using "" as default argument because we're going to use `top_k=None` in user code to declare
|
| 95 |
+
# "No top_k"
|
| 96 |
+
preprocess_params = tokenizer_kwargs
|
| 97 |
+
|
| 98 |
+
postprocess_params = {}
|
| 99 |
+
if hasattr(self.model.config, "return_all_scores") and return_all_scores is None:
|
| 100 |
+
return_all_scores = self.model.config.return_all_scores
|
| 101 |
+
|
| 102 |
+
if isinstance(top_k, int) or top_k is None:
|
| 103 |
+
postprocess_params["top_k"] = top_k
|
| 104 |
+
postprocess_params["_legacy"] = False
|
| 105 |
+
elif return_all_scores is not None:
|
| 106 |
+
warnings.warn(
|
| 107 |
+
"`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of"
|
| 108 |
+
" `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.",
|
| 109 |
+
UserWarning,
|
| 110 |
+
)
|
| 111 |
+
if return_all_scores:
|
| 112 |
+
postprocess_params["top_k"] = None
|
| 113 |
+
else:
|
| 114 |
+
postprocess_params["top_k"] = 1
|
| 115 |
+
|
| 116 |
+
if isinstance(function_to_apply, str):
|
| 117 |
+
function_to_apply = ClassificationFunction[function_to_apply.upper()]
|
| 118 |
+
|
| 119 |
+
if function_to_apply is not None:
|
| 120 |
+
postprocess_params["function_to_apply"] = function_to_apply
|
| 121 |
+
return preprocess_params, {}, postprocess_params
|
| 122 |
+
|
| 123 |
+
def __call__(self, inputs, **kwargs):
|
| 124 |
+
"""
|
| 125 |
+
Classify the text(s) given as inputs.
|
| 126 |
+
|
| 127 |
+
Args:
|
| 128 |
+
inputs (`str` or `List[str]` or `Dict[str]`, or `List[Dict[str]]`):
|
| 129 |
+
One or several texts to classify. In order to use text pairs for your classification, you can send a
|
| 130 |
+
dictionary containing `{"text", "text_pair"}` keys, or a list of those.
|
| 131 |
+
top_k (`int`, *optional*, defaults to `1`):
|
| 132 |
+
How many results to return.
|
| 133 |
+
function_to_apply (`str`, *optional*, defaults to `"default"`):
|
| 134 |
+
The function to apply to the model outputs in order to retrieve the scores. Accepts four different
|
| 135 |
+
values:
|
| 136 |
+
|
| 137 |
+
If this argument is not specified, then it will apply the following functions according to the number
|
| 138 |
+
of labels:
|
| 139 |
+
|
| 140 |
+
- If problem type is regression, will not apply any function on the output.
|
| 141 |
+
- If the model has a single label, will apply the sigmoid function on the output.
|
| 142 |
+
- If the model has several labels, will apply the softmax function on the output.
|
| 143 |
+
|
| 144 |
+
Possible values are:
|
| 145 |
+
|
| 146 |
+
- `"sigmoid"`: Applies the sigmoid function on the output.
|
| 147 |
+
- `"softmax"`: Applies the softmax function on the output.
|
| 148 |
+
- `"none"`: Does not apply any function on the output.
|
| 149 |
+
|
| 150 |
+
Return:
|
| 151 |
+
A list or a list of list of `dict`: Each result comes as list of dictionaries with the following keys:
|
| 152 |
+
|
| 153 |
+
- **label** (`str`) -- The label predicted.
|
| 154 |
+
- **score** (`float`) -- The corresponding probability.
|
| 155 |
+
|
| 156 |
+
If `top_k` is used, one such dictionary is returned per label.
|
| 157 |
+
"""
|
| 158 |
+
inputs = (inputs,)
|
| 159 |
+
result = super().__call__(*inputs, **kwargs)
|
| 160 |
+
# TODO try and retrieve it in a nicer way from _sanitize_parameters.
|
| 161 |
+
_legacy = "top_k" not in kwargs
|
| 162 |
+
if isinstance(inputs[0], str) and _legacy:
|
| 163 |
+
# This pipeline is odd, and return a list when single item is run
|
| 164 |
+
return [result]
|
| 165 |
+
else:
|
| 166 |
+
return result
|
| 167 |
+
|
| 168 |
+
def preprocess(self, inputs, **tokenizer_kwargs) -> Dict[str, GenericTensor]:
|
| 169 |
+
return_tensors = self.framework
|
| 170 |
+
if isinstance(inputs, dict):
|
| 171 |
+
return self.tokenizer(**inputs, return_tensors=return_tensors, **tokenizer_kwargs)
|
| 172 |
+
elif isinstance(inputs, list) and len(inputs) == 1 and isinstance(inputs[0], list) and len(inputs[0]) == 2:
|
| 173 |
+
# It used to be valid to use a list of list of list for text pairs, keeping this path for BC
|
| 174 |
+
return self.tokenizer(
|
| 175 |
+
text=inputs[0][0], text_pair=inputs[0][1], return_tensors=return_tensors, **tokenizer_kwargs
|
| 176 |
+
)
|
| 177 |
+
elif isinstance(inputs, list):
|
| 178 |
+
# This is likely an invalid usage of the pipeline attempting to pass text pairs.
|
| 179 |
+
raise ValueError(
|
| 180 |
+
"The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a"
|
| 181 |
+
' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'
|
| 182 |
+
)
|
| 183 |
+
return self.tokenizer(inputs, return_tensors=return_tensors, **tokenizer_kwargs)
|
| 184 |
+
|
| 185 |
+
def _forward(self, model_inputs):
|
| 186 |
+
# `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported
|
| 187 |
+
model_forward = self.model.forward if self.framework == "pt" else self.model.call
|
| 188 |
+
if "use_cache" in inspect.signature(model_forward).parameters.keys():
|
| 189 |
+
model_inputs["use_cache"] = False
|
| 190 |
+
return self.model(**model_inputs)
|
| 191 |
+
|
| 192 |
+
def postprocess(self, model_outputs, function_to_apply=None, top_k=1, _legacy=True):
|
| 193 |
+
# `_legacy` is used to determine if we're running the naked pipeline and in backward
|
| 194 |
+
# compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
|
| 195 |
+
# the more natural result containing the list.
|
| 196 |
+
# Default value before `set_parameters`
|
| 197 |
+
if function_to_apply is None:
|
| 198 |
+
if self.model.config.problem_type == "regression":
|
| 199 |
+
function_to_apply = ClassificationFunction.NONE
|
| 200 |
+
elif self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
|
| 201 |
+
function_to_apply = ClassificationFunction.SIGMOID
|
| 202 |
+
elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
|
| 203 |
+
function_to_apply = ClassificationFunction.SOFTMAX
|
| 204 |
+
elif hasattr(self.model.config, "function_to_apply") and function_to_apply is None:
|
| 205 |
+
function_to_apply = self.model.config.function_to_apply
|
| 206 |
+
else:
|
| 207 |
+
function_to_apply = ClassificationFunction.NONE
|
| 208 |
+
|
| 209 |
+
outputs = model_outputs["logits"][0]
|
| 210 |
+
|
| 211 |
+
if self.framework == "pt":
|
| 212 |
+
# To enable using fp16 and bf16
|
| 213 |
+
outputs = outputs.float().numpy()
|
| 214 |
+
else:
|
| 215 |
+
outputs = outputs.numpy()
|
| 216 |
+
|
| 217 |
+
if function_to_apply == ClassificationFunction.SIGMOID:
|
| 218 |
+
scores = sigmoid(outputs)
|
| 219 |
+
elif function_to_apply == ClassificationFunction.SOFTMAX:
|
| 220 |
+
scores = softmax(outputs)
|
| 221 |
+
elif function_to_apply == ClassificationFunction.NONE:
|
| 222 |
+
scores = outputs
|
| 223 |
+
else:
|
| 224 |
+
raise ValueError(f"Unrecognized `function_to_apply` argument: {function_to_apply}")
|
| 225 |
+
|
| 226 |
+
if top_k == 1 and _legacy:
|
| 227 |
+
return {"label": self.model.config.id2label[scores.argmax().item()], "score": scores.max().item()}
|
| 228 |
+
|
| 229 |
+
dict_scores = [
|
| 230 |
+
{"label": self.model.config.id2label[i], "score": score.item()} for i, score in enumerate(scores)
|
| 231 |
+
]
|
| 232 |
+
if not _legacy:
|
| 233 |
+
dict_scores.sort(key=lambda x: x["score"], reverse=True)
|
| 234 |
+
if top_k is not None:
|
| 235 |
+
dict_scores = dict_scores[:top_k]
|
| 236 |
+
return dict_scores
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/text_generation.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import enum
|
| 2 |
+
import warnings
|
| 3 |
+
from typing import Dict
|
| 4 |
+
|
| 5 |
+
from ..utils import add_end_docstrings, is_tf_available, is_torch_available
|
| 6 |
+
from .base import Pipeline, build_pipeline_init_args
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
if is_torch_available():
|
| 10 |
+
from ..models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
|
| 11 |
+
from .pt_utils import KeyDataset
|
| 12 |
+
|
| 13 |
+
if is_tf_available():
|
| 14 |
+
import tensorflow as tf
|
| 15 |
+
|
| 16 |
+
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ReturnType(enum.Enum):
|
| 20 |
+
TENSORS = 0
|
| 21 |
+
NEW_TEXT = 1
|
| 22 |
+
FULL_TEXT = 2
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Chat:
|
| 26 |
+
"""This class is intended to just be used internally in this pipeline and not exposed to users. We convert chats
|
| 27 |
+
to this format because the rest of the pipeline code tends to assume that lists of messages are
|
| 28 |
+
actually a batch of samples rather than messages in the same conversation."""
|
| 29 |
+
|
| 30 |
+
def __init__(self, messages: Dict):
|
| 31 |
+
for message in messages:
|
| 32 |
+
if not ("role" in message and "content" in message):
|
| 33 |
+
raise ValueError("When passing chat dicts as input, each dict must have a 'role' and 'content' key.")
|
| 34 |
+
self.messages = messages
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
|
| 38 |
+
class TextGenerationPipeline(Pipeline):
|
| 39 |
+
"""
|
| 40 |
+
Language generation pipeline using any `ModelWithLMHead`. This pipeline predicts the words that will follow a
|
| 41 |
+
specified text prompt. When the underlying model is a conversational model, it can also accept one or more chats,
|
| 42 |
+
in which case the pipeline will operate in chat mode and will continue the chat(s) by adding its response(s).
|
| 43 |
+
Each chat takes the form of a list of dicts, where each dict contains "role" and "content" keys.
|
| 44 |
+
|
| 45 |
+
Examples:
|
| 46 |
+
|
| 47 |
+
```python
|
| 48 |
+
>>> from transformers import pipeline
|
| 49 |
+
|
| 50 |
+
>>> generator = pipeline(model="openai-community/gpt2")
|
| 51 |
+
>>> generator("I can't believe you did such a ", do_sample=False)
|
| 52 |
+
[{'generated_text': "I can't believe you did such a icky thing to me. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I"}]
|
| 53 |
+
|
| 54 |
+
>>> # These parameters will return suggestions, and only the newly created text making it easier for prompting suggestions.
|
| 55 |
+
>>> outputs = generator("My tart needs some", num_return_sequences=4, return_full_text=False)
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
```python
|
| 59 |
+
>>> from transformers import pipeline
|
| 60 |
+
|
| 61 |
+
>>> generator = pipeline(model="HuggingFaceH4/zephyr-7b-beta")
|
| 62 |
+
>>> # Zephyr-beta is a conversational model, so let's pass it a chat instead of a single string
|
| 63 |
+
>>> generator([{"role": "user", "content": "What is the capital of France? Answer in one word."}], do_sample=False, max_new_tokens=2)
|
| 64 |
+
[{'generated_text': [{'role': 'user', 'content': 'What is the capital of France? Answer in one word.'}, {'role': 'assistant', 'content': 'Paris'}]}]
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial). You can pass text
|
| 68 |
+
generation parameters to this pipeline to control stopping criteria, decoding strategy, and more. Learn more about
|
| 69 |
+
text generation parameters in [Text generation strategies](../generation_strategies) and [Text
|
| 70 |
+
generation](text_generation).
|
| 71 |
+
|
| 72 |
+
This language generation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 73 |
+
`"text-generation"`.
|
| 74 |
+
|
| 75 |
+
The models that this pipeline can use are models that have been trained with an autoregressive language modeling
|
| 76 |
+
objective. See the list of available [text completion models](https://huggingface.co/models?filter=text-generation)
|
| 77 |
+
and the list of [conversational models](https://huggingface.co/models?other=conversational)
|
| 78 |
+
on [huggingface.co/models].
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
# Prefix text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
|
| 82 |
+
# in https://github.com/rusiaaman/XLNet-gen#methodology
|
| 83 |
+
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
|
| 84 |
+
|
| 85 |
+
XL_PREFIX = """
|
| 86 |
+
In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
|
| 87 |
+
voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
|
| 88 |
+
Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
|
| 89 |
+
and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
|
| 90 |
+
accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
|
| 91 |
+
the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
|
| 92 |
+
begging for his blessing. <eod> </s> <eos>
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
def __init__(self, *args, **kwargs):
|
| 96 |
+
super().__init__(*args, **kwargs)
|
| 97 |
+
self.check_model_type(
|
| 98 |
+
TF_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
|
| 99 |
+
)
|
| 100 |
+
if "prefix" not in self._preprocess_params:
|
| 101 |
+
# This is very specific. The logic is quite complex and needs to be done
|
| 102 |
+
# as a "default".
|
| 103 |
+
# It also defines both some preprocess_kwargs and generate_kwargs
|
| 104 |
+
# which is why we cannot put them in their respective methods.
|
| 105 |
+
prefix = None
|
| 106 |
+
if self.prefix is not None:
|
| 107 |
+
prefix = self.prefix
|
| 108 |
+
if prefix is None and self.model.__class__.__name__ in [
|
| 109 |
+
"XLNetLMHeadModel",
|
| 110 |
+
"TransfoXLLMHeadModel",
|
| 111 |
+
"TFXLNetLMHeadModel",
|
| 112 |
+
"TFTransfoXLLMHeadModel",
|
| 113 |
+
]:
|
| 114 |
+
# For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
|
| 115 |
+
prefix = self.XL_PREFIX
|
| 116 |
+
if prefix is not None:
|
| 117 |
+
# Recalculate some generate_kwargs linked to prefix.
|
| 118 |
+
preprocess_params, forward_params, _ = self._sanitize_parameters(prefix=prefix, **self._forward_params)
|
| 119 |
+
self._preprocess_params = {**self._preprocess_params, **preprocess_params}
|
| 120 |
+
self._forward_params = {**self._forward_params, **forward_params}
|
| 121 |
+
|
| 122 |
+
def _sanitize_parameters(
|
| 123 |
+
self,
|
| 124 |
+
return_full_text=None,
|
| 125 |
+
return_tensors=None,
|
| 126 |
+
return_text=None,
|
| 127 |
+
return_type=None,
|
| 128 |
+
clean_up_tokenization_spaces=None,
|
| 129 |
+
prefix=None,
|
| 130 |
+
handle_long_generation=None,
|
| 131 |
+
stop_sequence=None,
|
| 132 |
+
truncation=None,
|
| 133 |
+
max_length=None,
|
| 134 |
+
continue_final_message=None,
|
| 135 |
+
**generate_kwargs,
|
| 136 |
+
):
|
| 137 |
+
preprocess_params = {}
|
| 138 |
+
|
| 139 |
+
add_special_tokens = False
|
| 140 |
+
if "add_special_tokens" in generate_kwargs:
|
| 141 |
+
add_special_tokens = preprocess_params["add_special_tokens"] = generate_kwargs.pop("add_special_tokens")
|
| 142 |
+
|
| 143 |
+
if "padding" in generate_kwargs:
|
| 144 |
+
preprocess_params["padding"] = generate_kwargs.pop("padding")
|
| 145 |
+
|
| 146 |
+
if truncation is not None:
|
| 147 |
+
preprocess_params["truncation"] = truncation
|
| 148 |
+
|
| 149 |
+
if max_length is not None:
|
| 150 |
+
preprocess_params["max_length"] = max_length
|
| 151 |
+
generate_kwargs["max_length"] = max_length
|
| 152 |
+
|
| 153 |
+
if prefix is not None:
|
| 154 |
+
preprocess_params["prefix"] = prefix
|
| 155 |
+
if prefix:
|
| 156 |
+
prefix_inputs = self.tokenizer(
|
| 157 |
+
prefix, padding=False, add_special_tokens=add_special_tokens, return_tensors=self.framework
|
| 158 |
+
)
|
| 159 |
+
generate_kwargs["prefix_length"] = prefix_inputs["input_ids"].shape[-1]
|
| 160 |
+
|
| 161 |
+
if handle_long_generation is not None:
|
| 162 |
+
if handle_long_generation not in {"hole"}:
|
| 163 |
+
raise ValueError(
|
| 164 |
+
f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"
|
| 165 |
+
" [None, 'hole']"
|
| 166 |
+
)
|
| 167 |
+
preprocess_params["handle_long_generation"] = handle_long_generation
|
| 168 |
+
|
| 169 |
+
if continue_final_message is not None:
|
| 170 |
+
preprocess_params["continue_final_message"] = continue_final_message
|
| 171 |
+
|
| 172 |
+
preprocess_params.update(generate_kwargs)
|
| 173 |
+
forward_params = generate_kwargs
|
| 174 |
+
|
| 175 |
+
postprocess_params = {}
|
| 176 |
+
if return_full_text is not None and return_type is None:
|
| 177 |
+
if return_text is not None:
|
| 178 |
+
raise ValueError("`return_text` is mutually exclusive with `return_full_text`")
|
| 179 |
+
if return_tensors is not None:
|
| 180 |
+
raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`")
|
| 181 |
+
return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
|
| 182 |
+
if return_tensors is not None and return_type is None:
|
| 183 |
+
if return_text is not None:
|
| 184 |
+
raise ValueError("`return_text` is mutually exclusive with `return_tensors`")
|
| 185 |
+
return_type = ReturnType.TENSORS
|
| 186 |
+
if return_type is not None:
|
| 187 |
+
postprocess_params["return_type"] = return_type
|
| 188 |
+
if clean_up_tokenization_spaces is not None:
|
| 189 |
+
postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces
|
| 190 |
+
if continue_final_message is not None:
|
| 191 |
+
postprocess_params["continue_final_message"] = continue_final_message
|
| 192 |
+
|
| 193 |
+
if stop_sequence is not None:
|
| 194 |
+
stop_sequence_ids = self.tokenizer.encode(stop_sequence, add_special_tokens=False)
|
| 195 |
+
if len(stop_sequence_ids) > 1:
|
| 196 |
+
warnings.warn(
|
| 197 |
+
"Stopping on a multiple token sequence is not yet supported on transformers. The first token of"
|
| 198 |
+
" the stop sequence will be used as the stop sequence string in the interim."
|
| 199 |
+
)
|
| 200 |
+
generate_kwargs["eos_token_id"] = stop_sequence_ids[0]
|
| 201 |
+
|
| 202 |
+
return preprocess_params, forward_params, postprocess_params
|
| 203 |
+
|
| 204 |
+
# overriding _parse_and_tokenize to allow for unusual language-modeling tokenizer arguments
|
| 205 |
+
def _parse_and_tokenize(self, *args, **kwargs):
|
| 206 |
+
"""
|
| 207 |
+
Parse arguments and tokenize
|
| 208 |
+
"""
|
| 209 |
+
# Parse arguments
|
| 210 |
+
if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
|
| 211 |
+
kwargs.update({"add_space_before_punct_symbol": True})
|
| 212 |
+
|
| 213 |
+
return super()._parse_and_tokenize(*args, **kwargs)
|
| 214 |
+
|
| 215 |
+
def __call__(self, text_inputs, **kwargs):
|
| 216 |
+
"""
|
| 217 |
+
Complete the prompt(s) given as inputs.
|
| 218 |
+
|
| 219 |
+
Args:
|
| 220 |
+
text_inputs (`str`, `List[str]`, List[Dict[str, str]], or `List[List[Dict[str, str]]]`):
|
| 221 |
+
One or several prompts (or one list of prompts) to complete. If strings or a list of string are
|
| 222 |
+
passed, this pipeline will continue each prompt. Alternatively, a "chat", in the form of a list
|
| 223 |
+
of dicts with "role" and "content" keys, can be passed, or a list of such chats. When chats are passed,
|
| 224 |
+
the model's chat template will be used to format them before passing them to the model.
|
| 225 |
+
return_tensors (`bool`, *optional*, defaults to `False`):
|
| 226 |
+
Returns the tensors of predictions (as token indices) in the outputs. If set to
|
| 227 |
+
`True`, the decoded text is not returned.
|
| 228 |
+
return_text (`bool`, *optional*):
|
| 229 |
+
Returns the decoded texts in the outputs.
|
| 230 |
+
return_full_text (`bool`, *optional*, defaults to `True`):
|
| 231 |
+
If set to `False` only added text is returned, otherwise the full text is returned. Cannot be
|
| 232 |
+
specified at the same time as `return_text`.
|
| 233 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
|
| 234 |
+
Whether or not to clean up the potential extra spaces in the text output.
|
| 235 |
+
continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the
|
| 236 |
+
last message in the input chat rather than starting a new one, allowing you to "prefill" its response.
|
| 237 |
+
By default this is `True` when the final message in the input chat has the `assistant` role and
|
| 238 |
+
`False` otherwise, but you can manually override that behaviour by setting this flag.
|
| 239 |
+
prefix (`str`, *optional*):
|
| 240 |
+
Prefix added to prompt.
|
| 241 |
+
handle_long_generation (`str`, *optional*):
|
| 242 |
+
By default, this pipelines does not handle long generation (ones that exceed in one form or the other
|
| 243 |
+
the model maximum length). There is no perfect way to adress this (more info
|
| 244 |
+
:https://github.com/huggingface/transformers/issues/14033#issuecomment-948385227). This provides common
|
| 245 |
+
strategies to work around that problem depending on your use case.
|
| 246 |
+
|
| 247 |
+
- `None` : default strategy where nothing in particular happens
|
| 248 |
+
- `"hole"`: Truncates left of input, and leaves a gap wide enough to let generation happen (might
|
| 249 |
+
truncate a lot of the prompt and not suitable when generation exceed the model capacity)
|
| 250 |
+
generate_kwargs (`dict`, *optional*):
|
| 251 |
+
Additional keyword arguments to pass along to the generate method of the model (see the generate method
|
| 252 |
+
corresponding to your framework [here](./text_generation)).
|
| 253 |
+
|
| 254 |
+
Return:
|
| 255 |
+
A list or a list of lists of `dict`: Returns one of the following dictionaries (cannot return a combination
|
| 256 |
+
of both `generated_text` and `generated_token_ids`):
|
| 257 |
+
|
| 258 |
+
- **generated_text** (`str`, present when `return_text=True`) -- The generated text.
|
| 259 |
+
- **generated_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The token
|
| 260 |
+
ids of the generated text.
|
| 261 |
+
"""
|
| 262 |
+
if isinstance(
|
| 263 |
+
text_inputs, (list, tuple, KeyDataset) if is_torch_available() else (list, tuple)
|
| 264 |
+
) and isinstance(text_inputs[0], (list, tuple, dict)):
|
| 265 |
+
# We have one or more prompts in list-of-dicts format, so this is chat mode
|
| 266 |
+
if isinstance(text_inputs[0], dict):
|
| 267 |
+
return super().__call__(Chat(text_inputs), **kwargs)
|
| 268 |
+
else:
|
| 269 |
+
chats = [Chat(chat) for chat in text_inputs] # 🐈 🐈 🐈
|
| 270 |
+
return super().__call__(chats, **kwargs)
|
| 271 |
+
else:
|
| 272 |
+
return super().__call__(text_inputs, **kwargs)
|
| 273 |
+
|
| 274 |
+
def preprocess(
|
| 275 |
+
self,
|
| 276 |
+
prompt_text,
|
| 277 |
+
prefix="",
|
| 278 |
+
handle_long_generation=None,
|
| 279 |
+
add_special_tokens=None,
|
| 280 |
+
truncation=None,
|
| 281 |
+
padding=None,
|
| 282 |
+
max_length=None,
|
| 283 |
+
continue_final_message=None,
|
| 284 |
+
**generate_kwargs,
|
| 285 |
+
):
|
| 286 |
+
# Only set non-None tokenizer kwargs, so as to rely on the tokenizer's defaults
|
| 287 |
+
tokenizer_kwargs = {
|
| 288 |
+
"add_special_tokens": add_special_tokens,
|
| 289 |
+
"truncation": truncation,
|
| 290 |
+
"padding": padding,
|
| 291 |
+
"max_length": max_length,
|
| 292 |
+
}
|
| 293 |
+
tokenizer_kwargs = {key: value for key, value in tokenizer_kwargs.items() if value is not None}
|
| 294 |
+
|
| 295 |
+
if isinstance(prompt_text, Chat):
|
| 296 |
+
tokenizer_kwargs.pop("add_special_tokens", None) # ignore add_special_tokens on chats
|
| 297 |
+
# If the user passes a chat that ends in an assistant message, we treat it as a prefill by default
|
| 298 |
+
# because very few models support multiple separate, consecutive assistant messages
|
| 299 |
+
if continue_final_message is None:
|
| 300 |
+
continue_final_message = prompt_text.messages[-1]["role"] == "assistant"
|
| 301 |
+
inputs = self.tokenizer.apply_chat_template(
|
| 302 |
+
prompt_text.messages,
|
| 303 |
+
add_generation_prompt=not continue_final_message,
|
| 304 |
+
continue_final_message=continue_final_message,
|
| 305 |
+
return_dict=True,
|
| 306 |
+
return_tensors=self.framework,
|
| 307 |
+
**tokenizer_kwargs,
|
| 308 |
+
)
|
| 309 |
+
else:
|
| 310 |
+
inputs = self.tokenizer(prefix + prompt_text, return_tensors=self.framework, **tokenizer_kwargs)
|
| 311 |
+
|
| 312 |
+
inputs["prompt_text"] = prompt_text
|
| 313 |
+
|
| 314 |
+
if handle_long_generation == "hole":
|
| 315 |
+
cur_len = inputs["input_ids"].shape[-1]
|
| 316 |
+
if "max_new_tokens" in generate_kwargs:
|
| 317 |
+
new_tokens = generate_kwargs["max_new_tokens"]
|
| 318 |
+
else:
|
| 319 |
+
new_tokens = generate_kwargs.get("max_length", self.generation_config.max_length) - cur_len
|
| 320 |
+
if new_tokens < 0:
|
| 321 |
+
raise ValueError("We cannot infer how many new tokens are expected")
|
| 322 |
+
if cur_len + new_tokens > self.tokenizer.model_max_length:
|
| 323 |
+
keep_length = self.tokenizer.model_max_length - new_tokens
|
| 324 |
+
if keep_length <= 0:
|
| 325 |
+
raise ValueError(
|
| 326 |
+
"We cannot use `hole` to handle this generation the number of desired tokens exceeds the"
|
| 327 |
+
" models max length"
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
inputs["input_ids"] = inputs["input_ids"][:, -keep_length:]
|
| 331 |
+
if "attention_mask" in inputs:
|
| 332 |
+
inputs["attention_mask"] = inputs["attention_mask"][:, -keep_length:]
|
| 333 |
+
|
| 334 |
+
return inputs
|
| 335 |
+
|
| 336 |
+
def _forward(self, model_inputs, **generate_kwargs):
|
| 337 |
+
input_ids = model_inputs["input_ids"]
|
| 338 |
+
attention_mask = model_inputs.get("attention_mask", None)
|
| 339 |
+
# Allow empty prompts
|
| 340 |
+
if input_ids.shape[1] == 0:
|
| 341 |
+
input_ids = None
|
| 342 |
+
attention_mask = None
|
| 343 |
+
in_b = 1
|
| 344 |
+
else:
|
| 345 |
+
in_b = input_ids.shape[0]
|
| 346 |
+
prompt_text = model_inputs.pop("prompt_text")
|
| 347 |
+
|
| 348 |
+
# If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
|
| 349 |
+
# generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
|
| 350 |
+
prefix_length = generate_kwargs.pop("prefix_length", 0)
|
| 351 |
+
if prefix_length > 0:
|
| 352 |
+
has_max_new_tokens = "max_new_tokens" in generate_kwargs or (
|
| 353 |
+
"generation_config" in generate_kwargs
|
| 354 |
+
and generate_kwargs["generation_config"].max_new_tokens is not None
|
| 355 |
+
)
|
| 356 |
+
if not has_max_new_tokens:
|
| 357 |
+
generate_kwargs["max_length"] = generate_kwargs.get("max_length") or self.generation_config.max_length
|
| 358 |
+
generate_kwargs["max_length"] += prefix_length
|
| 359 |
+
has_min_new_tokens = "min_new_tokens" in generate_kwargs or (
|
| 360 |
+
"generation_config" in generate_kwargs
|
| 361 |
+
and generate_kwargs["generation_config"].min_new_tokens is not None
|
| 362 |
+
)
|
| 363 |
+
if not has_min_new_tokens and "min_length" in generate_kwargs:
|
| 364 |
+
generate_kwargs["min_length"] += prefix_length
|
| 365 |
+
|
| 366 |
+
# User-defined `generation_config` passed to the pipeline call take precedence
|
| 367 |
+
if "generation_config" not in generate_kwargs:
|
| 368 |
+
generate_kwargs["generation_config"] = self.generation_config
|
| 369 |
+
|
| 370 |
+
generated_sequence = self.model.generate(input_ids=input_ids, attention_mask=attention_mask, **generate_kwargs)
|
| 371 |
+
out_b = generated_sequence.shape[0]
|
| 372 |
+
if self.framework == "pt":
|
| 373 |
+
generated_sequence = generated_sequence.reshape(in_b, out_b // in_b, *generated_sequence.shape[1:])
|
| 374 |
+
elif self.framework == "tf":
|
| 375 |
+
generated_sequence = tf.reshape(generated_sequence, (in_b, out_b // in_b, *generated_sequence.shape[1:]))
|
| 376 |
+
return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}
|
| 377 |
+
|
| 378 |
+
def postprocess(
|
| 379 |
+
self,
|
| 380 |
+
model_outputs,
|
| 381 |
+
return_type=ReturnType.FULL_TEXT,
|
| 382 |
+
clean_up_tokenization_spaces=True,
|
| 383 |
+
continue_final_message=None,
|
| 384 |
+
):
|
| 385 |
+
generated_sequence = model_outputs["generated_sequence"][0]
|
| 386 |
+
input_ids = model_outputs["input_ids"]
|
| 387 |
+
prompt_text = model_outputs["prompt_text"]
|
| 388 |
+
generated_sequence = generated_sequence.numpy().tolist()
|
| 389 |
+
records = []
|
| 390 |
+
for sequence in generated_sequence:
|
| 391 |
+
if return_type == ReturnType.TENSORS:
|
| 392 |
+
record = {"generated_token_ids": sequence}
|
| 393 |
+
elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
|
| 394 |
+
# Decode text
|
| 395 |
+
text = self.tokenizer.decode(
|
| 396 |
+
sequence,
|
| 397 |
+
skip_special_tokens=True,
|
| 398 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
# Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
|
| 402 |
+
if input_ids is None:
|
| 403 |
+
prompt_length = 0
|
| 404 |
+
else:
|
| 405 |
+
prompt_length = len(
|
| 406 |
+
self.tokenizer.decode(
|
| 407 |
+
input_ids[0],
|
| 408 |
+
skip_special_tokens=True,
|
| 409 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 410 |
+
)
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
all_text = text[prompt_length:]
|
| 414 |
+
if return_type == ReturnType.FULL_TEXT:
|
| 415 |
+
if isinstance(prompt_text, str):
|
| 416 |
+
all_text = prompt_text + all_text
|
| 417 |
+
elif isinstance(prompt_text, Chat):
|
| 418 |
+
if continue_final_message is None:
|
| 419 |
+
# If the user passes a chat ending in an assistant message, we treat it as a prefill by
|
| 420 |
+
# default because very few models support multiple separate, consecutive assistant messages
|
| 421 |
+
continue_final_message = prompt_text.messages[-1]["role"] == "assistant"
|
| 422 |
+
if continue_final_message:
|
| 423 |
+
# With assistant prefill, concat onto the end of the last message
|
| 424 |
+
all_text = list(prompt_text.messages)[:-1] + [
|
| 425 |
+
{
|
| 426 |
+
"role": prompt_text.messages[-1]["role"],
|
| 427 |
+
"content": prompt_text.messages[-1]["content"] + all_text,
|
| 428 |
+
}
|
| 429 |
+
]
|
| 430 |
+
else:
|
| 431 |
+
# When we're not starting from a prefill, the output is a new assistant message
|
| 432 |
+
all_text = list(prompt_text.messages) + [{"role": "assistant", "content": all_text}]
|
| 433 |
+
record = {"generated_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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.from typing import List, Union
|
| 14 |
+
from typing import List, Union
|
| 15 |
+
|
| 16 |
+
from ..utils import is_torch_available
|
| 17 |
+
from .base import Pipeline
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if is_torch_available():
|
| 21 |
+
from ..models.auto.modeling_auto import MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING
|
| 22 |
+
from ..models.speecht5.modeling_speecht5 import SpeechT5HifiGan
|
| 23 |
+
|
| 24 |
+
DEFAULT_VOCODER_ID = "microsoft/speecht5_hifigan"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class TextToAudioPipeline(Pipeline):
|
| 28 |
+
"""
|
| 29 |
+
Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`. This
|
| 30 |
+
pipeline generates an audio file from an input text and optional other conditional inputs.
|
| 31 |
+
|
| 32 |
+
Example:
|
| 33 |
+
|
| 34 |
+
```python
|
| 35 |
+
>>> from transformers import pipeline
|
| 36 |
+
|
| 37 |
+
>>> pipe = pipeline(model="suno/bark-small")
|
| 38 |
+
>>> output = pipe("Hey it's HuggingFace on the phone!")
|
| 39 |
+
|
| 40 |
+
>>> audio = output["audio"]
|
| 41 |
+
>>> sampling_rate = output["sampling_rate"]
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
| 45 |
+
|
| 46 |
+
<Tip>
|
| 47 |
+
|
| 48 |
+
You can specify parameters passed to the model by using [`TextToAudioPipeline.__call__.forward_params`] or
|
| 49 |
+
[`TextToAudioPipeline.__call__.generate_kwargs`].
|
| 50 |
+
|
| 51 |
+
Example:
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
>>> from transformers import pipeline
|
| 55 |
+
|
| 56 |
+
>>> music_generator = pipeline(task="text-to-audio", model="facebook/musicgen-small", framework="pt")
|
| 57 |
+
|
| 58 |
+
>>> # diversify the music generation by adding randomness with a high temperature and set a maximum music length
|
| 59 |
+
>>> generate_kwargs = {
|
| 60 |
+
... "do_sample": True,
|
| 61 |
+
... "temperature": 0.7,
|
| 62 |
+
... "max_new_tokens": 35,
|
| 63 |
+
... }
|
| 64 |
+
|
| 65 |
+
>>> outputs = music_generator("Techno music with high melodic riffs", generate_kwargs=generate_kwargs)
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
</Tip>
|
| 69 |
+
|
| 70 |
+
This pipeline can currently be loaded from [`pipeline`] using the following task identifiers: `"text-to-speech"` or
|
| 71 |
+
`"text-to-audio"`.
|
| 72 |
+
|
| 73 |
+
See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=text-to-speech).
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
def __init__(self, *args, vocoder=None, sampling_rate=None, **kwargs):
|
| 77 |
+
super().__init__(*args, **kwargs)
|
| 78 |
+
|
| 79 |
+
if self.framework == "tf":
|
| 80 |
+
raise ValueError("The TextToAudioPipeline is only available in PyTorch.")
|
| 81 |
+
|
| 82 |
+
self.vocoder = None
|
| 83 |
+
if self.model.__class__ in MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING.values():
|
| 84 |
+
self.vocoder = (
|
| 85 |
+
SpeechT5HifiGan.from_pretrained(DEFAULT_VOCODER_ID).to(self.model.device)
|
| 86 |
+
if vocoder is None
|
| 87 |
+
else vocoder
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
self.sampling_rate = sampling_rate
|
| 91 |
+
if self.vocoder is not None:
|
| 92 |
+
self.sampling_rate = self.vocoder.config.sampling_rate
|
| 93 |
+
|
| 94 |
+
if self.sampling_rate is None:
|
| 95 |
+
# get sampling_rate from config and generation config
|
| 96 |
+
|
| 97 |
+
config = self.model.config
|
| 98 |
+
gen_config = self.model.__dict__.get("generation_config", None)
|
| 99 |
+
if gen_config is not None:
|
| 100 |
+
config.update(gen_config.to_dict())
|
| 101 |
+
|
| 102 |
+
for sampling_rate_name in ["sample_rate", "sampling_rate"]:
|
| 103 |
+
sampling_rate = getattr(config, sampling_rate_name, None)
|
| 104 |
+
if sampling_rate is not None:
|
| 105 |
+
self.sampling_rate = sampling_rate
|
| 106 |
+
|
| 107 |
+
def preprocess(self, text, **kwargs):
|
| 108 |
+
if isinstance(text, str):
|
| 109 |
+
text = [text]
|
| 110 |
+
|
| 111 |
+
if self.model.config.model_type == "bark":
|
| 112 |
+
# bark Tokenizer is called with BarkProcessor which uses those kwargs
|
| 113 |
+
new_kwargs = {
|
| 114 |
+
"max_length": self.generation_config.semantic_config.get("max_input_semantic_length", 256),
|
| 115 |
+
"add_special_tokens": False,
|
| 116 |
+
"return_attention_mask": True,
|
| 117 |
+
"return_token_type_ids": False,
|
| 118 |
+
"padding": "max_length",
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
# priority is given to kwargs
|
| 122 |
+
new_kwargs.update(kwargs)
|
| 123 |
+
|
| 124 |
+
kwargs = new_kwargs
|
| 125 |
+
|
| 126 |
+
output = self.tokenizer(text, **kwargs, return_tensors="pt")
|
| 127 |
+
|
| 128 |
+
return output
|
| 129 |
+
|
| 130 |
+
def _forward(self, model_inputs, **kwargs):
|
| 131 |
+
# we expect some kwargs to be additional tensors which need to be on the right device
|
| 132 |
+
kwargs = self._ensure_tensor_on_device(kwargs, device=self.device)
|
| 133 |
+
forward_params = kwargs["forward_params"]
|
| 134 |
+
generate_kwargs = kwargs["generate_kwargs"]
|
| 135 |
+
|
| 136 |
+
if self.model.can_generate():
|
| 137 |
+
# we expect some kwargs to be additional tensors which need to be on the right device
|
| 138 |
+
generate_kwargs = self._ensure_tensor_on_device(generate_kwargs, device=self.device)
|
| 139 |
+
|
| 140 |
+
# User-defined `generation_config` passed to the pipeline call take precedence
|
| 141 |
+
if "generation_config" not in generate_kwargs:
|
| 142 |
+
generate_kwargs["generation_config"] = self.generation_config
|
| 143 |
+
|
| 144 |
+
# generate_kwargs get priority over forward_params
|
| 145 |
+
forward_params.update(generate_kwargs)
|
| 146 |
+
|
| 147 |
+
output = self.model.generate(**model_inputs, **forward_params)
|
| 148 |
+
else:
|
| 149 |
+
if len(generate_kwargs):
|
| 150 |
+
raise ValueError(
|
| 151 |
+
f"""You're using the `TextToAudioPipeline` with a forward-only model, but `generate_kwargs` is non empty.
|
| 152 |
+
For forward-only TTA models, please use `forward_params` instead of of
|
| 153 |
+
`generate_kwargs`. For reference, here are the `generate_kwargs` used here:
|
| 154 |
+
{generate_kwargs.keys()}"""
|
| 155 |
+
)
|
| 156 |
+
output = self.model(**model_inputs, **forward_params)[0]
|
| 157 |
+
|
| 158 |
+
if self.vocoder is not None:
|
| 159 |
+
# in that case, the output is a spectrogram that needs to be converted into a waveform
|
| 160 |
+
output = self.vocoder(output)
|
| 161 |
+
|
| 162 |
+
return output
|
| 163 |
+
|
| 164 |
+
def __call__(self, text_inputs: Union[str, List[str]], **forward_params):
|
| 165 |
+
"""
|
| 166 |
+
Generates speech/audio from the inputs. See the [`TextToAudioPipeline`] documentation for more information.
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
text_inputs (`str` or `List[str]`):
|
| 170 |
+
The text(s) to generate.
|
| 171 |
+
forward_params (`dict`, *optional*):
|
| 172 |
+
Parameters passed to the model generation/forward method. `forward_params` are always passed to the
|
| 173 |
+
underlying model.
|
| 174 |
+
generate_kwargs (`dict`, *optional*):
|
| 175 |
+
The dictionary of ad-hoc parametrization of `generate_config` to be used for the generation call. For a
|
| 176 |
+
complete overview of generate, check the [following
|
| 177 |
+
guide](https://huggingface.co/docs/transformers/en/main_classes/text_generation). `generate_kwargs` are
|
| 178 |
+
only passed to the underlying model if the latter is a generative model.
|
| 179 |
+
|
| 180 |
+
Return:
|
| 181 |
+
A `dict` or a list of `dict`: The dictionaries have two keys:
|
| 182 |
+
|
| 183 |
+
- **audio** (`np.ndarray` of shape `(nb_channels, audio_length)`) -- The generated audio waveform.
|
| 184 |
+
- **sampling_rate** (`int`) -- The sampling rate of the generated audio waveform.
|
| 185 |
+
"""
|
| 186 |
+
return super().__call__(text_inputs, **forward_params)
|
| 187 |
+
|
| 188 |
+
def _sanitize_parameters(
|
| 189 |
+
self,
|
| 190 |
+
preprocess_params=None,
|
| 191 |
+
forward_params=None,
|
| 192 |
+
generate_kwargs=None,
|
| 193 |
+
):
|
| 194 |
+
params = {
|
| 195 |
+
"forward_params": forward_params if forward_params else {},
|
| 196 |
+
"generate_kwargs": generate_kwargs if generate_kwargs else {},
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
if preprocess_params is None:
|
| 200 |
+
preprocess_params = {}
|
| 201 |
+
postprocess_params = {}
|
| 202 |
+
|
| 203 |
+
return preprocess_params, params, postprocess_params
|
| 204 |
+
|
| 205 |
+
def postprocess(self, waveform):
|
| 206 |
+
output_dict = {}
|
| 207 |
+
if isinstance(waveform, dict):
|
| 208 |
+
waveform = waveform["waveform"]
|
| 209 |
+
elif isinstance(waveform, tuple):
|
| 210 |
+
waveform = waveform[0]
|
| 211 |
+
output_dict["audio"] = waveform.cpu().float().numpy()
|
| 212 |
+
output_dict["sampling_rate"] = self.sampling_rate
|
| 213 |
+
|
| 214 |
+
return output_dict
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/token_classification.py
ADDED
|
@@ -0,0 +1,576 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import types
|
| 2 |
+
import warnings
|
| 3 |
+
from typing import List, Optional, Tuple, Union
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from ..models.bert.tokenization_bert import BasicTokenizer
|
| 8 |
+
from ..utils import (
|
| 9 |
+
ExplicitEnum,
|
| 10 |
+
add_end_docstrings,
|
| 11 |
+
is_tf_available,
|
| 12 |
+
is_torch_available,
|
| 13 |
+
)
|
| 14 |
+
from .base import ArgumentHandler, ChunkPipeline, Dataset, build_pipeline_init_args
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
if is_tf_available():
|
| 18 |
+
import tensorflow as tf
|
| 19 |
+
|
| 20 |
+
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
|
| 21 |
+
if is_torch_available():
|
| 22 |
+
import torch
|
| 23 |
+
|
| 24 |
+
from ..models.auto.modeling_auto import MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class TokenClassificationArgumentHandler(ArgumentHandler):
|
| 28 |
+
"""
|
| 29 |
+
Handles arguments for token classification.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __call__(self, inputs: Union[str, List[str]], **kwargs):
|
| 33 |
+
if inputs is not None and isinstance(inputs, (list, tuple)) and len(inputs) > 0:
|
| 34 |
+
inputs = list(inputs)
|
| 35 |
+
batch_size = len(inputs)
|
| 36 |
+
elif isinstance(inputs, str):
|
| 37 |
+
inputs = [inputs]
|
| 38 |
+
batch_size = 1
|
| 39 |
+
elif Dataset is not None and isinstance(inputs, Dataset) or isinstance(inputs, types.GeneratorType):
|
| 40 |
+
return inputs, None
|
| 41 |
+
else:
|
| 42 |
+
raise ValueError("At least one input is required.")
|
| 43 |
+
|
| 44 |
+
offset_mapping = kwargs.get("offset_mapping")
|
| 45 |
+
if offset_mapping:
|
| 46 |
+
if isinstance(offset_mapping, list) and isinstance(offset_mapping[0], tuple):
|
| 47 |
+
offset_mapping = [offset_mapping]
|
| 48 |
+
if len(offset_mapping) != batch_size:
|
| 49 |
+
raise ValueError("offset_mapping should have the same batch size as the input")
|
| 50 |
+
return inputs, offset_mapping
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class AggregationStrategy(ExplicitEnum):
|
| 54 |
+
"""All the valid aggregation strategies for TokenClassificationPipeline"""
|
| 55 |
+
|
| 56 |
+
NONE = "none"
|
| 57 |
+
SIMPLE = "simple"
|
| 58 |
+
FIRST = "first"
|
| 59 |
+
AVERAGE = "average"
|
| 60 |
+
MAX = "max"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@add_end_docstrings(
|
| 64 |
+
build_pipeline_init_args(has_tokenizer=True),
|
| 65 |
+
r"""
|
| 66 |
+
ignore_labels (`List[str]`, defaults to `["O"]`):
|
| 67 |
+
A list of labels to ignore.
|
| 68 |
+
grouped_entities (`bool`, *optional*, defaults to `False`):
|
| 69 |
+
DEPRECATED, use `aggregation_strategy` instead. Whether or not to group the tokens corresponding to the
|
| 70 |
+
same entity together in the predictions or not.
|
| 71 |
+
stride (`int`, *optional*):
|
| 72 |
+
If stride is provided, the pipeline is applied on all the text. The text is split into chunks of size
|
| 73 |
+
model_max_length. Works only with fast tokenizers and `aggregation_strategy` different from `NONE`. The
|
| 74 |
+
value of this argument defines the number of overlapping tokens between chunks. In other words, the model
|
| 75 |
+
will shift forward by `tokenizer.model_max_length - stride` tokens each step.
|
| 76 |
+
aggregation_strategy (`str`, *optional*, defaults to `"none"`):
|
| 77 |
+
The strategy to fuse (or not) tokens based on the model prediction.
|
| 78 |
+
|
| 79 |
+
- "none" : Will simply not do any aggregation and simply return raw results from the model
|
| 80 |
+
- "simple" : Will attempt to group entities following the default schema. (A, B-TAG), (B, I-TAG), (C,
|
| 81 |
+
I-TAG), (D, B-TAG2) (E, B-TAG2) will end up being [{"word": ABC, "entity": "TAG"}, {"word": "D",
|
| 82 |
+
"entity": "TAG2"}, {"word": "E", "entity": "TAG2"}] Notice that two consecutive B tags will end up as
|
| 83 |
+
different entities. On word based languages, we might end up splitting words undesirably : Imagine
|
| 84 |
+
Microsoft being tagged as [{"word": "Micro", "entity": "ENTERPRISE"}, {"word": "soft", "entity":
|
| 85 |
+
"NAME"}]. Look for FIRST, MAX, AVERAGE for ways to mitigate that and disambiguate words (on languages
|
| 86 |
+
that support that meaning, which is basically tokens separated by a space). These mitigations will
|
| 87 |
+
only work on real words, "New york" might still be tagged with two different entities.
|
| 88 |
+
- "first" : (works only on word based models) Will use the `SIMPLE` strategy except that words, cannot
|
| 89 |
+
end up with different tags. Words will simply use the tag of the first token of the word when there
|
| 90 |
+
is ambiguity.
|
| 91 |
+
- "average" : (works only on word based models) Will use the `SIMPLE` strategy except that words,
|
| 92 |
+
cannot end up with different tags. scores will be averaged first across tokens, and then the maximum
|
| 93 |
+
label is applied.
|
| 94 |
+
- "max" : (works only on word based models) Will use the `SIMPLE` strategy except that words, cannot
|
| 95 |
+
end up with different tags. Word entity will simply be the token with the maximum score.""",
|
| 96 |
+
)
|
| 97 |
+
class TokenClassificationPipeline(ChunkPipeline):
|
| 98 |
+
"""
|
| 99 |
+
Named Entity Recognition pipeline using any `ModelForTokenClassification`. See the [named entity recognition
|
| 100 |
+
examples](../task_summary#named-entity-recognition) for more information.
|
| 101 |
+
|
| 102 |
+
Example:
|
| 103 |
+
|
| 104 |
+
```python
|
| 105 |
+
>>> from transformers import pipeline
|
| 106 |
+
|
| 107 |
+
>>> token_classifier = pipeline(model="Jean-Baptiste/camembert-ner", aggregation_strategy="simple")
|
| 108 |
+
>>> sentence = "Je m'appelle jean-baptiste et je vis à montréal"
|
| 109 |
+
>>> tokens = token_classifier(sentence)
|
| 110 |
+
>>> tokens
|
| 111 |
+
[{'entity_group': 'PER', 'score': 0.9931, 'word': 'jean-baptiste', 'start': 12, 'end': 26}, {'entity_group': 'LOC', 'score': 0.998, 'word': 'montréal', 'start': 38, 'end': 47}]
|
| 112 |
+
|
| 113 |
+
>>> token = tokens[0]
|
| 114 |
+
>>> # Start and end provide an easy way to highlight words in the original text.
|
| 115 |
+
>>> sentence[token["start"] : token["end"]]
|
| 116 |
+
' jean-baptiste'
|
| 117 |
+
|
| 118 |
+
>>> # Some models use the same idea to do part of speech.
|
| 119 |
+
>>> syntaxer = pipeline(model="vblagoje/bert-english-uncased-finetuned-pos", aggregation_strategy="simple")
|
| 120 |
+
>>> syntaxer("My name is Sarah and I live in London")
|
| 121 |
+
[{'entity_group': 'PRON', 'score': 0.999, 'word': 'my', 'start': 0, 'end': 2}, {'entity_group': 'NOUN', 'score': 0.997, 'word': 'name', 'start': 3, 'end': 7}, {'entity_group': 'AUX', 'score': 0.994, 'word': 'is', 'start': 8, 'end': 10}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'sarah', 'start': 11, 'end': 16}, {'entity_group': 'CCONJ', 'score': 0.999, 'word': 'and', 'start': 17, 'end': 20}, {'entity_group': 'PRON', 'score': 0.999, 'word': 'i', 'start': 21, 'end': 22}, {'entity_group': 'VERB', 'score': 0.998, 'word': 'live', 'start': 23, 'end': 27}, {'entity_group': 'ADP', 'score': 0.999, 'word': 'in', 'start': 28, 'end': 30}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'london', 'start': 31, 'end': 37}]
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
| 125 |
+
|
| 126 |
+
This token recognition pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 127 |
+
`"ner"` (for predicting the classes of tokens in a sequence: person, organisation, location or miscellaneous).
|
| 128 |
+
|
| 129 |
+
The models that this pipeline can use are models that have been fine-tuned on a token classification task. See the
|
| 130 |
+
up-to-date list of available models on
|
| 131 |
+
[huggingface.co/models](https://huggingface.co/models?filter=token-classification).
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
default_input_names = "sequences"
|
| 135 |
+
|
| 136 |
+
def __init__(self, args_parser=TokenClassificationArgumentHandler(), *args, **kwargs):
|
| 137 |
+
super().__init__(*args, **kwargs)
|
| 138 |
+
self.check_model_type(
|
| 139 |
+
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
|
| 140 |
+
if self.framework == "tf"
|
| 141 |
+
else MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
self._basic_tokenizer = BasicTokenizer(do_lower_case=False)
|
| 145 |
+
self._args_parser = args_parser
|
| 146 |
+
|
| 147 |
+
def _sanitize_parameters(
|
| 148 |
+
self,
|
| 149 |
+
ignore_labels=None,
|
| 150 |
+
grouped_entities: Optional[bool] = None,
|
| 151 |
+
ignore_subwords: Optional[bool] = None,
|
| 152 |
+
aggregation_strategy: Optional[AggregationStrategy] = None,
|
| 153 |
+
offset_mapping: Optional[List[Tuple[int, int]]] = None,
|
| 154 |
+
stride: Optional[int] = None,
|
| 155 |
+
):
|
| 156 |
+
preprocess_params = {}
|
| 157 |
+
if offset_mapping is not None:
|
| 158 |
+
preprocess_params["offset_mapping"] = offset_mapping
|
| 159 |
+
|
| 160 |
+
postprocess_params = {}
|
| 161 |
+
if grouped_entities is not None or ignore_subwords is not None:
|
| 162 |
+
if grouped_entities and ignore_subwords:
|
| 163 |
+
aggregation_strategy = AggregationStrategy.FIRST
|
| 164 |
+
elif grouped_entities and not ignore_subwords:
|
| 165 |
+
aggregation_strategy = AggregationStrategy.SIMPLE
|
| 166 |
+
else:
|
| 167 |
+
aggregation_strategy = AggregationStrategy.NONE
|
| 168 |
+
|
| 169 |
+
if grouped_entities is not None:
|
| 170 |
+
warnings.warn(
|
| 171 |
+
"`grouped_entities` is deprecated and will be removed in version v5.0.0, defaulted to"
|
| 172 |
+
f' `aggregation_strategy="{aggregation_strategy}"` instead.'
|
| 173 |
+
)
|
| 174 |
+
if ignore_subwords is not None:
|
| 175 |
+
warnings.warn(
|
| 176 |
+
"`ignore_subwords` is deprecated and will be removed in version v5.0.0, defaulted to"
|
| 177 |
+
f' `aggregation_strategy="{aggregation_strategy}"` instead.'
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
if aggregation_strategy is not None:
|
| 181 |
+
if isinstance(aggregation_strategy, str):
|
| 182 |
+
aggregation_strategy = AggregationStrategy[aggregation_strategy.upper()]
|
| 183 |
+
if (
|
| 184 |
+
aggregation_strategy
|
| 185 |
+
in {AggregationStrategy.FIRST, AggregationStrategy.MAX, AggregationStrategy.AVERAGE}
|
| 186 |
+
and not self.tokenizer.is_fast
|
| 187 |
+
):
|
| 188 |
+
raise ValueError(
|
| 189 |
+
"Slow tokenizers cannot handle subwords. Please set the `aggregation_strategy` option"
|
| 190 |
+
' to `"simple"` or use a fast tokenizer.'
|
| 191 |
+
)
|
| 192 |
+
postprocess_params["aggregation_strategy"] = aggregation_strategy
|
| 193 |
+
if ignore_labels is not None:
|
| 194 |
+
postprocess_params["ignore_labels"] = ignore_labels
|
| 195 |
+
if stride is not None:
|
| 196 |
+
if stride >= self.tokenizer.model_max_length:
|
| 197 |
+
raise ValueError(
|
| 198 |
+
"`stride` must be less than `tokenizer.model_max_length` (or even lower if the tokenizer adds special tokens)"
|
| 199 |
+
)
|
| 200 |
+
if aggregation_strategy == AggregationStrategy.NONE:
|
| 201 |
+
raise ValueError(
|
| 202 |
+
"`stride` was provided to process all the text but `aggregation_strategy="
|
| 203 |
+
f'"{aggregation_strategy}"`, please select another one instead.'
|
| 204 |
+
)
|
| 205 |
+
else:
|
| 206 |
+
if self.tokenizer.is_fast:
|
| 207 |
+
tokenizer_params = {
|
| 208 |
+
"return_overflowing_tokens": True,
|
| 209 |
+
"padding": True,
|
| 210 |
+
"stride": stride,
|
| 211 |
+
}
|
| 212 |
+
preprocess_params["tokenizer_params"] = tokenizer_params
|
| 213 |
+
else:
|
| 214 |
+
raise ValueError(
|
| 215 |
+
"`stride` was provided to process all the text but you're using a slow tokenizer."
|
| 216 |
+
" Please use a fast tokenizer."
|
| 217 |
+
)
|
| 218 |
+
return preprocess_params, {}, postprocess_params
|
| 219 |
+
|
| 220 |
+
def __call__(self, inputs: Union[str, List[str]], **kwargs):
|
| 221 |
+
"""
|
| 222 |
+
Classify each token of the text(s) given as inputs.
|
| 223 |
+
|
| 224 |
+
Args:
|
| 225 |
+
inputs (`str` or `List[str]`):
|
| 226 |
+
One or several texts (or one list of texts) for token classification.
|
| 227 |
+
|
| 228 |
+
Return:
|
| 229 |
+
A list or a list of list of `dict`: Each result comes as a list of dictionaries (one for each token in the
|
| 230 |
+
corresponding input, or each entity if this pipeline was instantiated with an aggregation_strategy) with
|
| 231 |
+
the following keys:
|
| 232 |
+
|
| 233 |
+
- **word** (`str`) -- The token/word classified. This is obtained by decoding the selected tokens. If you
|
| 234 |
+
want to have the exact string in the original sentence, use `start` and `end`.
|
| 235 |
+
- **score** (`float`) -- The corresponding probability for `entity`.
|
| 236 |
+
- **entity** (`str`) -- The entity predicted for that token/word (it is named *entity_group* when
|
| 237 |
+
*aggregation_strategy* is not `"none"`.
|
| 238 |
+
- **index** (`int`, only present when `aggregation_strategy="none"`) -- The index of the corresponding
|
| 239 |
+
token in the sentence.
|
| 240 |
+
- **start** (`int`, *optional*) -- The index of the start of the corresponding entity in the sentence. Only
|
| 241 |
+
exists if the offsets are available within the tokenizer
|
| 242 |
+
- **end** (`int`, *optional*) -- The index of the end of the corresponding entity in the sentence. Only
|
| 243 |
+
exists if the offsets are available within the tokenizer
|
| 244 |
+
"""
|
| 245 |
+
|
| 246 |
+
_inputs, offset_mapping = self._args_parser(inputs, **kwargs)
|
| 247 |
+
if offset_mapping:
|
| 248 |
+
kwargs["offset_mapping"] = offset_mapping
|
| 249 |
+
|
| 250 |
+
return super().__call__(inputs, **kwargs)
|
| 251 |
+
|
| 252 |
+
def preprocess(self, sentence, offset_mapping=None, **preprocess_params):
|
| 253 |
+
tokenizer_params = preprocess_params.pop("tokenizer_params", {})
|
| 254 |
+
truncation = True if self.tokenizer.model_max_length and self.tokenizer.model_max_length > 0 else False
|
| 255 |
+
inputs = self.tokenizer(
|
| 256 |
+
sentence,
|
| 257 |
+
return_tensors=self.framework,
|
| 258 |
+
truncation=truncation,
|
| 259 |
+
return_special_tokens_mask=True,
|
| 260 |
+
return_offsets_mapping=self.tokenizer.is_fast,
|
| 261 |
+
**tokenizer_params,
|
| 262 |
+
)
|
| 263 |
+
inputs.pop("overflow_to_sample_mapping", None)
|
| 264 |
+
num_chunks = len(inputs["input_ids"])
|
| 265 |
+
|
| 266 |
+
for i in range(num_chunks):
|
| 267 |
+
if self.framework == "tf":
|
| 268 |
+
model_inputs = {k: tf.expand_dims(v[i], 0) for k, v in inputs.items()}
|
| 269 |
+
else:
|
| 270 |
+
model_inputs = {k: v[i].unsqueeze(0) for k, v in inputs.items()}
|
| 271 |
+
if offset_mapping is not None:
|
| 272 |
+
model_inputs["offset_mapping"] = offset_mapping
|
| 273 |
+
model_inputs["sentence"] = sentence if i == 0 else None
|
| 274 |
+
model_inputs["is_last"] = i == num_chunks - 1
|
| 275 |
+
|
| 276 |
+
yield model_inputs
|
| 277 |
+
|
| 278 |
+
def _forward(self, model_inputs):
|
| 279 |
+
# Forward
|
| 280 |
+
special_tokens_mask = model_inputs.pop("special_tokens_mask")
|
| 281 |
+
offset_mapping = model_inputs.pop("offset_mapping", None)
|
| 282 |
+
sentence = model_inputs.pop("sentence")
|
| 283 |
+
is_last = model_inputs.pop("is_last")
|
| 284 |
+
if self.framework == "tf":
|
| 285 |
+
logits = self.model(**model_inputs)[0]
|
| 286 |
+
else:
|
| 287 |
+
output = self.model(**model_inputs)
|
| 288 |
+
logits = output["logits"] if isinstance(output, dict) else output[0]
|
| 289 |
+
|
| 290 |
+
return {
|
| 291 |
+
"logits": logits,
|
| 292 |
+
"special_tokens_mask": special_tokens_mask,
|
| 293 |
+
"offset_mapping": offset_mapping,
|
| 294 |
+
"sentence": sentence,
|
| 295 |
+
"is_last": is_last,
|
| 296 |
+
**model_inputs,
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
def postprocess(self, all_outputs, aggregation_strategy=AggregationStrategy.NONE, ignore_labels=None):
|
| 300 |
+
if ignore_labels is None:
|
| 301 |
+
ignore_labels = ["O"]
|
| 302 |
+
all_entities = []
|
| 303 |
+
for model_outputs in all_outputs:
|
| 304 |
+
if self.framework == "pt" and model_outputs["logits"][0].dtype in (torch.bfloat16, torch.float16):
|
| 305 |
+
logits = model_outputs["logits"][0].to(torch.float32).numpy()
|
| 306 |
+
else:
|
| 307 |
+
logits = model_outputs["logits"][0].numpy()
|
| 308 |
+
|
| 309 |
+
sentence = all_outputs[0]["sentence"]
|
| 310 |
+
input_ids = model_outputs["input_ids"][0]
|
| 311 |
+
offset_mapping = (
|
| 312 |
+
model_outputs["offset_mapping"][0] if model_outputs["offset_mapping"] is not None else None
|
| 313 |
+
)
|
| 314 |
+
special_tokens_mask = model_outputs["special_tokens_mask"][0].numpy()
|
| 315 |
+
|
| 316 |
+
maxes = np.max(logits, axis=-1, keepdims=True)
|
| 317 |
+
shifted_exp = np.exp(logits - maxes)
|
| 318 |
+
scores = shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
|
| 319 |
+
|
| 320 |
+
if self.framework == "tf":
|
| 321 |
+
input_ids = input_ids.numpy()
|
| 322 |
+
offset_mapping = offset_mapping.numpy() if offset_mapping is not None else None
|
| 323 |
+
|
| 324 |
+
pre_entities = self.gather_pre_entities(
|
| 325 |
+
sentence, input_ids, scores, offset_mapping, special_tokens_mask, aggregation_strategy
|
| 326 |
+
)
|
| 327 |
+
grouped_entities = self.aggregate(pre_entities, aggregation_strategy)
|
| 328 |
+
# Filter anything that is in self.ignore_labels
|
| 329 |
+
entities = [
|
| 330 |
+
entity
|
| 331 |
+
for entity in grouped_entities
|
| 332 |
+
if entity.get("entity", None) not in ignore_labels
|
| 333 |
+
and entity.get("entity_group", None) not in ignore_labels
|
| 334 |
+
]
|
| 335 |
+
all_entities.extend(entities)
|
| 336 |
+
num_chunks = len(all_outputs)
|
| 337 |
+
if num_chunks > 1:
|
| 338 |
+
all_entities = self.aggregate_overlapping_entities(all_entities)
|
| 339 |
+
return all_entities
|
| 340 |
+
|
| 341 |
+
def aggregate_overlapping_entities(self, entities):
|
| 342 |
+
if len(entities) == 0:
|
| 343 |
+
return entities
|
| 344 |
+
entities = sorted(entities, key=lambda x: x["start"])
|
| 345 |
+
aggregated_entities = []
|
| 346 |
+
previous_entity = entities[0]
|
| 347 |
+
for entity in entities:
|
| 348 |
+
if previous_entity["start"] <= entity["start"] < previous_entity["end"]:
|
| 349 |
+
current_length = entity["end"] - entity["start"]
|
| 350 |
+
previous_length = previous_entity["end"] - previous_entity["start"]
|
| 351 |
+
if current_length > previous_length:
|
| 352 |
+
previous_entity = entity
|
| 353 |
+
elif current_length == previous_length and entity["score"] > previous_entity["score"]:
|
| 354 |
+
previous_entity = entity
|
| 355 |
+
else:
|
| 356 |
+
aggregated_entities.append(previous_entity)
|
| 357 |
+
previous_entity = entity
|
| 358 |
+
aggregated_entities.append(previous_entity)
|
| 359 |
+
return aggregated_entities
|
| 360 |
+
|
| 361 |
+
def gather_pre_entities(
|
| 362 |
+
self,
|
| 363 |
+
sentence: str,
|
| 364 |
+
input_ids: np.ndarray,
|
| 365 |
+
scores: np.ndarray,
|
| 366 |
+
offset_mapping: Optional[List[Tuple[int, int]]],
|
| 367 |
+
special_tokens_mask: np.ndarray,
|
| 368 |
+
aggregation_strategy: AggregationStrategy,
|
| 369 |
+
) -> List[dict]:
|
| 370 |
+
"""Fuse various numpy arrays into dicts with all the information needed for aggregation"""
|
| 371 |
+
pre_entities = []
|
| 372 |
+
for idx, token_scores in enumerate(scores):
|
| 373 |
+
# Filter special_tokens
|
| 374 |
+
if special_tokens_mask[idx]:
|
| 375 |
+
continue
|
| 376 |
+
|
| 377 |
+
word = self.tokenizer.convert_ids_to_tokens(int(input_ids[idx]))
|
| 378 |
+
if offset_mapping is not None:
|
| 379 |
+
start_ind, end_ind = offset_mapping[idx]
|
| 380 |
+
if not isinstance(start_ind, int):
|
| 381 |
+
if self.framework == "pt":
|
| 382 |
+
start_ind = start_ind.item()
|
| 383 |
+
end_ind = end_ind.item()
|
| 384 |
+
word_ref = sentence[start_ind:end_ind]
|
| 385 |
+
if getattr(self.tokenizer, "_tokenizer", None) and getattr(
|
| 386 |
+
self.tokenizer._tokenizer.model, "continuing_subword_prefix", None
|
| 387 |
+
):
|
| 388 |
+
# This is a BPE, word aware tokenizer, there is a correct way
|
| 389 |
+
# to fuse tokens
|
| 390 |
+
is_subword = len(word) != len(word_ref)
|
| 391 |
+
else:
|
| 392 |
+
# This is a fallback heuristic. This will fail most likely on any kind of text + punctuation mixtures that will be considered "words". Non word aware models cannot do better than this unfortunately.
|
| 393 |
+
if aggregation_strategy in {
|
| 394 |
+
AggregationStrategy.FIRST,
|
| 395 |
+
AggregationStrategy.AVERAGE,
|
| 396 |
+
AggregationStrategy.MAX,
|
| 397 |
+
}:
|
| 398 |
+
warnings.warn(
|
| 399 |
+
"Tokenizer does not support real words, using fallback heuristic",
|
| 400 |
+
UserWarning,
|
| 401 |
+
)
|
| 402 |
+
is_subword = start_ind > 0 and " " not in sentence[start_ind - 1 : start_ind + 1]
|
| 403 |
+
|
| 404 |
+
if int(input_ids[idx]) == self.tokenizer.unk_token_id:
|
| 405 |
+
word = word_ref
|
| 406 |
+
is_subword = False
|
| 407 |
+
else:
|
| 408 |
+
start_ind = None
|
| 409 |
+
end_ind = None
|
| 410 |
+
is_subword = False
|
| 411 |
+
|
| 412 |
+
pre_entity = {
|
| 413 |
+
"word": word,
|
| 414 |
+
"scores": token_scores,
|
| 415 |
+
"start": start_ind,
|
| 416 |
+
"end": end_ind,
|
| 417 |
+
"index": idx,
|
| 418 |
+
"is_subword": is_subword,
|
| 419 |
+
}
|
| 420 |
+
pre_entities.append(pre_entity)
|
| 421 |
+
return pre_entities
|
| 422 |
+
|
| 423 |
+
def aggregate(self, pre_entities: List[dict], aggregation_strategy: AggregationStrategy) -> List[dict]:
|
| 424 |
+
if aggregation_strategy in {AggregationStrategy.NONE, AggregationStrategy.SIMPLE}:
|
| 425 |
+
entities = []
|
| 426 |
+
for pre_entity in pre_entities:
|
| 427 |
+
entity_idx = pre_entity["scores"].argmax()
|
| 428 |
+
score = pre_entity["scores"][entity_idx]
|
| 429 |
+
entity = {
|
| 430 |
+
"entity": self.model.config.id2label[entity_idx],
|
| 431 |
+
"score": score,
|
| 432 |
+
"index": pre_entity["index"],
|
| 433 |
+
"word": pre_entity["word"],
|
| 434 |
+
"start": pre_entity["start"],
|
| 435 |
+
"end": pre_entity["end"],
|
| 436 |
+
}
|
| 437 |
+
entities.append(entity)
|
| 438 |
+
else:
|
| 439 |
+
entities = self.aggregate_words(pre_entities, aggregation_strategy)
|
| 440 |
+
|
| 441 |
+
if aggregation_strategy == AggregationStrategy.NONE:
|
| 442 |
+
return entities
|
| 443 |
+
return self.group_entities(entities)
|
| 444 |
+
|
| 445 |
+
def aggregate_word(self, entities: List[dict], aggregation_strategy: AggregationStrategy) -> dict:
|
| 446 |
+
word = self.tokenizer.convert_tokens_to_string([entity["word"] for entity in entities])
|
| 447 |
+
if aggregation_strategy == AggregationStrategy.FIRST:
|
| 448 |
+
scores = entities[0]["scores"]
|
| 449 |
+
idx = scores.argmax()
|
| 450 |
+
score = scores[idx]
|
| 451 |
+
entity = self.model.config.id2label[idx]
|
| 452 |
+
elif aggregation_strategy == AggregationStrategy.MAX:
|
| 453 |
+
max_entity = max(entities, key=lambda entity: entity["scores"].max())
|
| 454 |
+
scores = max_entity["scores"]
|
| 455 |
+
idx = scores.argmax()
|
| 456 |
+
score = scores[idx]
|
| 457 |
+
entity = self.model.config.id2label[idx]
|
| 458 |
+
elif aggregation_strategy == AggregationStrategy.AVERAGE:
|
| 459 |
+
scores = np.stack([entity["scores"] for entity in entities])
|
| 460 |
+
average_scores = np.nanmean(scores, axis=0)
|
| 461 |
+
entity_idx = average_scores.argmax()
|
| 462 |
+
entity = self.model.config.id2label[entity_idx]
|
| 463 |
+
score = average_scores[entity_idx]
|
| 464 |
+
else:
|
| 465 |
+
raise ValueError("Invalid aggregation_strategy")
|
| 466 |
+
new_entity = {
|
| 467 |
+
"entity": entity,
|
| 468 |
+
"score": score,
|
| 469 |
+
"word": word,
|
| 470 |
+
"start": entities[0]["start"],
|
| 471 |
+
"end": entities[-1]["end"],
|
| 472 |
+
}
|
| 473 |
+
return new_entity
|
| 474 |
+
|
| 475 |
+
def aggregate_words(self, entities: List[dict], aggregation_strategy: AggregationStrategy) -> List[dict]:
|
| 476 |
+
"""
|
| 477 |
+
Override tokens from a given word that disagree to force agreement on word boundaries.
|
| 478 |
+
|
| 479 |
+
Example: micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT will be rewritten with first strategy as microsoft|
|
| 480 |
+
company| B-ENT I-ENT
|
| 481 |
+
"""
|
| 482 |
+
if aggregation_strategy in {
|
| 483 |
+
AggregationStrategy.NONE,
|
| 484 |
+
AggregationStrategy.SIMPLE,
|
| 485 |
+
}:
|
| 486 |
+
raise ValueError("NONE and SIMPLE strategies are invalid for word aggregation")
|
| 487 |
+
|
| 488 |
+
word_entities = []
|
| 489 |
+
word_group = None
|
| 490 |
+
for entity in entities:
|
| 491 |
+
if word_group is None:
|
| 492 |
+
word_group = [entity]
|
| 493 |
+
elif entity["is_subword"]:
|
| 494 |
+
word_group.append(entity)
|
| 495 |
+
else:
|
| 496 |
+
word_entities.append(self.aggregate_word(word_group, aggregation_strategy))
|
| 497 |
+
word_group = [entity]
|
| 498 |
+
# Last item
|
| 499 |
+
if word_group is not None:
|
| 500 |
+
word_entities.append(self.aggregate_word(word_group, aggregation_strategy))
|
| 501 |
+
return word_entities
|
| 502 |
+
|
| 503 |
+
def group_sub_entities(self, entities: List[dict]) -> dict:
|
| 504 |
+
"""
|
| 505 |
+
Group together the adjacent tokens with the same entity predicted.
|
| 506 |
+
|
| 507 |
+
Args:
|
| 508 |
+
entities (`dict`): The entities predicted by the pipeline.
|
| 509 |
+
"""
|
| 510 |
+
# Get the first entity in the entity group
|
| 511 |
+
entity = entities[0]["entity"].split("-", 1)[-1]
|
| 512 |
+
scores = np.nanmean([entity["score"] for entity in entities])
|
| 513 |
+
tokens = [entity["word"] for entity in entities]
|
| 514 |
+
|
| 515 |
+
entity_group = {
|
| 516 |
+
"entity_group": entity,
|
| 517 |
+
"score": np.mean(scores),
|
| 518 |
+
"word": self.tokenizer.convert_tokens_to_string(tokens),
|
| 519 |
+
"start": entities[0]["start"],
|
| 520 |
+
"end": entities[-1]["end"],
|
| 521 |
+
}
|
| 522 |
+
return entity_group
|
| 523 |
+
|
| 524 |
+
def get_tag(self, entity_name: str) -> Tuple[str, str]:
|
| 525 |
+
if entity_name.startswith("B-"):
|
| 526 |
+
bi = "B"
|
| 527 |
+
tag = entity_name[2:]
|
| 528 |
+
elif entity_name.startswith("I-"):
|
| 529 |
+
bi = "I"
|
| 530 |
+
tag = entity_name[2:]
|
| 531 |
+
else:
|
| 532 |
+
# It's not in B-, I- format
|
| 533 |
+
# Default to I- for continuation.
|
| 534 |
+
bi = "I"
|
| 535 |
+
tag = entity_name
|
| 536 |
+
return bi, tag
|
| 537 |
+
|
| 538 |
+
def group_entities(self, entities: List[dict]) -> List[dict]:
|
| 539 |
+
"""
|
| 540 |
+
Find and group together the adjacent tokens with the same entity predicted.
|
| 541 |
+
|
| 542 |
+
Args:
|
| 543 |
+
entities (`dict`): The entities predicted by the pipeline.
|
| 544 |
+
"""
|
| 545 |
+
|
| 546 |
+
entity_groups = []
|
| 547 |
+
entity_group_disagg = []
|
| 548 |
+
|
| 549 |
+
for entity in entities:
|
| 550 |
+
if not entity_group_disagg:
|
| 551 |
+
entity_group_disagg.append(entity)
|
| 552 |
+
continue
|
| 553 |
+
|
| 554 |
+
# If the current entity is similar and adjacent to the previous entity,
|
| 555 |
+
# append it to the disaggregated entity group
|
| 556 |
+
# The split is meant to account for the "B" and "I" prefixes
|
| 557 |
+
# Shouldn't merge if both entities are B-type
|
| 558 |
+
bi, tag = self.get_tag(entity["entity"])
|
| 559 |
+
last_bi, last_tag = self.get_tag(entity_group_disagg[-1]["entity"])
|
| 560 |
+
|
| 561 |
+
if tag == last_tag and bi != "B":
|
| 562 |
+
# Modify subword type to be previous_type
|
| 563 |
+
entity_group_disagg.append(entity)
|
| 564 |
+
else:
|
| 565 |
+
# If the current entity is different from the previous entity
|
| 566 |
+
# aggregate the disaggregated entity group
|
| 567 |
+
entity_groups.append(self.group_sub_entities(entity_group_disagg))
|
| 568 |
+
entity_group_disagg = [entity]
|
| 569 |
+
if entity_group_disagg:
|
| 570 |
+
# it's the last entity, add it to the entity groups
|
| 571 |
+
entity_groups.append(self.group_sub_entities(entity_group_disagg))
|
| 572 |
+
|
| 573 |
+
return entity_groups
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
NerPipeline = TokenClassificationPipeline
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/video_classification.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 warnings
|
| 15 |
+
from io import BytesIO
|
| 16 |
+
from typing import List, Union
|
| 17 |
+
|
| 18 |
+
import requests
|
| 19 |
+
|
| 20 |
+
from ..utils import (
|
| 21 |
+
add_end_docstrings,
|
| 22 |
+
is_av_available,
|
| 23 |
+
is_torch_available,
|
| 24 |
+
logging,
|
| 25 |
+
requires_backends,
|
| 26 |
+
)
|
| 27 |
+
from .base import Pipeline, build_pipeline_init_args
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_av_available():
|
| 31 |
+
import av
|
| 32 |
+
import numpy as np
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if is_torch_available():
|
| 36 |
+
from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES
|
| 37 |
+
|
| 38 |
+
logger = logging.get_logger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
|
| 42 |
+
class VideoClassificationPipeline(Pipeline):
|
| 43 |
+
"""
|
| 44 |
+
Video classification pipeline using any `AutoModelForVideoClassification`. This pipeline predicts the class of a
|
| 45 |
+
video.
|
| 46 |
+
|
| 47 |
+
This video classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 48 |
+
`"video-classification"`.
|
| 49 |
+
|
| 50 |
+
See the list of available models on
|
| 51 |
+
[huggingface.co/models](https://huggingface.co/models?filter=video-classification).
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(self, *args, **kwargs):
|
| 55 |
+
super().__init__(*args, **kwargs)
|
| 56 |
+
requires_backends(self, "av")
|
| 57 |
+
self.check_model_type(MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES)
|
| 58 |
+
|
| 59 |
+
def _sanitize_parameters(self, top_k=None, num_frames=None, frame_sampling_rate=None, function_to_apply=None):
|
| 60 |
+
preprocess_params = {}
|
| 61 |
+
if frame_sampling_rate is not None:
|
| 62 |
+
preprocess_params["frame_sampling_rate"] = frame_sampling_rate
|
| 63 |
+
if num_frames is not None:
|
| 64 |
+
preprocess_params["num_frames"] = num_frames
|
| 65 |
+
|
| 66 |
+
postprocess_params = {}
|
| 67 |
+
if top_k is not None:
|
| 68 |
+
postprocess_params["top_k"] = top_k
|
| 69 |
+
if function_to_apply is not None:
|
| 70 |
+
if function_to_apply not in ["softmax", "sigmoid", "none"]:
|
| 71 |
+
raise ValueError(
|
| 72 |
+
f"Invalid value for `function_to_apply`: {function_to_apply}. "
|
| 73 |
+
"Valid options are ['softmax', 'sigmoid', 'none']"
|
| 74 |
+
)
|
| 75 |
+
postprocess_params["function_to_apply"] = function_to_apply
|
| 76 |
+
else:
|
| 77 |
+
postprocess_params["function_to_apply"] = "softmax"
|
| 78 |
+
return preprocess_params, {}, postprocess_params
|
| 79 |
+
|
| 80 |
+
def __call__(self, inputs: Union[str, List[str]] = None, **kwargs):
|
| 81 |
+
"""
|
| 82 |
+
Assign labels to the video(s) passed as inputs.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
inputs (`str`, `List[str]`):
|
| 86 |
+
The pipeline handles three types of videos:
|
| 87 |
+
|
| 88 |
+
- A string containing a http link pointing to a video
|
| 89 |
+
- A string containing a local path to a video
|
| 90 |
+
|
| 91 |
+
The pipeline accepts either a single video or a batch of videos, which must then be passed as a string.
|
| 92 |
+
Videos in a batch must all be in the same format: all as http links or all as local paths.
|
| 93 |
+
top_k (`int`, *optional*, defaults to 5):
|
| 94 |
+
The number of top labels that will be returned by the pipeline. If the provided number is higher than
|
| 95 |
+
the number of labels available in the model configuration, it will default to the number of labels.
|
| 96 |
+
num_frames (`int`, *optional*, defaults to `self.model.config.num_frames`):
|
| 97 |
+
The number of frames sampled from the video to run the classification on. If not provided, will default
|
| 98 |
+
to the number of frames specified in the model configuration.
|
| 99 |
+
frame_sampling_rate (`int`, *optional*, defaults to 1):
|
| 100 |
+
The sampling rate used to select frames from the video. If not provided, will default to 1, i.e. every
|
| 101 |
+
frame will be used.
|
| 102 |
+
function_to_apply(`str`, *optional*, defaults to "softmax"):
|
| 103 |
+
The function to apply to the model output. By default, the pipeline will apply the softmax function to
|
| 104 |
+
the output of the model. Valid options: ["softmax", "sigmoid", "none"]. Note that passing Python's
|
| 105 |
+
built-in `None` will default to "softmax", so you need to pass the string "none" to disable any
|
| 106 |
+
post-processing.
|
| 107 |
+
|
| 108 |
+
Return:
|
| 109 |
+
A dictionary or a list of dictionaries containing result. If the input is a single video, will return a
|
| 110 |
+
dictionary, if the input is a list of several videos, will return a list of dictionaries corresponding to
|
| 111 |
+
the videos.
|
| 112 |
+
|
| 113 |
+
The dictionaries contain the following keys:
|
| 114 |
+
|
| 115 |
+
- **label** (`str`) -- The label identified by the model.
|
| 116 |
+
- **score** (`int`) -- The score attributed by the model for that label.
|
| 117 |
+
"""
|
| 118 |
+
# After deprecation of this is completed, remove the default `None` value for `images`
|
| 119 |
+
if "videos" in kwargs:
|
| 120 |
+
warnings.warn(
|
| 121 |
+
"The `videos` argument has been renamed to `inputs`. In version 5 of Transformers, `videos` will no longer be accepted",
|
| 122 |
+
FutureWarning,
|
| 123 |
+
)
|
| 124 |
+
inputs = kwargs.pop("videos")
|
| 125 |
+
if inputs is None:
|
| 126 |
+
raise ValueError("Cannot call the video-classification pipeline without an inputs argument!")
|
| 127 |
+
return super().__call__(inputs, **kwargs)
|
| 128 |
+
|
| 129 |
+
def preprocess(self, video, num_frames=None, frame_sampling_rate=1):
|
| 130 |
+
if num_frames is None:
|
| 131 |
+
num_frames = self.model.config.num_frames
|
| 132 |
+
|
| 133 |
+
if video.startswith("http://") or video.startswith("https://"):
|
| 134 |
+
video = BytesIO(requests.get(video).content)
|
| 135 |
+
|
| 136 |
+
container = av.open(video)
|
| 137 |
+
|
| 138 |
+
start_idx = 0
|
| 139 |
+
end_idx = num_frames * frame_sampling_rate - 1
|
| 140 |
+
indices = np.linspace(start_idx, end_idx, num=num_frames, dtype=np.int64)
|
| 141 |
+
|
| 142 |
+
video = read_video_pyav(container, indices)
|
| 143 |
+
video = list(video)
|
| 144 |
+
|
| 145 |
+
model_inputs = self.image_processor(video, return_tensors=self.framework)
|
| 146 |
+
if self.framework == "pt":
|
| 147 |
+
model_inputs = model_inputs.to(self.torch_dtype)
|
| 148 |
+
return model_inputs
|
| 149 |
+
|
| 150 |
+
def _forward(self, model_inputs):
|
| 151 |
+
model_outputs = self.model(**model_inputs)
|
| 152 |
+
return model_outputs
|
| 153 |
+
|
| 154 |
+
def postprocess(self, model_outputs, top_k=5, function_to_apply="softmax"):
|
| 155 |
+
if top_k > self.model.config.num_labels:
|
| 156 |
+
top_k = self.model.config.num_labels
|
| 157 |
+
|
| 158 |
+
if self.framework == "pt":
|
| 159 |
+
if function_to_apply == "softmax":
|
| 160 |
+
probs = model_outputs.logits[0].softmax(-1)
|
| 161 |
+
elif function_to_apply == "sigmoid":
|
| 162 |
+
probs = model_outputs.logits[0].sigmoid()
|
| 163 |
+
else:
|
| 164 |
+
probs = model_outputs.logits[0]
|
| 165 |
+
scores, ids = probs.topk(top_k)
|
| 166 |
+
else:
|
| 167 |
+
raise ValueError(f"Unsupported framework: {self.framework}")
|
| 168 |
+
|
| 169 |
+
scores = scores.tolist()
|
| 170 |
+
ids = ids.tolist()
|
| 171 |
+
return [{"score": score, "label": self.model.config.id2label[_id]} for score, _id in zip(scores, ids)]
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def read_video_pyav(container, indices):
|
| 175 |
+
frames = []
|
| 176 |
+
container.seek(0)
|
| 177 |
+
start_index = indices[0]
|
| 178 |
+
end_index = indices[-1]
|
| 179 |
+
for i, frame in enumerate(container.decode(video=0)):
|
| 180 |
+
if i > end_index:
|
| 181 |
+
break
|
| 182 |
+
if i >= start_index and i in indices:
|
| 183 |
+
frames.append(frame)
|
| 184 |
+
return np.stack([x.to_ndarray(format="rgb24") for x in frames])
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/visual_question_answering.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Union
|
| 2 |
+
|
| 3 |
+
from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging
|
| 4 |
+
from .base import Pipeline, build_pipeline_init_args
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
if is_vision_available():
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
from ..image_utils import load_image
|
| 11 |
+
|
| 12 |
+
if is_torch_available():
|
| 13 |
+
from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES
|
| 14 |
+
from .pt_utils import KeyDataset
|
| 15 |
+
|
| 16 |
+
logger = logging.get_logger(__name__)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True, has_image_processor=True))
|
| 20 |
+
class VisualQuestionAnsweringPipeline(Pipeline):
|
| 21 |
+
"""
|
| 22 |
+
Visual Question Answering pipeline using a `AutoModelForVisualQuestionAnswering`. This pipeline is currently only
|
| 23 |
+
available in PyTorch.
|
| 24 |
+
|
| 25 |
+
Example:
|
| 26 |
+
|
| 27 |
+
```python
|
| 28 |
+
>>> from transformers import pipeline
|
| 29 |
+
|
| 30 |
+
>>> oracle = pipeline(model="dandelin/vilt-b32-finetuned-vqa")
|
| 31 |
+
>>> image_url = "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/lena.png"
|
| 32 |
+
>>> oracle(question="What is she wearing ?", image=image_url)
|
| 33 |
+
[{'score': 0.948, 'answer': 'hat'}, {'score': 0.009, 'answer': 'fedora'}, {'score': 0.003, 'answer': 'clothes'}, {'score': 0.003, 'answer': 'sun hat'}, {'score': 0.002, 'answer': 'nothing'}]
|
| 34 |
+
|
| 35 |
+
>>> oracle(question="What is she wearing ?", image=image_url, top_k=1)
|
| 36 |
+
[{'score': 0.948, 'answer': 'hat'}]
|
| 37 |
+
|
| 38 |
+
>>> oracle(question="Is this a person ?", image=image_url, top_k=1)
|
| 39 |
+
[{'score': 0.993, 'answer': 'yes'}]
|
| 40 |
+
|
| 41 |
+
>>> oracle(question="Is this a man ?", image=image_url, top_k=1)
|
| 42 |
+
[{'score': 0.996, 'answer': 'no'}]
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
| 46 |
+
|
| 47 |
+
This visual question answering pipeline can currently be loaded from [`pipeline`] using the following task
|
| 48 |
+
identifiers: `"visual-question-answering", "vqa"`.
|
| 49 |
+
|
| 50 |
+
The models that this pipeline can use are models that have been fine-tuned on a visual question answering task. See
|
| 51 |
+
the up-to-date list of available models on
|
| 52 |
+
[huggingface.co/models](https://huggingface.co/models?filter=visual-question-answering).
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
def __init__(self, *args, **kwargs):
|
| 56 |
+
super().__init__(*args, **kwargs)
|
| 57 |
+
self.check_model_type(MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES)
|
| 58 |
+
|
| 59 |
+
def _sanitize_parameters(self, top_k=None, padding=None, truncation=None, timeout=None, **kwargs):
|
| 60 |
+
preprocess_params, postprocess_params = {}, {}
|
| 61 |
+
if padding is not None:
|
| 62 |
+
preprocess_params["padding"] = padding
|
| 63 |
+
if truncation is not None:
|
| 64 |
+
preprocess_params["truncation"] = truncation
|
| 65 |
+
if timeout is not None:
|
| 66 |
+
preprocess_params["timeout"] = timeout
|
| 67 |
+
if top_k is not None:
|
| 68 |
+
postprocess_params["top_k"] = top_k
|
| 69 |
+
return preprocess_params, {}, postprocess_params
|
| 70 |
+
|
| 71 |
+
def __call__(
|
| 72 |
+
self,
|
| 73 |
+
image: Union["Image.Image", str, List["Image.Image"], List[str], "KeyDataset"],
|
| 74 |
+
question: Union[str, List[str]] = None,
|
| 75 |
+
**kwargs,
|
| 76 |
+
):
|
| 77 |
+
r"""
|
| 78 |
+
Answers open-ended questions about images. The pipeline accepts several types of inputs which are detailed
|
| 79 |
+
below:
|
| 80 |
+
|
| 81 |
+
- `pipeline(image=image, question=question)`
|
| 82 |
+
- `pipeline({"image": image, "question": question})`
|
| 83 |
+
- `pipeline([{"image": image, "question": question}])`
|
| 84 |
+
- `pipeline([{"image": image, "question": question}, {"image": image, "question": question}])`
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
image (`str`, `List[str]`, `PIL.Image`, `List[PIL.Image]` or `KeyDataset`):
|
| 88 |
+
The pipeline handles three types of images:
|
| 89 |
+
|
| 90 |
+
- A string containing a http link pointing to an image
|
| 91 |
+
- A string containing a local path to an image
|
| 92 |
+
- An image loaded in PIL directly
|
| 93 |
+
|
| 94 |
+
The pipeline accepts either a single image or a batch of images. If given a single image, it can be
|
| 95 |
+
broadcasted to multiple questions.
|
| 96 |
+
For dataset: the passed in dataset must be of type `transformers.pipelines.pt_utils.KeyDataset`
|
| 97 |
+
Example:
|
| 98 |
+
```python
|
| 99 |
+
>>> from transformers.pipelines.pt_utils import KeyDataset
|
| 100 |
+
>>> from datasets import load_dataset
|
| 101 |
+
|
| 102 |
+
>>> dataset = load_dataset("detection-datasets/coco")
|
| 103 |
+
>>> oracle(image=KeyDataset(dataset, "image"), question="What's in this image?")
|
| 104 |
+
|
| 105 |
+
```
|
| 106 |
+
question (`str`, `List[str]`):
|
| 107 |
+
The question(s) asked. If given a single question, it can be broadcasted to multiple images.
|
| 108 |
+
If multiple images and questions are given, each and every question will be broadcasted to all images
|
| 109 |
+
(same effect as a Cartesian product)
|
| 110 |
+
top_k (`int`, *optional*, defaults to 5):
|
| 111 |
+
The number of top labels that will be returned by the pipeline. If the provided number is higher than
|
| 112 |
+
the number of labels available in the model configuration, it will default to the number of labels.
|
| 113 |
+
timeout (`float`, *optional*, defaults to None):
|
| 114 |
+
The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
|
| 115 |
+
the call may block forever.
|
| 116 |
+
Return:
|
| 117 |
+
A dictionary or a list of dictionaries containing the result. The dictionaries contain the following keys:
|
| 118 |
+
|
| 119 |
+
- **label** (`str`) -- The label identified by the model.
|
| 120 |
+
- **score** (`int`) -- The score attributed by the model for that label.
|
| 121 |
+
"""
|
| 122 |
+
is_dataset = isinstance(image, KeyDataset)
|
| 123 |
+
is_image_batch = isinstance(image, list) and all(isinstance(item, (Image.Image, str)) for item in image)
|
| 124 |
+
is_question_batch = isinstance(question, list) and all(isinstance(item, str) for item in question)
|
| 125 |
+
|
| 126 |
+
if isinstance(image, (Image.Image, str)) and isinstance(question, str):
|
| 127 |
+
inputs = {"image": image, "question": question}
|
| 128 |
+
elif (is_image_batch or is_dataset) and isinstance(question, str):
|
| 129 |
+
inputs = [{"image": im, "question": question} for im in image]
|
| 130 |
+
elif isinstance(image, (Image.Image, str)) and is_question_batch:
|
| 131 |
+
inputs = [{"image": image, "question": q} for q in question]
|
| 132 |
+
elif (is_image_batch or is_dataset) and is_question_batch:
|
| 133 |
+
question_image_pairs = []
|
| 134 |
+
for q in question:
|
| 135 |
+
for im in image:
|
| 136 |
+
question_image_pairs.append({"image": im, "question": q})
|
| 137 |
+
inputs = question_image_pairs
|
| 138 |
+
else:
|
| 139 |
+
"""
|
| 140 |
+
Supports the following format
|
| 141 |
+
- {"image": image, "question": question}
|
| 142 |
+
- [{"image": image, "question": question}]
|
| 143 |
+
- Generator and datasets
|
| 144 |
+
"""
|
| 145 |
+
inputs = image
|
| 146 |
+
results = super().__call__(inputs, **kwargs)
|
| 147 |
+
return results
|
| 148 |
+
|
| 149 |
+
def preprocess(self, inputs, padding=False, truncation=False, timeout=None):
|
| 150 |
+
image = load_image(inputs["image"], timeout=timeout)
|
| 151 |
+
model_inputs = self.tokenizer(
|
| 152 |
+
inputs["question"],
|
| 153 |
+
return_tensors=self.framework,
|
| 154 |
+
padding=padding,
|
| 155 |
+
truncation=truncation,
|
| 156 |
+
)
|
| 157 |
+
image_features = self.image_processor(images=image, return_tensors=self.framework)
|
| 158 |
+
if self.framework == "pt":
|
| 159 |
+
image_features = image_features.to(self.torch_dtype)
|
| 160 |
+
model_inputs.update(image_features)
|
| 161 |
+
return model_inputs
|
| 162 |
+
|
| 163 |
+
def _forward(self, model_inputs, **generate_kwargs):
|
| 164 |
+
if self.model.can_generate():
|
| 165 |
+
# User-defined `generation_config` passed to the pipeline call take precedence
|
| 166 |
+
if "generation_config" not in generate_kwargs:
|
| 167 |
+
generate_kwargs["generation_config"] = self.generation_config
|
| 168 |
+
|
| 169 |
+
model_outputs = self.model.generate(**model_inputs, **generate_kwargs)
|
| 170 |
+
else:
|
| 171 |
+
model_outputs = self.model(**model_inputs)
|
| 172 |
+
return model_outputs
|
| 173 |
+
|
| 174 |
+
def postprocess(self, model_outputs, top_k=5):
|
| 175 |
+
if self.model.can_generate():
|
| 176 |
+
return [
|
| 177 |
+
{"answer": self.tokenizer.decode(output_ids, skip_special_tokens=True).strip()}
|
| 178 |
+
for output_ids in model_outputs
|
| 179 |
+
]
|
| 180 |
+
else:
|
| 181 |
+
if top_k > self.model.config.num_labels:
|
| 182 |
+
top_k = self.model.config.num_labels
|
| 183 |
+
|
| 184 |
+
if self.framework == "pt":
|
| 185 |
+
probs = model_outputs.logits.sigmoid()[0]
|
| 186 |
+
scores, ids = probs.topk(top_k)
|
| 187 |
+
else:
|
| 188 |
+
raise ValueError(f"Unsupported framework: {self.framework}")
|
| 189 |
+
|
| 190 |
+
scores = scores.tolist()
|
| 191 |
+
ids = ids.tolist()
|
| 192 |
+
return [{"score": score, "answer": self.model.config.id2label[_id]} for score, _id in zip(scores, ids)]
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/zero_shot_audio_classification.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 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 |
+
from collections import UserDict
|
| 16 |
+
from typing import Union
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import requests
|
| 20 |
+
|
| 21 |
+
from ..utils import (
|
| 22 |
+
add_end_docstrings,
|
| 23 |
+
logging,
|
| 24 |
+
)
|
| 25 |
+
from .audio_classification import ffmpeg_read
|
| 26 |
+
from .base import Pipeline, build_pipeline_init_args
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@add_end_docstrings(build_pipeline_init_args(has_feature_extractor=True, has_tokenizer=True))
|
| 33 |
+
class ZeroShotAudioClassificationPipeline(Pipeline):
|
| 34 |
+
"""
|
| 35 |
+
Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you
|
| 36 |
+
provide an audio and a set of `candidate_labels`.
|
| 37 |
+
|
| 38 |
+
<Tip warning={true}>
|
| 39 |
+
|
| 40 |
+
The default `hypothesis_template` is : `"This is a sound of {}."`. Make sure you update it for your usage.
|
| 41 |
+
|
| 42 |
+
</Tip>
|
| 43 |
+
|
| 44 |
+
Example:
|
| 45 |
+
```python
|
| 46 |
+
>>> from transformers import pipeline
|
| 47 |
+
>>> from datasets import load_dataset
|
| 48 |
+
|
| 49 |
+
>>> dataset = load_dataset("ashraq/esc50")
|
| 50 |
+
>>> audio = next(iter(dataset["train"]["audio"]))["array"]
|
| 51 |
+
>>> classifier = pipeline(task="zero-shot-audio-classification", model="laion/clap-htsat-unfused")
|
| 52 |
+
>>> classifier(audio, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"])
|
| 53 |
+
[{'score': 0.9996, 'label': 'Sound of a dog'}, {'score': 0.0004, 'label': 'Sound of vaccum cleaner'}]
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This audio
|
| 58 |
+
classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 59 |
+
`"zero-shot-audio-classification"`. See the list of available models on
|
| 60 |
+
[huggingface.co/models](https://huggingface.co/models?filter=zero-shot-audio-classification).
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(self, **kwargs):
|
| 64 |
+
super().__init__(**kwargs)
|
| 65 |
+
|
| 66 |
+
if self.framework != "pt":
|
| 67 |
+
raise ValueError(f"The {self.__class__} is only available in PyTorch.")
|
| 68 |
+
# No specific FOR_XXX available yet
|
| 69 |
+
|
| 70 |
+
def __call__(self, audios: Union[np.ndarray, bytes, str], **kwargs):
|
| 71 |
+
"""
|
| 72 |
+
Assign labels to the audio(s) passed as inputs.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
audios (`str`, `List[str]`, `np.array` or `List[np.array]`):
|
| 76 |
+
The pipeline handles three types of inputs:
|
| 77 |
+
- A string containing a http link pointing to an audio
|
| 78 |
+
- A string containing a local path to an audio
|
| 79 |
+
- An audio loaded in numpy
|
| 80 |
+
candidate_labels (`List[str]`):
|
| 81 |
+
The candidate labels for this audio. They will be formatted using *hypothesis_template*.
|
| 82 |
+
hypothesis_template (`str`, *optional*, defaults to `"This is a sound of {}"`):
|
| 83 |
+
The format used in conjunction with *candidate_labels* to attempt the audio classification by
|
| 84 |
+
replacing the placeholder with the candidate_labels. Pass "{}" if *candidate_labels* are
|
| 85 |
+
already formatted.
|
| 86 |
+
Return:
|
| 87 |
+
A list of dictionaries containing one entry per proposed label. Each dictionary contains the
|
| 88 |
+
following keys:
|
| 89 |
+
- **label** (`str`) -- One of the suggested *candidate_labels*.
|
| 90 |
+
- **score** (`float`) -- The score attributed by the model to that label. It is a value between
|
| 91 |
+
0 and 1, computed as the `softmax` of `logits_per_audio`.
|
| 92 |
+
"""
|
| 93 |
+
return super().__call__(audios, **kwargs)
|
| 94 |
+
|
| 95 |
+
def _sanitize_parameters(self, **kwargs):
|
| 96 |
+
preprocess_params = {}
|
| 97 |
+
if "candidate_labels" in kwargs:
|
| 98 |
+
preprocess_params["candidate_labels"] = kwargs["candidate_labels"]
|
| 99 |
+
if "hypothesis_template" in kwargs:
|
| 100 |
+
preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"]
|
| 101 |
+
|
| 102 |
+
return preprocess_params, {}, {}
|
| 103 |
+
|
| 104 |
+
def preprocess(self, audio, candidate_labels=None, hypothesis_template="This is a sound of {}."):
|
| 105 |
+
if isinstance(audio, str):
|
| 106 |
+
if audio.startswith("http://") or audio.startswith("https://"):
|
| 107 |
+
# We need to actually check for a real protocol, otherwise it's impossible to use a local file
|
| 108 |
+
# like http_huggingface_co.png
|
| 109 |
+
audio = requests.get(audio).content
|
| 110 |
+
else:
|
| 111 |
+
with open(audio, "rb") as f:
|
| 112 |
+
audio = f.read()
|
| 113 |
+
|
| 114 |
+
if isinstance(audio, bytes):
|
| 115 |
+
audio = ffmpeg_read(audio, self.feature_extractor.sampling_rate)
|
| 116 |
+
|
| 117 |
+
if not isinstance(audio, np.ndarray):
|
| 118 |
+
raise TypeError("We expect a numpy ndarray as input")
|
| 119 |
+
if len(audio.shape) != 1:
|
| 120 |
+
raise ValueError("We expect a single channel audio input for ZeroShotAudioClassificationPipeline")
|
| 121 |
+
|
| 122 |
+
inputs = self.feature_extractor(
|
| 123 |
+
[audio], sampling_rate=self.feature_extractor.sampling_rate, return_tensors="pt"
|
| 124 |
+
)
|
| 125 |
+
if self.framework == "pt":
|
| 126 |
+
inputs = inputs.to(self.torch_dtype)
|
| 127 |
+
inputs["candidate_labels"] = candidate_labels
|
| 128 |
+
sequences = [hypothesis_template.format(x) for x in candidate_labels]
|
| 129 |
+
text_inputs = self.tokenizer(sequences, return_tensors=self.framework, padding=True)
|
| 130 |
+
inputs["text_inputs"] = [text_inputs]
|
| 131 |
+
return inputs
|
| 132 |
+
|
| 133 |
+
def _forward(self, model_inputs):
|
| 134 |
+
candidate_labels = model_inputs.pop("candidate_labels")
|
| 135 |
+
text_inputs = model_inputs.pop("text_inputs")
|
| 136 |
+
if isinstance(text_inputs[0], UserDict):
|
| 137 |
+
text_inputs = text_inputs[0]
|
| 138 |
+
else:
|
| 139 |
+
# Batching case.
|
| 140 |
+
text_inputs = text_inputs[0][0]
|
| 141 |
+
|
| 142 |
+
outputs = self.model(**text_inputs, **model_inputs)
|
| 143 |
+
|
| 144 |
+
model_outputs = {
|
| 145 |
+
"candidate_labels": candidate_labels,
|
| 146 |
+
"logits": outputs.logits_per_audio,
|
| 147 |
+
}
|
| 148 |
+
return model_outputs
|
| 149 |
+
|
| 150 |
+
def postprocess(self, model_outputs):
|
| 151 |
+
candidate_labels = model_outputs.pop("candidate_labels")
|
| 152 |
+
logits = model_outputs["logits"][0]
|
| 153 |
+
|
| 154 |
+
if self.framework == "pt":
|
| 155 |
+
probs = logits.softmax(dim=0)
|
| 156 |
+
scores = probs.tolist()
|
| 157 |
+
else:
|
| 158 |
+
raise ValueError("`tf` framework not supported.")
|
| 159 |
+
|
| 160 |
+
result = [
|
| 161 |
+
{"score": score, "label": candidate_label}
|
| 162 |
+
for score, candidate_label in sorted(zip(scores, candidate_labels), key=lambda x: -x[0])
|
| 163 |
+
]
|
| 164 |
+
return result
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/zero_shot_classification.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
from typing import List, Union
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from ..tokenization_utils import TruncationStrategy
|
| 7 |
+
from ..utils import add_end_docstrings, logging
|
| 8 |
+
from .base import ArgumentHandler, ChunkPipeline, build_pipeline_init_args
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
logger = logging.get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ZeroShotClassificationArgumentHandler(ArgumentHandler):
|
| 15 |
+
"""
|
| 16 |
+
Handles arguments for zero-shot for text classification by turning each possible label into an NLI
|
| 17 |
+
premise/hypothesis pair.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def _parse_labels(self, labels):
|
| 21 |
+
if isinstance(labels, str):
|
| 22 |
+
labels = [label.strip() for label in labels.split(",") if label.strip()]
|
| 23 |
+
return labels
|
| 24 |
+
|
| 25 |
+
def __call__(self, sequences, labels, hypothesis_template):
|
| 26 |
+
if len(labels) == 0 or len(sequences) == 0:
|
| 27 |
+
raise ValueError("You must include at least one label and at least one sequence.")
|
| 28 |
+
if hypothesis_template.format(labels[0]) == hypothesis_template:
|
| 29 |
+
raise ValueError(
|
| 30 |
+
(
|
| 31 |
+
'The provided hypothesis_template "{}" was not able to be formatted with the target labels. '
|
| 32 |
+
"Make sure the passed template includes formatting syntax such as {{}} where the label should go."
|
| 33 |
+
).format(hypothesis_template)
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
if isinstance(sequences, str):
|
| 37 |
+
sequences = [sequences]
|
| 38 |
+
|
| 39 |
+
sequence_pairs = []
|
| 40 |
+
for sequence in sequences:
|
| 41 |
+
sequence_pairs.extend([[sequence, hypothesis_template.format(label)] for label in labels])
|
| 42 |
+
|
| 43 |
+
return sequence_pairs, sequences
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
|
| 47 |
+
class ZeroShotClassificationPipeline(ChunkPipeline):
|
| 48 |
+
"""
|
| 49 |
+
NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification` trained on NLI (natural
|
| 50 |
+
language inference) tasks. Equivalent of `text-classification` pipelines, but these models don't require a
|
| 51 |
+
hardcoded number of potential classes, they can be chosen at runtime. It usually means it's slower but it is
|
| 52 |
+
**much** more flexible.
|
| 53 |
+
|
| 54 |
+
Any combination of sequences and labels can be passed and each combination will be posed as a premise/hypothesis
|
| 55 |
+
pair and passed to the pretrained model. Then, the logit for *entailment* is taken as the logit for the candidate
|
| 56 |
+
label being valid. Any NLI model can be used, but the id of the *entailment* label must be included in the model
|
| 57 |
+
config's :attr:*~transformers.PretrainedConfig.label2id*.
|
| 58 |
+
|
| 59 |
+
Example:
|
| 60 |
+
|
| 61 |
+
```python
|
| 62 |
+
>>> from transformers import pipeline
|
| 63 |
+
|
| 64 |
+
>>> oracle = pipeline(model="facebook/bart-large-mnli")
|
| 65 |
+
>>> oracle(
|
| 66 |
+
... "I have a problem with my iphone that needs to be resolved asap!!",
|
| 67 |
+
... candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
|
| 68 |
+
... )
|
| 69 |
+
{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}
|
| 70 |
+
|
| 71 |
+
>>> oracle(
|
| 72 |
+
... "I have a problem with my iphone that needs to be resolved asap!!",
|
| 73 |
+
... candidate_labels=["english", "german"],
|
| 74 |
+
... )
|
| 75 |
+
{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['english', 'german'], 'scores': [0.814, 0.186]}
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
| 79 |
+
|
| 80 |
+
This NLI pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 81 |
+
`"zero-shot-classification"`.
|
| 82 |
+
|
| 83 |
+
The models that this pipeline can use are models that have been fine-tuned on an NLI task. See the up-to-date list
|
| 84 |
+
of available models on [huggingface.co/models](https://huggingface.co/models?search=nli).
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
def __init__(self, args_parser=ZeroShotClassificationArgumentHandler(), *args, **kwargs):
|
| 88 |
+
self._args_parser = args_parser
|
| 89 |
+
super().__init__(*args, **kwargs)
|
| 90 |
+
if self.entailment_id == -1:
|
| 91 |
+
logger.warning(
|
| 92 |
+
"Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to "
|
| 93 |
+
"-1. Define a descriptive label2id mapping in the model config to ensure correct outputs."
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def entailment_id(self):
|
| 98 |
+
for label, ind in self.model.config.label2id.items():
|
| 99 |
+
if label.lower().startswith("entail"):
|
| 100 |
+
return ind
|
| 101 |
+
return -1
|
| 102 |
+
|
| 103 |
+
def _parse_and_tokenize(
|
| 104 |
+
self, sequence_pairs, padding=True, add_special_tokens=True, truncation=TruncationStrategy.ONLY_FIRST, **kwargs
|
| 105 |
+
):
|
| 106 |
+
"""
|
| 107 |
+
Parse arguments and tokenize only_first so that hypothesis (label) is not truncated
|
| 108 |
+
"""
|
| 109 |
+
return_tensors = self.framework
|
| 110 |
+
if self.tokenizer.pad_token is None:
|
| 111 |
+
# Override for tokenizers not supporting padding
|
| 112 |
+
logger.error(
|
| 113 |
+
"Tokenizer was not supporting padding necessary for zero-shot, attempting to use "
|
| 114 |
+
" `pad_token=eos_token`"
|
| 115 |
+
)
|
| 116 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 117 |
+
try:
|
| 118 |
+
inputs = self.tokenizer(
|
| 119 |
+
sequence_pairs,
|
| 120 |
+
add_special_tokens=add_special_tokens,
|
| 121 |
+
return_tensors=return_tensors,
|
| 122 |
+
padding=padding,
|
| 123 |
+
truncation=truncation,
|
| 124 |
+
)
|
| 125 |
+
except Exception as e:
|
| 126 |
+
if "too short" in str(e):
|
| 127 |
+
# tokenizers might yell that we want to truncate
|
| 128 |
+
# to a value that is not even reached by the input.
|
| 129 |
+
# In that case we don't want to truncate.
|
| 130 |
+
# It seems there's not a really better way to catch that
|
| 131 |
+
# exception.
|
| 132 |
+
|
| 133 |
+
inputs = self.tokenizer(
|
| 134 |
+
sequence_pairs,
|
| 135 |
+
add_special_tokens=add_special_tokens,
|
| 136 |
+
return_tensors=return_tensors,
|
| 137 |
+
padding=padding,
|
| 138 |
+
truncation=TruncationStrategy.DO_NOT_TRUNCATE,
|
| 139 |
+
)
|
| 140 |
+
else:
|
| 141 |
+
raise e
|
| 142 |
+
|
| 143 |
+
return inputs
|
| 144 |
+
|
| 145 |
+
def _sanitize_parameters(self, **kwargs):
|
| 146 |
+
if kwargs.get("multi_class", None) is not None:
|
| 147 |
+
kwargs["multi_label"] = kwargs["multi_class"]
|
| 148 |
+
logger.warning(
|
| 149 |
+
"The `multi_class` argument has been deprecated and renamed to `multi_label`. "
|
| 150 |
+
"`multi_class` will be removed in a future version of Transformers."
|
| 151 |
+
)
|
| 152 |
+
preprocess_params = {}
|
| 153 |
+
if "candidate_labels" in kwargs:
|
| 154 |
+
preprocess_params["candidate_labels"] = self._args_parser._parse_labels(kwargs["candidate_labels"])
|
| 155 |
+
if "hypothesis_template" in kwargs:
|
| 156 |
+
preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"]
|
| 157 |
+
|
| 158 |
+
postprocess_params = {}
|
| 159 |
+
if "multi_label" in kwargs:
|
| 160 |
+
postprocess_params["multi_label"] = kwargs["multi_label"]
|
| 161 |
+
return preprocess_params, {}, postprocess_params
|
| 162 |
+
|
| 163 |
+
def __call__(
|
| 164 |
+
self,
|
| 165 |
+
sequences: Union[str, List[str]],
|
| 166 |
+
*args,
|
| 167 |
+
**kwargs,
|
| 168 |
+
):
|
| 169 |
+
"""
|
| 170 |
+
Classify the sequence(s) given as inputs. See the [`ZeroShotClassificationPipeline`] documentation for more
|
| 171 |
+
information.
|
| 172 |
+
|
| 173 |
+
Args:
|
| 174 |
+
sequences (`str` or `List[str]`):
|
| 175 |
+
The sequence(s) to classify, will be truncated if the model input is too large.
|
| 176 |
+
candidate_labels (`str` or `List[str]`):
|
| 177 |
+
The set of possible class labels to classify each sequence into. Can be a single label, a string of
|
| 178 |
+
comma-separated labels, or a list of labels.
|
| 179 |
+
hypothesis_template (`str`, *optional*, defaults to `"This example is {}."`):
|
| 180 |
+
The template used to turn each label into an NLI-style hypothesis. This template must include a {} or
|
| 181 |
+
similar syntax for the candidate label to be inserted into the template. For example, the default
|
| 182 |
+
template is `"This example is {}."` With the candidate label `"sports"`, this would be fed into the
|
| 183 |
+
model like `"<cls> sequence to classify <sep> This example is sports . <sep>"`. The default template
|
| 184 |
+
works well in many cases, but it may be worthwhile to experiment with different templates depending on
|
| 185 |
+
the task setting.
|
| 186 |
+
multi_label (`bool`, *optional*, defaults to `False`):
|
| 187 |
+
Whether or not multiple candidate labels can be true. If `False`, the scores are normalized such that
|
| 188 |
+
the sum of the label likelihoods for each sequence is 1. If `True`, the labels are considered
|
| 189 |
+
independent and probabilities are normalized for each candidate by doing a softmax of the entailment
|
| 190 |
+
score vs. the contradiction score.
|
| 191 |
+
|
| 192 |
+
Return:
|
| 193 |
+
A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys:
|
| 194 |
+
|
| 195 |
+
- **sequence** (`str`) -- The sequence for which this is the output.
|
| 196 |
+
- **labels** (`List[str]`) -- The labels sorted by order of likelihood.
|
| 197 |
+
- **scores** (`List[float]`) -- The probabilities for each of the labels.
|
| 198 |
+
"""
|
| 199 |
+
if len(args) == 0:
|
| 200 |
+
pass
|
| 201 |
+
elif len(args) == 1 and "candidate_labels" not in kwargs:
|
| 202 |
+
kwargs["candidate_labels"] = args[0]
|
| 203 |
+
else:
|
| 204 |
+
raise ValueError(f"Unable to understand extra arguments {args}")
|
| 205 |
+
|
| 206 |
+
return super().__call__(sequences, **kwargs)
|
| 207 |
+
|
| 208 |
+
def preprocess(self, inputs, candidate_labels=None, hypothesis_template="This example is {}."):
|
| 209 |
+
sequence_pairs, sequences = self._args_parser(inputs, candidate_labels, hypothesis_template)
|
| 210 |
+
|
| 211 |
+
for i, (candidate_label, sequence_pair) in enumerate(zip(candidate_labels, sequence_pairs)):
|
| 212 |
+
model_input = self._parse_and_tokenize([sequence_pair])
|
| 213 |
+
|
| 214 |
+
yield {
|
| 215 |
+
"candidate_label": candidate_label,
|
| 216 |
+
"sequence": sequences[0],
|
| 217 |
+
"is_last": i == len(candidate_labels) - 1,
|
| 218 |
+
**model_input,
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
def _forward(self, inputs):
|
| 222 |
+
candidate_label = inputs["candidate_label"]
|
| 223 |
+
sequence = inputs["sequence"]
|
| 224 |
+
model_inputs = {k: inputs[k] for k in self.tokenizer.model_input_names}
|
| 225 |
+
# `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported
|
| 226 |
+
model_forward = self.model.forward if self.framework == "pt" else self.model.call
|
| 227 |
+
if "use_cache" in inspect.signature(model_forward).parameters.keys():
|
| 228 |
+
model_inputs["use_cache"] = False
|
| 229 |
+
outputs = self.model(**model_inputs)
|
| 230 |
+
|
| 231 |
+
model_outputs = {
|
| 232 |
+
"candidate_label": candidate_label,
|
| 233 |
+
"sequence": sequence,
|
| 234 |
+
"is_last": inputs["is_last"],
|
| 235 |
+
**outputs,
|
| 236 |
+
}
|
| 237 |
+
return model_outputs
|
| 238 |
+
|
| 239 |
+
def postprocess(self, model_outputs, multi_label=False):
|
| 240 |
+
candidate_labels = [outputs["candidate_label"] for outputs in model_outputs]
|
| 241 |
+
sequences = [outputs["sequence"] for outputs in model_outputs]
|
| 242 |
+
if self.framework == "pt":
|
| 243 |
+
logits = np.concatenate([output["logits"].float().numpy() for output in model_outputs])
|
| 244 |
+
else:
|
| 245 |
+
logits = np.concatenate([output["logits"].numpy() for output in model_outputs])
|
| 246 |
+
N = logits.shape[0]
|
| 247 |
+
n = len(candidate_labels)
|
| 248 |
+
num_sequences = N // n
|
| 249 |
+
reshaped_outputs = logits.reshape((num_sequences, n, -1))
|
| 250 |
+
|
| 251 |
+
if multi_label or len(candidate_labels) == 1:
|
| 252 |
+
# softmax over the entailment vs. contradiction dim for each label independently
|
| 253 |
+
entailment_id = self.entailment_id
|
| 254 |
+
contradiction_id = -1 if entailment_id == 0 else 0
|
| 255 |
+
entail_contr_logits = reshaped_outputs[..., [contradiction_id, entailment_id]]
|
| 256 |
+
scores = np.exp(entail_contr_logits) / np.exp(entail_contr_logits).sum(-1, keepdims=True)
|
| 257 |
+
scores = scores[..., 1]
|
| 258 |
+
else:
|
| 259 |
+
# softmax the "entailment" logits over all candidate labels
|
| 260 |
+
entail_logits = reshaped_outputs[..., self.entailment_id]
|
| 261 |
+
scores = np.exp(entail_logits) / np.exp(entail_logits).sum(-1, keepdims=True)
|
| 262 |
+
|
| 263 |
+
top_inds = list(reversed(scores[0].argsort()))
|
| 264 |
+
return {
|
| 265 |
+
"sequence": sequences[0],
|
| 266 |
+
"labels": [candidate_labels[i] for i in top_inds],
|
| 267 |
+
"scores": scores[0, top_inds].tolist(),
|
| 268 |
+
}
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/zero_shot_image_classification.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from collections import UserDict
|
| 3 |
+
from typing import List, Union
|
| 4 |
+
|
| 5 |
+
from ..utils import (
|
| 6 |
+
add_end_docstrings,
|
| 7 |
+
is_tf_available,
|
| 8 |
+
is_torch_available,
|
| 9 |
+
is_vision_available,
|
| 10 |
+
logging,
|
| 11 |
+
requires_backends,
|
| 12 |
+
)
|
| 13 |
+
from .base import Pipeline, build_pipeline_init_args
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
if is_vision_available():
|
| 17 |
+
from PIL import Image
|
| 18 |
+
|
| 19 |
+
from ..image_utils import load_image
|
| 20 |
+
|
| 21 |
+
if is_torch_available():
|
| 22 |
+
import torch
|
| 23 |
+
|
| 24 |
+
from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
|
| 25 |
+
|
| 26 |
+
if is_tf_available():
|
| 27 |
+
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
|
| 28 |
+
from ..tf_utils import stable_softmax
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
|
| 34 |
+
class ZeroShotImageClassificationPipeline(Pipeline):
|
| 35 |
+
"""
|
| 36 |
+
Zero shot image classification pipeline using `CLIPModel`. This pipeline predicts the class of an image when you
|
| 37 |
+
provide an image and a set of `candidate_labels`.
|
| 38 |
+
|
| 39 |
+
Example:
|
| 40 |
+
|
| 41 |
+
```python
|
| 42 |
+
>>> from transformers import pipeline
|
| 43 |
+
|
| 44 |
+
>>> classifier = pipeline(model="google/siglip-so400m-patch14-384")
|
| 45 |
+
>>> classifier(
|
| 46 |
+
... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
|
| 47 |
+
... candidate_labels=["animals", "humans", "landscape"],
|
| 48 |
+
... )
|
| 49 |
+
[{'score': 0.965, 'label': 'animals'}, {'score': 0.03, 'label': 'humans'}, {'score': 0.005, 'label': 'landscape'}]
|
| 50 |
+
|
| 51 |
+
>>> classifier(
|
| 52 |
+
... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
|
| 53 |
+
... candidate_labels=["black and white", "photorealist", "painting"],
|
| 54 |
+
... )
|
| 55 |
+
[{'score': 0.996, 'label': 'black and white'}, {'score': 0.003, 'label': 'photorealist'}, {'score': 0.0, 'label': 'painting'}]
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
| 59 |
+
|
| 60 |
+
This image classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 61 |
+
`"zero-shot-image-classification"`.
|
| 62 |
+
|
| 63 |
+
See the list of available models on
|
| 64 |
+
[huggingface.co/models](https://huggingface.co/models?filter=zero-shot-image-classification).
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def __init__(self, **kwargs):
|
| 68 |
+
super().__init__(**kwargs)
|
| 69 |
+
|
| 70 |
+
requires_backends(self, "vision")
|
| 71 |
+
self.check_model_type(
|
| 72 |
+
TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
|
| 73 |
+
if self.framework == "tf"
|
| 74 |
+
else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
def __call__(self, image: Union[str, List[str], "Image", List["Image"]] = None, **kwargs):
|
| 78 |
+
"""
|
| 79 |
+
Assign labels to the image(s) passed as inputs.
|
| 80 |
+
|
| 81 |
+
Args:
|
| 82 |
+
image (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
|
| 83 |
+
The pipeline handles three types of images:
|
| 84 |
+
|
| 85 |
+
- A string containing a http link pointing to an image
|
| 86 |
+
- A string containing a local path to an image
|
| 87 |
+
- An image loaded in PIL directly
|
| 88 |
+
|
| 89 |
+
candidate_labels (`List[str]`):
|
| 90 |
+
The candidate labels for this image. They will be formatted using *hypothesis_template*.
|
| 91 |
+
|
| 92 |
+
hypothesis_template (`str`, *optional*, defaults to `"This is a photo of {}"`):
|
| 93 |
+
The format used in conjunction with *candidate_labels* to attempt the image classification by
|
| 94 |
+
replacing the placeholder with the candidate_labels. Pass "{}" if *candidate_labels* are
|
| 95 |
+
already formatted.
|
| 96 |
+
|
| 97 |
+
timeout (`float`, *optional*, defaults to None):
|
| 98 |
+
The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
|
| 99 |
+
the call may block forever.
|
| 100 |
+
|
| 101 |
+
Return:
|
| 102 |
+
A list of dictionaries containing one entry per proposed label. Each dictionary contains the
|
| 103 |
+
following keys:
|
| 104 |
+
- **label** (`str`) -- One of the suggested *candidate_labels*.
|
| 105 |
+
- **score** (`float`) -- The score attributed by the model to that label. It is a value between
|
| 106 |
+
0 and 1, computed as the `softmax` of `logits_per_image`.
|
| 107 |
+
"""
|
| 108 |
+
# After deprecation of this is completed, remove the default `None` value for `image`
|
| 109 |
+
if "images" in kwargs:
|
| 110 |
+
image = kwargs.pop("images")
|
| 111 |
+
if image is None:
|
| 112 |
+
raise ValueError("Cannot call the zero-shot-image-classification pipeline without an images argument!")
|
| 113 |
+
return super().__call__(image, **kwargs)
|
| 114 |
+
|
| 115 |
+
def _sanitize_parameters(self, tokenizer_kwargs=None, **kwargs):
|
| 116 |
+
preprocess_params = {}
|
| 117 |
+
if "candidate_labels" in kwargs:
|
| 118 |
+
preprocess_params["candidate_labels"] = kwargs["candidate_labels"]
|
| 119 |
+
if "timeout" in kwargs:
|
| 120 |
+
preprocess_params["timeout"] = kwargs["timeout"]
|
| 121 |
+
if "hypothesis_template" in kwargs:
|
| 122 |
+
preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"]
|
| 123 |
+
if tokenizer_kwargs is not None:
|
| 124 |
+
warnings.warn(
|
| 125 |
+
"The `tokenizer_kwargs` argument is deprecated and will be removed in version 5 of Transformers",
|
| 126 |
+
FutureWarning,
|
| 127 |
+
)
|
| 128 |
+
preprocess_params["tokenizer_kwargs"] = tokenizer_kwargs
|
| 129 |
+
|
| 130 |
+
return preprocess_params, {}, {}
|
| 131 |
+
|
| 132 |
+
def preprocess(
|
| 133 |
+
self,
|
| 134 |
+
image,
|
| 135 |
+
candidate_labels=None,
|
| 136 |
+
hypothesis_template="This is a photo of {}.",
|
| 137 |
+
timeout=None,
|
| 138 |
+
tokenizer_kwargs=None,
|
| 139 |
+
):
|
| 140 |
+
if tokenizer_kwargs is None:
|
| 141 |
+
tokenizer_kwargs = {}
|
| 142 |
+
image = load_image(image, timeout=timeout)
|
| 143 |
+
inputs = self.image_processor(images=[image], return_tensors=self.framework)
|
| 144 |
+
if self.framework == "pt":
|
| 145 |
+
inputs = inputs.to(self.torch_dtype)
|
| 146 |
+
inputs["candidate_labels"] = candidate_labels
|
| 147 |
+
sequences = [hypothesis_template.format(x) for x in candidate_labels]
|
| 148 |
+
padding = "max_length" if self.model.config.model_type == "siglip" else True
|
| 149 |
+
text_inputs = self.tokenizer(sequences, return_tensors=self.framework, padding=padding, **tokenizer_kwargs)
|
| 150 |
+
inputs["text_inputs"] = [text_inputs]
|
| 151 |
+
return inputs
|
| 152 |
+
|
| 153 |
+
def _forward(self, model_inputs):
|
| 154 |
+
candidate_labels = model_inputs.pop("candidate_labels")
|
| 155 |
+
text_inputs = model_inputs.pop("text_inputs")
|
| 156 |
+
if isinstance(text_inputs[0], UserDict):
|
| 157 |
+
text_inputs = text_inputs[0]
|
| 158 |
+
else:
|
| 159 |
+
# Batching case.
|
| 160 |
+
text_inputs = text_inputs[0][0]
|
| 161 |
+
|
| 162 |
+
outputs = self.model(**text_inputs, **model_inputs)
|
| 163 |
+
|
| 164 |
+
model_outputs = {
|
| 165 |
+
"candidate_labels": candidate_labels,
|
| 166 |
+
"logits": outputs.logits_per_image,
|
| 167 |
+
}
|
| 168 |
+
return model_outputs
|
| 169 |
+
|
| 170 |
+
def postprocess(self, model_outputs):
|
| 171 |
+
candidate_labels = model_outputs.pop("candidate_labels")
|
| 172 |
+
logits = model_outputs["logits"][0]
|
| 173 |
+
if self.framework == "pt" and self.model.config.model_type == "siglip":
|
| 174 |
+
probs = torch.sigmoid(logits).squeeze(-1)
|
| 175 |
+
scores = probs.tolist()
|
| 176 |
+
if not isinstance(scores, list):
|
| 177 |
+
scores = [scores]
|
| 178 |
+
elif self.framework == "pt":
|
| 179 |
+
probs = logits.softmax(dim=-1).squeeze(-1)
|
| 180 |
+
scores = probs.tolist()
|
| 181 |
+
if not isinstance(scores, list):
|
| 182 |
+
scores = [scores]
|
| 183 |
+
elif self.framework == "tf":
|
| 184 |
+
probs = stable_softmax(logits, axis=-1)
|
| 185 |
+
scores = probs.numpy().tolist()
|
| 186 |
+
else:
|
| 187 |
+
raise ValueError(f"Unsupported framework: {self.framework}")
|
| 188 |
+
|
| 189 |
+
result = [
|
| 190 |
+
{"score": score, "label": candidate_label}
|
| 191 |
+
for score, candidate_label in sorted(zip(scores, candidate_labels), key=lambda x: -x[0])
|
| 192 |
+
]
|
| 193 |
+
return result
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pipelines/zero_shot_object_detection.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Union
|
| 2 |
+
|
| 3 |
+
from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
|
| 4 |
+
from .base import ChunkPipeline, build_pipeline_init_args
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
if is_vision_available():
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
from ..image_utils import load_image, valid_images
|
| 11 |
+
|
| 12 |
+
if is_torch_available():
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
from transformers.modeling_outputs import BaseModelOutput
|
| 16 |
+
|
| 17 |
+
from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES
|
| 18 |
+
|
| 19 |
+
logger = logging.get_logger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
|
| 23 |
+
class ZeroShotObjectDetectionPipeline(ChunkPipeline):
|
| 24 |
+
"""
|
| 25 |
+
Zero shot object detection pipeline using `OwlViTForObjectDetection`. This pipeline predicts bounding boxes of
|
| 26 |
+
objects when you provide an image and a set of `candidate_labels`.
|
| 27 |
+
|
| 28 |
+
Example:
|
| 29 |
+
|
| 30 |
+
```python
|
| 31 |
+
>>> from transformers import pipeline
|
| 32 |
+
|
| 33 |
+
>>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection")
|
| 34 |
+
>>> detector(
|
| 35 |
+
... "http://images.cocodataset.org/val2017/000000039769.jpg",
|
| 36 |
+
... candidate_labels=["cat", "couch"],
|
| 37 |
+
... )
|
| 38 |
+
[{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]
|
| 39 |
+
|
| 40 |
+
>>> detector(
|
| 41 |
+
... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
|
| 42 |
+
... candidate_labels=["head", "bird"],
|
| 43 |
+
... )
|
| 44 |
+
[{'score': 0.119, 'label': 'bird', 'box': {'xmin': 71, 'ymin': 170, 'xmax': 410, 'ymax': 508}}]
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
| 48 |
+
|
| 49 |
+
This object detection pipeline can currently be loaded from [`pipeline`] using the following task identifier:
|
| 50 |
+
`"zero-shot-object-detection"`.
|
| 51 |
+
|
| 52 |
+
See the list of available models on
|
| 53 |
+
[huggingface.co/models](https://huggingface.co/models?filter=zero-shot-object-detection).
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
def __init__(self, **kwargs):
|
| 57 |
+
super().__init__(**kwargs)
|
| 58 |
+
|
| 59 |
+
if self.framework == "tf":
|
| 60 |
+
raise ValueError(f"The {self.__class__} is only available in PyTorch.")
|
| 61 |
+
|
| 62 |
+
requires_backends(self, "vision")
|
| 63 |
+
self.check_model_type(MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES)
|
| 64 |
+
|
| 65 |
+
def __call__(
|
| 66 |
+
self,
|
| 67 |
+
image: Union[str, "Image.Image", List[Dict[str, Any]]],
|
| 68 |
+
candidate_labels: Union[str, List[str]] = None,
|
| 69 |
+
**kwargs,
|
| 70 |
+
):
|
| 71 |
+
"""
|
| 72 |
+
Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
image (`str`, `PIL.Image` or `List[Dict[str, Any]]`):
|
| 76 |
+
The pipeline handles three types of images:
|
| 77 |
+
|
| 78 |
+
- A string containing an http url pointing to an image
|
| 79 |
+
- A string containing a local path to an image
|
| 80 |
+
- An image loaded in PIL directly
|
| 81 |
+
|
| 82 |
+
You can use this parameter to send directly a list of images, or a dataset or a generator like so:
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
>>> from transformers import pipeline
|
| 86 |
+
|
| 87 |
+
>>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection")
|
| 88 |
+
>>> detector(
|
| 89 |
+
... [
|
| 90 |
+
... {
|
| 91 |
+
... "image": "http://images.cocodataset.org/val2017/000000039769.jpg",
|
| 92 |
+
... "candidate_labels": ["cat", "couch"],
|
| 93 |
+
... },
|
| 94 |
+
... {
|
| 95 |
+
... "image": "http://images.cocodataset.org/val2017/000000039769.jpg",
|
| 96 |
+
... "candidate_labels": ["cat", "couch"],
|
| 97 |
+
... },
|
| 98 |
+
... ]
|
| 99 |
+
... )
|
| 100 |
+
[[{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.25, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}], [{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]]
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
candidate_labels (`str` or `List[str]` or `List[List[str]]`):
|
| 105 |
+
What the model should recognize in the image.
|
| 106 |
+
|
| 107 |
+
threshold (`float`, *optional*, defaults to 0.1):
|
| 108 |
+
The probability necessary to make a prediction.
|
| 109 |
+
|
| 110 |
+
top_k (`int`, *optional*, defaults to None):
|
| 111 |
+
The number of top predictions that will be returned by the pipeline. If the provided number is `None`
|
| 112 |
+
or higher than the number of predictions available, it will default to the number of predictions.
|
| 113 |
+
|
| 114 |
+
timeout (`float`, *optional*, defaults to None):
|
| 115 |
+
The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
|
| 116 |
+
the call may block forever.
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
Return:
|
| 120 |
+
A list of lists containing prediction results, one list per input image. Each list contains dictionaries
|
| 121 |
+
with the following keys:
|
| 122 |
+
|
| 123 |
+
- **label** (`str`) -- Text query corresponding to the found object.
|
| 124 |
+
- **score** (`float`) -- Score corresponding to the object (between 0 and 1).
|
| 125 |
+
- **box** (`Dict[str,int]`) -- Bounding box of the detected object in image's original size. It is a
|
| 126 |
+
dictionary with `x_min`, `x_max`, `y_min`, `y_max` keys.
|
| 127 |
+
"""
|
| 128 |
+
if "text_queries" in kwargs:
|
| 129 |
+
candidate_labels = kwargs.pop("text_queries")
|
| 130 |
+
|
| 131 |
+
if isinstance(image, (str, Image.Image)):
|
| 132 |
+
inputs = {"image": image, "candidate_labels": candidate_labels}
|
| 133 |
+
elif isinstance(image, (list, tuple)) and valid_images(image):
|
| 134 |
+
return list(
|
| 135 |
+
super().__call__(
|
| 136 |
+
({"image": img, "candidate_labels": labels} for img, labels in zip(image, candidate_labels)),
|
| 137 |
+
**kwargs,
|
| 138 |
+
)
|
| 139 |
+
)
|
| 140 |
+
else:
|
| 141 |
+
"""
|
| 142 |
+
Supports the following format
|
| 143 |
+
- {"image": image, "candidate_labels": candidate_labels}
|
| 144 |
+
- [{"image": image, "candidate_labels": candidate_labels}]
|
| 145 |
+
- Generator and datasets
|
| 146 |
+
This is a common pattern in other multimodal pipelines, so we support it here as well.
|
| 147 |
+
"""
|
| 148 |
+
inputs = image
|
| 149 |
+
|
| 150 |
+
results = super().__call__(inputs, **kwargs)
|
| 151 |
+
return results
|
| 152 |
+
|
| 153 |
+
def _sanitize_parameters(self, **kwargs):
|
| 154 |
+
preprocess_params = {}
|
| 155 |
+
if "timeout" in kwargs:
|
| 156 |
+
preprocess_params["timeout"] = kwargs["timeout"]
|
| 157 |
+
postprocess_params = {}
|
| 158 |
+
if "threshold" in kwargs:
|
| 159 |
+
postprocess_params["threshold"] = kwargs["threshold"]
|
| 160 |
+
if "top_k" in kwargs:
|
| 161 |
+
postprocess_params["top_k"] = kwargs["top_k"]
|
| 162 |
+
return preprocess_params, {}, postprocess_params
|
| 163 |
+
|
| 164 |
+
def preprocess(self, inputs, timeout=None):
|
| 165 |
+
image = load_image(inputs["image"], timeout=timeout)
|
| 166 |
+
candidate_labels = inputs["candidate_labels"]
|
| 167 |
+
if isinstance(candidate_labels, str):
|
| 168 |
+
candidate_labels = candidate_labels.split(",")
|
| 169 |
+
|
| 170 |
+
target_size = torch.tensor([[image.height, image.width]], dtype=torch.int32)
|
| 171 |
+
for i, candidate_label in enumerate(candidate_labels):
|
| 172 |
+
text_inputs = self.tokenizer(candidate_label, return_tensors=self.framework)
|
| 173 |
+
image_features = self.image_processor(image, return_tensors=self.framework)
|
| 174 |
+
if self.framework == "pt":
|
| 175 |
+
image_features = image_features.to(self.torch_dtype)
|
| 176 |
+
yield {
|
| 177 |
+
"is_last": i == len(candidate_labels) - 1,
|
| 178 |
+
"target_size": target_size,
|
| 179 |
+
"candidate_label": candidate_label,
|
| 180 |
+
**text_inputs,
|
| 181 |
+
**image_features,
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
def _forward(self, model_inputs):
|
| 185 |
+
target_size = model_inputs.pop("target_size")
|
| 186 |
+
candidate_label = model_inputs.pop("candidate_label")
|
| 187 |
+
is_last = model_inputs.pop("is_last")
|
| 188 |
+
|
| 189 |
+
outputs = self.model(**model_inputs)
|
| 190 |
+
|
| 191 |
+
model_outputs = {"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs}
|
| 192 |
+
return model_outputs
|
| 193 |
+
|
| 194 |
+
def postprocess(self, model_outputs, threshold=0.1, top_k=None):
|
| 195 |
+
results = []
|
| 196 |
+
for model_output in model_outputs:
|
| 197 |
+
label = model_output["candidate_label"]
|
| 198 |
+
model_output = BaseModelOutput(model_output)
|
| 199 |
+
outputs = self.image_processor.post_process_object_detection(
|
| 200 |
+
outputs=model_output, threshold=threshold, target_sizes=model_output["target_size"]
|
| 201 |
+
)[0]
|
| 202 |
+
|
| 203 |
+
for index in outputs["scores"].nonzero():
|
| 204 |
+
score = outputs["scores"][index].item()
|
| 205 |
+
box = self._get_bounding_box(outputs["boxes"][index][0])
|
| 206 |
+
|
| 207 |
+
result = {"score": score, "label": label, "box": box}
|
| 208 |
+
results.append(result)
|
| 209 |
+
|
| 210 |
+
results = sorted(results, key=lambda x: x["score"], reverse=True)
|
| 211 |
+
if top_k:
|
| 212 |
+
results = results[:top_k]
|
| 213 |
+
|
| 214 |
+
return results
|
| 215 |
+
|
| 216 |
+
def _get_bounding_box(self, box: "torch.Tensor") -> Dict[str, int]:
|
| 217 |
+
"""
|
| 218 |
+
Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... }
|
| 219 |
+
|
| 220 |
+
Args:
|
| 221 |
+
box (`torch.Tensor`): Tensor containing the coordinates in corners format.
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
bbox (`Dict[str, int]`): Dict containing the coordinates in corners format.
|
| 225 |
+
"""
|
| 226 |
+
if self.framework != "pt":
|
| 227 |
+
raise ValueError("The ZeroShotObjectDetectionPipeline is only available in PyTorch.")
|
| 228 |
+
xmin, ymin, xmax, ymax = box.int().tolist()
|
| 229 |
+
bbox = {
|
| 230 |
+
"xmin": xmin,
|
| 231 |
+
"ymin": ymin,
|
| 232 |
+
"xmax": xmax,
|
| 233 |
+
"ymax": ymax,
|
| 234 |
+
}
|
| 235 |
+
return bbox
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/processing_utils.py
ADDED
|
@@ -0,0 +1,1212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 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 |
+
"""
|
| 16 |
+
Processing saving/loading class for common processors.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import copy
|
| 20 |
+
import inspect
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import sys
|
| 24 |
+
import typing
|
| 25 |
+
import warnings
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
from typing import Any, Dict, List, Optional, Tuple, TypedDict, Union
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import typing_extensions
|
| 31 |
+
|
| 32 |
+
from .dynamic_module_utils import custom_object_save
|
| 33 |
+
from .image_utils import ChannelDimension, is_valid_image, is_vision_available
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if is_vision_available():
|
| 37 |
+
from .image_utils import PILImageResampling
|
| 38 |
+
|
| 39 |
+
from .tokenization_utils_base import (
|
| 40 |
+
PaddingStrategy,
|
| 41 |
+
PreTokenizedInput,
|
| 42 |
+
PreTrainedTokenizerBase,
|
| 43 |
+
TextInput,
|
| 44 |
+
TruncationStrategy,
|
| 45 |
+
)
|
| 46 |
+
from .utils import (
|
| 47 |
+
PROCESSOR_NAME,
|
| 48 |
+
PushToHubMixin,
|
| 49 |
+
TensorType,
|
| 50 |
+
add_model_info_to_auto_map,
|
| 51 |
+
add_model_info_to_custom_pipelines,
|
| 52 |
+
cached_file,
|
| 53 |
+
copy_func,
|
| 54 |
+
direct_transformers_import,
|
| 55 |
+
download_url,
|
| 56 |
+
is_offline_mode,
|
| 57 |
+
is_remote_url,
|
| 58 |
+
logging,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
logger = logging.get_logger(__name__)
|
| 63 |
+
|
| 64 |
+
# Dynamically import the Transformers module to grab the attribute classes of the processor form their names.
|
| 65 |
+
transformers_module = direct_transformers_import(Path(__file__).parent)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
AUTO_TO_BASE_CLASS_MAPPING = {
|
| 69 |
+
"AutoTokenizer": "PreTrainedTokenizerBase",
|
| 70 |
+
"AutoFeatureExtractor": "FeatureExtractionMixin",
|
| 71 |
+
"AutoImageProcessor": "ImageProcessingMixin",
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
if sys.version_info >= (3, 11):
|
| 75 |
+
Unpack = typing.Unpack
|
| 76 |
+
else:
|
| 77 |
+
Unpack = typing_extensions.Unpack
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class TextKwargs(TypedDict, total=False):
|
| 81 |
+
"""
|
| 82 |
+
Keyword arguments for text processing. For extended documentation, check out tokenization_utils_base methods and
|
| 83 |
+
docstrings associated.
|
| 84 |
+
|
| 85 |
+
Attributes:
|
| 86 |
+
add_special_tokens (`bool`, *optional*)
|
| 87 |
+
Whether or not to add special tokens when encoding the sequences.
|
| 88 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*)
|
| 89 |
+
Activates and controls padding.
|
| 90 |
+
truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*):
|
| 91 |
+
Activates and controls truncation.
|
| 92 |
+
max_length (`int`, *optional*):
|
| 93 |
+
Controls the maximum length to use by one of the truncation/padding parameters.
|
| 94 |
+
stride (`int`, *optional*):
|
| 95 |
+
If set, the overflowing tokens will contain some tokens from the end of the truncated sequence.
|
| 96 |
+
is_split_into_words (`bool`, *optional*):
|
| 97 |
+
Whether or not the input is already pre-tokenized.
|
| 98 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 99 |
+
If set, will pad the sequence to a multiple of the provided value.
|
| 100 |
+
return_token_type_ids (`bool`, *optional*):
|
| 101 |
+
Whether to return token type IDs.
|
| 102 |
+
return_attention_mask (`bool`, *optional*):
|
| 103 |
+
Whether to return the attention mask.
|
| 104 |
+
return_overflowing_tokens (`bool`, *optional*):
|
| 105 |
+
Whether or not to return overflowing token sequences.
|
| 106 |
+
return_special_tokens_mask (`bool`, *optional*):
|
| 107 |
+
Whether or not to return special tokens mask information.
|
| 108 |
+
return_offsets_mapping (`bool`, *optional*):
|
| 109 |
+
Whether or not to return `(char_start, char_end)` for each token.
|
| 110 |
+
return_length (`bool`, *optional*):
|
| 111 |
+
Whether or not to return the lengths of the encoded inputs.
|
| 112 |
+
verbose (`bool`, *optional*):
|
| 113 |
+
Whether or not to print more information and warnings.
|
| 114 |
+
padding_side (`str`, *optional*):
|
| 115 |
+
The side on which padding will be applied.
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
text_pair: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]]
|
| 119 |
+
text_target: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]
|
| 120 |
+
text_pair_target: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]]
|
| 121 |
+
add_special_tokens: Optional[bool]
|
| 122 |
+
padding: Union[bool, str, PaddingStrategy]
|
| 123 |
+
truncation: Union[bool, str, TruncationStrategy]
|
| 124 |
+
max_length: Optional[int]
|
| 125 |
+
stride: Optional[int]
|
| 126 |
+
is_split_into_words: Optional[bool]
|
| 127 |
+
pad_to_multiple_of: Optional[int]
|
| 128 |
+
return_token_type_ids: Optional[bool]
|
| 129 |
+
return_attention_mask: Optional[bool]
|
| 130 |
+
return_overflowing_tokens: Optional[bool]
|
| 131 |
+
return_special_tokens_mask: Optional[bool]
|
| 132 |
+
return_offsets_mapping: Optional[bool]
|
| 133 |
+
return_length: Optional[bool]
|
| 134 |
+
verbose: Optional[bool]
|
| 135 |
+
padding_side: Optional[str]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class ImagesKwargs(TypedDict, total=False):
|
| 139 |
+
"""
|
| 140 |
+
Keyword arguments for image processing. For extended documentation, check the appropriate ImageProcessor
|
| 141 |
+
class methods and docstrings.
|
| 142 |
+
|
| 143 |
+
Attributes:
|
| 144 |
+
do_resize (`bool`, *optional*):
|
| 145 |
+
Whether to resize the image.
|
| 146 |
+
size (`Dict[str, int]`, *optional*):
|
| 147 |
+
Resize the shorter side of the input to `size["shortest_edge"]`.
|
| 148 |
+
size_divisor (`int`, *optional*):
|
| 149 |
+
The size by which to make sure both the height and width can be divided.
|
| 150 |
+
crop_size (`Dict[str, int]`, *optional*):
|
| 151 |
+
Desired output size when applying center-cropping.
|
| 152 |
+
resample (`PILImageResampling`, *optional*):
|
| 153 |
+
Resampling filter to use if resizing the image.
|
| 154 |
+
do_rescale (`bool`, *optional*):
|
| 155 |
+
Whether to rescale the image by the specified scale `rescale_factor`.
|
| 156 |
+
rescale_factor (`int` or `float`, *optional*):
|
| 157 |
+
Scale factor to use if rescaling the image.
|
| 158 |
+
do_normalize (`bool`, *optional*):
|
| 159 |
+
Whether to normalize the image.
|
| 160 |
+
image_mean (`float` or `List[float]`, *optional*):
|
| 161 |
+
Mean to use if normalizing the image.
|
| 162 |
+
image_std (`float` or `List[float]`, *optional*):
|
| 163 |
+
Standard deviation to use if normalizing the image.
|
| 164 |
+
do_pad (`bool`, *optional*):
|
| 165 |
+
Whether to pad the image to the `(max_height, max_width)` of the images in the batch.
|
| 166 |
+
pad_size (`Dict[str, int]`, *optional*):
|
| 167 |
+
The size `{"height": int, "width" int}` to pad the images to.
|
| 168 |
+
do_center_crop (`bool`, *optional*):
|
| 169 |
+
Whether to center crop the image.
|
| 170 |
+
data_format (`ChannelDimension` or `str`, *optional*):
|
| 171 |
+
The channel dimension format for the output image.
|
| 172 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 173 |
+
The channel dimension format for the input image.
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
do_resize: Optional[bool]
|
| 177 |
+
size: Optional[Dict[str, int]]
|
| 178 |
+
size_divisor: Optional[int]
|
| 179 |
+
crop_size: Optional[Dict[str, int]]
|
| 180 |
+
resample: Optional[Union["PILImageResampling", int]]
|
| 181 |
+
do_rescale: Optional[bool]
|
| 182 |
+
rescale_factor: Optional[float]
|
| 183 |
+
do_normalize: Optional[bool]
|
| 184 |
+
image_mean: Optional[Union[float, List[float]]]
|
| 185 |
+
image_std: Optional[Union[float, List[float]]]
|
| 186 |
+
do_pad: Optional[bool]
|
| 187 |
+
pad_size: Optional[Dict[str, int]]
|
| 188 |
+
do_center_crop: Optional[bool]
|
| 189 |
+
data_format: Optional[ChannelDimension]
|
| 190 |
+
input_data_format: Optional[Union[str, ChannelDimension]]
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class VideosKwargs(TypedDict, total=False):
|
| 194 |
+
"""
|
| 195 |
+
Keyword arguments for video processing.
|
| 196 |
+
|
| 197 |
+
Attributes:
|
| 198 |
+
do_resize (`bool`):
|
| 199 |
+
Whether to resize the image.
|
| 200 |
+
size (`Dict[str, int]`, *optional*):
|
| 201 |
+
Resize the shorter side of the input to `size["shortest_edge"]`.
|
| 202 |
+
size_divisor (`int`, *optional*):
|
| 203 |
+
The size by which to make sure both the height and width can be divided.
|
| 204 |
+
resample (`PILImageResampling`, *optional*):
|
| 205 |
+
Resampling filter to use if resizing the image.
|
| 206 |
+
do_rescale (`bool`, *optional*):
|
| 207 |
+
Whether to rescale the image by the specified scale `rescale_factor`.
|
| 208 |
+
rescale_factor (`int` or `float`, *optional*):
|
| 209 |
+
Scale factor to use if rescaling the image.
|
| 210 |
+
do_normalize (`bool`, *optional*):
|
| 211 |
+
Whether to normalize the image.
|
| 212 |
+
image_mean (`float` or `List[float]`, *optional*):
|
| 213 |
+
Mean to use if normalizing the image.
|
| 214 |
+
image_std (`float` or `List[float]`, *optional*):
|
| 215 |
+
Standard deviation to use if normalizing the image.
|
| 216 |
+
do_pad (`bool`, *optional*):
|
| 217 |
+
Whether to pad the image to the `(max_height, max_width)` of the images in the batch.
|
| 218 |
+
do_center_crop (`bool`, *optional*):
|
| 219 |
+
Whether to center crop the image.
|
| 220 |
+
data_format (`ChannelDimension` or `str`, *optional*):
|
| 221 |
+
The channel dimension format for the output image.
|
| 222 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 223 |
+
The channel dimension format for the input image.
|
| 224 |
+
"""
|
| 225 |
+
|
| 226 |
+
do_resize: Optional[bool]
|
| 227 |
+
size: Optional[Dict[str, int]]
|
| 228 |
+
size_divisor: Optional[int]
|
| 229 |
+
resample: Optional["PILImageResampling"]
|
| 230 |
+
do_rescale: Optional[bool]
|
| 231 |
+
rescale_factor: Optional[float]
|
| 232 |
+
do_normalize: Optional[bool]
|
| 233 |
+
image_mean: Optional[Union[float, List[float]]]
|
| 234 |
+
image_std: Optional[Union[float, List[float]]]
|
| 235 |
+
do_pad: Optional[bool]
|
| 236 |
+
do_center_crop: Optional[bool]
|
| 237 |
+
data_format: Optional[ChannelDimension]
|
| 238 |
+
input_data_format: Optional[Union[str, ChannelDimension]]
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
class AudioKwargs(TypedDict, total=False):
|
| 242 |
+
"""
|
| 243 |
+
Keyword arguments for audio processing.
|
| 244 |
+
|
| 245 |
+
Attributes:
|
| 246 |
+
sampling_rate (`int`, *optional*):
|
| 247 |
+
The sampling rate at which the `raw_speech` input was sampled.
|
| 248 |
+
raw_speech (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`):
|
| 249 |
+
The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
|
| 250 |
+
values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
|
| 251 |
+
stereo, i.e. single float per timestep.
|
| 252 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*):
|
| 253 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
| 254 |
+
index) among:
|
| 255 |
+
|
| 256 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
| 257 |
+
sequence if provided).
|
| 258 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 259 |
+
acceptable input length for the model if that argument is not provided.
|
| 260 |
+
- `False` or `'do_not_pad'`
|
| 261 |
+
max_length (`int`, *optional*):
|
| 262 |
+
Maximum length of the returned list and optionally padding length (see above).
|
| 263 |
+
truncation (`bool`, *optional*):
|
| 264 |
+
Activates truncation to cut input sequences longer than *max_length* to *max_length*.
|
| 265 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 266 |
+
If set, will pad the sequence to a multiple of the provided value.
|
| 267 |
+
return_attention_mask (`bool`, *optional*):
|
| 268 |
+
Whether or not [`~ASTFeatureExtractor.__call__`] should return `attention_mask`.
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
sampling_rate: Optional[int]
|
| 272 |
+
raw_speech: Optional[Union["np.ndarray", List[float], List["np.ndarray"], List[List[float]]]]
|
| 273 |
+
padding: Optional[Union[bool, str, PaddingStrategy]]
|
| 274 |
+
max_length: Optional[int]
|
| 275 |
+
truncation: Optional[bool]
|
| 276 |
+
pad_to_multiple_of: Optional[int]
|
| 277 |
+
return_attention_mask: Optional[bool]
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class CommonKwargs(TypedDict, total=False):
|
| 281 |
+
return_tensors: Optional[Union[str, TensorType]]
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class ProcessingKwargs(TextKwargs, ImagesKwargs, VideosKwargs, AudioKwargs, CommonKwargs, total=False):
|
| 285 |
+
"""
|
| 286 |
+
Base class for kwargs passing to processors.
|
| 287 |
+
A model should have its own `ModelProcessorKwargs` class that inherits from `ProcessingKwargs` to provide:
|
| 288 |
+
1) Additional typed keys and that this model requires to process inputs.
|
| 289 |
+
2) Default values for existing keys under a `_defaults` attribute.
|
| 290 |
+
New keys have to be defined as follows to ensure type hinting is done correctly.
|
| 291 |
+
|
| 292 |
+
```python
|
| 293 |
+
# adding a new image kwarg for this model
|
| 294 |
+
class ModelImagesKwargs(ImagesKwargs, total=False):
|
| 295 |
+
new_image_kwarg: Optional[bool]
|
| 296 |
+
|
| 297 |
+
class ModelProcessorKwargs(ProcessingKwargs, total=False):
|
| 298 |
+
images_kwargs: ModelImagesKwargs
|
| 299 |
+
_defaults = {
|
| 300 |
+
"images_kwargs: {
|
| 301 |
+
"new_image_kwarg": False,
|
| 302 |
+
}
|
| 303 |
+
"text_kwargs": {
|
| 304 |
+
"padding": "max_length",
|
| 305 |
+
},
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
```
|
| 309 |
+
|
| 310 |
+
For Python 3.8 compatibility, when inheriting from this class and overriding one of the kwargs,
|
| 311 |
+
you need to manually update the __annotations__ dictionary. This can be done as follows:
|
| 312 |
+
|
| 313 |
+
```python
|
| 314 |
+
class CustomProcessorKwargs(ProcessingKwargs, total=False):
|
| 315 |
+
images_kwargs: CustomImagesKwargs
|
| 316 |
+
|
| 317 |
+
CustomProcessorKwargs.__annotations__["images_kwargs"] = CustomImagesKwargs # python 3.8 compatibility
|
| 318 |
+
```python
|
| 319 |
+
|
| 320 |
+
"""
|
| 321 |
+
|
| 322 |
+
common_kwargs: CommonKwargs = {
|
| 323 |
+
**CommonKwargs.__annotations__,
|
| 324 |
+
}
|
| 325 |
+
text_kwargs: TextKwargs = {
|
| 326 |
+
**TextKwargs.__annotations__,
|
| 327 |
+
}
|
| 328 |
+
images_kwargs: ImagesKwargs = {
|
| 329 |
+
**ImagesKwargs.__annotations__,
|
| 330 |
+
}
|
| 331 |
+
videos_kwargs: VideosKwargs = {
|
| 332 |
+
**VideosKwargs.__annotations__,
|
| 333 |
+
}
|
| 334 |
+
audio_kwargs: AudioKwargs = {
|
| 335 |
+
**AudioKwargs.__annotations__,
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class ProcessorMixin(PushToHubMixin):
|
| 340 |
+
"""
|
| 341 |
+
This is a mixin used to provide saving/loading functionality for all processor classes.
|
| 342 |
+
"""
|
| 343 |
+
|
| 344 |
+
attributes = ["feature_extractor", "tokenizer"]
|
| 345 |
+
optional_attributes = ["chat_template"]
|
| 346 |
+
optional_call_args: List[str] = []
|
| 347 |
+
# Names need to be attr_class for attr in attributes
|
| 348 |
+
feature_extractor_class = None
|
| 349 |
+
tokenizer_class = None
|
| 350 |
+
_auto_class = None
|
| 351 |
+
valid_kwargs: List[str] = []
|
| 352 |
+
|
| 353 |
+
# args have to match the attributes class attribute
|
| 354 |
+
def __init__(self, *args, **kwargs):
|
| 355 |
+
# First, extract optional attributes from kwargs if present
|
| 356 |
+
# Optional attributes can never be positional arguments
|
| 357 |
+
for optional_attribute in self.optional_attributes:
|
| 358 |
+
setattr(self, optional_attribute, kwargs.pop(optional_attribute, None))
|
| 359 |
+
# Sanitize args and kwargs
|
| 360 |
+
for key in kwargs:
|
| 361 |
+
if key not in self.attributes:
|
| 362 |
+
raise TypeError(f"Unexpected keyword argument {key}.")
|
| 363 |
+
for arg, attribute_name in zip(args, self.attributes):
|
| 364 |
+
if attribute_name in kwargs:
|
| 365 |
+
raise TypeError(f"Got multiple values for argument {attribute_name}.")
|
| 366 |
+
else:
|
| 367 |
+
kwargs[attribute_name] = arg
|
| 368 |
+
|
| 369 |
+
if len(kwargs) != len(self.attributes):
|
| 370 |
+
raise ValueError(
|
| 371 |
+
f"This processor requires {len(self.attributes)} arguments: {', '.join(self.attributes)}. Got "
|
| 372 |
+
f"{len(args)} arguments instead."
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
# Check each arg is of the proper class (this will also catch a user initializing in the wrong order)
|
| 376 |
+
for attribute_name, arg in kwargs.items():
|
| 377 |
+
class_name = getattr(self, f"{attribute_name}_class")
|
| 378 |
+
# Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class.
|
| 379 |
+
class_name = AUTO_TO_BASE_CLASS_MAPPING.get(class_name, class_name)
|
| 380 |
+
if isinstance(class_name, tuple):
|
| 381 |
+
proper_class = tuple(getattr(transformers_module, n) for n in class_name if n is not None)
|
| 382 |
+
else:
|
| 383 |
+
proper_class = getattr(transformers_module, class_name)
|
| 384 |
+
|
| 385 |
+
if not isinstance(arg, proper_class):
|
| 386 |
+
raise TypeError(
|
| 387 |
+
f"Received a {type(arg).__name__} for argument {attribute_name}, but a {class_name} was expected."
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
setattr(self, attribute_name, arg)
|
| 391 |
+
|
| 392 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 393 |
+
"""
|
| 394 |
+
Serializes this instance to a Python dictionary.
|
| 395 |
+
|
| 396 |
+
Returns:
|
| 397 |
+
`Dict[str, Any]`: Dictionary of all the attributes that make up this processor instance.
|
| 398 |
+
"""
|
| 399 |
+
output = copy.deepcopy(self.__dict__)
|
| 400 |
+
|
| 401 |
+
# Get the kwargs in `__init__`.
|
| 402 |
+
sig = inspect.signature(self.__init__)
|
| 403 |
+
# Only save the attributes that are presented in the kwargs of `__init__`.
|
| 404 |
+
attrs_to_save = sig.parameters
|
| 405 |
+
# Don't save attributes like `tokenizer`, `image processor` etc.
|
| 406 |
+
attrs_to_save = [x for x in attrs_to_save if x not in self.__class__.attributes]
|
| 407 |
+
# extra attributes to be kept
|
| 408 |
+
attrs_to_save += ["auto_map"]
|
| 409 |
+
|
| 410 |
+
output = {k: v for k, v in output.items() if k in attrs_to_save}
|
| 411 |
+
|
| 412 |
+
output["processor_class"] = self.__class__.__name__
|
| 413 |
+
|
| 414 |
+
if "tokenizer" in output:
|
| 415 |
+
del output["tokenizer"]
|
| 416 |
+
if "image_processor" in output:
|
| 417 |
+
del output["image_processor"]
|
| 418 |
+
if "feature_extractor" in output:
|
| 419 |
+
del output["feature_extractor"]
|
| 420 |
+
if "chat_template" in output:
|
| 421 |
+
del output["chat_template"]
|
| 422 |
+
|
| 423 |
+
# Some attributes have different names but containing objects that are not simple strings
|
| 424 |
+
output = {
|
| 425 |
+
k: v
|
| 426 |
+
for k, v in output.items()
|
| 427 |
+
if not (isinstance(v, PushToHubMixin) or v.__class__.__name__ == "BeamSearchDecoderCTC")
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
return output
|
| 431 |
+
|
| 432 |
+
def to_json_string(self) -> str:
|
| 433 |
+
"""
|
| 434 |
+
Serializes this instance to a JSON string.
|
| 435 |
+
|
| 436 |
+
Returns:
|
| 437 |
+
`str`: String containing all the attributes that make up this feature_extractor instance in JSON format.
|
| 438 |
+
"""
|
| 439 |
+
dictionary = self.to_dict()
|
| 440 |
+
|
| 441 |
+
return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"
|
| 442 |
+
|
| 443 |
+
def to_json_file(self, json_file_path: Union[str, os.PathLike]):
|
| 444 |
+
"""
|
| 445 |
+
Save this instance to a JSON file.
|
| 446 |
+
|
| 447 |
+
Args:
|
| 448 |
+
json_file_path (`str` or `os.PathLike`):
|
| 449 |
+
Path to the JSON file in which this processor instance's parameters will be saved.
|
| 450 |
+
"""
|
| 451 |
+
with open(json_file_path, "w", encoding="utf-8") as writer:
|
| 452 |
+
writer.write(self.to_json_string())
|
| 453 |
+
|
| 454 |
+
def __repr__(self):
|
| 455 |
+
attributes_repr = [f"- {name}: {repr(getattr(self, name))}" for name in self.attributes]
|
| 456 |
+
attributes_repr = "\n".join(attributes_repr)
|
| 457 |
+
return f"{self.__class__.__name__}:\n{attributes_repr}\n\n{self.to_json_string()}"
|
| 458 |
+
|
| 459 |
+
def save_pretrained(self, save_directory, push_to_hub: bool = False, **kwargs):
|
| 460 |
+
"""
|
| 461 |
+
Saves the attributes of this processor (feature extractor, tokenizer...) in the specified directory so that it
|
| 462 |
+
can be reloaded using the [`~ProcessorMixin.from_pretrained`] method.
|
| 463 |
+
|
| 464 |
+
<Tip>
|
| 465 |
+
|
| 466 |
+
This class method is simply calling [`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] and
|
| 467 |
+
[`~tokenization_utils_base.PreTrainedTokenizerBase.save_pretrained`]. Please refer to the docstrings of the
|
| 468 |
+
methods above for more information.
|
| 469 |
+
|
| 470 |
+
</Tip>
|
| 471 |
+
|
| 472 |
+
Args:
|
| 473 |
+
save_directory (`str` or `os.PathLike`):
|
| 474 |
+
Directory where the feature extractor JSON file and the tokenizer files will be saved (directory will
|
| 475 |
+
be created if it does not exist).
|
| 476 |
+
push_to_hub (`bool`, *optional*, defaults to `False`):
|
| 477 |
+
Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
|
| 478 |
+
repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
|
| 479 |
+
namespace).
|
| 480 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 481 |
+
Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
|
| 482 |
+
"""
|
| 483 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 484 |
+
|
| 485 |
+
if use_auth_token is not None:
|
| 486 |
+
warnings.warn(
|
| 487 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 488 |
+
FutureWarning,
|
| 489 |
+
)
|
| 490 |
+
if kwargs.get("token", None) is not None:
|
| 491 |
+
raise ValueError(
|
| 492 |
+
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
|
| 493 |
+
)
|
| 494 |
+
kwargs["token"] = use_auth_token
|
| 495 |
+
|
| 496 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 497 |
+
|
| 498 |
+
if push_to_hub:
|
| 499 |
+
commit_message = kwargs.pop("commit_message", None)
|
| 500 |
+
repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
|
| 501 |
+
repo_id = self._create_repo(repo_id, **kwargs)
|
| 502 |
+
files_timestamps = self._get_files_timestamps(save_directory)
|
| 503 |
+
# If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
|
| 504 |
+
# loaded from the Hub.
|
| 505 |
+
if self._auto_class is not None:
|
| 506 |
+
attrs = [getattr(self, attribute_name) for attribute_name in self.attributes]
|
| 507 |
+
configs = [(a.init_kwargs if isinstance(a, PreTrainedTokenizerBase) else a) for a in attrs]
|
| 508 |
+
configs.append(self)
|
| 509 |
+
custom_object_save(self, save_directory, config=configs)
|
| 510 |
+
|
| 511 |
+
for attribute_name in self.attributes:
|
| 512 |
+
attribute = getattr(self, attribute_name)
|
| 513 |
+
# Include the processor class in the attribute config so this processor can then be reloaded with the
|
| 514 |
+
# `AutoProcessor` API.
|
| 515 |
+
if hasattr(attribute, "_set_processor_class"):
|
| 516 |
+
attribute._set_processor_class(self.__class__.__name__)
|
| 517 |
+
attribute.save_pretrained(save_directory)
|
| 518 |
+
|
| 519 |
+
if self._auto_class is not None:
|
| 520 |
+
# We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up.
|
| 521 |
+
for attribute_name in self.attributes:
|
| 522 |
+
attribute = getattr(self, attribute_name)
|
| 523 |
+
if isinstance(attribute, PreTrainedTokenizerBase):
|
| 524 |
+
del attribute.init_kwargs["auto_map"]
|
| 525 |
+
|
| 526 |
+
# If we save using the predefined names, we can load using `from_pretrained`
|
| 527 |
+
# plus we save chat_template in its own file
|
| 528 |
+
output_processor_file = os.path.join(save_directory, PROCESSOR_NAME)
|
| 529 |
+
output_raw_chat_template_file = os.path.join(save_directory, "chat_template.jinja")
|
| 530 |
+
output_chat_template_file = os.path.join(save_directory, "chat_template.json")
|
| 531 |
+
|
| 532 |
+
processor_dict = self.to_dict()
|
| 533 |
+
# Save `chat_template` in its own file. We can't get it from `processor_dict` as we popped it in `to_dict`
|
| 534 |
+
# to avoid serializing chat template in json config file. So let's get it from `self` directly
|
| 535 |
+
if self.chat_template is not None:
|
| 536 |
+
if kwargs.get("save_raw_chat_template", False):
|
| 537 |
+
with open(output_raw_chat_template_file, "w", encoding="utf-8") as writer:
|
| 538 |
+
writer.write(self.chat_template)
|
| 539 |
+
logger.info(f"chat template saved in {output_raw_chat_template_file}")
|
| 540 |
+
else:
|
| 541 |
+
chat_template_json_string = (
|
| 542 |
+
json.dumps({"chat_template": self.chat_template}, indent=2, sort_keys=True) + "\n"
|
| 543 |
+
)
|
| 544 |
+
with open(output_chat_template_file, "w", encoding="utf-8") as writer:
|
| 545 |
+
writer.write(chat_template_json_string)
|
| 546 |
+
logger.info(f"chat template saved in {output_chat_template_file}")
|
| 547 |
+
|
| 548 |
+
# For now, let's not save to `processor_config.json` if the processor doesn't have extra attributes and
|
| 549 |
+
# `auto_map` is not specified.
|
| 550 |
+
if set(processor_dict.keys()) != {"processor_class"}:
|
| 551 |
+
self.to_json_file(output_processor_file)
|
| 552 |
+
logger.info(f"processor saved in {output_processor_file}")
|
| 553 |
+
|
| 554 |
+
if push_to_hub:
|
| 555 |
+
self._upload_modified_files(
|
| 556 |
+
save_directory,
|
| 557 |
+
repo_id,
|
| 558 |
+
files_timestamps,
|
| 559 |
+
commit_message=commit_message,
|
| 560 |
+
token=kwargs.get("token"),
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
if set(processor_dict.keys()) == {"processor_class"}:
|
| 564 |
+
return []
|
| 565 |
+
return [output_processor_file]
|
| 566 |
+
|
| 567 |
+
@classmethod
|
| 568 |
+
def get_processor_dict(
|
| 569 |
+
cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
|
| 570 |
+
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
| 571 |
+
"""
|
| 572 |
+
From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
|
| 573 |
+
processor of type [`~processing_utils.ProcessingMixin`] using `from_args_and_dict`.
|
| 574 |
+
|
| 575 |
+
Parameters:
|
| 576 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 577 |
+
The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.
|
| 578 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
| 579 |
+
In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
|
| 580 |
+
specify the folder name here.
|
| 581 |
+
|
| 582 |
+
Returns:
|
| 583 |
+
`Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the processor object.
|
| 584 |
+
"""
|
| 585 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
| 586 |
+
force_download = kwargs.pop("force_download", False)
|
| 587 |
+
resume_download = kwargs.pop("resume_download", None)
|
| 588 |
+
proxies = kwargs.pop("proxies", None)
|
| 589 |
+
token = kwargs.pop("token", None)
|
| 590 |
+
local_files_only = kwargs.pop("local_files_only", False)
|
| 591 |
+
revision = kwargs.pop("revision", None)
|
| 592 |
+
subfolder = kwargs.pop("subfolder", "")
|
| 593 |
+
|
| 594 |
+
from_pipeline = kwargs.pop("_from_pipeline", None)
|
| 595 |
+
from_auto_class = kwargs.pop("_from_auto", False)
|
| 596 |
+
|
| 597 |
+
user_agent = {"file_type": "processor", "from_auto_class": from_auto_class}
|
| 598 |
+
if from_pipeline is not None:
|
| 599 |
+
user_agent["using_pipeline"] = from_pipeline
|
| 600 |
+
|
| 601 |
+
if is_offline_mode() and not local_files_only:
|
| 602 |
+
logger.info("Offline mode: forcing local_files_only=True")
|
| 603 |
+
local_files_only = True
|
| 604 |
+
|
| 605 |
+
pretrained_model_name_or_path = str(pretrained_model_name_or_path)
|
| 606 |
+
is_local = os.path.isdir(pretrained_model_name_or_path)
|
| 607 |
+
if os.path.isdir(pretrained_model_name_or_path):
|
| 608 |
+
processor_file = os.path.join(pretrained_model_name_or_path, PROCESSOR_NAME)
|
| 609 |
+
|
| 610 |
+
if os.path.isfile(pretrained_model_name_or_path):
|
| 611 |
+
resolved_processor_file = pretrained_model_name_or_path
|
| 612 |
+
# cant't load chat-template when given a file as pretrained_model_name_or_path
|
| 613 |
+
resolved_chat_template_file = None
|
| 614 |
+
resolved_raw_chat_template_file = None
|
| 615 |
+
is_local = True
|
| 616 |
+
elif is_remote_url(pretrained_model_name_or_path):
|
| 617 |
+
processor_file = pretrained_model_name_or_path
|
| 618 |
+
resolved_processor_file = download_url(pretrained_model_name_or_path)
|
| 619 |
+
# can't load chat-template when given a file url as pretrained_model_name_or_path
|
| 620 |
+
resolved_chat_template_file = None
|
| 621 |
+
resolved_raw_chat_template_file = None
|
| 622 |
+
else:
|
| 623 |
+
processor_file = PROCESSOR_NAME
|
| 624 |
+
chat_template_file = "chat_template.json"
|
| 625 |
+
raw_chat_template_file = "chat_template.jinja"
|
| 626 |
+
try:
|
| 627 |
+
# Load from local folder or from cache or download from model Hub and cache
|
| 628 |
+
resolved_processor_file = cached_file(
|
| 629 |
+
pretrained_model_name_or_path,
|
| 630 |
+
processor_file,
|
| 631 |
+
cache_dir=cache_dir,
|
| 632 |
+
force_download=force_download,
|
| 633 |
+
proxies=proxies,
|
| 634 |
+
resume_download=resume_download,
|
| 635 |
+
local_files_only=local_files_only,
|
| 636 |
+
token=token,
|
| 637 |
+
user_agent=user_agent,
|
| 638 |
+
revision=revision,
|
| 639 |
+
subfolder=subfolder,
|
| 640 |
+
_raise_exceptions_for_missing_entries=False,
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
# Load chat template from a separate json if exists
|
| 644 |
+
# because making it part of processor-config break BC.
|
| 645 |
+
# Processors in older version do not accept any kwargs
|
| 646 |
+
resolved_chat_template_file = cached_file(
|
| 647 |
+
pretrained_model_name_or_path,
|
| 648 |
+
chat_template_file,
|
| 649 |
+
cache_dir=cache_dir,
|
| 650 |
+
force_download=force_download,
|
| 651 |
+
proxies=proxies,
|
| 652 |
+
resume_download=resume_download,
|
| 653 |
+
local_files_only=local_files_only,
|
| 654 |
+
token=token,
|
| 655 |
+
user_agent=user_agent,
|
| 656 |
+
revision=revision,
|
| 657 |
+
subfolder=subfolder,
|
| 658 |
+
_raise_exceptions_for_missing_entries=False,
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
resolved_raw_chat_template_file = cached_file(
|
| 662 |
+
pretrained_model_name_or_path,
|
| 663 |
+
raw_chat_template_file,
|
| 664 |
+
cache_dir=cache_dir,
|
| 665 |
+
force_download=force_download,
|
| 666 |
+
proxies=proxies,
|
| 667 |
+
resume_download=resume_download,
|
| 668 |
+
local_files_only=local_files_only,
|
| 669 |
+
token=token,
|
| 670 |
+
user_agent=user_agent,
|
| 671 |
+
revision=revision,
|
| 672 |
+
subfolder=subfolder,
|
| 673 |
+
_raise_exceptions_for_missing_entries=False,
|
| 674 |
+
)
|
| 675 |
+
except EnvironmentError:
|
| 676 |
+
# Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
|
| 677 |
+
# the original exception.
|
| 678 |
+
raise
|
| 679 |
+
except Exception:
|
| 680 |
+
# For any other exception, we throw a generic error.
|
| 681 |
+
raise EnvironmentError(
|
| 682 |
+
f"Can't load processor for '{pretrained_model_name_or_path}'. If you were trying to load"
|
| 683 |
+
" it from 'https://huggingface.co/models', make sure you don't have a local directory with the"
|
| 684 |
+
f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
|
| 685 |
+
f" directory containing a {PROCESSOR_NAME} file"
|
| 686 |
+
)
|
| 687 |
+
|
| 688 |
+
# Add chat template as kwarg before returning because most models don't have processor config
|
| 689 |
+
if resolved_raw_chat_template_file is not None:
|
| 690 |
+
with open(resolved_raw_chat_template_file, "r", encoding="utf-8") as reader:
|
| 691 |
+
chat_template = reader.read()
|
| 692 |
+
kwargs["chat_template"] = chat_template
|
| 693 |
+
elif resolved_chat_template_file is not None:
|
| 694 |
+
with open(resolved_chat_template_file, "r", encoding="utf-8") as reader:
|
| 695 |
+
text = reader.read()
|
| 696 |
+
chat_template = json.loads(text)["chat_template"]
|
| 697 |
+
kwargs["chat_template"] = chat_template
|
| 698 |
+
|
| 699 |
+
# Existing processors on the Hub created before #27761 being merged don't have `processor_config.json` (if not
|
| 700 |
+
# updated afterward), and we need to keep `from_pretrained` work. So here it fallbacks to the empty dict.
|
| 701 |
+
# (`cached_file` called using `_raise_exceptions_for_missing_entries=False` to avoid exception)
|
| 702 |
+
# However, for models added in the future, we won't get the expected error if this file is missing.
|
| 703 |
+
if resolved_processor_file is None:
|
| 704 |
+
return {}, kwargs
|
| 705 |
+
|
| 706 |
+
try:
|
| 707 |
+
# Load processor dict
|
| 708 |
+
with open(resolved_processor_file, "r", encoding="utf-8") as reader:
|
| 709 |
+
text = reader.read()
|
| 710 |
+
processor_dict = json.loads(text)
|
| 711 |
+
|
| 712 |
+
except json.JSONDecodeError:
|
| 713 |
+
raise EnvironmentError(
|
| 714 |
+
f"It looks like the config file at '{resolved_processor_file}' is not a valid JSON file."
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
if is_local:
|
| 718 |
+
logger.info(f"loading configuration file {resolved_processor_file}")
|
| 719 |
+
else:
|
| 720 |
+
logger.info(f"loading configuration file {processor_file} from cache at {resolved_processor_file}")
|
| 721 |
+
|
| 722 |
+
if "chat_template" in processor_dict and processor_dict["chat_template"] is not None:
|
| 723 |
+
logger.warning_once(
|
| 724 |
+
"Chat templates should be in a 'chat_template.jinja' file but found key='chat_template' "
|
| 725 |
+
"in the processor's config. Make sure to move your template to its own file."
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
if not is_local:
|
| 729 |
+
if "auto_map" in processor_dict:
|
| 730 |
+
processor_dict["auto_map"] = add_model_info_to_auto_map(
|
| 731 |
+
processor_dict["auto_map"], pretrained_model_name_or_path
|
| 732 |
+
)
|
| 733 |
+
if "custom_pipelines" in processor_dict:
|
| 734 |
+
processor_dict["custom_pipelines"] = add_model_info_to_custom_pipelines(
|
| 735 |
+
processor_dict["custom_pipelines"], pretrained_model_name_or_path
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
return processor_dict, kwargs
|
| 739 |
+
|
| 740 |
+
@classmethod
|
| 741 |
+
def from_args_and_dict(cls, args, processor_dict: Dict[str, Any], **kwargs):
|
| 742 |
+
"""
|
| 743 |
+
Instantiates a type of [`~processing_utils.ProcessingMixin`] from a Python dictionary of parameters.
|
| 744 |
+
|
| 745 |
+
Args:
|
| 746 |
+
processor_dict (`Dict[str, Any]`):
|
| 747 |
+
Dictionary that will be used to instantiate the processor object. Such a dictionary can be
|
| 748 |
+
retrieved from a pretrained checkpoint by leveraging the
|
| 749 |
+
[`~processing_utils.ProcessingMixin.to_dict`] method.
|
| 750 |
+
kwargs (`Dict[str, Any]`):
|
| 751 |
+
Additional parameters from which to initialize the processor object.
|
| 752 |
+
|
| 753 |
+
Returns:
|
| 754 |
+
[`~processing_utils.ProcessingMixin`]: The processor object instantiated from those
|
| 755 |
+
parameters.
|
| 756 |
+
"""
|
| 757 |
+
processor_dict = processor_dict.copy()
|
| 758 |
+
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
|
| 759 |
+
chat_template = kwargs.pop("chat_template", None)
|
| 760 |
+
|
| 761 |
+
# We have to pop up some unused (but specific) kwargs and then validate that it doesn't contain unused kwargs
|
| 762 |
+
# If we don't pop, some specific kwargs will raise a warning
|
| 763 |
+
if "processor_class" in processor_dict:
|
| 764 |
+
del processor_dict["processor_class"]
|
| 765 |
+
|
| 766 |
+
if "auto_map" in processor_dict:
|
| 767 |
+
del processor_dict["auto_map"]
|
| 768 |
+
|
| 769 |
+
unused_kwargs = cls.validate_init_kwargs(processor_config=processor_dict, valid_kwargs=cls.valid_kwargs)
|
| 770 |
+
processor = cls(*args, **processor_dict)
|
| 771 |
+
if chat_template is not None:
|
| 772 |
+
setattr(processor, "chat_template", chat_template)
|
| 773 |
+
|
| 774 |
+
# Update processor with kwargs if needed
|
| 775 |
+
for key in set(kwargs.keys()):
|
| 776 |
+
if hasattr(processor, key):
|
| 777 |
+
setattr(processor, key, kwargs.pop(key))
|
| 778 |
+
|
| 779 |
+
kwargs.update(unused_kwargs)
|
| 780 |
+
logger.info(f"Processor {processor}")
|
| 781 |
+
if return_unused_kwargs:
|
| 782 |
+
return processor, kwargs
|
| 783 |
+
else:
|
| 784 |
+
return processor
|
| 785 |
+
|
| 786 |
+
def _merge_kwargs(
|
| 787 |
+
self,
|
| 788 |
+
ModelProcessorKwargs: ProcessingKwargs,
|
| 789 |
+
tokenizer_init_kwargs: Optional[Dict] = None,
|
| 790 |
+
**kwargs,
|
| 791 |
+
) -> Dict[str, Dict]:
|
| 792 |
+
"""
|
| 793 |
+
Method to merge dictionaries of kwargs cleanly separated by modality within a Processor instance.
|
| 794 |
+
The order of operations is as follows:
|
| 795 |
+
1) kwargs passed as before have highest priority to preserve BC.
|
| 796 |
+
```python
|
| 797 |
+
high_priority_kwargs = {"crop_size" = {"height": 222, "width": 222}, "padding" = "max_length"}
|
| 798 |
+
processor(..., **high_priority_kwargs)
|
| 799 |
+
```
|
| 800 |
+
2) kwargs passed as modality-specific kwargs have second priority. This is the recommended API.
|
| 801 |
+
```python
|
| 802 |
+
processor(..., text_kwargs={"padding": "max_length"}, images_kwargs={"crop_size": {"height": 222, "width": 222}}})
|
| 803 |
+
```
|
| 804 |
+
3) kwargs passed during instantiation of a modality processor have fourth priority.
|
| 805 |
+
```python
|
| 806 |
+
tokenizer = tokenizer_class(..., {"padding": "max_length"})
|
| 807 |
+
image_processor = image_processor_class(...)
|
| 808 |
+
processor(tokenizer, image_processor) # will pass max_length unless overriden by kwargs at call
|
| 809 |
+
```
|
| 810 |
+
4) defaults kwargs specified at processor level have lowest priority.
|
| 811 |
+
```python
|
| 812 |
+
class MyProcessingKwargs(ProcessingKwargs, CommonKwargs, TextKwargs, ImagesKwargs, total=False):
|
| 813 |
+
_defaults = {
|
| 814 |
+
"text_kwargs": {
|
| 815 |
+
"padding": "max_length",
|
| 816 |
+
"max_length": 64,
|
| 817 |
+
},
|
| 818 |
+
}
|
| 819 |
+
```
|
| 820 |
+
Args:
|
| 821 |
+
ModelProcessorKwargs (`ProcessingKwargs`):
|
| 822 |
+
Typed dictionary of kwargs specifically required by the model passed.
|
| 823 |
+
tokenizer_init_kwargs (`Dict`, *optional*):
|
| 824 |
+
Dictionary of kwargs the tokenizer was instantiated with and need to take precedence over defaults.
|
| 825 |
+
|
| 826 |
+
Returns:
|
| 827 |
+
output_kwargs (`Dict`):
|
| 828 |
+
Dictionary of per-modality kwargs to be passed to each modality-specific processor.
|
| 829 |
+
|
| 830 |
+
"""
|
| 831 |
+
# Initialize dictionaries
|
| 832 |
+
output_kwargs = {
|
| 833 |
+
"text_kwargs": {},
|
| 834 |
+
"images_kwargs": {},
|
| 835 |
+
"audio_kwargs": {},
|
| 836 |
+
"videos_kwargs": {},
|
| 837 |
+
"common_kwargs": {},
|
| 838 |
+
}
|
| 839 |
+
|
| 840 |
+
default_kwargs = {
|
| 841 |
+
"text_kwargs": {},
|
| 842 |
+
"images_kwargs": {},
|
| 843 |
+
"audio_kwargs": {},
|
| 844 |
+
"videos_kwargs": {},
|
| 845 |
+
"common_kwargs": {},
|
| 846 |
+
}
|
| 847 |
+
|
| 848 |
+
used_keys = set()
|
| 849 |
+
|
| 850 |
+
# get defaults from set model processor kwargs if they exist
|
| 851 |
+
for modality in default_kwargs:
|
| 852 |
+
default_kwargs[modality] = ModelProcessorKwargs._defaults.get(modality, {}).copy()
|
| 853 |
+
# update defaults with arguments from tokenizer init
|
| 854 |
+
for modality_key in ModelProcessorKwargs.__annotations__[modality].__annotations__.keys():
|
| 855 |
+
# init with tokenizer init kwargs if necessary
|
| 856 |
+
if modality_key in tokenizer_init_kwargs:
|
| 857 |
+
value = (
|
| 858 |
+
getattr(self.tokenizer, modality_key)
|
| 859 |
+
if hasattr(self.tokenizer, modality_key)
|
| 860 |
+
else tokenizer_init_kwargs[modality_key]
|
| 861 |
+
)
|
| 862 |
+
default_kwargs[modality][modality_key] = value
|
| 863 |
+
# now defaults kwargs are updated with the tokenizers defaults.
|
| 864 |
+
# pass defaults to output dictionary
|
| 865 |
+
output_kwargs.update(default_kwargs)
|
| 866 |
+
|
| 867 |
+
# update modality kwargs with passed kwargs
|
| 868 |
+
non_modality_kwargs = set(kwargs) - set(output_kwargs)
|
| 869 |
+
for modality in output_kwargs:
|
| 870 |
+
for modality_key in ModelProcessorKwargs.__annotations__[modality].__annotations__.keys():
|
| 871 |
+
# check if we received a structured kwarg dict or not to handle it correctly
|
| 872 |
+
if modality in kwargs:
|
| 873 |
+
kwarg_value = kwargs[modality].pop(modality_key, "__empty__")
|
| 874 |
+
# check if this key was passed as a flat kwarg.
|
| 875 |
+
if kwarg_value != "__empty__" and modality_key in non_modality_kwargs:
|
| 876 |
+
raise ValueError(
|
| 877 |
+
f"Keyword argument {modality_key} was passed two times:\n"
|
| 878 |
+
f"in a dictionary for {modality} and as a **kwarg."
|
| 879 |
+
)
|
| 880 |
+
elif modality_key in kwargs:
|
| 881 |
+
# we get a modality_key instead of popping it because modality-specific processors
|
| 882 |
+
# can have overlapping kwargs
|
| 883 |
+
kwarg_value = kwargs.get(modality_key, "__empty__")
|
| 884 |
+
else:
|
| 885 |
+
kwarg_value = "__empty__"
|
| 886 |
+
if kwarg_value != "__empty__":
|
| 887 |
+
output_kwargs[modality][modality_key] = kwarg_value
|
| 888 |
+
used_keys.add(modality_key)
|
| 889 |
+
|
| 890 |
+
# Determine if kwargs is a flat dictionary or contains nested dictionaries
|
| 891 |
+
if any(key in default_kwargs for key in kwargs):
|
| 892 |
+
# kwargs is dictionary-based, and some keys match modality names
|
| 893 |
+
for modality, subdict in kwargs.items():
|
| 894 |
+
if modality in default_kwargs:
|
| 895 |
+
for subkey, subvalue in subdict.items():
|
| 896 |
+
if subkey not in used_keys:
|
| 897 |
+
output_kwargs[modality][subkey] = subvalue
|
| 898 |
+
used_keys.add(subkey)
|
| 899 |
+
else:
|
| 900 |
+
# kwargs is a flat dictionary
|
| 901 |
+
for key in kwargs:
|
| 902 |
+
if key not in used_keys:
|
| 903 |
+
if key in ModelProcessorKwargs.__annotations__["common_kwargs"].__annotations__.keys():
|
| 904 |
+
output_kwargs["common_kwargs"][key] = kwargs[key]
|
| 905 |
+
else:
|
| 906 |
+
logger.warning_once(
|
| 907 |
+
f"Keyword argument `{key}` is not a valid argument for this processor and will be ignored."
|
| 908 |
+
)
|
| 909 |
+
|
| 910 |
+
# all modality-specific kwargs are updated with common kwargs
|
| 911 |
+
for modality in output_kwargs:
|
| 912 |
+
output_kwargs[modality].update(output_kwargs["common_kwargs"])
|
| 913 |
+
return output_kwargs
|
| 914 |
+
|
| 915 |
+
@classmethod
|
| 916 |
+
def from_pretrained(
|
| 917 |
+
cls,
|
| 918 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
| 919 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
| 920 |
+
force_download: bool = False,
|
| 921 |
+
local_files_only: bool = False,
|
| 922 |
+
token: Optional[Union[str, bool]] = None,
|
| 923 |
+
revision: str = "main",
|
| 924 |
+
**kwargs,
|
| 925 |
+
):
|
| 926 |
+
r"""
|
| 927 |
+
Instantiate a processor associated with a pretrained model.
|
| 928 |
+
|
| 929 |
+
<Tip>
|
| 930 |
+
|
| 931 |
+
This class method is simply calling the feature extractor
|
| 932 |
+
[`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`], image processor
|
| 933 |
+
[`~image_processing_utils.ImageProcessingMixin`] and the tokenizer
|
| 934 |
+
[`~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`] methods. Please refer to the docstrings of the
|
| 935 |
+
methods above for more information.
|
| 936 |
+
|
| 937 |
+
</Tip>
|
| 938 |
+
|
| 939 |
+
Args:
|
| 940 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 941 |
+
This can be either:
|
| 942 |
+
|
| 943 |
+
- a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
|
| 944 |
+
huggingface.co.
|
| 945 |
+
- a path to a *directory* containing a feature extractor file saved using the
|
| 946 |
+
[`~SequenceFeatureExtractor.save_pretrained`] method, e.g., `./my_model_directory/`.
|
| 947 |
+
- a path or url to a saved feature extractor JSON *file*, e.g.,
|
| 948 |
+
`./my_model_directory/preprocessor_config.json`.
|
| 949 |
+
**kwargs
|
| 950 |
+
Additional keyword arguments passed along to both
|
| 951 |
+
[`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`] and
|
| 952 |
+
[`~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`].
|
| 953 |
+
"""
|
| 954 |
+
kwargs["cache_dir"] = cache_dir
|
| 955 |
+
kwargs["force_download"] = force_download
|
| 956 |
+
kwargs["local_files_only"] = local_files_only
|
| 957 |
+
kwargs["revision"] = revision
|
| 958 |
+
|
| 959 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 960 |
+
if use_auth_token is not None:
|
| 961 |
+
warnings.warn(
|
| 962 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 963 |
+
FutureWarning,
|
| 964 |
+
)
|
| 965 |
+
if token is not None:
|
| 966 |
+
raise ValueError(
|
| 967 |
+
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
|
| 968 |
+
)
|
| 969 |
+
token = use_auth_token
|
| 970 |
+
|
| 971 |
+
if token is not None:
|
| 972 |
+
kwargs["token"] = token
|
| 973 |
+
|
| 974 |
+
args = cls._get_arguments_from_pretrained(pretrained_model_name_or_path, **kwargs)
|
| 975 |
+
processor_dict, kwargs = cls.get_processor_dict(pretrained_model_name_or_path, **kwargs)
|
| 976 |
+
|
| 977 |
+
return cls.from_args_and_dict(args, processor_dict, **kwargs)
|
| 978 |
+
|
| 979 |
+
@classmethod
|
| 980 |
+
def register_for_auto_class(cls, auto_class="AutoProcessor"):
|
| 981 |
+
"""
|
| 982 |
+
Register this class with a given auto class. This should only be used for custom feature extractors as the ones
|
| 983 |
+
in the library are already mapped with `AutoProcessor`.
|
| 984 |
+
|
| 985 |
+
<Tip warning={true}>
|
| 986 |
+
|
| 987 |
+
This API is experimental and may have some slight breaking changes in the next releases.
|
| 988 |
+
|
| 989 |
+
</Tip>
|
| 990 |
+
|
| 991 |
+
Args:
|
| 992 |
+
auto_class (`str` or `type`, *optional*, defaults to `"AutoProcessor"`):
|
| 993 |
+
The auto class to register this new feature extractor with.
|
| 994 |
+
"""
|
| 995 |
+
if not isinstance(auto_class, str):
|
| 996 |
+
auto_class = auto_class.__name__
|
| 997 |
+
|
| 998 |
+
import transformers.models.auto as auto_module
|
| 999 |
+
|
| 1000 |
+
if not hasattr(auto_module, auto_class):
|
| 1001 |
+
raise ValueError(f"{auto_class} is not a valid auto class.")
|
| 1002 |
+
|
| 1003 |
+
cls._auto_class = auto_class
|
| 1004 |
+
|
| 1005 |
+
@classmethod
|
| 1006 |
+
def _get_arguments_from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 1007 |
+
args = []
|
| 1008 |
+
for attribute_name in cls.attributes:
|
| 1009 |
+
class_name = getattr(cls, f"{attribute_name}_class")
|
| 1010 |
+
if isinstance(class_name, tuple):
|
| 1011 |
+
classes = tuple(getattr(transformers_module, n) if n is not None else None for n in class_name)
|
| 1012 |
+
use_fast = kwargs.get("use_fast", True)
|
| 1013 |
+
if use_fast and classes[1] is not None:
|
| 1014 |
+
attribute_class = classes[1]
|
| 1015 |
+
else:
|
| 1016 |
+
attribute_class = classes[0]
|
| 1017 |
+
else:
|
| 1018 |
+
attribute_class = getattr(transformers_module, class_name)
|
| 1019 |
+
|
| 1020 |
+
args.append(attribute_class.from_pretrained(pretrained_model_name_or_path, **kwargs))
|
| 1021 |
+
return args
|
| 1022 |
+
|
| 1023 |
+
@property
|
| 1024 |
+
def model_input_names(self):
|
| 1025 |
+
first_attribute = getattr(self, self.attributes[0])
|
| 1026 |
+
return getattr(first_attribute, "model_input_names", None)
|
| 1027 |
+
|
| 1028 |
+
@staticmethod
|
| 1029 |
+
def validate_init_kwargs(processor_config, valid_kwargs):
|
| 1030 |
+
kwargs_from_config = processor_config.keys()
|
| 1031 |
+
unused_kwargs = {}
|
| 1032 |
+
unused_keys = set(kwargs_from_config) - set(valid_kwargs)
|
| 1033 |
+
if unused_keys:
|
| 1034 |
+
unused_key_str = ", ".join(unused_keys)
|
| 1035 |
+
logger.warning(
|
| 1036 |
+
f"Some kwargs in processor config are unused and will not have any effect: {unused_key_str}. "
|
| 1037 |
+
)
|
| 1038 |
+
unused_kwargs = {k: processor_config[k] for k in unused_keys}
|
| 1039 |
+
return unused_kwargs
|
| 1040 |
+
|
| 1041 |
+
def prepare_and_validate_optional_call_args(self, *args):
|
| 1042 |
+
"""
|
| 1043 |
+
Matches optional positional arguments to their corresponding names in `optional_call_args`
|
| 1044 |
+
in the processor class in the order they are passed to the processor call.
|
| 1045 |
+
|
| 1046 |
+
Note that this should only be used in the `__call__` method of the processors with special
|
| 1047 |
+
arguments. Special arguments are arguments that aren't `text`, `images`, `audio`, nor `videos`
|
| 1048 |
+
but also aren't passed to the tokenizer, image processor, etc. Examples of such processors are:
|
| 1049 |
+
- `CLIPSegProcessor`
|
| 1050 |
+
- `LayoutLMv2Processor`
|
| 1051 |
+
- `OwlViTProcessor`
|
| 1052 |
+
|
| 1053 |
+
Also note that passing by position to the processor call is now deprecated and will be disallowed
|
| 1054 |
+
in future versions. We only have this for backward compatibility.
|
| 1055 |
+
|
| 1056 |
+
Example:
|
| 1057 |
+
Suppose that the processor class has `optional_call_args = ["arg_name_1", "arg_name_2"]`.
|
| 1058 |
+
And we define the call method as:
|
| 1059 |
+
```python
|
| 1060 |
+
def __call__(
|
| 1061 |
+
self,
|
| 1062 |
+
text: str,
|
| 1063 |
+
images: Optional[ImageInput] = None,
|
| 1064 |
+
*arg,
|
| 1065 |
+
audio=None,
|
| 1066 |
+
videos=None,
|
| 1067 |
+
)
|
| 1068 |
+
```
|
| 1069 |
+
|
| 1070 |
+
Then, if we call the processor as:
|
| 1071 |
+
```python
|
| 1072 |
+
images = [...]
|
| 1073 |
+
processor("What is common in these images?", images, arg_value_1, arg_value_2)
|
| 1074 |
+
```
|
| 1075 |
+
|
| 1076 |
+
Then, this method will return:
|
| 1077 |
+
```python
|
| 1078 |
+
{
|
| 1079 |
+
"arg_name_1": arg_value_1,
|
| 1080 |
+
"arg_name_2": arg_value_2,
|
| 1081 |
+
}
|
| 1082 |
+
```
|
| 1083 |
+
which we could then pass as kwargs to `self._merge_kwargs`
|
| 1084 |
+
"""
|
| 1085 |
+
if len(args):
|
| 1086 |
+
warnings.warn(
|
| 1087 |
+
"Passing positional arguments to the processor call is now deprecated and will be disallowed in v4.47. "
|
| 1088 |
+
"Please pass all arguments as keyword arguments."
|
| 1089 |
+
)
|
| 1090 |
+
if len(args) > len(self.optional_call_args):
|
| 1091 |
+
raise ValueError(
|
| 1092 |
+
f"Expected *at most* {len(self.optional_call_args)} optional positional arguments in processor call"
|
| 1093 |
+
f"which will be matched with {' '.join(self.optional_call_args)} in the order they are passed."
|
| 1094 |
+
f"However, got {len(args)} positional arguments instead."
|
| 1095 |
+
"Please pass all arguments as keyword arguments instead (e.g. `processor(arg_name_1=..., arg_name_2=...))`."
|
| 1096 |
+
)
|
| 1097 |
+
return {arg_name: arg_value for arg_value, arg_name in zip(args, self.optional_call_args)}
|
| 1098 |
+
|
| 1099 |
+
def apply_chat_template(
|
| 1100 |
+
self,
|
| 1101 |
+
conversation: Union[List[Dict[str, str]]],
|
| 1102 |
+
chat_template: Optional[str] = None,
|
| 1103 |
+
tokenize: bool = False,
|
| 1104 |
+
**kwargs,
|
| 1105 |
+
) -> str:
|
| 1106 |
+
"""
|
| 1107 |
+
Similar to the `apply_chat_template` method on tokenizers, this method applies a Jinja template to input
|
| 1108 |
+
conversations to turn them into a single tokenizable string.
|
| 1109 |
+
|
| 1110 |
+
Args:
|
| 1111 |
+
conversation (`List[Dict, str, str]`):
|
| 1112 |
+
The conversation to format.
|
| 1113 |
+
chat_template (`Optional[str]`, *optional*):
|
| 1114 |
+
The Jinja template to use for formatting the conversation. If not provided, the tokenizer's
|
| 1115 |
+
chat template is used.
|
| 1116 |
+
tokenize (`bool`, *optional*, defaults to `False`):
|
| 1117 |
+
Whether to tokenize the output or not.
|
| 1118 |
+
**kwargs:
|
| 1119 |
+
Additional keyword arguments
|
| 1120 |
+
"""
|
| 1121 |
+
|
| 1122 |
+
if chat_template is None:
|
| 1123 |
+
if self.chat_template is not None:
|
| 1124 |
+
chat_template = self.chat_template
|
| 1125 |
+
else:
|
| 1126 |
+
raise ValueError(
|
| 1127 |
+
"No chat template is set for this processor. Please either set the `chat_template` attribute, "
|
| 1128 |
+
"or provide a chat template as an argument. See "
|
| 1129 |
+
"https://huggingface.co/docs/transformers/main/en/chat_templating for more information."
|
| 1130 |
+
)
|
| 1131 |
+
return self.tokenizer.apply_chat_template(
|
| 1132 |
+
conversation, chat_template=chat_template, tokenize=tokenize, **kwargs
|
| 1133 |
+
)
|
| 1134 |
+
|
| 1135 |
+
def post_process_image_text_to_text(self, generated_outputs):
|
| 1136 |
+
"""
|
| 1137 |
+
Post-process the output of a vlm to decode the text.
|
| 1138 |
+
|
| 1139 |
+
Args:
|
| 1140 |
+
generated_outputs (`torch.Tensor` or `np.ndarray`):
|
| 1141 |
+
The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
|
| 1142 |
+
or `(sequence_length,)`.
|
| 1143 |
+
|
| 1144 |
+
Returns:
|
| 1145 |
+
`List[str]`: The decoded text.
|
| 1146 |
+
"""
|
| 1147 |
+
return self.tokenizer.batch_decode(generated_outputs, skip_special_tokens=True)
|
| 1148 |
+
|
| 1149 |
+
|
| 1150 |
+
def _validate_images_text_input_order(images, text):
|
| 1151 |
+
"""
|
| 1152 |
+
For backward compatibility: reverse the order of `images` and `text` inputs if they are swapped.
|
| 1153 |
+
This method should only be called for processors where `images` and `text` have been swapped for uniformization purposes.
|
| 1154 |
+
Note that this method assumes that two `None` inputs are valid inputs. If this is not the case, it should be handled
|
| 1155 |
+
in the processor's `__call__` method before calling this method.
|
| 1156 |
+
"""
|
| 1157 |
+
|
| 1158 |
+
def is_url(val) -> bool:
|
| 1159 |
+
return isinstance(val, str) and val.startswith("http")
|
| 1160 |
+
|
| 1161 |
+
def _is_valid_images_input_for_processor(imgs):
|
| 1162 |
+
# If we have an list of images, make sure every image is valid
|
| 1163 |
+
if isinstance(imgs, (list, tuple)):
|
| 1164 |
+
for img in imgs:
|
| 1165 |
+
if not _is_valid_images_input_for_processor(img):
|
| 1166 |
+
return False
|
| 1167 |
+
# If not a list or tuple, we have been given a single image or batched tensor of images
|
| 1168 |
+
elif not (is_valid_image(imgs) or is_url(imgs)):
|
| 1169 |
+
return False
|
| 1170 |
+
return True
|
| 1171 |
+
|
| 1172 |
+
def _is_valid_text_input_for_processor(t):
|
| 1173 |
+
if isinstance(t, str):
|
| 1174 |
+
# Strings are fine
|
| 1175 |
+
return True
|
| 1176 |
+
elif isinstance(t, (list, tuple)):
|
| 1177 |
+
# List are fine as long as they are...
|
| 1178 |
+
if len(t) == 0:
|
| 1179 |
+
# ... not empty
|
| 1180 |
+
return False
|
| 1181 |
+
for t_s in t:
|
| 1182 |
+
return _is_valid_text_input_for_processor(t_s)
|
| 1183 |
+
return False
|
| 1184 |
+
|
| 1185 |
+
def _is_valid(input, validator):
|
| 1186 |
+
return validator(input) or input is None
|
| 1187 |
+
|
| 1188 |
+
images_is_valid = _is_valid(images, _is_valid_images_input_for_processor)
|
| 1189 |
+
images_is_text = _is_valid_text_input_for_processor(images)
|
| 1190 |
+
|
| 1191 |
+
text_is_valid = _is_valid(text, _is_valid_text_input_for_processor)
|
| 1192 |
+
text_is_images = _is_valid_images_input_for_processor(text)
|
| 1193 |
+
# Handle cases where both inputs are valid
|
| 1194 |
+
if images_is_valid and text_is_valid:
|
| 1195 |
+
return images, text
|
| 1196 |
+
|
| 1197 |
+
# Handle cases where inputs need to and can be swapped
|
| 1198 |
+
if (images is None and text_is_images) or (text is None and images_is_text) or (images_is_text and text_is_images):
|
| 1199 |
+
logger.warning_once(
|
| 1200 |
+
"You may have used the wrong order for inputs. `images` should be passed before `text`. "
|
| 1201 |
+
"The `images` and `text` inputs will be swapped. This behavior will be deprecated in transformers v4.47."
|
| 1202 |
+
)
|
| 1203 |
+
return text, images
|
| 1204 |
+
|
| 1205 |
+
raise ValueError("Invalid input type. Check that `images` and/or `text` are valid inputs.")
|
| 1206 |
+
|
| 1207 |
+
|
| 1208 |
+
ProcessorMixin.push_to_hub = copy_func(ProcessorMixin.push_to_hub)
|
| 1209 |
+
if ProcessorMixin.push_to_hub.__doc__ is not None:
|
| 1210 |
+
ProcessorMixin.push_to_hub.__doc__ = ProcessorMixin.push_to_hub.__doc__.format(
|
| 1211 |
+
object="processor", object_class="AutoProcessor", object_files="processor files"
|
| 1212 |
+
)
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/pytorch_utils.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import inspect
|
| 17 |
+
from typing import Callable, List, Optional, Set, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from packaging import version
|
| 21 |
+
from safetensors.torch import storage_ptr, storage_size
|
| 22 |
+
from torch import nn
|
| 23 |
+
|
| 24 |
+
from .utils import is_torch_greater_or_equal, is_torch_xla_available, logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
ALL_LAYERNORM_LAYERS = [nn.LayerNorm]
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
parsed_torch_version_base = version.parse(version.parse(torch.__version__).base_version)
|
| 32 |
+
|
| 33 |
+
is_torch_greater_or_equal_than_2_4 = parsed_torch_version_base >= version.parse("2.4")
|
| 34 |
+
is_torch_greater_or_equal_than_2_3 = parsed_torch_version_base >= version.parse("2.3")
|
| 35 |
+
is_torch_greater_or_equal_than_2_2 = parsed_torch_version_base >= version.parse("2.2")
|
| 36 |
+
is_torch_greater_or_equal_than_2_1 = parsed_torch_version_base >= version.parse("2.1")
|
| 37 |
+
|
| 38 |
+
# Cache this result has it's a C FFI call which can be pretty time-consuming
|
| 39 |
+
_torch_distributed_available = torch.distributed.is_available()
|
| 40 |
+
|
| 41 |
+
if is_torch_greater_or_equal("2.5") and _torch_distributed_available:
|
| 42 |
+
from torch.distributed.tensor import Replicate
|
| 43 |
+
from torch.distributed.tensor.parallel import (
|
| 44 |
+
ColwiseParallel,
|
| 45 |
+
RowwiseParallel,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def softmax_backward_data(parent, grad_output, output, dim, self):
|
| 50 |
+
"""
|
| 51 |
+
A function that calls the internal `_softmax_backward_data` PyTorch method and that adjusts the arguments according
|
| 52 |
+
to the torch version detected.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
from torch import _softmax_backward_data
|
| 56 |
+
|
| 57 |
+
return _softmax_backward_data(grad_output, output, parent.dim, self.dtype)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: int = 0) -> nn.Linear:
|
| 61 |
+
"""
|
| 62 |
+
Prune a linear layer to keep only entries in index.
|
| 63 |
+
|
| 64 |
+
Used to remove heads.
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
layer (`torch.nn.Linear`): The layer to prune.
|
| 68 |
+
index (`torch.LongTensor`): The indices to keep in the layer.
|
| 69 |
+
dim (`int`, *optional*, defaults to 0): The dimension on which to keep the indices.
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
`torch.nn.Linear`: The pruned layer as a new layer with `requires_grad=True`.
|
| 73 |
+
"""
|
| 74 |
+
index = index.to(layer.weight.device)
|
| 75 |
+
W = layer.weight.index_select(dim, index).clone().detach()
|
| 76 |
+
if layer.bias is not None:
|
| 77 |
+
if dim == 1:
|
| 78 |
+
b = layer.bias.clone().detach()
|
| 79 |
+
else:
|
| 80 |
+
b = layer.bias[index].clone().detach()
|
| 81 |
+
new_size = list(layer.weight.size())
|
| 82 |
+
new_size[dim] = len(index)
|
| 83 |
+
new_layer = nn.Linear(new_size[1], new_size[0], bias=layer.bias is not None).to(layer.weight.device)
|
| 84 |
+
new_layer.weight.requires_grad = False
|
| 85 |
+
new_layer.weight.copy_(W.contiguous())
|
| 86 |
+
new_layer.weight.requires_grad = True
|
| 87 |
+
if layer.bias is not None:
|
| 88 |
+
new_layer.bias.requires_grad = False
|
| 89 |
+
new_layer.bias.copy_(b.contiguous())
|
| 90 |
+
new_layer.bias.requires_grad = True
|
| 91 |
+
return new_layer
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class Conv1D(nn.Module):
|
| 95 |
+
"""
|
| 96 |
+
1D-convolutional layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2).
|
| 97 |
+
|
| 98 |
+
Basically works like a linear layer but the weights are transposed.
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
nf (`int`): The number of output features.
|
| 102 |
+
nx (`int`): The number of input features.
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
def __init__(self, nf, nx):
|
| 106 |
+
super().__init__()
|
| 107 |
+
self.nf = nf
|
| 108 |
+
self.nx = nx
|
| 109 |
+
self.weight = nn.Parameter(torch.empty(nx, nf))
|
| 110 |
+
self.bias = nn.Parameter(torch.zeros(nf))
|
| 111 |
+
nn.init.normal_(self.weight, std=0.02)
|
| 112 |
+
|
| 113 |
+
def __repr__(self) -> str:
|
| 114 |
+
return "Conv1D(nf={nf}, nx={nx})".format(**self.__dict__)
|
| 115 |
+
|
| 116 |
+
def forward(self, x):
|
| 117 |
+
size_out = x.size()[:-1] + (self.nf,)
|
| 118 |
+
x = torch.addmm(self.bias, x.view(-1, x.size(-1)), self.weight)
|
| 119 |
+
x = x.view(size_out)
|
| 120 |
+
return x
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def prune_conv1d_layer(layer: Conv1D, index: torch.LongTensor, dim: int = 1) -> Conv1D:
|
| 124 |
+
"""
|
| 125 |
+
Prune a Conv1D layer to keep only entries in index. A Conv1D work as a Linear layer (see e.g. BERT) but the weights
|
| 126 |
+
are transposed.
|
| 127 |
+
|
| 128 |
+
Used to remove heads.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
layer ([`~pytorch_utils.Conv1D`]): The layer to prune.
|
| 132 |
+
index (`torch.LongTensor`): The indices to keep in the layer.
|
| 133 |
+
dim (`int`, *optional*, defaults to 1): The dimension on which to keep the indices.
|
| 134 |
+
|
| 135 |
+
Returns:
|
| 136 |
+
[`~pytorch_utils.Conv1D`]: The pruned layer as a new layer with `requires_grad=True`.
|
| 137 |
+
"""
|
| 138 |
+
index = index.to(layer.weight.device)
|
| 139 |
+
W = layer.weight.index_select(dim, index).clone().detach()
|
| 140 |
+
if dim == 0:
|
| 141 |
+
b = layer.bias.clone().detach()
|
| 142 |
+
else:
|
| 143 |
+
b = layer.bias[index].clone().detach()
|
| 144 |
+
new_size = list(layer.weight.size())
|
| 145 |
+
new_size[dim] = len(index)
|
| 146 |
+
new_layer = Conv1D(new_size[1], new_size[0]).to(layer.weight.device)
|
| 147 |
+
new_layer.weight.requires_grad = False
|
| 148 |
+
new_layer.weight.copy_(W.contiguous())
|
| 149 |
+
new_layer.weight.requires_grad = True
|
| 150 |
+
new_layer.bias.requires_grad = False
|
| 151 |
+
new_layer.bias.copy_(b.contiguous())
|
| 152 |
+
new_layer.bias.requires_grad = True
|
| 153 |
+
return new_layer
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def prune_layer(
|
| 157 |
+
layer: Union[nn.Linear, Conv1D], index: torch.LongTensor, dim: Optional[int] = None
|
| 158 |
+
) -> Union[nn.Linear, Conv1D]:
|
| 159 |
+
"""
|
| 160 |
+
Prune a Conv1D or linear layer to keep only entries in index.
|
| 161 |
+
|
| 162 |
+
Used to remove heads.
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
layer (`Union[torch.nn.Linear, Conv1D]`): The layer to prune.
|
| 166 |
+
index (`torch.LongTensor`): The indices to keep in the layer.
|
| 167 |
+
dim (`int`, *optional*): The dimension on which to keep the indices.
|
| 168 |
+
|
| 169 |
+
Returns:
|
| 170 |
+
`torch.nn.Linear` or [`~pytorch_utils.Conv1D`]: The pruned layer as a new layer with `requires_grad=True`.
|
| 171 |
+
"""
|
| 172 |
+
if isinstance(layer, nn.Linear):
|
| 173 |
+
return prune_linear_layer(layer, index, dim=0 if dim is None else dim)
|
| 174 |
+
elif isinstance(layer, Conv1D):
|
| 175 |
+
return prune_conv1d_layer(layer, index, dim=1 if dim is None else dim)
|
| 176 |
+
else:
|
| 177 |
+
raise ValueError(f"Can't prune layer of class {layer.__class__}")
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def apply_chunking_to_forward(
|
| 181 |
+
forward_fn: Callable[..., torch.Tensor],
|
| 182 |
+
chunk_size: int,
|
| 183 |
+
chunk_dim: int,
|
| 184 |
+
*input_tensors,
|
| 185 |
+
) -> torch.Tensor:
|
| 186 |
+
"""
|
| 187 |
+
This function chunks the `input_tensors` into smaller input tensor parts of size `chunk_size` over the dimension
|
| 188 |
+
`chunk_dim`. It then applies a layer `forward_fn` to each chunk independently to save memory.
|
| 189 |
+
|
| 190 |
+
If the `forward_fn` is independent across the `chunk_dim` this function will yield the same result as directly
|
| 191 |
+
applying `forward_fn` to `input_tensors`.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
forward_fn (`Callable[..., torch.Tensor]`):
|
| 195 |
+
The forward function of the model.
|
| 196 |
+
chunk_size (`int`):
|
| 197 |
+
The chunk size of a chunked tensor: `num_chunks = len(input_tensors[0]) / chunk_size`.
|
| 198 |
+
chunk_dim (`int`):
|
| 199 |
+
The dimension over which the `input_tensors` should be chunked.
|
| 200 |
+
input_tensors (`Tuple[torch.Tensor]`):
|
| 201 |
+
The input tensors of `forward_fn` which will be chunked
|
| 202 |
+
|
| 203 |
+
Returns:
|
| 204 |
+
`torch.Tensor`: A tensor with the same shape as the `forward_fn` would have given if applied`.
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
Examples:
|
| 208 |
+
|
| 209 |
+
```python
|
| 210 |
+
# rename the usual forward() fn to forward_chunk()
|
| 211 |
+
def forward_chunk(self, hidden_states):
|
| 212 |
+
hidden_states = self.decoder(hidden_states)
|
| 213 |
+
return hidden_states
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
# implement a chunked forward function
|
| 217 |
+
def forward(self, hidden_states):
|
| 218 |
+
return apply_chunking_to_forward(self.forward_chunk, self.chunk_size_lm_head, self.seq_len_dim, hidden_states)
|
| 219 |
+
```"""
|
| 220 |
+
|
| 221 |
+
assert len(input_tensors) > 0, f"{input_tensors} has to be a tuple/list of tensors"
|
| 222 |
+
|
| 223 |
+
# inspect.signature exist since python 3.5 and is a python method -> no problem with backward compatibility
|
| 224 |
+
num_args_in_forward_chunk_fn = len(inspect.signature(forward_fn).parameters)
|
| 225 |
+
if num_args_in_forward_chunk_fn != len(input_tensors):
|
| 226 |
+
raise ValueError(
|
| 227 |
+
f"forward_chunk_fn expects {num_args_in_forward_chunk_fn} arguments, but only {len(input_tensors)} input "
|
| 228 |
+
"tensors are given"
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
if chunk_size > 0:
|
| 232 |
+
tensor_shape = input_tensors[0].shape[chunk_dim]
|
| 233 |
+
for input_tensor in input_tensors:
|
| 234 |
+
if input_tensor.shape[chunk_dim] != tensor_shape:
|
| 235 |
+
raise ValueError(
|
| 236 |
+
f"All input tenors have to be of the same shape: {tensor_shape}, "
|
| 237 |
+
f"found shape {input_tensor.shape[chunk_dim]}"
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
if input_tensors[0].shape[chunk_dim] % chunk_size != 0:
|
| 241 |
+
raise ValueError(
|
| 242 |
+
f"The dimension to be chunked {input_tensors[0].shape[chunk_dim]} has to be a multiple of the chunk "
|
| 243 |
+
f"size {chunk_size}"
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
num_chunks = input_tensors[0].shape[chunk_dim] // chunk_size
|
| 247 |
+
|
| 248 |
+
# chunk input tensor into tuples
|
| 249 |
+
input_tensors_chunks = tuple(input_tensor.chunk(num_chunks, dim=chunk_dim) for input_tensor in input_tensors)
|
| 250 |
+
# apply forward fn to every tuple
|
| 251 |
+
output_chunks = tuple(forward_fn(*input_tensors_chunk) for input_tensors_chunk in zip(*input_tensors_chunks))
|
| 252 |
+
# concatenate output at same dimension
|
| 253 |
+
return torch.cat(output_chunks, dim=chunk_dim)
|
| 254 |
+
|
| 255 |
+
return forward_fn(*input_tensors)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def find_pruneable_heads_and_indices(
|
| 259 |
+
heads: List[int], n_heads: int, head_size: int, already_pruned_heads: Set[int]
|
| 260 |
+
) -> Tuple[Set[int], torch.LongTensor]:
|
| 261 |
+
"""
|
| 262 |
+
Finds the heads and their indices taking `already_pruned_heads` into account.
|
| 263 |
+
|
| 264 |
+
Args:
|
| 265 |
+
heads (`List[int]`): List of the indices of heads to prune.
|
| 266 |
+
n_heads (`int`): The number of heads in the model.
|
| 267 |
+
head_size (`int`): The size of each head.
|
| 268 |
+
already_pruned_heads (`Set[int]`): A set of already pruned heads.
|
| 269 |
+
|
| 270 |
+
Returns:
|
| 271 |
+
`Tuple[Set[int], torch.LongTensor]`: A tuple with the indices of heads to prune taking `already_pruned_heads`
|
| 272 |
+
into account and the indices of rows/columns to keep in the layer weight.
|
| 273 |
+
"""
|
| 274 |
+
mask = torch.ones(n_heads, head_size)
|
| 275 |
+
heads = set(heads) - already_pruned_heads # Convert to set and remove already pruned heads
|
| 276 |
+
for head in heads:
|
| 277 |
+
# Compute how many pruned heads are before the head and move the index accordingly
|
| 278 |
+
head = head - sum(1 if h < head else 0 for h in already_pruned_heads)
|
| 279 |
+
mask[head] = 0
|
| 280 |
+
mask = mask.view(-1).contiguous().eq(1)
|
| 281 |
+
index: torch.LongTensor = torch.arange(len(mask))[mask].long()
|
| 282 |
+
return heads, index
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def meshgrid(
|
| 286 |
+
*tensors: Union[torch.Tensor, List[torch.Tensor]], indexing: Optional[str] = None
|
| 287 |
+
) -> Tuple[torch.Tensor, ...]:
|
| 288 |
+
"""
|
| 289 |
+
Wrapper around torch.meshgrid to avoid warning messages about the introduced `indexing` argument.
|
| 290 |
+
|
| 291 |
+
Reference: https://pytorch.org/docs/1.13/generated/torch.meshgrid.html
|
| 292 |
+
"""
|
| 293 |
+
return torch.meshgrid(*tensors, indexing=indexing)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def id_tensor_storage(tensor: torch.Tensor) -> Tuple[torch.device, int, int]:
|
| 297 |
+
"""
|
| 298 |
+
Unique identifier to a tensor storage. Multiple different tensors can share the same underlying storage. For
|
| 299 |
+
example, "meta" tensors all share the same storage, and thus their identifier will all be equal. This identifier is
|
| 300 |
+
guaranteed to be unique and constant for this tensor's storage during its lifetime. Two tensor storages with
|
| 301 |
+
non-overlapping lifetimes may have the same id.
|
| 302 |
+
"""
|
| 303 |
+
if tensor.device.type == "xla" and is_torch_xla_available():
|
| 304 |
+
# NOTE: xla tensors dont have storage
|
| 305 |
+
# use some other unique id to distinguish.
|
| 306 |
+
# this is a XLA tensor, it must be created using torch_xla's
|
| 307 |
+
# device. So the following import is safe:
|
| 308 |
+
import torch_xla
|
| 309 |
+
|
| 310 |
+
unique_id = torch_xla._XLAC._xla_get_tensor_id(tensor)
|
| 311 |
+
else:
|
| 312 |
+
unique_id = storage_ptr(tensor)
|
| 313 |
+
|
| 314 |
+
return tensor.device, unique_id, storage_size(tensor)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def isin_mps_friendly(elements: torch.Tensor, test_elements: torch.Tensor | int) -> torch.Tensor:
|
| 318 |
+
"""
|
| 319 |
+
Same as `torch.isin` without flags, but MPS-friendly. We can remove this function when we stop supporting
|
| 320 |
+
torch <= 2.3. See https://github.com/pytorch/pytorch/issues/77764#issuecomment-2067838075
|
| 321 |
+
|
| 322 |
+
Args:
|
| 323 |
+
elements (`torch.Tensor`): Input elements
|
| 324 |
+
test_elements (`torch.Tensor` or `int`): The elements to check against.
|
| 325 |
+
|
| 326 |
+
Returns:
|
| 327 |
+
`torch.Tensor`: A boolean tensor of the same shape as `elements` that is True for `elements` in `test_elements`
|
| 328 |
+
and False otherwise
|
| 329 |
+
"""
|
| 330 |
+
|
| 331 |
+
if elements.device.type == "mps" and not is_torch_greater_or_equal_than_2_4:
|
| 332 |
+
test_elements = torch.tensor(test_elements)
|
| 333 |
+
if test_elements.ndim == 0:
|
| 334 |
+
test_elements = test_elements.unsqueeze(0)
|
| 335 |
+
return elements.tile(test_elements.shape[0], 1).eq(test_elements.unsqueeze(1)).sum(dim=0).bool().squeeze()
|
| 336 |
+
else:
|
| 337 |
+
# Note: don't use named arguments in `torch.isin`, see https://github.com/pytorch/pytorch/issues/126045
|
| 338 |
+
return torch.isin(elements, test_elements)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def translate_to_torch_parallel_style(style: str):
|
| 342 |
+
"""
|
| 343 |
+
In model configurations, we use a neutral type (string) to specify parallel
|
| 344 |
+
styles, here we translate them into torch.distributed tensor-parallel
|
| 345 |
+
types.
|
| 346 |
+
"""
|
| 347 |
+
if not isinstance(style, str):
|
| 348 |
+
raise ValueError(f"Unsupported parallel style type {type(style)}, expected str")
|
| 349 |
+
|
| 350 |
+
if style == "colwise":
|
| 351 |
+
return ColwiseParallel()
|
| 352 |
+
elif style == "rowwise":
|
| 353 |
+
return RowwiseParallel()
|
| 354 |
+
elif style == "colwise_rep":
|
| 355 |
+
return ColwiseParallel(output_layouts=Replicate())
|
| 356 |
+
else:
|
| 357 |
+
raise ValueError(f"Unsupported parallel style value: {style}")
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 |
+
from .auto import AutoHfQuantizer, AutoQuantizationConfig
|
| 15 |
+
from .base import HfQuantizer
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/auto.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 warnings
|
| 15 |
+
from typing import Dict, Optional, Union
|
| 16 |
+
|
| 17 |
+
from ..models.auto.configuration_auto import AutoConfig
|
| 18 |
+
from ..utils.quantization_config import (
|
| 19 |
+
AqlmConfig,
|
| 20 |
+
AwqConfig,
|
| 21 |
+
BitNetConfig,
|
| 22 |
+
BitsAndBytesConfig,
|
| 23 |
+
CompressedTensorsConfig,
|
| 24 |
+
EetqConfig,
|
| 25 |
+
FbgemmFp8Config,
|
| 26 |
+
GPTQConfig,
|
| 27 |
+
HiggsConfig,
|
| 28 |
+
HqqConfig,
|
| 29 |
+
QuantizationConfigMixin,
|
| 30 |
+
QuantizationMethod,
|
| 31 |
+
QuantoConfig,
|
| 32 |
+
TorchAoConfig,
|
| 33 |
+
VptqConfig,
|
| 34 |
+
)
|
| 35 |
+
from .quantizer_aqlm import AqlmHfQuantizer
|
| 36 |
+
from .quantizer_awq import AwqQuantizer
|
| 37 |
+
from .quantizer_bitnet import BitNetHfQuantizer
|
| 38 |
+
from .quantizer_bnb_4bit import Bnb4BitHfQuantizer
|
| 39 |
+
from .quantizer_bnb_8bit import Bnb8BitHfQuantizer
|
| 40 |
+
from .quantizer_compressed_tensors import CompressedTensorsHfQuantizer
|
| 41 |
+
from .quantizer_eetq import EetqHfQuantizer
|
| 42 |
+
from .quantizer_fbgemm_fp8 import FbgemmFp8HfQuantizer
|
| 43 |
+
from .quantizer_gptq import GptqHfQuantizer
|
| 44 |
+
from .quantizer_higgs import HiggsHfQuantizer
|
| 45 |
+
from .quantizer_hqq import HqqHfQuantizer
|
| 46 |
+
from .quantizer_quanto import QuantoHfQuantizer
|
| 47 |
+
from .quantizer_torchao import TorchAoHfQuantizer
|
| 48 |
+
from .quantizer_vptq import VptqHfQuantizer
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
AUTO_QUANTIZER_MAPPING = {
|
| 52 |
+
"awq": AwqQuantizer,
|
| 53 |
+
"bitsandbytes_4bit": Bnb4BitHfQuantizer,
|
| 54 |
+
"bitsandbytes_8bit": Bnb8BitHfQuantizer,
|
| 55 |
+
"gptq": GptqHfQuantizer,
|
| 56 |
+
"aqlm": AqlmHfQuantizer,
|
| 57 |
+
"quanto": QuantoHfQuantizer,
|
| 58 |
+
"eetq": EetqHfQuantizer,
|
| 59 |
+
"higgs": HiggsHfQuantizer,
|
| 60 |
+
"hqq": HqqHfQuantizer,
|
| 61 |
+
"compressed-tensors": CompressedTensorsHfQuantizer,
|
| 62 |
+
"fbgemm_fp8": FbgemmFp8HfQuantizer,
|
| 63 |
+
"torchao": TorchAoHfQuantizer,
|
| 64 |
+
"bitnet": BitNetHfQuantizer,
|
| 65 |
+
"vptq": VptqHfQuantizer,
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
AUTO_QUANTIZATION_CONFIG_MAPPING = {
|
| 69 |
+
"awq": AwqConfig,
|
| 70 |
+
"bitsandbytes_4bit": BitsAndBytesConfig,
|
| 71 |
+
"bitsandbytes_8bit": BitsAndBytesConfig,
|
| 72 |
+
"eetq": EetqConfig,
|
| 73 |
+
"gptq": GPTQConfig,
|
| 74 |
+
"aqlm": AqlmConfig,
|
| 75 |
+
"quanto": QuantoConfig,
|
| 76 |
+
"hqq": HqqConfig,
|
| 77 |
+
"compressed-tensors": CompressedTensorsConfig,
|
| 78 |
+
"fbgemm_fp8": FbgemmFp8Config,
|
| 79 |
+
"higgs": HiggsConfig,
|
| 80 |
+
"torchao": TorchAoConfig,
|
| 81 |
+
"bitnet": BitNetConfig,
|
| 82 |
+
"vptq": VptqConfig,
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class AutoQuantizationConfig:
|
| 87 |
+
"""
|
| 88 |
+
The Auto-HF quantization config class that takes care of automatically dispatching to the correct
|
| 89 |
+
quantization config given a quantization config stored in a dictionary.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
@classmethod
|
| 93 |
+
def from_dict(cls, quantization_config_dict: Dict):
|
| 94 |
+
quant_method = quantization_config_dict.get("quant_method", None)
|
| 95 |
+
# We need a special care for bnb models to make sure everything is BC ..
|
| 96 |
+
if quantization_config_dict.get("load_in_8bit", False) or quantization_config_dict.get("load_in_4bit", False):
|
| 97 |
+
suffix = "_4bit" if quantization_config_dict.get("load_in_4bit", False) else "_8bit"
|
| 98 |
+
quant_method = QuantizationMethod.BITS_AND_BYTES + suffix
|
| 99 |
+
elif quant_method is None:
|
| 100 |
+
raise ValueError(
|
| 101 |
+
"The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized"
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
if quant_method not in AUTO_QUANTIZATION_CONFIG_MAPPING.keys():
|
| 105 |
+
raise ValueError(
|
| 106 |
+
f"Unknown quantization type, got {quant_method} - supported types are:"
|
| 107 |
+
f" {list(AUTO_QUANTIZER_MAPPING.keys())}"
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
target_cls = AUTO_QUANTIZATION_CONFIG_MAPPING[quant_method]
|
| 111 |
+
return target_cls.from_dict(quantization_config_dict)
|
| 112 |
+
|
| 113 |
+
@classmethod
|
| 114 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 115 |
+
model_config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
|
| 116 |
+
if getattr(model_config, "quantization_config", None) is None:
|
| 117 |
+
raise ValueError(
|
| 118 |
+
f"Did not found a `quantization_config` in {pretrained_model_name_or_path}. Make sure that the model is correctly quantized."
|
| 119 |
+
)
|
| 120 |
+
quantization_config_dict = model_config.quantization_config
|
| 121 |
+
quantization_config = cls.from_dict(quantization_config_dict)
|
| 122 |
+
# Update with potential kwargs that are passed through from_pretrained.
|
| 123 |
+
quantization_config.update(**kwargs)
|
| 124 |
+
return quantization_config
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class AutoHfQuantizer:
|
| 128 |
+
"""
|
| 129 |
+
The Auto-HF quantizer class that takes care of automatically instantiating to the correct
|
| 130 |
+
`HfQuantizer` given the `QuantizationConfig`.
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
@classmethod
|
| 134 |
+
def from_config(cls, quantization_config: Union[QuantizationConfigMixin, Dict], **kwargs):
|
| 135 |
+
# Convert it to a QuantizationConfig if the q_config is a dict
|
| 136 |
+
if isinstance(quantization_config, dict):
|
| 137 |
+
quantization_config = AutoQuantizationConfig.from_dict(quantization_config)
|
| 138 |
+
|
| 139 |
+
quant_method = quantization_config.quant_method
|
| 140 |
+
|
| 141 |
+
# Again, we need a special care for bnb as we have a single quantization config
|
| 142 |
+
# class for both 4-bit and 8-bit quantization
|
| 143 |
+
if quant_method == QuantizationMethod.BITS_AND_BYTES:
|
| 144 |
+
if quantization_config.load_in_8bit:
|
| 145 |
+
quant_method += "_8bit"
|
| 146 |
+
else:
|
| 147 |
+
quant_method += "_4bit"
|
| 148 |
+
|
| 149 |
+
if quant_method not in AUTO_QUANTIZER_MAPPING.keys():
|
| 150 |
+
raise ValueError(
|
| 151 |
+
f"Unknown quantization type, got {quant_method} - supported types are:"
|
| 152 |
+
f" {list(AUTO_QUANTIZER_MAPPING.keys())}"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
target_cls = AUTO_QUANTIZER_MAPPING[quant_method]
|
| 156 |
+
return target_cls(quantization_config, **kwargs)
|
| 157 |
+
|
| 158 |
+
@classmethod
|
| 159 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 160 |
+
quantization_config = AutoQuantizationConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
|
| 161 |
+
return cls.from_config(quantization_config)
|
| 162 |
+
|
| 163 |
+
@classmethod
|
| 164 |
+
def merge_quantization_configs(
|
| 165 |
+
cls,
|
| 166 |
+
quantization_config: Union[dict, QuantizationConfigMixin],
|
| 167 |
+
quantization_config_from_args: Optional[QuantizationConfigMixin],
|
| 168 |
+
):
|
| 169 |
+
"""
|
| 170 |
+
handles situations where both quantization_config from args and quantization_config from model config are present.
|
| 171 |
+
"""
|
| 172 |
+
if quantization_config_from_args is not None:
|
| 173 |
+
warning_msg = (
|
| 174 |
+
"You passed `quantization_config` or equivalent parameters to `from_pretrained` but the model you're loading"
|
| 175 |
+
" already has a `quantization_config` attribute. The `quantization_config` from the model will be used."
|
| 176 |
+
)
|
| 177 |
+
else:
|
| 178 |
+
warning_msg = ""
|
| 179 |
+
|
| 180 |
+
if isinstance(quantization_config, dict):
|
| 181 |
+
quantization_config = AutoQuantizationConfig.from_dict(quantization_config)
|
| 182 |
+
|
| 183 |
+
if (
|
| 184 |
+
isinstance(quantization_config, (GPTQConfig, AwqConfig, FbgemmFp8Config, CompressedTensorsConfig))
|
| 185 |
+
and quantization_config_from_args is not None
|
| 186 |
+
):
|
| 187 |
+
# special case for GPTQ / AWQ / FbgemmFp8 config collision
|
| 188 |
+
loading_attr_dict = quantization_config_from_args.get_loading_attributes()
|
| 189 |
+
for attr, val in loading_attr_dict.items():
|
| 190 |
+
setattr(quantization_config, attr, val)
|
| 191 |
+
|
| 192 |
+
warning_msg += f"However, loading attributes (e.g. {list(loading_attr_dict.keys())}) will be overwritten with the one you passed to `from_pretrained`. The rest will be ignored."
|
| 193 |
+
|
| 194 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 |
+
from abc import ABC, abstractmethod
|
| 15 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
|
| 16 |
+
|
| 17 |
+
from ..utils import is_torch_available
|
| 18 |
+
from ..utils.quantization_config import QuantizationConfigMixin
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from ..modeling_utils import PreTrainedModel
|
| 23 |
+
|
| 24 |
+
if is_torch_available():
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class HfQuantizer(ABC):
|
| 29 |
+
"""
|
| 30 |
+
Abstract class of the HuggingFace quantizer. Supports for now quantizing HF transformers models for inference and/or quantization.
|
| 31 |
+
This class is used only for transformers.PreTrainedModel.from_pretrained and cannot be easily used outside the scope of that method
|
| 32 |
+
yet.
|
| 33 |
+
|
| 34 |
+
Attributes
|
| 35 |
+
quantization_config (`transformers.utils.quantization_config.QuantizationConfigMixin`):
|
| 36 |
+
The quantization config that defines the quantization parameters of your model that you want to quantize.
|
| 37 |
+
modules_to_not_convert (`List[str]`, *optional*):
|
| 38 |
+
The list of module names to not convert when quantizing the model.
|
| 39 |
+
required_packages (`List[str]`, *optional*):
|
| 40 |
+
The list of required pip packages to install prior to using the quantizer
|
| 41 |
+
requires_calibration (`bool`):
|
| 42 |
+
Whether the quantization method requires to calibrate the model before using it.
|
| 43 |
+
requires_parameters_quantization (`bool`):
|
| 44 |
+
Whether the quantization method requires to create a new Parameter. For example, for bitsandbytes, it is
|
| 45 |
+
required to create a new xxxParameter in order to properly quantize the model.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
requires_calibration = False
|
| 49 |
+
required_packages = None
|
| 50 |
+
requires_parameters_quantization = False
|
| 51 |
+
|
| 52 |
+
def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
|
| 53 |
+
self.quantization_config = quantization_config
|
| 54 |
+
|
| 55 |
+
# -- Handle extra kwargs below --
|
| 56 |
+
self.modules_to_not_convert = kwargs.pop("modules_to_not_convert", [])
|
| 57 |
+
self.pre_quantized = kwargs.pop("pre_quantized", True)
|
| 58 |
+
|
| 59 |
+
if not self.pre_quantized and self.requires_calibration:
|
| 60 |
+
raise ValueError(
|
| 61 |
+
f"The quantization method {quantization_config.quant_method} does require the model to be pre-quantized."
|
| 62 |
+
f" You explicitly passed `pre_quantized=False` meaning your model weights are not quantized. Make sure to "
|
| 63 |
+
f"pass `pre_quantized=True` while knowing what you are doing."
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 67 |
+
"""
|
| 68 |
+
Some quantization methods require to explicitly set the dtype of the model to a
|
| 69 |
+
target dtype. You need to override this method in case you want to make sure that behavior is
|
| 70 |
+
preserved
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
torch_dtype (`torch.dtype`):
|
| 74 |
+
The input dtype that is passed in `from_pretrained`
|
| 75 |
+
"""
|
| 76 |
+
return torch_dtype
|
| 77 |
+
|
| 78 |
+
def update_device_map(self, device_map: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
| 79 |
+
"""
|
| 80 |
+
Override this method if you want to pass a override the existing device map with a new
|
| 81 |
+
one. E.g. for bitsandbytes, since `accelerate` is a hard requirement, if no device_map is
|
| 82 |
+
passed, the device_map is set to `"auto"``
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
device_map (`Union[dict, str]`, *optional*):
|
| 86 |
+
The device_map that is passed through the `from_pretrained` method.
|
| 87 |
+
"""
|
| 88 |
+
return device_map
|
| 89 |
+
|
| 90 |
+
def adjust_target_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 91 |
+
"""
|
| 92 |
+
Override this method if you want to adjust the `target_dtype` variable used in `from_pretrained`
|
| 93 |
+
to compute the device_map in case the device_map is a `str`. E.g. for bitsandbytes we force-set `target_dtype`
|
| 94 |
+
to `torch.int8` and for 4-bit we pass a custom enum `accelerate.CustomDtype.int4`.
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
torch_dtype (`torch.dtype`, *optional*):
|
| 98 |
+
The torch_dtype that is used to compute the device_map.
|
| 99 |
+
"""
|
| 100 |
+
return torch_dtype
|
| 101 |
+
|
| 102 |
+
def update_missing_keys(self, model, missing_keys: List[str], prefix: str) -> List[str]:
|
| 103 |
+
"""
|
| 104 |
+
Override this method if you want to adjust the `missing_keys`.
|
| 105 |
+
|
| 106 |
+
Args:
|
| 107 |
+
missing_keys (`List[str]`, *optional*):
|
| 108 |
+
The list of missing keys in the checkpoint compared to the state dict of the model
|
| 109 |
+
"""
|
| 110 |
+
return missing_keys
|
| 111 |
+
|
| 112 |
+
def update_expected_keys(self, model, expected_keys: List[str], loaded_keys: List[str]) -> List[str]:
|
| 113 |
+
"""
|
| 114 |
+
Override this method if you want to adjust the `update_expected_keys`.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
expected_keys (`List[str]`, *optional*):
|
| 118 |
+
The list of the expected keys in the initialized model.
|
| 119 |
+
loaded_keys (`List[str]`, *optional*):
|
| 120 |
+
The list of the loaded keys in the checkpoint.
|
| 121 |
+
"""
|
| 122 |
+
return expected_keys
|
| 123 |
+
|
| 124 |
+
def get_special_dtypes_update(self, model, torch_dtype: "torch.dtype") -> Dict[str, "torch.dtype"]:
|
| 125 |
+
"""
|
| 126 |
+
returns dtypes for modules that are not quantized - used for the computation of the device_map in case
|
| 127 |
+
one passes a str as a device_map. The method will use the `modules_to_not_convert` that is modified
|
| 128 |
+
in `_process_model_before_weight_loading`.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
model (`~transformers.PreTrainedModel`):
|
| 132 |
+
The model to quantize
|
| 133 |
+
torch_dtype (`torch.dtype`):
|
| 134 |
+
The dtype passed in `from_pretrained` method.
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
return {
|
| 138 |
+
name: torch_dtype
|
| 139 |
+
for name, _ in model.named_parameters()
|
| 140 |
+
if any(m in name for m in self.modules_to_not_convert)
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
|
| 144 |
+
"""adjust max_memory argument for infer_auto_device_map() if extra memory is needed for quantization"""
|
| 145 |
+
return max_memory
|
| 146 |
+
|
| 147 |
+
def check_quantized_param(
|
| 148 |
+
self,
|
| 149 |
+
model: "PreTrainedModel",
|
| 150 |
+
param_value: "torch.Tensor",
|
| 151 |
+
param_name: str,
|
| 152 |
+
state_dict: Dict[str, Any],
|
| 153 |
+
**kwargs,
|
| 154 |
+
) -> bool:
|
| 155 |
+
"""
|
| 156 |
+
checks if a loaded state_dict component is part of quantized param + some validation; only defined if
|
| 157 |
+
requires_parameters_quantization == True for quantization methods that require to create a new parameters
|
| 158 |
+
for quantization.
|
| 159 |
+
"""
|
| 160 |
+
return False
|
| 161 |
+
|
| 162 |
+
def create_quantized_param(self, *args, **kwargs) -> "torch.nn.Parameter":
|
| 163 |
+
"""
|
| 164 |
+
takes needed components from state_dict and creates quantized param; only applicable if
|
| 165 |
+
requires_parameters_quantization == True
|
| 166 |
+
"""
|
| 167 |
+
if not self.requires_parameters_quantization:
|
| 168 |
+
raise AttributeError(
|
| 169 |
+
f"`.create_quantized_param()` method is not supported by quantizer class {self.__class__.__name__}."
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
def validate_environment(self, *args, **kwargs):
|
| 173 |
+
"""
|
| 174 |
+
This method is used to potentially check for potential conflicts with arguments that are
|
| 175 |
+
passed in `from_pretrained`. You need to define it for all future quantizers that are integrated with transformers.
|
| 176 |
+
If no explicit check are needed, simply return nothing.
|
| 177 |
+
"""
|
| 178 |
+
return
|
| 179 |
+
|
| 180 |
+
def preprocess_model(self, model: "PreTrainedModel", **kwargs):
|
| 181 |
+
"""
|
| 182 |
+
Setting model attributes and/or converting model before weights loading. At this point
|
| 183 |
+
the model should be initialized on the meta device so you can freely manipulate the skeleton
|
| 184 |
+
of the model in order to replace modules in-place. Make sure to override the abstract method `_process_model_before_weight_loading`.
|
| 185 |
+
|
| 186 |
+
Args:
|
| 187 |
+
model (`~transformers.PreTrainedModel`):
|
| 188 |
+
The model to quantize
|
| 189 |
+
kwargs (`dict`, *optional*):
|
| 190 |
+
The keyword arguments that are passed along `_process_model_before_weight_loading`.
|
| 191 |
+
"""
|
| 192 |
+
model.is_quantized = True
|
| 193 |
+
model.quantization_method = self.quantization_config.quant_method
|
| 194 |
+
return self._process_model_before_weight_loading(model, **kwargs)
|
| 195 |
+
|
| 196 |
+
def postprocess_model(self, model: "PreTrainedModel", **kwargs):
|
| 197 |
+
"""
|
| 198 |
+
Post-process the model post weights loading.
|
| 199 |
+
Make sure to override the abstract method `_process_model_after_weight_loading`.
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
model (`~transformers.PreTrainedModel`):
|
| 203 |
+
The model to quantize
|
| 204 |
+
kwargs (`dict`, *optional*):
|
| 205 |
+
The keyword arguments that are passed along `_process_model_after_weight_loading`.
|
| 206 |
+
"""
|
| 207 |
+
return self._process_model_after_weight_loading(model, **kwargs)
|
| 208 |
+
|
| 209 |
+
def dequantize(self, model):
|
| 210 |
+
"""
|
| 211 |
+
Potentially dequantize the model to retrive the original model, with some loss in accuracy / performance.
|
| 212 |
+
Note not all quantization schemes support this.
|
| 213 |
+
"""
|
| 214 |
+
model = self._dequantize(model)
|
| 215 |
+
|
| 216 |
+
# Delete quantizer and quantization config
|
| 217 |
+
del model.hf_quantizer
|
| 218 |
+
del model.config.quantization_config
|
| 219 |
+
del model.config._pre_quantization_dtype
|
| 220 |
+
model.is_quantized = False
|
| 221 |
+
|
| 222 |
+
return model
|
| 223 |
+
|
| 224 |
+
def _dequantize(self, model):
|
| 225 |
+
raise NotImplementedError(
|
| 226 |
+
f"{self.quantization_config.quant_method} has no implementation of `dequantize`, please raise an issue on GitHub."
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
@property
|
| 230 |
+
def is_qat_trainable(self) -> bool:
|
| 231 |
+
"""Flag indicating whether the quantized model can carry out quantization aware training"""
|
| 232 |
+
return False
|
| 233 |
+
|
| 234 |
+
@abstractmethod
|
| 235 |
+
def _process_model_before_weight_loading(self, model, **kwargs): ...
|
| 236 |
+
|
| 237 |
+
@abstractmethod
|
| 238 |
+
def _process_model_after_weight_loading(self, model, **kwargs): ...
|
| 239 |
+
|
| 240 |
+
@abstractmethod
|
| 241 |
+
def is_serializable(self, safe_serialization=None): ...
|
| 242 |
+
|
| 243 |
+
@property
|
| 244 |
+
@abstractmethod
|
| 245 |
+
def is_trainable(self): ...
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_aqlm.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 importlib
|
| 15 |
+
from typing import TYPE_CHECKING, Optional
|
| 16 |
+
|
| 17 |
+
from packaging import version
|
| 18 |
+
|
| 19 |
+
from .base import HfQuantizer
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from ..modeling_utils import PreTrainedModel
|
| 24 |
+
|
| 25 |
+
from ..integrations import replace_with_aqlm_linear
|
| 26 |
+
from ..utils import is_accelerate_available, is_aqlm_available, is_torch_available, logging
|
| 27 |
+
from ..utils.quantization_config import QuantizationConfigMixin
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_torch_available():
|
| 31 |
+
import torch
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class AqlmHfQuantizer(HfQuantizer):
|
| 37 |
+
"""
|
| 38 |
+
Quantizer of the AQLM method. Enables the loading of prequantized models.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
requires_calibration = True
|
| 42 |
+
required_packages = ["aqlm"]
|
| 43 |
+
optimum_quantizer = None
|
| 44 |
+
|
| 45 |
+
def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
|
| 46 |
+
super().__init__(quantization_config, **kwargs)
|
| 47 |
+
self.quantization_config = quantization_config
|
| 48 |
+
|
| 49 |
+
def validate_environment(self, *args, **kwargs):
|
| 50 |
+
if not is_accelerate_available():
|
| 51 |
+
raise ImportError("Using `aqlm` quantization requires Accelerate: `pip install accelerate`")
|
| 52 |
+
|
| 53 |
+
if not is_aqlm_available():
|
| 54 |
+
raise ImportError("Using `aqlm` quantization requires AQLM: `pip install aqlm[gpu,cpu]`")
|
| 55 |
+
|
| 56 |
+
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 57 |
+
if torch_dtype is None:
|
| 58 |
+
if torch.cuda.is_available():
|
| 59 |
+
torch_dtype = torch.float16
|
| 60 |
+
logger.info(
|
| 61 |
+
"CUDA available. Assuming AQLM inference on GPU and loading the model in `torch.float16`. To overwrite it, set `torch_dtype` manually."
|
| 62 |
+
)
|
| 63 |
+
else:
|
| 64 |
+
torch_dtype = torch.float32
|
| 65 |
+
logger.info(
|
| 66 |
+
"CUDA is unavailable. Assuming AQLM inference on CPU and loading the model in `torch.float32`. To overwrite it, set `torch_dtype` manually."
|
| 67 |
+
)
|
| 68 |
+
return torch_dtype
|
| 69 |
+
|
| 70 |
+
def _process_model_before_weight_loading(
|
| 71 |
+
self,
|
| 72 |
+
model: "PreTrainedModel",
|
| 73 |
+
**kwargs,
|
| 74 |
+
):
|
| 75 |
+
replace_with_aqlm_linear(
|
| 76 |
+
model,
|
| 77 |
+
quantization_config=self.quantization_config,
|
| 78 |
+
linear_weights_not_to_quantize=self.quantization_config.linear_weights_not_to_quantize,
|
| 79 |
+
)
|
| 80 |
+
model.config.quantization_config = self.quantization_config
|
| 81 |
+
|
| 82 |
+
def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
|
| 83 |
+
return model
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def is_trainable(self, model: Optional["PreTrainedModel"] = None):
|
| 87 |
+
aqlm_supports_training = version.parse(importlib.metadata.version("aqlm")) >= version.parse("1.0.2")
|
| 88 |
+
if aqlm_supports_training:
|
| 89 |
+
return True
|
| 90 |
+
else:
|
| 91 |
+
logger.warning(
|
| 92 |
+
f"Currently installed `aqlm` version ({importlib.metadata.version('aqlm')}) doesn't support training. If you wish to train a quantized model, please update `aqlm` with `pip install aqlm>=1.0.2`"
|
| 93 |
+
)
|
| 94 |
+
return False
|
| 95 |
+
|
| 96 |
+
def is_serializable(self, safe_serialization=None):
|
| 97 |
+
return True
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_awq.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 importlib.metadata
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from packaging import version
|
| 18 |
+
|
| 19 |
+
from .base import HfQuantizer
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from ..modeling_utils import PreTrainedModel
|
| 24 |
+
|
| 25 |
+
from ..utils import is_accelerate_available, is_auto_awq_available, is_torch_available, logging
|
| 26 |
+
from ..utils.quantization_config import AWQLinearVersion
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_torch_available():
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class AwqQuantizer(HfQuantizer):
|
| 36 |
+
"""
|
| 37 |
+
4-bit quantization for Activation-aware Weight Quantization(AWQ) (https://arxiv.org/abs/2306.00978)
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
# AWQ requires data callibration - we support only inference
|
| 41 |
+
requires_calibration = True
|
| 42 |
+
|
| 43 |
+
required_packages = ["awq", "accelerate"]
|
| 44 |
+
|
| 45 |
+
def __init__(self, quantization_config, **kwargs):
|
| 46 |
+
super().__init__(quantization_config, **kwargs)
|
| 47 |
+
|
| 48 |
+
def validate_environment(self, device_map, **kwargs):
|
| 49 |
+
if not is_auto_awq_available():
|
| 50 |
+
raise ImportError("Loading an AWQ quantized model requires auto-awq library (`pip install autoawq`)")
|
| 51 |
+
|
| 52 |
+
if not is_accelerate_available():
|
| 53 |
+
raise ImportError("Loading an AWQ quantized model requires accelerate (`pip install accelerate`)")
|
| 54 |
+
|
| 55 |
+
if self.quantization_config.version == AWQLinearVersion.IPEX:
|
| 56 |
+
if version.parse(importlib.metadata.version("autoawq")) < version.parse("0.2.6"):
|
| 57 |
+
raise RuntimeError(
|
| 58 |
+
"To use IPEX backend, you need autoawq>0.6.2. Please install the latest version or from source."
|
| 59 |
+
)
|
| 60 |
+
if device_map is None:
|
| 61 |
+
logger.warning_once(
|
| 62 |
+
"You have loaded an AWQ model without setting device_map, please set 'cpu' or 'xpu' or 'auto'"
|
| 63 |
+
)
|
| 64 |
+
elif isinstance(device_map, dict) and "disk" in device_map.values():
|
| 65 |
+
raise ValueError(
|
| 66 |
+
"You are attempting to load an IPEX version AWQ model with a device_map that contains disk device."
|
| 67 |
+
" This is not supported. Please make sure only cpu and xpu in the device_map."
|
| 68 |
+
)
|
| 69 |
+
else:
|
| 70 |
+
if not torch.cuda.is_available():
|
| 71 |
+
raise RuntimeError(
|
| 72 |
+
"GPU is required to run AWQ quantized model. You can use IPEX version AWQ if you have an Intel CPU"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
if device_map is None:
|
| 76 |
+
logger.warning_once(
|
| 77 |
+
"You have loaded an AWQ model on CPU and have a CUDA device available, make sure to set "
|
| 78 |
+
"your model on a GPU device in order to run your model."
|
| 79 |
+
)
|
| 80 |
+
elif device_map is not None:
|
| 81 |
+
if isinstance(device_map, dict) and ("cpu" in device_map.values() or "disk" in device_map.values()):
|
| 82 |
+
raise ValueError(
|
| 83 |
+
"You are attempting to load an AWQ model with a device_map that contains a CPU or disk device."
|
| 84 |
+
" This is not supported. Please remove the CPU or disk device from the device_map."
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
def update_torch_dtype(self, torch_dtype):
|
| 88 |
+
if torch_dtype is None:
|
| 89 |
+
torch_dtype = torch.float16
|
| 90 |
+
logger.info("Loading the model in `torch.float16`. To overwrite it, set `torch_dtype` manually.")
|
| 91 |
+
elif torch_dtype != torch.float16:
|
| 92 |
+
logger.warning("We suggest you to set `torch_dtype=torch.float16` for better efficiency with AWQ.")
|
| 93 |
+
return torch_dtype
|
| 94 |
+
|
| 95 |
+
def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs):
|
| 96 |
+
from ..integrations import get_keys_to_not_convert, replace_quantization_scales, replace_with_awq_linear
|
| 97 |
+
|
| 98 |
+
self.modules_to_not_convert = get_keys_to_not_convert(model)
|
| 99 |
+
|
| 100 |
+
if self.quantization_config.modules_to_not_convert is not None:
|
| 101 |
+
self.modules_to_not_convert.extend(self.quantization_config.modules_to_not_convert)
|
| 102 |
+
|
| 103 |
+
model, has_been_replaced = replace_with_awq_linear(
|
| 104 |
+
model, quantization_config=self.quantization_config, modules_to_not_convert=self.modules_to_not_convert
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
model = replace_quantization_scales(model, model.config.model_type)
|
| 108 |
+
|
| 109 |
+
if not has_been_replaced:
|
| 110 |
+
logger.warning(
|
| 111 |
+
"You are loading an AWQ model but no linear modules were found in your model."
|
| 112 |
+
" Please double check your model architecture, or submit an issue on github if you think this is a bug."
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def _process_model_after_weight_loading(self, model, **kwargs):
|
| 116 |
+
if self.quantization_config.do_fuse:
|
| 117 |
+
from ..integrations import fuse_awq_modules
|
| 118 |
+
|
| 119 |
+
model = fuse_awq_modules(model, self.quantization_config)
|
| 120 |
+
model._awq_is_fused = True # TODO: consider storing this flag in model.config instead
|
| 121 |
+
|
| 122 |
+
if self.quantization_config.version == AWQLinearVersion.EXLLAMA:
|
| 123 |
+
from ..integrations import post_init_awq_exllama_modules
|
| 124 |
+
|
| 125 |
+
model = post_init_awq_exllama_modules(model, self.quantization_config.exllama_config)
|
| 126 |
+
|
| 127 |
+
if self.quantization_config.version == AWQLinearVersion.IPEX:
|
| 128 |
+
from ..integrations import post_init_awq_ipex_modules
|
| 129 |
+
|
| 130 |
+
model = post_init_awq_ipex_modules(model)
|
| 131 |
+
|
| 132 |
+
def is_serializable(self, safe_serialization=None):
|
| 133 |
+
# AWQ through auto-awq has been always serializable, except if the model is fused.
|
| 134 |
+
if self.quantization_config.do_fuse:
|
| 135 |
+
logger.warning("You cannot save an AWQ model that uses fused modules!")
|
| 136 |
+
return False
|
| 137 |
+
|
| 138 |
+
if self.quantization_config.version == AWQLinearVersion.EXLLAMA:
|
| 139 |
+
logger.warning("You cannot save an AWQ model that uses Exllama backend!")
|
| 140 |
+
return False
|
| 141 |
+
|
| 142 |
+
return True
|
| 143 |
+
|
| 144 |
+
@property
|
| 145 |
+
def is_trainable(self):
|
| 146 |
+
# AWQ supports PEFT fine-tuning from version 0.2.0
|
| 147 |
+
MIN_AWQ_VERSION_FOR_PEFT = "0.2.0"
|
| 148 |
+
return version.parse(importlib.metadata.version("autoawq")) >= version.parse(MIN_AWQ_VERSION_FOR_PEFT)
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_bitnet.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 |
+
from typing import TYPE_CHECKING, Dict, List, Union
|
| 15 |
+
|
| 16 |
+
from .base import HfQuantizer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from ..modeling_utils import PreTrainedModel
|
| 21 |
+
|
| 22 |
+
from ..utils import is_accelerate_available, is_torch_available, logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if is_torch_available():
|
| 26 |
+
import torch
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class BitNetHfQuantizer(HfQuantizer):
|
| 33 |
+
"""
|
| 34 |
+
1.58-bit quantization from BitNet quantization method:
|
| 35 |
+
Before loading: it converts the linear layers into BitLinear layers during loading.
|
| 36 |
+
|
| 37 |
+
Checkout the paper introducing this method : https://arxiv.org/pdf/2402.17764
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
requires_parameters_quantization = False
|
| 41 |
+
requires_calibration = True
|
| 42 |
+
|
| 43 |
+
required_packages = ["accelerate"]
|
| 44 |
+
|
| 45 |
+
def __init__(self, quantization_config, **kwargs):
|
| 46 |
+
super().__init__(quantization_config, **kwargs)
|
| 47 |
+
self.quantization_config = quantization_config
|
| 48 |
+
|
| 49 |
+
def validate_environment(self, *args, **kwargs):
|
| 50 |
+
if not is_accelerate_available():
|
| 51 |
+
raise ImportError("Loading a BitNet quantized model requires accelerate (`pip install accelerate`)")
|
| 52 |
+
|
| 53 |
+
if kwargs.get("from_tf", False) or kwargs.get("from_flax", False):
|
| 54 |
+
raise ValueError(
|
| 55 |
+
"Loading ternary weights from tf/flax is currently not supported, please make"
|
| 56 |
+
" sure the weights are in PyTorch format."
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
if not torch.cuda.is_available():
|
| 60 |
+
logger.warning_once(
|
| 61 |
+
"You don't have a GPU available to load the model, the inference will be slow because of weight unpacking"
|
| 62 |
+
)
|
| 63 |
+
return
|
| 64 |
+
|
| 65 |
+
device_map = kwargs.get("device_map", None)
|
| 66 |
+
if device_map is None:
|
| 67 |
+
logger.warning_once(
|
| 68 |
+
"You have loaded a BitNet model on CPU and have a CUDA device available, make sure to set "
|
| 69 |
+
"your model on a GPU device in order to run your model."
|
| 70 |
+
)
|
| 71 |
+
elif device_map is not None:
|
| 72 |
+
if isinstance(device_map, dict) and ("cpu" in device_map.values() or "disk" in device_map.values()):
|
| 73 |
+
raise ValueError(
|
| 74 |
+
"You are attempting to load a BitNet model with a device_map that contains a CPU or disk device."
|
| 75 |
+
"This is not supported. Please remove the CPU or disk device from the device_map."
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
|
| 79 |
+
return model
|
| 80 |
+
|
| 81 |
+
def _process_model_before_weight_loading(
|
| 82 |
+
self,
|
| 83 |
+
model: "PreTrainedModel",
|
| 84 |
+
device_map,
|
| 85 |
+
keep_in_fp32_modules: List[str] = [],
|
| 86 |
+
**kwargs,
|
| 87 |
+
):
|
| 88 |
+
from ..integrations import get_keys_to_not_convert, replace_with_bitnet_linear
|
| 89 |
+
|
| 90 |
+
self.modules_to_not_convert = get_keys_to_not_convert(model)
|
| 91 |
+
|
| 92 |
+
if self.quantization_config.modules_to_not_convert is not None:
|
| 93 |
+
self.modules_to_not_convert.extend(self.quantization_config.modules_to_not_convert)
|
| 94 |
+
|
| 95 |
+
model = replace_with_bitnet_linear(
|
| 96 |
+
model,
|
| 97 |
+
modules_to_not_convert=self.modules_to_not_convert,
|
| 98 |
+
quantization_config=self.quantization_config,
|
| 99 |
+
pre_quantized=self.pre_quantized,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
|
| 103 |
+
max_memory = {key: val * 0.90 for key, val in max_memory.items()}
|
| 104 |
+
return max_memory
|
| 105 |
+
|
| 106 |
+
def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
|
| 107 |
+
target_dtype = torch.int8
|
| 108 |
+
return target_dtype
|
| 109 |
+
|
| 110 |
+
def is_serializable(self, safe_serialization=None):
|
| 111 |
+
return True
|
| 112 |
+
|
| 113 |
+
@property
|
| 114 |
+
def is_trainable(self) -> bool:
|
| 115 |
+
return False
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_bnb_4bit.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 importlib
|
| 15 |
+
from functools import cached_property
|
| 16 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
|
| 17 |
+
|
| 18 |
+
from packaging import version
|
| 19 |
+
|
| 20 |
+
from .base import HfQuantizer
|
| 21 |
+
from .quantizers_utils import get_module_from_name
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if TYPE_CHECKING:
|
| 25 |
+
from ..modeling_utils import PreTrainedModel
|
| 26 |
+
|
| 27 |
+
from ..utils import (
|
| 28 |
+
ACCELERATE_MIN_VERSION,
|
| 29 |
+
is_accelerate_available,
|
| 30 |
+
is_bitsandbytes_available,
|
| 31 |
+
is_torch_available,
|
| 32 |
+
is_torch_npu_available,
|
| 33 |
+
is_torch_xpu_available,
|
| 34 |
+
logging,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if is_torch_available():
|
| 39 |
+
import torch
|
| 40 |
+
|
| 41 |
+
from ..pytorch_utils import Conv1D
|
| 42 |
+
|
| 43 |
+
logger = logging.get_logger(__name__)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class Bnb4BitHfQuantizer(HfQuantizer):
|
| 47 |
+
"""
|
| 48 |
+
4-bit quantization from bitsandbytes.py quantization method:
|
| 49 |
+
before loading: converts transformer layers into Linear4bit during loading: load 16bit weight and pass to the
|
| 50 |
+
layer object after: quantizes individual weights in Linear4bit into 4bit at the first .cuda() call
|
| 51 |
+
saving:
|
| 52 |
+
from state dict, as usual; saves weights and `quant_state` components
|
| 53 |
+
loading:
|
| 54 |
+
need to locate `quant_state` components and pass to Param4bit constructor
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
use_keep_in_fp32_modules = True
|
| 58 |
+
requires_parameters_quantization = True
|
| 59 |
+
requires_calibration = False
|
| 60 |
+
|
| 61 |
+
required_packages = ["bitsandbytes", "accelerate"]
|
| 62 |
+
|
| 63 |
+
def __init__(self, quantization_config, **kwargs):
|
| 64 |
+
super().__init__(quantization_config, **kwargs)
|
| 65 |
+
|
| 66 |
+
if self.quantization_config.llm_int8_skip_modules is not None:
|
| 67 |
+
self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
|
| 68 |
+
|
| 69 |
+
def validate_environment(self, *args, **kwargs):
|
| 70 |
+
if not is_accelerate_available():
|
| 71 |
+
raise ImportError(
|
| 72 |
+
f"Using `bitsandbytes` 4-bit quantization requires Accelerate: `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`"
|
| 73 |
+
)
|
| 74 |
+
if not is_bitsandbytes_available():
|
| 75 |
+
raise ImportError(
|
| 76 |
+
"Using `bitsandbytes` 4-bit quantization requires the latest version of bitsandbytes: `pip install -U bitsandbytes`"
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
from ..integrations import validate_bnb_backend_availability
|
| 80 |
+
from ..utils import is_bitsandbytes_multi_backend_available
|
| 81 |
+
|
| 82 |
+
bnb_multibackend_is_enabled = is_bitsandbytes_multi_backend_available()
|
| 83 |
+
validate_bnb_backend_availability(raise_exception=True)
|
| 84 |
+
|
| 85 |
+
if kwargs.get("from_tf", False) or kwargs.get("from_flax", False):
|
| 86 |
+
raise ValueError(
|
| 87 |
+
"Converting into 4-bit or 8-bit weights from tf/flax weights is currently not supported, please make"
|
| 88 |
+
" sure the weights are in PyTorch format."
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
device_map = kwargs.get("device_map", None)
|
| 92 |
+
if (
|
| 93 |
+
device_map is not None
|
| 94 |
+
and isinstance(device_map, dict)
|
| 95 |
+
and not self.quantization_config.llm_int8_enable_fp32_cpu_offload
|
| 96 |
+
):
|
| 97 |
+
device_map_without_lm_head = {
|
| 98 |
+
key: device_map[key] for key in device_map.keys() if key not in self.modules_to_not_convert
|
| 99 |
+
}
|
| 100 |
+
if set(device_map.values()) == {"cpu"} and bnb_multibackend_is_enabled:
|
| 101 |
+
pass
|
| 102 |
+
elif "cpu" in device_map_without_lm_head.values() or "disk" in device_map_without_lm_head.values():
|
| 103 |
+
raise ValueError(
|
| 104 |
+
"Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the "
|
| 105 |
+
"quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules "
|
| 106 |
+
"in 32-bit, you need to set `llm_int8_enable_fp32_cpu_offload=True` and pass a custom `device_map` to "
|
| 107 |
+
"`from_pretrained`. Check "
|
| 108 |
+
"https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu "
|
| 109 |
+
"for more details. "
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.39.0"):
|
| 113 |
+
raise ValueError(
|
| 114 |
+
"You have a version of `bitsandbytes` that is not compatible with 4bit inference and training"
|
| 115 |
+
" make sure you have the latest version of `bitsandbytes` installed"
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
|
| 119 |
+
if version.parse(importlib.metadata.version("accelerate")) > version.parse("0.19.0"):
|
| 120 |
+
from accelerate.utils import CustomDtype
|
| 121 |
+
|
| 122 |
+
if target_dtype != torch.int8:
|
| 123 |
+
logger.info("target_dtype {target_dtype} is replaced by `CustomDtype.INT4` for 4-bit BnB quantization")
|
| 124 |
+
return CustomDtype.INT4
|
| 125 |
+
else:
|
| 126 |
+
raise ValueError(
|
| 127 |
+
"You are using `device_map='auto'` on a 4bit loaded version of the model. To automatically compute"
|
| 128 |
+
" the appropriate device map, you should upgrade your `accelerate` library,"
|
| 129 |
+
"`pip install --upgrade accelerate` or install it from source to support fp4 auto device map"
|
| 130 |
+
"calculation. You may encounter unexpected behavior, or pass your own device map"
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
def check_quantized_param(
|
| 134 |
+
self,
|
| 135 |
+
model: "PreTrainedModel",
|
| 136 |
+
param_value: "torch.Tensor",
|
| 137 |
+
param_name: str,
|
| 138 |
+
state_dict: Dict[str, Any],
|
| 139 |
+
**kwargs,
|
| 140 |
+
) -> bool:
|
| 141 |
+
import bitsandbytes as bnb
|
| 142 |
+
|
| 143 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 144 |
+
if isinstance(module._parameters.get(tensor_name, None), bnb.nn.Params4bit):
|
| 145 |
+
# Add here check for loaded components' dtypes once serialization is implemented
|
| 146 |
+
return True
|
| 147 |
+
elif isinstance(module, bnb.nn.Linear4bit) and tensor_name == "bias":
|
| 148 |
+
# bias could be loaded by regular set_module_tensor_to_device() from accelerate,
|
| 149 |
+
# but it would wrongly use uninitialized weight there.
|
| 150 |
+
return True
|
| 151 |
+
else:
|
| 152 |
+
return False
|
| 153 |
+
|
| 154 |
+
def create_quantized_param(
|
| 155 |
+
self,
|
| 156 |
+
model: "PreTrainedModel",
|
| 157 |
+
param_value: "torch.Tensor",
|
| 158 |
+
param_name: str,
|
| 159 |
+
target_device: "torch.device",
|
| 160 |
+
state_dict: Dict[str, Any],
|
| 161 |
+
unexpected_keys: Optional[List[str]] = None,
|
| 162 |
+
):
|
| 163 |
+
"""
|
| 164 |
+
combines logic from _load_state_dict_into_meta_model and .integrations.bitsandbytes.py::set_module_quantized_tensor_to_device()
|
| 165 |
+
"""
|
| 166 |
+
import bitsandbytes as bnb
|
| 167 |
+
|
| 168 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 169 |
+
|
| 170 |
+
if tensor_name not in module._parameters:
|
| 171 |
+
raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.")
|
| 172 |
+
|
| 173 |
+
old_value = getattr(module, tensor_name)
|
| 174 |
+
|
| 175 |
+
# `torch.Tensor.to(<int num>)` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)).
|
| 176 |
+
if isinstance(target_device, int) and is_torch_npu_available():
|
| 177 |
+
target_device = f"npu:{target_device}"
|
| 178 |
+
if tensor_name == "bias":
|
| 179 |
+
if param_value is None:
|
| 180 |
+
new_value = old_value.to(target_device)
|
| 181 |
+
else:
|
| 182 |
+
new_value = param_value.to(target_device)
|
| 183 |
+
|
| 184 |
+
new_value = torch.nn.Parameter(new_value, requires_grad=old_value.requires_grad)
|
| 185 |
+
module._parameters[tensor_name] = new_value
|
| 186 |
+
return
|
| 187 |
+
|
| 188 |
+
if not isinstance(module._parameters[tensor_name], bnb.nn.Params4bit):
|
| 189 |
+
raise ValueError("this function only loads `Linear4bit components`")
|
| 190 |
+
if (
|
| 191 |
+
old_value.device == torch.device("meta")
|
| 192 |
+
and target_device not in ["meta", torch.device("meta")]
|
| 193 |
+
and param_value is None
|
| 194 |
+
):
|
| 195 |
+
raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {target_device}.")
|
| 196 |
+
|
| 197 |
+
# construct `new_value` for the module._parameters[tensor_name]:
|
| 198 |
+
if self.pre_quantized:
|
| 199 |
+
# 4bit loading. Collecting components for restoring quantized weight
|
| 200 |
+
# This can be expanded to make a universal call for any quantized weight loading
|
| 201 |
+
|
| 202 |
+
if not self.is_serializable:
|
| 203 |
+
raise ValueError(
|
| 204 |
+
"Detected int4 weights but the version of bitsandbytes is not compatible with int4 serialization. "
|
| 205 |
+
"Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
if (param_name + ".quant_state.bitsandbytes__fp4" not in state_dict) and (
|
| 209 |
+
param_name + ".quant_state.bitsandbytes__nf4" not in state_dict
|
| 210 |
+
):
|
| 211 |
+
raise ValueError(
|
| 212 |
+
f"Supplied state dict for {param_name} does not contain `bitsandbytes__*` and possibly other `quantized_stats` components."
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
quantized_stats = {}
|
| 216 |
+
for k, v in state_dict.items():
|
| 217 |
+
if param_name + "." in k:
|
| 218 |
+
quantized_stats[k] = v
|
| 219 |
+
if unexpected_keys is not None and k in unexpected_keys:
|
| 220 |
+
unexpected_keys.remove(k)
|
| 221 |
+
|
| 222 |
+
param_kwargs = {}
|
| 223 |
+
if self.is_bnb_supports_quant_storage_module:
|
| 224 |
+
param_kwargs["module"] = module
|
| 225 |
+
|
| 226 |
+
new_value = bnb.nn.Params4bit.from_prequantized(
|
| 227 |
+
data=param_value,
|
| 228 |
+
quantized_stats=quantized_stats,
|
| 229 |
+
requires_grad=False,
|
| 230 |
+
device=target_device,
|
| 231 |
+
**param_kwargs,
|
| 232 |
+
)
|
| 233 |
+
else:
|
| 234 |
+
new_value = param_value.to("cpu")
|
| 235 |
+
|
| 236 |
+
# Support models using `Conv1D` in place of `nn.Linear` (e.g. openai-community/gpt2) by transposing the weight matrix prior to quantization.
|
| 237 |
+
# Since weights are saved in the correct "orientation", we skip transposing when loading.
|
| 238 |
+
if issubclass(module.source_cls, Conv1D):
|
| 239 |
+
new_value = new_value.T
|
| 240 |
+
|
| 241 |
+
kwargs = old_value.__dict__
|
| 242 |
+
new_value = bnb.nn.Params4bit(new_value, requires_grad=False, **kwargs).to(target_device)
|
| 243 |
+
|
| 244 |
+
module._parameters[tensor_name] = new_value
|
| 245 |
+
|
| 246 |
+
# Copied from transformers.quantizers.quantizer_bnb_8bit.Bnb8BitHfQuantizer.adjust_max_memory
|
| 247 |
+
def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
|
| 248 |
+
# need more space for buffers that are created during quantization
|
| 249 |
+
max_memory = {key: val * 0.90 for key, val in max_memory.items()}
|
| 250 |
+
return max_memory
|
| 251 |
+
|
| 252 |
+
# Copied from transformers.quantizers.quantizer_bnb_8bit.Bnb8BitHfQuantizer.update_torch_dtype
|
| 253 |
+
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 254 |
+
if torch_dtype is None:
|
| 255 |
+
# We force the `dtype` to be float16, this is a requirement from `bitsandbytes`
|
| 256 |
+
logger.info(
|
| 257 |
+
"Overriding torch_dtype=%s with `torch_dtype=torch.float16` due to "
|
| 258 |
+
"requirements of `bitsandbytes` to enable model loading in 8-bit or 4-bit. "
|
| 259 |
+
"Pass your own torch_dtype to specify the dtype of the remaining non-linear layers or pass"
|
| 260 |
+
" torch_dtype=torch.float16 to remove this warning.",
|
| 261 |
+
torch_dtype,
|
| 262 |
+
)
|
| 263 |
+
torch_dtype = torch.float16
|
| 264 |
+
return torch_dtype
|
| 265 |
+
|
| 266 |
+
def update_device_map(self, device_map):
|
| 267 |
+
if device_map is None:
|
| 268 |
+
if torch.cuda.is_available():
|
| 269 |
+
device_map = {"": torch.cuda.current_device()}
|
| 270 |
+
elif is_torch_npu_available():
|
| 271 |
+
device_map = {"": f"npu:{torch.npu.current_device()}"}
|
| 272 |
+
elif is_torch_xpu_available():
|
| 273 |
+
device_map = {"": f"xpu:{torch.xpu.current_device()}"}
|
| 274 |
+
else:
|
| 275 |
+
device_map = {"": "cpu"}
|
| 276 |
+
logger.info(
|
| 277 |
+
"The device_map was not initialized. "
|
| 278 |
+
f"Setting device_map to {device_map}. "
|
| 279 |
+
"If you want to use the model for inference, please set device_map ='auto' "
|
| 280 |
+
)
|
| 281 |
+
return device_map
|
| 282 |
+
|
| 283 |
+
# Copied from transformers.quantizers.quantizer_bnb_8bit.Bnb8BitHfQuantizer._process_model_before_weight_loading
|
| 284 |
+
def _process_model_before_weight_loading(
|
| 285 |
+
self,
|
| 286 |
+
model: "PreTrainedModel",
|
| 287 |
+
device_map,
|
| 288 |
+
keep_in_fp32_modules: List[str] = [],
|
| 289 |
+
**kwargs,
|
| 290 |
+
):
|
| 291 |
+
from ..integrations import get_keys_to_not_convert, replace_with_bnb_linear
|
| 292 |
+
|
| 293 |
+
llm_int8_enable_fp32_cpu_offload = self.quantization_config.llm_int8_enable_fp32_cpu_offload
|
| 294 |
+
|
| 295 |
+
# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
|
| 296 |
+
if self.quantization_config.llm_int8_skip_modules is None:
|
| 297 |
+
self.modules_to_not_convert = get_keys_to_not_convert(model)
|
| 298 |
+
else:
|
| 299 |
+
self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
|
| 300 |
+
|
| 301 |
+
if not isinstance(self.modules_to_not_convert, list):
|
| 302 |
+
self.modules_to_not_convert = [self.modules_to_not_convert]
|
| 303 |
+
|
| 304 |
+
self.modules_to_not_convert.extend(keep_in_fp32_modules)
|
| 305 |
+
|
| 306 |
+
# Extend `self.modules_to_not_convert` to keys that are supposed to be offloaded to `cpu` or `disk`
|
| 307 |
+
if isinstance(device_map, dict) and len(device_map.keys()) > 1:
|
| 308 |
+
keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
|
| 309 |
+
|
| 310 |
+
if len(keys_on_cpu) > 0 and not llm_int8_enable_fp32_cpu_offload:
|
| 311 |
+
raise ValueError(
|
| 312 |
+
"If you want to offload some keys to `cpu` or `disk`, you need to set "
|
| 313 |
+
"`llm_int8_enable_fp32_cpu_offload=True`. Note that these modules will not be "
|
| 314 |
+
" converted to 8-bit but kept in 32-bit."
|
| 315 |
+
)
|
| 316 |
+
self.modules_to_not_convert.extend(keys_on_cpu)
|
| 317 |
+
|
| 318 |
+
model = replace_with_bnb_linear(
|
| 319 |
+
model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
|
| 320 |
+
)
|
| 321 |
+
# TODO: consider bringing replace_with_bnb_linear() code from ..integrations/bitsandbyter.py to here
|
| 322 |
+
|
| 323 |
+
model.config.quantization_config = self.quantization_config
|
| 324 |
+
|
| 325 |
+
# Copied from transformers.quantizers.quantizer_bnb_8bit.Bnb8BitHfQuantizer._process_model_after_weight_loading with 8bit->4bit
|
| 326 |
+
def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
|
| 327 |
+
model.is_loaded_in_4bit = True
|
| 328 |
+
model.is_4bit_serializable = self.is_serializable()
|
| 329 |
+
return model
|
| 330 |
+
|
| 331 |
+
def is_serializable(self, safe_serialization=None):
|
| 332 |
+
_is_4bit_serializable = version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse("0.41.3")
|
| 333 |
+
|
| 334 |
+
if not _is_4bit_serializable:
|
| 335 |
+
logger.warning(
|
| 336 |
+
"You are calling `save_pretrained` to a 4-bit converted model, but your `bitsandbytes` version doesn't support it. "
|
| 337 |
+
"If you want to save 4-bit models, make sure to have `bitsandbytes>=0.41.3` installed."
|
| 338 |
+
)
|
| 339 |
+
return False
|
| 340 |
+
|
| 341 |
+
return True
|
| 342 |
+
|
| 343 |
+
@cached_property
|
| 344 |
+
def is_bnb_supports_quant_storage_module(self) -> bool:
|
| 345 |
+
"""
|
| 346 |
+
determines if the current version of bitsandbytes supports
|
| 347 |
+
the `module` parameter in `Params4bit.from_prequantized`
|
| 348 |
+
:return:
|
| 349 |
+
"""
|
| 350 |
+
return version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse("0.43.3")
|
| 351 |
+
|
| 352 |
+
@property
|
| 353 |
+
def is_trainable(self) -> bool:
|
| 354 |
+
return True
|
| 355 |
+
|
| 356 |
+
def _dequantize(self, model):
|
| 357 |
+
from ..integrations import dequantize_and_replace
|
| 358 |
+
|
| 359 |
+
model = dequantize_and_replace(
|
| 360 |
+
model, self.modules_to_not_convert, quantization_config=self.quantization_config
|
| 361 |
+
)
|
| 362 |
+
return model
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_bnb_8bit.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 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 importlib
|
| 15 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
|
| 16 |
+
|
| 17 |
+
from packaging import version
|
| 18 |
+
|
| 19 |
+
from .base import HfQuantizer
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from ..modeling_utils import PreTrainedModel
|
| 24 |
+
|
| 25 |
+
from ..utils import (
|
| 26 |
+
ACCELERATE_MIN_VERSION,
|
| 27 |
+
is_accelerate_available,
|
| 28 |
+
is_bitsandbytes_available,
|
| 29 |
+
is_torch_available,
|
| 30 |
+
is_torch_xpu_available,
|
| 31 |
+
logging,
|
| 32 |
+
)
|
| 33 |
+
from .quantizers_utils import get_module_from_name
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if is_torch_available():
|
| 37 |
+
import torch
|
| 38 |
+
|
| 39 |
+
from ..pytorch_utils import Conv1D
|
| 40 |
+
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Bnb8BitHfQuantizer(HfQuantizer):
|
| 45 |
+
"""
|
| 46 |
+
8-bit quantization from bitsandbytes quantization method:
|
| 47 |
+
before loading: converts transformer layers into Linear8bitLt during loading: load 16bit weight and pass to the
|
| 48 |
+
layer object after: quantizes individual weights in Linear8bitLt into 8bit at fitst .cuda() call
|
| 49 |
+
saving:
|
| 50 |
+
from state dict, as usual; saves weights and 'SCB' component
|
| 51 |
+
loading:
|
| 52 |
+
need to locate SCB component and pass to the Linear8bitLt object
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
use_keep_in_fp32_modules = True
|
| 56 |
+
requires_parameters_quantization = True
|
| 57 |
+
requires_calibration = False
|
| 58 |
+
|
| 59 |
+
required_packages = ["bitsandbytes", "accelerate"]
|
| 60 |
+
|
| 61 |
+
def __init__(self, quantization_config, **kwargs):
|
| 62 |
+
super().__init__(quantization_config, **kwargs)
|
| 63 |
+
|
| 64 |
+
if self.quantization_config.llm_int8_skip_modules is not None:
|
| 65 |
+
self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
|
| 66 |
+
|
| 67 |
+
def validate_environment(self, *args, **kwargs):
|
| 68 |
+
if not is_accelerate_available():
|
| 69 |
+
raise ImportError(
|
| 70 |
+
f"Using `bitsandbytes` 8-bit quantization requires Accelerate: `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`"
|
| 71 |
+
)
|
| 72 |
+
if not is_bitsandbytes_available():
|
| 73 |
+
raise ImportError(
|
| 74 |
+
"Using `bitsandbytes` 8-bit quantization requires the latest version of bitsandbytes: `pip install -U bitsandbytes`"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
from ..integrations import validate_bnb_backend_availability
|
| 78 |
+
from ..utils import is_bitsandbytes_multi_backend_available
|
| 79 |
+
|
| 80 |
+
bnb_multibackend_is_enabled = is_bitsandbytes_multi_backend_available()
|
| 81 |
+
validate_bnb_backend_availability(raise_exception=True)
|
| 82 |
+
|
| 83 |
+
if kwargs.get("from_tf", False) or kwargs.get("from_flax", False):
|
| 84 |
+
raise ValueError(
|
| 85 |
+
"Converting into 4-bit or 8-bit weights from tf/flax weights is currently not supported, please make"
|
| 86 |
+
" sure the weights are in PyTorch format."
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
device_map = kwargs.get("device_map", None)
|
| 90 |
+
if (
|
| 91 |
+
device_map is not None
|
| 92 |
+
and isinstance(device_map, dict)
|
| 93 |
+
and not self.quantization_config.llm_int8_enable_fp32_cpu_offload
|
| 94 |
+
):
|
| 95 |
+
device_map_without_lm_head = {
|
| 96 |
+
key: device_map[key] for key in device_map.keys() if key not in self.modules_to_not_convert
|
| 97 |
+
}
|
| 98 |
+
if set(device_map.values()) == {"cpu"} and bnb_multibackend_is_enabled:
|
| 99 |
+
pass
|
| 100 |
+
elif "cpu" in device_map_without_lm_head.values() or "disk" in device_map_without_lm_head.values():
|
| 101 |
+
raise ValueError(
|
| 102 |
+
"Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the "
|
| 103 |
+
"quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules "
|
| 104 |
+
"in 32-bit, you need to set `llm_int8_enable_fp32_cpu_offload=True` and pass a custom `device_map` to "
|
| 105 |
+
"`from_pretrained`. Check "
|
| 106 |
+
"https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu "
|
| 107 |
+
"for more details. "
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.37.2"):
|
| 111 |
+
raise ValueError(
|
| 112 |
+
"You have a version of `bitsandbytes` that is not compatible with 8bit inference and training"
|
| 113 |
+
" make sure you have the latest version of `bitsandbytes` installed"
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
|
| 117 |
+
# need more space for buffers that are created during quantization
|
| 118 |
+
max_memory = {key: val * 0.90 for key, val in max_memory.items()}
|
| 119 |
+
return max_memory
|
| 120 |
+
|
| 121 |
+
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 122 |
+
if torch_dtype is None:
|
| 123 |
+
# We force the `dtype` to be float16, this is a requirement from `bitsandbytes`
|
| 124 |
+
logger.info(
|
| 125 |
+
"Overriding torch_dtype=%s with `torch_dtype=torch.float16` due to "
|
| 126 |
+
"requirements of `bitsandbytes` to enable model loading in 8-bit or 4-bit. "
|
| 127 |
+
"Pass your own torch_dtype to specify the dtype of the remaining non-linear layers or pass"
|
| 128 |
+
" torch_dtype=torch.float16 to remove this warning.",
|
| 129 |
+
torch_dtype,
|
| 130 |
+
)
|
| 131 |
+
torch_dtype = torch.float16
|
| 132 |
+
return torch_dtype
|
| 133 |
+
|
| 134 |
+
def update_device_map(self, device_map):
|
| 135 |
+
if device_map is None:
|
| 136 |
+
if torch.cuda.is_available():
|
| 137 |
+
device_map = {"": torch.cuda.current_device()}
|
| 138 |
+
elif is_torch_xpu_available():
|
| 139 |
+
device_map = {"": f"xpu:{torch.xpu.current_device()}"}
|
| 140 |
+
else:
|
| 141 |
+
device_map = {"": "cpu"}
|
| 142 |
+
logger.info(
|
| 143 |
+
"The device_map was not initialized. "
|
| 144 |
+
f"Setting device_map to {device_map}. "
|
| 145 |
+
"If you want to use the model for inference, please set device_map ='auto' "
|
| 146 |
+
)
|
| 147 |
+
return device_map
|
| 148 |
+
|
| 149 |
+
def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
|
| 150 |
+
if target_dtype != torch.int8:
|
| 151 |
+
logger.info("target_dtype {target_dtype} is replaced by `torch.int8` for 8-bit BnB quantization")
|
| 152 |
+
return torch.int8
|
| 153 |
+
|
| 154 |
+
def check_quantized_param(
|
| 155 |
+
self,
|
| 156 |
+
model: "PreTrainedModel",
|
| 157 |
+
param_value: "torch.Tensor",
|
| 158 |
+
param_name: str,
|
| 159 |
+
state_dict: Dict[str, Any],
|
| 160 |
+
**kwargs,
|
| 161 |
+
):
|
| 162 |
+
import bitsandbytes as bnb
|
| 163 |
+
|
| 164 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 165 |
+
if isinstance(module._parameters.get(tensor_name, None), bnb.nn.Int8Params):
|
| 166 |
+
if self.pre_quantized:
|
| 167 |
+
if param_name.replace("weight", "SCB") not in state_dict.keys():
|
| 168 |
+
raise ValueError("Missing quantization component `SCB`")
|
| 169 |
+
if param_value.dtype != torch.int8:
|
| 170 |
+
raise ValueError(
|
| 171 |
+
f"Incompatible dtype `{param_value.dtype}` when loading 8-bit prequantized weight. Expected `torch.int8`."
|
| 172 |
+
)
|
| 173 |
+
return True
|
| 174 |
+
return False
|
| 175 |
+
|
| 176 |
+
def create_quantized_param(
|
| 177 |
+
self,
|
| 178 |
+
model: "PreTrainedModel",
|
| 179 |
+
param_value: "torch.Tensor",
|
| 180 |
+
param_name: str,
|
| 181 |
+
target_device: "torch.device",
|
| 182 |
+
state_dict: Dict[str, Any],
|
| 183 |
+
unexpected_keys: Optional[List[str]] = None,
|
| 184 |
+
):
|
| 185 |
+
"""
|
| 186 |
+
combines logic from _load_state_dict_into_meta_model and .integrations.bitsandbytes.py::set_module_quantized_tensor_to_device()
|
| 187 |
+
needs aux items from state dicts, if found - removes them from unexpected_keys
|
| 188 |
+
"""
|
| 189 |
+
import bitsandbytes as bnb
|
| 190 |
+
|
| 191 |
+
fp16_statistics_key = param_name.replace("weight", "SCB")
|
| 192 |
+
fp16_weights_format_key = param_name.replace("weight", "weight_format")
|
| 193 |
+
|
| 194 |
+
fp16_statistics = state_dict.get(fp16_statistics_key, None)
|
| 195 |
+
fp16_weights_format = state_dict.get(fp16_weights_format_key, None)
|
| 196 |
+
|
| 197 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 198 |
+
if tensor_name not in module._parameters:
|
| 199 |
+
raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.")
|
| 200 |
+
|
| 201 |
+
old_value = getattr(module, tensor_name)
|
| 202 |
+
|
| 203 |
+
if not isinstance(module._parameters[tensor_name], bnb.nn.Int8Params):
|
| 204 |
+
raise ValueError(f"Parameter `{tensor_name}` should only be a `bnb.nn.Int8Params` instance.")
|
| 205 |
+
if (
|
| 206 |
+
old_value.device == torch.device("meta")
|
| 207 |
+
and target_device not in ["meta", torch.device("meta")]
|
| 208 |
+
and param_value is None
|
| 209 |
+
):
|
| 210 |
+
raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {target_device}.")
|
| 211 |
+
|
| 212 |
+
new_value = param_value.to("cpu")
|
| 213 |
+
if self.pre_quantized and not self.is_serializable():
|
| 214 |
+
raise ValueError(
|
| 215 |
+
"Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. "
|
| 216 |
+
"Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
# Support models using `Conv1D` in place of `nn.Linear` (e.g. openai-community/gpt2) by transposing the weight matrix prior to quantization.
|
| 220 |
+
# Since weights are saved in the correct "orientation", we skip transposing when loading.
|
| 221 |
+
if issubclass(module.source_cls, Conv1D):
|
| 222 |
+
if fp16_statistics is None:
|
| 223 |
+
new_value = new_value.T
|
| 224 |
+
|
| 225 |
+
kwargs = old_value.__dict__
|
| 226 |
+
new_value = bnb.nn.Int8Params(new_value, requires_grad=False, **kwargs).to(target_device)
|
| 227 |
+
|
| 228 |
+
module._parameters[tensor_name] = new_value
|
| 229 |
+
if fp16_statistics is not None:
|
| 230 |
+
setattr(module.weight, "SCB", fp16_statistics.to(target_device))
|
| 231 |
+
if unexpected_keys is not None:
|
| 232 |
+
unexpected_keys.remove(fp16_statistics_key)
|
| 233 |
+
|
| 234 |
+
# We just need to pop the `weight_format` keys from the state dict to remove unneeded
|
| 235 |
+
# messages. The correct format is correctly retrieved during the first forward pass.
|
| 236 |
+
if fp16_weights_format is not None and unexpected_keys is not None:
|
| 237 |
+
unexpected_keys.remove(fp16_weights_format_key)
|
| 238 |
+
|
| 239 |
+
def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
|
| 240 |
+
model.is_loaded_in_8bit = True
|
| 241 |
+
model.is_8bit_serializable = self.is_serializable()
|
| 242 |
+
return model
|
| 243 |
+
|
| 244 |
+
def _process_model_before_weight_loading(
|
| 245 |
+
self,
|
| 246 |
+
model: "PreTrainedModel",
|
| 247 |
+
device_map,
|
| 248 |
+
keep_in_fp32_modules: List[str] = [],
|
| 249 |
+
**kwargs,
|
| 250 |
+
):
|
| 251 |
+
from ..integrations import get_keys_to_not_convert, replace_with_bnb_linear
|
| 252 |
+
|
| 253 |
+
llm_int8_enable_fp32_cpu_offload = self.quantization_config.llm_int8_enable_fp32_cpu_offload
|
| 254 |
+
|
| 255 |
+
# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
|
| 256 |
+
if self.quantization_config.llm_int8_skip_modules is None:
|
| 257 |
+
self.modules_to_not_convert = get_keys_to_not_convert(model)
|
| 258 |
+
else:
|
| 259 |
+
self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
|
| 260 |
+
|
| 261 |
+
if not isinstance(self.modules_to_not_convert, list):
|
| 262 |
+
self.modules_to_not_convert = [self.modules_to_not_convert]
|
| 263 |
+
|
| 264 |
+
self.modules_to_not_convert.extend(keep_in_fp32_modules)
|
| 265 |
+
|
| 266 |
+
# Extend `self.modules_to_not_convert` to keys that are supposed to be offloaded to `cpu` or `disk`
|
| 267 |
+
if isinstance(device_map, dict) and len(device_map.keys()) > 1:
|
| 268 |
+
keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
|
| 269 |
+
|
| 270 |
+
if len(keys_on_cpu) > 0 and not llm_int8_enable_fp32_cpu_offload:
|
| 271 |
+
raise ValueError(
|
| 272 |
+
"If you want to offload some keys to `cpu` or `disk`, you need to set "
|
| 273 |
+
"`llm_int8_enable_fp32_cpu_offload=True`. Note that these modules will not be "
|
| 274 |
+
" converted to 8-bit but kept in 32-bit."
|
| 275 |
+
)
|
| 276 |
+
self.modules_to_not_convert.extend(keys_on_cpu)
|
| 277 |
+
|
| 278 |
+
model = replace_with_bnb_linear(
|
| 279 |
+
model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
|
| 280 |
+
)
|
| 281 |
+
# TODO: consider bringing replace_with_bnb_linear() code from ..integrations/bitsandbyter.py to here
|
| 282 |
+
|
| 283 |
+
model.config.quantization_config = self.quantization_config
|
| 284 |
+
|
| 285 |
+
def is_serializable(self, safe_serialization=None):
|
| 286 |
+
_bnb_supports_8bit_serialization = version.parse(importlib.metadata.version("bitsandbytes")) > version.parse(
|
| 287 |
+
"0.37.2"
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
if not _bnb_supports_8bit_serialization:
|
| 291 |
+
logger.warning(
|
| 292 |
+
"You are calling `save_pretrained` to a 8-bit converted model, but your `bitsandbytes` version doesn't support it. "
|
| 293 |
+
"If you want to save 8-bit models, make sure to have `bitsandbytes>0.37.2` installed. You will most likely face errors or"
|
| 294 |
+
" unexpected behaviours."
|
| 295 |
+
)
|
| 296 |
+
return False
|
| 297 |
+
|
| 298 |
+
return True
|
| 299 |
+
|
| 300 |
+
@property
|
| 301 |
+
def is_trainable(self) -> bool:
|
| 302 |
+
return version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse("0.37.0")
|
| 303 |
+
|
| 304 |
+
def _dequantize(self, model):
|
| 305 |
+
from ..integrations import dequantize_and_replace
|
| 306 |
+
|
| 307 |
+
model = dequantize_and_replace(
|
| 308 |
+
model, self.modules_to_not_convert, quantization_config=self.quantization_config
|
| 309 |
+
)
|
| 310 |
+
return model
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_compressed_tensors.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 |
+
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
|
| 18 |
+
from ..utils import is_compressed_tensors_available, is_torch_available, logging
|
| 19 |
+
from ..utils.quantization_config import CompressedTensorsConfig
|
| 20 |
+
from .base import HfQuantizer
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if is_torch_available():
|
| 24 |
+
import torch
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class CompressedTensorsHfQuantizer(HfQuantizer):
|
| 30 |
+
"""
|
| 31 |
+
Quantizer for the compressed_tensors package. Loads and restores models to
|
| 32 |
+
quantized state with compressed_tensors
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
requires_calibration = True
|
| 36 |
+
required_packages = ["compressed_tensors"]
|
| 37 |
+
|
| 38 |
+
def __init__(self, quantization_config: CompressedTensorsConfig, **kwargs):
|
| 39 |
+
super().__init__(quantization_config, **kwargs)
|
| 40 |
+
from compressed_tensors.compressors import ModelCompressor
|
| 41 |
+
|
| 42 |
+
self.compressor = ModelCompressor.from_compression_config(quantization_config)
|
| 43 |
+
self.run_compressed = quantization_config.run_compressed
|
| 44 |
+
self.quantization_config = quantization_config
|
| 45 |
+
|
| 46 |
+
def validate_environment(self, *args, **kwargs):
|
| 47 |
+
if not is_compressed_tensors_available():
|
| 48 |
+
raise ImportError(
|
| 49 |
+
"Using `compressed_tensors` quantized models requires the compressed-tensors library: "
|
| 50 |
+
"`pip install compressed-tensors`"
|
| 51 |
+
)
|
| 52 |
+
if not is_torch_available():
|
| 53 |
+
# torch already should be installed as part of compressed tensors
|
| 54 |
+
raise ImportError("torch is required for using compressed-tensors quantization")
|
| 55 |
+
|
| 56 |
+
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 57 |
+
if torch_dtype is None:
|
| 58 |
+
logger.info("Loading model using torch.float16 for compressed-tensors quantization")
|
| 59 |
+
torch_dtype = torch.float16
|
| 60 |
+
elif torch_dtype != torch.float16:
|
| 61 |
+
logger.info(
|
| 62 |
+
"We suggest you to set `torch_dtype=torch.float16` for better efficiency with compressed_tensors."
|
| 63 |
+
)
|
| 64 |
+
return torch_dtype
|
| 65 |
+
|
| 66 |
+
def _process_model_before_weight_loading(self, model, **kwargs):
|
| 67 |
+
from compressed_tensors.quantization import apply_quantization_config
|
| 68 |
+
|
| 69 |
+
ct_quantization_config = self.compressor.quantization_config
|
| 70 |
+
|
| 71 |
+
if self.run_compressed and self.is_quantization_compressed:
|
| 72 |
+
apply_quantization_config(model, ct_quantization_config, run_compressed=True)
|
| 73 |
+
elif not self.is_quantization_compressed:
|
| 74 |
+
apply_quantization_config(model, ct_quantization_config)
|
| 75 |
+
|
| 76 |
+
def _process_model_after_weight_loading(self, model, **kwargs):
|
| 77 |
+
"""Decompress loaded model if necessary - need for qat"""
|
| 78 |
+
|
| 79 |
+
if (self.is_quantization_compressed and not self.run_compressed) or self.is_sparsification_compressed:
|
| 80 |
+
config = kwargs.get("config", None)
|
| 81 |
+
cache_path = config._name_or_path
|
| 82 |
+
|
| 83 |
+
if not os.path.exists(cache_path):
|
| 84 |
+
from transformers.utils import cached_file
|
| 85 |
+
|
| 86 |
+
config_file_path = cached_file(cache_path, "config.json")
|
| 87 |
+
cache_path = os.path.sep.join(config_file_path.split(os.path.sep)[:-1])
|
| 88 |
+
|
| 89 |
+
if self.is_quantization_compressed and not self.run_compressed:
|
| 90 |
+
from compressed_tensors.quantization import QuantizationStatus
|
| 91 |
+
|
| 92 |
+
self.compressor.quantization_config.quantization_status = QuantizationStatus.FROZEN
|
| 93 |
+
self.compressor.decompress(model_path=cache_path, model=model)
|
| 94 |
+
|
| 95 |
+
@property
|
| 96 |
+
def is_quantization_compressed(self):
|
| 97 |
+
from compressed_tensors.quantization import QuantizationStatus
|
| 98 |
+
|
| 99 |
+
return (
|
| 100 |
+
self.quantization_config.quantization_config is not None
|
| 101 |
+
and self.quantization_config.quantization_config.quantization_status == QuantizationStatus.COMPRESSED
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
@property
|
| 105 |
+
def is_sparsification_compressed(self):
|
| 106 |
+
from compressed_tensors.config.base import CompressionFormat
|
| 107 |
+
|
| 108 |
+
return (
|
| 109 |
+
self.quantization_config.sparsity_config is not None
|
| 110 |
+
and self.quantization_config.sparsity_config.format != CompressionFormat.dense.value
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
@property
|
| 114 |
+
def is_trainable(self):
|
| 115 |
+
return True
|
| 116 |
+
|
| 117 |
+
def is_qat_trainable(self) -> bool:
|
| 118 |
+
"""Loaded Models can carry out quantization aware training"""
|
| 119 |
+
# models need to be decompressed carry out qat
|
| 120 |
+
return not self.run_compressed or not self.is_quantization_compressed
|
| 121 |
+
|
| 122 |
+
def is_serializable(self, safe_serialization=None) -> bool:
|
| 123 |
+
"""Models quantized using compressed tensors can be saved to disk"""
|
| 124 |
+
return True
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_eetq.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional
|
| 15 |
+
|
| 16 |
+
from .base import HfQuantizer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from ..modeling_utils import PreTrainedModel
|
| 21 |
+
|
| 22 |
+
from ..utils import is_accelerate_available, is_eetq_available, is_torch_available, logging
|
| 23 |
+
from .quantizers_utils import get_module_from_name
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if is_torch_available():
|
| 27 |
+
import torch
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class EetqHfQuantizer(HfQuantizer):
|
| 34 |
+
"""
|
| 35 |
+
8-bit quantization from EETQ quantization method:
|
| 36 |
+
before loading: converts transformer layers into W8A16Linear during loading: load 16bit weight and pass to the
|
| 37 |
+
layer object after: quantizes individual weights in Linear8bitLt into 8bit at first .cuda() call
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
requires_parameters_quantization = True
|
| 41 |
+
requires_calibration = False
|
| 42 |
+
|
| 43 |
+
required_packages = ["eetq", "accelerate"]
|
| 44 |
+
|
| 45 |
+
def __init__(self, quantization_config, **kwargs):
|
| 46 |
+
super().__init__(quantization_config, **kwargs)
|
| 47 |
+
self.quantization_config = quantization_config
|
| 48 |
+
|
| 49 |
+
def validate_environment(self, *args, **kwargs):
|
| 50 |
+
if not is_eetq_available():
|
| 51 |
+
raise ImportError(
|
| 52 |
+
"Using `eetq` 8-bit quantization requires eetq."
|
| 53 |
+
"Please install the latest version of eetq from : https://github.com/NetEase-FuXi/EETQ"
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
import eetq # noqa: F401
|
| 58 |
+
except ImportError as exc:
|
| 59 |
+
if "shard_checkpoint" in str(exc):
|
| 60 |
+
# EETQ 1.0.0 is currently broken with the latest transformers because it tries to import the removed
|
| 61 |
+
# shard_checkpoint function, see https://github.com/NetEase-FuXi/EETQ/issues/34.
|
| 62 |
+
# TODO: Update message once eetq releases a fix
|
| 63 |
+
raise ImportError(
|
| 64 |
+
"You are using a version of EETQ that is incompatible with the current transformers version. "
|
| 65 |
+
"Either downgrade transformers to <= v4.46.3 or, if available, upgrade EETQ to > v1.0.0."
|
| 66 |
+
) from exc
|
| 67 |
+
else:
|
| 68 |
+
raise
|
| 69 |
+
|
| 70 |
+
if not is_accelerate_available():
|
| 71 |
+
raise ImportError("Loading an EETQ quantized model requires accelerate (`pip install accelerate`)")
|
| 72 |
+
|
| 73 |
+
if kwargs.get("from_tf", False) or kwargs.get("from_flax", False):
|
| 74 |
+
raise ValueError(
|
| 75 |
+
"Converting into 8-bit weights from tf/flax weights is currently not supported, please make"
|
| 76 |
+
" sure the weights are in PyTorch format."
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
if not torch.cuda.is_available():
|
| 80 |
+
raise RuntimeError("No GPU found. A GPU is needed for quantization.")
|
| 81 |
+
|
| 82 |
+
device_map = kwargs.get("device_map", None)
|
| 83 |
+
if device_map is None:
|
| 84 |
+
logger.warning_once(
|
| 85 |
+
"You have loaded an EETQ model on CPU and have a CUDA device available, make sure to set "
|
| 86 |
+
"your model on a GPU device in order to run your model."
|
| 87 |
+
)
|
| 88 |
+
elif device_map is not None:
|
| 89 |
+
if isinstance(device_map, dict) and ("cpu" in device_map.values() or "disk" in device_map.values()):
|
| 90 |
+
raise ValueError(
|
| 91 |
+
"You are attempting to load an EETQ model with a device_map that contains a CPU or disk device."
|
| 92 |
+
" This is not supported. Please remove the CPU or disk device from the device_map."
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 96 |
+
if torch_dtype is None:
|
| 97 |
+
torch_dtype = torch.float16
|
| 98 |
+
logger.info(
|
| 99 |
+
"Overriding torch_dtype=%s with `torch_dtype=torch.float16` due to "
|
| 100 |
+
"requirements of `eetq` to enable model loading in 8-bit. "
|
| 101 |
+
"Pass your own torch_dtype to specify the dtype of the remaining non-linear layers or pass"
|
| 102 |
+
" torch_dtype=torch.float16 to remove this warning.",
|
| 103 |
+
torch_dtype,
|
| 104 |
+
)
|
| 105 |
+
elif torch_dtype != torch.float16:
|
| 106 |
+
logger.info("We suggest you to set `torch_dtype=torch.float16` for better efficiency with EETQ.")
|
| 107 |
+
return torch_dtype
|
| 108 |
+
|
| 109 |
+
def check_quantized_param(
|
| 110 |
+
self,
|
| 111 |
+
model: "PreTrainedModel",
|
| 112 |
+
param_value: "torch.Tensor",
|
| 113 |
+
param_name: str,
|
| 114 |
+
state_dict: Dict[str, Any],
|
| 115 |
+
**kwargs,
|
| 116 |
+
):
|
| 117 |
+
from eetq import EetqLinear
|
| 118 |
+
|
| 119 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 120 |
+
|
| 121 |
+
if isinstance(module, EetqLinear):
|
| 122 |
+
if self.pre_quantized or tensor_name == "bias":
|
| 123 |
+
if tensor_name == "weight" and param_value.dtype != torch.int8:
|
| 124 |
+
raise ValueError("Expect quantized weights but got an unquantized weight")
|
| 125 |
+
return False
|
| 126 |
+
else:
|
| 127 |
+
if tensor_name == "weight_scale":
|
| 128 |
+
raise ValueError("Expect unquantized weights but got a quantized weight_scale")
|
| 129 |
+
return True
|
| 130 |
+
return False
|
| 131 |
+
|
| 132 |
+
def create_quantized_param(
|
| 133 |
+
self,
|
| 134 |
+
model: "PreTrainedModel",
|
| 135 |
+
param_value: "torch.Tensor",
|
| 136 |
+
param_name: str,
|
| 137 |
+
target_device: "torch.device",
|
| 138 |
+
state_dict: Dict[str, Any],
|
| 139 |
+
unexpected_keys: Optional[List[str]] = None,
|
| 140 |
+
):
|
| 141 |
+
"""
|
| 142 |
+
quantizes weights into qweight and weight_scales
|
| 143 |
+
"""
|
| 144 |
+
from eetq import quantize_and_preprocess_weights
|
| 145 |
+
|
| 146 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 147 |
+
new_value, weight_scale = quantize_and_preprocess_weights(param_value)
|
| 148 |
+
|
| 149 |
+
module._buffers[tensor_name] = new_value.to(target_device)
|
| 150 |
+
module.register("weight_scales", weight_scale.to(target_device))
|
| 151 |
+
|
| 152 |
+
def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
|
| 153 |
+
return model
|
| 154 |
+
|
| 155 |
+
def _process_model_before_weight_loading(
|
| 156 |
+
self,
|
| 157 |
+
model: "PreTrainedModel",
|
| 158 |
+
device_map,
|
| 159 |
+
keep_in_fp32_modules: List[str] = [],
|
| 160 |
+
**kwargs,
|
| 161 |
+
):
|
| 162 |
+
from ..integrations import get_keys_to_not_convert, replace_with_eetq_linear
|
| 163 |
+
|
| 164 |
+
self.modules_to_not_convert = get_keys_to_not_convert(model)
|
| 165 |
+
|
| 166 |
+
if self.quantization_config.modules_to_not_convert is not None:
|
| 167 |
+
self.modules_to_not_convert.extend(self.quantization_config.modules_to_not_convert)
|
| 168 |
+
|
| 169 |
+
model = replace_with_eetq_linear(
|
| 170 |
+
model,
|
| 171 |
+
modules_to_not_convert=self.modules_to_not_convert,
|
| 172 |
+
quantization_config=self.quantization_config,
|
| 173 |
+
pre_quantized=self.pre_quantized,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
model.config.quantization_config = self.quantization_config
|
| 177 |
+
|
| 178 |
+
def is_serializable(self, safe_serialization=None):
|
| 179 |
+
return True
|
| 180 |
+
|
| 181 |
+
@property
|
| 182 |
+
def is_trainable(self) -> bool:
|
| 183 |
+
return True
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_fbgemm_fp8.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 importlib
|
| 15 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional
|
| 16 |
+
|
| 17 |
+
from packaging import version
|
| 18 |
+
|
| 19 |
+
from .base import HfQuantizer
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from ..modeling_utils import PreTrainedModel
|
| 24 |
+
|
| 25 |
+
from ..utils import is_accelerate_available, is_fbgemm_gpu_available, is_torch_available, logging
|
| 26 |
+
from .quantizers_utils import get_module_from_name
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_torch_available():
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class FbgemmFp8HfQuantizer(HfQuantizer):
|
| 37 |
+
"""
|
| 38 |
+
FP8 quantization using fbgemm kernels
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
requires_parameters_quantization = True
|
| 42 |
+
requires_calibration = False
|
| 43 |
+
|
| 44 |
+
required_packages = ["fbgemm-gpu", "accelerate"]
|
| 45 |
+
|
| 46 |
+
def __init__(self, quantization_config, **kwargs):
|
| 47 |
+
super().__init__(quantization_config, **kwargs)
|
| 48 |
+
self.quantization_config = quantization_config
|
| 49 |
+
|
| 50 |
+
def validate_environment(self, *args, **kwargs):
|
| 51 |
+
if not is_torch_available() or version.parse(importlib.metadata.version("torch")) < version.parse("2.1.0"):
|
| 52 |
+
raise ImportError(
|
| 53 |
+
"Using fbgemm fp8 quantization requires torch > 2.1.0"
|
| 54 |
+
"Please install the latest version of torch ( pip install --upgrade torch )"
|
| 55 |
+
)
|
| 56 |
+
if not is_fbgemm_gpu_available():
|
| 57 |
+
raise ImportError(
|
| 58 |
+
"Using fbgemm fp8 quantization requires fbgemm-gpu library"
|
| 59 |
+
"Please install the latest version of fbgemm-gpu library by following : https://pytorch.org/FBGEMM/fbgemm_gpu-development/InstallationInstructions.html#fbgemm-gpu-install-libraries"
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
if not is_accelerate_available("0.32.2"):
|
| 63 |
+
raise ImportError(
|
| 64 |
+
"Loading an FP8 quantized model requires accelerate > 0.32.1 (`pip install --upgrade accelerate`)"
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
if not torch.cuda.is_available():
|
| 68 |
+
raise RuntimeError("Using FP8 quantized models with fbgemm kernels requires a GPU")
|
| 69 |
+
|
| 70 |
+
compute_capability = torch.cuda.get_device_capability()
|
| 71 |
+
major, minor = compute_capability
|
| 72 |
+
if major < 9:
|
| 73 |
+
raise ValueError(
|
| 74 |
+
"FP8 quantized models is only supported on GPUs with compute capability >= 9.0 (e.g H100)"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
device_map = kwargs.get("device_map", None)
|
| 78 |
+
if device_map is None:
|
| 79 |
+
logger.warning_once(
|
| 80 |
+
"You have loaded an FP8 model on CPU and have a CUDA device available, make sure to set "
|
| 81 |
+
"your model on a GPU device in order to run your model. To remove this warning, pass device_map = 'cuda'. "
|
| 82 |
+
)
|
| 83 |
+
elif device_map is not None:
|
| 84 |
+
if (
|
| 85 |
+
not self.pre_quantized
|
| 86 |
+
and isinstance(device_map, dict)
|
| 87 |
+
and ("cpu" in device_map.values() or "disk" in device_map.values())
|
| 88 |
+
):
|
| 89 |
+
raise ValueError(
|
| 90 |
+
"You are attempting to load an FP8 model with a device_map that contains a CPU or disk device."
|
| 91 |
+
"This is not supported when the model is quantized on the fly. "
|
| 92 |
+
"Please use a quantized checkpoint or remove the CPU or disk device from the device_map."
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 96 |
+
if torch_dtype is None:
|
| 97 |
+
torch_dtype = torch.bfloat16
|
| 98 |
+
logger.info(
|
| 99 |
+
"Overriding torch_dtype=%s with `torch_dtype=torch.bloat16` due to "
|
| 100 |
+
"requirements of `fbgemm-gpu` to enable model loading in fp8. "
|
| 101 |
+
"Pass your own torch_dtype to specify the dtype of the remaining non-linear layers or pass"
|
| 102 |
+
" torch_dtype=torch.bfloat16 to remove this warning.",
|
| 103 |
+
torch_dtype,
|
| 104 |
+
)
|
| 105 |
+
elif torch_dtype == torch.float16:
|
| 106 |
+
raise ValueError(
|
| 107 |
+
"You cannot use FP8 with torch_dtype=torch.float16."
|
| 108 |
+
"We recommend you passing torch_dtype=torch.bfloat16"
|
| 109 |
+
)
|
| 110 |
+
return torch_dtype
|
| 111 |
+
|
| 112 |
+
def check_quantized_param(
|
| 113 |
+
self,
|
| 114 |
+
model: "PreTrainedModel",
|
| 115 |
+
param_value: "torch.Tensor",
|
| 116 |
+
param_name: str,
|
| 117 |
+
state_dict: Dict[str, Any],
|
| 118 |
+
**kwargs,
|
| 119 |
+
):
|
| 120 |
+
from ..integrations import FbgemmFp8Linear
|
| 121 |
+
|
| 122 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 123 |
+
|
| 124 |
+
if isinstance(module, FbgemmFp8Linear):
|
| 125 |
+
if self.pre_quantized or tensor_name == "bias":
|
| 126 |
+
if tensor_name == "weight" and param_value.dtype != torch.float8_e4m3fn:
|
| 127 |
+
raise ValueError("Expect quantized weights but got an unquantized weight")
|
| 128 |
+
return False
|
| 129 |
+
else:
|
| 130 |
+
if tensor_name == "weight_scale":
|
| 131 |
+
raise ValueError("Expect unquantized weights but got a quantized weight_scale")
|
| 132 |
+
return True
|
| 133 |
+
return False
|
| 134 |
+
|
| 135 |
+
def create_quantized_param(
|
| 136 |
+
self,
|
| 137 |
+
model: "PreTrainedModel",
|
| 138 |
+
param_value: "torch.Tensor",
|
| 139 |
+
param_name: str,
|
| 140 |
+
target_device: "torch.device",
|
| 141 |
+
state_dict: Dict[str, Any],
|
| 142 |
+
unexpected_keys: Optional[List[str]] = None,
|
| 143 |
+
):
|
| 144 |
+
"""
|
| 145 |
+
Quantizes weights into weight and weight_scale
|
| 146 |
+
"""
|
| 147 |
+
new_value, weight_scale = torch.ops.fbgemm.quantize_fp8_per_row(param_value)
|
| 148 |
+
|
| 149 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 150 |
+
module._buffers[tensor_name] = new_value.to(target_device)
|
| 151 |
+
# to have the right output shape -> (out_features, 1)
|
| 152 |
+
module._buffers["weight_scale"] = weight_scale.view(weight_scale.shape[0], 1).to(target_device)
|
| 153 |
+
|
| 154 |
+
if unexpected_keys is not None and param_name in unexpected_keys:
|
| 155 |
+
unexpected_keys.remove(param_name)
|
| 156 |
+
del param_name
|
| 157 |
+
|
| 158 |
+
def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
|
| 159 |
+
return model
|
| 160 |
+
|
| 161 |
+
def _process_model_before_weight_loading(
|
| 162 |
+
self,
|
| 163 |
+
model: "PreTrainedModel",
|
| 164 |
+
device_map,
|
| 165 |
+
keep_in_fp32_modules: List[str] = [],
|
| 166 |
+
**kwargs,
|
| 167 |
+
):
|
| 168 |
+
from ..integrations import get_keys_to_not_convert, replace_with_fbgemm_fp8_linear
|
| 169 |
+
|
| 170 |
+
self.modules_to_not_convert = get_keys_to_not_convert(model)
|
| 171 |
+
|
| 172 |
+
if self.quantization_config.modules_to_not_convert is not None:
|
| 173 |
+
self.modules_to_not_convert.extend(self.quantization_config.modules_to_not_convert)
|
| 174 |
+
|
| 175 |
+
model = replace_with_fbgemm_fp8_linear(
|
| 176 |
+
model,
|
| 177 |
+
modules_to_not_convert=self.modules_to_not_convert,
|
| 178 |
+
quantization_config=self.quantization_config,
|
| 179 |
+
pre_quantized=self.pre_quantized,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
model.config.quantization_config = self.quantization_config
|
| 183 |
+
|
| 184 |
+
def update_missing_keys(self, model, missing_keys: List[str], prefix: str) -> List[str]:
|
| 185 |
+
from ..integrations import FbgemmFp8Linear
|
| 186 |
+
|
| 187 |
+
not_missing_keys = []
|
| 188 |
+
for name, module in model.named_modules():
|
| 189 |
+
if isinstance(module, FbgemmFp8Linear):
|
| 190 |
+
for missing in missing_keys:
|
| 191 |
+
if (
|
| 192 |
+
(name in missing or name in f"{prefix}.{missing}")
|
| 193 |
+
and not missing.endswith(".weight")
|
| 194 |
+
and not missing.endswith(".bias")
|
| 195 |
+
):
|
| 196 |
+
not_missing_keys.append(missing)
|
| 197 |
+
return [k for k in missing_keys if k not in not_missing_keys]
|
| 198 |
+
|
| 199 |
+
def is_serializable(self, safe_serialization=None):
|
| 200 |
+
return True
|
| 201 |
+
|
| 202 |
+
@property
|
| 203 |
+
def is_trainable(self) -> bool:
|
| 204 |
+
return False
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_gptq.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 importlib
|
| 15 |
+
from typing import TYPE_CHECKING, Optional
|
| 16 |
+
|
| 17 |
+
from packaging import version
|
| 18 |
+
|
| 19 |
+
from .base import HfQuantizer
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from ..modeling_utils import PreTrainedModel
|
| 24 |
+
|
| 25 |
+
from ..utils import is_auto_gptq_available, is_optimum_available, is_torch_available, logging
|
| 26 |
+
from ..utils.quantization_config import GPTQConfig, QuantizationConfigMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_torch_available():
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class GptqHfQuantizer(HfQuantizer):
|
| 36 |
+
"""
|
| 37 |
+
Quantizer of the GPTQ method - for GPTQ the quantizer support calibration of the model through
|
| 38 |
+
`auto_gptq` package. Quantization is done under the hood for users if they load a non-prequantized model.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
requires_calibration = False
|
| 42 |
+
required_packages = ["optimum", "auto_gptq"]
|
| 43 |
+
optimum_quantizer = None
|
| 44 |
+
|
| 45 |
+
def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
|
| 46 |
+
super().__init__(quantization_config, **kwargs)
|
| 47 |
+
from optimum.gptq import GPTQQuantizer
|
| 48 |
+
|
| 49 |
+
self.optimum_quantizer = GPTQQuantizer.from_dict(self.quantization_config.to_dict_optimum())
|
| 50 |
+
|
| 51 |
+
def validate_environment(self, *args, **kwargs):
|
| 52 |
+
gptq_supports_cpu = version.parse(importlib.metadata.version("auto-gptq")) > version.parse("0.4.2")
|
| 53 |
+
if not gptq_supports_cpu and not torch.cuda.is_available():
|
| 54 |
+
raise RuntimeError("GPU is required to quantize or run quantize model.")
|
| 55 |
+
elif not (is_optimum_available() and is_auto_gptq_available()):
|
| 56 |
+
raise ImportError(
|
| 57 |
+
"Loading a GPTQ quantized model requires optimum (`pip install optimum`) and auto-gptq library (`pip install auto-gptq`)"
|
| 58 |
+
)
|
| 59 |
+
elif version.parse(importlib.metadata.version("auto_gptq")) < version.parse("0.4.2"):
|
| 60 |
+
raise ImportError(
|
| 61 |
+
"You need a version of auto_gptq >= 0.4.2 to use GPTQ: `pip install --upgrade auto-gptq`"
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 65 |
+
if torch_dtype is None:
|
| 66 |
+
torch_dtype = torch.float16
|
| 67 |
+
logger.info("Loading the model in `torch.float16`. To overwrite it, set `torch_dtype` manually.")
|
| 68 |
+
elif torch_dtype != torch.float16:
|
| 69 |
+
logger.info("We suggest you to set `torch_dtype=torch.float16` for better efficiency with GPTQ.")
|
| 70 |
+
return torch_dtype
|
| 71 |
+
|
| 72 |
+
def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs):
|
| 73 |
+
if model.__class__.main_input_name != "input_ids":
|
| 74 |
+
raise RuntimeError("We can only quantize pure text model.")
|
| 75 |
+
|
| 76 |
+
if self.pre_quantized:
|
| 77 |
+
model = self.optimum_quantizer.convert_model(model)
|
| 78 |
+
|
| 79 |
+
def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
|
| 80 |
+
if self.pre_quantized:
|
| 81 |
+
model = self.optimum_quantizer.post_init_model(model)
|
| 82 |
+
else:
|
| 83 |
+
if self.quantization_config.tokenizer is None:
|
| 84 |
+
self.quantization_config.tokenizer = model.name_or_path
|
| 85 |
+
|
| 86 |
+
self.optimum_quantizer.quantize_model(model, self.quantization_config.tokenizer)
|
| 87 |
+
model.config.quantization_config = GPTQConfig.from_dict(self.optimum_quantizer.to_dict())
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def is_trainable(self, model: Optional["PreTrainedModel"] = None):
|
| 91 |
+
return True
|
| 92 |
+
|
| 93 |
+
def is_serializable(self, safe_serialization=None):
|
| 94 |
+
return True
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_higgs.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional
|
| 15 |
+
|
| 16 |
+
from .base import HfQuantizer
|
| 17 |
+
from .quantizers_utils import get_module_from_name
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from ..modeling_utils import PreTrainedModel
|
| 22 |
+
|
| 23 |
+
from ..utils import is_accelerate_available, is_flute_available, is_hadamard_available, is_torch_available, logging
|
| 24 |
+
from ..utils.quantization_config import QuantizationConfigMixin
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if is_torch_available():
|
| 28 |
+
import torch
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_num_sms_from_device(device):
|
| 34 |
+
target_device_cc = torch.cuda.get_device_capability(device=device)
|
| 35 |
+
if target_device_cc == (8, 6):
|
| 36 |
+
return 84
|
| 37 |
+
elif target_device_cc == (8, 0):
|
| 38 |
+
return 108
|
| 39 |
+
elif target_device_cc == (8, 9):
|
| 40 |
+
return 128
|
| 41 |
+
else:
|
| 42 |
+
raise NotImplementedError(
|
| 43 |
+
f"Device capability {target_device_cc} not supported for FLUTE (yet?) to verify your device capability check out https://developer.nvidia.com/cuda-gpus"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class HiggsHfQuantizer(HfQuantizer):
|
| 48 |
+
"""
|
| 49 |
+
Quantizer of the HIGGS method. Enables the loading of prequantized models and in-flight quantization of full-precision models.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
requires_calibration = False
|
| 53 |
+
requires_parameters_quantization = True
|
| 54 |
+
required_packages = ["flute-kernel", "fast_hadamard_transform"]
|
| 55 |
+
|
| 56 |
+
def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
|
| 57 |
+
super().__init__(quantization_config, **kwargs)
|
| 58 |
+
self.quantization_config = quantization_config
|
| 59 |
+
|
| 60 |
+
def validate_environment(self, device_map, **kwargs):
|
| 61 |
+
if not torch.cuda.is_available():
|
| 62 |
+
raise NotImplementedError("HIGGS quantization is only supported on GPU. Please use a different quantizer.")
|
| 63 |
+
|
| 64 |
+
if not is_accelerate_available():
|
| 65 |
+
raise ImportError("Using `higgs` quantization requires Accelerate: `pip install accelerate`")
|
| 66 |
+
|
| 67 |
+
if not is_flute_available():
|
| 68 |
+
raise ImportError("Using `higgs` quantization requires FLUTE: `pip install flute-kernel>=0.3.0`")
|
| 69 |
+
|
| 70 |
+
if not is_hadamard_available():
|
| 71 |
+
raise ImportError(
|
| 72 |
+
"Using `higgs` quantization requires fast_hadamard_transform: `pip install fast_hadamard_transform`"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
if device_map is None:
|
| 76 |
+
raise ValueError(
|
| 77 |
+
"You are attempting to load a HIGGS model without setting device_map."
|
| 78 |
+
" Please set device_map comprised of 'cuda' devices."
|
| 79 |
+
)
|
| 80 |
+
elif isinstance(device_map, dict) and ("cpu" in device_map.values() or "disk" in device_map.values()):
|
| 81 |
+
raise ValueError(
|
| 82 |
+
"You are attempting to load a HIGGS model with a device_map that contains a CPU or disk device."
|
| 83 |
+
" This is not supported. Please remove the CPU or disk device from the device_map."
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 87 |
+
if torch_dtype is None:
|
| 88 |
+
logger.info("`torch_dtype` is None. Setting `torch_dtype=torch.float16` for FLUTE compatibility.")
|
| 89 |
+
torch_dtype = torch.float16
|
| 90 |
+
elif torch_dtype != torch.float16 and torch_dtype != torch.bfloat16:
|
| 91 |
+
raise ValueError(
|
| 92 |
+
f"Invalid `torch_dtype` {torch_dtype}. HIGGS quantization only supports `torch_dtype=torch.float16` or `torch_dtype=torch.bfloat16`."
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
return torch_dtype
|
| 96 |
+
|
| 97 |
+
def create_quantized_param(
|
| 98 |
+
self,
|
| 99 |
+
model: "PreTrainedModel",
|
| 100 |
+
param_value: "torch.Tensor",
|
| 101 |
+
param_name: str,
|
| 102 |
+
target_device: "torch.device",
|
| 103 |
+
state_dict: Dict[str, Any],
|
| 104 |
+
unexpected_keys: Optional[List[str]] = None,
|
| 105 |
+
):
|
| 106 |
+
from ..integrations import quantize_with_higgs
|
| 107 |
+
|
| 108 |
+
"""
|
| 109 |
+
Quantizes weights into weight and weight_scale
|
| 110 |
+
"""
|
| 111 |
+
flute_dict = quantize_with_higgs(
|
| 112 |
+
param_value.to(target_device),
|
| 113 |
+
self.quantization_config.bits,
|
| 114 |
+
self.quantization_config.p,
|
| 115 |
+
self.quantization_config.group_size,
|
| 116 |
+
self.quantization_config.hadamard_size,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
del param_value
|
| 120 |
+
|
| 121 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 122 |
+
for key, value in flute_dict.items():
|
| 123 |
+
if key in module._parameters:
|
| 124 |
+
module._parameters[key] = torch.nn.Parameter(value, requires_grad=False)
|
| 125 |
+
elif key in module._buffers:
|
| 126 |
+
module._buffers[key] = torch.nn.Buffer(value)
|
| 127 |
+
else:
|
| 128 |
+
raise ValueError(f"Unexpected key {key} in module {module}")
|
| 129 |
+
|
| 130 |
+
if unexpected_keys is not None and param_name in unexpected_keys:
|
| 131 |
+
unexpected_keys.remove(param_name)
|
| 132 |
+
|
| 133 |
+
module.num_sms_packed = torch.nn.Parameter(
|
| 134 |
+
torch.tensor(get_num_sms_from_device(target_device), device=target_device, dtype=torch.int32),
|
| 135 |
+
requires_grad=False,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
def _process_model_before_weight_loading(
|
| 139 |
+
self,
|
| 140 |
+
model: "PreTrainedModel",
|
| 141 |
+
**kwargs,
|
| 142 |
+
):
|
| 143 |
+
from ..integrations import replace_with_higgs_linear
|
| 144 |
+
|
| 145 |
+
replace_with_higgs_linear(
|
| 146 |
+
model,
|
| 147 |
+
quantization_config=self.quantization_config,
|
| 148 |
+
)
|
| 149 |
+
model.config.quantization_config = self.quantization_config
|
| 150 |
+
|
| 151 |
+
def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
|
| 152 |
+
import flute.utils
|
| 153 |
+
|
| 154 |
+
from ..integrations import HiggsLinear
|
| 155 |
+
|
| 156 |
+
flute_workspaces = {}
|
| 157 |
+
for name, module in model.named_modules():
|
| 158 |
+
if isinstance(module, HiggsLinear):
|
| 159 |
+
# Every HiggsLinear needs a "workspace": a buffer for the unpacking operation.
|
| 160 |
+
# This buffer needs to be on the same device as the weights, but can be reused across modules otherwise.
|
| 161 |
+
if module.weight.device not in flute_workspaces:
|
| 162 |
+
flute_workspaces[module.weight.device] = flute.utils.make_workspace_streamk(
|
| 163 |
+
device=module.weight.device
|
| 164 |
+
)
|
| 165 |
+
module.workspace = flute_workspaces[module.weight.device]
|
| 166 |
+
|
| 167 |
+
# FLUTE weights are packed in a way that is optimized for a specific number of SMs (GPU streaming multiprocessors).
|
| 168 |
+
# If the model is loaded on a different device than the one it was saved on, we need to repack the weights.
|
| 169 |
+
if module.num_sms_packed.item() != get_num_sms_from_device(module.weight.device):
|
| 170 |
+
new_device = module.weight.device
|
| 171 |
+
new_num_sms = get_num_sms_from_device(new_device)
|
| 172 |
+
module.weight.data = flute.utils.pack(
|
| 173 |
+
flute.utils.unpack(
|
| 174 |
+
weight=module.weight.data,
|
| 175 |
+
scales=module.scales.data,
|
| 176 |
+
workspace=module.workspace,
|
| 177 |
+
num_bits=module.num_bits,
|
| 178 |
+
group_size=module.group_size,
|
| 179 |
+
num_sms_packed=module.num_sms_packed.item(),
|
| 180 |
+
).T.contiguous(),
|
| 181 |
+
module.num_bits,
|
| 182 |
+
module.group_size,
|
| 183 |
+
)
|
| 184 |
+
module.num_sms_packed = torch.nn.Parameter(
|
| 185 |
+
torch.tensor(new_num_sms, device=new_device, dtype=torch.int32),
|
| 186 |
+
requires_grad=False,
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
def update_missing_keys(self, model, missing_keys: List[str], prefix: str) -> List[str]:
|
| 190 |
+
from ..integrations import HiggsLinear
|
| 191 |
+
|
| 192 |
+
not_missing_keys = []
|
| 193 |
+
for name, module in model.named_modules():
|
| 194 |
+
if isinstance(module, HiggsLinear):
|
| 195 |
+
for missing in missing_keys:
|
| 196 |
+
if (
|
| 197 |
+
(name in missing or name in f"{prefix}.{missing}")
|
| 198 |
+
and not missing.endswith(".weight")
|
| 199 |
+
and not missing.endswith(".bias")
|
| 200 |
+
):
|
| 201 |
+
not_missing_keys.append(missing)
|
| 202 |
+
return [k for k in missing_keys if k not in not_missing_keys]
|
| 203 |
+
|
| 204 |
+
@property
|
| 205 |
+
def is_trainable(self, model: Optional["PreTrainedModel"] = None):
|
| 206 |
+
return False
|
| 207 |
+
|
| 208 |
+
def is_serializable(self, safe_serialization=None):
|
| 209 |
+
return True
|
| 210 |
+
|
| 211 |
+
def check_quantized_param(
|
| 212 |
+
self,
|
| 213 |
+
model: "PreTrainedModel",
|
| 214 |
+
param_value: "torch.Tensor",
|
| 215 |
+
param_name: str,
|
| 216 |
+
state_dict: Dict[str, Any],
|
| 217 |
+
**kwargs,
|
| 218 |
+
) -> bool:
|
| 219 |
+
from ..integrations import HiggsLinear
|
| 220 |
+
|
| 221 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 222 |
+
if isinstance(module, HiggsLinear) and tensor_name == "weight" and param_value.dtype != torch.int16:
|
| 223 |
+
# Only quantize weights of HiggsLinear modules that are not already quantized
|
| 224 |
+
return True
|
| 225 |
+
else:
|
| 226 |
+
return False
|
| 227 |
+
|
| 228 |
+
def _dequantize(self, model):
|
| 229 |
+
from ..integrations import dequantize_higgs
|
| 230 |
+
|
| 231 |
+
model = dequantize_higgs(model)
|
| 232 |
+
return model
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_hqq.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ved.
|
| 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 |
+
from typing import TYPE_CHECKING, Any, Dict, List
|
| 16 |
+
|
| 17 |
+
from ..integrations import prepare_for_hqq_linear
|
| 18 |
+
from ..utils import is_accelerate_available, is_hqq_available, is_torch_available, logging
|
| 19 |
+
from .base import HfQuantizer
|
| 20 |
+
from .quantizers_utils import get_module_from_name
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
from ..modeling_utils import PreTrainedModel
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if is_accelerate_available():
|
| 28 |
+
from accelerate.hooks import remove_hook_from_module
|
| 29 |
+
|
| 30 |
+
if is_torch_available():
|
| 31 |
+
import torch
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# Finds the parent of a node module named "name"
|
| 37 |
+
def find_parent(model, name):
|
| 38 |
+
module_tree = name.split(".")[:-1]
|
| 39 |
+
parent = model
|
| 40 |
+
for m in module_tree:
|
| 41 |
+
parent = parent._modules[m]
|
| 42 |
+
return parent
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class HqqHfQuantizer(HfQuantizer):
|
| 46 |
+
"""
|
| 47 |
+
HQQ quantizer base HF class.
|
| 48 |
+
nn.Linear modules are first tagged with quant_config in _process_model_before_weight_loading().
|
| 49 |
+
The actual quantization and offloading to the GPU is done in check_quantized_param().
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
use_keep_in_fp32_modules = False
|
| 53 |
+
requires_parameters_quantization = True
|
| 54 |
+
requires_calibration = False
|
| 55 |
+
required_packages = ["hqq"]
|
| 56 |
+
|
| 57 |
+
def __init__(self, quantization_config, **kwargs):
|
| 58 |
+
super().__init__(quantization_config, **kwargs)
|
| 59 |
+
self.torch_dtype = None
|
| 60 |
+
self.using_multi_gpu = False
|
| 61 |
+
|
| 62 |
+
def validate_environment(self, *args, **kwargs):
|
| 63 |
+
if not (is_hqq_available()):
|
| 64 |
+
raise ImportError(
|
| 65 |
+
"A valid HQQ version (>=0.2.1) is not available. Please follow the instructions to install it: `https://github.com/mobiusml/hqq/`."
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
if kwargs.get("from_tf", False) or kwargs.get("from_flax", False):
|
| 69 |
+
raise ValueError(
|
| 70 |
+
"Converting weights from tf/flax weights is currently not supported, please make"
|
| 71 |
+
" sure the weights are in PyTorch format."
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
if not torch.cuda.is_available():
|
| 75 |
+
raise RuntimeError("No GPU found. A GPU is needed for quantization.")
|
| 76 |
+
|
| 77 |
+
if self.torch_dtype is None:
|
| 78 |
+
if "torch_dtype" in kwargs:
|
| 79 |
+
self.torch_dtype = kwargs["torch_dtype"]
|
| 80 |
+
else:
|
| 81 |
+
self.torch_dtype = torch.float32
|
| 82 |
+
logger.info("Setting torch_dtype to torch.float32 as the default value since it was not specified.")
|
| 83 |
+
|
| 84 |
+
device_map = kwargs.get("device_map", None)
|
| 85 |
+
if isinstance(device_map, dict):
|
| 86 |
+
if "cpu" in device_map.values() or "disk" in device_map.values():
|
| 87 |
+
raise ValueError(
|
| 88 |
+
"You are attempting to use an HQQ model with a device_map that contains a CPU or disk device."
|
| 89 |
+
" This is not supported. Please remove the CPU or disk device from the device_map."
|
| 90 |
+
)
|
| 91 |
+
else:
|
| 92 |
+
self.using_multi_gpu = len(set(device_map.values())) > 1
|
| 93 |
+
|
| 94 |
+
def update_missing_keys(
|
| 95 |
+
self, model: "PreTrainedModel", missing_keys: List[str], prefix: str, **kwargs
|
| 96 |
+
) -> List[str]:
|
| 97 |
+
if self.pre_quantized:
|
| 98 |
+
return [key for key in missing_keys if ("weight" not in key)]
|
| 99 |
+
else:
|
| 100 |
+
return missing_keys
|
| 101 |
+
|
| 102 |
+
# Adds missing keys for HQQLinear modules that are loaded but the model with initialized with torch.nn.Linear
|
| 103 |
+
def update_expected_keys(
|
| 104 |
+
self, model: "PreTrainedModel", expected_keys: List[str], loaded_keys: List[str]
|
| 105 |
+
) -> List[str]:
|
| 106 |
+
if not self.pre_quantized:
|
| 107 |
+
return expected_keys
|
| 108 |
+
|
| 109 |
+
# Collects all quantizable (linear) layers
|
| 110 |
+
def _find_hqq_quantizable_layers(model, layers):
|
| 111 |
+
for name, module in model.named_children():
|
| 112 |
+
if isinstance(module, (torch.nn.Linear)):
|
| 113 |
+
layers.add(module.name)
|
| 114 |
+
_find_hqq_quantizable_layers(module, layers)
|
| 115 |
+
|
| 116 |
+
new_keys = set(expected_keys)
|
| 117 |
+
if is_hqq_available():
|
| 118 |
+
from hqq.core.quantize import HQQLinear
|
| 119 |
+
|
| 120 |
+
# Name modules
|
| 121 |
+
for name, module in model.named_modules():
|
| 122 |
+
module.name = name
|
| 123 |
+
|
| 124 |
+
# valid modules are Linear layers that have HQQLinear state_dict. We ignore skip_modules and any layers with Linear state_dict() params
|
| 125 |
+
_valid_modules = set()
|
| 126 |
+
_find_hqq_quantizable_layers(model, _valid_modules)
|
| 127 |
+
_valid_modules -= set(model.config.quantization_config["skip_modules"])
|
| 128 |
+
|
| 129 |
+
# Append new expected layers based on _ref_keys
|
| 130 |
+
_ref_keys = HQQLinear(
|
| 131 |
+
linear_layer=None, quant_config=None, compute_dtype=torch.float16, device="cpu"
|
| 132 |
+
).state_dict_keys() - {"bias"}
|
| 133 |
+
|
| 134 |
+
# Clean-up
|
| 135 |
+
_rm_keys = set()
|
| 136 |
+
for key in new_keys:
|
| 137 |
+
if any(_module in key for _module in _valid_modules):
|
| 138 |
+
_rm_keys.add(key)
|
| 139 |
+
new_keys -= _rm_keys
|
| 140 |
+
# At this point, new_keys contains all the keys of the layers that are NOT HQQLinear or torch.nn.Linear
|
| 141 |
+
|
| 142 |
+
# Re-populate Linear/HQQLinear
|
| 143 |
+
for _module in _valid_modules:
|
| 144 |
+
if _module + ".weight" in loaded_keys:
|
| 145 |
+
new_keys.add(_module + ".weight")
|
| 146 |
+
else:
|
| 147 |
+
new_keys.update({_module + "." + _ref_key for _ref_key in _ref_keys})
|
| 148 |
+
if _module + ".bias" in loaded_keys:
|
| 149 |
+
new_keys.add(_module + ".bias")
|
| 150 |
+
|
| 151 |
+
return list(new_keys)
|
| 152 |
+
|
| 153 |
+
def check_quantized_param(
|
| 154 |
+
self,
|
| 155 |
+
model: "PreTrainedModel",
|
| 156 |
+
param_value: "torch.Tensor",
|
| 157 |
+
param_name: str,
|
| 158 |
+
state_dict: Dict[str, Any],
|
| 159 |
+
**kwargs,
|
| 160 |
+
) -> bool:
|
| 161 |
+
if is_hqq_available():
|
| 162 |
+
from hqq.core.quantize import HQQLinear
|
| 163 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 164 |
+
|
| 165 |
+
if self.pre_quantized:
|
| 166 |
+
return (
|
| 167 |
+
(isinstance(module, torch.nn.Linear) or isinstance(module, HQQLinear))
|
| 168 |
+
and tensor_name != "weight"
|
| 169 |
+
and tensor_name != "bias"
|
| 170 |
+
)
|
| 171 |
+
else:
|
| 172 |
+
return isinstance(module, torch.nn.Linear) and tensor_name == "weight"
|
| 173 |
+
|
| 174 |
+
def create_quantized_param(
|
| 175 |
+
self,
|
| 176 |
+
model: "PreTrainedModel",
|
| 177 |
+
param_value: "torch.Tensor",
|
| 178 |
+
param_name: str,
|
| 179 |
+
target_device: "torch.device",
|
| 180 |
+
state_dict: Dict[str, Any],
|
| 181 |
+
unexpected_keys: List[str],
|
| 182 |
+
):
|
| 183 |
+
"""
|
| 184 |
+
Each nn.Linear layer is processsed here.
|
| 185 |
+
We first check if the corresponding module state_dict contains already HQQ quantized parameters.
|
| 186 |
+
If not, we create a temp linear layer with the module state_dict params and use it for quantization
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
if is_hqq_available():
|
| 190 |
+
from hqq.core.quantize import HQQLinear
|
| 191 |
+
|
| 192 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 193 |
+
layer_name = ".".join(param_name.split(".")[:-1])
|
| 194 |
+
parent_module = find_parent(model, layer_name)
|
| 195 |
+
node = layer_name.split(".")[-1]
|
| 196 |
+
|
| 197 |
+
# set module state_dict
|
| 198 |
+
module_state_dict = {}
|
| 199 |
+
for k, v in state_dict.items():
|
| 200 |
+
if layer_name + "." in k:
|
| 201 |
+
module_state_dict[k.split(".")[-1]] = v
|
| 202 |
+
if unexpected_keys is not None and k in unexpected_keys:
|
| 203 |
+
unexpected_keys.remove(k)
|
| 204 |
+
|
| 205 |
+
if self.pre_quantized:
|
| 206 |
+
if isinstance(module, HQQLinear):
|
| 207 |
+
return
|
| 208 |
+
else:
|
| 209 |
+
hqq_layer = HQQLinear(
|
| 210 |
+
linear_layer=None,
|
| 211 |
+
quant_config=None,
|
| 212 |
+
compute_dtype=self.torch_dtype,
|
| 213 |
+
device=target_device,
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
hqq_layer.load_state_dict(module_state_dict)
|
| 217 |
+
|
| 218 |
+
if hqq_layer.bias is not None and isinstance(hqq_layer.bias, torch.Tensor):
|
| 219 |
+
hqq_layer.bias = torch.nn.Parameter(hqq_layer.bias)
|
| 220 |
+
|
| 221 |
+
if self.using_multi_gpu:
|
| 222 |
+
hqq_layer = self._patch_layer_for_multigpu(hqq_layer)
|
| 223 |
+
|
| 224 |
+
setattr(parent_module, node, hqq_layer)
|
| 225 |
+
|
| 226 |
+
# cleanup
|
| 227 |
+
del module.__dict__, module
|
| 228 |
+
torch.cuda.empty_cache()
|
| 229 |
+
return
|
| 230 |
+
|
| 231 |
+
# Step 1: populate module with weight/bias from module state dict
|
| 232 |
+
for key in module_state_dict:
|
| 233 |
+
setattr(module, key, torch.nn.Parameter(module_state_dict[key]))
|
| 234 |
+
|
| 235 |
+
# Step 2: Replace module with either HQQLinear or move it to device. We do this via setattr on the parent as doing on it on the module
|
| 236 |
+
# directly doesn't work.
|
| 237 |
+
if hasattr(module, "quant_config"):
|
| 238 |
+
hqq_layer = HQQLinear(
|
| 239 |
+
module,
|
| 240 |
+
module.quant_config,
|
| 241 |
+
compute_dtype=self.torch_dtype,
|
| 242 |
+
device=target_device,
|
| 243 |
+
del_orig=True,
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
if hqq_layer.bias is not None and isinstance(hqq_layer.bias, torch.Tensor):
|
| 247 |
+
hqq_layer.bias = torch.nn.Parameter(hqq_layer.bias)
|
| 248 |
+
|
| 249 |
+
if self.using_multi_gpu:
|
| 250 |
+
hqq_layer = self._patch_layer_for_multigpu(hqq_layer)
|
| 251 |
+
|
| 252 |
+
setattr(parent_module, node, hqq_layer)
|
| 253 |
+
|
| 254 |
+
else:
|
| 255 |
+
module = module.to(dtype=self.torch_dtype, device=target_device)
|
| 256 |
+
setattr(parent_module, node, module)
|
| 257 |
+
|
| 258 |
+
torch.cuda.empty_cache()
|
| 259 |
+
|
| 260 |
+
# Remove accelerate hook and uses a simpler forward pass. Otherwise, this breaks with multi-gpu
|
| 261 |
+
def _patch_layer_for_multigpu(self, hqq_layer):
|
| 262 |
+
hqq_layer = remove_hook_from_module(hqq_layer)
|
| 263 |
+
|
| 264 |
+
def forward_with_device(self, x):
|
| 265 |
+
out = torch.matmul(x.to(self.device), self.dequantize().t())
|
| 266 |
+
if self.bias is not None:
|
| 267 |
+
out += self.bias
|
| 268 |
+
return out
|
| 269 |
+
|
| 270 |
+
hqq_layer.forward = lambda x: forward_with_device(hqq_layer, x)
|
| 271 |
+
return hqq_layer
|
| 272 |
+
|
| 273 |
+
def _process_model_before_weight_loading(
|
| 274 |
+
self,
|
| 275 |
+
model: "PreTrainedModel",
|
| 276 |
+
device_map,
|
| 277 |
+
keep_in_fp32_modules: List[str] = None,
|
| 278 |
+
**kwargs,
|
| 279 |
+
):
|
| 280 |
+
keep_in_fp32_modules = keep_in_fp32_modules if keep_in_fp32_modules is not None else []
|
| 281 |
+
|
| 282 |
+
# Add the corresponding quant_config to each valid module. This allows us to do the actual nn.Linear -> HQQLinear conversion in create_quantized_param().
|
| 283 |
+
# prepare_for_hqq_linear() also sets the right quantization config inside the model (model.config.quantization_config) and the layers (hqq_layer.quant_config)
|
| 284 |
+
model = prepare_for_hqq_linear(model, quantization_config=self.quantization_config)
|
| 285 |
+
|
| 286 |
+
def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
|
| 287 |
+
model.is_hqq_quantized = True
|
| 288 |
+
model.is_hqq_serializable = self.is_serializable()
|
| 289 |
+
return model
|
| 290 |
+
|
| 291 |
+
def is_serializable(self, safe_serialization=None):
|
| 292 |
+
return True
|
| 293 |
+
|
| 294 |
+
@property
|
| 295 |
+
def is_trainable(self) -> bool:
|
| 296 |
+
return True
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_quanto.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
# 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 importlib
|
| 15 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
|
| 16 |
+
|
| 17 |
+
from packaging import version
|
| 18 |
+
|
| 19 |
+
from .base import HfQuantizer
|
| 20 |
+
from .quantizers_utils import get_module_from_name
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
from ..modeling_utils import PreTrainedModel
|
| 25 |
+
|
| 26 |
+
from ..utils import (
|
| 27 |
+
is_accelerate_available,
|
| 28 |
+
is_optimum_quanto_available,
|
| 29 |
+
is_torch_available,
|
| 30 |
+
logging,
|
| 31 |
+
)
|
| 32 |
+
from ..utils.quantization_config import QuantoConfig
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if is_torch_available():
|
| 36 |
+
import torch
|
| 37 |
+
|
| 38 |
+
logger = logging.get_logger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class QuantoHfQuantizer(HfQuantizer):
|
| 42 |
+
"""
|
| 43 |
+
Quantizer for the quanto library
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
required_packages = ["quanto", "accelerate"]
|
| 47 |
+
requires_parameters_quantization = True
|
| 48 |
+
requires_calibration = False
|
| 49 |
+
|
| 50 |
+
def __init__(self, quantization_config: QuantoConfig, **kwargs):
|
| 51 |
+
super().__init__(quantization_config, **kwargs)
|
| 52 |
+
self.post_init()
|
| 53 |
+
|
| 54 |
+
def post_init(self):
|
| 55 |
+
r"""
|
| 56 |
+
Safety checker
|
| 57 |
+
"""
|
| 58 |
+
if self.quantization_config.activations is not None and not self.pre_quantized:
|
| 59 |
+
raise ValueError(
|
| 60 |
+
"We don't support quantizing the activations with transformers library."
|
| 61 |
+
"Use quanto library for more complex use cases such as activations quantization, calibration and quantization aware training."
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
def validate_environment(self, *args, **kwargs):
|
| 65 |
+
if not is_optimum_quanto_available():
|
| 66 |
+
raise ImportError(
|
| 67 |
+
"Loading an optimum-quanto quantized model requires optimum-quanto library (`pip install optimum-quanto`)"
|
| 68 |
+
)
|
| 69 |
+
if not is_accelerate_available():
|
| 70 |
+
raise ImportError(
|
| 71 |
+
"Loading an optimum-quanto quantized model requires accelerate library (`pip install accelerate`)"
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def update_device_map(self, device_map):
|
| 75 |
+
if device_map is None:
|
| 76 |
+
device_map = {"": "cpu"}
|
| 77 |
+
logger.info(
|
| 78 |
+
"The device_map was not initialized. "
|
| 79 |
+
"Setting device_map to {'':'cpu'}. "
|
| 80 |
+
"If you want to use the model for inference, please set device_map ='auto'"
|
| 81 |
+
)
|
| 82 |
+
return device_map
|
| 83 |
+
|
| 84 |
+
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 85 |
+
if torch_dtype is None:
|
| 86 |
+
logger.info("You did not specify `torch_dtype` in `from_pretrained`. Setting it to `torch.float32`.")
|
| 87 |
+
torch_dtype = torch.float32
|
| 88 |
+
return torch_dtype
|
| 89 |
+
|
| 90 |
+
def update_missing_keys(self, model, missing_keys: List[str], prefix: str) -> List[str]:
|
| 91 |
+
if is_optimum_quanto_available():
|
| 92 |
+
from optimum.quanto import QModuleMixin
|
| 93 |
+
|
| 94 |
+
not_missing_keys = []
|
| 95 |
+
for name, module in model.named_modules():
|
| 96 |
+
if isinstance(module, QModuleMixin):
|
| 97 |
+
for missing in missing_keys:
|
| 98 |
+
if (
|
| 99 |
+
(name in missing or name in f"{prefix}.{missing}")
|
| 100 |
+
and not missing.endswith(".weight")
|
| 101 |
+
and not missing.endswith(".bias")
|
| 102 |
+
):
|
| 103 |
+
not_missing_keys.append(missing)
|
| 104 |
+
return [k for k in missing_keys if k not in not_missing_keys]
|
| 105 |
+
|
| 106 |
+
def check_quantized_param(
|
| 107 |
+
self,
|
| 108 |
+
model: "PreTrainedModel",
|
| 109 |
+
param_value: "torch.Tensor",
|
| 110 |
+
param_name: str,
|
| 111 |
+
state_dict: Dict[str, Any],
|
| 112 |
+
**kwargs,
|
| 113 |
+
) -> bool:
|
| 114 |
+
"""
|
| 115 |
+
Check if a parameter needs to be quantized.
|
| 116 |
+
"""
|
| 117 |
+
if is_optimum_quanto_available():
|
| 118 |
+
from optimum.quanto import QModuleMixin
|
| 119 |
+
|
| 120 |
+
device_map = kwargs.get("device_map", None)
|
| 121 |
+
param_device = kwargs.get("param_device", None)
|
| 122 |
+
# we don't quantize the model if the module is going to be offloaded to the cpu
|
| 123 |
+
if device_map is not None and param_device is not None:
|
| 124 |
+
device_map_values = set(device_map.values())
|
| 125 |
+
if param_device == "cpu" and len(device_map_values) > 1:
|
| 126 |
+
if not (device_map_values == {"cpu"} or device_map_values == {"cpu", "disk"}):
|
| 127 |
+
return False
|
| 128 |
+
|
| 129 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 130 |
+
# We only quantize the weights and the bias is not quantized.
|
| 131 |
+
if isinstance(module, QModuleMixin) and "weight" in tensor_name:
|
| 132 |
+
# if the weights are quantized, don't need to recreate it again with `create_quantized_param`
|
| 133 |
+
return not module.frozen
|
| 134 |
+
else:
|
| 135 |
+
return False
|
| 136 |
+
|
| 137 |
+
def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
|
| 138 |
+
max_memory = {key: val * 0.90 for key, val in max_memory.items()}
|
| 139 |
+
return max_memory
|
| 140 |
+
|
| 141 |
+
def create_quantized_param(
|
| 142 |
+
self,
|
| 143 |
+
model: "PreTrainedModel",
|
| 144 |
+
param_value: "torch.Tensor",
|
| 145 |
+
param_name: str,
|
| 146 |
+
target_device: "torch.device",
|
| 147 |
+
*args,
|
| 148 |
+
**kwargs,
|
| 149 |
+
):
|
| 150 |
+
"""
|
| 151 |
+
Create the quantized parameter by calling .freeze() after setting it to the module.
|
| 152 |
+
"""
|
| 153 |
+
from accelerate.utils import set_module_tensor_to_device
|
| 154 |
+
|
| 155 |
+
set_module_tensor_to_device(model, param_name, target_device, param_value)
|
| 156 |
+
module, _ = get_module_from_name(model, param_name)
|
| 157 |
+
module.freeze()
|
| 158 |
+
module.weight.requires_grad = False
|
| 159 |
+
|
| 160 |
+
def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
|
| 161 |
+
if version.parse(importlib.metadata.version("accelerate")) > version.parse("0.27.0"):
|
| 162 |
+
from accelerate.utils import CustomDtype
|
| 163 |
+
|
| 164 |
+
mapping = {
|
| 165 |
+
"int8": torch.int8,
|
| 166 |
+
"float8": CustomDtype.FP8,
|
| 167 |
+
"int4": CustomDtype.INT4,
|
| 168 |
+
"int2": CustomDtype.INT2,
|
| 169 |
+
}
|
| 170 |
+
target_dtype = mapping[self.quantization_config.weights]
|
| 171 |
+
return target_dtype
|
| 172 |
+
else:
|
| 173 |
+
raise ValueError(
|
| 174 |
+
"You are using `device_map='auto'` on an optimum-quanto quantized model. To automatically compute"
|
| 175 |
+
" the appropriate device map, you should upgrade your `accelerate` library,"
|
| 176 |
+
"`pip install --upgrade accelerate` or install it from source."
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
def _process_model_before_weight_loading(
|
| 180 |
+
self, model: "PreTrainedModel", keep_in_fp32_modules: List[str] = [], **kwargs
|
| 181 |
+
):
|
| 182 |
+
from ..integrations import get_keys_to_not_convert, replace_with_quanto_layers
|
| 183 |
+
|
| 184 |
+
# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
|
| 185 |
+
if self.quantization_config.modules_to_not_convert is None:
|
| 186 |
+
self.modules_to_not_convert = get_keys_to_not_convert(model)
|
| 187 |
+
else:
|
| 188 |
+
self.modules_to_not_convert = self.quantization_config.modules_to_not_convert
|
| 189 |
+
|
| 190 |
+
if not isinstance(self.modules_to_not_convert, list):
|
| 191 |
+
self.modules_to_not_convert = [self.modules_to_not_convert]
|
| 192 |
+
|
| 193 |
+
self.modules_to_not_convert.extend(keep_in_fp32_modules)
|
| 194 |
+
|
| 195 |
+
model, _ = replace_with_quanto_layers(
|
| 196 |
+
model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
|
| 197 |
+
)
|
| 198 |
+
model.config.quantization_config = self.quantization_config
|
| 199 |
+
|
| 200 |
+
def _process_model_after_weight_loading(self, model, **kwargs):
|
| 201 |
+
return model
|
| 202 |
+
|
| 203 |
+
@property
|
| 204 |
+
def is_trainable(self, model: Optional["PreTrainedModel"] = None):
|
| 205 |
+
return True
|
| 206 |
+
|
| 207 |
+
def is_serializable(self, safe_serialization=None):
|
| 208 |
+
return False
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_torchao.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 importlib
|
| 15 |
+
import types
|
| 16 |
+
from typing import TYPE_CHECKING, Union
|
| 17 |
+
|
| 18 |
+
from packaging import version
|
| 19 |
+
|
| 20 |
+
from .base import HfQuantizer
|
| 21 |
+
from .quantizers_utils import get_module_from_name
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if TYPE_CHECKING:
|
| 25 |
+
from ..modeling_utils import PreTrainedModel
|
| 26 |
+
|
| 27 |
+
from typing import Any, Dict, List
|
| 28 |
+
|
| 29 |
+
from ..utils import is_torch_available, is_torchao_available, logging
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if is_torch_available():
|
| 33 |
+
import torch
|
| 34 |
+
import torch.nn as nn
|
| 35 |
+
|
| 36 |
+
logger = logging.get_logger(__name__)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Finds the parent of a node module named "name"
|
| 40 |
+
def find_parent(model, name):
|
| 41 |
+
module_tree = name.split(".")[:-1]
|
| 42 |
+
parent = model
|
| 43 |
+
for m in module_tree:
|
| 44 |
+
parent = parent._modules[m]
|
| 45 |
+
return parent
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _quantization_type(weight):
|
| 49 |
+
from torchao.dtypes import AffineQuantizedTensor
|
| 50 |
+
from torchao.quantization.linear_activation_quantized_tensor import LinearActivationQuantizedTensor
|
| 51 |
+
|
| 52 |
+
if isinstance(weight, AffineQuantizedTensor):
|
| 53 |
+
return f"{weight.__class__.__name__}({weight._quantization_type()})"
|
| 54 |
+
|
| 55 |
+
if isinstance(weight, LinearActivationQuantizedTensor):
|
| 56 |
+
return f"{weight.__class__.__name__}(activation={weight.input_quant_func}, weight={_quantization_type(weight.original_weight_tensor)})"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _linear_extra_repr(self):
|
| 60 |
+
weight = _quantization_type(self.weight)
|
| 61 |
+
if weight is None:
|
| 62 |
+
return f"in_features={self.weight.shape[1]}, out_features={self.weight.shape[0]}, weight=None"
|
| 63 |
+
else:
|
| 64 |
+
return f"in_features={self.weight.shape[1]}, out_features={self.weight.shape[0]}, weight={weight}"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class TorchAoHfQuantizer(HfQuantizer):
|
| 68 |
+
"""
|
| 69 |
+
Quantizer for torchao: https://github.com/pytorch/ao/
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
requires_parameters_quantization = True
|
| 73 |
+
requires_calibration = False
|
| 74 |
+
required_packages = ["torchao"]
|
| 75 |
+
|
| 76 |
+
def __init__(self, quantization_config, **kwargs):
|
| 77 |
+
super().__init__(quantization_config, **kwargs)
|
| 78 |
+
|
| 79 |
+
def validate_environment(self, *args, **kwargs):
|
| 80 |
+
if not is_torchao_available():
|
| 81 |
+
raise ImportError("Loading an torchao quantized model requires torchao library (`pip install torchao`)")
|
| 82 |
+
|
| 83 |
+
self.offload = False
|
| 84 |
+
device_map = kwargs.get("device_map", None)
|
| 85 |
+
if isinstance(device_map, dict):
|
| 86 |
+
if "cpu" in device_map.values() or "disk" in device_map.values():
|
| 87 |
+
if self.pre_quantized:
|
| 88 |
+
raise ValueError(
|
| 89 |
+
"You are attempting to perform cpu/disk offload with a pre-quantized torchao model "
|
| 90 |
+
"This is not supported yet . Please remove the CPU or disk device from the device_map."
|
| 91 |
+
)
|
| 92 |
+
else:
|
| 93 |
+
self.offload = True
|
| 94 |
+
if self.pre_quantized:
|
| 95 |
+
weights_only = kwargs.get("weights_only", None)
|
| 96 |
+
if weights_only:
|
| 97 |
+
torch_version = version.parse(importlib.metadata.version("torch"))
|
| 98 |
+
if torch_version < version.parse("2.5.0"):
|
| 99 |
+
raise RuntimeError(
|
| 100 |
+
f"In order to use torchao pre-quantized model, you need to have torch>=2.5.0. However, the current version is {torch_version}."
|
| 101 |
+
f" You can also set with `weights_only=False` in `from_pretrained` if you don't want to update torch"
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
def update_torch_dtype(self, torch_dtype):
|
| 105 |
+
if self.quantization_config.quant_type == "int4_weight_only":
|
| 106 |
+
if torch_dtype is not None and torch_dtype != torch.bfloat16:
|
| 107 |
+
logger.warning_once(
|
| 108 |
+
f"Setting torch_dtype to {torch_dtype} for int4_weight_only quantization, but only bfloat16 is supported right now. Please set the torch_dtype to bfloat16."
|
| 109 |
+
)
|
| 110 |
+
if torch_dtype is None:
|
| 111 |
+
logger.warning_once(
|
| 112 |
+
"Setting torch_dtype to torch.bfloat16 for int4_weight_only quantization since only bfloat16 is supported right now. Please set torch_dtype=torch.bfloat16 to remove this warning."
|
| 113 |
+
)
|
| 114 |
+
torch_dtype = torch.bfloat16
|
| 115 |
+
if self.quantization_config.quant_type == "int8_dynamic_activation_int8_weight":
|
| 116 |
+
if torch_dtype is None:
|
| 117 |
+
logger.info(
|
| 118 |
+
"Setting torch_dtype to torch.float32 for int8_dynamic_activation_int8_weight quantization as no torch_dtype was specified in from_pretrained"
|
| 119 |
+
)
|
| 120 |
+
# we need to set the torch_dtype, otherwise we have dtype mismatch when performing the quantized linear op
|
| 121 |
+
torch_dtype = torch.float32
|
| 122 |
+
return torch_dtype
|
| 123 |
+
|
| 124 |
+
def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
|
| 125 |
+
if version.parse(importlib.metadata.version("accelerate")) > version.parse("0.19.0"):
|
| 126 |
+
from accelerate.utils import CustomDtype
|
| 127 |
+
|
| 128 |
+
map_to_target_dtype = {
|
| 129 |
+
"int4_weight_only": CustomDtype.INT4,
|
| 130 |
+
"int8_weight_only": torch.int8,
|
| 131 |
+
"int8_dynamic_activation_int8_weight": torch.int8,
|
| 132 |
+
}
|
| 133 |
+
return map_to_target_dtype[self.quantization_config.quant_type]
|
| 134 |
+
else:
|
| 135 |
+
raise ValueError(
|
| 136 |
+
"You are using `device_map='auto'` on a torchao quantized model. To automatically compute"
|
| 137 |
+
" the appropriate device map, you should upgrade your `accelerate` library with "
|
| 138 |
+
"`pip install --upgrade accelerate`"
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
|
| 142 |
+
# need more space for the quantization parameters (e.g. scale). Tested with int4 wo and group size = 128
|
| 143 |
+
max_memory = {key: val * 0.9 for key, val in max_memory.items()}
|
| 144 |
+
return max_memory
|
| 145 |
+
|
| 146 |
+
def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs):
|
| 147 |
+
from ..integrations import get_keys_to_not_convert
|
| 148 |
+
|
| 149 |
+
self.modules_to_not_convert = get_keys_to_not_convert(model)
|
| 150 |
+
|
| 151 |
+
if self.quantization_config.modules_to_not_convert is not None:
|
| 152 |
+
self.modules_to_not_convert.extend(self.quantization_config.modules_to_not_convert)
|
| 153 |
+
|
| 154 |
+
return
|
| 155 |
+
|
| 156 |
+
def check_quantized_param(
|
| 157 |
+
self,
|
| 158 |
+
model: "PreTrainedModel",
|
| 159 |
+
param_value: "torch.Tensor",
|
| 160 |
+
param_name: str,
|
| 161 |
+
state_dict: Dict[str, Any],
|
| 162 |
+
**kwargs,
|
| 163 |
+
) -> bool:
|
| 164 |
+
param_device = kwargs.pop("param_device", None)
|
| 165 |
+
# check if the param_name is not in self.modules_to_not_convert
|
| 166 |
+
if any((key + "." in param_name) or (key == param_name) for key in self.modules_to_not_convert):
|
| 167 |
+
return False
|
| 168 |
+
elif param_device == "cpu" and self.offload:
|
| 169 |
+
# We don't quantize weights that we offload
|
| 170 |
+
return False
|
| 171 |
+
else:
|
| 172 |
+
# we only quantize the weight of nn.Linear
|
| 173 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 174 |
+
return isinstance(module, torch.nn.Linear) and (tensor_name == "weight")
|
| 175 |
+
|
| 176 |
+
def create_quantized_param(
|
| 177 |
+
self,
|
| 178 |
+
model: "PreTrainedModel",
|
| 179 |
+
param_value: "torch.Tensor",
|
| 180 |
+
param_name: str,
|
| 181 |
+
target_device: "torch.device",
|
| 182 |
+
state_dict: Dict[str, Any],
|
| 183 |
+
unexpected_keys: List[str],
|
| 184 |
+
):
|
| 185 |
+
"""
|
| 186 |
+
Each nn.Linear layer that needs to be quantized is processsed here.
|
| 187 |
+
First, we set the value the weight tensor, then we move it to the target device. Finally, we quantize the module.
|
| 188 |
+
"""
|
| 189 |
+
from torchao.quantization import quantize_
|
| 190 |
+
|
| 191 |
+
module, tensor_name = get_module_from_name(model, param_name)
|
| 192 |
+
|
| 193 |
+
if self.pre_quantized:
|
| 194 |
+
module._parameters[tensor_name] = torch.nn.Parameter(param_value.to(device=target_device))
|
| 195 |
+
if isinstance(module, nn.Linear):
|
| 196 |
+
module.extra_repr = types.MethodType(_linear_extra_repr, module)
|
| 197 |
+
else:
|
| 198 |
+
module._parameters[tensor_name] = torch.nn.Parameter(param_value).to(device=target_device)
|
| 199 |
+
quantize_(module, self.quantization_config.get_apply_tensor_subclass())
|
| 200 |
+
|
| 201 |
+
def _process_model_after_weight_loading(self, model, **kwargs):
|
| 202 |
+
"""No process required for torchao quantized model"""
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
def is_serializable(self, safe_serialization=None):
|
| 206 |
+
if safe_serialization:
|
| 207 |
+
logger.warning(
|
| 208 |
+
"torchao quantized model does not support safe serialization, "
|
| 209 |
+
"please set `safe_serialization` to False"
|
| 210 |
+
)
|
| 211 |
+
return False
|
| 212 |
+
_is_torchao_serializable = version.parse(importlib.metadata.version("huggingface_hub")) >= version.parse(
|
| 213 |
+
"0.25.0"
|
| 214 |
+
)
|
| 215 |
+
if not _is_torchao_serializable:
|
| 216 |
+
logger.warning("torchao quantized model is only serializable after huggingface_hub >= 0.25.0 ")
|
| 217 |
+
if self.offload and self.quantization_config.modules_to_not_convert is None:
|
| 218 |
+
logger.warning(
|
| 219 |
+
"The model contains offloaded modules and these modules are not quantized. We don't recommend saving the model as we won't be able to reload them."
|
| 220 |
+
"If you want to specify modules to not quantize, please specify modules_to_not_convert in the quantization_config."
|
| 221 |
+
)
|
| 222 |
+
return False
|
| 223 |
+
return _is_torchao_serializable
|
| 224 |
+
|
| 225 |
+
@property
|
| 226 |
+
def is_trainable(self):
|
| 227 |
+
supported_quant_types_for_training = [
|
| 228 |
+
"int8_weight_only",
|
| 229 |
+
"int8_dynamic_activation_int8_weight",
|
| 230 |
+
]
|
| 231 |
+
return self.quantization_config.quant_type in supported_quant_types_for_training
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizer_vptq.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 |
+
from typing import TYPE_CHECKING, Optional
|
| 15 |
+
|
| 16 |
+
from .base import HfQuantizer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from ..modeling_utils import PreTrainedModel
|
| 21 |
+
|
| 22 |
+
from ..utils import is_accelerate_available, is_torch_available, is_vptq_available, logging
|
| 23 |
+
from ..utils.quantization_config import QuantizationConfigMixin
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if is_torch_available():
|
| 27 |
+
import torch
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class VptqHfQuantizer(HfQuantizer):
|
| 33 |
+
"""
|
| 34 |
+
Quantizer of the VPTQ method. Enables the loading of prequantized models.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
requires_calibration = True
|
| 38 |
+
required_packages = ["vptq"]
|
| 39 |
+
|
| 40 |
+
def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
|
| 41 |
+
super().__init__(quantization_config, **kwargs)
|
| 42 |
+
self.quantization_config = quantization_config
|
| 43 |
+
|
| 44 |
+
def validate_environment(self, *args, **kwargs):
|
| 45 |
+
if not is_accelerate_available():
|
| 46 |
+
raise ImportError("Using `vptq` quantization requires Accelerate: `pip install accelerate`")
|
| 47 |
+
|
| 48 |
+
if not is_vptq_available():
|
| 49 |
+
raise ImportError("Using `vptq` quantization requires VPTQ>=0.0.4: `pip install -U vptq`")
|
| 50 |
+
|
| 51 |
+
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 52 |
+
if torch_dtype is None:
|
| 53 |
+
if torch.cuda.is_available():
|
| 54 |
+
torch_dtype = torch.float16
|
| 55 |
+
logger.info(
|
| 56 |
+
"CUDA available. Assuming VPTQ inference on GPU and loading the model in `torch.float16`. To overwrite it, set `torch_dtype` manually."
|
| 57 |
+
)
|
| 58 |
+
else:
|
| 59 |
+
import vptq
|
| 60 |
+
|
| 61 |
+
device_availability = getattr(vptq, "device_availability", lambda device: False)
|
| 62 |
+
if device_availability("cpu") is True:
|
| 63 |
+
raise RuntimeError("No GPU found. Please wait for the next release of VPTQ to use CPU inference")
|
| 64 |
+
torch_dtype = torch.float32
|
| 65 |
+
logger.info("No GPU found. Assuming VPTQ inference on CPU and loading the model in `torch.float32`.")
|
| 66 |
+
return torch_dtype
|
| 67 |
+
|
| 68 |
+
def _process_model_before_weight_loading(
|
| 69 |
+
self,
|
| 70 |
+
model: "PreTrainedModel",
|
| 71 |
+
**kwargs,
|
| 72 |
+
):
|
| 73 |
+
"""
|
| 74 |
+
we don't have param like modules_to_not_convert to indicate which layers should not be quantized
|
| 75 |
+
because `quantization_config` include the layers that should be quantized
|
| 76 |
+
"""
|
| 77 |
+
from ..integrations import replace_with_vptq_linear
|
| 78 |
+
|
| 79 |
+
modules_to_not_convert = kwargs.get("modules_to_not_convert", []) + (
|
| 80 |
+
self.quantization_config.modules_to_not_convert or []
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
replace_with_vptq_linear(
|
| 84 |
+
model,
|
| 85 |
+
quantization_config=self.quantization_config,
|
| 86 |
+
modules_to_not_convert=modules_to_not_convert,
|
| 87 |
+
)
|
| 88 |
+
model.config.quantization_config = self.quantization_config
|
| 89 |
+
|
| 90 |
+
def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
|
| 91 |
+
return model
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def is_trainable(self, model: Optional["PreTrainedModel"] = None):
|
| 95 |
+
return False
|
| 96 |
+
|
| 97 |
+
def is_serializable(self, safe_serialization=None):
|
| 98 |
+
return True
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/quantizers/quantizers_utils.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 |
+
from typing import Any, Tuple
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_module_from_name(module, tensor_name: str) -> Tuple[Any, str]:
|
| 18 |
+
if "." in tensor_name:
|
| 19 |
+
splits = tensor_name.split(".")
|
| 20 |
+
for split in splits[:-1]:
|
| 21 |
+
new_module = getattr(module, split)
|
| 22 |
+
if new_module is None:
|
| 23 |
+
raise ValueError(f"{module} has no attribute {split}.")
|
| 24 |
+
module = new_module
|
| 25 |
+
tensor_name = splits[-1]
|
| 26 |
+
return module, tensor_name
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/safetensors_conversion.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
import requests
|
| 4 |
+
from huggingface_hub import Discussion, HfApi, get_repo_discussions
|
| 5 |
+
|
| 6 |
+
from .utils import cached_file, http_user_agent, logging
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
logger = logging.get_logger(__name__)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def previous_pr(api: HfApi, model_id: str, pr_title: str, token: str) -> Optional["Discussion"]:
|
| 13 |
+
main_commit = api.list_repo_commits(model_id, token=token)[0].commit_id
|
| 14 |
+
for discussion in get_repo_discussions(repo_id=model_id, token=token):
|
| 15 |
+
if discussion.title == pr_title and discussion.status == "open" and discussion.is_pull_request:
|
| 16 |
+
commits = api.list_repo_commits(model_id, revision=discussion.git_reference, token=token)
|
| 17 |
+
|
| 18 |
+
if main_commit == commits[1].commit_id:
|
| 19 |
+
return discussion
|
| 20 |
+
return None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def spawn_conversion(token: str, private: bool, model_id: str):
|
| 24 |
+
logger.info("Attempting to convert .bin model on the fly to safetensors.")
|
| 25 |
+
|
| 26 |
+
safetensors_convert_space_url = "https://safetensors-convert.hf.space"
|
| 27 |
+
sse_url = f"{safetensors_convert_space_url}/call/run"
|
| 28 |
+
|
| 29 |
+
def start(_sse_connection):
|
| 30 |
+
for line in _sse_connection.iter_lines():
|
| 31 |
+
line = line.decode()
|
| 32 |
+
if line.startswith("event:"):
|
| 33 |
+
status = line[7:]
|
| 34 |
+
logger.debug(f"Safetensors conversion status: {status}")
|
| 35 |
+
|
| 36 |
+
if status == "complete":
|
| 37 |
+
return
|
| 38 |
+
elif status == "heartbeat":
|
| 39 |
+
logger.debug("Heartbeat")
|
| 40 |
+
else:
|
| 41 |
+
logger.debug(f"Unknown status {status}")
|
| 42 |
+
else:
|
| 43 |
+
logger.debug(line)
|
| 44 |
+
|
| 45 |
+
data = {"data": [model_id, private, token]}
|
| 46 |
+
|
| 47 |
+
result = requests.post(sse_url, stream=True, json=data).json()
|
| 48 |
+
event_id = result["event_id"]
|
| 49 |
+
|
| 50 |
+
with requests.get(f"{sse_url}/{event_id}", stream=True) as sse_connection:
|
| 51 |
+
try:
|
| 52 |
+
logger.debug("Spawning safetensors automatic conversion.")
|
| 53 |
+
start(sse_connection)
|
| 54 |
+
except Exception as e:
|
| 55 |
+
logger.warning(f"Error during conversion: {repr(e)}")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def get_conversion_pr_reference(api: HfApi, model_id: str, **kwargs):
|
| 59 |
+
private = api.model_info(model_id).private
|
| 60 |
+
|
| 61 |
+
logger.info("Attempting to create safetensors variant")
|
| 62 |
+
pr_title = "Adding `safetensors` variant of this model"
|
| 63 |
+
token = kwargs.get("token")
|
| 64 |
+
|
| 65 |
+
# This looks into the current repo's open PRs to see if a PR for safetensors was already open. If so, it
|
| 66 |
+
# returns it. It checks that the PR was opened by the bot and not by another user so as to prevent
|
| 67 |
+
# security breaches.
|
| 68 |
+
pr = previous_pr(api, model_id, pr_title, token=token)
|
| 69 |
+
|
| 70 |
+
if pr is None or (not private and pr.author != "SFconvertbot"):
|
| 71 |
+
spawn_conversion(token, private, model_id)
|
| 72 |
+
pr = previous_pr(api, model_id, pr_title, token=token)
|
| 73 |
+
else:
|
| 74 |
+
logger.info("Safetensors PR exists")
|
| 75 |
+
|
| 76 |
+
sha = f"refs/pr/{pr.num}"
|
| 77 |
+
|
| 78 |
+
return sha
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def auto_conversion(pretrained_model_name_or_path: str, ignore_errors_during_conversion=False, **cached_file_kwargs):
|
| 82 |
+
try:
|
| 83 |
+
api = HfApi(token=cached_file_kwargs.get("token"), headers={"user-agent": http_user_agent()})
|
| 84 |
+
sha = get_conversion_pr_reference(api, pretrained_model_name_or_path, **cached_file_kwargs)
|
| 85 |
+
|
| 86 |
+
if sha is None:
|
| 87 |
+
return None, None
|
| 88 |
+
cached_file_kwargs["revision"] = sha
|
| 89 |
+
del cached_file_kwargs["_commit_hash"]
|
| 90 |
+
|
| 91 |
+
# This is an additional HEAD call that could be removed if we could infer sharded/non-sharded from the PR
|
| 92 |
+
# description.
|
| 93 |
+
sharded = api.file_exists(
|
| 94 |
+
pretrained_model_name_or_path,
|
| 95 |
+
"model.safetensors.index.json",
|
| 96 |
+
revision=sha,
|
| 97 |
+
token=cached_file_kwargs.get("token"),
|
| 98 |
+
)
|
| 99 |
+
filename = "model.safetensors.index.json" if sharded else "model.safetensors"
|
| 100 |
+
|
| 101 |
+
resolved_archive_file = cached_file(pretrained_model_name_or_path, filename, **cached_file_kwargs)
|
| 102 |
+
return resolved_archive_file, sha, sharded
|
| 103 |
+
except Exception as e:
|
| 104 |
+
if not ignore_errors_during_conversion:
|
| 105 |
+
raise e
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/sagemaker/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 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 |
+
from .trainer_sm import SageMakerTrainer
|
| 16 |
+
from .training_args_sm import SageMakerTrainingArguments, is_sagemaker_dp_enabled
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/sagemaker/trainer_sm.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 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 warnings
|
| 15 |
+
|
| 16 |
+
from ..trainer import Trainer
|
| 17 |
+
from ..utils import logging
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
logger = logging.get_logger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class SageMakerTrainer(Trainer):
|
| 24 |
+
def __init__(self, args=None, **kwargs):
|
| 25 |
+
warnings.warn(
|
| 26 |
+
"`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` "
|
| 27 |
+
"instead.",
|
| 28 |
+
FutureWarning,
|
| 29 |
+
)
|
| 30 |
+
super().__init__(args=args, **kwargs)
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/sagemaker/training_args_sm.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 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 importlib.util
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import warnings
|
| 19 |
+
from dataclasses import dataclass, field
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
|
| 23 |
+
from ..training_args import TrainingArguments
|
| 24 |
+
from ..utils import cached_property, is_sagemaker_dp_enabled, logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
# TODO: should be moved to `utils` after refactoring of SageMakerTrainer
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def is_sagemaker_model_parallel_available():
|
| 33 |
+
# Get the sagemaker specific mp parameters from smp_options variable.
|
| 34 |
+
smp_options = os.getenv("SM_HP_MP_PARAMETERS", "{}")
|
| 35 |
+
try:
|
| 36 |
+
# Parse it and check the field "partitions" is included, it is required for model parallel.
|
| 37 |
+
smp_options = json.loads(smp_options)
|
| 38 |
+
if "partitions" not in smp_options:
|
| 39 |
+
return False
|
| 40 |
+
except json.JSONDecodeError:
|
| 41 |
+
return False
|
| 42 |
+
|
| 43 |
+
# Get the sagemaker specific framework parameters from mpi_options variable.
|
| 44 |
+
mpi_options = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
|
| 45 |
+
try:
|
| 46 |
+
# Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
|
| 47 |
+
mpi_options = json.loads(mpi_options)
|
| 48 |
+
if not mpi_options.get("sagemaker_mpi_enabled", False):
|
| 49 |
+
return False
|
| 50 |
+
except json.JSONDecodeError:
|
| 51 |
+
return False
|
| 52 |
+
# Lastly, check if the `smdistributed` module is present.
|
| 53 |
+
return importlib.util.find_spec("smdistributed") is not None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
if is_sagemaker_model_parallel_available():
|
| 57 |
+
import smdistributed.modelparallel.torch as smp
|
| 58 |
+
|
| 59 |
+
smp.init()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@dataclass
|
| 63 |
+
class SageMakerTrainingArguments(TrainingArguments):
|
| 64 |
+
mp_parameters: str = field(
|
| 65 |
+
default="",
|
| 66 |
+
metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"},
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
def __post_init__(self):
|
| 70 |
+
super().__post_init__()
|
| 71 |
+
warnings.warn(
|
| 72 |
+
"`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use "
|
| 73 |
+
"`TrainingArguments` instead.",
|
| 74 |
+
FutureWarning,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
@cached_property
|
| 78 |
+
def _setup_devices(self) -> "torch.device":
|
| 79 |
+
logger.info("PyTorch: setting up devices")
|
| 80 |
+
if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1:
|
| 81 |
+
logger.warning(
|
| 82 |
+
"torch.distributed process group is initialized, but local_rank == -1. "
|
| 83 |
+
"In order to use Torch DDP, launch your script with `python -m torch.distributed.launch"
|
| 84 |
+
)
|
| 85 |
+
if self.no_cuda:
|
| 86 |
+
device = torch.device("cpu")
|
| 87 |
+
self._n_gpu = 0
|
| 88 |
+
elif is_sagemaker_model_parallel_available():
|
| 89 |
+
local_rank = smp.local_rank()
|
| 90 |
+
device = torch.device("cuda", local_rank)
|
| 91 |
+
self._n_gpu = 1
|
| 92 |
+
elif is_sagemaker_dp_enabled():
|
| 93 |
+
import smdistributed.dataparallel.torch.torch_smddp # noqa: F401
|
| 94 |
+
|
| 95 |
+
torch.distributed.init_process_group(backend="smddp", timeout=self.ddp_timeout_delta)
|
| 96 |
+
self.local_rank = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK"))
|
| 97 |
+
device = torch.device("cuda", self.local_rank)
|
| 98 |
+
self._n_gpu = 1
|
| 99 |
+
elif self.local_rank == -1:
|
| 100 |
+
# if n_gpu is > 1 we'll use nn.DataParallel.
|
| 101 |
+
# If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
|
| 102 |
+
# Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will
|
| 103 |
+
# trigger an error that a device index is missing. Index 0 takes into account the
|
| 104 |
+
# GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0`
|
| 105 |
+
# will use the first GPU in that env, i.e. GPU#1
|
| 106 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 107 |
+
# Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at
|
| 108 |
+
# the default value.
|
| 109 |
+
self._n_gpu = torch.cuda.device_count()
|
| 110 |
+
else:
|
| 111 |
+
# Here, we'll use torch.distributed.
|
| 112 |
+
# Initializes the distributed backend which will take care of synchronizing nodes/GPUs
|
| 113 |
+
if not torch.distributed.is_initialized():
|
| 114 |
+
torch.distributed.init_process_group(backend="nccl", timeout=self.ddp_timeout_delta)
|
| 115 |
+
device = torch.device("cuda", self.local_rank)
|
| 116 |
+
self._n_gpu = 1
|
| 117 |
+
|
| 118 |
+
if device.type == "cuda":
|
| 119 |
+
torch.cuda.set_device(device)
|
| 120 |
+
|
| 121 |
+
return device
|
| 122 |
+
|
| 123 |
+
@property
|
| 124 |
+
def world_size(self):
|
| 125 |
+
if is_sagemaker_model_parallel_available():
|
| 126 |
+
return smp.dp_size()
|
| 127 |
+
|
| 128 |
+
return super().world_size
|
| 129 |
+
|
| 130 |
+
@property
|
| 131 |
+
def place_model_on_device(self):
|
| 132 |
+
return not is_sagemaker_model_parallel_available()
|
| 133 |
+
|
| 134 |
+
@property
|
| 135 |
+
def _no_sync_in_gradient_accumulation(self):
|
| 136 |
+
return False
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/testing_utils.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/tf_utils.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
from typing import List, Optional, Union
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import tensorflow as tf
|
| 19 |
+
|
| 20 |
+
from .feature_extraction_utils import BatchFeature
|
| 21 |
+
from .tokenization_utils_base import BatchEncoding
|
| 22 |
+
from .utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def shape_list(tensor: Union[tf.Tensor, np.ndarray]) -> List[int]:
|
| 29 |
+
"""
|
| 30 |
+
Deal with dynamic shape in tensorflow cleanly.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
tensor (`tf.Tensor` or `np.ndarray`): The tensor we want the shape of.
|
| 34 |
+
|
| 35 |
+
Returns:
|
| 36 |
+
`List[int]`: The shape of the tensor as a list.
|
| 37 |
+
"""
|
| 38 |
+
if isinstance(tensor, np.ndarray):
|
| 39 |
+
return list(tensor.shape)
|
| 40 |
+
|
| 41 |
+
dynamic = tf.shape(tensor)
|
| 42 |
+
|
| 43 |
+
if tensor.shape == tf.TensorShape(None):
|
| 44 |
+
return dynamic
|
| 45 |
+
|
| 46 |
+
static = tensor.shape.as_list()
|
| 47 |
+
|
| 48 |
+
return [dynamic[i] if s is None else s for i, s in enumerate(static)]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def stable_softmax(logits: tf.Tensor, axis: Optional[int] = None, name: Optional[str] = None) -> tf.Tensor:
|
| 52 |
+
"""
|
| 53 |
+
Stable wrapper that returns the same output as `tf.nn.softmax`, but that works reliably with XLA on CPU. It is
|
| 54 |
+
meant as a workaround for the [following issue](https://github.com/tensorflow/tensorflow/issues/55682), and will be
|
| 55 |
+
removed after it gets fixed. The arguments and outputs are the same as `tf.nn.softmax`, and relies on the fact that
|
| 56 |
+
`softmax(x) = softmax(x + c)` (see https://ogunlao.github.io/2020/04/26/you_dont_really_know_softmax.html).
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
logits (`tf.Tensor`):
|
| 60 |
+
Must be one of the following types: half, float32, float64.
|
| 61 |
+
axis (`int`, *optional*):
|
| 62 |
+
The dimension softmax would be performed on. The default is -1 which indicates the last dimension.
|
| 63 |
+
name (`str`, *optional*):
|
| 64 |
+
A name for the operation.
|
| 65 |
+
|
| 66 |
+
Returns:
|
| 67 |
+
`tf.Tensor`:
|
| 68 |
+
A Tensor. Has the same type and shape as logits.
|
| 69 |
+
"""
|
| 70 |
+
# TODO: When the issue linked above gets sorted, add a check on TF version here and use the original function if
|
| 71 |
+
# it has the fix. After we drop the support for unfixed versions, remove this function.
|
| 72 |
+
return tf.nn.softmax(logits=logits + 1e-9, axis=axis, name=name)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def functional_layernorm(inputs, weight, bias, epsilon=1e-5, axis=-1):
|
| 76 |
+
# This is a very simplified functional layernorm, designed to duplicate
|
| 77 |
+
# the functionality of PyTorch nn.functional.layer_norm when this is needed to port
|
| 78 |
+
# models in Transformers.
|
| 79 |
+
|
| 80 |
+
if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(axis, int):
|
| 81 |
+
raise NotImplementedError("Only 1D weight and bias tensors are supported for now, with only a single axis.")
|
| 82 |
+
|
| 83 |
+
# Get mean and variance on the axis to be normalized
|
| 84 |
+
mean, variance = tf.nn.moments(inputs, axes=[axis], keepdims=True)
|
| 85 |
+
|
| 86 |
+
if axis != -1:
|
| 87 |
+
# Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
|
| 88 |
+
# on every dimension except axis
|
| 89 |
+
shape = [1] * inputs.shape.rank
|
| 90 |
+
shape[axis] = shape_list(inputs)[axis]
|
| 91 |
+
weight = tf.reshape(weight, shape)
|
| 92 |
+
bias = tf.reshape(bias, shape)
|
| 93 |
+
|
| 94 |
+
# Compute layer normalization using the batch_normalization
|
| 95 |
+
# function.
|
| 96 |
+
outputs = tf.nn.batch_normalization(
|
| 97 |
+
inputs,
|
| 98 |
+
mean,
|
| 99 |
+
variance,
|
| 100 |
+
offset=bias,
|
| 101 |
+
scale=weight,
|
| 102 |
+
variance_epsilon=epsilon,
|
| 103 |
+
)
|
| 104 |
+
return outputs
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def scaled_dot_product_attention(
|
| 108 |
+
query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False, scale: float = None
|
| 109 |
+
):
|
| 110 |
+
"""TF equivalent for torch's nn.functional.scaled_dot_product_attention"""
|
| 111 |
+
if dropout_p != 0.0:
|
| 112 |
+
raise ValueError(
|
| 113 |
+
"Dropout is not supported in this implementation - file an issue "
|
| 114 |
+
"with Transformers and ping @Rocketknight1 if you need it for a port!"
|
| 115 |
+
)
|
| 116 |
+
if is_causal and attn_mask is not None:
|
| 117 |
+
raise ValueError("You cannot specify an attn_mask and is_causal at the same time!")
|
| 118 |
+
if is_causal:
|
| 119 |
+
attn_mask = tf.ones((tf.shape(query)[-2], tf.shape(key)[-2]), dtype=tf.int32)
|
| 120 |
+
attn_mask = tf.experimental.numpy.tril(attn_mask, k=0)
|
| 121 |
+
if attn_mask is not None and (attn_mask.dtype.is_integer or attn_mask.dtype.is_bool):
|
| 122 |
+
# Convert boolean mask to a negative logit bias
|
| 123 |
+
attn_mask = tf.where(attn_mask > 0, tf.cast(0.0, query.dtype), tf.cast(-1000.0, query.dtype))
|
| 124 |
+
logits = tf.einsum("...qd, ...kd -> ...qk", query, key)
|
| 125 |
+
if scale is None:
|
| 126 |
+
scale = tf.cast(tf.shape(key)[-1], logits.dtype) ** -0.5
|
| 127 |
+
logits *= scale # scale by 1/sqrt(key_dim)
|
| 128 |
+
if attn_mask is not None:
|
| 129 |
+
logits += attn_mask
|
| 130 |
+
probs = tf.nn.softmax(logits)
|
| 131 |
+
return probs @ value
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def flatten(input, start_dim=0, end_dim=-1):
|
| 135 |
+
# Replicates the behavior of torch.flatten in TF
|
| 136 |
+
|
| 137 |
+
# If end_dim or start_dim is negative, count them from the end
|
| 138 |
+
if end_dim < 0:
|
| 139 |
+
end_dim += input.shape.rank
|
| 140 |
+
if start_dim < 0:
|
| 141 |
+
start_dim += input.shape.rank
|
| 142 |
+
|
| 143 |
+
if start_dim == end_dim:
|
| 144 |
+
return input
|
| 145 |
+
|
| 146 |
+
in_shape = tf.shape(input)
|
| 147 |
+
flattened_dim = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1])
|
| 148 |
+
out_shape = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]], axis=0)
|
| 149 |
+
return tf.reshape(input, out_shape)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def invert_attention_mask(encoder_attention_mask: tf.Tensor) -> tf.Tensor:
|
| 153 |
+
"""
|
| 154 |
+
Invert an attention mask (e.g., switches 0. and 1.).
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
encoder_attention_mask (`torch.Tensor`): An attention mask.
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
`tf.Tensor`: The inverted attention mask.
|
| 161 |
+
"""
|
| 162 |
+
if not isinstance(encoder_attention_mask, tf.Tensor):
|
| 163 |
+
encoder_attention_mask = tf.convert_to_tensor(encoder_attention_mask) # Catches stray NumPy inputs
|
| 164 |
+
if encoder_attention_mask.shape.rank == 3:
|
| 165 |
+
encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :]
|
| 166 |
+
if encoder_attention_mask.shape.rank == 2:
|
| 167 |
+
encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :]
|
| 168 |
+
# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
|
| 169 |
+
# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
|
| 170 |
+
# /transformer/transformer_layers.py#L270
|
| 171 |
+
# encoder_extended_attention_mask = (encoder_extended_attention_mask ==
|
| 172 |
+
# encoder_extended_attention_mask.transpose(-1, -2))
|
| 173 |
+
encoder_extended_attention_mask = (
|
| 174 |
+
tf.cast(1, encoder_attention_mask.dtype) - encoder_extended_attention_mask
|
| 175 |
+
) * encoder_extended_attention_mask.dtype.min
|
| 176 |
+
|
| 177 |
+
return encoder_extended_attention_mask
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def check_embeddings_within_bounds(tensor: tf.Tensor, embed_dim: int, tensor_name: str = "input_ids") -> None:
|
| 181 |
+
"""
|
| 182 |
+
`tf.gather`, on which TF embedding layers are based, won't check positive out of bound indices on GPU, returning
|
| 183 |
+
zeros instead. This function adds a check against that dangerous silent behavior.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
tensor (`tf.Tensor`): The tensor of indices to check.
|
| 187 |
+
embed_dim (`int`): The embedding dimension.
|
| 188 |
+
tensor_name (`str`, *optional*): The name of the tensor to use in the error message.
|
| 189 |
+
"""
|
| 190 |
+
tf.debugging.assert_less(
|
| 191 |
+
tensor,
|
| 192 |
+
tf.cast(embed_dim, dtype=tensor.dtype),
|
| 193 |
+
message=(
|
| 194 |
+
f"The maximum value of {tensor_name} ({tf.math.reduce_max(tensor)}) must be smaller than the embedding "
|
| 195 |
+
f"layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time."
|
| 196 |
+
),
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def save_attributes_to_hdf5_group(group, name, data):
|
| 201 |
+
"""Saves attributes (data) of the specified name into the HDF5 group.
|
| 202 |
+
|
| 203 |
+
This method deals with an inherent problem of HDF5 file which is not able to store data larger than
|
| 204 |
+
HDF5_OBJECT_HEADER_LIMIT bytes.
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
group: A pointer to a HDF5 group.
|
| 208 |
+
name: A name of the attributes to save.
|
| 209 |
+
data: Attributes data to store.
|
| 210 |
+
|
| 211 |
+
Raises:
|
| 212 |
+
RuntimeError: If any single attribute is too large to be saved.
|
| 213 |
+
|
| 214 |
+
Copied from Keras to Transformers to avoid versioning issues.
|
| 215 |
+
"""
|
| 216 |
+
HDF5_OBJECT_HEADER_LIMIT = 64512
|
| 217 |
+
# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
|
| 218 |
+
# because in that case even chunking the array would not make the saving
|
| 219 |
+
# possible.
|
| 220 |
+
bad_attributes = [x for x in data if len(x) > HDF5_OBJECT_HEADER_LIMIT]
|
| 221 |
+
|
| 222 |
+
# Expecting this to never be true.
|
| 223 |
+
if bad_attributes:
|
| 224 |
+
raise RuntimeError(
|
| 225 |
+
"The following attributes cannot be saved to HDF5 file because "
|
| 226 |
+
f"they are larger than {HDF5_OBJECT_HEADER_LIMIT} "
|
| 227 |
+
f"bytes: {bad_attributes}"
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
data_npy = np.asarray(data)
|
| 231 |
+
|
| 232 |
+
num_chunks = 1
|
| 233 |
+
chunked_data = np.array_split(data_npy, num_chunks)
|
| 234 |
+
|
| 235 |
+
# This will never loop forever thanks to the test above.
|
| 236 |
+
while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data):
|
| 237 |
+
num_chunks += 1
|
| 238 |
+
chunked_data = np.array_split(data_npy, num_chunks)
|
| 239 |
+
|
| 240 |
+
if num_chunks > 1:
|
| 241 |
+
for chunk_id, chunk_data in enumerate(chunked_data):
|
| 242 |
+
group.attrs["%s%d" % (name, chunk_id)] = chunk_data
|
| 243 |
+
else:
|
| 244 |
+
group.attrs[name] = data
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def load_attributes_from_hdf5_group(group, name):
|
| 248 |
+
"""Loads attributes of the specified name from the HDF5 group.
|
| 249 |
+
|
| 250 |
+
This method deals with an inherent problem of HDF5 file which is not able to store data larger than
|
| 251 |
+
HDF5_OBJECT_HEADER_LIMIT bytes.
|
| 252 |
+
|
| 253 |
+
Args:
|
| 254 |
+
group: A pointer to a HDF5 group.
|
| 255 |
+
name: A name of the attributes to load.
|
| 256 |
+
|
| 257 |
+
Returns:
|
| 258 |
+
data: Attributes data.
|
| 259 |
+
|
| 260 |
+
Copied from Keras to Transformers to avoid versioning issues.
|
| 261 |
+
"""
|
| 262 |
+
if name in group.attrs:
|
| 263 |
+
data = [n.decode("utf8") if hasattr(n, "decode") else n for n in group.attrs[name]]
|
| 264 |
+
else:
|
| 265 |
+
data = []
|
| 266 |
+
chunk_id = 0
|
| 267 |
+
while "%s%d" % (name, chunk_id) in group.attrs:
|
| 268 |
+
data.extend(
|
| 269 |
+
[n.decode("utf8") if hasattr(n, "decode") else n for n in group.attrs["%s%d" % (name, chunk_id)]]
|
| 270 |
+
)
|
| 271 |
+
chunk_id += 1
|
| 272 |
+
return data
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def expand_1d(data):
|
| 276 |
+
"""Expands 1-dimensional `Tensor`s into 2-dimensional `Tensor`s.
|
| 277 |
+
Copied from Keras to here to avoid versioning issues."""
|
| 278 |
+
|
| 279 |
+
def _expand_single_1d_tensor(t):
|
| 280 |
+
if isinstance(t, tf.Tensor) and t.shape.rank == 1:
|
| 281 |
+
return tf.expand_dims(t, axis=-1)
|
| 282 |
+
return t
|
| 283 |
+
|
| 284 |
+
return tf.nest.map_structure(_expand_single_1d_tensor, data)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def convert_batch_encoding(*args, **kwargs):
|
| 288 |
+
# Convert HF BatchEncoding/BatchFeature objects in the inputs to dicts that Keras understands
|
| 289 |
+
if args and isinstance(args[0], (BatchEncoding, BatchFeature)):
|
| 290 |
+
args = list(args)
|
| 291 |
+
args[0] = dict(args[0])
|
| 292 |
+
elif "x" in kwargs and isinstance(kwargs["x"], (BatchEncoding, BatchFeature)):
|
| 293 |
+
kwargs["x"] = dict(kwargs["x"])
|
| 294 |
+
return args, kwargs
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/time_series_utils.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 3 |
+
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""
|
| 17 |
+
Time series distributional output classes and utilities.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from typing import Callable, Dict, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from torch import nn
|
| 24 |
+
from torch.distributions import (
|
| 25 |
+
AffineTransform,
|
| 26 |
+
Distribution,
|
| 27 |
+
Independent,
|
| 28 |
+
NegativeBinomial,
|
| 29 |
+
Normal,
|
| 30 |
+
StudentT,
|
| 31 |
+
TransformedDistribution,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class AffineTransformed(TransformedDistribution):
|
| 36 |
+
def __init__(self, base_distribution: Distribution, loc=None, scale=None, event_dim=0):
|
| 37 |
+
self.scale = 1.0 if scale is None else scale
|
| 38 |
+
self.loc = 0.0 if loc is None else loc
|
| 39 |
+
|
| 40 |
+
super().__init__(base_distribution, [AffineTransform(loc=self.loc, scale=self.scale, event_dim=event_dim)])
|
| 41 |
+
|
| 42 |
+
@property
|
| 43 |
+
def mean(self):
|
| 44 |
+
"""
|
| 45 |
+
Returns the mean of the distribution.
|
| 46 |
+
"""
|
| 47 |
+
return self.base_dist.mean * self.scale + self.loc
|
| 48 |
+
|
| 49 |
+
@property
|
| 50 |
+
def variance(self):
|
| 51 |
+
"""
|
| 52 |
+
Returns the variance of the distribution.
|
| 53 |
+
"""
|
| 54 |
+
return self.base_dist.variance * self.scale**2
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def stddev(self):
|
| 58 |
+
"""
|
| 59 |
+
Returns the standard deviation of the distribution.
|
| 60 |
+
"""
|
| 61 |
+
return self.variance.sqrt()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class ParameterProjection(nn.Module):
|
| 65 |
+
def __init__(
|
| 66 |
+
self, in_features: int, args_dim: Dict[str, int], domain_map: Callable[..., Tuple[torch.Tensor]], **kwargs
|
| 67 |
+
) -> None:
|
| 68 |
+
super().__init__(**kwargs)
|
| 69 |
+
self.args_dim = args_dim
|
| 70 |
+
self.proj = nn.ModuleList([nn.Linear(in_features, dim) for dim in args_dim.values()])
|
| 71 |
+
self.domain_map = domain_map
|
| 72 |
+
|
| 73 |
+
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor]:
|
| 74 |
+
params_unbounded = [proj(x) for proj in self.proj]
|
| 75 |
+
|
| 76 |
+
return self.domain_map(*params_unbounded)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class LambdaLayer(nn.Module):
|
| 80 |
+
def __init__(self, function):
|
| 81 |
+
super().__init__()
|
| 82 |
+
self.function = function
|
| 83 |
+
|
| 84 |
+
def forward(self, x, *args):
|
| 85 |
+
return self.function(x, *args)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class DistributionOutput:
|
| 89 |
+
distribution_class: type
|
| 90 |
+
in_features: int
|
| 91 |
+
args_dim: Dict[str, int]
|
| 92 |
+
|
| 93 |
+
def __init__(self, dim: int = 1) -> None:
|
| 94 |
+
self.dim = dim
|
| 95 |
+
self.args_dim = {k: dim * self.args_dim[k] for k in self.args_dim}
|
| 96 |
+
|
| 97 |
+
def _base_distribution(self, distr_args):
|
| 98 |
+
if self.dim == 1:
|
| 99 |
+
return self.distribution_class(*distr_args)
|
| 100 |
+
else:
|
| 101 |
+
return Independent(self.distribution_class(*distr_args), 1)
|
| 102 |
+
|
| 103 |
+
def distribution(
|
| 104 |
+
self,
|
| 105 |
+
distr_args,
|
| 106 |
+
loc: Optional[torch.Tensor] = None,
|
| 107 |
+
scale: Optional[torch.Tensor] = None,
|
| 108 |
+
) -> Distribution:
|
| 109 |
+
distr = self._base_distribution(distr_args)
|
| 110 |
+
if loc is None and scale is None:
|
| 111 |
+
return distr
|
| 112 |
+
else:
|
| 113 |
+
return AffineTransformed(distr, loc=loc, scale=scale, event_dim=self.event_dim)
|
| 114 |
+
|
| 115 |
+
@property
|
| 116 |
+
def event_shape(self) -> Tuple:
|
| 117 |
+
r"""
|
| 118 |
+
Shape of each individual event contemplated by the distributions that this object constructs.
|
| 119 |
+
"""
|
| 120 |
+
return () if self.dim == 1 else (self.dim,)
|
| 121 |
+
|
| 122 |
+
@property
|
| 123 |
+
def event_dim(self) -> int:
|
| 124 |
+
r"""
|
| 125 |
+
Number of event dimensions, i.e., length of the `event_shape` tuple, of the distributions that this object
|
| 126 |
+
constructs.
|
| 127 |
+
"""
|
| 128 |
+
return len(self.event_shape)
|
| 129 |
+
|
| 130 |
+
@property
|
| 131 |
+
def value_in_support(self) -> float:
|
| 132 |
+
r"""
|
| 133 |
+
A float that will have a valid numeric value when computing the log-loss of the corresponding distribution. By
|
| 134 |
+
default 0.0. This value will be used when padding data series.
|
| 135 |
+
"""
|
| 136 |
+
return 0.0
|
| 137 |
+
|
| 138 |
+
def get_parameter_projection(self, in_features: int) -> nn.Module:
|
| 139 |
+
r"""
|
| 140 |
+
Return the parameter projection layer that maps the input to the appropriate parameters of the distribution.
|
| 141 |
+
"""
|
| 142 |
+
return ParameterProjection(
|
| 143 |
+
in_features=in_features,
|
| 144 |
+
args_dim=self.args_dim,
|
| 145 |
+
domain_map=LambdaLayer(self.domain_map),
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
def domain_map(self, *args: torch.Tensor):
|
| 149 |
+
r"""
|
| 150 |
+
Converts arguments to the right shape and domain. The domain depends on the type of distribution, while the
|
| 151 |
+
correct shape is obtained by reshaping the trailing axis in such a way that the returned tensors define a
|
| 152 |
+
distribution of the right event_shape.
|
| 153 |
+
"""
|
| 154 |
+
raise NotImplementedError()
|
| 155 |
+
|
| 156 |
+
@staticmethod
|
| 157 |
+
def squareplus(x: torch.Tensor) -> torch.Tensor:
|
| 158 |
+
r"""
|
| 159 |
+
Helper to map inputs to the positive orthant by applying the square-plus operation. Reference:
|
| 160 |
+
https://twitter.com/jon_barron/status/1387167648669048833
|
| 161 |
+
"""
|
| 162 |
+
return (x + torch.sqrt(torch.square(x) + 4.0)) / 2.0
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class StudentTOutput(DistributionOutput):
|
| 166 |
+
"""
|
| 167 |
+
Student-T distribution output class.
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
args_dim: Dict[str, int] = {"df": 1, "loc": 1, "scale": 1}
|
| 171 |
+
distribution_class: type = StudentT
|
| 172 |
+
|
| 173 |
+
@classmethod
|
| 174 |
+
def domain_map(cls, df: torch.Tensor, loc: torch.Tensor, scale: torch.Tensor):
|
| 175 |
+
scale = cls.squareplus(scale).clamp_min(torch.finfo(scale.dtype).eps)
|
| 176 |
+
df = 2.0 + cls.squareplus(df)
|
| 177 |
+
return df.squeeze(-1), loc.squeeze(-1), scale.squeeze(-1)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class NormalOutput(DistributionOutput):
|
| 181 |
+
"""
|
| 182 |
+
Normal distribution output class.
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
args_dim: Dict[str, int] = {"loc": 1, "scale": 1}
|
| 186 |
+
distribution_class: type = Normal
|
| 187 |
+
|
| 188 |
+
@classmethod
|
| 189 |
+
def domain_map(cls, loc: torch.Tensor, scale: torch.Tensor):
|
| 190 |
+
scale = cls.squareplus(scale).clamp_min(torch.finfo(scale.dtype).eps)
|
| 191 |
+
return loc.squeeze(-1), scale.squeeze(-1)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class NegativeBinomialOutput(DistributionOutput):
|
| 195 |
+
"""
|
| 196 |
+
Negative Binomial distribution output class.
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
args_dim: Dict[str, int] = {"total_count": 1, "logits": 1}
|
| 200 |
+
distribution_class: type = NegativeBinomial
|
| 201 |
+
|
| 202 |
+
@classmethod
|
| 203 |
+
def domain_map(cls, total_count: torch.Tensor, logits: torch.Tensor):
|
| 204 |
+
total_count = cls.squareplus(total_count)
|
| 205 |
+
return total_count.squeeze(-1), logits.squeeze(-1)
|
| 206 |
+
|
| 207 |
+
def _base_distribution(self, distr_args) -> Distribution:
|
| 208 |
+
total_count, logits = distr_args
|
| 209 |
+
if self.dim == 1:
|
| 210 |
+
return self.distribution_class(total_count=total_count, logits=logits)
|
| 211 |
+
else:
|
| 212 |
+
return Independent(self.distribution_class(total_count=total_count, logits=logits), 1)
|
| 213 |
+
|
| 214 |
+
# Overwrites the parent class method. We cannot scale using the affine
|
| 215 |
+
# transformation since negative binomial should return integers. Instead
|
| 216 |
+
# we scale the parameters.
|
| 217 |
+
def distribution(
|
| 218 |
+
self, distr_args, loc: Optional[torch.Tensor] = None, scale: Optional[torch.Tensor] = None
|
| 219 |
+
) -> Distribution:
|
| 220 |
+
total_count, logits = distr_args
|
| 221 |
+
|
| 222 |
+
if scale is not None:
|
| 223 |
+
# See scaling property of Gamma.
|
| 224 |
+
logits += scale.log()
|
| 225 |
+
|
| 226 |
+
return self._base_distribution((total_count, logits))
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/tokenization_utils.py
ADDED
|
@@ -0,0 +1,1134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Inc. team.
|
| 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 |
+
"""
|
| 16 |
+
Tokenization classes for python tokenizers. For fast tokenizers (provided by HuggingFace's tokenizers library) see
|
| 17 |
+
tokenization_utils_fast.py
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import bisect
|
| 21 |
+
import itertools
|
| 22 |
+
import re
|
| 23 |
+
import unicodedata
|
| 24 |
+
from collections import OrderedDict
|
| 25 |
+
from typing import Any, Dict, List, Optional, Tuple, Union, overload
|
| 26 |
+
|
| 27 |
+
from .tokenization_utils_base import (
|
| 28 |
+
ENCODE_KWARGS_DOCSTRING,
|
| 29 |
+
ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING,
|
| 30 |
+
INIT_TOKENIZER_DOCSTRING,
|
| 31 |
+
AddedToken,
|
| 32 |
+
BatchEncoding,
|
| 33 |
+
EncodedInput,
|
| 34 |
+
EncodedInputPair,
|
| 35 |
+
PreTokenizedInput,
|
| 36 |
+
PreTokenizedInputPair,
|
| 37 |
+
PreTrainedTokenizerBase,
|
| 38 |
+
TextInput,
|
| 39 |
+
TextInputPair,
|
| 40 |
+
TruncationStrategy,
|
| 41 |
+
)
|
| 42 |
+
from .utils import PaddingStrategy, TensorType, add_end_docstrings, logging
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
logger = logging.get_logger(__name__)
|
| 46 |
+
|
| 47 |
+
# Slow tokenizers are saved in a vocabulary plus three separated files
|
| 48 |
+
SPECIAL_TOKENS_MAP_FILE = "special_tokens_map.json"
|
| 49 |
+
ADDED_TOKENS_FILE = "added_tokens.json"
|
| 50 |
+
TOKENIZER_CONFIG_FILE = "tokenizer_config.json"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class Trie:
|
| 54 |
+
"""
|
| 55 |
+
Trie in Python. Creates a Trie out of a list of words. The trie is used to split on `added_tokens` in one pass
|
| 56 |
+
Loose reference https://en.wikipedia.org/wiki/Trie
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(self, *args):
|
| 60 |
+
self.data = {}
|
| 61 |
+
self._tokens = set()
|
| 62 |
+
self._termination_char = ""
|
| 63 |
+
self.update(*args)
|
| 64 |
+
|
| 65 |
+
def update(self, *args):
|
| 66 |
+
"""
|
| 67 |
+
Updates the Trie with new tokens provided as arguments.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
*args: Variable number of words to be added to the Trie.
|
| 71 |
+
"""
|
| 72 |
+
for token in tuple(*args):
|
| 73 |
+
self.add(token)
|
| 74 |
+
|
| 75 |
+
def add(self, word: str):
|
| 76 |
+
"""
|
| 77 |
+
Passes over every char (utf-8 char) on word and recursively adds it to the internal `data` trie representation.
|
| 78 |
+
The special key `""` in `self._termination_char` is used to represent termination.
|
| 79 |
+
|
| 80 |
+
This function is idempotent, adding twice the same word will leave the trie unchanged
|
| 81 |
+
|
| 82 |
+
Example:
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
>>> trie = Trie()
|
| 86 |
+
>>> trie.add("Hello 友達")
|
| 87 |
+
>>> trie.data
|
| 88 |
+
{"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}}
|
| 89 |
+
|
| 90 |
+
>>> trie.add("Hello")
|
| 91 |
+
>>> trie.data
|
| 92 |
+
{"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}}
|
| 93 |
+
```
|
| 94 |
+
"""
|
| 95 |
+
if not word:
|
| 96 |
+
# Prevent empty string
|
| 97 |
+
return
|
| 98 |
+
|
| 99 |
+
self._tokens.add(word)
|
| 100 |
+
ref = self.data
|
| 101 |
+
for char in word:
|
| 102 |
+
ref[char] = ref.setdefault(char, {})
|
| 103 |
+
ref = ref[char]
|
| 104 |
+
ref[self._termination_char] = 1
|
| 105 |
+
|
| 106 |
+
def split(self, text: str) -> List[str]:
|
| 107 |
+
"""
|
| 108 |
+
Will look for the words added to the trie within `text`. Output is the original string splitted along the
|
| 109 |
+
boundaries of the words found.
|
| 110 |
+
|
| 111 |
+
This trie will match the longest possible word first !
|
| 112 |
+
|
| 113 |
+
Example:
|
| 114 |
+
|
| 115 |
+
```python
|
| 116 |
+
>>> trie = Trie()
|
| 117 |
+
>>> trie.split("[CLS] This is a extra_id_100")
|
| 118 |
+
["[CLS] This is a extra_id_100"]
|
| 119 |
+
|
| 120 |
+
>>> trie.add("[CLS]")
|
| 121 |
+
>>> trie.add("extra_id_1")
|
| 122 |
+
>>> trie.add("extra_id_100")
|
| 123 |
+
>>> trie.split("[CLS] This is a extra_id_100")
|
| 124 |
+
["[CLS]", " This is a ", "extra_id_100"]
|
| 125 |
+
```
|
| 126 |
+
"""
|
| 127 |
+
# indexes are counted left of the chars index.
|
| 128 |
+
# "hello", index 0, is left of h, index 1 is between h and e.
|
| 129 |
+
# index 5 is right of the "o".
|
| 130 |
+
|
| 131 |
+
# States are going to capture every possible start (indexes as above)
|
| 132 |
+
# as keys, and have as values, a pointer to the position in the trie
|
| 133 |
+
# where we're at. This is a partial match for now.
|
| 134 |
+
# This enables to keep track of multiple matches while we're iterating
|
| 135 |
+
# the string
|
| 136 |
+
# If the trie contains, "blowing", and "lower" and we encounter the
|
| 137 |
+
# string "blower", we need to split into ["b", "lower"].
|
| 138 |
+
# This is where we need to keep track of multiple possible starts.
|
| 139 |
+
states = OrderedDict()
|
| 140 |
+
|
| 141 |
+
# This will contain every indices where we need
|
| 142 |
+
# to cut.
|
| 143 |
+
# We force to cut at offset 0 and len(text) (added later)
|
| 144 |
+
offsets = [0]
|
| 145 |
+
|
| 146 |
+
# This is used by the lookahead which needs to skip over
|
| 147 |
+
# some text where the full match exceeded the place in the initial
|
| 148 |
+
# for loop
|
| 149 |
+
skip = 0
|
| 150 |
+
# Main loop, Giving this algorithm O(n) complexity
|
| 151 |
+
for current, current_char in enumerate(text):
|
| 152 |
+
if skip and current < skip:
|
| 153 |
+
# Prevents the lookahead for matching twice
|
| 154 |
+
# like extra_id_100 and id_100
|
| 155 |
+
continue
|
| 156 |
+
|
| 157 |
+
# This will track every state
|
| 158 |
+
# that stop matching, we need to stop tracking them.
|
| 159 |
+
# If we look at "lowball", we're going to match "l" (add it to states), "o", "w", then
|
| 160 |
+
# fail on "b", we need to remove 0 from the valid states.
|
| 161 |
+
to_remove = set()
|
| 162 |
+
# Whenever we found a match, we need to drop everything
|
| 163 |
+
# this is a greedy algorithm, it will match on the first found token
|
| 164 |
+
reset = False
|
| 165 |
+
|
| 166 |
+
# In this case, we already have partial matches (But unfinished)
|
| 167 |
+
for start, trie_pointer in states.items():
|
| 168 |
+
if "" in trie_pointer:
|
| 169 |
+
# This is a final match, we need to reset and
|
| 170 |
+
# store the results in `offsets`.
|
| 171 |
+
|
| 172 |
+
# Lookahead to match longest first
|
| 173 |
+
# Important in case of extra_id_1 vs extra_id_100
|
| 174 |
+
# Here we are also actively looking for other earlier partial
|
| 175 |
+
# matches
|
| 176 |
+
# "[CLS]", "L", we need to match CLS even if L is special
|
| 177 |
+
for lookstart, looktrie_pointer in states.items():
|
| 178 |
+
if lookstart > start:
|
| 179 |
+
# This partial match is later, we can stop looking
|
| 180 |
+
break
|
| 181 |
+
elif lookstart < start:
|
| 182 |
+
# This partial match is earlier, the trie pointer
|
| 183 |
+
# was already updated, so index is + 1
|
| 184 |
+
lookahead_index = current + 1
|
| 185 |
+
end = current + 1
|
| 186 |
+
else:
|
| 187 |
+
# Here lookstart == start and
|
| 188 |
+
# looktrie_pointer == trie_pointer
|
| 189 |
+
# It wasn't updated yet so indices are current ones
|
| 190 |
+
lookahead_index = current
|
| 191 |
+
end = current
|
| 192 |
+
next_char = text[lookahead_index] if lookahead_index < len(text) else None
|
| 193 |
+
if "" in looktrie_pointer:
|
| 194 |
+
start = lookstart
|
| 195 |
+
end = lookahead_index
|
| 196 |
+
skip = lookahead_index
|
| 197 |
+
|
| 198 |
+
while next_char in looktrie_pointer:
|
| 199 |
+
looktrie_pointer = looktrie_pointer[next_char]
|
| 200 |
+
lookahead_index += 1
|
| 201 |
+
if "" in looktrie_pointer:
|
| 202 |
+
start = lookstart
|
| 203 |
+
end = lookahead_index
|
| 204 |
+
skip = lookahead_index
|
| 205 |
+
|
| 206 |
+
if lookahead_index == len(text):
|
| 207 |
+
# End of string
|
| 208 |
+
break
|
| 209 |
+
next_char = text[lookahead_index]
|
| 210 |
+
# End lookahead
|
| 211 |
+
|
| 212 |
+
# Storing and resetting
|
| 213 |
+
offsets.append(start)
|
| 214 |
+
offsets.append(end)
|
| 215 |
+
reset = True
|
| 216 |
+
break
|
| 217 |
+
elif current_char in trie_pointer:
|
| 218 |
+
# The current character being looked at has a match within the trie
|
| 219 |
+
# update the pointer (it will be stored back into states later).
|
| 220 |
+
trie_pointer = trie_pointer[current_char]
|
| 221 |
+
|
| 222 |
+
# Storing back the new pointer into the states.
|
| 223 |
+
# Partial matches got longer by one.
|
| 224 |
+
states[start] = trie_pointer
|
| 225 |
+
else:
|
| 226 |
+
# The new character has not match in the trie, we need
|
| 227 |
+
# to stop keeping track of this partial match.
|
| 228 |
+
# We can't do it directly within the loop because of how
|
| 229 |
+
# python iteration works
|
| 230 |
+
to_remove.add(start)
|
| 231 |
+
|
| 232 |
+
# Either clearing the full start (we found a real match)
|
| 233 |
+
# Or clearing only the partial matches that didn't work.
|
| 234 |
+
if reset:
|
| 235 |
+
states = {}
|
| 236 |
+
else:
|
| 237 |
+
for start in to_remove:
|
| 238 |
+
del states[start]
|
| 239 |
+
|
| 240 |
+
# If this character is a starting character within the trie
|
| 241 |
+
# start keeping track of this partial match.
|
| 242 |
+
if current >= skip and current_char in self.data:
|
| 243 |
+
states[current] = self.data[current_char]
|
| 244 |
+
|
| 245 |
+
# We have a cut at the end with states.
|
| 246 |
+
for start, trie_pointer in states.items():
|
| 247 |
+
if "" in trie_pointer:
|
| 248 |
+
# This is a final match, we need to reset and
|
| 249 |
+
# store the results in `offsets`.
|
| 250 |
+
end = len(text)
|
| 251 |
+
offsets.append(start)
|
| 252 |
+
offsets.append(end)
|
| 253 |
+
# Longest cut is always the one with lower start so the first
|
| 254 |
+
# item so we need to break.
|
| 255 |
+
break
|
| 256 |
+
|
| 257 |
+
return self.cut_text(text, offsets)
|
| 258 |
+
|
| 259 |
+
def cut_text(self, text, offsets):
|
| 260 |
+
# We have all the offsets now, we just need to do the actual splitting.
|
| 261 |
+
# We need to eventually add the first part of the string and the eventual
|
| 262 |
+
# last part.
|
| 263 |
+
offsets.append(len(text))
|
| 264 |
+
tokens = []
|
| 265 |
+
start = 0
|
| 266 |
+
for end in offsets:
|
| 267 |
+
if start > end:
|
| 268 |
+
logger.error(
|
| 269 |
+
"There was a bug in Trie algorithm in tokenization. Attempting to recover. Please report it"
|
| 270 |
+
" anyway."
|
| 271 |
+
)
|
| 272 |
+
continue
|
| 273 |
+
elif start == end:
|
| 274 |
+
# This might happen if there's a match at index 0
|
| 275 |
+
# we're also preventing zero-width cuts in case of two
|
| 276 |
+
# consecutive matches
|
| 277 |
+
continue
|
| 278 |
+
tokens.append(text[start:end])
|
| 279 |
+
start = end
|
| 280 |
+
|
| 281 |
+
return tokens
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class ExtensionsTrie(Trie):
|
| 285 |
+
def __init__(self, *args):
|
| 286 |
+
super().__init__(*args)
|
| 287 |
+
|
| 288 |
+
def extensions(self, prefix: str):
|
| 289 |
+
"""
|
| 290 |
+
Generates all extensions of a given prefix token in the Trie.
|
| 291 |
+
|
| 292 |
+
Example:
|
| 293 |
+
|
| 294 |
+
```python
|
| 295 |
+
>>> trie = Trie()
|
| 296 |
+
>>> trie.add("apple")
|
| 297 |
+
>>> trie.add("app")
|
| 298 |
+
>>> trie.add("application")
|
| 299 |
+
>>> trie.extensions("app")
|
| 300 |
+
['app', 'apple', 'application']
|
| 301 |
+
```
|
| 302 |
+
"""
|
| 303 |
+
prefix_node = self._get_node(prefix)
|
| 304 |
+
ret = self._collect_tokens(prefix_node)
|
| 305 |
+
return [prefix + token for token in ret]
|
| 306 |
+
|
| 307 |
+
def _get_node(self, token: str) -> dict:
|
| 308 |
+
"""
|
| 309 |
+
Retrieves the node corresponding to the given token in the Trie.
|
| 310 |
+
|
| 311 |
+
Args:
|
| 312 |
+
token (str): The token for which the corresponding node needs to be retrieved.
|
| 313 |
+
|
| 314 |
+
Returns:
|
| 315 |
+
dict: The node in the Trie corresponding to the given token.
|
| 316 |
+
"""
|
| 317 |
+
node = self.data
|
| 318 |
+
for char in token:
|
| 319 |
+
if char not in node:
|
| 320 |
+
break
|
| 321 |
+
|
| 322 |
+
node = node[char]
|
| 323 |
+
return node
|
| 324 |
+
|
| 325 |
+
def _collect_tokens(self, node: dict) -> list:
|
| 326 |
+
"""
|
| 327 |
+
Generates all tokens in the Trie starting from a given node.
|
| 328 |
+
|
| 329 |
+
Args:
|
| 330 |
+
node (dict): The node in the Trie from which tokens need to be generated.
|
| 331 |
+
|
| 332 |
+
Returns:
|
| 333 |
+
list: List of tokens generated from the given node.
|
| 334 |
+
"""
|
| 335 |
+
tokens = [self._termination_char] if self._termination_char in node else []
|
| 336 |
+
for token, subtrie_head in node.items():
|
| 337 |
+
if token != self._termination_char:
|
| 338 |
+
subtokens = self._collect_tokens(subtrie_head)
|
| 339 |
+
tokens.extend([token + subtoken for subtoken in subtokens])
|
| 340 |
+
return tokens
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def _is_whitespace(char):
|
| 344 |
+
"""Checks whether `char` is a whitespace character."""
|
| 345 |
+
# \t, \n, and \r are technically control characters but we treat them
|
| 346 |
+
# as whitespace since they are generally considered as such.
|
| 347 |
+
if char == " " or char == "\t" or char == "\n" or char == "\r":
|
| 348 |
+
return True
|
| 349 |
+
cat = unicodedata.category(char)
|
| 350 |
+
if cat == "Zs":
|
| 351 |
+
return True
|
| 352 |
+
return False
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _is_control(char):
|
| 356 |
+
"""Checks whether `char` is a control character."""
|
| 357 |
+
# These are technically control characters but we count them as whitespace
|
| 358 |
+
# characters.
|
| 359 |
+
if char == "\t" or char == "\n" or char == "\r":
|
| 360 |
+
return False
|
| 361 |
+
cat = unicodedata.category(char)
|
| 362 |
+
if cat.startswith("C"):
|
| 363 |
+
return True
|
| 364 |
+
return False
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _is_punctuation(char):
|
| 368 |
+
"""Checks whether `char` is a punctuation character."""
|
| 369 |
+
cp = ord(char)
|
| 370 |
+
# We treat all non-letter/number ASCII as punctuation.
|
| 371 |
+
# Characters such as "^", "$", and "`" are not in the Unicode
|
| 372 |
+
# Punctuation class but we treat them as punctuation anyways, for
|
| 373 |
+
# consistency.
|
| 374 |
+
if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126):
|
| 375 |
+
return True
|
| 376 |
+
cat = unicodedata.category(char)
|
| 377 |
+
if cat.startswith("P"):
|
| 378 |
+
return True
|
| 379 |
+
return False
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def _is_end_of_word(text):
|
| 383 |
+
"""Checks whether the last character in text is one of a punctuation, control or whitespace character."""
|
| 384 |
+
last_char = text[-1]
|
| 385 |
+
return bool(_is_control(last_char) | _is_punctuation(last_char) | _is_whitespace(last_char))
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def _is_start_of_word(text):
|
| 389 |
+
"""Checks whether the first character in text is one of a punctuation, control or whitespace character."""
|
| 390 |
+
first_char = text[0]
|
| 391 |
+
return bool(_is_control(first_char) | _is_punctuation(first_char) | _is_whitespace(first_char))
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def _insert_one_token_to_ordered_list(token_list: List[str], new_token: str):
|
| 395 |
+
"""
|
| 396 |
+
Inserts one token to an ordered list if it does not already exist. Note: token_list must be sorted.
|
| 397 |
+
"""
|
| 398 |
+
insertion_idx = bisect.bisect_left(token_list, new_token)
|
| 399 |
+
# Checks if new_token is already in the ordered token_list
|
| 400 |
+
if insertion_idx < len(token_list) and token_list[insertion_idx] == new_token:
|
| 401 |
+
# new_token is in token_list, don't add
|
| 402 |
+
return
|
| 403 |
+
else:
|
| 404 |
+
token_list.insert(insertion_idx, new_token)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
@add_end_docstrings(INIT_TOKENIZER_DOCSTRING)
|
| 408 |
+
class PreTrainedTokenizer(PreTrainedTokenizerBase):
|
| 409 |
+
"""
|
| 410 |
+
Base class for all slow tokenizers.
|
| 411 |
+
|
| 412 |
+
Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`].
|
| 413 |
+
|
| 414 |
+
Handle all the shared methods for tokenization and special tokens as well as methods downloading/caching/loading
|
| 415 |
+
pretrained tokenizers as well as adding tokens to the vocabulary.
|
| 416 |
+
|
| 417 |
+
This class also contain the added tokens in a unified way on top of all tokenizers so we don't have to handle the
|
| 418 |
+
specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).
|
| 419 |
+
"""
|
| 420 |
+
|
| 421 |
+
def __init__(self, **kwargs):
|
| 422 |
+
# 1. Init the parent class
|
| 423 |
+
|
| 424 |
+
self.tokens_trie = Trie()
|
| 425 |
+
|
| 426 |
+
# 2. init `_added_tokens_decoder` if child class did not
|
| 427 |
+
if not hasattr(self, "_added_tokens_decoder"):
|
| 428 |
+
self._added_tokens_decoder: Dict[int, AddedToken] = {}
|
| 429 |
+
|
| 430 |
+
# 3. if a `added_tokens_decoder` is passed, we are loading from a saved tokenizer, we overwrite
|
| 431 |
+
self._added_tokens_decoder.update(kwargs.pop("added_tokens_decoder", {}))
|
| 432 |
+
self._added_tokens_encoder: Dict[str, int] = {k.content: v for v, k in self._added_tokens_decoder.items()}
|
| 433 |
+
|
| 434 |
+
# 4 init the parent class
|
| 435 |
+
super().__init__(**kwargs)
|
| 436 |
+
|
| 437 |
+
# 4. If some of the special tokens are not part of the vocab, we add them, at the end.
|
| 438 |
+
# the order of addition is the same as self.SPECIAL_TOKENS_ATTRIBUTES following `tokenizers`
|
| 439 |
+
self._add_tokens(
|
| 440 |
+
[token for token in self.all_special_tokens_extended if token not in self._added_tokens_encoder],
|
| 441 |
+
special_tokens=True,
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
self._decode_use_source_tokenizer = False
|
| 445 |
+
|
| 446 |
+
@property
|
| 447 |
+
def is_fast(self) -> bool:
|
| 448 |
+
return False
|
| 449 |
+
|
| 450 |
+
@property
|
| 451 |
+
def vocab_size(self) -> int:
|
| 452 |
+
"""
|
| 453 |
+
`int`: Size of the base vocabulary (without the added tokens).
|
| 454 |
+
"""
|
| 455 |
+
raise NotImplementedError
|
| 456 |
+
|
| 457 |
+
@property
|
| 458 |
+
def added_tokens_encoder(self) -> Dict[str, int]:
|
| 459 |
+
"""
|
| 460 |
+
Returns the sorted mapping from string to index. The added tokens encoder is cached for performance
|
| 461 |
+
optimisation in `self._added_tokens_encoder` for the slow tokenizers.
|
| 462 |
+
"""
|
| 463 |
+
return {k.content: v for v, k in sorted(self._added_tokens_decoder.items(), key=lambda item: item[0])}
|
| 464 |
+
|
| 465 |
+
@property
|
| 466 |
+
def added_tokens_decoder(self) -> Dict[int, AddedToken]:
|
| 467 |
+
"""
|
| 468 |
+
Returns the added tokens in the vocabulary as a dictionary of index to AddedToken.
|
| 469 |
+
|
| 470 |
+
Returns:
|
| 471 |
+
`Dict[str, int]`: The added tokens.
|
| 472 |
+
"""
|
| 473 |
+
return dict(sorted(self._added_tokens_decoder.items(), key=lambda item: item[0]))
|
| 474 |
+
|
| 475 |
+
@added_tokens_decoder.setter
|
| 476 |
+
def added_tokens_decoder(self, value: Dict[int, Union[AddedToken, str]]) -> Dict[int, AddedToken]:
|
| 477 |
+
# Always raise an error if string because users should define the behavior
|
| 478 |
+
for index, token in value.items():
|
| 479 |
+
if not isinstance(token, (str, AddedToken)) or not isinstance(index, int):
|
| 480 |
+
raise TypeError(
|
| 481 |
+
f"The provided `added_tokens_decoder` has an element of type {index.__class__, token.__class__}, should be a dict of {int, Union[AddedToken, str]}"
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
self._added_tokens_decoder[index] = AddedToken(token) if isinstance(token, str) else token
|
| 485 |
+
self._added_tokens_encoder[str(token)] = index
|
| 486 |
+
self._update_total_vocab_size()
|
| 487 |
+
|
| 488 |
+
def get_added_vocab(self) -> Dict[str, int]:
|
| 489 |
+
"""
|
| 490 |
+
Returns the added tokens in the vocabulary as a dictionary of token to index. Results might be different from
|
| 491 |
+
the fast call because for now we always add the tokens even if they are already in the vocabulary. This is
|
| 492 |
+
something we should change.
|
| 493 |
+
|
| 494 |
+
Returns:
|
| 495 |
+
`Dict[str, int]`: The added tokens.
|
| 496 |
+
"""
|
| 497 |
+
return self._added_tokens_encoder
|
| 498 |
+
|
| 499 |
+
def __len__(self):
|
| 500 |
+
"""
|
| 501 |
+
Size of the full vocabulary with the added tokens.
|
| 502 |
+
"""
|
| 503 |
+
return self.total_vocab_size
|
| 504 |
+
|
| 505 |
+
def _update_total_vocab_size(self):
|
| 506 |
+
"""
|
| 507 |
+
Update the size of the full vocabulary with the added tokens. Counts the `keys` and not the `values` because
|
| 508 |
+
otherwise if there is a hole in the vocab, we will add tokenizers at a wrong index. This operation is slow and
|
| 509 |
+
is only updated when adding tokens.
|
| 510 |
+
"""
|
| 511 |
+
self.total_vocab_size = len(self.get_vocab())
|
| 512 |
+
|
| 513 |
+
def _add_tokens(self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False) -> int:
|
| 514 |
+
"""
|
| 515 |
+
Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to
|
| 516 |
+
it with indices starting from length of the current vocabulary. Special tokens are sometimes already in the
|
| 517 |
+
vocab which is why they have to be handled specifically.
|
| 518 |
+
|
| 519 |
+
Args:
|
| 520 |
+
new_tokens (`List[str]`or `List[tokenizers.AddedToken]`):
|
| 521 |
+
Token(s) to add in vocabulary. A token is counted as added if it's not already in the vocabulary
|
| 522 |
+
(tested by checking if the tokenizer assign the index of the `unk_token` to them). If a token is part
|
| 523 |
+
of the vocabulary then we simply mark this token as an `AddedToken` which allows to control the
|
| 524 |
+
stripping and normalization of this token. This is NOT possible in `tokenizers`.
|
| 525 |
+
special_tokens (`bool`, *optional*, defaults to `False`):
|
| 526 |
+
Whether or not the tokens should be added as special tokens.
|
| 527 |
+
|
| 528 |
+
Returns:
|
| 529 |
+
`int`: The number of tokens actually added to the vocabulary.
|
| 530 |
+
|
| 531 |
+
Examples:
|
| 532 |
+
|
| 533 |
+
```python
|
| 534 |
+
# Let's see how to increase the vocabulary of Bert model and tokenizer
|
| 535 |
+
tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 536 |
+
model = BertModel.from_pretrained("google-bert/bert-base-uncased")
|
| 537 |
+
|
| 538 |
+
num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-tok2"])
|
| 539 |
+
print("We have added", num_added_toks, "tokens")
|
| 540 |
+
# Note: resize_token_embeddings expects to receive the full size of the new vocabulary, i.e. the length of the tokenizer.
|
| 541 |
+
model.resize_token_embeddings(len(tokenizer))
|
| 542 |
+
```"""
|
| 543 |
+
added_tokens = 0
|
| 544 |
+
if new_tokens is None:
|
| 545 |
+
return added_tokens
|
| 546 |
+
# TODO this is fairly slow to improve!
|
| 547 |
+
current_vocab = self.get_vocab().copy()
|
| 548 |
+
new_idx = len(current_vocab) # only call this once, len gives the last index + 1
|
| 549 |
+
for token in new_tokens:
|
| 550 |
+
if not isinstance(token, (str, AddedToken)):
|
| 551 |
+
raise TypeError(f"Token {token} is not a string but a {type(token)}.")
|
| 552 |
+
if str(token) == "":
|
| 553 |
+
continue
|
| 554 |
+
if isinstance(token, str):
|
| 555 |
+
if token in self._added_tokens_encoder:
|
| 556 |
+
continue
|
| 557 |
+
else:
|
| 558 |
+
# very important for fast and slow equivalence!
|
| 559 |
+
is_special = token in self.all_special_tokens or special_tokens
|
| 560 |
+
token = AddedToken(
|
| 561 |
+
token, rstrip=False, lstrip=False, normalized=not is_special, special=is_special
|
| 562 |
+
)
|
| 563 |
+
elif special_tokens:
|
| 564 |
+
# doing token.special=True changes the normalization! will fix in rust
|
| 565 |
+
# this is important and the only reason why the AddedTokens in each class are normalized by default
|
| 566 |
+
token.__setstate__({"special": True, "normalized": token.normalized})
|
| 567 |
+
if token in self._added_tokens_decoder:
|
| 568 |
+
continue
|
| 569 |
+
if not token.special and token.normalized and getattr(self, "do_lower_case", False):
|
| 570 |
+
# Normalize if requested
|
| 571 |
+
token.content = token.content.lower()
|
| 572 |
+
if token.content not in current_vocab:
|
| 573 |
+
token_index = new_idx + added_tokens
|
| 574 |
+
current_vocab[token.content] = token_index
|
| 575 |
+
added_tokens += 1
|
| 576 |
+
else:
|
| 577 |
+
token_index = current_vocab[token.content]
|
| 578 |
+
|
| 579 |
+
if token.special and str(token) not in self.all_special_tokens:
|
| 580 |
+
self._special_tokens_map["additional_special_tokens"].append(token)
|
| 581 |
+
# the setter automatically updates the reverse map
|
| 582 |
+
self._added_tokens_decoder[token_index] = token
|
| 583 |
+
self._added_tokens_encoder[token.content] = token_index
|
| 584 |
+
if self.verbose:
|
| 585 |
+
logger.info(f"Adding {token} to the vocabulary")
|
| 586 |
+
|
| 587 |
+
self._update_trie()
|
| 588 |
+
self._update_total_vocab_size()
|
| 589 |
+
return added_tokens
|
| 590 |
+
|
| 591 |
+
def _update_trie(self, unique_no_split_tokens: Optional[str] = []):
|
| 592 |
+
for token in self._added_tokens_decoder.values():
|
| 593 |
+
if token not in self.tokens_trie._tokens:
|
| 594 |
+
self.tokens_trie.add(token.content)
|
| 595 |
+
for token in unique_no_split_tokens:
|
| 596 |
+
if token not in self.tokens_trie._tokens:
|
| 597 |
+
self.tokens_trie.add(token)
|
| 598 |
+
|
| 599 |
+
def num_special_tokens_to_add(self, pair: bool = False) -> int:
|
| 600 |
+
"""
|
| 601 |
+
Returns the number of added tokens when encoding a sequence with special tokens.
|
| 602 |
+
|
| 603 |
+
<Tip>
|
| 604 |
+
|
| 605 |
+
This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put
|
| 606 |
+
this inside your training loop.
|
| 607 |
+
|
| 608 |
+
</Tip>
|
| 609 |
+
|
| 610 |
+
Args:
|
| 611 |
+
pair (`bool`, *optional*, defaults to `False`):
|
| 612 |
+
Whether the number of added tokens should be computed in the case of a sequence pair or a single
|
| 613 |
+
sequence.
|
| 614 |
+
|
| 615 |
+
Returns:
|
| 616 |
+
`int`: Number of special tokens added to sequences.
|
| 617 |
+
"""
|
| 618 |
+
token_ids_0 = []
|
| 619 |
+
token_ids_1 = []
|
| 620 |
+
return len(self.build_inputs_with_special_tokens(token_ids_0, token_ids_1 if pair else None))
|
| 621 |
+
|
| 622 |
+
def tokenize(self, text: TextInput, **kwargs) -> List[str]:
|
| 623 |
+
"""
|
| 624 |
+
Converts a string into a sequence of tokens, using the tokenizer.
|
| 625 |
+
|
| 626 |
+
Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies
|
| 627 |
+
(BPE/SentencePieces/WordPieces). Takes care of added tokens.
|
| 628 |
+
|
| 629 |
+
Args:
|
| 630 |
+
text (`str`):
|
| 631 |
+
The sequence to be encoded.
|
| 632 |
+
**kwargs (additional keyword arguments):
|
| 633 |
+
Passed along to the model-specific `prepare_for_tokenization` preprocessing method.
|
| 634 |
+
|
| 635 |
+
Returns:
|
| 636 |
+
`List[str]`: The list of tokens.
|
| 637 |
+
"""
|
| 638 |
+
split_special_tokens = kwargs.pop("split_special_tokens", self.split_special_tokens)
|
| 639 |
+
|
| 640 |
+
text, kwargs = self.prepare_for_tokenization(text, **kwargs)
|
| 641 |
+
|
| 642 |
+
if kwargs:
|
| 643 |
+
logger.warning(f"Keyword arguments {kwargs} not recognized.")
|
| 644 |
+
|
| 645 |
+
if hasattr(self, "do_lower_case") and self.do_lower_case:
|
| 646 |
+
# convert non-special tokens to lowercase. Might be super slow as well?
|
| 647 |
+
escaped_special_toks = [re.escape(s_tok) for s_tok in (self.all_special_tokens)]
|
| 648 |
+
escaped_special_toks += [
|
| 649 |
+
re.escape(s_tok.content)
|
| 650 |
+
for s_tok in (self._added_tokens_decoder.values())
|
| 651 |
+
if not s_tok.special and s_tok.normalized
|
| 652 |
+
]
|
| 653 |
+
pattern = r"(" + r"|".join(escaped_special_toks) + r")|" + r"(.+?)"
|
| 654 |
+
text = re.sub(pattern, lambda m: m.groups()[0] or m.groups()[1].lower(), text)
|
| 655 |
+
|
| 656 |
+
if split_special_tokens:
|
| 657 |
+
no_split_token = []
|
| 658 |
+
tokens = [text]
|
| 659 |
+
else:
|
| 660 |
+
no_split_token = self._added_tokens_encoder.keys() # don't split on any of the added tokens
|
| 661 |
+
# "This is something<special_token_1> else"
|
| 662 |
+
tokens = self.tokens_trie.split(text)
|
| 663 |
+
|
| 664 |
+
# ["This is something", "<special_token_1>", " else"]
|
| 665 |
+
for i, token in enumerate(tokens):
|
| 666 |
+
if token in no_split_token:
|
| 667 |
+
tok_extended = self._added_tokens_decoder.get(self._added_tokens_encoder[token], None)
|
| 668 |
+
left = tokens[i - 1] if i > 0 else None
|
| 669 |
+
right = tokens[i + 1] if i < len(tokens) - 1 else None
|
| 670 |
+
if isinstance(tok_extended, AddedToken):
|
| 671 |
+
if tok_extended.rstrip and right:
|
| 672 |
+
# A bit counter-intuitive but we strip the left of the string
|
| 673 |
+
# since tok_extended.rstrip means the special token is eating all white spaces on its right
|
| 674 |
+
tokens[i + 1] = right.lstrip()
|
| 675 |
+
# Strip white spaces on the left
|
| 676 |
+
if tok_extended.lstrip and left:
|
| 677 |
+
tokens[i - 1] = left.rstrip() # Opposite here
|
| 678 |
+
if tok_extended.single_word and left and left[-1] != " ":
|
| 679 |
+
tokens[i - 1] += token
|
| 680 |
+
tokens[i] = ""
|
| 681 |
+
elif tok_extended.single_word and right and right[0] != " ":
|
| 682 |
+
tokens[i + 1] = token + tokens[i + 1]
|
| 683 |
+
tokens[i] = ""
|
| 684 |
+
else:
|
| 685 |
+
raise ValueError(
|
| 686 |
+
f"{tok_extended} cannot be tokenized because it was not properly added"
|
| 687 |
+
f" to the tokenizer. This means that it is not an `AddedToken` but a {type(tok_extended)}"
|
| 688 |
+
)
|
| 689 |
+
# ["This is something", "<special_token_1>", "else"]
|
| 690 |
+
tokenized_text = []
|
| 691 |
+
for token in tokens:
|
| 692 |
+
# Need to skip eventual empty (fully stripped) tokens
|
| 693 |
+
if not token:
|
| 694 |
+
continue
|
| 695 |
+
if token in no_split_token:
|
| 696 |
+
tokenized_text.append(token)
|
| 697 |
+
else:
|
| 698 |
+
tokenized_text.extend(self._tokenize(token))
|
| 699 |
+
# ["This", " is", " something", "<special_token_1>", "else"]
|
| 700 |
+
return tokenized_text
|
| 701 |
+
|
| 702 |
+
def _tokenize(self, text, **kwargs):
|
| 703 |
+
"""
|
| 704 |
+
Converts a string into a sequence of tokens (string), using the tokenizer. Split in words for word-based
|
| 705 |
+
vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
|
| 706 |
+
|
| 707 |
+
Do NOT take care of added tokens.
|
| 708 |
+
"""
|
| 709 |
+
raise NotImplementedError
|
| 710 |
+
|
| 711 |
+
def convert_tokens_to_ids(self, tokens: Union[str, List[str]]) -> Union[int, List[int]]:
|
| 712 |
+
"""
|
| 713 |
+
Converts a token string (or a sequence of tokens) in a single integer id (or a sequence of ids), using the
|
| 714 |
+
vocabulary.
|
| 715 |
+
|
| 716 |
+
Args:
|
| 717 |
+
tokens (`str` or `List[str]`): One or several token(s) to convert to token id(s).
|
| 718 |
+
|
| 719 |
+
Returns:
|
| 720 |
+
`int` or `List[int]`: The token id or list of token ids.
|
| 721 |
+
"""
|
| 722 |
+
if tokens is None:
|
| 723 |
+
return None
|
| 724 |
+
|
| 725 |
+
if isinstance(tokens, str):
|
| 726 |
+
return self._convert_token_to_id_with_added_voc(tokens)
|
| 727 |
+
|
| 728 |
+
ids = []
|
| 729 |
+
for token in tokens:
|
| 730 |
+
ids.append(self._convert_token_to_id_with_added_voc(token))
|
| 731 |
+
return ids
|
| 732 |
+
|
| 733 |
+
def _convert_token_to_id_with_added_voc(self, token):
|
| 734 |
+
if token is None:
|
| 735 |
+
return None
|
| 736 |
+
|
| 737 |
+
if token in self._added_tokens_encoder:
|
| 738 |
+
return self._added_tokens_encoder[token]
|
| 739 |
+
return self._convert_token_to_id(token)
|
| 740 |
+
|
| 741 |
+
def _convert_token_to_id(self, token):
|
| 742 |
+
raise NotImplementedError
|
| 743 |
+
|
| 744 |
+
def _encode_plus(
|
| 745 |
+
self,
|
| 746 |
+
text: Union[TextInput, PreTokenizedInput, EncodedInput],
|
| 747 |
+
text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
|
| 748 |
+
add_special_tokens: bool = True,
|
| 749 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 750 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 751 |
+
max_length: Optional[int] = None,
|
| 752 |
+
stride: int = 0,
|
| 753 |
+
is_split_into_words: bool = False,
|
| 754 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 755 |
+
padding_side: Optional[bool] = None,
|
| 756 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 757 |
+
return_token_type_ids: Optional[bool] = None,
|
| 758 |
+
return_attention_mask: Optional[bool] = None,
|
| 759 |
+
return_overflowing_tokens: bool = False,
|
| 760 |
+
return_special_tokens_mask: bool = False,
|
| 761 |
+
return_offsets_mapping: bool = False,
|
| 762 |
+
return_length: bool = False,
|
| 763 |
+
verbose: bool = True,
|
| 764 |
+
**kwargs,
|
| 765 |
+
) -> BatchEncoding:
|
| 766 |
+
def get_input_ids(text):
|
| 767 |
+
if isinstance(text, str):
|
| 768 |
+
tokens = self.tokenize(text, **kwargs)
|
| 769 |
+
return self.convert_tokens_to_ids(tokens)
|
| 770 |
+
elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], str):
|
| 771 |
+
if is_split_into_words:
|
| 772 |
+
tokens = list(
|
| 773 |
+
itertools.chain(*(self.tokenize(t, is_split_into_words=True, **kwargs) for t in text))
|
| 774 |
+
)
|
| 775 |
+
return self.convert_tokens_to_ids(tokens)
|
| 776 |
+
else:
|
| 777 |
+
return self.convert_tokens_to_ids(text)
|
| 778 |
+
elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
|
| 779 |
+
return text
|
| 780 |
+
else:
|
| 781 |
+
if is_split_into_words:
|
| 782 |
+
raise ValueError(
|
| 783 |
+
f"Input {text} is not valid. Should be a string or a list/tuple of strings when"
|
| 784 |
+
" `is_split_into_words=True`."
|
| 785 |
+
)
|
| 786 |
+
else:
|
| 787 |
+
raise ValueError(
|
| 788 |
+
f"Input {text} is not valid. Should be a string, a list/tuple of strings or a list/tuple of"
|
| 789 |
+
" integers."
|
| 790 |
+
)
|
| 791 |
+
|
| 792 |
+
if return_offsets_mapping:
|
| 793 |
+
raise NotImplementedError(
|
| 794 |
+
"return_offset_mapping is not available when using Python tokenizers. "
|
| 795 |
+
"To use this feature, change your tokenizer to one deriving from "
|
| 796 |
+
"transformers.PreTrainedTokenizerFast. "
|
| 797 |
+
"More information on available tokenizers at "
|
| 798 |
+
"https://github.com/huggingface/transformers/pull/2674"
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
first_ids = get_input_ids(text)
|
| 802 |
+
second_ids = get_input_ids(text_pair) if text_pair is not None else None
|
| 803 |
+
|
| 804 |
+
return self.prepare_for_model(
|
| 805 |
+
first_ids,
|
| 806 |
+
pair_ids=second_ids,
|
| 807 |
+
add_special_tokens=add_special_tokens,
|
| 808 |
+
padding=padding_strategy.value,
|
| 809 |
+
truncation=truncation_strategy.value,
|
| 810 |
+
max_length=max_length,
|
| 811 |
+
stride=stride,
|
| 812 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 813 |
+
padding_side=padding_side,
|
| 814 |
+
return_tensors=return_tensors,
|
| 815 |
+
prepend_batch_axis=True,
|
| 816 |
+
return_attention_mask=return_attention_mask,
|
| 817 |
+
return_token_type_ids=return_token_type_ids,
|
| 818 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 819 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 820 |
+
return_length=return_length,
|
| 821 |
+
verbose=verbose,
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
def _batch_encode_plus(
|
| 825 |
+
self,
|
| 826 |
+
batch_text_or_text_pairs: Union[
|
| 827 |
+
List[TextInput],
|
| 828 |
+
List[TextInputPair],
|
| 829 |
+
List[PreTokenizedInput],
|
| 830 |
+
List[PreTokenizedInputPair],
|
| 831 |
+
List[EncodedInput],
|
| 832 |
+
List[EncodedInputPair],
|
| 833 |
+
],
|
| 834 |
+
add_special_tokens: bool = True,
|
| 835 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 836 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 837 |
+
max_length: Optional[int] = None,
|
| 838 |
+
stride: int = 0,
|
| 839 |
+
is_split_into_words: bool = False,
|
| 840 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 841 |
+
padding_side: Optional[bool] = None,
|
| 842 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 843 |
+
return_token_type_ids: Optional[bool] = None,
|
| 844 |
+
return_attention_mask: Optional[bool] = None,
|
| 845 |
+
return_overflowing_tokens: bool = False,
|
| 846 |
+
return_special_tokens_mask: bool = False,
|
| 847 |
+
return_offsets_mapping: bool = False,
|
| 848 |
+
return_length: bool = False,
|
| 849 |
+
verbose: bool = True,
|
| 850 |
+
split_special_tokens: bool = False,
|
| 851 |
+
**kwargs,
|
| 852 |
+
) -> BatchEncoding:
|
| 853 |
+
def get_input_ids(text):
|
| 854 |
+
if isinstance(text, str):
|
| 855 |
+
tokens = self.tokenize(text, **kwargs)
|
| 856 |
+
return self.convert_tokens_to_ids(tokens)
|
| 857 |
+
elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], str):
|
| 858 |
+
if is_split_into_words:
|
| 859 |
+
tokens = list(
|
| 860 |
+
itertools.chain(*(self.tokenize(t, is_split_into_words=True, **kwargs) for t in text))
|
| 861 |
+
)
|
| 862 |
+
return self.convert_tokens_to_ids(tokens)
|
| 863 |
+
else:
|
| 864 |
+
return self.convert_tokens_to_ids(text)
|
| 865 |
+
elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
|
| 866 |
+
return text
|
| 867 |
+
else:
|
| 868 |
+
raise ValueError(
|
| 869 |
+
"Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
|
| 870 |
+
)
|
| 871 |
+
|
| 872 |
+
if return_offsets_mapping:
|
| 873 |
+
raise NotImplementedError(
|
| 874 |
+
"return_offset_mapping is not available when using Python tokenizers. "
|
| 875 |
+
"To use this feature, change your tokenizer to one deriving from "
|
| 876 |
+
"transformers.PreTrainedTokenizerFast."
|
| 877 |
+
)
|
| 878 |
+
|
| 879 |
+
input_ids = []
|
| 880 |
+
for ids_or_pair_ids in batch_text_or_text_pairs:
|
| 881 |
+
if not isinstance(ids_or_pair_ids, (list, tuple)):
|
| 882 |
+
ids, pair_ids = ids_or_pair_ids, None
|
| 883 |
+
elif is_split_into_words and not isinstance(ids_or_pair_ids[0], (list, tuple)):
|
| 884 |
+
ids, pair_ids = ids_or_pair_ids, None
|
| 885 |
+
else:
|
| 886 |
+
ids, pair_ids = ids_or_pair_ids
|
| 887 |
+
|
| 888 |
+
first_ids = get_input_ids(ids)
|
| 889 |
+
second_ids = get_input_ids(pair_ids) if pair_ids is not None else None
|
| 890 |
+
input_ids.append((first_ids, second_ids))
|
| 891 |
+
|
| 892 |
+
batch_outputs = self._batch_prepare_for_model(
|
| 893 |
+
input_ids,
|
| 894 |
+
add_special_tokens=add_special_tokens,
|
| 895 |
+
padding_strategy=padding_strategy,
|
| 896 |
+
truncation_strategy=truncation_strategy,
|
| 897 |
+
max_length=max_length,
|
| 898 |
+
stride=stride,
|
| 899 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 900 |
+
padding_side=padding_side,
|
| 901 |
+
return_attention_mask=return_attention_mask,
|
| 902 |
+
return_token_type_ids=return_token_type_ids,
|
| 903 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 904 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 905 |
+
return_length=return_length,
|
| 906 |
+
return_tensors=return_tensors,
|
| 907 |
+
verbose=verbose,
|
| 908 |
+
split_special_tokens=split_special_tokens,
|
| 909 |
+
)
|
| 910 |
+
|
| 911 |
+
return BatchEncoding(batch_outputs)
|
| 912 |
+
|
| 913 |
+
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
|
| 914 |
+
def _batch_prepare_for_model(
|
| 915 |
+
self,
|
| 916 |
+
batch_ids_pairs: List[Union[PreTokenizedInputPair, Tuple[List[int], None]]],
|
| 917 |
+
add_special_tokens: bool = True,
|
| 918 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 919 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 920 |
+
max_length: Optional[int] = None,
|
| 921 |
+
stride: int = 0,
|
| 922 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 923 |
+
padding_side: Optional[bool] = None,
|
| 924 |
+
return_tensors: Optional[str] = None,
|
| 925 |
+
return_token_type_ids: Optional[bool] = None,
|
| 926 |
+
return_attention_mask: Optional[bool] = None,
|
| 927 |
+
return_overflowing_tokens: bool = False,
|
| 928 |
+
return_special_tokens_mask: bool = False,
|
| 929 |
+
return_length: bool = False,
|
| 930 |
+
verbose: bool = True,
|
| 931 |
+
split_special_tokens: bool = False,
|
| 932 |
+
) -> BatchEncoding:
|
| 933 |
+
"""
|
| 934 |
+
Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
|
| 935 |
+
adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
|
| 936 |
+
manages a moving window (with user defined stride) for overflowing tokens
|
| 937 |
+
|
| 938 |
+
Args:
|
| 939 |
+
batch_ids_pairs: list of tokenized input ids or input ids pairs
|
| 940 |
+
"""
|
| 941 |
+
|
| 942 |
+
batch_outputs = {}
|
| 943 |
+
for first_ids, second_ids in batch_ids_pairs:
|
| 944 |
+
outputs = self.prepare_for_model(
|
| 945 |
+
first_ids,
|
| 946 |
+
second_ids,
|
| 947 |
+
add_special_tokens=add_special_tokens,
|
| 948 |
+
padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward
|
| 949 |
+
truncation=truncation_strategy.value,
|
| 950 |
+
max_length=max_length,
|
| 951 |
+
stride=stride,
|
| 952 |
+
pad_to_multiple_of=None, # we pad in batch afterward
|
| 953 |
+
padding_side=None, # we pad in batch afterward
|
| 954 |
+
return_attention_mask=False, # we pad in batch afterward
|
| 955 |
+
return_token_type_ids=return_token_type_ids,
|
| 956 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 957 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 958 |
+
return_length=return_length,
|
| 959 |
+
return_tensors=None, # We convert the whole batch to tensors at the end
|
| 960 |
+
prepend_batch_axis=False,
|
| 961 |
+
verbose=verbose,
|
| 962 |
+
split_special_tokens=split_special_tokens,
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
+
for key, value in outputs.items():
|
| 966 |
+
if key not in batch_outputs:
|
| 967 |
+
batch_outputs[key] = []
|
| 968 |
+
batch_outputs[key].append(value)
|
| 969 |
+
|
| 970 |
+
batch_outputs = self.pad(
|
| 971 |
+
batch_outputs,
|
| 972 |
+
padding=padding_strategy.value,
|
| 973 |
+
max_length=max_length,
|
| 974 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 975 |
+
padding_side=padding_side,
|
| 976 |
+
return_attention_mask=return_attention_mask,
|
| 977 |
+
)
|
| 978 |
+
|
| 979 |
+
batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
|
| 980 |
+
|
| 981 |
+
return batch_outputs
|
| 982 |
+
|
| 983 |
+
def prepare_for_tokenization(
|
| 984 |
+
self, text: str, is_split_into_words: bool = False, **kwargs
|
| 985 |
+
) -> Tuple[str, Dict[str, Any]]:
|
| 986 |
+
"""
|
| 987 |
+
Performs any necessary transformations before tokenization.
|
| 988 |
+
|
| 989 |
+
This method should pop the arguments from kwargs and return the remaining `kwargs` as well. We test the
|
| 990 |
+
`kwargs` at the end of the encoding process to be sure all the arguments have been used.
|
| 991 |
+
|
| 992 |
+
Args:
|
| 993 |
+
text (`str`):
|
| 994 |
+
The text to prepare.
|
| 995 |
+
is_split_into_words (`bool`, *optional*, defaults to `False`):
|
| 996 |
+
Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the
|
| 997 |
+
tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)
|
| 998 |
+
which it will tokenize. This is useful for NER or token classification.
|
| 999 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 1000 |
+
Keyword arguments to use for the tokenization.
|
| 1001 |
+
|
| 1002 |
+
Returns:
|
| 1003 |
+
`Tuple[str, Dict[str, Any]]`: The prepared text and the unused kwargs.
|
| 1004 |
+
"""
|
| 1005 |
+
return (text, kwargs)
|
| 1006 |
+
|
| 1007 |
+
def get_special_tokens_mask(
|
| 1008 |
+
self, token_ids_0: List, token_ids_1: Optional[List] = None, already_has_special_tokens: bool = False
|
| 1009 |
+
) -> List[int]:
|
| 1010 |
+
"""
|
| 1011 |
+
Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 1012 |
+
special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
|
| 1013 |
+
|
| 1014 |
+
Args:
|
| 1015 |
+
token_ids_0 (`List[int]`):
|
| 1016 |
+
List of ids of the first sequence.
|
| 1017 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 1018 |
+
List of ids of the second sequence.
|
| 1019 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 1020 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 1021 |
+
|
| 1022 |
+
Returns:
|
| 1023 |
+
A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 1024 |
+
"""
|
| 1025 |
+
if already_has_special_tokens:
|
| 1026 |
+
if token_ids_1 is not None:
|
| 1027 |
+
raise ValueError(
|
| 1028 |
+
"You should not supply a second sequence if the provided sequence of "
|
| 1029 |
+
"ids is already formatted with special tokens for the model."
|
| 1030 |
+
)
|
| 1031 |
+
|
| 1032 |
+
return super().get_special_tokens_mask(
|
| 1033 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 1034 |
+
)
|
| 1035 |
+
return [0] * ((len(token_ids_1) if token_ids_1 else 0) + len(token_ids_0))
|
| 1036 |
+
|
| 1037 |
+
@overload
|
| 1038 |
+
def convert_ids_to_tokens(self, ids: int, skip_special_tokens: bool = False) -> str: ...
|
| 1039 |
+
|
| 1040 |
+
@overload
|
| 1041 |
+
def convert_ids_to_tokens(self, ids: List[int], skip_special_tokens: bool = False) -> List[str]: ...
|
| 1042 |
+
|
| 1043 |
+
def convert_ids_to_tokens(
|
| 1044 |
+
self, ids: Union[int, List[int]], skip_special_tokens: bool = False
|
| 1045 |
+
) -> Union[str, List[str]]:
|
| 1046 |
+
"""
|
| 1047 |
+
Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and
|
| 1048 |
+
added tokens.
|
| 1049 |
+
|
| 1050 |
+
Args:
|
| 1051 |
+
ids (`int` or `List[int]`):
|
| 1052 |
+
The token id (or token ids) to convert to tokens.
|
| 1053 |
+
skip_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 1054 |
+
Whether or not to remove special tokens in the decoding.
|
| 1055 |
+
|
| 1056 |
+
Returns:
|
| 1057 |
+
`str` or `List[str]`: The decoded token(s).
|
| 1058 |
+
"""
|
| 1059 |
+
if isinstance(ids, int):
|
| 1060 |
+
if ids in self._added_tokens_decoder:
|
| 1061 |
+
return self._added_tokens_decoder[ids].content
|
| 1062 |
+
else:
|
| 1063 |
+
return self._convert_id_to_token(ids)
|
| 1064 |
+
tokens = []
|
| 1065 |
+
for index in ids:
|
| 1066 |
+
index = int(index)
|
| 1067 |
+
if skip_special_tokens and index in self.all_special_ids:
|
| 1068 |
+
continue
|
| 1069 |
+
if index in self._added_tokens_decoder:
|
| 1070 |
+
tokens.append(self._added_tokens_decoder[index].content)
|
| 1071 |
+
else:
|
| 1072 |
+
tokens.append(self._convert_id_to_token(index))
|
| 1073 |
+
return tokens
|
| 1074 |
+
|
| 1075 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 1076 |
+
raise NotImplementedError
|
| 1077 |
+
|
| 1078 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
| 1079 |
+
return " ".join(tokens)
|
| 1080 |
+
|
| 1081 |
+
def _decode(
|
| 1082 |
+
self,
|
| 1083 |
+
token_ids: Union[int, List[int]],
|
| 1084 |
+
skip_special_tokens: bool = False,
|
| 1085 |
+
clean_up_tokenization_spaces: bool = None,
|
| 1086 |
+
spaces_between_special_tokens: bool = True,
|
| 1087 |
+
**kwargs,
|
| 1088 |
+
) -> str:
|
| 1089 |
+
self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False)
|
| 1090 |
+
|
| 1091 |
+
filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)
|
| 1092 |
+
# If given is a single id, prevents splitting the string in upcoming loop
|
| 1093 |
+
if isinstance(filtered_tokens, str):
|
| 1094 |
+
filtered_tokens = [filtered_tokens]
|
| 1095 |
+
|
| 1096 |
+
legacy_added_tokens = set(self._added_tokens_encoder.keys()) - set(self.all_special_tokens) | {
|
| 1097 |
+
token for token in self.additional_special_tokens if self.convert_tokens_to_ids(token) >= self.vocab_size
|
| 1098 |
+
}
|
| 1099 |
+
# To avoid mixing byte-level and unicode for byte-level BPT
|
| 1100 |
+
# we need to build string separately for added tokens and byte-level tokens
|
| 1101 |
+
# cf. https://github.com/huggingface/transformers/issues/1133
|
| 1102 |
+
sub_texts = []
|
| 1103 |
+
current_sub_text = []
|
| 1104 |
+
# TODO @ArthurZ in version 5, special tokens should be handled in convert_tokens_to_string, while _convert_tokens_to_string
|
| 1105 |
+
for token in filtered_tokens:
|
| 1106 |
+
if skip_special_tokens and token in self.all_special_tokens:
|
| 1107 |
+
continue
|
| 1108 |
+
if token in legacy_added_tokens:
|
| 1109 |
+
if current_sub_text:
|
| 1110 |
+
string = self.convert_tokens_to_string(current_sub_text)
|
| 1111 |
+
if len(string) > 0:
|
| 1112 |
+
sub_texts.append(string)
|
| 1113 |
+
current_sub_text = []
|
| 1114 |
+
sub_texts.append(token)
|
| 1115 |
+
else:
|
| 1116 |
+
current_sub_text.append(token)
|
| 1117 |
+
if current_sub_text:
|
| 1118 |
+
sub_texts.append(self.convert_tokens_to_string(current_sub_text))
|
| 1119 |
+
|
| 1120 |
+
if spaces_between_special_tokens:
|
| 1121 |
+
text = " ".join(sub_texts)
|
| 1122 |
+
else:
|
| 1123 |
+
text = "".join(sub_texts)
|
| 1124 |
+
|
| 1125 |
+
clean_up_tokenization_spaces = (
|
| 1126 |
+
clean_up_tokenization_spaces
|
| 1127 |
+
if clean_up_tokenization_spaces is not None
|
| 1128 |
+
else self.clean_up_tokenization_spaces
|
| 1129 |
+
)
|
| 1130 |
+
if clean_up_tokenization_spaces:
|
| 1131 |
+
clean_text = self.clean_up_tokenization(text)
|
| 1132 |
+
return clean_text
|
| 1133 |
+
else:
|
| 1134 |
+
return text
|
tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/tokenization_utils_base.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tas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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Inc. team.
|
| 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 |
+
"""
|
| 16 |
+
Tokenization classes for fast tokenizers (provided by HuggingFace's tokenizers library). For slow (python) tokenizers
|
| 17 |
+
see tokenization_utils.py
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import copy
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
from collections import defaultdict
|
| 24 |
+
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
|
| 25 |
+
|
| 26 |
+
import tokenizers.pre_tokenizers as pre_tokenizers_fast
|
| 27 |
+
from tokenizers import Encoding as EncodingFast
|
| 28 |
+
from tokenizers import Tokenizer as TokenizerFast
|
| 29 |
+
from tokenizers.decoders import Decoder as DecoderFast
|
| 30 |
+
from tokenizers.trainers import BpeTrainer, UnigramTrainer, WordLevelTrainer, WordPieceTrainer
|
| 31 |
+
|
| 32 |
+
from .convert_slow_tokenizer import convert_slow_tokenizer
|
| 33 |
+
from .integrations.ggml import convert_gguf_tokenizer
|
| 34 |
+
from .modeling_gguf_pytorch_utils import load_gguf_checkpoint
|
| 35 |
+
from .tokenization_utils import PreTrainedTokenizer
|
| 36 |
+
from .tokenization_utils_base import (
|
| 37 |
+
INIT_TOKENIZER_DOCSTRING,
|
| 38 |
+
AddedToken,
|
| 39 |
+
BatchEncoding,
|
| 40 |
+
PreTokenizedInput,
|
| 41 |
+
PreTokenizedInputPair,
|
| 42 |
+
PreTrainedTokenizerBase,
|
| 43 |
+
SpecialTokensMixin,
|
| 44 |
+
TextInput,
|
| 45 |
+
TextInputPair,
|
| 46 |
+
TruncationStrategy,
|
| 47 |
+
)
|
| 48 |
+
from .utils import PaddingStrategy, add_end_docstrings, logging
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
logger = logging.get_logger(__name__)
|
| 52 |
+
|
| 53 |
+
# Fast tokenizers (provided by HuggingFace tokenizer's library) can be saved in a single file
|
| 54 |
+
TOKENIZER_FILE = "tokenizer.json"
|
| 55 |
+
SPECIAL_TOKENS_MAP_FILE = "special_tokens_map.json"
|
| 56 |
+
TOKENIZER_CONFIG_FILE = "tokenizer_config.json"
|
| 57 |
+
TIKTOKEN_VOCAB_FILE = "tokenizer.model"
|
| 58 |
+
|
| 59 |
+
# Slow tokenizers have an additional added tokens files
|
| 60 |
+
ADDED_TOKENS_FILE = "added_tokens.json"
|
| 61 |
+
|
| 62 |
+
INIT_TOKENIZER_DOCSTRING += """
|
| 63 |
+
tokenizer_object ([`tokenizers.Tokenizer`]):
|
| 64 |
+
A [`tokenizers.Tokenizer`] object from 🤗 tokenizers to instantiate from. See [Using tokenizers from 🤗
|
| 65 |
+
tokenizers](../fast_tokenizers) for more information.
|
| 66 |
+
tokenizer_file ([`str`]):
|
| 67 |
+
A path to a local JSON file representing a previously serialized [`tokenizers.Tokenizer`] object from 🤗
|
| 68 |
+
tokenizers.
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
MODEL_TO_TRAINER_MAPPING = {
|
| 72 |
+
"BPE": BpeTrainer,
|
| 73 |
+
"Unigram": UnigramTrainer,
|
| 74 |
+
"WordLevel": WordLevelTrainer,
|
| 75 |
+
"WordPiece": WordPieceTrainer,
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
VOCAB_FILES_NAMES = {"tokenizer_file": TOKENIZER_FILE, "vocab_file": TIKTOKEN_VOCAB_FILE}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@add_end_docstrings(INIT_TOKENIZER_DOCSTRING)
|
| 82 |
+
class PreTrainedTokenizerFast(PreTrainedTokenizerBase):
|
| 83 |
+
"""
|
| 84 |
+
Base class for all fast tokenizers (wrapping HuggingFace tokenizers library).
|
| 85 |
+
|
| 86 |
+
Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`].
|
| 87 |
+
|
| 88 |
+
Handles all the shared methods for tokenization and special tokens, as well as methods for
|
| 89 |
+
downloading/caching/loading pretrained tokenizers, as well as adding tokens to the vocabulary.
|
| 90 |
+
|
| 91 |
+
This class also contains the added tokens in a unified way on top of all tokenizers so we don't have to handle the
|
| 92 |
+
specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 96 |
+
slow_tokenizer_class: PreTrainedTokenizer = None
|
| 97 |
+
|
| 98 |
+
def __init__(self, *args, **kwargs):
|
| 99 |
+
tokenizer_object = kwargs.pop("tokenizer_object", None)
|
| 100 |
+
slow_tokenizer = kwargs.pop("__slow_tokenizer", None)
|
| 101 |
+
gguf_file = kwargs.pop("gguf_file", None)
|
| 102 |
+
fast_tokenizer_file = kwargs.pop("tokenizer_file", None)
|
| 103 |
+
from_slow = kwargs.pop("from_slow", False)
|
| 104 |
+
added_tokens_decoder = kwargs.pop("added_tokens_decoder", {})
|
| 105 |
+
|
| 106 |
+
if from_slow and slow_tokenizer is None and self.slow_tokenizer_class is None:
|
| 107 |
+
raise ValueError(
|
| 108 |
+
"Cannot instantiate this tokenizer from a slow version. If it's based on sentencepiece, make sure you "
|
| 109 |
+
"have sentencepiece installed."
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
if tokenizer_object is not None:
|
| 113 |
+
fast_tokenizer = copy.deepcopy(tokenizer_object)
|
| 114 |
+
elif fast_tokenizer_file is not None and not from_slow:
|
| 115 |
+
# We have a serialization from tokenizers which let us directly build the backend
|
| 116 |
+
fast_tokenizer = TokenizerFast.from_file(fast_tokenizer_file)
|
| 117 |
+
elif slow_tokenizer:
|
| 118 |
+
# We need to convert a slow tokenizer to build the backend
|
| 119 |
+
fast_tokenizer = convert_slow_tokenizer(slow_tokenizer)
|
| 120 |
+
elif gguf_file is not None:
|
| 121 |
+
# We need to convert a slow tokenizer to build the backend
|
| 122 |
+
gguf_param = load_gguf_checkpoint(kwargs.get("vocab_file"))
|
| 123 |
+
architecture = gguf_param["config"]["model_type"]
|
| 124 |
+
tokenizer_dict = gguf_param["tokenizer"]
|
| 125 |
+
tokenizer_config = gguf_param["tokenizer_config"]
|
| 126 |
+
fast_tokenizer, additional_kwargs = convert_gguf_tokenizer(architecture, tokenizer_dict)
|
| 127 |
+
kwargs.update(tokenizer_config)
|
| 128 |
+
if len(additional_kwargs) > 0:
|
| 129 |
+
kwargs.update(additional_kwargs)
|
| 130 |
+
elif self.slow_tokenizer_class is not None and slow_tokenizer is not False:
|
| 131 |
+
# We need to create and convert a slow tokenizer to build the backend
|
| 132 |
+
slow_tokenizer = self.slow_tokenizer_class(*args, **kwargs)
|
| 133 |
+
fast_tokenizer = convert_slow_tokenizer(slow_tokenizer)
|
| 134 |
+
elif not slow_tokenizer:
|
| 135 |
+
# We tried loading a slow_tokenizer with spm and failed, try to load with tiktoken
|
| 136 |
+
self.vocab_file = kwargs.get("vocab_file", None)
|
| 137 |
+
self.additional_special_tokens = kwargs.get("additional_special_tokens", [])
|
| 138 |
+
fast_tokenizer = convert_slow_tokenizer(self, from_tiktoken=True)
|
| 139 |
+
slow_tokenizer = None
|
| 140 |
+
else:
|
| 141 |
+
raise ValueError(
|
| 142 |
+
"Couldn't instantiate the backend tokenizer from one of: \n"
|
| 143 |
+
"(1) a `tokenizers` library serialization file, \n"
|
| 144 |
+
"(2) a slow tokenizer instance to convert or \n"
|
| 145 |
+
"(3) an equivalent slow tokenizer class to instantiate and convert. \n"
|
| 146 |
+
"You need to have sentencepiece or tiktoken installed to convert a slow tokenizer to a fast one."
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
self._tokenizer = fast_tokenizer
|
| 150 |
+
|
| 151 |
+
if slow_tokenizer is not None:
|
| 152 |
+
kwargs.update(slow_tokenizer.init_kwargs)
|
| 153 |
+
|
| 154 |
+
self._decode_use_source_tokenizer = False
|
| 155 |
+
|
| 156 |
+
_truncation = self._tokenizer.truncation
|
| 157 |
+
|
| 158 |
+
if _truncation is not None:
|
| 159 |
+
self._tokenizer.enable_truncation(**_truncation)
|
| 160 |
+
kwargs.setdefault("max_length", _truncation["max_length"])
|
| 161 |
+
kwargs.setdefault("truncation_side", _truncation["direction"])
|
| 162 |
+
kwargs.setdefault("stride", _truncation["stride"])
|
| 163 |
+
kwargs.setdefault("truncation_strategy", _truncation["strategy"])
|
| 164 |
+
else:
|
| 165 |
+
self._tokenizer.no_truncation()
|
| 166 |
+
|
| 167 |
+
_padding = self._tokenizer.padding
|
| 168 |
+
if _padding is not None:
|
| 169 |
+
self._tokenizer.enable_padding(**_padding)
|
| 170 |
+
kwargs.setdefault("pad_token", _padding["pad_token"])
|
| 171 |
+
kwargs.setdefault("pad_token_type_id", _padding["pad_type_id"])
|
| 172 |
+
kwargs.setdefault("padding_side", _padding["direction"])
|
| 173 |
+
kwargs.setdefault("max_length", _padding["length"])
|
| 174 |
+
kwargs.setdefault("pad_to_multiple_of", _padding["pad_to_multiple_of"])
|
| 175 |
+
|
| 176 |
+
# We call this after having initialized the backend tokenizer because we update it.
|
| 177 |
+
super().__init__(**kwargs)
|
| 178 |
+
self._tokenizer.encode_special_tokens = self.split_special_tokens
|
| 179 |
+
|
| 180 |
+
added_tokens_decoder_hash = {hash(repr(token)) for token in self.added_tokens_decoder}
|
| 181 |
+
tokens_to_add = [
|
| 182 |
+
token
|
| 183 |
+
for index, token in sorted(added_tokens_decoder.items(), key=lambda x: x[0])
|
| 184 |
+
if hash(repr(token)) not in added_tokens_decoder_hash
|
| 185 |
+
]
|
| 186 |
+
encoder = list(self.added_tokens_encoder.keys()) + [str(token) for token in tokens_to_add]
|
| 187 |
+
# if some of the special tokens are strings, we check if we don't already have a token
|
| 188 |
+
tokens_to_add += [
|
| 189 |
+
token for token in self.all_special_tokens_extended if token not in encoder and token not in tokens_to_add
|
| 190 |
+
]
|
| 191 |
+
|
| 192 |
+
if len(tokens_to_add) > 0:
|
| 193 |
+
tokens = []
|
| 194 |
+
special_tokens = self.all_special_tokens
|
| 195 |
+
for token in tokens_to_add:
|
| 196 |
+
is_special = (
|
| 197 |
+
(token.special or str(token) in special_tokens)
|
| 198 |
+
if isinstance(token, AddedToken)
|
| 199 |
+
else str(token) in special_tokens
|
| 200 |
+
)
|
| 201 |
+
if isinstance(token, str):
|
| 202 |
+
token = AddedToken(token, special=is_special)
|
| 203 |
+
else:
|
| 204 |
+
token.special = is_special
|
| 205 |
+
tokens.append(token)
|
| 206 |
+
if tokens:
|
| 207 |
+
self.add_tokens(tokens)
|
| 208 |
+
|
| 209 |
+
@property
|
| 210 |
+
def is_fast(self) -> bool:
|
| 211 |
+
return True
|
| 212 |
+
|
| 213 |
+
@property
|
| 214 |
+
def can_save_slow_tokenizer(self) -> bool:
|
| 215 |
+
"""
|
| 216 |
+
`bool`: Whether or not the slow tokenizer can be saved. Usually for sentencepiece based slow tokenizer, this
|
| 217 |
+
can only be `True` if the original `"sentencepiece.model"` was not deleted.
|
| 218 |
+
"""
|
| 219 |
+
return True
|
| 220 |
+
|
| 221 |
+
@property
|
| 222 |
+
def vocab_size(self) -> int:
|
| 223 |
+
"""
|
| 224 |
+
`int`: Size of the base vocabulary (without the added tokens).
|
| 225 |
+
"""
|
| 226 |
+
return self._tokenizer.get_vocab_size(with_added_tokens=False)
|
| 227 |
+
|
| 228 |
+
def get_vocab(self) -> Dict[str, int]:
|
| 229 |
+
return self._tokenizer.get_vocab(with_added_tokens=True)
|
| 230 |
+
|
| 231 |
+
@property
|
| 232 |
+
def vocab(self) -> Dict[str, int]:
|
| 233 |
+
return self.get_vocab()
|
| 234 |
+
|
| 235 |
+
@property
|
| 236 |
+
def added_tokens_encoder(self) -> Dict[str, int]:
|
| 237 |
+
"""
|
| 238 |
+
Returns the sorted mapping from string to index. The added tokens encoder is cached for performance
|
| 239 |
+
optimisation in `self._added_tokens_encoder` for the slow tokenizers.
|
| 240 |
+
"""
|
| 241 |
+
return {k.content: v for v, k in sorted(self.added_tokens_decoder.items(), key=lambda item: item[0])}
|
| 242 |
+
|
| 243 |
+
@property
|
| 244 |
+
def added_tokens_decoder(self) -> Dict[int, AddedToken]:
|
| 245 |
+
"""
|
| 246 |
+
Returns the added tokens in the vocabulary as a dictionary of index to AddedToken.
|
| 247 |
+
|
| 248 |
+
Returns:
|
| 249 |
+
`Dict[str, int]`: The added tokens.
|
| 250 |
+
"""
|
| 251 |
+
return self._tokenizer.get_added_tokens_decoder()
|
| 252 |
+
|
| 253 |
+
def get_added_vocab(self) -> Dict[str, int]:
|
| 254 |
+
"""
|
| 255 |
+
Returns the added tokens in the vocabulary as a dictionary of token to index.
|
| 256 |
+
|
| 257 |
+
Returns:
|
| 258 |
+
`Dict[str, int]`: The added tokens.
|
| 259 |
+
"""
|
| 260 |
+
return {k.content: v for v, k in sorted(self.added_tokens_decoder.items(), key=lambda item: item[0])}
|
| 261 |
+
|
| 262 |
+
def __len__(self) -> int:
|
| 263 |
+
"""
|
| 264 |
+
Size of the full vocabulary with the added tokens.
|
| 265 |
+
"""
|
| 266 |
+
return self._tokenizer.get_vocab_size(with_added_tokens=True)
|
| 267 |
+
|
| 268 |
+
@property
|
| 269 |
+
def backend_tokenizer(self) -> TokenizerFast:
|
| 270 |
+
"""
|
| 271 |
+
`tokenizers.implementations.BaseTokenizer`: The Rust tokenizer used as a backend.
|
| 272 |
+
"""
|
| 273 |
+
return self._tokenizer
|
| 274 |
+
|
| 275 |
+
@property
|
| 276 |
+
def decoder(self) -> DecoderFast:
|
| 277 |
+
"""
|
| 278 |
+
`tokenizers.decoders.Decoder`: The Rust decoder for this tokenizer.
|
| 279 |
+
"""
|
| 280 |
+
return self._tokenizer.decoder
|
| 281 |
+
|
| 282 |
+
def _convert_encoding(
|
| 283 |
+
self,
|
| 284 |
+
encoding: EncodingFast,
|
| 285 |
+
return_token_type_ids: Optional[bool] = None,
|
| 286 |
+
return_attention_mask: Optional[bool] = None,
|
| 287 |
+
return_overflowing_tokens: bool = False,
|
| 288 |
+
return_special_tokens_mask: bool = False,
|
| 289 |
+
return_offsets_mapping: bool = False,
|
| 290 |
+
return_length: bool = False,
|
| 291 |
+
verbose: bool = True,
|
| 292 |
+
) -> Tuple[Dict[str, Any], List[EncodingFast]]:
|
| 293 |
+
"""
|
| 294 |
+
Convert the encoding representation (from low-level HuggingFace tokenizer output) to a python Dict and a list
|
| 295 |
+
of encodings, take care of building a batch from overflowing tokens.
|
| 296 |
+
|
| 297 |
+
Overflowing tokens are converted to additional examples (like batches) so the output values of the dict are
|
| 298 |
+
lists (overflows) of lists (tokens).
|
| 299 |
+
|
| 300 |
+
Output shape: (overflows, sequence length)
|
| 301 |
+
"""
|
| 302 |
+
if return_token_type_ids is None:
|
| 303 |
+
return_token_type_ids = "token_type_ids" in self.model_input_names
|
| 304 |
+
if return_attention_mask is None:
|
| 305 |
+
return_attention_mask = "attention_mask" in self.model_input_names
|
| 306 |
+
|
| 307 |
+
if return_overflowing_tokens and encoding.overflowing is not None:
|
| 308 |
+
encodings = [encoding] + encoding.overflowing
|
| 309 |
+
else:
|
| 310 |
+
encodings = [encoding]
|
| 311 |
+
|
| 312 |
+
encoding_dict = defaultdict(list)
|
| 313 |
+
for e in encodings:
|
| 314 |
+
encoding_dict["input_ids"].append(e.ids)
|
| 315 |
+
|
| 316 |
+
if return_token_type_ids:
|
| 317 |
+
encoding_dict["token_type_ids"].append(e.type_ids)
|
| 318 |
+
if return_attention_mask:
|
| 319 |
+
encoding_dict["attention_mask"].append(e.attention_mask)
|
| 320 |
+
if return_special_tokens_mask:
|
| 321 |
+
encoding_dict["special_tokens_mask"].append(e.special_tokens_mask)
|
| 322 |
+
if return_offsets_mapping:
|
| 323 |
+
encoding_dict["offset_mapping"].append(e.offsets)
|
| 324 |
+
if return_length:
|
| 325 |
+
encoding_dict["length"].append(len(e.ids))
|
| 326 |
+
|
| 327 |
+
return encoding_dict, encodings
|
| 328 |
+
|
| 329 |
+
def convert_tokens_to_ids(self, tokens: Union[str, Iterable[str]]) -> Union[int, List[int]]:
|
| 330 |
+
"""
|
| 331 |
+
Converts a token string (or a sequence of tokens) in a single integer id (or a Iterable of ids), using the
|
| 332 |
+
vocabulary.
|
| 333 |
+
|
| 334 |
+
Args:
|
| 335 |
+
tokens (`str` or `Iterable[str]`): One or several token(s) to convert to token id(s).
|
| 336 |
+
|
| 337 |
+
Returns:
|
| 338 |
+
`int` or `List[int]`: The token id or list of token ids.
|
| 339 |
+
"""
|
| 340 |
+
if isinstance(tokens, str):
|
| 341 |
+
return self._convert_token_to_id_with_added_voc(tokens)
|
| 342 |
+
|
| 343 |
+
return [self._convert_token_to_id_with_added_voc(token) for token in tokens]
|
| 344 |
+
|
| 345 |
+
def _convert_token_to_id_with_added_voc(self, token: str) -> int:
|
| 346 |
+
index = self._tokenizer.token_to_id(token)
|
| 347 |
+
if index is None:
|
| 348 |
+
return self.unk_token_id
|
| 349 |
+
return index
|
| 350 |
+
|
| 351 |
+
def _convert_id_to_token(self, index: int) -> Optional[str]:
|
| 352 |
+
return self._tokenizer.id_to_token(int(index))
|
| 353 |
+
|
| 354 |
+
def _add_tokens(self, new_tokens: List[Union[str, AddedToken]], special_tokens=False) -> int:
|
| 355 |
+
if special_tokens:
|
| 356 |
+
return self._tokenizer.add_special_tokens(new_tokens)
|
| 357 |
+
|
| 358 |
+
return self._tokenizer.add_tokens(new_tokens)
|
| 359 |
+
|
| 360 |
+
def num_special_tokens_to_add(self, pair: bool = False) -> int:
|
| 361 |
+
"""
|
| 362 |
+
Returns the number of added tokens when encoding a sequence with special tokens.
|
| 363 |
+
|
| 364 |
+
<Tip>
|
| 365 |
+
|
| 366 |
+
This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put
|
| 367 |
+
this inside your training loop.
|
| 368 |
+
|
| 369 |
+
</Tip>
|
| 370 |
+
|
| 371 |
+
Args:
|
| 372 |
+
pair (`bool`, *optional*, defaults to `False`):
|
| 373 |
+
Whether the number of added tokens should be computed in the case of a sequence pair or a single
|
| 374 |
+
sequence.
|
| 375 |
+
|
| 376 |
+
Returns:
|
| 377 |
+
`int`: Number of special tokens added to sequences.
|
| 378 |
+
"""
|
| 379 |
+
return self._tokenizer.num_special_tokens_to_add(pair)
|
| 380 |
+
|
| 381 |
+
def convert_ids_to_tokens(
|
| 382 |
+
self, ids: Union[int, List[int]], skip_special_tokens: bool = False
|
| 383 |
+
) -> Union[str, List[str]]:
|
| 384 |
+
"""
|
| 385 |
+
Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and
|
| 386 |
+
added tokens.
|
| 387 |
+
|
| 388 |
+
Args:
|
| 389 |
+
ids (`int` or `List[int]`):
|
| 390 |
+
The token id (or token ids) to convert to tokens.
|
| 391 |
+
skip_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 392 |
+
Whether or not to remove special tokens in the decoding.
|
| 393 |
+
|
| 394 |
+
Returns:
|
| 395 |
+
`str` or `List[str]`: The decoded token(s).
|
| 396 |
+
"""
|
| 397 |
+
if isinstance(ids, int):
|
| 398 |
+
return self._tokenizer.id_to_token(ids)
|
| 399 |
+
tokens = []
|
| 400 |
+
for index in ids:
|
| 401 |
+
index = int(index)
|
| 402 |
+
if skip_special_tokens and index in self.all_special_ids:
|
| 403 |
+
continue
|
| 404 |
+
tokens.append(self._tokenizer.id_to_token(index))
|
| 405 |
+
return tokens
|
| 406 |
+
|
| 407 |
+
def tokenize(self, text: str, pair: Optional[str] = None, add_special_tokens: bool = False, **kwargs) -> List[str]:
|
| 408 |
+
return self.encode_plus(text=text, text_pair=pair, add_special_tokens=add_special_tokens, **kwargs).tokens()
|
| 409 |
+
|
| 410 |
+
def set_truncation_and_padding(
|
| 411 |
+
self,
|
| 412 |
+
padding_strategy: PaddingStrategy,
|
| 413 |
+
truncation_strategy: TruncationStrategy,
|
| 414 |
+
max_length: int,
|
| 415 |
+
stride: int,
|
| 416 |
+
pad_to_multiple_of: Optional[int],
|
| 417 |
+
padding_side: Optional[bool],
|
| 418 |
+
):
|
| 419 |
+
"""
|
| 420 |
+
Define the truncation and the padding strategies for fast tokenizers (provided by HuggingFace tokenizers
|
| 421 |
+
library) and restore the tokenizer settings afterwards.
|
| 422 |
+
|
| 423 |
+
The provided tokenizer has no padding / truncation strategy before the managed section. If your tokenizer set a
|
| 424 |
+
padding / truncation strategy before, then it will be reset to no padding / truncation when exiting the managed
|
| 425 |
+
section.
|
| 426 |
+
|
| 427 |
+
Args:
|
| 428 |
+
padding_strategy ([`~utils.PaddingStrategy`]):
|
| 429 |
+
The kind of padding that will be applied to the input
|
| 430 |
+
truncation_strategy ([`~tokenization_utils_base.TruncationStrategy`]):
|
| 431 |
+
The kind of truncation that will be applied to the input
|
| 432 |
+
max_length (`int`):
|
| 433 |
+
The maximum size of a sequence.
|
| 434 |
+
stride (`int`):
|
| 435 |
+
The stride to use when handling overflow.
|
| 436 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 437 |
+
If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
|
| 438 |
+
the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
|
| 439 |
+
padding_side (`str`, *optional*):
|
| 440 |
+
The side on which the model should have padding applied. Should be selected between ['right', 'left'].
|
| 441 |
+
Default value is picked from the class attribute of the same name.
|
| 442 |
+
"""
|
| 443 |
+
_truncation = self._tokenizer.truncation
|
| 444 |
+
_padding = self._tokenizer.padding
|
| 445 |
+
# Set truncation and padding on the backend tokenizer
|
| 446 |
+
if truncation_strategy == TruncationStrategy.DO_NOT_TRUNCATE:
|
| 447 |
+
if _truncation is not None:
|
| 448 |
+
self._tokenizer.no_truncation()
|
| 449 |
+
else:
|
| 450 |
+
target = {
|
| 451 |
+
"max_length": max_length,
|
| 452 |
+
"stride": stride,
|
| 453 |
+
"strategy": truncation_strategy.value,
|
| 454 |
+
"direction": self.truncation_side,
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
# _truncation might contain more keys that the target `transformers`
|
| 458 |
+
# supports. Use only the target keys to trigger `enable_truncation`.
|
| 459 |
+
# This should enable this code to works on various `tokenizers`
|
| 460 |
+
# targets.
|
| 461 |
+
if _truncation is None:
|
| 462 |
+
current = None
|
| 463 |
+
else:
|
| 464 |
+
current = {k: _truncation.get(k, None) for k in target}
|
| 465 |
+
|
| 466 |
+
if current != target:
|
| 467 |
+
self._tokenizer.enable_truncation(**target)
|
| 468 |
+
|
| 469 |
+
if padding_strategy == PaddingStrategy.DO_NOT_PAD:
|
| 470 |
+
if _padding is not None:
|
| 471 |
+
self._tokenizer.no_padding()
|
| 472 |
+
else:
|
| 473 |
+
length = max_length if padding_strategy == PaddingStrategy.MAX_LENGTH else None
|
| 474 |
+
target = {
|
| 475 |
+
"length": length,
|
| 476 |
+
"direction": padding_side if padding_side is not None else self.padding_side,
|
| 477 |
+
"pad_id": self.pad_token_id,
|
| 478 |
+
"pad_token": self.pad_token,
|
| 479 |
+
"pad_type_id": self.pad_token_type_id,
|
| 480 |
+
"pad_to_multiple_of": pad_to_multiple_of,
|
| 481 |
+
}
|
| 482 |
+
if _padding != target:
|
| 483 |
+
self._tokenizer.enable_padding(**target)
|
| 484 |
+
|
| 485 |
+
def _batch_encode_plus(
|
| 486 |
+
self,
|
| 487 |
+
batch_text_or_text_pairs: Union[
|
| 488 |
+
List[TextInput], List[TextInputPair], List[PreTokenizedInput], List[PreTokenizedInputPair]
|
| 489 |
+
],
|
| 490 |
+
add_special_tokens: bool = True,
|
| 491 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 492 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 493 |
+
max_length: Optional[int] = None,
|
| 494 |
+
stride: int = 0,
|
| 495 |
+
is_split_into_words: bool = False,
|
| 496 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 497 |
+
padding_side: Optional[bool] = None,
|
| 498 |
+
return_tensors: Optional[str] = None,
|
| 499 |
+
return_token_type_ids: Optional[bool] = None,
|
| 500 |
+
return_attention_mask: Optional[bool] = None,
|
| 501 |
+
return_overflowing_tokens: bool = False,
|
| 502 |
+
return_special_tokens_mask: bool = False,
|
| 503 |
+
return_offsets_mapping: bool = False,
|
| 504 |
+
return_length: bool = False,
|
| 505 |
+
verbose: bool = True,
|
| 506 |
+
split_special_tokens: bool = False,
|
| 507 |
+
) -> BatchEncoding:
|
| 508 |
+
if not isinstance(batch_text_or_text_pairs, (tuple, list)):
|
| 509 |
+
raise TypeError(
|
| 510 |
+
f"batch_text_or_text_pairs has to be a list or a tuple (got {type(batch_text_or_text_pairs)})"
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
# Set the truncation and padding strategy and restore the initial configuration
|
| 514 |
+
self.set_truncation_and_padding(
|
| 515 |
+
padding_strategy=padding_strategy,
|
| 516 |
+
truncation_strategy=truncation_strategy,
|
| 517 |
+
max_length=max_length,
|
| 518 |
+
stride=stride,
|
| 519 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 520 |
+
padding_side=padding_side,
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
if self._tokenizer.encode_special_tokens != split_special_tokens:
|
| 524 |
+
self._tokenizer.encode_special_tokens = split_special_tokens
|
| 525 |
+
|
| 526 |
+
encodings = self._tokenizer.encode_batch(
|
| 527 |
+
batch_text_or_text_pairs,
|
| 528 |
+
add_special_tokens=add_special_tokens,
|
| 529 |
+
is_pretokenized=is_split_into_words,
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
# Convert encoding to dict
|
| 533 |
+
# `Tokens` has type: Tuple[
|
| 534 |
+
# List[Dict[str, List[List[int]]]] or List[Dict[str, 2D-Tensor]],
|
| 535 |
+
# List[EncodingFast]
|
| 536 |
+
# ]
|
| 537 |
+
# with nested dimensions corresponding to batch, overflows, sequence length
|
| 538 |
+
tokens_and_encodings = [
|
| 539 |
+
self._convert_encoding(
|
| 540 |
+
encoding=encoding,
|
| 541 |
+
return_token_type_ids=return_token_type_ids,
|
| 542 |
+
return_attention_mask=return_attention_mask,
|
| 543 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 544 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 545 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 546 |
+
return_length=return_length,
|
| 547 |
+
verbose=verbose,
|
| 548 |
+
)
|
| 549 |
+
for encoding in encodings
|
| 550 |
+
]
|
| 551 |
+
|
| 552 |
+
# Convert the output to have dict[list] from list[dict] and remove the additional overflows dimension
|
| 553 |
+
# From (variable) shape (batch, overflows, sequence length) to ~ (batch * overflows, sequence length)
|
| 554 |
+
# (we say ~ because the number of overflow varies with the example in the batch)
|
| 555 |
+
#
|
| 556 |
+
# To match each overflowing sample with the original sample in the batch
|
| 557 |
+
# we add an overflow_to_sample_mapping array (see below)
|
| 558 |
+
sanitized_tokens = {}
|
| 559 |
+
for key in tokens_and_encodings[0][0].keys():
|
| 560 |
+
stack = [e for item, _ in tokens_and_encodings for e in item[key]]
|
| 561 |
+
sanitized_tokens[key] = stack
|
| 562 |
+
sanitized_encodings = [e for _, item in tokens_and_encodings for e in item]
|
| 563 |
+
|
| 564 |
+
# If returning overflowing tokens, we need to return a mapping
|
| 565 |
+
# from the batch idx to the original sample
|
| 566 |
+
if return_overflowing_tokens:
|
| 567 |
+
overflow_to_sample_mapping = []
|
| 568 |
+
for i, (toks, _) in enumerate(tokens_and_encodings):
|
| 569 |
+
overflow_to_sample_mapping += [i] * len(toks["input_ids"])
|
| 570 |
+
sanitized_tokens["overflow_to_sample_mapping"] = overflow_to_sample_mapping
|
| 571 |
+
|
| 572 |
+
for input_ids in sanitized_tokens["input_ids"]:
|
| 573 |
+
self._eventual_warn_about_too_long_sequence(input_ids, max_length, verbose)
|
| 574 |
+
return BatchEncoding(sanitized_tokens, sanitized_encodings, tensor_type=return_tensors)
|
| 575 |
+
|
| 576 |
+
def _encode_plus(
|
| 577 |
+
self,
|
| 578 |
+
text: Union[TextInput, PreTokenizedInput],
|
| 579 |
+
text_pair: Optional[Union[TextInput, PreTokenizedInput]] = None,
|
| 580 |
+
add_special_tokens: bool = True,
|
| 581 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 582 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 583 |
+
max_length: Optional[int] = None,
|
| 584 |
+
stride: int = 0,
|
| 585 |
+
is_split_into_words: bool = False,
|
| 586 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 587 |
+
padding_side: Optional[bool] = None,
|
| 588 |
+
return_tensors: Optional[bool] = None,
|
| 589 |
+
return_token_type_ids: Optional[bool] = None,
|
| 590 |
+
return_attention_mask: Optional[bool] = None,
|
| 591 |
+
return_overflowing_tokens: bool = False,
|
| 592 |
+
return_special_tokens_mask: bool = False,
|
| 593 |
+
return_offsets_mapping: bool = False,
|
| 594 |
+
return_length: bool = False,
|
| 595 |
+
verbose: bool = True,
|
| 596 |
+
split_special_tokens: bool = False,
|
| 597 |
+
**kwargs,
|
| 598 |
+
) -> BatchEncoding:
|
| 599 |
+
batched_input = [(text, text_pair)] if text_pair else [text]
|
| 600 |
+
batched_output = self._batch_encode_plus(
|
| 601 |
+
batched_input,
|
| 602 |
+
is_split_into_words=is_split_into_words,
|
| 603 |
+
add_special_tokens=add_special_tokens,
|
| 604 |
+
padding_strategy=padding_strategy,
|
| 605 |
+
truncation_strategy=truncation_strategy,
|
| 606 |
+
max_length=max_length,
|
| 607 |
+
stride=stride,
|
| 608 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 609 |
+
padding_side=padding_side,
|
| 610 |
+
return_tensors=return_tensors,
|
| 611 |
+
return_token_type_ids=return_token_type_ids,
|
| 612 |
+
return_attention_mask=return_attention_mask,
|
| 613 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 614 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 615 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 616 |
+
return_length=return_length,
|
| 617 |
+
verbose=verbose,
|
| 618 |
+
split_special_tokens=split_special_tokens,
|
| 619 |
+
**kwargs,
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
# Return tensor is None, then we can remove the leading batch axis
|
| 623 |
+
# Overflowing tokens are returned as a batch of output so we keep them in this case
|
| 624 |
+
if return_tensors is None and not return_overflowing_tokens:
|
| 625 |
+
batched_output = BatchEncoding(
|
| 626 |
+
{
|
| 627 |
+
key: (value[0] if len(value) > 0 and isinstance(value[0], list) else value)
|
| 628 |
+
for key, value in batched_output.items()
|
| 629 |
+
},
|
| 630 |
+
batched_output.encodings,
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
self._eventual_warn_about_too_long_sequence(batched_output["input_ids"], max_length, verbose)
|
| 634 |
+
|
| 635 |
+
return batched_output
|
| 636 |
+
|
| 637 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
| 638 |
+
return (
|
| 639 |
+
self.backend_tokenizer.decoder.decode(tokens)
|
| 640 |
+
if self.backend_tokenizer.decoder is not None
|
| 641 |
+
else " ".join(tokens)
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
def _decode(
|
| 645 |
+
self,
|
| 646 |
+
token_ids: Union[int, List[int]],
|
| 647 |
+
skip_special_tokens: bool = False,
|
| 648 |
+
clean_up_tokenization_spaces: bool = None,
|
| 649 |
+
**kwargs,
|
| 650 |
+
) -> str:
|
| 651 |
+
self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False)
|
| 652 |
+
|
| 653 |
+
if isinstance(token_ids, int):
|
| 654 |
+
token_ids = [token_ids]
|
| 655 |
+
text = self._tokenizer.decode(token_ids, skip_special_tokens=skip_special_tokens)
|
| 656 |
+
|
| 657 |
+
clean_up_tokenization_spaces = (
|
| 658 |
+
clean_up_tokenization_spaces
|
| 659 |
+
if clean_up_tokenization_spaces is not None
|
| 660 |
+
else self.clean_up_tokenization_spaces
|
| 661 |
+
)
|
| 662 |
+
if clean_up_tokenization_spaces:
|
| 663 |
+
clean_text = self.clean_up_tokenization(text)
|
| 664 |
+
return clean_text
|
| 665 |
+
else:
|
| 666 |
+
return text
|
| 667 |
+
|
| 668 |
+
def _save_pretrained(
|
| 669 |
+
self,
|
| 670 |
+
save_directory: Union[str, os.PathLike],
|
| 671 |
+
file_names: Tuple[str],
|
| 672 |
+
legacy_format: Optional[bool] = None,
|
| 673 |
+
filename_prefix: Optional[str] = None,
|
| 674 |
+
) -> Tuple[str]:
|
| 675 |
+
"""
|
| 676 |
+
Save a tokenizer using the slow-tokenizer/legacy format: vocabulary + added tokens as well as in a unique JSON
|
| 677 |
+
file containing {config + vocab + added-tokens}.
|
| 678 |
+
"""
|
| 679 |
+
save_directory = str(save_directory)
|
| 680 |
+
|
| 681 |
+
if self.slow_tokenizer_class is None and legacy_format is True:
|
| 682 |
+
raise ValueError(
|
| 683 |
+
"Your tokenizer does not have a legacy version defined and therefore cannot register this version. You"
|
| 684 |
+
" might consider leaving the legacy_format at `None` or setting it to `False`."
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
save_slow = (
|
| 688 |
+
(legacy_format is None or legacy_format is True)
|
| 689 |
+
and self.slow_tokenizer_class is not None
|
| 690 |
+
and self.can_save_slow_tokenizer
|
| 691 |
+
)
|
| 692 |
+
save_fast = legacy_format is None or legacy_format is False
|
| 693 |
+
|
| 694 |
+
if save_slow:
|
| 695 |
+
added_tokens_file = os.path.join(
|
| 696 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + ADDED_TOKENS_FILE
|
| 697 |
+
)
|
| 698 |
+
# make sure to be foward compatible
|
| 699 |
+
added_vocab = {tok: index for tok, index in self.added_tokens_encoder.items() if index >= self.vocab_size}
|
| 700 |
+
if added_vocab:
|
| 701 |
+
with open(added_tokens_file, "w", encoding="utf-8") as f:
|
| 702 |
+
out_str = json.dumps(added_vocab, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
|
| 703 |
+
f.write(out_str)
|
| 704 |
+
|
| 705 |
+
vocab_files = self.save_vocabulary(save_directory, filename_prefix=filename_prefix)
|
| 706 |
+
file_names = file_names + vocab_files + (added_tokens_file,)
|
| 707 |
+
|
| 708 |
+
if save_fast:
|
| 709 |
+
tokenizer_file = os.path.join(
|
| 710 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + TOKENIZER_FILE
|
| 711 |
+
)
|
| 712 |
+
self.backend_tokenizer.save(tokenizer_file)
|
| 713 |
+
file_names = file_names + (tokenizer_file,)
|
| 714 |
+
|
| 715 |
+
return file_names
|
| 716 |
+
|
| 717 |
+
def train_new_from_iterator(
|
| 718 |
+
self,
|
| 719 |
+
text_iterator,
|
| 720 |
+
vocab_size,
|
| 721 |
+
length=None,
|
| 722 |
+
new_special_tokens=None,
|
| 723 |
+
special_tokens_map=None,
|
| 724 |
+
**kwargs,
|
| 725 |
+
):
|
| 726 |
+
"""
|
| 727 |
+
Trains a tokenizer on a new corpus with the same defaults (in terms of special tokens or tokenization pipeline)
|
| 728 |
+
as the current one.
|
| 729 |
+
|
| 730 |
+
Args:
|
| 731 |
+
text_iterator (generator of `List[str]`):
|
| 732 |
+
The training corpus. Should be a generator of batches of texts, for instance a list of lists of texts
|
| 733 |
+
if you have everything in memory.
|
| 734 |
+
vocab_size (`int`):
|
| 735 |
+
The size of the vocabulary you want for your tokenizer.
|
| 736 |
+
length (`int`, *optional*):
|
| 737 |
+
The total number of sequences in the iterator. This is used to provide meaningful progress tracking
|
| 738 |
+
new_special_tokens (list of `str` or `AddedToken`, *optional*):
|
| 739 |
+
A list of new special tokens to add to the tokenizer you are training.
|
| 740 |
+
special_tokens_map (`Dict[str, str]`, *optional*):
|
| 741 |
+
If you want to rename some of the special tokens this tokenizer uses, pass along a mapping old special
|
| 742 |
+
token name to new special token name in this argument.
|
| 743 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 744 |
+
Additional keyword arguments passed along to the trainer from the 🤗 Tokenizers library.
|
| 745 |
+
|
| 746 |
+
Returns:
|
| 747 |
+
[`PreTrainedTokenizerFast`]: A new tokenizer of the same type as the original one, trained on
|
| 748 |
+
`text_iterator`.
|
| 749 |
+
|
| 750 |
+
"""
|
| 751 |
+
tokenizer_json = json.loads(self._tokenizer.to_str())
|
| 752 |
+
# Remove added tokens for now (uses IDs of tokens)
|
| 753 |
+
added_tokens = tokenizer_json.pop("added_tokens")
|
| 754 |
+
# Remove post processor for now (uses IDs of tokens)
|
| 755 |
+
post_processor = tokenizer_json.pop("post_processor")
|
| 756 |
+
|
| 757 |
+
unk_token = None
|
| 758 |
+
# Remove vocab
|
| 759 |
+
if tokenizer_json["model"]["type"] == "BPE":
|
| 760 |
+
tokenizer_json["model"]["vocab"] = {}
|
| 761 |
+
tokenizer_json["model"]["merges"] = []
|
| 762 |
+
elif tokenizer_json["model"]["type"] == "Unigram":
|
| 763 |
+
if tokenizer_json["model"]["unk_id"] is not None:
|
| 764 |
+
unk_id = tokenizer_json["model"]["unk_id"]
|
| 765 |
+
unk_token = tokenizer_json["model"]["vocab"][unk_id][0]
|
| 766 |
+
if special_tokens_map is not None and unk_token in special_tokens_map:
|
| 767 |
+
unk_token = special_tokens_map[unk_token]
|
| 768 |
+
tokenizer_json["model"]["unk_id"] = 0
|
| 769 |
+
tokenizer_json["model"]["vocab"] = [[unk_token, 0.0]]
|
| 770 |
+
elif tokenizer_json["model"]["type"] in ["WordLevel", "WordPiece"]:
|
| 771 |
+
tokenizer_json["model"]["vocab"] = {}
|
| 772 |
+
else:
|
| 773 |
+
raise ValueError(
|
| 774 |
+
f"This method does not support this type of tokenizer (found {tokenizer_json['model']['type']}) "
|
| 775 |
+
"only BPE, Unigram, WordLevel and WordPiece."
|
| 776 |
+
)
|
| 777 |
+
|
| 778 |
+
if (
|
| 779 |
+
special_tokens_map is not None
|
| 780 |
+
and "unk_token" in tokenizer_json["model"]
|
| 781 |
+
and tokenizer_json["model"]["unk_token"] in special_tokens_map
|
| 782 |
+
):
|
| 783 |
+
tokenizer_json["model"]["unk_token"] = special_tokens_map[tokenizer_json["model"]["unk_token"]]
|
| 784 |
+
|
| 785 |
+
tokenizer = TokenizerFast.from_str(json.dumps(tokenizer_json))
|
| 786 |
+
|
| 787 |
+
# Get the special tokens from the current tokenizer if none are specified.
|
| 788 |
+
special_tokens = []
|
| 789 |
+
for added_token in added_tokens:
|
| 790 |
+
special = added_token.pop("special", None)
|
| 791 |
+
_ = added_token.pop("id", None)
|
| 792 |
+
if tokenizer_json["model"]["type"] != "Unigram" and not special:
|
| 793 |
+
continue
|
| 794 |
+
if special_tokens_map is not None and added_token["content"] in special_tokens_map:
|
| 795 |
+
added_token["content"] = special_tokens_map[added_token["content"]]
|
| 796 |
+
special_tokens.append(AddedToken(**added_token))
|
| 797 |
+
|
| 798 |
+
if new_special_tokens is not None:
|
| 799 |
+
special_tokens.extend(new_special_tokens)
|
| 800 |
+
|
| 801 |
+
# Trainer needs to know the end of word / continuing subword thingies in BPE
|
| 802 |
+
if (
|
| 803 |
+
tokenizer_json["model"]["type"] == "BPE"
|
| 804 |
+
and "continuing_subword_prefix" not in kwargs
|
| 805 |
+
and tokenizer_json["model"]["continuing_subword_prefix"] is not None
|
| 806 |
+
):
|
| 807 |
+
kwargs["continuing_subword_prefix"] = tokenizer_json["model"]["continuing_subword_prefix"]
|
| 808 |
+
if (
|
| 809 |
+
tokenizer_json["model"]["type"] == "BPE"
|
| 810 |
+
and "end_of_word_suffix" not in kwargs
|
| 811 |
+
and tokenizer_json["model"]["end_of_word_suffix"] is not None
|
| 812 |
+
):
|
| 813 |
+
kwargs["end_of_word_suffix"] = tokenizer_json["model"]["end_of_word_suffix"]
|
| 814 |
+
if tokenizer_json["model"]["type"] == "Unigram" and unk_token is not None:
|
| 815 |
+
kwargs["unk_token"] = unk_token
|
| 816 |
+
if (
|
| 817 |
+
tokenizer_json["pre_tokenizer"] is not None
|
| 818 |
+
and tokenizer_json["pre_tokenizer"]["type"] == "ByteLevel"
|
| 819 |
+
or tokenizer_json["pre_tokenizer"]["type"] == "Sequence"
|
| 820 |
+
and "pretokenizers" in tokenizer_json["pre_tokenizer"]
|
| 821 |
+
and any(
|
| 822 |
+
pretokenizer["type"] == "ByteLevel"
|
| 823 |
+
for pretokenizer in tokenizer_json["pre_tokenizer"]["pretokenizers"]
|
| 824 |
+
)
|
| 825 |
+
):
|
| 826 |
+
kwargs["initial_alphabet"] = pre_tokenizers_fast.ByteLevel.alphabet()
|
| 827 |
+
|
| 828 |
+
trainer_class = MODEL_TO_TRAINER_MAPPING[tokenizer_json["model"]["type"]]
|
| 829 |
+
trainer = trainer_class(vocab_size=vocab_size, special_tokens=special_tokens, **kwargs)
|
| 830 |
+
tokenizer.train_from_iterator(text_iterator, length=length, trainer=trainer)
|
| 831 |
+
|
| 832 |
+
if post_processor is not None:
|
| 833 |
+
trained_tokenizer_json = json.loads(tokenizer.to_str())
|
| 834 |
+
# Almost done, we just have to adjust the token IDs in the post processor
|
| 835 |
+
if "special_tokens" in post_processor:
|
| 836 |
+
for key in post_processor["special_tokens"]:
|
| 837 |
+
tokens = post_processor["special_tokens"][key]["tokens"]
|
| 838 |
+
if special_tokens_map is not None:
|
| 839 |
+
tokens = [special_tokens_map.get(token, token) for token in tokens]
|
| 840 |
+
post_processor["special_tokens"][key]["tokens"] = tokens
|
| 841 |
+
for token in tokens:
|
| 842 |
+
token_id = tokenizer.token_to_id(token)
|
| 843 |
+
if token_id is None:
|
| 844 |
+
raise ValueError(
|
| 845 |
+
"Attempted to set a token in the post processor that does not exist in the mapping"
|
| 846 |
+
)
|
| 847 |
+
|
| 848 |
+
post_processor["special_tokens"][key]["ids"] = [tokenizer.token_to_id(token) for token in tokens]
|
| 849 |
+
|
| 850 |
+
for special_token in ["cls", "sep"]:
|
| 851 |
+
if special_token in post_processor:
|
| 852 |
+
token, _ = post_processor[special_token]
|
| 853 |
+
if special_tokens_map is not None and token in special_tokens_map:
|
| 854 |
+
token = special_tokens_map[token]
|
| 855 |
+
token_id = tokenizer.token_to_id(token)
|
| 856 |
+
if token_id is None:
|
| 857 |
+
raise ValueError(
|
| 858 |
+
"Attempted to set a token in the post processor that does not exist in the mapping"
|
| 859 |
+
)
|
| 860 |
+
post_processor[special_token] = [token, token_id]
|
| 861 |
+
|
| 862 |
+
trained_tokenizer_json["post_processor"] = post_processor
|
| 863 |
+
tokenizer = TokenizerFast.from_str(json.dumps(trained_tokenizer_json))
|
| 864 |
+
|
| 865 |
+
kwargs = self.init_kwargs.copy()
|
| 866 |
+
# Map pad/cls/mask token at the Transformers level
|
| 867 |
+
special_tokens_list = SpecialTokensMixin.SPECIAL_TOKENS_ATTRIBUTES.copy()
|
| 868 |
+
special_tokens_list.remove("additional_special_tokens")
|
| 869 |
+
for token in special_tokens_list:
|
| 870 |
+
if getattr(self, token) is not None:
|
| 871 |
+
special_token = getattr(self, token)
|
| 872 |
+
if special_tokens_map is not None and special_token in special_tokens_map:
|
| 873 |
+
special_token = special_tokens_map[special_token]
|
| 874 |
+
|
| 875 |
+
special_token_full = self._special_tokens_map.get(token, None)
|
| 876 |
+
if isinstance(special_token_full, AddedToken):
|
| 877 |
+
# Create an added token with the same parameters except the content
|
| 878 |
+
kwargs[token] = AddedToken(
|
| 879 |
+
special_token,
|
| 880 |
+
single_word=special_token_full.single_word,
|
| 881 |
+
lstrip=special_token_full.lstrip,
|
| 882 |
+
rstrip=special_token_full.rstrip,
|
| 883 |
+
normalized=special_token_full.normalized,
|
| 884 |
+
special=True,
|
| 885 |
+
)
|
| 886 |
+
else:
|
| 887 |
+
kwargs[token] = special_token
|
| 888 |
+
|
| 889 |
+
additional_special_tokens = self.additional_special_tokens
|
| 890 |
+
if new_special_tokens is not None:
|
| 891 |
+
additional_special_tokens.extend(new_special_tokens)
|
| 892 |
+
if len(additional_special_tokens) > 0:
|
| 893 |
+
kwargs["additional_special_tokens"] = additional_special_tokens
|
| 894 |
+
|
| 895 |
+
return self.__class__(tokenizer_object=tokenizer, **kwargs)
|