Upload 8 files
Browse filesFiles changed (8)
- LICENSEAdded+242
- README.md+5-4
- app.pyAdded+298
- gitattributesAdded+35
- model.pyAdded+113
- pipeline.pyAdded+471
- requirements.txtAdded+12
- style_template.pyAdded+59
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242Tencent is pleased to support the open source community by making PhotoMaker available.
Copyright (C) 2024 THL A29 Limited, a Tencent company. All rights reserved.
PhotoMaker is licensed under the Apache License Version 2.0 except for the third-party components listed below.
Terms of the Apache License Version 2.0:---------------------------------------------Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION1. Definitions.
“License” shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, “control” means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
“Object” form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, “submitted” means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a “NOTICE” text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
SDXL unstable YamerMix checkpoints follow the LICENSE with:Copyright (c) 2023 Stability AI CreativeML Open RAIL++-M License dated July 26, 2023
Section I: PREAMBLE Multimodal generative models are being widely adopted and used, andhave the potential to transform the way artists, among other individuals, conceive andbenefit from AI or ML technologies as a tool for content creation. Notwithstanding thecurrent and potential benefits that these artifacts can bring to society at large, thereare also concerns about potential misuses of them, either due to their technicallimitations or ethical considerations. In short, this license strives for both the openand responsible downstream use of the accompanying model. When it comes to the opencharacter, we took inspiration from open source permissive licenses regarding the grantof IP rights. Referring to the downstream responsible use, we added use-basedrestrictions not permitting the use of the model in very specific scenarios, in orderfor the licensor to be able to enforce the license in case potential misuses of theModel may occur. At the same time, we strive to promote open and responsible research ongenerative models for art and content generation. Even though downstream derivativeversions of the model could be released under different licensing terms, the latter willalways have to include - at minimum - the same use-based restrictions as the ones in theoriginal license (this license). We believe in the intersection between open andresponsible AI development; thus, this agreement aims to strike a balance between bothin order to enable responsible open-science in the field of AI. This CreativeML OpenRAIL++-M License governs the use of the model (and its derivatives) and is informed bythe model card associated with the model. NOW THEREFORE, You and Licensor agree asfollows: Definitions "License" means the terms and conditions for use, reproduction, andDistribution as defined in this document. "Data" means a collection of informationand/or content extracted from the dataset used with the Model, including to train,pretrain, or otherwise evaluate the Model. The Data is not licensed under this License."Output" means the results of operating a Model as embodied in informational contentresulting therefrom. "Model" means any accompanying machine-learning based assemblies(including checkpoints), consisting of learnt weights, parameters (including optimizerstates), corresponding to the model architecture as embodied in the ComplementaryMaterial, that have been trained or tuned, in whole or in part on the Data, using theComplementary Material. "Derivatives of the Model" means all modifications to the Model,works based on the Model, or any other model which is created or initialized by transferof patterns of the weights, parameters, activations or output of the Model, to the othermodel, in order to cause the other model to perform similarly to the Model, including -but not limited to - distillation methods entailing the use of intermediate datarepresentations or methods based on the generation of synthetic data by the Model fortraining the other model. "Complementary Material" means the accompanying source codeand scripts used to define, run, load, benchmark or evaluate the Model, and used toprepare data for training or evaluation, if any. This includes any accompanyingdocumentation, tutorials, examples, etc, if any. "Distribution" means any transmission,reproduction, publication or other sharing of the Model or Derivatives of the Model to athird party, including providing the Model as a hosted service made available byelectronic or other remote means - e.g. API-based or web access. "Licensor" means thecopyright owner or entity authorized by the copyright owner that is granting theLicense, including the persons or entities that may have rights in the Model and/ordistributing the Model. "You" (or "Your") means an individual or Legal Entity exercisingpermissions granted by this License and/or making use of the Model for whichever purposeand in any field of use, including usage of the Model in an end-use application - e.g.chatbot, translator, image generator. "Third Parties" means individuals or legalentities that are not under common control with Licensor or You. "Contribution" meansany work of authorship, including the original version of the Model and anymodifications or additions to that Model or Derivatives of the Model thereof, that isintentionally submitted to Licensor for inclusion in the Model by the copyright owner orby an individual or Legal Entity authorized to submit on behalf of the copyright owner.For the purposes of this definition, "submitted" means any form of electronic, verbal,or written communication sent to the Licensor or its representatives, including but notlimited to communication on electronic mailing lists, source code control systems, andissue tracking systems that are managed by, or on behalf of, the Licensor for thepurpose of discussing and improving the Model, but excluding communication that isconspicuously marked or otherwise designated in writing by the copyright owner as "Not aContribution." "Contributor" means Licensor and any individual or Legal Entity on behalfof whom a Contribution has been received by Licensor and subsequently incorporatedwithin the Model.
Section II: INTELLECTUAL PROPERTY RIGHTS Both copyright and patent grants apply to theModel, Derivatives of the Model and Complementary Material. The Model and Derivatives ofthe Model are subject to additional terms as described in
Section III. Grant of Copyright License. Subject to the terms and conditions of thisLicense, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publiclydisplay, publicly perform, sublicense, and distribute the Complementary Material, theModel, and Derivatives of the Model. Grant of Patent License. Subject to the terms andconditions of this License and where and as applicable, each Contributor hereby grantsto You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable(except as stated in this paragraph) patent license to make, have made, use, offer tosell, sell, import, and otherwise transfer the Model and the Complementary Material,where such license applies only to those patent claims licensable by such Contributorthat are necessarily infringed by their Contribution(s) alone or by combination of theirContribution(s) with the Model to which such Contribution(s) was submitted. If Youinstitute patent litigation against any entity (including a cross-claim or counterclaimin a lawsuit) alleging that the Model and/or Complementary Material or a Contributionincorporated within the Model and/or Complementary Material constitutes direct orcontributory patent infringement, then any patent licenses granted to You under thisLicense for the Model and/or Work shall terminate as of the date such litigation isasserted or filed. Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTIONDistribution and Redistribution. You may host for Third Party remote access purposes(e.g. software-as-a-service), reproduce and distribute copies of the Model orDerivatives of the Model thereof in any medium, with or without modifications, providedthat You meet the following conditions: Use-based restrictions as referenced inparagraph 5 MUST be included as an enforceable provision by You in any type of legalagreement (e.g. a license) governing the use and/or distribution of the Model orDerivatives of the Model, and You shall give notice to subsequent users You Distributeto, that the Model or Derivatives of the Model are subject to paragraph 5. Thisprovision does not apply to the use of Complementary Material. You must give any ThirdParty recipients of the Model or Derivatives of the Model a copy of this License; Youmust cause any modified files to carry prominent notices stating that You changed thefiles; You must retain all copyright, patent, trademark, and attribution noticesexcluding those notices that do not pertain to any part of the Model, Derivatives of theModel. You may add Your own copyright statement to Your modifications and may provideadditional or different license terms and conditions - respecting paragraph 4.a. - foruse, reproduction, or Distribution of Your modifications, or for any such Derivatives ofthe Model as a whole, provided Your use, reproduction, and Distribution of the Modelotherwise complies with the conditions stated in this License. Use-based restrictions.The restrictions set forth in Attachment A are considered Use-based restrictions.Therefore You cannot use the Model and the Derivatives of the Model for the specifiedrestricted uses. You may use the Model subject to this License, including only forlawful purposes and in accordance with the License. Use may include creating any contentwith, finetuning, updating, running, training, evaluating and/or reparametrizing theModel. You shall require all of Your users who use the Model or a Derivative of theModel to comply with the terms of this paragraph (paragraph 5). The Output You Generate.Except as set forth herein, Licensor claims no rights in the Output You generate usingthe Model. You are accountable for the Output you generate and its subsequent uses. Nouse of the output can contravene any provision as stated in the License.
Section IV: OTHER PROVISIONS Updates and Runtime Restrictions. To the maximum extentpermitted by law, Licensor reserves the right to restrict (remotely or otherwise) usageof the Model in violation of this License. Trademarks and related. Nothing in thisLicense permits You to make use of Licensors’ trademarks, trade names, logos or tootherwise suggest endorsement or misrepresent the relationship between the parties; andany rights not expressly granted herein are reserved by the Licensors. Disclaimer ofWarranty. Unless required by applicable law or agreed to in writing, Licensor providesthe Model and the Complementary Material (and each Contributor provides itsContributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, eitherexpress or implied, including, without limitation, any warranties or conditions ofTITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You aresolely responsible for determining the appropriateness of using or redistributing theModel, Derivatives of the Model, and the Complementary Material and assume any risksassociated with Your exercise of permissions under this License. Limitation ofLiability. In no event and under no legal theory, whether in tort (includingnegligence), contract, or otherwise, unless required by applicable law (such asdeliberate and grossly negligent acts) or agreed to in writing, shall any Contributor beliable to You for damages, including any direct, indirect, special, incidental, orconsequential damages of any character arising as a result of this License or out of theuse or inability to use the Model and the Complementary Material (including but notlimited to damages for loss of goodwill, work stoppage, computer failure or malfunction,or any and all other commercial damages or losses), even if such Contributor has beenadvised of the possibility of such damages. Accepting Warranty or Additional Liability.While redistributing the Model, Derivatives of the Model and the Complementary Materialthereof, You may choose to offer, and charge a fee for, acceptance of support, warranty,indemnity, or other liability obligations and/or rights consistent with this License.However, in accepting such obligations, You may act only on Your own behalf and on Yoursole responsibility, not on behalf of any other Contributor, and only if You agree toindemnify, defend, and hold each Contributor harmless for any liability incurred by, orclaims asserted against, such Contributor by reason of your accepting any such warrantyor additional liability. If any provision of this License is held to be invalid, illegalor unenforceable, the remaining provisions shall be unaffected thereby and remain validas if such provision had not been set forth herein.
END OF TERMS AND CONDITIONS
Attachment A Use RestrictionsYou agree not to use the Model or Derivatives of the Model:In any way that violates any applicable national, federal, state, local orinternational law or regulation; For the purpose of exploiting, harming or attempting toexploit or harm minors in any way; To generate or disseminate verifiably falseinformation and/or content with the purpose of harming others; To generate ordisseminate personal identifiable information that can be used to harm an individual; Todefame, disparage or otherwise harass others; For fully automated decision making thatadversely impacts an individual’s legal rights or otherwise creates or modifies abinding, enforceable obligation; For any use intended to or which has the effect ofdiscriminating against or harming individuals or groups based on online or offlinesocial behavior or known or predicted personal or personality characteristics; Toexploit any of the vulnerabilities of a specific group of persons based on their age,social, physical or mental characteristics, in order to materially distort the behaviorof a person pertaining to that group in a manner that causes or is likely to cause thatperson or another person physical or psychological harm; For any use intended to orwhich has the effect of discriminating against individuals or groups based on legallyprotected characteristics or categories; To provide medical advice and medical resultsinterpretation; To generate or disseminate information for the purpose to be used foradministration of justice, law enforcement, immigration or asylum processes, such aspredicting an individual will commit fraud/crime commitment (e.g. by text profiling,drawing causal relationships between assertions made in documents, indiscriminate andarbitrarily-targeted use).123456789101112---title: FaceAIemoji: 💻colorFrom: yellowcolorTo: redsdk: gradiosdk_version: 4.26.0app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213---title: PhotoMaker Styleemoji: 📷 🎨colorFrom: indigocolorTo: redsdk: gradiosdk_version: 4.14.0app_file: app.pypinned: falselicense: apache-2.0---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298import torchimport numpy as npimport randomimport os
from diffusers.utils import load_imagefrom diffusers import EulerAncestralDiscreteScheduler
from huggingface_hub import hf_hub_downloadimport spacesimport gradio as gr
from pipeline import PhotoMakerStableDiffusionXLPipelinefrom style_template import styles
# Download civitai modelscivitai_model_path = "./civitai_models"os.makedirs(civitai_model_path, exist_ok=True)base_model_name = "sdxlUnstableDiffusers_v11.safetensors"base_model_path = os.path.join(civitai_model_path, base_model_name)if not os.path.exists(base_model_path): base_model_path = hf_hub_download(repo_id="Paper99/sdxlUnstableDiffusers_v11", filename=base_model_name, repo_type="model")
lora_model_name = "xl_more_art-full.safetensors"lora_path = os.path.join(civitai_model_path, lora_model_name)if not os.path.exists(lora_path): lora_path = hf_hub_download(repo_id="Paper99/sdxlUnstableDiffusers_v11", filename=lora_model_name, repo_type="model") # global variabledevice = "cuda" if torch.cuda.is_available() else "cpu"MAX_SEED = np.iinfo(np.int32).maxSTYLE_NAMES = list(styles.keys())DEFAULT_STYLE_NAME = "(No style)"
# download PhotoMaker checkpoint to cachephotomaker_ckpt = hf_hub_download(repo_id="TencentARC/PhotoMaker", filename="photomaker-v1.bin", repo_type="model")
pipe = PhotoMakerStableDiffusionXLPipeline.from_single_file( base_model_path, torch_dtype=torch.bfloat16, original_config_file=None,).to(device)
pipe.load_photomaker_adapter( os.path.dirname(photomaker_ckpt), subfolder="", weight_name=os.path.basename(photomaker_ckpt), trigger_word="img") pipe.id_encoder.to(device)
pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)pipe.load_lora_weights(os.path.dirname(lora_path), weight_name=lora_model_name, adapter_name="xl_more_art-full")pipe.set_adapters(["photomaker", "xl_more_art-full"], adapter_weights=[1.0, 0.5])pipe.fuse_lora()
@spaces.GPUdef generate_image(upload_images, prompt, negative_prompt, style_name, num_steps, style_strength_ratio, num_outputs, guidance_scale, seed, progress=gr.Progress(track_tqdm=True)): # check the trigger word image_token_id = pipe.tokenizer.convert_tokens_to_ids(pipe.trigger_word) input_ids = pipe.tokenizer.encode(prompt) if image_token_id not in input_ids: raise gr.Error(f"Cannot find the trigger word '{pipe.trigger_word}' in text prompt! Please refer to step 2️⃣")
if input_ids.count(image_token_id) > 1: raise gr.Error(f"Cannot use multiple trigger words '{pipe.trigger_word}' in text prompt!")
# apply the style template prompt, negative_prompt = apply_style(style_name, prompt, negative_prompt)
if upload_images is None: raise gr.Error(f"Cannot find any input face image! Please refer to step 1️⃣")
input_id_images = [] for img in upload_images: input_id_images.append(load_image(img)) generator = torch.Generator(device=device).manual_seed(seed)
print("Start inference...") print(f"[Debug] Prompt: {prompt}, \n[Debug] Neg Prompt: {negative_prompt}") start_merge_step = int(float(style_strength_ratio) / 100 * num_steps) if start_merge_step > 30: start_merge_step = 30 print(start_merge_step) images = pipe( prompt=prompt, input_id_images=input_id_images, negative_prompt=negative_prompt, num_images_per_prompt=num_outputs, num_inference_steps=num_steps, start_merge_step=start_merge_step, generator=generator, guidance_scale=guidance_scale, ).images return images, gr.update(visible=True)
def swap_to_gallery(images): return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
def upload_example_to_gallery(images, prompt, style, negative_prompt): return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
def remove_back_to_files(): return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True) def remove_tips(): return gr.update(visible=False)
def randomize_seed_fn(seed: int, randomize_seed: bool) -> int: if randomize_seed: seed = random.randint(0, MAX_SEED) return seed
def apply_style(style_name: str, positive: str, negative: str = "") -> tuple[str, str]: p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME]) return p.replace("{prompt}", positive), n + ' ' + negative
def get_image_path_list(folder_name): image_basename_list = os.listdir(folder_name) image_path_list = sorted([os.path.join(folder_name, basename) for basename in image_basename_list]) return image_path_list
def get_example(): case = [ [ get_image_path_list('./examples/yangmi_woman'), "a woman img, retro futurism, retro game art style but extremely beautiful, intricate details, masterpiece, best quality, space-themed, cosmic, celestial, stars, galaxies, nebulas, planets, science fiction, highly detailed", 35, "realistic, photo-realistic, worst quality, greyscale, bad anatomy, bad hands, error, text", ], [ get_image_path_list('./examples/lenna_woman'), "A girl img riding dragon over a whimsical castle, 3d CGI, art by Pixar, half-body, screenshot from animation", 20, "realistic, photo-realistic, bad quality, bad anatomy, worst quality, low quality, lowres, extra fingers, blur, blurry, ugly, wrong proportions, watermark, image artifacts, bad eyes", ], ] return case
### Description and stylelogo = r"""<center><img src='https://photo-maker.github.io/assets/logo.png' alt='PhotoMaker logo' style="width:80px; margin-bottom:10px"></center>"""title = r"""<h1 align="center">PhotoMaker: Customizing Realistic Human Photos via Stacked ID Embedding</h1><h3 align="center">-- Stylization version --</h3>"""
description = r"""<b>Official 🤗 Gradio demo</b> for <a href='https://github.com/TencentARC/PhotoMaker' target='_blank'><b>PhotoMaker: Customizing Realistic Human Photos via Stacked ID Embedding</b></a>.<br><br>For photo-realistic generation, you could use our other gradio demo [PhotoMaker](https://huggingface.co/spaces/TencentARC/PhotoMaker).<br>❗️❗️❗️[<b>Important</b>] Personalization steps:<br>1️⃣ Upload images of someone you want to customize. One image is ok, but more is better. Although we do not perform face detection, the face in the uploaded image should <b>occupy the majority of the image</b>.<br>2️⃣ Enter a text prompt, making sure to <b>follow the class word</b> you want to customize with the <b>trigger word</b>: `img`, such as: `man img` or `woman img` or `girl img`.<br>3️⃣ Choose your preferred style template.<br>4️⃣ Click the <b>Submit</b> button to start customizing."""
article = r"""
If PhotoMaker is helpful, please help to ⭐ the <a href='https://github.com/TencentARC/PhotoMaker' target='_blank'>Github Repo</a>. Thanks! [](https://github.com/TencentARC/PhotoMaker)---📝 **Citation**<br>If our work is useful for your research, please consider citing:
```bibtex@inproceedings{li2023photomaker, title={PhotoMaker: Customizing Realistic Human Photos via Stacked ID Embedding}, author={Li, Zhen and Cao, Mingdeng and Wang, Xintao and Qi, Zhongang and Cheng, Ming-Ming and Shan, Ying}, booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2024}}```📋 **License**<br>Apache-2.0 LICENSE. Please refer to the [LICENSE file](https://huggingface.co/TencentARC/PhotoMaker/blob/main/LICENSE) for details.
📧 **Contact**<br>If you have any questions, please feel free to reach me out at <b>zhenli1031@gmail.com</b>."""
tips = r"""### Usage tips of PhotoMaker1. Upload more photos of the person to be customized to **improve ID fidelty**. If the input is Asian face(s), maybe consider adding 'asian' before the class word, e.g., `asian woman img`2. When stylizing, does the generated face look too realistic? Adjust the **Style strength** to 30-50, the larger the number, the less ID fidelty, but the stylization ability will be better.3. If you want to generate realistic photos, you could try switching to our other gradio application [PhotoMaker](https://huggingface.co/spaces/TencentARC/PhotoMaker).4. For **faster** speed, reduce the number of generated images and sampling steps. However, please note that reducing the sampling steps may compromise the ID fidelity."""# 3. Don't make the prompt too long, as we will trim it if it exceeds 77 tokens. But we will fix it in the future.
css = '''.gradio-container {width: 85% !important}'''with gr.Blocks(css=css) as demo: gr.Markdown(logo) gr.Markdown(title) gr.Markdown(description) # gr.DuplicateButton( # value="Duplicate Space for private use ", # elem_id="duplicate-button", # visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1", # ) with gr.Row(): with gr.Column(): files = gr.Files( label="Drag (Select) 1 or more photos of your face", file_types=["image"] ) uploaded_files = gr.Gallery(label="Your images", visible=False, columns=5, rows=1, height=200) with gr.Column(visible=False) as clear_button: remove_and_reupload = gr.ClearButton(value="Remove and upload new ones", components=files, size="sm") prompt = gr.Textbox(label="Prompt", info="Try something like 'a photo of a man/woman img', 'img' is the trigger word.", placeholder="A photo of a [man/woman img]...") style = gr.Dropdown(label="Style template", choices=STYLE_NAMES, value=DEFAULT_STYLE_NAME) submit = gr.Button("Submit")
with gr.Accordion(open=False, label="Advanced Options"): negative_prompt = gr.Textbox( label="Negative Prompt", placeholder="low quality", value="nsfw, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry", ) num_steps = gr.Slider( label="Number of sample steps", minimum=20, maximum=100, step=1, value=50, ) style_strength_ratio = gr.Slider( label="Style strength (%)", minimum=15, maximum=50, step=1, value=20, ) num_outputs = gr.Slider( label="Number of output images", minimum=1, maximum=4, step=1, value=2, ) guidance_scale = gr.Slider( label="Guidance scale", minimum=0.1, maximum=10.0, step=0.1, value=5, ) seed = gr.Slider( label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, ) randomize_seed = gr.Checkbox(label="Randomize seed", value=True) with gr.Column(): gallery = gr.Gallery(label="Generated Images") usage_tips = gr.Markdown(label="Usage tips of PhotoMaker", value=tips ,visible=False)
files.upload(fn=swap_to_gallery, inputs=files, outputs=[uploaded_files, clear_button, files]) remove_and_reupload.click(fn=remove_back_to_files, outputs=[uploaded_files, clear_button, files])
submit.click( fn=remove_tips, outputs=usage_tips, ).then( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, queue=False, api_name=False, ).then( fn=generate_image, inputs=[files, prompt, negative_prompt, style, num_steps, style_strength_ratio, num_outputs, guidance_scale, seed], outputs=[gallery, usage_tips] )
gr.Examples( examples=get_example(), inputs=[files, prompt, style_strength_ratio, negative_prompt], run_on_click=True, fn=upload_example_to_gallery, outputs=[uploaded_files, clear_button, files], ) gr.Markdown(article) demo.launch()1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113# Merge image encoder and fuse module to create a ID Encoder# send multiple ID images, we can directly obtain the updated text encoder containing a stacked ID embedding
import torchimport torch.nn as nnfrom transformers.models.clip.modeling_clip import CLIPVisionModelWithProjectionfrom transformers.models.clip.configuration_clip import CLIPVisionConfigfrom transformers import PretrainedConfig
VISION_CONFIG_DICT = { "hidden_size": 1024, "intermediate_size": 4096, "num_attention_heads": 16, "num_hidden_layers": 24, "patch_size": 14, "projection_dim": 768}
class MLP(nn.Module): def __init__(self, in_dim, out_dim, hidden_dim, use_residual=True): super().__init__() if use_residual: assert in_dim == out_dim self.layernorm = nn.LayerNorm(in_dim) self.fc1 = nn.Linear(in_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, out_dim) self.use_residual = use_residual self.act_fn = nn.GELU()
def forward(self, x): residual = x x = self.layernorm(x) x = self.fc1(x) x = self.act_fn(x) x = self.fc2(x) if self.use_residual: x = x + residual return x
class FuseModule(nn.Module): def __init__(self, embed_dim): super().__init__() self.mlp1 = MLP(embed_dim * 2, embed_dim, embed_dim, use_residual=False) self.mlp2 = MLP(embed_dim, embed_dim, embed_dim, use_residual=True) self.layer_norm = nn.LayerNorm(embed_dim)
def fuse_fn(self, prompt_embeds, id_embeds): stacked_id_embeds = torch.cat([prompt_embeds, id_embeds], dim=-1) stacked_id_embeds = self.mlp1(stacked_id_embeds) + prompt_embeds stacked_id_embeds = self.mlp2(stacked_id_embeds) stacked_id_embeds = self.layer_norm(stacked_id_embeds) return stacked_id_embeds
def forward( self, prompt_embeds, id_embeds, class_tokens_mask, ) -> torch.Tensor: # id_embeds shape: [b, max_num_inputs, 1, 2048] id_embeds = id_embeds.to(prompt_embeds.dtype) num_inputs = class_tokens_mask.sum().unsqueeze(0) # TODO: check for training case batch_size, max_num_inputs = id_embeds.shape[:2] # seq_length: 77 seq_length = prompt_embeds.shape[1] # flat_id_embeds shape: [b*max_num_inputs, 1, 2048] flat_id_embeds = id_embeds.view( -1, id_embeds.shape[-2], id_embeds.shape[-1] ) # valid_id_mask [b*max_num_inputs] valid_id_mask = ( torch.arange(max_num_inputs, device=flat_id_embeds.device)[None, :] < num_inputs[:, None] ) valid_id_embeds = flat_id_embeds[valid_id_mask.flatten()]
prompt_embeds = prompt_embeds.view(-1, prompt_embeds.shape[-1]) class_tokens_mask = class_tokens_mask.view(-1) valid_id_embeds = valid_id_embeds.view(-1, valid_id_embeds.shape[-1]) # slice out the image token embeddings image_token_embeds = prompt_embeds[class_tokens_mask] stacked_id_embeds = self.fuse_fn(image_token_embeds, valid_id_embeds) assert class_tokens_mask.sum() == stacked_id_embeds.shape[0], f"{class_tokens_mask.sum()} != {stacked_id_embeds.shape[0]}" prompt_embeds.masked_scatter_(class_tokens_mask[:, None], stacked_id_embeds.to(prompt_embeds.dtype)) updated_prompt_embeds = prompt_embeds.view(batch_size, seq_length, -1) return updated_prompt_embeds
class PhotoMakerIDEncoder(CLIPVisionModelWithProjection): def __init__(self): super().__init__(CLIPVisionConfig(**VISION_CONFIG_DICT)) self.visual_projection_2 = nn.Linear(1024, 1280, bias=False) self.fuse_module = FuseModule(2048)
def forward(self, id_pixel_values, prompt_embeds, class_tokens_mask): b, num_inputs, c, h, w = id_pixel_values.shape id_pixel_values = id_pixel_values.view(b * num_inputs, c, h, w)
shared_id_embeds = self.vision_model(id_pixel_values)[1] id_embeds = self.visual_projection(shared_id_embeds) id_embeds_2 = self.visual_projection_2(shared_id_embeds)
id_embeds = id_embeds.view(b, num_inputs, 1, -1) id_embeds_2 = id_embeds_2.view(b, num_inputs, 1, -1)
id_embeds = torch.cat((id_embeds, id_embeds_2), dim=-1) updated_prompt_embeds = self.fuse_module(prompt_embeds, id_embeds, class_tokens_mask)
return updated_prompt_embeds
if __name__ == "__main__": PhotoMakerIDEncoder()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471from typing import Any, Callable, Dict, List, Optional, Union, Tuplefrom collections import OrderedDictimport osimport PILimport numpy as np
import torchfrom torchvision import transforms as T
from safetensors import safe_openfrom huggingface_hub.utils import validate_hf_hub_argsfrom transformers import CLIPImageProcessor, CLIPTokenizerfrom diffusers import StableDiffusionXLPipelinefrom diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutputfrom diffusers.utils import ( _get_model_file, is_transformers_available, logging,)
from model import PhotoMakerIDEncoder
PipelineImageInput = Union[ PIL.Image.Image, torch.FloatTensor, List[PIL.Image.Image], List[torch.FloatTensor],]
class PhotoMakerStableDiffusionXLPipeline(StableDiffusionXLPipeline): @validate_hf_hub_args def load_photomaker_adapter( self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], weight_name: str, subfolder: str = '', trigger_word: str = 'img', **kwargs, ): """ #TODO Parameters: pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`): Can be either:
- A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on the Hub. - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved with [`ModelMixin.save_pretrained`]. - A [torch state dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
weight_name (`str`): The subfolder location of a model file within a larger model repository on the Hub or locally.
subfolder (`str`, defaults to `""`): The subfolder location of a model file within a larger model repository on the Hub or locally.
trigger_word (`str`, *optional*, defaults to `"img"`): The subfolder location of a model file within a larger model repository on the Hub or locally. """
# Load the main state dict first. cache_dir = kwargs.pop("cache_dir", None) force_download = kwargs.pop("force_download", False) resume_download = kwargs.pop("resume_download", False) proxies = kwargs.pop("proxies", None) local_files_only = kwargs.pop("local_files_only", None) token = kwargs.pop("token", None) revision = kwargs.pop("revision", None)
user_agent = { "file_type": "attn_procs_weights", "framework": "pytorch", }
if not isinstance(pretrained_model_name_or_path_or_dict, dict): model_file = _get_model_file( pretrained_model_name_or_path_or_dict, weights_name=weight_name, cache_dir=cache_dir, force_download=force_download, resume_download=resume_download, proxies=proxies, local_files_only=local_files_only, token=token, revision=revision, subfolder=subfolder, user_agent=user_agent, ) if weight_name.endswith(".safetensors"): state_dict = {"id_encoder": {}, "lora_weights": {}} with safe_open(model_file, framework="pt", device="cpu") as f: for key in f.keys(): if key.startswith("id_encoder."): state_dict["id_encoder"][key.replace("id_encoder.", "")] = f.get_tensor(key) elif key.startswith("lora_weights."): state_dict["lora_weights"][key.replace("lora_weights.", "")] = f.get_tensor(key) else: state_dict = torch.load(model_file, map_location="cpu") else: state_dict = pretrained_model_name_or_path_or_dict
keys = list(state_dict.keys()) if keys != ["id_encoder", "lora_weights"]: raise ValueError("Required keys are (`id_encoder` and `lora_weights`) missing from the state dict.")
self.trigger_word = trigger_word # load finetuned CLIP image encoder and fuse module here if it has not been registered to the pipeline yet print(f"Loading PhotoMaker components [1] id_encoder from [{pretrained_model_name_or_path_or_dict}]...") id_encoder = PhotoMakerIDEncoder() id_encoder.load_state_dict(state_dict["id_encoder"], strict=True) id_encoder = id_encoder.to(self.device, dtype=self.unet.dtype) self.id_encoder = id_encoder self.id_image_processor = CLIPImageProcessor()
# load lora into models print(f"Loading PhotoMaker components [2] lora_weights from [{pretrained_model_name_or_path_or_dict}]") self.load_lora_weights(state_dict["lora_weights"], adapter_name="photomaker")
# Add trigger word token if self.tokenizer is not None: self.tokenizer.add_tokens([self.trigger_word], special_tokens=True) self.tokenizer_2.add_tokens([self.trigger_word], special_tokens=True)
def encode_prompt_with_trigger_word( self, prompt: str, prompt_2: Optional[str] = None, num_id_images: int = 1, device: Optional[torch.device] = None, prompt_embeds: Optional[torch.FloatTensor] = None, pooled_prompt_embeds: Optional[torch.FloatTensor] = None, class_tokens_mask: Optional[torch.LongTensor] = None, ): device = device or self._execution_device
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]
# Find the token id of the trigger word image_token_id = self.tokenizer_2.convert_tokens_to_ids(self.trigger_word)
# Define tokenizers and text encoders tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2] text_encoders = ( [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2] )
if prompt_embeds is None: prompt_2 = prompt_2 or prompt prompt_embeds_list = [] prompts = [prompt, prompt_2] for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders): input_ids = tokenizer.encode(prompt) # TODO: batch encode clean_index = 0 clean_input_ids = [] class_token_index = [] # Find out the corrresponding class word token based on the newly added trigger word token for i, token_id in enumerate(input_ids): if token_id == image_token_id: class_token_index.append(clean_index - 1) else: clean_input_ids.append(token_id) clean_index += 1
if len(class_token_index) != 1: raise ValueError( f"PhotoMaker currently does not support multiple trigger words in a single prompt.\ Trigger word: {self.trigger_word}, Prompt: {prompt}." ) class_token_index = class_token_index[0]
# Expand the class word token and corresponding mask class_token = clean_input_ids[class_token_index] clean_input_ids = clean_input_ids[:class_token_index] + [class_token] * num_id_images + \ clean_input_ids[class_token_index+1:] # Truncation or padding max_len = tokenizer.model_max_length if len(clean_input_ids) > max_len: clean_input_ids = clean_input_ids[:max_len] else: clean_input_ids = clean_input_ids + [tokenizer.pad_token_id] * ( max_len - len(clean_input_ids) )
class_tokens_mask = [True if class_token_index <= i < class_token_index+num_id_images else False \ for i in range(len(clean_input_ids))] clean_input_ids = torch.tensor(clean_input_ids, dtype=torch.long).unsqueeze(0) class_tokens_mask = torch.tensor(class_tokens_mask, dtype=torch.bool).unsqueeze(0) prompt_embeds = text_encoder( clean_input_ids.to(device), output_hidden_states=True, )
# We are only ALWAYS interested in the pooled output of the final text encoder pooled_prompt_embeds = prompt_embeds[0] prompt_embeds = prompt_embeds.hidden_states[-2] prompt_embeds_list.append(prompt_embeds)
prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device) class_tokens_mask = class_tokens_mask.to(device=device) # TODO: ignoring two-prompt case
return prompt_embeds, pooled_prompt_embeds, class_tokens_mask
@torch.no_grad() def __call__( self, prompt: Union[str, List[str]] = None, prompt_2: Optional[Union[str, List[str]]] = None, height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 50, denoising_end: Optional[float] = None, guidance_scale: float = 5.0, negative_prompt: Optional[Union[str, List[str]]] = None, negative_prompt_2: Optional[Union[str, List[str]]] = None, num_images_per_prompt: Optional[int] = 1, eta: float = 0.0, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.FloatTensor] = None, prompt_embeds: Optional[torch.FloatTensor] = None, negative_prompt_embeds: Optional[torch.FloatTensor] = None, pooled_prompt_embeds: Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None, output_type: Optional[str] = "pil", return_dict: bool = True, cross_attention_kwargs: Optional[Dict[str, Any]] = None, guidance_rescale: float = 0.0, original_size: Optional[Tuple[int, int]] = None, crops_coords_top_left: Tuple[int, int] = (0, 0), target_size: Optional[Tuple[int, int]] = None, callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, callback_steps: int = 1, # Added parameters (for PhotoMaker) input_id_images: PipelineImageInput = None, class_tokens_mask: Optional[torch.LongTensor] = None, prompt_embeds_text_only: Optional[torch.FloatTensor] = None, pooled_prompt_embeds_text_only: Optional[torch.FloatTensor] = None, start_merge_step: int = 0, ): # TODO: doc # 0. Default height and width to unet height = height or self.unet.config.sample_size * self.vae_scale_factor width = width or self.unet.config.sample_size * self.vae_scale_factor
original_size = original_size or (height, width) target_size = target_size or (height, width)
# 1. Check inputs. Raise error if not correct self.check_inputs( prompt, prompt_2, height, width, callback_steps, negative_prompt, negative_prompt_2, prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds, ) # if prompt_embeds is not None and class_tokens_mask is None: raise ValueError( "If `prompt_embeds` are provided, `class_tokens_mask` also have to be passed. Make sure to generate `class_tokens_mask` from the same tokenizer that was used to generate `prompt_embeds`." ) # check the input id images if input_id_images is None: raise ValueError( "Provide `input_id_images`. Cannot leave `input_id_images` undefined for PhotoMaker pipeline." ) if not isinstance(input_id_images, list): input_id_images = [input_id_images]
# 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
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. do_classifier_free_guidance = guidance_scale > 1.0
assert do_classifier_free_guidance
# 3. Encode input prompt num_id_images = len(input_id_images) ( prompt_embeds, pooled_prompt_embeds, class_tokens_mask, ) = self.encode_prompt_with_trigger_word( prompt=prompt, prompt_2=prompt_2, device=device, num_id_images=num_id_images, prompt_embeds=prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, class_tokens_mask=class_tokens_mask, ) # 4. Encode input prompt without the trigger word for delayed conditioning prompt_text_only = prompt.replace(" "+self.trigger_word, "") # sensitive to white space ( prompt_embeds_text_only, negative_prompt_embeds, pooled_prompt_embeds_text_only, # TODO: replace the pooled_prompt_embeds with text only prompt negative_pooled_prompt_embeds, ) = self.encode_prompt( prompt=prompt_text_only, prompt_2=prompt_2, device=device, num_images_per_prompt=num_images_per_prompt, do_classifier_free_guidance=do_classifier_free_guidance, negative_prompt=negative_prompt, negative_prompt_2=negative_prompt_2, prompt_embeds=prompt_embeds_text_only, negative_prompt_embeds=negative_prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds_text_only, negative_pooled_prompt_embeds=negative_pooled_prompt_embeds, )
# 5. Prepare the input ID images dtype = next(self.id_encoder.parameters()).dtype if not isinstance(input_id_images[0], torch.Tensor): id_pixel_values = self.id_image_processor(input_id_images, return_tensors="pt").pixel_values
id_pixel_values = id_pixel_values.unsqueeze(0).to(device=device, dtype=dtype) # TODO: multiple prompts
# 6. Get the update text embedding with the stacked ID embedding prompt_embeds = self.id_encoder(id_pixel_values, prompt_embeds, class_tokens_mask) bs_embed, seq_len, _ = prompt_embeds.shape # duplicate text embeddings 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(bs_embed * num_images_per_prompt, seq_len, -1) pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view( bs_embed * num_images_per_prompt, -1 )
# 7. Prepare timesteps self.scheduler.set_timesteps(num_inference_steps, device=device) timesteps = self.scheduler.timesteps
# 8. Prepare latent variables num_channels_latents = self.unet.config.in_channels latents = self.prepare_latents( batch_size * num_images_per_prompt, num_channels_latents, height, width, prompt_embeds.dtype, device, generator, latents, )
# 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
# 10. Prepare added time ids & embeddings if self.text_encoder_2 is None: text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1]) else: text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
add_time_ids = self._get_add_time_ids( original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype, text_encoder_projection_dim=text_encoder_projection_dim, ) add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0) add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
# 11. Denoising loop num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order with self.progress_bar(total=num_inference_steps) as progress_bar: for i, t in enumerate(timesteps): latent_model_input = ( torch.cat([latents] * 2) if do_classifier_free_guidance else latents ) latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
if i <= start_merge_step: current_prompt_embeds = torch.cat( [negative_prompt_embeds, prompt_embeds_text_only], dim=0 ) add_text_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds_text_only], dim=0) else: current_prompt_embeds = torch.cat( [negative_prompt_embeds, prompt_embeds], dim=0 ) add_text_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0) # predict the noise residual added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids} noise_pred = self.unet( latent_model_input, t, encoder_hidden_states=current_prompt_embeds, cross_attention_kwargs=cross_attention_kwargs, added_cond_kwargs=added_cond_kwargs, return_dict=False, )[0]
# perform guidance if do_classifier_free_guidance: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
if do_classifier_free_guidance and guidance_rescale > 0.0: # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
# compute the previous noisy sample x_t -> x_t-1 latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
# 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 callback is not None and i % callback_steps == 0: callback(i, t, latents)
# make sure the VAE is in float32 mode, as it overflows in float16 if self.vae.dtype == torch.float16 and self.vae.config.force_upcast: self.upcast_vae() latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
if not output_type == "latent": image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0] else: image = latents return StableDiffusionXLPipelineOutput(images=image)
# apply watermark if available # if self.watermark is not None: # image = self.watermark.apply_watermark(image)
image = self.image_processor.postprocess(image, output_type=output_type)
# Offload last model to CPU if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: self.final_offload_hook.offload()
if not return_dict: return (image,)
return StableDiffusionXLPipelineOutput(images=image)123456789101112diffusers==0.25.0torch==2.0.0torchvision==0.15.1transformers==4.36.2acceleratesafetensorseinopsonnxruntime-gpuspaces==0.19.4omegaconfpefthuggingface-hub==0.20.21234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859style_list = [ { "name": "(No style)", "prompt": "{prompt}", "negative_prompt": "", }, { "name": "Cinematic", "prompt": "cinematic still {prompt} . emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy", "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured", }, { "name": "Disney Charactor", "prompt": "A Pixar animation character of {prompt} . pixar-style, studio anime, Disney, high-quality", "negative_prompt": "lowres, bad anatomy, bad hands, text, bad eyes, bad arms, bad legs, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, blurry, grayscale, noisy, sloppy, messy, grainy, highly detailed, ultra textured, photo", }, { "name": "Digital Art", "prompt": "concept art {prompt} . digital artwork, illustrative, painterly, matte painting, highly detailed", "negative_prompt": "photo, photorealistic, realism, ugly", }, { "name": "Photographic (Default)", "prompt": "cinematic photo {prompt} . 35mm photograph, film, bokeh, professional, 4k, highly detailed", "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly", }, { "name": "Fantasy art", "prompt": "ethereal fantasy concept art of {prompt} . magnificent, celestial, ethereal, painterly, epic, majestic, magical, fantasy art, cover art, dreamy", "negative_prompt": "photographic, realistic, realism, 35mm film, dslr, cropped, frame, text, deformed, glitch, noise, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, sloppy, duplicate, mutated, black and white", }, { "name": "Neonpunk", "prompt": "neonpunk style {prompt} . cyberpunk, vaporwave, neon, vibes, vibrant, stunningly beautiful, crisp, detailed, sleek, ultramodern, magenta highlights, dark purple shadows, high contrast, cinematic, ultra detailed, intricate, professional", "negative_prompt": "painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured", }, { "name": "Enhance", "prompt": "breathtaking {prompt} . award-winning, professional, highly detailed", "negative_prompt": "ugly, deformed, noisy, blurry, distorted, grainy", }, { "name": "Comic book", "prompt": "comic {prompt} . graphic illustration, comic art, graphic novel art, vibrant, highly detailed", "negative_prompt": "photograph, deformed, glitch, noisy, realistic, stock photo", }, { "name": "Lowpoly", "prompt": "low-poly style {prompt} . low-poly game art, polygon mesh, jagged, blocky, wireframe edges, centered composition", "negative_prompt": "noisy, sloppy, messy, grainy, highly detailed, ultra textured, photo", }, { "name": "Line art", "prompt": "line art drawing {prompt} . professional, sleek, modern, minimalist, graphic, line art, vector graphics", "negative_prompt": "anime, photorealistic, 35mm film, deformed, glitch, blurry, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, mutated, realism, realistic, impressionism, expressionism, oil, acrylic", }]
styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}LICENSEAdded+242
README.md+5-4
app.pyAdded+298
gitattributesAdded+35
model.pyAdded+113
pipeline.pyAdded+471
requirements.txtAdded+12
style_template.pyAdded+59