CoolFace
Modelpublic

27M/PreFLMR_ViT-G

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes6downloads
tokenization_flmr.py240 linesDownload Raw Back to root
1# coding=utf-82# Copyright 2024 The HuggingFace Inc. team, The Hugging Face 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 at7#8#     http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# 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 and14# limitations under the License.15"""Tokenization classes for FLMR."""16 17 18from typing import List, Optional, Union19 20from transformers.utils import TensorType, logging21from transformers.models.bert.tokenization_bert import BertTokenizer22 23 24logger = logging.get_logger(__name__)25 26VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer_config.json"}27 28CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP = {29    "vocab_file": {30        "LinWeizheDragon/PreFLMR_ViT-L": (31            "https://huggingface.co/LinWeizheDragon/PreFLMR_ViT-L/resolve/main/context_tokenizer/vocab.txt"32        ),33        "LinWeizheDragon/FLMR": (34            "https://huggingface.co/LinWeizheDragon/FLMR/resolve/main/context_tokenizer/vocab.txt"35        ),36    },37    "tokenizer_file": {38        "LinWeizheDragon/PreFLMR_ViT-L": (39            "https://huggingface.co/LinWeizheDragon/PreFLMR_ViT-L/resolve/main/context_tokenizer/tokenizer_config.json"40        ),41        "LinWeizheDragon/FLMR": (42            "https://huggingface.co/LinWeizheDragon/FLMR/resolve/main/context_tokenizer/tokenizer_config.json"43        ),44    },45}46QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP = {47    "vocab_file": {48        "LinWeizheDragon/PreFLMR_ViT-L": (49            "https://huggingface.co/LinWeizheDragon/PreFLMR_ViT-L/resolve/main/query_tokenizer/vocab.txt"50        ),51        "LinWeizheDragon/FLMR": ("https://huggingface.co/LinWeizheDragon/FLMR/resolve/main/query_tokenizer/vocab.txt"),52    },53    "tokenizer_file": {54        "LinWeizheDragon/PreFLMR_ViT-L": (55            "https://huggingface.co/LinWeizheDragon/PreFLMR_ViT-L/resolve/main/query_tokenizer/tokenizer_config.json"56        ),57        "LinWeizheDragon/FLMR": (58            "https://huggingface.co/LinWeizheDragon/FLMR/resolve/main/query_tokenizer/tokenizer_config.json"59        ),60    },61}62 63 64CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {65    "LinWeizheDragon/PreFLMR_ViT-L": 512,66    "LinWeizheDragon/FLMR": 512,67}68QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {69    "LinWeizheDragon/PreFLMR_ViT-L": 512,70    "LinWeizheDragon/FLMR": 512,71}72 73 74CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION = {75    "LinWeizheDragon/PreFLMR_ViT-L": {"do_lower_case": True},76    "LinWeizheDragon/FLMR": {"do_lower_case": True},77}78QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION = {79    "LinWeizheDragon/PreFLMR_ViT-L": {"do_lower_case": True},80    "LinWeizheDragon/FLMR": {"do_lower_case": True},81}82 83 84# Modified from colbert.modeling.tokenization85class FLMRContextEncoderTokenizer(BertTokenizer):86    r"""87    Construct a FLMRContextEncoder tokenizer.88 89    [`FLMRContextEncoderTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation90    splitting and wordpiece.91 92    Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.93    """94 95    vocab_files_names = VOCAB_FILES_NAMES96    pretrained_vocab_files_map = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP97    max_model_input_sizes = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES98    pretrained_init_configuration = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION99 100    def __init__(101        self,102        doc_maxlen: Optional[int] = 512,103        **kwargs,104    ):105        super().__init__(106            doc_maxlen=doc_maxlen,107            **kwargs,108        )109 110        self.doc_maxlen = doc_maxlen111        self.D_marker_token, self.D_marker_token_id = "[D]", self.convert_tokens_to_ids("[unused1]")112 113    def __call__(114        self,115        text: List[str],116        padding: Optional[Union[str, bool]] = "max_length",117        truncation: Optional[Union[bool, str]] = "longest_first",118        max_length: Optional[int] = 512,119        return_tensors: Optional[Union[str, TensorType]] = "pt",120        **kwargs,121    ):122        # add placehold for the [D] marker123        text = [". " + x for x in text]124 125        if max_length > self.doc_maxlen:126            # can not exceed the pre-set length127            max_length = self.doc_maxlen128 129        encoding = super().__call__(130            text,131            padding=padding,132            truncation=truncation,133            return_tensors=return_tensors,134            max_length=max_length,135            **kwargs,136        )137 138        ids, mask = encoding["input_ids"], encoding["attention_mask"]139 140        # postprocess for the [D] marker141        ids[:, 1] = self.D_marker_token_id142 143        # if bsize:144        #     # This bsize function is used in the original ColBERT codebase to split inputs into multiple batches145        #     if image_features is not None:146        #         ids, mask, image_features, reverse_indices = _sort_by_length(ids, mask, bsize, image_features=image_features)147        #         batches = _split_into_batches(ids, mask, bsize, image_features=image_features)148        #     else:149        #         ids, mask, reverse_indices = _sort_by_length(ids, mask, bsize)150        #         batches = _split_into_batches(ids, mask, bsize)151 152        #     return batches, reverse_indices153 154        encoding["input_ids"] = ids155        encoding["attention_mask"] = mask156 157        return encoding158 159 160# Modified from colbert.modeling.tokenization161class FLMRQueryEncoderTokenizer(BertTokenizer):162    r"""163    Constructs a FLMRQueryEncoder tokenizer.164 165    [`FLMRQueryEncoder`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation166    splitting and wordpiece.167 168    Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.169    """170 171    vocab_files_names = VOCAB_FILES_NAMES172    pretrained_vocab_files_map = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP173    max_model_input_sizes = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES174    pretrained_init_configuration = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION175 176    def __init__(177        self,178        *args,179        query_maxlen: Optional[int] = 32,180        attend_to_mask_tokens: Optional[bool] = False,181        **kwargs,182    ):183        super().__init__(184            *args,185            query_maxlen=query_maxlen,186            attend_to_mask_tokens=attend_to_mask_tokens,187            **kwargs,188        )189 190        self.query_maxlen = query_maxlen191        self.background_maxlen = 512 - self.query_maxlen + 1  # FIXME: Make this configurable192        self.attend_to_mask_tokens = attend_to_mask_tokens193 194        self.Q_marker_token, self.Q_marker_token_id = "[Q]", self.convert_tokens_to_ids("[unused0]")195 196    def __call__(197        self,198        text: Union[str, List[str]],199        padding: Optional[Union[str, bool]] = "max_length",200        truncation: Optional[Union[bool, str]] = True,201        max_length: Optional[int] = None,202        return_tensors: Optional[Union[str, TensorType]] = "pt",203        **kwargs,204    ):205        if isinstance(text, str):206            # convert to list if input is a single string207            text = [text]208 209        # add placehold for the [Q] marker210        text = [". " + x for x in text]211 212        if max_length is not None:213            # use user specified max_length214            pass215        else:216            # use default max length217            max_length = self.query_maxlen218 219        encoding = super().__call__(220            text,221            padding=padding,222            truncation=truncation,223            return_tensors=return_tensors,224            max_length=max_length,225            **kwargs,226        )227 228        ids, mask = encoding["input_ids"], encoding["attention_mask"]229 230        # postprocess for the [Q] marker and the [MASK] augmentation231        ids[:, 1] = self.Q_marker_token_id232        ids[ids == self.pad_token_id] = self.mask_token_id233 234        if self.attend_to_mask_tokens:235            # When attend_to_mask_tokens is True, we want to attend to the [MASK] tokens236            mask[ids == self.mask_token_id] = 1237            assert mask.sum().item() == mask.size(0) * mask.size(1), mask238 239        return {"input_ids": ids, "attention_mask": mask}240