Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/__pycache__/data_collator.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/__init__.py +23 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/glue.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/language_modeling.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/squad.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/glue.py +162 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/language_modeling.py +530 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/squad.py +230 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/metrics/__init__.py +98 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/metrics/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/metrics/__pycache__/squad_metrics.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/metrics/squad_metrics.py +779 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/__init__.py +18 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/__pycache__/glue.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/__pycache__/squad.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/__pycache__/utils.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/__pycache__/xnli.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/glue.py +643 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/squad.py +845 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/utils.py +349 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/xnli.py +96 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/distributed/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/distributed/__pycache__/configuration_utils.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/beam_constraints.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/beam_search.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/candidate_generator.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/configuration_utils.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/flax_logits_process.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/flax_utils.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/stopping_criteria.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/streamers.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/tf_logits_process.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/watermarking.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__init__.py +26 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__pycache__/cache.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__pycache__/cache_manager.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__pycache__/continuous_api.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__pycache__/requests.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__pycache__/scheduler.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/cache.py +606 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/cache_manager.py +226 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/continuous_api.py +1047 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/requests.py +204 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/scheduler.py +300 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/loss/__pycache__/__init__.cpython-310.pyc +0 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.22 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/__pycache__/data_collator.cpython-310.pyc
ADDED
|
Binary file (63.8 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .glue import GlueDataset, GlueDataTrainingArguments
|
| 16 |
+
from .language_modeling import (
|
| 17 |
+
LineByLineTextDataset,
|
| 18 |
+
LineByLineWithRefDataset,
|
| 19 |
+
LineByLineWithSOPTextDataset,
|
| 20 |
+
TextDataset,
|
| 21 |
+
TextDatasetForNextSentencePrediction,
|
| 22 |
+
)
|
| 23 |
+
from .squad import SquadDataset, SquadDataTrainingArguments
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (561 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/glue.cpython-310.pyc
ADDED
|
Binary file (4.93 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/language_modeling.cpython-310.pyc
ADDED
|
Binary file (13 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/squad.cpython-310.pyc
ADDED
|
Binary file (6.4 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/glue.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import time
|
| 17 |
+
import warnings
|
| 18 |
+
from dataclasses import dataclass, field
|
| 19 |
+
from enum import Enum
|
| 20 |
+
from typing import Optional, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from filelock import FileLock
|
| 24 |
+
from torch.utils.data import Dataset
|
| 25 |
+
|
| 26 |
+
from ...tokenization_utils_base import PreTrainedTokenizerBase
|
| 27 |
+
from ...utils import check_torch_load_is_safe, logging
|
| 28 |
+
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
|
| 29 |
+
from ..processors.utils import InputFeatures
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class GlueDataTrainingArguments:
|
| 37 |
+
"""
|
| 38 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
| 39 |
+
|
| 40 |
+
Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify them on the command
|
| 41 |
+
line.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
task_name: str = field(metadata={"help": "The name of the task to train on: " + ", ".join(glue_processors.keys())})
|
| 45 |
+
data_dir: str = field(
|
| 46 |
+
metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."}
|
| 47 |
+
)
|
| 48 |
+
max_seq_length: int = field(
|
| 49 |
+
default=128,
|
| 50 |
+
metadata={
|
| 51 |
+
"help": (
|
| 52 |
+
"The maximum total input sequence length after tokenization. Sequences longer "
|
| 53 |
+
"than this will be truncated, sequences shorter will be padded."
|
| 54 |
+
)
|
| 55 |
+
},
|
| 56 |
+
)
|
| 57 |
+
overwrite_cache: bool = field(
|
| 58 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
def __post_init__(self):
|
| 62 |
+
self.task_name = self.task_name.lower()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class Split(Enum):
|
| 66 |
+
train = "train"
|
| 67 |
+
dev = "dev"
|
| 68 |
+
test = "test"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class GlueDataset(Dataset):
|
| 72 |
+
"""
|
| 73 |
+
This will be superseded by a framework-agnostic approach soon.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
args: GlueDataTrainingArguments
|
| 77 |
+
output_mode: str
|
| 78 |
+
features: list[InputFeatures]
|
| 79 |
+
|
| 80 |
+
def __init__(
|
| 81 |
+
self,
|
| 82 |
+
args: GlueDataTrainingArguments,
|
| 83 |
+
tokenizer: PreTrainedTokenizerBase,
|
| 84 |
+
limit_length: Optional[int] = None,
|
| 85 |
+
mode: Union[str, Split] = Split.train,
|
| 86 |
+
cache_dir: Optional[str] = None,
|
| 87 |
+
):
|
| 88 |
+
warnings.warn(
|
| 89 |
+
"This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets "
|
| 90 |
+
"library. You can have a look at this example script for pointers: "
|
| 91 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py",
|
| 92 |
+
FutureWarning,
|
| 93 |
+
)
|
| 94 |
+
self.args = args
|
| 95 |
+
self.processor = glue_processors[args.task_name]()
|
| 96 |
+
self.output_mode = glue_output_modes[args.task_name]
|
| 97 |
+
if isinstance(mode, str):
|
| 98 |
+
try:
|
| 99 |
+
mode = Split[mode]
|
| 100 |
+
except KeyError:
|
| 101 |
+
raise KeyError("mode is not a valid split name")
|
| 102 |
+
# Load data features from cache or dataset file
|
| 103 |
+
cached_features_file = os.path.join(
|
| 104 |
+
cache_dir if cache_dir is not None else args.data_dir,
|
| 105 |
+
f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}",
|
| 106 |
+
)
|
| 107 |
+
label_list = self.processor.get_labels()
|
| 108 |
+
if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
|
| 109 |
+
"RobertaTokenizer",
|
| 110 |
+
"RobertaTokenizerFast",
|
| 111 |
+
"XLMRobertaTokenizer",
|
| 112 |
+
"BartTokenizer",
|
| 113 |
+
"BartTokenizerFast",
|
| 114 |
+
):
|
| 115 |
+
# HACK(label indices are swapped in RoBERTa pretrained model)
|
| 116 |
+
label_list[1], label_list[2] = label_list[2], label_list[1]
|
| 117 |
+
self.label_list = label_list
|
| 118 |
+
|
| 119 |
+
# Make sure only the first process in distributed training processes the dataset,
|
| 120 |
+
# and the others will use the cache.
|
| 121 |
+
lock_path = cached_features_file + ".lock"
|
| 122 |
+
with FileLock(lock_path):
|
| 123 |
+
if os.path.exists(cached_features_file) and not args.overwrite_cache:
|
| 124 |
+
start = time.time()
|
| 125 |
+
check_torch_load_is_safe()
|
| 126 |
+
self.features = torch.load(cached_features_file, weights_only=True)
|
| 127 |
+
logger.info(
|
| 128 |
+
f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start
|
| 129 |
+
)
|
| 130 |
+
else:
|
| 131 |
+
logger.info(f"Creating features from dataset file at {args.data_dir}")
|
| 132 |
+
|
| 133 |
+
if mode == Split.dev:
|
| 134 |
+
examples = self.processor.get_dev_examples(args.data_dir)
|
| 135 |
+
elif mode == Split.test:
|
| 136 |
+
examples = self.processor.get_test_examples(args.data_dir)
|
| 137 |
+
else:
|
| 138 |
+
examples = self.processor.get_train_examples(args.data_dir)
|
| 139 |
+
if limit_length is not None:
|
| 140 |
+
examples = examples[:limit_length]
|
| 141 |
+
self.features = glue_convert_examples_to_features(
|
| 142 |
+
examples,
|
| 143 |
+
tokenizer,
|
| 144 |
+
max_length=args.max_seq_length,
|
| 145 |
+
label_list=label_list,
|
| 146 |
+
output_mode=self.output_mode,
|
| 147 |
+
)
|
| 148 |
+
start = time.time()
|
| 149 |
+
torch.save(self.features, cached_features_file)
|
| 150 |
+
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
|
| 151 |
+
logger.info(
|
| 152 |
+
f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
def __len__(self):
|
| 156 |
+
return len(self.features)
|
| 157 |
+
|
| 158 |
+
def __getitem__(self, i) -> InputFeatures:
|
| 159 |
+
return self.features[i]
|
| 160 |
+
|
| 161 |
+
def get_labels(self):
|
| 162 |
+
return self.label_list
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/language_modeling.py
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import pickle
|
| 18 |
+
import random
|
| 19 |
+
import time
|
| 20 |
+
import warnings
|
| 21 |
+
from typing import Optional
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from filelock import FileLock
|
| 25 |
+
from torch.utils.data import Dataset
|
| 26 |
+
|
| 27 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 28 |
+
from ...utils import logging
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
DEPRECATION_WARNING = (
|
| 35 |
+
"This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets "
|
| 36 |
+
"library. You can have a look at this example script for pointers: {0}"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TextDataset(Dataset):
|
| 41 |
+
"""
|
| 42 |
+
This will be superseded by a framework-agnostic approach soon.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
tokenizer: PreTrainedTokenizer,
|
| 48 |
+
file_path: str,
|
| 49 |
+
block_size: int,
|
| 50 |
+
overwrite_cache=False,
|
| 51 |
+
cache_dir: Optional[str] = None,
|
| 52 |
+
):
|
| 53 |
+
warnings.warn(
|
| 54 |
+
DEPRECATION_WARNING.format(
|
| 55 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm.py"
|
| 56 |
+
),
|
| 57 |
+
FutureWarning,
|
| 58 |
+
)
|
| 59 |
+
if os.path.isfile(file_path) is False:
|
| 60 |
+
raise ValueError(f"Input file path {file_path} not found")
|
| 61 |
+
|
| 62 |
+
block_size = block_size - tokenizer.num_special_tokens_to_add(pair=False)
|
| 63 |
+
|
| 64 |
+
directory, filename = os.path.split(file_path)
|
| 65 |
+
cached_features_file = os.path.join(
|
| 66 |
+
cache_dir if cache_dir is not None else directory,
|
| 67 |
+
f"cached_lm_{tokenizer.__class__.__name__}_{block_size}_{filename}",
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
# Make sure only the first process in distributed training processes the dataset,
|
| 71 |
+
# and the others will use the cache.
|
| 72 |
+
lock_path = cached_features_file + ".lock"
|
| 73 |
+
with FileLock(lock_path):
|
| 74 |
+
if os.path.exists(cached_features_file) and not overwrite_cache:
|
| 75 |
+
start = time.time()
|
| 76 |
+
with open(cached_features_file, "rb") as handle:
|
| 77 |
+
self.examples = pickle.load(handle)
|
| 78 |
+
logger.info(
|
| 79 |
+
f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
else:
|
| 83 |
+
logger.info(f"Creating features from dataset file at {directory}")
|
| 84 |
+
|
| 85 |
+
self.examples = []
|
| 86 |
+
with open(file_path, encoding="utf-8") as f:
|
| 87 |
+
text = f.read()
|
| 88 |
+
|
| 89 |
+
tokenized_text = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(text))
|
| 90 |
+
|
| 91 |
+
for i in range(0, len(tokenized_text) - block_size + 1, block_size): # Truncate in block of block_size
|
| 92 |
+
self.examples.append(
|
| 93 |
+
tokenizer.build_inputs_with_special_tokens(tokenized_text[i : i + block_size])
|
| 94 |
+
)
|
| 95 |
+
# Note that we are losing the last truncated example here for the sake of simplicity (no padding)
|
| 96 |
+
# If your dataset is small, first you should look for a bigger one :-) and second you
|
| 97 |
+
# can change this behavior by adding (model specific) padding.
|
| 98 |
+
|
| 99 |
+
start = time.time()
|
| 100 |
+
with open(cached_features_file, "wb") as handle:
|
| 101 |
+
pickle.dump(self.examples, handle, protocol=pickle.HIGHEST_PROTOCOL)
|
| 102 |
+
logger.info(
|
| 103 |
+
f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
def __len__(self):
|
| 107 |
+
return len(self.examples)
|
| 108 |
+
|
| 109 |
+
def __getitem__(self, i) -> torch.Tensor:
|
| 110 |
+
return torch.tensor(self.examples[i], dtype=torch.long)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class LineByLineTextDataset(Dataset):
|
| 114 |
+
"""
|
| 115 |
+
This will be superseded by a framework-agnostic approach soon.
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
def __init__(self, tokenizer: PreTrainedTokenizer, file_path: str, block_size: int):
|
| 119 |
+
warnings.warn(
|
| 120 |
+
DEPRECATION_WARNING.format(
|
| 121 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm.py"
|
| 122 |
+
),
|
| 123 |
+
FutureWarning,
|
| 124 |
+
)
|
| 125 |
+
if os.path.isfile(file_path) is False:
|
| 126 |
+
raise ValueError(f"Input file path {file_path} not found")
|
| 127 |
+
# Here, we do not cache the features, operating under the assumption
|
| 128 |
+
# that we will soon use fast multithreaded tokenizers from the
|
| 129 |
+
# `tokenizers` repo everywhere =)
|
| 130 |
+
logger.info(f"Creating features from dataset file at {file_path}")
|
| 131 |
+
|
| 132 |
+
with open(file_path, encoding="utf-8") as f:
|
| 133 |
+
lines = [line for line in f.read().splitlines() if (len(line) > 0 and not line.isspace())]
|
| 134 |
+
|
| 135 |
+
batch_encoding = tokenizer(lines, add_special_tokens=True, truncation=True, max_length=block_size)
|
| 136 |
+
self.examples = batch_encoding["input_ids"]
|
| 137 |
+
self.examples = [{"input_ids": torch.tensor(e, dtype=torch.long)} for e in self.examples]
|
| 138 |
+
|
| 139 |
+
def __len__(self):
|
| 140 |
+
return len(self.examples)
|
| 141 |
+
|
| 142 |
+
def __getitem__(self, i) -> dict[str, torch.tensor]:
|
| 143 |
+
return self.examples[i]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class LineByLineWithRefDataset(Dataset):
|
| 147 |
+
"""
|
| 148 |
+
This will be superseded by a framework-agnostic approach soon.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
def __init__(self, tokenizer: PreTrainedTokenizer, file_path: str, block_size: int, ref_path: str):
|
| 152 |
+
warnings.warn(
|
| 153 |
+
DEPRECATION_WARNING.format(
|
| 154 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm_wwm.py"
|
| 155 |
+
),
|
| 156 |
+
FutureWarning,
|
| 157 |
+
)
|
| 158 |
+
if os.path.isfile(file_path) is False:
|
| 159 |
+
raise ValueError(f"Input file path {file_path} not found")
|
| 160 |
+
if os.path.isfile(ref_path) is False:
|
| 161 |
+
raise ValueError(f"Ref file path {file_path} not found")
|
| 162 |
+
# Here, we do not cache the features, operating under the assumption
|
| 163 |
+
# that we will soon use fast multithreaded tokenizers from the
|
| 164 |
+
# `tokenizers` repo everywhere =)
|
| 165 |
+
logger.info(f"Creating features from dataset file at {file_path}")
|
| 166 |
+
logger.info(f"Use ref segment results at {ref_path}")
|
| 167 |
+
with open(file_path, encoding="utf-8") as f:
|
| 168 |
+
data = f.readlines() # use this method to avoid delimiter '\u2029' to split a line
|
| 169 |
+
data = [line.strip() for line in data if len(line) > 0 and not line.isspace()]
|
| 170 |
+
# Get ref inf from file
|
| 171 |
+
with open(ref_path, encoding="utf-8") as f:
|
| 172 |
+
ref = [json.loads(line) for line in f.read().splitlines() if (len(line) > 0 and not line.isspace())]
|
| 173 |
+
if len(data) != len(ref):
|
| 174 |
+
raise ValueError(
|
| 175 |
+
f"Length of Input file should be equal to Ref file. But the length of {file_path} is {len(data)} "
|
| 176 |
+
f"while length of {ref_path} is {len(ref)}"
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
batch_encoding = tokenizer(data, add_special_tokens=True, truncation=True, max_length=block_size)
|
| 180 |
+
self.examples = batch_encoding["input_ids"]
|
| 181 |
+
self.examples = [{"input_ids": torch.tensor(e, dtype=torch.long)} for e in self.examples]
|
| 182 |
+
|
| 183 |
+
n = len(self.examples)
|
| 184 |
+
for i in range(n):
|
| 185 |
+
self.examples[i]["chinese_ref"] = torch.tensor(ref[i], dtype=torch.long)
|
| 186 |
+
|
| 187 |
+
def __len__(self):
|
| 188 |
+
return len(self.examples)
|
| 189 |
+
|
| 190 |
+
def __getitem__(self, i) -> dict[str, torch.tensor]:
|
| 191 |
+
return self.examples[i]
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class LineByLineWithSOPTextDataset(Dataset):
|
| 195 |
+
"""
|
| 196 |
+
Dataset for sentence order prediction task, prepare sentence pairs for SOP task
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
def __init__(self, tokenizer: PreTrainedTokenizer, file_dir: str, block_size: int):
|
| 200 |
+
warnings.warn(
|
| 201 |
+
DEPRECATION_WARNING.format(
|
| 202 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm.py"
|
| 203 |
+
),
|
| 204 |
+
FutureWarning,
|
| 205 |
+
)
|
| 206 |
+
if os.path.isdir(file_dir) is False:
|
| 207 |
+
raise ValueError(f"{file_dir} is not a directory")
|
| 208 |
+
logger.info(f"Creating features from dataset file folder at {file_dir}")
|
| 209 |
+
self.examples = []
|
| 210 |
+
# TODO: randomness could apply a random seed, ex. rng = random.Random(random_seed)
|
| 211 |
+
# file path looks like ./dataset/wiki_1, ./dataset/wiki_2
|
| 212 |
+
for file_name in os.listdir(file_dir):
|
| 213 |
+
file_path = os.path.join(file_dir, file_name)
|
| 214 |
+
if os.path.isfile(file_path) is False:
|
| 215 |
+
raise ValueError(f"{file_path} is not a file")
|
| 216 |
+
article_open = False
|
| 217 |
+
with open(file_path, encoding="utf-8") as f:
|
| 218 |
+
original_lines = f.readlines()
|
| 219 |
+
article_lines = []
|
| 220 |
+
for line in original_lines:
|
| 221 |
+
if "<doc id=" in line:
|
| 222 |
+
article_open = True
|
| 223 |
+
elif "</doc>" in line:
|
| 224 |
+
article_open = False
|
| 225 |
+
document = [
|
| 226 |
+
tokenizer.convert_tokens_to_ids(tokenizer.tokenize(line))
|
| 227 |
+
for line in article_lines[1:]
|
| 228 |
+
if (len(line) > 0 and not line.isspace())
|
| 229 |
+
]
|
| 230 |
+
|
| 231 |
+
examples = self.create_examples_from_document(document, block_size, tokenizer)
|
| 232 |
+
self.examples.extend(examples)
|
| 233 |
+
article_lines = []
|
| 234 |
+
else:
|
| 235 |
+
if article_open:
|
| 236 |
+
article_lines.append(line)
|
| 237 |
+
|
| 238 |
+
logger.info("Dataset parse finished.")
|
| 239 |
+
|
| 240 |
+
def create_examples_from_document(self, document, block_size, tokenizer, short_seq_prob=0.1):
|
| 241 |
+
"""Creates examples for a single document."""
|
| 242 |
+
|
| 243 |
+
# Account for special tokens
|
| 244 |
+
max_num_tokens = block_size - tokenizer.num_special_tokens_to_add(pair=True)
|
| 245 |
+
|
| 246 |
+
# We *usually* want to fill up the entire sequence since we are padding
|
| 247 |
+
# to `block_size` anyways, so short sequences are generally wasted
|
| 248 |
+
# computation. However, we *sometimes*
|
| 249 |
+
# (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter
|
| 250 |
+
# sequences to minimize the mismatch between pretraining and fine-tuning.
|
| 251 |
+
# The `target_seq_length` is just a rough target however, whereas
|
| 252 |
+
# `block_size` is a hard limit.
|
| 253 |
+
target_seq_length = max_num_tokens
|
| 254 |
+
if random.random() < short_seq_prob:
|
| 255 |
+
target_seq_length = random.randint(2, max_num_tokens)
|
| 256 |
+
|
| 257 |
+
# We DON'T just concatenate all of the tokens from a document into a long
|
| 258 |
+
# sequence and choose an arbitrary split point because this would make the
|
| 259 |
+
# next sentence prediction task too easy. Instead, we split the input into
|
| 260 |
+
# segments "A" and "B" based on the actual "sentences" provided by the user
|
| 261 |
+
# input.
|
| 262 |
+
examples = []
|
| 263 |
+
current_chunk = [] # a buffer stored current working segments
|
| 264 |
+
current_length = 0
|
| 265 |
+
i = 0
|
| 266 |
+
while i < len(document):
|
| 267 |
+
segment = document[i] # get a segment
|
| 268 |
+
if not segment:
|
| 269 |
+
i += 1
|
| 270 |
+
continue
|
| 271 |
+
current_chunk.append(segment) # add a segment to current chunk
|
| 272 |
+
current_length += len(segment) # overall token length
|
| 273 |
+
# if current length goes to the target length or reaches the end of file, start building token a and b
|
| 274 |
+
if i == len(document) - 1 or current_length >= target_seq_length:
|
| 275 |
+
if current_chunk:
|
| 276 |
+
# `a_end` is how many segments from `current_chunk` go into the `A` (first) sentence.
|
| 277 |
+
a_end = 1
|
| 278 |
+
# if current chunk has more than 2 sentences, pick part of it `A` (first) sentence
|
| 279 |
+
if len(current_chunk) >= 2:
|
| 280 |
+
a_end = random.randint(1, len(current_chunk) - 1)
|
| 281 |
+
# token a
|
| 282 |
+
tokens_a = []
|
| 283 |
+
for j in range(a_end):
|
| 284 |
+
tokens_a.extend(current_chunk[j])
|
| 285 |
+
|
| 286 |
+
# token b
|
| 287 |
+
tokens_b = []
|
| 288 |
+
for j in range(a_end, len(current_chunk)):
|
| 289 |
+
tokens_b.extend(current_chunk[j])
|
| 290 |
+
|
| 291 |
+
if len(tokens_a) == 0 or len(tokens_b) == 0:
|
| 292 |
+
continue
|
| 293 |
+
|
| 294 |
+
# switch tokens_a and tokens_b randomly
|
| 295 |
+
if random.random() < 0.5:
|
| 296 |
+
is_next = False
|
| 297 |
+
tokens_a, tokens_b = tokens_b, tokens_a
|
| 298 |
+
else:
|
| 299 |
+
is_next = True
|
| 300 |
+
|
| 301 |
+
def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens):
|
| 302 |
+
"""Truncates a pair of sequences to a maximum sequence length."""
|
| 303 |
+
while True:
|
| 304 |
+
total_length = len(tokens_a) + len(tokens_b)
|
| 305 |
+
if total_length <= max_num_tokens:
|
| 306 |
+
break
|
| 307 |
+
trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b
|
| 308 |
+
if not (len(trunc_tokens) >= 1):
|
| 309 |
+
raise ValueError("Sequence length to be truncated must be no less than one")
|
| 310 |
+
# We want to sometimes truncate from the front and sometimes from the
|
| 311 |
+
# back to add more randomness and avoid biases.
|
| 312 |
+
if random.random() < 0.5:
|
| 313 |
+
del trunc_tokens[0]
|
| 314 |
+
else:
|
| 315 |
+
trunc_tokens.pop()
|
| 316 |
+
|
| 317 |
+
truncate_seq_pair(tokens_a, tokens_b, max_num_tokens)
|
| 318 |
+
if not (len(tokens_a) >= 1):
|
| 319 |
+
raise ValueError(f"Length of sequence a is {len(tokens_a)} which must be no less than 1")
|
| 320 |
+
if not (len(tokens_b) >= 1):
|
| 321 |
+
raise ValueError(f"Length of sequence b is {len(tokens_b)} which must be no less than 1")
|
| 322 |
+
|
| 323 |
+
# add special tokens
|
| 324 |
+
input_ids = tokenizer.build_inputs_with_special_tokens(tokens_a, tokens_b)
|
| 325 |
+
# add token type ids, 0 for sentence a, 1 for sentence b
|
| 326 |
+
token_type_ids = tokenizer.create_token_type_ids_from_sequences(tokens_a, tokens_b)
|
| 327 |
+
|
| 328 |
+
example = {
|
| 329 |
+
"input_ids": torch.tensor(input_ids, dtype=torch.long),
|
| 330 |
+
"token_type_ids": torch.tensor(token_type_ids, dtype=torch.long),
|
| 331 |
+
"sentence_order_label": torch.tensor(0 if is_next else 1, dtype=torch.long),
|
| 332 |
+
}
|
| 333 |
+
examples.append(example)
|
| 334 |
+
current_chunk = [] # clear current chunk
|
| 335 |
+
current_length = 0 # reset current text length
|
| 336 |
+
i += 1 # go to next line
|
| 337 |
+
return examples
|
| 338 |
+
|
| 339 |
+
def __len__(self):
|
| 340 |
+
return len(self.examples)
|
| 341 |
+
|
| 342 |
+
def __getitem__(self, i) -> dict[str, torch.tensor]:
|
| 343 |
+
return self.examples[i]
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class TextDatasetForNextSentencePrediction(Dataset):
|
| 347 |
+
"""
|
| 348 |
+
This will be superseded by a framework-agnostic approach soon.
|
| 349 |
+
"""
|
| 350 |
+
|
| 351 |
+
def __init__(
|
| 352 |
+
self,
|
| 353 |
+
tokenizer: PreTrainedTokenizer,
|
| 354 |
+
file_path: str,
|
| 355 |
+
block_size: int,
|
| 356 |
+
overwrite_cache=False,
|
| 357 |
+
short_seq_probability=0.1,
|
| 358 |
+
nsp_probability=0.5,
|
| 359 |
+
):
|
| 360 |
+
warnings.warn(
|
| 361 |
+
DEPRECATION_WARNING.format(
|
| 362 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm.py"
|
| 363 |
+
),
|
| 364 |
+
FutureWarning,
|
| 365 |
+
)
|
| 366 |
+
if not os.path.isfile(file_path):
|
| 367 |
+
raise ValueError(f"Input file path {file_path} not found")
|
| 368 |
+
|
| 369 |
+
self.short_seq_probability = short_seq_probability
|
| 370 |
+
self.nsp_probability = nsp_probability
|
| 371 |
+
|
| 372 |
+
directory, filename = os.path.split(file_path)
|
| 373 |
+
cached_features_file = os.path.join(
|
| 374 |
+
directory,
|
| 375 |
+
f"cached_nsp_{tokenizer.__class__.__name__}_{block_size}_{filename}",
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
self.tokenizer = tokenizer
|
| 379 |
+
|
| 380 |
+
# Make sure only the first process in distributed training processes the dataset,
|
| 381 |
+
# and the others will use the cache.
|
| 382 |
+
lock_path = cached_features_file + ".lock"
|
| 383 |
+
|
| 384 |
+
# Input file format:
|
| 385 |
+
# (1) One sentence per line. These should ideally be actual sentences, not
|
| 386 |
+
# entire paragraphs or arbitrary spans of text. (Because we use the
|
| 387 |
+
# sentence boundaries for the "next sentence prediction" task).
|
| 388 |
+
# (2) Blank lines between documents. Document boundaries are needed so
|
| 389 |
+
# that the "next sentence prediction" task doesn't span between documents.
|
| 390 |
+
#
|
| 391 |
+
# Example:
|
| 392 |
+
# I am very happy.
|
| 393 |
+
# Here is the second sentence.
|
| 394 |
+
#
|
| 395 |
+
# A new document.
|
| 396 |
+
|
| 397 |
+
with FileLock(lock_path):
|
| 398 |
+
if os.path.exists(cached_features_file) and not overwrite_cache:
|
| 399 |
+
start = time.time()
|
| 400 |
+
with open(cached_features_file, "rb") as handle:
|
| 401 |
+
self.examples = pickle.load(handle)
|
| 402 |
+
logger.info(
|
| 403 |
+
f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start
|
| 404 |
+
)
|
| 405 |
+
else:
|
| 406 |
+
logger.info(f"Creating features from dataset file at {directory}")
|
| 407 |
+
|
| 408 |
+
self.documents = [[]]
|
| 409 |
+
with open(file_path, encoding="utf-8") as f:
|
| 410 |
+
while True:
|
| 411 |
+
line = f.readline()
|
| 412 |
+
if not line:
|
| 413 |
+
break
|
| 414 |
+
line = line.strip()
|
| 415 |
+
|
| 416 |
+
# Empty lines are used as document delimiters
|
| 417 |
+
if not line and len(self.documents[-1]) != 0:
|
| 418 |
+
self.documents.append([])
|
| 419 |
+
tokens = tokenizer.tokenize(line)
|
| 420 |
+
tokens = tokenizer.convert_tokens_to_ids(tokens)
|
| 421 |
+
if tokens:
|
| 422 |
+
self.documents[-1].append(tokens)
|
| 423 |
+
|
| 424 |
+
logger.info(f"Creating examples from {len(self.documents)} documents.")
|
| 425 |
+
self.examples = []
|
| 426 |
+
for doc_index, document in enumerate(self.documents):
|
| 427 |
+
self.create_examples_from_document(document, doc_index, block_size)
|
| 428 |
+
|
| 429 |
+
start = time.time()
|
| 430 |
+
with open(cached_features_file, "wb") as handle:
|
| 431 |
+
pickle.dump(self.examples, handle, protocol=pickle.HIGHEST_PROTOCOL)
|
| 432 |
+
logger.info(
|
| 433 |
+
f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
def create_examples_from_document(self, document: list[list[int]], doc_index: int, block_size: int):
|
| 437 |
+
"""Creates examples for a single document."""
|
| 438 |
+
|
| 439 |
+
max_num_tokens = block_size - self.tokenizer.num_special_tokens_to_add(pair=True)
|
| 440 |
+
|
| 441 |
+
# We *usually* want to fill up the entire sequence since we are padding
|
| 442 |
+
# to `block_size` anyways, so short sequences are generally wasted
|
| 443 |
+
# computation. However, we *sometimes*
|
| 444 |
+
# (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter
|
| 445 |
+
# sequences to minimize the mismatch between pretraining and fine-tuning.
|
| 446 |
+
# The `target_seq_length` is just a rough target however, whereas
|
| 447 |
+
# `block_size` is a hard limit.
|
| 448 |
+
target_seq_length = max_num_tokens
|
| 449 |
+
if random.random() < self.short_seq_probability:
|
| 450 |
+
target_seq_length = random.randint(2, max_num_tokens)
|
| 451 |
+
|
| 452 |
+
current_chunk = [] # a buffer stored current working segments
|
| 453 |
+
current_length = 0
|
| 454 |
+
i = 0
|
| 455 |
+
|
| 456 |
+
while i < len(document):
|
| 457 |
+
segment = document[i]
|
| 458 |
+
current_chunk.append(segment)
|
| 459 |
+
current_length += len(segment)
|
| 460 |
+
if i == len(document) - 1 or current_length >= target_seq_length:
|
| 461 |
+
if current_chunk:
|
| 462 |
+
# `a_end` is how many segments from `current_chunk` go into the `A`
|
| 463 |
+
# (first) sentence.
|
| 464 |
+
a_end = 1
|
| 465 |
+
if len(current_chunk) >= 2:
|
| 466 |
+
a_end = random.randint(1, len(current_chunk) - 1)
|
| 467 |
+
|
| 468 |
+
tokens_a = []
|
| 469 |
+
for j in range(a_end):
|
| 470 |
+
tokens_a.extend(current_chunk[j])
|
| 471 |
+
|
| 472 |
+
tokens_b = []
|
| 473 |
+
|
| 474 |
+
if len(current_chunk) == 1 or random.random() < self.nsp_probability:
|
| 475 |
+
is_random_next = True
|
| 476 |
+
target_b_length = target_seq_length - len(tokens_a)
|
| 477 |
+
|
| 478 |
+
# This should rarely go for more than one iteration for large
|
| 479 |
+
# corpora. However, just to be careful, we try to make sure that
|
| 480 |
+
# the random document is not the same as the document
|
| 481 |
+
# we're processing.
|
| 482 |
+
for _ in range(10):
|
| 483 |
+
random_document_index = random.randint(0, len(self.documents) - 1)
|
| 484 |
+
if random_document_index != doc_index:
|
| 485 |
+
break
|
| 486 |
+
|
| 487 |
+
random_document = self.documents[random_document_index]
|
| 488 |
+
random_start = random.randint(0, len(random_document) - 1)
|
| 489 |
+
for j in range(random_start, len(random_document)):
|
| 490 |
+
tokens_b.extend(random_document[j])
|
| 491 |
+
if len(tokens_b) >= target_b_length:
|
| 492 |
+
break
|
| 493 |
+
# We didn't actually use these segments so we "put them back" so
|
| 494 |
+
# they don't go to waste.
|
| 495 |
+
num_unused_segments = len(current_chunk) - a_end
|
| 496 |
+
i -= num_unused_segments
|
| 497 |
+
# Actual next
|
| 498 |
+
else:
|
| 499 |
+
is_random_next = False
|
| 500 |
+
for j in range(a_end, len(current_chunk)):
|
| 501 |
+
tokens_b.extend(current_chunk[j])
|
| 502 |
+
|
| 503 |
+
if not (len(tokens_a) >= 1):
|
| 504 |
+
raise ValueError(f"Length of sequence a is {len(tokens_a)} which must be no less than 1")
|
| 505 |
+
if not (len(tokens_b) >= 1):
|
| 506 |
+
raise ValueError(f"Length of sequence b is {len(tokens_b)} which must be no less than 1")
|
| 507 |
+
|
| 508 |
+
# add special tokens
|
| 509 |
+
input_ids = self.tokenizer.build_inputs_with_special_tokens(tokens_a, tokens_b)
|
| 510 |
+
# add token type ids, 0 for sentence a, 1 for sentence b
|
| 511 |
+
token_type_ids = self.tokenizer.create_token_type_ids_from_sequences(tokens_a, tokens_b)
|
| 512 |
+
|
| 513 |
+
example = {
|
| 514 |
+
"input_ids": torch.tensor(input_ids, dtype=torch.long),
|
| 515 |
+
"token_type_ids": torch.tensor(token_type_ids, dtype=torch.long),
|
| 516 |
+
"next_sentence_label": torch.tensor(1 if is_random_next else 0, dtype=torch.long),
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
self.examples.append(example)
|
| 520 |
+
|
| 521 |
+
current_chunk = []
|
| 522 |
+
current_length = 0
|
| 523 |
+
|
| 524 |
+
i += 1
|
| 525 |
+
|
| 526 |
+
def __len__(self):
|
| 527 |
+
return len(self.examples)
|
| 528 |
+
|
| 529 |
+
def __getitem__(self, i):
|
| 530 |
+
return self.examples[i]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/datasets/squad.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import time
|
| 17 |
+
from dataclasses import dataclass, field
|
| 18 |
+
from enum import Enum
|
| 19 |
+
from typing import Optional, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from filelock import FileLock
|
| 23 |
+
from torch.utils.data import Dataset
|
| 24 |
+
|
| 25 |
+
from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
|
| 26 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 27 |
+
from ...utils import check_torch_load_is_safe, logging
|
| 28 |
+
from ..processors.squad import SquadFeatures, SquadV1Processor, SquadV2Processor, squad_convert_examples_to_features
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
MODEL_CONFIG_CLASSES = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
|
| 34 |
+
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@dataclass
|
| 38 |
+
class SquadDataTrainingArguments:
|
| 39 |
+
"""
|
| 40 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
model_type: str = field(
|
| 44 |
+
default=None, metadata={"help": "Model type selected in the list: " + ", ".join(MODEL_TYPES)}
|
| 45 |
+
)
|
| 46 |
+
data_dir: str = field(
|
| 47 |
+
default=None, metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."}
|
| 48 |
+
)
|
| 49 |
+
max_seq_length: int = field(
|
| 50 |
+
default=128,
|
| 51 |
+
metadata={
|
| 52 |
+
"help": (
|
| 53 |
+
"The maximum total input sequence length after tokenization. Sequences longer "
|
| 54 |
+
"than this will be truncated, sequences shorter will be padded."
|
| 55 |
+
)
|
| 56 |
+
},
|
| 57 |
+
)
|
| 58 |
+
doc_stride: int = field(
|
| 59 |
+
default=128,
|
| 60 |
+
metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."},
|
| 61 |
+
)
|
| 62 |
+
max_query_length: int = field(
|
| 63 |
+
default=64,
|
| 64 |
+
metadata={
|
| 65 |
+
"help": (
|
| 66 |
+
"The maximum number of tokens for the question. Questions longer than this will "
|
| 67 |
+
"be truncated to this length."
|
| 68 |
+
)
|
| 69 |
+
},
|
| 70 |
+
)
|
| 71 |
+
max_answer_length: int = field(
|
| 72 |
+
default=30,
|
| 73 |
+
metadata={
|
| 74 |
+
"help": (
|
| 75 |
+
"The maximum length of an answer that can be generated. This is needed because the start "
|
| 76 |
+
"and end predictions are not conditioned on one another."
|
| 77 |
+
)
|
| 78 |
+
},
|
| 79 |
+
)
|
| 80 |
+
overwrite_cache: bool = field(
|
| 81 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
| 82 |
+
)
|
| 83 |
+
version_2_with_negative: bool = field(
|
| 84 |
+
default=False, metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."}
|
| 85 |
+
)
|
| 86 |
+
null_score_diff_threshold: float = field(
|
| 87 |
+
default=0.0, metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."}
|
| 88 |
+
)
|
| 89 |
+
n_best_size: int = field(
|
| 90 |
+
default=20, metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."}
|
| 91 |
+
)
|
| 92 |
+
lang_id: int = field(
|
| 93 |
+
default=0,
|
| 94 |
+
metadata={
|
| 95 |
+
"help": (
|
| 96 |
+
"language id of input for language-specific xlm models (see"
|
| 97 |
+
" tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"
|
| 98 |
+
)
|
| 99 |
+
},
|
| 100 |
+
)
|
| 101 |
+
threads: int = field(default=1, metadata={"help": "multiple threads for converting example to features"})
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class Split(Enum):
|
| 105 |
+
train = "train"
|
| 106 |
+
dev = "dev"
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class SquadDataset(Dataset):
|
| 110 |
+
"""
|
| 111 |
+
This will be superseded by a framework-agnostic approach soon.
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
args: SquadDataTrainingArguments
|
| 115 |
+
features: list[SquadFeatures]
|
| 116 |
+
mode: Split
|
| 117 |
+
is_language_sensitive: bool
|
| 118 |
+
|
| 119 |
+
def __init__(
|
| 120 |
+
self,
|
| 121 |
+
args: SquadDataTrainingArguments,
|
| 122 |
+
tokenizer: PreTrainedTokenizer,
|
| 123 |
+
limit_length: Optional[int] = None,
|
| 124 |
+
mode: Union[str, Split] = Split.train,
|
| 125 |
+
is_language_sensitive: bool = False,
|
| 126 |
+
cache_dir: Optional[str] = None,
|
| 127 |
+
dataset_format: str = "pt",
|
| 128 |
+
):
|
| 129 |
+
self.args = args
|
| 130 |
+
self.is_language_sensitive = is_language_sensitive
|
| 131 |
+
self.processor = SquadV2Processor() if args.version_2_with_negative else SquadV1Processor()
|
| 132 |
+
if isinstance(mode, str):
|
| 133 |
+
try:
|
| 134 |
+
mode = Split[mode]
|
| 135 |
+
except KeyError:
|
| 136 |
+
raise KeyError("mode is not a valid split name")
|
| 137 |
+
self.mode = mode
|
| 138 |
+
# Load data features from cache or dataset file
|
| 139 |
+
version_tag = "v2" if args.version_2_with_negative else "v1"
|
| 140 |
+
cached_features_file = os.path.join(
|
| 141 |
+
cache_dir if cache_dir is not None else args.data_dir,
|
| 142 |
+
f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}",
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
# Make sure only the first process in distributed training processes the dataset,
|
| 146 |
+
# and the others will use the cache.
|
| 147 |
+
lock_path = cached_features_file + ".lock"
|
| 148 |
+
with FileLock(lock_path):
|
| 149 |
+
if os.path.exists(cached_features_file) and not args.overwrite_cache:
|
| 150 |
+
start = time.time()
|
| 151 |
+
check_torch_load_is_safe()
|
| 152 |
+
self.old_features = torch.load(cached_features_file, weights_only=True)
|
| 153 |
+
|
| 154 |
+
# Legacy cache files have only features, while new cache files
|
| 155 |
+
# will have dataset and examples also.
|
| 156 |
+
self.features = self.old_features["features"]
|
| 157 |
+
self.dataset = self.old_features.get("dataset", None)
|
| 158 |
+
self.examples = self.old_features.get("examples", None)
|
| 159 |
+
logger.info(
|
| 160 |
+
f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
if self.dataset is None or self.examples is None:
|
| 164 |
+
logger.warning(
|
| 165 |
+
f"Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"
|
| 166 |
+
" future run"
|
| 167 |
+
)
|
| 168 |
+
else:
|
| 169 |
+
if mode == Split.dev:
|
| 170 |
+
self.examples = self.processor.get_dev_examples(args.data_dir)
|
| 171 |
+
else:
|
| 172 |
+
self.examples = self.processor.get_train_examples(args.data_dir)
|
| 173 |
+
|
| 174 |
+
self.features, self.dataset = squad_convert_examples_to_features(
|
| 175 |
+
examples=self.examples,
|
| 176 |
+
tokenizer=tokenizer,
|
| 177 |
+
max_seq_length=args.max_seq_length,
|
| 178 |
+
doc_stride=args.doc_stride,
|
| 179 |
+
max_query_length=args.max_query_length,
|
| 180 |
+
is_training=mode == Split.train,
|
| 181 |
+
threads=args.threads,
|
| 182 |
+
return_dataset=dataset_format,
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
start = time.time()
|
| 186 |
+
torch.save(
|
| 187 |
+
{"features": self.features, "dataset": self.dataset, "examples": self.examples},
|
| 188 |
+
cached_features_file,
|
| 189 |
+
)
|
| 190 |
+
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
|
| 191 |
+
logger.info(
|
| 192 |
+
f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
def __len__(self):
|
| 196 |
+
return len(self.features)
|
| 197 |
+
|
| 198 |
+
def __getitem__(self, i) -> dict[str, torch.Tensor]:
|
| 199 |
+
# Convert to Tensors and build dataset
|
| 200 |
+
feature = self.features[i]
|
| 201 |
+
|
| 202 |
+
input_ids = torch.tensor(feature.input_ids, dtype=torch.long)
|
| 203 |
+
attention_mask = torch.tensor(feature.attention_mask, dtype=torch.long)
|
| 204 |
+
token_type_ids = torch.tensor(feature.token_type_ids, dtype=torch.long)
|
| 205 |
+
cls_index = torch.tensor(feature.cls_index, dtype=torch.long)
|
| 206 |
+
p_mask = torch.tensor(feature.p_mask, dtype=torch.float)
|
| 207 |
+
is_impossible = torch.tensor(feature.is_impossible, dtype=torch.float)
|
| 208 |
+
|
| 209 |
+
inputs = {
|
| 210 |
+
"input_ids": input_ids,
|
| 211 |
+
"attention_mask": attention_mask,
|
| 212 |
+
"token_type_ids": token_type_ids,
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
|
| 216 |
+
del inputs["token_type_ids"]
|
| 217 |
+
|
| 218 |
+
if self.args.model_type in ["xlnet", "xlm"]:
|
| 219 |
+
inputs.update({"cls_index": cls_index, "p_mask": p_mask})
|
| 220 |
+
if self.args.version_2_with_negative:
|
| 221 |
+
inputs.update({"is_impossible": is_impossible})
|
| 222 |
+
if self.is_language_sensitive:
|
| 223 |
+
inputs.update({"langs": (torch.ones(input_ids.shape, dtype=torch.int64) * self.args.lang_id)})
|
| 224 |
+
|
| 225 |
+
if self.mode == Split.train:
|
| 226 |
+
start_positions = torch.tensor(feature.start_position, dtype=torch.long)
|
| 227 |
+
end_positions = torch.tensor(feature.end_position, dtype=torch.long)
|
| 228 |
+
inputs.update({"start_positions": start_positions, "end_positions": end_positions})
|
| 229 |
+
|
| 230 |
+
return inputs
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/metrics/__init__.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 2 |
+
# you may not use this file except in compliance with the License.
|
| 3 |
+
# You may obtain a copy of the License at
|
| 4 |
+
#
|
| 5 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 6 |
+
#
|
| 7 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 8 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 9 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 10 |
+
# See the License for the specific language governing permissions and
|
| 11 |
+
# limitations under the License.
|
| 12 |
+
|
| 13 |
+
import warnings
|
| 14 |
+
|
| 15 |
+
from ...utils import is_sklearn_available, requires_backends
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if is_sklearn_available():
|
| 19 |
+
from scipy.stats import pearsonr, spearmanr
|
| 20 |
+
from sklearn.metrics import f1_score, matthews_corrcoef
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
DEPRECATION_WARNING = (
|
| 24 |
+
"This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate "
|
| 25 |
+
"library. You can have a look at this example script for pointers: "
|
| 26 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py"
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def simple_accuracy(preds, labels):
|
| 31 |
+
warnings.warn(DEPRECATION_WARNING, FutureWarning)
|
| 32 |
+
requires_backends(simple_accuracy, "sklearn")
|
| 33 |
+
return (preds == labels).mean()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def acc_and_f1(preds, labels):
|
| 37 |
+
warnings.warn(DEPRECATION_WARNING, FutureWarning)
|
| 38 |
+
requires_backends(acc_and_f1, "sklearn")
|
| 39 |
+
acc = simple_accuracy(preds, labels)
|
| 40 |
+
f1 = f1_score(y_true=labels, y_pred=preds)
|
| 41 |
+
return {
|
| 42 |
+
"acc": acc,
|
| 43 |
+
"f1": f1,
|
| 44 |
+
"acc_and_f1": (acc + f1) / 2,
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def pearson_and_spearman(preds, labels):
|
| 49 |
+
warnings.warn(DEPRECATION_WARNING, FutureWarning)
|
| 50 |
+
requires_backends(pearson_and_spearman, "sklearn")
|
| 51 |
+
pearson_corr = pearsonr(preds, labels)[0]
|
| 52 |
+
spearman_corr = spearmanr(preds, labels)[0]
|
| 53 |
+
return {
|
| 54 |
+
"pearson": pearson_corr,
|
| 55 |
+
"spearmanr": spearman_corr,
|
| 56 |
+
"corr": (pearson_corr + spearman_corr) / 2,
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def glue_compute_metrics(task_name, preds, labels):
|
| 61 |
+
warnings.warn(DEPRECATION_WARNING, FutureWarning)
|
| 62 |
+
requires_backends(glue_compute_metrics, "sklearn")
|
| 63 |
+
assert len(preds) == len(labels), f"Predictions and labels have mismatched lengths {len(preds)} and {len(labels)}"
|
| 64 |
+
if task_name == "cola":
|
| 65 |
+
return {"mcc": matthews_corrcoef(labels, preds)}
|
| 66 |
+
elif task_name == "sst-2":
|
| 67 |
+
return {"acc": simple_accuracy(preds, labels)}
|
| 68 |
+
elif task_name == "mrpc":
|
| 69 |
+
return acc_and_f1(preds, labels)
|
| 70 |
+
elif task_name == "sts-b":
|
| 71 |
+
return pearson_and_spearman(preds, labels)
|
| 72 |
+
elif task_name == "qqp":
|
| 73 |
+
return acc_and_f1(preds, labels)
|
| 74 |
+
elif task_name == "mnli":
|
| 75 |
+
return {"mnli/acc": simple_accuracy(preds, labels)}
|
| 76 |
+
elif task_name == "mnli-mm":
|
| 77 |
+
return {"mnli-mm/acc": simple_accuracy(preds, labels)}
|
| 78 |
+
elif task_name == "qnli":
|
| 79 |
+
return {"acc": simple_accuracy(preds, labels)}
|
| 80 |
+
elif task_name == "rte":
|
| 81 |
+
return {"acc": simple_accuracy(preds, labels)}
|
| 82 |
+
elif task_name == "wnli":
|
| 83 |
+
return {"acc": simple_accuracy(preds, labels)}
|
| 84 |
+
elif task_name == "hans":
|
| 85 |
+
return {"acc": simple_accuracy(preds, labels)}
|
| 86 |
+
else:
|
| 87 |
+
raise KeyError(task_name)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def xnli_compute_metrics(task_name, preds, labels):
|
| 91 |
+
warnings.warn(DEPRECATION_WARNING, FutureWarning)
|
| 92 |
+
requires_backends(xnli_compute_metrics, "sklearn")
|
| 93 |
+
if len(preds) != len(labels):
|
| 94 |
+
raise ValueError(f"Predictions and labels have mismatched lengths {len(preds)} and {len(labels)}")
|
| 95 |
+
if task_name == "xnli":
|
| 96 |
+
return {"acc": simple_accuracy(preds, labels)}
|
| 97 |
+
else:
|
| 98 |
+
raise KeyError(task_name)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/metrics/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (2.55 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/metrics/__pycache__/squad_metrics.cpython-310.pyc
ADDED
|
Binary file (16 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/metrics/squad_metrics.py
ADDED
|
@@ -0,0 +1,779 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""
|
| 15 |
+
Very heavily inspired by the official evaluation script for SQuAD version 2.0 which was modified by XLNet authors to
|
| 16 |
+
update `find_best_threshold` scripts for SQuAD V2.0
|
| 17 |
+
|
| 18 |
+
In addition to basic functionality, we also compute additional statistics and plot precision-recall curves if an
|
| 19 |
+
additional na_prob.json file is provided. This file is expected to map question ID's to the model's predicted
|
| 20 |
+
probability that a question is unanswerable.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
import collections
|
| 24 |
+
import json
|
| 25 |
+
import math
|
| 26 |
+
import re
|
| 27 |
+
import string
|
| 28 |
+
|
| 29 |
+
from ...models.bert import BasicTokenizer
|
| 30 |
+
from ...utils import logging
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def normalize_answer(s):
|
| 37 |
+
"""Lower text and remove punctuation, articles and extra whitespace."""
|
| 38 |
+
|
| 39 |
+
def remove_articles(text):
|
| 40 |
+
regex = re.compile(r"\b(a|an|the)\b", re.UNICODE)
|
| 41 |
+
return re.sub(regex, " ", text)
|
| 42 |
+
|
| 43 |
+
def white_space_fix(text):
|
| 44 |
+
return " ".join(text.split())
|
| 45 |
+
|
| 46 |
+
def remove_punc(text):
|
| 47 |
+
exclude = set(string.punctuation)
|
| 48 |
+
return "".join(ch for ch in text if ch not in exclude)
|
| 49 |
+
|
| 50 |
+
def lower(text):
|
| 51 |
+
return text.lower()
|
| 52 |
+
|
| 53 |
+
return white_space_fix(remove_articles(remove_punc(lower(s))))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_tokens(s):
|
| 57 |
+
if not s:
|
| 58 |
+
return []
|
| 59 |
+
return normalize_answer(s).split()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def compute_exact(a_gold, a_pred):
|
| 63 |
+
return int(normalize_answer(a_gold) == normalize_answer(a_pred))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def compute_f1(a_gold, a_pred):
|
| 67 |
+
gold_toks = get_tokens(a_gold)
|
| 68 |
+
pred_toks = get_tokens(a_pred)
|
| 69 |
+
common = collections.Counter(gold_toks) & collections.Counter(pred_toks)
|
| 70 |
+
num_same = sum(common.values())
|
| 71 |
+
if len(gold_toks) == 0 or len(pred_toks) == 0:
|
| 72 |
+
# If either is no-answer, then F1 is 1 if they agree, 0 otherwise
|
| 73 |
+
return int(gold_toks == pred_toks)
|
| 74 |
+
if num_same == 0:
|
| 75 |
+
return 0
|
| 76 |
+
precision = 1.0 * num_same / len(pred_toks)
|
| 77 |
+
recall = 1.0 * num_same / len(gold_toks)
|
| 78 |
+
f1 = (2 * precision * recall) / (precision + recall)
|
| 79 |
+
return f1
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def get_raw_scores(examples, preds):
|
| 83 |
+
"""
|
| 84 |
+
Computes the exact and f1 scores from the examples and the model predictions
|
| 85 |
+
"""
|
| 86 |
+
exact_scores = {}
|
| 87 |
+
f1_scores = {}
|
| 88 |
+
|
| 89 |
+
for example in examples:
|
| 90 |
+
qas_id = example.qas_id
|
| 91 |
+
gold_answers = [answer["text"] for answer in example.answers if normalize_answer(answer["text"])]
|
| 92 |
+
|
| 93 |
+
if not gold_answers:
|
| 94 |
+
# For unanswerable questions, only correct answer is empty string
|
| 95 |
+
gold_answers = [""]
|
| 96 |
+
|
| 97 |
+
if qas_id not in preds:
|
| 98 |
+
print(f"Missing prediction for {qas_id}")
|
| 99 |
+
continue
|
| 100 |
+
|
| 101 |
+
prediction = preds[qas_id]
|
| 102 |
+
exact_scores[qas_id] = max(compute_exact(a, prediction) for a in gold_answers)
|
| 103 |
+
f1_scores[qas_id] = max(compute_f1(a, prediction) for a in gold_answers)
|
| 104 |
+
|
| 105 |
+
return exact_scores, f1_scores
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def apply_no_ans_threshold(scores, na_probs, qid_to_has_ans, na_prob_thresh):
|
| 109 |
+
new_scores = {}
|
| 110 |
+
for qid, s in scores.items():
|
| 111 |
+
pred_na = na_probs[qid] > na_prob_thresh
|
| 112 |
+
if pred_na:
|
| 113 |
+
new_scores[qid] = float(not qid_to_has_ans[qid])
|
| 114 |
+
else:
|
| 115 |
+
new_scores[qid] = s
|
| 116 |
+
return new_scores
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def make_eval_dict(exact_scores, f1_scores, qid_list=None):
|
| 120 |
+
if not qid_list:
|
| 121 |
+
total = len(exact_scores)
|
| 122 |
+
return collections.OrderedDict(
|
| 123 |
+
[
|
| 124 |
+
("exact", 100.0 * sum(exact_scores.values()) / total),
|
| 125 |
+
("f1", 100.0 * sum(f1_scores.values()) / total),
|
| 126 |
+
("total", total),
|
| 127 |
+
]
|
| 128 |
+
)
|
| 129 |
+
else:
|
| 130 |
+
total = len(qid_list)
|
| 131 |
+
return collections.OrderedDict(
|
| 132 |
+
[
|
| 133 |
+
("exact", 100.0 * sum(exact_scores[k] for k in qid_list) / total),
|
| 134 |
+
("f1", 100.0 * sum(f1_scores[k] for k in qid_list) / total),
|
| 135 |
+
("total", total),
|
| 136 |
+
]
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def merge_eval(main_eval, new_eval, prefix):
|
| 141 |
+
for k in new_eval:
|
| 142 |
+
main_eval[f"{prefix}_{k}"] = new_eval[k]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def find_best_thresh_v2(preds, scores, na_probs, qid_to_has_ans):
|
| 146 |
+
num_no_ans = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k])
|
| 147 |
+
cur_score = num_no_ans
|
| 148 |
+
best_score = cur_score
|
| 149 |
+
best_thresh = 0.0
|
| 150 |
+
qid_list = sorted(na_probs, key=lambda k: na_probs[k])
|
| 151 |
+
for qid in qid_list:
|
| 152 |
+
if qid not in scores:
|
| 153 |
+
continue
|
| 154 |
+
if qid_to_has_ans[qid]:
|
| 155 |
+
diff = scores[qid]
|
| 156 |
+
else:
|
| 157 |
+
if preds[qid]:
|
| 158 |
+
diff = -1
|
| 159 |
+
else:
|
| 160 |
+
diff = 0
|
| 161 |
+
cur_score += diff
|
| 162 |
+
if cur_score > best_score:
|
| 163 |
+
best_score = cur_score
|
| 164 |
+
best_thresh = na_probs[qid]
|
| 165 |
+
|
| 166 |
+
has_ans_score, has_ans_cnt = 0, 0
|
| 167 |
+
for qid in qid_list:
|
| 168 |
+
if not qid_to_has_ans[qid]:
|
| 169 |
+
continue
|
| 170 |
+
has_ans_cnt += 1
|
| 171 |
+
|
| 172 |
+
if qid not in scores:
|
| 173 |
+
continue
|
| 174 |
+
has_ans_score += scores[qid]
|
| 175 |
+
|
| 176 |
+
return 100.0 * best_score / len(scores), best_thresh, 1.0 * has_ans_score / has_ans_cnt
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def find_all_best_thresh_v2(main_eval, preds, exact_raw, f1_raw, na_probs, qid_to_has_ans):
|
| 180 |
+
best_exact, exact_thresh, has_ans_exact = find_best_thresh_v2(preds, exact_raw, na_probs, qid_to_has_ans)
|
| 181 |
+
best_f1, f1_thresh, has_ans_f1 = find_best_thresh_v2(preds, f1_raw, na_probs, qid_to_has_ans)
|
| 182 |
+
main_eval["best_exact"] = best_exact
|
| 183 |
+
main_eval["best_exact_thresh"] = exact_thresh
|
| 184 |
+
main_eval["best_f1"] = best_f1
|
| 185 |
+
main_eval["best_f1_thresh"] = f1_thresh
|
| 186 |
+
main_eval["has_ans_exact"] = has_ans_exact
|
| 187 |
+
main_eval["has_ans_f1"] = has_ans_f1
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def find_best_thresh(preds, scores, na_probs, qid_to_has_ans):
|
| 191 |
+
num_no_ans = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k])
|
| 192 |
+
cur_score = num_no_ans
|
| 193 |
+
best_score = cur_score
|
| 194 |
+
best_thresh = 0.0
|
| 195 |
+
qid_list = sorted(na_probs, key=lambda k: na_probs[k])
|
| 196 |
+
for _, qid in enumerate(qid_list):
|
| 197 |
+
if qid not in scores:
|
| 198 |
+
continue
|
| 199 |
+
if qid_to_has_ans[qid]:
|
| 200 |
+
diff = scores[qid]
|
| 201 |
+
else:
|
| 202 |
+
if preds[qid]:
|
| 203 |
+
diff = -1
|
| 204 |
+
else:
|
| 205 |
+
diff = 0
|
| 206 |
+
cur_score += diff
|
| 207 |
+
if cur_score > best_score:
|
| 208 |
+
best_score = cur_score
|
| 209 |
+
best_thresh = na_probs[qid]
|
| 210 |
+
return 100.0 * best_score / len(scores), best_thresh
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def find_all_best_thresh(main_eval, preds, exact_raw, f1_raw, na_probs, qid_to_has_ans):
|
| 214 |
+
best_exact, exact_thresh = find_best_thresh(preds, exact_raw, na_probs, qid_to_has_ans)
|
| 215 |
+
best_f1, f1_thresh = find_best_thresh(preds, f1_raw, na_probs, qid_to_has_ans)
|
| 216 |
+
|
| 217 |
+
main_eval["best_exact"] = best_exact
|
| 218 |
+
main_eval["best_exact_thresh"] = exact_thresh
|
| 219 |
+
main_eval["best_f1"] = best_f1
|
| 220 |
+
main_eval["best_f1_thresh"] = f1_thresh
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def squad_evaluate(examples, preds, no_answer_probs=None, no_answer_probability_threshold=1.0):
|
| 224 |
+
qas_id_to_has_answer = {example.qas_id: bool(example.answers) for example in examples}
|
| 225 |
+
has_answer_qids = [qas_id for qas_id, has_answer in qas_id_to_has_answer.items() if has_answer]
|
| 226 |
+
no_answer_qids = [qas_id for qas_id, has_answer in qas_id_to_has_answer.items() if not has_answer]
|
| 227 |
+
|
| 228 |
+
if no_answer_probs is None:
|
| 229 |
+
no_answer_probs = dict.fromkeys(preds, 0.0)
|
| 230 |
+
|
| 231 |
+
exact, f1 = get_raw_scores(examples, preds)
|
| 232 |
+
|
| 233 |
+
exact_threshold = apply_no_ans_threshold(
|
| 234 |
+
exact, no_answer_probs, qas_id_to_has_answer, no_answer_probability_threshold
|
| 235 |
+
)
|
| 236 |
+
f1_threshold = apply_no_ans_threshold(f1, no_answer_probs, qas_id_to_has_answer, no_answer_probability_threshold)
|
| 237 |
+
|
| 238 |
+
evaluation = make_eval_dict(exact_threshold, f1_threshold)
|
| 239 |
+
|
| 240 |
+
if has_answer_qids:
|
| 241 |
+
has_ans_eval = make_eval_dict(exact_threshold, f1_threshold, qid_list=has_answer_qids)
|
| 242 |
+
merge_eval(evaluation, has_ans_eval, "HasAns")
|
| 243 |
+
|
| 244 |
+
if no_answer_qids:
|
| 245 |
+
no_ans_eval = make_eval_dict(exact_threshold, f1_threshold, qid_list=no_answer_qids)
|
| 246 |
+
merge_eval(evaluation, no_ans_eval, "NoAns")
|
| 247 |
+
|
| 248 |
+
if no_answer_probs:
|
| 249 |
+
find_all_best_thresh(evaluation, preds, exact, f1, no_answer_probs, qas_id_to_has_answer)
|
| 250 |
+
|
| 251 |
+
return evaluation
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def get_final_text(pred_text, orig_text, do_lower_case, verbose_logging=False):
|
| 255 |
+
"""Project the tokenized prediction back to the original text."""
|
| 256 |
+
|
| 257 |
+
# When we created the data, we kept track of the alignment between original
|
| 258 |
+
# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
|
| 259 |
+
# now `orig_text` contains the span of our original text corresponding to the
|
| 260 |
+
# span that we predicted.
|
| 261 |
+
#
|
| 262 |
+
# However, `orig_text` may contain extra characters that we don't want in
|
| 263 |
+
# our prediction.
|
| 264 |
+
#
|
| 265 |
+
# For example, let's say:
|
| 266 |
+
# pred_text = steve smith
|
| 267 |
+
# orig_text = Steve Smith's
|
| 268 |
+
#
|
| 269 |
+
# We don't want to return `orig_text` because it contains the extra "'s".
|
| 270 |
+
#
|
| 271 |
+
# We don't want to return `pred_text` because it's already been normalized
|
| 272 |
+
# (the SQuAD eval script also does punctuation stripping/lower casing but
|
| 273 |
+
# our tokenizer does additional normalization like stripping accent
|
| 274 |
+
# characters).
|
| 275 |
+
#
|
| 276 |
+
# What we really want to return is "Steve Smith".
|
| 277 |
+
#
|
| 278 |
+
# Therefore, we have to apply a semi-complicated alignment heuristic between
|
| 279 |
+
# `pred_text` and `orig_text` to get a character-to-character alignment. This
|
| 280 |
+
# can fail in certain cases in which case we just return `orig_text`.
|
| 281 |
+
|
| 282 |
+
def _strip_spaces(text):
|
| 283 |
+
ns_chars = []
|
| 284 |
+
ns_to_s_map = collections.OrderedDict()
|
| 285 |
+
for i, c in enumerate(text):
|
| 286 |
+
if c == " ":
|
| 287 |
+
continue
|
| 288 |
+
ns_to_s_map[len(ns_chars)] = i
|
| 289 |
+
ns_chars.append(c)
|
| 290 |
+
ns_text = "".join(ns_chars)
|
| 291 |
+
return (ns_text, ns_to_s_map)
|
| 292 |
+
|
| 293 |
+
# We first tokenize `orig_text`, strip whitespace from the result
|
| 294 |
+
# and `pred_text`, and check if they are the same length. If they are
|
| 295 |
+
# NOT the same length, the heuristic has failed. If they are the same
|
| 296 |
+
# length, we assume the characters are one-to-one aligned.
|
| 297 |
+
tokenizer = BasicTokenizer(do_lower_case=do_lower_case)
|
| 298 |
+
|
| 299 |
+
tok_text = " ".join(tokenizer.tokenize(orig_text))
|
| 300 |
+
|
| 301 |
+
start_position = tok_text.find(pred_text)
|
| 302 |
+
if start_position == -1:
|
| 303 |
+
if verbose_logging:
|
| 304 |
+
logger.info(f"Unable to find text: '{pred_text}' in '{orig_text}'")
|
| 305 |
+
return orig_text
|
| 306 |
+
end_position = start_position + len(pred_text) - 1
|
| 307 |
+
|
| 308 |
+
(orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)
|
| 309 |
+
(tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)
|
| 310 |
+
|
| 311 |
+
if len(orig_ns_text) != len(tok_ns_text):
|
| 312 |
+
if verbose_logging:
|
| 313 |
+
logger.info(f"Length not equal after stripping spaces: '{orig_ns_text}' vs '{tok_ns_text}'")
|
| 314 |
+
return orig_text
|
| 315 |
+
|
| 316 |
+
# We then project the characters in `pred_text` back to `orig_text` using
|
| 317 |
+
# the character-to-character alignment.
|
| 318 |
+
tok_s_to_ns_map = {}
|
| 319 |
+
for i, tok_index in tok_ns_to_s_map.items():
|
| 320 |
+
tok_s_to_ns_map[tok_index] = i
|
| 321 |
+
|
| 322 |
+
orig_start_position = None
|
| 323 |
+
if start_position in tok_s_to_ns_map:
|
| 324 |
+
ns_start_position = tok_s_to_ns_map[start_position]
|
| 325 |
+
if ns_start_position in orig_ns_to_s_map:
|
| 326 |
+
orig_start_position = orig_ns_to_s_map[ns_start_position]
|
| 327 |
+
|
| 328 |
+
if orig_start_position is None:
|
| 329 |
+
if verbose_logging:
|
| 330 |
+
logger.info("Couldn't map start position")
|
| 331 |
+
return orig_text
|
| 332 |
+
|
| 333 |
+
orig_end_position = None
|
| 334 |
+
if end_position in tok_s_to_ns_map:
|
| 335 |
+
ns_end_position = tok_s_to_ns_map[end_position]
|
| 336 |
+
if ns_end_position in orig_ns_to_s_map:
|
| 337 |
+
orig_end_position = orig_ns_to_s_map[ns_end_position]
|
| 338 |
+
|
| 339 |
+
if orig_end_position is None:
|
| 340 |
+
if verbose_logging:
|
| 341 |
+
logger.info("Couldn't map end position")
|
| 342 |
+
return orig_text
|
| 343 |
+
|
| 344 |
+
output_text = orig_text[orig_start_position : (orig_end_position + 1)]
|
| 345 |
+
return output_text
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def _get_best_indexes(logits, n_best_size):
|
| 349 |
+
"""Get the n-best logits from a list."""
|
| 350 |
+
index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
|
| 351 |
+
|
| 352 |
+
best_indexes = []
|
| 353 |
+
for i in range(len(index_and_score)):
|
| 354 |
+
if i >= n_best_size:
|
| 355 |
+
break
|
| 356 |
+
best_indexes.append(index_and_score[i][0])
|
| 357 |
+
return best_indexes
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def _compute_softmax(scores):
|
| 361 |
+
"""Compute softmax probability over raw logits."""
|
| 362 |
+
if not scores:
|
| 363 |
+
return []
|
| 364 |
+
|
| 365 |
+
max_score = None
|
| 366 |
+
for score in scores:
|
| 367 |
+
if max_score is None or score > max_score:
|
| 368 |
+
max_score = score
|
| 369 |
+
|
| 370 |
+
exp_scores = []
|
| 371 |
+
total_sum = 0.0
|
| 372 |
+
for score in scores:
|
| 373 |
+
x = math.exp(score - max_score)
|
| 374 |
+
exp_scores.append(x)
|
| 375 |
+
total_sum += x
|
| 376 |
+
|
| 377 |
+
probs = []
|
| 378 |
+
for score in exp_scores:
|
| 379 |
+
probs.append(score / total_sum)
|
| 380 |
+
return probs
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def compute_predictions_logits(
|
| 384 |
+
all_examples,
|
| 385 |
+
all_features,
|
| 386 |
+
all_results,
|
| 387 |
+
n_best_size,
|
| 388 |
+
max_answer_length,
|
| 389 |
+
do_lower_case,
|
| 390 |
+
output_prediction_file,
|
| 391 |
+
output_nbest_file,
|
| 392 |
+
output_null_log_odds_file,
|
| 393 |
+
verbose_logging,
|
| 394 |
+
version_2_with_negative,
|
| 395 |
+
null_score_diff_threshold,
|
| 396 |
+
tokenizer,
|
| 397 |
+
):
|
| 398 |
+
"""Write final predictions to the json file and log-odds of null if needed."""
|
| 399 |
+
if output_prediction_file:
|
| 400 |
+
logger.info(f"Writing predictions to: {output_prediction_file}")
|
| 401 |
+
if output_nbest_file:
|
| 402 |
+
logger.info(f"Writing nbest to: {output_nbest_file}")
|
| 403 |
+
if output_null_log_odds_file and version_2_with_negative:
|
| 404 |
+
logger.info(f"Writing null_log_odds to: {output_null_log_odds_file}")
|
| 405 |
+
|
| 406 |
+
example_index_to_features = collections.defaultdict(list)
|
| 407 |
+
for feature in all_features:
|
| 408 |
+
example_index_to_features[feature.example_index].append(feature)
|
| 409 |
+
|
| 410 |
+
unique_id_to_result = {}
|
| 411 |
+
for result in all_results:
|
| 412 |
+
unique_id_to_result[result.unique_id] = result
|
| 413 |
+
|
| 414 |
+
_PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
|
| 415 |
+
"PrelimPrediction", ["feature_index", "start_index", "end_index", "start_logit", "end_logit"]
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
all_predictions = collections.OrderedDict()
|
| 419 |
+
all_nbest_json = collections.OrderedDict()
|
| 420 |
+
scores_diff_json = collections.OrderedDict()
|
| 421 |
+
|
| 422 |
+
for example_index, example in enumerate(all_examples):
|
| 423 |
+
features = example_index_to_features[example_index]
|
| 424 |
+
|
| 425 |
+
prelim_predictions = []
|
| 426 |
+
# keep track of the minimum score of null start+end of position 0
|
| 427 |
+
score_null = 1000000 # large and positive
|
| 428 |
+
min_null_feature_index = 0 # the paragraph slice with min null score
|
| 429 |
+
null_start_logit = 0 # the start logit at the slice with min null score
|
| 430 |
+
null_end_logit = 0 # the end logit at the slice with min null score
|
| 431 |
+
for feature_index, feature in enumerate(features):
|
| 432 |
+
result = unique_id_to_result[feature.unique_id]
|
| 433 |
+
start_indexes = _get_best_indexes(result.start_logits, n_best_size)
|
| 434 |
+
end_indexes = _get_best_indexes(result.end_logits, n_best_size)
|
| 435 |
+
# if we could have irrelevant answers, get the min score of irrelevant
|
| 436 |
+
if version_2_with_negative:
|
| 437 |
+
feature_null_score = result.start_logits[0] + result.end_logits[0]
|
| 438 |
+
if feature_null_score < score_null:
|
| 439 |
+
score_null = feature_null_score
|
| 440 |
+
min_null_feature_index = feature_index
|
| 441 |
+
null_start_logit = result.start_logits[0]
|
| 442 |
+
null_end_logit = result.end_logits[0]
|
| 443 |
+
for start_index in start_indexes:
|
| 444 |
+
for end_index in end_indexes:
|
| 445 |
+
# We could hypothetically create invalid predictions, e.g., predict
|
| 446 |
+
# that the start of the span is in the question. We throw out all
|
| 447 |
+
# invalid predictions.
|
| 448 |
+
if start_index >= len(feature.tokens):
|
| 449 |
+
continue
|
| 450 |
+
if end_index >= len(feature.tokens):
|
| 451 |
+
continue
|
| 452 |
+
if start_index not in feature.token_to_orig_map:
|
| 453 |
+
continue
|
| 454 |
+
if end_index not in feature.token_to_orig_map:
|
| 455 |
+
continue
|
| 456 |
+
if not feature.token_is_max_context.get(start_index, False):
|
| 457 |
+
continue
|
| 458 |
+
if end_index < start_index:
|
| 459 |
+
continue
|
| 460 |
+
length = end_index - start_index + 1
|
| 461 |
+
if length > max_answer_length:
|
| 462 |
+
continue
|
| 463 |
+
prelim_predictions.append(
|
| 464 |
+
_PrelimPrediction(
|
| 465 |
+
feature_index=feature_index,
|
| 466 |
+
start_index=start_index,
|
| 467 |
+
end_index=end_index,
|
| 468 |
+
start_logit=result.start_logits[start_index],
|
| 469 |
+
end_logit=result.end_logits[end_index],
|
| 470 |
+
)
|
| 471 |
+
)
|
| 472 |
+
if version_2_with_negative:
|
| 473 |
+
prelim_predictions.append(
|
| 474 |
+
_PrelimPrediction(
|
| 475 |
+
feature_index=min_null_feature_index,
|
| 476 |
+
start_index=0,
|
| 477 |
+
end_index=0,
|
| 478 |
+
start_logit=null_start_logit,
|
| 479 |
+
end_logit=null_end_logit,
|
| 480 |
+
)
|
| 481 |
+
)
|
| 482 |
+
prelim_predictions = sorted(prelim_predictions, key=lambda x: (x.start_logit + x.end_logit), reverse=True)
|
| 483 |
+
|
| 484 |
+
_NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
|
| 485 |
+
"NbestPrediction", ["text", "start_logit", "end_logit"]
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
seen_predictions = {}
|
| 489 |
+
nbest = []
|
| 490 |
+
for pred in prelim_predictions:
|
| 491 |
+
if len(nbest) >= n_best_size:
|
| 492 |
+
break
|
| 493 |
+
feature = features[pred.feature_index]
|
| 494 |
+
if pred.start_index > 0: # this is a non-null prediction
|
| 495 |
+
tok_tokens = feature.tokens[pred.start_index : (pred.end_index + 1)]
|
| 496 |
+
orig_doc_start = feature.token_to_orig_map[pred.start_index]
|
| 497 |
+
orig_doc_end = feature.token_to_orig_map[pred.end_index]
|
| 498 |
+
orig_tokens = example.doc_tokens[orig_doc_start : (orig_doc_end + 1)]
|
| 499 |
+
|
| 500 |
+
tok_text = tokenizer.convert_tokens_to_string(tok_tokens)
|
| 501 |
+
|
| 502 |
+
# tok_text = " ".join(tok_tokens)
|
| 503 |
+
#
|
| 504 |
+
# # De-tokenize WordPieces that have been split off.
|
| 505 |
+
# tok_text = tok_text.replace(" ##", "")
|
| 506 |
+
# tok_text = tok_text.replace("##", "")
|
| 507 |
+
|
| 508 |
+
# Clean whitespace
|
| 509 |
+
tok_text = tok_text.strip()
|
| 510 |
+
tok_text = " ".join(tok_text.split())
|
| 511 |
+
orig_text = " ".join(orig_tokens)
|
| 512 |
+
|
| 513 |
+
final_text = get_final_text(tok_text, orig_text, do_lower_case, verbose_logging)
|
| 514 |
+
if final_text in seen_predictions:
|
| 515 |
+
continue
|
| 516 |
+
|
| 517 |
+
seen_predictions[final_text] = True
|
| 518 |
+
else:
|
| 519 |
+
final_text = ""
|
| 520 |
+
seen_predictions[final_text] = True
|
| 521 |
+
|
| 522 |
+
nbest.append(_NbestPrediction(text=final_text, start_logit=pred.start_logit, end_logit=pred.end_logit))
|
| 523 |
+
# if we didn't include the empty option in the n-best, include it
|
| 524 |
+
if version_2_with_negative:
|
| 525 |
+
if "" not in seen_predictions:
|
| 526 |
+
nbest.append(_NbestPrediction(text="", start_logit=null_start_logit, end_logit=null_end_logit))
|
| 527 |
+
|
| 528 |
+
# In very rare edge cases we could only have single null prediction.
|
| 529 |
+
# So we just create a nonce prediction in this case to avoid failure.
|
| 530 |
+
if len(nbest) == 1:
|
| 531 |
+
nbest.insert(0, _NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
|
| 532 |
+
|
| 533 |
+
# In very rare edge cases we could have no valid predictions. So we
|
| 534 |
+
# just create a nonce prediction in this case to avoid failure.
|
| 535 |
+
if not nbest:
|
| 536 |
+
nbest.append(_NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
|
| 537 |
+
|
| 538 |
+
if len(nbest) < 1:
|
| 539 |
+
raise ValueError("No valid predictions")
|
| 540 |
+
|
| 541 |
+
total_scores = []
|
| 542 |
+
best_non_null_entry = None
|
| 543 |
+
for entry in nbest:
|
| 544 |
+
total_scores.append(entry.start_logit + entry.end_logit)
|
| 545 |
+
if not best_non_null_entry:
|
| 546 |
+
if entry.text:
|
| 547 |
+
best_non_null_entry = entry
|
| 548 |
+
|
| 549 |
+
probs = _compute_softmax(total_scores)
|
| 550 |
+
|
| 551 |
+
nbest_json = []
|
| 552 |
+
for i, entry in enumerate(nbest):
|
| 553 |
+
output = collections.OrderedDict()
|
| 554 |
+
output["text"] = entry.text
|
| 555 |
+
output["probability"] = probs[i]
|
| 556 |
+
output["start_logit"] = entry.start_logit
|
| 557 |
+
output["end_logit"] = entry.end_logit
|
| 558 |
+
nbest_json.append(output)
|
| 559 |
+
|
| 560 |
+
if len(nbest_json) < 1:
|
| 561 |
+
raise ValueError("No valid predictions")
|
| 562 |
+
|
| 563 |
+
if not version_2_with_negative:
|
| 564 |
+
all_predictions[example.qas_id] = nbest_json[0]["text"]
|
| 565 |
+
else:
|
| 566 |
+
# predict "" iff the null score - the score of best non-null > threshold
|
| 567 |
+
score_diff = score_null - best_non_null_entry.start_logit - (best_non_null_entry.end_logit)
|
| 568 |
+
scores_diff_json[example.qas_id] = score_diff
|
| 569 |
+
if score_diff > null_score_diff_threshold:
|
| 570 |
+
all_predictions[example.qas_id] = ""
|
| 571 |
+
else:
|
| 572 |
+
all_predictions[example.qas_id] = best_non_null_entry.text
|
| 573 |
+
all_nbest_json[example.qas_id] = nbest_json
|
| 574 |
+
|
| 575 |
+
if output_prediction_file:
|
| 576 |
+
with open(output_prediction_file, "w") as writer:
|
| 577 |
+
writer.write(json.dumps(all_predictions, indent=4) + "\n")
|
| 578 |
+
|
| 579 |
+
if output_nbest_file:
|
| 580 |
+
with open(output_nbest_file, "w") as writer:
|
| 581 |
+
writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
|
| 582 |
+
|
| 583 |
+
if output_null_log_odds_file and version_2_with_negative:
|
| 584 |
+
with open(output_null_log_odds_file, "w") as writer:
|
| 585 |
+
writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
|
| 586 |
+
|
| 587 |
+
return all_predictions
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def compute_predictions_log_probs(
|
| 591 |
+
all_examples,
|
| 592 |
+
all_features,
|
| 593 |
+
all_results,
|
| 594 |
+
n_best_size,
|
| 595 |
+
max_answer_length,
|
| 596 |
+
output_prediction_file,
|
| 597 |
+
output_nbest_file,
|
| 598 |
+
output_null_log_odds_file,
|
| 599 |
+
start_n_top,
|
| 600 |
+
end_n_top,
|
| 601 |
+
version_2_with_negative,
|
| 602 |
+
tokenizer,
|
| 603 |
+
verbose_logging,
|
| 604 |
+
):
|
| 605 |
+
"""
|
| 606 |
+
XLNet write prediction logic (more complex than Bert's). Write final predictions to the json file and log-odds of
|
| 607 |
+
null if needed.
|
| 608 |
+
|
| 609 |
+
Requires utils_squad_evaluate.py
|
| 610 |
+
"""
|
| 611 |
+
_PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
|
| 612 |
+
"PrelimPrediction", ["feature_index", "start_index", "end_index", "start_log_prob", "end_log_prob"]
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
_NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
|
| 616 |
+
"NbestPrediction", ["text", "start_log_prob", "end_log_prob"]
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
logger.info(f"Writing predictions to: {output_prediction_file}")
|
| 620 |
+
|
| 621 |
+
example_index_to_features = collections.defaultdict(list)
|
| 622 |
+
for feature in all_features:
|
| 623 |
+
example_index_to_features[feature.example_index].append(feature)
|
| 624 |
+
|
| 625 |
+
unique_id_to_result = {}
|
| 626 |
+
for result in all_results:
|
| 627 |
+
unique_id_to_result[result.unique_id] = result
|
| 628 |
+
|
| 629 |
+
all_predictions = collections.OrderedDict()
|
| 630 |
+
all_nbest_json = collections.OrderedDict()
|
| 631 |
+
scores_diff_json = collections.OrderedDict()
|
| 632 |
+
|
| 633 |
+
for example_index, example in enumerate(all_examples):
|
| 634 |
+
features = example_index_to_features[example_index]
|
| 635 |
+
|
| 636 |
+
prelim_predictions = []
|
| 637 |
+
# keep track of the minimum score of null start+end of position 0
|
| 638 |
+
score_null = 1000000 # large and positive
|
| 639 |
+
|
| 640 |
+
for feature_index, feature in enumerate(features):
|
| 641 |
+
result = unique_id_to_result[feature.unique_id]
|
| 642 |
+
|
| 643 |
+
cur_null_score = result.cls_logits
|
| 644 |
+
|
| 645 |
+
# if we could have irrelevant answers, get the min score of irrelevant
|
| 646 |
+
score_null = min(score_null, cur_null_score)
|
| 647 |
+
|
| 648 |
+
for i in range(start_n_top):
|
| 649 |
+
for j in range(end_n_top):
|
| 650 |
+
start_log_prob = result.start_logits[i]
|
| 651 |
+
start_index = result.start_top_index[i]
|
| 652 |
+
|
| 653 |
+
j_index = i * end_n_top + j
|
| 654 |
+
|
| 655 |
+
end_log_prob = result.end_logits[j_index]
|
| 656 |
+
end_index = result.end_top_index[j_index]
|
| 657 |
+
|
| 658 |
+
# We could hypothetically create invalid predictions, e.g., predict
|
| 659 |
+
# that the start of the span is in the question. We throw out all
|
| 660 |
+
# invalid predictions.
|
| 661 |
+
if start_index >= feature.paragraph_len - 1:
|
| 662 |
+
continue
|
| 663 |
+
if end_index >= feature.paragraph_len - 1:
|
| 664 |
+
continue
|
| 665 |
+
|
| 666 |
+
if not feature.token_is_max_context.get(start_index, False):
|
| 667 |
+
continue
|
| 668 |
+
if end_index < start_index:
|
| 669 |
+
continue
|
| 670 |
+
length = end_index - start_index + 1
|
| 671 |
+
if length > max_answer_length:
|
| 672 |
+
continue
|
| 673 |
+
|
| 674 |
+
prelim_predictions.append(
|
| 675 |
+
_PrelimPrediction(
|
| 676 |
+
feature_index=feature_index,
|
| 677 |
+
start_index=start_index,
|
| 678 |
+
end_index=end_index,
|
| 679 |
+
start_log_prob=start_log_prob,
|
| 680 |
+
end_log_prob=end_log_prob,
|
| 681 |
+
)
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
prelim_predictions = sorted(
|
| 685 |
+
prelim_predictions, key=lambda x: (x.start_log_prob + x.end_log_prob), reverse=True
|
| 686 |
+
)
|
| 687 |
+
|
| 688 |
+
seen_predictions = {}
|
| 689 |
+
nbest = []
|
| 690 |
+
for pred in prelim_predictions:
|
| 691 |
+
if len(nbest) >= n_best_size:
|
| 692 |
+
break
|
| 693 |
+
feature = features[pred.feature_index]
|
| 694 |
+
|
| 695 |
+
# XLNet un-tokenizer
|
| 696 |
+
# Let's keep it simple for now and see if we need all this later.
|
| 697 |
+
#
|
| 698 |
+
# tok_start_to_orig_index = feature.tok_start_to_orig_index
|
| 699 |
+
# tok_end_to_orig_index = feature.tok_end_to_orig_index
|
| 700 |
+
# start_orig_pos = tok_start_to_orig_index[pred.start_index]
|
| 701 |
+
# end_orig_pos = tok_end_to_orig_index[pred.end_index]
|
| 702 |
+
# paragraph_text = example.paragraph_text
|
| 703 |
+
# final_text = paragraph_text[start_orig_pos: end_orig_pos + 1].strip()
|
| 704 |
+
|
| 705 |
+
# Previously used Bert untokenizer
|
| 706 |
+
tok_tokens = feature.tokens[pred.start_index : (pred.end_index + 1)]
|
| 707 |
+
orig_doc_start = feature.token_to_orig_map[pred.start_index]
|
| 708 |
+
orig_doc_end = feature.token_to_orig_map[pred.end_index]
|
| 709 |
+
orig_tokens = example.doc_tokens[orig_doc_start : (orig_doc_end + 1)]
|
| 710 |
+
tok_text = tokenizer.convert_tokens_to_string(tok_tokens)
|
| 711 |
+
|
| 712 |
+
# Clean whitespace
|
| 713 |
+
tok_text = tok_text.strip()
|
| 714 |
+
tok_text = " ".join(tok_text.split())
|
| 715 |
+
orig_text = " ".join(orig_tokens)
|
| 716 |
+
|
| 717 |
+
if hasattr(tokenizer, "do_lower_case"):
|
| 718 |
+
do_lower_case = tokenizer.do_lower_case
|
| 719 |
+
else:
|
| 720 |
+
do_lower_case = tokenizer.do_lowercase_and_remove_accent
|
| 721 |
+
|
| 722 |
+
final_text = get_final_text(tok_text, orig_text, do_lower_case, verbose_logging)
|
| 723 |
+
|
| 724 |
+
if final_text in seen_predictions:
|
| 725 |
+
continue
|
| 726 |
+
|
| 727 |
+
seen_predictions[final_text] = True
|
| 728 |
+
|
| 729 |
+
nbest.append(
|
| 730 |
+
_NbestPrediction(text=final_text, start_log_prob=pred.start_log_prob, end_log_prob=pred.end_log_prob)
|
| 731 |
+
)
|
| 732 |
+
|
| 733 |
+
# In very rare edge cases we could have no valid predictions. So we
|
| 734 |
+
# just create a nonce prediction in this case to avoid failure.
|
| 735 |
+
if not nbest:
|
| 736 |
+
nbest.append(_NbestPrediction(text="", start_log_prob=-1e6, end_log_prob=-1e6))
|
| 737 |
+
|
| 738 |
+
total_scores = []
|
| 739 |
+
best_non_null_entry = None
|
| 740 |
+
for entry in nbest:
|
| 741 |
+
total_scores.append(entry.start_log_prob + entry.end_log_prob)
|
| 742 |
+
if not best_non_null_entry:
|
| 743 |
+
best_non_null_entry = entry
|
| 744 |
+
|
| 745 |
+
probs = _compute_softmax(total_scores)
|
| 746 |
+
|
| 747 |
+
nbest_json = []
|
| 748 |
+
for i, entry in enumerate(nbest):
|
| 749 |
+
output = collections.OrderedDict()
|
| 750 |
+
output["text"] = entry.text
|
| 751 |
+
output["probability"] = probs[i]
|
| 752 |
+
output["start_log_prob"] = entry.start_log_prob
|
| 753 |
+
output["end_log_prob"] = entry.end_log_prob
|
| 754 |
+
nbest_json.append(output)
|
| 755 |
+
|
| 756 |
+
if len(nbest_json) < 1:
|
| 757 |
+
raise ValueError("No valid predictions")
|
| 758 |
+
if best_non_null_entry is None:
|
| 759 |
+
raise ValueError("No valid predictions")
|
| 760 |
+
|
| 761 |
+
score_diff = score_null
|
| 762 |
+
scores_diff_json[example.qas_id] = score_diff
|
| 763 |
+
# note(zhiliny): always predict best_non_null_entry
|
| 764 |
+
# and the evaluation script will search for the best threshold
|
| 765 |
+
all_predictions[example.qas_id] = best_non_null_entry.text
|
| 766 |
+
|
| 767 |
+
all_nbest_json[example.qas_id] = nbest_json
|
| 768 |
+
|
| 769 |
+
with open(output_prediction_file, "w") as writer:
|
| 770 |
+
writer.write(json.dumps(all_predictions, indent=4) + "\n")
|
| 771 |
+
|
| 772 |
+
with open(output_nbest_file, "w") as writer:
|
| 773 |
+
writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
|
| 774 |
+
|
| 775 |
+
if version_2_with_negative:
|
| 776 |
+
with open(output_null_log_odds_file, "w") as writer:
|
| 777 |
+
writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
|
| 778 |
+
|
| 779 |
+
return all_predictions
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels
|
| 16 |
+
from .squad import SquadExample, SquadFeatures, SquadV1Processor, SquadV2Processor, squad_convert_examples_to_features
|
| 17 |
+
from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor
|
| 18 |
+
from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (757 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/__pycache__/glue.cpython-310.pyc
ADDED
|
Binary file (17.7 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/__pycache__/squad.cpython-310.pyc
ADDED
|
Binary file (20.2 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (12.1 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/__pycache__/xnli.cpython-310.pyc
ADDED
|
Binary file (2.53 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/glue.py
ADDED
|
@@ -0,0 +1,643 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. 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 |
+
"""GLUE processors and helpers"""
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import warnings
|
| 20 |
+
from dataclasses import asdict
|
| 21 |
+
from enum import Enum
|
| 22 |
+
from typing import Optional, Union
|
| 23 |
+
|
| 24 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 25 |
+
from ...utils import is_tf_available, logging
|
| 26 |
+
from .utils import DataProcessor, InputExample, InputFeatures
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_tf_available():
|
| 30 |
+
import tensorflow as tf
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
DEPRECATION_WARNING = (
|
| 35 |
+
"This {0} will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets "
|
| 36 |
+
"library. You can have a look at this example script for pointers: "
|
| 37 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py"
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def glue_convert_examples_to_features(
|
| 42 |
+
examples: Union[list[InputExample], "tf.data.Dataset"],
|
| 43 |
+
tokenizer: PreTrainedTokenizer,
|
| 44 |
+
max_length: Optional[int] = None,
|
| 45 |
+
task=None,
|
| 46 |
+
label_list=None,
|
| 47 |
+
output_mode=None,
|
| 48 |
+
):
|
| 49 |
+
"""
|
| 50 |
+
Loads a data file into a list of `InputFeatures`
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
examples: List of `InputExamples` or `tf.data.Dataset` containing the examples.
|
| 54 |
+
tokenizer: Instance of a tokenizer that will tokenize the examples
|
| 55 |
+
max_length: Maximum example length. Defaults to the tokenizer's max_len
|
| 56 |
+
task: GLUE task
|
| 57 |
+
label_list: List of labels. Can be obtained from the processor using the `processor.get_labels()` method
|
| 58 |
+
output_mode: String indicating the output mode. Either `regression` or `classification`
|
| 59 |
+
|
| 60 |
+
Returns:
|
| 61 |
+
If the `examples` input is a `tf.data.Dataset`, will return a `tf.data.Dataset` containing the task-specific
|
| 62 |
+
features. If the input is a list of `InputExamples`, will return a list of task-specific `InputFeatures` which
|
| 63 |
+
can be fed to the model.
|
| 64 |
+
|
| 65 |
+
"""
|
| 66 |
+
warnings.warn(DEPRECATION_WARNING.format("function"), FutureWarning)
|
| 67 |
+
if is_tf_available() and isinstance(examples, tf.data.Dataset):
|
| 68 |
+
if task is None:
|
| 69 |
+
raise ValueError("When calling glue_convert_examples_to_features from TF, the task parameter is required.")
|
| 70 |
+
return _tf_glue_convert_examples_to_features(examples, tokenizer, max_length=max_length, task=task)
|
| 71 |
+
return _glue_convert_examples_to_features(
|
| 72 |
+
examples, tokenizer, max_length=max_length, task=task, label_list=label_list, output_mode=output_mode
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if is_tf_available():
|
| 77 |
+
|
| 78 |
+
def _tf_glue_convert_examples_to_features(
|
| 79 |
+
examples: tf.data.Dataset,
|
| 80 |
+
tokenizer: PreTrainedTokenizer,
|
| 81 |
+
task=str,
|
| 82 |
+
max_length: Optional[int] = None,
|
| 83 |
+
) -> tf.data.Dataset:
|
| 84 |
+
"""
|
| 85 |
+
Returns:
|
| 86 |
+
A `tf.data.Dataset` containing the task-specific features.
|
| 87 |
+
|
| 88 |
+
"""
|
| 89 |
+
processor = glue_processors[task]()
|
| 90 |
+
examples = [processor.tfds_map(processor.get_example_from_tensor_dict(example)) for example in examples]
|
| 91 |
+
features = glue_convert_examples_to_features(examples, tokenizer, max_length=max_length, task=task)
|
| 92 |
+
label_type = tf.float32 if task == "sts-b" else tf.int64
|
| 93 |
+
|
| 94 |
+
def gen():
|
| 95 |
+
for ex in features:
|
| 96 |
+
d = {k: v for k, v in asdict(ex).items() if v is not None}
|
| 97 |
+
label = d.pop("label")
|
| 98 |
+
yield (d, label)
|
| 99 |
+
|
| 100 |
+
input_names = tokenizer.model_input_names
|
| 101 |
+
|
| 102 |
+
return tf.data.Dataset.from_generator(
|
| 103 |
+
gen,
|
| 104 |
+
(dict.fromkeys(input_names, tf.int32), label_type),
|
| 105 |
+
({k: tf.TensorShape([None]) for k in input_names}, tf.TensorShape([])),
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _glue_convert_examples_to_features(
|
| 110 |
+
examples: list[InputExample],
|
| 111 |
+
tokenizer: PreTrainedTokenizer,
|
| 112 |
+
max_length: Optional[int] = None,
|
| 113 |
+
task=None,
|
| 114 |
+
label_list=None,
|
| 115 |
+
output_mode=None,
|
| 116 |
+
):
|
| 117 |
+
if max_length is None:
|
| 118 |
+
max_length = tokenizer.model_max_length
|
| 119 |
+
|
| 120 |
+
if task is not None:
|
| 121 |
+
processor = glue_processors[task]()
|
| 122 |
+
if label_list is None:
|
| 123 |
+
label_list = processor.get_labels()
|
| 124 |
+
logger.info(f"Using label list {label_list} for task {task}")
|
| 125 |
+
if output_mode is None:
|
| 126 |
+
output_mode = glue_output_modes[task]
|
| 127 |
+
logger.info(f"Using output mode {output_mode} for task {task}")
|
| 128 |
+
|
| 129 |
+
label_map = {label: i for i, label in enumerate(label_list)}
|
| 130 |
+
|
| 131 |
+
def label_from_example(example: InputExample) -> Union[int, float, None]:
|
| 132 |
+
if example.label is None:
|
| 133 |
+
return None
|
| 134 |
+
if output_mode == "classification":
|
| 135 |
+
return label_map[example.label]
|
| 136 |
+
elif output_mode == "regression":
|
| 137 |
+
return float(example.label)
|
| 138 |
+
raise KeyError(output_mode)
|
| 139 |
+
|
| 140 |
+
labels = [label_from_example(example) for example in examples]
|
| 141 |
+
|
| 142 |
+
batch_encoding = tokenizer(
|
| 143 |
+
[(example.text_a, example.text_b) for example in examples],
|
| 144 |
+
max_length=max_length,
|
| 145 |
+
padding="max_length",
|
| 146 |
+
truncation=True,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
features = []
|
| 150 |
+
for i in range(len(examples)):
|
| 151 |
+
inputs = {k: batch_encoding[k][i] for k in batch_encoding}
|
| 152 |
+
|
| 153 |
+
feature = InputFeatures(**inputs, label=labels[i])
|
| 154 |
+
features.append(feature)
|
| 155 |
+
|
| 156 |
+
for i, example in enumerate(examples[:5]):
|
| 157 |
+
logger.info("*** Example ***")
|
| 158 |
+
logger.info(f"guid: {example.guid}")
|
| 159 |
+
logger.info(f"features: {features[i]}")
|
| 160 |
+
|
| 161 |
+
return features
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class OutputMode(Enum):
|
| 165 |
+
classification = "classification"
|
| 166 |
+
regression = "regression"
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class MrpcProcessor(DataProcessor):
|
| 170 |
+
"""Processor for the MRPC data set (GLUE version)."""
|
| 171 |
+
|
| 172 |
+
def __init__(self, *args, **kwargs):
|
| 173 |
+
super().__init__(*args, **kwargs)
|
| 174 |
+
warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning)
|
| 175 |
+
|
| 176 |
+
def get_example_from_tensor_dict(self, tensor_dict):
|
| 177 |
+
"""See base class."""
|
| 178 |
+
return InputExample(
|
| 179 |
+
tensor_dict["idx"].numpy(),
|
| 180 |
+
tensor_dict["sentence1"].numpy().decode("utf-8"),
|
| 181 |
+
tensor_dict["sentence2"].numpy().decode("utf-8"),
|
| 182 |
+
str(tensor_dict["label"].numpy()),
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
def get_train_examples(self, data_dir):
|
| 186 |
+
"""See base class."""
|
| 187 |
+
logger.info(f"LOOKING AT {os.path.join(data_dir, 'train.tsv')}")
|
| 188 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
|
| 189 |
+
|
| 190 |
+
def get_dev_examples(self, data_dir):
|
| 191 |
+
"""See base class."""
|
| 192 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
|
| 193 |
+
|
| 194 |
+
def get_test_examples(self, data_dir):
|
| 195 |
+
"""See base class."""
|
| 196 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
|
| 197 |
+
|
| 198 |
+
def get_labels(self):
|
| 199 |
+
"""See base class."""
|
| 200 |
+
return ["0", "1"]
|
| 201 |
+
|
| 202 |
+
def _create_examples(self, lines, set_type):
|
| 203 |
+
"""Creates examples for the training, dev and test sets."""
|
| 204 |
+
examples = []
|
| 205 |
+
for i, line in enumerate(lines):
|
| 206 |
+
if i == 0:
|
| 207 |
+
continue
|
| 208 |
+
guid = f"{set_type}-{i}"
|
| 209 |
+
text_a = line[3]
|
| 210 |
+
text_b = line[4]
|
| 211 |
+
label = None if set_type == "test" else line[0]
|
| 212 |
+
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
|
| 213 |
+
return examples
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class MnliProcessor(DataProcessor):
|
| 217 |
+
"""Processor for the MultiNLI data set (GLUE version)."""
|
| 218 |
+
|
| 219 |
+
def __init__(self, *args, **kwargs):
|
| 220 |
+
super().__init__(*args, **kwargs)
|
| 221 |
+
warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning)
|
| 222 |
+
|
| 223 |
+
def get_example_from_tensor_dict(self, tensor_dict):
|
| 224 |
+
"""See base class."""
|
| 225 |
+
return InputExample(
|
| 226 |
+
tensor_dict["idx"].numpy(),
|
| 227 |
+
tensor_dict["premise"].numpy().decode("utf-8"),
|
| 228 |
+
tensor_dict["hypothesis"].numpy().decode("utf-8"),
|
| 229 |
+
str(tensor_dict["label"].numpy()),
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
def get_train_examples(self, data_dir):
|
| 233 |
+
"""See base class."""
|
| 234 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
|
| 235 |
+
|
| 236 |
+
def get_dev_examples(self, data_dir):
|
| 237 |
+
"""See base class."""
|
| 238 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")), "dev_matched")
|
| 239 |
+
|
| 240 |
+
def get_test_examples(self, data_dir):
|
| 241 |
+
"""See base class."""
|
| 242 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test_matched.tsv")), "test_matched")
|
| 243 |
+
|
| 244 |
+
def get_labels(self):
|
| 245 |
+
"""See base class."""
|
| 246 |
+
return ["contradiction", "entailment", "neutral"]
|
| 247 |
+
|
| 248 |
+
def _create_examples(self, lines, set_type):
|
| 249 |
+
"""Creates examples for the training, dev and test sets."""
|
| 250 |
+
examples = []
|
| 251 |
+
for i, line in enumerate(lines):
|
| 252 |
+
if i == 0:
|
| 253 |
+
continue
|
| 254 |
+
guid = f"{set_type}-{line[0]}"
|
| 255 |
+
text_a = line[8]
|
| 256 |
+
text_b = line[9]
|
| 257 |
+
label = None if set_type.startswith("test") else line[-1]
|
| 258 |
+
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
|
| 259 |
+
return examples
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class MnliMismatchedProcessor(MnliProcessor):
|
| 263 |
+
"""Processor for the MultiNLI Mismatched data set (GLUE version)."""
|
| 264 |
+
|
| 265 |
+
def __init__(self, *args, **kwargs):
|
| 266 |
+
super().__init__(*args, **kwargs)
|
| 267 |
+
warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning)
|
| 268 |
+
|
| 269 |
+
def get_dev_examples(self, data_dir):
|
| 270 |
+
"""See base class."""
|
| 271 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev_mismatched.tsv")), "dev_mismatched")
|
| 272 |
+
|
| 273 |
+
def get_test_examples(self, data_dir):
|
| 274 |
+
"""See base class."""
|
| 275 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test_mismatched.tsv")), "test_mismatched")
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class ColaProcessor(DataProcessor):
|
| 279 |
+
"""Processor for the CoLA data set (GLUE version)."""
|
| 280 |
+
|
| 281 |
+
def __init__(self, *args, **kwargs):
|
| 282 |
+
super().__init__(*args, **kwargs)
|
| 283 |
+
warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning)
|
| 284 |
+
|
| 285 |
+
def get_example_from_tensor_dict(self, tensor_dict):
|
| 286 |
+
"""See base class."""
|
| 287 |
+
return InputExample(
|
| 288 |
+
tensor_dict["idx"].numpy(),
|
| 289 |
+
tensor_dict["sentence"].numpy().decode("utf-8"),
|
| 290 |
+
None,
|
| 291 |
+
str(tensor_dict["label"].numpy()),
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
def get_train_examples(self, data_dir):
|
| 295 |
+
"""See base class."""
|
| 296 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
|
| 297 |
+
|
| 298 |
+
def get_dev_examples(self, data_dir):
|
| 299 |
+
"""See base class."""
|
| 300 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
|
| 301 |
+
|
| 302 |
+
def get_test_examples(self, data_dir):
|
| 303 |
+
"""See base class."""
|
| 304 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
|
| 305 |
+
|
| 306 |
+
def get_labels(self):
|
| 307 |
+
"""See base class."""
|
| 308 |
+
return ["0", "1"]
|
| 309 |
+
|
| 310 |
+
def _create_examples(self, lines, set_type):
|
| 311 |
+
"""Creates examples for the training, dev and test sets."""
|
| 312 |
+
test_mode = set_type == "test"
|
| 313 |
+
if test_mode:
|
| 314 |
+
lines = lines[1:]
|
| 315 |
+
text_index = 1 if test_mode else 3
|
| 316 |
+
examples = []
|
| 317 |
+
for i, line in enumerate(lines):
|
| 318 |
+
guid = f"{set_type}-{i}"
|
| 319 |
+
text_a = line[text_index]
|
| 320 |
+
label = None if test_mode else line[1]
|
| 321 |
+
examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label))
|
| 322 |
+
return examples
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
class Sst2Processor(DataProcessor):
|
| 326 |
+
"""Processor for the SST-2 data set (GLUE version)."""
|
| 327 |
+
|
| 328 |
+
def __init__(self, *args, **kwargs):
|
| 329 |
+
super().__init__(*args, **kwargs)
|
| 330 |
+
warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning)
|
| 331 |
+
|
| 332 |
+
def get_example_from_tensor_dict(self, tensor_dict):
|
| 333 |
+
"""See base class."""
|
| 334 |
+
return InputExample(
|
| 335 |
+
tensor_dict["idx"].numpy(),
|
| 336 |
+
tensor_dict["sentence"].numpy().decode("utf-8"),
|
| 337 |
+
None,
|
| 338 |
+
str(tensor_dict["label"].numpy()),
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
def get_train_examples(self, data_dir):
|
| 342 |
+
"""See base class."""
|
| 343 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
|
| 344 |
+
|
| 345 |
+
def get_dev_examples(self, data_dir):
|
| 346 |
+
"""See base class."""
|
| 347 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
|
| 348 |
+
|
| 349 |
+
def get_test_examples(self, data_dir):
|
| 350 |
+
"""See base class."""
|
| 351 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
|
| 352 |
+
|
| 353 |
+
def get_labels(self):
|
| 354 |
+
"""See base class."""
|
| 355 |
+
return ["0", "1"]
|
| 356 |
+
|
| 357 |
+
def _create_examples(self, lines, set_type):
|
| 358 |
+
"""Creates examples for the training, dev and test sets."""
|
| 359 |
+
examples = []
|
| 360 |
+
text_index = 1 if set_type == "test" else 0
|
| 361 |
+
for i, line in enumerate(lines):
|
| 362 |
+
if i == 0:
|
| 363 |
+
continue
|
| 364 |
+
guid = f"{set_type}-{i}"
|
| 365 |
+
text_a = line[text_index]
|
| 366 |
+
label = None if set_type == "test" else line[1]
|
| 367 |
+
examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label))
|
| 368 |
+
return examples
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class StsbProcessor(DataProcessor):
|
| 372 |
+
"""Processor for the STS-B data set (GLUE version)."""
|
| 373 |
+
|
| 374 |
+
def __init__(self, *args, **kwargs):
|
| 375 |
+
super().__init__(*args, **kwargs)
|
| 376 |
+
warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning)
|
| 377 |
+
|
| 378 |
+
def get_example_from_tensor_dict(self, tensor_dict):
|
| 379 |
+
"""See base class."""
|
| 380 |
+
return InputExample(
|
| 381 |
+
tensor_dict["idx"].numpy(),
|
| 382 |
+
tensor_dict["sentence1"].numpy().decode("utf-8"),
|
| 383 |
+
tensor_dict["sentence2"].numpy().decode("utf-8"),
|
| 384 |
+
str(tensor_dict["label"].numpy()),
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
def get_train_examples(self, data_dir):
|
| 388 |
+
"""See base class."""
|
| 389 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
|
| 390 |
+
|
| 391 |
+
def get_dev_examples(self, data_dir):
|
| 392 |
+
"""See base class."""
|
| 393 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
|
| 394 |
+
|
| 395 |
+
def get_test_examples(self, data_dir):
|
| 396 |
+
"""See base class."""
|
| 397 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
|
| 398 |
+
|
| 399 |
+
def get_labels(self):
|
| 400 |
+
"""See base class."""
|
| 401 |
+
return [None]
|
| 402 |
+
|
| 403 |
+
def _create_examples(self, lines, set_type):
|
| 404 |
+
"""Creates examples for the training, dev and test sets."""
|
| 405 |
+
examples = []
|
| 406 |
+
for i, line in enumerate(lines):
|
| 407 |
+
if i == 0:
|
| 408 |
+
continue
|
| 409 |
+
guid = f"{set_type}-{line[0]}"
|
| 410 |
+
text_a = line[7]
|
| 411 |
+
text_b = line[8]
|
| 412 |
+
label = None if set_type == "test" else line[-1]
|
| 413 |
+
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
|
| 414 |
+
return examples
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class QqpProcessor(DataProcessor):
|
| 418 |
+
"""Processor for the QQP data set (GLUE version)."""
|
| 419 |
+
|
| 420 |
+
def __init__(self, *args, **kwargs):
|
| 421 |
+
super().__init__(*args, **kwargs)
|
| 422 |
+
warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning)
|
| 423 |
+
|
| 424 |
+
def get_example_from_tensor_dict(self, tensor_dict):
|
| 425 |
+
"""See base class."""
|
| 426 |
+
return InputExample(
|
| 427 |
+
tensor_dict["idx"].numpy(),
|
| 428 |
+
tensor_dict["question1"].numpy().decode("utf-8"),
|
| 429 |
+
tensor_dict["question2"].numpy().decode("utf-8"),
|
| 430 |
+
str(tensor_dict["label"].numpy()),
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
def get_train_examples(self, data_dir):
|
| 434 |
+
"""See base class."""
|
| 435 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
|
| 436 |
+
|
| 437 |
+
def get_dev_examples(self, data_dir):
|
| 438 |
+
"""See base class."""
|
| 439 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
|
| 440 |
+
|
| 441 |
+
def get_test_examples(self, data_dir):
|
| 442 |
+
"""See base class."""
|
| 443 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
|
| 444 |
+
|
| 445 |
+
def get_labels(self):
|
| 446 |
+
"""See base class."""
|
| 447 |
+
return ["0", "1"]
|
| 448 |
+
|
| 449 |
+
def _create_examples(self, lines, set_type):
|
| 450 |
+
"""Creates examples for the training, dev and test sets."""
|
| 451 |
+
test_mode = set_type == "test"
|
| 452 |
+
q1_index = 1 if test_mode else 3
|
| 453 |
+
q2_index = 2 if test_mode else 4
|
| 454 |
+
examples = []
|
| 455 |
+
for i, line in enumerate(lines):
|
| 456 |
+
if i == 0:
|
| 457 |
+
continue
|
| 458 |
+
guid = f"{set_type}-{line[0]}"
|
| 459 |
+
try:
|
| 460 |
+
text_a = line[q1_index]
|
| 461 |
+
text_b = line[q2_index]
|
| 462 |
+
label = None if test_mode else line[5]
|
| 463 |
+
except IndexError:
|
| 464 |
+
continue
|
| 465 |
+
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
|
| 466 |
+
return examples
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
class QnliProcessor(DataProcessor):
|
| 470 |
+
"""Processor for the QNLI data set (GLUE version)."""
|
| 471 |
+
|
| 472 |
+
def __init__(self, *args, **kwargs):
|
| 473 |
+
super().__init__(*args, **kwargs)
|
| 474 |
+
warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning)
|
| 475 |
+
|
| 476 |
+
def get_example_from_tensor_dict(self, tensor_dict):
|
| 477 |
+
"""See base class."""
|
| 478 |
+
return InputExample(
|
| 479 |
+
tensor_dict["idx"].numpy(),
|
| 480 |
+
tensor_dict["question"].numpy().decode("utf-8"),
|
| 481 |
+
tensor_dict["sentence"].numpy().decode("utf-8"),
|
| 482 |
+
str(tensor_dict["label"].numpy()),
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
def get_train_examples(self, data_dir):
|
| 486 |
+
"""See base class."""
|
| 487 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
|
| 488 |
+
|
| 489 |
+
def get_dev_examples(self, data_dir):
|
| 490 |
+
"""See base class."""
|
| 491 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
|
| 492 |
+
|
| 493 |
+
def get_test_examples(self, data_dir):
|
| 494 |
+
"""See base class."""
|
| 495 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
|
| 496 |
+
|
| 497 |
+
def get_labels(self):
|
| 498 |
+
"""See base class."""
|
| 499 |
+
return ["entailment", "not_entailment"]
|
| 500 |
+
|
| 501 |
+
def _create_examples(self, lines, set_type):
|
| 502 |
+
"""Creates examples for the training, dev and test sets."""
|
| 503 |
+
examples = []
|
| 504 |
+
for i, line in enumerate(lines):
|
| 505 |
+
if i == 0:
|
| 506 |
+
continue
|
| 507 |
+
guid = f"{set_type}-{line[0]}"
|
| 508 |
+
text_a = line[1]
|
| 509 |
+
text_b = line[2]
|
| 510 |
+
label = None if set_type == "test" else line[-1]
|
| 511 |
+
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
|
| 512 |
+
return examples
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
class RteProcessor(DataProcessor):
|
| 516 |
+
"""Processor for the RTE data set (GLUE version)."""
|
| 517 |
+
|
| 518 |
+
def __init__(self, *args, **kwargs):
|
| 519 |
+
super().__init__(*args, **kwargs)
|
| 520 |
+
warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning)
|
| 521 |
+
|
| 522 |
+
def get_example_from_tensor_dict(self, tensor_dict):
|
| 523 |
+
"""See base class."""
|
| 524 |
+
return InputExample(
|
| 525 |
+
tensor_dict["idx"].numpy(),
|
| 526 |
+
tensor_dict["sentence1"].numpy().decode("utf-8"),
|
| 527 |
+
tensor_dict["sentence2"].numpy().decode("utf-8"),
|
| 528 |
+
str(tensor_dict["label"].numpy()),
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
def get_train_examples(self, data_dir):
|
| 532 |
+
"""See base class."""
|
| 533 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
|
| 534 |
+
|
| 535 |
+
def get_dev_examples(self, data_dir):
|
| 536 |
+
"""See base class."""
|
| 537 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
|
| 538 |
+
|
| 539 |
+
def get_test_examples(self, data_dir):
|
| 540 |
+
"""See base class."""
|
| 541 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
|
| 542 |
+
|
| 543 |
+
def get_labels(self):
|
| 544 |
+
"""See base class."""
|
| 545 |
+
return ["entailment", "not_entailment"]
|
| 546 |
+
|
| 547 |
+
def _create_examples(self, lines, set_type):
|
| 548 |
+
"""Creates examples for the training, dev and test sets."""
|
| 549 |
+
examples = []
|
| 550 |
+
for i, line in enumerate(lines):
|
| 551 |
+
if i == 0:
|
| 552 |
+
continue
|
| 553 |
+
guid = f"{set_type}-{line[0]}"
|
| 554 |
+
text_a = line[1]
|
| 555 |
+
text_b = line[2]
|
| 556 |
+
label = None if set_type == "test" else line[-1]
|
| 557 |
+
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
|
| 558 |
+
return examples
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
class WnliProcessor(DataProcessor):
|
| 562 |
+
"""Processor for the WNLI data set (GLUE version)."""
|
| 563 |
+
|
| 564 |
+
def __init__(self, *args, **kwargs):
|
| 565 |
+
super().__init__(*args, **kwargs)
|
| 566 |
+
warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning)
|
| 567 |
+
|
| 568 |
+
def get_example_from_tensor_dict(self, tensor_dict):
|
| 569 |
+
"""See base class."""
|
| 570 |
+
return InputExample(
|
| 571 |
+
tensor_dict["idx"].numpy(),
|
| 572 |
+
tensor_dict["sentence1"].numpy().decode("utf-8"),
|
| 573 |
+
tensor_dict["sentence2"].numpy().decode("utf-8"),
|
| 574 |
+
str(tensor_dict["label"].numpy()),
|
| 575 |
+
)
|
| 576 |
+
|
| 577 |
+
def get_train_examples(self, data_dir):
|
| 578 |
+
"""See base class."""
|
| 579 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
|
| 580 |
+
|
| 581 |
+
def get_dev_examples(self, data_dir):
|
| 582 |
+
"""See base class."""
|
| 583 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
|
| 584 |
+
|
| 585 |
+
def get_test_examples(self, data_dir):
|
| 586 |
+
"""See base class."""
|
| 587 |
+
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
|
| 588 |
+
|
| 589 |
+
def get_labels(self):
|
| 590 |
+
"""See base class."""
|
| 591 |
+
return ["0", "1"]
|
| 592 |
+
|
| 593 |
+
def _create_examples(self, lines, set_type):
|
| 594 |
+
"""Creates examples for the training, dev and test sets."""
|
| 595 |
+
examples = []
|
| 596 |
+
for i, line in enumerate(lines):
|
| 597 |
+
if i == 0:
|
| 598 |
+
continue
|
| 599 |
+
guid = f"{set_type}-{line[0]}"
|
| 600 |
+
text_a = line[1]
|
| 601 |
+
text_b = line[2]
|
| 602 |
+
label = None if set_type == "test" else line[-1]
|
| 603 |
+
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
|
| 604 |
+
return examples
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
glue_tasks_num_labels = {
|
| 608 |
+
"cola": 2,
|
| 609 |
+
"mnli": 3,
|
| 610 |
+
"mrpc": 2,
|
| 611 |
+
"sst-2": 2,
|
| 612 |
+
"sts-b": 1,
|
| 613 |
+
"qqp": 2,
|
| 614 |
+
"qnli": 2,
|
| 615 |
+
"rte": 2,
|
| 616 |
+
"wnli": 2,
|
| 617 |
+
}
|
| 618 |
+
|
| 619 |
+
glue_processors = {
|
| 620 |
+
"cola": ColaProcessor,
|
| 621 |
+
"mnli": MnliProcessor,
|
| 622 |
+
"mnli-mm": MnliMismatchedProcessor,
|
| 623 |
+
"mrpc": MrpcProcessor,
|
| 624 |
+
"sst-2": Sst2Processor,
|
| 625 |
+
"sts-b": StsbProcessor,
|
| 626 |
+
"qqp": QqpProcessor,
|
| 627 |
+
"qnli": QnliProcessor,
|
| 628 |
+
"rte": RteProcessor,
|
| 629 |
+
"wnli": WnliProcessor,
|
| 630 |
+
}
|
| 631 |
+
|
| 632 |
+
glue_output_modes = {
|
| 633 |
+
"cola": "classification",
|
| 634 |
+
"mnli": "classification",
|
| 635 |
+
"mnli-mm": "classification",
|
| 636 |
+
"mrpc": "classification",
|
| 637 |
+
"sst-2": "classification",
|
| 638 |
+
"sts-b": "regression",
|
| 639 |
+
"qqp": "classification",
|
| 640 |
+
"qnli": "classification",
|
| 641 |
+
"rte": "classification",
|
| 642 |
+
"wnli": "classification",
|
| 643 |
+
}
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/squad.py
ADDED
|
@@ -0,0 +1,845 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 (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 json
|
| 16 |
+
import os
|
| 17 |
+
from functools import partial
|
| 18 |
+
from multiprocessing import Pool, cpu_count
|
| 19 |
+
from multiprocessing.pool import ThreadPool
|
| 20 |
+
from typing import Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from tqdm import tqdm
|
| 24 |
+
|
| 25 |
+
from ...models.bert.tokenization_bert import whitespace_tokenize
|
| 26 |
+
from ...tokenization_utils_base import BatchEncoding, PreTrainedTokenizerBase, TruncationStrategy
|
| 27 |
+
from ...utils import is_tf_available, is_torch_available, is_torch_hpu_available, logging
|
| 28 |
+
from .utils import DataProcessor
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Store the tokenizers which insert 2 separators tokens
|
| 32 |
+
MULTI_SEP_TOKENS_TOKENIZERS_SET = {"roberta", "camembert", "bart", "mpnet"}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if is_torch_available():
|
| 36 |
+
import torch
|
| 37 |
+
from torch.utils.data import TensorDataset
|
| 38 |
+
|
| 39 |
+
if is_tf_available():
|
| 40 |
+
import tensorflow as tf
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text):
|
| 46 |
+
"""Returns tokenized answer spans that better match the annotated answer."""
|
| 47 |
+
tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))
|
| 48 |
+
|
| 49 |
+
for new_start in range(input_start, input_end + 1):
|
| 50 |
+
for new_end in range(input_end, new_start - 1, -1):
|
| 51 |
+
text_span = " ".join(doc_tokens[new_start : (new_end + 1)])
|
| 52 |
+
if text_span == tok_answer_text:
|
| 53 |
+
return (new_start, new_end)
|
| 54 |
+
|
| 55 |
+
return (input_start, input_end)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _check_is_max_context(doc_spans, cur_span_index, position):
|
| 59 |
+
"""Check if this is the 'max context' doc span for the token."""
|
| 60 |
+
best_score = None
|
| 61 |
+
best_span_index = None
|
| 62 |
+
for span_index, doc_span in enumerate(doc_spans):
|
| 63 |
+
end = doc_span.start + doc_span.length - 1
|
| 64 |
+
if position < doc_span.start:
|
| 65 |
+
continue
|
| 66 |
+
if position > end:
|
| 67 |
+
continue
|
| 68 |
+
num_left_context = position - doc_span.start
|
| 69 |
+
num_right_context = end - position
|
| 70 |
+
score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
|
| 71 |
+
if best_score is None or score > best_score:
|
| 72 |
+
best_score = score
|
| 73 |
+
best_span_index = span_index
|
| 74 |
+
|
| 75 |
+
return cur_span_index == best_span_index
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _new_check_is_max_context(doc_spans, cur_span_index, position):
|
| 79 |
+
"""Check if this is the 'max context' doc span for the token."""
|
| 80 |
+
# if len(doc_spans) == 1:
|
| 81 |
+
# return True
|
| 82 |
+
best_score = None
|
| 83 |
+
best_span_index = None
|
| 84 |
+
for span_index, doc_span in enumerate(doc_spans):
|
| 85 |
+
end = doc_span["start"] + doc_span["length"] - 1
|
| 86 |
+
if position < doc_span["start"]:
|
| 87 |
+
continue
|
| 88 |
+
if position > end:
|
| 89 |
+
continue
|
| 90 |
+
num_left_context = position - doc_span["start"]
|
| 91 |
+
num_right_context = end - position
|
| 92 |
+
score = min(num_left_context, num_right_context) + 0.01 * doc_span["length"]
|
| 93 |
+
if best_score is None or score > best_score:
|
| 94 |
+
best_score = score
|
| 95 |
+
best_span_index = span_index
|
| 96 |
+
|
| 97 |
+
return cur_span_index == best_span_index
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _is_whitespace(c):
|
| 101 |
+
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
|
| 102 |
+
return True
|
| 103 |
+
return False
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def squad_convert_example_to_features(
|
| 107 |
+
example, max_seq_length, doc_stride, max_query_length, padding_strategy, is_training
|
| 108 |
+
):
|
| 109 |
+
features = []
|
| 110 |
+
if is_training and not example.is_impossible:
|
| 111 |
+
# Get start and end position
|
| 112 |
+
start_position = example.start_position
|
| 113 |
+
end_position = example.end_position
|
| 114 |
+
|
| 115 |
+
# If the answer cannot be found in the text, then skip this example.
|
| 116 |
+
actual_text = " ".join(example.doc_tokens[start_position : (end_position + 1)])
|
| 117 |
+
cleaned_answer_text = " ".join(whitespace_tokenize(example.answer_text))
|
| 118 |
+
if actual_text.find(cleaned_answer_text) == -1:
|
| 119 |
+
logger.warning(f"Could not find answer: '{actual_text}' vs. '{cleaned_answer_text}'")
|
| 120 |
+
return []
|
| 121 |
+
|
| 122 |
+
tok_to_orig_index = []
|
| 123 |
+
orig_to_tok_index = []
|
| 124 |
+
all_doc_tokens = []
|
| 125 |
+
for i, token in enumerate(example.doc_tokens):
|
| 126 |
+
orig_to_tok_index.append(len(all_doc_tokens))
|
| 127 |
+
if tokenizer.__class__.__name__ in [
|
| 128 |
+
"RobertaTokenizer",
|
| 129 |
+
"LongformerTokenizer",
|
| 130 |
+
"BartTokenizer",
|
| 131 |
+
"RobertaTokenizerFast",
|
| 132 |
+
"LongformerTokenizerFast",
|
| 133 |
+
"BartTokenizerFast",
|
| 134 |
+
]:
|
| 135 |
+
sub_tokens = tokenizer.tokenize(token, add_prefix_space=True)
|
| 136 |
+
else:
|
| 137 |
+
sub_tokens = tokenizer.tokenize(token)
|
| 138 |
+
for sub_token in sub_tokens:
|
| 139 |
+
tok_to_orig_index.append(i)
|
| 140 |
+
all_doc_tokens.append(sub_token)
|
| 141 |
+
|
| 142 |
+
if is_training and not example.is_impossible:
|
| 143 |
+
tok_start_position = orig_to_tok_index[example.start_position]
|
| 144 |
+
if example.end_position < len(example.doc_tokens) - 1:
|
| 145 |
+
tok_end_position = orig_to_tok_index[example.end_position + 1] - 1
|
| 146 |
+
else:
|
| 147 |
+
tok_end_position = len(all_doc_tokens) - 1
|
| 148 |
+
|
| 149 |
+
(tok_start_position, tok_end_position) = _improve_answer_span(
|
| 150 |
+
all_doc_tokens, tok_start_position, tok_end_position, tokenizer, example.answer_text
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
spans = []
|
| 154 |
+
|
| 155 |
+
truncated_query = tokenizer.encode(
|
| 156 |
+
example.question_text, add_special_tokens=False, truncation=True, max_length=max_query_length
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
# Tokenizers who insert 2 SEP tokens in-between <context> & <question> need to have special handling
|
| 160 |
+
# in the way they compute mask of added tokens.
|
| 161 |
+
tokenizer_type = type(tokenizer).__name__.replace("Tokenizer", "").lower()
|
| 162 |
+
sequence_added_tokens = (
|
| 163 |
+
tokenizer.model_max_length - tokenizer.max_len_single_sentence + 1
|
| 164 |
+
if tokenizer_type in MULTI_SEP_TOKENS_TOKENIZERS_SET
|
| 165 |
+
else tokenizer.model_max_length - tokenizer.max_len_single_sentence
|
| 166 |
+
)
|
| 167 |
+
sequence_pair_added_tokens = tokenizer.model_max_length - tokenizer.max_len_sentences_pair
|
| 168 |
+
|
| 169 |
+
span_doc_tokens = all_doc_tokens
|
| 170 |
+
while len(spans) * doc_stride < len(all_doc_tokens):
|
| 171 |
+
# Define the side we want to truncate / pad and the text/pair sorting
|
| 172 |
+
if tokenizer.padding_side == "right":
|
| 173 |
+
texts = truncated_query
|
| 174 |
+
pairs = span_doc_tokens
|
| 175 |
+
truncation = TruncationStrategy.ONLY_SECOND.value
|
| 176 |
+
else:
|
| 177 |
+
texts = span_doc_tokens
|
| 178 |
+
pairs = truncated_query
|
| 179 |
+
truncation = TruncationStrategy.ONLY_FIRST.value
|
| 180 |
+
|
| 181 |
+
encoded_dict = tokenizer.encode_plus( # TODO(thom) update this logic
|
| 182 |
+
texts,
|
| 183 |
+
pairs,
|
| 184 |
+
truncation=truncation,
|
| 185 |
+
padding=padding_strategy,
|
| 186 |
+
max_length=max_seq_length,
|
| 187 |
+
return_overflowing_tokens=True,
|
| 188 |
+
stride=max_seq_length - doc_stride - len(truncated_query) - sequence_pair_added_tokens,
|
| 189 |
+
return_token_type_ids=True,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
paragraph_len = min(
|
| 193 |
+
len(all_doc_tokens) - len(spans) * doc_stride,
|
| 194 |
+
max_seq_length - len(truncated_query) - sequence_pair_added_tokens,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
if tokenizer.pad_token_id in encoded_dict["input_ids"]:
|
| 198 |
+
if tokenizer.padding_side == "right":
|
| 199 |
+
non_padded_ids = encoded_dict["input_ids"][: encoded_dict["input_ids"].index(tokenizer.pad_token_id)]
|
| 200 |
+
else:
|
| 201 |
+
last_padding_id_position = (
|
| 202 |
+
len(encoded_dict["input_ids"]) - 1 - encoded_dict["input_ids"][::-1].index(tokenizer.pad_token_id)
|
| 203 |
+
)
|
| 204 |
+
non_padded_ids = encoded_dict["input_ids"][last_padding_id_position + 1 :]
|
| 205 |
+
|
| 206 |
+
else:
|
| 207 |
+
non_padded_ids = encoded_dict["input_ids"]
|
| 208 |
+
|
| 209 |
+
tokens = tokenizer.convert_ids_to_tokens(non_padded_ids)
|
| 210 |
+
|
| 211 |
+
token_to_orig_map = {}
|
| 212 |
+
for i in range(paragraph_len):
|
| 213 |
+
index = len(truncated_query) + sequence_added_tokens + i if tokenizer.padding_side == "right" else i
|
| 214 |
+
token_to_orig_map[index] = tok_to_orig_index[len(spans) * doc_stride + i]
|
| 215 |
+
|
| 216 |
+
encoded_dict["paragraph_len"] = paragraph_len
|
| 217 |
+
encoded_dict["tokens"] = tokens
|
| 218 |
+
encoded_dict["token_to_orig_map"] = token_to_orig_map
|
| 219 |
+
encoded_dict["truncated_query_with_special_tokens_length"] = len(truncated_query) + sequence_added_tokens
|
| 220 |
+
encoded_dict["token_is_max_context"] = {}
|
| 221 |
+
encoded_dict["start"] = len(spans) * doc_stride
|
| 222 |
+
encoded_dict["length"] = paragraph_len
|
| 223 |
+
|
| 224 |
+
spans.append(encoded_dict)
|
| 225 |
+
|
| 226 |
+
if "overflowing_tokens" not in encoded_dict or (
|
| 227 |
+
"overflowing_tokens" in encoded_dict and len(encoded_dict["overflowing_tokens"]) == 0
|
| 228 |
+
):
|
| 229 |
+
break
|
| 230 |
+
span_doc_tokens = encoded_dict["overflowing_tokens"]
|
| 231 |
+
|
| 232 |
+
for doc_span_index in range(len(spans)):
|
| 233 |
+
for j in range(spans[doc_span_index]["paragraph_len"]):
|
| 234 |
+
is_max_context = _new_check_is_max_context(spans, doc_span_index, doc_span_index * doc_stride + j)
|
| 235 |
+
index = (
|
| 236 |
+
j
|
| 237 |
+
if tokenizer.padding_side == "left"
|
| 238 |
+
else spans[doc_span_index]["truncated_query_with_special_tokens_length"] + j
|
| 239 |
+
)
|
| 240 |
+
spans[doc_span_index]["token_is_max_context"][index] = is_max_context
|
| 241 |
+
|
| 242 |
+
for span in spans:
|
| 243 |
+
# Identify the position of the CLS token
|
| 244 |
+
cls_index = span["input_ids"].index(tokenizer.cls_token_id)
|
| 245 |
+
|
| 246 |
+
# p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer)
|
| 247 |
+
# Original TF implementation also keep the classification token (set to 0)
|
| 248 |
+
p_mask = np.ones_like(span["token_type_ids"])
|
| 249 |
+
if tokenizer.padding_side == "right":
|
| 250 |
+
p_mask[len(truncated_query) + sequence_added_tokens :] = 0
|
| 251 |
+
else:
|
| 252 |
+
p_mask[-len(span["tokens"]) : -(len(truncated_query) + sequence_added_tokens)] = 0
|
| 253 |
+
|
| 254 |
+
pad_token_indices = np.where(np.atleast_1d(span["input_ids"] == tokenizer.pad_token_id))
|
| 255 |
+
special_token_indices = np.asarray(
|
| 256 |
+
tokenizer.get_special_tokens_mask(span["input_ids"], already_has_special_tokens=True)
|
| 257 |
+
).nonzero()
|
| 258 |
+
|
| 259 |
+
p_mask[pad_token_indices] = 1
|
| 260 |
+
p_mask[special_token_indices] = 1
|
| 261 |
+
|
| 262 |
+
# Set the cls index to 0: the CLS index can be used for impossible answers
|
| 263 |
+
p_mask[cls_index] = 0
|
| 264 |
+
|
| 265 |
+
span_is_impossible = example.is_impossible
|
| 266 |
+
start_position = 0
|
| 267 |
+
end_position = 0
|
| 268 |
+
if is_training and not span_is_impossible:
|
| 269 |
+
# For training, if our document chunk does not contain an annotation
|
| 270 |
+
# we throw it out, since there is nothing to predict.
|
| 271 |
+
doc_start = span["start"]
|
| 272 |
+
doc_end = span["start"] + span["length"] - 1
|
| 273 |
+
out_of_span = False
|
| 274 |
+
|
| 275 |
+
if not (tok_start_position >= doc_start and tok_end_position <= doc_end):
|
| 276 |
+
out_of_span = True
|
| 277 |
+
|
| 278 |
+
if out_of_span:
|
| 279 |
+
start_position = cls_index
|
| 280 |
+
end_position = cls_index
|
| 281 |
+
span_is_impossible = True
|
| 282 |
+
else:
|
| 283 |
+
if tokenizer.padding_side == "left":
|
| 284 |
+
doc_offset = 0
|
| 285 |
+
else:
|
| 286 |
+
doc_offset = len(truncated_query) + sequence_added_tokens
|
| 287 |
+
|
| 288 |
+
start_position = tok_start_position - doc_start + doc_offset
|
| 289 |
+
end_position = tok_end_position - doc_start + doc_offset
|
| 290 |
+
features.append(
|
| 291 |
+
SquadFeatures(
|
| 292 |
+
span["input_ids"],
|
| 293 |
+
span["attention_mask"],
|
| 294 |
+
span["token_type_ids"],
|
| 295 |
+
cls_index,
|
| 296 |
+
p_mask.tolist(),
|
| 297 |
+
example_index=0, # Can not set unique_id and example_index here. They will be set after multiple processing.
|
| 298 |
+
unique_id=0,
|
| 299 |
+
paragraph_len=span["paragraph_len"],
|
| 300 |
+
token_is_max_context=span["token_is_max_context"],
|
| 301 |
+
tokens=span["tokens"],
|
| 302 |
+
token_to_orig_map=span["token_to_orig_map"],
|
| 303 |
+
start_position=start_position,
|
| 304 |
+
end_position=end_position,
|
| 305 |
+
is_impossible=span_is_impossible,
|
| 306 |
+
qas_id=example.qas_id,
|
| 307 |
+
)
|
| 308 |
+
)
|
| 309 |
+
return features
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def squad_convert_example_to_features_init(tokenizer_for_convert: PreTrainedTokenizerBase):
|
| 313 |
+
global tokenizer
|
| 314 |
+
tokenizer = tokenizer_for_convert
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def squad_convert_examples_to_features(
|
| 318 |
+
examples,
|
| 319 |
+
tokenizer,
|
| 320 |
+
max_seq_length,
|
| 321 |
+
doc_stride,
|
| 322 |
+
max_query_length,
|
| 323 |
+
is_training,
|
| 324 |
+
padding_strategy="max_length",
|
| 325 |
+
return_dataset=False,
|
| 326 |
+
threads=1,
|
| 327 |
+
tqdm_enabled=True,
|
| 328 |
+
):
|
| 329 |
+
"""
|
| 330 |
+
Converts a list of examples into a list of features that can be directly given as input to a model. It is
|
| 331 |
+
model-dependant and takes advantage of many of the tokenizer's features to create the model's inputs.
|
| 332 |
+
|
| 333 |
+
Args:
|
| 334 |
+
examples: list of [`~data.processors.squad.SquadExample`]
|
| 335 |
+
tokenizer: an instance of a child of [`PreTrainedTokenizer`]
|
| 336 |
+
max_seq_length: The maximum sequence length of the inputs.
|
| 337 |
+
doc_stride: The stride used when the context is too large and is split across several features.
|
| 338 |
+
max_query_length: The maximum length of the query.
|
| 339 |
+
is_training: whether to create features for model evaluation or model training.
|
| 340 |
+
padding_strategy: Default to "max_length". Which padding strategy to use
|
| 341 |
+
return_dataset: Default False. Either 'pt' or 'tf'.
|
| 342 |
+
if 'pt': returns a torch.data.TensorDataset, if 'tf': returns a tf.data.Dataset
|
| 343 |
+
threads: multiple processing threads.
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
Returns:
|
| 347 |
+
list of [`~data.processors.squad.SquadFeatures`]
|
| 348 |
+
|
| 349 |
+
Example:
|
| 350 |
+
|
| 351 |
+
```python
|
| 352 |
+
processor = SquadV2Processor()
|
| 353 |
+
examples = processor.get_dev_examples(data_dir)
|
| 354 |
+
|
| 355 |
+
features = squad_convert_examples_to_features(
|
| 356 |
+
examples=examples,
|
| 357 |
+
tokenizer=tokenizer,
|
| 358 |
+
max_seq_length=args.max_seq_length,
|
| 359 |
+
doc_stride=args.doc_stride,
|
| 360 |
+
max_query_length=args.max_query_length,
|
| 361 |
+
is_training=not evaluate,
|
| 362 |
+
)
|
| 363 |
+
```"""
|
| 364 |
+
|
| 365 |
+
threads = min(threads, cpu_count())
|
| 366 |
+
pool_cls = ThreadPool if is_torch_hpu_available() else Pool
|
| 367 |
+
with pool_cls(threads, initializer=squad_convert_example_to_features_init, initargs=(tokenizer,)) as p:
|
| 368 |
+
annotate_ = partial(
|
| 369 |
+
squad_convert_example_to_features,
|
| 370 |
+
max_seq_length=max_seq_length,
|
| 371 |
+
doc_stride=doc_stride,
|
| 372 |
+
max_query_length=max_query_length,
|
| 373 |
+
padding_strategy=padding_strategy,
|
| 374 |
+
is_training=is_training,
|
| 375 |
+
)
|
| 376 |
+
features = list(
|
| 377 |
+
tqdm(
|
| 378 |
+
p.imap(annotate_, examples, chunksize=32),
|
| 379 |
+
total=len(examples),
|
| 380 |
+
desc="convert squad examples to features",
|
| 381 |
+
disable=not tqdm_enabled,
|
| 382 |
+
)
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
new_features = []
|
| 386 |
+
unique_id = 1000000000
|
| 387 |
+
example_index = 0
|
| 388 |
+
for example_features in tqdm(
|
| 389 |
+
features, total=len(features), desc="add example index and unique id", disable=not tqdm_enabled
|
| 390 |
+
):
|
| 391 |
+
if not example_features:
|
| 392 |
+
continue
|
| 393 |
+
for example_feature in example_features:
|
| 394 |
+
example_feature.example_index = example_index
|
| 395 |
+
example_feature.unique_id = unique_id
|
| 396 |
+
new_features.append(example_feature)
|
| 397 |
+
unique_id += 1
|
| 398 |
+
example_index += 1
|
| 399 |
+
features = new_features
|
| 400 |
+
del new_features
|
| 401 |
+
if return_dataset == "pt":
|
| 402 |
+
if not is_torch_available():
|
| 403 |
+
raise RuntimeError("PyTorch must be installed to return a PyTorch dataset.")
|
| 404 |
+
|
| 405 |
+
# Convert to Tensors and build dataset
|
| 406 |
+
all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
|
| 407 |
+
all_attention_masks = torch.tensor([f.attention_mask for f in features], dtype=torch.long)
|
| 408 |
+
all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long)
|
| 409 |
+
all_cls_index = torch.tensor([f.cls_index for f in features], dtype=torch.long)
|
| 410 |
+
all_p_mask = torch.tensor([f.p_mask for f in features], dtype=torch.float)
|
| 411 |
+
all_is_impossible = torch.tensor([f.is_impossible for f in features], dtype=torch.float)
|
| 412 |
+
|
| 413 |
+
if not is_training:
|
| 414 |
+
all_feature_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
|
| 415 |
+
dataset = TensorDataset(
|
| 416 |
+
all_input_ids, all_attention_masks, all_token_type_ids, all_feature_index, all_cls_index, all_p_mask
|
| 417 |
+
)
|
| 418 |
+
else:
|
| 419 |
+
all_start_positions = torch.tensor([f.start_position for f in features], dtype=torch.long)
|
| 420 |
+
all_end_positions = torch.tensor([f.end_position for f in features], dtype=torch.long)
|
| 421 |
+
dataset = TensorDataset(
|
| 422 |
+
all_input_ids,
|
| 423 |
+
all_attention_masks,
|
| 424 |
+
all_token_type_ids,
|
| 425 |
+
all_start_positions,
|
| 426 |
+
all_end_positions,
|
| 427 |
+
all_cls_index,
|
| 428 |
+
all_p_mask,
|
| 429 |
+
all_is_impossible,
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
return features, dataset
|
| 433 |
+
elif return_dataset == "tf":
|
| 434 |
+
if not is_tf_available():
|
| 435 |
+
raise RuntimeError("TensorFlow must be installed to return a TensorFlow dataset.")
|
| 436 |
+
|
| 437 |
+
def gen():
|
| 438 |
+
for i, ex in enumerate(features):
|
| 439 |
+
if ex.token_type_ids is None:
|
| 440 |
+
yield (
|
| 441 |
+
{
|
| 442 |
+
"input_ids": ex.input_ids,
|
| 443 |
+
"attention_mask": ex.attention_mask,
|
| 444 |
+
"feature_index": i,
|
| 445 |
+
"qas_id": ex.qas_id,
|
| 446 |
+
},
|
| 447 |
+
{
|
| 448 |
+
"start_positions": ex.start_position,
|
| 449 |
+
"end_positions": ex.end_position,
|
| 450 |
+
"cls_index": ex.cls_index,
|
| 451 |
+
"p_mask": ex.p_mask,
|
| 452 |
+
"is_impossible": ex.is_impossible,
|
| 453 |
+
},
|
| 454 |
+
)
|
| 455 |
+
else:
|
| 456 |
+
yield (
|
| 457 |
+
{
|
| 458 |
+
"input_ids": ex.input_ids,
|
| 459 |
+
"attention_mask": ex.attention_mask,
|
| 460 |
+
"token_type_ids": ex.token_type_ids,
|
| 461 |
+
"feature_index": i,
|
| 462 |
+
"qas_id": ex.qas_id,
|
| 463 |
+
},
|
| 464 |
+
{
|
| 465 |
+
"start_positions": ex.start_position,
|
| 466 |
+
"end_positions": ex.end_position,
|
| 467 |
+
"cls_index": ex.cls_index,
|
| 468 |
+
"p_mask": ex.p_mask,
|
| 469 |
+
"is_impossible": ex.is_impossible,
|
| 470 |
+
},
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
# Why have we split the batch into a tuple? PyTorch just has a list of tensors.
|
| 474 |
+
if "token_type_ids" in tokenizer.model_input_names:
|
| 475 |
+
train_types = (
|
| 476 |
+
{
|
| 477 |
+
"input_ids": tf.int32,
|
| 478 |
+
"attention_mask": tf.int32,
|
| 479 |
+
"token_type_ids": tf.int32,
|
| 480 |
+
"feature_index": tf.int64,
|
| 481 |
+
"qas_id": tf.string,
|
| 482 |
+
},
|
| 483 |
+
{
|
| 484 |
+
"start_positions": tf.int64,
|
| 485 |
+
"end_positions": tf.int64,
|
| 486 |
+
"cls_index": tf.int64,
|
| 487 |
+
"p_mask": tf.int32,
|
| 488 |
+
"is_impossible": tf.int32,
|
| 489 |
+
},
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
train_shapes = (
|
| 493 |
+
{
|
| 494 |
+
"input_ids": tf.TensorShape([None]),
|
| 495 |
+
"attention_mask": tf.TensorShape([None]),
|
| 496 |
+
"token_type_ids": tf.TensorShape([None]),
|
| 497 |
+
"feature_index": tf.TensorShape([]),
|
| 498 |
+
"qas_id": tf.TensorShape([]),
|
| 499 |
+
},
|
| 500 |
+
{
|
| 501 |
+
"start_positions": tf.TensorShape([]),
|
| 502 |
+
"end_positions": tf.TensorShape([]),
|
| 503 |
+
"cls_index": tf.TensorShape([]),
|
| 504 |
+
"p_mask": tf.TensorShape([None]),
|
| 505 |
+
"is_impossible": tf.TensorShape([]),
|
| 506 |
+
},
|
| 507 |
+
)
|
| 508 |
+
else:
|
| 509 |
+
train_types = (
|
| 510 |
+
{"input_ids": tf.int32, "attention_mask": tf.int32, "feature_index": tf.int64, "qas_id": tf.string},
|
| 511 |
+
{
|
| 512 |
+
"start_positions": tf.int64,
|
| 513 |
+
"end_positions": tf.int64,
|
| 514 |
+
"cls_index": tf.int64,
|
| 515 |
+
"p_mask": tf.int32,
|
| 516 |
+
"is_impossible": tf.int32,
|
| 517 |
+
},
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
train_shapes = (
|
| 521 |
+
{
|
| 522 |
+
"input_ids": tf.TensorShape([None]),
|
| 523 |
+
"attention_mask": tf.TensorShape([None]),
|
| 524 |
+
"feature_index": tf.TensorShape([]),
|
| 525 |
+
"qas_id": tf.TensorShape([]),
|
| 526 |
+
},
|
| 527 |
+
{
|
| 528 |
+
"start_positions": tf.TensorShape([]),
|
| 529 |
+
"end_positions": tf.TensorShape([]),
|
| 530 |
+
"cls_index": tf.TensorShape([]),
|
| 531 |
+
"p_mask": tf.TensorShape([None]),
|
| 532 |
+
"is_impossible": tf.TensorShape([]),
|
| 533 |
+
},
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
return tf.data.Dataset.from_generator(gen, train_types, train_shapes)
|
| 537 |
+
else:
|
| 538 |
+
return features
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
class SquadProcessor(DataProcessor):
|
| 542 |
+
"""
|
| 543 |
+
Processor for the SQuAD data set. overridden by SquadV1Processor and SquadV2Processor, used by the version 1.1 and
|
| 544 |
+
version 2.0 of SQuAD, respectively.
|
| 545 |
+
"""
|
| 546 |
+
|
| 547 |
+
train_file = None
|
| 548 |
+
dev_file = None
|
| 549 |
+
|
| 550 |
+
def _get_example_from_tensor_dict(self, tensor_dict, evaluate=False):
|
| 551 |
+
if not evaluate:
|
| 552 |
+
answer = tensor_dict["answers"]["text"][0].numpy().decode("utf-8")
|
| 553 |
+
answer_start = tensor_dict["answers"]["answer_start"][0].numpy()
|
| 554 |
+
answers = []
|
| 555 |
+
else:
|
| 556 |
+
answers = [
|
| 557 |
+
{"answer_start": start.numpy(), "text": text.numpy().decode("utf-8")}
|
| 558 |
+
for start, text in zip(tensor_dict["answers"]["answer_start"], tensor_dict["answers"]["text"])
|
| 559 |
+
]
|
| 560 |
+
|
| 561 |
+
answer = None
|
| 562 |
+
answer_start = None
|
| 563 |
+
|
| 564 |
+
return SquadExample(
|
| 565 |
+
qas_id=tensor_dict["id"].numpy().decode("utf-8"),
|
| 566 |
+
question_text=tensor_dict["question"].numpy().decode("utf-8"),
|
| 567 |
+
context_text=tensor_dict["context"].numpy().decode("utf-8"),
|
| 568 |
+
answer_text=answer,
|
| 569 |
+
start_position_character=answer_start,
|
| 570 |
+
title=tensor_dict["title"].numpy().decode("utf-8"),
|
| 571 |
+
answers=answers,
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
def get_examples_from_dataset(self, dataset, evaluate=False):
|
| 575 |
+
"""
|
| 576 |
+
Creates a list of [`~data.processors.squad.SquadExample`] using a TFDS dataset.
|
| 577 |
+
|
| 578 |
+
Args:
|
| 579 |
+
dataset: The tfds dataset loaded from *tensorflow_datasets.load("squad")*
|
| 580 |
+
evaluate: Boolean specifying if in evaluation mode or in training mode
|
| 581 |
+
|
| 582 |
+
Returns:
|
| 583 |
+
List of SquadExample
|
| 584 |
+
|
| 585 |
+
Examples:
|
| 586 |
+
|
| 587 |
+
```python
|
| 588 |
+
>>> import tensorflow_datasets as tfds
|
| 589 |
+
|
| 590 |
+
>>> dataset = tfds.load("squad")
|
| 591 |
+
|
| 592 |
+
>>> training_examples = get_examples_from_dataset(dataset, evaluate=False)
|
| 593 |
+
>>> evaluation_examples = get_examples_from_dataset(dataset, evaluate=True)
|
| 594 |
+
```"""
|
| 595 |
+
|
| 596 |
+
if evaluate:
|
| 597 |
+
dataset = dataset["validation"]
|
| 598 |
+
else:
|
| 599 |
+
dataset = dataset["train"]
|
| 600 |
+
|
| 601 |
+
examples = []
|
| 602 |
+
for tensor_dict in tqdm(dataset):
|
| 603 |
+
examples.append(self._get_example_from_tensor_dict(tensor_dict, evaluate=evaluate))
|
| 604 |
+
|
| 605 |
+
return examples
|
| 606 |
+
|
| 607 |
+
def get_train_examples(self, data_dir, filename=None):
|
| 608 |
+
"""
|
| 609 |
+
Returns the training examples from the data directory.
|
| 610 |
+
|
| 611 |
+
Args:
|
| 612 |
+
data_dir: Directory containing the data files used for training and evaluating.
|
| 613 |
+
filename: None by default, specify this if the training file has a different name than the original one
|
| 614 |
+
which is `train-v1.1.json` and `train-v2.0.json` for squad versions 1.1 and 2.0 respectively.
|
| 615 |
+
|
| 616 |
+
"""
|
| 617 |
+
if data_dir is None:
|
| 618 |
+
data_dir = ""
|
| 619 |
+
|
| 620 |
+
if self.train_file is None:
|
| 621 |
+
raise ValueError("SquadProcessor should be instantiated via SquadV1Processor or SquadV2Processor")
|
| 622 |
+
|
| 623 |
+
with open(
|
| 624 |
+
os.path.join(data_dir, self.train_file if filename is None else filename), "r", encoding="utf-8"
|
| 625 |
+
) as reader:
|
| 626 |
+
input_data = json.load(reader)["data"]
|
| 627 |
+
return self._create_examples(input_data, "train")
|
| 628 |
+
|
| 629 |
+
def get_dev_examples(self, data_dir, filename=None):
|
| 630 |
+
"""
|
| 631 |
+
Returns the evaluation example from the data directory.
|
| 632 |
+
|
| 633 |
+
Args:
|
| 634 |
+
data_dir: Directory containing the data files used for training and evaluating.
|
| 635 |
+
filename: None by default, specify this if the evaluation file has a different name than the original one
|
| 636 |
+
which is `dev-v1.1.json` and `dev-v2.0.json` for squad versions 1.1 and 2.0 respectively.
|
| 637 |
+
"""
|
| 638 |
+
if data_dir is None:
|
| 639 |
+
data_dir = ""
|
| 640 |
+
|
| 641 |
+
if self.dev_file is None:
|
| 642 |
+
raise ValueError("SquadProcessor should be instantiated via SquadV1Processor or SquadV2Processor")
|
| 643 |
+
|
| 644 |
+
with open(
|
| 645 |
+
os.path.join(data_dir, self.dev_file if filename is None else filename), "r", encoding="utf-8"
|
| 646 |
+
) as reader:
|
| 647 |
+
input_data = json.load(reader)["data"]
|
| 648 |
+
return self._create_examples(input_data, "dev")
|
| 649 |
+
|
| 650 |
+
def _create_examples(self, input_data, set_type):
|
| 651 |
+
is_training = set_type == "train"
|
| 652 |
+
examples = []
|
| 653 |
+
for entry in tqdm(input_data):
|
| 654 |
+
title = entry["title"]
|
| 655 |
+
for paragraph in entry["paragraphs"]:
|
| 656 |
+
context_text = paragraph["context"]
|
| 657 |
+
for qa in paragraph["qas"]:
|
| 658 |
+
qas_id = qa["id"]
|
| 659 |
+
question_text = qa["question"]
|
| 660 |
+
start_position_character = None
|
| 661 |
+
answer_text = None
|
| 662 |
+
answers = []
|
| 663 |
+
|
| 664 |
+
is_impossible = qa.get("is_impossible", False)
|
| 665 |
+
if not is_impossible:
|
| 666 |
+
if is_training:
|
| 667 |
+
answer = qa["answers"][0]
|
| 668 |
+
answer_text = answer["text"]
|
| 669 |
+
start_position_character = answer["answer_start"]
|
| 670 |
+
else:
|
| 671 |
+
answers = qa["answers"]
|
| 672 |
+
|
| 673 |
+
example = SquadExample(
|
| 674 |
+
qas_id=qas_id,
|
| 675 |
+
question_text=question_text,
|
| 676 |
+
context_text=context_text,
|
| 677 |
+
answer_text=answer_text,
|
| 678 |
+
start_position_character=start_position_character,
|
| 679 |
+
title=title,
|
| 680 |
+
is_impossible=is_impossible,
|
| 681 |
+
answers=answers,
|
| 682 |
+
)
|
| 683 |
+
examples.append(example)
|
| 684 |
+
return examples
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
class SquadV1Processor(SquadProcessor):
|
| 688 |
+
train_file = "train-v1.1.json"
|
| 689 |
+
dev_file = "dev-v1.1.json"
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
class SquadV2Processor(SquadProcessor):
|
| 693 |
+
train_file = "train-v2.0.json"
|
| 694 |
+
dev_file = "dev-v2.0.json"
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
class SquadExample:
|
| 698 |
+
"""
|
| 699 |
+
A single training/test example for the Squad dataset, as loaded from disk.
|
| 700 |
+
|
| 701 |
+
Args:
|
| 702 |
+
qas_id: The example's unique identifier
|
| 703 |
+
question_text: The question string
|
| 704 |
+
context_text: The context string
|
| 705 |
+
answer_text: The answer string
|
| 706 |
+
start_position_character: The character position of the start of the answer
|
| 707 |
+
title: The title of the example
|
| 708 |
+
answers: None by default, this is used during evaluation. Holds answers as well as their start positions.
|
| 709 |
+
is_impossible: False by default, set to True if the example has no possible answer.
|
| 710 |
+
"""
|
| 711 |
+
|
| 712 |
+
def __init__(
|
| 713 |
+
self,
|
| 714 |
+
qas_id,
|
| 715 |
+
question_text,
|
| 716 |
+
context_text,
|
| 717 |
+
answer_text,
|
| 718 |
+
start_position_character,
|
| 719 |
+
title,
|
| 720 |
+
answers=[],
|
| 721 |
+
is_impossible=False,
|
| 722 |
+
):
|
| 723 |
+
self.qas_id = qas_id
|
| 724 |
+
self.question_text = question_text
|
| 725 |
+
self.context_text = context_text
|
| 726 |
+
self.answer_text = answer_text
|
| 727 |
+
self.title = title
|
| 728 |
+
self.is_impossible = is_impossible
|
| 729 |
+
self.answers = answers
|
| 730 |
+
|
| 731 |
+
self.start_position, self.end_position = 0, 0
|
| 732 |
+
|
| 733 |
+
doc_tokens = []
|
| 734 |
+
char_to_word_offset = []
|
| 735 |
+
prev_is_whitespace = True
|
| 736 |
+
|
| 737 |
+
# Split on whitespace so that different tokens may be attributed to their original position.
|
| 738 |
+
for c in self.context_text:
|
| 739 |
+
if _is_whitespace(c):
|
| 740 |
+
prev_is_whitespace = True
|
| 741 |
+
else:
|
| 742 |
+
if prev_is_whitespace:
|
| 743 |
+
doc_tokens.append(c)
|
| 744 |
+
else:
|
| 745 |
+
doc_tokens[-1] += c
|
| 746 |
+
prev_is_whitespace = False
|
| 747 |
+
char_to_word_offset.append(len(doc_tokens) - 1)
|
| 748 |
+
|
| 749 |
+
self.doc_tokens = doc_tokens
|
| 750 |
+
self.char_to_word_offset = char_to_word_offset
|
| 751 |
+
|
| 752 |
+
# Start and end positions only has a value during evaluation.
|
| 753 |
+
if start_position_character is not None and not is_impossible:
|
| 754 |
+
self.start_position = char_to_word_offset[start_position_character]
|
| 755 |
+
self.end_position = char_to_word_offset[
|
| 756 |
+
min(start_position_character + len(answer_text) - 1, len(char_to_word_offset) - 1)
|
| 757 |
+
]
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
class SquadFeatures:
|
| 761 |
+
"""
|
| 762 |
+
Single squad example features to be fed to a model. Those features are model-specific and can be crafted from
|
| 763 |
+
[`~data.processors.squad.SquadExample`] using the
|
| 764 |
+
:method:*~transformers.data.processors.squad.squad_convert_examples_to_features* method.
|
| 765 |
+
|
| 766 |
+
Args:
|
| 767 |
+
input_ids: Indices of input sequence tokens in the vocabulary.
|
| 768 |
+
attention_mask: Mask to avoid performing attention on padding token indices.
|
| 769 |
+
token_type_ids: Segment token indices to indicate first and second portions of the inputs.
|
| 770 |
+
cls_index: the index of the CLS token.
|
| 771 |
+
p_mask: Mask identifying tokens that can be answers vs. tokens that cannot.
|
| 772 |
+
Mask with 1 for tokens than cannot be in the answer and 0 for token that can be in an answer
|
| 773 |
+
example_index: the index of the example
|
| 774 |
+
unique_id: The unique Feature identifier
|
| 775 |
+
paragraph_len: The length of the context
|
| 776 |
+
token_is_max_context:
|
| 777 |
+
List of booleans identifying which tokens have their maximum context in this feature object. If a token
|
| 778 |
+
does not have their maximum context in this feature object, it means that another feature object has more
|
| 779 |
+
information related to that token and should be prioritized over this feature for that token.
|
| 780 |
+
tokens: list of tokens corresponding to the input ids
|
| 781 |
+
token_to_orig_map: mapping between the tokens and the original text, needed in order to identify the answer.
|
| 782 |
+
start_position: start of the answer token index
|
| 783 |
+
end_position: end of the answer token index
|
| 784 |
+
encoding: optionally store the BatchEncoding with the fast-tokenizer alignment methods.
|
| 785 |
+
"""
|
| 786 |
+
|
| 787 |
+
def __init__(
|
| 788 |
+
self,
|
| 789 |
+
input_ids,
|
| 790 |
+
attention_mask,
|
| 791 |
+
token_type_ids,
|
| 792 |
+
cls_index,
|
| 793 |
+
p_mask,
|
| 794 |
+
example_index,
|
| 795 |
+
unique_id,
|
| 796 |
+
paragraph_len,
|
| 797 |
+
token_is_max_context,
|
| 798 |
+
tokens,
|
| 799 |
+
token_to_orig_map,
|
| 800 |
+
start_position,
|
| 801 |
+
end_position,
|
| 802 |
+
is_impossible,
|
| 803 |
+
qas_id: Optional[str] = None,
|
| 804 |
+
encoding: Optional[BatchEncoding] = None,
|
| 805 |
+
):
|
| 806 |
+
self.input_ids = input_ids
|
| 807 |
+
self.attention_mask = attention_mask
|
| 808 |
+
self.token_type_ids = token_type_ids
|
| 809 |
+
self.cls_index = cls_index
|
| 810 |
+
self.p_mask = p_mask
|
| 811 |
+
|
| 812 |
+
self.example_index = example_index
|
| 813 |
+
self.unique_id = unique_id
|
| 814 |
+
self.paragraph_len = paragraph_len
|
| 815 |
+
self.token_is_max_context = token_is_max_context
|
| 816 |
+
self.tokens = tokens
|
| 817 |
+
self.token_to_orig_map = token_to_orig_map
|
| 818 |
+
|
| 819 |
+
self.start_position = start_position
|
| 820 |
+
self.end_position = end_position
|
| 821 |
+
self.is_impossible = is_impossible
|
| 822 |
+
self.qas_id = qas_id
|
| 823 |
+
|
| 824 |
+
self.encoding = encoding
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
class SquadResult:
|
| 828 |
+
"""
|
| 829 |
+
Constructs a SquadResult which can be used to evaluate a model's output on the SQuAD dataset.
|
| 830 |
+
|
| 831 |
+
Args:
|
| 832 |
+
unique_id: The unique identifier corresponding to that example.
|
| 833 |
+
start_logits: The logits corresponding to the start of the answer
|
| 834 |
+
end_logits: The logits corresponding to the end of the answer
|
| 835 |
+
"""
|
| 836 |
+
|
| 837 |
+
def __init__(self, unique_id, start_logits, end_logits, start_top_index=None, end_top_index=None, cls_logits=None):
|
| 838 |
+
self.start_logits = start_logits
|
| 839 |
+
self.end_logits = end_logits
|
| 840 |
+
self.unique_id = unique_id
|
| 841 |
+
|
| 842 |
+
if start_top_index:
|
| 843 |
+
self.start_top_index = start_top_index
|
| 844 |
+
self.end_top_index = end_top_index
|
| 845 |
+
self.cls_logits = cls_logits
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/utils.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. 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 |
+
import csv
|
| 18 |
+
import dataclasses
|
| 19 |
+
import json
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from typing import Optional, Union
|
| 22 |
+
|
| 23 |
+
from ...utils import is_tf_available, is_torch_available, logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class InputExample:
|
| 31 |
+
"""
|
| 32 |
+
A single training/test example for simple sequence classification.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
guid: Unique id for the example.
|
| 36 |
+
text_a: string. The untokenized text of the first sequence. For single
|
| 37 |
+
sequence tasks, only this sequence must be specified.
|
| 38 |
+
text_b: (Optional) string. The untokenized text of the second sequence.
|
| 39 |
+
Only must be specified for sequence pair tasks.
|
| 40 |
+
label: (Optional) string. The label of the example. This should be
|
| 41 |
+
specified for train and dev examples, but not for test examples.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
guid: str
|
| 45 |
+
text_a: str
|
| 46 |
+
text_b: Optional[str] = None
|
| 47 |
+
label: Optional[str] = None
|
| 48 |
+
|
| 49 |
+
def to_json_string(self):
|
| 50 |
+
"""Serializes this instance to a JSON string."""
|
| 51 |
+
return json.dumps(dataclasses.asdict(self), indent=2) + "\n"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@dataclass(frozen=True)
|
| 55 |
+
class InputFeatures:
|
| 56 |
+
"""
|
| 57 |
+
A single set of features of data. Property names are the same names as the corresponding inputs to a model.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
input_ids: Indices of input sequence tokens in the vocabulary.
|
| 61 |
+
attention_mask: Mask to avoid performing attention on padding token indices.
|
| 62 |
+
Mask values selected in `[0, 1]`: Usually `1` for tokens that are NOT MASKED, `0` for MASKED (padded)
|
| 63 |
+
tokens.
|
| 64 |
+
token_type_ids: (Optional) Segment token indices to indicate first and second
|
| 65 |
+
portions of the inputs. Only some models use them.
|
| 66 |
+
label: (Optional) Label corresponding to the input. Int for classification problems,
|
| 67 |
+
float for regression problems.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
input_ids: list[int]
|
| 71 |
+
attention_mask: Optional[list[int]] = None
|
| 72 |
+
token_type_ids: Optional[list[int]] = None
|
| 73 |
+
label: Optional[Union[int, float]] = None
|
| 74 |
+
|
| 75 |
+
def to_json_string(self):
|
| 76 |
+
"""Serializes this instance to a JSON string."""
|
| 77 |
+
return json.dumps(dataclasses.asdict(self)) + "\n"
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class DataProcessor:
|
| 81 |
+
"""Base class for data converters for sequence classification data sets."""
|
| 82 |
+
|
| 83 |
+
def get_example_from_tensor_dict(self, tensor_dict):
|
| 84 |
+
"""
|
| 85 |
+
Gets an example from a dict with tensorflow tensors.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
tensor_dict: Keys and values should match the corresponding Glue
|
| 89 |
+
tensorflow_dataset examples.
|
| 90 |
+
"""
|
| 91 |
+
raise NotImplementedError()
|
| 92 |
+
|
| 93 |
+
def get_train_examples(self, data_dir):
|
| 94 |
+
"""Gets a collection of [`InputExample`] for the train set."""
|
| 95 |
+
raise NotImplementedError()
|
| 96 |
+
|
| 97 |
+
def get_dev_examples(self, data_dir):
|
| 98 |
+
"""Gets a collection of [`InputExample`] for the dev set."""
|
| 99 |
+
raise NotImplementedError()
|
| 100 |
+
|
| 101 |
+
def get_test_examples(self, data_dir):
|
| 102 |
+
"""Gets a collection of [`InputExample`] for the test set."""
|
| 103 |
+
raise NotImplementedError()
|
| 104 |
+
|
| 105 |
+
def get_labels(self):
|
| 106 |
+
"""Gets the list of labels for this data set."""
|
| 107 |
+
raise NotImplementedError()
|
| 108 |
+
|
| 109 |
+
def tfds_map(self, example):
|
| 110 |
+
"""
|
| 111 |
+
Some tensorflow_datasets datasets are not formatted the same way the GLUE datasets are. This method converts
|
| 112 |
+
examples to the correct format.
|
| 113 |
+
"""
|
| 114 |
+
if len(self.get_labels()) > 1:
|
| 115 |
+
example.label = self.get_labels()[int(example.label)]
|
| 116 |
+
return example
|
| 117 |
+
|
| 118 |
+
@classmethod
|
| 119 |
+
def _read_tsv(cls, input_file, quotechar=None):
|
| 120 |
+
"""Reads a tab separated value file."""
|
| 121 |
+
with open(input_file, "r", encoding="utf-8-sig") as f:
|
| 122 |
+
return list(csv.reader(f, delimiter="\t", quotechar=quotechar))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class SingleSentenceClassificationProcessor(DataProcessor):
|
| 126 |
+
"""Generic processor for a single sentence classification data set."""
|
| 127 |
+
|
| 128 |
+
def __init__(self, labels=None, examples=None, mode="classification", verbose=False):
|
| 129 |
+
self.labels = [] if labels is None else labels
|
| 130 |
+
self.examples = [] if examples is None else examples
|
| 131 |
+
self.mode = mode
|
| 132 |
+
self.verbose = verbose
|
| 133 |
+
|
| 134 |
+
def __len__(self):
|
| 135 |
+
return len(self.examples)
|
| 136 |
+
|
| 137 |
+
def __getitem__(self, idx):
|
| 138 |
+
if isinstance(idx, slice):
|
| 139 |
+
return SingleSentenceClassificationProcessor(labels=self.labels, examples=self.examples[idx])
|
| 140 |
+
return self.examples[idx]
|
| 141 |
+
|
| 142 |
+
@classmethod
|
| 143 |
+
def create_from_csv(
|
| 144 |
+
cls, file_name, split_name="", column_label=0, column_text=1, column_id=None, skip_first_row=False, **kwargs
|
| 145 |
+
):
|
| 146 |
+
processor = cls(**kwargs)
|
| 147 |
+
processor.add_examples_from_csv(
|
| 148 |
+
file_name,
|
| 149 |
+
split_name=split_name,
|
| 150 |
+
column_label=column_label,
|
| 151 |
+
column_text=column_text,
|
| 152 |
+
column_id=column_id,
|
| 153 |
+
skip_first_row=skip_first_row,
|
| 154 |
+
overwrite_labels=True,
|
| 155 |
+
overwrite_examples=True,
|
| 156 |
+
)
|
| 157 |
+
return processor
|
| 158 |
+
|
| 159 |
+
@classmethod
|
| 160 |
+
def create_from_examples(cls, texts_or_text_and_labels, labels=None, **kwargs):
|
| 161 |
+
processor = cls(**kwargs)
|
| 162 |
+
processor.add_examples(texts_or_text_and_labels, labels=labels)
|
| 163 |
+
return processor
|
| 164 |
+
|
| 165 |
+
def add_examples_from_csv(
|
| 166 |
+
self,
|
| 167 |
+
file_name,
|
| 168 |
+
split_name="",
|
| 169 |
+
column_label=0,
|
| 170 |
+
column_text=1,
|
| 171 |
+
column_id=None,
|
| 172 |
+
skip_first_row=False,
|
| 173 |
+
overwrite_labels=False,
|
| 174 |
+
overwrite_examples=False,
|
| 175 |
+
):
|
| 176 |
+
lines = self._read_tsv(file_name)
|
| 177 |
+
if skip_first_row:
|
| 178 |
+
lines = lines[1:]
|
| 179 |
+
texts = []
|
| 180 |
+
labels = []
|
| 181 |
+
ids = []
|
| 182 |
+
for i, line in enumerate(lines):
|
| 183 |
+
texts.append(line[column_text])
|
| 184 |
+
labels.append(line[column_label])
|
| 185 |
+
if column_id is not None:
|
| 186 |
+
ids.append(line[column_id])
|
| 187 |
+
else:
|
| 188 |
+
guid = f"{split_name}-{i}" if split_name else str(i)
|
| 189 |
+
ids.append(guid)
|
| 190 |
+
|
| 191 |
+
return self.add_examples(
|
| 192 |
+
texts, labels, ids, overwrite_labels=overwrite_labels, overwrite_examples=overwrite_examples
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
def add_examples(
|
| 196 |
+
self, texts_or_text_and_labels, labels=None, ids=None, overwrite_labels=False, overwrite_examples=False
|
| 197 |
+
):
|
| 198 |
+
if labels is not None and len(texts_or_text_and_labels) != len(labels):
|
| 199 |
+
raise ValueError(
|
| 200 |
+
f"Text and labels have mismatched lengths {len(texts_or_text_and_labels)} and {len(labels)}"
|
| 201 |
+
)
|
| 202 |
+
if ids is not None and len(texts_or_text_and_labels) != len(ids):
|
| 203 |
+
raise ValueError(f"Text and ids have mismatched lengths {len(texts_or_text_and_labels)} and {len(ids)}")
|
| 204 |
+
if ids is None:
|
| 205 |
+
ids = [None] * len(texts_or_text_and_labels)
|
| 206 |
+
if labels is None:
|
| 207 |
+
labels = [None] * len(texts_or_text_and_labels)
|
| 208 |
+
examples = []
|
| 209 |
+
added_labels = set()
|
| 210 |
+
for text_or_text_and_label, label, guid in zip(texts_or_text_and_labels, labels, ids):
|
| 211 |
+
if isinstance(text_or_text_and_label, (tuple, list)) and label is None:
|
| 212 |
+
text, label = text_or_text_and_label
|
| 213 |
+
else:
|
| 214 |
+
text = text_or_text_and_label
|
| 215 |
+
added_labels.add(label)
|
| 216 |
+
examples.append(InputExample(guid=guid, text_a=text, text_b=None, label=label))
|
| 217 |
+
|
| 218 |
+
# Update examples
|
| 219 |
+
if overwrite_examples:
|
| 220 |
+
self.examples = examples
|
| 221 |
+
else:
|
| 222 |
+
self.examples.extend(examples)
|
| 223 |
+
|
| 224 |
+
# Update labels
|
| 225 |
+
if overwrite_labels:
|
| 226 |
+
self.labels = list(added_labels)
|
| 227 |
+
else:
|
| 228 |
+
self.labels = list(set(self.labels).union(added_labels))
|
| 229 |
+
|
| 230 |
+
return self.examples
|
| 231 |
+
|
| 232 |
+
def get_features(
|
| 233 |
+
self,
|
| 234 |
+
tokenizer,
|
| 235 |
+
max_length=None,
|
| 236 |
+
pad_on_left=False,
|
| 237 |
+
pad_token=0,
|
| 238 |
+
mask_padding_with_zero=True,
|
| 239 |
+
return_tensors=None,
|
| 240 |
+
):
|
| 241 |
+
"""
|
| 242 |
+
Convert examples in a list of `InputFeatures`
|
| 243 |
+
|
| 244 |
+
Args:
|
| 245 |
+
tokenizer: Instance of a tokenizer that will tokenize the examples
|
| 246 |
+
max_length: Maximum example length
|
| 247 |
+
pad_on_left: If set to `True`, the examples will be padded on the left rather than on the right (default)
|
| 248 |
+
pad_token: Padding token
|
| 249 |
+
mask_padding_with_zero: If set to `True`, the attention mask will be filled by `1` for actual values
|
| 250 |
+
and by `0` for padded values. If set to `False`, inverts it (`1` for padded values, `0` for actual
|
| 251 |
+
values)
|
| 252 |
+
|
| 253 |
+
Returns:
|
| 254 |
+
If the `examples` input is a `tf.data.Dataset`, will return a `tf.data.Dataset` containing the
|
| 255 |
+
task-specific features. If the input is a list of `InputExamples`, will return a list of task-specific
|
| 256 |
+
`InputFeatures` which can be fed to the model.
|
| 257 |
+
|
| 258 |
+
"""
|
| 259 |
+
if max_length is None:
|
| 260 |
+
max_length = tokenizer.max_len
|
| 261 |
+
|
| 262 |
+
label_map = {label: i for i, label in enumerate(self.labels)}
|
| 263 |
+
|
| 264 |
+
all_input_ids = []
|
| 265 |
+
for ex_index, example in enumerate(self.examples):
|
| 266 |
+
if ex_index % 10000 == 0:
|
| 267 |
+
logger.info(f"Tokenizing example {ex_index}")
|
| 268 |
+
|
| 269 |
+
input_ids = tokenizer.encode(
|
| 270 |
+
example.text_a,
|
| 271 |
+
add_special_tokens=True,
|
| 272 |
+
max_length=min(max_length, tokenizer.max_len),
|
| 273 |
+
)
|
| 274 |
+
all_input_ids.append(input_ids)
|
| 275 |
+
|
| 276 |
+
batch_length = max(len(input_ids) for input_ids in all_input_ids)
|
| 277 |
+
|
| 278 |
+
features = []
|
| 279 |
+
for ex_index, (input_ids, example) in enumerate(zip(all_input_ids, self.examples)):
|
| 280 |
+
if ex_index % 10000 == 0:
|
| 281 |
+
logger.info(f"Writing example {ex_index}/{len(self.examples)}")
|
| 282 |
+
# The mask has 1 for real tokens and 0 for padding tokens. Only real
|
| 283 |
+
# tokens are attended to.
|
| 284 |
+
attention_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)
|
| 285 |
+
|
| 286 |
+
# Zero-pad up to the sequence length.
|
| 287 |
+
padding_length = batch_length - len(input_ids)
|
| 288 |
+
if pad_on_left:
|
| 289 |
+
input_ids = ([pad_token] * padding_length) + input_ids
|
| 290 |
+
attention_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + attention_mask
|
| 291 |
+
else:
|
| 292 |
+
input_ids = input_ids + ([pad_token] * padding_length)
|
| 293 |
+
attention_mask = attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length)
|
| 294 |
+
|
| 295 |
+
if len(input_ids) != batch_length:
|
| 296 |
+
raise ValueError(f"Error with input length {len(input_ids)} vs {batch_length}")
|
| 297 |
+
if len(attention_mask) != batch_length:
|
| 298 |
+
raise ValueError(f"Error with input length {len(attention_mask)} vs {batch_length}")
|
| 299 |
+
|
| 300 |
+
if self.mode == "classification":
|
| 301 |
+
label = label_map[example.label]
|
| 302 |
+
elif self.mode == "regression":
|
| 303 |
+
label = float(example.label)
|
| 304 |
+
else:
|
| 305 |
+
raise ValueError(self.mode)
|
| 306 |
+
|
| 307 |
+
if ex_index < 5 and self.verbose:
|
| 308 |
+
logger.info("*** Example ***")
|
| 309 |
+
logger.info(f"guid: {example.guid}")
|
| 310 |
+
logger.info(f"input_ids: {' '.join([str(x) for x in input_ids])}")
|
| 311 |
+
logger.info(f"attention_mask: {' '.join([str(x) for x in attention_mask])}")
|
| 312 |
+
logger.info(f"label: {example.label} (id = {label})")
|
| 313 |
+
|
| 314 |
+
features.append(InputFeatures(input_ids=input_ids, attention_mask=attention_mask, label=label))
|
| 315 |
+
|
| 316 |
+
if return_tensors is None:
|
| 317 |
+
return features
|
| 318 |
+
elif return_tensors == "tf":
|
| 319 |
+
if not is_tf_available():
|
| 320 |
+
raise RuntimeError("return_tensors set to 'tf' but TensorFlow 2.0 can't be imported")
|
| 321 |
+
import tensorflow as tf
|
| 322 |
+
|
| 323 |
+
def gen():
|
| 324 |
+
for ex in features:
|
| 325 |
+
yield ({"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label)
|
| 326 |
+
|
| 327 |
+
dataset = tf.data.Dataset.from_generator(
|
| 328 |
+
gen,
|
| 329 |
+
({"input_ids": tf.int32, "attention_mask": tf.int32}, tf.int64),
|
| 330 |
+
({"input_ids": tf.TensorShape([None]), "attention_mask": tf.TensorShape([None])}, tf.TensorShape([])),
|
| 331 |
+
)
|
| 332 |
+
return dataset
|
| 333 |
+
elif return_tensors == "pt":
|
| 334 |
+
if not is_torch_available():
|
| 335 |
+
raise RuntimeError("return_tensors set to 'pt' but PyTorch can't be imported")
|
| 336 |
+
import torch
|
| 337 |
+
from torch.utils.data import TensorDataset
|
| 338 |
+
|
| 339 |
+
all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
|
| 340 |
+
all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long)
|
| 341 |
+
if self.mode == "classification":
|
| 342 |
+
all_labels = torch.tensor([f.label for f in features], dtype=torch.long)
|
| 343 |
+
elif self.mode == "regression":
|
| 344 |
+
all_labels = torch.tensor([f.label for f in features], dtype=torch.float)
|
| 345 |
+
|
| 346 |
+
dataset = TensorDataset(all_input_ids, all_attention_mask, all_labels)
|
| 347 |
+
return dataset
|
| 348 |
+
else:
|
| 349 |
+
raise ValueError("return_tensors should be one of 'tf' or 'pt'")
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/data/processors/xnli.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. 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 |
+
"""XNLI utils (dataset loading and evaluation)"""
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
from .utils import DataProcessor, InputExample
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class XnliProcessor(DataProcessor):
|
| 28 |
+
"""
|
| 29 |
+
Processor for the XNLI dataset. Adapted from
|
| 30 |
+
https://github.com/google-research/bert/blob/f39e881b169b9d53bea03d2d341b31707a6c052b/run_classifier.py#L207
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, language, train_language=None):
|
| 34 |
+
self.language = language
|
| 35 |
+
self.train_language = train_language
|
| 36 |
+
|
| 37 |
+
def get_train_examples(self, data_dir):
|
| 38 |
+
"""See base class."""
|
| 39 |
+
lg = self.language if self.train_language is None else self.train_language
|
| 40 |
+
lines = self._read_tsv(os.path.join(data_dir, f"XNLI-MT-1.0/multinli/multinli.train.{lg}.tsv"))
|
| 41 |
+
examples = []
|
| 42 |
+
for i, line in enumerate(lines):
|
| 43 |
+
if i == 0:
|
| 44 |
+
continue
|
| 45 |
+
guid = f"train-{i}"
|
| 46 |
+
text_a = line[0]
|
| 47 |
+
text_b = line[1]
|
| 48 |
+
label = "contradiction" if line[2] == "contradictory" else line[2]
|
| 49 |
+
if not isinstance(text_a, str):
|
| 50 |
+
raise TypeError(f"Training input {text_a} is not a string")
|
| 51 |
+
if not isinstance(text_b, str):
|
| 52 |
+
raise TypeError(f"Training input {text_b} is not a string")
|
| 53 |
+
if not isinstance(label, str):
|
| 54 |
+
raise TypeError(f"Training label {label} is not a string")
|
| 55 |
+
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
|
| 56 |
+
return examples
|
| 57 |
+
|
| 58 |
+
def get_test_examples(self, data_dir):
|
| 59 |
+
"""See base class."""
|
| 60 |
+
lines = self._read_tsv(os.path.join(data_dir, "XNLI-1.0/xnli.test.tsv"))
|
| 61 |
+
examples = []
|
| 62 |
+
for i, line in enumerate(lines):
|
| 63 |
+
if i == 0:
|
| 64 |
+
continue
|
| 65 |
+
language = line[0]
|
| 66 |
+
if language != self.language:
|
| 67 |
+
continue
|
| 68 |
+
guid = f"test-{i}"
|
| 69 |
+
text_a = line[6]
|
| 70 |
+
text_b = line[7]
|
| 71 |
+
label = line[1]
|
| 72 |
+
if not isinstance(text_a, str):
|
| 73 |
+
raise TypeError(f"Training input {text_a} is not a string")
|
| 74 |
+
if not isinstance(text_b, str):
|
| 75 |
+
raise TypeError(f"Training input {text_b} is not a string")
|
| 76 |
+
if not isinstance(label, str):
|
| 77 |
+
raise TypeError(f"Training label {label} is not a string")
|
| 78 |
+
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
|
| 79 |
+
return examples
|
| 80 |
+
|
| 81 |
+
def get_labels(self):
|
| 82 |
+
"""See base class."""
|
| 83 |
+
return ["contradiction", "entailment", "neutral"]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
xnli_processors = {
|
| 87 |
+
"xnli": XnliProcessor,
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
xnli_output_modes = {
|
| 91 |
+
"xnli": "classification",
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
xnli_tasks_num_labels = {
|
| 95 |
+
"xnli": 3,
|
| 96 |
+
}
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/distributed/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (515 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/distributed/__pycache__/configuration_utils.cpython-310.pyc
ADDED
|
Binary file (4.28 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (6.47 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/beam_constraints.cpython-310.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/beam_search.cpython-310.pyc
ADDED
|
Binary file (28.9 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/candidate_generator.cpython-310.pyc
ADDED
|
Binary file (40.5 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/configuration_utils.cpython-310.pyc
ADDED
|
Binary file (60.7 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/flax_logits_process.cpython-310.pyc
ADDED
|
Binary file (21.7 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/flax_utils.cpython-310.pyc
ADDED
|
Binary file (27.7 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/stopping_criteria.cpython-310.pyc
ADDED
|
Binary file (23.8 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/streamers.cpython-310.pyc
ADDED
|
Binary file (11.5 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/tf_logits_process.cpython-310.pyc
ADDED
|
Binary file (27.2 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/__pycache__/watermarking.cpython-310.pyc
ADDED
|
Binary file (21.5 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 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 .cache import PagedAttentionCache
|
| 16 |
+
from .continuous_api import ContinuousBatchingManager, ContinuousMixin
|
| 17 |
+
from .requests import RequestState, RequestStatus
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
__all__ = [
|
| 21 |
+
"ContinuousBatchingManager",
|
| 22 |
+
"ContinuousMixin",
|
| 23 |
+
"PagedAttentionCache",
|
| 24 |
+
"RequestState",
|
| 25 |
+
"RequestStatus",
|
| 26 |
+
]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (471 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__pycache__/cache.cpython-310.pyc
ADDED
|
Binary file (22.9 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__pycache__/cache_manager.cpython-310.pyc
ADDED
|
Binary file (8.86 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__pycache__/continuous_api.cpython-310.pyc
ADDED
|
Binary file (32.6 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__pycache__/requests.cpython-310.pyc
ADDED
|
Binary file (7.16 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/__pycache__/scheduler.cpython-310.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/cache.py
ADDED
|
@@ -0,0 +1,606 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 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 deque
|
| 16 |
+
from math import floor, gcd, sqrt
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from ...configuration_utils import PretrainedConfig
|
| 22 |
+
from ...generation.configuration_utils import GenerationConfig
|
| 23 |
+
from ...utils.metrics import attach_tracer, traced
|
| 24 |
+
from .cache_manager import CacheAllocator, FullAttentionCacheAllocator, SlidingAttentionCacheAllocator
|
| 25 |
+
from .requests import get_device_and_memory_breakdown, logger
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def group_layers_by_attn_type(config: PretrainedConfig) -> tuple[list[list[int]], list[str]]:
|
| 29 |
+
"""
|
| 30 |
+
Group layers depending on the attention mix, according to VLLM's hybrid allocator rules:
|
| 31 |
+
- Layers in each group need to have the same type of attention
|
| 32 |
+
- All groups have the same number of layers
|
| 33 |
+
|
| 34 |
+
For a model with the following layer types: ["sliding", "full", "full", "sliding", "full", "full", "full", "full"]
|
| 35 |
+
We would get two groups: [0, 3] and [1, 2], [4,5], [6,7].
|
| 36 |
+
"""
|
| 37 |
+
# If the config has no layer_type attribute, it means all layers are the same attention type
|
| 38 |
+
layer_types = getattr(config, "layer_types", None)
|
| 39 |
+
if layer_types is None:
|
| 40 |
+
attn_type = "sliding_attention" if getattr(config, "sliding_window", None) is not None else "full_attention"
|
| 41 |
+
layer_types = [attn_type for _ in range(config.num_hidden_layers)]
|
| 42 |
+
|
| 43 |
+
# We then count the number of layers of each type
|
| 44 |
+
layer_counts = {}
|
| 45 |
+
for i, layer_type in enumerate(layer_types):
|
| 46 |
+
layer_counts[layer_type] = layer_counts.get(layer_type, []) + [i]
|
| 47 |
+
|
| 48 |
+
# The size of all groups is the greatest common divisor of the number of layers of each type
|
| 49 |
+
group_size = gcd(*[len(indices) for indices in layer_counts.values()])
|
| 50 |
+
|
| 51 |
+
# We then group the layers by type
|
| 52 |
+
layer_groups = []
|
| 53 |
+
for layer_type, indices in layer_counts.items():
|
| 54 |
+
for i in range(0, len(indices), group_size):
|
| 55 |
+
layer_groups.append(indices[i : i + group_size])
|
| 56 |
+
# And note the layer types
|
| 57 |
+
group_types = [layer_types[lg[0]] for lg in layer_groups]
|
| 58 |
+
return layer_groups, group_types
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@attach_tracer()
|
| 62 |
+
class PagedAttentionCache:
|
| 63 |
+
"""
|
| 64 |
+
Manages the cache for a paged attention mechanism, inspired by VLLM's hybrid allocator. The cache relies on making
|
| 65 |
+
groups of layers to reduce the complexity of cache management and fragmentation.
|
| 66 |
+
|
| 67 |
+
The cache uses a three-level hierarchy:
|
| 68 |
+
- Pages: The smallest unit of cache, a page has a size of [num_heads, head_size], which is the space needed to
|
| 69 |
+
store the key or value states for one token and one layer. For a model with only full-attention layers, to store
|
| 70 |
+
the KV cache of one token, we need `2 * num_layers` pages: key and values each take `num_layers` pages.
|
| 71 |
+
Pages are grouped into blocks:
|
| 72 |
+
- Blocks: A block is a collection of `block_size` pages, serving as the allocation unit to reduce management
|
| 73 |
+
complexity and fragmentation. Cache is allocated and freed block by block, not page by page. One block is
|
| 74 |
+
allocated to one layer group, which only has one attention type, like full-attention or sliding-attention.
|
| 75 |
+
If all layers in the model have the same attention type, then all layers will be in the same group. There is
|
| 76 |
+
more than one group if and only if the model has a mixed attention types, like layers with full-attention and
|
| 77 |
+
layers with sliding-attention.
|
| 78 |
+
- Cache tensors: The physical supports for the cache. There are as many cache tensors as there are layer in a
|
| 79 |
+
layer group, and the shape of the cache tensor is `[num_blocks * block_size, num_heads, head_size]`.
|
| 80 |
+
|
| 81 |
+
Grouping layers into groups is useful because when we allocate one block to a group N, the block allocated is the
|
| 82 |
+
same for all layers in group N, equivalently it is allocated across all cache tensors. This allows us to
|
| 83 |
+
efficiently allocate and free blocks, and to efficiently read and write key and value states.
|
| 84 |
+
|
| 85 |
+
For instance, imagine we have 8 blocks of cache and a model with two layer groups: a full-attention group with 3
|
| 86 |
+
layers and a sliding-attention group with 3 layers. At creation time, the physical cache tensors look like this:
|
| 87 |
+
|
| 88 |
+
cache_tensor_0: □ □ □ □ □ □ □ □
|
| 89 |
+
cache_tensor_1: □ □ □ □ □ □ □ □
|
| 90 |
+
cache_tensor_2: □ □ □ □ □ □ □ □
|
| 91 |
+
|
| 92 |
+
where □ means the blocks is not allocated to any layer group yet. We have 3 cache tensors because there are
|
| 93 |
+
3 layers per group.
|
| 94 |
+
We allocate 1 block to each group, after allocation, the cache tensors look like this:
|
| 95 |
+
|
| 96 |
+
cache_tensor_0: ✖ ◉ □ □ □ □ □ □
|
| 97 |
+
cache_tensor_1: ✖ ◉ □ □ □ □ □ □
|
| 98 |
+
cache_tensor_2: ✖ ◉ □ □ □ □ □ □
|
| 99 |
+
|
| 100 |
+
where ✖ means the block is allocated to the full-attention group, and ◉ means the block is allocated to the
|
| 101 |
+
sliding-attention group.
|
| 102 |
+
Now, if we continue to generate, and the sliding window has been reached, we only need to allocate a new block
|
| 103 |
+
for the full-attention group, and the cache tensors look like this:
|
| 104 |
+
|
| 105 |
+
cache_tensor_0: ✖ ◉ ✖ □ □ □ □ □
|
| 106 |
+
cache_tensor_1: ✖ ◉ ✖ □ □ □ □ □
|
| 107 |
+
cache_tensor_2: ✖ ◉ ✖ □ □ □ □ □
|
| 108 |
+
|
| 109 |
+
And after further generation, when we need a new block allocated:
|
| 110 |
+
|
| 111 |
+
cache_tensor_0: ✖ ◉ ✖ ✖ □ □ □ □
|
| 112 |
+
cache_tensor_1: ✖ ◉ ✖ ✖ □ □ □ □
|
| 113 |
+
cache_tensor_2: ✖ ◉ ✖ ✖ □ □ □ □
|
| 114 |
+
|
| 115 |
+
This would not have been possible if all layers were in the same group: we would have had to allocate a new block
|
| 116 |
+
for the sliding-attention group, although it is not needed.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
# TODO: this init is quite long, maybe a refactor is in order
|
| 120 |
+
def __init__(
|
| 121 |
+
self,
|
| 122 |
+
config: PretrainedConfig,
|
| 123 |
+
generation_config: GenerationConfig,
|
| 124 |
+
device: torch.device,
|
| 125 |
+
dtype: torch.dtype = torch.float16,
|
| 126 |
+
layer_device_map: Optional[dict[int, Union[str, torch.device, int]]] = None,
|
| 127 |
+
tp_size: Optional[int] = None,
|
| 128 |
+
) -> None:
|
| 129 |
+
"""Initialize a paged attention cache for efficient memory usage.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
config: Model configuration
|
| 133 |
+
generation_config: Generation configuration containing cache parameters
|
| 134 |
+
device: Device for the cache tensors
|
| 135 |
+
dtype: Data type of the cache
|
| 136 |
+
layer_device_map: Optional mapping of layer indices to devices
|
| 137 |
+
tp_size: Tensor parallelism size
|
| 138 |
+
"""
|
| 139 |
+
self.config = config
|
| 140 |
+
self.dtype = dtype
|
| 141 |
+
self.device = device
|
| 142 |
+
|
| 143 |
+
# Extract model dimensions
|
| 144 |
+
kv_heads = getattr(config, "num_key_value_heads", None)
|
| 145 |
+
self.num_key_value_heads: int = kv_heads if kv_heads is not None else config.num_attention_heads
|
| 146 |
+
head_dim = getattr(config, "head_dim", None)
|
| 147 |
+
self.head_dim: int = head_dim if head_dim is not None else config.hidden_size // config.num_attention_heads
|
| 148 |
+
|
| 149 |
+
# Extract cache dimensions
|
| 150 |
+
self.block_size = getattr(generation_config, "block_size", 32)
|
| 151 |
+
|
| 152 |
+
# Group layers depending on the attention mix
|
| 153 |
+
layer_groups, group_types = group_layers_by_attn_type(config)
|
| 154 |
+
group_size = len(layer_groups[0])
|
| 155 |
+
self.num_groups = len(layer_groups)
|
| 156 |
+
|
| 157 |
+
self.sliding_windows = {}
|
| 158 |
+
self.layer_index_to_group_indices = {}
|
| 159 |
+
for i, group in enumerate(layer_groups):
|
| 160 |
+
sliding_window = config.sliding_window if group_types[i] == "sliding_attention" else 1
|
| 161 |
+
for j, layer in enumerate(group):
|
| 162 |
+
self.layer_index_to_group_indices[layer] = (i, j)
|
| 163 |
+
self.sliding_windows[layer] = sliding_window
|
| 164 |
+
|
| 165 |
+
# Handle TP (or dont)
|
| 166 |
+
if tp_size is not None and tp_size > 1:
|
| 167 |
+
if self.num_key_value_heads % tp_size != 0:
|
| 168 |
+
raise ValueError(
|
| 169 |
+
f"Number of key value heads {self.num_key_value_heads} must be divisible by tensor parallel size {tp_size}."
|
| 170 |
+
)
|
| 171 |
+
# If the model is using tensor parallelism, we need to adjust the number of heads accordingly.
|
| 172 |
+
# self.num_key_value_heads //= tp_size # TODO: why is this commented out?
|
| 173 |
+
|
| 174 |
+
# Infer number of blocks and max batch tokens
|
| 175 |
+
page_size = self.head_dim * self.num_key_value_heads
|
| 176 |
+
|
| 177 |
+
if getattr(config, "attn_implementation", None) == "paged_attention":
|
| 178 |
+
num_attention_masks = 0
|
| 179 |
+
else:
|
| 180 |
+
# TODO: when we generalize to allow for block-attn, we can use `num_attention_masks=sum(set(group_types))`
|
| 181 |
+
num_attention_masks = 2 if "sliding_attention" in group_types else 1
|
| 182 |
+
|
| 183 |
+
memory_handler = PagedAttentionMemoryHandler(
|
| 184 |
+
block_size=self.block_size,
|
| 185 |
+
page_size=page_size,
|
| 186 |
+
num_groups=self.num_groups,
|
| 187 |
+
group_size=group_size,
|
| 188 |
+
peak_activation_per_token=(config.hidden_size + config.vocab_size),
|
| 189 |
+
num_attention_masks=num_attention_masks,
|
| 190 |
+
)
|
| 191 |
+
num_blocks, max_batch_tokens = memory_handler.infer_num_blocks_and_max_batch_tokens(
|
| 192 |
+
num_blocks=getattr(generation_config, "num_blocks", None),
|
| 193 |
+
max_batch_tokens=getattr(generation_config, "max_batch_tokens", None),
|
| 194 |
+
max_memory_percent=getattr(generation_config, "max_memory", 0.9),
|
| 195 |
+
cache_dtype=self.dtype,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
# Add the inferred attributes to the class
|
| 199 |
+
self.num_blocks = num_blocks
|
| 200 |
+
self.max_batch_tokens = max_batch_tokens
|
| 201 |
+
logger.info(
|
| 202 |
+
f"PagedAttentionCache initialized with {self.num_blocks = }, {self.block_size = }, {page_size = }, "
|
| 203 |
+
f"{self.max_batch_tokens = } {num_attention_masks = }"
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
# Initialize the cache
|
| 207 |
+
self.key_cache: list[torch.Tensor] = []
|
| 208 |
+
self.value_cache: list[torch.Tensor] = []
|
| 209 |
+
# We add one extra token to the cache to handle padding and generally discard unwanted tokens
|
| 210 |
+
self.cache_shape = (num_blocks * self.block_size + 1, self.num_key_value_heads, self.head_dim)
|
| 211 |
+
for _ in range(group_size):
|
| 212 |
+
new_layer_key_cache = torch.empty(self.cache_shape, dtype=self.dtype, device=self.device)
|
| 213 |
+
new_layer_value_cache = torch.empty(self.cache_shape, dtype=self.dtype, device=self.device)
|
| 214 |
+
torch._dynamo.mark_static_address(new_layer_key_cache)
|
| 215 |
+
torch._dynamo.mark_static_address(new_layer_value_cache)
|
| 216 |
+
self.key_cache.append(new_layer_key_cache)
|
| 217 |
+
self.value_cache.append(new_layer_value_cache)
|
| 218 |
+
logger.info(f"{self.cache_shape = } {self.key_cache[0].shape = } {self.key_cache[0].numel() = }")
|
| 219 |
+
|
| 220 |
+
# Block management data structures
|
| 221 |
+
self._free_blocks = deque(range(num_blocks))
|
| 222 |
+
self.group_cache_managers: list[CacheAllocator] = []
|
| 223 |
+
for i, group_type in enumerate(group_types):
|
| 224 |
+
if group_type == "full_attention":
|
| 225 |
+
cm = FullAttentionCacheAllocator(i, self.block_size)
|
| 226 |
+
elif group_type == "sliding_attention":
|
| 227 |
+
cm = SlidingAttentionCacheAllocator(i, self.block_size, config.sliding_window)
|
| 228 |
+
else:
|
| 229 |
+
raise ValueError(f"Invalid group type: {group_type}")
|
| 230 |
+
self.group_cache_managers.append(cm)
|
| 231 |
+
|
| 232 |
+
@traced
|
| 233 |
+
def allocate_blocks(self, n_blocks: int, request_id: str) -> int:
|
| 234 |
+
"""Allocate cache blocks across all layer groups for a given request. Actual allocation is done by the cache
|
| 235 |
+
managers, and this method only returns the maximum number of blocks actually allocated across all managers."""
|
| 236 |
+
max_allocated = 0
|
| 237 |
+
for cm in self.group_cache_managers:
|
| 238 |
+
allocated = cm.allocate_blocks(n_blocks, request_id, self._free_blocks)
|
| 239 |
+
if allocated is None:
|
| 240 |
+
return None
|
| 241 |
+
max_allocated = max(max_allocated, allocated)
|
| 242 |
+
return max_allocated
|
| 243 |
+
|
| 244 |
+
@traced
|
| 245 |
+
def free_blocks(self, request_id: str) -> None:
|
| 246 |
+
"""Free all allocated cache blocks for a given request across all layer groups. Actual deallocation is done
|
| 247 |
+
by the cache managers."""
|
| 248 |
+
for cm in self.group_cache_managers:
|
| 249 |
+
cm.free_blocks(request_id, self._free_blocks)
|
| 250 |
+
|
| 251 |
+
def get_num_free_blocks(self) -> int:
|
| 252 |
+
"""Get the current number of unallocated blocks available for new requests."""
|
| 253 |
+
return len(self._free_blocks)
|
| 254 |
+
|
| 255 |
+
@traced
|
| 256 |
+
def extend_read_indices(
|
| 257 |
+
self, request_id: str, past_length: int, query_length: int, read_index: list[list[int]]
|
| 258 |
+
) -> None:
|
| 259 |
+
"""Retrieve physical cache indices for reading KV states in the cache across all layer groups. This method
|
| 260 |
+
coordinates with all cache managers to build the complete set of read indices needed for attention computation.
|
| 261 |
+
"""
|
| 262 |
+
for cm, read_indices in zip(self.group_cache_managers, read_index):
|
| 263 |
+
indices = cm.get_read_indices(request_id, past_length, query_length)
|
| 264 |
+
read_indices.extend(indices)
|
| 265 |
+
|
| 266 |
+
@traced
|
| 267 |
+
def extend_write_indices(
|
| 268 |
+
self, request_id: str, past_length: int, query_length: int, write_index: list[list[int]]
|
| 269 |
+
) -> None:
|
| 270 |
+
"""Retrieve physical cache indices for writing new KV states to the cache across all layer groups. This method
|
| 271 |
+
coordinates with all cache managers to build the complete set of write indices needed to store computed KV
|
| 272 |
+
states."""
|
| 273 |
+
for cm, write_indices in zip(self.group_cache_managers, write_index):
|
| 274 |
+
indices = cm.get_write_indices(request_id, past_length, query_length)
|
| 275 |
+
write_indices.extend(indices)
|
| 276 |
+
|
| 277 |
+
@traced
|
| 278 |
+
def get_seqlens_k(self, request_id: str, past_length: int, query_length: int) -> dict[str, int]:
|
| 279 |
+
"""Retrieve the key sequence length for the given request_id across all layer types. Returns a dictionary of
|
| 280 |
+
layer types to their corresponding key sequence lengths."""
|
| 281 |
+
seqlens_k = {}
|
| 282 |
+
for cm in self.group_cache_managers:
|
| 283 |
+
attn_type, seqlen_k = cm.get_seqlens_k(request_id, past_length, query_length)
|
| 284 |
+
seqlens_k[attn_type] = seqlen_k
|
| 285 |
+
return seqlens_k
|
| 286 |
+
|
| 287 |
+
@traced
|
| 288 |
+
def update(
|
| 289 |
+
self,
|
| 290 |
+
key_states: torch.Tensor, # shape [1, num_kv_heads, seqlen_kv, head_dim]
|
| 291 |
+
value_states: torch.Tensor, # shape [1, num_kv_heads, seqlen_kv, head_dim]
|
| 292 |
+
layer_idx: int,
|
| 293 |
+
read_index: list[torch.Tensor], # shape [num_layer_groups, seqlen_kv + past_length]
|
| 294 |
+
write_index: list[torch.Tensor], # shape [num_layer_groups, seqlen_q]
|
| 295 |
+
**kwargs,
|
| 296 |
+
) -> tuple[torch.Tensor, torch.Tensor]: # shape [seqlen_kv + past_length, num_kv_heads, head_dim]
|
| 297 |
+
"""Update the cache with new key-value states for a specific layer. This method writes new KV states to the
|
| 298 |
+
appropriate cache locations. The behavior differs based on the layer's attention type:
|
| 299 |
+
|
| 300 |
+
- Full attention: New KV states are written to cache, then complete sequence is read from cache
|
| 301 |
+
- Sliding window: Old KV is read from cache along with extra spaces for the new KV, then new KV is written to
|
| 302 |
+
cache. This is because new KV might overwrite the old KV, so we need to read the old KV first.
|
| 303 |
+
|
| 304 |
+
Returns the complete KV states (cached + new) for attention computation.
|
| 305 |
+
"""
|
| 306 |
+
# Retrieve the layer read and write indices, and if there is a sliding window
|
| 307 |
+
group_idx, layer_idx_in_group = self.layer_index_to_group_indices[layer_idx]
|
| 308 |
+
layer_read_index = read_index[group_idx]
|
| 309 |
+
layer_write_index = write_index[group_idx]
|
| 310 |
+
# Select the correct cache
|
| 311 |
+
k_cache = self.key_cache[layer_idx_in_group]
|
| 312 |
+
v_cache = self.value_cache[layer_idx_in_group]
|
| 313 |
+
# Transpose the key and value states to match the cache shape, after which shape is [seqlen_kv, num_kv_heads, head_dim]
|
| 314 |
+
key_states = key_states.transpose(1, 2).squeeze(0)
|
| 315 |
+
value_states = value_states.transpose(1, 2).squeeze(0)
|
| 316 |
+
|
| 317 |
+
# Case: full attention
|
| 318 |
+
sliding_window = self.sliding_windows[layer_idx]
|
| 319 |
+
if sliding_window == 1:
|
| 320 |
+
k_cache[layer_write_index, :, :] = key_states
|
| 321 |
+
v_cache[layer_write_index, :, :] = value_states
|
| 322 |
+
key_states_with_cache = k_cache[layer_read_index, :, :]
|
| 323 |
+
value_states_with_cache = v_cache[layer_read_index, :, :]
|
| 324 |
+
|
| 325 |
+
# Case: sliding window -- we need to be careful of read/write order because of chunked prefill, because it's
|
| 326 |
+
# the only case where you may write over cache you need to use
|
| 327 |
+
else:
|
| 328 |
+
# Add the cache to the key and value states
|
| 329 |
+
mask = layer_read_index == -1 # TODO: can this can be efficiently precomputed?
|
| 330 |
+
key_states_with_cache = k_cache[layer_read_index, :, :]
|
| 331 |
+
key_states_with_cache[mask] = key_states
|
| 332 |
+
value_states_with_cache = v_cache[layer_read_index, :, :]
|
| 333 |
+
value_states_with_cache[mask] = value_states
|
| 334 |
+
# Write new KV values to the cache
|
| 335 |
+
k_cache[layer_write_index, :, :] = key_states
|
| 336 |
+
v_cache[layer_write_index, :, :] = value_states
|
| 337 |
+
|
| 338 |
+
# Return the new KV values
|
| 339 |
+
return key_states_with_cache, value_states_with_cache
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
# TODO: rework computation with the groups and their sizes
|
| 343 |
+
class PagedAttentionMemoryHandler:
|
| 344 |
+
"""A helper class to determine the best number of pages and maximum number of tokens per batch for the paged
|
| 345 |
+
attention cache, providing automatic sizing based on available GPU memory.
|
| 346 |
+
The helper works using the number of pages, which is tied to the number of blocks by:
|
| 347 |
+
num_blocks = num_pages // block_size
|
| 348 |
+
|
| 349 |
+
The memory footprint consists of three main components:
|
| 350 |
+
- Cache memory: the space needed to store the cache tensors:
|
| 351 |
+
2 * layer_group_size * [num_pages, page_size] * cache_dtype
|
| 352 |
+
- Activation memory: the space temporarily taken by the largest activation during the model forward pass:
|
| 353 |
+
peak_activation_per_token * max_tokens_per_batch * activation_dtype_size
|
| 354 |
+
- Static tensors: the space taken by the input/output buffers and metadata tensors for batch processing, sum of:
|
| 355 |
+
- inputs_ids + outputs_ids + position_ids + logits_indices: 4 * max_tokens_per_batch * int32_size
|
| 356 |
+
- attention_mask: num_attention_masks * num_pages * max_tokens_per_batch * activation_dtype_size
|
| 357 |
+
- cumulative_seqlens_q + cumulative_seqlens_k: (1 + 2) * max_tokens_per_batch * int32_size
|
| 358 |
+
- write_index_tensor: num_groups * max_tokens_per_batch * int32_size
|
| 359 |
+
- read_index_tensor: num_groups * (num_pages + max_tokens_per_batch) * int32_size
|
| 360 |
+
|
| 361 |
+
The handler can operate in three modes:
|
| 362 |
+
1. Auto-sizing: Determines both number of pages and maximum number of tokens per batch using quadratic optimization
|
| 363 |
+
2. Fixed cache: Calculates max batch tokens given a fixed number of pages
|
| 364 |
+
3. Fixed batch: Calculates number of pages given a fixed maximum batch size
|
| 365 |
+
|
| 366 |
+
"""
|
| 367 |
+
|
| 368 |
+
_activation_dtype = torch.bfloat16
|
| 369 |
+
_input_dtype = torch.int32
|
| 370 |
+
_upper_bound_max_batch_tokens = 256
|
| 371 |
+
_upper_bound_num_blocks = 4096
|
| 372 |
+
|
| 373 |
+
def __init__(
|
| 374 |
+
self,
|
| 375 |
+
block_size: int,
|
| 376 |
+
page_size: int,
|
| 377 |
+
num_groups: int,
|
| 378 |
+
group_size: int,
|
| 379 |
+
peak_activation_per_token: int,
|
| 380 |
+
num_attention_masks: int,
|
| 381 |
+
) -> None:
|
| 382 |
+
"""Initialize the memory handler with the parameters that cannot be automatically inferred.
|
| 383 |
+
|
| 384 |
+
Args:
|
| 385 |
+
block_size: Size of the cache blocks
|
| 386 |
+
page_size: Size of the cache pages
|
| 387 |
+
num_groups: Number of layer groups
|
| 388 |
+
group_size: Number of layers per layer group
|
| 389 |
+
peak_activation_per_token: Maximum size of activation tensor per token, = hidden_size + vocab_size
|
| 390 |
+
num_attention_masks: Number of attention masks, 0 if no attention mask is used, 2 if hybrid model, else 1
|
| 391 |
+
"""
|
| 392 |
+
self.block_size = block_size
|
| 393 |
+
self.page_size = page_size
|
| 394 |
+
self.num_groups = num_groups
|
| 395 |
+
self.group_size = group_size
|
| 396 |
+
self.peak_activation_per_token = peak_activation_per_token
|
| 397 |
+
self.num_attention_masks = num_attention_masks
|
| 398 |
+
|
| 399 |
+
@staticmethod
|
| 400 |
+
def get_available_memory(max_memory_percent: float = 1.0) -> int:
|
| 401 |
+
"""Calculate available GPU memory for cache allocation, accounting for already allocated tensors.
|
| 402 |
+
This method queries the current memory state and applies the specified percentage limit to determine
|
| 403 |
+
how much memory can be safely used for the paged attention cache.
|
| 404 |
+
|
| 405 |
+
Args:
|
| 406 |
+
max_memory_percent: Fraction of available memory to use (0.0-1.0). 1.0 means use all available memory.
|
| 407 |
+
|
| 408 |
+
Returns:
|
| 409 |
+
int: Available memory in bytes for cache allocation
|
| 410 |
+
"""
|
| 411 |
+
_, total, reserved, allocated = get_device_and_memory_breakdown()
|
| 412 |
+
available_memory = total - max(allocated, reserved)
|
| 413 |
+
available_memory = int(available_memory * max_memory_percent)
|
| 414 |
+
return available_memory
|
| 415 |
+
|
| 416 |
+
def infer_num_blocks_and_max_batch_tokens(
|
| 417 |
+
self,
|
| 418 |
+
num_blocks: Optional[int] = None,
|
| 419 |
+
max_batch_tokens: Optional[int] = None,
|
| 420 |
+
max_memory_percent: float = 0.9,
|
| 421 |
+
cache_dtype: torch.dtype = torch.float16,
|
| 422 |
+
) -> tuple[int, int]:
|
| 423 |
+
"""Determine optimal number of blocks and maximum number of tokens per batch based on available memory and
|
| 424 |
+
constraints. Check the class docstring for more details. Naming the number of pages as N and the maximum number
|
| 425 |
+
of tokens per batch as M, the equation solved is:
|
| 426 |
+
|
| 427 |
+
available_memory = sum([
|
| 428 |
+
MN * num_attention_masks * activation_dtype_size,
|
| 429 |
+
2N * (layer_group_size * page_size * cache_dtype + 2 * num_group),
|
| 430 |
+
M * (peak_activation_per_token * activation_dtype + 28 + 4 * num_group),
|
| 431 |
+
])
|
| 432 |
+
|
| 433 |
+
where we already simplified int32_size = 4.
|
| 434 |
+
"""
|
| 435 |
+
# If neither num_blocks nor max_batch_tokens are provided, we use a second-order polynomial
|
| 436 |
+
if num_blocks is None and max_batch_tokens is None:
|
| 437 |
+
num_blocks, max_batch_tokens = self.compute_num_blocks_and_max_batch_tokens(
|
| 438 |
+
max_memory_percent, cache_dtype
|
| 439 |
+
)
|
| 440 |
+
# If only num_blocks is provided, we infer the max_batch_tokens
|
| 441 |
+
elif num_blocks is not None and max_batch_tokens is None:
|
| 442 |
+
max_batch_tokens = self.compute_max_batch_tokens(num_blocks, max_memory_percent, cache_dtype)
|
| 443 |
+
# If only max_batch_tokens is provided, we infer the num_blocks
|
| 444 |
+
elif max_batch_tokens is not None and num_blocks is None:
|
| 445 |
+
num_blocks = self.compute_num_blocks(max_batch_tokens, max_memory_percent, cache_dtype)
|
| 446 |
+
|
| 447 |
+
# We check if the memory footprint is too large in all cases
|
| 448 |
+
available_memory = self.get_available_memory(max_memory_percent)
|
| 449 |
+
memory_footprint = self.compute_memory_footprint(
|
| 450 |
+
max_batch_tokens=max_batch_tokens,
|
| 451 |
+
num_blocks=num_blocks,
|
| 452 |
+
cache_dtype=cache_dtype,
|
| 453 |
+
)
|
| 454 |
+
if memory_footprint > available_memory:
|
| 455 |
+
raise MemoryError(f"Memory footprint {memory_footprint} is more than available memory {available_memory}")
|
| 456 |
+
return num_blocks, max_batch_tokens
|
| 457 |
+
|
| 458 |
+
def compute_num_blocks_and_max_batch_tokens(
|
| 459 |
+
self,
|
| 460 |
+
max_memory_percent: float = 0.9,
|
| 461 |
+
cache_dtype: torch.dtype = torch.float16,
|
| 462 |
+
m: float = 0.01,
|
| 463 |
+
) -> tuple[int, int]:
|
| 464 |
+
"""Calculate optimal number of blocks and maximum number of tokens per batch using quadratic optimization when
|
| 465 |
+
neither is fixed. This method assumes a relationship M = m * N where m is a small ratio below 1 and solves the
|
| 466 |
+
resulting quadratic equation to find the optimal N that maximizes utilization within memory constraints. m is
|
| 467 |
+
the amount of cache we can fill with one batch: m=0.01 means a batch fills at most 1% of the cache. The equation
|
| 468 |
+
to solve is:
|
| 469 |
+
|
| 470 |
+
available_memory = sum([
|
| 471 |
+
m * N^2 * num_attention_masks * activation_dtype_size,
|
| 472 |
+
2N * (layer_group_size * page_size * cache_dtype + 2 * num_group),
|
| 473 |
+
m * N * (peak_activation_per_token * activation_dtype + 28 + 4 * num_group),
|
| 474 |
+
])
|
| 475 |
+
"""
|
| 476 |
+
cache_memory = self.get_available_memory(max_memory_percent)
|
| 477 |
+
logger.info(f"Cache memory: {cache_memory}")
|
| 478 |
+
|
| 479 |
+
# Compute second-degree polynomial coefficients
|
| 480 |
+
a = m * self.num_attention_masks * self._activation_dtype.itemsize
|
| 481 |
+
b = 2 * (self.group_size * self.page_size * cache_dtype.itemsize + 2 * self.num_groups)
|
| 482 |
+
b += m * (self.peak_activation_per_token * self._activation_dtype.itemsize + 28 + 4 * self.num_groups)
|
| 483 |
+
c = -cache_memory
|
| 484 |
+
logger.debug(f"Coefficients of 2nd degree polynomial: {a = }, {b = }, {c = }")
|
| 485 |
+
|
| 486 |
+
# Compute discriminant and greatest solution
|
| 487 |
+
discriminant = b**2 - 4 * a * c
|
| 488 |
+
if discriminant < 0:
|
| 489 |
+
raise ValueError(f"Discriminant is negative: {discriminant = }")
|
| 490 |
+
greatest_solution = (-b + sqrt(discriminant)) / (2 * a)
|
| 491 |
+
if greatest_solution < 0:
|
| 492 |
+
raise ValueError(f"Greatest solution is negative: {greatest_solution = }")
|
| 493 |
+
|
| 494 |
+
# Infer number of blocks and max batch tokens
|
| 495 |
+
num_pages = floor(greatest_solution)
|
| 496 |
+
num_blocks = num_pages // self.block_size
|
| 497 |
+
if num_blocks > self._upper_bound_num_blocks:
|
| 498 |
+
logger.info(f"{num_blocks = } is too large, setting to {self._upper_bound_num_blocks = }")
|
| 499 |
+
num_blocks = self._upper_bound_num_blocks
|
| 500 |
+
max_batch_tokens = int(greatest_solution * m)
|
| 501 |
+
if max_batch_tokens > self._upper_bound_max_batch_tokens:
|
| 502 |
+
logger.info(f"{max_batch_tokens = } is too large, setting to {self._upper_bound_max_batch_tokens = }")
|
| 503 |
+
max_batch_tokens = self._upper_bound_max_batch_tokens
|
| 504 |
+
return num_blocks, max_batch_tokens
|
| 505 |
+
|
| 506 |
+
def compute_max_batch_tokens(
|
| 507 |
+
self,
|
| 508 |
+
num_blocks: int,
|
| 509 |
+
max_memory_percent: float = 0.9,
|
| 510 |
+
cache_dtype: torch.dtype = torch.float16,
|
| 511 |
+
) -> int:
|
| 512 |
+
"""Calculate maximum batch tokens M given a fixed number of cache blocks. The formula for M is given by:
|
| 513 |
+
|
| 514 |
+
M = (available_memory - 2N * (layer_group_size * page_size * cache_dtype + 2 * num_group))
|
| 515 |
+
/ (activation_dtype_size * (N * num_attention_masks + peak_activation_per_token) + 28 + 4 * num_group)
|
| 516 |
+
"""
|
| 517 |
+
cache_memory = self.get_available_memory(max_memory_percent)
|
| 518 |
+
num_pages = num_blocks * self.block_size
|
| 519 |
+
# Compute numerator
|
| 520 |
+
num = cache_memory
|
| 521 |
+
num -= 2 * num_pages * (self.group_size * self.page_size * cache_dtype.itemsize + 2 * self.num_groups)
|
| 522 |
+
# Compute denominator
|
| 523 |
+
denum = self._activation_dtype.itemsize * (
|
| 524 |
+
num_pages * self.num_attention_masks + self.peak_activation_per_token
|
| 525 |
+
)
|
| 526 |
+
denum += 28 + 4 * self.num_groups
|
| 527 |
+
# Compute max batch tokens and return
|
| 528 |
+
max_batch_tokens = floor(num / denum)
|
| 529 |
+
if max_batch_tokens > self._upper_bound_max_batch_tokens:
|
| 530 |
+
logger.info(f"{max_batch_tokens = } is too large, setting to {self._upper_bound_max_batch_tokens = }")
|
| 531 |
+
max_batch_tokens = self._upper_bound_max_batch_tokens
|
| 532 |
+
return max_batch_tokens
|
| 533 |
+
|
| 534 |
+
def compute_num_blocks(
|
| 535 |
+
self,
|
| 536 |
+
max_batch_tokens: int,
|
| 537 |
+
max_memory_percent: float = 0.9,
|
| 538 |
+
cache_dtype: torch.dtype = torch.float16,
|
| 539 |
+
) -> int:
|
| 540 |
+
"""Calculate number of cache blocks N given a fixed maximum token per token M. The formula for N is given by:
|
| 541 |
+
|
| 542 |
+
N = (available_memory - M * (peak_activation_per_token * activation_dtype + 28 + 4 * num_group))
|
| 543 |
+
/ (2 * (layer_group_size * page_size * cache_dtype + 2 * num_group) + M * (num_attention_masks * activation_dtype_size))
|
| 544 |
+
"""
|
| 545 |
+
cache_memory = self.get_available_memory(max_memory_percent)
|
| 546 |
+
# Compute numerator
|
| 547 |
+
num = cache_memory
|
| 548 |
+
num -= max_batch_tokens * self.peak_activation_per_token * self._activation_dtype.itemsize
|
| 549 |
+
num -= max_batch_tokens * (28 + 4 * self.num_groups)
|
| 550 |
+
# Compute denominator
|
| 551 |
+
denum = 2 * (self.group_size * self.page_size * cache_dtype.itemsize + 2 * self.num_groups)
|
| 552 |
+
denum += max_batch_tokens * (self.num_attention_masks * self._activation_dtype.itemsize)
|
| 553 |
+
denum += max_batch_tokens * self._activation_dtype.itemsize
|
| 554 |
+
# Compute cache size and return number of blocks
|
| 555 |
+
num_pages = floor(num / denum)
|
| 556 |
+
num_blocks = num_pages // self.block_size
|
| 557 |
+
if num_blocks > self._upper_bound_num_blocks:
|
| 558 |
+
logger.info(f"{num_blocks = } is too large, setting to {self._upper_bound_num_blocks = }")
|
| 559 |
+
num_blocks = self._upper_bound_num_blocks
|
| 560 |
+
return num_blocks
|
| 561 |
+
|
| 562 |
+
def compute_memory_footprint(
|
| 563 |
+
self,
|
| 564 |
+
num_blocks: Optional[int] = None,
|
| 565 |
+
max_batch_tokens: Optional[int] = None,
|
| 566 |
+
cache_dtype: torch.dtype = torch.float16,
|
| 567 |
+
) -> tuple[int, int, int]:
|
| 568 |
+
"""Calculate the memory footprint breakdown for a given number of blocks and maximum batch tokens. The memory
|
| 569 |
+
footprint is given by:
|
| 570 |
+
|
| 571 |
+
available_memory = sum([
|
| 572 |
+
MN * num_attention_masks * activation_dtype_size,
|
| 573 |
+
2N * (layer_group_size * page_size * cache_dtype + 2 * num_group),
|
| 574 |
+
M * (peak_activation_per_token * activation_dtype + 28 + 4 * num_group),
|
| 575 |
+
])
|
| 576 |
+
but is broken down below.
|
| 577 |
+
"""
|
| 578 |
+
num_pages = num_blocks * self.block_size
|
| 579 |
+
|
| 580 |
+
cache_memory_footprint = 2 * self.group_size * num_pages * self.page_size * cache_dtype.itemsize
|
| 581 |
+
|
| 582 |
+
activation_memory_footprint = self.peak_activation_per_token * self._activation_dtype.itemsize
|
| 583 |
+
activation_memory_footprint *= max_batch_tokens
|
| 584 |
+
|
| 585 |
+
inputs_outputs_positions_and_logits_memory_footprint = 4 * max_batch_tokens * 4 # second 4 is for int32 size
|
| 586 |
+
|
| 587 |
+
attention_memory_footprint = self.num_attention_masks * self._activation_dtype.itemsize
|
| 588 |
+
attention_memory_footprint *= num_pages * max_batch_tokens
|
| 589 |
+
|
| 590 |
+
cumulative_seqlens_memory_footprint = 3 * max_batch_tokens * 4 # 4 is for int32 size
|
| 591 |
+
|
| 592 |
+
write_index_memory_footprint = self.num_groups * max_batch_tokens * 4 # 4 is for int32 size
|
| 593 |
+
read_index_memory_footprint = self.num_groups * (num_pages + max_batch_tokens) * 4 # 4 is for int32 size
|
| 594 |
+
|
| 595 |
+
total_memory_footprint = sum(
|
| 596 |
+
[
|
| 597 |
+
cache_memory_footprint,
|
| 598 |
+
activation_memory_footprint,
|
| 599 |
+
inputs_outputs_positions_and_logits_memory_footprint,
|
| 600 |
+
attention_memory_footprint,
|
| 601 |
+
cumulative_seqlens_memory_footprint,
|
| 602 |
+
write_index_memory_footprint,
|
| 603 |
+
read_index_memory_footprint,
|
| 604 |
+
]
|
| 605 |
+
)
|
| 606 |
+
return total_memory_footprint
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/cache_manager.py
ADDED
|
@@ -0,0 +1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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 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 abc import ABC, abstractmethod
|
| 16 |
+
from collections import deque
|
| 17 |
+
from math import ceil
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
from .requests import logger
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class CacheAllocator(ABC):
|
| 24 |
+
"""Abstract base class for cache managers. Cache managers keep track of per-request cache allocations, determine
|
| 25 |
+
when a new physical block needs to be allocated and compute physical indices for reading or writing to the cache."""
|
| 26 |
+
|
| 27 |
+
_index: int
|
| 28 |
+
_block_table: dict[str, list[int]] # request_id -> list of block_ids allocated to the request
|
| 29 |
+
|
| 30 |
+
@abstractmethod
|
| 31 |
+
def allocate_blocks(self, n_blocks: int, request_id: str, free_blocks: deque[int]) -> Optional[int]:
|
| 32 |
+
"""Allocates n_blocks for a given request_id. Returns the num of blocks allocated if successful and None
|
| 33 |
+
otherwise."""
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
def free_blocks(self, request_id: str, free_blocks: deque[int]) -> None:
|
| 37 |
+
"""Frees all blocks associated with a request_id."""
|
| 38 |
+
if request_id in self._block_table:
|
| 39 |
+
blocks_to_free = self._block_table.pop(request_id)
|
| 40 |
+
free_blocks.extend(blocks_to_free)
|
| 41 |
+
else:
|
| 42 |
+
logger.warning(
|
| 43 |
+
f"CacheAllocator {self._index} attempted to free blocks for non-existent request_id: {request_id}"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
@abstractmethod
|
| 47 |
+
def get_read_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
|
| 48 |
+
"""Returns the physical indices of where to read request_id's cache in the cache tensor."""
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
@abstractmethod
|
| 52 |
+
def get_write_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
|
| 53 |
+
"""Returns the physical indices of where to write request_id's cache in the cache tensor."""
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
+
@abstractmethod
|
| 57 |
+
def get_seqlens_k(self, request_id: str, past_length: int, query_length: int) -> tuple[str, int]:
|
| 58 |
+
"""Returns the attention type of the cache allocator and the key sequence length for the given request_id."""
|
| 59 |
+
pass
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class FullAttentionCacheAllocator(CacheAllocator):
|
| 63 |
+
"""Cache manager for a group of full attention layers."""
|
| 64 |
+
|
| 65 |
+
def __init__(self, index: int, block_size: int) -> None:
|
| 66 |
+
"""Initializes the cache manager for a group of full attention layers.
|
| 67 |
+
Args:
|
| 68 |
+
- index: the index of the associated layer group
|
| 69 |
+
- block_size: the size of the blocks in the cache
|
| 70 |
+
"""
|
| 71 |
+
self._index = index
|
| 72 |
+
self.block_size = block_size
|
| 73 |
+
self._block_table = {}
|
| 74 |
+
|
| 75 |
+
def allocate_blocks(self, n_blocks: int, request_id: str, free_blocks: deque[int]) -> Optional[int]:
|
| 76 |
+
"""Allocate blocks for a given request_id. Returns the number of blocks allocated if successful and None
|
| 77 |
+
otherwise. For group of full attention layers, we always allocate the number of requested blocks."""
|
| 78 |
+
if len(free_blocks) < n_blocks:
|
| 79 |
+
return None
|
| 80 |
+
if request_id not in self._block_table:
|
| 81 |
+
self._block_table[request_id] = []
|
| 82 |
+
self._block_table[request_id].extend(free_blocks.popleft() for _ in range(n_blocks))
|
| 83 |
+
return n_blocks
|
| 84 |
+
|
| 85 |
+
def get_read_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
|
| 86 |
+
"""Returns the physical indices of where to read request_id's cache. For a group of full attention layers, we
|
| 87 |
+
first write the new cache to the cache tensor and then read the entire cache from the beginning to the end."""
|
| 88 |
+
# Retrieve the block table for the request and raise an error if it doesn't exist
|
| 89 |
+
block_table = self._block_table.get(request_id)
|
| 90 |
+
if block_table is None:
|
| 91 |
+
raise ValueError(f"No block table found for request {request_id}")
|
| 92 |
+
# Compute the physical indices
|
| 93 |
+
physical_indices = []
|
| 94 |
+
for i in range(past_length + query_length):
|
| 95 |
+
block_idx = i // self.block_size
|
| 96 |
+
block_offset = i % self.block_size
|
| 97 |
+
physical_index = block_table[block_idx] * self.block_size + block_offset
|
| 98 |
+
physical_indices.append(physical_index)
|
| 99 |
+
return physical_indices
|
| 100 |
+
|
| 101 |
+
def get_write_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
|
| 102 |
+
"""Returns the physical indices for writing to the cache. For a group of full attention layers, we write the new
|
| 103 |
+
cache as a continuation of the existing cache for the same request."""
|
| 104 |
+
block_table = self._block_table.get(request_id)
|
| 105 |
+
if block_table is None:
|
| 106 |
+
raise ValueError(f"No block table found for request {request_id}")
|
| 107 |
+
# Compute the physical indices
|
| 108 |
+
physical_indices = []
|
| 109 |
+
for i in range(past_length, past_length + query_length):
|
| 110 |
+
block_idx = i // self.block_size
|
| 111 |
+
block_offset = i % self.block_size
|
| 112 |
+
physical_index = block_table[block_idx] * self.block_size + block_offset
|
| 113 |
+
physical_indices.append(physical_index)
|
| 114 |
+
return physical_indices
|
| 115 |
+
|
| 116 |
+
def get_seqlens_k(self, request_id: str, past_length: int, query_length: int) -> tuple[str, int]:
|
| 117 |
+
"""Returns the attention type of the cache allocator and the key sequence length for the given request_id."""
|
| 118 |
+
seqlens_k = past_length + query_length
|
| 119 |
+
return "full_attention", seqlens_k
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class SlidingAttentionCacheAllocator(CacheAllocator):
|
| 123 |
+
"""Cache manager for sliding window attention layers."""
|
| 124 |
+
|
| 125 |
+
def __init__(self, index: int, block_size: int, sliding_window: int) -> None:
|
| 126 |
+
"""Initializes the cache manager for a group of sliding window attention layers.
|
| 127 |
+
Args:
|
| 128 |
+
- index: the index of the associated layer group
|
| 129 |
+
- block_size: the size of the blocks in the cache
|
| 130 |
+
- sliding_window: the size of the sliding window
|
| 131 |
+
"""
|
| 132 |
+
self._index = index
|
| 133 |
+
self.block_size = block_size
|
| 134 |
+
self.sliding_window = sliding_window
|
| 135 |
+
self._max_blocks_per_request = ceil(self.sliding_window / self.block_size)
|
| 136 |
+
self._block_table = {}
|
| 137 |
+
|
| 138 |
+
def allocate_blocks(self, n_blocks: int, request_id: str, free_blocks: deque[int]) -> Optional[int]:
|
| 139 |
+
"""Allocate blocks for a given request_id. Returns the number of blocks allocated if successful and None
|
| 140 |
+
otherwise. For group of sliding window attention layers, we only allocate up to the point where we can fit an
|
| 141 |
+
entire sliding window in the cache tensor."""
|
| 142 |
+
if request_id not in self._block_table:
|
| 143 |
+
self._block_table[request_id] = []
|
| 144 |
+
# Early return if we are already at the max number of blocks per request
|
| 145 |
+
already_allocated = len(self._block_table[request_id])
|
| 146 |
+
if already_allocated == self._max_blocks_per_request:
|
| 147 |
+
return 0
|
| 148 |
+
# Compute actual number of blocks to allocate
|
| 149 |
+
after_allocation = min(already_allocated + n_blocks, self._max_blocks_per_request)
|
| 150 |
+
actual_n_blocks = after_allocation - already_allocated
|
| 151 |
+
# Classic allocation
|
| 152 |
+
if len(free_blocks) < actual_n_blocks:
|
| 153 |
+
return None
|
| 154 |
+
self._block_table[request_id].extend(free_blocks.popleft() for _ in range(actual_n_blocks))
|
| 155 |
+
return actual_n_blocks
|
| 156 |
+
|
| 157 |
+
def get_read_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
|
| 158 |
+
"""Returns the physical indices of where to read request_id's cache in the cache tensor.
|
| 159 |
+
For a group of sliding window attention layers, we read from the cache tensor before writing on it, because the
|
| 160 |
+
new cache can overwrite the old one. To form the cache + new key / values states, we read the at most
|
| 161 |
+
sliding_window - 1 cache page and then manually add the new key / values states after. Hence the -1 indices
|
| 162 |
+
which indicate where to store the new key or values indices."""
|
| 163 |
+
# Retrieve the block table for the request and raise an error if it doesn't exist
|
| 164 |
+
block_table = self._block_table.get(request_id)
|
| 165 |
+
if block_table is None:
|
| 166 |
+
raise ValueError(f"No block table found for request {request_id}")
|
| 167 |
+
# Apply sliding window
|
| 168 |
+
start_index = 0 if past_length < self.sliding_window else past_length % self.sliding_window
|
| 169 |
+
cache_length = min(past_length, self.sliding_window - 1)
|
| 170 |
+
# Compute the physical indices
|
| 171 |
+
physical_indices = []
|
| 172 |
+
for i in range(start_index, start_index + cache_length):
|
| 173 |
+
i %= self.sliding_window
|
| 174 |
+
block_idx = i // self.block_size
|
| 175 |
+
block_offset = i % self.block_size
|
| 176 |
+
physical_index = block_table[block_idx] * self.block_size + block_offset
|
| 177 |
+
physical_indices.append(physical_index)
|
| 178 |
+
return physical_indices + [-1] * query_length
|
| 179 |
+
|
| 180 |
+
def get_write_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
|
| 181 |
+
"""Returns the physical indices of where to write request_id's cache in the cache tensor. For a group of
|
| 182 |
+
sliding window attention layers, we write the new cache in rolling-buffer kind of way: if we reach the end of
|
| 183 |
+
the allocated physical cache, we start writing from the beginning of the physical cache again."""
|
| 184 |
+
# Retrieve the block table for the request and raise an error if it doesn't exist
|
| 185 |
+
block_table = self._block_table.get(request_id)
|
| 186 |
+
if block_table is None:
|
| 187 |
+
raise ValueError(f"No block table found for request {request_id}")
|
| 188 |
+
# Apply sliding window
|
| 189 |
+
start_index = past_length % self.sliding_window
|
| 190 |
+
cache_length = min(query_length, self.sliding_window)
|
| 191 |
+
padding_length = query_length - cache_length
|
| 192 |
+
# Compute the physical indices
|
| 193 |
+
physical_indices = []
|
| 194 |
+
for i in range(start_index, start_index + cache_length):
|
| 195 |
+
i %= self.sliding_window
|
| 196 |
+
block_idx = i // self.block_size
|
| 197 |
+
block_offset = i % self.block_size
|
| 198 |
+
physical_index = block_table[block_idx] * self.block_size + block_offset
|
| 199 |
+
physical_indices.append(physical_index)
|
| 200 |
+
if padding_length > 0:
|
| 201 |
+
physical_indices = [-1] * padding_length + physical_indices
|
| 202 |
+
return physical_indices
|
| 203 |
+
|
| 204 |
+
def get_seqlens_k(self, request_id: str, past_length: int, query_length: int) -> tuple[str, int]:
|
| 205 |
+
"""Returns the attention type of the cache allocator and the key sequence length for the given request_id."""
|
| 206 |
+
seqlens_k = query_length + min(past_length, self.sliding_window - 1)
|
| 207 |
+
return "sliding_attention", seqlens_k
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
# TODO: test the impact of this
|
| 211 |
+
# def get_read_indices(self, request_id: str, past_length: int) -> list[int]:
|
| 212 |
+
# # Retrieve the block table for the request and raise an error if it doesn't exist
|
| 213 |
+
# block_table = self._block_table.get(request_id)
|
| 214 |
+
# if block_table is None:
|
| 215 |
+
# raise ValueError(f"No block table found for request {request_id}")
|
| 216 |
+
# # Compute the physical indices
|
| 217 |
+
# physical_indices = []
|
| 218 |
+
# n_left = past_length
|
| 219 |
+
# for block_idx in block_table:
|
| 220 |
+
# block_physical_index = block_idx * self.block_size
|
| 221 |
+
# pages_used = min(self.block_size, n_left)
|
| 222 |
+
# physical_indices.extend(block_physical_index + i for i in range(pages_used))
|
| 223 |
+
# n_left -= pages_used
|
| 224 |
+
# if n_left == 0:
|
| 225 |
+
# return physical_indices
|
| 226 |
+
# raise ValueError(f"Request {request_id} required too many indices: {past_length = } and {len(block_table) = }")
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/continuous_api.py
ADDED
|
@@ -0,0 +1,1047 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2020, NVIDIA CORPORATION. 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 |
+
import queue
|
| 17 |
+
import threading
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from functools import partial
|
| 20 |
+
from itertools import count
|
| 21 |
+
from time import perf_counter
|
| 22 |
+
from typing import Optional, Union
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
from torch import nn
|
| 26 |
+
from tqdm import tqdm
|
| 27 |
+
|
| 28 |
+
from ...configuration_utils import PretrainedConfig
|
| 29 |
+
from ...generation.configuration_utils import GenerationConfig
|
| 30 |
+
from ...utils.logging import logging
|
| 31 |
+
from ...utils.metrics import ContinuousBatchProcessorMetrics, attach_tracer, traced
|
| 32 |
+
from .cache import PagedAttentionCache
|
| 33 |
+
from .requests import GenerationOutput, RequestState, RequestStatus, get_device_and_memory_breakdown, logger
|
| 34 |
+
from .scheduler import SCHEDULER_MAPPING, FIFOScheduler, Scheduler
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def build_attention_mask(
|
| 38 |
+
attention_mask: torch.Tensor,
|
| 39 |
+
cumulative_seqlens_q: torch.Tensor,
|
| 40 |
+
cumulative_seqlens_k: torch.Tensor,
|
| 41 |
+
sliding_window: int = 1,
|
| 42 |
+
) -> None:
|
| 43 |
+
"""Builds an attention mask inplace using the cumulative seqlens of the query and key. If given a sliding window, it
|
| 44 |
+
will also apply a sliding window mask on top. The attention mask is not boolean, it uses zeroes and -inf (or its
|
| 45 |
+
equivalent) so it's more of an attention score bias tensor.
|
| 46 |
+
The attention mask is a block-diagonal matrix, with each block an attention mask for a single query-key pair.
|
| 47 |
+
Each of those block is built from a causal mask and, if there is a sliding window, a sliding window mask.
|
| 48 |
+
|
| 49 |
+
An example is represented below, with seqlen_k = 8, seqlen_q = 4 and sliding_window = 6:
|
| 50 |
+
|
| 51 |
+
CAUSAL MASK:
|
| 52 |
+
|
| 53 |
+
█ █ █ █ █ ░ ░ ░
|
| 54 |
+
█ █ █ █ █ █ ░ ░
|
| 55 |
+
█ █ █ █ █ █ █ ░
|
| 56 |
+
█ █ █ █ █ █ █ █
|
| 57 |
+
|
| 58 |
+
SLIDING WINDOW MASK:
|
| 59 |
+
┌──────────────────────── seqlen_k - seqlen_q - sliding_window = 8 - 4 - 6 = -2 offset to the right
|
| 60 |
+
<─┴─>
|
| 61 |
+
░ █ | █ █ █ █ █ █ █ █
|
| 62 |
+
░ ░ | █ █ █ █ █ █ █ █
|
| 63 |
+
░ ░ | ░ █ █ █ █ █ █ █
|
| 64 |
+
░ ░ | ░ ░ █ █ █ █ █ █
|
| 65 |
+
|
| 66 |
+
ATTENTION MASK (sum of causal and sliding window masks):
|
| 67 |
+
|
| 68 |
+
█ █ █ █ █ ░ ░ ░
|
| 69 |
+
█ █ █ █ █ █ ░ ░
|
| 70 |
+
░ █ █ █ █ █ █ ░
|
| 71 |
+
░ ░ █ █ █ █ █ █
|
| 72 |
+
|
| 73 |
+
Another example with seqlen_k = 5, seqlen_q = 3 and sliding_window = 2:
|
| 74 |
+
|
| 75 |
+
CAUSAL MASK:
|
| 76 |
+
|
| 77 |
+
█ █ █ ░ ░
|
| 78 |
+
█ █ █ █ ░
|
| 79 |
+
█ █ █ █ █
|
| 80 |
+
|
| 81 |
+
SLIDING WINDOW MASK:
|
| 82 |
+
┌──────────────────────── seqlen_k - seqlen_q - sliding_window = 5 - 3 - 2 = 0 offset to the right
|
| 83 |
+
<┴>
|
| 84 |
+
| ░ █ █ █ █
|
| 85 |
+
| ░ ░ █ █ █
|
| 86 |
+
| ░ ░ ░ █ █
|
| 87 |
+
|
| 88 |
+
ATTENTION MASK (sum of causal and sliding window masks):
|
| 89 |
+
|
| 90 |
+
░ █ █ ░ ░
|
| 91 |
+
░ ░ █ █ ░
|
| 92 |
+
░ ░ ░ █ █
|
| 93 |
+
|
| 94 |
+
"""
|
| 95 |
+
min_value = torch.finfo(attention_mask.dtype).min
|
| 96 |
+
for i in range(len(cumulative_seqlens_q) - 1):
|
| 97 |
+
seqlen_q = cumulative_seqlens_q[i + 1] - cumulative_seqlens_q[i]
|
| 98 |
+
seqlen_k = cumulative_seqlens_k[i + 1] - cumulative_seqlens_k[i]
|
| 99 |
+
if seqlen_q < seqlen_k and seqlen_q >= 1:
|
| 100 |
+
causal_diagonal = seqlen_k - seqlen_q + 1
|
| 101 |
+
else:
|
| 102 |
+
causal_diagonal = 1
|
| 103 |
+
query_range = slice(cumulative_seqlens_q[i], cumulative_seqlens_q[i + 1])
|
| 104 |
+
key_range = slice(cumulative_seqlens_k[i], cumulative_seqlens_k[i + 1])
|
| 105 |
+
# Apply causal mask
|
| 106 |
+
minus_inf = torch.full(
|
| 107 |
+
attention_mask[..., query_range, key_range].shape,
|
| 108 |
+
min_value,
|
| 109 |
+
dtype=attention_mask.dtype,
|
| 110 |
+
device=attention_mask.device,
|
| 111 |
+
)
|
| 112 |
+
masked = torch.triu(minus_inf, diagonal=causal_diagonal)
|
| 113 |
+
# Apply sliding window mask if needed
|
| 114 |
+
if sliding_window > 1:
|
| 115 |
+
sliding_diagonal = seqlen_k - seqlen_q - sliding_window
|
| 116 |
+
masked += torch.tril(minus_inf, diagonal=sliding_diagonal)
|
| 117 |
+
# Replace in attention mask
|
| 118 |
+
attention_mask[..., query_range, key_range] = masked
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@dataclass
|
| 122 |
+
class PagedAttentionArgs:
|
| 123 |
+
input_ids: torch.Tensor
|
| 124 |
+
attention_mask: Optional[torch.Tensor]
|
| 125 |
+
position_ids: torch.Tensor
|
| 126 |
+
cumulative_seqlens_q: torch.Tensor
|
| 127 |
+
cumulative_seqlens_k: torch.Tensor
|
| 128 |
+
max_seqlen_q: int
|
| 129 |
+
max_seqlen_k: int
|
| 130 |
+
write_index: list[torch.Tensor]
|
| 131 |
+
read_index: list[torch.Tensor]
|
| 132 |
+
logits_indices: torch.Tensor
|
| 133 |
+
cache: PagedAttentionCache
|
| 134 |
+
use_cache: bool = False
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# Continuous Batch Processor (Internal Logic)
|
| 138 |
+
@attach_tracer()
|
| 139 |
+
class ContinuousBatchProcessor:
|
| 140 |
+
def __init__(
|
| 141 |
+
self,
|
| 142 |
+
cache: PagedAttentionCache,
|
| 143 |
+
config: PretrainedConfig,
|
| 144 |
+
generation_config: GenerationConfig,
|
| 145 |
+
input_queue: queue.Queue,
|
| 146 |
+
output_queue: queue.Queue,
|
| 147 |
+
stop_event: threading.Event,
|
| 148 |
+
model_device: torch.device,
|
| 149 |
+
model_dtype: torch.dtype,
|
| 150 |
+
scheduler: Scheduler,
|
| 151 |
+
streaming: bool = False,
|
| 152 |
+
manual_eviction: bool = False,
|
| 153 |
+
slice_inputs: bool = True, # TODO: There should be an heuristic to decide on slicing, compile, cuda graphs...
|
| 154 |
+
) -> None:
|
| 155 |
+
"""Initialize the continuous batch processor.
|
| 156 |
+
|
| 157 |
+
Args:
|
| 158 |
+
cache: A [`PagedAttentionCache`] object
|
| 159 |
+
config: The model configuration
|
| 160 |
+
generation_config: The generation configuration
|
| 161 |
+
input_queue: Queue for incoming requests
|
| 162 |
+
output_queue: Queue for outgoing results
|
| 163 |
+
stop_event: Event to signal processing should stop
|
| 164 |
+
model_device: Device for model inputs/outputs
|
| 165 |
+
model_dtype: Data type for model inputs/outputs
|
| 166 |
+
scheduler: The [`Scheduler`] to use
|
| 167 |
+
streaming: Whether to stream tokens as they're generated
|
| 168 |
+
manual_eviction: Whether to manually evict blocks from the cache
|
| 169 |
+
slice_inputs: Whether to slice the inputs to the model
|
| 170 |
+
"""
|
| 171 |
+
self.cache = cache
|
| 172 |
+
self.config = config
|
| 173 |
+
self.generation_config = generation_config
|
| 174 |
+
self.input_queue = input_queue
|
| 175 |
+
self.output_queue = output_queue
|
| 176 |
+
self.stop_event = stop_event
|
| 177 |
+
self.model_device = model_device
|
| 178 |
+
self.model_dtype = model_dtype
|
| 179 |
+
self.scheduler = scheduler
|
| 180 |
+
self.streaming = streaming
|
| 181 |
+
self.manual_eviction = manual_eviction
|
| 182 |
+
self.slice_inputs = slice_inputs
|
| 183 |
+
|
| 184 |
+
# Retrieve the size of the sliding window if there is one
|
| 185 |
+
self.sliding_window = 1 if getattr(config, "sliding_window", None) is None else config.sliding_window
|
| 186 |
+
|
| 187 |
+
self.requests_in_batch: list[RequestState] = []
|
| 188 |
+
|
| 189 |
+
# Set up metrics collector
|
| 190 |
+
self.max_batch_tokens = cache.max_batch_tokens
|
| 191 |
+
self.metrics = ContinuousBatchProcessorMetrics(cache.max_batch_tokens)
|
| 192 |
+
|
| 193 |
+
# Setup static tensors
|
| 194 |
+
self.total_query_length = 0
|
| 195 |
+
self.total_key_length = 0
|
| 196 |
+
self.total_batch_size = 0
|
| 197 |
+
self.setup_static_tensors(cache.num_groups)
|
| 198 |
+
|
| 199 |
+
@traced(standalone=True)
|
| 200 |
+
def setup_static_tensors(self, num_groups: int) -> None:
|
| 201 |
+
T = self.max_batch_tokens
|
| 202 |
+
num_pages = self.cache.num_blocks * self.cache.block_size
|
| 203 |
+
self.tensor_metadata = {"dtype": torch.int32, "device": self.model_device}
|
| 204 |
+
|
| 205 |
+
# Some tensors always have the same shape regardless of the model
|
| 206 |
+
self.input_ids = torch.empty((1, T), **self.tensor_metadata)
|
| 207 |
+
self.position_ids = torch.empty((1, T), **self.tensor_metadata)
|
| 208 |
+
self.cumulative_seqlens_q = torch.empty((T + 1,), **self.tensor_metadata)
|
| 209 |
+
self.max_seqlen_q = 0
|
| 210 |
+
self.logits_indices = torch.empty((T,), **self.tensor_metadata)
|
| 211 |
+
self.output_ids = torch.empty((1, T), **self.tensor_metadata)
|
| 212 |
+
|
| 213 |
+
# For some kwargs, we have a dict of tensors with as many items as there are attention types
|
| 214 |
+
layer_types = getattr(self.config, "layer_types", None)
|
| 215 |
+
if layer_types is None:
|
| 216 |
+
sliding_window = getattr(self.config, "sliding_window", 1)
|
| 217 |
+
layer_types = ["full_attention"] if sliding_window in [1, None] else ["sliding_attention"]
|
| 218 |
+
layer_types = list(set(layer_types))
|
| 219 |
+
|
| 220 |
+
self.cumulative_seqlens_k = {
|
| 221 |
+
layer_type: torch.empty((T + 1), **self.tensor_metadata) for layer_type in layer_types
|
| 222 |
+
}
|
| 223 |
+
self.max_seqlen_k = dict.fromkeys(layer_types, 0)
|
| 224 |
+
|
| 225 |
+
if self.return_attention_mask():
|
| 226 |
+
attn_mask_kwargs = {
|
| 227 |
+
"size": (1, 1, T, num_pages + T),
|
| 228 |
+
"dtype": self.model_dtype,
|
| 229 |
+
"device": self.model_device,
|
| 230 |
+
}
|
| 231 |
+
self.attention_mask = {layer_type: torch.empty(**attn_mask_kwargs) for layer_type in layer_types}
|
| 232 |
+
else:
|
| 233 |
+
self.attention_mask = None
|
| 234 |
+
|
| 235 |
+
# For other kwargs, we need a list of tensors with as many tensors as there are groups
|
| 236 |
+
self.write_index_storage = [torch.empty((T,), **self.tensor_metadata) for _ in range(num_groups)]
|
| 237 |
+
self.read_index_storage = [torch.empty((num_pages + T), **self.tensor_metadata) for _ in range(num_groups)]
|
| 238 |
+
# For read index, the +T is because there are -1 for seqlen_q when model uses a sliding window
|
| 239 |
+
|
| 240 |
+
# After allocating empty tensors, we reset them to the right value
|
| 241 |
+
self.reset_static_tensors(full_reset=True)
|
| 242 |
+
|
| 243 |
+
def return_attention_mask(self) -> bool:
|
| 244 |
+
return self.config._attn_implementation != "paged_attention" # we set `is_causal` to True in paged call
|
| 245 |
+
|
| 246 |
+
@traced
|
| 247 |
+
@torch.no_grad()
|
| 248 |
+
def reset_static_tensors(self, full_reset: bool = False):
|
| 249 |
+
"""Reset static tensors for the next batch. In between batches, reset only the parts that were used in the last
|
| 250 |
+
batch, but for initialisation, we can reset everything using the (full_reset) flag."""
|
| 251 |
+
# Compute the slice to reset
|
| 252 |
+
if full_reset or not self.slice_inputs:
|
| 253 |
+
q_len = self.write_index_storage[0].size(-1)
|
| 254 |
+
k_len = self.read_index_storage[0].size(-1)
|
| 255 |
+
b_size = self.write_index_storage[0].size(0)
|
| 256 |
+
else:
|
| 257 |
+
q_len = self.total_query_length
|
| 258 |
+
k_len = self.total_key_length
|
| 259 |
+
b_size = self.total_batch_size
|
| 260 |
+
|
| 261 |
+
# Reset the attributes that always have the same shape
|
| 262 |
+
self.input_ids[:, :q_len].zero_()
|
| 263 |
+
self.position_ids[:, :q_len].zero_()
|
| 264 |
+
self.cumulative_seqlens_q[: b_size + 1].zero_()
|
| 265 |
+
self.max_seqlen_q = 0
|
| 266 |
+
self.logits_indices[:q_len].fill_(-1)
|
| 267 |
+
self.output_ids[:, :q_len].fill_(-1)
|
| 268 |
+
|
| 269 |
+
# Reset the attributes that are either tensors or dict of tensors
|
| 270 |
+
for layer_type in self.cumulative_seqlens_k:
|
| 271 |
+
self.cumulative_seqlens_k[layer_type][: b_size + 1].zero_()
|
| 272 |
+
self.max_seqlen_k[layer_type] = 0
|
| 273 |
+
if self.attention_mask is not None:
|
| 274 |
+
self.attention_mask[layer_type][:, :, :q_len, :k_len].fill_(torch.finfo(self.model_dtype).min)
|
| 275 |
+
|
| 276 |
+
# Reset the attributes that are lists of tensors
|
| 277 |
+
for i in range(self.cache.num_groups):
|
| 278 |
+
self.write_index_storage[i][:q_len].fill_(-1)
|
| 279 |
+
self.read_index_storage[i][: q_len + k_len].fill_(-1)
|
| 280 |
+
|
| 281 |
+
def get_model_kwargs(self) -> PagedAttentionArgs:
|
| 282 |
+
"""Get model keyword arguments for the current batch."""
|
| 283 |
+
# Compute the slice to return
|
| 284 |
+
q_len = self.total_query_length if self.slice_inputs else self.write_index_storage[0].size(-1)
|
| 285 |
+
b_size = self.total_batch_size if self.slice_inputs else self.cumulative_seqlens_q.size(-1) - 1
|
| 286 |
+
|
| 287 |
+
# Prepare the kwargs, the attributes that are either tensors or dict of tensors are initialized to empty dicts
|
| 288 |
+
kwargs = {
|
| 289 |
+
"input_ids": self.input_ids[:, :q_len],
|
| 290 |
+
"position_ids": self.position_ids[:, :q_len],
|
| 291 |
+
"cu_seq_lens_q": self.cumulative_seqlens_q[: b_size + 1],
|
| 292 |
+
"max_seqlen_q": self.max_seqlen_q,
|
| 293 |
+
"logits_indices": self.logits_indices[:q_len],
|
| 294 |
+
"cu_seq_lens_k": {},
|
| 295 |
+
"max_seqlen_k": {},
|
| 296 |
+
"attention_mask": {},
|
| 297 |
+
"read_index": self.read_index, # slicing is done during building
|
| 298 |
+
"write_index": self.write_index, # slicing is done during building
|
| 299 |
+
"cache": self.cache,
|
| 300 |
+
"use_cache": False,
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
# For the attributes that are dict of tensors, we replace the dict with a tensor if there is only one entry
|
| 304 |
+
layer_types = list(self.cumulative_seqlens_k.keys())
|
| 305 |
+
if len(layer_types) > 1:
|
| 306 |
+
for layer_type, seqlens_k in self.cumulative_seqlens_k.items():
|
| 307 |
+
kwargs["cu_seq_lens_k"][layer_type] = seqlens_k[: b_size + 1]
|
| 308 |
+
kwargs["max_seqlen_k"][layer_type] = self.max_seqlen_k[layer_type]
|
| 309 |
+
if self.attention_mask is not None:
|
| 310 |
+
k_len = seqlens_k[b_size] if self.slice_inputs else self.attention_mask[layer_type].size(-1)
|
| 311 |
+
kwargs["attention_mask"][layer_type] = self.attention_mask[layer_type][..., :q_len, :k_len]
|
| 312 |
+
else:
|
| 313 |
+
layer_type = layer_types[0]
|
| 314 |
+
kwargs["cu_seq_lens_k"] = self.cumulative_seqlens_k[layer_type][: b_size + 1]
|
| 315 |
+
kwargs["max_seqlen_k"] = self.max_seqlen_k[layer_type]
|
| 316 |
+
if self.attention_mask is not None:
|
| 317 |
+
k_len = self.cumulative_seqlens_k[layer_type][b_size]
|
| 318 |
+
k_len = k_len if self.slice_inputs else self.attention_mask[layer_type].size(-1)
|
| 319 |
+
kwargs["attention_mask"] = self.attention_mask[layer_type][..., :q_len, :k_len]
|
| 320 |
+
|
| 321 |
+
if self.attention_mask is None:
|
| 322 |
+
kwargs["attention_mask"] = None
|
| 323 |
+
return kwargs
|
| 324 |
+
|
| 325 |
+
def __repr__(self):
|
| 326 |
+
return (
|
| 327 |
+
f"ContinuousBatchProcessor(input_queue={self.input_queue}, output_queue={self.output_queue}, "
|
| 328 |
+
f"active_requests={self.scheduler.active_requests}, waiting_requests={self.scheduler.waiting_requests})"
|
| 329 |
+
+ self.get_model_kwargs().__repr__()
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
@traced
|
| 333 |
+
def _get_new_requests(self):
|
| 334 |
+
"""Pull new requests from the input queue and add to waiting list."""
|
| 335 |
+
while not self.input_queue.empty():
|
| 336 |
+
try:
|
| 337 |
+
state = self.input_queue.get_nowait()
|
| 338 |
+
if state is None: # Sentinel value
|
| 339 |
+
continue
|
| 340 |
+
self.scheduler.add_waiting_request(state)
|
| 341 |
+
|
| 342 |
+
except queue.Empty:
|
| 343 |
+
break
|
| 344 |
+
except Exception as e:
|
| 345 |
+
logger.error(f"Error processing new request: {e}", exc_info=True)
|
| 346 |
+
state: RequestState = locals().get("state")
|
| 347 |
+
if state is not None:
|
| 348 |
+
self._handle_request_error(e, state)
|
| 349 |
+
|
| 350 |
+
@traced
|
| 351 |
+
def _handle_request_error(self, error, state: RequestState):
|
| 352 |
+
"""Handle general request processing error."""
|
| 353 |
+
state.status = RequestStatus.FAILED
|
| 354 |
+
state.error = str(error)
|
| 355 |
+
|
| 356 |
+
# Include any generated tokens if this is an active request
|
| 357 |
+
if isinstance(state.request_id, str):
|
| 358 |
+
state.static_outputs = self.scheduler.get_active_request_static_outputs(state.request_id)
|
| 359 |
+
else:
|
| 360 |
+
state.static_outputs = []
|
| 361 |
+
|
| 362 |
+
self.metrics.record_request_completion(state.created_time, state.request_id)
|
| 363 |
+
self.output_queue.put(state.to_generation_output())
|
| 364 |
+
|
| 365 |
+
@traced
|
| 366 |
+
def prepare_next_batch(self) -> bool:
|
| 367 |
+
"""Prepare tensors and metadata for the next model forward pass. Returns True if there are requests to process,
|
| 368 |
+
False otherwise."""
|
| 369 |
+
|
| 370 |
+
# Get new requests from the queue, stop if there are no pending requests
|
| 371 |
+
self._get_new_requests()
|
| 372 |
+
self.scheduler.clear_cancelled_requests()
|
| 373 |
+
if not self.scheduler.has_pending_requests():
|
| 374 |
+
return False
|
| 375 |
+
self.metrics.record_queue_metrics(len(self.scheduler.active_requests), len(self.scheduler.waiting_requests))
|
| 376 |
+
|
| 377 |
+
# Schedule the next batch of requests, stop if there are no requests in the batch
|
| 378 |
+
self.requests_in_batch = self.scheduler.schedule_batch(self.max_batch_tokens)
|
| 379 |
+
if not self.requests_in_batch:
|
| 380 |
+
return False
|
| 381 |
+
self.metrics.record_batch_metrics(self.requests_in_batch)
|
| 382 |
+
|
| 383 |
+
# Reset the static tensors used for storage
|
| 384 |
+
self.reset_static_tensors() # TODO: with slice_inputs, this might be unnecessary
|
| 385 |
+
|
| 386 |
+
# Prepare accumulators
|
| 387 |
+
self.total_query_length = 0
|
| 388 |
+
self.total_key_length = 0
|
| 389 |
+
self.total_batch_size = 0
|
| 390 |
+
|
| 391 |
+
input_ids = []
|
| 392 |
+
position_ids = []
|
| 393 |
+
cumulative_seqlens_q = [0]
|
| 394 |
+
logits_indices = []
|
| 395 |
+
|
| 396 |
+
if isinstance(self.cumulative_seqlens_k, dict):
|
| 397 |
+
cumulative_seqlens_k = {layer_type: [0] for layer_type in self.cumulative_seqlens_k}
|
| 398 |
+
else:
|
| 399 |
+
cumulative_seqlens_k = [0]
|
| 400 |
+
|
| 401 |
+
read_index = [[] for _ in range(self.cache.num_groups)]
|
| 402 |
+
write_index = [[] for _ in range(self.cache.num_groups)]
|
| 403 |
+
|
| 404 |
+
# Go through all the requests in the batch
|
| 405 |
+
for state in self.requests_in_batch:
|
| 406 |
+
# First we retrieve the lengths related to the request
|
| 407 |
+
past_length = state.position_offset
|
| 408 |
+
query_length = len(state.prompt_ids)
|
| 409 |
+
seqlens_k = self.cache.get_seqlens_k(state.request_id, past_length, query_length)
|
| 410 |
+
|
| 411 |
+
# Then we update the total lengths that are used for slicing
|
| 412 |
+
self.total_query_length += query_length
|
| 413 |
+
# total_key_length is used to slice the keys so we need to take the max of all the key lengths
|
| 414 |
+
self.total_key_length += max(seqlens_k.values())
|
| 415 |
+
self.total_batch_size += 1
|
| 416 |
+
# And the attribute tracking the position in the request object
|
| 417 |
+
state.position_offset += query_length
|
| 418 |
+
|
| 419 |
+
# Then we accumulate for the object used in the kwargs
|
| 420 |
+
input_ids.extend(state.prompt_ids)
|
| 421 |
+
position_ids.extend(range(past_length, past_length + query_length))
|
| 422 |
+
cumulative_seqlens_q.append(cumulative_seqlens_q[-1] + query_length)
|
| 423 |
+
self.max_seqlen_q = max(self.max_seqlen_q, query_length)
|
| 424 |
+
|
| 425 |
+
if not state.remaining_prompt_ids:
|
| 426 |
+
logits_indices.append(cumulative_seqlens_q[-1] - 1)
|
| 427 |
+
|
| 428 |
+
for layer_type, layer_type_seqlen_k in seqlens_k.items():
|
| 429 |
+
cumulative_seqlens_k[layer_type].append(cumulative_seqlens_k[layer_type][-1] + layer_type_seqlen_k)
|
| 430 |
+
self.max_seqlen_k[layer_type] = max(self.max_seqlen_k[layer_type], layer_type_seqlen_k)
|
| 431 |
+
|
| 432 |
+
self.cache.extend_read_indices(state.request_id, past_length, query_length, read_index)
|
| 433 |
+
self.cache.extend_write_indices(state.request_id, past_length, query_length, write_index)
|
| 434 |
+
|
| 435 |
+
# When looping over request is done, we can build the actual tensors
|
| 436 |
+
self._build_tensors(
|
| 437 |
+
input_ids,
|
| 438 |
+
position_ids,
|
| 439 |
+
read_index,
|
| 440 |
+
write_index,
|
| 441 |
+
cumulative_seqlens_q,
|
| 442 |
+
cumulative_seqlens_k,
|
| 443 |
+
logits_indices,
|
| 444 |
+
)
|
| 445 |
+
self.metrics.record_kv_cache_memory_metrics(self.cache)
|
| 446 |
+
|
| 447 |
+
if logger.isEnabledFor(logging.DEBUG):
|
| 448 |
+
if isinstance(self.cumulative_seqlens_k, dict):
|
| 449 |
+
ck = max(cumulative_seqlens_k[layer_type][-1] for layer_type in self.cumulative_seqlens_k)
|
| 450 |
+
else:
|
| 451 |
+
ck = cumulative_seqlens_k[-1]
|
| 452 |
+
logger.debug(
|
| 453 |
+
f"Scheduled: {len(self.requests_in_batch)}, Waiting: {len(self.scheduler.waiting_requests)}, "
|
| 454 |
+
f"Active: {len(self.scheduler.active_requests)}. cum Q: {cumulative_seqlens_q[-1]}. "
|
| 455 |
+
f"cum KV: {ck}, free blocks: {self.cache.get_num_free_blocks()}"
|
| 456 |
+
)
|
| 457 |
+
return True
|
| 458 |
+
|
| 459 |
+
@traced
|
| 460 |
+
def _build_tensors(
|
| 461 |
+
self,
|
| 462 |
+
input_ids: list[int],
|
| 463 |
+
position_ids: list[int],
|
| 464 |
+
read_index: list[list[int]],
|
| 465 |
+
write_index: list[list[int]],
|
| 466 |
+
cumulative_seqlens_q: list[int],
|
| 467 |
+
cumulative_seqlens_k: Union[list[int], dict[str, list[int]]],
|
| 468 |
+
logits_indices: list[int],
|
| 469 |
+
) -> None:
|
| 470 |
+
"""Builds the actual tensors for the current batch, by modifying the already allocated tensors in place."""
|
| 471 |
+
to_tensor = partial(torch.tensor, **self.tensor_metadata)
|
| 472 |
+
|
| 473 |
+
# Those kwargs always have the same type regardless of the model
|
| 474 |
+
self.input_ids[:, : len(input_ids)] = to_tensor(input_ids)
|
| 475 |
+
self.position_ids[:, : len(position_ids)] = to_tensor(position_ids)
|
| 476 |
+
self.cumulative_seqlens_q[: len(cumulative_seqlens_q)] = to_tensor(cumulative_seqlens_q)
|
| 477 |
+
self.logits_indices[: len(logits_indices)] = to_tensor(logits_indices)
|
| 478 |
+
|
| 479 |
+
# Those kwargs are either dict of tensors or tensors, so we need to handle both cases
|
| 480 |
+
for layer_type, layer_type_seqlens_k in cumulative_seqlens_k.items():
|
| 481 |
+
self.cumulative_seqlens_k[layer_type][: len(layer_type_seqlens_k)] = to_tensor(layer_type_seqlens_k)
|
| 482 |
+
if self.attention_mask is not None:
|
| 483 |
+
build_attention_mask(
|
| 484 |
+
attention_mask=self.attention_mask[layer_type],
|
| 485 |
+
cumulative_seqlens_q=cumulative_seqlens_q,
|
| 486 |
+
cumulative_seqlens_k=layer_type_seqlens_k,
|
| 487 |
+
sliding_window=self.sliding_window if layer_type == "sliding_attention" else 1,
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
# The index only contain references to the storage tensors, so we update the storage and their references
|
| 491 |
+
self.read_index = []
|
| 492 |
+
self.write_index = []
|
| 493 |
+
for i, group_read_indices, group_write_indices in zip(count(), read_index, write_index):
|
| 494 |
+
# Write in the actual tensors
|
| 495 |
+
self.read_index_storage[i][: len(group_read_indices)] = to_tensor(group_read_indices)
|
| 496 |
+
self.write_index_storage[i][: len(group_write_indices)] = to_tensor(group_write_indices)
|
| 497 |
+
# Slice to the right size
|
| 498 |
+
r = len(group_read_indices) if self.slice_inputs else self.read_index_storage[i].size(-1)
|
| 499 |
+
w = len(group_write_indices) if self.slice_inputs else self.write_index_storage[i].size(-1)
|
| 500 |
+
# Add to the index
|
| 501 |
+
self.read_index.append(self.read_index_storage[i][:r])
|
| 502 |
+
self.write_index.append(self.write_index_storage[i][:w])
|
| 503 |
+
|
| 504 |
+
@traced
|
| 505 |
+
def _sync(self):
|
| 506 |
+
if self.output_ids is not None:
|
| 507 |
+
try:
|
| 508 |
+
out = self.output_ids.tolist()[0] # should be the only sync we do
|
| 509 |
+
except Exception:
|
| 510 |
+
out = [0, 1]
|
| 511 |
+
else:
|
| 512 |
+
out = [0, 0]
|
| 513 |
+
return out
|
| 514 |
+
|
| 515 |
+
@traced
|
| 516 |
+
def _maybe_send_output(self, state: RequestState, token: int):
|
| 517 |
+
"""Send output to the queue based on streaming mode and request state."""
|
| 518 |
+
if self.streaming:
|
| 519 |
+
self.output_queue.put(state.to_generation_output())
|
| 520 |
+
elif state.status == RequestStatus.FINISHED:
|
| 521 |
+
self.output_queue.put(state.to_generation_output())
|
| 522 |
+
|
| 523 |
+
@traced
|
| 524 |
+
def update_batch(self):
|
| 525 |
+
"""Update request states based on generated tokens."""
|
| 526 |
+
out_tokens = self._sync()
|
| 527 |
+
finished_request_ids = []
|
| 528 |
+
for i, state in enumerate(self.requests_in_batch):
|
| 529 |
+
req_id = state.request_id
|
| 530 |
+
if len(state.remaining_prompt_ids) == 0:
|
| 531 |
+
self.metrics.record_ttft_metric(state.created_time, state.request_id)
|
| 532 |
+
state.status = RequestStatus.DECODING
|
| 533 |
+
token = out_tokens[self.logits_indices[i]]
|
| 534 |
+
state.prompt_ids = [token]
|
| 535 |
+
if state.update_with_token(token):
|
| 536 |
+
self.metrics.record_request_completion(state.created_time, state.request_id)
|
| 537 |
+
self.scheduler.finish_request(state.request_id, evict_from_cache=(not self.manual_eviction))
|
| 538 |
+
finished_request_ids.append(req_id)
|
| 539 |
+
self._maybe_send_output(state, token)
|
| 540 |
+
elif state.status == RequestStatus.PREFILLING_SPLIT:
|
| 541 |
+
state.status = RequestStatus.SPLIT_PENDING_REMAINDER
|
| 542 |
+
if self.cache.get_num_free_blocks() == 0:
|
| 543 |
+
raise ValueError("No more free blocks")
|
| 544 |
+
|
| 545 |
+
@traced
|
| 546 |
+
def has_pending_requests(self) -> bool:
|
| 547 |
+
"""Check if there are any active or waiting requests."""
|
| 548 |
+
return self.scheduler.has_pending_requests()
|
| 549 |
+
|
| 550 |
+
@traced
|
| 551 |
+
def handle_batch_error(self, error):
|
| 552 |
+
"""Handle errors during batch processing."""
|
| 553 |
+
failed_reqs = self.requests_in_batch
|
| 554 |
+
for req in failed_reqs:
|
| 555 |
+
self._handle_request_error(error, req)
|
| 556 |
+
self.scheduler.finish_request(req.request_id)
|
| 557 |
+
|
| 558 |
+
@traced
|
| 559 |
+
def fail_all_requests(self, error):
|
| 560 |
+
"""Fail all active requests with the given error.
|
| 561 |
+
|
| 562 |
+
Args:
|
| 563 |
+
error: The error to report in the failure message
|
| 564 |
+
"""
|
| 565 |
+
|
| 566 |
+
requests = list(self.scheduler.active_requests.values())
|
| 567 |
+
for state in requests:
|
| 568 |
+
self._handle_request_error(error, state)
|
| 569 |
+
self.scheduler.finish_request(state.request_id)
|
| 570 |
+
|
| 571 |
+
# Also fail any requests in the waiting queue
|
| 572 |
+
for req_id in list(self.scheduler.waiting_requests.keys()):
|
| 573 |
+
state = self.scheduler.waiting_requests.pop(req_id)
|
| 574 |
+
self._handle_request_error(error, state)
|
| 575 |
+
|
| 576 |
+
# Clear the ordering queue
|
| 577 |
+
self.scheduler.waiting_requests_order.clear()
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
# Manager Class (User Interface)
|
| 581 |
+
@attach_tracer()
|
| 582 |
+
class ContinuousBatchingManager:
|
| 583 |
+
"""Manager for handling continuous batching of generation requests.
|
| 584 |
+
|
| 585 |
+
This class provides the user interface for submitting generation requests,
|
| 586 |
+
retrieving results, and managing the background generation thread.
|
| 587 |
+
"""
|
| 588 |
+
|
| 589 |
+
def __init__(
|
| 590 |
+
self,
|
| 591 |
+
model,
|
| 592 |
+
generation_config: GenerationConfig,
|
| 593 |
+
manual_eviction: bool = False,
|
| 594 |
+
max_queue_size=0,
|
| 595 |
+
streaming: bool = True,
|
| 596 |
+
slice_inputs: bool = True,
|
| 597 |
+
):
|
| 598 |
+
"""Initialize the continuous batching manager.
|
| 599 |
+
|
| 600 |
+
Args:
|
| 601 |
+
model: The language model for generation
|
| 602 |
+
generation_config: Configuration for generation parameters
|
| 603 |
+
max_queue_size: Maximum size of the request queue (0 = unlimited)
|
| 604 |
+
streaming: Whether to stream tokens as they are generated
|
| 605 |
+
"""
|
| 606 |
+
self.model = model.eval()
|
| 607 |
+
generation_config = model.generation_config if generation_config is None else generation_config
|
| 608 |
+
self.generation_config = generation_config
|
| 609 |
+
self.input_queue = queue.Queue(maxsize=max_queue_size)
|
| 610 |
+
self.output_queue = queue.Queue()
|
| 611 |
+
self.stop_event = threading.Event()
|
| 612 |
+
self.streaming = streaming
|
| 613 |
+
self.log_prob_generation = getattr(generation_config, "log_prob_generation", False)
|
| 614 |
+
self._generation_thread = None
|
| 615 |
+
self._request_counter = 0
|
| 616 |
+
self._request_lock = threading.Lock()
|
| 617 |
+
self.model.generation_config.top_p = None
|
| 618 |
+
self.do_sample = getattr(generation_config, "do_sample", True)
|
| 619 |
+
self.logit_processor = self.model._get_logits_processor(generation_config)
|
| 620 |
+
self.use_cuda_graph = getattr(generation_config, "use_cuda_graph", False) # TODO: same as do_sample
|
| 621 |
+
self.profile = getattr(generation_config, "profile", False)
|
| 622 |
+
self.manual_eviction = manual_eviction
|
| 623 |
+
self.batch_processor: Optional[ContinuousBatchProcessor] = None
|
| 624 |
+
self.slice_inputs = slice_inputs
|
| 625 |
+
|
| 626 |
+
if self.use_cuda_graph:
|
| 627 |
+
raise NotImplementedError("Cuda graphs are not supported yet")
|
| 628 |
+
|
| 629 |
+
@traced
|
| 630 |
+
def start(self):
|
| 631 |
+
"""Start the background generation thread."""
|
| 632 |
+
if self._generation_thread is not None and self._generation_thread.is_alive():
|
| 633 |
+
logger.warning("Manager thread is already running.")
|
| 634 |
+
return
|
| 635 |
+
|
| 636 |
+
self._result_queue = queue.Queue()
|
| 637 |
+
self._generation_thread = threading.Thread(target=self._run_generation_loop)
|
| 638 |
+
self._generation_thread.start()
|
| 639 |
+
|
| 640 |
+
def is_running(self):
|
| 641 |
+
"""Check if the background generation thread is running."""
|
| 642 |
+
return self._generation_thread is not None and self._generation_thread.is_alive()
|
| 643 |
+
|
| 644 |
+
def stop(self, block: bool = False, timeout: Optional[float] = None):
|
| 645 |
+
"""Signal the background thread to stop.
|
| 646 |
+
|
| 647 |
+
Args:
|
| 648 |
+
block: Whether to wait for the thread to stop
|
| 649 |
+
timeout: Maximum time to wait for the thread to stop
|
| 650 |
+
"""
|
| 651 |
+
if self._generation_thread is None:
|
| 652 |
+
logger.warning("Manager not started.")
|
| 653 |
+
return
|
| 654 |
+
|
| 655 |
+
if not self.stop_event.is_set():
|
| 656 |
+
self.stop_event.set()
|
| 657 |
+
logger.info("Stopping continuous batching manager...")
|
| 658 |
+
|
| 659 |
+
if block:
|
| 660 |
+
self.join(timeout)
|
| 661 |
+
|
| 662 |
+
def join(self, timeout: Optional[float] = None):
|
| 663 |
+
"""Wait for the background thread to finish.
|
| 664 |
+
|
| 665 |
+
Args:
|
| 666 |
+
timeout: Maximum time to wait for the thread to stop
|
| 667 |
+
"""
|
| 668 |
+
if self._generation_thread is not None:
|
| 669 |
+
self._generation_thread.join(timeout=timeout)
|
| 670 |
+
if self._generation_thread.is_alive():
|
| 671 |
+
logger.warning("Generation thread did not exit after join timeout.")
|
| 672 |
+
else:
|
| 673 |
+
logger.info("Continuous Batching Manager stopped.")
|
| 674 |
+
self._generation_thread = None
|
| 675 |
+
|
| 676 |
+
def add_request(
|
| 677 |
+
self, input_ids: list[int], request_id: Optional[str] = None, max_new_tokens: Optional[int] = None
|
| 678 |
+
) -> str:
|
| 679 |
+
"""Add a new generation request to the queue.
|
| 680 |
+
|
| 681 |
+
Args:
|
| 682 |
+
input_ids: Input token IDs to use as prompt
|
| 683 |
+
request_id: Optional custom request ID (auto-generated if None)
|
| 684 |
+
**kwargs: Additional generation parameters
|
| 685 |
+
|
| 686 |
+
Returns:
|
| 687 |
+
str: The request ID
|
| 688 |
+
"""
|
| 689 |
+
if request_id is None:
|
| 690 |
+
with self._request_lock:
|
| 691 |
+
request_id = f"req_{self._request_counter}"
|
| 692 |
+
self._request_counter += 1
|
| 693 |
+
|
| 694 |
+
max_new_tokens = self.generation_config.max_new_tokens if max_new_tokens is None else max_new_tokens
|
| 695 |
+
|
| 696 |
+
# NOTE: do we want to handle a case when the user wants token ids returned instead of decoded text?
|
| 697 |
+
state = RequestState(
|
| 698 |
+
request_id=request_id,
|
| 699 |
+
prompt_ids=list(input_ids),
|
| 700 |
+
full_prompt_ids=list(input_ids),
|
| 701 |
+
max_new_tokens=max_new_tokens,
|
| 702 |
+
eos_token_id=self.generation_config.eos_token_id,
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
# Use block=True with timeout to handle backpressure if queue is full
|
| 706 |
+
self.input_queue.put(state, block=True, timeout=10) # XXX: pass timeout as fn arg?
|
| 707 |
+
logger.debug(f"Added request {request_id} to queue.")
|
| 708 |
+
return request_id
|
| 709 |
+
|
| 710 |
+
def add_requests(self, inputs: list[list[int]], **kwargs):
|
| 711 |
+
for input_ids in inputs:
|
| 712 |
+
self.add_request(input_ids, **kwargs)
|
| 713 |
+
|
| 714 |
+
def cancel_request(self, request_id: str):
|
| 715 |
+
"""Cancel a request by its ID.
|
| 716 |
+
|
| 717 |
+
Args:
|
| 718 |
+
request_id: The ID of the request to cancel
|
| 719 |
+
"""
|
| 720 |
+
if self.batch_processor is not None:
|
| 721 |
+
self.batch_processor.scheduler.set_request_cancellation(request_id)
|
| 722 |
+
|
| 723 |
+
def get_result(self, request_id=None, timeout=None) -> Optional[GenerationOutput]:
|
| 724 |
+
"""Retrieve one result from the output queue.
|
| 725 |
+
|
| 726 |
+
Args:
|
| 727 |
+
timeout: Maximum time to wait for a result
|
| 728 |
+
|
| 729 |
+
Returns:
|
| 730 |
+
Optional[GenerationOutput]: The result data or None if timeout
|
| 731 |
+
"""
|
| 732 |
+
if self._generation_thread is None and self.output_queue.empty():
|
| 733 |
+
return None
|
| 734 |
+
try:
|
| 735 |
+
result = self.output_queue.get(block=True, timeout=timeout)
|
| 736 |
+
if request_id is not None and result.request_id != request_id:
|
| 737 |
+
self.output_queue.put(result)
|
| 738 |
+
return None
|
| 739 |
+
logger.debug(f"Retrieved result for request {result.request_id}")
|
| 740 |
+
return result
|
| 741 |
+
except queue.Empty:
|
| 742 |
+
return None
|
| 743 |
+
|
| 744 |
+
def __iter__(self):
|
| 745 |
+
"""Iterate over results as they become available."""
|
| 746 |
+
while self._generation_thread is not None and self._generation_thread.is_alive():
|
| 747 |
+
result = self.get_result(timeout=0.1)
|
| 748 |
+
if result is not None:
|
| 749 |
+
yield result
|
| 750 |
+
|
| 751 |
+
def request_id_iter(self, request_id):
|
| 752 |
+
"""Iterate over results matching a specific request id as they become available."""
|
| 753 |
+
request_cancelled = False
|
| 754 |
+
while self._generation_thread is not None and self._generation_thread.is_alive() and not request_cancelled:
|
| 755 |
+
result = self.get_result(request_id=request_id, timeout=0.1)
|
| 756 |
+
if result is not None:
|
| 757 |
+
yield result
|
| 758 |
+
if self.batch_processor is not None:
|
| 759 |
+
request_cancelled = self.batch_processor.scheduler.request_is_cancelled(request_id)
|
| 760 |
+
|
| 761 |
+
@staticmethod
|
| 762 |
+
def supported_attention_implementations() -> set[str]:
|
| 763 |
+
return {"eager_paged", "sdpa_paged", "flash_attention_2"}
|
| 764 |
+
|
| 765 |
+
@staticmethod
|
| 766 |
+
def default_attention_implementation() -> str:
|
| 767 |
+
return "sdpa_paged"
|
| 768 |
+
|
| 769 |
+
@traced
|
| 770 |
+
def warmup(self, batch_processor):
|
| 771 |
+
stream = torch.cuda.Stream(device=self.model.device)
|
| 772 |
+
stream.wait_stream(torch.cuda.current_stream())
|
| 773 |
+
with torch.cuda.stream(stream):
|
| 774 |
+
# Warmup the model with a dummy forward pass
|
| 775 |
+
self._generation_step(batch_processor)
|
| 776 |
+
torch.cuda.current_stream().wait_stream(stream)
|
| 777 |
+
|
| 778 |
+
self.graph = torch.cuda.CUDAGraph()
|
| 779 |
+
with torch.cuda.graph(self.graph, stream=stream):
|
| 780 |
+
self._generation_step(batch_processor)
|
| 781 |
+
|
| 782 |
+
@traced
|
| 783 |
+
# @torch.compile
|
| 784 |
+
def _generation_step(self, batch_processor: ContinuousBatchProcessor):
|
| 785 |
+
"""Perform a single generation step. This is cuda graphed"""
|
| 786 |
+
batch_data = batch_processor.get_model_kwargs()
|
| 787 |
+
with torch.no_grad():
|
| 788 |
+
logits = self._model_forward(batch_data)
|
| 789 |
+
if self.log_prob_generation:
|
| 790 |
+
batch_processor.output_probs.copy_(logits) # TODO
|
| 791 |
+
probs = self._process_logit(batch_data, logits)
|
| 792 |
+
self._sample(batch_processor, probs)
|
| 793 |
+
|
| 794 |
+
@traced(span_name="model_forward")
|
| 795 |
+
def _model_forward(self, batch_data):
|
| 796 |
+
return self.model(**batch_data).logits
|
| 797 |
+
|
| 798 |
+
@traced(span_name="logit_processing")
|
| 799 |
+
def _process_logit(self, batch_data, logits):
|
| 800 |
+
# Pass continuous batching context to logits processor if it supports it. TODO we should find a way to make this a little bit cleaner!
|
| 801 |
+
if hasattr(self.logit_processor, "set_continuous_batching_context"):
|
| 802 |
+
self.logit_processor.set_continuous_batching_context(
|
| 803 |
+
batch_data["logits_indices"], batch_data["cu_seq_lens_q"]
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
# Handle shape compatibility: logit processors expect 2D tensors [batch_size, vocab_size]
|
| 807 |
+
# but continuous batching always produces 3D tensors [batch_size, seq_len, vocab_size]
|
| 808 |
+
batch_size, seq_len, vocab_size = logits.shape
|
| 809 |
+
logits_2d = logits.view(batch_size * seq_len, vocab_size)
|
| 810 |
+
input_ids_2d = batch_data["input_ids"].view(batch_size * seq_len)
|
| 811 |
+
|
| 812 |
+
# Process with 2D tensors
|
| 813 |
+
processed_logits_2d = self.logit_processor(input_ids_2d, logits_2d)
|
| 814 |
+
|
| 815 |
+
# Reshape back to 3D
|
| 816 |
+
return processed_logits_2d.view(batch_size, seq_len, vocab_size)
|
| 817 |
+
|
| 818 |
+
@traced(span_name="sampling")
|
| 819 |
+
def _sample(self, batch_processor: ContinuousBatchProcessor, probs):
|
| 820 |
+
if self.do_sample: # sample
|
| 821 |
+
probs = nn.functional.softmax(probs, dim=-1)
|
| 822 |
+
# probs[0] has shape [seq_len, vocab_size], multinomial returns [seq_len, 1]
|
| 823 |
+
next_tokens = torch.multinomial(probs[0], num_samples=1).squeeze(-1) # Now [seq_len]
|
| 824 |
+
# Add batch dimension back to match argmax output
|
| 825 |
+
next_tokens = next_tokens.unsqueeze(0) # Now [1, seq_len]
|
| 826 |
+
else:
|
| 827 |
+
next_tokens = torch.argmax(probs, dim=-1) # Already [1, seq_len]
|
| 828 |
+
|
| 829 |
+
tokens = next_tokens.size(1) # Get seq_len dimension
|
| 830 |
+
batch_processor.output_ids[:, :tokens].copy_(next_tokens)
|
| 831 |
+
|
| 832 |
+
def _run_generation_loop(self):
|
| 833 |
+
"""Main processing loop running in the background thread."""
|
| 834 |
+
batch_processor = None
|
| 835 |
+
try:
|
| 836 |
+
ref_time = perf_counter()
|
| 837 |
+
paged_attention_cache = PagedAttentionCache(
|
| 838 |
+
self.model.config,
|
| 839 |
+
self.generation_config,
|
| 840 |
+
self.model.device,
|
| 841 |
+
self.model.dtype,
|
| 842 |
+
tp_size=getattr(self.model, "_tp_size", None), # Use model's actual TP setting
|
| 843 |
+
)
|
| 844 |
+
logger.debug(f"PagedAttentionCache created in {perf_counter() - ref_time} seconds")
|
| 845 |
+
|
| 846 |
+
scheduler = None
|
| 847 |
+
if hasattr(self.generation_config, "scheduler"):
|
| 848 |
+
scheduler = SCHEDULER_MAPPING.get(self.generation_config.scheduler, None)
|
| 849 |
+
if scheduler is None:
|
| 850 |
+
logger.warning(f"Scheduler '{scheduler}' not found. Defaulting to FIFO.")
|
| 851 |
+
scheduler = FIFOScheduler
|
| 852 |
+
else:
|
| 853 |
+
# Default to fifo
|
| 854 |
+
scheduler = FIFOScheduler
|
| 855 |
+
|
| 856 |
+
ref_time = perf_counter()
|
| 857 |
+
batch_processor = ContinuousBatchProcessor(
|
| 858 |
+
paged_attention_cache,
|
| 859 |
+
self.model.config,
|
| 860 |
+
self.generation_config,
|
| 861 |
+
self.input_queue,
|
| 862 |
+
self.output_queue,
|
| 863 |
+
self.stop_event,
|
| 864 |
+
self.model.device,
|
| 865 |
+
self.model.dtype,
|
| 866 |
+
scheduler(paged_attention_cache, self.manual_eviction),
|
| 867 |
+
self.streaming,
|
| 868 |
+
self.manual_eviction,
|
| 869 |
+
slice_inputs=self.slice_inputs,
|
| 870 |
+
)
|
| 871 |
+
self.batch_processor = batch_processor
|
| 872 |
+
self.current_batch = 0
|
| 873 |
+
logger.debug(f"batch_processor created in {perf_counter() - ref_time} seconds")
|
| 874 |
+
while (not self.stop_event.is_set()) or batch_processor.has_pending_requests():
|
| 875 |
+
self._inner_generation_loop(batch_processor)
|
| 876 |
+
self.current_batch += 1
|
| 877 |
+
|
| 878 |
+
except Exception as e:
|
| 879 |
+
logger.error(f"Error in generation loop: {e}", exc_info=True)
|
| 880 |
+
self._handle_critical_error(e, batch_processor)
|
| 881 |
+
finally:
|
| 882 |
+
logger.info("Generation loop finished.")
|
| 883 |
+
|
| 884 |
+
@traced(span_name="generation_loop")
|
| 885 |
+
def _inner_generation_loop(self, batch_processor: ContinuousBatchProcessor):
|
| 886 |
+
if torch.cuda.is_available():
|
| 887 |
+
torch.cuda.synchronize()
|
| 888 |
+
if not batch_processor.prepare_next_batch():
|
| 889 |
+
return
|
| 890 |
+
if logger.level <= logging.DEBUG:
|
| 891 |
+
device, total, reserved, allocated = get_device_and_memory_breakdown()
|
| 892 |
+
logger.debug(f"[Memory] Device: {device}, Total: {total}, Reserved: {reserved}, Allocated: {allocated}")
|
| 893 |
+
if torch.cuda.is_available() and self.use_cuda_graph:
|
| 894 |
+
if self.current_batch == 0:
|
| 895 |
+
self.warmup(batch_processor)
|
| 896 |
+
elif hasattr(self, "graph"):
|
| 897 |
+
try:
|
| 898 |
+
self._graph_replay()
|
| 899 |
+
except Exception as e:
|
| 900 |
+
logger.error(f"Model forward pass failed: {e}", exc_info=True)
|
| 901 |
+
batch_processor.handle_batch_error(e)
|
| 902 |
+
return
|
| 903 |
+
else:
|
| 904 |
+
self._generation_step(batch_processor)
|
| 905 |
+
else:
|
| 906 |
+
self._generation_step(batch_processor)
|
| 907 |
+
if torch.cuda.is_available():
|
| 908 |
+
torch.cuda.synchronize()
|
| 909 |
+
batch_processor.update_batch()
|
| 910 |
+
|
| 911 |
+
@traced(span_name="graph_replay")
|
| 912 |
+
def _graph_replay(self):
|
| 913 |
+
self.graph.replay()
|
| 914 |
+
|
| 915 |
+
@traced
|
| 916 |
+
def _handle_critical_error(self, error, batch_processor: Optional[ContinuousBatchProcessor]):
|
| 917 |
+
"""Handle critical errors that terminate the generation loop."""
|
| 918 |
+
# Signal stop
|
| 919 |
+
self.stop_event.set()
|
| 920 |
+
|
| 921 |
+
# Fail pending requests in input queue
|
| 922 |
+
try:
|
| 923 |
+
while True:
|
| 924 |
+
req_data = self.input_queue.get_nowait()
|
| 925 |
+
if batch_processor is not None:
|
| 926 |
+
batch_processor._handle_request_error(error, req_data)
|
| 927 |
+
except queue.Empty:
|
| 928 |
+
pass
|
| 929 |
+
|
| 930 |
+
# Fail active requests
|
| 931 |
+
if batch_processor is not None:
|
| 932 |
+
batch_processor.fail_all_requests(error)
|
| 933 |
+
|
| 934 |
+
@traced
|
| 935 |
+
def evict_request_from_cache(self, request_id: str):
|
| 936 |
+
"""Evict a request from the cache. It is assumed that the request is already finished."""
|
| 937 |
+
if not self.manual_eviction:
|
| 938 |
+
raise RuntimeError("Manual eviction is not enabled for this manager.")
|
| 939 |
+
if self.batch_processor is not None:
|
| 940 |
+
self.batch_processor.scheduler.finish_request(request_id)
|
| 941 |
+
|
| 942 |
+
|
| 943 |
+
class ContinuousMixin:
|
| 944 |
+
"""Mixin class for models to add continuous batching capabilities."""
|
| 945 |
+
|
| 946 |
+
def init_continuous_batching(
|
| 947 |
+
self,
|
| 948 |
+
generation_config: Optional[GenerationConfig] = None,
|
| 949 |
+
manual_eviction: bool = False,
|
| 950 |
+
max_queue_size: int = 0,
|
| 951 |
+
streaming: bool = False,
|
| 952 |
+
slice_inputs: bool = True,
|
| 953 |
+
) -> ContinuousBatchingManager:
|
| 954 |
+
"""Initialize a manager for continuous batching inference.
|
| 955 |
+
|
| 956 |
+
Args:
|
| 957 |
+
generation_config: Custom generation configuration
|
| 958 |
+
max_queue_size: Maximum size of the input request queue
|
| 959 |
+
streaming: Whether to stream tokens as they are generated
|
| 960 |
+
|
| 961 |
+
Returns:
|
| 962 |
+
`ContinuousBatchingManager`: The manager instance to add requests and retrieve results.
|
| 963 |
+
"""
|
| 964 |
+
if not hasattr(self, "config") or not hasattr(self, "device") or not hasattr(self, "dtype"):
|
| 965 |
+
raise AttributeError("Model must have 'config', 'device', and 'dtype' attributes.")
|
| 966 |
+
|
| 967 |
+
gen_config = generation_config if generation_config is not None else self.generation_config
|
| 968 |
+
if gen_config is None:
|
| 969 |
+
raise ValueError("A GenerationConfig must be provided or set in the model.")
|
| 970 |
+
|
| 971 |
+
if gen_config.eos_token_id is None:
|
| 972 |
+
logger.warning("`eos_token_id` not set in GenerationConfig. Setting to -1 (disabled).")
|
| 973 |
+
gen_config.eos_token_id = -1
|
| 974 |
+
|
| 975 |
+
# Create and return the manager
|
| 976 |
+
return ContinuousBatchingManager(
|
| 977 |
+
model=self,
|
| 978 |
+
generation_config=gen_config,
|
| 979 |
+
manual_eviction=manual_eviction,
|
| 980 |
+
max_queue_size=max_queue_size,
|
| 981 |
+
streaming=streaming,
|
| 982 |
+
slice_inputs=slice_inputs,
|
| 983 |
+
)
|
| 984 |
+
|
| 985 |
+
@traced
|
| 986 |
+
@torch.inference_mode()
|
| 987 |
+
def generate_batch(
|
| 988 |
+
self,
|
| 989 |
+
inputs: list[list[int]],
|
| 990 |
+
generation_config: Optional[GenerationConfig] = None,
|
| 991 |
+
progress_bar: bool = True,
|
| 992 |
+
slice_inputs: bool = True,
|
| 993 |
+
**kwargs,
|
| 994 |
+
) -> list[list[int]]:
|
| 995 |
+
"""Generate sequences for a batch of prompts using continuous batching.
|
| 996 |
+
|
| 997 |
+
Args:
|
| 998 |
+
inputs: List of input token sequences (prompts)
|
| 999 |
+
generation_config: Optional generation configuration
|
| 1000 |
+
**kwargs: Additional generation parameters
|
| 1001 |
+
|
| 1002 |
+
Returns:
|
| 1003 |
+
`list[list[int]]`: A list containing the generated sequences (including prompt tokens
|
| 1004 |
+
if not handled otherwise) for each input prompt, in the same order.
|
| 1005 |
+
Returns an empty list `[]` for requests that failed.
|
| 1006 |
+
"""
|
| 1007 |
+
if not inputs:
|
| 1008 |
+
return []
|
| 1009 |
+
if logger.getEffectiveLevel() <= logging.DEBUG:
|
| 1010 |
+
logger.warning("Progress bar is disabled when logger level is less than DEBUG")
|
| 1011 |
+
progress_bar = False
|
| 1012 |
+
|
| 1013 |
+
# Initialize manager with the batch inputs
|
| 1014 |
+
manager = self.init_continuous_batching(generation_config=generation_config, slice_inputs=slice_inputs)
|
| 1015 |
+
manager.start()
|
| 1016 |
+
results = {}
|
| 1017 |
+
num_requests = len(inputs)
|
| 1018 |
+
try:
|
| 1019 |
+
from tqdm.contrib.logging import logging_redirect_tqdm
|
| 1020 |
+
|
| 1021 |
+
with logging_redirect_tqdm([logger]):
|
| 1022 |
+
with tqdm(
|
| 1023 |
+
total=num_requests,
|
| 1024 |
+
disable=(not progress_bar),
|
| 1025 |
+
desc=f"Solving {num_requests} requests",
|
| 1026 |
+
unit="request",
|
| 1027 |
+
) as pbar:
|
| 1028 |
+
manager.add_requests(inputs, **kwargs)
|
| 1029 |
+
finished_count = 0
|
| 1030 |
+
while finished_count < num_requests:
|
| 1031 |
+
result = manager.get_result(timeout=1)
|
| 1032 |
+
if result:
|
| 1033 |
+
req_id = result.request_id
|
| 1034 |
+
if result.status == RequestStatus.FINISHED:
|
| 1035 |
+
results[req_id] = result
|
| 1036 |
+
finished_count += 1
|
| 1037 |
+
pbar.update(1)
|
| 1038 |
+
else:
|
| 1039 |
+
if not manager.is_running():
|
| 1040 |
+
logger.error("Generation thread terminated unexpectedly.")
|
| 1041 |
+
break
|
| 1042 |
+
|
| 1043 |
+
except Exception as e:
|
| 1044 |
+
logger.error(f"Error during batch generation: {e}", exc_info=True)
|
| 1045 |
+
finally:
|
| 1046 |
+
manager.stop(block=True, timeout=5.0)
|
| 1047 |
+
return results
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/requests.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 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 |
+
import time
|
| 16 |
+
from dataclasses import dataclass, field
|
| 17 |
+
from enum import Enum
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from ...utils.logging import logging
|
| 23 |
+
from ...utils.metrics import traced
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# We centralize the logger here to coordinate between logging and progress bar
|
| 27 |
+
logger = logging.getLogger("ContinuousBatchingLogger")
|
| 28 |
+
# logger.setLevel(logging.INFO)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_device_and_memory_breakdown() -> tuple[torch.device, int, int, int]:
|
| 32 |
+
if torch.cuda.is_available():
|
| 33 |
+
device = torch.device("cuda")
|
| 34 |
+
torch.cuda.empty_cache()
|
| 35 |
+
torch.cuda.synchronize()
|
| 36 |
+
total_memory = torch.cuda.get_device_properties(device).total_memory
|
| 37 |
+
reserved_memory = torch.cuda.memory_reserved(device)
|
| 38 |
+
allocated_memory = torch.cuda.memory_allocated(device)
|
| 39 |
+
elif torch.backends.mps.is_available() and torch.backends.mps.is_built():
|
| 40 |
+
device = torch.device("mps")
|
| 41 |
+
# MPS memory reporting (PyTorch 2.0+)
|
| 42 |
+
total_memory = torch.mps.driver_allocated_memory()
|
| 43 |
+
allocated_memory = total_memory - torch.mps.recommended_max_memory()
|
| 44 |
+
reserved_memory = 0 # MPS does not track reserved separately
|
| 45 |
+
else:
|
| 46 |
+
device = torch.device("cpu")
|
| 47 |
+
total_memory = None
|
| 48 |
+
reserved_memory = 0
|
| 49 |
+
allocated_memory = 0
|
| 50 |
+
return device, total_memory, reserved_memory, allocated_memory
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class RequestStatus(Enum):
|
| 54 |
+
"""Status of a generation request through its lifecycle."""
|
| 55 |
+
|
| 56 |
+
PENDING = "pending"
|
| 57 |
+
PREFILLING = "prefilling"
|
| 58 |
+
PREFILLING_SPLIT = "prefilling_split"
|
| 59 |
+
SPLIT_PENDING_REMAINDER = "split_pending_remainder"
|
| 60 |
+
DECODING = "decoding"
|
| 61 |
+
FINISHED = "finished"
|
| 62 |
+
FAILED = "failed"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@dataclass
|
| 66 |
+
class GenerationOutput:
|
| 67 |
+
"""Tracks the output of a generation request.
|
| 68 |
+
|
| 69 |
+
Attributes:
|
| 70 |
+
request_id (str): The ID of the generation request.
|
| 71 |
+
prompt_ids (list[int]): The IDs of the prompt tokens.
|
| 72 |
+
generated_tokens (list[int]): The generated tokens.
|
| 73 |
+
logprobs (list[float]): The log probabilities of the generated tokens.
|
| 74 |
+
error (Optional[str]): Any error message associated with the request. When None, the request was successful.
|
| 75 |
+
status (RequestStatus): The status of the request.
|
| 76 |
+
created_time (float): The time the request was created.
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
request_id: str
|
| 80 |
+
prompt_ids: list[int] = field(default_factory=list)
|
| 81 |
+
generated_tokens: list[int] = field(default_factory=list)
|
| 82 |
+
logprobs: list[float] = field(default_factory=list)
|
| 83 |
+
error: Optional[str] = None
|
| 84 |
+
status: RequestStatus = RequestStatus.PENDING
|
| 85 |
+
created_time: float = field(default_factory=time.time)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@dataclass
|
| 89 |
+
class RequestState:
|
| 90 |
+
"""Tracks the state of a generation request through its lifecycle.
|
| 91 |
+
|
| 92 |
+
Attributes:
|
| 93 |
+
request_id (str): The ID of the generation request.
|
| 94 |
+
full_prompt_ids (list[int] | None): The tokens IDs of the full prompt.
|
| 95 |
+
prompt_ids (list[int] | None): The tokens IDs currently being processed.
|
| 96 |
+
remaining_prompt_ids (list[int]): The tokens IDs remaining to be processed (for split requests).
|
| 97 |
+
static_outputs (list[int]): The generated tokens.
|
| 98 |
+
allocated_blocks (int): The number of blocks allocated to the request.
|
| 99 |
+
position_offset (int): The current position in the sequence for position_ids.
|
| 100 |
+
status (RequestStatus): The status of the request: can be one of PENDING, PREFILLING, PREFILLING_SPLIT,
|
| 101 |
+
SPLIT_PENDING_REMAINDER, DECODING, FINISHED, FAILED
|
| 102 |
+
max_new_tokens (int): The maximum number of new tokens to generate.
|
| 103 |
+
eos_token_id (int): The ID of the end-of-sequence token.
|
| 104 |
+
created_time (float): The time the request was created.
|
| 105 |
+
error (Optional[str]): Any error message associated with the request. When None, has had no error yet.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
# Required fields
|
| 109 |
+
request_id: str
|
| 110 |
+
full_prompt_ids: Optional[list[int]] = None # Full initial prompt
|
| 111 |
+
prompt_ids: Optional[list[int]] = None # Tokens IDs currently being processed (initial + generated)
|
| 112 |
+
remaining_prompt_ids: list[int] = field(default_factory=list) # For split requests, prefill left to process
|
| 113 |
+
static_outputs: list[int] = field(default_factory=list) # Generated tokens
|
| 114 |
+
allocated_blocks: int = 0 # Number of blocks allocated to the request
|
| 115 |
+
position_offset: int = 0 # Current position in the sequence for position_ids
|
| 116 |
+
_status: RequestStatus = RequestStatus.PENDING # Status of the request, hidden behind a property
|
| 117 |
+
max_new_tokens: int = 20 # Maximum number of new tokens to generate
|
| 118 |
+
eos_token_id: int = -1 # ID of the end-of-sequence token
|
| 119 |
+
created_time: float = field(default_factory=time.time) # Time the request was created
|
| 120 |
+
error: Optional[str] = None # Error message if the request failed
|
| 121 |
+
lifespan: tuple[float, float] = (-1, -1) # (time request was no longer pending, time request finished)
|
| 122 |
+
|
| 123 |
+
@property
|
| 124 |
+
def status(self) -> RequestStatus:
|
| 125 |
+
return self._status
|
| 126 |
+
|
| 127 |
+
@status.setter
|
| 128 |
+
def status(self, value: RequestStatus):
|
| 129 |
+
if self._status == RequestStatus.PENDING:
|
| 130 |
+
self.lifespan = (time.time(), -1)
|
| 131 |
+
elif value == RequestStatus.FINISHED:
|
| 132 |
+
self.lifespan = (self.lifespan[0], time.time())
|
| 133 |
+
self.log_end_of_request()
|
| 134 |
+
self._status = value
|
| 135 |
+
|
| 136 |
+
def log_end_of_request(self):
|
| 137 |
+
prefill_len = len(self.full_prompt_ids)
|
| 138 |
+
decode_len = self.generated_len()
|
| 139 |
+
start_time = self.lifespan[0] - self.created_time
|
| 140 |
+
end_time = self.lifespan[1] - self.created_time
|
| 141 |
+
logger.info(
|
| 142 |
+
f"Request {self.request_id} finished: {prefill_len = } {decode_len = } {start_time = } {end_time = }"
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def current_len(self) -> int:
|
| 146 |
+
"""Get the current length of the sequence (prompt + generated tokens)."""
|
| 147 |
+
return self.position_offset
|
| 148 |
+
|
| 149 |
+
def generated_len(self) -> int:
|
| 150 |
+
"""Get the number of tokens generated so far."""
|
| 151 |
+
return len(self.static_outputs)
|
| 152 |
+
|
| 153 |
+
# TODO: this logic seems one token off, check it out
|
| 154 |
+
@traced
|
| 155 |
+
def update_with_token(self, token_id: int) -> bool:
|
| 156 |
+
"""Update the request with a newly generated token and check for completion.
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
token_id: The token ID to add to the output sequence
|
| 160 |
+
|
| 161 |
+
Returns:
|
| 162 |
+
bool: True if the request is now complete, False otherwise
|
| 163 |
+
"""
|
| 164 |
+
# Only update if we're in decoding state
|
| 165 |
+
if self.status != RequestStatus.DECODING:
|
| 166 |
+
return False
|
| 167 |
+
|
| 168 |
+
is_eos = token_id == self.eos_token_id and self.eos_token_id != -1
|
| 169 |
+
is_max_len = self.generated_len() >= self.max_new_tokens
|
| 170 |
+
|
| 171 |
+
# Only add the token if we're not finishing due to max length
|
| 172 |
+
# (EOS tokens should still be added to the output)
|
| 173 |
+
if not (is_max_len and not is_eos):
|
| 174 |
+
self.static_outputs.extend([token_id])
|
| 175 |
+
|
| 176 |
+
if is_eos or is_max_len:
|
| 177 |
+
self.status = RequestStatus.FINISHED
|
| 178 |
+
return True
|
| 179 |
+
return False
|
| 180 |
+
|
| 181 |
+
def __repr__(self):
|
| 182 |
+
msg = [
|
| 183 |
+
f"request_id={self.request_id}",
|
| 184 |
+
f"status={self._status}",
|
| 185 |
+
f"out_tokens={self.generated_len()}",
|
| 186 |
+
f"query_length={len(self.prompt_ids)}",
|
| 187 |
+
f"remaining_tokens={len(self.remaining_prompt_ids)}",
|
| 188 |
+
f"kv_length={self.position_offset}",
|
| 189 |
+
f"full_prompt_length={len(self.full_prompt_ids)}",
|
| 190 |
+
f"allocated_blocks={self.allocated_blocks}",
|
| 191 |
+
f"generated_tokens={self.static_outputs}",
|
| 192 |
+
]
|
| 193 |
+
return "RequestState(\n\t" + ",\n\t".join(msg) + "\n)"
|
| 194 |
+
|
| 195 |
+
def to_generation_output(self):
|
| 196 |
+
"""Convert the request state to a GenerationOutput object."""
|
| 197 |
+
return GenerationOutput(
|
| 198 |
+
request_id=self.request_id,
|
| 199 |
+
prompt_ids=self.full_prompt_ids,
|
| 200 |
+
status=self.status,
|
| 201 |
+
generated_tokens=self.static_outputs,
|
| 202 |
+
logprobs=[],
|
| 203 |
+
error=self.error,
|
| 204 |
+
)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/generation/continuous_batching/scheduler.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 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 |
+
import threading
|
| 16 |
+
from abc import ABC, abstractmethod
|
| 17 |
+
from collections import deque
|
| 18 |
+
|
| 19 |
+
from ...utils.metrics import attach_tracer, traced
|
| 20 |
+
from .cache import PagedAttentionCache
|
| 21 |
+
from .requests import RequestState, RequestStatus
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Scheduler(ABC):
|
| 25 |
+
"""
|
| 26 |
+
Abstract base class for scheduling requests in the continuous batch processor. Schedulers manage the lifecycle of
|
| 27 |
+
requests from when they are added to the waiting queue to when they are scheduled for processing. Different
|
| 28 |
+
schedulers implement different strategies for prioritizing and batching requests.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self, cache: PagedAttentionCache, retain_cache_on_finish: bool = False):
|
| 32 |
+
self.active_requests: dict[str, RequestState] = {}
|
| 33 |
+
self.waiting_requests: dict[str, RequestState] = {}
|
| 34 |
+
self.waiting_requests_order: deque[str] = deque()
|
| 35 |
+
self.cache = cache
|
| 36 |
+
self.retain_cache_on_finish = retain_cache_on_finish
|
| 37 |
+
self._cancellation_lock = threading.Lock()
|
| 38 |
+
self._requests_to_cancel: set[str] = set()
|
| 39 |
+
|
| 40 |
+
@traced
|
| 41 |
+
def add_waiting_request(self, state: RequestState):
|
| 42 |
+
"""Adds a request to the waiting list."""
|
| 43 |
+
if self.retain_cache_on_finish and state.request_id in self.active_requests:
|
| 44 |
+
old_state = self.active_requests.pop(state.request_id)
|
| 45 |
+
state.prompt_ids = state.prompt_ids[len(old_state.full_prompt_ids) :] # XXX: check for indexing error?
|
| 46 |
+
state.allocated_blocks = old_state.allocated_blocks
|
| 47 |
+
state.position_offset = old_state.position_offset
|
| 48 |
+
self.waiting_requests[state.request_id] = state
|
| 49 |
+
self.waiting_requests_order.append(state.request_id)
|
| 50 |
+
|
| 51 |
+
@abstractmethod
|
| 52 |
+
def schedule_batch(self, token_budget: int) -> list[RequestState]:
|
| 53 |
+
"""Schedules requests for the next batch based on available token budget. This method selects which requests
|
| 54 |
+
should be processed in the current batch, considering the token budget and the scheduler's prioritization rules.
|
| 55 |
+
The token_budget is the maximum number of tokens that can be processed in this batch."""
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
@traced
|
| 59 |
+
def has_pending_requests(self) -> bool:
|
| 60 |
+
"""Checks if there are requests ready to be processed."""
|
| 61 |
+
return len(self.active_requests) or len(self.waiting_requests)
|
| 62 |
+
|
| 63 |
+
@traced
|
| 64 |
+
def finish_request(self, request_id: str, evict_from_cache: bool = True):
|
| 65 |
+
"""Completes processing of a request and optionally frees its allocated cache blocks. This method is called
|
| 66 |
+
when a request has finished generation or encountered an error.
|
| 67 |
+
"""
|
| 68 |
+
if evict_from_cache:
|
| 69 |
+
self.cache.free_blocks(request_id)
|
| 70 |
+
if request_id in self.active_requests:
|
| 71 |
+
del self.active_requests[request_id]
|
| 72 |
+
|
| 73 |
+
@traced
|
| 74 |
+
def get_active_request_static_outputs(self, request_id: str) -> list[int]:
|
| 75 |
+
"""Gets generated tokens for an active request."""
|
| 76 |
+
if request_id in self.active_requests:
|
| 77 |
+
return self.active_requests[request_id].static_outputs
|
| 78 |
+
return []
|
| 79 |
+
|
| 80 |
+
@traced
|
| 81 |
+
def set_request_cancellation(self, request_id: str):
|
| 82 |
+
"""Marks a request for cancellation."""
|
| 83 |
+
with self._cancellation_lock:
|
| 84 |
+
self._requests_to_cancel.add(request_id)
|
| 85 |
+
|
| 86 |
+
@traced
|
| 87 |
+
def clear_cancelled_requests(self):
|
| 88 |
+
"""Remove all cancelled requests from active and waiting queues."""
|
| 89 |
+
with self._cancellation_lock:
|
| 90 |
+
for request_id in self._requests_to_cancel:
|
| 91 |
+
if request_id in self.active_requests:
|
| 92 |
+
del self.active_requests[request_id]
|
| 93 |
+
if request_id in self.waiting_requests:
|
| 94 |
+
del self.waiting_requests[request_id]
|
| 95 |
+
if request_id in self.waiting_requests_order:
|
| 96 |
+
self.waiting_requests_order.remove(request_id)
|
| 97 |
+
self.cache.free_blocks(request_id)
|
| 98 |
+
self._requests_to_cancel = set()
|
| 99 |
+
|
| 100 |
+
@traced
|
| 101 |
+
def request_is_cancelled(self, request_id: str) -> bool:
|
| 102 |
+
"""Checks if a request has been cancelled or removed."""
|
| 103 |
+
return request_id in self._requests_to_cancel or (
|
| 104 |
+
request_id not in self.active_requests and request_id not in self.waiting_requests
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
@traced
|
| 108 |
+
def _allocate_blocks_if_needed(self, state: RequestState, len_next_tokens: int) -> bool:
|
| 109 |
+
"""Allocate additional cache blocks for a request if the currently allocated blocks are insufficient to
|
| 110 |
+
accommodate the next tokens. It calculates how many blocks are needed based on the request's current
|
| 111 |
+
cache occupancy and the number of tokens to be processed. The allocation itself is done by the CacheAllocator
|
| 112 |
+
objects. Returns a boolean indicating if the allocation was successful or not.
|
| 113 |
+
"""
|
| 114 |
+
# 1. we check that the occupancy is less than the requested length
|
| 115 |
+
# 2. we allocate enough blocks to cover the requested length
|
| 116 |
+
current_len = state.current_len()
|
| 117 |
+
occupancy = state.allocated_blocks * self.cache.block_size - current_len
|
| 118 |
+
if occupancy < len_next_tokens or state.allocated_blocks == 0:
|
| 119 |
+
blocks_needed = ((len_next_tokens - occupancy + 1) // self.cache.block_size) + 1
|
| 120 |
+
allocated = self.cache.allocate_blocks(blocks_needed, state.request_id)
|
| 121 |
+
if allocated is None:
|
| 122 |
+
return False
|
| 123 |
+
state.allocated_blocks += allocated
|
| 124 |
+
return True
|
| 125 |
+
|
| 126 |
+
@traced(span_name="prepare_request")
|
| 127 |
+
def _prepare_request_for_processing(
|
| 128 |
+
self, state: RequestState, token_budget: int, request_ids_to_remove_from_waiting: set[str]
|
| 129 |
+
):
|
| 130 |
+
"""Prepares a request for processing in the current batch."""
|
| 131 |
+
request_tokens = (
|
| 132 |
+
state.remaining_prompt_ids if state.status == RequestStatus.SPLIT_PENDING_REMAINDER else state.prompt_ids
|
| 133 |
+
)
|
| 134 |
+
if len(request_tokens) < token_budget:
|
| 135 |
+
# Can process the entire prompt/remainder
|
| 136 |
+
if state.status == RequestStatus.PENDING:
|
| 137 |
+
self.active_requests[state.request_id] = state
|
| 138 |
+
state.status = RequestStatus.PREFILLING
|
| 139 |
+
request_ids_to_remove_from_waiting.add(state.request_id)
|
| 140 |
+
elif state.status == RequestStatus.SPLIT_PENDING_REMAINDER:
|
| 141 |
+
state.status = RequestStatus.PREFILLING
|
| 142 |
+
state.prompt_ids = state.remaining_prompt_ids
|
| 143 |
+
state.remaining_prompt_ids = []
|
| 144 |
+
else:
|
| 145 |
+
# Need to split the request
|
| 146 |
+
if state.status == RequestStatus.PENDING:
|
| 147 |
+
self.active_requests[state.request_id] = state
|
| 148 |
+
state.status = RequestStatus.PREFILLING_SPLIT
|
| 149 |
+
request_ids_to_remove_from_waiting.add(state.request_id)
|
| 150 |
+
elif state.status == RequestStatus.SPLIT_PENDING_REMAINDER:
|
| 151 |
+
state.status = RequestStatus.PREFILLING_SPLIT
|
| 152 |
+
state.remaining_prompt_ids = request_tokens[token_budget:]
|
| 153 |
+
state.prompt_ids = request_tokens[:token_budget]
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@attach_tracer()
|
| 157 |
+
class FIFOScheduler(Scheduler):
|
| 158 |
+
"""This scheduler processes requests in the order they arrive, meaning decoding requests has priority over
|
| 159 |
+
prefilling requests. Additionally, it includes a safety margin mechanism to prevent cache exhaustion. By default,
|
| 160 |
+
when 80% of the cache is full, new requests will not be scheduled to prioritize decoding active requests."""
|
| 161 |
+
|
| 162 |
+
def __init__(self, cache: PagedAttentionCache, retain_cache_on_finish: bool = False, safety_margin: float = 0.2):
|
| 163 |
+
"""Initializes the FIFO scheduler. The safety margin is the percentage of free blocks under which we stop
|
| 164 |
+
scheduling new prefill requests, so safety_margin = 0.1 means that when there is less than 10% of free blocks,
|
| 165 |
+
or equivalently when more than 90% of blocks are already allocated, we stop scheduling new prefill requests.
|
| 166 |
+
"""
|
| 167 |
+
super().__init__(cache, retain_cache_on_finish)
|
| 168 |
+
self.safety_margin = safety_margin
|
| 169 |
+
|
| 170 |
+
@traced
|
| 171 |
+
def schedule_batch(self, token_budget: int) -> list[RequestState]:
|
| 172 |
+
priority_states: list[RequestState] = []
|
| 173 |
+
second_priority_states: list[RequestState] = []
|
| 174 |
+
scheduled_requests = []
|
| 175 |
+
|
| 176 |
+
for state in self.active_requests.values():
|
| 177 |
+
if state.status == RequestStatus.DECODING:
|
| 178 |
+
priority_states.append(state)
|
| 179 |
+
if state.status in [RequestStatus.SPLIT_PENDING_REMAINDER, RequestStatus.PREFILLING_SPLIT]:
|
| 180 |
+
second_priority_states.append(state)
|
| 181 |
+
|
| 182 |
+
# Add waiting requests to second priority
|
| 183 |
+
for req_id in self.waiting_requests_order:
|
| 184 |
+
second_priority_states.append(self.waiting_requests[req_id])
|
| 185 |
+
|
| 186 |
+
candidates = priority_states + second_priority_states
|
| 187 |
+
request_ids_to_remove_from_waiting = set()
|
| 188 |
+
safety_margins = self.safety_margin * self.cache.num_blocks
|
| 189 |
+
|
| 190 |
+
for state in candidates:
|
| 191 |
+
# If we are out the safety margin, we only accept decoding requests or the first prefill request
|
| 192 |
+
num_free_blocks = self.cache.get_num_free_blocks()
|
| 193 |
+
outside_safety_margin = num_free_blocks < safety_margins
|
| 194 |
+
if outside_safety_margin and scheduled_requests and state.status != RequestStatus.DECODING:
|
| 195 |
+
break
|
| 196 |
+
|
| 197 |
+
self._prepare_request_for_processing(state, token_budget, request_ids_to_remove_from_waiting)
|
| 198 |
+
request_len = len(state.prompt_ids)
|
| 199 |
+
if not self._allocate_blocks_if_needed(
|
| 200 |
+
state, len(state.prompt_ids)
|
| 201 |
+
): # don't schedule if we can't allocate blocks
|
| 202 |
+
if len(self.cache._free_blocks) == 0:
|
| 203 |
+
break
|
| 204 |
+
continue
|
| 205 |
+
|
| 206 |
+
@traced
|
| 207 |
+
def _add_to_scheduled_requests(state: RequestState):
|
| 208 |
+
scheduled_requests.append(state)
|
| 209 |
+
|
| 210 |
+
_add_to_scheduled_requests(state)
|
| 211 |
+
|
| 212 |
+
token_budget -= request_len
|
| 213 |
+
|
| 214 |
+
@traced
|
| 215 |
+
def _remove_from_waiting_requests(state: RequestState):
|
| 216 |
+
req_id = state.request_id
|
| 217 |
+
if req_id in self.waiting_requests:
|
| 218 |
+
del self.waiting_requests[req_id]
|
| 219 |
+
request_ids_to_remove_from_waiting.add(req_id)
|
| 220 |
+
|
| 221 |
+
_remove_from_waiting_requests(state)
|
| 222 |
+
|
| 223 |
+
if token_budget == 0:
|
| 224 |
+
break
|
| 225 |
+
|
| 226 |
+
self.waiting_requests_order = deque(
|
| 227 |
+
[req_id for req_id in self.waiting_requests_order if req_id not in request_ids_to_remove_from_waiting]
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
return scheduled_requests
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
# FIXME: prioritize adding from waiting reqs before scheduling `RequestStatus.DECODING` when cache space allows it
|
| 234 |
+
@attach_tracer()
|
| 235 |
+
class PrefillFirstScheduler(Scheduler):
|
| 236 |
+
"""Scheduler that prioritizes split prefill requests over decoding requests. This scheduler ensures that split
|
| 237 |
+
prefill requests (which are continuations of partially processed prompts) are completed before processing new
|
| 238 |
+
decoding requests."""
|
| 239 |
+
|
| 240 |
+
@traced
|
| 241 |
+
def schedule_batch(self, token_budget: int) -> list[RequestState]:
|
| 242 |
+
priority_states: list[RequestState] = []
|
| 243 |
+
second_priority_states: list[RequestState] = []
|
| 244 |
+
scheduled_requests = []
|
| 245 |
+
|
| 246 |
+
for state in self.active_requests.values():
|
| 247 |
+
# XXX: when cache is full, state can stay on `PREFILLING_SPLIT` so we need to take those into account
|
| 248 |
+
if state.status in [RequestStatus.PREFILLING_SPLIT, RequestStatus.SPLIT_PENDING_REMAINDER]:
|
| 249 |
+
priority_states.append(state)
|
| 250 |
+
elif state.status == RequestStatus.DECODING:
|
| 251 |
+
second_priority_states.append(state)
|
| 252 |
+
|
| 253 |
+
for req_id in self.waiting_requests_order:
|
| 254 |
+
second_priority_states.append(self.waiting_requests[req_id])
|
| 255 |
+
|
| 256 |
+
candidates = priority_states + second_priority_states
|
| 257 |
+
|
| 258 |
+
request_ids_to_remove_from_waiting = set()
|
| 259 |
+
|
| 260 |
+
for state in candidates:
|
| 261 |
+
self._prepare_request_for_processing(state, token_budget, request_ids_to_remove_from_waiting)
|
| 262 |
+
request_len = len(state.prompt_ids)
|
| 263 |
+
if not self._allocate_blocks_if_needed(
|
| 264 |
+
state, len(state.prompt_ids)
|
| 265 |
+
): # don't schedule if we can't allocate blocks
|
| 266 |
+
if len(self.cache._free_blocks) == 0:
|
| 267 |
+
break
|
| 268 |
+
continue
|
| 269 |
+
|
| 270 |
+
@traced
|
| 271 |
+
def _add_to_scheduled_requests(state: RequestState):
|
| 272 |
+
scheduled_requests.append(state)
|
| 273 |
+
|
| 274 |
+
_add_to_scheduled_requests(state)
|
| 275 |
+
|
| 276 |
+
token_budget -= request_len
|
| 277 |
+
|
| 278 |
+
@traced
|
| 279 |
+
def _remove_from_waiting_requests(state: RequestState):
|
| 280 |
+
req_id = state.request_id
|
| 281 |
+
if req_id in self.waiting_requests:
|
| 282 |
+
del self.waiting_requests[req_id]
|
| 283 |
+
request_ids_to_remove_from_waiting.add(req_id)
|
| 284 |
+
|
| 285 |
+
_remove_from_waiting_requests(state)
|
| 286 |
+
|
| 287 |
+
if token_budget == 0:
|
| 288 |
+
break
|
| 289 |
+
|
| 290 |
+
self.waiting_requests_order = deque(
|
| 291 |
+
[req_id for req_id in self.waiting_requests_order if req_id not in request_ids_to_remove_from_waiting]
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
return scheduled_requests
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
SCHEDULER_MAPPING = {
|
| 298 |
+
"fifo": FIFOScheduler,
|
| 299 |
+
"prefill_first": PrefillFirstScheduler,
|
| 300 |
+
}
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/loss/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (191 Bytes). View file
|
|
|