mirror of
https://github.com/huggingface/transformers.git
synced 2025-07-05 05:40:05 +06:00

* feat: run `add-new-model-like` * feat: add paligemma code with "copied from" * feat: add ColPaliProcessor * feat: add ColPaliModel * feat: add ColPaliConfig * feat: rename `ColPaliForConditionalGeneration` to `ColPaliModel` * fixup modeling colpali * fix: fix root import shortcuts * fix: fix `modeling_auto` dict * feat: comment out ColPali test file * fix: fix typos from `add-new-model-like` * feat: explicit the forward input args * feat: move everything to `modular_colpali.py` * fix: put back ColPaliProcesor * feat: add auto-generated files * fix: run `fix-copies` * fix: remove DOCStRING constants to make modular converter work * fix: fix typo + modular converter * fix: add missing imports * feat: no more errors when loading ColPaliModel * fix: remove unused args in forward + tweak doc * feat: rename `ColPaliModel` to `ColPaliForRetrieval` * fix: apply `fix-copies` * feat: add ColPaliProcessor to `modular_colpali` * fix: run make quality + make style * fix: remove duplicate line in configuration_auto * feat: make ColPaliModel inehrit from PaliGemmaForConditionalGeneration * fix: tweak and use ColPaliConfig * feat: rename `score` to `post_process_retrieval` * build: run modular formatter + make style * feat: convert colpali weights + fixes * feat: remove old weight converter file * feat: add and validate tests * feat: replace harcoded path to "vidore/colpali-v1.2-hf" in tests * fix: add bfloat16 conversion in weight converter * feat: replace pytest with unittest in modeling colpali test * feat: add sanity check for weight conversion (doesn't work yet) * feat: add shape sanity check in weigth converter * feat: make ColPaliProcessor args explicit * doc: add doc for ColPali * fix: trying to fix output mismatch * feat: tweaks * fix: ColPaliModelOutput inherits from ModelOutput instead of PaliGemmaCausalLMOutputWithPast * fix: address comments on PR * fix: adapt tests to the Hf norm * wip: try things * feat: add `__call__` method to `ColPaliProcessor` * feat: remove need for dummy image in `process_queries` * build: run new modular converter * fix: fix incorrect method override * Fix tests, processing, modular, convert * fix tokenization auto * hotfix: manually fix processor -> fixme once convert modular is fixed * fix: convert weights working * feat: rename and improve convert weight script * feat: tweaks * fest: remove `device` input for `post_process_retrieval` * refactor: remove unused `get_torch_device` * Fix all tests * docs: update ColPali model doc * wip: fix convert weights to hf * fix logging modular * docs: add acknowledgements in model doc * docs: add missing docstring to ColPaliProcessor * docs: tweak * docs: add doc for `ColPaliForRetrievalOutput.forward` * feat: add modifications from colpali-engine v0.3.2 in ColPaliProcessor * fix: fix and upload colapli hf weights * refactor: rename `post_process_retrieval` to `score_retrieval` * fix: fix wrong typing for `score_retrieval` * test: add integration test for ColPali * chore: rerun convert modular * build: fix root imports * Update docs/source/en/index.md Co-authored-by: Yoni Gozlan <74535834+yonigozlan@users.noreply.github.com> * fix: address PR comments * wip: reduce the prediction gap in weight conversion * docs: add comment in weight conversion script * docs: add example for `ColPaliForRetrieval.forward` * tests: change dataset path to the new one in hf-internal * fix: colpali weight conversion works * test: add fine-grained check for ColPali integration test * fix: fix typos in convert weight script * docs: move input docstring in a variable * fix: remove hardcoded torch device in test * fix: run the new modular refactor * docs: fix python example for ColPali * feat: add option to choose `score_retrieval`'s output dtype and device * docs: update doc for `score_retrieval` * feat: add `patch_size` property in ColPali model * chore: run `make fix-copies` * docs: update description for ColPali cookbooks * fix: remove `ignore_index` methods * feat: remove non-transformers specific methods * feat: update `__init__.py` to new hf format * fix: fix root imports in transformers * feat: remove ColPali's inheritance from PaliGemma * Fix CI issues * nit remove prints * feat: remove ColPali config and model from `modular_colpali.py` * feat: add `ColPaliPreTrainedModel` and update modeling and configuration code * fix: fix auto-removed imports in root `__init__.py` * fix: various fixes * fix: fix `_init_weight` * temp: comment `AutoModel.from_config` for experiments * fix: add missing `output_attentions` arg in ColPali's forward * fix: fix `resize_token_embeddings` * fix: make `input_ids` optional in forward * feat: rename `projection_layer` to `embedding_proj_layer` * wip: fix convert colpali weight script * fix tests and convert weights from original repo * fix unprotected import * fix unprotected torch import * fix style * change vlm_backbone_config to vlm_config * fix unprotected import in modular this time * fix: load config from Hub + tweaks in convert weight script * docs: move example usage from model docstring to model markdown * docs: fix input docstring for ColPali's forward method * fix: use `sub_configs` for ColPaliConfig * fix: remove non-needed sanity checks in weight conversion script + tweaks * fix: fix issue with `replace_return_docstrings` in ColPali's `forward` * docs: update docstring for `ColPaliConfig` * test: change model path in ColPali test * fix: fix ColPaliConfig * fix: fix weight conversion script * test: fix expected weights for ColPali model * docs: update ColPali markdown * docs: fix minor typo in ColPaliProcessor * Fix tests and add _no_split_modules * add text_config to colpali config * [run slow] colpali * move inputs to torch_device in integration test * skip test_model_parallelism * docs: clarify quickstart snippet in ColPali's model card * docs: update ColPali's model card --------- Co-authored-by: yonigozlan <yoni.gozlan@huggingface.co> Co-authored-by: Yoni Gozlan <74535834+yonigozlan@users.noreply.github.com>
302 lines
11 KiB
Python
302 lines
11 KiB
Python
# coding=utf-8
|
|
# Copyright 2020 The HuggingFace Inc. team.
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
"""
|
|
Utility that checks the big table in the file docs/source/en/index.md and potentially updates it.
|
|
|
|
Use from the root of the repo with:
|
|
|
|
```bash
|
|
python utils/check_inits.py
|
|
```
|
|
|
|
for a check that will error in case of inconsistencies (used by `make repo-consistency`).
|
|
|
|
To auto-fix issues run:
|
|
|
|
```bash
|
|
python utils/check_inits.py --fix_and_overwrite
|
|
```
|
|
|
|
which is used by `make fix-copies`.
|
|
"""
|
|
|
|
import argparse
|
|
import collections
|
|
import os
|
|
import re
|
|
from typing import List
|
|
|
|
from transformers.utils import direct_transformers_import
|
|
|
|
|
|
# All paths are set with the intent you should run this script from the root of the repo with the command
|
|
# python utils/check_table.py
|
|
TRANSFORMERS_PATH = "src/transformers"
|
|
PATH_TO_DOCS = "docs/source/en"
|
|
REPO_PATH = "."
|
|
|
|
|
|
def _find_text_in_file(filename: str, start_prompt: str, end_prompt: str) -> str:
|
|
"""
|
|
Find the text in filename between two prompts.
|
|
|
|
Args:
|
|
filename (`str`): The file to search into.
|
|
start_prompt (`str`): A string to look for at the start of the content searched.
|
|
end_prompt (`str`): A string that will mark the end of the content to look for.
|
|
|
|
Returns:
|
|
`str`: The content between the prompts.
|
|
"""
|
|
with open(filename, "r", encoding="utf-8", newline="\n") as f:
|
|
lines = f.readlines()
|
|
|
|
# Find the start prompt.
|
|
start_index = 0
|
|
while not lines[start_index].startswith(start_prompt):
|
|
start_index += 1
|
|
start_index += 1
|
|
|
|
# Now go until the end prompt.
|
|
end_index = start_index
|
|
while not lines[end_index].startswith(end_prompt):
|
|
end_index += 1
|
|
end_index -= 1
|
|
|
|
while len(lines[start_index]) <= 1:
|
|
start_index += 1
|
|
while len(lines[end_index]) <= 1:
|
|
end_index -= 1
|
|
end_index += 1
|
|
return "".join(lines[start_index:end_index]), start_index, end_index, lines
|
|
|
|
|
|
# Regexes that match TF/Flax/PT model names. Add here suffixes that are used to identify models, separated by |
|
|
_re_tf_models = re.compile(r"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
|
|
_re_flax_models = re.compile(r"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
|
|
# Will match any TF or Flax model too so need to be in an else branch after the two previous regexes.
|
|
_re_pt_models = re.compile(r"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration|ForRetrieval)")
|
|
|
|
|
|
# This is to make sure the transformers module imported is the one in the repo.
|
|
transformers_module = direct_transformers_import(TRANSFORMERS_PATH)
|
|
|
|
|
|
def camel_case_split(identifier: str) -> List[str]:
|
|
"""
|
|
Split a camel-cased name into words.
|
|
|
|
Args:
|
|
identifier (`str`): The camel-cased name to parse.
|
|
|
|
Returns:
|
|
`List[str]`: The list of words in the identifier (as seprated by capital letters).
|
|
|
|
Example:
|
|
|
|
```py
|
|
>>> camel_case_split("CamelCasedClass")
|
|
["Camel", "Cased", "Class"]
|
|
```
|
|
"""
|
|
# Regex thanks to https://stackoverflow.com/questions/29916065/how-to-do-camelcase-split-in-python
|
|
matches = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)", identifier)
|
|
return [m.group(0) for m in matches]
|
|
|
|
|
|
def _center_text(text: str, width: int) -> str:
|
|
"""
|
|
Utility that will add spaces on the left and right of a text to make it centered for a given width.
|
|
|
|
Args:
|
|
text (`str`): The text to center.
|
|
width (`int`): The desired length of the result.
|
|
|
|
Returns:
|
|
`str`: A text of length `width` with the original `text` in the middle.
|
|
"""
|
|
text_length = 2 if text == "✅" or text == "❌" else len(text)
|
|
left_indent = (width - text_length) // 2
|
|
right_indent = width - text_length - left_indent
|
|
return " " * left_indent + text + " " * right_indent
|
|
|
|
|
|
SPECIAL_MODEL_NAME_LINK_MAPPING = {
|
|
"Data2VecAudio": "[Data2VecAudio](model_doc/data2vec)",
|
|
"Data2VecText": "[Data2VecText](model_doc/data2vec)",
|
|
"Data2VecVision": "[Data2VecVision](model_doc/data2vec)",
|
|
"DonutSwin": "[DonutSwin](model_doc/donut)",
|
|
}
|
|
|
|
MODEL_NAMES_WITH_SAME_CONFIG = {
|
|
"BARThez": "BART",
|
|
"BARTpho": "BART",
|
|
"BertJapanese": "BERT",
|
|
"BERTweet": "BERT",
|
|
"BORT": "BERT",
|
|
"ByT5": "T5",
|
|
"CPM": "OpenAI GPT-2",
|
|
"DePlot": "Pix2Struct",
|
|
"DialoGPT": "OpenAI GPT-2",
|
|
"DiT": "BEiT",
|
|
"FLAN-T5": "T5",
|
|
"FLAN-UL2": "T5",
|
|
"HerBERT": "BERT",
|
|
"LayoutXLM": "LayoutLMv2",
|
|
"Llama2": "LLaMA",
|
|
"Llama3": "LLaMA",
|
|
"MADLAD-400": "T5",
|
|
"MatCha": "Pix2Struct",
|
|
"mBART-50": "mBART",
|
|
"Megatron-GPT2": "OpenAI GPT-2",
|
|
"mLUKE": "LUKE",
|
|
"MMS": "Wav2Vec2",
|
|
"NLLB": "M2M100",
|
|
"PhoBERT": "BERT",
|
|
"T5v1.1": "T5",
|
|
"TAPEX": "BART",
|
|
"UL2": "T5",
|
|
"Wav2Vec2Phoneme": "Wav2Vec2",
|
|
"XLM-V": "XLM-RoBERTa",
|
|
"XLS-R": "Wav2Vec2",
|
|
"XLSR-Wav2Vec2": "Wav2Vec2",
|
|
}
|
|
MODEL_NAMES_TO_IGNORE = [
|
|
"ChineseCLIPVisionModel",
|
|
"CLIPTextModel",
|
|
"CLIPVisionModel",
|
|
"Qwen2AudioEncoder",
|
|
"SiglipVisionModel",
|
|
]
|
|
|
|
|
|
def get_model_table_from_auto_modules() -> str:
|
|
"""
|
|
Generates an up-to-date model table from the content of the auto modules.
|
|
"""
|
|
# Dictionary model names to config.
|
|
config_maping_names = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
|
|
model_name_to_config = {
|
|
name: config_maping_names[code]
|
|
for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
|
|
if code in config_maping_names
|
|
}
|
|
model_name_to_prefix = {name: config.replace("Config", "") for name, config in model_name_to_config.items()}
|
|
|
|
# Dictionaries flagging if each model prefix has a backend in PT/TF/Flax.
|
|
pt_models = collections.defaultdict(bool)
|
|
tf_models = collections.defaultdict(bool)
|
|
flax_models = collections.defaultdict(bool)
|
|
|
|
# Let's lookup through all transformers object (once).
|
|
for attr_name in dir(transformers_module):
|
|
lookup_dict = None
|
|
if _re_tf_models.match(attr_name) is not None:
|
|
lookup_dict = tf_models
|
|
attr_name = _re_tf_models.match(attr_name).groups()[0]
|
|
elif _re_flax_models.match(attr_name) is not None:
|
|
lookup_dict = flax_models
|
|
attr_name = _re_flax_models.match(attr_name).groups()[0]
|
|
elif _re_pt_models.match(attr_name) is not None:
|
|
lookup_dict = pt_models
|
|
attr_name = _re_pt_models.match(attr_name).groups()[0]
|
|
|
|
if lookup_dict is not None:
|
|
while len(attr_name) > 0:
|
|
if attr_name in model_name_to_prefix.values():
|
|
lookup_dict[attr_name] = True
|
|
break
|
|
# Try again after removing the last word in the name
|
|
attr_name = "".join(camel_case_split(attr_name)[:-1])
|
|
|
|
# Let's build that table!
|
|
model_names = list(model_name_to_config.keys()) + list(MODEL_NAMES_WITH_SAME_CONFIG.keys())
|
|
|
|
# model name to doc link mapping
|
|
model_names_mapping = transformers_module.models.auto.configuration_auto.MODEL_NAMES_MAPPING
|
|
model_name_to_link_mapping = {value: f"[{value}](model_doc/{key})" for key, value in model_names_mapping.items()}
|
|
# update mapping with special model names
|
|
model_name_to_link_mapping = {
|
|
k: SPECIAL_MODEL_NAME_LINK_MAPPING[k] if k in SPECIAL_MODEL_NAME_LINK_MAPPING else v
|
|
for k, v in model_name_to_link_mapping.items()
|
|
}
|
|
|
|
# MaskFormerSwin and TimmBackbone are backbones and so not meant to be loaded and used on their own. Instead, they define architectures which can be loaded using the AutoBackbone API.
|
|
names_to_exclude = ["MaskFormerSwin", "TimmBackbone", "Speech2Text2"]
|
|
model_names = [name for name in model_names if name not in names_to_exclude]
|
|
model_names.sort(key=str.lower)
|
|
|
|
columns = ["Model", "PyTorch support", "TensorFlow support", "Flax Support"]
|
|
# We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side).
|
|
|
|
widths = [len(c) + 2 for c in columns]
|
|
widths[0] = max([len(doc_link) for doc_link in model_name_to_link_mapping.values()]) + 2
|
|
|
|
# Build the table per se
|
|
table = "|" + "|".join([_center_text(c, w) for c, w in zip(columns, widths)]) + "|\n"
|
|
# Use ":-----:" format to center-aligned table cell texts
|
|
table += "|" + "|".join([":" + "-" * (w - 2) + ":" for w in widths]) + "|\n"
|
|
|
|
check = {True: "✅", False: "❌"}
|
|
|
|
for name in model_names:
|
|
if name in MODEL_NAMES_TO_IGNORE:
|
|
continue
|
|
if name in MODEL_NAMES_WITH_SAME_CONFIG.keys():
|
|
prefix = model_name_to_prefix[MODEL_NAMES_WITH_SAME_CONFIG[name]]
|
|
else:
|
|
prefix = model_name_to_prefix[name]
|
|
line = [
|
|
model_name_to_link_mapping[name],
|
|
check[pt_models[prefix]],
|
|
check[tf_models[prefix]],
|
|
check[flax_models[prefix]],
|
|
]
|
|
table += "|" + "|".join([_center_text(l, w) for l, w in zip(line, widths)]) + "|\n"
|
|
return table
|
|
|
|
|
|
def check_model_table(overwrite=False):
|
|
"""
|
|
Check the model table in the index.md is consistent with the state of the lib and potentially fix it.
|
|
|
|
Args:
|
|
overwrite (`bool`, *optional*, defaults to `False`):
|
|
Whether or not to overwrite the table when it's not up to date.
|
|
"""
|
|
current_table, start_index, end_index, lines = _find_text_in_file(
|
|
filename=os.path.join(PATH_TO_DOCS, "index.md"),
|
|
start_prompt="<!--This table is updated automatically from the auto modules",
|
|
end_prompt="<!-- End table-->",
|
|
)
|
|
new_table = get_model_table_from_auto_modules()
|
|
|
|
if current_table != new_table:
|
|
if overwrite:
|
|
with open(os.path.join(PATH_TO_DOCS, "index.md"), "w", encoding="utf-8", newline="\n") as f:
|
|
f.writelines(lines[:start_index] + [new_table] + lines[end_index:])
|
|
else:
|
|
raise ValueError(
|
|
"The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this."
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
|
|
args = parser.parse_args()
|
|
|
|
check_model_table(args.fix_and_overwrite)
|