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)
- BiRefNet/README.mdAdded+8
- BiRefNet/RMBG-2.0/BiRefNet_config.pyAdded+11
- BiRefNet/RMBG-2.0/birefnet.pyAdded+2244
- BiRefNet/RMBG-2.0/config.jsonAdded+21
- BiRefNet/RMBG-2.0/diagram1.pngAdded
- BiRefNet/RMBG-2.0/preprocessor_config.jsonAdded+23
- Joy_caption/README.mdAdded+79
- Joy_caption/app.pyAdded+536
- Joy_caption/cgrkzexw-599808/config.yamlAdded+39
- Joy_caption/cgrkzexw-599808/text_model/README.mdAdded+202
- Joy_caption/cgrkzexw-599808/text_model/adapter_config.jsonAdded+34
- Joy_caption/cgrkzexw-599808/text_model/tokenizer.jsonAdded
- Joy_caption/joycaption_alpha_two_cli_mod.ipynbAdded+46
- Joy_caption/requirements.txtAdded+10
- LLM/Florence-2-base-PromptGen-v2.0/configuration_florence2.pyAdded+340
- LLM/Florence-2-base-PromptGen-v2.0/generation_config.jsonAdded+13
- LLM/Florence-2-base-PromptGen-v2.0/merges.txtAdded
- LLM/Florence-2-base-PromptGen-v2.0/processing_florence2.pyAdded+1088
- LLM/Florence-2-large-PromptGen-v2.0/README.mdAdded+71
- LLM/Florence-2-large-PromptGen-v2.0/added_tokens.jsonAdded+1026
- LLM/Florence-2-large-PromptGen-v2.0/config.jsonAdded+138
- LLM/Florence-2-large-PromptGen-v2.0/configuration_florence2.pyAdded+340
- LLM/Florence-2-large-PromptGen-v2.0/generation_config.jsonAdded+4
- LLM/Florence-2-large-PromptGen-v2.0/merges.txtAdded
- LLM/Florence-2-large-PromptGen-v2.0/modeling_florence2.pyAdded
- LLM/Florence-2-large-PromptGen-v2.0/preprocessor_config.jsonAdded+33
- LLM/Florence-2-large-PromptGen-v2.0/processing_florence2.pyAdded+1088
- LLM/Florence-2-large-PromptGen-v2.0/special_tokens_map.jsonAdded
- LLM/Florence-2-large-PromptGen-v2.0/tokenizer.jsonAdded
- LLM/Florence-2-large-PromptGen-v2.0/tokenizer_config.jsonAdded
- LLM/Florence-2-large-PromptGen-v2.0/vocab.jsonAdded
- LLM/Llama-3.1-8B-Lexi-Uncensored-V2/README.mdAdded+155
- LLM/Llama-3.1-8B-Lexi-Uncensored-V2/config.jsonAdded+41
- LLM/Llama-3.1-8B-Lexi-Uncensored-V2/generation_config.jsonAdded+14
- LLM/Llama-3.1-8B-Lexi-Uncensored-V2/model.safetensors.index.jsonAdded+298
- LLM/Llama-3.1-8B-Lexi-Uncensored-V2/special_tokens_map.jsonAdded+23
- LLM/Llama-3.1-8B-Lexi-Uncensored-V2/tokenizer.jsonAdded
- LLM/Llama-3.1-8B-Lexi-Uncensored-V2/tokenizer_config.jsonAdded+2064
- clip/siglip-so400m-patch14-384/README.mdAdded+112
- clip/siglip-so400m-patch14-384/config.jsonAdded+25
- clip/siglip-so400m-patch14-384/preprocessor_config.jsonAdded+23
- clip/siglip-so400m-patch14-384/special_tokens_map.jsonAdded+23
- clip/siglip-so400m-patch14-384/tokenizer.jsonAdded
- clip/siglip-so400m-patch14-384/tokenizer_config.jsonAdded+33
- clip_interrogator/models--timm--vit_large_patch14_clip_224.openai/refs/mainAdded+1
- controlnet/FLUX.1/FLUX.1-dev-ControlNet-Union-Pro-2.0/README.mdAdded+154
- controlnet/FLUX.1/FLUX.1-dev-ControlNet-Union-Pro-2.0/conds/canny.pngAdded
- controlnet/FLUX.1/FLUX.1-dev-ControlNet-Union-Pro-2.0/config.jsonAdded+19
- controlnet/FLUX.1/FLUX.1-dev-ControlNet-Union-Pro-2.0/controlnet_flux.pyAdded+509
- controlnet/FLUX.1/FLUX.1-dev-ControlNet-Union-Pro-2.0/pipeline_flux_controlnet.pyAdded+1181
12345678
---license: mit---
This is used to store the checkpoints of BiRefNet, please refer the following repo link1. Official implement https://github.com/zhengpeng7/birefnet2. ComfyUI BiRefNet node https://github.com/viperyl/ComfyUI-BiRefNet1234567891011from transformers import PretrainedConfig
class BiRefNetConfig(PretrainedConfig): model_type = "SegformerForSemanticSegmentation" def __init__( self, bb_pretrained=False, **kwargs ): self.bb_pretrained = bb_pretrained super().__init__(**kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244### config.py
import osimport mathfrom transformers import PretrainedConfig
class Config(PretrainedConfig): def __init__(self) -> None: # PATH settings self.sys_home_dir = os.path.expanduser('~') # Make up your file system as: SYS_HOME_DIR/codes/dis/BiRefNet, SYS_HOME_DIR/datasets/dis/xx, SYS_HOME_DIR/weights/xx
# TASK settings self.task = ['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'][0] self.training_set = { 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0], 'COD': 'TR-COD10K+TR-CAMO', 'HRSOD': ['TR-DUTS', 'TR-HRSOD', 'TR-UHRSD', 'TR-DUTS+TR-HRSOD', 'TR-DUTS+TR-UHRSD', 'TR-HRSOD+TR-UHRSD', 'TR-DUTS+TR-HRSOD+TR-UHRSD'][5], 'DIS5K+HRSOD+HRS10K': 'DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4+DIS-TR+TE-HRS10K+TE-HRSOD+TE-UHRSD+TR-HRS10K+TR-HRSOD+TR-UHRSD', # leave DIS-VD for evaluation. 'P3M-10k': 'TR-P3M-10k', }[self.task] self.prompt4loc = ['dense', 'sparse'][0]
# Faster-Training settings self.load_all = True self.compile = True # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch. # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting. # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607. # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training. self.precisionHigh = True
# MODEL settings self.ms_supervision = True self.out_ref = self.ms_supervision and True self.dec_ipt = True self.dec_ipt_split = True self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder self.mul_scl_ipt = ['', 'add', 'cat'][2] self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2] self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1] self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0]
# TRAINING settings self.batch_size = 4 self.IoU_finetune_last_epochs = [ 0, { 'DIS5K': -50, 'COD': -20, 'HRSOD': -20, 'DIS5K+HRSOD+HRS10K': -20, 'P3M-10k': -20, }[self.task] ][1] # choose 0 to skip self.lr = (1e-4 if 'DIS5K' in self.task else 1e-5) * math.sqrt(self.batch_size / 4) # DIS needs high lr to converge faster. Adapt the lr linearly self.size = 1024 self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader
# Backbone settings self.bb = [ 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2 'swin_v1_t', 'swin_v1_s', # 3, 4 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs4 'pvt_v2_b0', 'pvt_v2_b1', # 7, 8 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5 ][6] self.lateral_channels_in_collection = { 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96], 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64], }[self.bb] if self.mul_scl_ipt == 'cat': self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection] self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []
# MODEL settings - inactive self.lat_blk = ['BasicLatBlk'][0] self.dec_channels_inter = ['fixed', 'adap'][0] self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0] self.progressive_ref = self.refine and True self.ender = self.progressive_ref and False self.scale = self.progressive_ref and 2 self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`. self.refine_iteration = 1 self.freeze_bb = False self.model = [ 'BiRefNet', ][0] if self.dec_blk == 'HierarAttDecBlk': self.batch_size = 2 ** [0, 1, 2, 3, 4][2]
# TRAINING settings - inactive self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4] self.optimizer = ['Adam', 'AdamW'][1] self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch. self.lr_decay_rate = 0.5 # Loss self.lambdas_pix_last = { # not 0 means opening this loss # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30 'bce': 30 * 1, # high performance 'iou': 0.5 * 1, # 0 / 255 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64) 'mse': 150 * 0, # can smooth the saliency map 'triplet': 3 * 0, 'reg': 100 * 0, 'ssim': 10 * 1, # help contours, 'cnt': 5 * 0, # help contours 'structure': 5 * 0, # structure loss from codes of MVANet. A little improvement on DIS-TE[1,2,3], a bit more decrease on DIS-TE4. } self.lambdas_cls = { 'ce': 5.0 } # Adv self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training self.lambda_adv_d = 3. * (self.lambda_adv_g > 0)
# PATH settings - inactive self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis') self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights') self.weights = { 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'), 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]), 'swin_v1_b': os.path.join(self.weights_root_dir, ['swin_base_patch4_window12_384_22kto1k.pth', 'swin_base_patch4_window12_384_22k.pth'][0]), 'swin_v1_l': os.path.join(self.weights_root_dir, ['swin_large_patch4_window12_384_22kto1k.pth', 'swin_large_patch4_window12_384_22k.pth'][0]), 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]), 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]), 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]), 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]), }
# Callbacks - inactive self.verbose_eval = True self.only_S_MAE = False self.use_fp16 = False # Bugs. It may cause nan in training. self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs
# others self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')
self.batch_size_valid = 1 self.rand_seed = 7 # run_sh_file = [f for f in os.listdir('.') if 'train.sh' == f] + [os.path.join('..', f) for f in os.listdir('..') if 'train.sh' == f] # with open(run_sh_file[0], 'r') as f: # lines = f.readlines() # self.save_last = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'val_last=' in l][0].split('val_last=')[-1].split()[0]) # self.save_step = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'step=' in l][0].split('step=')[-1].split()[0]) # self.val_step = [0, self.save_step][0]
def print_task(self) -> None: # Return task for choosing settings in shell scripts. print(self.task)
### models/backbones/pvt_v2.py
import torchimport torch.nn as nnfrom functools import partial
from timm.models.layers import DropPath, to_2tuple, trunc_normal_from timm.models.registry import register_model
import math
# from config import Config
# config = Config()
class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.dwconv = DWConv(hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop)
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def forward(self, x, H, W): x = self.fc1(x) x = self.dwconv(x, H, W) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x
class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1): super().__init__() assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
self.dim = dim self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5
self.q = nn.Linear(dim, dim, bias=qkv_bias) self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias) self.attn_drop_prob = attn_drop self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop)
self.sr_ratio = sr_ratio if sr_ratio > 1: self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio) self.norm = nn.LayerNorm(dim)
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def forward(self, x, H, W): B, N, C = x.shape q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
if self.sr_ratio > 1: x_ = x.permute(0, 2, 1).reshape(B, C, H, W) x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1) x_ = self.norm(x_) kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) else: kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) k, v = kv[0], kv[1]
if config.SDPA_enabled: x = torch.nn.functional.scaled_dot_product_attention( q, k, v, attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False ).transpose(1, 2).reshape(B, N, C) else: attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x)
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio) # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def forward(self, x, H, W): x = x + self.drop_path(self.attn(self.norm1(x), H, W)) x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
return x
class OverlapPatchEmbed(nn.Module): """ Image to Patch Embedding """
def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size)
self.img_size = img_size self.patch_size = patch_size self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1] self.num_patches = self.H * self.W self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride, padding=(patch_size[0] // 2, patch_size[1] // 2)) self.norm = nn.LayerNorm(embed_dim)
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def forward(self, x): x = self.proj(x) _, _, H, W = x.shape x = x.flatten(2).transpose(1, 2) x = self.norm(x)
return x, H, W
class PyramidVisionTransformerImpr(nn.Module): def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512], num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm, depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]): super().__init__() self.num_classes = num_classes self.depths = depths
# patch_embed self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels, embed_dim=embed_dims[0]) self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0], embed_dim=embed_dims[1]) self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1], embed_dim=embed_dims[2]) self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2], embed_dim=embed_dims[3])
# transformer encoder dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule cur = 0 self.block1 = nn.ModuleList([Block( dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[0]) for i in range(depths[0])]) self.norm1 = norm_layer(embed_dims[0])
cur += depths[0] self.block2 = nn.ModuleList([Block( dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[1]) for i in range(depths[1])]) self.norm2 = norm_layer(embed_dims[1])
cur += depths[1] self.block3 = nn.ModuleList([Block( dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[2]) for i in range(depths[2])]) self.norm3 = norm_layer(embed_dims[2])
cur += depths[2] self.block4 = nn.ModuleList([Block( dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[3]) for i in range(depths[3])]) self.norm4 = norm_layer(embed_dims[3])
# classification head # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def init_weights(self, pretrained=None): if isinstance(pretrained, str): logger = 1 #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
def reset_drop_path(self, drop_path_rate): dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))] cur = 0 for i in range(self.depths[0]): self.block1[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[0] for i in range(self.depths[1]): self.block2[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[1] for i in range(self.depths[2]): self.block3[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[2] for i in range(self.depths[3]): self.block4[i].drop_path.drop_prob = dpr[cur + i]
def freeze_patch_emb(self): self.patch_embed1.requires_grad = False
@torch.jit.ignore def no_weight_decay(self): return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
def get_classifier(self): return self.head
def reset_classifier(self, num_classes, global_pool=''): self.num_classes = num_classes self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
def forward_features(self, x): B = x.shape[0] outs = []
# stage 1 x, H, W = self.patch_embed1(x) for i, blk in enumerate(self.block1): x = blk(x, H, W) x = self.norm1(x) x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() outs.append(x)
# stage 2 x, H, W = self.patch_embed2(x) for i, blk in enumerate(self.block2): x = blk(x, H, W) x = self.norm2(x) x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() outs.append(x)
# stage 3 x, H, W = self.patch_embed3(x) for i, blk in enumerate(self.block3): x = blk(x, H, W) x = self.norm3(x) x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() outs.append(x)
# stage 4 x, H, W = self.patch_embed4(x) for i, blk in enumerate(self.block4): x = blk(x, H, W) x = self.norm4(x) x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() outs.append(x)
return outs
# return x.mean(dim=1)
def forward(self, x): x = self.forward_features(x) # x = self.head(x)
return x
class DWConv(nn.Module): def __init__(self, dim=768): super(DWConv, self).__init__() self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
def forward(self, x, H, W): B, N, C = x.shape x = x.transpose(1, 2).view(B, C, H, W).contiguous() x = self.dwconv(x) x = x.flatten(2).transpose(1, 2)
return x
def _conv_filter(state_dict, patch_size=16): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k: v = v.reshape((v.shape[0], 3, patch_size, patch_size)) out_dict[k] = v
return out_dict
## @register_modelclass pvt_v2_b0(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b0, self).__init__( patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
## @register_modelclass pvt_v2_b1(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b1, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
## @register_modelclass pvt_v2_b2(PyramidVisionTransformerImpr): def __init__(self, in_channels=3, **kwargs): super(pvt_v2_b2, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)
## @register_modelclass pvt_v2_b3(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b3, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
## @register_modelclass pvt_v2_b4(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b4, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
## @register_modelclass pvt_v2_b5(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b5, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
### models/backbones/swin_v1.py
# --------------------------------------------------------# Swin Transformer# Copyright (c) 2021 Microsoft# Licensed under The MIT License [see LICENSE for details]# Written by Ze Liu, Yutong Lin, Yixuan Wei# --------------------------------------------------------
import torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.utils.checkpoint as checkpointimport numpy as npfrom timm.models.layers import DropPath, to_2tuple, trunc_normal_
# from config import Config
# config = Config()
class Mlp(nn.Module): """ Multilayer perceptron."""
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop)
def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x
def window_partition(x, window_size): """ Args: x: (B, H, W, C) window_size (int): window size
Returns: windows: (num_windows*B, window_size, window_size, C) """ B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) return windows
def window_reverse(windows, window_size, H, W): """ Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image
Returns: x: (B, H, W, C) """ B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return x
class WindowAttention(nn.Module): """ Window based multi-head self attention (W-MSA) module with relative position bias. It supports both of shifted and non-shifted window.
Args: dim (int): Number of input channels. window_size (tuple[int]): The height and width of the window. num_heads (int): Number of attention heads. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 proj_drop (float, optional): Dropout ratio of output. Default: 0.0 """
def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
super().__init__() self.dim = dim self.window_size = window_size # Wh, Ww self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5
# define a parameter table of relative position bias self.relative_position_bias_table = nn.Parameter( torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
# get pair-wise relative position index for each token inside the window coords_h = torch.arange(self.window_size[0]) coords_w = torch.arange(self.window_size[1]) coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 relative_coords[:, :, 1] += self.window_size[1] - 1 relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww self.register_buffer("relative_position_index", relative_position_index)
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop_prob = attn_drop self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop)
trunc_normal_(self.relative_position_bias_table, std=.02) self.softmax = nn.Softmax(dim=-1)
def forward(self, x, mask=None): """ Forward function.
Args: x: input features with shape of (num_windows*B, N, C) mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None """ B_, N, C = x.shape qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
q = q * self.scale
if config.SDPA_enabled: x = torch.nn.functional.scaled_dot_product_attention( q, k, v, attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False ).transpose(1, 2).reshape(B_, N, C) else: attn = (q @ k.transpose(-2, -1))
relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww attn = attn + relative_position_bias.unsqueeze(0)
if mask is not None: nW = mask.shape[0] attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) attn = attn.view(-1, self.num_heads, N, N) attn = self.softmax(attn) else: attn = self.softmax(attn)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B_, N, C) x = self.proj(x) x = self.proj_drop(x) return x
class SwinTransformerBlock(nn.Module): """ Swin Transformer Block.
Args: dim (int): Number of input channels. num_heads (int): Number of attention heads. window_size (int): Window size. shift_size (int): Shift size for SW-MSA. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. drop (float, optional): Dropout rate. Default: 0.0 attn_drop (float, optional): Attention dropout rate. Default: 0.0 drop_path (float, optional): Stochastic depth rate. Default: 0.0 act_layer (nn.Module, optional): Activation layer. Default: nn.GELU norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """
def __init__(self, dim, num_heads, window_size=7, shift_size=0, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.dim = dim self.num_heads = num_heads self.window_size = window_size self.shift_size = shift_size self.mlp_ratio = mlp_ratio assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
self.norm1 = norm_layer(dim) self.attn = WindowAttention( dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.H = None self.W = None
def forward(self, x, mask_matrix): """ Forward function.
Args: x: Input feature, tensor size (B, H*W, C). H, W: Spatial resolution of the input feature. mask_matrix: Attention mask for cyclic shift. """ B, L, C = x.shape H, W = self.H, self.W assert L == H * W, "input feature has wrong size"
shortcut = x x = self.norm1(x) x = x.view(B, H, W, C)
# pad feature maps to multiples of window size pad_l = pad_t = 0 pad_r = (self.window_size - W % self.window_size) % self.window_size pad_b = (self.window_size - H % self.window_size) % self.window_size x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) _, Hp, Wp, _ = x.shape
# cyclic shift if self.shift_size > 0: shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) attn_mask = mask_matrix else: shifted_x = x attn_mask = None
# partition windows x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
# W-MSA/SW-MSA attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
# merge windows attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
# reverse cyclic shift if self.shift_size > 0: x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) else: x = shifted_x
if pad_r > 0 or pad_b > 0: x = x[:, :H, :W, :].contiguous()
x = x.view(B, H * W, C)
# FFN x = shortcut + self.drop_path(x) x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
class PatchMerging(nn.Module): """ Patch Merging Layer
Args: dim (int): Number of input channels. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """ def __init__(self, dim, norm_layer=nn.LayerNorm): super().__init__() self.dim = dim self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) self.norm = norm_layer(4 * dim)
def forward(self, x, H, W): """ Forward function.
Args: x: Input feature, tensor size (B, H*W, C). H, W: Spatial resolution of the input feature. """ B, L, C = x.shape assert L == H * W, "input feature has wrong size"
x = x.view(B, H, W, C)
# padding pad_input = (H % 2 == 1) or (W % 2 == 1) if pad_input: x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
x = self.norm(x) x = self.reduction(x)
return x
class BasicLayer(nn.Module): """ A basic Swin Transformer layer for one stage.
Args: dim (int): Number of feature channels depth (int): Depths of this stage. num_heads (int): Number of attention head. window_size (int): Local window size. Default: 7. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. drop (float, optional): Dropout rate. Default: 0.0 attn_drop (float, optional): Attention dropout rate. Default: 0.0 drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. """
def __init__(self, dim, depth, num_heads, window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False): super().__init__() self.window_size = window_size self.shift_size = window_size // 2 self.depth = depth self.use_checkpoint = use_checkpoint
# build blocks self.blocks = nn.ModuleList([ SwinTransformerBlock( dim=dim, num_heads=num_heads, window_size=window_size, shift_size=0 if (i % 2 == 0) else window_size // 2, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop, attn_drop=attn_drop, drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, norm_layer=norm_layer) for i in range(depth)])
# patch merging layer if downsample is not None: self.downsample = downsample(dim=dim, norm_layer=norm_layer) else: self.downsample = None
def forward(self, x, H, W): """ Forward function.
Args: x: Input feature, tensor size (B, H*W, C). H, W: Spatial resolution of the input feature. """
# calculate attention mask for SW-MSA Hp = int(np.ceil(H / self.window_size)) * self.window_size Wp = int(np.ceil(W / self.window_size)) * self.window_size img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1 h_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) w_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) cnt = 0 for h in h_slices: for w in w_slices: img_mask[:, h, w, :] = cnt cnt += 1
mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1 mask_windows = mask_windows.view(-1, self.window_size * self.window_size) attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
for blk in self.blocks: blk.H, blk.W = H, W if self.use_checkpoint: x = checkpoint.checkpoint(blk, x, attn_mask) else: x = blk(x, attn_mask) if self.downsample is not None: x_down = self.downsample(x, H, W) Wh, Ww = (H + 1) // 2, (W + 1) // 2 return x, H, W, x_down, Wh, Ww else: return x, H, W, x, H, W
class PatchEmbed(nn.Module): """ Image to Patch Embedding
Args: patch_size (int): Patch token size. Default: 4. in_channels (int): Number of input image channels. Default: 3. embed_dim (int): Number of linear projection output channels. Default: 96. norm_layer (nn.Module, optional): Normalization layer. Default: None """
def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None): super().__init__() patch_size = to_2tuple(patch_size) self.patch_size = patch_size
self.in_channels = in_channels self.embed_dim = embed_dim
self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size) if norm_layer is not None: self.norm = norm_layer(embed_dim) else: self.norm = None
def forward(self, x): """Forward function.""" # padding _, _, H, W = x.size() if W % self.patch_size[1] != 0: x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1])) if H % self.patch_size[0] != 0: x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
x = self.proj(x) # B C Wh Ww if self.norm is not None: Wh, Ww = x.size(2), x.size(3) x = x.flatten(2).transpose(1, 2) x = self.norm(x) x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
return x
class SwinTransformer(nn.Module): """ Swin Transformer backbone. A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - https://arxiv.org/pdf/2103.14030
Args: pretrain_img_size (int): Input image size for training the pretrained model, used in absolute postion embedding. Default 224. patch_size (int | tuple(int)): Patch size. Default: 4. in_channels (int): Number of input image channels. Default: 3. embed_dim (int): Number of linear projection output channels. Default: 96. depths (tuple[int]): Depths of each Swin Transformer stage. num_heads (tuple[int]): Number of attention head of each stage. window_size (int): Window size. Default: 7. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. drop_rate (float): Dropout rate. attn_drop_rate (float): Attention dropout rate. Default: 0. drop_path_rate (float): Stochastic depth rate. Default: 0.2. norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. ape (bool): If True, add absolute position embedding to the patch embedding. Default: False. patch_norm (bool): If True, add normalization after patch embedding. Default: True. out_indices (Sequence[int]): Output from which stages. frozen_stages (int): Stages to be frozen (stop grad and set eval mode). -1 means not freezing any parameters. use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. """
def __init__(self, pretrain_img_size=224, patch_size=4, in_channels=3, embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.2, norm_layer=nn.LayerNorm, ape=False, patch_norm=True, out_indices=(0, 1, 2, 3), frozen_stages=-1, use_checkpoint=False): super().__init__()
self.pretrain_img_size = pretrain_img_size self.num_layers = len(depths) self.embed_dim = embed_dim self.ape = ape self.patch_norm = patch_norm self.out_indices = out_indices self.frozen_stages = frozen_stages
# split image into non-overlapping patches self.patch_embed = PatchEmbed( patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim, norm_layer=norm_layer if self.patch_norm else None)
# absolute position embedding if self.ape: pretrain_img_size = to_2tuple(pretrain_img_size) patch_size = to_2tuple(patch_size) patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1])) trunc_normal_(self.absolute_pos_embed, std=.02)
self.pos_drop = nn.Dropout(p=drop_rate)
# stochastic depth dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
# build layers self.layers = nn.ModuleList() for i_layer in range(self.num_layers): layer = BasicLayer( dim=int(embed_dim * 2 ** i_layer), depth=depths[i_layer], num_heads=num_heads[i_layer], window_size=window_size, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], norm_layer=norm_layer, downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, use_checkpoint=use_checkpoint) self.layers.append(layer)
num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)] self.num_features = num_features
# add a norm layer for each output for i_layer in out_indices: layer = norm_layer(num_features[i_layer]) layer_name = f'norm{i_layer}' self.add_module(layer_name, layer)
self._freeze_stages()
def _freeze_stages(self): if self.frozen_stages >= 0: self.patch_embed.eval() for param in self.patch_embed.parameters(): param.requires_grad = False
if self.frozen_stages >= 1 and self.ape: self.absolute_pos_embed.requires_grad = False
if self.frozen_stages >= 2: self.pos_drop.eval() for i in range(0, self.frozen_stages - 1): m = self.layers[i] m.eval() for param in m.parameters(): param.requires_grad = False
def forward(self, x): """Forward function.""" x = self.patch_embed(x)
Wh, Ww = x.size(2), x.size(3) if self.ape: # interpolate the position embedding to the corresponding size absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic') x = (x + absolute_pos_embed) # B Wh*Ww C outs = []#x.contiguous()] x = x.flatten(2).transpose(1, 2) x = self.pos_drop(x) for i in range(self.num_layers): layer = self.layers[i] x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
if i in self.out_indices: norm_layer = getattr(self, f'norm{i}') x_out = norm_layer(x_out)
out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous() outs.append(out)
return tuple(outs)
def train(self, mode=True): """Convert the model into training mode while keep layers freezed.""" super(SwinTransformer, self).train(mode) self._freeze_stages()
def swin_v1_t(): model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7) return model
def swin_v1_s(): model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7) return model
def swin_v1_b(): model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12) return model
def swin_v1_l(): model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12) return model
### models/modules/deform_conv.py
import torchimport torch.nn as nnfrom torchvision.ops import deform_conv2d
class DeformableConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False):
super(DeformableConv2d, self).__init__() assert type(kernel_size) == tuple or type(kernel_size) == int
kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size) self.stride = stride if type(stride) == tuple else (stride, stride) self.padding = padding self.offset_conv = nn.Conv2d(in_channels, 2 * kernel_size[0] * kernel_size[1], kernel_size=kernel_size, stride=stride, padding=self.padding, bias=True)
nn.init.constant_(self.offset_conv.weight, 0.) nn.init.constant_(self.offset_conv.bias, 0.) self.modulator_conv = nn.Conv2d(in_channels, 1 * kernel_size[0] * kernel_size[1], kernel_size=kernel_size, stride=stride, padding=self.padding, bias=True)
nn.init.constant_(self.modulator_conv.weight, 0.) nn.init.constant_(self.modulator_conv.bias, 0.)
self.regular_conv = nn.Conv2d(in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=self.padding, bias=bias)
def forward(self, x): #h, w = x.shape[2:] #max_offset = max(h, w)/4.
offset = self.offset_conv(x)#.clamp(-max_offset, max_offset) modulator = 2. * torch.sigmoid(self.modulator_conv(x)) x = deform_conv2d( input=x, offset=offset, weight=self.regular_conv.weight, bias=self.regular_conv.bias, padding=self.padding, mask=modulator, stride=self.stride, ) return x
### utils.py
import torch.nn as nn
def build_act_layer(act_layer): if act_layer == 'ReLU': return nn.ReLU(inplace=True) elif act_layer == 'SiLU': return nn.SiLU(inplace=True) elif act_layer == 'GELU': return nn.GELU()
raise NotImplementedError(f'build_act_layer does not support {act_layer}')
def build_norm_layer(dim, norm_layer, in_format='channels_last', out_format='channels_last', eps=1e-6): layers = [] if norm_layer == 'BN': if in_format == 'channels_last': layers.append(to_channels_first()) layers.append(nn.BatchNorm2d(dim)) if out_format == 'channels_last': layers.append(to_channels_last()) elif norm_layer == 'LN': if in_format == 'channels_first': layers.append(to_channels_last()) layers.append(nn.LayerNorm(dim, eps=eps)) if out_format == 'channels_first': layers.append(to_channels_first()) else: raise NotImplementedError( f'build_norm_layer does not support {norm_layer}') return nn.Sequential(*layers)
class to_channels_first(nn.Module):
def __init__(self): super().__init__()
def forward(self, x): return x.permute(0, 3, 1, 2)
class to_channels_last(nn.Module):
def __init__(self): super().__init__()
def forward(self, x): return x.permute(0, 2, 3, 1)
### dataset.py
_class_labels_TR_sorted = ( 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, ' 'BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, ' 'CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, ' 'Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, ' 'Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, ' 'Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, ' 'KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, ' 'Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, ' 'OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, ' 'RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, ' 'ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, ' 'Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, ' 'TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, ' 'UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht')class_labels_TR_sorted = _class_labels_TR_sorted.split(', ')
### models/backbones/build_backbones.py
import torchimport torch.nn as nnfrom collections import OrderedDictfrom torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights# from models.pvt_v2 import pvt_v2_b0, pvt_v2_b1, pvt_v2_b2, pvt_v2_b5# from models.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l# from config import Config
config = Config()
def build_backbone(bb_name, pretrained=True, params_settings=''): if bb_name == 'vgg16': bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0] bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]})) elif bb_name == 'vgg16bn': bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0] bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]})) elif bb_name == 'resnet50': bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children()) bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]})) else: bb = eval('{}({})'.format(bb_name, params_settings)) if pretrained: bb = load_weights(bb, bb_name) return bb
def load_weights(model, model_name): save_model = torch.load(config.weights[model_name], map_location='cpu') model_dict = model.state_dict() state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model.items() if k in model_dict.keys()} # to ignore the weights with mismatched size when I modify the backbone itself. if not state_dict: save_model_keys = list(save_model.keys()) sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model[sub_item].items() if k in model_dict.keys()} if not state_dict or not sub_item: print('Weights are not successully loaded. Check the state dict of weights file.') return None else: print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item)) model_dict.update(state_dict) model.load_state_dict(model_dict) return model
### models/modules/decoder_blocks.py
import torchimport torch.nn as nn# from models.aspp import ASPP, ASPPDeformable# from config import Config
# config = Config()
class BasicDecBlk(nn.Module): def __init__(self, in_channels=64, out_channels=64, inter_channels=64): super(BasicDecBlk, self).__init__() inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1) self.relu_in = nn.ReLU(inplace=True) if config.dec_att == 'ASPP': self.dec_att = ASPP(in_channels=inter_channels) elif config.dec_att == 'ASPPDeformable': self.dec_att = ASPPDeformable(in_channels=inter_channels) self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1) self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity() self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
def forward(self, x): x = self.conv_in(x) x = self.bn_in(x) x = self.relu_in(x) if hasattr(self, 'dec_att'): x = self.dec_att(x) x = self.conv_out(x) x = self.bn_out(x) return x
class ResBlk(nn.Module): def __init__(self, in_channels=64, out_channels=None, inter_channels=64): super(ResBlk, self).__init__() if out_channels is None: out_channels = in_channels inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1) self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity() self.relu_in = nn.ReLU(inplace=True)
if config.dec_att == 'ASPP': self.dec_att = ASPP(in_channels=inter_channels) elif config.dec_att == 'ASPPDeformable': self.dec_att = ASPPDeformable(in_channels=inter_channels)
self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1) self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity() self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
def forward(self, x): _x = self.conv_resi(x) x = self.conv_in(x) x = self.bn_in(x) x = self.relu_in(x) if hasattr(self, 'dec_att'): x = self.dec_att(x) x = self.conv_out(x) x = self.bn_out(x) return x + _x
### models/modules/lateral_blocks.py
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom functools import partial
# from config import Config
# config = Config()
class BasicLatBlk(nn.Module): def __init__(self, in_channels=64, out_channels=64, inter_channels=64): super(BasicLatBlk, self).__init__() inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
def forward(self, x): x = self.conv(x) return x
### models/modules/aspp.py
import torchimport torch.nn as nnimport torch.nn.functional as F# from models.deform_conv import DeformableConv2d# from config import Config
# config = Config()
class _ASPPModule(nn.Module): def __init__(self, in_channels, planes, kernel_size, padding, dilation): super(_ASPPModule, self).__init__() self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size, stride=1, padding=padding, dilation=dilation, bias=False) self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity() self.relu = nn.ReLU(inplace=True)
def forward(self, x): x = self.atrous_conv(x) x = self.bn(x)
return self.relu(x)
class ASPP(nn.Module): def __init__(self, in_channels=64, out_channels=None, output_stride=16): super(ASPP, self).__init__() self.down_scale = 1 if out_channels is None: out_channels = in_channels self.in_channelster = 256 // self.down_scale if output_stride == 16: dilations = [1, 6, 12, 18] elif output_stride == 8: dilations = [1, 12, 24, 36] else: raise NotImplementedError
self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0]) self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1]) self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2]) self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3])
self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True)) self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False) self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity() self.relu = nn.ReLU(inplace=True) self.dropout = nn.Dropout(0.5)
def forward(self, x): x1 = self.aspp1(x) x2 = self.aspp2(x) x3 = self.aspp3(x) x4 = self.aspp4(x) x5 = self.global_avg_pool(x) x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) x = torch.cat((x1, x2, x3, x4, x5), dim=1)
x = self.conv1(x) x = self.bn1(x) x = self.relu(x)
return self.dropout(x)
##################### Deformableclass _ASPPModuleDeformable(nn.Module): def __init__(self, in_channels, planes, kernel_size, padding): super(_ASPPModuleDeformable, self).__init__() self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size, stride=1, padding=padding, bias=False) self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity() self.relu = nn.ReLU(inplace=True)
def forward(self, x): x = self.atrous_conv(x) x = self.bn(x)
return self.relu(x)
class ASPPDeformable(nn.Module): def __init__(self, in_channels, out_channels=None, parallel_block_sizes=[1, 3, 7]): super(ASPPDeformable, self).__init__() self.down_scale = 1 if out_channels is None: out_channels = in_channels self.in_channelster = 256 // self.down_scale
self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0) self.aspp_deforms = nn.ModuleList([ _ASPPModuleDeformable(in_channels, self.in_channelster, conv_size, padding=int(conv_size//2)) for conv_size in parallel_block_sizes ])
self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True)) self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False) self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity() self.relu = nn.ReLU(inplace=True) self.dropout = nn.Dropout(0.5)
def forward(self, x): x1 = self.aspp1(x) x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms] x5 = self.global_avg_pool(x) x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) x = torch.cat((x1, *x_aspp_deforms, x5), dim=1)
x = self.conv1(x) x = self.bn1(x) x = self.relu(x)
return self.dropout(x)
### models/refinement/refiner.py
import torchimport torch.nn as nnfrom collections import OrderedDictimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torchvision.models import vgg16, vgg16_bnfrom torchvision.models import resnet50
# from config import Config# from dataset import class_labels_TR_sorted# from models.build_backbone import build_backbone# from models.decoder_blocks import BasicDecBlk# from models.lateral_blocks import BasicLatBlk# from models.ing import *# from models.stem_layer import StemLayer
class RefinerPVTInChannels4(nn.Module): def __init__(self, in_channels=3+1): super(RefinerPVTInChannels4, self).__init__() self.config = Config() self.epoch = 1 self.bb = build_backbone(self.config.bb, params_settings='in_channels=4')
lateral_channels_in_collection = { 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], } channels = lateral_channels_in_collection[self.config.bb] self.squeeze_module = BasicDecBlk(channels[0], channels[0])
self.decoder = Decoder(channels)
if 0: for key, value in self.named_parameters(): if 'bb.' in key: value.requires_grad = False
def forward(self, x): if isinstance(x, list): x = torch.cat(x, dim=1) ########## Encoder ########## if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: x1 = self.bb.conv1(x) x2 = self.bb.conv2(x1) x3 = self.bb.conv3(x2) x4 = self.bb.conv4(x3) else: x1, x2, x3, x4 = self.bb(x)
x4 = self.squeeze_module(x4)
########## Decoder ##########
features = [x, x1, x2, x3, x4] scaled_preds = self.decoder(features)
return scaled_preds
class Refiner(nn.Module): def __init__(self, in_channels=3+1): super(Refiner, self).__init__() self.config = Config() self.epoch = 1 self.stem_layer = StemLayer(in_channels=in_channels, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN') self.bb = build_backbone(self.config.bb)
lateral_channels_in_collection = { 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], } channels = lateral_channels_in_collection[self.config.bb] self.squeeze_module = BasicDecBlk(channels[0], channels[0])
self.decoder = Decoder(channels)
if 0: for key, value in self.named_parameters(): if 'bb.' in key: value.requires_grad = False
def forward(self, x): if isinstance(x, list): x = torch.cat(x, dim=1) x = self.stem_layer(x) ########## Encoder ########## if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: x1 = self.bb.conv1(x) x2 = self.bb.conv2(x1) x3 = self.bb.conv3(x2) x4 = self.bb.conv4(x3) else: x1, x2, x3, x4 = self.bb(x)
x4 = self.squeeze_module(x4)
########## Decoder ##########
features = [x, x1, x2, x3, x4] scaled_preds = self.decoder(features)
return scaled_preds
class Decoder(nn.Module): def __init__(self, channels): super(Decoder, self).__init__() self.config = Config() DecoderBlock = eval('BasicDecBlk') LateralBlock = eval('BasicLatBlk')
self.decoder_block4 = DecoderBlock(channels[0], channels[1]) self.decoder_block3 = DecoderBlock(channels[1], channels[2]) self.decoder_block2 = DecoderBlock(channels[2], channels[3]) self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2)
self.lateral_block4 = LateralBlock(channels[1], channels[1]) self.lateral_block3 = LateralBlock(channels[2], channels[2]) self.lateral_block2 = LateralBlock(channels[3], channels[3])
if self.config.ms_supervision: self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0) self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0) self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0) self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0))
def forward(self, features): x, x1, x2, x3, x4 = features outs = [] p4 = self.decoder_block4(x4) _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True) _p3 = _p4 + self.lateral_block4(x3)
p3 = self.decoder_block3(_p3) _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True) _p2 = _p3 + self.lateral_block3(x2)
p2 = self.decoder_block2(_p2) _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True) _p1 = _p2 + self.lateral_block2(x1)
_p1 = self.decoder_block1(_p1) _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True) p1_out = self.conv_out1(_p1)
if self.config.ms_supervision: outs.append(self.conv_ms_spvn_4(p4)) outs.append(self.conv_ms_spvn_3(p3)) outs.append(self.conv_ms_spvn_2(p2)) outs.append(p1_out) return outs
class RefUNet(nn.Module): # Refinement def __init__(self, in_channels=3+1): super(RefUNet, self).__init__() self.encoder_1 = nn.Sequential( nn.Conv2d(in_channels, 64, 3, 1, 1), nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.encoder_2 = nn.Sequential( nn.MaxPool2d(2, 2, ceil_mode=True), nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.encoder_3 = nn.Sequential( nn.MaxPool2d(2, 2, ceil_mode=True), nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.encoder_4 = nn.Sequential( nn.MaxPool2d(2, 2, ceil_mode=True), nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True) ##### self.decoder_5 = nn.Sequential( nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) ) ##### self.decoder_4 = nn.Sequential( nn.Conv2d(128, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.decoder_3 = nn.Sequential( nn.Conv2d(128, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.decoder_2 = nn.Sequential( nn.Conv2d(128, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.decoder_1 = nn.Sequential( nn.Conv2d(128, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1)
self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
def forward(self, x): outs = [] if isinstance(x, list): x = torch.cat(x, dim=1) hx = x
hx1 = self.encoder_1(hx) hx2 = self.encoder_2(hx1) hx3 = self.encoder_3(hx2) hx4 = self.encoder_4(hx3)
hx = self.decoder_5(self.pool4(hx4)) hx = torch.cat((self.upscore2(hx), hx4), 1)
d4 = self.decoder_4(hx) hx = torch.cat((self.upscore2(d4), hx3), 1)
d3 = self.decoder_3(hx) hx = torch.cat((self.upscore2(d3), hx2), 1)
d2 = self.decoder_2(hx) hx = torch.cat((self.upscore2(d2), hx1), 1)
d1 = self.decoder_1(hx)
x = self.conv_d0(d1) outs.append(x) return outs
### models/stem_layer.py
import torch.nn as nn# from utils import build_act_layer, build_norm_layer
class StemLayer(nn.Module): r""" Stem layer of InternImage Args: in_channels (int): number of input channels out_channels (int): number of output channels act_layer (str): activation layer norm_layer (str): normalization layer """
def __init__(self, in_channels=3+1, inter_channels=48, out_channels=96, act_layer='GELU', norm_layer='BN'): super().__init__() self.conv1 = nn.Conv2d(in_channels, inter_channels, kernel_size=3, stride=1, padding=1) self.norm1 = build_norm_layer( inter_channels, norm_layer, 'channels_first', 'channels_first' ) self.act = build_act_layer(act_layer) self.conv2 = nn.Conv2d(inter_channels, out_channels, kernel_size=3, stride=1, padding=1) self.norm2 = build_norm_layer( out_channels, norm_layer, 'channels_first', 'channels_first' )
def forward(self, x): x = self.conv1(x) x = self.norm1(x) x = self.act(x) x = self.conv2(x) x = self.norm2(x) return x
### models/birefnet.py
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom kornia.filters import laplacianfrom transformers import PreTrainedModel
# from config import Config# from dataset import class_labels_TR_sorted# from models.build_backbone import build_backbone# from models.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk# from models.lateral_blocks import BasicLatBlk# from models.aspp import ASPP, ASPPDeformable# from models.ing import *# from models.refiner import Refiner, RefinerPVTInChannels4, RefUNet# from models.stem_layer import StemLayerfrom .BiRefNet_config import BiRefNetConfig
class BiRefNet( PreTrainedModel): config_class = BiRefNetConfig def __init__(self, bb_pretrained=True, config=BiRefNetConfig()): super(BiRefNet, self).__init__(config) bb_pretrained = config.bb_pretrained self.config = Config() self.epoch = 1 self.bb = build_backbone(self.config.bb, pretrained=bb_pretrained)
channels = self.config.lateral_channels_in_collection
if self.config.auxiliary_classification: self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.cls_head = nn.Sequential( nn.Linear(channels[0], len(class_labels_TR_sorted)) )
if self.config.squeeze_block: self.squeeze_module = nn.Sequential(*[ eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0]) for _ in range(eval(self.config.squeeze_block.split('_x')[1])) ])
self.decoder = Decoder(channels)
if self.config.ender: self.dec_end = nn.Sequential( nn.Conv2d(1, 16, 3, 1, 1), nn.Conv2d(16, 1, 3, 1, 1), nn.ReLU(inplace=True), )
# refine patch-level segmentation if self.config.refine: if self.config.refine == 'itself': self.stem_layer = StemLayer(in_channels=3+1, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN') else: self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1'))
if self.config.freeze_bb: # Freeze the backbone... print(self.named_parameters()) for key, value in self.named_parameters(): if 'bb.' in key and 'refiner.' not in key: value.requires_grad = False
def forward_enc(self, x): if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3) else: x1, x2, x3, x4 = self.bb(x) if self.config.mul_scl_ipt == 'cat': B, C, H, W = x.shape x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True)) x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1) x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1) x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1) x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1) elif self.config.mul_scl_ipt == 'add': B, C, H, W = x.shape x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True)) x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True) x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True) x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True) x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True) class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None if self.config.cxt: x4 = torch.cat( ( *[ F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True), F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True), F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True), ][-len(self.config.cxt):], x4 ), dim=1 ) return (x1, x2, x3, x4), class_preds
def forward_ori(self, x): ########## Encoder ########## (x1, x2, x3, x4), class_preds = self.forward_enc(x) if self.config.squeeze_block: x4 = self.squeeze_module(x4) ########## Decoder ########## features = [x, x1, x2, x3, x4] if self.training and self.config.out_ref: features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5)) scaled_preds = self.decoder(features) return scaled_preds, class_preds
def forward(self, x): scaled_preds, class_preds = self.forward_ori(x) class_preds_lst = [class_preds] return [scaled_preds, class_preds_lst] if self.training else scaled_preds
class Decoder(nn.Module): def __init__(self, channels): super(Decoder, self).__init__() self.config = Config() DecoderBlock = eval(self.config.dec_blk) LateralBlock = eval(self.config.lat_blk)
if self.config.dec_ipt: self.split = self.config.dec_ipt_split N_dec_ipt = 64 DBlock = SimpleConvs ic = 64 ipt_cha_opt = 1 self.ipt_blk5 = DBlock(2**10*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic) self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic) self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic) self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic) self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic) else: self.split = None
self.decoder_block4 = DecoderBlock(channels[0]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[1]) self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2]) self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]) self.decoder_block1 = DecoderBlock(channels[3]+([N_dec_ipt, channels[2]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]//2) self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2+([N_dec_ipt, channels[3]//8][ipt_cha_opt] if self.config.dec_ipt else 0), 1, 1, 1, 0))
self.lateral_block4 = LateralBlock(channels[1], channels[1]) self.lateral_block3 = LateralBlock(channels[2], channels[2]) self.lateral_block2 = LateralBlock(channels[3], channels[3])
if self.config.ms_supervision: self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0) self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0) self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
if self.config.out_ref: _N = 16 self.gdt_convs_4 = nn.Sequential(nn.Conv2d(channels[1], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True)) self.gdt_convs_3 = nn.Sequential(nn.Conv2d(channels[2], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True)) self.gdt_convs_2 = nn.Sequential(nn.Conv2d(channels[3], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
def get_patches_batch(self, x, p): _size_h, _size_w = p.shape[2:] patches_batch = [] for idx in range(x.shape[0]): columns_x = torch.split(x[idx], split_size_or_sections=_size_w, dim=-1) patches_x = [] for column_x in columns_x: patches_x += [p.unsqueeze(0) for p in torch.split(column_x, split_size_or_sections=_size_h, dim=-2)] patch_sample = torch.cat(patches_x, dim=1) patches_batch.append(patch_sample) return torch.cat(patches_batch, dim=0)
def forward(self, features): if self.training and self.config.out_ref: outs_gdt_pred = [] outs_gdt_label = [] x, x1, x2, x3, x4, gdt_gt = features else: x, x1, x2, x3, x4 = features outs = []
if self.config.dec_ipt: patches_batch = self.get_patches_batch(x, x4) if self.split else x x4 = torch.cat((x4, self.ipt_blk5(F.interpolate(patches_batch, size=x4.shape[2:], mode='bilinear', align_corners=True))), 1) p4 = self.decoder_block4(x4) m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision else None if self.config.out_ref: p4_gdt = self.gdt_convs_4(p4) if self.training: # >> GT: m4_dia = m4 gdt_label_main_4 = gdt_gt * F.interpolate(m4_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) outs_gdt_label.append(gdt_label_main_4) # >> Pred: gdt_pred_4 = self.gdt_convs_pred_4(p4_gdt) outs_gdt_pred.append(gdt_pred_4) gdt_attn_4 = self.gdt_convs_attn_4(p4_gdt).sigmoid() # >> Finally: p4 = p4 * gdt_attn_4 _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True) _p3 = _p4 + self.lateral_block4(x3)
if self.config.dec_ipt: patches_batch = self.get_patches_batch(x, _p3) if self.split else x _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1) p3 = self.decoder_block3(_p3) m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision else None if self.config.out_ref: p3_gdt = self.gdt_convs_3(p3) if self.training: # >> GT: # m3 --dilation--> m3_dia # G_3^gt * m3_dia --> G_3^m, which is the label of gradient m3_dia = m3 gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) outs_gdt_label.append(gdt_label_main_3) # >> Pred: # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx # F_3^G --sigmoid--> A_3^G gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt) outs_gdt_pred.append(gdt_pred_3) gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid() # >> Finally: # p3 = p3 * A_3^G p3 = p3 * gdt_attn_3 _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True) _p2 = _p3 + self.lateral_block3(x2)
if self.config.dec_ipt: patches_batch = self.get_patches_batch(x, _p2) if self.split else x _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1) p2 = self.decoder_block2(_p2) m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision else None if self.config.out_ref: p2_gdt = self.gdt_convs_2(p2) if self.training: # >> GT: m2_dia = m2 gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) outs_gdt_label.append(gdt_label_main_2) # >> Pred: gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt) outs_gdt_pred.append(gdt_pred_2) gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid() # >> Finally: p2 = p2 * gdt_attn_2 _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True) _p1 = _p2 + self.lateral_block2(x1)
if self.config.dec_ipt: patches_batch = self.get_patches_batch(x, _p1) if self.split else x _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1) _p1 = self.decoder_block1(_p1) _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
if self.config.dec_ipt: patches_batch = self.get_patches_batch(x, _p1) if self.split else x _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1) p1_out = self.conv_out1(_p1)
if self.config.ms_supervision: outs.append(m4) outs.append(m3) outs.append(m2) outs.append(p1_out) return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs)
class SimpleConvs(nn.Module): def __init__( self, in_channels: int, out_channels: int, inter_channels=64 ) -> None: super().__init__() self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1) self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)
def forward(self, x): return self.conv_out(self.conv1(x))123456789101112131415161718192021{ "_name_or_path": "ZhengPeng7/BiRefNet", "architectures": [ "BiRefNet" ], "auto_map": { "AutoConfig": "BiRefNet_config.BiRefNetConfig", "AutoModelForImageSegmentation": "birefnet.BiRefNet" }, "custom_pipelines": { "image-segmentation": { "pt": [ "AutoModelForImageSegmentation" ], "tf": [], "type": "image" } }, "bb_pretrained": false, "model_type": "birefnet"}1234567891011121314151617181920212223{ "do_normalize": true, "do_rescale": true, "do_resize": true, "feature_extractor_type": "ViTFeatureExtractor", "image_mean": [ 0.485, 0.456, 0.406 ], "image_processor_type": "ViTFeatureExtractor", "image_std": [ 0.229, 0.224, 0.225 ], "resample": 2, "rescale_factor": 0.00392156862745098, "size": { "height": 1024, "width": 1024 }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879---license: mitlanguage:- en---# Image Captioning App
This is a mod of [Wi-zz/joy-caption-pre-alpha](https://huggingface.co/Wi-zz/joy-caption-pre-alpha) and [fancyfeast/joy-caption-alpha-two](https://huggingface.co/spaces/fancyfeast/joy-caption-alpha-two). Thanks to [dominic1021](https://huggingface.co/dominic1021), [IceHibiki](https://huggingface.co/IceHibiki), [BullseyeMxP](https://huggingface.co/BullseyeMxP), [Wakeme](https://huggingface.co/Wakeme).
# Notice: I will contribute to Wi-zz after shaping the code.
## Overview
This application generates descriptive captions for images using advanced ML models. It processes single images or entire directories, leveraging CLIP and LLM models for accurate and contextual captions. It has NSFW captioning support with natural language. This is just an extension of the original author's efforts to improve performance. Their repo is located here: https://huggingface.co/spaces/fancyfeast/joy-caption-alpha-two.
## Features
- Single image and batch processing- Multiple directory support- Custom output directory- Adjustable batch size- Progress tracking
## Usage
| Command | Description ||---------|-------------|| `python app.py image.jpg` | Process a single image || `python app.py /path/to/directory` | Process all images in a directory || `python app.py /path/to/dir1 /path/to/dir2` | Process multiple directories || `python app.py /path/to/dir --output /path/to/output` | Specify output directory || `python app.py /path/to/dir --bs 8` | Set batch size (default: 4) |
## Technical Details
- **Models**: CLIP (vision), LLM (language), custom ImageAdapter- **Optimization**: CUDA-enabled GPU support- **Error Handling**: Skips problematic images in batch processing
## Requirements
- Python 3.x- PyTorch- Transformers library- PEFT library- CUDA-capable GPU (recommended)
## Installation
Windows
```bashgit clone https://huggingface.co/John6666/joy-caption-alpha-two-cli-modcd joy-caption-alpha-two-cli-modpython -m venv venv.\venv\Scripts\activate# Change as per https://pytorch.org/get-started/locally/pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121pip install -r requirements.txt```
Linux
```bashgit clone https://huggingface.co/John6666/joy-caption-alpha-two-cli-modcd joy-caption-alpha-two-cli-modpython3 -m venv venvsource venv/bin/activatepip3 install torch torchvision torchaudiopip3 install -r requirements.txt```
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## License
This project is licensed under the [MIT License](LICENSE).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536import torch
import torch.amp.autocast_mode
import os
import sys
import logging
import warnings
import argparse
from PIL import Image
from pathlib import Path
from tqdm import tqdm
from torch import nn
from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM
from typing import List, Union
import torchvision.transforms.functional as TVF
from peft import PeftModel
import gc
import sys
IS_COLAB = 'google.colab' in sys.modules
# Constants
IMAGE_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.bmp', '.webp')
HF_TOKEN = os.environ.get("HF_TOKEN", None)
BASE_DIR = Path(__file__).resolve().parent # Define the base directory
CHECKPOINT_PATH = BASE_DIR / Path("cgrkzexw-599808")
CLIP_PATH = "google/siglip-so400m-patch14-384"
DEFAULT_MODEL_PATH = "unsloth/Meta-Llama-3.1-8B-bnb-4bit"
#DEFAULT_MODEL_PATH = "unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit" # Default in Alpha One Two.
#DEFAULT_MODEL_PATH = "Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2" # Works better but full weight.
LORA_PATH = CHECKPOINT_PATH / "text_model"
CAPTION_TYPE_MAP = {
"Descriptive": [
"Write a descriptive caption for this image in a formal tone.",
"Write a descriptive caption for this image in a formal tone within {word_count} words.",
"Write a {length} descriptive caption for this image in a formal tone.",
],
"Descriptive (Informal)": [
"Write a descriptive caption for this image in a casual tone.",
"Write a descriptive caption for this image in a casual tone within {word_count} words.",
"Write a {length} descriptive caption for this image in a casual tone.",
],
"Training Prompt": [
"Write a stable diffusion prompt for this image.",
"Write a stable diffusion prompt for this image within {word_count} words.",
"Write a {length} stable diffusion prompt for this image.",
],
"MidJourney": [
"Write a MidJourney prompt for this image.",
"Write a MidJourney prompt for this image within {word_count} words.",
"Write a {length} MidJourney prompt for this image.",
],
"Booru tag list": [
"Write a list of Booru tags for this image.",
"Write a list of Booru tags for this image within {word_count} words.",
"Write a {length} list of Booru tags for this image.",
],
"Booru-like tag list": [
"Write a list of Booru-like tags for this image.",
"Write a list of Booru-like tags for this image within {word_count} words.",
"Write a {length} list of Booru-like tags for this image.",
],
"Art Critic": [
"Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc.",
"Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it within {word_count} words.",
"Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it {length}.",
],
"Product Listing": [
"Write a caption for this image as though it were a product listing.",
"Write a caption for this image as though it were a product listing. Keep it under {word_count} words.",
"Write a {length} caption for this image as though it were a product listing.",
],
"Social Media Post": [
"Write a caption for this image as if it were being used for a social media post.",
"Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.",
"Write a {length} caption for this image as if it were being used for a social media post.",
],
}
class ImageAdapter(nn.Module):
def __init__(self, input_features: int, output_features: int, ln1: bool, pos_emb: bool, num_image_tokens: int, deep_extract: bool):
super().__init__()
self.deep_extract = deep_extract
if self.deep_extract:
input_features = input_features * 5
self.linear1 = nn.Linear(input_features, output_features)
self.activation = nn.GELU()
self.linear2 = nn.Linear(output_features, output_features)
self.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features)
self.pos_emb = None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features))
# Other tokens (<|image_start|>, <|image_end|>, <|eot_id|>)
self.other_tokens = nn.Embedding(3, output_features)
self.other_tokens.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3
def forward(self, vision_outputs: torch.Tensor):
if self.deep_extract:
x = torch.concat((
vision_outputs[-2],
vision_outputs[3],
vision_outputs[7],
vision_outputs[13],
vision_outputs[20],
), dim=-1)
assert len(x.shape) == 3, f"Expected 3, got {len(x.shape)}" # batch, tokens, features
assert x.shape[-1] == vision_outputs[-2].shape[-1] * 5, f"Expected {vision_outputs[-2].shape[-1] * 5}, got {x.shape[-1]}"
else:
x = vision_outputs[-2]
x = self.ln1(x)
if self.pos_emb is not None:
assert x.shape[-2:] == self.pos_emb.shape, f"Expected {self.pos_emb.shape}, got {x.shape[-2:]}"
x = x + self.pos_emb
x = self.linear1(x)
x = self.activation(x)
x = self.linear2(x)
# <|image_start|>, IMAGE, <|image_end|>
other_tokens = self.other_tokens(torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1))
assert other_tokens.shape == (x.shape[0], 2, x.shape[2]), f"Expected {(x.shape[0], 2, x.shape[2])}, got {other_tokens.shape}"
x = torch.cat((other_tokens[:, 0:1], x, other_tokens[:, 1:2]), dim=1)
return x
def get_eot_embedding(self):
return self.other_tokens(torch.tensor([2], device=self.other_tokens.weight.device)).squeeze(0)
# Global Variables
IS_NF4 = True
IS_LORA = True
MODEL_PATH = DEFAULT_MODEL_PATH
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Running on {device}")
warnings.filterwarnings("ignore", category=UserWarning)
logging.getLogger("transformers").setLevel(logging.ERROR)
class ImageAdapter(nn.Module):
def __init__(self, input_features: int, output_features: int, ln1: bool, pos_emb: bool, num_image_tokens: int, deep_extract: bool):
super().__init__()
self.deep_extract = deep_extract
if self.deep_extract:
input_features = input_features * 5
self.linear1 = nn.Linear(input_features, output_features)
self.activation = nn.GELU()
self.linear2 = nn.Linear(output_features, output_features)
self.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features)
self.pos_emb = None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features))
# Mode token
#self.mode_token = nn.Embedding(n_modes, output_features)
#self.mode_token.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3
# Other tokens (<|image_start|>, <|image_end|>, <|eot_id|>)
self.other_tokens = nn.Embedding(3, output_features)
self.other_tokens.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3
def forward(self, vision_outputs: torch.Tensor):
if self.deep_extract:
x = torch.concat((
vision_outputs[-2],
vision_outputs[3],
vision_outputs[7],
vision_outputs[13],
vision_outputs[20],
), dim=-1)
assert len(x.shape) == 3, f"Expected 3, got {len(x.shape)}" # batch, tokens, features
assert x.shape[-1] == vision_outputs[-2].shape[-1] * 5, f"Expected {vision_outputs[-2].shape[-1] * 5}, got {x.shape[-1]}"
else:
x = vision_outputs[-2]
x = self.ln1(x)
if self.pos_emb is not None:
assert x.shape[-2:] == self.pos_emb.shape, f"Expected {self.pos_emb.shape}, got {x.shape[-2:]}"
x = x + self.pos_emb
x = self.linear1(x)
x = self.activation(x)
x = self.linear2(x)
# Mode token
#mode_token = self.mode_token(mode)
#assert mode_token.shape == (x.shape[0], mode_token.shape[1], x.shape[2]), f"Expected {(x.shape[0], 1, x.shape[2])}, got {mode_token.shape}"
#x = torch.cat((x, mode_token), dim=1)
# <|image_start|>, IMAGE, <|image_end|>
other_tokens = self.other_tokens(torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1))
assert other_tokens.shape == (x.shape[0], 2, x.shape[2]), f"Expected {(x.shape[0], 2, x.shape[2])}, got {other_tokens.shape}"
x = torch.cat((other_tokens[:, 0:1], x, other_tokens[:, 1:2]), dim=1)
return x
def get_eot_embedding(self):
return self.other_tokens(torch.tensor([2], device=self.other_tokens.weight.device)).squeeze(0)
def load_models():
global MODEL_PATH, IS_NF4, IS_LORA
try:
if IS_NF4:
from transformers import BitsAndBytesConfig
nf4_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16)
print("Loading in NF4")
print("Loading CLIP 📎")
clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
clip_model = AutoModel.from_pretrained(CLIP_PATH).vision_model
assert (CHECKPOINT_PATH / "clip_model.pt").exists()
if (CHECKPOINT_PATH / "clip_model.pt").exists():
print("Loading VLM's custom vision model 📎")
checkpoint = torch.load(CHECKPOINT_PATH / "clip_model.pt", map_location='cpu', weights_only=False)
checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()}
clip_model.load_state_dict(checkpoint)
del checkpoint
clip_model.eval().requires_grad_(False).to(device)
print("Loading tokenizer 🪙")
tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT_PATH / "text_model", use_fast=True)
assert isinstance(tokenizer, (PreTrainedTokenizer, PreTrainedTokenizerFast)), f"Tokenizer is of type {type(tokenizer)}"
print(f"Loading LLM: {MODEL_PATH} 🤖")
text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, quantization_config=nf4_config).eval()
if False and IS_LORA and LORA_PATH.exists(): # omitted
print("Loading VLM's custom text model 🤖")
text_model = PeftModel.from_pretrained(model=text_model, model_id=LORA_PATH, quantization_config=nf4_config)
text_model = text_model.merge_and_unload(safe_merge=True) # to avoid PEFT bug https://github.com/huggingface/transformers/issues/28515
else: print("VLM's custom text model isn't loaded 🤖")
print("Loading image adapter 🖼️")
image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, False).eval().to("cpu")
image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu", weights_only=False))
image_adapter.eval().to(device)
else:
print("Loading in bfloat16")
print("Loading CLIP 📎")
clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
clip_model = AutoModel.from_pretrained(CLIP_PATH).vision_model
if (CHECKPOINT_PATH / "clip_model.pt").exists():
print("Loading VLM's custom vision model 📎")
checkpoint = torch.load(CHECKPOINT_PATH / "clip_model.pt", map_location='cpu', weights_only=False)
checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()}
clip_model.load_state_dict(checkpoint)
del checkpoint
clip_model.eval().requires_grad_(False).to(device)
print("Loading tokenizer 🪙")
tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT_PATH / "text_model", use_fast=True)
assert isinstance(tokenizer, (PreTrainedTokenizer, PreTrainedTokenizerFast)), f"Tokenizer is of type {type(tokenizer)}"
print(f"Loading LLM: {MODEL_PATH} 🤖")
text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map="auto", torch_dtype=torch.bfloat16).eval() # device_map="auto" may cause LoRA issue
if IS_LORA and LORA_PATH.exists():
print("Loading VLM's custom text model 🤖")
text_model = PeftModel.from_pretrained(model=text_model, model_id=LORA_PATH, device_map=device)
text_model = text_model.merge_and_unload(safe_merge=True) # to avoid PEFT bug https://github.com/huggingface/transformers/issues/28515
else: print("VLM's custom text model isn't loaded 🤖")
print("Loading image adapter 🖼️")
image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, False).eval().to("cpu")
image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu", weights_only=False))
except Exception as e:
print(f"Error loading models: {e}")
sys.exit(1)
finally:
torch.cuda.empty_cache()
gc.collect()
return clip_processor, clip_model, tokenizer, text_model, image_adapter
@torch.inference_mode()
def stream_chat(input_images: List[Image.Image], caption_type: str, caption_length: Union[str, int], extra_options: list[str], name_input: str, custom_prompt: str,
max_new_tokens: int, top_p: float, temperature: float, batch_size: int, pbar: tqdm, models: tuple) -> List[str]:
global MODEL_PATH
clip_processor, clip_model, tokenizer, text_model, image_adapter = models
torch.cuda.empty_cache()
all_captions = []
# 'any' means no length specified
length = None if caption_length == "any" else caption_length
if isinstance(length, str):
try:
length = int(length)
except ValueError:
pass
# Build prompt
if length is None:
map_idx = 0
elif isinstance(length, int):
map_idx = 1
elif isinstance(length, str):
map_idx = 2
else:
raise ValueError(f"Invalid caption length: {length}")
prompt_str = CAPTION_TYPE_MAP[caption_type][map_idx]
# Add extra options
if len(extra_options) > 0:
prompt_str += " " + " ".join(extra_options)
# Add name, length, word_count
prompt_str = prompt_str.format(name=name_input, length=caption_length, word_count=caption_length)
if custom_prompt.strip() != "":
prompt_str = custom_prompt.strip()
# For debugging
print(f"Prompt: {prompt_str}")
for i in range(0, len(input_images), batch_size):
batch = input_images[i:i+batch_size]
for input_image in input_images:
try:
# Preprocess image
# NOTE: I found the default processor for so400M to have worse results than just using PIL directly
#image = clip_processor(images=input_image, return_tensors='pt').pixel_values
image = input_image.resize((384, 384), Image.LANCZOS)
pixel_values = TVF.pil_to_tensor(image).unsqueeze(0) / 255.0
pixel_values = TVF.normalize(pixel_values, [0.5], [0.5])
pixel_values = pixel_values.to(device)
except ValueError as e:
print(f"Error processing image: {e}")
print("Skipping this image and continuing...")
continue
# Embed image
# This results in Batch x Image Tokens x Features
with torch.amp.autocast_mode.autocast(device, enabled=True):
vision_outputs = clip_model(pixel_values=pixel_values, output_hidden_states=True)
image_features = vision_outputs.hidden_states
embedded_images = image_adapter(image_features).to(device)
# Build the conversation
convo = [
{
"role": "system",
"content": "You are a helpful image captioner.",
},
{
"role": "user",
"content": prompt_str,
},
]
# Format the conversation
convo_string = tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = True)
assert isinstance(convo_string, str)
# Tokenize the conversation
# prompt_str is tokenized separately so we can do the calculations below
convo_tokens = tokenizer.encode(convo_string, return_tensors="pt", add_special_tokens=False, truncation=False)
prompt_tokens = tokenizer.encode(prompt_str, return_tensors="pt", add_special_tokens=False, truncation=False)
assert isinstance(convo_tokens, torch.Tensor) and isinstance(prompt_tokens, torch.Tensor)
convo_tokens = convo_tokens.squeeze(0) # Squeeze just to make the following easier
prompt_tokens = prompt_tokens.squeeze(0)
# Calculate where to inject the image
eot_id_indices = (convo_tokens == tokenizer.convert_tokens_to_ids("<|eot_id|>")).nonzero(as_tuple=True)[0].tolist()
assert len(eot_id_indices) == 2, f"Expected 2 <|eot_id|> tokens, got {len(eot_id_indices)}"
preamble_len = eot_id_indices[1] - prompt_tokens.shape[0] # Number of tokens before the prompt
# Embed the tokens
convo_embeds = text_model.model.embed_tokens(convo_tokens.unsqueeze(0).to(device))
# Construct the input
input_embeds = torch.cat([
convo_embeds[:, :preamble_len], # Part before the prompt
embedded_images.to(dtype=convo_embeds.dtype), # Image
convo_embeds[:, preamble_len:], # The prompt and anything after it
], dim=1).to(device)
input_ids = torch.cat([
convo_tokens[:preamble_len].unsqueeze(0),
torch.zeros((1, embedded_images.shape[1]), dtype=torch.long), # Dummy tokens for the image (TODO: Should probably use a special token here so as not to confuse any generation algorithms that might be inspecting the input)
convo_tokens[preamble_len:].unsqueeze(0),
], dim=1).to(device)
attention_mask = torch.ones_like(input_ids)
# Debugging
#print(f"Input to model: {repr(tokenizer.decode(input_ids[0]))}")
generate_ids = text_model.generate(input_ids=input_ids, inputs_embeds=input_embeds, attention_mask=attention_mask, do_sample=True,
suppress_tokens=None, max_new_tokens=max_new_tokens, top_p=top_p, temperature=temperature)
# Trim off the prompt
generate_ids = generate_ids[:, input_ids.shape[1]:]
if generate_ids[0][-1] == tokenizer.eos_token_id or generate_ids[0][-1] == tokenizer.convert_tokens_to_ids("<|eot_id|>"):
generate_ids = generate_ids[:, :-1]
caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
all_captions.append(caption.strip())
if pbar:
pbar.update(len(batch))
return all_captions
def process_directory(input_dir: Path, output_dir: Path, caption_type: str, caption_length: Union[str, int], extra_options: list[str], name_input: str, custom_prompt: str,
max_new_tokens: int, top_p: float, temperature: float, batch_size: int, models: tuple):
output_dir.mkdir(parents=True, exist_ok=True)
image_files = [f for f in input_dir.iterdir() if f.suffix.lower() in IMAGE_EXTENSIONS]
images_to_process = [f for f in image_files if not (output_dir / f"{f.stem}.txt").exists()]
if not images_to_process:
print("No new images to process.")
return
with tqdm(total=len(images_to_process), desc="Processing images", unit="image") as pbar:
for i in range(0, len(images_to_process), batch_size):
batch_files = images_to_process[i:i+batch_size]
batch_images = [Image.open(f).convert('RGB') for f in batch_files]
captions = stream_chat(batch_images, caption_type, caption_length, extra_options, name_input, custom_prompt,
max_new_tokens, top_p, temperature, batch_size, pbar, models)
for file, caption in zip(batch_files, captions):
with open(output_dir / f"{file.stem}.txt", 'w', encoding='utf-8') as f:
f.write(caption)
for img in batch_images:
img.close()
def parse_arguments():
parser = argparse.ArgumentParser(description="Process images and generate captions.")
parser.add_argument("input", nargs='+', help="Input image file or directory (or multiple directories)")
parser.add_argument("--output", help="Output directory (optional)")
parser.add_argument("--bs", type=int, default=4, help="Batch size (default: 4)")
parser.add_argument("--type", type=str, default="Descriptive",
choices=["Descriptive", "Descriptive (Informal)", "Training Prompt", "MidJourney", "Booru tag list", "Booru-like tag list", "Art Critic", "Product Listing", "Social Media Post"],
help='Caption Type (default: "Descriptive")')
parser.add_argument("--len", default="long",
choices=["any", "very short", "short", "medium-length", "long", "very long"] + [str(i) for i in range(20, 261, 10)],
help='Caption Length (default: "long")')
parser.add_argument("--extra", default=[], type=list[str], help='Extra Options',
choices=[
"If there is a person/character in the image you must refer to them as {name}.",
"Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).",
"Include information about lighting.",
"Include information about camera angle.",
"Include information about whether there is a watermark or not.",
"Include information about whether there are JPEG artifacts or not.",
"If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.",
"Do NOT include anything sexual; keep it PG.",
"Do NOT mention the image's resolution.",
"You MUST include information about the subjective aesthetic quality of the image from low to very high.",
"Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.",
"Do NOT mention any text that is in the image.",
"Specify the depth of field and whether the background is in focus or blurred.",
"If applicable, mention the likely use of artificial or natural lighting sources.",
"Do NOT use any ambiguous language.",
"Include whether the image is sfw, suggestive, or nsfw.",
"ONLY describe the most important elements of the image."
])
parser.add_argument("--name", type=str, default="", help='Person/Character Name (if applicable)')
parser.add_argument("--prompt", type=str, default="", help='Custom Prompt (optional, will override all other settings)')
parser.add_argument("--model", type=str, default=DEFAULT_MODEL_PATH,
help='Huggingface LLM repo (default: "unsloth/Meta-Llama-3.1-8B-bnb-4bit")')
parser.add_argument("--bf16", action="store_true", default=False, help="Use bfloat16 (default: NF4)")
parser.add_argument("--nolora", action="store_true", default=False, help="Disable VLM's custom text model (default: Enable)")
parser.add_argument("--tokens", type=int, default=300, help="Max tokens (default: 300)")
parser.add_argument("--topp", type=float, default=0.9, help="Top-P (default: 0.9)")
parser.add_argument("--temp", type=float, default=0.6, help="Temperature (default: 0.6)")
return parser.parse_args()
def is_valid_repo(repo_id):
from huggingface_hub import HfApi
import re
try:
if not re.fullmatch(r'^[^/,\s\"\']+/[^/,\s\"\']+$', repo_id): return False
api = HfApi()
if api.repo_exists(repo_id=repo_id): return True
else: return False
except Exception as e:
print(f"Failed to connect {repo_id}. {e}")
return False
def main():
global MODEL_PATH, IS_NF4, IS_LORA
args = parse_arguments()
input_paths = [Path(input_path) for input_path in args.input]
batch_size = args.bs
caption_type = args.type
caption_length = args.len
extra_options = args.extra
name_input = args.name
custom_prompt = args.prompt
max_new_tokens = args.tokens
top_p = args.topp
temperature = args.temp
IS_NF4 = False if args.bf16 else True
IS_LORA = False if args.nolora else True
if is_valid_repo(args.model): MODEL_PATH = args.model
else: sys.exit(1)
models = load_models()
for input_path in input_paths:
if input_path.is_file() and input_path.suffix.lower() in IMAGE_EXTENSIONS:
output_path = input_path.with_suffix('.txt')
print(f"Processing single image 🎞️: {input_path.name}")
with tqdm(total=1, desc="Processing image", unit="image") as pbar:
captions = stream_chat([Image.open(input_path).convert('RGB')], caption_type, caption_length, extra_options, name_input, custom_prompt,
max_new_tokens, top_p, temperature, 1, pbar, models)
with open(output_path, 'w', encoding='utf-8') as f:
f.write(captions[0])
print(f"Output saved to {output_path}")
elif input_path.is_dir():
output_path = Path(args.output) if args.output else input_path
print(f"Processing directory 📁: {input_path}")
print(f"Output directory 📦: {output_path}")
print(f"Batch size 🗄️: {batch_size}")
process_directory(input_path, output_path, caption_type, caption_length, extra_options, name_input, custom_prompt,
max_new_tokens, top_p, temperature, batch_size, models)
else:
print(f"Invalid input: {input_path}")
print("Skipping...")
if not input_paths:
print("Usage:")
print("For single image: python app.py [image_file] [--bs batch_size]")
print("For directory (same input/output): python app.py [directory] [--bs batch_size]")
print("For directory (separate input/output): python app.py [directory] --output [output_directory] [--bs batch_size]")
print("For multiple directories: python app.py [directory1] [directory2] ... [--output output_directory] [--bs batch_size]")
sys.exit(1)
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839wandb_project: joy-caption-1
device_batch_size: 2
batch_size: 256
learning_rate: 0.0002
warmup_samples: 18000
max_samples: 600000
save_every: 50000
test_every: 50000
use_amp: true
grad_scaler: true
lr_scheduler_type: cosine
min_lr_ratio: 0.0
allow_tf32: true
seed: 69
num_workers: 8
optimizer_type: adamw
adam_beta1: 0.9
adam_beta2: 0.999
adam_eps: 1.0e-08
adam_weight_decay: 0.0
clip_grad_norm: 1.0
dataset: fancyfeast/joy-captioning-20240924a
clip_model: google/siglip-so400m-patch14-384
text_model: ../lora-train/lora_model_vwbzycxh
resume: null
gradient_checkpointing: false
test_size: 2048
grad_scaler_init: 65536.0
max_caption_length: 257
num_image_tokens: 32
adapter_type: mlp
text_model_dtype: bfloat16
pre_test: false
train_image_model: true
image_model_lr: null
train_lora: true
lora_r: 64
lora_alpha: 16
lora_dropout: 0.1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202---
base_model: unsloth/Meta-Llama-3.1-8B-Instruct
library_name: peft
---
# Model Card for Model ID
<!-- Provide a quick summary of what the model is/does. -->
## Model Details
### Model Description
<!-- Provide a longer summary of what this model is. -->
- **Developed by:** [More Information Needed]
- **Funded by [optional]:** [More Information Needed]
- **Shared by [optional]:** [More Information Needed]
- **Model type:** [More Information Needed]
- **Language(s) (NLP):** [More Information Needed]
- **License:** [More Information Needed]
- **Finetuned from model [optional]:** [More Information Needed]
### Model Sources [optional]
<!-- Provide the basic links for the model. -->
- **Repository:** [More Information Needed]
- **Paper [optional]:** [More Information Needed]
- **Demo [optional]:** [More Information Needed]
## Uses
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
### Direct Use
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
[More Information Needed]
### Downstream Use [optional]
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
[More Information Needed]
### Out-of-Scope Use
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
[More Information Needed]
## Bias, Risks, and Limitations
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
[More Information Needed]
### Recommendations
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
## How to Get Started with the Model
Use the code below to get started with the model.
[More Information Needed]
## Training Details
### Training Data
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
[More Information Needed]
### Training Procedure
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
#### Preprocessing [optional]
[More Information Needed]
#### Training Hyperparameters
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
#### Speeds, Sizes, Times [optional]
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
[More Information Needed]
## Evaluation
<!-- This section describes the evaluation protocols and provides the results. -->
### Testing Data, Factors & Metrics
#### Testing Data
<!-- This should link to a Dataset Card if possible. -->
[More Information Needed]
#### Factors
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
[More Information Needed]
#### Metrics
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
[More Information Needed]
### Results
[More Information Needed]
#### Summary
## Model Examination [optional]
<!-- Relevant interpretability work for the model goes here -->
[More Information Needed]
## Environmental Impact
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
- **Hardware Type:** [More Information Needed]
- **Hours used:** [More Information Needed]
- **Cloud Provider:** [More Information Needed]
- **Compute Region:** [More Information Needed]
- **Carbon Emitted:** [More Information Needed]
## Technical Specifications [optional]
### Model Architecture and Objective
[More Information Needed]
### Compute Infrastructure
[More Information Needed]
#### Hardware
[More Information Needed]
#### Software
[More Information Needed]
## Citation [optional]
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
**BibTeX:**
[More Information Needed]
**APA:**
[More Information Needed]
## Glossary [optional]
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
[More Information Needed]
## More Information [optional]
[More Information Needed]
## Model Card Authors [optional]
[More Information Needed]
## Model Card Contact
[More Information Needed]
### Framework versions
- PEFT 0.12.012345678910111213141516171819202122232425262728293031323334{
"alpha_pattern": {},
"auto_mapping": null,
"base_model_name_or_path": "unsloth/Meta-Llama-3.1-8B-Instruct",
"bias": "none",
"fan_in_fan_out": false,
"inference_mode": true,
"init_lora_weights": true,
"layer_replication": null,
"layers_pattern": null,
"layers_to_transform": null,
"loftq_config": {},
"lora_alpha": 16,
"lora_dropout": 0,
"megatron_config": null,
"megatron_core": "megatron.core",
"modules_to_save": null,
"peft_type": "LORA",
"r": 64,
"rank_pattern": {},
"revision": null,
"target_modules": [
"q_proj",
"v_proj",
"gate_proj",
"down_proj",
"o_proj",
"k_proj",
"up_proj"
],
"task_type": "CAUSAL_LM",
"use_dora": false,
"use_rslora": false
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "id": "ZgkQ4kDil23W" }, "outputs": [], "source": [ "!git clone https://huggingface.co/John6666/joy-caption-alpha-two-cli-mod/\n", "!pip install -r /content/joy-caption-alpha-two-cli-mod/requirements.txt\n", "!pip install bitsandbytes triton\n", "!pip install accelerate==0.30.1\n", "!python /content/joy-caption-alpha-two-cli-mod/app.py" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "gPwD8BVsnU7p" }, "outputs": [], "source": [ "!python /content/joy-caption-alpha-two-cli-mod/app.py" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "T4", "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 0}12345678910huggingface_hub>=0.23.4
accelerate
torch
transformers==4.44.0
sentencepiece
bitsandbytes
Pillow
protobuf
peft==0.12.0
torchvision123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340# 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)
12345678910111213{ "_from_model_config": true, "bos_token_id": 0, "decoder_start_token_id": 2, "early_stopping": true, "eos_token_id": 2, "forced_bos_token_id": 0, "forced_eos_token_id": 2, "no_repeat_ngram_size": 3, "num_beams": 3, "pad_token_id": 1, "transformers_version": "4.44.2"}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_dict1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071---license: mit---# Florence-2-large-PromptGen v2.0This upgrade is based on PromptGen 1.5 with some new features to the model:
## Features:* Improved caption quality for \<GENERATE_TAGS\>, \<DETAILED_CAPTION\> and \<MORE_DETAILED_CAPTION\>. <img style="width:100%; hight:100%" src="https://msdn.miaoshouai.com/miaoshou/bo/2024-11-05_03-15-15.png" /> <img style="width:100%; hight:100%" src="https://msdn.miaoshouai.com/miaoshou/bo/2024-11-05_03-40-29.png" />* A new \<ANALYZE\> instruction, which helps the model to better understands the image composition of the input image. <img style="width:100%; hight:100%" src="https://msdn.miaoshouai.com/miaoshou/bo/2024-11-05_03-42-58.png" /> <img style="width:100%; hight:100%" src="https://msdn.miaoshouai.com/miaoshou/bo/2024-11-05_07-42-36.png" />* Memory efficient compare to other models! This is a really light weight caption model that allows you to use a little more than 1G of VRAM and produce lightening fast and high quality image captions. <img style="width:100%; hight:100%" src="https://msdn.miaoshouai.com/miaoshou/bo/2024-09-05_12-56-39.png" />* Designed to handle image captions for Flux model for both T5XXL CLIP and CLIP_L, the Miaoshou Tagger new node called "Flux CLIP Text Encode" which eliminates the need to run two separate tagger tools for caption creation. You can easily populate both CLIPs in a single generation, significantly boosting speed when working with Flux models. <img style="width:100%; hight:100%" src="https://msdn.miaoshouai.com/miaoshou/bo/2024-09-05_14-11-02.png" /> ## Instruction prompt:\<GENERATE_TAGS\> generate prompt as danbooru style tags<br>\<CAPTION\> a one line caption for the image<br>\<DETAILED_CAPTION\> a structured caption format which detects the position of the subjects in the image<br>\<MORE_DETAILED_CAPTION\> a very detailed description for the image<br>\<ANALYZE\> image composition analysis mode<br>\<MIXED_CAPTION\> a mixed caption style of more detailed caption and tags, this is extremely useful for FLUX model when using T5XXL and CLIP_L together. A new node in MiaoshouTagger ComfyUI is added to support this instruction.<br>\<MIXED_CAPTION_PLUS\> Combine the power of mixed caption with analyze.<br>
## Version History:For version 2.0, you will notice the following1. \<ANALYZE\> along with a beta node in ComfyUI for partial image analysis2. A new instruction for \<MIXED_CAPTION_PLUS\>3. A much improve accuracy for \<GENERATE_TAGS\>, \<DETAILED_CAPTION\> and \<MORE_DETAILED_CAPTION\>
## How to use:
To use this model, you can load it directly from the Hugging Face Model Hub:
```python
model = AutoModelForCausalLM.from_pretrained("MiaoshouAI/Florence-2-large-PromptGen-v2.0", trust_remote_code=True)processor = AutoProcessor.from_pretrained("MiaoshouAI/Florence-2-large-PromptGen-v2.0", trust_remote_code=True)
prompt = "<MORE_DETAILED_CAPTION>"
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg?download=true"image = Image.open(requests.get(url, stream=True).raw)
inputs = processor(text=prompt, images=image, return_tensors="pt").to(device)
generated_ids = model.generate( input_ids=inputs["input_ids"], pixel_values=inputs["pixel_values"], max_new_tokens=1024, do_sample=False, num_beams=3)generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
parsed_answer = processor.post_process_generation(generated_text, task=prompt, image_size=(image.width, image.height))
print(parsed_answer)```
## Use under MiaoshouAI Tagger ComfyUIIf you just want to use this model, you can use it under ComfyUI-Miaoshouai-Tagger
https://github.com/miaoshouai/ComfyUI-Miaoshouai-Tagger
A detailed use and install instruction is already there.(If you have already installed MiaoshouAI Tagger, you need to update the node in ComfyUI Manager first or use git pull to get the latest update.)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026{ "</cap>": 51270, "</dcap>": 51274, "</grounding>": 51276, "</ncap>": 51272, "</ocr>": 50268, "</od>": 50266, "</poly>": 51287, "</proposal>": 51285, "</region_cap>": 51281, "</region_to_desciption>": 51283, "</seg>": 51278, "<and>": 51288, "<cap>": 51269, "<dcap>": 51273, "<grounding>": 51275, "<loc_0>": 50269, "<loc_100>": 50369, "<loc_101>": 50370, "<loc_102>": 50371, "<loc_103>": 50372, "<loc_104>": 50373, "<loc_105>": 50374, "<loc_106>": 50375, "<loc_107>": 50376, "<loc_108>": 50377, "<loc_109>": 50378, "<loc_10>": 50279, "<loc_110>": 50379, "<loc_111>": 50380, "<loc_112>": 50381, "<loc_113>": 50382, "<loc_114>": 50383, "<loc_115>": 50384, "<loc_116>": 50385, "<loc_117>": 50386, "<loc_118>": 50387, "<loc_119>": 50388, "<loc_11>": 50280, "<loc_120>": 50389, "<loc_121>": 50390, "<loc_122>": 50391, "<loc_123>": 50392, "<loc_124>": 50393, "<loc_125>": 50394, "<loc_126>": 50395, "<loc_127>": 50396, "<loc_128>": 50397, "<loc_129>": 50398, "<loc_12>": 50281, "<loc_130>": 50399, "<loc_131>": 50400, "<loc_132>": 50401, "<loc_133>": 50402, "<loc_134>": 50403, "<loc_135>": 50404, "<loc_136>": 50405, "<loc_137>": 50406, "<loc_138>": 50407, "<loc_139>": 50408, "<loc_13>": 50282, "<loc_140>": 50409, "<loc_141>": 50410, "<loc_142>": 50411, "<loc_143>": 50412, "<loc_144>": 50413, "<loc_145>": 50414, "<loc_146>": 50415, "<loc_147>": 50416, "<loc_148>": 50417, "<loc_149>": 50418, "<loc_14>": 50283, "<loc_150>": 50419, "<loc_151>": 50420, "<loc_152>": 50421, "<loc_153>": 50422, "<loc_154>": 50423, "<loc_155>": 50424, "<loc_156>": 50425, "<loc_157>": 50426, "<loc_158>": 50427, "<loc_159>": 50428, "<loc_15>": 50284, "<loc_160>": 50429, "<loc_161>": 50430, "<loc_162>": 50431, "<loc_163>": 50432, "<loc_164>": 50433, "<loc_165>": 50434, "<loc_166>": 50435, "<loc_167>": 50436, "<loc_168>": 50437, "<loc_169>": 50438, "<loc_16>": 50285, "<loc_170>": 50439, "<loc_171>": 50440, "<loc_172>": 50441, "<loc_173>": 50442, "<loc_174>": 50443, "<loc_175>": 50444, "<loc_176>": 50445, "<loc_177>": 50446, "<loc_178>": 50447, "<loc_179>": 50448, "<loc_17>": 50286, "<loc_180>": 50449, "<loc_181>": 50450, "<loc_182>": 50451, "<loc_183>": 50452, "<loc_184>": 50453, "<loc_185>": 50454, "<loc_186>": 50455, "<loc_187>": 50456, "<loc_188>": 50457, "<loc_189>": 50458, "<loc_18>": 50287, "<loc_190>": 50459, "<loc_191>": 50460, "<loc_192>": 50461, "<loc_193>": 50462, "<loc_194>": 50463, "<loc_195>": 50464, "<loc_196>": 50465, "<loc_197>": 50466, "<loc_198>": 50467, "<loc_199>": 50468, "<loc_19>": 50288, "<loc_1>": 50270, "<loc_200>": 50469, "<loc_201>": 50470, "<loc_202>": 50471, "<loc_203>": 50472, "<loc_204>": 50473, "<loc_205>": 50474, "<loc_206>": 50475, "<loc_207>": 50476, "<loc_208>": 50477, "<loc_209>": 50478, "<loc_20>": 50289, "<loc_210>": 50479, "<loc_211>": 50480, "<loc_212>": 50481, "<loc_213>": 50482, "<loc_214>": 50483, "<loc_215>": 50484, "<loc_216>": 50485, "<loc_217>": 50486, "<loc_218>": 50487, "<loc_219>": 50488, "<loc_21>": 50290, "<loc_220>": 50489, "<loc_221>": 50490, "<loc_222>": 50491, "<loc_223>": 50492, "<loc_224>": 50493, "<loc_225>": 50494, "<loc_226>": 50495, "<loc_227>": 50496, "<loc_228>": 50497, "<loc_229>": 50498, "<loc_22>": 50291, "<loc_230>": 50499, "<loc_231>": 50500, "<loc_232>": 50501, "<loc_233>": 50502, "<loc_234>": 50503, "<loc_235>": 50504, "<loc_236>": 50505, "<loc_237>": 50506, "<loc_238>": 50507, "<loc_239>": 50508, "<loc_23>": 50292, "<loc_240>": 50509, "<loc_241>": 50510, "<loc_242>": 50511, "<loc_243>": 50512, "<loc_244>": 50513, "<loc_245>": 50514, "<loc_246>": 50515, "<loc_247>": 50516, "<loc_248>": 50517, "<loc_249>": 50518, "<loc_24>": 50293, "<loc_250>": 50519, "<loc_251>": 50520, "<loc_252>": 50521, "<loc_253>": 50522, "<loc_254>": 50523, "<loc_255>": 50524, "<loc_256>": 50525, "<loc_257>": 50526, "<loc_258>": 50527, "<loc_259>": 50528, "<loc_25>": 50294, "<loc_260>": 50529, "<loc_261>": 50530, "<loc_262>": 50531, "<loc_263>": 50532, "<loc_264>": 50533, "<loc_265>": 50534, "<loc_266>": 50535, "<loc_267>": 50536, "<loc_268>": 50537, "<loc_269>": 50538, "<loc_26>": 50295, "<loc_270>": 50539, "<loc_271>": 50540, "<loc_272>": 50541, "<loc_273>": 50542, "<loc_274>": 50543, "<loc_275>": 50544, "<loc_276>": 50545, "<loc_277>": 50546, "<loc_278>": 50547, "<loc_279>": 50548, "<loc_27>": 50296, "<loc_280>": 50549, "<loc_281>": 50550, "<loc_282>": 50551, "<loc_283>": 50552, "<loc_284>": 50553, "<loc_285>": 50554, "<loc_286>": 50555, "<loc_287>": 50556, "<loc_288>": 50557, "<loc_289>": 50558, "<loc_28>": 50297, "<loc_290>": 50559, "<loc_291>": 50560, "<loc_292>": 50561, "<loc_293>": 50562, "<loc_294>": 50563, "<loc_295>": 50564, "<loc_296>": 50565, "<loc_297>": 50566, "<loc_298>": 50567, "<loc_299>": 50568, "<loc_29>": 50298, "<loc_2>": 50271, "<loc_300>": 50569, "<loc_301>": 50570, "<loc_302>": 50571, "<loc_303>": 50572, "<loc_304>": 50573, "<loc_305>": 50574, "<loc_306>": 50575, "<loc_307>": 50576, "<loc_308>": 50577, "<loc_309>": 50578, "<loc_30>": 50299, "<loc_310>": 50579, "<loc_311>": 50580, "<loc_312>": 50581, "<loc_313>": 50582, "<loc_314>": 50583, "<loc_315>": 50584, "<loc_316>": 50585, "<loc_317>": 50586, "<loc_318>": 50587, "<loc_319>": 50588, "<loc_31>": 50300, "<loc_320>": 50589, "<loc_321>": 50590, "<loc_322>": 50591, "<loc_323>": 50592, "<loc_324>": 50593, "<loc_325>": 50594, "<loc_326>": 50595, "<loc_327>": 50596, "<loc_328>": 50597, "<loc_329>": 50598, "<loc_32>": 50301, "<loc_330>": 50599, "<loc_331>": 50600, "<loc_332>": 50601, "<loc_333>": 50602, "<loc_334>": 50603, "<loc_335>": 50604, "<loc_336>": 50605, "<loc_337>": 50606, "<loc_338>": 50607, "<loc_339>": 50608, "<loc_33>": 50302, "<loc_340>": 50609, "<loc_341>": 50610, "<loc_342>": 50611, "<loc_343>": 50612, "<loc_344>": 50613, "<loc_345>": 50614, "<loc_346>": 50615, "<loc_347>": 50616, "<loc_348>": 50617, "<loc_349>": 50618, "<loc_34>": 50303, "<loc_350>": 50619, "<loc_351>": 50620, "<loc_352>": 50621, "<loc_353>": 50622, "<loc_354>": 50623, "<loc_355>": 50624, "<loc_356>": 50625, "<loc_357>": 50626, "<loc_358>": 50627, "<loc_359>": 50628, "<loc_35>": 50304, "<loc_360>": 50629, "<loc_361>": 50630, "<loc_362>": 50631, "<loc_363>": 50632, "<loc_364>": 50633, "<loc_365>": 50634, "<loc_366>": 50635, "<loc_367>": 50636, "<loc_368>": 50637, "<loc_369>": 50638, "<loc_36>": 50305, "<loc_370>": 50639, "<loc_371>": 50640, "<loc_372>": 50641, "<loc_373>": 50642, "<loc_374>": 50643, "<loc_375>": 50644, "<loc_376>": 50645, "<loc_377>": 50646, "<loc_378>": 50647, "<loc_379>": 50648, "<loc_37>": 50306, "<loc_380>": 50649, "<loc_381>": 50650, "<loc_382>": 50651, "<loc_383>": 50652, "<loc_384>": 50653, "<loc_385>": 50654, "<loc_386>": 50655, "<loc_387>": 50656, "<loc_388>": 50657, "<loc_389>": 50658, "<loc_38>": 50307, "<loc_390>": 50659, "<loc_391>": 50660, "<loc_392>": 50661, "<loc_393>": 50662, "<loc_394>": 50663, "<loc_395>": 50664, "<loc_396>": 50665, "<loc_397>": 50666, "<loc_398>": 50667, "<loc_399>": 50668, "<loc_39>": 50308, "<loc_3>": 50272, "<loc_400>": 50669, "<loc_401>": 50670, "<loc_402>": 50671, "<loc_403>": 50672, "<loc_404>": 50673, "<loc_405>": 50674, "<loc_406>": 50675, "<loc_407>": 50676, "<loc_408>": 50677, "<loc_409>": 50678, "<loc_40>": 50309, "<loc_410>": 50679, "<loc_411>": 50680, "<loc_412>": 50681, "<loc_413>": 50682, "<loc_414>": 50683, "<loc_415>": 50684, "<loc_416>": 50685, "<loc_417>": 50686, "<loc_418>": 50687, "<loc_419>": 50688, "<loc_41>": 50310, "<loc_420>": 50689, "<loc_421>": 50690, "<loc_422>": 50691, "<loc_423>": 50692, "<loc_424>": 50693, "<loc_425>": 50694, "<loc_426>": 50695, "<loc_427>": 50696, "<loc_428>": 50697, "<loc_429>": 50698, "<loc_42>": 50311, "<loc_430>": 50699, "<loc_431>": 50700, "<loc_432>": 50701, "<loc_433>": 50702, "<loc_434>": 50703, "<loc_435>": 50704, "<loc_436>": 50705, "<loc_437>": 50706, "<loc_438>": 50707, "<loc_439>": 50708, "<loc_43>": 50312, "<loc_440>": 50709, "<loc_441>": 50710, "<loc_442>": 50711, "<loc_443>": 50712, "<loc_444>": 50713, "<loc_445>": 50714, "<loc_446>": 50715, "<loc_447>": 50716, "<loc_448>": 50717, "<loc_449>": 50718, "<loc_44>": 50313, "<loc_450>": 50719, "<loc_451>": 50720, "<loc_452>": 50721, "<loc_453>": 50722, "<loc_454>": 50723, "<loc_455>": 50724, "<loc_456>": 50725, "<loc_457>": 50726, "<loc_458>": 50727, "<loc_459>": 50728, "<loc_45>": 50314, "<loc_460>": 50729, "<loc_461>": 50730, "<loc_462>": 50731, "<loc_463>": 50732, "<loc_464>": 50733, "<loc_465>": 50734, "<loc_466>": 50735, "<loc_467>": 50736, "<loc_468>": 50737, "<loc_469>": 50738, "<loc_46>": 50315, "<loc_470>": 50739, "<loc_471>": 50740, "<loc_472>": 50741, "<loc_473>": 50742, "<loc_474>": 50743, "<loc_475>": 50744, "<loc_476>": 50745, "<loc_477>": 50746, "<loc_478>": 50747, "<loc_479>": 50748, "<loc_47>": 50316, "<loc_480>": 50749, "<loc_481>": 50750, "<loc_482>": 50751, "<loc_483>": 50752, "<loc_484>": 50753, "<loc_485>": 50754, "<loc_486>": 50755, "<loc_487>": 50756, "<loc_488>": 50757, "<loc_489>": 50758, "<loc_48>": 50317, "<loc_490>": 50759, "<loc_491>": 50760, "<loc_492>": 50761, "<loc_493>": 50762, "<loc_494>": 50763, "<loc_495>": 50764, "<loc_496>": 50765, "<loc_497>": 50766, "<loc_498>": 50767, "<loc_499>": 50768, "<loc_49>": 50318, "<loc_4>": 50273, "<loc_500>": 50769, "<loc_501>": 50770, "<loc_502>": 50771, "<loc_503>": 50772, "<loc_504>": 50773, "<loc_505>": 50774, "<loc_506>": 50775, "<loc_507>": 50776, "<loc_508>": 50777, "<loc_509>": 50778, "<loc_50>": 50319, "<loc_510>": 50779, "<loc_511>": 50780, "<loc_512>": 50781, "<loc_513>": 50782, "<loc_514>": 50783, "<loc_515>": 50784, "<loc_516>": 50785, "<loc_517>": 50786, "<loc_518>": 50787, "<loc_519>": 50788, "<loc_51>": 50320, "<loc_520>": 50789, "<loc_521>": 50790, "<loc_522>": 50791, "<loc_523>": 50792, "<loc_524>": 50793, "<loc_525>": 50794, "<loc_526>": 50795, "<loc_527>": 50796, "<loc_528>": 50797, "<loc_529>": 50798, "<loc_52>": 50321, "<loc_530>": 50799, "<loc_531>": 50800, "<loc_532>": 50801, "<loc_533>": 50802, "<loc_534>": 50803, "<loc_535>": 50804, "<loc_536>": 50805, "<loc_537>": 50806, "<loc_538>": 50807, "<loc_539>": 50808, "<loc_53>": 50322, "<loc_540>": 50809, "<loc_541>": 50810, "<loc_542>": 50811, "<loc_543>": 50812, "<loc_544>": 50813, "<loc_545>": 50814, "<loc_546>": 50815, "<loc_547>": 50816, "<loc_548>": 50817, "<loc_549>": 50818, "<loc_54>": 50323, "<loc_550>": 50819, "<loc_551>": 50820, "<loc_552>": 50821, "<loc_553>": 50822, "<loc_554>": 50823, "<loc_555>": 50824, "<loc_556>": 50825, "<loc_557>": 50826, "<loc_558>": 50827, "<loc_559>": 50828, "<loc_55>": 50324, "<loc_560>": 50829, "<loc_561>": 50830, "<loc_562>": 50831, "<loc_563>": 50832, "<loc_564>": 50833, "<loc_565>": 50834, "<loc_566>": 50835, "<loc_567>": 50836, "<loc_568>": 50837, "<loc_569>": 50838, "<loc_56>": 50325, "<loc_570>": 50839, "<loc_571>": 50840, "<loc_572>": 50841, "<loc_573>": 50842, "<loc_574>": 50843, "<loc_575>": 50844, "<loc_576>": 50845, "<loc_577>": 50846, "<loc_578>": 50847, "<loc_579>": 50848, "<loc_57>": 50326, "<loc_580>": 50849, "<loc_581>": 50850, "<loc_582>": 50851, "<loc_583>": 50852, "<loc_584>": 50853, "<loc_585>": 50854, "<loc_586>": 50855, "<loc_587>": 50856, "<loc_588>": 50857, "<loc_589>": 50858, "<loc_58>": 50327, "<loc_590>": 50859, "<loc_591>": 50860, "<loc_592>": 50861, "<loc_593>": 50862, "<loc_594>": 50863, "<loc_595>": 50864, "<loc_596>": 50865, "<loc_597>": 50866, "<loc_598>": 50867, "<loc_599>": 50868, "<loc_59>": 50328, "<loc_5>": 50274, "<loc_600>": 50869, "<loc_601>": 50870, "<loc_602>": 50871, "<loc_603>": 50872, "<loc_604>": 50873, "<loc_605>": 50874, "<loc_606>": 50875, "<loc_607>": 50876, "<loc_608>": 50877, "<loc_609>": 50878, "<loc_60>": 50329, "<loc_610>": 50879, "<loc_611>": 50880, "<loc_612>": 50881, "<loc_613>": 50882, "<loc_614>": 50883, "<loc_615>": 50884, "<loc_616>": 50885, "<loc_617>": 50886, "<loc_618>": 50887, "<loc_619>": 50888, "<loc_61>": 50330, "<loc_620>": 50889, "<loc_621>": 50890, "<loc_622>": 50891, "<loc_623>": 50892, "<loc_624>": 50893, "<loc_625>": 50894, "<loc_626>": 50895, "<loc_627>": 50896, "<loc_628>": 50897, "<loc_629>": 50898, "<loc_62>": 50331, "<loc_630>": 50899, "<loc_631>": 50900, "<loc_632>": 50901, "<loc_633>": 50902, "<loc_634>": 50903, "<loc_635>": 50904, "<loc_636>": 50905, "<loc_637>": 50906, "<loc_638>": 50907, "<loc_639>": 50908, "<loc_63>": 50332, "<loc_640>": 50909, "<loc_641>": 50910, "<loc_642>": 50911, "<loc_643>": 50912, "<loc_644>": 50913, "<loc_645>": 50914, "<loc_646>": 50915, "<loc_647>": 50916, "<loc_648>": 50917, "<loc_649>": 50918, "<loc_64>": 50333, "<loc_650>": 50919, "<loc_651>": 50920, "<loc_652>": 50921, "<loc_653>": 50922, "<loc_654>": 50923, "<loc_655>": 50924, "<loc_656>": 50925, "<loc_657>": 50926, "<loc_658>": 50927, "<loc_659>": 50928, "<loc_65>": 50334, "<loc_660>": 50929, "<loc_661>": 50930, "<loc_662>": 50931, "<loc_663>": 50932, "<loc_664>": 50933, "<loc_665>": 50934, "<loc_666>": 50935, "<loc_667>": 50936, "<loc_668>": 50937, "<loc_669>": 50938, "<loc_66>": 50335, "<loc_670>": 50939, "<loc_671>": 50940, "<loc_672>": 50941, "<loc_673>": 50942, "<loc_674>": 50943, "<loc_675>": 50944, "<loc_676>": 50945, "<loc_677>": 50946, "<loc_678>": 50947, "<loc_679>": 50948, "<loc_67>": 50336, "<loc_680>": 50949, "<loc_681>": 50950, "<loc_682>": 50951, "<loc_683>": 50952, "<loc_684>": 50953, "<loc_685>": 50954, "<loc_686>": 50955, "<loc_687>": 50956, "<loc_688>": 50957, "<loc_689>": 50958, "<loc_68>": 50337, "<loc_690>": 50959, "<loc_691>": 50960, "<loc_692>": 50961, "<loc_693>": 50962, "<loc_694>": 50963, "<loc_695>": 50964, "<loc_696>": 50965, "<loc_697>": 50966, "<loc_698>": 50967, "<loc_699>": 50968, "<loc_69>": 50338, "<loc_6>": 50275, "<loc_700>": 50969, "<loc_701>": 50970, "<loc_702>": 50971, "<loc_703>": 50972, "<loc_704>": 50973, "<loc_705>": 50974, "<loc_706>": 50975, "<loc_707>": 50976, "<loc_708>": 50977, "<loc_709>": 50978, "<loc_70>": 50339, "<loc_710>": 50979, "<loc_711>": 50980, "<loc_712>": 50981, "<loc_713>": 50982, "<loc_714>": 50983, "<loc_715>": 50984, "<loc_716>": 50985, "<loc_717>": 50986, "<loc_718>": 50987, "<loc_719>": 50988, "<loc_71>": 50340, "<loc_720>": 50989, "<loc_721>": 50990, "<loc_722>": 50991, "<loc_723>": 50992, "<loc_724>": 50993, "<loc_725>": 50994, "<loc_726>": 50995, "<loc_727>": 50996, "<loc_728>": 50997, "<loc_729>": 50998, "<loc_72>": 50341, "<loc_730>": 50999, "<loc_731>": 51000, "<loc_732>": 51001, "<loc_733>": 51002, "<loc_734>": 51003, "<loc_735>": 51004, "<loc_736>": 51005, "<loc_737>": 51006, "<loc_738>": 51007, "<loc_739>": 51008, "<loc_73>": 50342, "<loc_740>": 51009, "<loc_741>": 51010, "<loc_742>": 51011, "<loc_743>": 51012, "<loc_744>": 51013, "<loc_745>": 51014, "<loc_746>": 51015, "<loc_747>": 51016, "<loc_748>": 51017, "<loc_749>": 51018, "<loc_74>": 50343, "<loc_750>": 51019, "<loc_751>": 51020, "<loc_752>": 51021, "<loc_753>": 51022, "<loc_754>": 51023, "<loc_755>": 51024, "<loc_756>": 51025, "<loc_757>": 51026, "<loc_758>": 51027, "<loc_759>": 51028, "<loc_75>": 50344, "<loc_760>": 51029, "<loc_761>": 51030, "<loc_762>": 51031, "<loc_763>": 51032, "<loc_764>": 51033, "<loc_765>": 51034, "<loc_766>": 51035, "<loc_767>": 51036, "<loc_768>": 51037, "<loc_769>": 51038, "<loc_76>": 50345, "<loc_770>": 51039, "<loc_771>": 51040, "<loc_772>": 51041, "<loc_773>": 51042, "<loc_774>": 51043, "<loc_775>": 51044, "<loc_776>": 51045, "<loc_777>": 51046, "<loc_778>": 51047, "<loc_779>": 51048, "<loc_77>": 50346, "<loc_780>": 51049, "<loc_781>": 51050, "<loc_782>": 51051, "<loc_783>": 51052, "<loc_784>": 51053, "<loc_785>": 51054, "<loc_786>": 51055, "<loc_787>": 51056, "<loc_788>": 51057, "<loc_789>": 51058, "<loc_78>": 50347, "<loc_790>": 51059, "<loc_791>": 51060, "<loc_792>": 51061, "<loc_793>": 51062, "<loc_794>": 51063, "<loc_795>": 51064, "<loc_796>": 51065, "<loc_797>": 51066, "<loc_798>": 51067, "<loc_799>": 51068, "<loc_79>": 50348, "<loc_7>": 50276, "<loc_800>": 51069, "<loc_801>": 51070, "<loc_802>": 51071, "<loc_803>": 51072, "<loc_804>": 51073, "<loc_805>": 51074, "<loc_806>": 51075, "<loc_807>": 51076, "<loc_808>": 51077, "<loc_809>": 51078, "<loc_80>": 50349, "<loc_810>": 51079, "<loc_811>": 51080, "<loc_812>": 51081, "<loc_813>": 51082, "<loc_814>": 51083, "<loc_815>": 51084, "<loc_816>": 51085, "<loc_817>": 51086, "<loc_818>": 51087, "<loc_819>": 51088, "<loc_81>": 50350, "<loc_820>": 51089, "<loc_821>": 51090, "<loc_822>": 51091, "<loc_823>": 51092, "<loc_824>": 51093, "<loc_825>": 51094, "<loc_826>": 51095, "<loc_827>": 51096, "<loc_828>": 51097, "<loc_829>": 51098, "<loc_82>": 50351, "<loc_830>": 51099, "<loc_831>": 51100, "<loc_832>": 51101, "<loc_833>": 51102, "<loc_834>": 51103, "<loc_835>": 51104, "<loc_836>": 51105, "<loc_837>": 51106, "<loc_838>": 51107, "<loc_839>": 51108, "<loc_83>": 50352, "<loc_840>": 51109, "<loc_841>": 51110, "<loc_842>": 51111, "<loc_843>": 51112, "<loc_844>": 51113, "<loc_845>": 51114, "<loc_846>": 51115, "<loc_847>": 51116, "<loc_848>": 51117, "<loc_849>": 51118, "<loc_84>": 50353, "<loc_850>": 51119, "<loc_851>": 51120, "<loc_852>": 51121, "<loc_853>": 51122, "<loc_854>": 51123, "<loc_855>": 51124, "<loc_856>": 51125, "<loc_857>": 51126, "<loc_858>": 51127, "<loc_859>": 51128, "<loc_85>": 50354, "<loc_860>": 51129, "<loc_861>": 51130, "<loc_862>": 51131, "<loc_863>": 51132, "<loc_864>": 51133, "<loc_865>": 51134, "<loc_866>": 51135, "<loc_867>": 51136, "<loc_868>": 51137, "<loc_869>": 51138, "<loc_86>": 50355, "<loc_870>": 51139, "<loc_871>": 51140, "<loc_872>": 51141, "<loc_873>": 51142, "<loc_874>": 51143, "<loc_875>": 51144, "<loc_876>": 51145, "<loc_877>": 51146, "<loc_878>": 51147, "<loc_879>": 51148, "<loc_87>": 50356, "<loc_880>": 51149, "<loc_881>": 51150, "<loc_882>": 51151, "<loc_883>": 51152, "<loc_884>": 51153, "<loc_885>": 51154, "<loc_886>": 51155, "<loc_887>": 51156, "<loc_888>": 51157, "<loc_889>": 51158, "<loc_88>": 50357, "<loc_890>": 51159, "<loc_891>": 51160, "<loc_892>": 51161, "<loc_893>": 51162, "<loc_894>": 51163, "<loc_895>": 51164, "<loc_896>": 51165, "<loc_897>": 51166, "<loc_898>": 51167, "<loc_899>": 51168, "<loc_89>": 50358, "<loc_8>": 50277, "<loc_900>": 51169, "<loc_901>": 51170, "<loc_902>": 51171, "<loc_903>": 51172, "<loc_904>": 51173, "<loc_905>": 51174, "<loc_906>": 51175, "<loc_907>": 51176, "<loc_908>": 51177, "<loc_909>": 51178, "<loc_90>": 50359, "<loc_910>": 51179, "<loc_911>": 51180, "<loc_912>": 51181, "<loc_913>": 51182, "<loc_914>": 51183, "<loc_915>": 51184, "<loc_916>": 51185, "<loc_917>": 51186, "<loc_918>": 51187, "<loc_919>": 51188, "<loc_91>": 50360, "<loc_920>": 51189, "<loc_921>": 51190, "<loc_922>": 51191, "<loc_923>": 51192, "<loc_924>": 51193, "<loc_925>": 51194, "<loc_926>": 51195, "<loc_927>": 51196, "<loc_928>": 51197, "<loc_929>": 51198, "<loc_92>": 50361, "<loc_930>": 51199, "<loc_931>": 51200, "<loc_932>": 51201, "<loc_933>": 51202, "<loc_934>": 51203, "<loc_935>": 51204, "<loc_936>": 51205, "<loc_937>": 51206, "<loc_938>": 51207, "<loc_939>": 51208, "<loc_93>": 50362, "<loc_940>": 51209, "<loc_941>": 51210, "<loc_942>": 51211, "<loc_943>": 51212, "<loc_944>": 51213, "<loc_945>": 51214, "<loc_946>": 51215, "<loc_947>": 51216, "<loc_948>": 51217, "<loc_949>": 51218, "<loc_94>": 50363, "<loc_950>": 51219, "<loc_951>": 51220, "<loc_952>": 51221, "<loc_953>": 51222, "<loc_954>": 51223, "<loc_955>": 51224, "<loc_956>": 51225, "<loc_957>": 51226, "<loc_958>": 51227, "<loc_959>": 51228, "<loc_95>": 50364, "<loc_960>": 51229, "<loc_961>": 51230, "<loc_962>": 51231, "<loc_963>": 51232, "<loc_964>": 51233, "<loc_965>": 51234, "<loc_966>": 51235, "<loc_967>": 51236, "<loc_968>": 51237, "<loc_969>": 51238, "<loc_96>": 50365, "<loc_970>": 51239, "<loc_971>": 51240, "<loc_972>": 51241, "<loc_973>": 51242, "<loc_974>": 51243, "<loc_975>": 51244, "<loc_976>": 51245, "<loc_977>": 51246, "<loc_978>": 51247, "<loc_979>": 51248, "<loc_97>": 50366, "<loc_980>": 51249, "<loc_981>": 51250, "<loc_982>": 51251, "<loc_983>": 51252, "<loc_984>": 51253, "<loc_985>": 51254, "<loc_986>": 51255, "<loc_987>": 51256, "<loc_988>": 51257, "<loc_989>": 51258, "<loc_98>": 50367, "<loc_990>": 51259, "<loc_991>": 51260, "<loc_992>": 51261, "<loc_993>": 51262, "<loc_994>": 51263, "<loc_995>": 51264, "<loc_996>": 51265, "<loc_997>": 51266, "<loc_998>": 51267, "<loc_999>": 51268, "<loc_99>": 50368, "<loc_9>": 50278, "<ncap>": 51271, "<ocr>": 50267, "<od>": 50265, "<poly>": 51286, "<proposal>": 51284, "<region_cap>": 51280, "<region_to_desciption>": 51282, "<seg>": 51277, "<sep>": 51279}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138{ "_name_or_path": "microsoft/Florence-2-large", "architectures": [ "Florence2ForConditionalGeneration" ], "auto_map": { "AutoConfig": "configuration_florence2.Florence2Config", "AutoModelForCausalLM": "modeling_florence2.Florence2ForConditionalGeneration" }, "bos_token_id": 0, "eos_token_id": 2, "ignore_index": -100, "is_encoder_decoder": true, "model_type": "florence2", "pad_token_id": 1, "projection_dim": 1024, "text_config": { "_attn_implementation_autoset": true, "_name_or_path": "", "activation_dropout": 0.1, "activation_function": "gelu", "add_bias_logits": false, "add_cross_attention": false, "add_final_layer_norm": false, "architectures": null, "attention_dropout": 0.1, "bad_words_ids": null, "begin_suppress_tokens": null, "bos_token_id": 0, "chunk_size_feed_forward": 0, "classif_dropout": 0.1, "classifier_dropout": 0.0, "cross_attention_hidden_size": null, "d_model": 1024, "decoder_attention_heads": 16, "decoder_ffn_dim": 4096, "decoder_layerdrop": 0.0, "decoder_layers": 12, "decoder_start_token_id": 2, "diversity_penalty": 0.0, "do_sample": false, "dropout": 0.1, "early_stopping": true, "encoder_attention_heads": 16, "encoder_ffn_dim": 4096, "encoder_layerdrop": 0.0, "encoder_layers": 12, "encoder_no_repeat_ngram_size": 0, "eos_token_id": 2, "exponential_decay_length_penalty": null, "finetuning_task": null, "forced_bos_token_id": 0, "forced_eos_token_id": 2, "gradient_checkpointing": false, "id2label": { "0": "LABEL_0", "1": "LABEL_1", "2": "LABEL_2" }, "init_std": 0.02, "is_decoder": false, "is_encoder_decoder": true, "label2id": { "LABEL_0": 0, "LABEL_1": 1, "LABEL_2": 2 }, "length_penalty": 1.0, "max_length": 20, "max_position_embeddings": 1024, "min_length": 0, "model_type": "florence2_language", "no_repeat_ngram_size": 3, "normalize_before": false, "num_beam_groups": 1, "num_beams": 3, "num_hidden_layers": 12, "num_return_sequences": 1, "output_attentions": false, "output_hidden_states": false, "output_scores": false, "pad_token_id": 1, "prefix": null, "problem_type": null, "pruned_heads": {}, "remove_invalid_values": false, "repetition_penalty": 1.0, "return_dict": true, "return_dict_in_generate": false, "scale_embedding": false, "sep_token_id": null, "suppress_tokens": null, "task_specific_params": null, "temperature": 1.0, "tf_legacy_loss": false, "tie_encoder_decoder": false, "tie_word_embeddings": true, "tokenizer_class": null, "top_k": 50, "top_p": 1.0, "torch_dtype": null, "torchscript": false, "typical_p": 1.0, "use_bfloat16": false, "use_cache": true, "vocab_size": 51289 }, "torch_dtype": "float32", "transformers_version": "4.46.1", "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": [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": { "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)
1234{ "num_beams": 3, "transformers_version": "4.46.1"}123456789101112131415161718192021222324252627282930313233{ "auto_map": { "AutoProcessor": "processing_florence2.Florence2Processor" }, "crop_size": { "height": 768, "width": 768 }, "do_center_crop": false, "do_convert_rgb": null, "do_normalize": true, "do_rescale": true, "do_resize": true, "image_mean": [ 0.485, 0.456, 0.406 ], "image_processor_type": "CLIPImageProcessor", "image_seq_length": 577, "image_std": [ 0.229, 0.224, 0.225 ], "processor_class": "Florence2Processor", "resample": 3, "rescale_factor": 0.00392156862745098, "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): r""" 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_dict123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155---license: llama3.1model-index:- name: Llama-3.1-8B-Lexi-Uncensored-V2 results: - task: type: text-generation name: Text Generation dataset: name: IFEval (0-Shot) type: HuggingFaceH4/ifeval args: num_few_shot: 0 metrics: - type: inst_level_strict_acc and prompt_level_strict_acc value: 77.92 name: strict accuracy source: url: https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard?query=Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2 name: Open LLM Leaderboard - task: type: text-generation name: Text Generation dataset: name: BBH (3-Shot) type: BBH args: num_few_shot: 3 metrics: - type: acc_norm value: 29.69 name: normalized accuracy source: url: https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard?query=Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2 name: Open LLM Leaderboard - task: type: text-generation name: Text Generation dataset: name: MATH Lvl 5 (4-Shot) type: hendrycks/competition_math args: num_few_shot: 4 metrics: - type: exact_match value: 16.92 name: exact match source: url: https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard?query=Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2 name: Open LLM Leaderboard - task: type: text-generation name: Text Generation dataset: name: GPQA (0-shot) type: Idavidrein/gpqa args: num_few_shot: 0 metrics: - type: acc_norm value: 4.36 name: acc_norm source: url: https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard?query=Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2 name: Open LLM Leaderboard - task: type: text-generation name: Text Generation dataset: name: MuSR (0-shot) type: TAUR-Lab/MuSR args: num_few_shot: 0 metrics: - type: acc_norm value: 7.77 name: acc_norm source: url: https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard?query=Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2 name: Open LLM Leaderboard - task: type: text-generation name: Text Generation dataset: name: MMLU-PRO (5-shot) type: TIGER-Lab/MMLU-Pro config: main split: test args: num_few_shot: 5 metrics: - type: acc value: 30.9 name: accuracy source: url: https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard?query=Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2 name: Open LLM Leaderboardlibrary_name: transformers---

VERSION 2 Update Notes:---- More compliant- Smarter- For best response, use this system prompt (feel free to expand upon it as you wish):
Think step by step with a logical reasoning and intellectual sense before you provide any response.
- For more uncensored and compliant response, you can expand the system message differently, or simply enter a dot "." as system message.
- IMPORTANT: Upon further investigation, the Q4 seems to have refusal issues sometimes. There seems to be some of the fine-tune loss happening due to the quantization. I will look into it for V3. Until then, I suggest you run F16 or Q8 if possible.

GENERAL INFO:---
This model is based on Llama-3.1-8b-Instruct, and is governed by [META LLAMA 3.1 COMMUNITY LICENSE AGREEMENT](https://github.com/meta-llama/llama-models/blob/main/models/llama3_1/LICENSE)
Lexi is uncensored, which makes the model compliant. You are advised to implement your own alignment layer before exposing the model as a service. It will be highly compliant with any requests, even unethical ones.
You are responsible for any content you create using this model. Please use it responsibly.
Lexi is licensed according to Meta's Llama license. I grant permission for any use, including commercial, that falls within accordance with Meta's Llama-3.1 license.
IMPORTANT:---Use the same template as the official Llama 3.1 8B instruct.System tokens must be present during inference, even if you set an empty system message. If you are unsure, just add a short system message as you wish.
FEEDBACK:---If you find any issues or have suggestions for improvements, feel free to leave a review and I will look into it for upcoming improvements and next version.

# [Open LLM Leaderboard Evaluation Results](https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard)Detailed results can be found [here](https://huggingface.co/datasets/open-llm-leaderboard/details_Orenguteng__Llama-3.1-8B-Lexi-Uncensored-V2)
| Metric |Value||-------------------|----:||Avg. |27.93||IFEval (0-Shot) |77.92||BBH (3-Shot) |29.69||MATH Lvl 5 (4-Shot)|16.92||GPQA (0-shot) | 4.36||MuSR (0-shot) | 7.77||MMLU-PRO (5-shot) |30.90|
1234567891011121314151617181920212223242526272829303132333435363738394041{ "_name_or_path": "unsloth/meta-llama-3.1-8b-instruct", "architectures": [ "LlamaForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "bos_token_id": 128000, "eos_token_id": [ 128001, 128008, 128009 ], "hidden_act": "silu", "hidden_size": 4096, "initializer_range": 0.02, "intermediate_size": 14336, "max_position_embeddings": 131072, "mlp_bias": false, "model_type": "llama", "num_attention_heads": 32, "num_hidden_layers": 32, "num_key_value_heads": 8, "pad_token_id": 128004, "pretraining_tp": 1, "rms_norm_eps": 1e-05, "rope_scaling": { "factor": 8.0, "high_freq_factor": 4.0, "low_freq_factor": 1.0, "original_max_position_embeddings": 8192, "rope_type": "llama3" }, "rope_theta": 500000.0, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.44.0.dev0", "unsloth_version": "2024.8", "use_cache": true, "vocab_size": 128256}1234567891011121314{ "bos_token_id": 128000, "do_sample": true, "eos_token_id": [ 128001, 128008, 128009 ], "max_length": 131072, "pad_token_id": 128004, "temperature": 0.6, "top_p": 0.9, "transformers_version": "4.44.0.dev0"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298{ "metadata": { "total_size": 16060522496 }, "weight_map": { "lm_head.weight": "model-00004-of-00004.safetensors", "model.embed_tokens.weight": "model-00001-of-00004.safetensors", "model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors", "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors", "model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors", "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors", "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors", "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors", "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors", "model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors", "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors", "model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors", "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors", "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors", "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors", "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors", "model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors", "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00004.safetensors", "model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors", "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00004.safetensors", "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors", "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors", "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00004.safetensors", "model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors", "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors", "model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors", "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors", "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors", "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors", "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors", "model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors", "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors", "model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors", "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors", "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors", "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors", "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors", "model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors", "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors", "model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors", "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors", "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors", "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors", "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors", "model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors", "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors", "model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors", "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors", "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors", "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors", "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors", "model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors", "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors", "model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors", "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors", "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors", "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors", "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors", "model.layers.16.input_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.16.mlp.down_proj.weight": "model-00002-of-00004.safetensors", "model.layers.16.mlp.gate_proj.weight": "model-00002-of-00004.safetensors", "model.layers.16.mlp.up_proj.weight": "model-00002-of-00004.safetensors", "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors", "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors", "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors", "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors", "model.layers.17.input_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.17.mlp.down_proj.weight": "model-00002-of-00004.safetensors", "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00004.safetensors", "model.layers.17.mlp.up_proj.weight": "model-00002-of-00004.safetensors", "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00004.safetensors", "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00004.safetensors", "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00004.safetensors", "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00004.safetensors", "model.layers.18.input_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.18.mlp.down_proj.weight": "model-00002-of-00004.safetensors", "model.layers.18.mlp.gate_proj.weight": "model-00002-of-00004.safetensors", "model.layers.18.mlp.up_proj.weight": "model-00002-of-00004.safetensors", "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00004.safetensors", "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00004.safetensors", "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00004.safetensors", "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00004.safetensors", "model.layers.19.input_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.19.mlp.down_proj.weight": "model-00002-of-00004.safetensors", "model.layers.19.mlp.gate_proj.weight": "model-00002-of-00004.safetensors", "model.layers.19.mlp.up_proj.weight": "model-00002-of-00004.safetensors", "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.19.self_attn.k_proj.weight": "model-00002-of-00004.safetensors", "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00004.safetensors", "model.layers.19.self_attn.q_proj.weight": "model-00002-of-00004.safetensors", "model.layers.19.self_attn.v_proj.weight": "model-00002-of-00004.safetensors", "model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors", "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors", "model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors", "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors", "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors", "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors", "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors", "model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors", "model.layers.20.mlp.gate_proj.weight": "model-00002-of-00004.safetensors", "model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors", "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.20.self_attn.k_proj.weight": "model-00002-of-00004.safetensors", "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00004.safetensors", "model.layers.20.self_attn.q_proj.weight": "model-00002-of-00004.safetensors", "model.layers.20.self_attn.v_proj.weight": "model-00002-of-00004.safetensors", "model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors", "model.layers.21.mlp.gate_proj.weight": "model-00003-of-00004.safetensors", "model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors", "model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.21.self_attn.k_proj.weight": "model-00003-of-00004.safetensors", "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors", "model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors", "model.layers.21.self_attn.v_proj.weight": "model-00003-of-00004.safetensors", "model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors", "model.layers.22.mlp.gate_proj.weight": "model-00003-of-00004.safetensors", "model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors", "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.22.self_attn.k_proj.weight": "model-00003-of-00004.safetensors", "model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors", "model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors", "model.layers.22.self_attn.v_proj.weight": "model-00003-of-00004.safetensors", "model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors", "model.layers.23.mlp.gate_proj.weight": "model-00003-of-00004.safetensors", "model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors", "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.23.self_attn.k_proj.weight": "model-00003-of-00004.safetensors", "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors", "model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors", "model.layers.23.self_attn.v_proj.weight": "model-00003-of-00004.safetensors", "model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors", "model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors", "model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors", "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.24.self_attn.k_proj.weight": "model-00003-of-00004.safetensors", "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors", "model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors", "model.layers.24.self_attn.v_proj.weight": "model-00003-of-00004.safetensors", "model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors", "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors", "model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors", "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors", "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors", "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors", "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors", "model.layers.26.input_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.26.mlp.down_proj.weight": "model-00003-of-00004.safetensors", "model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors", "model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors", "model.layers.26.post_attention_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors", "model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors", "model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors", "model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors", "model.layers.27.input_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.27.mlp.down_proj.weight": "model-00003-of-00004.safetensors", "model.layers.27.mlp.gate_proj.weight": "model-00003-of-00004.safetensors", "model.layers.27.mlp.up_proj.weight": "model-00003-of-00004.safetensors", "model.layers.27.post_attention_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.27.self_attn.k_proj.weight": "model-00003-of-00004.safetensors", "model.layers.27.self_attn.o_proj.weight": "model-00003-of-00004.safetensors", "model.layers.27.self_attn.q_proj.weight": "model-00003-of-00004.safetensors", "model.layers.27.self_attn.v_proj.weight": "model-00003-of-00004.safetensors", "model.layers.28.input_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.28.mlp.down_proj.weight": "model-00003-of-00004.safetensors", "model.layers.28.mlp.gate_proj.weight": "model-00003-of-00004.safetensors", "model.layers.28.mlp.up_proj.weight": "model-00003-of-00004.safetensors", "model.layers.28.post_attention_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.28.self_attn.k_proj.weight": "model-00003-of-00004.safetensors", "model.layers.28.self_attn.o_proj.weight": "model-00003-of-00004.safetensors", "model.layers.28.self_attn.q_proj.weight": "model-00003-of-00004.safetensors", "model.layers.28.self_attn.v_proj.weight": "model-00003-of-00004.safetensors", "model.layers.29.input_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.29.mlp.down_proj.weight": "model-00003-of-00004.safetensors", "model.layers.29.mlp.gate_proj.weight": "model-00003-of-00004.safetensors", "model.layers.29.mlp.up_proj.weight": "model-00003-of-00004.safetensors", "model.layers.29.post_attention_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.29.self_attn.k_proj.weight": "model-00003-of-00004.safetensors", "model.layers.29.self_attn.o_proj.weight": "model-00003-of-00004.safetensors", "model.layers.29.self_attn.q_proj.weight": "model-00003-of-00004.safetensors", "model.layers.29.self_attn.v_proj.weight": "model-00003-of-00004.safetensors", "model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors", "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors", "model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors", "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors", "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors", "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors", "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors", "model.layers.30.input_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.30.mlp.down_proj.weight": "model-00003-of-00004.safetensors", "model.layers.30.mlp.gate_proj.weight": "model-00003-of-00004.safetensors", "model.layers.30.mlp.up_proj.weight": "model-00003-of-00004.safetensors", "model.layers.30.post_attention_layernorm.weight": "model-00003-of-00004.safetensors", "model.layers.30.self_attn.k_proj.weight": "model-00003-of-00004.safetensors", "model.layers.30.self_attn.o_proj.weight": "model-00003-of-00004.safetensors", "model.layers.30.self_attn.q_proj.weight": "model-00003-of-00004.safetensors", "model.layers.30.self_attn.v_proj.weight": "model-00003-of-00004.safetensors", "model.layers.31.input_layernorm.weight": "model-00004-of-00004.safetensors", "model.layers.31.mlp.down_proj.weight": "model-00004-of-00004.safetensors", "model.layers.31.mlp.gate_proj.weight": "model-00003-of-00004.safetensors", "model.layers.31.mlp.up_proj.weight": "model-00003-of-00004.safetensors", "model.layers.31.post_attention_layernorm.weight": "model-00004-of-00004.safetensors", "model.layers.31.self_attn.k_proj.weight": "model-00003-of-00004.safetensors", "model.layers.31.self_attn.o_proj.weight": "model-00003-of-00004.safetensors", "model.layers.31.self_attn.q_proj.weight": "model-00003-of-00004.safetensors", "model.layers.31.self_attn.v_proj.weight": "model-00003-of-00004.safetensors", "model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors", "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors", "model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors", "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors", "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors", "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors", "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors", "model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors", "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors", "model.layers.5.mlp.up_proj.weight": "model-00001-of-00004.safetensors", "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors", "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors", "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors", "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors", "model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors", "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00004.safetensors", "model.layers.6.mlp.up_proj.weight": "model-00001-of-00004.safetensors", "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00004.safetensors", "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors", "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00004.safetensors", "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00004.safetensors", "model.layers.7.input_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.7.mlp.down_proj.weight": "model-00001-of-00004.safetensors", "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00004.safetensors", "model.layers.7.mlp.up_proj.weight": "model-00001-of-00004.safetensors", "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00004.safetensors", "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00004.safetensors", "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00004.safetensors", "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00004.safetensors", "model.layers.8.input_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.8.mlp.down_proj.weight": "model-00001-of-00004.safetensors", "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00004.safetensors", "model.layers.8.mlp.up_proj.weight": "model-00001-of-00004.safetensors", "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00004.safetensors", "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00004.safetensors", "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00004.safetensors", "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00004.safetensors", "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00004.safetensors", "model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors", "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00004.safetensors", "model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors", "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors", "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00004.safetensors", "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors", "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors", "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00004.safetensors", "model.norm.weight": "model-00004-of-00004.safetensors" }}1234567891011121314151617181920212223{ "bos_token": { "content": "<|begin_of_text|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": { "content": "<|eot_id|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|finetune_right_pad_id|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064{ "added_tokens_decoder": { "128000": { "content": "<|begin_of_text|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128001": { "content": "<|end_of_text|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128002": { "content": "<|reserved_special_token_0|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128003": { "content": "<|reserved_special_token_1|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128004": { "content": "<|finetune_right_pad_id|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128005": { "content": "<|reserved_special_token_2|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128006": { "content": "<|start_header_id|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128007": { "content": "<|end_header_id|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128008": { "content": "<|eom_id|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128009": { "content": "<|eot_id|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128010": { "content": "<|python_tag|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128011": { "content": "<|reserved_special_token_3|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128012": { "content": "<|reserved_special_token_4|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128013": { "content": "<|reserved_special_token_5|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128014": { "content": "<|reserved_special_token_6|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128015": { "content": "<|reserved_special_token_7|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128016": { "content": "<|reserved_special_token_8|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128017": { "content": "<|reserved_special_token_9|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128018": { "content": "<|reserved_special_token_10|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128019": { "content": "<|reserved_special_token_11|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128020": { "content": "<|reserved_special_token_12|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128021": { "content": "<|reserved_special_token_13|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128022": { "content": "<|reserved_special_token_14|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128023": { "content": "<|reserved_special_token_15|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128024": { "content": "<|reserved_special_token_16|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128025": { "content": "<|reserved_special_token_17|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128026": { "content": "<|reserved_special_token_18|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128027": { "content": "<|reserved_special_token_19|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128028": { "content": "<|reserved_special_token_20|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128029": { "content": "<|reserved_special_token_21|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128030": { "content": "<|reserved_special_token_22|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128031": { "content": "<|reserved_special_token_23|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128032": { "content": "<|reserved_special_token_24|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128033": { "content": "<|reserved_special_token_25|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128034": { "content": "<|reserved_special_token_26|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128035": { "content": "<|reserved_special_token_27|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128036": { "content": "<|reserved_special_token_28|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128037": { "content": "<|reserved_special_token_29|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128038": { "content": "<|reserved_special_token_30|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128039": { "content": "<|reserved_special_token_31|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128040": { "content": "<|reserved_special_token_32|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128041": { "content": "<|reserved_special_token_33|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128042": { "content": "<|reserved_special_token_34|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128043": { "content": "<|reserved_special_token_35|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128044": { "content": "<|reserved_special_token_36|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128045": { "content": "<|reserved_special_token_37|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128046": { "content": "<|reserved_special_token_38|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128047": { "content": "<|reserved_special_token_39|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128048": { "content": "<|reserved_special_token_40|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128049": { "content": "<|reserved_special_token_41|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128050": { "content": "<|reserved_special_token_42|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128051": { "content": "<|reserved_special_token_43|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128052": { "content": "<|reserved_special_token_44|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128053": { "content": "<|reserved_special_token_45|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128054": { "content": "<|reserved_special_token_46|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128055": { "content": "<|reserved_special_token_47|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128056": { "content": "<|reserved_special_token_48|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128057": { "content": "<|reserved_special_token_49|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128058": { "content": "<|reserved_special_token_50|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128059": { "content": "<|reserved_special_token_51|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128060": { "content": "<|reserved_special_token_52|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128061": { "content": "<|reserved_special_token_53|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128062": { "content": "<|reserved_special_token_54|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128063": { "content": "<|reserved_special_token_55|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128064": { "content": "<|reserved_special_token_56|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128065": { "content": "<|reserved_special_token_57|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128066": { "content": "<|reserved_special_token_58|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128067": { "content": "<|reserved_special_token_59|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128068": { "content": "<|reserved_special_token_60|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128069": { "content": "<|reserved_special_token_61|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128070": { "content": "<|reserved_special_token_62|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128071": { "content": "<|reserved_special_token_63|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128072": { "content": "<|reserved_special_token_64|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128073": { "content": "<|reserved_special_token_65|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128074": { "content": "<|reserved_special_token_66|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128075": { "content": "<|reserved_special_token_67|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128076": { "content": "<|reserved_special_token_68|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128077": { "content": "<|reserved_special_token_69|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128078": { "content": "<|reserved_special_token_70|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128079": { "content": "<|reserved_special_token_71|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128080": { "content": "<|reserved_special_token_72|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128081": { "content": "<|reserved_special_token_73|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128082": { "content": "<|reserved_special_token_74|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128083": { "content": "<|reserved_special_token_75|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128084": { "content": "<|reserved_special_token_76|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128085": { "content": "<|reserved_special_token_77|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128086": { "content": "<|reserved_special_token_78|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128087": { "content": "<|reserved_special_token_79|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128088": { "content": "<|reserved_special_token_80|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128089": { "content": "<|reserved_special_token_81|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128090": { "content": "<|reserved_special_token_82|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128091": { "content": "<|reserved_special_token_83|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128092": { "content": "<|reserved_special_token_84|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128093": { "content": "<|reserved_special_token_85|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128094": { "content": "<|reserved_special_token_86|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128095": { "content": "<|reserved_special_token_87|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128096": { "content": "<|reserved_special_token_88|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128097": { "content": "<|reserved_special_token_89|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128098": { "content": "<|reserved_special_token_90|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128099": { "content": "<|reserved_special_token_91|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128100": { "content": "<|reserved_special_token_92|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128101": { "content": "<|reserved_special_token_93|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128102": { "content": "<|reserved_special_token_94|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128103": { "content": "<|reserved_special_token_95|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128104": { "content": "<|reserved_special_token_96|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128105": { "content": "<|reserved_special_token_97|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128106": { "content": "<|reserved_special_token_98|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128107": { "content": "<|reserved_special_token_99|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128108": { "content": "<|reserved_special_token_100|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128109": { "content": "<|reserved_special_token_101|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128110": { "content": "<|reserved_special_token_102|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128111": { "content": "<|reserved_special_token_103|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128112": { "content": "<|reserved_special_token_104|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128113": { "content": "<|reserved_special_token_105|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128114": { "content": "<|reserved_special_token_106|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128115": { "content": "<|reserved_special_token_107|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128116": { "content": "<|reserved_special_token_108|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128117": { "content": "<|reserved_special_token_109|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128118": { "content": "<|reserved_special_token_110|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128119": { "content": "<|reserved_special_token_111|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128120": { "content": "<|reserved_special_token_112|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128121": { "content": "<|reserved_special_token_113|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128122": { "content": "<|reserved_special_token_114|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128123": { "content": "<|reserved_special_token_115|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128124": { "content": "<|reserved_special_token_116|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128125": { "content": "<|reserved_special_token_117|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128126": { "content": "<|reserved_special_token_118|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128127": { "content": "<|reserved_special_token_119|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128128": { "content": "<|reserved_special_token_120|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128129": { "content": "<|reserved_special_token_121|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128130": { "content": "<|reserved_special_token_122|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128131": { "content": "<|reserved_special_token_123|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128132": { "content": "<|reserved_special_token_124|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128133": { "content": "<|reserved_special_token_125|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128134": { "content": "<|reserved_special_token_126|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128135": { "content": "<|reserved_special_token_127|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128136": { "content": "<|reserved_special_token_128|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128137": { "content": "<|reserved_special_token_129|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128138": { "content": "<|reserved_special_token_130|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128139": { "content": "<|reserved_special_token_131|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128140": { "content": "<|reserved_special_token_132|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128141": { "content": "<|reserved_special_token_133|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128142": { "content": "<|reserved_special_token_134|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128143": { "content": "<|reserved_special_token_135|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128144": { "content": "<|reserved_special_token_136|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128145": { "content": "<|reserved_special_token_137|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128146": { "content": "<|reserved_special_token_138|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128147": { "content": "<|reserved_special_token_139|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128148": { "content": "<|reserved_special_token_140|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128149": { "content": "<|reserved_special_token_141|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128150": { "content": "<|reserved_special_token_142|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128151": { "content": "<|reserved_special_token_143|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128152": { "content": "<|reserved_special_token_144|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128153": { "content": "<|reserved_special_token_145|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128154": { "content": "<|reserved_special_token_146|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128155": { "content": "<|reserved_special_token_147|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128156": { "content": "<|reserved_special_token_148|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128157": { "content": "<|reserved_special_token_149|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128158": { "content": "<|reserved_special_token_150|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128159": { "content": "<|reserved_special_token_151|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128160": { "content": "<|reserved_special_token_152|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128161": { "content": "<|reserved_special_token_153|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128162": { "content": "<|reserved_special_token_154|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128163": { "content": "<|reserved_special_token_155|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128164": { "content": "<|reserved_special_token_156|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128165": { "content": "<|reserved_special_token_157|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128166": { "content": "<|reserved_special_token_158|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128167": { "content": "<|reserved_special_token_159|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128168": { "content": "<|reserved_special_token_160|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128169": { "content": "<|reserved_special_token_161|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128170": { "content": "<|reserved_special_token_162|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128171": { "content": "<|reserved_special_token_163|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128172": { "content": "<|reserved_special_token_164|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128173": { "content": "<|reserved_special_token_165|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128174": { "content": "<|reserved_special_token_166|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128175": { "content": "<|reserved_special_token_167|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128176": { "content": "<|reserved_special_token_168|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128177": { "content": "<|reserved_special_token_169|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128178": { "content": "<|reserved_special_token_170|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128179": { "content": "<|reserved_special_token_171|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128180": { "content": "<|reserved_special_token_172|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128181": { "content": "<|reserved_special_token_173|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128182": { "content": "<|reserved_special_token_174|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128183": { "content": "<|reserved_special_token_175|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128184": { "content": "<|reserved_special_token_176|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128185": { "content": "<|reserved_special_token_177|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128186": { "content": "<|reserved_special_token_178|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128187": { "content": "<|reserved_special_token_179|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128188": { "content": "<|reserved_special_token_180|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128189": { "content": "<|reserved_special_token_181|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128190": { "content": "<|reserved_special_token_182|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128191": { "content": "<|reserved_special_token_183|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128192": { "content": "<|reserved_special_token_184|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128193": { "content": "<|reserved_special_token_185|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128194": { "content": "<|reserved_special_token_186|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128195": { "content": "<|reserved_special_token_187|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128196": { "content": "<|reserved_special_token_188|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128197": { "content": "<|reserved_special_token_189|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128198": { "content": "<|reserved_special_token_190|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128199": { "content": "<|reserved_special_token_191|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128200": { "content": "<|reserved_special_token_192|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128201": { "content": "<|reserved_special_token_193|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128202": { "content": "<|reserved_special_token_194|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128203": { "content": "<|reserved_special_token_195|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128204": { "content": "<|reserved_special_token_196|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128205": { "content": "<|reserved_special_token_197|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128206": { "content": "<|reserved_special_token_198|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128207": { "content": "<|reserved_special_token_199|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128208": { "content": "<|reserved_special_token_200|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128209": { "content": "<|reserved_special_token_201|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128210": { "content": "<|reserved_special_token_202|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128211": { "content": "<|reserved_special_token_203|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128212": { "content": "<|reserved_special_token_204|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128213": { "content": "<|reserved_special_token_205|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128214": { "content": "<|reserved_special_token_206|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128215": { "content": "<|reserved_special_token_207|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128216": { "content": "<|reserved_special_token_208|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128217": { "content": "<|reserved_special_token_209|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128218": { "content": "<|reserved_special_token_210|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128219": { "content": "<|reserved_special_token_211|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128220": { "content": "<|reserved_special_token_212|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128221": { "content": "<|reserved_special_token_213|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128222": { "content": "<|reserved_special_token_214|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128223": { "content": "<|reserved_special_token_215|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128224": { "content": "<|reserved_special_token_216|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128225": { "content": "<|reserved_special_token_217|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128226": { "content": "<|reserved_special_token_218|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128227": { "content": "<|reserved_special_token_219|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128228": { "content": "<|reserved_special_token_220|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128229": { "content": "<|reserved_special_token_221|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128230": { "content": "<|reserved_special_token_222|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128231": { "content": "<|reserved_special_token_223|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128232": { "content": "<|reserved_special_token_224|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128233": { "content": "<|reserved_special_token_225|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128234": { "content": "<|reserved_special_token_226|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128235": { "content": "<|reserved_special_token_227|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128236": { "content": "<|reserved_special_token_228|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128237": { "content": "<|reserved_special_token_229|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128238": { "content": "<|reserved_special_token_230|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128239": { "content": "<|reserved_special_token_231|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128240": { "content": "<|reserved_special_token_232|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128241": { "content": "<|reserved_special_token_233|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128242": { "content": "<|reserved_special_token_234|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128243": { "content": "<|reserved_special_token_235|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128244": { "content": "<|reserved_special_token_236|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128245": { "content": "<|reserved_special_token_237|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128246": { "content": "<|reserved_special_token_238|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128247": { "content": "<|reserved_special_token_239|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128248": { "content": "<|reserved_special_token_240|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128249": { "content": "<|reserved_special_token_241|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128250": { "content": "<|reserved_special_token_242|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128251": { "content": "<|reserved_special_token_243|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128252": { "content": "<|reserved_special_token_244|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128253": { "content": "<|reserved_special_token_245|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128254": { "content": "<|reserved_special_token_246|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "128255": { "content": "<|reserved_special_token_247|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "bos_token": "<|begin_of_text|>", "chat_template": "{{- bos_token }}\n{%- if custom_tools is defined %}\n {%- set tools = custom_tools %}\n{%- endif %}\n{%- if not tools_in_user_message is defined %}\n {%- set tools_in_user_message = true %}\n{%- endif %}\n{%- if not date_string is defined %}\n {%- set date_string = \"26 Jul 2024\" %}\n{%- endif %}\n{%- if not tools is defined %}\n {%- set tools = none %}\n{%- endif %}\n\n{#- This block extracts the system message, so we can slot it into the right place. #}\n{%- if messages[0]['role'] == 'system' %}\n {%- set system_message = messages[0]['content']|trim %}\n {%- set messages = messages[1:] %}\n{%- else %}\n {%- set system_message = \"\" %}\n{%- endif %}\n\n{#- System message + builtin tools #}\n{{- \"<|start_header_id|>system<|end_header_id|>\\n\\n\" }}\n{%- if builtin_tools is defined or tools is not none %}\n {{- \"Environment: ipython\\n\" }}\n{%- endif %}\n{%- if builtin_tools is defined %}\n {{- \"Tools: \" + builtin_tools | reject('equalto', 'code_interpreter') | join(\", \") + \"\\n\\n\"}}\n{%- endif %}\n{{- \"Cutting Knowledge Date: December 2023\\n\" }}\n{{- \"Today Date: \" + date_string + \"\\n\\n\" }}\n{%- if tools is not none and not tools_in_user_message %}\n {{- \"You have access to the following functions. To call a function, please respond with JSON for a function call.\" }}\n {{- 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{- \"Do not use variables.\\n\\n\" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- \"\\n\\n\" }}\n {%- endfor %}\n{%- endif %}\n{{- system_message }}\n{{- \"<|eot_id|>\" }}\n\n{#- Custom tools are passed in a user message with some extra guidance #}\n{%- if tools_in_user_message and not tools is none %}\n {#- Extract the first user message so we can plug it in here #}\n {%- if messages | length != 0 %}\n {%- set first_user_message = messages[0]['content']|trim %}\n {%- set messages = messages[1:] %}\n {%- else %}\n {{- raise_exception(\"Cannot put tools in the first user message when there's no first user message!\") }}\n{%- endif %}\n {{- '<|start_header_id|>user<|end_header_id|>\\n\\n' -}}\n {{- \"Given the following functions, please respond with a JSON for a function call \" }}\n {{- \"with its proper arguments that best answers the given prompt.\\n\\n\" }}\n {{- 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{- \"Do not use variables.\\n\\n\" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- \"\\n\\n\" }}\n {%- endfor %}\n {{- first_user_message + \"<|eot_id|>\"}}\n{%- endif %}\n\n{%- for message in messages %}\n {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %}\n {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\\n\\n'+ message['content'] | trim + '<|eot_id|>' }}\n {%- elif 'tool_calls' in message %}\n {%- if not message.tool_calls|length == 1 %}\n {{- raise_exception(\"This model only supports single tool-calls at once!\") }}\n {%- endif %}\n {%- set tool_call = message.tool_calls[0].function %}\n {%- if builtin_tools is defined and tool_call.name in builtin_tools %}\n {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' -}}\n {{- \"<|python_tag|>\" + tool_call.name + \".call(\" }}\n {%- for arg_name, arg_val in tool_call.arguments | items %}\n {{- arg_name + '=\"' + arg_val + '\"' }}\n {%- if not loop.last %}\n {{- \", \" }}\n {%- endif %}\n {%- endfor %}\n {{- \")\" }}\n {%- else %}\n {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' -}}\n {{- '{\"name\": \"' + tool_call.name + '\", ' }}\n {{- '\"parameters\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- \"}\" }}\n {%- endif %}\n {%- if builtin_tools is defined %}\n {#- This means we're in ipython mode #}\n {{- \"<|eom_id|>\" }}\n {%- else %}\n {{- \"<|eot_id|>\" }}\n {%- endif %}\n {%- elif message.role == \"tool\" or message.role == \"ipython\" %}\n {{- \"<|start_header_id|>ipython<|end_header_id|>\\n\\n\" }}\n {%- if message.content is mapping or message.content is iterable %}\n {{- message.content | tojson }}\n {%- else %}\n {{- message.content }}\n {%- endif %}\n {{- \"<|eot_id|>\" }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' }}\n{%- endif %}\n", "clean_up_tokenization_spaces": true, "eos_token": "<|eot_id|>", "model_input_names": [ "input_ids", "attention_mask" ], "model_max_length": 131072, "pad_token": "<|finetune_right_pad_id|>", "padding_side": "right", "tokenizer_class": "PreTrainedTokenizerFast"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112---license: apache-2.0tags:- visionwidget:- src: https://huggingface.co/datasets/mishig/sample_images/resolve/main/cat-dog-music.png candidate_labels: playing music, playing sports example_title: Cat & Dog---
# SigLIP (shape-optimized model)
SigLIP model pre-trained on WebLi at resolution 384x384. It was introduced in the paper [Sigmoid Loss for Language Image Pre-Training](https://arxiv.org/abs/2303.15343) by Zhai et al. and first released in [this repository](https://github.com/google-research/big_vision).
This model has the SoViT-400m architecture, which is the shape-optimized version as presented in [Getting ViT in Shape: Scaling Laws for Compute-Optimal Model Design](https://arxiv.org/abs/2305.13035) by Alabdulmohsin et al.
Disclaimer: The team releasing SigLIP did not write a model card for this model so this model card has been written by the Hugging Face team.
## Model description
SigLIP is [CLIP](https://huggingface.co/docs/transformers/model_doc/clip), a multimodal model, with a better loss function. The sigmoid loss operates solely on image-text pairs and does not require a global view of the pairwise similarities for normalization. This allows further scaling up the batch size, while also performing better at smaller batch sizes.
A TLDR of SigLIP by one of the authors can be found [here](https://twitter.com/giffmana/status/1692641733459267713).
## Intended uses & limitations
You can use the raw model for tasks like zero-shot image classification and image-text retrieval. See the [model hub](https://huggingface.co/models?search=google/siglip) to look forother versions on a task that interests you.
### How to use
Here is how to use this model to perform zero-shot image classification:
```pythonfrom PIL import Imageimport requestsfrom transformers import AutoProcessor, AutoModelimport torch
model = AutoModel.from_pretrained("google/siglip-so400m-patch14-384")processor = AutoProcessor.from_pretrained("google/siglip-so400m-patch14-384")
url = "http://images.cocodataset.org/val2017/000000039769.jpg"image = Image.open(requests.get(url, stream=True).raw)
texts = ["a photo of 2 cats", "a photo of 2 dogs"]inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt")
with torch.no_grad(): outputs = model(**inputs)
logits_per_image = outputs.logits_per_imageprobs = torch.sigmoid(logits_per_image) # these are the probabilitiesprint(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'")```
Alternatively, one can leverage the pipeline API which abstracts away the complexity for the user:
```pythonfrom transformers import pipelinefrom PIL import Imageimport requests
# load pipeimage_classifier = pipeline(task="zero-shot-image-classification", model="google/siglip-so400m-patch14-384")
# load imageurl = 'http://images.cocodataset.org/val2017/000000039769.jpg'image = Image.open(requests.get(url, stream=True).raw)
# inferenceoutputs = image_classifier(image, candidate_labels=["2 cats", "a plane", "a remote"])outputs = [{"score": round(output["score"], 4), "label": output["label"] } for output in outputs]print(outputs)```For more code examples, we refer to the [documentation](https://huggingface.co/transformers/main/model_doc/siglip.html#).
## Training procedure
### Training data
SigLIP is pre-trained on the WebLI dataset [(Chen et al., 2023)](https://arxiv.org/abs/2209.06794).
### Preprocessing
Images are resized/rescaled to the same resolution (384x384) and normalized across the RGB channels with mean (0.5, 0.5, 0.5) and standard deviation (0.5, 0.5, 0.5).
Texts are tokenized and padded to the same length (64 tokens).
### Compute
The model was trained on 16 TPU-v4 chips for three days.
## Evaluation results
Evaluation of SigLIP compared to CLIP is shown below (taken from the paper).
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/siglip_table.jpeg"alt="drawing" width="600"/>
### BibTeX entry and citation info
```bibtex@misc{zhai2023sigmoid, title={Sigmoid Loss for Language Image Pre-Training}, author={Xiaohua Zhai and Basil Mustafa and Alexander Kolesnikov and Lucas Beyer}, year={2023}, eprint={2303.15343}, archivePrefix={arXiv}, primaryClass={cs.CV}}```12345678910111213141516171819202122232425{ "architectures": [ "SiglipModel" ], "initializer_factor": 1.0, "model_type": "siglip", "text_config": { "hidden_size": 1152, "intermediate_size": 4304, "model_type": "siglip_text_model", "num_attention_heads": 16, "num_hidden_layers": 27 }, "torch_dtype": "float32", "transformers_version": "4.37.0.dev0", "vision_config": { "hidden_size": 1152, "image_size": 384, "intermediate_size": 4304, "model_type": "siglip_vision_model", "num_attention_heads": 16, "num_hidden_layers": 27, "patch_size": 14 }}1234567891011121314151617181920212223{ "do_normalize": true, "do_rescale": true, "do_resize": true, "image_mean": [ 0.5, 0.5, 0.5 ], "image_processor_type": "SiglipImageProcessor", "image_std": [ 0.5, 0.5, 0.5 ], "processor_class": "SiglipProcessor", "resample": 3, "rescale_factor": 0.00392156862745098, "size": { "height": 384, "width": 384 }}1234567891011121314151617181920212223{ "eos_token": { "content": "</s>", "lstrip": true, "normalized": false, "rstrip": true, "single_word": false }, "pad_token": { "content": "</s>", "lstrip": true, "normalized": false, "rstrip": true, "single_word": false }, "unk_token": { "content": "<unk>", "lstrip": true, "normalized": false, "rstrip": true, "single_word": false }}123456789101112131415161718192021222324252627282930313233{ "added_tokens_decoder": { "1": { "content": "</s>", "lstrip": true, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "2": { "content": "<unk>", "lstrip": true, "normalized": false, "rstrip": true, "single_word": false, "special": true } }, "additional_special_tokens": [], "clean_up_tokenization_spaces": true, "do_lower_case": true, "eos_token": "</s>", "model_input_names": [ "input_ids" ], "model_max_length": 64, "pad_token": "</s>", "processor_class": "SiglipProcessor", "sp_model_kwargs": {}, "tokenizer_class": "SiglipTokenizer", "unk_token": "<unk>"}118d0535469bb561bf468d76c1d73aa35156c922b123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154---license: otherlicense_name: flux-1-dev-non-commercial-licenselicense_link: https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md
language: - enlibrary_name: diffuserspipeline_tag: text-to-image
tags:- Text-to-Image- ControlNet- Diffusers- Flux.1-dev- image-generation- Stable Diffusionbase_model: black-forest-labs/FLUX.1-dev---
# FLUX.1-dev-ControlNet-Union-Pro-2.0
This repository contains an unified ControlNet for FLUX.1-dev model released by [Shakker Labs](https://huggingface.co/Shakker-Labs). We provide an [online demo](https://huggingface.co/spaces/Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro-2.0). A FP8 quantized version provided by community can be found in [ABDALLALSWAITI/FLUX.1-dev-ControlNet-Union-Pro-2.0-fp8](https://huggingface.co/ABDALLALSWAITI/FLUX.1-dev-ControlNet-Union-Pro-2.0-fp8).
# KeynotesIn comparison with [Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro](https://huggingface.co/Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro),- Remove mode embedding, has smaller model size.- Improve on canny and pose, better control and aesthetics.- Add support for soft edge. Remove support for tile.
# Model Cards- This ControlNet consists of 6 double blocks and 0 single block. Mode embedding is removed.- We train the model from scratch for 300k steps using a dataset of 20M high-quality general and human images. We train at 512x512 resolution in BFloat16, batch size = 128, learning rate = 2e-5, the guidance is uniformly sampled from [1, 7]. We set the text drop ratio to 0.20.- This model supports multiple control modes, including canny, soft edge, depth, pose, gray. You can use it just as a normal ControlNet.- This model can be jointly used with other ControlNets.
# Showcases
<table> <tr> <td><img src="./images/canny.png" alt="canny" style="height:100%"></td> </tr> <tr> <td><img src="./images/softedge.png" alt="softedge" style="height:100%"></td> </tr> <tr> <td><img src="./images/pose.png" alt="pose" style="height:100%"></td> </tr> <tr> <td><img src="./images/depth.png" alt="depth" style="height:100%"></td> </tr> <tr> <td><img src="./images/gray.png" alt="gray" style="height:100%"></td> </tr></table> # Inference```pythonimport torchfrom diffusers.utils import load_imagefrom diffusers import FluxControlNetPipeline, FluxControlNetModel
base_model = 'black-forest-labs/FLUX.1-dev'controlnet_model_union = 'Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro-2.0'
controlnet = FluxControlNetModel.from_pretrained(controlnet_model_union, torch_dtype=torch.bfloat16)pipe = FluxControlNetPipeline.from_pretrained(base_model, controlnet=controlnet, torch_dtype=torch.bfloat16)pipe.to("cuda")
# replace with other condscontrol_image = load_image("./conds/canny.png")width, height = control_image.size
prompt = "A young girl stands gracefully at the edge of a serene beach, her long, flowing hair gently tousled by the sea breeze. She wears a soft, pastel-colored dress that complements the tranquil blues and greens of the coastal scenery. The golden hues of the setting sun cast a warm glow on her face, highlighting her serene expression. The background features a vast, azure ocean with gentle waves lapping at the shore, surrounded by distant cliffs and a clear, cloudless sky. The composition emphasizes the girl's serene presence amidst the natural beauty, with a balanced blend of warm and cool tones."
image = pipe( prompt, control_image=control_image, width=width, height=height, controlnet_conditioning_scale=0.7, control_guidance_end=0.8, num_inference_steps=30, guidance_scale=3.5, generator=torch.Generator(device="cuda").manual_seed(42),).images[0]```
# Multi-Inference```pythonimport torchfrom diffusers.utils import load_image
# https://github.com/huggingface/diffusers/pull/11350# You can directly import from diffusers by install the laster version from source# from diffusers import FluxControlNetPipeline, FluxControlNetModel
# use local files for this momentfrom pipeline_flux_controlnet import FluxControlNetPipelinefrom controlnet_flux import FluxControlNetModel
base_model = 'black-forest-labs/FLUX.1-dev'controlnet_model_union = 'Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro-2.0'
controlnet = FluxControlNetModel.from_pretrained(controlnet_model_union, torch_dtype=torch.bfloat16)pipe = FluxControlNetPipeline.from_pretrained(base_model, controlnet=[controlnet], torch_dtype=torch.bfloat16) # use [] to enable multi-CNspipe.to("cuda")
# replace with other condscontrol_image = load_image("./conds/canny.png")width, height = control_image.size
prompt = "A young girl stands gracefully at the edge of a serene beach, her long, flowing hair gently tousled by the sea breeze. She wears a soft, pastel-colored dress that complements the tranquil blues and greens of the coastal scenery. The golden hues of the setting sun cast a warm glow on her face, highlighting her serene expression. The background features a vast, azure ocean with gentle waves lapping at the shore, surrounded by distant cliffs and a clear, cloudless sky. The composition emphasizes the girl's serene presence amidst the natural beauty, with a balanced blend of warm and cool tones."
image = pipe( prompt, control_image=[control_image, control_image], # try with different conds such as canny&depth, pose&depth width=width, height=height, controlnet_conditioning_scale=[0.35, 0.35], control_guidance_end=[0.8, 0.8], num_inference_steps=30, guidance_scale=3.5, generator=torch.Generator(device="cuda").manual_seed(42),).images[0]```
# Recommended ParametersYou can adjust controlnet_conditioning_scale and control_guidance_end for stronger control and better detail preservation. For better stability, we highly suggest to use detailed prompt, for some cases, multi-conditions help.- Canny: use cv2.Canny, controlnet_conditioning_scale=0.7, control_guidance_end=0.8.- Soft Edge: use [AnylineDetector](https://github.com/huggingface/controlnet_aux), controlnet_conditioning_scale=0.7, control_guidance_end=0.8.- Depth: use [depth-anything](https://github.com/DepthAnything/Depth-Anything-V2), controlnet_conditioning_scale=0.8, control_guidance_end=0.8.- Pose: use [DWPose](https://github.com/IDEA-Research/DWPose/tree/onnx), controlnet_conditioning_scale=0.9, control_guidance_end=0.65.- Gray: use cv2.cvtColor, controlnet_conditioning_scale=0.9, control_guidance_end=0.8.
# Resources- [InstantX/FLUX.1-dev-IP-Adapter](https://huggingface.co/InstantX/FLUX.1-dev-IP-Adapter)- [InstantX/FLUX.1-dev-Controlnet-Canny](https://huggingface.co/InstantX/FLUX.1-dev-Controlnet-Canny)- [Shakker-Labs/FLUX.1-dev-ControlNet-Depth](https://huggingface.co/Shakker-Labs/FLUX.1-dev-ControlNet-Depth)- [Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro](https://huggingface.co/Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro)
# AcknowledgementsThis model is developed by [Shakker Labs](https://huggingface.co/Shakker-Labs). The original idea is inspired by [xinsir/controlnet-union-sdxl-1.0](https://huggingface.co/xinsir/controlnet-union-sdxl-1.0). All copyright reserved.
# CitationIf you find this project useful in your research, please cite us via```@misc{flux-cn-union-pro-2, author = {Shakker-Labs}, title = {ControlNet-Union}, year = {2025}, howpublished={\url{https://huggingface.co/Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro-2.0}},}```12345678910111213141516171819{ "_class_name": "FluxControlNetModel", "_diffusers_version": "0.31.0.dev0", "attention_head_dim": 128, "axes_dims_rope": [ 16, 56, 56 ], "guidance_embeds": true, "in_channels": 64, "joint_attention_dim": 4096, "num_attention_heads": 24, "num_layers": 6, "num_mode": null, "num_single_layers": 0, "patch_size": 1, "pooled_projection_dim": 768}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509# Copyright 2024 Black Forest Labs, The HuggingFace Team and The InstantX 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.
from dataclasses import dataclassfrom typing import Any, Dict, List, Optional, Tuple, Union
import torchimport torch.nn as nn
from diffusers.configuration_utils import ConfigMixin, register_to_configfrom diffusers.loaders import PeftAdapterMixinfrom diffusers.models.attention_processor import AttentionProcessorfrom diffusers.models.modeling_utils import ModelMixinfrom diffusers.utils import USE_PEFT_BACKEND, BaseOutput, logging, scale_lora_layers, unscale_lora_layersfrom diffusers.models.controlnets.controlnet import ControlNetConditioningEmbedding, zero_modulefrom diffusers.models.embeddings import CombinedTimestepGuidanceTextProjEmbeddings, CombinedTimestepTextProjEmbeddings, FluxPosEmbedfrom diffusers.models.modeling_outputs import Transformer2DModelOutputfrom diffusers.models.transformers.transformer_flux import FluxSingleTransformerBlock, FluxTransformerBlock
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
@dataclassclass FluxControlNetOutput(BaseOutput): controlnet_block_samples: Tuple[torch.Tensor] controlnet_single_block_samples: Tuple[torch.Tensor]
class FluxControlNetModel(ModelMixin, ConfigMixin, PeftAdapterMixin): _supports_gradient_checkpointing = True
@register_to_config def __init__( self, patch_size: int = 1, in_channels: int = 64, num_layers: int = 19, num_single_layers: int = 38, attention_head_dim: int = 128, num_attention_heads: int = 24, joint_attention_dim: int = 4096, pooled_projection_dim: int = 768, guidance_embeds: bool = False, axes_dims_rope: List[int] = [16, 56, 56], num_mode: int = None, conditioning_embedding_channels: int = None, ): super().__init__() self.out_channels = in_channels self.inner_dim = num_attention_heads * attention_head_dim
self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope) text_time_guidance_cls = ( CombinedTimestepGuidanceTextProjEmbeddings if guidance_embeds else CombinedTimestepTextProjEmbeddings ) self.time_text_embed = text_time_guidance_cls( embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim )
self.context_embedder = nn.Linear(joint_attention_dim, self.inner_dim) self.x_embedder = torch.nn.Linear(in_channels, self.inner_dim)
self.transformer_blocks = nn.ModuleList( [ FluxTransformerBlock( dim=self.inner_dim, num_attention_heads=num_attention_heads, attention_head_dim=attention_head_dim, ) for i in range(num_layers) ] )
self.single_transformer_blocks = nn.ModuleList( [ FluxSingleTransformerBlock( dim=self.inner_dim, num_attention_heads=num_attention_heads, attention_head_dim=attention_head_dim, ) for i in range(num_single_layers) ] )
# controlnet_blocks self.controlnet_blocks = nn.ModuleList([]) for _ in range(len(self.transformer_blocks)): self.controlnet_blocks.append(zero_module(nn.Linear(self.inner_dim, self.inner_dim)))
self.controlnet_single_blocks = nn.ModuleList([]) for _ in range(len(self.single_transformer_blocks)): self.controlnet_single_blocks.append(zero_module(nn.Linear(self.inner_dim, self.inner_dim)))
self.union = num_mode is not None if self.union: self.controlnet_mode_embedder = nn.Embedding(num_mode, self.inner_dim)
if conditioning_embedding_channels is not None: self.input_hint_block = ControlNetConditioningEmbedding( conditioning_embedding_channels=conditioning_embedding_channels, block_out_channels=(16, 16, 16, 16) ) self.controlnet_x_embedder = torch.nn.Linear(in_channels, self.inner_dim) else: self.input_hint_block = None self.controlnet_x_embedder = zero_module(torch.nn.Linear(in_channels, self.inner_dim))
self.gradient_checkpointing = False
@property # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors def attn_processors(self): r""" Returns: `dict` of attention processors: A dictionary containing all attention processors used in the model with indexed by its weight name. """ # set recursively processors = {}
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]): if hasattr(module, "get_processor"): processors[f"{name}.processor"] = module.get_processor()
for sub_name, child in module.named_children(): fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
return processors
for name, module in self.named_children(): fn_recursive_add_processors(name, module, processors)
return processors
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor def set_attn_processor(self, processor): r""" Sets the attention processor to use to compute attention.
Parameters: processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`): The instantiated processor class or a dictionary of processor classes that will be set as the processor for **all** `Attention` layers.
If `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors.
""" count = len(self.attn_processors.keys())
if isinstance(processor, dict) and len(processor) != count: raise ValueError( f"A dict of processors was passed, but the number of processors {len(processor)} does not match the" f" number of attention layers: {count}. Please make sure to pass {count} processor classes." )
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor): if hasattr(module, "set_processor"): if not isinstance(processor, dict): module.set_processor(processor) else: module.set_processor(processor.pop(f"{name}.processor"))
for sub_name, child in module.named_children(): fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
for name, module in self.named_children(): fn_recursive_attn_processor(name, module, processor)
@classmethod def from_transformer( cls, transformer, num_layers: int = 4, num_single_layers: int = 10, attention_head_dim: int = 128, num_attention_heads: int = 24, load_weights_from_transformer=True, ): config = dict(transformer.config) config["num_layers"] = num_layers config["num_single_layers"] = num_single_layers config["attention_head_dim"] = attention_head_dim config["num_attention_heads"] = num_attention_heads
controlnet = cls.from_config(config)
if load_weights_from_transformer: controlnet.pos_embed.load_state_dict(transformer.pos_embed.state_dict()) controlnet.time_text_embed.load_state_dict(transformer.time_text_embed.state_dict()) controlnet.context_embedder.load_state_dict(transformer.context_embedder.state_dict()) controlnet.x_embedder.load_state_dict(transformer.x_embedder.state_dict()) controlnet.transformer_blocks.load_state_dict(transformer.transformer_blocks.state_dict(), strict=False) controlnet.single_transformer_blocks.load_state_dict( transformer.single_transformer_blocks.state_dict(), strict=False )
controlnet.controlnet_x_embedder = zero_module(controlnet.controlnet_x_embedder)
return controlnet
def forward( self, hidden_states: torch.Tensor, controlnet_cond: torch.Tensor, controlnet_mode: torch.Tensor = None, conditioning_scale: float = 1.0, encoder_hidden_states: torch.Tensor = None, pooled_projections: torch.Tensor = None, timestep: torch.LongTensor = None, img_ids: torch.Tensor = None, txt_ids: torch.Tensor = None, guidance: torch.Tensor = None, joint_attention_kwargs: Optional[Dict[str, Any]] = None, return_dict: bool = True, ) -> Union[torch.FloatTensor, Transformer2DModelOutput]: """ The [`FluxTransformer2DModel`] forward method.
Args: hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`): Input `hidden_states`. controlnet_cond (`torch.Tensor`): The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`. controlnet_mode (`torch.Tensor`): The mode tensor of shape `(batch_size, 1)`. conditioning_scale (`float`, defaults to `1.0`): The scale factor for ControlNet outputs. encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`): Conditional embeddings (embeddings computed from the input conditions such as prompts) to use. pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected from the embeddings of input conditions. timestep ( `torch.LongTensor`): Used to indicate denoising step. block_controlnet_hidden_states: (`list` of `torch.Tensor`): A list of tensors that if specified are added to the residuals of transformer blocks. joint_attention_kwargs (`dict`, *optional*): A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under `self.processor` in [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain tuple.
Returns: If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a `tuple` where the first element is the sample tensor. """ if joint_attention_kwargs is not None: joint_attention_kwargs = joint_attention_kwargs.copy() lora_scale = joint_attention_kwargs.pop("scale", 1.0) else: lora_scale = 1.0
if USE_PEFT_BACKEND: # weight the lora layers by setting `lora_scale` for each PEFT layer scale_lora_layers(self, lora_scale) else: if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None: logger.warning( "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective." ) hidden_states = self.x_embedder(hidden_states)
if self.input_hint_block is not None: controlnet_cond = self.input_hint_block(controlnet_cond) batch_size, channels, height_pw, width_pw = controlnet_cond.shape height = height_pw // self.config.patch_size width = width_pw // self.config.patch_size controlnet_cond = controlnet_cond.reshape( batch_size, channels, height, self.config.patch_size, width, self.config.patch_size ) controlnet_cond = controlnet_cond.permute(0, 2, 4, 1, 3, 5) controlnet_cond = controlnet_cond.reshape(batch_size, height * width, -1) # add hidden_states = hidden_states + self.controlnet_x_embedder(controlnet_cond)
timestep = timestep.to(hidden_states.dtype) * 1000 if guidance is not None: guidance = guidance.to(hidden_states.dtype) * 1000 else: guidance = None temb = ( self.time_text_embed(timestep, pooled_projections) if guidance is None else self.time_text_embed(timestep, guidance, pooled_projections) ) encoder_hidden_states = self.context_embedder(encoder_hidden_states)
if txt_ids.ndim == 3: logger.warning( "Passing `txt_ids` 3d torch.Tensor is deprecated." "Please remove the batch dimension and pass it as a 2d torch Tensor" ) txt_ids = txt_ids[0] if img_ids.ndim == 3: logger.warning( "Passing `img_ids` 3d torch.Tensor is deprecated." "Please remove the batch dimension and pass it as a 2d torch Tensor" ) img_ids = img_ids[0]
if self.union: # union mode if controlnet_mode is None: raise ValueError("`controlnet_mode` cannot be `None` when applying ControlNet-Union") # union mode emb controlnet_mode_emb = self.controlnet_mode_embedder(controlnet_mode) encoder_hidden_states = torch.cat([controlnet_mode_emb, encoder_hidden_states], dim=1) txt_ids = torch.cat([txt_ids[:1], txt_ids], dim=0)
ids = torch.cat((txt_ids, img_ids), dim=0) image_rotary_emb = self.pos_embed(ids)
block_samples = () for index_block, block in enumerate(self.transformer_blocks): if torch.is_grad_enabled() and self.gradient_checkpointing: encoder_hidden_states, hidden_states = self._gradient_checkpointing_func( block, hidden_states, encoder_hidden_states, temb, image_rotary_emb, )
else: encoder_hidden_states, hidden_states = block( hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states, temb=temb, image_rotary_emb=image_rotary_emb, ) block_samples = block_samples + (hidden_states,)
hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
single_block_samples = () for index_block, block in enumerate(self.single_transformer_blocks): if torch.is_grad_enabled() and self.gradient_checkpointing: hidden_states = self._gradient_checkpointing_func( block, hidden_states, temb, image_rotary_emb, )
else: hidden_states = block( hidden_states=hidden_states, temb=temb, image_rotary_emb=image_rotary_emb, ) single_block_samples = single_block_samples + (hidden_states[:, encoder_hidden_states.shape[1] :],)
# controlnet block controlnet_block_samples = () for block_sample, controlnet_block in zip(block_samples, self.controlnet_blocks): block_sample = controlnet_block(block_sample) controlnet_block_samples = controlnet_block_samples + (block_sample,)
controlnet_single_block_samples = () for single_block_sample, controlnet_block in zip(single_block_samples, self.controlnet_single_blocks): single_block_sample = controlnet_block(single_block_sample) controlnet_single_block_samples = controlnet_single_block_samples + (single_block_sample,)
# scaling controlnet_block_samples = [sample * conditioning_scale for sample in controlnet_block_samples] controlnet_single_block_samples = [sample * conditioning_scale for sample in controlnet_single_block_samples]
controlnet_block_samples = None if len(controlnet_block_samples) == 0 else controlnet_block_samples controlnet_single_block_samples = ( None if len(controlnet_single_block_samples) == 0 else controlnet_single_block_samples )
if USE_PEFT_BACKEND: # remove `lora_scale` from each PEFT layer unscale_lora_layers(self, lora_scale)
if not return_dict: return (controlnet_block_samples, controlnet_single_block_samples)
return FluxControlNetOutput( controlnet_block_samples=controlnet_block_samples, controlnet_single_block_samples=controlnet_single_block_samples, )
class FluxMultiControlNetModel(ModelMixin): r""" `FluxMultiControlNetModel` wrapper class for Multi-FluxControlNetModel
This module is a wrapper for multiple instances of the `FluxControlNetModel`. The `forward()` API is designed to be compatible with `FluxControlNetModel`.
Args: controlnets (`List[FluxControlNetModel]`): Provides additional conditioning to the unet during the denoising process. You must set multiple `FluxControlNetModel` as a list. """
def __init__(self, controlnets): super().__init__() self.nets = nn.ModuleList(controlnets)
def forward( self, hidden_states: torch.FloatTensor, controlnet_cond: List[torch.tensor], controlnet_mode: List[torch.tensor], conditioning_scale: List[float], encoder_hidden_states: torch.Tensor = None, pooled_projections: torch.Tensor = None, timestep: torch.LongTensor = None, img_ids: torch.Tensor = None, txt_ids: torch.Tensor = None, guidance: torch.Tensor = None, joint_attention_kwargs: Optional[Dict[str, Any]] = None, return_dict: bool = True, ) -> Union[FluxControlNetOutput, Tuple]: # ControlNet-Union with multiple conditions # only load one ControlNet for saving memories if len(self.nets) == 1: controlnet = self.nets[0]
for i, (image, mode, scale) in enumerate(zip(controlnet_cond, controlnet_mode, conditioning_scale)): block_samples, single_block_samples = controlnet( hidden_states=hidden_states, controlnet_cond=image, controlnet_mode=mode[:, None], conditioning_scale=scale, timestep=timestep, guidance=guidance, pooled_projections=pooled_projections, encoder_hidden_states=encoder_hidden_states, txt_ids=txt_ids, img_ids=img_ids, joint_attention_kwargs=joint_attention_kwargs, return_dict=return_dict, )
# merge samples if i == 0: control_block_samples = block_samples control_single_block_samples = single_block_samples else: if block_samples is not None and control_block_samples is not None: control_block_samples = [ control_block_sample + block_sample for control_block_sample, block_sample in zip(control_block_samples, block_samples) ] if single_block_samples is not None and control_single_block_samples is not None: control_single_block_samples = [ control_single_block_sample + block_sample for control_single_block_sample, block_sample in zip( control_single_block_samples, single_block_samples ) ]
# Regular Multi-ControlNets # load all ControlNets into memories else: for i, (image, mode, scale, controlnet) in enumerate( zip(controlnet_cond, controlnet_mode, conditioning_scale, self.nets) ): block_samples, single_block_samples = controlnet( hidden_states=hidden_states, controlnet_cond=image, controlnet_mode=mode[:, None], conditioning_scale=scale, timestep=timestep, guidance=guidance, pooled_projections=pooled_projections, encoder_hidden_states=encoder_hidden_states, txt_ids=txt_ids, img_ids=img_ids, joint_attention_kwargs=joint_attention_kwargs, return_dict=return_dict, )
# merge samples if i == 0: control_block_samples = block_samples control_single_block_samples = single_block_samples else: if block_samples is not None and control_block_samples is not None: control_block_samples = [ control_block_sample + block_sample for control_block_sample, block_sample in zip(control_block_samples, block_samples) ] if single_block_samples is not None and control_single_block_samples is not None: control_single_block_samples = [ control_single_block_sample + block_sample for control_single_block_sample, block_sample in zip( control_single_block_samples, single_block_samples ) ]
return control_block_samples, control_single_block_samples12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181# Copyright 2024 Black Forest Labs, The HuggingFace Team and The InstantX 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 inspectfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as npimport torchfrom transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection, T5EncoderModel, T5TokenizerFast,)
from diffusers.image_processor import PipelineImageInput, VaeImageProcessorfrom diffusers.loaders import FluxIPAdapterMixin, FluxLoraLoaderMixin, FromSingleFileMixin, TextualInversionLoaderMixinfrom diffusers.models.autoencoders import AutoencoderKL
# from diffusers.models.controlnets.controlnet_flux import FluxControlNetModel, FluxMultiControlNetModelfrom controlnet_flux import FluxControlNetModel, FluxMultiControlNetModel
from diffusers.models.transformers import FluxTransformer2DModelfrom diffusers.schedulers import FlowMatchEulerDiscreteSchedulerfrom diffusers.utils import ( USE_PEFT_BACKEND, is_torch_xla_available, logging, replace_example_docstring, scale_lora_layers, unscale_lora_layers,)from diffusers.utils.torch_utils import randn_tensorfrom diffusers.pipelines.pipeline_utils import DiffusionPipelinefrom diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
if is_torch_xla_available(): import torch_xla.core.xla_model as xm
XLA_AVAILABLE = Trueelse: XLA_AVAILABLE = False
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
EXAMPLE_DOC_STRING = """ Examples: ```py >>> import torch >>> from diffusers.utils import load_image >>> from diffusers import FluxControlNetPipeline >>> from diffusers import FluxControlNetModel
>>> base_model = "black-forest-labs/FLUX.1-dev" >>> controlnet_model = "InstantX/FLUX.1-dev-controlnet-canny" >>> controlnet = FluxControlNetModel.from_pretrained(controlnet_model, torch_dtype=torch.bfloat16) >>> pipe = FluxControlNetPipeline.from_pretrained( ... base_model, controlnet=controlnet, torch_dtype=torch.bfloat16 ... ) >>> pipe.to("cuda") >>> control_image = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Canny/resolve/main/canny.jpg") >>> prompt = "A girl in city, 25 years old, cool, futuristic" >>> image = pipe( ... prompt, ... control_image=control_image, ... control_guidance_start=0.2, ... control_guidance_end=0.8, ... controlnet_conditioning_scale=1.0, ... num_inference_steps=28, ... guidance_scale=3.5, ... ).images[0] >>> image.save("flux.png") ```"""
# Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shiftdef calculate_shift( image_seq_len, base_seq_len: int = 256, max_seq_len: int = 4096, base_shift: float = 0.5, max_shift: float = 1.15,): m = (max_shift - base_shift) / (max_seq_len - base_seq_len) b = base_shift - m * base_seq_len mu = image_seq_len * m + b return mu
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latentsdef retrieve_latents( encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"): if hasattr(encoder_output, "latent_dist") and sample_mode == "sample": return encoder_output.latent_dist.sample(generator) elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax": return encoder_output.latent_dist.mode() elif hasattr(encoder_output, "latents"): return encoder_output.latents else: raise AttributeError("Could not access latents of provided encoder_output")
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timestepsdef retrieve_timesteps( scheduler, num_inference_steps: Optional[int] = None, device: Optional[Union[str, torch.device]] = None, timesteps: Optional[List[int]] = None, sigmas: Optional[List[float]] = None, **kwargs,): r""" Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
Args: scheduler (`SchedulerMixin`): The scheduler to get timesteps from. num_inference_steps (`int`): The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps` must be `None`. device (`str` or `torch.device`, *optional*): The device to which the timesteps should be moved to. If `None`, the timesteps are not moved. timesteps (`List[int]`, *optional*): Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed, `num_inference_steps` and `sigmas` must be `None`. sigmas (`List[float]`, *optional*): Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed, `num_inference_steps` and `timesteps` must be `None`.
Returns: `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the second element is the number of inference steps. """ if timesteps is not None and sigmas is not None: raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values") if timesteps is not None: accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys()) if not accepts_timesteps: raise ValueError( f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom" f" timestep schedules. Please check whether you are using the correct scheduler." ) scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs) timesteps = scheduler.timesteps num_inference_steps = len(timesteps) elif sigmas is not None: accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys()) if not accept_sigmas: raise ValueError( f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom" f" sigmas schedules. Please check whether you are using the correct scheduler." ) scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs) timesteps = scheduler.timesteps num_inference_steps = len(timesteps) else: scheduler.set_timesteps(num_inference_steps, device=device, **kwargs) timesteps = scheduler.timesteps return timesteps, num_inference_steps
class FluxControlNetPipeline(DiffusionPipeline, FluxLoraLoaderMixin, FromSingleFileMixin, FluxIPAdapterMixin): r""" The Flux pipeline for text-to-image generation.
Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
Args: transformer ([`FluxTransformer2DModel`]): Conditional Transformer (MMDiT) architecture to denoise the encoded image latents. scheduler ([`FlowMatchEulerDiscreteScheduler`]): A scheduler to be used in combination with `transformer` to denoise the encoded image latents. vae ([`AutoencoderKL`]): Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. text_encoder ([`CLIPTextModel`]): [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. text_encoder_2 ([`T5EncoderModel`]): [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant. tokenizer (`CLIPTokenizer`): Tokenizer of class [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer). tokenizer_2 (`T5TokenizerFast`): Second Tokenizer of class [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast). """
model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->transformer->vae" _optional_components = ["image_encoder", "feature_extractor"] _callback_tensor_inputs = ["latents", "prompt_embeds", "control_image"]
def __init__( self, scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5TokenizerFast, transformer: FluxTransformer2DModel, controlnet: Union[ FluxControlNetModel, List[FluxControlNetModel], Tuple[FluxControlNetModel], FluxMultiControlNetModel ], image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessor = None, ): super().__init__() if isinstance(controlnet, (list, tuple)): controlnet = FluxMultiControlNetModel(controlnet)
self.register_modules( vae=vae, text_encoder=text_encoder, text_encoder_2=text_encoder_2, tokenizer=tokenizer, tokenizer_2=tokenizer_2, transformer=transformer, scheduler=scheduler, controlnet=controlnet, image_encoder=image_encoder, feature_extractor=feature_extractor, ) self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8 # Flux latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible # by the patch size. So the vae scale factor is multiplied by the patch size to account for this self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2) self.tokenizer_max_length = ( self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77 ) self.default_sample_size = 128
def _get_t5_prompt_embeds( self, prompt: Union[str, List[str]] = None, num_images_per_prompt: int = 1, max_sequence_length: int = 512, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None, ): device = device or self._execution_device dtype = dtype or self.text_encoder.dtype
prompt = [prompt] if isinstance(prompt, str) else prompt batch_size = len(prompt)
if isinstance(self, TextualInversionLoaderMixin): prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
text_inputs = self.tokenizer_2( prompt, padding="max_length", max_length=max_sequence_length, truncation=True, return_length=False, return_overflowing_tokens=False, return_tensors="pt", ) text_input_ids = text_inputs.input_ids untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids): removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1]) logger.warning( "The following part of your input was truncated because `max_sequence_length` is set to " f" {max_sequence_length} tokens: {removed_text}" )
prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
dtype = self.text_encoder_2.dtype prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
_, seq_len, _ = prompt_embeds.shape
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
return prompt_embeds
def _get_clip_prompt_embeds( self, prompt: Union[str, List[str]], num_images_per_prompt: int = 1, device: Optional[torch.device] = None, ): device = device or self._execution_device
prompt = [prompt] if isinstance(prompt, str) else prompt batch_size = len(prompt)
if isinstance(self, TextualInversionLoaderMixin): prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
text_inputs = self.tokenizer( prompt, padding="max_length", max_length=self.tokenizer_max_length, truncation=True, return_overflowing_tokens=False, return_length=False, return_tensors="pt", )
text_input_ids = text_inputs.input_ids untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids): removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1]) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" f" {self.tokenizer_max_length} tokens: {removed_text}" ) prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
# Use pooled output of CLIPTextModel prompt_embeds = prompt_embeds.pooler_output prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
# duplicate text embeddings for each generation per prompt, using mps friendly method prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt) prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
return prompt_embeds
def encode_prompt( self, prompt: Union[str, List[str]], prompt_2: Union[str, List[str]], device: Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: Optional[torch.FloatTensor] = None, pooled_prompt_embeds: Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: Optional[float] = None, ): r"""
Args: prompt (`str` or `List[str]`, *optional*): prompt to be encoded prompt_2 (`str` or `List[str]`, *optional*): The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is used in all text-encoders device: (`torch.device`): torch device num_images_per_prompt (`int`): number of images that should be generated per prompt prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument. pooled_prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, pooled text embeddings will be generated from `prompt` input argument. clip_skip (`int`, *optional*): Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that the output of the pre-final layer will be used for computing the prompt embeddings. lora_scale (`float`, *optional*): A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded. """ device = device or self._execution_device
# set lora scale so that monkey patched LoRA # function of text encoder can correctly access it if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin): self._lora_scale = lora_scale
# dynamically adjust the LoRA scale if self.text_encoder is not None and USE_PEFT_BACKEND: scale_lora_layers(self.text_encoder, lora_scale) if self.text_encoder_2 is not None and USE_PEFT_BACKEND: scale_lora_layers(self.text_encoder_2, lora_scale)
prompt = [prompt] if isinstance(prompt, str) else prompt
if prompt_embeds is None: prompt_2 = prompt_2 or prompt prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
# We only use the pooled prompt output from the CLIPTextModel pooled_prompt_embeds = self._get_clip_prompt_embeds( prompt=prompt, device=device, num_images_per_prompt=num_images_per_prompt, ) prompt_embeds = self._get_t5_prompt_embeds( prompt=prompt_2, num_images_per_prompt=num_images_per_prompt, max_sequence_length=max_sequence_length, device=device, )
if self.text_encoder is not None: if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND: # Retrieve the original scale by scaling back the LoRA layers unscale_lora_layers(self.text_encoder, lora_scale)
if self.text_encoder_2 is not None: if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND: # Retrieve the original scale by scaling back the LoRA layers unscale_lora_layers(self.text_encoder_2, lora_scale)
dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
return prompt_embeds, pooled_prompt_embeds, text_ids
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.encode_image def encode_image(self, image, device, num_images_per_prompt): dtype = next(self.image_encoder.parameters()).dtype
if not isinstance(image, torch.Tensor): image = self.feature_extractor(image, return_tensors="pt").pixel_values
image = image.to(device=device, dtype=dtype) image_embeds = self.image_encoder(image).image_embeds image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0) return image_embeds
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.prepare_ip_adapter_image_embeds def prepare_ip_adapter_image_embeds( self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt ): image_embeds = [] if ip_adapter_image_embeds is None: if not isinstance(ip_adapter_image, list): ip_adapter_image = [ip_adapter_image]
if len(ip_adapter_image) != self.transformer.encoder_hid_proj.num_ip_adapters: raise ValueError( f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {self.transformer.encoder_hid_proj.num_ip_adapters} IP Adapters." )
for single_ip_adapter_image in ip_adapter_image: single_image_embeds = self.encode_image(single_ip_adapter_image, device, 1) image_embeds.append(single_image_embeds[None, :]) else: if not isinstance(ip_adapter_image_embeds, list): ip_adapter_image_embeds = [ip_adapter_image_embeds]
if len(ip_adapter_image_embeds) != self.transformer.encoder_hid_proj.num_ip_adapters: raise ValueError( f"`ip_adapter_image_embeds` must have same length as the number of IP Adapters. Got {len(ip_adapter_image_embeds)} image embeds and {self.transformer.encoder_hid_proj.num_ip_adapters} IP Adapters." )
for single_image_embeds in ip_adapter_image_embeds: image_embeds.append(single_image_embeds)
ip_adapter_image_embeds = [] for single_image_embeds in image_embeds: single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0) single_image_embeds = single_image_embeds.to(device=device) ip_adapter_image_embeds.append(single_image_embeds)
return ip_adapter_image_embeds
def check_inputs( self, prompt, prompt_2, height, width, negative_prompt=None, negative_prompt_2=None, prompt_embeds=None, negative_prompt_embeds=None, pooled_prompt_embeds=None, negative_pooled_prompt_embeds=None, callback_on_step_end_tensor_inputs=None, max_sequence_length=None, ): if height % (self.vae_scale_factor * 2) != 0 or width % (self.vae_scale_factor * 2) != 0: logger.warning( f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly" )
if callback_on_step_end_tensor_inputs is not None and not all( k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs ): raise ValueError( f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}" )
if prompt is not None and prompt_embeds is not None: raise ValueError( f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" " only forward one of the two." ) elif prompt_2 is not None and prompt_embeds is not None: raise ValueError( f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to" " only forward one of the two." ) elif prompt is None and prompt_embeds is None: raise ValueError( "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." ) elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)): raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
if negative_prompt is not None and negative_prompt_embeds is not None: raise ValueError( f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:" f" {negative_prompt_embeds}. Please make sure to only forward one of the two." ) elif negative_prompt_2 is not None and negative_prompt_embeds is not None: raise ValueError( f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:" f" {negative_prompt_embeds}. Please make sure to only forward one of the two." )
if prompt_embeds is not None and negative_prompt_embeds is not None: if prompt_embeds.shape != negative_prompt_embeds.shape: raise ValueError( "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" f" {negative_prompt_embeds.shape}." )
if prompt_embeds is not None and pooled_prompt_embeds is None: raise ValueError( "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`." ) if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None: raise ValueError( "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`." )
if max_sequence_length is not None and max_sequence_length > 512: raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
@staticmethod # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._prepare_latent_image_ids def _prepare_latent_image_ids(batch_size, height, width, device, dtype): latent_image_ids = torch.zeros(height, width, 3) latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height)[:, None] latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width)[None, :]
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
latent_image_ids = latent_image_ids.reshape( latent_image_id_height * latent_image_id_width, latent_image_id_channels )
return latent_image_ids.to(device=device, dtype=dtype)
@staticmethod # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._pack_latents def _pack_latents(latents, batch_size, num_channels_latents, height, width): latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2) latents = latents.permute(0, 2, 4, 1, 3, 5) latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
return latents
@staticmethod # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._unpack_latents def _unpack_latents(latents, height, width, vae_scale_factor): batch_size, num_patches, channels = latents.shape
# VAE applies 8x compression on images but we must also account for packing which requires # latent height and width to be divisible by 2. height = 2 * (int(height) // (vae_scale_factor * 2)) width = 2 * (int(width) // (vae_scale_factor * 2))
latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2) latents = latents.permute(0, 3, 1, 4, 2, 5)
latents = latents.reshape(batch_size, channels // (2 * 2), height, width)
return latents
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.prepare_latents def prepare_latents( self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None, ): # VAE applies 8x compression on images but we must also account for packing which requires # latent height and width to be divisible by 2. height = 2 * (int(height) // (self.vae_scale_factor * 2)) width = 2 * (int(width) // (self.vae_scale_factor * 2))
shape = (batch_size, num_channels_latents, height, width)
if latents is not None: latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype) return latents.to(device=device, dtype=dtype), latent_image_ids
if isinstance(generator, list) and len(generator) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." )
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype) latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
return latents, latent_image_ids
# Copied from diffusers.pipelines.controlnet_sd3.pipeline_stable_diffusion_3_controlnet.StableDiffusion3ControlNetPipeline.prepare_image def prepare_image( self, image, width, height, batch_size, num_images_per_prompt, device, dtype, do_classifier_free_guidance=False, guess_mode=False, ): if isinstance(image, torch.Tensor): pass else: image = self.image_processor.preprocess(image, height=height, width=width)
image_batch_size = image.shape[0]
if image_batch_size == 1: repeat_by = batch_size else: # image batch size is the same as prompt batch size repeat_by = num_images_per_prompt
image = image.repeat_interleave(repeat_by, dim=0)
image = image.to(device=device, dtype=dtype)
if do_classifier_free_guidance and not guess_mode: image = torch.cat([image] * 2)
return image
@property def guidance_scale(self): return self._guidance_scale
@property def joint_attention_kwargs(self): return self._joint_attention_kwargs
@property def num_timesteps(self): return self._num_timesteps
@property def interrupt(self): return self._interrupt
@torch.no_grad() @replace_example_docstring(EXAMPLE_DOC_STRING) def __call__( self, prompt: Union[str, List[str]] = None, prompt_2: Optional[Union[str, List[str]]] = None, negative_prompt: Union[str, List[str]] = None, negative_prompt_2: Optional[Union[str, List[str]]] = None, true_cfg_scale: float = 1.0, height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 28, sigmas: Optional[List[float]] = None, guidance_scale: float = 7.0, control_guidance_start: Union[float, List[float]] = 0.0, control_guidance_end: Union[float, List[float]] = 1.0, control_image: PipelineImageInput = None, control_mode: Optional[Union[int, List[int]]] = None, controlnet_conditioning_scale: Union[float, List[float]] = 1.0, num_images_per_prompt: Optional[int] = 1, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.FloatTensor] = None, prompt_embeds: Optional[torch.FloatTensor] = None, pooled_prompt_embeds: Optional[torch.FloatTensor] = None, ip_adapter_image: Optional[PipelineImageInput] = None, ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None, negative_ip_adapter_image: Optional[PipelineImageInput] = None, negative_ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None, negative_prompt_embeds: Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None, output_type: Optional[str] = "pil", return_dict: bool = True, joint_attention_kwargs: Optional[Dict[str, Any]] = None, callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None, callback_on_step_end_tensor_inputs: List[str] = ["latents"], max_sequence_length: int = 512, ): r""" Function invoked when calling the pipeline for generation.
Args: prompt (`str` or `List[str]`, *optional*): The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. instead. prompt_2 (`str` or `List[str]`, *optional*): The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is will be used instead height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): The height in pixels of the generated image. This is set to 1024 by default for the best results. width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): The width in pixels of the generated image. This is set to 1024 by default for the best results. num_inference_steps (`int`, *optional*, defaults to 50): The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference. sigmas (`List[float]`, *optional*): Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed will be used. guidance_scale (`float`, *optional*, defaults to 7.0): Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). `guidance_scale` is defined as `w` of equation 2. of [Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, usually at the expense of lower image quality. control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0): The percentage of total steps at which the ControlNet starts applying. control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0): The percentage of total steps at which the ControlNet stops applying. control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,: `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`): The ControlNet input condition to provide guidance to the `unet` for generation. If the type is specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`, images must be passed as a list such that each element of the list can be correctly batched for input to a single ControlNet. controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0): The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set the corresponding scale as a list. control_mode (`int` or `List[int]`,, *optional*, defaults to None): The control mode when applying ControlNet-Union. num_images_per_prompt (`int`, *optional*, defaults to 1): The number of images to generate per prompt. generator (`torch.Generator` or `List[torch.Generator]`, *optional*): One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation deterministic. latents (`torch.FloatTensor`, *optional*): Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor will ge generated by sampling using the supplied random `generator`. prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument. pooled_prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, pooled text embeddings will be generated from `prompt` input argument. ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters. ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*): Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. If not provided, embeddings are computed from the `ip_adapter_image` input argument. negative_ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters. negative_ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*): Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. If not provided, embeddings are computed from the `ip_adapter_image` input argument. output_type (`str`, *optional*, defaults to `"pil"`): The output format of the generate image. Choose between [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple. joint_attention_kwargs (`dict`, *optional*): A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under `self.processor` in [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). callback_on_step_end (`Callable`, *optional*): A function that calls at the end of each denoising steps during the inference. The function is called with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by `callback_on_step_end_tensor_inputs`. callback_on_step_end_tensor_inputs (`List`, *optional*): The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the `._callback_tensor_inputs` attribute of your pipeline class. max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
Examples:
Returns: [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated images. """
height = height or self.default_sample_size * self.vae_scale_factor width = width or self.default_sample_size * self.vae_scale_factor
if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list): control_guidance_start = len(control_guidance_end) * [control_guidance_start] elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list): control_guidance_end = len(control_guidance_start) * [control_guidance_end] elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list): mult = len(self.controlnet.nets) if isinstance(self.controlnet, FluxMultiControlNetModel) else 1 control_guidance_start, control_guidance_end = ( mult * [control_guidance_start], mult * [control_guidance_end], )
# 1. Check inputs. Raise error if not correct self.check_inputs( prompt, prompt_2, height, width, negative_prompt=negative_prompt, negative_prompt_2=negative_prompt_2, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, negative_pooled_prompt_embeds=negative_pooled_prompt_embeds, callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs, max_sequence_length=max_sequence_length, )
self._guidance_scale = guidance_scale self._joint_attention_kwargs = joint_attention_kwargs self._interrupt = False
# 2. Define call parameters if prompt is not None and isinstance(prompt, str): batch_size = 1 elif prompt is not None and isinstance(prompt, list): batch_size = len(prompt) else: batch_size = prompt_embeds.shape[0]
device = self._execution_device dtype = self.transformer.dtype
# 3. Prepare text embeddings lora_scale = ( self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None ) do_true_cfg = true_cfg_scale > 1 and negative_prompt is not None ( prompt_embeds, pooled_prompt_embeds, text_ids, ) = self.encode_prompt( prompt=prompt, prompt_2=prompt_2, prompt_embeds=prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, device=device, num_images_per_prompt=num_images_per_prompt, max_sequence_length=max_sequence_length, lora_scale=lora_scale, ) if do_true_cfg: ( negative_prompt_embeds, negative_pooled_prompt_embeds, _, ) = self.encode_prompt( prompt=negative_prompt, prompt_2=negative_prompt_2, prompt_embeds=negative_prompt_embeds, pooled_prompt_embeds=negative_pooled_prompt_embeds, device=device, num_images_per_prompt=num_images_per_prompt, max_sequence_length=max_sequence_length, lora_scale=lora_scale, )
# 3. Prepare control image num_channels_latents = self.transformer.config.in_channels // 4 if isinstance(self.controlnet, FluxControlNetModel): control_image = self.prepare_image( image=control_image, width=width, height=height, batch_size=batch_size * num_images_per_prompt, num_images_per_prompt=num_images_per_prompt, device=device, dtype=self.vae.dtype, ) height, width = control_image.shape[-2:]
# xlab controlnet has a input_hint_block and instantx controlnet does not controlnet_blocks_repeat = False if self.controlnet.input_hint_block is None else True if self.controlnet.input_hint_block is None: # vae encode control_image = retrieve_latents(self.vae.encode(control_image), generator=generator) control_image = (control_image - self.vae.config.shift_factor) * self.vae.config.scaling_factor
# pack height_control_image, width_control_image = control_image.shape[2:] control_image = self._pack_latents( control_image, batch_size * num_images_per_prompt, num_channels_latents, height_control_image, width_control_image, )
# Here we ensure that `control_mode` has the same length as the control_image. if control_mode is not None: if not isinstance(control_mode, int): raise ValueError(" For `FluxControlNet`, `control_mode` should be an `int` or `None`") control_mode = torch.tensor(control_mode).to(device, dtype=torch.long) control_mode = control_mode.view(-1, 1).expand(control_image.shape[0], 1)
elif isinstance(self.controlnet, FluxMultiControlNetModel): control_images = [] # xlab controlnet has a input_hint_block and instantx controlnet does not controlnet_blocks_repeat = False if self.controlnet.nets[0].input_hint_block is None else True for i, control_image_ in enumerate(control_image): control_image_ = self.prepare_image( image=control_image_, width=width, height=height, batch_size=batch_size * num_images_per_prompt, num_images_per_prompt=num_images_per_prompt, device=device, dtype=self.vae.dtype, ) height, width = control_image_.shape[-2:]
if self.controlnet.nets[0].input_hint_block is None: # vae encode control_image_ = retrieve_latents(self.vae.encode(control_image_), generator=generator) control_image_ = (control_image_ - self.vae.config.shift_factor) * self.vae.config.scaling_factor
# pack height_control_image, width_control_image = control_image_.shape[2:] control_image_ = self._pack_latents( control_image_, batch_size * num_images_per_prompt, num_channels_latents, height_control_image, width_control_image, ) control_images.append(control_image_)
control_image = control_images
# Here we ensure that `control_mode` has the same length as the control_image. if isinstance(control_mode, list) and len(control_mode) != len(control_image): raise ValueError( "For Multi-ControlNet, `control_mode` must be a list of the same " + " length as the number of controlnets (control images) specified" ) if not isinstance(control_mode, list): control_mode = [control_mode] * len(control_image) # set control mode control_modes = [] for cmode in control_mode: if cmode is None: cmode = -1 control_mode = torch.tensor(cmode).expand(control_images[0].shape[0]).to(device, dtype=torch.long) control_modes.append(control_mode) control_mode = control_modes
# 4. Prepare latent variables num_channels_latents = self.transformer.config.in_channels // 4 latents, latent_image_ids = self.prepare_latents( batch_size * num_images_per_prompt, num_channels_latents, height, width, prompt_embeds.dtype, device, generator, latents, )
# 5. Prepare timesteps sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas image_seq_len = latents.shape[1] mu = calculate_shift( image_seq_len, self.scheduler.config.get("base_image_seq_len", 256), self.scheduler.config.get("max_image_seq_len", 4096), self.scheduler.config.get("base_shift", 0.5), self.scheduler.config.get("max_shift", 1.15), ) timesteps, num_inference_steps = retrieve_timesteps( self.scheduler, num_inference_steps, device, sigmas=sigmas, mu=mu, )
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0) self._num_timesteps = len(timesteps)
# 6. Create tensor stating which controlnets to keep controlnet_keep = [] for i in range(len(timesteps)): keeps = [ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e) for s, e in zip(control_guidance_start, control_guidance_end) ] controlnet_keep.append(keeps[0] if isinstance(self.controlnet, FluxControlNetModel) else keeps)
if (ip_adapter_image is not None or ip_adapter_image_embeds is not None) and ( negative_ip_adapter_image is None and negative_ip_adapter_image_embeds is None ): negative_ip_adapter_image = np.zeros((width, height, 3), dtype=np.uint8) elif (ip_adapter_image is None and ip_adapter_image_embeds is None) and ( negative_ip_adapter_image is not None or negative_ip_adapter_image_embeds is not None ): ip_adapter_image = np.zeros((width, height, 3), dtype=np.uint8)
if self.joint_attention_kwargs is None: self._joint_attention_kwargs = {}
image_embeds = None negative_image_embeds = None if ip_adapter_image is not None or ip_adapter_image_embeds is not None: image_embeds = self.prepare_ip_adapter_image_embeds( ip_adapter_image, ip_adapter_image_embeds, device, batch_size * num_images_per_prompt, ) if negative_ip_adapter_image is not None or negative_ip_adapter_image_embeds is not None: negative_image_embeds = self.prepare_ip_adapter_image_embeds( negative_ip_adapter_image, negative_ip_adapter_image_embeds, device, batch_size * num_images_per_prompt, )
# 7. Denoising loop with self.progress_bar(total=num_inference_steps) as progress_bar: for i, t in enumerate(timesteps): if self.interrupt: continue
if image_embeds is not None: self._joint_attention_kwargs["ip_adapter_image_embeds"] = image_embeds # broadcast to batch dimension in a way that's compatible with ONNX/Core ML timestep = t.expand(latents.shape[0]).to(latents.dtype)
if isinstance(self.controlnet, FluxMultiControlNetModel): use_guidance = self.controlnet.nets[0].config.guidance_embeds else: use_guidance = self.controlnet.config.guidance_embeds
guidance = torch.tensor([guidance_scale], device=device) if use_guidance else None guidance = guidance.expand(latents.shape[0]) if guidance is not None else None
if isinstance(controlnet_keep[i], list): cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])] else: controlnet_cond_scale = controlnet_conditioning_scale if isinstance(controlnet_cond_scale, list): controlnet_cond_scale = controlnet_cond_scale[0] cond_scale = controlnet_cond_scale * controlnet_keep[i]
# controlnet controlnet_block_samples, controlnet_single_block_samples = self.controlnet( hidden_states=latents, controlnet_cond=control_image, controlnet_mode=control_mode, conditioning_scale=cond_scale, timestep=timestep / 1000, guidance=guidance, pooled_projections=pooled_prompt_embeds, encoder_hidden_states=prompt_embeds, txt_ids=text_ids, img_ids=latent_image_ids, joint_attention_kwargs=self.joint_attention_kwargs, return_dict=False, )
guidance = ( torch.tensor([guidance_scale], device=device) if self.transformer.config.guidance_embeds else None ) guidance = guidance.expand(latents.shape[0]) if guidance is not None else None
noise_pred = self.transformer( hidden_states=latents, timestep=timestep / 1000, guidance=guidance, pooled_projections=pooled_prompt_embeds, encoder_hidden_states=prompt_embeds, controlnet_block_samples=controlnet_block_samples, controlnet_single_block_samples=controlnet_single_block_samples, txt_ids=text_ids, img_ids=latent_image_ids, joint_attention_kwargs=self.joint_attention_kwargs, return_dict=False, controlnet_blocks_repeat=controlnet_blocks_repeat, )[0]
if do_true_cfg: if negative_image_embeds is not None: self._joint_attention_kwargs["ip_adapter_image_embeds"] = negative_image_embeds neg_noise_pred = self.transformer( hidden_states=latents, timestep=timestep / 1000, guidance=guidance, pooled_projections=negative_pooled_prompt_embeds, encoder_hidden_states=negative_prompt_embeds, controlnet_block_samples=controlnet_block_samples, controlnet_single_block_samples=controlnet_single_block_samples, txt_ids=text_ids, img_ids=latent_image_ids, joint_attention_kwargs=self.joint_attention_kwargs, return_dict=False, controlnet_blocks_repeat=controlnet_blocks_repeat, )[0] noise_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
# compute the previous noisy sample x_t -> x_t-1 latents_dtype = latents.dtype latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
if latents.dtype != latents_dtype: if torch.backends.mps.is_available(): # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272 latents = latents.to(latents_dtype)
if callback_on_step_end is not None: callback_kwargs = {} for k in callback_on_step_end_tensor_inputs: callback_kwargs[k] = locals()[k] callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
latents = callback_outputs.pop("latents", latents) prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) control_image = callback_outputs.pop("control_image", control_image)
# call the callback, if provided if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): progress_bar.update()
if XLA_AVAILABLE: xm.mark_step()
if output_type == "latent": image = latents
else: latents = self._unpack_latents(latents, height, width, self.vae_scale_factor) latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
image = self.vae.decode(latents, return_dict=False)[0] image = self.image_processor.postprocess(image, output_type=output_type)
# Offload all models self.maybe_free_model_hooks()
if not return_dict: return (image,)
return FluxPipelineOutput(images=image)BiRefNet/README.mdAdded+8
BiRefNet/RMBG-2.0/BiRefNet_config.pyAdded+11
BiRefNet/RMBG-2.0/birefnet.pyAdded+2244
BiRefNet/RMBG-2.0/config.jsonAdded+21
BiRefNet/RMBG-2.0/diagram1.pngAdded

BiRefNet/RMBG-2.0/preprocessor_config.jsonAdded+23
Joy_caption/README.mdAdded+79
Joy_caption/app.pyAdded+536
Joy_caption/cgrkzexw-599808/config.yamlAdded+39
Joy_caption/cgrkzexw-599808/text_model/README.mdAdded+202
Joy_caption/cgrkzexw-599808/text_model/adapter_config.jsonAdded+34
Joy_caption/cgrkzexw-599808/text_model/tokenizer.jsonAdded
Joy_caption/joycaption_alpha_two_cli_mod.ipynbAdded+46
Joy_caption/requirements.txtAdded+10
LLM/Florence-2-base-PromptGen-v2.0/configuration_florence2.pyAdded+340
LLM/Florence-2-base-PromptGen-v2.0/generation_config.jsonAdded+13
LLM/Florence-2-base-PromptGen-v2.0/merges.txtAdded
LLM/Florence-2-base-PromptGen-v2.0/processing_florence2.pyAdded+1088
LLM/Florence-2-large-PromptGen-v2.0/README.mdAdded+71
LLM/Florence-2-large-PromptGen-v2.0/added_tokens.jsonAdded+1026
LLM/Florence-2-large-PromptGen-v2.0/config.jsonAdded+138
LLM/Florence-2-large-PromptGen-v2.0/configuration_florence2.pyAdded+340
LLM/Florence-2-large-PromptGen-v2.0/generation_config.jsonAdded+4
LLM/Florence-2-large-PromptGen-v2.0/merges.txtAdded
LLM/Florence-2-large-PromptGen-v2.0/modeling_florence2.pyAdded
LLM/Florence-2-large-PromptGen-v2.0/preprocessor_config.jsonAdded+33
LLM/Florence-2-large-PromptGen-v2.0/processing_florence2.pyAdded+1088
LLM/Florence-2-large-PromptGen-v2.0/special_tokens_map.jsonAdded
LLM/Florence-2-large-PromptGen-v2.0/tokenizer.jsonAdded
LLM/Florence-2-large-PromptGen-v2.0/tokenizer_config.jsonAdded
LLM/Florence-2-large-PromptGen-v2.0/vocab.jsonAdded
LLM/Llama-3.1-8B-Lexi-Uncensored-V2/README.mdAdded+155
LLM/Llama-3.1-8B-Lexi-Uncensored-V2/config.jsonAdded+41
LLM/Llama-3.1-8B-Lexi-Uncensored-V2/generation_config.jsonAdded+14
LLM/Llama-3.1-8B-Lexi-Uncensored-V2/model.safetensors.index.jsonAdded+298
LLM/Llama-3.1-8B-Lexi-Uncensored-V2/special_tokens_map.jsonAdded+23
LLM/Llama-3.1-8B-Lexi-Uncensored-V2/tokenizer.jsonAdded
LLM/Llama-3.1-8B-Lexi-Uncensored-V2/tokenizer_config.jsonAdded+2064
clip/siglip-so400m-patch14-384/README.mdAdded+112
clip/siglip-so400m-patch14-384/config.jsonAdded+25
clip/siglip-so400m-patch14-384/preprocessor_config.jsonAdded+23
clip/siglip-so400m-patch14-384/special_tokens_map.jsonAdded+23
clip/siglip-so400m-patch14-384/tokenizer.jsonAdded
clip/siglip-so400m-patch14-384/tokenizer_config.jsonAdded+33
clip_interrogator/models--timm--vit_large_patch14_clip_224.openai/refs/mainAdded+1
controlnet/FLUX.1/FLUX.1-dev-ControlNet-Union-Pro-2.0/README.mdAdded+154
controlnet/FLUX.1/FLUX.1-dev-ControlNet-Union-Pro-2.0/conds/canny.pngAdded

controlnet/FLUX.1/FLUX.1-dev-ControlNet-Union-Pro-2.0/config.jsonAdded+19
controlnet/FLUX.1/FLUX.1-dev-ControlNet-Union-Pro-2.0/controlnet_flux.pyAdded+509
controlnet/FLUX.1/FLUX.1-dev-ControlNet-Union-Pro-2.0/pipeline_flux_controlnet.pyAdded+1181