Run this model with HF Jobs
Run ChuuniZ/xcw-models on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/ChuuniZ/xcw-models. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/ChuuniZ/xcw-models on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use ChuuniZ/xcw-models with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use ChuuniZ/xcw-models with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("ChuuniZ/xcw-models", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- RMBG/body_segment/deeplabv3p-resnet50-human.onnxAdded+3
- florence2/DocVQA/configuration_florence2.pyAdded+340
- florence2/DocVQA/processing_florence2.pyAdded+1088
- florence2/base-ft/LICENSEAdded+21
- florence2/base-ft/config.jsonAdded+85
- florence2/base-ft/configuration_florence2.pyAdded+340
- florence2/base-ft/modeling_florence2.pyAdded
- florence2/base-ft/preprocessor_config.jsonAdded+39
- florence2/base-ft/processing_florence2.pyAdded+1088
- florence2/base-ft/tokenizer.jsonAdded
- florence2/base-ft/tokenizer_config.jsonAdded+4
- florence2/base-ft/vocab.jsonAdded
- florence2/large-ft/pytorch_model.binAdded+3
- ipadapter/ip-adapter-plus-face_sdxl_vit-h.safetensorsAdded+3
- ipadapter/ip-adapter-plus_sdxl_vit-h.safetensorsAdded+3
- ipadapter/ip-adapter_sdxl_vit-h.safetensorsAdded+3
- ipadapter/ip_plus_composition_sdxl.safetensorsAdded+3
- ipadapter/noobIPAMARK1_mark1.safetensorsAdded+3
- loras/flux/20 (1).safetensorsAdded+3
- loras/flux/3D玩具手办盲盒_FLUX-V1.safetensorsAdded+3
- loras/flux/5yocrayon1_cap_d6a3e12.safetensorsAdded+3
- loras/flux/Bacun_style_Flux_Test_000003000.safetensorsAdded+3
- loras/flux/Belly_Stuffed-000003.safetensorsAdded+3
- loras/flux/Dakimakura_Body_Pillow_Designer_FLUX-000021.safetensorsAdded+3
- loras/flux/DigitalMatte_FLUX.safetensorsAdded+3
- loras/flux/Dollification_-_inflatable_sex_doll_transformation_rubber_skin_sdol_-_flux.safetensorsAdded+3
- loras/flux/FLUX|Y2K girl manga style-Cassiopeia_TypeB V1.2.0.safetensorsAdded+3
- loras/flux/Flux_penis.safetensorsAdded+3
- loras/flux/Illumination_Style_Flux.safetensorsAdded+3
- loras/flux/LOL_Emotes_HD_-_FLUX_dev.safetensorsAdded+3
- loras/flux/MLKBC 微观世界-盲盒手办_V1.safetensorsAdded+3
- loras/flux/OB乐高人物V1.0.safetensorsAdded+3
- loras/flux/Simpsons_Style_-_FLUX.safetensorsAdded+3
- loras/flux/VectorCharm_Flux.safetensorsAdded+3
- loras/flux/Yogisya_FLUX.safetensorsAdded+3
- loras/flux/arcane-style-2.safetensorsAdded+3
- loras/flux/archerstyle_v1_000002800.safetensorsAdded+3
- loras/flux/cartoon_saloon_flux_000007000.safetensorsAdded+3
- loras/flux/flux-lora-vintage-tarot.safetensorsAdded+3
- loras/flux/hugeboobs.safetensorsAdded+3
- loras/flux/j_dsstyle_flux.safetensorsAdded+3
- loras/flux/jet_set_radio_flux_000002800.safetensorsAdded+3
- loras/flux/labubu jastu.safetensorsAdded+3
- loras/flux/lowerdecks_style_v1.0.safetensorsAdded+3
- loras/flux/paipai.safetensorsAdded+3
- loras/flux/removal_timestep_alpha-2-1740.safetensorsAdded+3
- loras/flux/torikun_flux_lora_000003000.safetensorsAdded+3
- loras/flux/users_LORA_639195226744978302_32f14df2-e590-4d28-b20f-140d2ec39970.TA_trained.safetensorsAdded+3
- loras/flux/users_LORA_766170570185454547_1ff18e01-e4ab-40fa-8211-4f7b325fd7b3.by_tusi.safetensorsAdded+3
- loras/flux/users_LORA_766170570185454547_fbdd160e-01f5-4f6e-90b5-a73870ecf720.by_tusi.safetensorsAdded+3
123version https://git-lfs.github.com/spec/v1oid sha256:a6e823a82da10ba24c29adfb544130684568c46bfac865e215bbace3b4035a71size 47210581123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340# coding=utf-8# Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.# 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.import warnings""" Florence-2 configuration"""
from typing import Optional
from transformers import AutoConfigfrom transformers.configuration_utils import PretrainedConfigfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class Florence2VisionConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Florence2VisionModel`]. It is used to instantiate a Florence2VisionModel according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Florence2VisionModel architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: drop_path_rate (`float`, *optional*, defaults to 0.1): The dropout rate of the drop path layer. patch_size (`List[int]`, *optional*, defaults to [7, 3, 3, 3]): The patch size of the image. patch_stride (`List[int]`, *optional*, defaults to [4, 2, 2, 2]): The patch stride of the image. patch_padding (`List[int]`, *optional*, defaults to [3, 1, 1, 1]): The patch padding of the image. patch_prenorm (`List[bool]`, *optional*, defaults to [false, true, true, true]): Whether to apply layer normalization before the patch embedding layer. enable_checkpoint (`bool`, *optional*, defaults to False): Whether to enable checkpointing. dim_embed (`List[int]`, *optional*, defaults to [256, 512, 1024, 2048]): The dimension of the embedding layer. num_heads (`List[int]`, *optional*, defaults to [8, 16, 32, 64]): The number of attention heads. num_groups (`List[int]`, *optional*, defaults to [8, 16, 32, 64]): The number of groups. depths (`List[int]`, *optional*, defaults to [1, 1, 9, 1]): The depth of the model. window_size (`int`, *optional*, defaults to 12): The window size of the model. projection_dim (`int`, *optional*, defaults to 1024): The dimension of the projection layer. visual_temporal_embedding (`dict`, *optional*): The configuration of the visual temporal embedding. image_pos_embed (`dict`, *optional*): The configuration of the image position embedding. image_feature_source (`List[str]`, *optional*, defaults to ["spatial_avg_pool", "temporal_avg_pool"]): The source of the image feature. Example:
```python >>> from transformers import Florence2VisionConfig, Florence2VisionModel
>>> # Initializing a Florence2 Vision style configuration >>> configuration = Florence2VisionConfig()
>>> # Initializing a model (with random weights) >>> model = Florence2VisionModel(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "florence2_vision" keys_to_ignore_at_inference = ["past_key_values"]
def __init__( self, drop_path_rate=0.1, patch_size=[7, 3, 3, 3], patch_stride=[4, 2, 2, 2], patch_padding=[3, 1, 1, 1], patch_prenorm=[False, True, True, True], enable_checkpoint=False, dim_embed=[256, 512, 1024, 2048], num_heads=[8, 16, 32, 64], num_groups=[8, 16, 32, 64], depths=[1, 1, 9, 1], window_size=12, projection_dim=1024, visual_temporal_embedding=None, image_pos_embed=None, image_feature_source=["spatial_avg_pool", "temporal_avg_pool"], **kwargs, ): self.drop_path_rate = drop_path_rate self.patch_size = patch_size self.patch_stride = patch_stride self.patch_padding = patch_padding self.patch_prenorm = patch_prenorm self.enable_checkpoint = enable_checkpoint self.dim_embed = dim_embed self.num_heads = num_heads self.num_groups = num_groups self.depths = depths self.window_size = window_size self.projection_dim = projection_dim self.visual_temporal_embedding = visual_temporal_embedding self.image_pos_embed = image_pos_embed self.image_feature_source = image_feature_source
super().__init__(**kwargs)
class Florence2LanguageConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Florence2LanguagePreTrainedModel`]. It is used to instantiate a BART model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the BART [facebook/bart-large](https://huggingface.co/facebook/bart-large) architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: vocab_size (`int`, *optional*, defaults to 51289): Vocabulary size of the Florence2Language model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Florence2LanguageModel`]. d_model (`int`, *optional*, defaults to 1024): Dimensionality of the layers and the pooler layer. encoder_layers (`int`, *optional*, defaults to 12): Number of encoder layers. decoder_layers (`int`, *optional*, defaults to 12): Number of decoder layers. encoder_attention_heads (`int`, *optional*, defaults to 16): Number of attention heads for each attention layer in the Transformer encoder. decoder_attention_heads (`int`, *optional*, defaults to 16): Number of attention heads for each attention layer in the Transformer decoder. decoder_ffn_dim (`int`, *optional*, defaults to 4096): Dimensionality of the "intermediate" (often named feed-forward) layer in decoder. encoder_ffn_dim (`int`, *optional*, defaults to 4096): Dimensionality of the "intermediate" (often named feed-forward) layer in decoder. activation_function (`str` or `function`, *optional*, defaults to `"gelu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported. dropout (`float`, *optional*, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. activation_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for activations inside the fully connected layer. classifier_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for classifier. max_position_embeddings (`int`, *optional*, defaults to 1024): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). init_std (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. encoder_layerdrop (`float`, *optional*, defaults to 0.0): The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more details. decoder_layerdrop (`float`, *optional*, defaults to 0.0): The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more details. scale_embedding (`bool`, *optional*, defaults to `False`): Scale embeddings by diving by sqrt(d_model). use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). num_labels (`int`, *optional*, defaults to 3): The number of labels to use in [`Florence2LanguageForSequenceClassification`]. forced_eos_token_id (`int`, *optional*, defaults to 2): The id of the token to force as the last generated token when `max_length` is reached. Usually set to `eos_token_id`.
Example:
```python >>> from transformers import Florence2LanguageConfig, Florence2LanguageModel
>>> # Initializing a Florence2 Language style configuration >>> configuration = Florence2LanguageConfig()
>>> # Initializing a model (with random weights) >>> model = Florence2LangaugeModel(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "florence2_language" keys_to_ignore_at_inference = ["past_key_values"] attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
def __init__( self, vocab_size=51289, max_position_embeddings=1024, encoder_layers=12, encoder_ffn_dim=4096, encoder_attention_heads=16, decoder_layers=12, decoder_ffn_dim=4096, decoder_attention_heads=16, encoder_layerdrop=0.0, decoder_layerdrop=0.0, activation_function="gelu", d_model=1024, dropout=0.1, attention_dropout=0.0, activation_dropout=0.0, init_std=0.02, classifier_dropout=0.0, scale_embedding=False, use_cache=True, num_labels=3, pad_token_id=1, bos_token_id=0, eos_token_id=2, is_encoder_decoder=True, decoder_start_token_id=2, forced_eos_token_id=2, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.d_model = d_model self.encoder_ffn_dim = encoder_ffn_dim self.encoder_layers = encoder_layers self.encoder_attention_heads = encoder_attention_heads self.decoder_ffn_dim = decoder_ffn_dim self.decoder_layers = decoder_layers self.decoder_attention_heads = decoder_attention_heads self.dropout = dropout self.attention_dropout = attention_dropout self.activation_dropout = activation_dropout self.activation_function = activation_function self.init_std = init_std self.encoder_layerdrop = encoder_layerdrop self.decoder_layerdrop = decoder_layerdrop self.classifier_dropout = classifier_dropout self.use_cache = use_cache self.num_hidden_layers = encoder_layers self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
super().__init__( num_labels=num_labels, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, is_encoder_decoder=is_encoder_decoder, decoder_start_token_id=decoder_start_token_id, forced_eos_token_id=forced_eos_token_id, **kwargs, )
# ensure backward compatibility for BART CNN models if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated", False): self.forced_bos_token_id = self.bos_token_id warnings.warn( f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " "The config can simply be saved and uploaded again to be fixed." )
class Florence2Config(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Florence2ForConditionalGeneration`]. It is used to instantiate an Florence-2 model according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: vision_config (`Florence2VisionConfig`, *optional*): Custom vision config or dict text_config (`Union[AutoConfig, dict]`, *optional*): The config object of the text backbone. ignore_index (`int`, *optional*, defaults to -100): The ignore index for the loss function. vocab_size (`int`, *optional*, defaults to 51289): Vocabulary size of the Florence2model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`~Florence2ForConditionalGeneration`] projection_dim (`int`, *optional*, defaults to 1024): Dimension of the multimodal projection space.
Example:
```python >>> from transformers import Florence2ForConditionalGeneration, Florence2Config, CLIPVisionConfig, BartConfig
>>> # Initializing a clip-like vision config >>> vision_config = CLIPVisionConfig()
>>> # Initializing a Bart config >>> text_config = BartConfig()
>>> # Initializing a Florence-2 configuration >>> configuration = Florence2Config(vision_config, text_config)
>>> # Initializing a model from the florence-2 configuration >>> model = Florence2ForConditionalGeneration(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "florence2" is_composition = False
def __init__( self, vision_config=None, text_config=None, ignore_index=-100, vocab_size=51289, projection_dim=1024, **kwargs, ): self.ignore_index = ignore_index self.vocab_size = vocab_size self.projection_dim = projection_dim if vision_config is not None: vision_config = PretrainedConfig(**vision_config) self.vision_config = vision_config self.vocab_size = self.vocab_size
self.text_config = text_config if text_config is not None: self.text_config = Florence2LanguageConfig(**text_config)
super().__init__(**kwargs)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088# coding=utf-8# Copyright 2024 Microsoft and 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."""Processor class for Florence-2."""
import reimport loggingfrom typing import List, Optional, Unionimport numpy as np
import torch
from transformers.feature_extraction_utils import BatchFeaturefrom transformers.image_utils import ImageInput, is_valid_imagefrom transformers.processing_utils import ProcessorMixinfrom transformers.tokenization_utils_base import ( PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy,)from transformers.utils import TensorType
logger = logging.getLogger(__name__)
# Copied from transformers.models.idefics2.processing_idefics2.is_urldef is_url(val) -> bool: return isinstance(val, str) and val.startswith("http")
# Copied from transformers.models.idefics2.processing_idefics2.is_image_or_image_urldef is_image_or_image_url(elem): return is_url(elem) or is_valid_image(elem)
def _is_str_or_image(elem): return isinstance(elem, (str)) or is_image_or_image_url(elem)
class Florence2Processor(ProcessorMixin): r""" Constructs a Florence2 processor which wraps a Florence2 image processor and a Florence2 tokenizer into a single processor.
[`Florence2Processor`] offers all the functionalities of [`CLIPImageProcessor`] and [`BartTokenizerFast`]. See the [`~Florence2Processor.__call__`] and [`~Florence2Processor.decode`] for more information.
Args: image_processor ([`CLIPImageProcessor`], *optional*): The image processor is a required input. tokenizer ([`BartTokenizerFast`], *optional*): The tokenizer is a required input. """
attributes = ["image_processor", "tokenizer"] image_processor_class = "CLIPImageProcessor" tokenizer_class = ("BartTokenizer", "BartTokenizerFast")
def __init__( self, image_processor=None, tokenizer=None, ): if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") if not hasattr(image_processor, "image_seq_length"): raise ValueError("Image processor is missing an `image_seq_length` attribute.")
self.image_seq_length = image_processor.image_seq_length
tokens_to_add = { 'additional_special_tokens': \ tokenizer.additional_special_tokens + \ ['<od>', '</od>', '<ocr>', '</ocr>'] + \ [f'<loc_{x}>' for x in range(1000)] + \ ['<cap>', '</cap>', '<ncap>', '</ncap>','<dcap>', '</dcap>', '<grounding>', '</grounding>', '<seg>', '</seg>', '<sep>', '<region_cap>', '</region_cap>', '<region_to_desciption>', '</region_to_desciption>', '<proposal>', '</proposal>', '<poly>', '</poly>', '<and>'] } tokenizer.add_special_tokens(tokens_to_add)
self.tasks_answer_post_processing_type = { '<OCR>': 'pure_text', '<OCR_WITH_REGION>': 'ocr', '<CAPTION>': 'pure_text', '<DETAILED_CAPTION>': 'pure_text', '<MORE_DETAILED_CAPTION>': 'pure_text', '<OD>': 'description_with_bboxes', '<DENSE_REGION_CAPTION>': 'description_with_bboxes', '<CAPTION_TO_PHRASE_GROUNDING>': "phrase_grounding", '<REFERRING_EXPRESSION_SEGMENTATION>': 'polygons', '<REGION_TO_SEGMENTATION>': 'polygons', '<OPEN_VOCABULARY_DETECTION>': 'description_with_bboxes_or_polygons', '<REGION_TO_CATEGORY>': 'pure_text', '<REGION_TO_DESCRIPTION>': 'pure_text', '<REGION_TO_OCR>': 'pure_text', '<REGION_PROPOSAL>': 'bboxes' }
self.task_prompts_without_inputs = { '<OCR>': 'What is the text in the image?', '<OCR_WITH_REGION>': 'What is the text in the image, with regions?', '<CAPTION>': 'What does the image describe?', '<DETAILED_CAPTION>': 'Describe in detail what is shown in the image.', '<MORE_DETAILED_CAPTION>': 'Describe with a paragraph what is shown in the image.', '<OD>': 'Locate the objects with category name in the image.', '<DENSE_REGION_CAPTION>': 'Locate the objects in the image, with their descriptions.', '<REGION_PROPOSAL>': 'Locate the region proposals in the image.' }
self.task_prompts_with_input = { '<CAPTION_TO_PHRASE_GROUNDING>': "Locate the phrases in the caption: {input}", '<REFERRING_EXPRESSION_SEGMENTATION>': 'Locate {input} in the image with mask', '<REGION_TO_SEGMENTATION>': 'What is the polygon mask of region {input}', '<OPEN_VOCABULARY_DETECTION>': 'Locate {input} in the image.', '<REGION_TO_CATEGORY>': 'What is the region {input}?', '<REGION_TO_DESCRIPTION>': 'What does the region {input} describe?', '<REGION_TO_OCR>': 'What text is in the region {input}?', }
self.post_processor = Florence2PostProcesser(tokenizer=tokenizer)
super().__init__(image_processor, tokenizer) def _construct_prompts(self, text): # replace the task tokens with the task prompts if task token is in the text prompts = [] for _text in text: # 1. fixed task prompts without additional inputs for task_token, task_prompt in self.task_prompts_without_inputs.items(): if task_token in _text: assert _text == task_token, f"Task token {task_token} should be the only token in the text." _text = task_prompt break # 2. task prompts with additional inputs for task_token, task_prompt in self.task_prompts_with_input.items(): if task_token in _text: _text = task_prompt.format(input=_text.replace(task_token, '')) break prompts.append(_text) return prompts
def __call__( self, text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None, images: ImageInput = None, tokenize_newline_separately: bool = True, padding: Union[bool, str, PaddingStrategy] = False, truncation: Union[bool, str, TruncationStrategy] = None, max_length=None, return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH, do_resize: bool = None, do_normalize: bool = None, image_mean: Optional[Union[float, List[float]]] = None, image_std: Optional[Union[float, List[float]]] = None, data_format: Optional["ChannelDimension"] = "channels_first", # noqa: F821 input_data_format: Optional[ Union[str, "ChannelDimension"] # noqa: F821 ] = None, resample: "PILImageResampling" = None, # noqa: F821 do_convert_rgb: bool = None, do_thumbnail: bool = None, do_align_long_axis: bool = None, do_rescale: bool = None, ) -> BatchFeature: """ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text` and `kwargs` arguments to BartTokenizerFast's [`~BartTokenizerFast.__call__`] if `text` is not `None` to encode the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring of the above two methods for more information.
Args: text (`str`, `List[str]`, `List[List[str]]`): The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences). images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`): The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a number of channels, H and W are image height and width. tokenize_newline_separately (`bool`, defaults to `True`): Adds a separately tokenized '\n' at the end of the prompt. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Select a strategy to pad the returned sequences (according to the model's padding side and padding index) among: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). max_length (`int`, *optional*): Maximum length of the returned list and optionally padding length (see above). truncation (`bool`, *optional*): Activates truncation to cut input sequences longer than `max_length` to `max_length`. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are:
- `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. - `'jax'`: Return JAX `jnp.ndarray` objects.
Returns: [`BatchFeature`]: A [`BatchFeature`] with the following fields:
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. If `suffix` is provided, the `input_ids` will also contain the suffix input ids. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not `None`). - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`. - **labels** -- Labels compatible with training if `suffix` is not None """
return_token_type_ids = False
if images is None: raise ValueError("`images` are expected as arguments to a `Florence2Processor` instance.") if text is None: logger.warning_once( "You are using Florence-2 without a text prompt." ) text = ""
if isinstance(text, List) and isinstance(images, List): if len(images) < len(text): raise ValueError( f"Received {len(images)} images for {len(text)} prompts. Each prompt should be associated with an image." ) if _is_str_or_image(text): text = [text] elif isinstance(text, list) and _is_str_or_image(text[0]): pass
pixel_values = self.image_processor( images, do_resize=do_resize, do_normalize=do_normalize, return_tensors=return_tensors, image_mean=image_mean, image_std=image_std, input_data_format=input_data_format, data_format=data_format, resample=resample, do_convert_rgb=do_convert_rgb, )["pixel_values"]
if max_length is not None: max_length -= self.image_seq_length # max_length has to account for the image tokens
text = self._construct_prompts(text)
inputs = self.tokenizer( text, return_tensors=return_tensors, padding=padding, max_length=max_length, truncation=truncation, return_token_type_ids=return_token_type_ids, )
return_data = {**inputs, "pixel_values": pixel_values}
if return_token_type_ids: labels = inputs["input_ids"].masked_fill(inputs["token_type_ids"] == 0, -100) return_data.update({"labels": labels}) return BatchFeature(data=return_data)
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Florence2 def batch_decode(self, *args, **kwargs): """ This method forwards all its arguments to BartTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.batch_decode(*args, **kwargs)
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Florence2 def decode(self, *args, **kwargs): """ This method forwards all its arguments to BartTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.decode(*args, **kwargs)
@property # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names with CLIP->Florence2 def model_input_names(self): tokenizer_input_names = self.tokenizer.model_input_names image_processor_input_names = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
def post_process_generation(self, text, task, image_size): """ Post-process the output of the model to each of the task outputs.
Args: text (`str`): The text to post-process. task (`str`): The task to post-process the text for. image_size (`Tuple[int, int]`): The size of the image. height x width. """
task_answer_post_processing_type = self.tasks_answer_post_processing_type.get(task, 'pure_text') task_answer = self.post_processor( text=text, image_size=image_size, parse_tasks=task_answer_post_processing_type, )[task_answer_post_processing_type]
if task_answer_post_processing_type == 'pure_text': final_answer = task_answer # remove the special tokens final_answer = final_answer.replace('<s>', '').replace('</s>', '') elif task_answer_post_processing_type in ['od', 'description_with_bboxes', 'bboxes']: od_instances = task_answer bboxes_od = [_od_instance['bbox'] for _od_instance in od_instances] labels_od = [str(_od_instance['cat_name']) for _od_instance in od_instances] final_answer = {'bboxes': bboxes_od, 'labels': labels_od} elif task_answer_post_processing_type in ['ocr']: bboxes = [_od_instance['quad_box'] for _od_instance in task_answer] labels = [str(_od_instance['text']) for _od_instance in task_answer] final_answer = {'quad_boxes': bboxes, 'labels': labels} elif task_answer_post_processing_type in ['phrase_grounding']: bboxes = [] labels = [] for _grounded_phrase in task_answer: for _bbox in _grounded_phrase['bbox']: bboxes.append(_bbox) labels.append(_grounded_phrase['cat_name']) final_answer = {'bboxes': bboxes, 'labels': labels} elif task_answer_post_processing_type in ['description_with_polygons', 'polygons']: labels = [] polygons = [] for result in task_answer: label = result['cat_name'] _polygons = result['polygons'] labels.append(label) polygons.append(_polygons) final_answer = {'polygons': polygons, 'labels': labels} elif task_answer_post_processing_type in ['description_with_bboxes_or_polygons']: bboxes = [] bboxes_labels = [] polygons = [] polygons_labels = [] for result in task_answer: label = result['cat_name'] if 'polygons' in result: _polygons = result['polygons'] polygons.append(_polygons) polygons_labels.append(label) else: _bbox = result['bbox'] bboxes.append(_bbox) bboxes_labels.append(label) final_answer = {'bboxes': bboxes, 'bboxes_labels': bboxes_labels, 'polygons': polygons, 'polygons_labels': polygons_labels} else: raise ValueError('Unknown task answer post processing type: {}'.format(task_answer_post_processing_type))
final_answer = { task: final_answer} return final_answer
class BoxQuantizer(object): def __init__(self, mode, bins): self.mode = mode self.bins = bins
def quantize(self, boxes: torch.Tensor, size): bins_w, bins_h = self.bins # Quantization bins. size_w, size_h = size # Original image size. size_per_bin_w = size_w / bins_w size_per_bin_h = size_h / bins_h xmin, ymin, xmax, ymax = boxes.split(1, dim=-1) # Shape: 4 * [N, 1].
if self.mode == 'floor': quantized_xmin = ( xmin / size_per_bin_w).floor().clamp(0, bins_w - 1) quantized_ymin = ( ymin / size_per_bin_h).floor().clamp(0, bins_h - 1) quantized_xmax = ( xmax / size_per_bin_w).floor().clamp(0, bins_w - 1) quantized_ymax = ( ymax / size_per_bin_h).floor().clamp(0, bins_h - 1)
elif self.mode == 'round': raise NotImplementedError()
else: raise ValueError('Incorrect quantization type.')
quantized_boxes = torch.cat( (quantized_xmin, quantized_ymin, quantized_xmax, quantized_ymax), dim=-1 ).int()
return quantized_boxes
def dequantize(self, boxes: torch.Tensor, size): bins_w, bins_h = self.bins # Quantization bins. size_w, size_h = size # Original image size. size_per_bin_w = size_w / bins_w size_per_bin_h = size_h / bins_h xmin, ymin, xmax, ymax = boxes.split(1, dim=-1) # Shape: 4 * [N, 1].
if self.mode == 'floor': # Add 0.5 to use the center position of the bin as the coordinate. dequantized_xmin = (xmin + 0.5) * size_per_bin_w dequantized_ymin = (ymin + 0.5) * size_per_bin_h dequantized_xmax = (xmax + 0.5) * size_per_bin_w dequantized_ymax = (ymax + 0.5) * size_per_bin_h
elif self.mode == 'round': raise NotImplementedError()
else: raise ValueError('Incorrect quantization type.')
dequantized_boxes = torch.cat( (dequantized_xmin, dequantized_ymin, dequantized_xmax, dequantized_ymax), dim=-1 )
return dequantized_boxes
class CoordinatesQuantizer(object): """ Quantize coornidates (Nx2) """
def __init__(self, mode, bins): self.mode = mode self.bins = bins
def quantize(self, coordinates: torch.Tensor, size): bins_w, bins_h = self.bins # Quantization bins. size_w, size_h = size # Original image size. size_per_bin_w = size_w / bins_w size_per_bin_h = size_h / bins_h assert coordinates.shape[-1] == 2, 'coordinates should be shape (N, 2)' x, y = coordinates.split(1, dim=-1) # Shape: 4 * [N, 1].
if self.mode == 'floor': quantized_x = (x / size_per_bin_w).floor().clamp(0, bins_w - 1) quantized_y = (y / size_per_bin_h).floor().clamp(0, bins_h - 1)
elif self.mode == 'round': raise NotImplementedError()
else: raise ValueError('Incorrect quantization type.')
quantized_coordinates = torch.cat( (quantized_x, quantized_y), dim=-1 ).int()
return quantized_coordinates
def dequantize(self, coordinates: torch.Tensor, size): bins_w, bins_h = self.bins # Quantization bins. size_w, size_h = size # Original image size. size_per_bin_w = size_w / bins_w size_per_bin_h = size_h / bins_h assert coordinates.shape[-1] == 2, 'coordinates should be shape (N, 2)' x, y = coordinates.split(1, dim=-1) # Shape: 4 * [N, 1].
if self.mode == 'floor': # Add 0.5 to use the center position of the bin as the coordinate. dequantized_x = (x + 0.5) * size_per_bin_w dequantized_y = (y + 0.5) * size_per_bin_h
elif self.mode == 'round': raise NotImplementedError()
else: raise ValueError('Incorrect quantization type.')
dequantized_coordinates = torch.cat( (dequantized_x, dequantized_y), dim=-1 )
return dequantized_coordinates
class Florence2PostProcesser(object): """ Florence-2 post process for converting text prediction to various tasks results.
Args: config: A dict of configs. tokenizer: A tokenizer for decoding text to spans. sample config: UNIFIED_POST_PROCESS: # commom configs NUM_BBOX_HEIGHT_BINS: 1000 NUM_BBOX_WIDTH_BINS: 1000 COORDINATES_HEIGHT_BINS: 1000 COORDINATES_WIDTH_BINS: 1000 # task specific configs, override the common configs PRASE_TASKS: - TASK_NAME: 'video_dense_caption' PATTERN: 'r<time_(\d+)><time_(\d+)>([a-zA-Z0-9 ]+)' SCORE_MODE: 'avg_cat_name_scores' NUM_BINS: 100 - TASK_NAME: 'od' PATTERN: 'r<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>([a-zA-Z0-9 ]+)' SCORE_MODE: 'avg_cat_name_scores'
Returns: parsed_dict (dict): A dict of parsed results. """ def __init__( self, tokenizer=None ): parse_tasks = [] parse_task_configs = {} config = self._create_default_config() for task in config['PARSE_TASKS']: parse_tasks.append(task['TASK_NAME']) parse_task_configs[task['TASK_NAME']] = task
self.config = config self.parse_tasks = parse_tasks self.parse_tasks_configs = parse_task_configs
self.tokenizer = tokenizer if self.tokenizer is not None: self.all_special_tokens = set(self.tokenizer.all_special_tokens)
self.init_quantizers() self.black_list_of_phrase_grounding = self._create_black_list_of_phrase_grounding()
def _create_black_list_of_phrase_grounding(self): black_list = {}
if 'phrase_grounding' in self.parse_tasks and self.parse_tasks_configs['phrase_grounding']['FILTER_BY_BLACK_LIST']: black_list = set( ['it', 'I', 'me', 'mine', 'you', 'your', 'yours', 'he', 'him', 'his', 'she', 'her', 'hers', 'they', 'them', 'their', 'theirs', 'one', 'oneself', 'we', 'us', 'our', 'ours', 'you', 'your', 'yours', 'they', 'them', 'their', 'theirs', 'mine', 'yours', 'his', 'hers', 'its', 'ours', 'yours', 'theirs', 'myself', 'yourself', 'himself', 'herself', 'itself', 'ourselves', 'yourselves', 'themselves', 'this', 'that', 'these', 'those', 'who', 'whom', 'whose', 'which', 'what', 'who', 'whom', 'whose', 'which', 'that', 'all', 'another', 'any', 'anybody', 'anyone', 'anything', 'each', 'everybody', 'everyone', 'everything', 'few', 'many', 'nobody', 'none', 'one', 'several', 'some', 'somebody', 'someone', 'something', 'each other', 'one another', 'myself', 'yourself', 'himself', 'herself', 'itself', 'ourselves', 'yourselves', 'themselves', 'the image', 'image', 'images', 'the', 'a', 'an', 'a group', 'other objects', 'lots', 'a set', ] )
return black_list def _create_default_config(self): config = { 'NUM_BBOX_HEIGHT_BINS': 1000, 'NUM_BBOX_WIDTH_BINS': 1000, 'BOX_QUANTIZATION_MODE': 'floor', 'COORDINATES_HEIGHT_BINS': 1000, 'COORDINATES_WIDTH_BINS': 1000, 'COORDINATES_QUANTIZATION_MODE': 'floor', 'PARSE_TASKS': [ { 'TASK_NAME': 'od', 'PATTERN': r'([a-zA-Z0-9 ]+)<loc_(\\d+)><loc_(\\d+)><loc_(\\d+)><loc_(\\d+)>' }, { 'TASK_NAME': 'ocr', 'PATTERN': r'(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>', 'AREA_THRESHOLD': 0.01 }, { 'TASK_NAME': 'phrase_grounding', 'FILTER_BY_BLACK_LIST': True }, { 'TASK_NAME': 'pure_text', }, { 'TASK_NAME': 'description_with_bboxes', }, { 'TASK_NAME': 'description_with_polygons', }, { 'TASK_NAME': 'polygons', }, { 'TASK_NAME': 'bboxes', }, { 'TASK_NAME': 'description_with_bboxes_or_polygons', } ] }
return config
def init_quantizers(self): # we have box_quantizer (od, grounding) and coordinates_quantizer (ocr, referring_segmentation) num_bbox_height_bins = self.config.get('NUM_BBOX_HEIGHT_BINS', 1000) num_bbox_width_bins = self.config.get('NUM_BBOX_WIDTH_BINS', 1000) box_quantization_mode = self.config.get('BOX_QUANTIZATION_MODE', 'floor') self.box_quantizer = BoxQuantizer( box_quantization_mode, (num_bbox_width_bins, num_bbox_height_bins), ) num_bbox_height_bins = self.config['COORDINATES_HEIGHT_BINS'] if 'COORDINATES_HEIGHT_BINS' in self.config else self.config.get('NUM_BBOX_HEIGHT_BINS', 1000) num_bbox_width_bins = self.config['COORDINATES_WIDTH_BINS'] if 'COORDINATES_WIDTH_BINS' in self.config else self.config.get('NUM_BBOX_WIDTH_BINS', 1000) box_quantization_mode = self.config.get('COORDINATES_QUANTIZATION_MODE') if 'COORDINATES_QUANTIZATION_MODE' in self.config else self.config.get('BOX_QUANTIZATION_MODE', 'floor') self.coordinates_quantizer = CoordinatesQuantizer( box_quantization_mode, (num_bbox_width_bins, num_bbox_height_bins), )
def decode_with_spans(self, tokenizer, token_ids): filtered_tokens = tokenizer.convert_ids_to_tokens( token_ids, skip_special_tokens=False) assert len(filtered_tokens) == len(token_ids)
# To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 sub_texts = [] for token in filtered_tokens: if token in self.all_special_tokens: sub_texts.append(token) else: if isinstance(tokenizer, (BartTokenizer, BartTokenizerFast)): sub_text = tokenizer.convert_tokens_to_string([token]) elif isinstance(tokenizer, (T5Tokenizer, T5TokenizerFast)): # Ref: https://github.com/google/sentencepiece#whitespace-is-treated-as-a-basic-symbol # Note: Do not strip sub_text as it may have functional whitespace sub_text = token.replace('▁', ' ') else: raise ValueError(f'type {type(tokenizer)} not supported') sub_texts.append(sub_text)
text = '' spans = [] for sub_text in sub_texts: span = (len(text), len(text) + len(sub_text)) # [start index, end index). text += sub_text spans.append(span)
# Text format: # 1. T5Tokenizer/T5TokenizerFast: # "<loc_1><loc_2><loc_3><loc_4> transplanting dog<loc_1><loc_2><loc_3><loc_4> cat</s>" # Equivalent to t5_tokenizer.decode(input_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False, spaces_between_special_tokens=False) # 2. BartTokenizer (need to double check): # "<s><loc_1><loc_2><loc_3><loc_4>transplanting dog<loc_1><loc_2><loc_3><loc_4>cat</s>" # Equivalent to bart_tokenizer.decode(input_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False, spaces_between_special_tokens=False) return text, spans
def parse_od_from_text_and_spans( self, text, pattern, image_size, phrase_centric=False ): parsed = list(re.finditer(pattern, text))
instances = [] for i in range(len(parsed)): # Prepare instance. instance = {}
if phrase_centric: bbox_bins = [int(parsed[i].group(j)) for j in range(2, 6)] else: bbox_bins = [int(parsed[i].group(j)) for j in range(1, 5)] instance['bbox'] = self.box_quantizer.dequantize( boxes=torch.tensor(bbox_bins), size=image_size ).tolist()
if phrase_centric: instance['cat_name'] = parsed[i].group(1).lower().strip() else: instance['cat_name'] = parsed[i].group(5).lower().strip() instances.append(instance)
return instances
def parse_ocr_from_text_and_spans(self, text, pattern, image_size, area_threshold=-1.0, ): bboxes = [] labels = [] text = text.replace('<s>', '') # ocr with regions parsed = re.findall(pattern, text) instances = [] image_width, image_height = image_size
for ocr_line in parsed: ocr_content = ocr_line[0] quad_box = ocr_line[1:] quad_box = [int(i) for i in quad_box] quad_box = self.coordinates_quantizer.dequantize( torch.tensor(np.array(quad_box).reshape(-1, 2)), size=image_size ).reshape(-1).tolist()
if area_threshold > 0: x_coords = [i for i in quad_box[0::2]] y_coords = [i for i in quad_box[1::2]]
# apply the Shoelace formula area = 0.5 * abs(sum(x_coords[i] * y_coords[i + 1] - x_coords[i + 1] * y_coords[i] for i in range(4 - 1)))
if area < (image_width * image_height) * area_threshold: continue
bboxes.append(quad_box) labels.append(ocr_content) instances.append({ 'quad_box': quad_box, 'text': ocr_content, }) return instances
def parse_phrase_grounding_from_text_and_spans(self, text, pattern, image_size): # ignore <s> </s> and <pad> cur_span = 0 if text.startswith('<s>'): cur_span += 3
text = text.replace('<s>', '') text = text.replace('</s>', '') text = text.replace('<pad>', '')
pattern = r"([^<]+(?:<loc_\d+>){4,})" phrases = re.findall(pattern, text) # pattern should be text pattern and od pattern pattern = r'^\s*(.*?)(?=<od>|</od>|<box>|</box>|<bbox>|</bbox>|<loc_)' box_pattern = r'<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>'
instances = [] for pharse_text in phrases: phrase_text_strip = pharse_text.replace('<ground>', '', 1) phrase_text_strip = pharse_text.replace('<obj>', '', 1)
if phrase_text_strip == '': cur_span += len(pharse_text) continue
# Prepare instance. instance = {}
# parse phrase, get string phrase = re.search(pattern, phrase_text_strip) if phrase is None: cur_span += len(pharse_text) continue
# parse bboxes by box_pattern bboxes_parsed = list(re.finditer(box_pattern, pharse_text)) if len(bboxes_parsed) == 0: cur_span += len(pharse_text) continue
phrase = phrase.group() # remove leading and trailing spaces phrase = phrase.strip()
if phrase in self.black_list_of_phrase_grounding: cur_span += len(pharse_text) continue
# a list of list bbox_bins = [[int(_bboxes_parsed.group(j)) for j in range(1, 5)] for _bboxes_parsed in bboxes_parsed] instance['bbox'] = self.box_quantizer.dequantize( boxes=torch.tensor(bbox_bins), size=image_size ).tolist()
# exclude non-ascii characters phrase = phrase.encode('ascii',errors='ignore').decode('ascii') instance['cat_name'] = phrase
instances.append(instance)
return instances
def parse_description_with_bboxes_from_text_and_spans(self, text, pattern, image_size, allow_empty_phrase=False): # temporary parse solution, split by '.' # ignore <s> </s> and <pad>
text = text.replace('<s>', '') text = text.replace('</s>', '') text = text.replace('<pad>', '')
if allow_empty_phrase: pattern = rf"(?:(?:<loc_\d+>){{4,}})" else: pattern = r"([^<]+(?:<loc_\d+>){4,})" phrases = re.findall(pattern, text) # pattern should be text pattern and od pattern pattern = r'^\s*(.*?)(?=<od>|</od>|<box>|</box>|<bbox>|</bbox>|<loc_)' box_pattern = r'<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>'
instances = [] for pharse_text in phrases: phrase_text_strip = pharse_text.replace('<ground>', '', 1) phrase_text_strip = pharse_text.replace('<obj>', '', 1)
if phrase_text_strip == '' and not allow_empty_phrase: continue
# parse phrase, get string phrase = re.search(pattern, phrase_text_strip) if phrase is None: continue
phrase = phrase.group() # remove leading and trailing spaces phrase = phrase.strip()
# parse bboxes by box_pattern bboxes_parsed = list(re.finditer(box_pattern, pharse_text)) if len(bboxes_parsed) == 0: continue
# a list of list bbox_bins = [[int(_bboxes_parsed.group(j)) for j in range(1, 5)] for _bboxes_parsed in bboxes_parsed]
bboxes = self.box_quantizer.dequantize( boxes=torch.tensor(bbox_bins), size=image_size ).tolist()
phrase = phrase.encode('ascii',errors='ignore').decode('ascii') for _bboxes in bboxes: # Prepare instance. instance = {} instance['bbox'] = _bboxes # exclude non-ascii characters instance['cat_name'] = phrase instances.append(instance)
return instances
def parse_description_with_polygons_from_text_and_spans(self, text, pattern, image_size, allow_empty_phrase=False, polygon_sep_token='<sep>', polygon_start_token='<poly>', polygon_end_token='</poly>', with_box_at_start=False, ): # ref_seg format: '<expression><x1><y1><x2><y2><><><sep><><><><>' # ignore <s> </s> and <pad>
text = text.replace('<s>', '') text = text.replace('</s>', '') text = text.replace('<pad>', '')
if allow_empty_phrase: pattern = rf"(?:(?:<loc_\d+>|{re.escape(polygon_sep_token)}|{re.escape(polygon_start_token)}|{re.escape(polygon_end_token)}){{4,}})" else: # [^<]+: This part matches one or more characters that are not the < symbol. # The ^ inside the square brackets [] is a negation, meaning it matches anything except <. # pattern = rf"([^<]+(?:<loc_\d+>|{re.escape(polygon_sep_token)}|{re.escape(polygon_start_token)}|{re.escape(polygon_end_token)}){{4,}})" phrases = re.findall(pattern, text)
phrase_string_pattern = r'^\s*(.*?)(?=<od>|</od>|<box>|</box>|<bbox>|</bbox>|<loc_|<poly>)' box_pattern = rf'((?:<loc_\d+>)+)(?:{re.escape(polygon_sep_token)}|$)'
# one polygons instance is separated by polygon_start_token and polygon_end_token polygons_instance_pattern = rf'{re.escape(polygon_start_token)}(.*?){re.escape(polygon_end_token)}' instances = [] for phrase_text in phrases:
# exclude loc_\d+> # need to get span if want to include category score phrase_text_strip = re.sub(r'^loc_\d+>', '', phrase_text, count=1)
# phrase = phrase.replace('<poly>', '') # phrase = phrase.replace('poly>', '')
if phrase_text_strip == '' and not allow_empty_phrase: continue
# parse phrase, get string phrase = re.search(phrase_string_pattern, phrase_text_strip) if phrase is None: continue phrase = phrase.group() # remove leading and trailing spaces phrase = phrase.strip()
# parse bboxes by box_pattern
# split by polygon_start_token and polygon_end_token first using polygons_instance_pattern if polygon_start_token in phrase_text and polygon_end_token in phrase_text: polygons_instances_parsed = list(re.finditer(polygons_instance_pattern, phrase_text)) else: polygons_instances_parsed = [phrase_text]
for _polygons_instances_parsed in polygons_instances_parsed: # Prepare instance. instance = {}
# polygons_parsed= list(re.finditer(box_pattern, phrase_text)) if isinstance(_polygons_instances_parsed, str): polygons_parsed= list(re.finditer(box_pattern, _polygons_instances_parsed)) else: polygons_parsed= list(re.finditer(box_pattern, _polygons_instances_parsed.group(1))) if len(polygons_parsed) == 0: continue
# a list of list (polygon) bbox = [] polygons = [] for _polygon_parsed in polygons_parsed: # group 1: whole <loc_\d+>...</loc_\d+> _polygon = _polygon_parsed.group(1) # parse into list of int _polygon = [int(_loc_parsed.group(1)) for _loc_parsed in re.finditer(r'<loc_(\d+)>', _polygon)] if with_box_at_start and len(bbox) == 0: if len(_polygon) > 4: # no valid bbox prediction bbox = _polygon[:4] _polygon = _polygon[4:] else: bbox = [0, 0, 0, 0] # abandon last element if is not paired if len(_polygon) % 2 == 1: _polygon = _polygon[:-1] # reshape into (n, 2) _polygon = self.coordinates_quantizer.dequantize( torch.tensor(np.array(_polygon).reshape(-1, 2)), size=image_size ).reshape(-1).tolist() # reshape back polygons.append(_polygon)
instance['cat_name'] = phrase instance['polygons'] = polygons if len(bbox) != 0: instance['bbox'] = self.box_quantizer.dequantize( boxes=torch.tensor([bbox]), size=image_size ).tolist()[0]
instances.append(instance)
return instances
def __call__( self, text=None, image_size=None, parse_tasks=None, ): """ Args: text: model outputs image_size: (width, height) parse_tasks: a list of tasks to parse, if None, parse all tasks.
""" if parse_tasks is not None: if isinstance(parse_tasks, str): parse_tasks = [parse_tasks] for _parse_task in parse_tasks: assert _parse_task in self.parse_tasks, f'parse task {_parse_task} not supported' # sequence or text should be provided assert text is not None, 'text should be provided'
parsed_dict = { 'text': text }
for task in self.parse_tasks: if parse_tasks is not None and task not in parse_tasks: continue
pattern = self.parse_tasks_configs[task].get('PATTERN', None)
if task == 'ocr': instances = self.parse_ocr_from_text_and_spans( text, pattern=pattern, image_size=image_size, area_threshold=self.parse_tasks_configs[task].get('AREA_THRESHOLD', 0.01), ) parsed_dict['ocr'] = instances elif task == 'phrase_grounding': instances = self.parse_phrase_grounding_from_text_and_spans( text, pattern=pattern, image_size=image_size, ) parsed_dict['phrase_grounding'] = instances elif task == 'pure_text': parsed_dict['pure_text'] = text elif task == 'description_with_bboxes': instances = self.parse_description_with_bboxes_from_text_and_spans( text, pattern=pattern, image_size=image_size, ) parsed_dict['description_with_bboxes'] = instances elif task == 'description_with_polygons': instances = self.parse_description_with_polygons_from_text_and_spans( text, pattern=pattern, image_size=image_size, ) parsed_dict['description_with_polygons'] = instances elif task == 'polygons': instances = self.parse_description_with_polygons_from_text_and_spans( text, pattern=pattern, image_size=image_size, allow_empty_phrase=True, ) parsed_dict['polygons'] = instances elif task == 'bboxes': instances = self.parse_description_with_bboxes_from_text_and_spans( text, pattern=pattern, image_size=image_size, allow_empty_phrase=True, ) parsed_dict['bboxes'] = instances elif task == 'description_with_bboxes_or_polygons': if '<poly>' in text: # only support either polygons or bboxes, not both at the same time instances = self.parse_description_with_polygons_from_text_and_spans( text, pattern=pattern, image_size=image_size, ) else: instances = self.parse_description_with_bboxes_from_text_and_spans( text, pattern=pattern, image_size=image_size, ) parsed_dict['description_with_bboxes_or_polygons'] = instances else: raise ValueError("task {} is not supported".format(task))
return parsed_dict123456789101112131415161718192021 MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485{ "_name_or_path": "florence2", "architectures": [ "Florence2ForConditionalGeneration" ], "auto_map": { "AutoConfig": "configuration_florence2.Florence2Config", "AutoModelForCausalLM": "modeling_florence2.Florence2ForConditionalGeneration" }, "bos_token_id": 0, "eos_token_id": 2, "ignore_index": -100, "model_type": "florence2", "pad_token_id": 1, "projection_dim": 768, "text_config": { "vocab_size": 51289, "activation_dropout": 0.1, "activation_function": "gelu", "add_bias_logits": false, "add_final_layer_norm": false, "attention_dropout": 0.1, "bos_token_id": 0, "classif_dropout": 0.1, "classifier_dropout": 0.0, "d_model": 768, "decoder_attention_heads": 12, "decoder_ffn_dim": 3072, "decoder_layerdrop": 0.0, "decoder_layers": 6, "decoder_start_token_id": 2, "dropout": 0.1, "early_stopping": true, "encoder_attention_heads": 12, "encoder_ffn_dim": 3072, "encoder_layerdrop": 0.0, "encoder_layers": 6, "eos_token_id": 2, "forced_eos_token_id": 2, "forced_bos_token_id": 0, "gradient_checkpointing": false, "init_std": 0.02, "is_encoder_decoder": true, "label2id": { "LABEL_0": 0, "LABEL_1": 1, "LABEL_2": 2 }, "max_position_embeddings": 1024, "no_repeat_ngram_size": 3, "normalize_before": false, "num_hidden_layers": 6, "pad_token_id": 1, "scale_embedding": false, "num_beams": 3 }, "vision_config": { "model_type": "davit", "drop_path_rate": 0.1, "patch_size": [7, 3, 3, 3], "patch_stride": [4, 2, 2, 2], "patch_padding": [3, 1, 1, 1], "patch_prenorm": [false, true, true, true], "enable_checkpoint": false, "dim_embed": [128, 256, 512, 1024], "num_heads": [4, 8, 16, 32], "num_groups": [4, 8, 16, 32], "depths": [1, 1, 9, 1], "window_size": 12, "projection_dim": 768, "visual_temporal_embedding": { "type": "COSINE", "max_temporal_embeddings": 100 }, "image_pos_embed": { "type": "learned_abs_2d", "max_pos_embeddings": 50 }, "image_feature_source": ["spatial_avg_pool", "temporal_avg_pool"] }, "vocab_size": 51289, "torch_dtype": "float16", "transformers_version": "4.41.0.dev0", "is_encoder_decoder": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340# coding=utf-8# Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.# 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.import warnings""" Florence-2 configuration"""
from typing import Optional
from transformers import AutoConfigfrom transformers.configuration_utils import PretrainedConfigfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class Florence2VisionConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Florence2VisionModel`]. It is used to instantiate a Florence2VisionModel according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Florence2VisionModel architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: drop_path_rate (`float`, *optional*, defaults to 0.1): The dropout rate of the drop path layer. patch_size (`List[int]`, *optional*, defaults to [7, 3, 3, 3]): The patch size of the image. patch_stride (`List[int]`, *optional*, defaults to [4, 2, 2, 2]): The patch stride of the image. patch_padding (`List[int]`, *optional*, defaults to [3, 1, 1, 1]): The patch padding of the image. patch_prenorm (`List[bool]`, *optional*, defaults to [false, true, true, true]): Whether to apply layer normalization before the patch embedding layer. enable_checkpoint (`bool`, *optional*, defaults to False): Whether to enable checkpointing. dim_embed (`List[int]`, *optional*, defaults to [256, 512, 1024, 2048]): The dimension of the embedding layer. num_heads (`List[int]`, *optional*, defaults to [8, 16, 32, 64]): The number of attention heads. num_groups (`List[int]`, *optional*, defaults to [8, 16, 32, 64]): The number of groups. depths (`List[int]`, *optional*, defaults to [1, 1, 9, 1]): The depth of the model. window_size (`int`, *optional*, defaults to 12): The window size of the model. projection_dim (`int`, *optional*, defaults to 1024): The dimension of the projection layer. visual_temporal_embedding (`dict`, *optional*): The configuration of the visual temporal embedding. image_pos_embed (`dict`, *optional*): The configuration of the image position embedding. image_feature_source (`List[str]`, *optional*, defaults to ["spatial_avg_pool", "temporal_avg_pool"]): The source of the image feature. Example:
```python >>> from transformers import Florence2VisionConfig, Florence2VisionModel
>>> # Initializing a Florence2 Vision style configuration >>> configuration = Florence2VisionConfig()
>>> # Initializing a model (with random weights) >>> model = Florence2VisionModel(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "florence2_vision" keys_to_ignore_at_inference = ["past_key_values"]
def __init__( self, drop_path_rate=0.1, patch_size=[7, 3, 3, 3], patch_stride=[4, 2, 2, 2], patch_padding=[3, 1, 1, 1], patch_prenorm=[False, True, True, True], enable_checkpoint=False, dim_embed=[256, 512, 1024, 2048], num_heads=[8, 16, 32, 64], num_groups=[8, 16, 32, 64], depths=[1, 1, 9, 1], window_size=12, projection_dim=1024, visual_temporal_embedding=None, image_pos_embed=None, image_feature_source=["spatial_avg_pool", "temporal_avg_pool"], **kwargs, ): self.drop_path_rate = drop_path_rate self.patch_size = patch_size self.patch_stride = patch_stride self.patch_padding = patch_padding self.patch_prenorm = patch_prenorm self.enable_checkpoint = enable_checkpoint self.dim_embed = dim_embed self.num_heads = num_heads self.num_groups = num_groups self.depths = depths self.window_size = window_size self.projection_dim = projection_dim self.visual_temporal_embedding = visual_temporal_embedding self.image_pos_embed = image_pos_embed self.image_feature_source = image_feature_source
super().__init__(**kwargs)
class Florence2LanguageConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Florence2LanguagePreTrainedModel`]. It is used to instantiate a BART model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the BART [facebook/bart-large](https://huggingface.co/facebook/bart-large) architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: vocab_size (`int`, *optional*, defaults to 51289): Vocabulary size of the Florence2Language model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Florence2LanguageModel`]. d_model (`int`, *optional*, defaults to 1024): Dimensionality of the layers and the pooler layer. encoder_layers (`int`, *optional*, defaults to 12): Number of encoder layers. decoder_layers (`int`, *optional*, defaults to 12): Number of decoder layers. encoder_attention_heads (`int`, *optional*, defaults to 16): Number of attention heads for each attention layer in the Transformer encoder. decoder_attention_heads (`int`, *optional*, defaults to 16): Number of attention heads for each attention layer in the Transformer decoder. decoder_ffn_dim (`int`, *optional*, defaults to 4096): Dimensionality of the "intermediate" (often named feed-forward) layer in decoder. encoder_ffn_dim (`int`, *optional*, defaults to 4096): Dimensionality of the "intermediate" (often named feed-forward) layer in decoder. activation_function (`str` or `function`, *optional*, defaults to `"gelu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported. dropout (`float`, *optional*, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. activation_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for activations inside the fully connected layer. classifier_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for classifier. max_position_embeddings (`int`, *optional*, defaults to 1024): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). init_std (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. encoder_layerdrop (`float`, *optional*, defaults to 0.0): The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more details. decoder_layerdrop (`float`, *optional*, defaults to 0.0): The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more details. scale_embedding (`bool`, *optional*, defaults to `False`): Scale embeddings by diving by sqrt(d_model). use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). num_labels (`int`, *optional*, defaults to 3): The number of labels to use in [`Florence2LanguageForSequenceClassification`]. forced_eos_token_id (`int`, *optional*, defaults to 2): The id of the token to force as the last generated token when `max_length` is reached. Usually set to `eos_token_id`.
Example:
```python >>> from transformers import Florence2LanguageConfig, Florence2LanguageModel
>>> # Initializing a Florence2 Language style configuration >>> configuration = Florence2LanguageConfig()
>>> # Initializing a model (with random weights) >>> model = Florence2LangaugeModel(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "florence2_language" keys_to_ignore_at_inference = ["past_key_values"] attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
def __init__( self, vocab_size=51289, max_position_embeddings=1024, encoder_layers=12, encoder_ffn_dim=4096, encoder_attention_heads=16, decoder_layers=12, decoder_ffn_dim=4096, decoder_attention_heads=16, encoder_layerdrop=0.0, decoder_layerdrop=0.0, activation_function="gelu", d_model=1024, dropout=0.1, attention_dropout=0.0, activation_dropout=0.0, init_std=0.02, classifier_dropout=0.0, scale_embedding=False, use_cache=True, num_labels=3, pad_token_id=1, bos_token_id=0, eos_token_id=2, is_encoder_decoder=True, decoder_start_token_id=2, forced_eos_token_id=2, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.d_model = d_model self.encoder_ffn_dim = encoder_ffn_dim self.encoder_layers = encoder_layers self.encoder_attention_heads = encoder_attention_heads self.decoder_ffn_dim = decoder_ffn_dim self.decoder_layers = decoder_layers self.decoder_attention_heads = decoder_attention_heads self.dropout = dropout self.attention_dropout = attention_dropout self.activation_dropout = activation_dropout self.activation_function = activation_function self.init_std = init_std self.encoder_layerdrop = encoder_layerdrop self.decoder_layerdrop = decoder_layerdrop self.classifier_dropout = classifier_dropout self.use_cache = use_cache self.num_hidden_layers = encoder_layers self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
super().__init__( num_labels=num_labels, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, is_encoder_decoder=is_encoder_decoder, decoder_start_token_id=decoder_start_token_id, forced_eos_token_id=forced_eos_token_id, **kwargs, )
# ensure backward compatibility for BART CNN models if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated", False): self.forced_bos_token_id = self.bos_token_id warnings.warn( f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " "The config can simply be saved and uploaded again to be fixed." )
class Florence2Config(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Florence2ForConditionalGeneration`]. It is used to instantiate an Florence-2 model according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: vision_config (`Florence2VisionConfig`, *optional*): Custom vision config or dict text_config (`Union[AutoConfig, dict]`, *optional*): The config object of the text backbone. ignore_index (`int`, *optional*, defaults to -100): The ignore index for the loss function. vocab_size (`int`, *optional*, defaults to 51289): Vocabulary size of the Florence2model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`~Florence2ForConditionalGeneration`] projection_dim (`int`, *optional*, defaults to 1024): Dimension of the multimodal projection space.
Example:
```python >>> from transformers import Florence2ForConditionalGeneration, Florence2Config, CLIPVisionConfig, BartConfig
>>> # Initializing a clip-like vision config >>> vision_config = CLIPVisionConfig()
>>> # Initializing a Bart config >>> text_config = BartConfig()
>>> # Initializing a Florence-2 configuration >>> configuration = Florence2Config(vision_config, text_config)
>>> # Initializing a model from the florence-2 configuration >>> model = Florence2ForConditionalGeneration(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "florence2" is_composition = False
def __init__( self, vision_config=None, text_config=None, ignore_index=-100, vocab_size=51289, projection_dim=1024, **kwargs, ): self.ignore_index = ignore_index self.vocab_size = vocab_size self.projection_dim = projection_dim if vision_config is not None: vision_config = PretrainedConfig(**vision_config) self.vision_config = vision_config self.vocab_size = self.vocab_size
self.text_config = text_config if text_config is not None: self.text_config = Florence2LanguageConfig(**text_config)
super().__init__(**kwargs)
123456789101112131415161718192021222324252627282930313233343536373839{ "auto_map": { "AutoProcessor": "processing_florence2.Florence2Processor" }, "_valid_processor_keys": [ "images", "do_resize", "size", "resample", "do_rescale", "rescale_factor", "do_normalize", "image_mean", "image_std", "return_tensors", "data_format", "input_data_format", "do_convert_rgb" ], "do_convert_rgb": null, "do_normalize": true, "do_rescale": true, "do_resize": true, "do_center_crop": false, "image_processor_type": "CLIPImageProcessor", "image_seq_length": 577, "image_mean": [0.485, 0.456, 0.406], "image_std": [0.229, 0.224, 0.225], "processor_class": "Florence2Processor", "resample": 3, "size": { "height": 768, "width":768 }, "crop_size": { "height": 768, "width": 768 }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088# coding=utf-8# Copyright 2024 Microsoft and 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."""Processor class for Florence-2."""
import reimport loggingfrom typing import List, Optional, Unionimport numpy as np
import torch
from transformers.feature_extraction_utils import BatchFeaturefrom transformers.image_utils import ImageInput, is_valid_imagefrom transformers.processing_utils import ProcessorMixinfrom transformers.tokenization_utils_base import ( PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy,)from transformers.utils import TensorType
logger = logging.getLogger(__name__)
# Copied from transformers.models.idefics2.processing_idefics2.is_urldef is_url(val) -> bool: return isinstance(val, str) and val.startswith("http")
# Copied from transformers.models.idefics2.processing_idefics2.is_image_or_image_urldef is_image_or_image_url(elem): return is_url(elem) or is_valid_image(elem)
def _is_str_or_image(elem): return isinstance(elem, (str)) or is_image_or_image_url(elem)
class Florence2Processor(ProcessorMixin): r""" Constructs a Florence2 processor which wraps a Florence2 image processor and a Florence2 tokenizer into a single processor.
[`Florence2Processor`] offers all the functionalities of [`CLIPImageProcessor`] and [`BartTokenizerFast`]. See the [`~Florence2Processor.__call__`] and [`~Florence2Processor.decode`] for more information.
Args: image_processor ([`CLIPImageProcessor`], *optional*): The image processor is a required input. tokenizer ([`BartTokenizerFast`], *optional*): The tokenizer is a required input. """
attributes = ["image_processor", "tokenizer"] image_processor_class = "CLIPImageProcessor" tokenizer_class = ("BartTokenizer", "BartTokenizerFast")
def __init__( self, image_processor=None, tokenizer=None, ): if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") if not hasattr(image_processor, "image_seq_length"): raise ValueError("Image processor is missing an `image_seq_length` attribute.")
self.image_seq_length = image_processor.image_seq_length
tokens_to_add = { 'additional_special_tokens': \ tokenizer.additional_special_tokens + \ ['<od>', '</od>', '<ocr>', '</ocr>'] + \ [f'<loc_{x}>' for x in range(1000)] + \ ['<cap>', '</cap>', '<ncap>', '</ncap>','<dcap>', '</dcap>', '<grounding>', '</grounding>', '<seg>', '</seg>', '<sep>', '<region_cap>', '</region_cap>', '<region_to_desciption>', '</region_to_desciption>', '<proposal>', '</proposal>', '<poly>', '</poly>', '<and>'] } tokenizer.add_special_tokens(tokens_to_add)
self.tasks_answer_post_processing_type = { '<OCR>': 'pure_text', '<OCR_WITH_REGION>': 'ocr', '<CAPTION>': 'pure_text', '<DETAILED_CAPTION>': 'pure_text', '<MORE_DETAILED_CAPTION>': 'pure_text', '<OD>': 'description_with_bboxes', '<DENSE_REGION_CAPTION>': 'description_with_bboxes', '<CAPTION_TO_PHRASE_GROUNDING>': "phrase_grounding", '<REFERRING_EXPRESSION_SEGMENTATION>': 'polygons', '<REGION_TO_SEGMENTATION>': 'polygons', '<OPEN_VOCABULARY_DETECTION>': 'description_with_bboxes_or_polygons', '<REGION_TO_CATEGORY>': 'pure_text', '<REGION_TO_DESCRIPTION>': 'pure_text', '<REGION_TO_OCR>': 'pure_text', '<REGION_PROPOSAL>': 'bboxes' }
self.task_prompts_without_inputs = { '<OCR>': 'What is the text in the image?', '<OCR_WITH_REGION>': 'What is the text in the image, with regions?', '<CAPTION>': 'What does the image describe?', '<DETAILED_CAPTION>': 'Describe in detail what is shown in the image.', '<MORE_DETAILED_CAPTION>': 'Describe with a paragraph what is shown in the image.', '<OD>': 'Locate the objects with category name in the image.', '<DENSE_REGION_CAPTION>': 'Locate the objects in the image, with their descriptions.', '<REGION_PROPOSAL>': 'Locate the region proposals in the image.' }
self.task_prompts_with_input = { '<CAPTION_TO_PHRASE_GROUNDING>': "Locate the phrases in the caption: {input}", '<REFERRING_EXPRESSION_SEGMENTATION>': 'Locate {input} in the image with mask', '<REGION_TO_SEGMENTATION>': 'What is the polygon mask of region {input}', '<OPEN_VOCABULARY_DETECTION>': 'Locate {input} in the image.', '<REGION_TO_CATEGORY>': 'What is the region {input}?', '<REGION_TO_DESCRIPTION>': 'What does the region {input} describe?', '<REGION_TO_OCR>': 'What text is in the region {input}?', }
self.post_processor = Florence2PostProcesser(tokenizer=tokenizer)
super().__init__(image_processor, tokenizer) def _construct_prompts(self, text): # replace the task tokens with the task prompts if task token is in the text prompts = [] for _text in text: # 1. fixed task prompts without additional inputs for task_token, task_prompt in self.task_prompts_without_inputs.items(): if task_token in _text: assert _text == task_token, f"Task token {task_token} should be the only token in the text." _text = task_prompt break # 2. task prompts with additional inputs for task_token, task_prompt in self.task_prompts_with_input.items(): if task_token in _text: _text = task_prompt.format(input=_text.replace(task_token, '')) break prompts.append(_text) return prompts
def __call__( self, text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None, images: ImageInput = None, tokenize_newline_separately: bool = True, padding: Union[bool, str, PaddingStrategy] = False, truncation: Union[bool, str, TruncationStrategy] = None, max_length=None, return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH, do_resize: bool = None, do_normalize: bool = None, image_mean: Optional[Union[float, List[float]]] = None, image_std: Optional[Union[float, List[float]]] = None, data_format: Optional["ChannelDimension"] = "channels_first", # noqa: F821 input_data_format: Optional[ Union[str, "ChannelDimension"] # noqa: F821 ] = None, resample: "PILImageResampling" = None, # noqa: F821 do_convert_rgb: bool = None, do_thumbnail: bool = None, do_align_long_axis: bool = None, do_rescale: bool = None, ) -> BatchFeature: """ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text` and `kwargs` arguments to BartTokenizerFast's [`~BartTokenizerFast.__call__`] if `text` is not `None` to encode the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring of the above two methods for more information.
Args: text (`str`, `List[str]`, `List[List[str]]`): The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences). images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`): The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a number of channels, H and W are image height and width. tokenize_newline_separately (`bool`, defaults to `True`): Adds a separately tokenized '\n' at the end of the prompt. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Select a strategy to pad the returned sequences (according to the model's padding side and padding index) among: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). max_length (`int`, *optional*): Maximum length of the returned list and optionally padding length (see above). truncation (`bool`, *optional*): Activates truncation to cut input sequences longer than `max_length` to `max_length`. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are:
- `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. - `'jax'`: Return JAX `jnp.ndarray` objects.
Returns: [`BatchFeature`]: A [`BatchFeature`] with the following fields:
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. If `suffix` is provided, the `input_ids` will also contain the suffix input ids. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not `None`). - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`. - **labels** -- Labels compatible with training if `suffix` is not None """
return_token_type_ids = False
if images is None: raise ValueError("`images` are expected as arguments to a `Florence2Processor` instance.") if text is None: logger.warning_once( "You are using Florence-2 without a text prompt." ) text = ""
if isinstance(text, List) and isinstance(images, List): if len(images) < len(text): raise ValueError( f"Received {len(images)} images for {len(text)} prompts. Each prompt should be associated with an image." ) if _is_str_or_image(text): text = [text] elif isinstance(text, list) and _is_str_or_image(text[0]): pass
pixel_values = self.image_processor( images, do_resize=do_resize, do_normalize=do_normalize, return_tensors=return_tensors, image_mean=image_mean, image_std=image_std, input_data_format=input_data_format, data_format=data_format, resample=resample, do_convert_rgb=do_convert_rgb, )["pixel_values"]
if max_length is not None: max_length -= self.image_seq_length # max_length has to account for the image tokens
text = self._construct_prompts(text)
inputs = self.tokenizer( text, return_tensors=return_tensors, padding=padding, max_length=max_length, truncation=truncation, return_token_type_ids=return_token_type_ids, )
return_data = {**inputs, "pixel_values": pixel_values}
if return_token_type_ids: labels = inputs["input_ids"].masked_fill(inputs["token_type_ids"] == 0, -100) return_data.update({"labels": labels}) return BatchFeature(data=return_data)
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Florence2 def batch_decode(self, *args, **kwargs): """ This method forwards all its arguments to BartTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.batch_decode(*args, **kwargs)
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Florence2 def decode(self, *args, **kwargs): """ This method forwards all its arguments to BartTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.decode(*args, **kwargs)
@property # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names with CLIP->Florence2 def model_input_names(self): tokenizer_input_names = self.tokenizer.model_input_names image_processor_input_names = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
def post_process_generation(self, text, task, image_size): """ Post-process the output of the model to each of the task outputs.
Args: text (`str`): The text to post-process. task (`str`): The task to post-process the text for. image_size (`Tuple[int, int]`): The size of the image. height x width. """
task_answer_post_processing_type = self.tasks_answer_post_processing_type.get(task, 'pure_text') task_answer = self.post_processor( text=text, image_size=image_size, parse_tasks=task_answer_post_processing_type, )[task_answer_post_processing_type]
if task_answer_post_processing_type == 'pure_text': final_answer = task_answer # remove the special tokens final_answer = final_answer.replace('<s>', '').replace('</s>', '') elif task_answer_post_processing_type in ['od', 'description_with_bboxes', 'bboxes']: od_instances = task_answer bboxes_od = [_od_instance['bbox'] for _od_instance in od_instances] labels_od = [str(_od_instance['cat_name']) for _od_instance in od_instances] final_answer = {'bboxes': bboxes_od, 'labels': labels_od} elif task_answer_post_processing_type in ['ocr']: bboxes = [_od_instance['quad_box'] for _od_instance in task_answer] labels = [str(_od_instance['text']) for _od_instance in task_answer] final_answer = {'quad_boxes': bboxes, 'labels': labels} elif task_answer_post_processing_type in ['phrase_grounding']: bboxes = [] labels = [] for _grounded_phrase in task_answer: for _bbox in _grounded_phrase['bbox']: bboxes.append(_bbox) labels.append(_grounded_phrase['cat_name']) final_answer = {'bboxes': bboxes, 'labels': labels} elif task_answer_post_processing_type in ['description_with_polygons', 'polygons']: labels = [] polygons = [] for result in task_answer: label = result['cat_name'] _polygons = result['polygons'] labels.append(label) polygons.append(_polygons) final_answer = {'polygons': polygons, 'labels': labels} elif task_answer_post_processing_type in ['description_with_bboxes_or_polygons']: bboxes = [] bboxes_labels = [] polygons = [] polygons_labels = [] for result in task_answer: label = result['cat_name'] if 'polygons' in result: _polygons = result['polygons'] polygons.append(_polygons) polygons_labels.append(label) else: _bbox = result['bbox'] bboxes.append(_bbox) bboxes_labels.append(label) final_answer = {'bboxes': bboxes, 'bboxes_labels': bboxes_labels, 'polygons': polygons, 'polygons_labels': polygons_labels} else: raise ValueError('Unknown task answer post processing type: {}'.format(task_answer_post_processing_type))
final_answer = { task: final_answer} return final_answer
class BoxQuantizer(object): def __init__(self, mode, bins): self.mode = mode self.bins = bins
def quantize(self, boxes: torch.Tensor, size): bins_w, bins_h = self.bins # Quantization bins. size_w, size_h = size # Original image size. size_per_bin_w = size_w / bins_w size_per_bin_h = size_h / bins_h xmin, ymin, xmax, ymax = boxes.split(1, dim=-1) # Shape: 4 * [N, 1].
if self.mode == 'floor': quantized_xmin = ( xmin / size_per_bin_w).floor().clamp(0, bins_w - 1) quantized_ymin = ( ymin / size_per_bin_h).floor().clamp(0, bins_h - 1) quantized_xmax = ( xmax / size_per_bin_w).floor().clamp(0, bins_w - 1) quantized_ymax = ( ymax / size_per_bin_h).floor().clamp(0, bins_h - 1)
elif self.mode == 'round': raise NotImplementedError()
else: raise ValueError('Incorrect quantization type.')
quantized_boxes = torch.cat( (quantized_xmin, quantized_ymin, quantized_xmax, quantized_ymax), dim=-1 ).int()
return quantized_boxes
def dequantize(self, boxes: torch.Tensor, size): bins_w, bins_h = self.bins # Quantization bins. size_w, size_h = size # Original image size. size_per_bin_w = size_w / bins_w size_per_bin_h = size_h / bins_h xmin, ymin, xmax, ymax = boxes.split(1, dim=-1) # Shape: 4 * [N, 1].
if self.mode == 'floor': # Add 0.5 to use the center position of the bin as the coordinate. dequantized_xmin = (xmin + 0.5) * size_per_bin_w dequantized_ymin = (ymin + 0.5) * size_per_bin_h dequantized_xmax = (xmax + 0.5) * size_per_bin_w dequantized_ymax = (ymax + 0.5) * size_per_bin_h
elif self.mode == 'round': raise NotImplementedError()
else: raise ValueError('Incorrect quantization type.')
dequantized_boxes = torch.cat( (dequantized_xmin, dequantized_ymin, dequantized_xmax, dequantized_ymax), dim=-1 )
return dequantized_boxes
class CoordinatesQuantizer(object): """ Quantize coornidates (Nx2) """
def __init__(self, mode, bins): self.mode = mode self.bins = bins
def quantize(self, coordinates: torch.Tensor, size): bins_w, bins_h = self.bins # Quantization bins. size_w, size_h = size # Original image size. size_per_bin_w = size_w / bins_w size_per_bin_h = size_h / bins_h assert coordinates.shape[-1] == 2, 'coordinates should be shape (N, 2)' x, y = coordinates.split(1, dim=-1) # Shape: 4 * [N, 1].
if self.mode == 'floor': quantized_x = (x / size_per_bin_w).floor().clamp(0, bins_w - 1) quantized_y = (y / size_per_bin_h).floor().clamp(0, bins_h - 1)
elif self.mode == 'round': raise NotImplementedError()
else: raise ValueError('Incorrect quantization type.')
quantized_coordinates = torch.cat( (quantized_x, quantized_y), dim=-1 ).int()
return quantized_coordinates
def dequantize(self, coordinates: torch.Tensor, size): bins_w, bins_h = self.bins # Quantization bins. size_w, size_h = size # Original image size. size_per_bin_w = size_w / bins_w size_per_bin_h = size_h / bins_h assert coordinates.shape[-1] == 2, 'coordinates should be shape (N, 2)' x, y = coordinates.split(1, dim=-1) # Shape: 4 * [N, 1].
if self.mode == 'floor': # Add 0.5 to use the center position of the bin as the coordinate. dequantized_x = (x + 0.5) * size_per_bin_w dequantized_y = (y + 0.5) * size_per_bin_h
elif self.mode == 'round': raise NotImplementedError()
else: raise ValueError('Incorrect quantization type.')
dequantized_coordinates = torch.cat( (dequantized_x, dequantized_y), dim=-1 )
return dequantized_coordinates
class Florence2PostProcesser(object): """ Florence-2 post process for converting text prediction to various tasks results.
Args: config: A dict of configs. tokenizer: A tokenizer for decoding text to spans. sample config: UNIFIED_POST_PROCESS: # commom configs NUM_BBOX_HEIGHT_BINS: 1000 NUM_BBOX_WIDTH_BINS: 1000 COORDINATES_HEIGHT_BINS: 1000 COORDINATES_WIDTH_BINS: 1000 # task specific configs, override the common configs PRASE_TASKS: - TASK_NAME: 'video_dense_caption' PATTERN: 'r<time_(\d+)><time_(\d+)>([a-zA-Z0-9 ]+)' SCORE_MODE: 'avg_cat_name_scores' NUM_BINS: 100 - TASK_NAME: 'od' PATTERN: 'r<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>([a-zA-Z0-9 ]+)' SCORE_MODE: 'avg_cat_name_scores'
Returns: parsed_dict (dict): A dict of parsed results. """ def __init__( self, tokenizer=None ): parse_tasks = [] parse_task_configs = {} config = self._create_default_config() for task in config['PARSE_TASKS']: parse_tasks.append(task['TASK_NAME']) parse_task_configs[task['TASK_NAME']] = task
self.config = config self.parse_tasks = parse_tasks self.parse_tasks_configs = parse_task_configs
self.tokenizer = tokenizer if self.tokenizer is not None: self.all_special_tokens = set(self.tokenizer.all_special_tokens)
self.init_quantizers() self.black_list_of_phrase_grounding = self._create_black_list_of_phrase_grounding()
def _create_black_list_of_phrase_grounding(self): black_list = {}
if 'phrase_grounding' in self.parse_tasks and self.parse_tasks_configs['phrase_grounding']['FILTER_BY_BLACK_LIST']: black_list = set( ['it', 'I', 'me', 'mine', 'you', 'your', 'yours', 'he', 'him', 'his', 'she', 'her', 'hers', 'they', 'them', 'their', 'theirs', 'one', 'oneself', 'we', 'us', 'our', 'ours', 'you', 'your', 'yours', 'they', 'them', 'their', 'theirs', 'mine', 'yours', 'his', 'hers', 'its', 'ours', 'yours', 'theirs', 'myself', 'yourself', 'himself', 'herself', 'itself', 'ourselves', 'yourselves', 'themselves', 'this', 'that', 'these', 'those', 'who', 'whom', 'whose', 'which', 'what', 'who', 'whom', 'whose', 'which', 'that', 'all', 'another', 'any', 'anybody', 'anyone', 'anything', 'each', 'everybody', 'everyone', 'everything', 'few', 'many', 'nobody', 'none', 'one', 'several', 'some', 'somebody', 'someone', 'something', 'each other', 'one another', 'myself', 'yourself', 'himself', 'herself', 'itself', 'ourselves', 'yourselves', 'themselves', 'the image', 'image', 'images', 'the', 'a', 'an', 'a group', 'other objects', 'lots', 'a set', ] )
return black_list def _create_default_config(self): config = { 'NUM_BBOX_HEIGHT_BINS': 1000, 'NUM_BBOX_WIDTH_BINS': 1000, 'BOX_QUANTIZATION_MODE': 'floor', 'COORDINATES_HEIGHT_BINS': 1000, 'COORDINATES_WIDTH_BINS': 1000, 'COORDINATES_QUANTIZATION_MODE': 'floor', 'PARSE_TASKS': [ { 'TASK_NAME': 'od', 'PATTERN': r'([a-zA-Z0-9 ]+)<loc_(\\d+)><loc_(\\d+)><loc_(\\d+)><loc_(\\d+)>' }, { 'TASK_NAME': 'ocr', 'PATTERN': r'(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>', 'AREA_THRESHOLD': 0.00 }, { 'TASK_NAME': 'phrase_grounding', 'FILTER_BY_BLACK_LIST': True }, { 'TASK_NAME': 'pure_text', }, { 'TASK_NAME': 'description_with_bboxes', }, { 'TASK_NAME': 'description_with_polygons', }, { 'TASK_NAME': 'polygons', }, { 'TASK_NAME': 'bboxes', }, { 'TASK_NAME': 'description_with_bboxes_or_polygons', } ] }
return config
def init_quantizers(self): # we have box_quantizer (od, grounding) and coordinates_quantizer (ocr, referring_segmentation) num_bbox_height_bins = self.config.get('NUM_BBOX_HEIGHT_BINS', 1000) num_bbox_width_bins = self.config.get('NUM_BBOX_WIDTH_BINS', 1000) box_quantization_mode = self.config.get('BOX_QUANTIZATION_MODE', 'floor') self.box_quantizer = BoxQuantizer( box_quantization_mode, (num_bbox_width_bins, num_bbox_height_bins), ) num_bbox_height_bins = self.config['COORDINATES_HEIGHT_BINS'] if 'COORDINATES_HEIGHT_BINS' in self.config else self.config.get('NUM_BBOX_HEIGHT_BINS', 1000) num_bbox_width_bins = self.config['COORDINATES_WIDTH_BINS'] if 'COORDINATES_WIDTH_BINS' in self.config else self.config.get('NUM_BBOX_WIDTH_BINS', 1000) box_quantization_mode = self.config.get('COORDINATES_QUANTIZATION_MODE') if 'COORDINATES_QUANTIZATION_MODE' in self.config else self.config.get('BOX_QUANTIZATION_MODE', 'floor') self.coordinates_quantizer = CoordinatesQuantizer( box_quantization_mode, (num_bbox_width_bins, num_bbox_height_bins), )
def decode_with_spans(self, tokenizer, token_ids): filtered_tokens = tokenizer.convert_ids_to_tokens( token_ids, skip_special_tokens=False) assert len(filtered_tokens) == len(token_ids)
# To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 sub_texts = [] for token in filtered_tokens: if token in self.all_special_tokens: sub_texts.append(token) else: if isinstance(tokenizer, (BartTokenizer, BartTokenizerFast)): sub_text = tokenizer.convert_tokens_to_string([token]) elif isinstance(tokenizer, (T5Tokenizer, T5TokenizerFast)): # Ref: https://github.com/google/sentencepiece#whitespace-is-treated-as-a-basic-symbol # Note: Do not strip sub_text as it may have functional whitespace sub_text = token.replace('▁', ' ') else: raise ValueError(f'type {type(tokenizer)} not supported') sub_texts.append(sub_text)
text = '' spans = [] for sub_text in sub_texts: span = (len(text), len(text) + len(sub_text)) # [start index, end index). text += sub_text spans.append(span)
# Text format: # 1. T5Tokenizer/T5TokenizerFast: # "<loc_1><loc_2><loc_3><loc_4> transplanting dog<loc_1><loc_2><loc_3><loc_4> cat</s>" # Equivalent to t5_tokenizer.decode(input_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False, spaces_between_special_tokens=False) # 2. BartTokenizer (need to double check): # "<s><loc_1><loc_2><loc_3><loc_4>transplanting dog<loc_1><loc_2><loc_3><loc_4>cat</s>" # Equivalent to bart_tokenizer.decode(input_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False, spaces_between_special_tokens=False) return text, spans
def parse_od_from_text_and_spans( self, text, pattern, image_size, phrase_centric=False ): parsed = list(re.finditer(pattern, text))
instances = [] for i in range(len(parsed)): # Prepare instance. instance = {}
if phrase_centric: bbox_bins = [int(parsed[i].group(j)) for j in range(2, 6)] else: bbox_bins = [int(parsed[i].group(j)) for j in range(1, 5)] instance['bbox'] = self.box_quantizer.dequantize( boxes=torch.tensor(bbox_bins), size=image_size ).tolist()
if phrase_centric: instance['cat_name'] = parsed[i].group(1).lower().strip() else: instance['cat_name'] = parsed[i].group(5).lower().strip() instances.append(instance)
return instances
def parse_ocr_from_text_and_spans(self, text, pattern, image_size, area_threshold=-1.0, ): bboxes = [] labels = [] text = text.replace('<s>', '') # ocr with regions parsed = re.findall(pattern, text) instances = [] image_width, image_height = image_size
for ocr_line in parsed: ocr_content = ocr_line[0] quad_box = ocr_line[1:] quad_box = [int(i) for i in quad_box] quad_box = self.coordinates_quantizer.dequantize( torch.tensor(np.array(quad_box).reshape(-1, 2)), size=image_size ).reshape(-1).tolist()
if area_threshold > 0: x_coords = [i for i in quad_box[0::2]] y_coords = [i for i in quad_box[1::2]]
# apply the Shoelace formula area = 0.5 * abs(sum(x_coords[i] * y_coords[i + 1] - x_coords[i + 1] * y_coords[i] for i in range(4 - 1)))
if area < (image_width * image_height) * area_threshold: continue
bboxes.append(quad_box) labels.append(ocr_content) instances.append({ 'quad_box': quad_box, 'text': ocr_content, }) return instances
def parse_phrase_grounding_from_text_and_spans(self, text, pattern, image_size): # ignore <s> </s> and <pad> cur_span = 0 if text.startswith('<s>'): cur_span += 3
text = text.replace('<s>', '') text = text.replace('</s>', '') text = text.replace('<pad>', '')
pattern = r"([^<]+(?:<loc_\d+>){4,})" phrases = re.findall(pattern, text) # pattern should be text pattern and od pattern pattern = r'^\s*(.*?)(?=<od>|</od>|<box>|</box>|<bbox>|</bbox>|<loc_)' box_pattern = r'<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>'
instances = [] for pharse_text in phrases: phrase_text_strip = pharse_text.replace('<ground>', '', 1) phrase_text_strip = pharse_text.replace('<obj>', '', 1)
if phrase_text_strip == '': cur_span += len(pharse_text) continue
# Prepare instance. instance = {}
# parse phrase, get string phrase = re.search(pattern, phrase_text_strip) if phrase is None: cur_span += len(pharse_text) continue
# parse bboxes by box_pattern bboxes_parsed = list(re.finditer(box_pattern, pharse_text)) if len(bboxes_parsed) == 0: cur_span += len(pharse_text) continue
phrase = phrase.group() # remove leading and trailing spaces phrase = phrase.strip()
if phrase in self.black_list_of_phrase_grounding: cur_span += len(pharse_text) continue
# a list of list bbox_bins = [[int(_bboxes_parsed.group(j)) for j in range(1, 5)] for _bboxes_parsed in bboxes_parsed] instance['bbox'] = self.box_quantizer.dequantize( boxes=torch.tensor(bbox_bins), size=image_size ).tolist()
# exclude non-ascii characters phrase = phrase.encode('ascii',errors='ignore').decode('ascii') instance['cat_name'] = phrase
instances.append(instance)
return instances
def parse_description_with_bboxes_from_text_and_spans(self, text, pattern, image_size, allow_empty_phrase=False): # temporary parse solution, split by '.' # ignore <s> </s> and <pad>
text = text.replace('<s>', '') text = text.replace('</s>', '') text = text.replace('<pad>', '')
if allow_empty_phrase: pattern = rf"(?:(?:<loc_\d+>){{4,}})" else: pattern = r"([^<]+(?:<loc_\d+>){4,})" phrases = re.findall(pattern, text) # pattern should be text pattern and od pattern pattern = r'^\s*(.*?)(?=<od>|</od>|<box>|</box>|<bbox>|</bbox>|<loc_)' box_pattern = r'<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>'
instances = [] for pharse_text in phrases: phrase_text_strip = pharse_text.replace('<ground>', '', 1) phrase_text_strip = pharse_text.replace('<obj>', '', 1)
if phrase_text_strip == '' and not allow_empty_phrase: continue
# parse phrase, get string phrase = re.search(pattern, phrase_text_strip) if phrase is None: continue
phrase = phrase.group() # remove leading and trailing spaces phrase = phrase.strip()
# parse bboxes by box_pattern bboxes_parsed = list(re.finditer(box_pattern, pharse_text)) if len(bboxes_parsed) == 0: continue
# a list of list bbox_bins = [[int(_bboxes_parsed.group(j)) for j in range(1, 5)] for _bboxes_parsed in bboxes_parsed]
bboxes = self.box_quantizer.dequantize( boxes=torch.tensor(bbox_bins), size=image_size ).tolist()
phrase = phrase.encode('ascii',errors='ignore').decode('ascii') for _bboxes in bboxes: # Prepare instance. instance = {} instance['bbox'] = _bboxes # exclude non-ascii characters instance['cat_name'] = phrase instances.append(instance)
return instances
def parse_description_with_polygons_from_text_and_spans(self, text, pattern, image_size, allow_empty_phrase=False, polygon_sep_token='<sep>', polygon_start_token='<poly>', polygon_end_token='</poly>', with_box_at_start=False, ): # ref_seg format: '<expression><x1><y1><x2><y2><><><sep><><><><>' # ignore <s> </s> and <pad>
text = text.replace('<s>', '') text = text.replace('</s>', '') text = text.replace('<pad>', '')
if allow_empty_phrase: pattern = rf"(?:(?:<loc_\d+>|{re.escape(polygon_sep_token)}|{re.escape(polygon_start_token)}|{re.escape(polygon_end_token)}){{4,}})" else: # [^<]+: This part matches one or more characters that are not the < symbol. # The ^ inside the square brackets [] is a negation, meaning it matches anything except <. # pattern = rf"([^<]+(?:<loc_\d+>|{re.escape(polygon_sep_token)}|{re.escape(polygon_start_token)}|{re.escape(polygon_end_token)}){{4,}})" phrases = re.findall(pattern, text)
phrase_string_pattern = r'^\s*(.*?)(?=<od>|</od>|<box>|</box>|<bbox>|</bbox>|<loc_|<poly>)' box_pattern = rf'((?:<loc_\d+>)+)(?:{re.escape(polygon_sep_token)}|$)'
# one polygons instance is separated by polygon_start_token and polygon_end_token polygons_instance_pattern = rf'{re.escape(polygon_start_token)}(.*?){re.escape(polygon_end_token)}' instances = [] for phrase_text in phrases:
# exclude loc_\d+> # need to get span if want to include category score phrase_text_strip = re.sub(r'^loc_\d+>', '', phrase_text, count=1)
# phrase = phrase.replace('<poly>', '') # phrase = phrase.replace('poly>', '')
if phrase_text_strip == '' and not allow_empty_phrase: continue
# parse phrase, get string phrase = re.search(phrase_string_pattern, phrase_text_strip) if phrase is None: continue phrase = phrase.group() # remove leading and trailing spaces phrase = phrase.strip()
# parse bboxes by box_pattern
# split by polygon_start_token and polygon_end_token first using polygons_instance_pattern if polygon_start_token in phrase_text and polygon_end_token in phrase_text: polygons_instances_parsed = list(re.finditer(polygons_instance_pattern, phrase_text)) else: polygons_instances_parsed = [phrase_text]
for _polygons_instances_parsed in polygons_instances_parsed: # Prepare instance. instance = {}
# polygons_parsed= list(re.finditer(box_pattern, phrase_text)) if isinstance(_polygons_instances_parsed, str): polygons_parsed= list(re.finditer(box_pattern, _polygons_instances_parsed)) else: polygons_parsed= list(re.finditer(box_pattern, _polygons_instances_parsed.group(1))) if len(polygons_parsed) == 0: continue
# a list of list (polygon) bbox = [] polygons = [] for _polygon_parsed in polygons_parsed: # group 1: whole <loc_\d+>...</loc_\d+> _polygon = _polygon_parsed.group(1) # parse into list of int _polygon = [int(_loc_parsed.group(1)) for _loc_parsed in re.finditer(r'<loc_(\d+)>', _polygon)] if with_box_at_start and len(bbox) == 0: if len(_polygon) > 4: # no valid bbox prediction bbox = _polygon[:4] _polygon = _polygon[4:] else: bbox = [0, 0, 0, 0] # abandon last element if is not paired if len(_polygon) % 2 == 1: _polygon = _polygon[:-1] # reshape into (n, 2) _polygon = self.coordinates_quantizer.dequantize( torch.tensor(np.array(_polygon).reshape(-1, 2)), size=image_size ).reshape(-1).tolist() # reshape back polygons.append(_polygon)
instance['cat_name'] = phrase instance['polygons'] = polygons if len(bbox) != 0: instance['bbox'] = self.box_quantizer.dequantize( boxes=torch.tensor([bbox]), size=image_size ).tolist()[0]
instances.append(instance)
return instances
def __call__( self, text=None, image_size=None, parse_tasks=None, ): """ Args: text: model outputs image_size: (width, height) parse_tasks: a list of tasks to parse, if None, parse all tasks.
""" if parse_tasks is not None: if isinstance(parse_tasks, str): parse_tasks = [parse_tasks] for _parse_task in parse_tasks: assert _parse_task in self.parse_tasks, f'parse task {_parse_task} not supported' # sequence or text should be provided assert text is not None, 'text should be provided'
parsed_dict = { 'text': text }
for task in self.parse_tasks: if parse_tasks is not None and task not in parse_tasks: continue
pattern = self.parse_tasks_configs[task].get('PATTERN', None)
if task == 'ocr': instances = self.parse_ocr_from_text_and_spans( text, pattern=pattern, image_size=image_size, area_threshold=self.parse_tasks_configs[task].get('AREA_THRESHOLD', 0.0), ) parsed_dict['ocr'] = instances elif task == 'phrase_grounding': instances = self.parse_phrase_grounding_from_text_and_spans( text, pattern=pattern, image_size=image_size, ) parsed_dict['phrase_grounding'] = instances elif task == 'pure_text': parsed_dict['pure_text'] = text elif task == 'description_with_bboxes': instances = self.parse_description_with_bboxes_from_text_and_spans( text, pattern=pattern, image_size=image_size, ) parsed_dict['description_with_bboxes'] = instances elif task == 'description_with_polygons': instances = self.parse_description_with_polygons_from_text_and_spans( text, pattern=pattern, image_size=image_size, ) parsed_dict['description_with_polygons'] = instances elif task == 'polygons': instances = self.parse_description_with_polygons_from_text_and_spans( text, pattern=pattern, image_size=image_size, allow_empty_phrase=True, ) parsed_dict['polygons'] = instances elif task == 'bboxes': instances = self.parse_description_with_bboxes_from_text_and_spans( text, pattern=pattern, image_size=image_size, allow_empty_phrase=True, ) parsed_dict['bboxes'] = instances elif task == 'description_with_bboxes_or_polygons': if '<poly>' in text: # only support either polygons or bboxes, not both at the same time instances = self.parse_description_with_polygons_from_text_and_spans( text, pattern=pattern, image_size=image_size, ) else: instances = self.parse_description_with_bboxes_from_text_and_spans( text, pattern=pattern, image_size=image_size, ) parsed_dict['description_with_bboxes_or_polygons'] = instances else: raise ValueError("task {} is not supported".format(task))
return parsed_dict1234{ "model_max_length": 1024}
123version https://git-lfs.github.com/spec/v1oid sha256:4188ce5a9364c358c3e28eb3e4155985867ef70bb3ae628f1f289d6a3538310asize 1543106435123version https://git-lfs.github.com/spec/v1oid sha256:677ad8860204f7d0bfba12d29e6c31ded9beefdf3e4bbd102518357d31a292c1size 847517512123version https://git-lfs.github.com/spec/v1oid sha256:3f5062b8400c94b7159665b21ba5c62acdcd7682262743d7f2aefedef00e6581size 847517512123version https://git-lfs.github.com/spec/v1oid sha256:ebf05d918348aec7abb02a5e9ecef77e0aaea6914a5c4ea13f50d45eb1681831size 698391064123version https://git-lfs.github.com/spec/v1oid sha256:e92dc36cc273bac3200b2e41807ebdc174076185d95a45238558d4c236b6da74size 847517960123version https://git-lfs.github.com/spec/v1oid sha256:5cdb6a00be1b12579745b5bed0c7b83f0869073d8a864fa8cd50a9356601919asize 1405172056123version https://git-lfs.github.com/spec/v1oid sha256:c4670b3ce5e1fa557b6f96daf3a077666765f8728e34e31f7cc626ba92ec6999size 153265768123version https://git-lfs.github.com/spec/v1oid sha256:d7b101a5ab6b7bda20cd8242ddfebf989535864cf34ffb437d739a00fd710a21size 612764760123version https://git-lfs.github.com/spec/v1oid sha256:6a1bd9e7614f7b97be3f2efd09c9f789b89ce63cf33c6825d3b3db7ae6ee503asize 57554040123version https://git-lfs.github.com/spec/v1oid sha256:3c2b5db3e0a47dc3fe95588100c9a470d0f9777178a6c8bcd6e81e3aa63463cdsize 171969428123version https://git-lfs.github.com/spec/v1oid sha256:b862b3edd880ab3671fd938cb934adfd80e75fd51391b94f721d764ec4c521cesize 19257040123version https://git-lfs.github.com/spec/v1oid sha256:dbfe12b51348772421be6f6b4d622508bb127b3720e24f187f84207b94b9d4absize 57588504123version https://git-lfs.github.com/spec/v1oid sha256:4551c87aa0bdc2400137fb70d60197dc455edce3ce00281514c18961507d2a29size 19599648123version https://git-lfs.github.com/spec/v1oid sha256:dc910b0e7caf58f9ea9d67a6213abb39b9e89c760747a0e2a48c04fc188d3c4fsize 19303584123version https://git-lfs.github.com/spec/v1oid sha256:692a3bc87fb830fcbf5f8b632ea11135635f66b71b76346b15079df2f08656e4size 612742496123version https://git-lfs.github.com/spec/v1oid sha256:ef52f03436a8b5e6d482b41c1d4ed28754fe4cec047d0d8ea58a325326ff4259size 306587024123version https://git-lfs.github.com/spec/v1oid sha256:b62f1e76dc7fce6081a840cd6537d3a5a2ce7179ade87d28a4adba276da5af5dsize 19269160123version https://git-lfs.github.com/spec/v1oid sha256:6ca062af78823e1ae01bcbbb3c18188645b245368247ac119d38894bdfda144csize 19314032123version https://git-lfs.github.com/spec/v1oid sha256:ef84fb37c5ba95183d77bea8d786c8b2c9a7adea6783b5590f0e1ce13f746de5size 306423864123version https://git-lfs.github.com/spec/v1oid sha256:81162bf6dfbb86a7a3dfa8186506d47e372b78cd59ee940571e7b22182071f43size 38441696123version https://git-lfs.github.com/spec/v1oid sha256:b6673370ffca6b31d4e784be8bcd715b449653ee108fa0a9317fb3642f007eb8size 19258944123version https://git-lfs.github.com/spec/v1oid sha256:58f32c0d528884720a554c01e3ff873779be4c4f49ba446fb2216775a1b45ee4size 19584360123version https://git-lfs.github.com/spec/v1oid sha256:a01432b6105b73d67c50d2d031fb2c34405e10d46776b0424369a10deed8782esize 79385656123version https://git-lfs.github.com/spec/v1oid sha256:5bd48e61bd50b3f3295df044fe316f8b761020042c4629979aa0538752a8bfabsize 39770448123version https://git-lfs.github.com/spec/v1oid sha256:fd6d1c1c0d994d9a94207d830ab1f81a3320d7cf51e29a744d14464f44056bbesize 171969414123version https://git-lfs.github.com/spec/v1oid sha256:2bb7dd6b07e7096fab8f9366e421ee63df6f83a66c4364950211d91d541ec025size 171969352123version https://git-lfs.github.com/spec/v1oid sha256:9e13351d7b19ef2591c4af6e3994deb89f32ee15246af99ec4ca18cb53c74f9fsize 171969394123version https://git-lfs.github.com/spec/v1oid sha256:ab39904df33d0ca22ec9be6335759db83e0d159c8fe2b869144e93508aaa3adbsize 19352488123version https://git-lfs.github.com/spec/v1oid sha256:f15a0d31047672e3442609468dafc3ebe133ab8eebfb3d6842ee1be2f1cc4dd7size 153307528123version https://git-lfs.github.com/spec/v1oid sha256:b618d1217e6ea0a589c5ac43bd2470f205c9dc954ef6d69471ddb4a7e7e4804dsize 86049797123version https://git-lfs.github.com/spec/v1oid sha256:bbaee4463eda76bfb82f571392471c462e3a78171161b59441f505ef3f95a477size 343805464123version https://git-lfs.github.com/spec/v1oid sha256:154feddcdb0f002d64ed208d313bac6984b12b612ca887aa35a2d1092cd1b15csize 171969427123version https://git-lfs.github.com/spec/v1oid sha256:3faab24912768f286c8038f522ca96b21b488181fb7a465593811cc13f0c9334size 153286040123version https://git-lfs.github.com/spec/v1oid sha256:9a51336bca7c6cf85a611209c4b01977a55c2add16ec4d0de2d3d7a2e00aa0fdsize 89746016123version https://git-lfs.github.com/spec/v1oid sha256:648977afffdd30f719931fdb30813d9578fe6a6f74f77b0cd57c4fd554d983f1size 343805456123version https://git-lfs.github.com/spec/v1oid sha256:6f366031c91ba99b0781d8895e95c01b62f2216c27f6209852255ccde1b88205size 612748624123version https://git-lfs.github.com/spec/v1oid sha256:a9ab8e7269637b6b0faabe40ad8a65a29bfd48b01e0b8ff910135954f1cdb207size 612763024123version https://git-lfs.github.com/spec/v1oid sha256:a72b237a50c292d7d6c84212be0106450f40a6fcaa77bfe38f8c19c9724f5fc1size 306447104RMBG/body_segment/deeplabv3p-resnet50-human.onnxAdded+3
florence2/DocVQA/configuration_florence2.pyAdded+340
florence2/DocVQA/processing_florence2.pyAdded+1088
florence2/base-ft/LICENSEAdded+21
florence2/base-ft/config.jsonAdded+85
florence2/base-ft/configuration_florence2.pyAdded+340
florence2/base-ft/modeling_florence2.pyAdded
florence2/base-ft/preprocessor_config.jsonAdded+39
florence2/base-ft/processing_florence2.pyAdded+1088
florence2/base-ft/tokenizer.jsonAdded
florence2/base-ft/tokenizer_config.jsonAdded+4
florence2/base-ft/vocab.jsonAdded
florence2/large-ft/pytorch_model.binAdded+3
ipadapter/ip-adapter-plus-face_sdxl_vit-h.safetensorsAdded+3
ipadapter/ip-adapter-plus_sdxl_vit-h.safetensorsAdded+3
ipadapter/ip-adapter_sdxl_vit-h.safetensorsAdded+3
ipadapter/ip_plus_composition_sdxl.safetensorsAdded+3
ipadapter/noobIPAMARK1_mark1.safetensorsAdded+3
loras/flux/20 (1).safetensorsAdded+3
loras/flux/3D玩具手办盲盒_FLUX-V1.safetensorsAdded+3
loras/flux/5yocrayon1_cap_d6a3e12.safetensorsAdded+3
loras/flux/Bacun_style_Flux_Test_000003000.safetensorsAdded+3
loras/flux/Belly_Stuffed-000003.safetensorsAdded+3
loras/flux/Dakimakura_Body_Pillow_Designer_FLUX-000021.safetensorsAdded+3
loras/flux/DigitalMatte_FLUX.safetensorsAdded+3
loras/flux/Dollification_-_inflatable_sex_doll_transformation_rubber_skin_sdol_-_flux.safetensorsAdded+3
loras/flux/FLUX|Y2K girl manga style-Cassiopeia_TypeB V1.2.0.safetensorsAdded+3
loras/flux/Flux_penis.safetensorsAdded+3
loras/flux/Illumination_Style_Flux.safetensorsAdded+3
loras/flux/LOL_Emotes_HD_-_FLUX_dev.safetensorsAdded+3
loras/flux/MLKBC 微观世界-盲盒手办_V1.safetensorsAdded+3
loras/flux/OB乐高人物V1.0.safetensorsAdded+3
loras/flux/Simpsons_Style_-_FLUX.safetensorsAdded+3
loras/flux/VectorCharm_Flux.safetensorsAdded+3
loras/flux/Yogisya_FLUX.safetensorsAdded+3
loras/flux/arcane-style-2.safetensorsAdded+3
loras/flux/archerstyle_v1_000002800.safetensorsAdded+3
loras/flux/cartoon_saloon_flux_000007000.safetensorsAdded+3
loras/flux/flux-lora-vintage-tarot.safetensorsAdded+3
loras/flux/hugeboobs.safetensorsAdded+3
loras/flux/j_dsstyle_flux.safetensorsAdded+3
loras/flux/jet_set_radio_flux_000002800.safetensorsAdded+3
loras/flux/labubu jastu.safetensorsAdded+3
loras/flux/lowerdecks_style_v1.0.safetensorsAdded+3
loras/flux/paipai.safetensorsAdded+3
loras/flux/removal_timestep_alpha-2-1740.safetensorsAdded+3
loras/flux/torikun_flux_lora_000003000.safetensorsAdded+3
loras/flux/users_LORA_639195226744978302_32f14df2-e590-4d28-b20f-140d2ec39970.TA_trained.safetensorsAdded+3
loras/flux/users_LORA_766170570185454547_1ff18e01-e4ab-40fa-8211-4f7b325fd7b3.by_tusi.safetensorsAdded+3
loras/flux/users_LORA_766170570185454547_fbdd160e-01f5-4f6e-90b5-a73870ecf720.by_tusi.safetensorsAdded+3