diff --git a/InstantCharacter/License.txt b/InstantCharacter/License.txt
new file mode 100644
index 0000000..fd51b4f
--- /dev/null
+++ b/InstantCharacter/License.txt
@@ -0,0 +1,15 @@
+Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. The below software and/or models in this distribution may have been modified by THL A29 Limited ("Tencent Modifications"). All Tencent Modifications are Copyright (C) THL A29 Limited.
+
+License Terms of the InstantCharacter:
+
+--------------------------------------------------------------------
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this Software and associated documentation files, to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sublicense copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+- You agree to use the InstantCharacter only for academic, research and education purposes, and refrain from using it for any commercial or production purposes under any circumstances.
+
+- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+For avoidance of doubts, “Software” means the InstantCharacter models and their software and algorithms, including trained model weights, parameters (including optimizer states), inference-enabling code, training-enabling code and/or other elements of the foregoing made publicly available by Tencent in accordance with the License.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/InstantCharacter/Notice.txt b/InstantCharacter/Notice.txt
new file mode 100644
index 0000000..704895b
--- /dev/null
+++ b/InstantCharacter/Notice.txt
@@ -0,0 +1,102 @@
+Usage and Legal Notices:
+
+Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved. The below software and/or models may have been modified by THL A29 Limited ("Tencent Modifications"). All Tencent Modifications are Copyright (C) THL A29 Limited.
+
+License of InstantCharacter ("License") can be found in this repository called "License" except for the third-party components listed below, which is licensed under different terms. The InstantCharacter does not impose any additional limitations beyond what is outlined in the respective licenses of these third-party components. Users must comply with all terms and conditions of original licenses of these third-party components and must ensure that the usage of the third party components adheres to all relevant laws and regulations.
+
+For avoidance of doubt, InstantCharacter means the models and their software and algorithms, including trained model weights, parameters (including optimizer states), inference-enabling code, training-enabling code and/or other elements of the foregoing made publicly available by Tencent in accordance with the License.
+
+
+Other dependencies and licenses:
+
+Open Source Model Licensed under the FLUX.1 [dev] Non-Commercial License:
+
+The InstantCharacter project under this repository does not contain any part of FLUX.1 [dev], but users, at its sole discretion, may import FLUX.1 [dev] and therefore should abide by the terms and conditions of FLUX.1 [dev] Non-Commercial License.
+--------------------------------------------------------------------
+1. FLUX.1 [dev]
+The FLUX.1 [dev] Model is licensed by Black Forest Labs. Inc. under the FLUX.1 [dev] Non-Commercial License. Copyright Black Forest Labs. Inc.
+
+IN NO EVENT SHALL BLACK FOREST LABS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH USE OF THIS MODEL.
+
+
+Terms of the FLUX.1 [dev] Non-Commercial License:
+--------------------------------------------------------------------
+Black Forest Labs, Inc. (“we” or “our” or “Company”) is pleased to make available the weights, parameters and inference code for the FLUX.1 [dev] Model (as defined below) freely available for your non-commercial and non-production use as set forth in this FLUX.1 [dev] Non-Commercial License (“License”). The “FLUX.1 [dev] Model” means the FLUX.1 [dev] text-to-image AI model and its elements which includes algorithms, software, checkpoints, parameters, source code (inference code, evaluation code, and if applicable, fine-tuning code) and any other materials associated with the FLUX.1 [dev] AI model made available by Company under this License, including if any, the technical documentation, manuals and instructions for the use and operation thereof (collectively, “FLUX.1 [dev] Model”).
+
+By downloading, accessing, use, Distributing (as defined below), or creating a Derivative (as defined below) of the FLUX.1 [dev] Model, you agree to the terms of this License. If you do not agree to this License, then you do not have any rights to access, use, Distribute or create a Derivative of the FLUX.1 [dev] Model and you must immediately cease using the FLUX.1 [dev] Model. If you are agreeing to be bound by the terms of this License on behalf of your employer or other entity, you represent and warrant to us that you have full legal authority to bind your employer or such entity to this License. If you do not have the requisite authority, you may not accept the License or access the FLUX.1 [dev] Model on behalf of your employer or other entity.
+
+1.Definitions. Capitalized terms used in this License but not defined herein have the following meanings:
+
+1.“Derivative” means any (i) modified version of the FLUX.1 [dev] Model (including but not limited to any customized or fine-tuned version thereof), (ii) work based on the FLUX.1 [dev] Model, or (iii) any other derivative work thereof. For the avoidance of doubt, Outputs are not considered Derivatives under this License.
+
+2.“Distribution” or “Distribute” or “Distributing” means providing or making available, by any means, a copy of the FLUX.1 [dev] Models and/or the Derivatives as the case may be.
+
+3.“Non-Commercial Purpose” means any of the following uses, but only so far as you do not receive any direct or indirect payment arising from the use of the model or its output: (i) personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, or otherwise not directly or indirectly connected to any commercial activities, business operations, or employment responsibilities; (ii) use by commercial or for-profit entities for testing, evaluation, or non-commercial research and development in a non-production environment, (iii) use by any charitable organization for charitable purposes, or for testing or evaluation. For clarity, use for revenue-generating activity or direct interactions with or impacts on end users, or use to train, fine tune or distill other models for commercial use is not a Non-Commercial purpose.
+
+4.“Outputs” means any content generated by the operation of the FLUX.1 [dev] Models or the Derivatives from a prompt (i.e., text instructions) provided by users. For the avoidance of doubt, Outputs do not include any components of a FLUX.1 [dev] Models, such as any fine-tuned versions of the FLUX.1 [dev] Models, the weights, or parameters.
+
+5.“you” or “your” means the individual or entity entering into this License with Company.
+
+2.License Grant.
+
+1.License. Subject to your compliance with this License, Company grants you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty free and limited license to access, use, create Derivatives of, and Distribute the FLUX.1 [dev] Models solely for your Non-Commercial Purposes. The foregoing license is personal to you, and you may not assign or sublicense this License or any other rights or obligations under this License without Company’s prior written consent; any such assignment or sublicense will be void and will automatically and immediately terminate this License. Any restrictions set forth herein in regarding the FLUX.1 [dev] Model also applies to any Derivative you create or that are created on your behalf.
+
+2.Non-Commercial Use Only. You may only access, use, Distribute, or creative Derivatives of or the FLUX.1 [dev] Model or Derivatives for Non-Commercial Purposes. If You want to use a FLUX.1 [dev] Model a Derivative for any purpose that is not expressly authorized under this License, such as for a commercial activity, you must request a license from Company, which Company may grant to you in Company’s sole discretion and which additional use may be subject to a fee, royalty or other revenue share. Please contact Company at the following e-mail address if you want to discuss such a license: info@blackforestlabs.ai.
+
+3.Reserved Rights. The grant of rights expressly set forth in this License are the complete grant of rights to you in the FLUX.1 [dev] Model, and no other licenses are granted, whether by waiver, estoppel, implication, equity or otherwise. Company and its licensors reserve all rights not expressly granted by this License.
+
+4.Outputs. We claim no ownership rights in and to the Outputs. You are solely responsible for the Outputs you generate and their subsequent uses in accordance with this License. You may use Output for any purpose (including for commercial purposes), except as expressly prohibited herein. You may not use the Output to train, fine-tune or distill a model that is competitive with the FLUX.1 [dev] Model.
+
+3.Distribution. Subject to this License, you may Distribute copies of the FLUX.1 [dev] Model and/or Derivatives made by you, under the following conditions:
+
+1.you must make available a copy of this License to third-party recipients of the FLUX.1 [dev] Models and/or Derivatives you Distribute, and specify that any rights to use the FLUX.1 [dev] Models and/or Derivatives shall be directly granted by Company to said third-party recipients pursuant to this License;
+
+2.you must make prominently display the following notice alongside the Distribution of the FLUX.1 [dev] Model or Derivative (such as via a “Notice” text file distributed as part of such FLUX.1 [dev] Model or Derivative) (the “Attribution Notice”):
+
+“The FLUX.1 [dev] Model is licensed by Black Forest Labs. Inc. under the FLUX.1 [dev] Non-Commercial License. Copyright Black Forest Labs. Inc.
+
+IN NO EVENT SHALL BLACK FOREST LABS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH USE OF THIS MODEL.”
+
+3.in the case of Distribution of Derivatives made by you, you must also include in the Attribution Notice a statement that you have modified the applicable FLUX.1 [dev] Model; and
+
+4.in the case of Distribution of Derivatives made by you, any terms and conditions you impose on any third-party recipients relating to Derivatives made by or for you shall neither limit such third-party recipients’ use of the FLUX.1 [dev] Model or any Derivatives made by or for Company in accordance with this License nor conflict with any of its terms and conditions.
+
+5.In the case of Distribution of Derivatives made by you, you must not misrepresent or imply, through any means, that the Derivatives made by or for you and/or any modified version of the FLUX.1 [dev] Model you Distribute under your name and responsibility is an official product of the Company or has been endorsed, approved or validated by the Company, unless you are authorized by Company to do so in writing.
+
+4.Restrictions. You will not, and will not permit, assist or cause any third party to
+
+1.use, modify, copy, reproduce, create Derivatives of, or Distribute the FLUX.1 [dev] Model (or any Derivative thereof, or any data produced by the FLUX.1 [dev] Model), in whole or in part, for (i) any commercial or production purposes, (ii) military purposes, (iii) purposes of surveillance, including any research or development relating to surveillance, (iv) biometric processing, (v) in any manner that infringes, misappropriates, or otherwise violates any third-party rights, or (vi) in any manner that violates any applicable law and violating any privacy or security laws, rules, regulations, directives, or governmental requirements (including the General Data Privacy Regulation (Regulation (EU) 2016/679), the California Consumer Privacy Act, and any and all laws governing the processing of biometric information), as well as all amendments and successor laws to any of the foregoing;
+
+2.alter or remove copyright and other proprietary notices which appear on or in any portion of the FLUX.1 [dev] Model;
+
+3.utilize any equipment, device, software, or other means to circumvent or remove any security or protection used by Company in connection with the FLUX.1 [dev] Model, or to circumvent or remove any usage restrictions, or to enable functionality disabled by FLUX.1 [dev] Model; or
+
+4.offer or impose any terms on the FLUX.1 [dev] Model that alter, restrict, or are inconsistent with the terms of this License.
+
+5.violate any applicable U.S. and non-U.S. export control and trade sanctions laws (“Export Laws”) in connection with your use or Distribution of any FLUX.1 [dev] Model;
+
+6.directly or indirectly Distribute, export, or otherwise transfer FLUX.1 [dev] Model (a) to any individual, entity, or country prohibited by Export Laws; (b) to anyone on U.S. or non-U.S. government restricted parties lists; or (c) for any purpose prohibited by Export Laws, including nuclear, chemical or biological weapons, or missile technology applications; 3) use or download FLUX.1 [dev] Model if you or they are (a) located in a comprehensively sanctioned jurisdiction, (b) currently listed on any U.S. or non-U.S. restricted parties list, or (c) for any purpose prohibited by Export Laws; and (4) will not disguise your location through IP proxying or other methods.
+
+5.DISCLAIMERS. THE FLUX.1 [dev] MODEL IS PROVIDED “AS IS” AND “WITH ALL FAULTS” WITH NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. COMPANY EXPRESSLY DISCLAIMS ALL REPRESENTATIONS AND WARRANTIES, EXPRESS OR IMPLIED, WHETHER BY STATUTE, CUSTOM, USAGE OR OTHERWISE AS TO ANY MATTERS RELATED TO THE FLUX.1 [dev] MODEL, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, SATISFACTORY QUALITY, OR NON-INFRINGEMENT. COMPANY MAKES NO WARRANTIES OR REPRESENTATIONS THAT THE FLUX.1 [dev] MODEL WILL BE ERROR FREE OR FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS, OR PRODUCE ANY PARTICULAR RESULTS.
+
+6.LIMITATION OF LIABILITY. TO THE FULLEST EXTENT PERMITTED BY LAW, IN NO EVENT WILL COMPANY BE LIABLE TO YOU OR YOUR EMPLOYEES, AFFILIATES, USERS, OFFICERS OR DIRECTORS (A) UNDER ANY THEORY OF LIABILITY, WHETHER BASED IN CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY, WARRANTY, OR OTHERWISE UNDER THIS LICENSE, OR (B) FOR ANY INDIRECT, CONSEQUENTIAL, EXEMPLARY, INCIDENTAL, PUNITIVE OR SPECIAL DAMAGES OR LOST PROFITS, EVEN IF COMPANY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. THE FLUX.1 [dev] MODEL, ITS CONSTITUENT COMPONENTS, AND ANY OUTPUT (COLLECTIVELY, “MODEL MATERIALS”) ARE NOT DESIGNED OR INTENDED FOR USE IN ANY APPLICATION OR SITUATION WHERE FAILURE OR FAULT OF THE MODEL MATERIALS COULD REASONABLY BE ANTICIPATED TO LEAD TO SERIOUS INJURY OF ANY PERSON, INCLUDING POTENTIAL DISCRIMINATION OR VIOLATION OF AN INDIVIDUAL’S PRIVACY RIGHTS, OR TO SEVERE PHYSICAL, PROPERTY, OR ENVIRONMENTAL DAMAGE (EACH, A “HIGH-RISK USE”). IF YOU ELECT TO USE ANY OF THE MODEL MATERIALS FOR A HIGH-RISK USE, YOU DO SO AT YOUR OWN RISK. YOU AGREE TO DESIGN AND IMPLEMENT APPROPRIATE DECISION-MAKING AND RISK-MITIGATION PROCEDURES AND POLICIES IN CONNECTION WITH A HIGH-RISK USE SUCH THAT EVEN IF THERE IS A FAILURE OR FAULT IN ANY OF THE MODEL MATERIALS, THE SAFETY OF PERSONS OR PROPERTY AFFECTED BY THE ACTIVITY STAYS AT A LEVEL THAT IS REASONABLE, APPROPRIATE, AND LAWFUL FOR THE FIELD OF THE HIGH-RISK USE.
+
+7.INDEMNIFICATION
+
+You will indemnify, defend and hold harmless Company and our subsidiaries and affiliates, and each of our respective shareholders, directors, officers, employees, agents, successors, and assigns (collectively, the “Company Parties”) from and against any losses, liabilities, damages, fines, penalties, and expenses (including reasonable attorneys’ fees) incurred by any Company Party in connection with any claim, demand, allegation, lawsuit, proceeding, or investigation (collectively, “Claims”) arising out of or related to (a) your access to or use of the FLUX.1 [dev] Model (as well as any Output, results or data generated from such access or use), including any High-Risk Use (defined below); (b) your violation of this License; or (c) your violation, misappropriation or infringement of any rights of another (including intellectual property or other proprietary rights and privacy rights). You will promptly notify the Company Parties of any such Claims, and cooperate with Company Parties in defending such Claims. You will also grant the Company Parties sole control of the defense or settlement, at Company’s sole option, of any Claims. This indemnity is in addition to, and not in lieu of, any other indemnities or remedies set forth in a written agreement between you and Company or the other Company Parties.
+
+8.Termination; Survival.
+
+1.This License will automatically terminate upon any breach by you of the terms of this License.
+
+2.We may terminate this License, in whole or in part, at any time upon notice (including electronic) to you.
+
+3.If You initiate any legal action or proceedings against Company or any other entity (including a cross-claim or counterclaim in a lawsuit), alleging that the FLUX.1 [dev] Model or any Derivative, or any part thereof, infringe upon intellectual property or other rights owned or licensable by you, then any licenses granted to you under this License will immediately terminate as of the date such legal action or claim is filed or initiated.
+
+4.Upon termination of this License, you must cease all use, access or Distribution of the FLUX.1 [dev] Model and any Derivatives. The following sections survive termination of this License 2(c), 2(d), 4-11.
+
+9.Third Party Materials. The FLUX.1 [dev] Model may contain third-party software or other components (including free and open source software) (all of the foregoing, “Third Party Materials”), which are subject to the license terms of the respective third-party licensors. Your dealings or correspondence with third parties and your use of or interaction with any Third Party Materials are solely between you and the third party. Company does not control or endorse, and makes no representations or warranties regarding, any Third Party Materials, and your access to and use of such Third Party Materials are at your own risk.
+
+10.Trademarks. You have not been granted any trademark license as part of this License and may not use any name or mark associated with Company without the prior written permission of Company, except to the extent necessary to make the reference required in the Attribution Notice as specified above or as is reasonably necessary in describing the FLUX.1 [dev] Model and its creators.
+
+11.General. This License will be governed and construed under the laws of the State of Delaware without regard to conflicts of law provisions. If any provision or part of a provision of this License is unlawful, void or unenforceable, that provision or part of the provision is deemed severed from this License, and will not affect the validity and enforceability of any remaining provisions. The failure of Company to exercise or enforce any right or provision of this License will not operate as a waiver of such right or provision. This License does not confer any third-party beneficiary rights upon any other person or entity. This License, together with the Documentation, contains the entire understanding between you and Company regarding the subject matter of this License, and supersedes all other written or oral agreements and understandings between you and Company regarding such subject matter. No change or addition to any provision of this License will be binding unless it is in writing and signed by an authorized representative of both you and Company.
\ No newline at end of file
diff --git a/InstantCharacter/README.md b/InstantCharacter/README.md
new file mode 100644
index 0000000..6413ba9
--- /dev/null
+++ b/InstantCharacter/README.md
@@ -0,0 +1,197 @@
+
+
InstantCharacter: Personalize Any Characters with a Scalable Diffusion Transformer Framework
+
+
+
+
+
+[**Jiale Tao**](https://github.com/JialeTao)
1 ·
+[**Yanbing Zhang**](https://github.com/Monalissaa)
1 ·
+[**Qixun Wang**](https://github.com/wangqixun)
12✝ ·
+[**Yiji Cheng**](https://www.linkedin.com/in/yiji-cheng-a8b922213/)
1 ·
+[**Haofan Wang**](https://haofanwang.github.io/)
2 ·
+[**Xu Bai**](https://huggingface.co/baymin0220)
2 ·
+Zhengguang Zhou
12 ·
+[**Ruihuang Li**](https://scholar.google.com/citations?user=8CfyOtQAAAAJ&hl=zh-CN)
1 ·
+[**Linqing Wang**](https://scholar.google.com/citations?user=Hy12lcEAAAAJ&hl=en)
12 · Chunyu Wang
1 ·
+Qin Lin
1 ·
+Qinglin Lu
1*
+
+
+
1Hunyuan, Tencent ·
2InstantX Team
+
+
✝tech lead ·
*corresponding authors
+
+

+

+

+
+
+
+
+
+
+InstantCharacter is an innovative, tuning-free method designed to achieve character-preserving generation from a single image, supporting a variety of downstream tasks.
+
+
+
+
+
+
+
+
+
+
+## Release
+- [2025/04/18] 🔥 We release the [demo](https://huggingface.co/spaces/InstantX/InstantCharacter) [checkpoints](https://huggingface.co/InstantX/InstantCharacter/) and [code](https://github.com/Tencent/InstantCharacter).
+
+- [2025/04/02] 🔥 We launch the [project page](https://instantcharacter.github.io/).
+
+
+## Download
+
+You can directly download the model from [Huggingface](https://huggingface.co/InstantX/InstantCharacter).
+```shell
+huggingface-cli download --resume-download Tencent/InstantCharacter --local-dir checkpoints --local-dir-use-symlinks False
+```
+
+If you cannot access to Huggingface, you can use [hf-mirror](https://hf-mirror.com/) to download models.
+```shell
+export HF_ENDPOINT=https://hf-mirror.com
+huggingface-cli download --resume-download Tencent/InstantCharacter --local-dir checkpoints --local-dir-use-symlinks False
+```
+
+Once you have prepared all models, the folder tree should be like:
+
+```
+ .
+ ├── assets
+ ├── checkpoints
+ ├── models
+ ├── infer_demo.py
+ ├── pipeline.py
+ └── README.md
+```
+
+
+## Usage
+
+
+```python
+# !pip install transformers accelerate diffusers huggingface_cli
+import torch
+from PIL import Image
+from pipeline import InstantCharacterFluxPipeline
+
+# Step 1 Load base model and adapter
+ip_adapter_path = 'checkpoints/instantcharacter_ip-adapter.bin'
+base_model = 'black-forest-labs/FLUX.1-dev'
+image_encoder_path = 'google/siglip-so400m-patch14-384'
+image_encoder_2_path = 'facebook/dinov2-giant'
+seed = 123456
+pipe = InstantCharacterFluxPipeline.from_pretrained(base_model, torch_dtype=torch.bfloat16)
+pipe.to("cuda")
+pipe.init_adapter(
+ image_encoder_path=image_encoder_path,
+ image_encoder_2_path=image_encoder_2_path,
+ subject_ipadapter_cfg=dict(subject_ip_adapter_path=ip_adapter_path, nb_token=1024),
+)
+
+# Step 2 Load reference image
+ref_image_path = 'assets/girl.jpg' # white background
+ref_image = Image.open(ref_image_path).convert('RGB')
+
+# Step 3 Inference without style
+prompt = "A girl is playing a guitar in street"
+image = pipe(
+ prompt=prompt,
+ num_inference_steps=28,
+ guidance_scale=3.5,
+ subject_image=ref_image,
+ subject_scale=0.9,
+ generator=torch.manual_seed(seed),
+).images[0]
+image.save("flux_instantcharacter.png")
+```
+
+
+You can use style lora
+
+
+```shell
+# download style lora
+huggingface-cli download --resume-download InstantX/FLUX.1-dev-LoRA-Ghibli --local-dir checkpoints/style_lora/ --local-dir-use-symlinks False
+huggingface-cli download --resume-download InstantX/FLUX.1-dev-LoRA-Makoto-Shinkai --local-dir checkpoints/style_lora/ --local-dir-use-symlinks False
+```
+
+```python
+# You can also use other style lora
+
+# Step 3 Inference with style
+lora_file_path = 'checkpoints/style_lora/ghibli_style.safetensors'
+trigger = 'ghibli style'
+prompt = "A girl is playing a guitar in street"
+image = pipe.with_style_lora(
+ lora_file_path=lora_file_path,
+ trigger=trigger,
+ prompt=prompt,
+ num_inference_steps=28,
+ guidance_scale=3.5,
+ subject_image=ref_image,
+ subject_scale=0.9,
+ generator=torch.manual_seed(seed),
+).images[0]
+image.save("flux_instantcharacter_style_ghibli.png")
+
+
+# Step 3 Inference with style
+lora_file_path = 'checkpoints/style_lora/Makoto_Shinkai_style.safetensors'
+trigger = 'Makoto Shinkai style'
+prompt = "A girl is playing a guitar in street"
+image = pipe.with_style_lora(
+ lora_file_path=lora_file_path,
+ trigger=trigger,
+ prompt=prompt,
+ num_inference_steps=28,
+ guidance_scale=3.5,
+ subject_image=ref_image,
+ subject_scale=0.9,
+ generator=torch.manual_seed(seed),
+).images[0]
+image.save("flux_instantcharacter_style_Makoto.png")
+```
+
+## More case
+Animal character are relatively unstable.
+
+
+
+
+
+
+
+
+
+
+
+
+## Acknowledgment
+ - Our work is sponsored by [HuggingFace](https://huggingface.co) and [fal.ai](https://fal.ai).
+
+
+

+
+
+ - Thanks to the model JY Duan.
+
+
+

+
+
+
+
+
+
+
diff --git a/InstantCharacter/app.py b/InstantCharacter/app.py
new file mode 100644
index 0000000..2ac448b
--- /dev/null
+++ b/InstantCharacter/app.py
@@ -0,0 +1,299 @@
+import torch
+import random
+import numpy as np
+from PIL import Image
+
+# import gradio as gr
+from huggingface_hub import hf_hub_download
+from transformers import AutoModelForImageSegmentation
+from torchvision import transforms
+
+from .pipeline import InstantCharacterFluxPipeline
+
+# global variable
+MAX_SEED = np.iinfo(np.int32).max
+device = "cuda" if torch.cuda.is_available() else "cpu"
+dtype = torch.float16 if str(device).__contains__("cuda") else torch.float32
+
+# pre-trained weights
+ip_adapter_path = hf_hub_download(repo_id="Tencent/InstantCharacter", filename="instantcharacter_ip-adapter.bin")
+base_model = 'black-forest-labs/FLUX.1-dev'
+image_encoder_path = 'google/siglip-so400m-patch14-384'
+image_encoder_2_path = 'facebook/dinov2-giant'
+birefnet_path = 'ZhengPeng7/BiRefNet'
+makoto_style_lora_path = hf_hub_download(repo_id="InstantX/FLUX.1-dev-LoRA-Makoto-Shinkai", filename="Makoto_Shinkai_style.safetensors")
+ghibli_style_lora_path = hf_hub_download(repo_id="InstantX/FLUX.1-dev-LoRA-Ghibli", filename="ghibli_style.safetensors")
+
+# init InstantCharacter pipeline
+pipe = InstantCharacterFluxPipeline.from_pretrained(base_model, torch_dtype=torch.bfloat16)
+pipe.to(device)
+
+# load InstantCharacter
+pipe.init_adapter(
+ image_encoder_path=image_encoder_path,
+ image_encoder_2_path=image_encoder_2_path,
+ subject_ipadapter_cfg=dict(subject_ip_adapter_path=ip_adapter_path, nb_token=1024),
+)
+
+# load matting model
+birefnet = AutoModelForImageSegmentation.from_pretrained(birefnet_path, trust_remote_code=True)
+birefnet.to('cuda')
+birefnet.eval()
+birefnet_transform_image = transforms.Compose([
+ transforms.Resize((1024, 1024)),
+ transforms.ToTensor(),
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
+])
+
+
+def remove_bkg(subject_image):
+
+ def infer_matting(img_pil):
+ input_images = birefnet_transform_image(img_pil).unsqueeze(0).to('cuda')
+
+ with torch.no_grad():
+ preds = birefnet(input_images)[-1].sigmoid().cpu()
+ pred = preds[0].squeeze()
+ pred_pil = transforms.ToPILImage()(pred)
+ mask = pred_pil.resize(img_pil.size)
+ mask = np.array(mask)
+ mask = mask[..., None]
+ return mask
+
+ def get_bbox_from_mask(mask, th=128):
+ height, width = mask.shape[:2]
+ x1, y1, x2, y2 = 0, 0, width - 1, height - 1
+
+ sample = np.max(mask, axis=0)
+ for idx in range(width):
+ if sample[idx] >= th:
+ x1 = idx
+ break
+
+ sample = np.max(mask[:, ::-1], axis=0)
+ for idx in range(width):
+ if sample[idx] >= th:
+ x2 = width - 1 - idx
+ break
+
+ sample = np.max(mask, axis=1)
+ for idx in range(height):
+ if sample[idx] >= th:
+ y1 = idx
+ break
+
+ sample = np.max(mask[::-1], axis=1)
+ for idx in range(height):
+ if sample[idx] >= th:
+ y2 = height - 1 - idx
+ break
+
+ x1 = np.clip(x1, 0, width-1).round().astype(np.int32)
+ y1 = np.clip(y1, 0, height-1).round().astype(np.int32)
+ x2 = np.clip(x2, 0, width-1).round().astype(np.int32)
+ y2 = np.clip(y2, 0, height-1).round().astype(np.int32)
+
+ return [x1, y1, x2, y2]
+
+ def pad_to_square(image, pad_value = 255, random = False):
+ '''
+ image: np.array [h, w, 3]
+ '''
+ H,W = image.shape[0], image.shape[1]
+ if H == W:
+ return image
+
+ padd = abs(H - W)
+ if random:
+ padd_1 = int(np.random.randint(0,padd))
+ else:
+ padd_1 = int(padd / 2)
+ padd_2 = padd - padd_1
+
+ if H > W:
+ pad_param = ((0,0),(padd_1,padd_2),(0,0))
+ else:
+ pad_param = ((padd_1,padd_2),(0,0),(0,0))
+
+ image = np.pad(image, pad_param, 'constant', constant_values=pad_value)
+ return image
+
+ salient_object_mask = infer_matting(subject_image)[..., 0]
+ x1, y1, x2, y2 = get_bbox_from_mask(salient_object_mask)
+ subject_image = np.array(subject_image)
+ salient_object_mask[salient_object_mask > 128] = 255
+ salient_object_mask[salient_object_mask < 128] = 0
+ sample_mask = np.concatenate([salient_object_mask[..., None]]*3, axis=2)
+ obj_image = sample_mask / 255 * subject_image + (1 - sample_mask / 255) * 255
+ crop_obj_image = obj_image[y1:y2, x1:x2]
+ crop_pad_obj_image = pad_to_square(crop_obj_image, 255)
+ subject_image = Image.fromarray(crop_pad_obj_image.astype(np.uint8))
+ return subject_image
+
+
+def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
+ if randomize_seed:
+ seed = random.randint(0, MAX_SEED)
+ return seed
+
+def get_example():
+ case = [
+ [
+ "./assets/girl.jpg",
+ "A girl is playing a guitar in street",
+ 0.9,
+ 'Makoto Shinkai style',
+ ],
+ [
+ "./assets/boy.jpg",
+ "A boy is riding a bike in snow",
+ 0.9,
+ 'Makoto Shinkai style',
+ ],
+ ]
+ return case
+
+def run_for_examples(source_image, prompt, scale, style_mode):
+
+ return create_image(
+ input_image=source_image,
+ prompt=prompt,
+ scale=scale,
+ guidance_scale=3.5,
+ num_inference_steps=28,
+ seed=123456,
+ style_mode=style_mode,
+ )
+
+def create_image(input_image,
+ prompt,
+ scale,
+ guidance_scale,
+ num_inference_steps,
+ seed,
+ style_mode=None):
+
+ input_image = remove_bkg(input_image)
+
+ if style_mode is None:
+ images = pipe(
+ prompt=prompt,
+ num_inference_steps=num_inference_steps,
+ guidance_scale=guidance_scale,
+ width=1024,
+ height=1024,
+ subject_image=input_image,
+ subject_scale=scale,
+ generator=torch.manual_seed(seed),
+ ).images
+ else:
+ if style_mode == 'Makoto Shinkai style':
+ lora_file_path = makoto_style_lora_path
+ trigger = 'Makoto Shinkai style'
+ elif style_mode == 'Ghibli style':
+ lora_file_path = ghibli_style_lora_path
+ trigger = 'ghibli style'
+
+ images = pipe.with_style_lora(
+ lora_file_path=lora_file_path,
+ trigger=trigger,
+ prompt=prompt,
+ num_inference_steps=num_inference_steps,
+ guidance_scale=guidance_scale,
+ width=1024,
+ height=1024,
+ subject_image=input_image,
+ subject_scale=scale,
+ generator=torch.manual_seed(seed),
+ ).images
+
+
+ return images
+
+# Description
+title = r"""
+InstantCharacter : Personalize Any Characters with a Scalable Diffusion Transformer Framework
+"""
+
+description = r"""
+Official 🤗 Gradio demo for InstantCharacter : Personalize Any Characters with a Scalable Diffusion Transformer Framework.
+How to use:
+1. Upload a character image, removing background would be preferred.
+2. Enter a text prompt to describe what you hope the chracter does.
+3. Click the Submit button to begin customization.
+4. Share your custimized photo with your friends and enjoy! 😊
+"""
+
+article = r"""
+---
+📝 **Citation**
+
+If our work is helpful for your research or applications, please cite us via:
+```bibtex
+TBD
+```
+📧 **Contact**
+
+If you have any questions, please feel free to open an issue.
+"""
+
+block = gr.Blocks(css="footer {visibility: hidden}").queue(max_size=10, api_open=False)
+with block:
+
+ # description
+ gr.Markdown(title)
+ gr.Markdown(description)
+
+ with gr.Tabs():
+ with gr.Row():
+ with gr.Column():
+
+ with gr.Row():
+ with gr.Column():
+ image_pil = gr.Image(label="Source Image", type='pil')
+
+ prompt = gr.Textbox(label="Prompt", value="a character is riding a bike in snow")
+
+ scale = gr.Slider(minimum=0, maximum=1.5, step=0.01,value=1.0, label="Scale")
+ style_mode = gr.Dropdown(label='Style', choices=[None, 'Makoto Shinkai style', 'Ghibli style'], value='Makoto Shinkai style')
+
+ with gr.Accordion(open=False, label="Advanced Options"):
+ guidance_scale = gr.Slider(minimum=1,maximum=7.0, step=0.01,value=3.5, label="guidance scale")
+ num_inference_steps = gr.Slider(minimum=5,maximum=50.0, step=1.0,value=28, label="num inference steps")
+ seed = gr.Slider(minimum=-1000000, maximum=1000000, value=123456, step=1, label="Seed Value")
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
+
+ generate_button = gr.Button("Generate Image")
+
+ with gr.Column():
+ generated_image = gr.Gallery(label="Generated Image")
+
+ generate_button.click(
+ fn=randomize_seed_fn,
+ inputs=[seed, randomize_seed],
+ outputs=seed,
+ queue=False,
+ api_name=False,
+ ).then(
+ fn=create_image,
+ inputs=[image_pil,
+ prompt,
+ scale,
+ guidance_scale,
+ num_inference_steps,
+ seed,
+ style_mode,
+ ],
+ outputs=[generated_image])
+
+ gr.Examples(
+ examples=get_example(),
+ inputs=[image_pil, prompt, scale, style_mode],
+ fn=run_for_examples,
+ outputs=[generated_image],
+ cache_examples=True,
+ )
+
+ gr.Markdown(article)
+
+block.launch(server_name="0.0.0.0", server_port=80)
\ No newline at end of file
diff --git a/InstantCharacter/infer_demo.py b/InstantCharacter/infer_demo.py
new file mode 100644
index 0000000..e34bf46
--- /dev/null
+++ b/InstantCharacter/infer_demo.py
@@ -0,0 +1,85 @@
+import torch
+from PIL import Image
+from .pipeline import InstantCharacterFluxPipeline
+
+# Step 1 Load base model and adapter
+ip_adapter_path = 'checkpoints/instantcharacter_ip-adapter.bin'
+base_model = 'black-forest-labs/FLUX.1-dev'
+image_encoder_path = 'google/siglip-so400m-patch14-384'
+image_encoder_2_path = 'facebook/dinov2-giant'
+seed = 123456
+pipe = InstantCharacterFluxPipeline.from_pretrained(base_model, torch_dtype=torch.bfloat16)
+pipe.to("cuda")
+pipe.init_adapter(
+ image_encoder_path=image_encoder_path,
+ image_encoder_2_path=image_encoder_2_path,
+ subject_ipadapter_cfg=dict(subject_ip_adapter_path=ip_adapter_path, nb_token=1024),
+)
+
+# Step 2 Load reference image
+ref_image_path = 'assets/girl.jpg' # white background
+ref_image = Image.open(ref_image_path).convert('RGB')
+
+# Step 3 Inference without style
+prompt = "A girl is playing a guitar in street"
+image = pipe(
+ prompt=prompt,
+ num_inference_steps=28,
+ guidance_scale=3.5,
+ subject_image=ref_image,
+ subject_scale=0.9,
+ generator=torch.manual_seed(seed),
+).images[0]
+image.save("flux_instantcharacter.png")
+
+
+# Step 3 Inference with style
+lora_file_path = 'checkpoints/style_lora/ghibli_style.safetensors'
+trigger = 'ghibli style'
+prompt = "A girl is playing a guitar in street"
+image = pipe.with_style_lora(
+ lora_file_path=lora_file_path,
+ trigger=trigger,
+ prompt=prompt,
+ num_inference_steps=28,
+ guidance_scale=3.5,
+ subject_image=ref_image,
+ subject_scale=0.9,
+ generator=torch.manual_seed(seed),
+).images[0]
+image.save("flux_instantcharacter_style_ghibli.png")
+
+
+# Step 3 Inference with style
+lora_file_path = 'checkpoints/style_lora/Makoto_Shinkai_style.safetensors'
+trigger = 'Makoto Shinkai style'
+prompt = "A girl is playing a guitar in street"
+image = pipe.with_style_lora(
+ lora_file_path=lora_file_path,
+ trigger=trigger,
+ prompt=prompt,
+ num_inference_steps=28,
+ guidance_scale=3.5,
+ subject_image=ref_image,
+ subject_scale=0.9,
+ generator=torch.manual_seed(seed),
+).images[0]
+image.save("flux_instantcharacter_style_Makoto.png")
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/InstantCharacter/pipeline.py b/InstantCharacter/pipeline.py
new file mode 100644
index 0000000..447a3c8
--- /dev/null
+++ b/InstantCharacter/pipeline.py
@@ -0,0 +1,550 @@
+# Copyright 2025 Tencent InstantX Team. All rights reserved.
+#
+
+from PIL import Image
+from einops import rearrange
+import torch
+from diffusers.pipelines.flux.pipeline_flux import *
+from transformers import SiglipVisionModel, SiglipImageProcessor, AutoModel, AutoImageProcessor
+
+from .models.attn_processor import FluxIPAttnProcessor
+from .models.resampler import CrossLayerCrossScaleProjector
+from .models.utils import flux_load_lora
+
+
+# TODO
+# EXAMPLE_DOC_STRING = """
+# Examples:
+# ```py
+# >>> import torch
+# >>> from diffusers import FluxPipeline
+
+# >>> pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
+# >>> pipe.to("cuda")
+# >>> prompt = "A cat holding a sign that says hello world"
+# >>> # Depending on the variant being used, the pipeline call will slightly vary.
+# >>> # Refer to the pipeline documentation for more details.
+# >>> image = pipe(prompt, num_inference_steps=4, guidance_scale=0.0).images[0]
+# >>> image.save("flux.png")
+# ```
+# """
+
+
+class InstantCharacterFluxPipeline(FluxPipeline):
+
+
+ @torch.inference_mode()
+ def encode_siglip_image_emb(self, siglip_image, device, dtype):
+ siglip_image = siglip_image.to(device, dtype=dtype)
+ res = self.siglip_image_encoder(siglip_image, output_hidden_states=True)
+
+ siglip_image_embeds = res.last_hidden_state
+
+ siglip_image_shallow_embeds = torch.cat([res.hidden_states[i] for i in [7, 13, 26]], dim=1)
+
+ return siglip_image_embeds, siglip_image_shallow_embeds
+
+
+ @torch.inference_mode()
+ def encode_dinov2_image_emb(self, dinov2_image, device, dtype):
+ dinov2_image = dinov2_image.to(device, dtype=dtype)
+ res = self.dino_image_encoder_2(dinov2_image, output_hidden_states=True)
+
+ dinov2_image_embeds = res.last_hidden_state[:, 1:]
+
+ dinov2_image_shallow_embeds = torch.cat([res.hidden_states[i][:, 1:] for i in [9, 19, 29]], dim=1)
+
+ return dinov2_image_embeds, dinov2_image_shallow_embeds
+
+
+ @torch.inference_mode()
+ def encode_image_emb(self, siglip_image, device, dtype):
+ object_image_pil = siglip_image
+ object_image_pil_low_res = [object_image_pil.resize((384, 384))]
+ object_image_pil_high_res = object_image_pil.resize((768, 768))
+ object_image_pil_high_res = [
+ object_image_pil_high_res.crop((0, 0, 384, 384)),
+ object_image_pil_high_res.crop((384, 0, 768, 384)),
+ object_image_pil_high_res.crop((0, 384, 384, 768)),
+ object_image_pil_high_res.crop((384, 384, 768, 768)),
+ ]
+ nb_split_image = len(object_image_pil_high_res)
+
+ siglip_image_embeds = self.encode_siglip_image_emb(
+ self.siglip_image_processor(images=object_image_pil_low_res, return_tensors="pt").pixel_values,
+ device,
+ dtype
+ )
+ dinov2_image_embeds = self.encode_dinov2_image_emb(
+ self.dino_image_processor_2(images=object_image_pil_low_res, return_tensors="pt").pixel_values,
+ device,
+ dtype
+ )
+
+ image_embeds_low_res_deep = torch.cat([siglip_image_embeds[0], dinov2_image_embeds[0]], dim=2)
+ image_embeds_low_res_shallow = torch.cat([siglip_image_embeds[1], dinov2_image_embeds[1]], dim=2)
+
+ siglip_image_high_res = self.siglip_image_processor(images=object_image_pil_high_res, return_tensors="pt").pixel_values
+ siglip_image_high_res = siglip_image_high_res[None]
+ siglip_image_high_res = rearrange(siglip_image_high_res, 'b n c h w -> (b n) c h w')
+ siglip_image_high_res_embeds = self.encode_siglip_image_emb(siglip_image_high_res, device, dtype)
+ siglip_image_high_res_deep = rearrange(siglip_image_high_res_embeds[0], '(b n) l c -> b (n l) c', n=nb_split_image)
+ dinov2_image_high_res = self.dino_image_processor_2(images=object_image_pil_high_res, return_tensors="pt").pixel_values
+ dinov2_image_high_res = dinov2_image_high_res[None]
+ dinov2_image_high_res = rearrange(dinov2_image_high_res, 'b n c h w -> (b n) c h w')
+ dinov2_image_high_res_embeds = self.encode_dinov2_image_emb(dinov2_image_high_res, device, dtype)
+ dinov2_image_high_res_deep = rearrange(dinov2_image_high_res_embeds[0], '(b n) l c -> b (n l) c', n=nb_split_image)
+ image_embeds_high_res_deep = torch.cat([siglip_image_high_res_deep, dinov2_image_high_res_deep], dim=2)
+
+ image_embeds_dict = dict(
+ image_embeds_low_res_shallow=image_embeds_low_res_shallow,
+ image_embeds_low_res_deep=image_embeds_low_res_deep,
+ image_embeds_high_res_deep=image_embeds_high_res_deep,
+ )
+ return image_embeds_dict
+
+
+ @torch.inference_mode()
+ def init_ccp_and_attn_processor(self, *args, **kwargs):
+ subject_ip_adapter_path = kwargs['subject_ip_adapter_path']
+ nb_token = kwargs['nb_token']
+ state_dict = torch.load(subject_ip_adapter_path, map_location="cpu")
+ device, dtype = self.transformer.device, self.transformer.dtype
+
+ print(f"=> init attn processor")
+ attn_procs = {}
+ for idx_attn, (name, v) in enumerate(self.transformer.attn_processors.items()):
+ attn_procs[name] = FluxIPAttnProcessor(
+ hidden_size=self.transformer.config.attention_head_dim * self.transformer.config.num_attention_heads,
+ ip_hidden_states_dim=self.text_encoder_2.config.d_model,
+ ).to(device, dtype=dtype)
+ self.transformer.set_attn_processor(attn_procs)
+ tmp_ip_layers = torch.nn.ModuleList(self.transformer.attn_processors.values())
+ key_name = tmp_ip_layers.load_state_dict(state_dict["ip_adapter"], strict=False)
+ print(f"=> load attn processor: {key_name}")
+
+ print(f"=> init project")
+ image_proj_model = CrossLayerCrossScaleProjector(
+ inner_dim=1152 + 1536,
+ num_attention_heads=42,
+ attention_head_dim=64,
+ cross_attention_dim=1152 + 1536,
+ num_layers=4,
+ dim=1280,
+ depth=4,
+ dim_head=64,
+ heads=20,
+ num_queries=nb_token,
+ embedding_dim=1152 + 1536,
+ output_dim=4096,
+ ff_mult=4,
+ timestep_in_dim=320,
+ timestep_flip_sin_to_cos=True,
+ timestep_freq_shift=0,
+ )
+ image_proj_model.eval()
+ image_proj_model.to(device, dtype=dtype)
+
+ key_name = image_proj_model.load_state_dict(state_dict["image_proj"], strict=False)
+ print(f"=> load project: {key_name}")
+ self.subject_image_proj_model = image_proj_model
+
+
+ @torch.inference_mode()
+ def init_adapter(
+ self,
+ image_encoder_path=None,
+ image_encoder_2_path=None,
+ subject_ipadapter_cfg=None,
+ ):
+ device, dtype = self.transformer.device, self.transformer.dtype
+
+ # image encoder
+ print(f"=> loading image_encoder_1: {image_encoder_path}")
+ image_encoder = SiglipVisionModel.from_pretrained(image_encoder_path)
+ image_processor = SiglipImageProcessor.from_pretrained(image_encoder_path)
+ image_encoder.eval()
+ image_encoder.to(device, dtype=dtype)
+ self.siglip_image_encoder = image_encoder
+ self.siglip_image_processor = image_processor
+
+ # image encoder 2
+ print(f"=> loading image_encoder_2: {image_encoder_2_path}")
+ image_encoder_2 = AutoModel.from_pretrained(image_encoder_2_path)
+ image_processor_2 = AutoImageProcessor.from_pretrained(image_encoder_2_path)
+ image_encoder_2.eval()
+ image_encoder_2.to(device, dtype=dtype)
+ image_processor_2.crop_size = dict(height=384, width=384)
+ image_processor_2.size = dict(shortest_edge=384)
+ self.dino_image_encoder_2 = image_encoder_2
+ self.dino_image_processor_2 = image_processor_2
+
+ # ccp and adapter
+ self.init_ccp_and_attn_processor(**subject_ipadapter_cfg)
+
+
+ @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 = 3.5,
+ 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,
+ subject_image: Image.Image = None,
+ subject_scale: float = 0.8,
+
+ ):
+ 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.
+ 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
+
+ # 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
+
+ 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.1 Prepare subject emb
+ if subject_image is not None:
+ subject_image = subject_image.resize((max(subject_image.size), max(subject_image.size)))
+ subject_image_embeds_dict = self.encode_image_emb(subject_image, device, dtype)
+
+ # 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.base_image_seq_len,
+ self.scheduler.config.max_image_seq_len,
+ self.scheduler.config.base_shift,
+ self.scheduler.config.max_shift,
+ )
+ 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)
+
+ # handle guidance
+ if self.transformer.config.guidance_embeds:
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
+ guidance = guidance.expand(latents.shape[0])
+ else:
+ guidance = None
+
+ 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,
+ )
+
+ # 6. 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)
+
+
+ # subject adapter
+ if subject_image is not None:
+ subject_image_prompt_embeds = self.subject_image_proj_model(
+ low_res_shallow=subject_image_embeds_dict['image_embeds_low_res_shallow'],
+ low_res_deep=subject_image_embeds_dict['image_embeds_low_res_deep'],
+ high_res_deep=subject_image_embeds_dict['image_embeds_high_res_deep'],
+ timesteps=timestep.to(dtype=latents.dtype),
+ need_temb=True
+ )[0]
+ self._joint_attention_kwargs['emb_dict'] = dict(
+ length_encoder_hidden_states=prompt_embeds.shape[1]
+ )
+ self._joint_attention_kwargs['subject_emb_dict'] = dict(
+ ip_hidden_states=subject_image_prompt_embeds,
+ scale=subject_scale,
+ )
+
+ noise_pred = self.transformer(
+ hidden_states=latents,
+ 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,
+ )[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,
+ txt_ids=text_ids,
+ img_ids=latent_image_ids,
+ joint_attention_kwargs=self.joint_attention_kwargs,
+ return_dict=False,
+ )[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)
+
+ # 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)
+
+
+ def with_style_lora(self, lora_file_path, lora_weight=1.0, trigger='', *args, **kwargs):
+ flux_load_lora(self, lora_file_path, lora_weight)
+ kwargs['prompt'] = f"{trigger}, {kwargs['prompt']}"
+ res = self.__call__(*args, **kwargs)
+ flux_load_lora(self, lora_file_path, -lora_weight)
+ return res
+
diff --git a/InstantCharacter/pipeline_wrapper.py b/InstantCharacter/pipeline_wrapper.py
new file mode 100644
index 0000000..cae74e4
--- /dev/null
+++ b/InstantCharacter/pipeline_wrapper.py
@@ -0,0 +1,555 @@
+# Copyright 2025 Tencent InstantX Team. All rights reserved.
+#
+
+from PIL import Image
+from einops import rearrange
+import torch
+from diffusers.pipelines.flux.pipeline_flux import *
+from transformers import SiglipVisionModel, SiglipImageProcessor, AutoModel, AutoImageProcessor
+
+from .models.attn_processor import FluxIPAttnProcessor
+from .models.resampler import CrossLayerCrossScaleProjector
+from .models.utils import flux_load_lora
+
+
+# TODO
+# EXAMPLE_DOC_STRING = """
+# Examples:
+# ```py
+# >>> import torch
+# >>> from diffusers import FluxPipeline
+
+# >>> pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
+# >>> pipe.to("cuda")
+# >>> prompt = "A cat holding a sign that says hello world"
+# >>> # Depending on the variant being used, the pipeline call will slightly vary.
+# >>> # Refer to the pipeline documentation for more details.
+# >>> image = pipe(prompt, num_inference_steps=4, guidance_scale=0.0).images[0]
+# >>> image.save("flux.png")
+# ```
+# """
+
+
+class InstantCharacterFluxPipeline(FluxPipeline):
+
+
+ # @torch.inference_mode()
+ # def encode_siglip_image_emb(self, siglip_image, device, dtype):
+ # siglip_image = siglip_image.to(device, dtype=dtype)
+ # res = self.siglip_image_encoder(siglip_image, output_hidden_states=True)
+
+ # siglip_image_embeds = res.last_hidden_state
+
+ # siglip_image_shallow_embeds = torch.cat([res.hidden_states[i] for i in [7, 13, 26]], dim=1)
+
+ # return siglip_image_embeds, siglip_image_shallow_embeds
+
+
+ # @torch.inference_mode()
+ # def encode_dinov2_image_emb(self, dinov2_image, device, dtype):
+ # dinov2_image = dinov2_image.to(device, dtype=dtype)
+ # res = self.dino_image_encoder_2(dinov2_image, output_hidden_states=True)
+
+ # dinov2_image_embeds = res.last_hidden_state[:, 1:]
+
+ # dinov2_image_shallow_embeds = torch.cat([res.hidden_states[i][:, 1:] for i in [9, 19, 29]], dim=1)
+
+ # return dinov2_image_embeds, dinov2_image_shallow_embeds
+
+
+ # @torch.inference_mode()
+ # def encode_image_emb(self, siglip_image, device, dtype):
+ # object_image_pil = siglip_image
+ # object_image_pil_low_res = [object_image_pil.resize((384, 384))]
+ # object_image_pil_high_res = object_image_pil.resize((768, 768))
+ # object_image_pil_high_res = [
+ # object_image_pil_high_res.crop((0, 0, 384, 384)),
+ # object_image_pil_high_res.crop((384, 0, 768, 384)),
+ # object_image_pil_high_res.crop((0, 384, 384, 768)),
+ # object_image_pil_high_res.crop((384, 384, 768, 768)),
+ # ]
+ # nb_split_image = len(object_image_pil_high_res)
+
+ # siglip_image_embeds = self.encode_siglip_image_emb(
+ # self.siglip_image_processor(images=object_image_pil_low_res, return_tensors="pt").pixel_values,
+ # device,
+ # dtype
+ # )
+ # dinov2_image_embeds = self.encode_dinov2_image_emb(
+ # self.dino_image_processor_2(images=object_image_pil_low_res, return_tensors="pt").pixel_values,
+ # device,
+ # dtype
+ # )
+
+ # image_embeds_low_res_deep = torch.cat([siglip_image_embeds[0], dinov2_image_embeds[0]], dim=2)
+ # image_embeds_low_res_shallow = torch.cat([siglip_image_embeds[1], dinov2_image_embeds[1]], dim=2)
+
+ # siglip_image_high_res = self.siglip_image_processor(images=object_image_pil_high_res, return_tensors="pt").pixel_values
+ # siglip_image_high_res = siglip_image_high_res[None]
+ # siglip_image_high_res = rearrange(siglip_image_high_res, 'b n c h w -> (b n) c h w')
+ # siglip_image_high_res_embeds = self.encode_siglip_image_emb(siglip_image_high_res, device, dtype)
+ # siglip_image_high_res_deep = rearrange(siglip_image_high_res_embeds[0], '(b n) l c -> b (n l) c', n=nb_split_image)
+ # dinov2_image_high_res = self.dino_image_processor_2(images=object_image_pil_high_res, return_tensors="pt").pixel_values
+ # dinov2_image_high_res = dinov2_image_high_res[None]
+ # dinov2_image_high_res = rearrange(dinov2_image_high_res, 'b n c h w -> (b n) c h w')
+ # dinov2_image_high_res_embeds = self.encode_dinov2_image_emb(dinov2_image_high_res, device, dtype)
+ # dinov2_image_high_res_deep = rearrange(dinov2_image_high_res_embeds[0], '(b n) l c -> b (n l) c', n=nb_split_image)
+ # image_embeds_high_res_deep = torch.cat([siglip_image_high_res_deep, dinov2_image_high_res_deep], dim=2)
+
+ # image_embeds_dict = dict(
+ # image_embeds_low_res_shallow=image_embeds_low_res_shallow,
+ # image_embeds_low_res_deep=image_embeds_low_res_deep,
+ # image_embeds_high_res_deep=image_embeds_high_res_deep,
+ # )
+ # return image_embeds_dict
+
+
+ @torch.inference_mode()
+ def init_ccp_and_attn_processor(self, *args, **kwargs):
+ subject_ip_adapter_path = kwargs['subject_ip_adapter_path']
+ nb_token = kwargs['nb_token']
+ state_dict = torch.load(subject_ip_adapter_path, map_location="cpu")
+ device, dtype = self.transformer.device, self.transformer.dtype
+
+ print(f"=> init attn processor")
+ attn_procs = {}
+ for idx_attn, (name, v) in enumerate(self.transformer.attn_processors.items()):
+ attn_procs[name] = FluxIPAttnProcessor(
+ hidden_size=self.transformer.config.attention_head_dim * self.transformer.config.num_attention_heads,
+ ip_hidden_states_dim=4096,#self.text_encoder_2.config.d_model
+ ).to(device, dtype=dtype)
+ self.transformer.set_attn_processor(attn_procs)
+ tmp_ip_layers = torch.nn.ModuleList(self.transformer.attn_processors.values())
+ key_name = tmp_ip_layers.load_state_dict(state_dict["ip_adapter"], strict=False)
+ print(f"=> load attn processor: {key_name}")
+
+ print(f"=> init project")
+ image_proj_model = CrossLayerCrossScaleProjector(
+ inner_dim=1152 + 1536,
+ num_attention_heads=42,
+ attention_head_dim=64,
+ cross_attention_dim=1152 + 1536,
+ num_layers=4,
+ dim=1280,
+ depth=4,
+ dim_head=64,
+ heads=20,
+ num_queries=nb_token,
+ embedding_dim=1152 + 1536,
+ output_dim=4096,
+ ff_mult=4,
+ timestep_in_dim=320,
+ timestep_flip_sin_to_cos=True,
+ timestep_freq_shift=0,
+ )
+ image_proj_model.eval()
+ image_proj_model.to(device, dtype=dtype)
+
+ key_name = image_proj_model.load_state_dict(state_dict["image_proj"], strict=False)
+ print(f"=> load project: {key_name}")
+ del state_dict
+ self.subject_image_proj_model = image_proj_model
+
+
+ @torch.inference_mode()
+ def init_adapter(
+ self,
+ subject_ipadapter_cfg=None,
+ ):
+ # device, dtype = self.transformer.device, self.transformer.dtype
+
+ # image encoder
+ # print(f"=> loading image_encoder_1: {image_encoder_path}")
+ # image_encoder = SiglipVisionModel.from_pretrained(image_encoder_path)
+ # image_processor = SiglipImageProcessor.from_pretrained(image_encoder_path)
+ # image_encoder.eval()
+ # image_encoder.to(device, dtype=dtype)
+ # self.siglip_image_encoder = image_encoder
+ # self.siglip_image_processor = image_processor
+
+ # # image encoder 2
+ # print(f"=> loading image_encoder_2: {image_encoder_2_path}")
+ # image_encoder_2 = AutoModel.from_pretrained(image_encoder_2_path)
+ # image_processor_2 = AutoImageProcessor.from_pretrained(image_encoder_2_path)
+ # image_encoder_2.eval()
+ # image_encoder_2.to(device, dtype=dtype)
+ # image_processor_2.crop_size = dict(height=384, width=384)
+ # image_processor_2.size = dict(shortest_edge=384)
+ # self.dino_image_encoder_2 = image_encoder_2
+ # self.dino_image_processor_2 = image_processor_2
+
+ # ccp and adapter
+ self.init_ccp_and_attn_processor(**subject_ipadapter_cfg)
+
+
+ @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 = 3.5,
+ 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] = "latent",
+ 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,
+ subject_image = True,
+ subject_scale: float = 0.8,
+ text_ids=None,
+ subject_image_embeds_dict=None,
+
+
+ ):
+ 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.
+ 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
+
+ # 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
+
+ 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
+
+ if 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.1 Prepare subject emb
+ # if subject_image is not None:
+ # subject_image = subject_image.resize((max(subject_image.size), max(subject_image.size)))
+ # subject_image_embeds_dict = self.encode_image_emb(subject_image, device, dtype)
+
+ # 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.base_image_seq_len,
+ self.scheduler.config.max_image_seq_len,
+ self.scheduler.config.base_shift,
+ self.scheduler.config.max_shift,
+ )
+ 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)
+
+ # handle guidance
+ if self.transformer.config.guidance_embeds:
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
+ guidance = guidance.expand(latents.shape[0])
+ else:
+ guidance = None
+
+ 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,
+ )
+
+ # 6. 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)
+
+
+ # subject adapter
+ if subject_image :
+ subject_image_prompt_embeds = self.subject_image_proj_model(
+ low_res_shallow=subject_image_embeds_dict['image_embeds_low_res_shallow'],
+ low_res_deep=subject_image_embeds_dict['image_embeds_low_res_deep'],
+ high_res_deep=subject_image_embeds_dict['image_embeds_high_res_deep'],
+ timesteps=timestep.to(dtype=latents.dtype),
+ need_temb=True
+ )[0]
+ self._joint_attention_kwargs['emb_dict'] = dict(
+ length_encoder_hidden_states=prompt_embeds.shape[1]
+ )
+ self._joint_attention_kwargs['subject_emb_dict'] = dict(
+ ip_hidden_states=subject_image_prompt_embeds,
+ scale=subject_scale,
+ )
+
+ noise_pred = self.transformer(
+ hidden_states=latents,
+ 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,
+ )[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,
+ txt_ids=text_ids,
+ img_ids=latent_image_ids,
+ joint_attention_kwargs=self.joint_attention_kwargs,
+ return_dict=False,
+ )[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)
+
+ # 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":
+ latents=self._unpack_latents(latents, height, width, self.vae_scale_factor)
+ image = latents/0.3611+0.1159
+
+ # 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)
+
+
+ def with_style_lora(self, lora_file_path, lora_weight=1.0, trigger='', *args, **kwargs):
+ flux_load_lora(self, lora_file_path, lora_weight)
+ kwargs['prompt'] = f"{trigger}, {kwargs['prompt']}"
+ res = self.__call__(*args, **kwargs)
+ flux_load_lora(self, lora_file_path, -lora_weight)
+ return res
+