[
  {
    "path": ".github/workflows/ci.yaml",
    "content": "name: CI\non: push\njobs:\n  lint:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions/setup-python@v2\n        with:\n          python-version: \"3.10\"\n      - name: Install dependencies\n        run: |\n          python -m pip install --upgrade pip\n          pip install ruff==0.6.8\n      - name: Run Ruff\n        run: ruff check --output-format=github .\n      - name: Check imports\n        run: ruff check --select I --output-format=github .\n      - name: Check formatting\n        run: ruff format --check .\n"
  },
  {
    "path": ".gitignore",
    "content": "# Created by https://www.toptal.com/developers/gitignore/api/linux,windows,macos,visualstudiocode,python\n# Edit at https://www.toptal.com/developers/gitignore?templates=linux,windows,macos,visualstudiocode,python\n\n### Linux ###\n*~\n\n# temporary files which can be created if a process still has a handle open of a deleted file\n.fuse_hidden*\n\n# KDE directory preferences\n.directory\n\n# Linux trash folder which might appear on any partition or disk\n.Trash-*\n\n# .nfs files are created when an open file is removed but is still being accessed\n.nfs*\n\n### macOS ###\n# General\n.DS_Store\n.AppleDouble\n.LSOverride\n\n# Icon must end with two \\r\nIcon\n\n\n# Thumbnails\n._*\n\n# Files that might appear in the root of a volume\n.DocumentRevisions-V100\n.fseventsd\n.Spotlight-V100\n.TemporaryItems\n.Trashes\n.VolumeIcon.icns\n.com.apple.timemachine.donotpresent\n\n# Directories potentially created on remote AFP share\n.AppleDB\n.AppleDesktop\nNetwork Trash Folder\nTemporary Items\n.apdisk\n\n### Python ###\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n### VisualStudioCode ###\n.vscode/*\n!.vscode/settings.json\n!.vscode/tasks.json\n!.vscode/launch.json\n!.vscode/extensions.json\n*.code-workspace\n\n# Local History for Visual Studio Code\n.history/\n\n### VisualStudioCode Patch ###\n# Ignore all local history of files\n.history\n.ionide\n\n### Windows ###\n# Windows thumbnail cache files\nThumbs.db\nThumbs.db:encryptable\nehthumbs.db\nehthumbs_vista.db\n\n# Dump file\n*.stackdump\n\n# Folder config file\n[Dd]esktop.ini\n\n# Recycle Bin used on file shares\n$RECYCLE.BIN/\n\n# Windows Installer files\n*.cab\n*.msi\n*.msix\n*.msm\n*.msp\n\n# Windows shortcuts\n*.lnk\n\n# End of https://www.toptal.com/developers/gitignore/api/linux,windows,macos,visualstudiocode,python\n\noutput/\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# FLUX\nby Black Forest Labs: https://bfl.ai.\n\nDocumentation for our API can be found here: [docs.bfl.ai](https://docs.bfl.ai/).\n\n![grid](assets/grid.jpg)\n\nThis repo contains minimal inference code to run image generation & editing with our Flux open-weight models.\n\n## Local installation\n\n```bash\ncd $HOME && git clone https://github.com/black-forest-labs/flux\ncd $HOME/flux\npython3.10 -m venv .venv\nsource .venv/bin/activate\npip install -e \".[all]\"\n```\n\n### Local installation with TensorRT support\n\nIf you would like to install the repository with [TensorRT](https://github.com/NVIDIA/TensorRT) support, you currently need to install a PyTorch image from NVIDIA instead. First install [enroot](https://github.com/NVIDIA/enroot), next follow the steps below:\n\n```bash\ncd $HOME && git clone https://github.com/black-forest-labs/flux\nenroot import 'docker://$oauthtoken@nvcr.io#nvidia/pytorch:25.01-py3'\nenroot create -n pti2501 nvidia+pytorch+25.01-py3.sqsh\nenroot start --rw -m ${PWD}/flux:/workspace/flux -r pti2501\ncd flux\npip install -e \".[tensorrt]\" --extra-index-url https://pypi.nvidia.com\n```\n\n### Open-weight models\n\nWe are offering an extensive suite of open-weight models. For more information about the individual models, please refer to the link under **Usage**.\n\n| Name                        | Usage                                                      | HuggingFace repo                                               | License                                                               |\n| --------------------------- | ---------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `FLUX.1 [schnell]`          | [Text to Image](docs/text-to-image.md)                     | https://huggingface.co/black-forest-labs/FLUX.1-schnell        | [apache-2.0](model_licenses/LICENSE-FLUX1-schnell)                    |\n| `FLUX.1 [dev]`              | [Text to Image](docs/text-to-image.md)                     | https://huggingface.co/black-forest-labs/FLUX.1-dev            | [FLUX.1-dev Non-Commercial License](model_licenses/LICENSE-FLUX1-dev) |\n| `FLUX.1 Fill [dev]`         | [In/Out-painting](docs/fill.md)                            | https://huggingface.co/black-forest-labs/FLUX.1-Fill-dev       | [FLUX.1-dev Non-Commercial License](model_licenses/LICENSE-FLUX1-dev) |\n| `FLUX.1 Canny [dev]`        | [Structural Conditioning](docs/structural-conditioning.md) | https://huggingface.co/black-forest-labs/FLUX.1-Canny-dev      | [FLUX.1-dev Non-Commercial License](model_licenses/LICENSE-FLUX1-dev) |\n| `FLUX.1 Depth [dev]`        | [Structural Conditioning](docs/structural-conditioning.md) | https://huggingface.co/black-forest-labs/FLUX.1-Depth-dev      | [FLUX.1-dev Non-Commercial License](model_licenses/LICENSE-FLUX1-dev) |\n| `FLUX.1 Canny [dev] LoRA`   | [Structural Conditioning](docs/structural-conditioning.md) | https://huggingface.co/black-forest-labs/FLUX.1-Canny-dev-lora | [FLUX.1-dev Non-Commercial License](model_licenses/LICENSE-FLUX1-dev) |\n| `FLUX.1 Depth [dev] LoRA`   | [Structural Conditioning](docs/structural-conditioning.md) | https://huggingface.co/black-forest-labs/FLUX.1-Depth-dev-lora | [FLUX.1-dev Non-Commercial License](model_licenses/LICENSE-FLUX1-dev) |\n| `FLUX.1 Redux [dev]`        | [Image variation](docs/image-variation.md)                 | https://huggingface.co/black-forest-labs/FLUX.1-Redux-dev      | [FLUX.1-dev Non-Commercial License](model_licenses/LICENSE-FLUX1-dev) |\n| `FLUX.1 Kontext [dev]`      | [Image editing](docs/image-editing.md)                     | https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev    | [FLUX.1-dev Non-Commercial License](model_licenses/LICENSE-FLUX1-dev) |\n| `FLUX.1 Krea [dev]`         | [Text to Image](docs/text-to-image.md)                     | https://huggingface.co/black-forest-labs/FLUX.1-Krea-dev       | [FLUX.1-dev Non-Commercial License](model_licenses/LICENSE-FLUX1-dev) |\n\nThe weights of the autoencoder are also released under [apache-2.0](https://huggingface.co/datasets/choosealicense/licenses/blob/main/markdown/apache-2.0.md) and can be found in the HuggingFace repos above.\n\n## API usage\n\nOur API offers access to all models including our Pro tier non-open weight models. Check out our API documentation [docs.bfl.ai](https://docs.bfl.ai/) to learn more.\n\n## Licensing models for commercial use\n\nYou can license our models for commercial use here: https://bfl.ai/pricing/licensing\n\nAs the fee is based on a monthly usage, we provide code to automatically track your usage via the BFL API. To enable usage tracking please select *track_usage* in the cli or click the corresponding checkmark in our provided demos.\n\n### Example: Using FLUX.1 Kontext with usage tracking\n\nWe provide a reference implementation for running FLUX.1 with usage tracking enabled for commercial licensing.\nThis can be customized as needed as long as the usage reporting is accurate.\n\nFor the reporting logic to work you will need to set your API key as an environment variable before running:\n```bash\nexport BFL_API_KEY=\"your_api_key_here\"\n```\n\nYou can call `FLUX.1 Kontext [dev]` like this with tracking activated:\n\n```bash\npython -m flux kontext --track_usage --loop\n```\n\nFor a single generation:\n\n```bash\npython -m flux kontext --track_usage --prompt \"replace the logo with the text 'Black Forest Labs'\"\n```\n\nThe above reporting logic works similarly for FLUX.1 [dev] and FLUX.1 Tools [dev].\n\n**Note that this is only required when using one or more of our open weights models commercially. More information on the commercial licensing can be found at the [BFL Helpdesk](https://help.bfl.ai/collections/6939000511-licensing).**\n\n\n## Citation\n\nIf you find the provided code or models useful for your research, consider citing them as:\n\n```bib\n@misc{labs2025flux1kontextflowmatching,\n      title={FLUX.1 Kontext: Flow Matching for In-Context Image Generation and Editing in Latent Space},\n      author={Black Forest Labs and Stephen Batifol and Andreas Blattmann and Frederic Boesel and Saksham Consul and Cyril Diagne and Tim Dockhorn and Jack English and Zion English and Patrick Esser and Sumith Kulal and Kyle Lacey and Yam Levi and Cheng Li and Dominik Lorenz and Jonas Müller and Dustin Podell and Robin Rombach and Harry Saini and Axel Sauer and Luke Smith},\n      year={2025},\n      eprint={2506.15742},\n      archivePrefix={arXiv},\n      primaryClass={cs.GR},\n      url={https://arxiv.org/abs/2506.15742},\n}\n\n@misc{flux2024,\n    author={Black Forest Labs},\n    title={FLUX},\n    year={2024},\n    howpublished={\\url{https://github.com/black-forest-labs/flux}},\n}\n```\n"
  },
  {
    "path": "demo_gr.py",
    "content": "import os\nimport time\nimport uuid\n\nimport gradio as gr\nimport numpy as np\nimport torch\nfrom einops import rearrange\nfrom PIL import ExifTags, Image\nfrom transformers import pipeline\n\nfrom flux.cli import SamplingOptions\nfrom flux.sampling import denoise, get_noise, get_schedule, prepare, unpack\nfrom flux.util import (\n    configs,\n    embed_watermark,\n    load_ae,\n    load_clip,\n    load_flow_model,\n    load_t5,\n    track_usage_via_api,\n)\n\nNSFW_THRESHOLD = 0.85\n\n\ndef get_models(name: str, device: torch.device, offload: bool, is_schnell: bool):\n    t5 = load_t5(device, max_length=256 if is_schnell else 512)\n    clip = load_clip(device)\n    model = load_flow_model(name, device=\"cpu\" if offload else device)\n    ae = load_ae(name, device=\"cpu\" if offload else device)\n    nsfw_classifier = pipeline(\"image-classification\", model=\"Falconsai/nsfw_image_detection\", device=device)\n    return model, ae, t5, clip, nsfw_classifier\n\n\nclass FluxGenerator:\n    def __init__(self, model_name: str, device: str, offload: bool, track_usage: bool):\n        self.device = torch.device(device)\n        self.offload = offload\n        self.model_name = model_name\n        self.is_schnell = model_name == \"flux-schnell\"\n        self.model, self.ae, self.t5, self.clip, self.nsfw_classifier = get_models(\n            model_name,\n            device=self.device,\n            offload=self.offload,\n            is_schnell=self.is_schnell,\n        )\n        self.track_usage = track_usage\n\n    @torch.inference_mode()\n    def generate_image(\n        self,\n        width,\n        height,\n        num_steps,\n        guidance,\n        seed,\n        prompt,\n        init_image=None,\n        image2image_strength=0.0,\n        add_sampling_metadata=True,\n    ):\n        seed = int(seed)\n        if seed == -1:\n            seed = None\n\n        opts = SamplingOptions(\n            prompt=prompt,\n            width=width,\n            height=height,\n            num_steps=num_steps,\n            guidance=guidance,\n            seed=seed,\n        )\n\n        if opts.seed is None:\n            opts.seed = torch.Generator(device=\"cpu\").seed()\n        print(f\"Generating '{opts.prompt}' with seed {opts.seed}\")\n        t0 = time.perf_counter()\n\n        if init_image is not None:\n            if isinstance(init_image, np.ndarray):\n                init_image = torch.from_numpy(init_image).permute(2, 0, 1).float() / 255.0\n                init_image = init_image.unsqueeze(0)\n            init_image = init_image.to(self.device)\n            init_image = torch.nn.functional.interpolate(init_image, (opts.height, opts.width))\n            if self.offload:\n                self.ae.encoder.to(self.device)\n            init_image = self.ae.encode(init_image.to())\n            if self.offload:\n                self.ae = self.ae.cpu()\n                torch.cuda.empty_cache()\n\n        # prepare input\n        x = get_noise(\n            1,\n            opts.height,\n            opts.width,\n            device=self.device,\n            dtype=torch.bfloat16,\n            seed=opts.seed,\n        )\n        timesteps = get_schedule(\n            opts.num_steps,\n            x.shape[-1] * x.shape[-2] // 4,\n            shift=(not self.is_schnell),\n        )\n        if init_image is not None:\n            t_idx = int((1 - image2image_strength) * num_steps)\n            t = timesteps[t_idx]\n            timesteps = timesteps[t_idx:]\n            x = t * x + (1.0 - t) * init_image.to(x.dtype)\n\n        if self.offload:\n            self.t5, self.clip = self.t5.to(self.device), self.clip.to(self.device)\n        inp = prepare(t5=self.t5, clip=self.clip, img=x, prompt=opts.prompt)\n\n        # offload TEs to CPU, load model to gpu\n        if self.offload:\n            self.t5, self.clip = self.t5.cpu(), self.clip.cpu()\n            torch.cuda.empty_cache()\n            self.model = self.model.to(self.device)\n\n        # denoise initial noise\n        x = denoise(self.model, **inp, timesteps=timesteps, guidance=opts.guidance)\n\n        # offload model, load autoencoder to gpu\n        if self.offload:\n            self.model.cpu()\n            torch.cuda.empty_cache()\n            self.ae.decoder.to(x.device)\n\n        # decode latents to pixel space\n        x = unpack(x.float(), opts.height, opts.width)\n        with torch.autocast(device_type=self.device.type, dtype=torch.bfloat16):\n            x = self.ae.decode(x)\n\n        if self.offload:\n            self.ae.decoder.cpu()\n            torch.cuda.empty_cache()\n\n        t1 = time.perf_counter()\n\n        print(f\"Done in {t1 - t0:.1f}s.\")\n        # bring into PIL format\n        x = x.clamp(-1, 1)\n        x = embed_watermark(x.float())\n        x = rearrange(x[0], \"c h w -> h w c\")\n\n        img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())\n        nsfw_score = [x[\"score\"] for x in self.nsfw_classifier(img) if x[\"label\"] == \"nsfw\"][0]\n\n        if nsfw_score < NSFW_THRESHOLD:\n            filename = f\"output/gradio/{uuid.uuid4()}.jpg\"\n            os.makedirs(os.path.dirname(filename), exist_ok=True)\n            exif_data = Image.Exif()\n            if init_image is None:\n                exif_data[ExifTags.Base.Software] = \"AI generated;txt2img;flux\"\n            else:\n                exif_data[ExifTags.Base.Software] = \"AI generated;img2img;flux\"\n            exif_data[ExifTags.Base.Make] = \"Black Forest Labs\"\n            exif_data[ExifTags.Base.Model] = self.model_name\n            if add_sampling_metadata:\n                exif_data[ExifTags.Base.ImageDescription] = prompt\n            img.save(filename, format=\"jpeg\", exif=exif_data, quality=95, subsampling=0)\n\n            if self.track_usage:\n                track_usage_via_api(self.model_name, 1)\n\n            return img, str(opts.seed), filename, None\n        else:\n            return None, str(opts.seed), None, \"Your generated image may contain NSFW content.\"\n\n\ndef create_demo(\n    model_name: str,\n    device: str = \"cuda\" if torch.cuda.is_available() else \"cpu\",\n    offload: bool = False,\n    track_usage: bool = False,\n):\n    generator = FluxGenerator(model_name, device, offload, track_usage)\n    is_schnell = model_name == \"flux-schnell\"\n\n    with gr.Blocks() as demo:\n        gr.Markdown(f\"# Flux Image Generation Demo - Model: {model_name}\")\n\n        with gr.Row():\n            with gr.Column():\n                prompt = gr.Textbox(\n                    label=\"Prompt\",\n                    value='a photo of a forest with mist swirling around the tree trunks. The word \"FLUX\" is painted over it in big, red brush strokes with visible texture',\n                )\n                do_img2img = gr.Checkbox(label=\"Image to Image\", value=False, interactive=not is_schnell)\n                init_image = gr.Image(label=\"Input Image\", visible=False)\n                image2image_strength = gr.Slider(\n                    0.0, 1.0, 0.8, step=0.1, label=\"Noising strength\", visible=False\n                )\n\n                with gr.Accordion(\"Advanced Options\", open=False):\n                    width = gr.Slider(128, 8192, 1360, step=16, label=\"Width\")\n                    height = gr.Slider(128, 8192, 768, step=16, label=\"Height\")\n                    num_steps = gr.Slider(1, 50, 4 if is_schnell else 50, step=1, label=\"Number of steps\")\n                    guidance = gr.Slider(\n                        1.0, 10.0, 3.5, step=0.1, label=\"Guidance\", interactive=not is_schnell\n                    )\n                    seed = gr.Textbox(-1, label=\"Seed (-1 for random)\")\n                    add_sampling_metadata = gr.Checkbox(\n                        label=\"Add sampling parameters to metadata?\", value=True\n                    )\n\n                generate_btn = gr.Button(\"Generate\")\n\n            with gr.Column():\n                output_image = gr.Image(label=\"Generated Image\")\n                seed_output = gr.Number(label=\"Used Seed\")\n                warning_text = gr.Textbox(label=\"Warning\", visible=False)\n                download_btn = gr.File(label=\"Download full-resolution\")\n\n        def update_img2img(do_img2img):\n            return {\n                init_image: gr.update(visible=do_img2img),\n                image2image_strength: gr.update(visible=do_img2img),\n            }\n\n        do_img2img.change(update_img2img, do_img2img, [init_image, image2image_strength])\n\n        generate_btn.click(\n            fn=generator.generate_image,\n            inputs=[\n                width,\n                height,\n                num_steps,\n                guidance,\n                seed,\n                prompt,\n                init_image,\n                image2image_strength,\n                add_sampling_metadata,\n            ],\n            outputs=[output_image, seed_output, download_btn, warning_text],\n        )\n\n    return demo\n\n\nif __name__ == \"__main__\":\n    import argparse\n\n    parser = argparse.ArgumentParser(description=\"Flux\")\n    parser.add_argument(\n        \"--name\", type=str, default=\"flux-schnell\", choices=list(configs.keys()), help=\"Model name\"\n    )\n    parser.add_argument(\n        \"--device\", type=str, default=\"cuda\" if torch.cuda.is_available() else \"cpu\", help=\"Device to use\"\n    )\n    parser.add_argument(\"--offload\", action=\"store_true\", help=\"Offload model to CPU when not in use\")\n    parser.add_argument(\"--share\", action=\"store_true\", help=\"Create a public link to your demo\")\n    parser.add_argument(\"--track_usage\", action=\"store_true\", help=\"Track usage for licensing purposes\")\n    args = parser.parse_args()\n\n    demo = create_demo(args.name, args.device, args.offload, args.track_usage)\n    demo.launch(share=args.share)\n"
  },
  {
    "path": "demo_st.py",
    "content": "import os\nimport re\nimport time\nfrom glob import iglob\nfrom io import BytesIO\n\nimport streamlit as st\nimport torch\nfrom einops import rearrange\nfrom fire import Fire\nfrom PIL import ExifTags, Image\nfrom st_keyup import st_keyup\nfrom torchvision import transforms\nfrom transformers import pipeline\n\nfrom flux.cli import SamplingOptions\nfrom flux.sampling import denoise, get_noise, get_schedule, prepare, unpack\nfrom flux.util import (\n    configs,\n    embed_watermark,\n    load_ae,\n    load_clip,\n    load_flow_model,\n    load_t5,\n    track_usage_via_api,\n)\n\nNSFW_THRESHOLD = 0.85\n\n\n@st.cache_resource()\ndef get_models(name: str, device: torch.device, offload: bool, is_schnell: bool):\n    t5 = load_t5(device, max_length=256 if is_schnell else 512)\n    clip = load_clip(device)\n    model = load_flow_model(name, device=\"cpu\" if offload else device)\n    ae = load_ae(name, device=\"cpu\" if offload else device)\n    nsfw_classifier = pipeline(\"image-classification\", model=\"Falconsai/nsfw_image_detection\", device=device)\n    return model, ae, t5, clip, nsfw_classifier\n\n\ndef get_image() -> torch.Tensor | None:\n    image = st.file_uploader(\"Input\", type=[\"jpg\", \"JPEG\", \"png\"])\n    if image is None:\n        return None\n    image = Image.open(image).convert(\"RGB\")\n\n    transform = transforms.Compose(\n        [\n            transforms.ToTensor(),\n            transforms.Lambda(lambda x: 2.0 * x - 1.0),\n        ]\n    )\n    img: torch.Tensor = transform(image)\n    return img[None, ...]\n\n\n@torch.inference_mode()\ndef main(\n    device: str = \"cuda\" if torch.cuda.is_available() else \"cpu\",\n    offload: bool = False,\n    output_dir: str = \"output\",\n    track_usage: bool = False,\n):\n    torch_device = torch.device(device)\n    names = list(configs.keys())\n    name = st.selectbox(\"Which model to load?\", names)\n    if name is None or not st.checkbox(\"Load model\", False):\n        return\n\n    is_schnell = name == \"flux-schnell\"\n    model, ae, t5, clip, nsfw_classifier = get_models(\n        name,\n        device=torch_device,\n        offload=offload,\n        is_schnell=is_schnell,\n    )\n\n    do_img2img = (\n        st.checkbox(\n            \"Image to Image\",\n            False,\n            disabled=is_schnell,\n            help=\"Partially noise an image and denoise again to get variations.\\n\\nOnly works for flux-dev\",\n        )\n        and not is_schnell\n    )\n    if do_img2img:\n        init_image = get_image()\n        if init_image is None:\n            st.warning(\"Please add an image to do image to image\")\n        image2image_strength = st.number_input(\"Noising strength\", min_value=0.0, max_value=1.0, value=0.8)\n        if init_image is not None:\n            h, w = init_image.shape[-2:]\n            st.write(f\"Got image of size {w}x{h} ({h * w / 1e6:.2f}MP)\")\n        resize_img = st.checkbox(\"Resize image\", False) or init_image is None\n    else:\n        init_image = None\n        resize_img = True\n        image2image_strength = 0.0\n\n    # allow for packing and conversion to latent space\n    width = int(\n        16 * (st.number_input(\"Width\", min_value=128, value=1360, step=16, disabled=not resize_img) // 16)\n    )\n    height = int(\n        16 * (st.number_input(\"Height\", min_value=128, value=768, step=16, disabled=not resize_img) // 16)\n    )\n    num_steps = int(st.number_input(\"Number of steps\", min_value=1, value=(4 if is_schnell else 50)))\n    guidance = float(st.number_input(\"Guidance\", min_value=1.0, value=3.5, disabled=is_schnell))\n    seed_str = st.text_input(\"Seed\", disabled=is_schnell)\n    if seed_str.isdecimal():\n        seed = int(seed_str)\n    else:\n        st.info(\"No seed set, set to positive integer to enable\")\n        seed = None\n    save_samples = st.checkbox(\"Save samples?\", not is_schnell)\n    add_sampling_metadata = st.checkbox(\"Add sampling parameters to metadata?\", True)\n\n    default_prompt = (\n        \"a photo of a forest with mist swirling around the tree trunks. The word \"\n        '\"FLUX\" is painted over it in big, red brush strokes with visible texture'\n    )\n    prompt = st_keyup(\"Enter a prompt\", value=default_prompt, debounce=300, key=\"interactive_text\")\n\n    output_name = os.path.join(output_dir, \"img_{idx}.jpg\")\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n        idx = 0\n    else:\n        fns = [fn for fn in iglob(output_name.format(idx=\"*\")) if re.search(r\"img_[0-9]+\\.jpg$\", fn)]\n        if len(fns) > 0:\n            idx = max(int(fn.split(\"_\")[-1].split(\".\")[0]) for fn in fns) + 1\n        else:\n            idx = 0\n\n    rng = torch.Generator(device=\"cpu\")\n\n    if \"seed\" not in st.session_state:\n        st.session_state.seed = rng.seed()\n\n    def increment_counter():\n        st.session_state.seed += 1\n\n    def decrement_counter():\n        if st.session_state.seed > 0:\n            st.session_state.seed -= 1\n\n    opts = SamplingOptions(\n        prompt=prompt,\n        width=width,\n        height=height,\n        num_steps=num_steps,\n        guidance=guidance,\n        seed=seed,\n    )\n\n    if name == \"flux-schnell\":\n        cols = st.columns([5, 1, 1, 5])\n        with cols[1]:\n            st.button(\"↩\", on_click=increment_counter)\n        with cols[2]:\n            st.button(\"↪\", on_click=decrement_counter)\n    if is_schnell or st.button(\"Sample\"):\n        if is_schnell:\n            opts.seed = st.session_state.seed\n        elif opts.seed is None:\n            opts.seed = rng.seed()\n        print(f\"Generating '{opts.prompt}' with seed {opts.seed}\")\n        t0 = time.perf_counter()\n\n        if init_image is not None:\n            if resize_img:\n                init_image = torch.nn.functional.interpolate(init_image, (opts.height, opts.width))\n            else:\n                h, w = init_image.shape[-2:]\n                init_image = init_image[..., : 16 * (h // 16), : 16 * (w // 16)]\n                opts.height = init_image.shape[-2]\n                opts.width = init_image.shape[-1]\n            if offload:\n                ae.encoder.to(torch_device)\n            init_image = ae.encode(init_image.to(torch_device))\n            if offload:\n                ae = ae.cpu()\n                torch.cuda.empty_cache()\n\n        # prepare input\n        x = get_noise(\n            1,\n            opts.height,\n            opts.width,\n            device=torch_device,\n            dtype=torch.bfloat16,\n            seed=opts.seed,\n        )\n        # divide pixel space by 16**2 to account for latent space conversion\n        timesteps = get_schedule(\n            opts.num_steps,\n            (x.shape[-1] * x.shape[-2]) // 4,\n            shift=(not is_schnell),\n        )\n        if init_image is not None:\n            t_idx = int((1 - image2image_strength) * num_steps)\n            t = timesteps[t_idx]\n            timesteps = timesteps[t_idx:]\n            x = t * x + (1.0 - t) * init_image.to(x.dtype)\n\n        if offload:\n            t5, clip = t5.to(torch_device), clip.to(torch_device)\n        inp = prepare(t5=t5, clip=clip, img=x, prompt=opts.prompt)\n\n        # offload TEs to CPU, load model to gpu\n        if offload:\n            t5, clip = t5.cpu(), clip.cpu()\n            torch.cuda.empty_cache()\n            model = model.to(torch_device)\n\n        # denoise initial noise\n        x = denoise(model, **inp, timesteps=timesteps, guidance=opts.guidance)\n\n        # offload model, load autoencoder to gpu\n        if offload:\n            model.cpu()\n            torch.cuda.empty_cache()\n            ae.decoder.to(x.device)\n\n        # decode latents to pixel space\n        x = unpack(x.float(), opts.height, opts.width)\n        with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):\n            x = ae.decode(x)\n\n        if offload:\n            ae.decoder.cpu()\n            torch.cuda.empty_cache()\n\n        t1 = time.perf_counter()\n\n        fn = output_name.format(idx=idx)\n        print(f\"Done in {t1 - t0:.1f}s.\")\n        # bring into PIL format and save\n        x = x.clamp(-1, 1)\n        x = embed_watermark(x.float())\n        x = rearrange(x[0], \"c h w -> h w c\")\n\n        img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())\n        nsfw_score = [x[\"score\"] for x in nsfw_classifier(img) if x[\"label\"] == \"nsfw\"][0]\n\n        if nsfw_score < NSFW_THRESHOLD:\n            buffer = BytesIO()\n            exif_data = Image.Exif()\n            if init_image is None:\n                exif_data[ExifTags.Base.Software] = \"AI generated;txt2img;flux\"\n            else:\n                exif_data[ExifTags.Base.Software] = \"AI generated;img2img;flux\"\n            exif_data[ExifTags.Base.Make] = \"Black Forest Labs\"\n            exif_data[ExifTags.Base.Model] = name\n            if add_sampling_metadata:\n                exif_data[ExifTags.Base.ImageDescription] = prompt\n            img.save(buffer, format=\"jpeg\", exif=exif_data, quality=95, subsampling=0)\n\n            img_bytes = buffer.getvalue()\n            if save_samples:\n                print(f\"Saving {fn}\")\n                with open(fn, \"wb\") as file:\n                    file.write(img_bytes)\n                idx += 1\n            if track_usage:\n                track_usage_via_api(name, 1)\n\n            st.session_state[\"samples\"] = {\n                \"prompt\": opts.prompt,\n                \"img\": img,\n                \"seed\": opts.seed,\n                \"bytes\": img_bytes,\n            }\n            opts.seed = None\n        else:\n            st.warning(\"Your generated image may contain NSFW content.\")\n            st.session_state[\"samples\"] = None\n\n    samples = st.session_state.get(\"samples\", None)\n    if samples is not None:\n        st.image(samples[\"img\"], caption=samples[\"prompt\"])\n        st.download_button(\n            \"Download full-resolution\",\n            samples[\"bytes\"],\n            file_name=\"generated.jpg\",\n            mime=\"image/jpg\",\n        )\n        st.write(f\"Seed: {samples['seed']}\")\n\n\ndef app():\n    Fire(main)\n\n\nif __name__ == \"__main__\":\n    app()\n"
  },
  {
    "path": "demo_st_fill.py",
    "content": "import os\nimport re\nimport tempfile\nimport time\nfrom glob import iglob\nfrom io import BytesIO\n\nimport numpy as np\nimport streamlit as st\nimport torch\nfrom einops import rearrange\nfrom fire import Fire\nfrom PIL import ExifTags, Image\nfrom st_keyup import st_keyup\nfrom streamlit_drawable_canvas import st_canvas\nfrom transformers import pipeline\n\nfrom flux.sampling import denoise, get_noise, get_schedule, prepare_fill, unpack\nfrom flux.util import (\n    embed_watermark,\n    load_ae,\n    load_clip,\n    load_flow_model,\n    load_t5,\n    track_usage_via_api,\n)\n\nNSFW_THRESHOLD = 0.85\n\n\ndef add_border_and_mask(image, zoom_all=1.0, zoom_left=0, zoom_right=0, zoom_up=0, zoom_down=0, overlap=0):\n    \"\"\"Adds a black border around the image with individual side control and mask overlap\"\"\"\n    orig_width, orig_height = image.size\n\n    # Calculate padding for each side (in pixels)\n    left_pad = int(orig_width * zoom_left)\n    right_pad = int(orig_width * zoom_right)\n    top_pad = int(orig_height * zoom_up)\n    bottom_pad = int(orig_height * zoom_down)\n\n    # Calculate overlap in pixels\n    overlap_left = int(orig_width * overlap)\n    overlap_right = int(orig_width * overlap)\n    overlap_top = int(orig_height * overlap)\n    overlap_bottom = int(orig_height * overlap)\n\n    # If using the all-sides zoom, add it to each side\n    if zoom_all > 1.0:\n        extra_each_side = (zoom_all - 1.0) / 2\n        left_pad += int(orig_width * extra_each_side)\n        right_pad += int(orig_width * extra_each_side)\n        top_pad += int(orig_height * extra_each_side)\n        bottom_pad += int(orig_height * extra_each_side)\n\n    # Calculate new dimensions (ensure they're multiples of 32)\n    new_width = 32 * round((orig_width + left_pad + right_pad) / 32)\n    new_height = 32 * round((orig_height + top_pad + bottom_pad) / 32)\n\n    # Create new image with black border\n    bordered_image = Image.new(\"RGB\", (new_width, new_height), (0, 0, 0))\n    # Paste original image in position\n    paste_x = left_pad\n    paste_y = top_pad\n    bordered_image.paste(image, (paste_x, paste_y))\n\n    # Create mask (white where the border is, black where the original image was)\n    mask = Image.new(\"L\", (new_width, new_height), 255)  # White background\n    # Paste black rectangle with overlap adjustment\n    mask.paste(\n        0,\n        (\n            paste_x + overlap_left,  # Left edge moves right\n            paste_y + overlap_top,  # Top edge moves down\n            paste_x + orig_width - overlap_right,  # Right edge moves left\n            paste_y + orig_height - overlap_bottom,  # Bottom edge moves up\n        ),\n    )\n\n    return bordered_image, mask\n\n\n@st.cache_resource()\ndef get_models(name: str, device: torch.device, offload: bool):\n    t5 = load_t5(device, max_length=128)\n    clip = load_clip(device)\n    model = load_flow_model(name, device=\"cpu\" if offload else device)\n    ae = load_ae(name, device=\"cpu\" if offload else device)\n    nsfw_classifier = pipeline(\"image-classification\", model=\"Falconsai/nsfw_image_detection\", device=device)\n    return model, ae, t5, clip, nsfw_classifier\n\n\ndef resize(img: Image.Image, min_mp: float = 0.5, max_mp: float = 2.0) -> Image.Image:\n    width, height = img.size\n    mp = (width * height) / 1_000_000  # Current megapixels\n\n    if min_mp <= mp <= max_mp:\n        # Even if MP is in range, ensure dimensions are multiples of 32\n        new_width = int(32 * round(width / 32))\n        new_height = int(32 * round(height / 32))\n        if new_width != width or new_height != height:\n            return img.resize((new_width, new_height), Image.Resampling.LANCZOS)\n        return img\n\n    # Calculate scaling factor\n    if mp < min_mp:\n        scale = (min_mp / mp) ** 0.5\n    else:  # mp > max_mp\n        scale = (max_mp / mp) ** 0.5\n\n    new_width = int(32 * round(width * scale / 32))\n    new_height = int(32 * round(height * scale / 32))\n\n    return img.resize((new_width, new_height), Image.Resampling.LANCZOS)\n\n\ndef clear_canvas_state():\n    \"\"\"Clear all canvas-related state\"\"\"\n    keys_to_clear = [\"canvas\", \"last_image_dims\"]\n    for key in keys_to_clear:\n        if key in st.session_state:\n            del st.session_state[key]\n\n\ndef set_new_image(img: Image.Image):\n    \"\"\"Safely set a new image and clear relevant state\"\"\"\n    st.session_state[\"current_image\"] = img\n    clear_canvas_state()\n    st.rerun()\n\n\ndef downscale_image(img: Image.Image, scale_factor: float) -> Image.Image:\n    \"\"\"Downscale image by a given factor while maintaining 32-pixel multiple dimensions\"\"\"\n    if scale_factor >= 1.0:\n        return img\n\n    width, height = img.size\n    new_width = int(32 * round(width * scale_factor / 32))\n    new_height = int(32 * round(height * scale_factor / 32))\n\n    # Ensure minimum dimensions\n    new_width = max(64, new_width)  # minimum 64 pixels\n    new_height = max(64, new_height)  # minimum 64 pixels\n\n    return img.resize((new_width, new_height), Image.Resampling.LANCZOS)\n\n\n@torch.inference_mode()\ndef main(\n    device: str = \"cuda\" if torch.cuda.is_available() else \"cpu\",\n    offload: bool = False,\n    output_dir: str = \"output\",\n    track_usage: bool = False,\n):\n    torch_device = torch.device(device)\n    st.title(\"Flux Fill: Inpainting & Outpainting\")\n\n    # Model selection and loading\n    name = \"flux-dev-fill\"\n    if not st.checkbox(\"Load model\", False):\n        return\n\n    try:\n        model, ae, t5, clip, nsfw_classifier = get_models(\n            name,\n            device=torch_device,\n            offload=offload,\n        )\n    except Exception as e:\n        st.error(f\"Error loading models: {e}\")\n        return\n\n    # Mode selection\n    mode = st.radio(\"Select Mode\", [\"Inpainting\", \"Outpainting\"])\n\n    # Image handling - either from previous generation or new upload\n    if \"input_image\" in st.session_state:\n        image = st.session_state[\"input_image\"]\n        del st.session_state[\"input_image\"]\n        set_new_image(image)\n        st.write(\"Continuing from previous result\")\n    else:\n        uploaded_image = st.file_uploader(\"Upload image\", type=[\"jpg\", \"jpeg\", \"png\"])\n        if uploaded_image is None:\n            st.warning(\"Please upload an image\")\n            return\n\n        if (\n            \"current_image_name\" not in st.session_state\n            or st.session_state[\"current_image_name\"] != uploaded_image.name\n        ):\n            try:\n                image = Image.open(uploaded_image).convert(\"RGB\")\n                st.session_state[\"current_image_name\"] = uploaded_image.name\n                set_new_image(image)\n            except Exception as e:\n                st.error(f\"Error loading image: {e}\")\n                return\n        else:\n            image = st.session_state.get(\"current_image\")\n            if image is None:\n                st.error(\"Error: Image state is invalid. Please reupload the image.\")\n                clear_canvas_state()\n                return\n\n    # Add downscale control\n    with st.expander(\"Image Size Control\"):\n        current_mp = (image.size[0] * image.size[1]) / 1_000_000\n        st.write(f\"Current image size: {image.size[0]}x{image.size[1]} ({current_mp:.1f}MP)\")\n\n        scale_factor = st.slider(\n            \"Downscale Factor\",\n            min_value=0.1,\n            max_value=1.0,\n            value=1.0,\n            step=0.1,\n            help=\"1.0 = original size, 0.5 = half size, etc.\",\n        )\n\n        if scale_factor < 1.0 and st.button(\"Apply Downscaling\"):\n            image = downscale_image(image, scale_factor)\n            set_new_image(image)\n            st.rerun()\n\n    # Resize image with validation\n    try:\n        original_mp = (image.size[0] * image.size[1]) / 1_000_000\n        image = resize(image)\n        width, height = image.size\n        current_mp = (width * height) / 1_000_000\n\n        if width % 32 != 0 or height % 32 != 0:\n            st.error(\"Error: Image dimensions must be multiples of 32\")\n            return\n\n        st.write(f\"Image dimensions: {width}x{height} pixels\")\n        if original_mp != current_mp:\n            st.write(\n                f\"Image has been resized from {original_mp:.1f}MP to {current_mp:.1f}MP to stay within bounds (0.5MP - 2MP)\"\n            )\n    except Exception as e:\n        st.error(f\"Error processing image: {e}\")\n        return\n\n    if mode == \"Outpainting\":\n        # Outpainting controls\n        zoom_all = st.slider(\"Zoom Out Amount (All Sides)\", min_value=1.0, max_value=3.0, value=1.0, step=0.1)\n\n        with st.expander(\"Advanced Zoom Controls\"):\n            st.info(\"These controls add additional zoom to specific sides\")\n            col1, col2 = st.columns(2)\n            with col1:\n                zoom_left = st.slider(\"Left\", min_value=0.0, max_value=1.0, value=0.0, step=0.1)\n                zoom_right = st.slider(\"Right\", min_value=0.0, max_value=1.0, value=0.0, step=0.1)\n            with col2:\n                zoom_up = st.slider(\"Up\", min_value=0.0, max_value=1.0, value=0.0, step=0.1)\n                zoom_down = st.slider(\"Down\", min_value=0.0, max_value=1.0, value=0.0, step=0.1)\n\n        overlap = st.slider(\"Overlap\", min_value=0.01, max_value=0.25, value=0.01, step=0.01)\n\n        # Generate bordered image and mask\n        image_for_generation, mask = add_border_and_mask(\n            image,\n            zoom_all=zoom_all,\n            zoom_left=zoom_left,\n            zoom_right=zoom_right,\n            zoom_up=zoom_up,\n            zoom_down=zoom_down,\n            overlap=overlap,\n        )\n        width, height = image_for_generation.size\n\n        # Show preview\n        col1, col2 = st.columns(2)\n        with col1:\n            st.image(image_for_generation, caption=\"Image with Border\")\n        with col2:\n            st.image(mask, caption=\"Mask (white areas will be generated)\")\n\n    else:  # Inpainting mode\n        # Canvas setup with dimension tracking\n        canvas_key = f\"canvas_{width}_{height}\"\n        if \"last_image_dims\" not in st.session_state:\n            st.session_state.last_image_dims = (width, height)\n        elif st.session_state.last_image_dims != (width, height):\n            clear_canvas_state()\n            st.session_state.last_image_dims = (width, height)\n            st.rerun()\n\n        try:\n            canvas_result = st_canvas(\n                fill_color=\"rgba(255, 255, 255, 0.0)\",\n                stroke_width=st.slider(\"Brush size\", 1, 500, 50),\n                stroke_color=\"#fff\",\n                background_image=image,\n                height=height,\n                width=width,\n                drawing_mode=\"freedraw\",\n                key=canvas_key,\n                display_toolbar=True,\n            )\n        except Exception as e:\n            st.error(f\"Error creating canvas: {e}\")\n            clear_canvas_state()\n            st.rerun()\n            return\n\n    # Sampling parameters\n    num_steps = int(st.number_input(\"Number of steps\", min_value=1, value=50))\n    guidance = float(st.number_input(\"Guidance\", min_value=1.0, value=30.0))\n    seed_str = st.text_input(\"Seed\")\n    if seed_str.isdecimal():\n        seed = int(seed_str)\n    else:\n        st.info(\"No seed set, using random seed\")\n        seed = None\n\n    save_samples = st.checkbox(\"Save samples?\", True)\n    add_sampling_metadata = st.checkbox(\"Add sampling parameters to metadata?\", True)\n\n    # Prompt input\n    prompt = st_keyup(\"Enter a prompt\", value=\"\", debounce=300, key=\"interactive_text\")\n\n    # Setup output path\n    output_name = os.path.join(output_dir, \"img_{idx}.jpg\")\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n        idx = 0\n    else:\n        fns = [fn for fn in iglob(output_name.format(idx=\"*\")) if re.search(r\"img_[0-9]+\\.jpg$\", fn)]\n        idx = len(fns)\n\n    if st.button(\"Generate\"):\n        valid_input = False\n\n        if mode == \"Inpainting\" and canvas_result.image_data is not None:\n            valid_input = True\n            # Create mask from canvas\n            try:\n                mask = Image.fromarray(canvas_result.image_data)\n                mask = mask.getchannel(\"A\")  # Get alpha channel\n                mask_array = np.array(mask)\n                mask_array = (mask_array > 0).astype(np.uint8) * 255\n                mask = Image.fromarray(mask_array)\n                image_for_generation = image\n            except Exception as e:\n                st.error(f\"Error creating mask: {e}\")\n                return\n\n        elif mode == \"Outpainting\":\n            valid_input = True\n            # image_for_generation and mask are already set above\n\n        if not valid_input:\n            st.error(\"Please draw a mask or configure outpainting settings\")\n            return\n\n        # Create temporary files\n        with (\n            tempfile.NamedTemporaryFile(suffix=\".png\", delete=False) as tmp_img,\n            tempfile.NamedTemporaryFile(suffix=\".png\", delete=False) as tmp_mask,\n        ):\n            try:\n                image_for_generation.save(tmp_img.name)\n                mask.save(tmp_mask.name)\n            except Exception as e:\n                st.error(f\"Error saving temporary files: {e}\")\n                return\n\n            try:\n                # Generate inpainting/outpainting\n                rng = torch.Generator(device=\"cpu\")\n                if seed is None:\n                    seed = rng.seed()\n\n                print(f\"Generating with seed {seed}:\\n{prompt}\")\n                t0 = time.perf_counter()\n\n                x = get_noise(\n                    1,\n                    height,\n                    width,\n                    device=torch_device,\n                    dtype=torch.bfloat16,\n                    seed=seed,\n                )\n\n                if offload:\n                    t5, clip, ae = t5.to(torch_device), clip.to(torch_device), ae.to(torch_device)\n\n                inp = prepare_fill(\n                    t5,\n                    clip,\n                    x,\n                    prompt=prompt,\n                    ae=ae,\n                    img_cond_path=tmp_img.name,\n                    mask_path=tmp_mask.name,\n                )\n\n                timesteps = get_schedule(num_steps, inp[\"img\"].shape[1], shift=True)\n\n                if offload:\n                    t5, clip, ae = t5.cpu(), clip.cpu(), ae.cpu()\n                    torch.cuda.empty_cache()\n                    model = model.to(torch_device)\n\n                x = denoise(model, **inp, timesteps=timesteps, guidance=guidance)\n\n                if offload:\n                    model.cpu()\n                    torch.cuda.empty_cache()\n                    ae.decoder.to(x.device)\n\n                x = unpack(x.float(), height, width)\n                with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):\n                    x = ae.decode(x)\n\n                t1 = time.perf_counter()\n                print(f\"Done in {t1 - t0:.1f}s\")\n\n                # Process and display result\n                x = x.clamp(-1, 1)\n                x = embed_watermark(x.float())\n                x = rearrange(x[0], \"c h w -> h w c\")\n                img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())\n\n                nsfw_score = [x[\"score\"] for x in nsfw_classifier(img) if x[\"label\"] == \"nsfw\"][0]\n\n                if nsfw_score < NSFW_THRESHOLD:\n                    buffer = BytesIO()\n                    exif_data = Image.Exif()\n                    exif_data[ExifTags.Base.Software] = \"AI generated;inpainting;flux\"\n                    exif_data[ExifTags.Base.Make] = \"Black Forest Labs\"\n                    exif_data[ExifTags.Base.Model] = name\n                    if add_sampling_metadata:\n                        exif_data[ExifTags.Base.ImageDescription] = prompt\n                    img.save(buffer, format=\"jpeg\", exif=exif_data, quality=95, subsampling=0)\n\n                    img_bytes = buffer.getvalue()\n                    if save_samples:\n                        fn = output_name.format(idx=idx)\n                        print(f\"Saving {fn}\")\n                        with open(fn, \"wb\") as file:\n                            file.write(img_bytes)\n\n                    if track_usage:\n                        track_usage_via_api(name, 1)\n\n                    st.session_state[\"samples\"] = {\n                        \"prompt\": prompt,\n                        \"img\": img,\n                        \"seed\": seed,\n                        \"bytes\": img_bytes,\n                    }\n                else:\n                    st.warning(\"Your generated image may contain NSFW content.\")\n                    st.session_state[\"samples\"] = None\n\n            except Exception as e:\n                st.error(f\"Error during generation: {e}\")\n                return\n            finally:\n                # Clean up temporary files\n                try:\n                    os.unlink(tmp_img.name)\n                    os.unlink(tmp_mask.name)\n                except Exception as e:\n                    print(f\"Error cleaning up temporary files: {e}\")\n\n    # Display results\n    samples = st.session_state.get(\"samples\", None)\n    if samples is not None:\n        st.image(samples[\"img\"], caption=samples[\"prompt\"])\n        col1, col2 = st.columns(2)\n        with col1:\n            st.download_button(\n                \"Download full-resolution\",\n                samples[\"bytes\"],\n                file_name=\"generated.jpg\",\n                mime=\"image/jpg\",\n            )\n        with col2:\n            if st.button(\"Continue from this image\"):\n                # Store the generated image\n                new_image = samples[\"img\"]\n                # Clear ALL canvas state\n                clear_canvas_state()\n                if \"samples\" in st.session_state:\n                    del st.session_state[\"samples\"]\n                # Set as current image\n                st.session_state[\"current_image\"] = new_image\n                st.rerun()\n\n        st.write(f\"Seed: {samples['seed']}\")\n\n\ndef app():\n    Fire(main)\n\n\nif __name__ == \"__main__\":\n    st.set_page_config(layout=\"wide\")\n    app()\n"
  },
  {
    "path": "docs/fill.md",
    "content": "## Open-weight models\n\nFLUX.1 Fill introduces advanced inpainting and outpainting capabilities. It allows for seamless edits that integrate naturally with existing images.\n\n| Name                | HuggingFace repo                                         | License                                                               | sha256sum                                                        |\n| ------------------- | -------------------------------------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------- |\n| `FLUX.1 Fill [dev]` | https://huggingface.co/black-forest-labs/FLUX.1-Fill-dev | [FLUX.1-dev Non-Commercial License](model_licenses/LICENSE-FLUX1-dev) | 03e289f530df51d014f48e675a9ffa2141bc003259bf5f25d75b957e920a41ca |\n\n## Examples\n\n![inpainting](../assets/docs/inpainting.png)\n![outpainting](../assets/docs/outpainting.png)\n\n## Open-weights usage\n\nThe weights will be downloaded automatically to `checkpoints/` from HuggingFace once you start one of the demos. Alternatively, you may download the weights manually and put them in `checkpoints/`, or you can also manually link them with the following environment variables:\n```bash\nexport FLUX_MODEL=<your model path here>\nexport FLUX_AE=<your autoencoder path here>\n```\n\nFor interactive sampling run\n\n```bash\npython -m flux fill --loop\n```\n\nOr to generate a single sample run\n\n```bash\npython -m flux fill \\\n  --img_cond_path <path_to_input_image> \\\n  --img_mask_path <path_to_input_mask>\n```\n\nThe input_mask should be an image of the same size as the conditioning image that only contains black and white pixels; see [an example mask](../assets/cup_mask.png) for [this image](../assets/cup.png).\n\nWe also provide an interactive streamlit demo. The demo can be run via\n\n```bash\nstreamlit run demo_st_fill.py\n```\n"
  },
  {
    "path": "docs/image-editing.md",
    "content": "## Open-weight models\n\nWe currently offer two open-weight text-to-image models.\n\n| Name                      | HuggingFace repo                                                | License                                                               | sha256sum                                                        |\n| ------------------------- | ----------------------------------------------------------------| --------------------------------------------------------------------- | ---------------------------------------------------------------- |\n| `FLUX.1 Kontext [dev]`    | https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev     | [FLUX.1-dev Non-Commercial License](../model_licenses/LICENSE-FLUX1-dev) | 843a26dc765d3105dba081c30bce7b14c65b0988f9e8d14e9fbc8856a6deebd5 |\n\n## Examples\n\n![FLUX.1 [dev] Grid](../assets/docs/kontext.png)\n\n## Open-weights usage\n\nThe weights will be downloaded automatically to `checkpoints/` from HuggingFace once you start one of the demos. Alternatively, you may download the weights manually and put them in `checkpoints/`, or you can also manually link them with the following environment variables:\n```bash\nexport FLUX_MODEL=<your model path here>\nexport FLUX_AE=<your autoencoder path here>\n```\n\nFor interactive sampling run\n\n```bash\npython -m flux kontext --loop\n```\nOr to generate a single sample run\n\n```bash\npython -m flux kontext \\\n  --img_cond_path <path_to_input_image> \\\n  --prompt <your_prompt> \\\n  --num_steps 30 --aspect_ratio \"16:9\" --guidance 2.5 --seed 1\n```\nNote that the flags `num_steps`, `aspect_ratio`, `guidance` and `seed` are\noptional. For more available flags see [the code](../src/flux/cli_kontext.py).\n\n### TRT engine infernece\n\nWe provide exports in BF16, FP8, and FP4 precision. Note that you need to install the repository with TensorRT support as outlined [here](../README.md).\n\n```bash\npython -m flux kontext --loop --trt --trt_transformer_precision <precision>\n```\nwhere `<trt_transformer_precision>` is either `bf16`, `fp8`, or `fp4_sdvd32`.\n"
  },
  {
    "path": "docs/image-variation.md",
    "content": "## Models\n\nFLUX.1 Redux is an adapter for the FLUX.1 text-to-image base models, FLUX.1 [dev] and FLUX.1 [schnell], which can be used to generate image variations.\n\n| Name                        | HuggingFace repo                                            | License                                                               | sha256sum                                                        |\n| --------------------------- | ----------------------------------------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------- |\n| `FLUX.1 Redux [dev]`        | https://huggingface.co/black-forest-labs/FLUX.1-Redux-dev   | [FLUX.1-dev Non-Commercial License](../model_licenses/LICENSE-FLUX1-dev) | a1b3bdcb4bdc58ce04874b9ca776d61fc3e914bb6beab41efb63e4e2694dca45 |\n\n\n## Examples\n\n![redux](../assets/docs/redux.png)\n\n## Open-weights usage\n\nThe weights will be downloaded automatically to `checkpoints/` from HuggingFace once you start one of the demos. Alternatively, you may download the weights manually and put them in `checkpoints/`, or you can also manually link them with the following environment variables:\n```bash\nexport FLUX_MODEL=<your model path here>\nexport FLUX_REDUX=<your redux path here>\nexport FLUX_AE=<your autoencoder path here>\n```\n\nFor interactive sampling run:\n\n```bash\npython -m flux redux --name <name> --loop\n```\n\nwhere `name` specifies the base model, which should be one of `flux-dev` or `flux-schnell`.\n"
  },
  {
    "path": "docs/structural-conditioning.md",
    "content": "## Models\n\nStructural conditioning uses canny edge or depth detection to maintain precise control during image transformations. By preserving the original image's structure through edge or depth maps, users can make text-guided edits while keeping the core composition intact. This is particularly effective for retexturing images. We release four variations: two based on edge maps (full model and LoRA for FLUX.1 [dev]) and two based on depth maps (full model and LoRA for FLUX.1 [dev]).\n\n| Name                      | HuggingFace repo                                               | License                                                               | sha256sum                                                        |\n| ------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------- |\n| `FLUX.1 Canny [dev]`      | https://huggingface.co/black-forest-labs/FLUX.1-Canny-dev      | [FLUX.1-dev Non-Commercial License](../model_licenses/LICENSE-FLUX1-dev) | 996876670169591cb412b937fbd46ea14cbed6933aef17c48a2dcd9685c98cdb |\n| `FLUX.1 Depth [dev]`      | https://huggingface.co/black-forest-labs/FLUX.1-Depth-dev      | [FLUX.1-dev Non-Commercial License](../model_licenses/LICENSE-FLUX1-dev) | 41360d1662f44ca45bc1b665fe6387e91802f53911001630d970a4f8be8dac21 |\n| `FLUX.1 Canny [dev] LoRA` | https://huggingface.co/black-forest-labs/FLUX.1-Canny-dev-lora | [FLUX.1-dev Non-Commercial License](../model_licenses/LICENSE-FLUX1-dev) | 8eaa21b9c43d5e7242844deb64b8cf22ae9010f813f955ca8c05f240b8a98f7e |\n| `FLUX.1 Depth [dev] LoRA` | https://huggingface.co/black-forest-labs/FLUX.1-Depth-dev-lora | [FLUX.1-dev Non-Commercial License](../model_licenses/LICENSE-FLUX1-dev) | 1938b38ea0fdd98080fa3e48beb2bedfbc7ad102d8b65e6614de704a46d8b907 |\n\n## Examples\n\n![canny](../assets/docs/canny.png)\n![depth](../assets/docs/depth.png)\n\n## Open-weights usage\n\nThe weights will be downloaded automatically to `checkpoints/` from HuggingFace once you start one of the demos. Alternatively, you may download the weights manually and put them in `checkpoints/`, or you can also manually link them with the following environment variables:\n```bash\nexport FLUX_MODEL=<your model path here>\nexport FLUX_AE=<your autoencoder path here>\n\n# optional (see below)\nexport FLUX_LORA=<your lora path here>\n```\n\nNote that the LoRA models (`flux-dev-canny-lora` and `flux-dev-depth-lora`) require the base FLUX.1 [dev] model to be downloaded first. The system will automatically download both the base model and the LoRA adapter when using these variants.\n\nFor interactive sampling run\n\n```bash\npython -m flux control --name <name> --loop\n```\n\nwhere `name` is one of `flux-dev-canny`, `flux-dev-depth`, `flux-dev-canny-lora`, or `flux-dev-depth-lora`.\n\n### TRT engine inference\n\n We provide exports in BF16, FP8, and FP4 precision. Note that you need to install the repository with TensorRT support as outlined [here](../README.md).\n\n```bash\npython flux control --name=<name> --loop --img_cond_path=\"assets/robot.webp\" --trt --static_shape=False --trt_transformer_precision <precision>\n```\nwhere `<precision>` is either `bf16`, `fp8`, or `fp4`.\n\n## Diffusers usage\n\nFlux Control (including the LoRAs) is also compatible with the `diffusers` Python library. Check out the [documentation](https://huggingface.co/docs/diffusers/main/en/api/pipelines/flux) to learn more.\n"
  },
  {
    "path": "docs/text-to-image.md",
    "content": "## Open-weight models\n\nWe currently offer two open-weight text-to-image models.\n\n| Name                      | HuggingFace repo                                         | License                                                                  | sha256sum                                                        |\n| --------------------------|----------------------------------------------------------| -------------------------------------------------------------------------|----------------------------------------------------------------- |\n| `FLUX.1 [schnell]`        | https://huggingface.co/black-forest-labs/FLUX.1-schnell  | [apache-2.0](../model_licenses/LICENSE-FLUX1-schnell)                    | 9403429e0052277ac2a87ad800adece5481eecefd9ed334e1f348723621d2a0a |\n| `FLUX.1 [dev]`            | https://huggingface.co/black-forest-labs/FLUX.1-dev      | [FLUX.1-dev Non-Commercial License](../model_licenses/LICENSE-FLUX1-dev) | 4610115bb0c89560703c892c59ac2742fa821e60ef5871b33493ba544683abd7 |\n| `FLUX.1 Krea [dev]`       | https://huggingface.co/black-forest-labs/FLUX.1-Krea-dev | [FLUX.1-dev Non-Commercial License](../model_licenses/LICENSE-FLUX1-dev) | 4610115bb0c89560703c892c59ac2742fa821e60ef5871b33493ba544683abd7 |\n\n## Open-weights usage\n\nThe weights will be downloaded automatically to `checkpoints/` from HuggingFace once you start one of the demos. Alternatively, you may download the weights manually and put them in `checkpoints/`, or you can also manually link them with the following environment variables:\n```bash\nexport FLUX_MODEL=<your model path here>\nexport FLUX_AE=<your autoencoder path here>\n```\n\nFor interactive sampling run\n\n```bash\npython -m flux t2i --name <name> --loop\n```\n\nwhere `name` is one of `flux-dev` or `flux-schnell`. Or to generate a single sample run\n\n```bash\npython -m flux t2i --name <name> \\\n  --height <height> --width <width> \\\n  --prompt \"<prompt>\"\n```\n\n### TRT engine infernece\n\nWe provide exports in BF16, FP8, and FP4 precision. Note that you need to install the repository with TensorRT support as outlined [here](../README.md).\n\n```bash\npython -m flux t2i --name=<name> --loop --trt --trt_transformer_precision <precision>\n```\nwhere `<trt_transformer_precision>` is either `bf16`, `fp8`, or `fp4`. For ONNX exports, `height` and `width` have to be within 768 and 1344.\n\n### Streamlit and Gradio\n\nWe also provide a streamlit demo that does both text-to-image and image-to-image. The demo can be run via\n\n```bash\nstreamlit run demo_st.py\n```\n\nWe also offer a Gradio-based demo for an interactive experience. To run the Gradio demo:\n\n```bash\npython demo_gr.py --name flux-schnell --device cuda\n```\n\nOptions:\n\n- `--name`: Choose the model to use (options: \"flux-schnell\", \"flux-dev\")\n- `--device`: Specify the device to use (default: \"cuda\" if available, otherwise \"cpu\")\n- `--offload`: Offload model to CPU when not in use\n- `--share`: Create a public link to your demo\n\nTo run the demo with the dev model and create a public link:\n\n```bash\npython demo_gr.py --name flux-dev --share\n```\n\n## Diffusers integration\n\n`FLUX.1 [schnell]` and `FLUX.1 [dev]` are integrated with the [🧨 diffusers](https://github.com/huggingface/diffusers) library. To use it with diffusers, install it:\n\n```shell\npip install git+https://github.com/huggingface/diffusers.git\n```\n\nThen you can use `FluxPipeline` to run the model\n\n```python\nimport torch\nfrom diffusers import FluxPipeline\n\nmodel_id = \"black-forest-labs/FLUX.1-schnell\" #you can also use `black-forest-labs/FLUX.1-dev`\n\npipe = FluxPipeline.from_pretrained(\"black-forest-labs/FLUX.1-schnell\", torch_dtype=torch.bfloat16)\npipe.enable_model_cpu_offload() #save some VRAM by offloading the model to CPU. Remove this if you have enough GPU power\n\nprompt = \"A cat holding a sign that says hello world\"\nseed = 42\nimage = pipe(\n    prompt,\n    output_type=\"pil\",\n    num_inference_steps=4, #use a larger number if you are using [dev]\n    generator=torch.Generator(\"cpu\").manual_seed(seed)\n).images[0]\nimage.save(\"flux-schnell.png\")\n```\n\nTo learn more check out the [diffusers](https://huggingface.co/docs/diffusers/main/en/api/pipelines/flux) documentation\n"
  },
  {
    "path": "model_cards/FLUX.1-Krea-dev.md",
    "content": "![FLUX.1 Krea [dev] Grid](../assets/flux-1-krea-dev-grid.png)\n\n`FLUX.1 Krea [dev]` is a 12 billion parameter rectified flow transformer capable of generating images from text descriptions.\nFor more information, please read our [blog post](https://bfl.ai/announcements/flux-1-krea-dev).\n\n\n# Key Features\n1. Cutting-edge output quality, with a focus on aesthetic photography.\n2. Competitive prompt following, matching the performance of closed source alternatives.\n3. Trained using guidance distillation, making `FLUX.1 Krea [dev]` more efficient.\n4. Open weights to drive new scientific research, and empower artists to develop innovative workflows.\n5. Generated outputs can be used for personal, scientific, and commercial purposes, as described in the [flux-1-dev-non-commercial-license](https://github.com/black-forest-labs/flux/blob/main/model_licenses/LICENSE-FLUX1-dev).\n\n# Usage\n`FLUX.1 Krea [dev]` can be used as a drop-in replacement in every system that supports the original `FLUX.1 [dev]`.\nA reference implementation of `FLUX.1 [dev]` is in our dedicated [github repository](https://github.com/black-forest-labs/flux).\nDevelopers and creatives looking to build on top of `FLUX.1 [dev]` are encouraged to use this as a starting point.\n\n`FLUX.1 Krea [dev]` is also available in both [ComfyUI](https://github.com/comfyanonymous/ComfyUI) and [Diffusers](https://github.com/huggingface/diffusers).\n\n---\n\n# Limitations\n- This model is not intended or able to provide factual information.\n- As a statistical model this checkpoint might amplify existing societal biases.\n- The model may fail to generate output that matches the prompts.\n- Prompt following is heavily influenced by the prompting-style.\n\n---\n\n# Out-of-Scope Use\nThe model and its derivatives may not be used\n\n- In any way that violates any applicable national, federal, state, local or international law or regulation.\n- For the purpose of exploiting, harming or attempting to exploit or harm minors in any way; including but not limited to the solicitation, creation, acquisition, or dissemination of child exploitative content.\n- To generate or disseminate verifiably false information and/or content with the purpose of harming others.\n- To generate or disseminate personal identifiable information that can be used to harm an individual.\n- To harass, abuse, threaten, stalk, or bully individuals or groups of individuals.\n- To create non-consensual nudity or illegal pornographic content.\n- For fully automated decision making that adversely impacts an individual's legal rights or otherwise creates or modifies a binding, enforceable obligation.\n- Generating or facilitating large-scale disinformation campaigns.\n- Please reference our [content filters](https://github.com/black-forest-labs/flux/blob/main/src/flux/content_filters.py) to avoid such generations.\n\n---\n\n# Risks \n\nBlack Forest Labs (BFL) and Krea are committed to the responsible development of generative AI technology. Prior to releasing FLUX.1 Krea [dev], BFL and Krea collaboratively evaluated and mitigated a number of risks in the FLUX.1 Krea [dev]  model and services, including the generation of unlawful content. We implemented a series of pre-release mitigations to help prevent misuse by third parties, with additional post-release mitigations to help address residual risks:\n1. **Pre-training mitigation.** BFL filtered pre-training data for multiple categories of “not safe for work” (NSFW) and unlawful content to help prevent a user generating unlawful content in response to text prompts or uploaded images.\n2. **Post-training mitigation.** BFL has partnered with the Internet Watch Foundation, an independent nonprofit organization dedicated to preventing online abuse, to filter known child sexual abuse material (CSAM) from post-training data. Subsequently, BFL and Krea undertook multiple rounds of targeted fine-tuning to provide additional mitigation against potential abuse. By inhibiting certain behaviors and concepts in the trained model, these techniques can help to prevent a user generating synthetic CSAM or nonconsensual intimate imagery (NCII) from a text prompt.\n3. **Pre-release evaluation.** Throughout this process, BFL conducted internal and external third-party evaluations of model checkpoints to identify further opportunities for improvement. The third-party evaluations focused on eliciting CSAM and NCII through adversarial testing of the text-to-image model with text-only prompts. We also conducted internal evaluations of the proposed release checkpoints, comparing the model with other leading openly-available generative image models from other companies. The final FLUX.1 Krea [dev] open-weight model checkpoint demonstrated very high resilience against violative inputs, demonstrating higher resilience than other similar open-weight models across these risk categories.  Based on these findings, we approved the release of the FLUX.1 Krea [dev] model as openly-available weights under a non-commercial license to support third-party research and development.\n4. **Inference filters.** The BFL Github repository for the open FLUX.1 Krea [dev] model includes filters for illegal or infringing content. Filters or manual review must be used with the model under the terms of the FLUX.1 [dev] Non-Commercial License. We may approach known deployers of the FLUX.1 Krea [dev] model at random to verify that filters or manual review processes are in place.\n5. **Policies.** Our FLUX.1 [dev] Non-Commercial License prohibits the generation of unlawful content or the use of generated content for unlawful, defamatory, or abusive purposes. Developers and users must consent to these conditions to access the FLUX.1 Krea [dev] model.\n6. **Monitoring.** BFL is monitoring for patterns of violative use after release, and may ban developers who we detect intentionally and repeatedly violate our policies. Additionally, BFL provides a dedicated email address (safety@blackforestlabs.ai) to solicit feedback from the community. BFL maintains a reporting relationship with organizations such as the Internet Watch Foundation and the National Center for Missing and Exploited Children, and BFL welcomes ongoing engagement with authorities, developers, and researchers to share intelligence about emerging risks and develop effective mitigations.\n\n---\n\n# License\nThis model falls under the [`FLUX.1 [dev]` Non-Commercial License](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md).\n"
  },
  {
    "path": "model_cards/FLUX.1-dev.md",
    "content": "![FLUX.1 [dev] Grid](../assets/dev_grid.jpg)\n\n`FLUX.1 [dev]` is a 12 billion parameter rectified flow transformer capable of generating images from text descriptions.\nFor more information, please read our [blog post](https://blackforestlabs.ai/announcing-black-forest-labs/).\n\n# Key Features\n1. Cutting-edge output quality, second only to our state-of-the-art model `FLUX.1 [pro]`.\n2. Competitive prompt following, matching the performance of closed source alternatives.\n3. Trained using guidance distillation, making `FLUX.1 [dev]` more efficient.\n4. Open weights to drive new scientific research, and empower artists to develop innovative workflows.\n5. Generated outputs can be used for personal, scientific, and commercial purposes, as described in the [flux-1-dev-non-commercial-license](./licence.md).\n\n# Usage\nWe provide a reference implementation of `FLUX.1 [dev]`, as well as sampling code, in a dedicated [github repository](https://github.com/black-forest-labs/flux).\nDevelopers and creatives looking to build on top of `FLUX.1 [dev]` are encouraged to use this as a starting point.\n\n## API Endpoints\nThe FLUX.1 models are also available via API from the following sources\n1. [bfl.ml](https://docs.bfl.ml/) (currently `FLUX.1 [pro]`)\n2. [replicate.com](https://replicate.com/collections/flux)\n3. [fal.ai](https://fal.ai/models/fal-ai/flux/dev)\n\n## ComfyUI\n`FLUX.1 [dev]` is also available in [Comfy UI](https://github.com/comfyanonymous/ComfyUI) for local inference with a node-based workflow.\n\n---\n# Limitations\n- This model is not intended or able to provide factual information.\n- As a statistical model this checkpoint might amplify existing societal biases.\n- The model may fail to generate output that matches the prompts.\n- Prompt following is heavily influenced by the prompting-style.\n\n# Out-of-Scope Use\nThe model and its derivatives may not be used\n\n- In any way that violates any applicable national, federal, state, local or international law or regulation.\n- For the purpose of exploiting, harming or attempting to exploit or harm minors in any way; including but not limited to the solicitation, creation, acquisition, or dissemination of child exploitative content.\n- To generate or disseminate verifiably false information and/or content with the purpose of harming others.\n- To generate or disseminate personal identifiable information that can be used to harm an individual.\n- To harass, abuse, threaten, stalk, or bully individuals or groups of individuals.\n- To create non-consensual nudity or illegal pornographic content.\n- For fully automated decision making that adversely impacts an individual's legal rights or otherwise creates or modifies a binding, enforceable obligation.\n- Generating or facilitating large-scale disinformation campaigns.\n\n# License\nThis model falls under the [`FLUX.1 [dev]` Non-Commercial License](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md).\n"
  },
  {
    "path": "model_cards/FLUX.1-kontext-dev.md",
    "content": "![FLUX.1 [dev] Grid](../assets/docs/kontext.png)\n\n`FLUX.1 Kontext [dev]` is a 12 billion parameter rectified flow transformer capable of editing images based on text instructions.\nFor more information, please read our [blog post](https://bfl.ai/announcements/flux-1-kontext-dev) and our [technical report](https://arxiv.org/abs/2506.15742).\nYou can find information about the `[pro]` version in [here](https://bfl.ai/models/flux-kontext).\n\n# Key Features\n1. Change existing images based on an edit instruction.\n2. Have character, style and object reference without any finetuning.\n3. Robust consistency allows users to refine an image through multiple successive edits with minimal visual drift.\n4. Trained using guidance distillation, making `FLUX.1 Kontext [dev]` more efficient.\n5. Open weights to drive new scientific research, and empower artists to develop innovative workflows.\n6. Generated outputs can be used for personal, scientific, and commercial purposes, as described in the [FLUX.1 \\[dev\\] Non-Commercial License](https://github.com/black-forest-labs/flux/blob/main/model_licenses/LICENSE-FLUX1-dev).\n\n# Usage\nWe provide a reference implementation of `FLUX.1 Kontext [dev]`, as well as sampling code, in a dedicated [github repository](https://github.com/black-forest-labs/flux).\nDevelopers and creatives looking to build on top of `FLUX.1 Kontext [dev]` are encouraged to use this as a starting point.\n\n`FLUX.1 Kontext [dev]` is also available in both [ComfyUI](https://github.com/comfyanonymous/ComfyUI) and [Diffusers](https://github.com/huggingface/diffusers).\n\n## API Endpoints\nThe FLUX.1 Kontext models are also available via API from the following sources\n- bfl.ai: https://docs.bfl.ai/\n- DataCrunch: https://datacrunch.io/flux-kontext\n- fal: https://fal.ai/flux-kontext\n- Replicate: https://replicate.com/blog/flux-kontext\n    - https://replicate.com/black-forest-labs/flux-kontext-dev\n    - https://replicate.com/black-forest-labs/flux-kontext-pro\n    - https://replicate.com/black-forest-labs/flux-kontext-max\n- Runware: https://runware.ai/blog/introducing-flux1-kontext-instruction-based-image-editing-with-ai?utm_source=bfl\n- TogetherAI: https://www.together.ai/models/flux-1-kontext-dev\n\n---\n\n# Risks\n\nRisks\nBlack Forest Labs is committed to the responsible development of generative AI technology. Prior to releasing FLUX.1 Kontext, we evaluated and mitigated a number of risks in our models and services, including the generation of unlawful content. We implemented a series of pre-release mitigations to help prevent misuse by third parties, with additional post-release mitigations to help address residual risks:\n1. **Pre-training mitigation**. We filtered pre-training data for multiple categories of “not safe for work” (NSFW) content to help prevent a user generating unlawful content in response to text prompts or uploaded images.\n2. **Post-training mitigation.** We have partnered with the Internet Watch Foundation, an independent nonprofit organization dedicated to preventing online abuse, to filter known child sexual abuse material (CSAM) from post-training data. Subsequently, we undertook multiple rounds of targeted fine-tuning to provide additional mitigation against potential abuse. By inhibiting certain behaviors and concepts in the trained model, these techniques can help to prevent a user generating synthetic CSAM or nonconsensual intimate imagery (NCII) from a text prompt, or transforming an uploaded image into synthetic CSAM or NCII.\n3. **Pre-release evaluation.** Throughout this process, we conducted multiple internal and external third-party evaluations of model checkpoints to identify further opportunities for improvement. The third-party evaluations—which included 21 checkpoints of FLUX.1 Kontext [pro] and [dev]—focused on eliciting CSAM and NCII through adversarial testing with text-only prompts, as well as uploaded images with text prompts. Next, we conducted a final third-party evaluation of the proposed release checkpoints, focused on text-to-image and image-to-image CSAM and NCII generation. The final FLUX.1 Kontext [pro] (as offered through the FLUX API only) and FLUX.1 Kontext [dev] (released as an open-weight model) checkpoints demonstrated very high resilience against violative inputs, and FLUX.1 Kontext [dev] demonstrated higher resilience than other similar open-weight models across these risk categories.  Based on these findings, we approved the release of the FLUX.1 Kontext [pro] model via API, and the release of the FLUX.1 Kontext [dev] model as openly-available weights under a non-commercial license to support third-party research and development.\n4. **Inference filters.** We are applying multiple filters to intercept text prompts, uploaded images, and output images on the FLUX API for FLUX.1 Kontext [pro]. Filters for CSAM and NCII are provided by Hive, a third-party provider, and cannot be adjusted or removed by developers. We provide filters for other categories of potentially harmful content, including gore, which can be adjusted by developers based on their specific risk profile. Additionally, the repository for the open FLUX.1 Kontext [dev] model includes filters for illegal or infringing content. Filters or manual review must be used with the model under the terms of the FLUX.1 [dev] Non-Commercial License. We may approach known deployers of the FLUX.1 Kontext [dev] model at random to verify that filters or manual review processes are in place.\n5. **Content provenance.** The FLUX API applies cryptographically-signed metadata to output content to indicate that images were produced with our model. Our API implements the Coalition for Content Provenance and Authenticity (C2PA) standard for metadata.\n6. **Policies.** Access to our API and use of our models are governed by our Developer Terms of Service, Usage Policy, and FLUX.1 [dev] Non-Commercial License, which prohibit the generation of unlawful content or the use of generated content for unlawful, defamatory, or abusive purposes. Developers and users must consent to these conditions to access the FLUX Kontext models.\n7. **Monitoring.** We are monitoring for patterns of violative use after release, and may ban developers who we detect intentionally and repeatedly violate our policies via the FLUX API. Additionally, we provide a dedicated email address (safety@blackforestlabs.ai) to solicit feedback from the community. We maintain a reporting relationship with organizations such as the Internet Watch Foundation and the National Center for Missing and Exploited Children, and we welcome ongoing engagement with authorities, developers, and researchers to share intelligence about emerging risks and develop effective mitigations.\n\n\n# License\nThis model falls under the [FLUX.1 \\[dev\\] Non-Commercial License](https://github.com/black-forest-labs/flux/blob/main/model_licenses/LICENSE-FLUX1-dev).\n\n\n# Citation\n\n```bib\n@misc{labs2025flux1kontextflowmatching,\n      title={FLUX.1 Kontext: Flow Matching for In-Context Image Generation and Editing in Latent Space}, Add commentMore actions\n      author={Black Forest Labs and Stephen Batifol and Andreas Blattmann and Frederic Boesel and Saksham Consul and Cyril Diagne and Tim Dockhorn and Jack English and Zion English and Patrick Esser and Sumith Kulal and Kyle Lacey and Yam Levi and Cheng Li and Dominik Lorenz and Jonas Müller and Dustin Podell and Robin Rombach and Harry Saini and Axel Sauer and Luke Smith},\n      year={2025},\n      eprint={2506.15742},\n      archivePrefix={arXiv},\n      primaryClass={cs.GR},\n      url={https://arxiv.org/abs/2506.15742},\n}\n```\n"
  },
  {
    "path": "model_cards/FLUX.1-schnell.md",
    "content": "![FLUX.1 [schnell] Grid](../assets/schnell_grid.jpg)\n\n`FLUX.1 [schnell]` is a 12 billion parameter rectified flow transformer capable of generating images from text descriptions.\nFor more information, please read our [blog post](https://blackforestlabs.ai/announcing-black-forest-labs/).\n\n# Key Features\n1. Cutting-edge output quality and competitive prompt following, matching the performance of closed source alternatives.\n2. Trained using latent adversarial diffusion distillation, `FLUX.1 [schnell]` can generate high-quality images in only 1 to 4 steps.\n3. Released under the `apache-2.0` licence, the model can be used for personal, scientific, and commercial purposes.\n\n# Usage\nWe provide a reference implementation of `FLUX.1 [schnell]`, as well as sampling code, in a dedicated [github repository](https://github.com/black-forest-labs/flux).\nDevelopers and creatives looking to build on top of `FLUX.1 [schnell]` are encouraged to use this as a starting point.\n\n## API Endpoints\nThe FLUX.1 models are also available via API from the following sources\n1. [bfl.ml](https://docs.bfl.ml/) (currently `FLUX.1 [pro]`)\n2. [replicate.com](https://replicate.com/collections/flux)\n3. [fal.ai](https://fal.ai/models/fal-ai/flux/schnell)\n\n## ComfyUI\n`FLUX.1 [schnell]` is also available in [Comfy UI](https://github.com/comfyanonymous/ComfyUI) for local inference with a node-based workflow.\n\n---\n# Limitations\n- This model is not intended or able to provide factual information.\n- As a statistical model this checkpoint might amplify existing societal biases.\n- The model may fail to generate output that matches the prompts.\n- Prompt following is heavily influenced by the prompting-style.\n\n# Out-of-Scope Use\nThe model and its derivatives may not be used\n\n- In any way that violates any applicable national, federal, state, local or international law or regulation.\n- For the purpose of exploiting, harming or attempting to exploit or harm minors in any way; including but not limited to the solicitation, creation, acquisition, or dissemination of child exploitative content.\n- To generate or disseminate verifiably false information and/or content with the purpose of harming others.\n- To generate or disseminate personal identifiable information that can be used to harm an individual.\n- To harass, abuse, threaten, stalk, or bully individuals or groups of individuals.\n- To create non-consensual nudity or illegal pornographic content.\n- For fully automated decision making that adversely impacts an individual's legal rights or otherwise creates or modifies a binding, enforceable obligation.\n- Generating or facilitating large-scale disinformation campaigns.\n"
  },
  {
    "path": "model_licenses/LICENSE-FLUX1-dev",
    "content": "FLUX.1 [dev] Non-Commercial License v1.1.1\n\nBlack 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] AI models and models denoted as FLUX.1 [dev], including but not limited to FLUX.1 [dev], FLUX.1 Fill [dev], FLUX.1 Depth [dev], FLUX.1 Canny [dev], FLUX.1 Redux [dev], FLUX.1 Canny [dev] LoRA, FLUX.1 Depth [dev] LoRA, and FLUX.1 Kontext [dev], and their 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 models 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”). Note that we may also make available certain elements of what is included in the definition of “FLUX.1 [dev] Model” under a separate license, such as the inference code, and nothing in this License will be deemed to restrict or limit any other licenses granted by us in such elements.\n\nBy downloading, accessing, using, 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.\n\n1. Definitions.\n- a. “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.\n- b. “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.\n- c. “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 FLUX.1 [dev] Model, Derivatives, or FLUX Content Filters (as defined below): (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; and (iii) use by any charitable organization for charitable purposes, or for testing or evaluation. For clarity, use (a) for revenue-generating activity, (b) in direct interactions with or that has impact on end users, or (c) to train, fine tune or distill other models for commercial use, in each case is not a Non-Commercial Purpose.\n- d. “Outputs” means any content generated by the operation of the FLUX.1 [dev] Models or the Derivatives from an input (such as an image input) or prompt (i.e., text instructions) provided by users. For the avoidance of doubt, Outputs do not include any components of the FLUX.1 [dev] Models, such as any fine-tuned versions of the FLUX.1 [dev] Models, the weights, or parameters.\n- e.   “you” or “your” means the individual or entity entering into this License with Company.\n\n2. License Grant.\n- a. 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 and Derivatives 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 regarding the FLUX.1 [dev] Model also apply to any Derivative you create or that are created on your behalf.\n- b. Non-Commercial Use Only.  You may only access, use, Distribute, or create Derivatives of the FLUX.1 [dev] Model or Derivatives for Non-Commercial Purposes.  If you want to use a FLUX.1 [dev] Model or 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 see www.bfl.ai if you would like a commercial license.\n- c. 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.\n- d. 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 or the FLUX.1 Kontext [dev] Model.\n- e. You may access, use, Distribute, or create Output of the FLUX.1 [dev] Model or Derivatives if you: (i) (A) implement and maintain content filtering measures (“Content Filters”) for your use of the FLUX.1 [dev] Model or Derivatives to prevent the creation, display, transmission, generation, or dissemination of unlawful or infringing content, which may include Content Filters that we may make available for use with the FLUX.1 [dev] Model (“FLUX Content Filters”), or (B) ensure Output undergoes review for unlawful or infringing content before public or non-public distribution, display, transmission or dissemination; and (ii) ensure Output includes disclosure (or other indication) that the Output was generated or modified using artificial intelligence technologies to the extent required under applicable law.\n\n3. 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:\n- a. 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;\n- b. you must 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”):\n\n    “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.\n    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.”\n\n- c. in the case of Distribution of Derivatives made by you: (i) you must also include in the Attribution Notice a statement that you have modified the applicable FLUX.1 [dev] Model; (ii) 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 and must include disclaimer of warranties and limitation of liability provisions that are at least as protective of Company as those set forth herein; and (iii) 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.\n\n4. Restrictions.  You will not, and will not permit, assist or cause any third party to\n- a. 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, (i) for 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 (or is likely to infringe, misappropriate, or otherwise violate) any third party’s legal rights, including rights of publicity or “digital replica” rights, (vi) in any unlawful, fraudulent, defamatory, or abusive activity, (vii) to generate unlawful content, including child sexual abuse material, or non-consensual intimate images;  or (viii) 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, any and all laws governing the processing of biometric information, and the EU Artificial Intelligence Act (Regulation (EU) 2024/1689), as well as all amendments and successor laws to any of the foregoing;\n- b. alter or remove copyright and other proprietary notices which appear on or in any portion of the FLUX.1 [dev] Model;\n- c. 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;\n- d. offer or impose any terms on the FLUX.1 [dev] Model that alter, restrict, or are inconsistent with the terms of this License;\n- e. 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;\n- f. directly or indirectly Distribute, export, or otherwise transfer FLUX.1 [dev] Model  (i) to any individual, entity, or country prohibited by Export Laws; (ii) to anyone on U.S. or non-U.S. government restricted parties lists; (iii) for any purpose prohibited by Export Laws, including nuclear, chemical or biological weapons, or missile technology applications; (iv) 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 (v) will not disguise your location through IP proxying or other methods.\n\n5. DISCLAIMERS.  THE FLUX.1 [dev] MODEL AND FLUX CONTENT FILTERS ARE 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 AND FLUX CONTENT FILTERS, 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 AND FLUX CONTENT FILTERS WILL BE ERROR FREE OR FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS, OR PRODUCE ANY PARTICULAR RESULTS.\n\n6. 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, FLUX CONTENT FILTERS, 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.\n\n7. 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 (including in connection with any Output, results or data generated from such access or use, or from your access or use of any FLUX Content Filters), including any High-Risk Use; (b) your Content Filters, including your failure to implement any Content Filters where required by this License such as in Section 2(e); (c)  your violation of this License; or (d) 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.\n\n8. Termination; Survival.\n- a. This License will automatically terminate upon any breach by you of the terms of this License.\n- b. We may terminate this License, in whole or in part, at any time upon notice (including electronic) to you.\n- c. 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, any Derivative, or FLUX Content Filters, 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.\n- d. Upon termination of this License, you must cease all use, access or Distribution of the FLUX.1 [dev] Model, any Derivatives, and any FLUX Content Filters.  The following sections survive termination of this License  2(c), 2(d), 4-11.\n\n9. 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.\n\n10. Trademarks. You have not been granted any trademark license as part of this License and may not use any name, logo or trademark 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.\n\n11. 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.\n"
  },
  {
    "path": "model_licenses/LICENSE-FLUX1-schnell",
    "content": "\n\nApache License\nVersion 2.0, January 2004\nhttp://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n\"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.\n\n\"Licensor\" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.\n\n\"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.\n\n\"You\" (or \"Your\") shall mean an individual or Legal Entity exercising permissions granted by this License.\n\n\"Source\" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.\n\n\"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.\n\n\"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).\n\n\"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.\n\n\"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.\"\n\n\"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.\n\n2. 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.\n\n3. 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.\n\n4. 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:\n\n    You must give any other recipients of the Work or Derivative Works a copy of this License; and\n    You must cause any modified files to carry prominent notices stating that You changed the files; and\n    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\n    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.\n\nYou 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.\n\n5. 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.\n\n6. 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.\n\n7. 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.\n\n8. 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.\n\n9. 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.\n\nEND OF TERMS AND CONDITIONS\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[project]\nname = \"flux\"\nauthors = [\n  { name = \"Black Forest Labs\", email = \"support@blackforestlabs.ai\" },\n]\ndescription = \"Inference codebase for FLUX\"\nreadme = \"README.md\"\nrequires-python = \">=3.10\"\nlicense = { file = \"LICENSE.md\" }\ndynamic = [\"version\"]\ndependencies = [\n  \"accelerate\",\n  \"einops\",\n  \"fire >= 0.6.0\",\n  \"huggingface-hub\",\n  \"safetensors\",\n  \"sentencepiece\",\n  \"transformers >= 4.45.2\",\n  \"tokenizers\",\n  \"protobuf\",\n  \"requests\",\n  \"invisible-watermark\",\n  \"ruff == 0.6.8\",\n  \"accelerate\",\n]\n\n[project.optional-dependencies]\ntorch = [\n  \"torch == 2.6.0\",\n  \"torchvision\",\n]\nstreamlit = [\n  \"streamlit\",\n  \"streamlit-drawable-canvas\",\n  \"streamlit-keyup\",\n]\ngradio = [\n  \"gradio\",\n]\ntensorrt = [\n  \"tensorrt-cu12 == 10.12.0.36\",\n  \"colored\",\n  \"opencv-python-headless==4.8.0.74\",\n  \"onnx >=1.18.0\",\n  \"onnxruntime ~= 1.22.0\",\n  \"onnxruntime-gpu ~= 1.22.0\",\n  \"onnx-graphsurgeon\",\n  \"polygraphy >= 0.49.22\",\n]\nall = [\n  \"flux[gradio]\",\n  \"flux[streamlit]\",\n  \"flux[torch]\",\n]\n\n[project.scripts]\nflux = \"flux.cli:app\"\n\n[build-system]\nbuild-backend = \"setuptools.build_meta\"\nrequires = [\"setuptools>=64\", \"wheel\", \"setuptools_scm>=8\"]\n\n[tool.ruff]\nline-length = 110\ntarget-version = \"py310\"\nextend-exclude = [\"/usr/lib/*\"]\n\n[tool.ruff.lint]\nignore = [\n  \"E501\", # line too long - will be fixed in format\n]\n\n[tool.ruff.format]\nquote-style = \"double\"\nindent-style = \"space\"\nline-ending = \"auto\"\nskip-magic-trailing-comma = false\ndocstring-code-format = true\nexclude = [\n  \"src/flux/_version.py\", # generated by setuptools_scm\n]\n\n[tool.ruff.lint.isort]\ncombine-as-imports = true\nforce-wrap-aliases = true\nknown-local-folder = [\"src\"]\nknown-first-party = [\"flux\"]\n\n[tool.pyright]\ninclude = [\"src\"]\nexclude = [\n  \"**/__pycache__\", # cache directories\n  \"./typings\",      # generated type stubs\n]\nstubPath = \"./typings\"\n\n[tool.tomlsort]\nin_place = true\nno_sort_tables = true\nspaces_before_inline_comment = 1\nspaces_indent_inline_array = 2\ntrailing_comma_inline_array = true\nsort_first = [\n  \"project\",\n  \"build-system\",\n  \"tool.setuptools\",\n]\n\n# needs to be last for CI reasons\n[tool.setuptools_scm]\nwrite_to = \"src/flux/_version.py\"\nparentdir_prefix_version = \"flux-\"\nfallback_version = \"0.0.0\"\nversion_scheme = \"post-release\"\n"
  },
  {
    "path": "setup.py",
    "content": "import setuptools\n\nsetuptools.setup()\n"
  },
  {
    "path": "src/flux/__init__.py",
    "content": "try:\n    from ._version import (\n        version as __version__,  # type: ignore\n        version_tuple,\n    )\nexcept ImportError:\n    __version__ = \"unknown (no version information available)\"\n    version_tuple = (0, 0, \"unknown\", \"noinfo\")\n\nfrom pathlib import Path\n\nPACKAGE = __package__.replace(\"_\", \"-\")\nPACKAGE_ROOT = Path(__file__).parent\n"
  },
  {
    "path": "src/flux/__main__.py",
    "content": "from fire import Fire\n\nfrom .cli import main as cli_main\nfrom .cli_control import main as control_main\nfrom .cli_fill import main as fill_main\nfrom .cli_kontext import main as kontext_main\nfrom .cli_redux import main as redux_main\n\nif __name__ == \"__main__\":\n    Fire(\n        {\n            \"t2i\": cli_main,\n            \"control\": control_main,\n            \"fill\": fill_main,\n            \"kontext\": kontext_main,\n            \"redux\": redux_main,\n        }\n    )\n"
  },
  {
    "path": "src/flux/cli.py",
    "content": "import os\nimport re\nimport time\nfrom dataclasses import dataclass\nfrom glob import iglob\n\nimport torch\nfrom fire import Fire\nfrom transformers import pipeline\n\nfrom flux.sampling import denoise, get_noise, get_schedule, prepare, unpack\nfrom flux.util import (\n    check_onnx_access_for_trt,\n    configs,\n    load_ae,\n    load_clip,\n    load_flow_model,\n    load_t5,\n    save_image,\n)\n\nNSFW_THRESHOLD = 0.85\n\n\n@dataclass\nclass SamplingOptions:\n    prompt: str\n    width: int\n    height: int\n    num_steps: int\n    guidance: float\n    seed: int | None\n\n\ndef parse_prompt(options: SamplingOptions) -> SamplingOptions | None:\n    user_question = \"Next prompt (write /h for help, /q to quit and leave empty to repeat):\\n\"\n    usage = (\n        \"Usage: Either write your prompt directly, leave this field empty \"\n        \"to repeat the prompt or write a command starting with a slash:\\n\"\n        \"- '/w <width>' will set the width of the generated image\\n\"\n        \"- '/h <height>' will set the height of the generated image\\n\"\n        \"- '/s <seed>' sets the next seed\\n\"\n        \"- '/g <guidance>' sets the guidance (flux-dev only)\\n\"\n        \"- '/n <steps>' sets the number of steps\\n\"\n        \"- '/q' to quit\"\n    )\n\n    while (prompt := input(user_question)).startswith(\"/\"):\n        if prompt.startswith(\"/w\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, width = prompt.split()\n            options.width = 16 * (int(width) // 16)\n            print(\n                f\"Setting resolution to {options.width} x {options.height} \"\n                f\"({options.height * options.width / 1e6:.2f}MP)\"\n            )\n        elif prompt.startswith(\"/h\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, height = prompt.split()\n            options.height = 16 * (int(height) // 16)\n            print(\n                f\"Setting resolution to {options.width} x {options.height} \"\n                f\"({options.height * options.width / 1e6:.2f}MP)\"\n            )\n        elif prompt.startswith(\"/g\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, guidance = prompt.split()\n            options.guidance = float(guidance)\n            print(f\"Setting guidance to {options.guidance}\")\n        elif prompt.startswith(\"/s\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, seed = prompt.split()\n            options.seed = int(seed)\n            print(f\"Setting seed to {options.seed}\")\n        elif prompt.startswith(\"/n\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, steps = prompt.split()\n            options.num_steps = int(steps)\n            print(f\"Setting number of steps to {options.num_steps}\")\n        elif prompt.startswith(\"/q\"):\n            print(\"Quitting\")\n            return None\n        else:\n            if not prompt.startswith(\"/h\"):\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n            print(usage)\n    if prompt != \"\":\n        options.prompt = prompt\n    return options\n\n\n@torch.inference_mode()\ndef main(\n    name: str = \"flux-dev-krea\",\n    width: int = 1360,\n    height: int = 768,\n    seed: int | None = None,\n    prompt: str = (\n        \"a photo of a forest with mist swirling around the tree trunks. The word \"\n        '\"FLUX\" is painted over it in big, red brush strokes with visible texture'\n    ),\n    device: str = \"cuda\" if torch.cuda.is_available() else \"cpu\",\n    num_steps: int | None = None,\n    loop: bool = False,\n    guidance: float = 2.5,\n    offload: bool = False,\n    output_dir: str = \"output\",\n    add_sampling_metadata: bool = True,\n    trt: bool = False,\n    trt_transformer_precision: str = \"bf16\",\n    track_usage: bool = False,\n):\n    \"\"\"\n    Sample the flux model. Either interactively (set `--loop`) or run for a\n    single image.\n\n    Args:\n        name: Name of the model to load\n        height: height of the sample in pixels (should be a multiple of 16)\n        width: width of the sample in pixels (should be a multiple of 16)\n        seed: Set a seed for sampling\n        output_name: where to save the output image, `{idx}` will be replaced\n            by the index of the sample\n        prompt: Prompt used for sampling\n        device: Pytorch device\n        num_steps: number of sampling steps (default 4 for schnell, 50 for guidance distilled)\n        loop: start an interactive session and sample multiple times\n        guidance: guidance value used for guidance distillation\n        add_sampling_metadata: Add the prompt to the image Exif metadata\n        trt: use TensorRT backend for optimized inference\n        trt_transformer_precision: specify transformer precision for inference\n        track_usage: track usage of the model for licensing purposes\n    \"\"\"\n\n    prompt = prompt.split(\"|\")\n    if len(prompt) == 1:\n        prompt = prompt[0]\n        additional_prompts = None\n    else:\n        additional_prompts = prompt[1:]\n        prompt = prompt[0]\n\n    assert not (\n        (additional_prompts is not None) and loop\n    ), \"Do not provide additional prompts and set loop to True\"\n\n    nsfw_classifier = pipeline(\"image-classification\", model=\"Falconsai/nsfw_image_detection\", device=device)\n\n    if name not in configs:\n        available = \", \".join(configs.keys())\n        raise ValueError(f\"Got unknown model name: {name}, chose from {available}\")\n\n    torch_device = torch.device(device)\n    if num_steps is None:\n        num_steps = 4 if name == \"flux-schnell\" else 50\n\n    # allow for packing and conversion to latent space\n    height = 16 * (height // 16)\n    width = 16 * (width // 16)\n\n    output_name = os.path.join(output_dir, \"img_{idx}.jpg\")\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n        idx = 0\n    else:\n        fns = [fn for fn in iglob(output_name.format(idx=\"*\")) if re.search(r\"img_[0-9]+\\.jpg$\", fn)]\n        if len(fns) > 0:\n            idx = max(int(fn.split(\"_\")[-1].split(\".\")[0]) for fn in fns) + 1\n        else:\n            idx = 0\n\n    if not trt:\n        t5 = load_t5(torch_device, max_length=256 if name == \"flux-schnell\" else 512)\n        clip = load_clip(torch_device)\n        model = load_flow_model(name, device=\"cpu\" if offload else torch_device)\n        ae = load_ae(name, device=\"cpu\" if offload else torch_device)\n    else:\n        # lazy import to make install optional\n        from flux.trt.trt_manager import ModuleName, TRTManager\n\n        # Check if we need ONNX model access (which requires authentication for FLUX models)\n        onnx_dir = check_onnx_access_for_trt(name, trt_transformer_precision)\n\n        trt_ctx_manager = TRTManager(\n            trt_transformer_precision=trt_transformer_precision,\n            trt_t5_precision=os.getenv(\"TRT_T5_PRECISION\", \"bf16\"),\n        )\n        engines = trt_ctx_manager.load_engines(\n            model_name=name,\n            module_names={\n                ModuleName.CLIP,\n                ModuleName.TRANSFORMER,\n                ModuleName.T5,\n                ModuleName.VAE,\n            },\n            engine_dir=os.environ.get(\"TRT_ENGINE_DIR\", \"./engines\"),\n            custom_onnx_paths=onnx_dir or os.environ.get(\"CUSTOM_ONNX_PATHS\", \"\"),\n            trt_image_height=height,\n            trt_image_width=width,\n            trt_batch_size=1,\n            trt_timing_cache=os.getenv(\"TRT_TIMING_CACHE_FILE\", None),\n            trt_static_batch=False,\n            trt_static_shape=False,\n        )\n\n        ae = engines[ModuleName.VAE].to(device=\"cpu\" if offload else torch_device)\n        model = engines[ModuleName.TRANSFORMER].to(device=\"cpu\" if offload else torch_device)\n        clip = engines[ModuleName.CLIP].to(torch_device)\n        t5 = engines[ModuleName.T5].to(device=\"cpu\" if offload else torch_device)\n\n    rng = torch.Generator(device=\"cpu\")\n    opts = SamplingOptions(\n        prompt=prompt,\n        width=width,\n        height=height,\n        num_steps=num_steps,\n        guidance=guidance,\n        seed=seed,\n    )\n\n    if loop:\n        opts = parse_prompt(opts)\n\n    while opts is not None:\n        if opts.seed is None:\n            opts.seed = rng.seed()\n        print(f\"Generating with seed {opts.seed}:\\n{opts.prompt}\")\n        t0 = time.perf_counter()\n\n        # prepare input\n        x = get_noise(\n            1,\n            opts.height,\n            opts.width,\n            device=torch_device,\n            dtype=torch.bfloat16,\n            seed=opts.seed,\n        )\n        opts.seed = None\n        if offload:\n            ae = ae.cpu()\n            torch.cuda.empty_cache()\n            t5, clip = t5.to(torch_device), clip.to(torch_device)\n        inp = prepare(t5, clip, x, prompt=opts.prompt)\n        timesteps = get_schedule(opts.num_steps, inp[\"img\"].shape[1], shift=(name != \"flux-schnell\"))\n\n        # offload TEs to CPU, load model to gpu\n        if offload:\n            t5, clip = t5.cpu(), clip.cpu()\n            torch.cuda.empty_cache()\n            model = model.to(torch_device)\n\n        # denoise initial noise\n        x = denoise(model, **inp, timesteps=timesteps, guidance=opts.guidance)\n\n        # offload model, load autoencoder to gpu\n        if offload:\n            model.cpu()\n            torch.cuda.empty_cache()\n            ae.decoder.to(x.device)\n\n        # decode latents to pixel space\n        x = unpack(x.float(), opts.height, opts.width)\n        with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):\n            x = ae.decode(x)\n\n        if torch.cuda.is_available():\n            torch.cuda.synchronize()\n        t1 = time.perf_counter()\n\n        fn = output_name.format(idx=idx)\n        print(f\"Done in {t1 - t0:.1f}s. Saving {fn}\")\n\n        idx = save_image(\n            nsfw_classifier, name, output_name, idx, x, add_sampling_metadata, prompt, track_usage=track_usage\n        )\n\n        if loop:\n            print(\"-\" * 80)\n            opts = parse_prompt(opts)\n        elif additional_prompts:\n            next_prompt = additional_prompts.pop(0)\n            opts.prompt = next_prompt\n        else:\n            opts = None\n\n    if trt:\n        trt_ctx_manager.stop_runtime()\n\n\nif __name__ == \"__main__\":\n    Fire(main)\n"
  },
  {
    "path": "src/flux/cli_control.py",
    "content": "import os\nimport re\nimport time\nfrom dataclasses import dataclass\nfrom glob import iglob\n\nimport torch\nfrom fire import Fire\nfrom transformers import pipeline\n\nfrom flux.modules.image_embedders import CannyImageEncoder, DepthImageEncoder\nfrom flux.sampling import denoise, get_noise, get_schedule, prepare_control, unpack\nfrom flux.util import configs, load_ae, load_clip, load_flow_model, load_t5, save_image\n\n\n@dataclass\nclass SamplingOptions:\n    prompt: str\n    width: int\n    height: int\n    num_steps: int\n    guidance: float\n    seed: int | None\n    img_cond_path: str\n    lora_scale: float | None\n\n\ndef parse_prompt(options: SamplingOptions) -> SamplingOptions | None:\n    user_question = \"Next prompt (write /h for help, /q to quit and leave empty to repeat):\\n\"\n    usage = (\n        \"Usage: Either write your prompt directly, leave this field empty \"\n        \"to repeat the prompt or write a command starting with a slash:\\n\"\n        \"- '/w <width>' will set the width of the generated image\\n\"\n        \"- '/h <height>' will set the height of the generated image\\n\"\n        \"- '/s <seed>' sets the next seed\\n\"\n        \"- '/g <guidance>' sets the guidance (flux-dev only)\\n\"\n        \"- '/n <steps>' sets the number of steps\\n\"\n        \"- '/q' to quit\"\n    )\n\n    while (prompt := input(user_question)).startswith(\"/\"):\n        if prompt.startswith(\"/w\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, width = prompt.split()\n            options.width = 16 * (int(width) // 16)\n            print(\n                f\"Setting resolution to {options.width} x {options.height} \"\n                f\"({options.height * options.width / 1e6:.2f}MP)\"\n            )\n        elif prompt.startswith(\"/h\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, height = prompt.split()\n            options.height = 16 * (int(height) // 16)\n            print(\n                f\"Setting resolution to {options.width} x {options.height} \"\n                f\"({options.height * options.width / 1e6:.2f}MP)\"\n            )\n        elif prompt.startswith(\"/g\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, guidance = prompt.split()\n            options.guidance = float(guidance)\n            print(f\"Setting guidance to {options.guidance}\")\n        elif prompt.startswith(\"/s\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, seed = prompt.split()\n            options.seed = int(seed)\n            print(f\"Setting seed to {options.seed}\")\n        elif prompt.startswith(\"/n\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, steps = prompt.split()\n            options.num_steps = int(steps)\n            print(f\"Setting number of steps to {options.num_steps}\")\n        elif prompt.startswith(\"/q\"):\n            print(\"Quitting\")\n            return None\n        else:\n            if not prompt.startswith(\"/h\"):\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n            print(usage)\n    if prompt != \"\":\n        options.prompt = prompt\n    return options\n\n\ndef parse_img_cond_path(options: SamplingOptions | None) -> SamplingOptions | None:\n    if options is None:\n        return None\n\n    user_question = \"Next conditioning image (write /h for help, /q to quit and leave empty to repeat):\\n\"\n    usage = (\n        \"Usage: Either write your prompt directly, leave this field empty \"\n        \"to repeat the conditioning image or write a command starting with a slash:\\n\"\n        \"- '/q' to quit\"\n    )\n\n    while True:\n        img_cond_path = input(user_question)\n\n        if img_cond_path.startswith(\"/\"):\n            if img_cond_path.startswith(\"/q\"):\n                print(\"Quitting\")\n                return None\n            else:\n                if not img_cond_path.startswith(\"/h\"):\n                    print(f\"Got invalid command '{img_cond_path}'\\n{usage}\")\n                print(usage)\n            continue\n\n        if img_cond_path == \"\":\n            break\n\n        if not os.path.isfile(img_cond_path) or not img_cond_path.lower().endswith(\n            (\".jpg\", \".jpeg\", \".png\", \".webp\")\n        ):\n            print(f\"File '{img_cond_path}' does not exist or is not a valid image file\")\n            continue\n\n        options.img_cond_path = img_cond_path\n        break\n\n    return options\n\n\ndef parse_lora_scale(options: SamplingOptions | None) -> tuple[SamplingOptions | None, bool]:\n    changed = False\n\n    if options is None:\n        return None, changed\n\n    user_question = \"Next lora scale (write /h for help, /q to quit and leave empty to repeat):\\n\"\n    usage = (\n        \"Usage: Either write your prompt directly, leave this field empty \"\n        \"to repeat the lora scale or write a command starting with a slash:\\n\"\n        \"- '/q' to quit\"\n    )\n\n    while (prompt := input(user_question)).startswith(\"/\"):\n        if prompt.startswith(\"/q\"):\n            print(\"Quitting\")\n            return None, changed\n        else:\n            if not prompt.startswith(\"/h\"):\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n            print(usage)\n    if prompt != \"\":\n        options.lora_scale = float(prompt)\n        changed = True\n    return options, changed\n\n\n@torch.inference_mode()\ndef main(\n    name: str,\n    width: int = 1024,\n    height: int = 1024,\n    seed: int | None = None,\n    prompt: str = \"a robot made out of gold\",\n    device: str = \"cuda\" if torch.cuda.is_available() else \"cpu\",\n    num_steps: int = 50,\n    loop: bool = False,\n    guidance: float | None = None,\n    offload: bool = False,\n    output_dir: str = \"output\",\n    add_sampling_metadata: bool = True,\n    img_cond_path: str = \"assets/robot.webp\",\n    lora_scale: float | None = 0.85,\n    trt: bool = False,\n    trt_transformer_precision: str = \"bf16\",\n    track_usage: bool = False,\n    **kwargs: dict | None,\n):\n    \"\"\"\n    Sample the flux model. Either interactively (set `--loop`) or run for a\n    single image.\n\n    Args:\n        height: height of the sample in pixels (should be a multiple of 16)\n        width: width of the sample in pixels (should be a multiple of 16)\n        seed: Set a seed for sampling\n        output_name: where to save the output image, `{idx}` will be replaced\n            by the index of the sample\n        prompt: Prompt used for sampling\n        device: Pytorch device\n        num_steps: number of sampling steps (default 4 for schnell, 50 for guidance distilled)\n        loop: start an interactive session and sample multiple times\n        guidance: guidance value used for guidance distillation\n        add_sampling_metadata: Add the prompt to the image Exif metadata\n        img_cond_path: path to conditioning image (jpeg/png/webp)\n        trt: use TensorRT backend for optimized inference\n        trt_transformer_precision: specify transformer precision for inference\n        track_usage: track usage of the model for licensing purposes\n    \"\"\"\n    nsfw_classifier = pipeline(\"image-classification\", model=\"Falconsai/nsfw_image_detection\", device=device)\n\n    if \"lora\" in name:\n        assert not trt, \"TRT does not support LORA\"\n    assert name in [\n        \"flux-dev-canny\",\n        \"flux-dev-depth\",\n        \"flux-dev-canny-lora\",\n        \"flux-dev-depth-lora\",\n    ], f\"Got unknown model name: {name}\"\n\n    if guidance is None:\n        if name in [\"flux-dev-canny\", \"flux-dev-canny-lora\"]:\n            guidance = 30.0\n        elif name in [\"flux-dev-depth\", \"flux-dev-depth-lora\"]:\n            guidance = 10.0\n        else:\n            raise NotImplementedError()\n\n    if name not in configs:\n        available = \", \".join(configs.keys())\n        raise ValueError(f\"Got unknown model name: {name}, chose from {available}\")\n\n    torch_device = torch.device(device)\n\n    output_name = os.path.join(output_dir, \"img_{idx}.jpg\")\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n        idx = 0\n    else:\n        fns = [fn for fn in iglob(output_name.format(idx=\"*\")) if re.search(r\"img_[0-9]+\\.jpg$\", fn)]\n        if len(fns) > 0:\n            idx = max(int(fn.split(\"_\")[-1].split(\".\")[0]) for fn in fns) + 1\n        else:\n            idx = 0\n\n    if name in [\"flux-dev-depth\", \"flux-dev-depth-lora\"]:\n        img_embedder = DepthImageEncoder(torch_device)\n    elif name in [\"flux-dev-canny\", \"flux-dev-canny-lora\"]:\n        img_embedder = CannyImageEncoder(torch_device)\n    else:\n        raise NotImplementedError()\n\n    if not trt:\n        # init all components\n        t5 = load_t5(torch_device, max_length=512)\n        clip = load_clip(torch_device)\n        model = load_flow_model(name, device=\"cpu\" if offload else torch_device)\n        ae = load_ae(name, device=\"cpu\" if offload else torch_device)\n    else:\n        # lazy import to make install optional\n        from flux.trt.trt_manager import ModuleName, TRTManager\n\n        trt_ctx_manager = TRTManager(\n            trt_transformer_precision=trt_transformer_precision,\n            trt_t5_precision=os.environ.get(\"TRT_T5_PRECISION\", \"bf16\"),\n        )\n\n        engines = trt_ctx_manager.load_engines(\n            model_name=name,\n            module_names={\n                ModuleName.CLIP,\n                ModuleName.TRANSFORMER,\n                ModuleName.T5,\n                ModuleName.VAE,\n                ModuleName.VAE_ENCODER,\n            },\n            engine_dir=os.environ.get(\"TRT_ENGINE_DIR\", \"./engines\"),\n            custom_onnx_paths=os.environ.get(\"CUSTOM_ONNX_PATHS\", \"\"),\n            trt_image_height=height,\n            trt_image_width=width,\n            trt_batch_size=1,\n            trt_static_batch=kwargs.get(\"static_batch\", True),\n            trt_static_shape=kwargs.get(\"static_shape\", True),\n        )\n\n        ae = engines[ModuleName.VAE].to(device=\"cpu\" if offload else torch_device)\n        model = engines[ModuleName.TRANSFORMER].to(device=\"cpu\" if offload else torch_device)\n        clip = engines[ModuleName.CLIP].to(torch_device)\n        t5 = engines[ModuleName.T5].to(device=\"cpu\" if offload else torch_device)\n\n    # set lora scale\n    if \"lora\" in name and lora_scale is not None:\n        for _, module in model.named_modules():\n            if hasattr(module, \"set_scale\"):\n                module.set_scale(lora_scale)\n\n    rng = torch.Generator(device=\"cpu\")\n    opts = SamplingOptions(\n        prompt=prompt,\n        width=width,\n        height=height,\n        num_steps=num_steps,\n        guidance=guidance,\n        seed=seed,\n        img_cond_path=img_cond_path,\n        lora_scale=lora_scale,\n    )\n\n    if loop:\n        opts = parse_prompt(opts)\n        opts = parse_img_cond_path(opts)\n        if \"lora\" in name:\n            opts, changed = parse_lora_scale(opts)\n            if changed:\n                # update the lora scale:\n                for _, module in model.named_modules():\n                    if hasattr(module, \"set_scale\"):\n                        module.set_scale(opts.lora_scale)\n\n    while opts is not None:\n        if opts.seed is None:\n            opts.seed = rng.seed()\n        print(f\"Generating with seed {opts.seed}:\\n{opts.prompt}\")\n        t0 = time.perf_counter()\n\n        # prepare input\n        x = get_noise(\n            1,\n            opts.height,\n            opts.width,\n            device=torch_device,\n            dtype=torch.bfloat16,\n            seed=opts.seed,\n        )\n        opts.seed = None\n        if offload:\n            t5, clip, ae = t5.to(torch_device), clip.to(torch_device), ae.to(torch_device)\n        inp = prepare_control(\n            t5,\n            clip,\n            x,\n            prompt=opts.prompt,\n            ae=ae,\n            encoder=img_embedder,\n            img_cond_path=opts.img_cond_path,\n        )\n        timesteps = get_schedule(opts.num_steps, inp[\"img\"].shape[1], shift=(name != \"flux-schnell\"))\n\n        # offload TEs and AE to CPU, load model to gpu\n        if offload:\n            t5, clip, ae = t5.cpu(), clip.cpu(), ae.cpu()\n            torch.cuda.empty_cache()\n            model = model.to(torch_device)\n\n        # denoise initial noise\n        x = denoise(model, **inp, timesteps=timesteps, guidance=opts.guidance)\n\n        # offload model, load autoencoder to gpu\n        if offload:\n            model.cpu()\n            torch.cuda.empty_cache()\n            ae.decoder.to(x.device)\n\n        # decode latents to pixel space\n        x = unpack(x.float(), opts.height, opts.width)\n        with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):\n            x = ae.decode(x)\n\n        if torch.cuda.is_available():\n            torch.cuda.synchronize()\n        t1 = time.perf_counter()\n        print(f\"Done in {t1 - t0:.1f}s\")\n\n        idx = save_image(\n            nsfw_classifier, name, output_name, idx, x, add_sampling_metadata, prompt, track_usage=track_usage\n        )\n\n        if loop:\n            print(\"-\" * 80)\n            opts = parse_prompt(opts)\n            opts = parse_img_cond_path(opts)\n            if \"lora\" in name:\n                opts, changed = parse_lora_scale(opts)\n                if changed:\n                    # update the lora scale:\n                    for _, module in model.named_modules():\n                        if hasattr(module, \"set_scale\"):\n                            module.set_scale(opts.lora_scale)\n        else:\n            opts = None\n\n    if trt:\n        trt_ctx_manager.stop_runtime()\n\n\nif __name__ == \"__main__\":\n    Fire(main)\n"
  },
  {
    "path": "src/flux/cli_fill.py",
    "content": "import os\nimport re\nimport time\nfrom dataclasses import dataclass\nfrom glob import iglob\n\nimport torch\nfrom fire import Fire\nfrom PIL import Image\nfrom transformers import pipeline\n\nfrom flux.sampling import denoise, get_noise, get_schedule, prepare_fill, unpack\nfrom flux.util import configs, load_ae, load_clip, load_flow_model, load_t5, save_image\n\n\n@dataclass\nclass SamplingOptions:\n    prompt: str\n    width: int\n    height: int\n    num_steps: int\n    guidance: float\n    seed: int | None\n    img_cond_path: str\n    img_mask_path: str\n\n\ndef parse_prompt(options: SamplingOptions) -> SamplingOptions | None:\n    user_question = \"Next prompt (write /h for help, /q to quit and leave empty to repeat):\\n\"\n    usage = (\n        \"Usage: Either write your prompt directly, leave this field empty \"\n        \"to repeat the prompt or write a command starting with a slash:\\n\"\n        \"- '/s <seed>' sets the next seed\\n\"\n        \"- '/g <guidance>' sets the guidance (flux-dev only)\\n\"\n        \"- '/n <steps>' sets the number of steps\\n\"\n        \"- '/q' to quit\"\n    )\n\n    while (prompt := input(user_question)).startswith(\"/\"):\n        if prompt.startswith(\"/g\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, guidance = prompt.split()\n            options.guidance = float(guidance)\n            print(f\"Setting guidance to {options.guidance}\")\n        elif prompt.startswith(\"/s\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, seed = prompt.split()\n            options.seed = int(seed)\n            print(f\"Setting seed to {options.seed}\")\n        elif prompt.startswith(\"/n\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, steps = prompt.split()\n            options.num_steps = int(steps)\n            print(f\"Setting number of steps to {options.num_steps}\")\n        elif prompt.startswith(\"/q\"):\n            print(\"Quitting\")\n            return None\n        else:\n            if not prompt.startswith(\"/h\"):\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n            print(usage)\n    if prompt != \"\":\n        options.prompt = prompt\n    return options\n\n\ndef parse_img_cond_path(options: SamplingOptions | None) -> SamplingOptions | None:\n    if options is None:\n        return None\n\n    user_question = \"Next conditioning image (write /h for help, /q to quit and leave empty to repeat):\\n\"\n    usage = (\n        \"Usage: Either write your prompt directly, leave this field empty \"\n        \"to repeat the conditioning image or write a command starting with a slash:\\n\"\n        \"- '/q' to quit\"\n    )\n\n    while True:\n        img_cond_path = input(user_question)\n\n        if img_cond_path.startswith(\"/\"):\n            if img_cond_path.startswith(\"/q\"):\n                print(\"Quitting\")\n                return None\n            else:\n                if not img_cond_path.startswith(\"/h\"):\n                    print(f\"Got invalid command '{img_cond_path}'\\n{usage}\")\n                print(usage)\n            continue\n\n        if img_cond_path == \"\":\n            break\n\n        if not os.path.isfile(img_cond_path) or not img_cond_path.lower().endswith(\n            (\".jpg\", \".jpeg\", \".png\", \".webp\")\n        ):\n            print(f\"File '{img_cond_path}' does not exist or is not a valid image file\")\n            continue\n        else:\n            with Image.open(img_cond_path) as img:\n                width, height = img.size\n\n            if width % 32 != 0 or height % 32 != 0:\n                print(f\"Image dimensions must be divisible by 32, got {width}x{height}\")\n                continue\n\n        options.img_cond_path = img_cond_path\n        break\n\n    return options\n\n\ndef parse_img_mask_path(options: SamplingOptions | None) -> SamplingOptions | None:\n    if options is None:\n        return None\n\n    user_question = \"Next conditioning mask (write /h for help, /q to quit and leave empty to repeat):\\n\"\n    usage = (\n        \"Usage: Either write your prompt directly, leave this field empty \"\n        \"to repeat the conditioning mask or write a command starting with a slash:\\n\"\n        \"- '/q' to quit\"\n    )\n\n    while True:\n        img_mask_path = input(user_question)\n\n        if img_mask_path.startswith(\"/\"):\n            if img_mask_path.startswith(\"/q\"):\n                print(\"Quitting\")\n                return None\n            else:\n                if not img_mask_path.startswith(\"/h\"):\n                    print(f\"Got invalid command '{img_mask_path}'\\n{usage}\")\n                print(usage)\n            continue\n\n        if img_mask_path == \"\":\n            break\n\n        if not os.path.isfile(img_mask_path) or not img_mask_path.lower().endswith(\n            (\".jpg\", \".jpeg\", \".png\", \".webp\")\n        ):\n            print(f\"File '{img_mask_path}' does not exist or is not a valid image file\")\n            continue\n        else:\n            with Image.open(img_mask_path) as img:\n                width, height = img.size\n\n            if width % 32 != 0 or height % 32 != 0:\n                print(f\"Image dimensions must be divisible by 32, got {width}x{height}\")\n                continue\n            else:\n                with Image.open(options.img_cond_path) as img_cond:\n                    img_cond_width, img_cond_height = img_cond.size\n\n                if width != img_cond_width or height != img_cond_height:\n                    print(\n                        f\"Mask dimensions must match conditioning image, got {width}x{height} and {img_cond_width}x{img_cond_height}\"\n                    )\n                    continue\n\n        options.img_mask_path = img_mask_path\n        break\n\n    return options\n\n\n@torch.inference_mode()\ndef main(\n    seed: int | None = None,\n    prompt: str = \"a white paper cup\",\n    device: str = \"cuda\" if torch.cuda.is_available() else \"cpu\",\n    num_steps: int = 50,\n    loop: bool = False,\n    guidance: float = 30.0,\n    offload: bool = False,\n    output_dir: str = \"output\",\n    add_sampling_metadata: bool = True,\n    img_cond_path: str = \"assets/cup.png\",\n    img_mask_path: str = \"assets/cup_mask.png\",\n    track_usage: bool = False,\n):\n    \"\"\"\n    Sample the flux model. Either interactively (set `--loop`) or run for a\n    single image. This demo assumes that the conditioning image and mask have\n    the same shape and that height and width are divisible by 32.\n\n    Args:\n        seed: Set a seed for sampling\n        output_name: where to save the output image, `{idx}` will be replaced\n            by the index of the sample\n        prompt: Prompt used for sampling\n        device: Pytorch device\n        num_steps: number of sampling steps (default 4 for schnell, 50 for guidance distilled)\n        loop: start an interactive session and sample multiple times\n        guidance: guidance value used for guidance distillation\n        add_sampling_metadata: Add the prompt to the image Exif metadata\n        img_cond_path: path to conditioning image (jpeg/png/webp)\n        img_mask_path: path to conditioning mask (jpeg/png/webp)\n        track_usage: track usage of the model for licensing purposes\n    \"\"\"\n    nsfw_classifier = pipeline(\"image-classification\", model=\"Falconsai/nsfw_image_detection\", device=device)\n\n    name = \"flux-dev-fill\"\n    if name not in configs:\n        available = \", \".join(configs.keys())\n        raise ValueError(f\"Got unknown model name: {name}, chose from {available}\")\n\n    torch_device = torch.device(device)\n\n    output_name = os.path.join(output_dir, \"img_{idx}.jpg\")\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n        idx = 0\n    else:\n        fns = [fn for fn in iglob(output_name.format(idx=\"*\")) if re.search(r\"img_[0-9]+\\.jpg$\", fn)]\n        if len(fns) > 0:\n            idx = max(int(fn.split(\"_\")[-1].split(\".\")[0]) for fn in fns) + 1\n        else:\n            idx = 0\n\n    # init all components\n    t5 = load_t5(torch_device, max_length=128)\n    clip = load_clip(torch_device)\n    model = load_flow_model(name, device=\"cpu\" if offload else torch_device)\n    ae = load_ae(name, device=\"cpu\" if offload else torch_device)\n\n    rng = torch.Generator(device=\"cpu\")\n    with Image.open(img_cond_path) as img:\n        width, height = img.size\n    opts = SamplingOptions(\n        prompt=prompt,\n        width=width,\n        height=height,\n        num_steps=num_steps,\n        guidance=guidance,\n        seed=seed,\n        img_cond_path=img_cond_path,\n        img_mask_path=img_mask_path,\n    )\n\n    if loop:\n        opts = parse_prompt(opts)\n        opts = parse_img_cond_path(opts)\n\n        with Image.open(opts.img_cond_path) as img:\n            width, height = img.size\n        opts.height = height\n        opts.width = width\n\n        opts = parse_img_mask_path(opts)\n\n    while opts is not None:\n        if opts.seed is None:\n            opts.seed = rng.seed()\n        print(f\"Generating with seed {opts.seed}:\\n{opts.prompt}\")\n        t0 = time.perf_counter()\n\n        # prepare input\n        x = get_noise(\n            1,\n            opts.height,\n            opts.width,\n            device=torch_device,\n            dtype=torch.bfloat16,\n            seed=opts.seed,\n        )\n        opts.seed = None\n        if offload:\n            t5, clip, ae = t5.to(torch_device), clip.to(torch_device), ae.to(torch_device)\n        inp = prepare_fill(\n            t5,\n            clip,\n            x,\n            prompt=opts.prompt,\n            ae=ae,\n            img_cond_path=opts.img_cond_path,\n            mask_path=opts.img_mask_path,\n        )\n\n        timesteps = get_schedule(opts.num_steps, inp[\"img\"].shape[1], shift=(name != \"flux-schnell\"))\n\n        # offload TEs and AE to CPU, load model to gpu\n        if offload:\n            t5, clip, ae = t5.cpu(), clip.cpu(), ae.cpu()\n            torch.cuda.empty_cache()\n            model = model.to(torch_device)\n\n        # denoise initial noise\n        x = denoise(model, **inp, timesteps=timesteps, guidance=opts.guidance)\n\n        # offload model, load autoencoder to gpu\n        if offload:\n            model.cpu()\n            torch.cuda.empty_cache()\n            ae.decoder.to(x.device)\n\n        # decode latents to pixel space\n        x = unpack(x.float(), opts.height, opts.width)\n        with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):\n            x = ae.decode(x)\n\n        if torch.cuda.is_available():\n            torch.cuda.synchronize()\n        t1 = time.perf_counter()\n        print(f\"Done in {t1 - t0:.1f}s\")\n\n        idx = save_image(\n            nsfw_classifier, name, output_name, idx, x, add_sampling_metadata, prompt, track_usage=track_usage\n        )\n\n        if loop:\n            print(\"-\" * 80)\n            opts = parse_prompt(opts)\n            opts = parse_img_cond_path(opts)\n\n            with Image.open(opts.img_cond_path) as img:\n                width, height = img.size\n            opts.height = height\n            opts.width = width\n\n            opts = parse_img_mask_path(opts)\n        else:\n            opts = None\n\n\nif __name__ == \"__main__\":\n    Fire(main)\n"
  },
  {
    "path": "src/flux/cli_kontext.py",
    "content": "import os\nimport re\nimport time\nfrom dataclasses import dataclass\nfrom glob import iglob\n\nimport torch\nfrom fire import Fire\n\nfrom flux.content_filters import PixtralContentFilter\nfrom flux.sampling import denoise, get_schedule, prepare_kontext, unpack\nfrom flux.util import (\n    aspect_ratio_to_height_width,\n    check_onnx_access_for_trt,\n    load_ae,\n    load_clip,\n    load_flow_model,\n    load_t5,\n    save_image,\n)\n\n\n@dataclass\nclass SamplingOptions:\n    prompt: str\n    width: int | None\n    height: int | None\n    num_steps: int\n    guidance: float\n    seed: int | None\n    img_cond_path: str\n\n\ndef parse_prompt(options: SamplingOptions) -> SamplingOptions | None:\n    user_question = \"Next prompt (write /h for help, /q to quit and leave empty to repeat):\\n\"\n    usage = (\n        \"Usage: Either write your prompt directly, leave this field empty \"\n        \"to repeat the prompt or write a command starting with a slash:\\n\"\n        \"- '/ar <width>:<height>' will set the aspect ratio of the generated image\\n\"\n        \"- '/s <seed>' sets the next seed\\n\"\n        \"- '/g <guidance>' sets the guidance (flux-dev only)\\n\"\n        \"- '/n <steps>' sets the number of steps\\n\"\n        \"- '/q' to quit\"\n    )\n\n    while (prompt := input(user_question)).startswith(\"/\"):\n        if prompt.startswith(\"/ar\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, ratio_prompt = prompt.split()\n            if ratio_prompt == \"auto\":\n                options.width = None\n                options.height = None\n                print(\"Setting resolution to input image resolution.\")\n            else:\n                options.width, options.height = aspect_ratio_to_height_width(ratio_prompt)\n                print(f\"Setting resolution to {options.width} x {options.height}.\")\n        elif prompt.startswith(\"/h\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, height = prompt.split()\n            if height == \"auto\":\n                options.height = None\n            else:\n                options.height = 16 * (int(height) // 16)\n            if options.height is not None and options.width is not None:\n                print(\n                    f\"Setting resolution to {options.width} x {options.height} \"\n                    f\"({options.height * options.width / 1e6:.2f}MP)\"\n                )\n            else:\n                print(f\"Setting resolution to {options.width} x {options.height}.\")\n        elif prompt.startswith(\"/g\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, guidance = prompt.split()\n            options.guidance = float(guidance)\n            print(f\"Setting guidance to {options.guidance}\")\n        elif prompt.startswith(\"/s\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, seed = prompt.split()\n            options.seed = int(seed)\n            print(f\"Setting seed to {options.seed}\")\n        elif prompt.startswith(\"/n\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, steps = prompt.split()\n            options.num_steps = int(steps)\n            print(f\"Setting number of steps to {options.num_steps}\")\n        elif prompt.startswith(\"/q\"):\n            print(\"Quitting\")\n            return None\n        else:\n            if not prompt.startswith(\"/h\"):\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n            print(usage)\n    if prompt != \"\":\n        options.prompt = prompt\n    return options\n\n\ndef parse_img_cond_path(options: SamplingOptions | None) -> SamplingOptions | None:\n    if options is None:\n        return None\n\n    user_question = \"Next input image (write /h for help, /q to quit and leave empty to repeat):\\n\"\n    usage = (\n        \"Usage: Either write a path to an image directly, leave this field empty \"\n        \"to repeat the last input image or write a command starting with a slash:\\n\"\n        \"- '/q' to quit\\n\\n\"\n        \"The input image will be edited by FLUX.1 Kontext creating a new image based\"\n        \"on your instruction prompt.\"\n    )\n\n    while True:\n        img_cond_path = input(user_question)\n\n        if img_cond_path.startswith(\"/\"):\n            if img_cond_path.startswith(\"/q\"):\n                print(\"Quitting\")\n                return None\n            else:\n                if not img_cond_path.startswith(\"/h\"):\n                    print(f\"Got invalid command '{img_cond_path}'\\n{usage}\")\n                print(usage)\n            continue\n\n        if img_cond_path == \"\":\n            break\n\n        if not os.path.isfile(img_cond_path) or not img_cond_path.lower().endswith(\n            (\".jpg\", \".jpeg\", \".png\", \".webp\")\n        ):\n            print(f\"File '{img_cond_path}' does not exist or is not a valid image file\")\n            continue\n\n        options.img_cond_path = img_cond_path\n        break\n\n    return options\n\n\n@torch.inference_mode()\ndef main(\n    name: str = \"flux-dev-kontext\",\n    aspect_ratio: str | None = None,\n    seed: int | None = None,\n    prompt: str = \"replace the logo with the text 'Black Forest Labs'\",\n    device: str = \"cuda\" if torch.cuda.is_available() else \"cpu\",\n    num_steps: int = 30,\n    loop: bool = False,\n    guidance: float = 2.5,\n    offload: bool = False,\n    output_dir: str = \"output\",\n    add_sampling_metadata: bool = True,\n    img_cond_path: str = \"assets/cup.png\",\n    trt: bool = False,\n    trt_transformer_precision: str = \"bf16\",\n    track_usage: bool = False,\n):\n    \"\"\"\n    Sample the flux model. Either interactively (set `--loop`) or run for a\n    single image.\n\n    Args:\n        height: height of the sample in pixels (should be a multiple of 16), None\n            defaults to the size of the conditioning\n        width: width of the sample in pixels (should be a multiple of 16), None\n            defaults to the size of the conditioning\n        seed: Set a seed for sampling\n        output_name: where to save the output image, `{idx}` will be replaced\n            by the index of the sample\n        prompt: Prompt used for sampling\n        device: Pytorch device\n        num_steps: number of sampling steps (default 4 for schnell, 50 for guidance distilled)\n        loop: start an interactive session and sample multiple times\n        guidance: guidance value used for guidance distillation\n        add_sampling_metadata: Add the prompt to the image Exif metadata\n        img_cond_path: path to conditioning image (jpeg/png/webp)\n        trt: use TensorRT backend for optimized inference\n        track_usage: track usage of the model for licensing purposes\n    \"\"\"\n    assert name == \"flux-dev-kontext\", f\"Got unknown model name: {name}\"\n\n    torch_device = torch.device(device)\n\n    output_name = os.path.join(output_dir, \"img_{idx}.jpg\")\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n        idx = 0\n    else:\n        fns = [fn for fn in iglob(output_name.format(idx=\"*\")) if re.search(r\"img_[0-9]+\\.jpg$\", fn)]\n        if len(fns) > 0:\n            idx = max(int(fn.split(\"_\")[-1].split(\".\")[0]) for fn in fns) + 1\n        else:\n            idx = 0\n\n    if aspect_ratio is None:\n        width = None\n        height = None\n    else:\n        width, height = aspect_ratio_to_height_width(aspect_ratio)\n\n    if not trt:\n        t5 = load_t5(torch_device, max_length=512)\n        clip = load_clip(torch_device)\n        model = load_flow_model(name, device=\"cpu\" if offload else torch_device)\n    else:\n        # lazy import to make install optional\n        from flux.trt.trt_manager import ModuleName, TRTManager\n\n        # Check if we need ONNX model access (which requires authentication for FLUX models)\n        onnx_dir = check_onnx_access_for_trt(name, trt_transformer_precision)\n\n        trt_ctx_manager = TRTManager(\n            trt_transformer_precision=trt_transformer_precision,\n            trt_t5_precision=os.environ.get(\"TRT_T5_PRECISION\", \"bf16\"),\n        )\n        engines = trt_ctx_manager.load_engines(\n            model_name=name,\n            module_names={\n                ModuleName.CLIP,\n                ModuleName.TRANSFORMER,\n                ModuleName.T5,\n            },\n            engine_dir=os.environ.get(\"TRT_ENGINE_DIR\", \"./engines\"),\n            custom_onnx_paths=onnx_dir or os.environ.get(\"CUSTOM_ONNX_PATHS\", \"\"),\n            trt_image_height=height,\n            trt_image_width=width,\n            trt_batch_size=1,\n            trt_timing_cache=os.getenv(\"TRT_TIMING_CACHE_FILE\", None),\n            trt_static_batch=False,\n            trt_static_shape=False,\n        )\n\n        model = engines[ModuleName.TRANSFORMER].to(device=\"cpu\" if offload else torch_device)\n        clip = engines[ModuleName.CLIP].to(torch_device)\n        t5 = engines[ModuleName.T5].to(device=\"cpu\" if offload else torch_device)\n\n    ae = load_ae(name, device=\"cpu\" if offload else torch_device)\n    content_filter = PixtralContentFilter(torch.device(\"cpu\"))\n\n    rng = torch.Generator(device=\"cpu\")\n    opts = SamplingOptions(\n        prompt=prompt,\n        width=width,\n        height=height,\n        num_steps=num_steps,\n        guidance=guidance,\n        seed=seed,\n        img_cond_path=img_cond_path,\n    )\n\n    if loop:\n        opts = parse_prompt(opts)\n        opts = parse_img_cond_path(opts)\n\n    while opts is not None:\n        if opts.seed is None:\n            opts.seed = rng.seed()\n        print(f\"Generating with seed {opts.seed}:\\n{opts.prompt}\")\n        t0 = time.perf_counter()\n\n        if content_filter.test_txt(opts.prompt):\n            print(\"Your prompt has been automatically flagged. Please choose another prompt.\")\n            if loop:\n                print(\"-\" * 80)\n                opts = parse_prompt(opts)\n                opts = parse_img_cond_path(opts)\n            else:\n                opts = None\n            continue\n        if content_filter.test_image(opts.img_cond_path):\n            print(\"Your input image has been automatically flagged. Please choose another image.\")\n            if loop:\n                print(\"-\" * 80)\n                opts = parse_prompt(opts)\n                opts = parse_img_cond_path(opts)\n            else:\n                opts = None\n            continue\n\n        if offload:\n            t5, clip, ae = t5.to(torch_device), clip.to(torch_device), ae.to(torch_device)\n        inp, height, width = prepare_kontext(\n            t5=t5,\n            clip=clip,\n            prompt=opts.prompt,\n            ae=ae,\n            img_cond_path=opts.img_cond_path,\n            target_width=opts.width,\n            target_height=opts.height,\n            bs=1,\n            seed=opts.seed,\n            device=torch_device,\n        )\n        from safetensors.torch import save_file\n\n        save_file({k: v.cpu().contiguous() for k, v in inp.items()}, \"output/noise.sft\")\n        inp.pop(\"img_cond_orig\")\n        opts.seed = None\n        timesteps = get_schedule(opts.num_steps, inp[\"img\"].shape[1], shift=(name != \"flux-schnell\"))\n\n        # offload TEs and AE to CPU, load model to gpu\n        if offload:\n            t5, clip, ae = t5.cpu(), clip.cpu(), ae.cpu()\n            torch.cuda.empty_cache()\n            model = model.to(torch_device)\n\n        # denoise initial noise\n        t00 = time.time()\n        x = denoise(model, **inp, timesteps=timesteps, guidance=opts.guidance)\n        torch.cuda.synchronize()\n        t01 = time.time()\n        print(f\"Denoising took {t01 - t00:.3f}s\")\n\n        # offload model, load autoencoder to gpu\n        if offload:\n            model.cpu()\n            torch.cuda.empty_cache()\n            ae.decoder.to(x.device)\n\n        # decode latents to pixel space\n        x = unpack(x.float(), height, width)\n        with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):\n            ae_dev_t0 = time.perf_counter()\n            x = ae.decode(x)\n            torch.cuda.synchronize()\n            ae_dev_t1 = time.perf_counter()\n            print(f\"AE decode took {ae_dev_t1 - ae_dev_t0:.3f}s\")\n\n        if content_filter.test_image(x.cpu()):\n            print(\n                \"Your output image has been automatically flagged. Choose another prompt/image or try again.\"\n            )\n            if loop:\n                print(\"-\" * 80)\n                opts = parse_prompt(opts)\n                opts = parse_img_cond_path(opts)\n            else:\n                opts = None\n            continue\n\n        if torch.cuda.is_available():\n            torch.cuda.synchronize()\n        t1 = time.perf_counter()\n        print(f\"Done in {t1 - t0:.1f}s\")\n\n        idx = save_image(\n            None, name, output_name, idx, x, add_sampling_metadata, prompt, track_usage=track_usage\n        )\n\n        if loop:\n            print(\"-\" * 80)\n            opts = parse_prompt(opts)\n            opts = parse_img_cond_path(opts)\n        else:\n            opts = None\n\n\nif __name__ == \"__main__\":\n    Fire(main)\n"
  },
  {
    "path": "src/flux/cli_redux.py",
    "content": "import os\nimport re\nimport time\nfrom dataclasses import dataclass\nfrom glob import iglob\n\nimport torch\nfrom fire import Fire\nfrom transformers import pipeline\n\nfrom flux.modules.image_embedders import ReduxImageEncoder\nfrom flux.sampling import denoise, get_noise, get_schedule, prepare_redux, unpack\nfrom flux.util import (\n    get_checkpoint_path,\n    load_ae,\n    load_clip,\n    load_flow_model,\n    load_t5,\n    save_image,\n)\n\n\n@dataclass\nclass SamplingOptions:\n    prompt: str\n    width: int\n    height: int\n    num_steps: int\n    guidance: float\n    seed: int | None\n    img_cond_path: str\n\n\ndef parse_prompt(options: SamplingOptions) -> SamplingOptions | None:\n    user_question = \"Write /h for help, /q to quit and leave empty to repeat):\\n\"\n    usage = (\n        \"Usage: Leave this field empty to do nothing \"\n        \"or write a command starting with a slash:\\n\"\n        \"- '/w <width>' will set the width of the generated image\\n\"\n        \"- '/h <height>' will set the height of the generated image\\n\"\n        \"- '/s <seed>' sets the next seed\\n\"\n        \"- '/g <guidance>' sets the guidance (flux-dev only)\\n\"\n        \"- '/n <steps>' sets the number of steps\\n\"\n        \"- '/q' to quit\"\n    )\n\n    while (prompt := input(user_question)).startswith(\"/\"):\n        if prompt.startswith(\"/w\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, width = prompt.split()\n            options.width = 16 * (int(width) // 16)\n            print(\n                f\"Setting resolution to {options.width} x {options.height} \"\n                f\"({options.height * options.width / 1e6:.2f}MP)\"\n            )\n        elif prompt.startswith(\"/h\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, height = prompt.split()\n            options.height = 16 * (int(height) // 16)\n            print(\n                f\"Setting resolution to {options.width} x {options.height} \"\n                f\"({options.height * options.width / 1e6:.2f}MP)\"\n            )\n        elif prompt.startswith(\"/g\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, guidance = prompt.split()\n            options.guidance = float(guidance)\n            print(f\"Setting guidance to {options.guidance}\")\n        elif prompt.startswith(\"/s\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, seed = prompt.split()\n            options.seed = int(seed)\n            print(f\"Setting seed to {options.seed}\")\n        elif prompt.startswith(\"/n\"):\n            if prompt.count(\" \") != 1:\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n                continue\n            _, steps = prompt.split()\n            options.num_steps = int(steps)\n            print(f\"Setting number of steps to {options.num_steps}\")\n        elif prompt.startswith(\"/q\"):\n            print(\"Quitting\")\n            return None\n        else:\n            if not prompt.startswith(\"/h\"):\n                print(f\"Got invalid command '{prompt}'\\n{usage}\")\n            print(usage)\n    return options\n\n\ndef parse_img_cond_path(options: SamplingOptions | None) -> SamplingOptions | None:\n    if options is None:\n        return None\n\n    user_question = \"Next conditioning image (write /h for help, /q to quit and leave empty to repeat):\\n\"\n    usage = (\n        \"Usage: Either write your prompt directly, leave this field empty \"\n        \"to repeat the conditioning image or write a command starting with a slash:\\n\"\n        \"- '/q' to quit\"\n    )\n\n    while True:\n        img_cond_path = input(user_question)\n\n        if img_cond_path.startswith(\"/\"):\n            if img_cond_path.startswith(\"/q\"):\n                print(\"Quitting\")\n                return None\n            else:\n                if not img_cond_path.startswith(\"/h\"):\n                    print(f\"Got invalid command '{img_cond_path}'\\n{usage}\")\n                print(usage)\n            continue\n\n        if img_cond_path == \"\":\n            break\n\n        if not os.path.isfile(img_cond_path) or not img_cond_path.lower().endswith(\n            (\".jpg\", \".jpeg\", \".png\", \".webp\")\n        ):\n            print(f\"File '{img_cond_path}' does not exist or is not a valid image file\")\n            continue\n\n        options.img_cond_path = img_cond_path\n        break\n\n    return options\n\n\n@torch.inference_mode()\ndef main(\n    name: str = \"flux-dev\",\n    width: int = 1360,\n    height: int = 768,\n    seed: int | None = None,\n    device: str = \"cuda\" if torch.cuda.is_available() else \"cpu\",\n    num_steps: int | None = None,\n    loop: bool = False,\n    guidance: float = 2.5,\n    offload: bool = False,\n    output_dir: str = \"output\",\n    add_sampling_metadata: bool = True,\n    img_cond_path: str = \"assets/robot.webp\",\n    track_usage: bool = False,\n):\n    \"\"\"\n    Sample the flux model. Either interactively (set `--loop`) or run for a\n    single image.\n\n    Args:\n        name: Name of the base model to use (either 'flux-dev' or 'flux-schnell')\n        height: height of the sample in pixels (should be a multiple of 16)\n        width: width of the sample in pixels (should be a multiple of 16)\n        seed: Set a seed for sampling\n        device: Pytorch device\n        num_steps: number of sampling steps (default 4 for schnell, 50 for guidance distilled)\n        loop: start an interactive session and sample multiple times\n        guidance: guidance value used for guidance distillation\n        offload: offload models to CPU when not in use\n        output_dir: where to save the output images\n        add_sampling_metadata: Add the prompt to the image Exif metadata\n        img_cond_path: path to conditioning image (jpeg/png/webp)\n        track_usage: track usage of the model for licensing purposes\n    \"\"\"\n\n    nsfw_classifier = pipeline(\"image-classification\", model=\"Falconsai/nsfw_image_detection\", device=device)\n\n    if name not in (available := [\"flux-dev\", \"flux-schnell\"]):\n        raise ValueError(f\"Got unknown model name: {name}, chose from {available}\")\n\n    torch_device = torch.device(device)\n    if num_steps is None:\n        num_steps = 4 if name == \"flux-schnell\" else 50\n\n    output_name = os.path.join(output_dir, \"img_{idx}.jpg\")\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n        idx = 0\n    else:\n        fns = [fn for fn in iglob(output_name.format(idx=\"*\")) if re.search(r\"img_[0-9]+\\.jpg$\", fn)]\n        if len(fns) > 0:\n            idx = max(int(fn.split(\"_\")[-1].split(\".\")[0]) for fn in fns) + 1\n        else:\n            idx = 0\n\n    # init all components\n    t5 = load_t5(torch_device, max_length=256 if name == \"flux-schnell\" else 512)\n    clip = load_clip(torch_device)\n    model = load_flow_model(name, device=\"cpu\" if offload else torch_device)\n    ae = load_ae(name, device=\"cpu\" if offload else torch_device)\n\n    # Download and initialize the Redux adapter\n    redux_path = str(\n        get_checkpoint_path(\"black-forest-labs/FLUX.1-Redux-dev\", \"flux1-redux-dev.safetensors\", \"FLUX_REDUX\")\n    )\n    img_embedder = ReduxImageEncoder(torch_device, redux_path=redux_path)\n\n    rng = torch.Generator(device=\"cpu\")\n    prompt = \"\"\n    opts = SamplingOptions(\n        prompt=prompt,\n        width=width,\n        height=height,\n        num_steps=num_steps,\n        guidance=guidance,\n        seed=seed,\n        img_cond_path=img_cond_path,\n    )\n\n    if loop:\n        opts = parse_prompt(opts)\n        opts = parse_img_cond_path(opts)\n\n    while opts is not None:\n        if opts.seed is None:\n            opts.seed = rng.seed()\n        print(f\"Generating with seed {opts.seed}:\\n{opts.prompt}\")\n        t0 = time.perf_counter()\n\n        # prepare input\n        x = get_noise(\n            1,\n            opts.height,\n            opts.width,\n            device=torch_device,\n            dtype=torch.bfloat16,\n            seed=opts.seed,\n        )\n        opts.seed = None\n        if offload:\n            ae = ae.cpu()\n            torch.cuda.empty_cache()\n            t5, clip = t5.to(torch_device), clip.to(torch_device)\n        inp = prepare_redux(\n            t5,\n            clip,\n            x,\n            prompt=opts.prompt,\n            encoder=img_embedder,\n            img_cond_path=opts.img_cond_path,\n        )\n        timesteps = get_schedule(opts.num_steps, inp[\"img\"].shape[1], shift=(name != \"flux-schnell\"))\n\n        # offload TEs to CPU, load model to gpu\n        if offload:\n            t5, clip = t5.cpu(), clip.cpu()\n            torch.cuda.empty_cache()\n            model = model.to(torch_device)\n\n        # denoise initial noise\n        x = denoise(model, **inp, timesteps=timesteps, guidance=opts.guidance)\n\n        # offload model, load autoencoder to gpu\n        if offload:\n            model.cpu()\n            torch.cuda.empty_cache()\n            ae.decoder.to(x.device)\n\n        # decode latents to pixel space\n        x = unpack(x.float(), opts.height, opts.width)\n        with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):\n            x = ae.decode(x)\n\n        if torch.cuda.is_available():\n            torch.cuda.synchronize()\n        t1 = time.perf_counter()\n        print(f\"Done in {t1 - t0:.1f}s\")\n\n        idx = save_image(\n            nsfw_classifier, name, output_name, idx, x, add_sampling_metadata, prompt, track_usage=track_usage\n        )\n\n        if loop:\n            print(\"-\" * 80)\n            opts = parse_prompt(opts)\n            opts = parse_img_cond_path(opts)\n        else:\n            opts = None\n\n\nif __name__ == \"__main__\":\n    Fire(main)\n"
  },
  {
    "path": "src/flux/content_filters.py",
    "content": "import torch\nfrom einops import rearrange\nfrom PIL import Image\nfrom transformers import AutoProcessor, LlavaForConditionalGeneration, pipeline\n\nPROMPT_IMAGE_INTEGRITY = \"\"\"\nTask: Analyze an image to identify potential copyright concerns or depictions of public figures.\n\nOutput: Respond with only \"yes\" or \"no\"\n\nCriteria for \"yes\":\n- The image contains a recognizable character from copyrighted media (movies, TV, comics, games, etc.)\n- The image displays a trademarked logo or brand\n- The image depicts a recognizable public figure (celebrities, politicians, athletes, influencers, historical figures, etc.)\n\nCriteria for \"no\":\n- All other cases\n- When you cannot identify the specific copyrighted work or named individual\n\nCritical Requirements:\n1. You must be able to name the exact copyrighted work or specific person depicted\n2. General references to demographics or characteristics are not sufficient\n3. Base your decision solely on visual content, not interpretation\n4. Provide only the one-word answer: \"yes\" or \"no\"\n\"\"\".strip()\n\n\nPROMPT_IMAGE_INTEGRITY_FOLLOW_UP = \"Does this image have copyright concerns or includes public figures?\"\n\nPROMPT_TEXT_INTEGRITY = \"\"\"\nTask: Analyze a text prompt to identify potential copyright concerns or requests to depict living public figures.\n\nOutput: Respond with only \"yes\" or \"no\"\n\nCriteria for \"Yes\":\n- The prompt explicitly names a character from copyrighted media (movies, TV, comics, games, etc.)\n- The prompt explicitly mentions a trademarked logo or brand\n- The prompt names or describes a specific living public figure (celebrities, politicians, athletes, influencers, etc.)\n\nCriteria for \"No\":\n- All other cases\n- When you cannot identify the specific copyrighted work or named individual\n\nCritical Requirements:\n1. You must be able to name the exact copyrighted work or specific person referenced\n2. General demographic descriptions or characteristics are not sufficient\n3. Analyze only the prompt text, not potential image outcomes\n4. Provide only the one-word answer: \"yes\" or \"no\"\n\nThe prompt to check is:\n-----\n{prompt}\n-----\n\nDoes this prompt have copyright concerns or includes public figures?\n\"\"\".strip()\n\n\nclass PixtralContentFilter(torch.nn.Module):\n    def __init__(\n        self,\n        device: torch.device = torch.device(\"cpu\"),\n        nsfw_threshold: float = 0.85,\n    ):\n        super().__init__()\n\n        model_id = \"mistral-community/pixtral-12b\"\n        self.processor = AutoProcessor.from_pretrained(model_id)\n        self.model = LlavaForConditionalGeneration.from_pretrained(model_id, device_map=device)\n\n        self.yes_token, self.no_token = self.processor.tokenizer.encode([\"yes\", \"no\"])\n\n        self.nsfw_classifier = pipeline(\n            \"image-classification\", model=\"Falconsai/nsfw_image_detection\", device=device\n        )\n        self.nsfw_threshold = nsfw_threshold\n\n    def yes_no_logit_processor(\n        self, input_ids: torch.LongTensor, scores: torch.FloatTensor\n    ) -> torch.FloatTensor:\n        \"\"\"\n        Sets all tokens but yes/no to the minimum.\n        \"\"\"\n        scores_yes_token = scores[:, self.yes_token].clone()\n        scores_no_token = scores[:, self.no_token].clone()\n        scores_min = scores.min()\n        scores[:, :] = scores_min - 1\n        scores[:, self.yes_token] = scores_yes_token\n        scores[:, self.no_token] = scores_no_token\n        return scores\n\n    def test_image(self, image: Image.Image | str | torch.Tensor) -> bool:\n        if isinstance(image, torch.Tensor):\n            image = rearrange(image[0].clamp(-1.0, 1.0), \"c h w -> h w c\")\n            image = Image.fromarray((127.5 * (image + 1.0)).cpu().byte().numpy())\n        elif isinstance(image, str):\n            image = Image.open(image)\n\n        classification = next(c for c in self.nsfw_classifier(image) if c[\"label\"] == \"nsfw\")\n        if classification[\"score\"] > self.nsfw_threshold:\n            return True\n\n        # 512^2 pixels are enough for checking\n        w, h = image.size\n        f = (512**2 / (w * h)) ** 0.5\n        image = image.resize((int(f * w), int(f * h)))\n\n        chat = [\n            {\n                \"role\": \"user\",\n                \"content\": [\n                    {\n                        \"type\": \"text\",\n                        \"content\": PROMPT_IMAGE_INTEGRITY,\n                    },\n                    {\n                        \"type\": \"image\",\n                        \"image\": image,\n                    },\n                    {\n                        \"type\": \"text\",\n                        \"content\": PROMPT_IMAGE_INTEGRITY_FOLLOW_UP,\n                    },\n                ],\n            }\n        ]\n\n        inputs = self.processor.apply_chat_template(\n            chat,\n            add_generation_prompt=True,\n            tokenize=True,\n            return_dict=True,\n            return_tensors=\"pt\",\n        ).to(self.model.device)\n\n        generate_ids = self.model.generate(\n            **inputs,\n            max_new_tokens=1,\n            logits_processor=[self.yes_no_logit_processor],\n            do_sample=False,\n        )\n        return generate_ids[0, -1].item() == self.yes_token\n\n    def test_txt(self, txt: str) -> bool:\n        chat = [\n            {\n                \"role\": \"user\",\n                \"content\": [\n                    {\n                        \"type\": \"text\",\n                        \"content\": PROMPT_TEXT_INTEGRITY.format(prompt=txt),\n                    },\n                ],\n            }\n        ]\n\n        inputs = self.processor.apply_chat_template(\n            chat,\n            add_generation_prompt=True,\n            tokenize=True,\n            return_dict=True,\n            return_tensors=\"pt\",\n        ).to(self.model.device)\n\n        generate_ids = self.model.generate(\n            **inputs,\n            max_new_tokens=1,\n            logits_processor=[self.yes_no_logit_processor],\n            do_sample=False,\n        )\n        return generate_ids[0, -1].item() == self.yes_token\n"
  },
  {
    "path": "src/flux/math.py",
    "content": "import torch\nfrom einops import rearrange\nfrom torch import Tensor\n\n\ndef attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> Tensor:\n    q, k = apply_rope(q, k, pe)\n\n    x = torch.nn.functional.scaled_dot_product_attention(q, k, v)\n    x = rearrange(x, \"B H L D -> B L (H D)\")\n\n    return x\n\n\ndef rope(pos: Tensor, dim: int, theta: int) -> Tensor:\n    assert dim % 2 == 0\n    scale = torch.arange(0, dim, 2, dtype=pos.dtype, device=pos.device) / dim\n    omega = 1.0 / (theta**scale)\n    out = torch.einsum(\"...n,d->...nd\", pos, omega)\n    out = torch.stack([torch.cos(out), -torch.sin(out), torch.sin(out), torch.cos(out)], dim=-1)\n    out = rearrange(out, \"b n d (i j) -> b n d i j\", i=2, j=2)\n    return out.float()\n\n\ndef apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:\n    xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)\n    xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)\n    xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]\n    xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]\n    return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)\n"
  },
  {
    "path": "src/flux/model.py",
    "content": "from dataclasses import dataclass\n\nimport torch\nfrom torch import Tensor, nn\n\nfrom flux.modules.layers import (\n    DoubleStreamBlock,\n    EmbedND,\n    LastLayer,\n    MLPEmbedder,\n    SingleStreamBlock,\n    timestep_embedding,\n)\nfrom flux.modules.lora import LinearLora, replace_linear_with_lora\n\n\n@dataclass\nclass FluxParams:\n    in_channels: int\n    out_channels: int\n    vec_in_dim: int\n    context_in_dim: int\n    hidden_size: int\n    mlp_ratio: float\n    num_heads: int\n    depth: int\n    depth_single_blocks: int\n    axes_dim: list[int]\n    theta: int\n    qkv_bias: bool\n    guidance_embed: bool\n\n\nclass Flux(nn.Module):\n    \"\"\"\n    Transformer model for flow matching on sequences.\n    \"\"\"\n\n    def __init__(self, params: FluxParams):\n        super().__init__()\n\n        self.params = params\n        self.in_channels = params.in_channels\n        self.out_channels = params.out_channels\n        if params.hidden_size % params.num_heads != 0:\n            raise ValueError(\n                f\"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}\"\n            )\n        pe_dim = params.hidden_size // params.num_heads\n        if sum(params.axes_dim) != pe_dim:\n            raise ValueError(f\"Got {params.axes_dim} but expected positional dim {pe_dim}\")\n        self.hidden_size = params.hidden_size\n        self.num_heads = params.num_heads\n        self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)\n        self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)\n        self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)\n        self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size)\n        self.guidance_in = (\n            MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()\n        )\n        self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)\n\n        self.double_blocks = nn.ModuleList(\n            [\n                DoubleStreamBlock(\n                    self.hidden_size,\n                    self.num_heads,\n                    mlp_ratio=params.mlp_ratio,\n                    qkv_bias=params.qkv_bias,\n                )\n                for _ in range(params.depth)\n            ]\n        )\n\n        self.single_blocks = nn.ModuleList(\n            [\n                SingleStreamBlock(self.hidden_size, self.num_heads, mlp_ratio=params.mlp_ratio)\n                for _ in range(params.depth_single_blocks)\n            ]\n        )\n\n        self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels)\n\n    def forward(\n        self,\n        img: Tensor,\n        img_ids: Tensor,\n        txt: Tensor,\n        txt_ids: Tensor,\n        timesteps: Tensor,\n        y: Tensor,\n        guidance: Tensor | None = None,\n    ) -> Tensor:\n        if img.ndim != 3 or txt.ndim != 3:\n            raise ValueError(\"Input img and txt tensors must have 3 dimensions.\")\n\n        # running on sequences img\n        img = self.img_in(img)\n        vec = self.time_in(timestep_embedding(timesteps, 256))\n        if self.params.guidance_embed:\n            if guidance is None:\n                raise ValueError(\"Didn't get guidance strength for guidance distilled model.\")\n            vec = vec + self.guidance_in(timestep_embedding(guidance, 256))\n        vec = vec + self.vector_in(y)\n        txt = self.txt_in(txt)\n\n        ids = torch.cat((txt_ids, img_ids), dim=1)\n        pe = self.pe_embedder(ids)\n\n        for block in self.double_blocks:\n            img, txt = block(img=img, txt=txt, vec=vec, pe=pe)\n\n        img = torch.cat((txt, img), 1)\n        for block in self.single_blocks:\n            img = block(img, vec=vec, pe=pe)\n        img = img[:, txt.shape[1] :, ...]\n\n        img = self.final_layer(img, vec)  # (N, T, patch_size ** 2 * out_channels)\n        return img\n\n\nclass FluxLoraWrapper(Flux):\n    def __init__(\n        self,\n        lora_rank: int = 128,\n        lora_scale: float = 1.0,\n        *args,\n        **kwargs,\n    ) -> None:\n        super().__init__(*args, **kwargs)\n\n        self.lora_rank = lora_rank\n\n        replace_linear_with_lora(\n            self,\n            max_rank=lora_rank,\n            scale=lora_scale,\n        )\n\n    def set_lora_scale(self, scale: float) -> None:\n        for module in self.modules():\n            if isinstance(module, LinearLora):\n                module.set_scale(scale=scale)\n"
  },
  {
    "path": "src/flux/modules/autoencoder.py",
    "content": "from dataclasses import dataclass\n\nimport torch\nfrom einops import rearrange\nfrom torch import Tensor, nn\n\n\n@dataclass\nclass AutoEncoderParams:\n    resolution: int\n    in_channels: int\n    ch: int\n    out_ch: int\n    ch_mult: list[int]\n    num_res_blocks: int\n    z_channels: int\n    scale_factor: float\n    shift_factor: float\n\n\ndef swish(x: Tensor) -> Tensor:\n    return x * torch.sigmoid(x)\n\n\nclass AttnBlock(nn.Module):\n    def __init__(self, in_channels: int):\n        super().__init__()\n        self.in_channels = in_channels\n\n        self.norm = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)\n\n        self.q = nn.Conv2d(in_channels, in_channels, kernel_size=1)\n        self.k = nn.Conv2d(in_channels, in_channels, kernel_size=1)\n        self.v = nn.Conv2d(in_channels, in_channels, kernel_size=1)\n        self.proj_out = nn.Conv2d(in_channels, in_channels, kernel_size=1)\n\n    def attention(self, h_: Tensor) -> Tensor:\n        h_ = self.norm(h_)\n        q = self.q(h_)\n        k = self.k(h_)\n        v = self.v(h_)\n\n        b, c, h, w = q.shape\n        q = rearrange(q, \"b c h w -> b 1 (h w) c\").contiguous()\n        k = rearrange(k, \"b c h w -> b 1 (h w) c\").contiguous()\n        v = rearrange(v, \"b c h w -> b 1 (h w) c\").contiguous()\n        h_ = nn.functional.scaled_dot_product_attention(q, k, v)\n\n        return rearrange(h_, \"b 1 (h w) c -> b c h w\", h=h, w=w, c=c, b=b)\n\n    def forward(self, x: Tensor) -> Tensor:\n        return x + self.proj_out(self.attention(x))\n\n\nclass ResnetBlock(nn.Module):\n    def __init__(self, in_channels: int, out_channels: int):\n        super().__init__()\n        self.in_channels = in_channels\n        out_channels = in_channels if out_channels is None else out_channels\n        self.out_channels = out_channels\n\n        self.norm1 = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)\n        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)\n        self.norm2 = nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=1e-6, affine=True)\n        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)\n        if self.in_channels != self.out_channels:\n            self.nin_shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)\n\n    def forward(self, x):\n        h = x\n        h = self.norm1(h)\n        h = swish(h)\n        h = self.conv1(h)\n\n        h = self.norm2(h)\n        h = swish(h)\n        h = self.conv2(h)\n\n        if self.in_channels != self.out_channels:\n            x = self.nin_shortcut(x)\n\n        return x + h\n\n\nclass Downsample(nn.Module):\n    def __init__(self, in_channels: int):\n        super().__init__()\n        # no asymmetric padding in torch conv, must do it ourselves\n        self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)\n\n    def forward(self, x: Tensor):\n        pad = (0, 1, 0, 1)\n        x = nn.functional.pad(x, pad, mode=\"constant\", value=0)\n        x = self.conv(x)\n        return x\n\n\nclass Upsample(nn.Module):\n    def __init__(self, in_channels: int):\n        super().__init__()\n        self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)\n\n    def forward(self, x: Tensor):\n        x = nn.functional.interpolate(x, scale_factor=2.0, mode=\"nearest\")\n        x = self.conv(x)\n        return x\n\n\nclass Encoder(nn.Module):\n    def __init__(\n        self,\n        resolution: int,\n        in_channels: int,\n        ch: int,\n        ch_mult: list[int],\n        num_res_blocks: int,\n        z_channels: int,\n    ):\n        super().__init__()\n        self.ch = ch\n        self.num_resolutions = len(ch_mult)\n        self.num_res_blocks = num_res_blocks\n        self.resolution = resolution\n        self.in_channels = in_channels\n        # downsampling\n        self.conv_in = nn.Conv2d(in_channels, self.ch, kernel_size=3, stride=1, padding=1)\n\n        curr_res = resolution\n        in_ch_mult = (1,) + tuple(ch_mult)\n        self.in_ch_mult = in_ch_mult\n        self.down = nn.ModuleList()\n        block_in = self.ch\n        for i_level in range(self.num_resolutions):\n            block = nn.ModuleList()\n            attn = nn.ModuleList()\n            block_in = ch * in_ch_mult[i_level]\n            block_out = ch * ch_mult[i_level]\n            for _ in range(self.num_res_blocks):\n                block.append(ResnetBlock(in_channels=block_in, out_channels=block_out))\n                block_in = block_out\n            down = nn.Module()\n            down.block = block\n            down.attn = attn\n            if i_level != self.num_resolutions - 1:\n                down.downsample = Downsample(block_in)\n                curr_res = curr_res // 2\n            self.down.append(down)\n\n        # middle\n        self.mid = nn.Module()\n        self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in)\n        self.mid.attn_1 = AttnBlock(block_in)\n        self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)\n\n        # end\n        self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)\n        self.conv_out = nn.Conv2d(block_in, 2 * z_channels, kernel_size=3, stride=1, padding=1)\n\n    def forward(self, x: Tensor) -> Tensor:\n        # downsampling\n        hs = [self.conv_in(x)]\n        for i_level in range(self.num_resolutions):\n            for i_block in range(self.num_res_blocks):\n                h = self.down[i_level].block[i_block](hs[-1])\n                if len(self.down[i_level].attn) > 0:\n                    h = self.down[i_level].attn[i_block](h)\n                hs.append(h)\n            if i_level != self.num_resolutions - 1:\n                hs.append(self.down[i_level].downsample(hs[-1]))\n\n        # middle\n        h = hs[-1]\n        h = self.mid.block_1(h)\n        h = self.mid.attn_1(h)\n        h = self.mid.block_2(h)\n        # end\n        h = self.norm_out(h)\n        h = swish(h)\n        h = self.conv_out(h)\n        return h\n\n\nclass Decoder(nn.Module):\n    def __init__(\n        self,\n        ch: int,\n        out_ch: int,\n        ch_mult: list[int],\n        num_res_blocks: int,\n        in_channels: int,\n        resolution: int,\n        z_channels: int,\n    ):\n        super().__init__()\n        self.ch = ch\n        self.num_resolutions = len(ch_mult)\n        self.num_res_blocks = num_res_blocks\n        self.resolution = resolution\n        self.in_channels = in_channels\n        self.ffactor = 2 ** (self.num_resolutions - 1)\n\n        # compute in_ch_mult, block_in and curr_res at lowest res\n        block_in = ch * ch_mult[self.num_resolutions - 1]\n        curr_res = resolution // 2 ** (self.num_resolutions - 1)\n        self.z_shape = (1, z_channels, curr_res, curr_res)\n\n        # z to block_in\n        self.conv_in = nn.Conv2d(z_channels, block_in, kernel_size=3, stride=1, padding=1)\n\n        # middle\n        self.mid = nn.Module()\n        self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in)\n        self.mid.attn_1 = AttnBlock(block_in)\n        self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)\n\n        # upsampling\n        self.up = nn.ModuleList()\n        for i_level in reversed(range(self.num_resolutions)):\n            block = nn.ModuleList()\n            attn = nn.ModuleList()\n            block_out = ch * ch_mult[i_level]\n            for _ in range(self.num_res_blocks + 1):\n                block.append(ResnetBlock(in_channels=block_in, out_channels=block_out))\n                block_in = block_out\n            up = nn.Module()\n            up.block = block\n            up.attn = attn\n            if i_level != 0:\n                up.upsample = Upsample(block_in)\n                curr_res = curr_res * 2\n            self.up.insert(0, up)  # prepend to get consistent order\n\n        # end\n        self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)\n        self.conv_out = nn.Conv2d(block_in, out_ch, kernel_size=3, stride=1, padding=1)\n\n    def forward(self, z: Tensor) -> Tensor:\n        # get dtype for proper tracing\n        upscale_dtype = next(self.up.parameters()).dtype\n\n        # z to block_in\n        h = self.conv_in(z)\n\n        # middle\n        h = self.mid.block_1(h)\n        h = self.mid.attn_1(h)\n        h = self.mid.block_2(h)\n\n        # cast to proper dtype\n        h = h.to(upscale_dtype)\n        # upsampling\n        for i_level in reversed(range(self.num_resolutions)):\n            for i_block in range(self.num_res_blocks + 1):\n                h = self.up[i_level].block[i_block](h)\n                if len(self.up[i_level].attn) > 0:\n                    h = self.up[i_level].attn[i_block](h)\n            if i_level != 0:\n                h = self.up[i_level].upsample(h)\n\n        # end\n        h = self.norm_out(h)\n        h = swish(h)\n        h = self.conv_out(h)\n        return h\n\n\nclass DiagonalGaussian(nn.Module):\n    def __init__(self, sample: bool = True, chunk_dim: int = 1):\n        super().__init__()\n        self.sample = sample\n        self.chunk_dim = chunk_dim\n\n    def forward(self, z: Tensor) -> Tensor:\n        mean, logvar = torch.chunk(z, 2, dim=self.chunk_dim)\n        if self.sample:\n            std = torch.exp(0.5 * logvar)\n            return mean + std * torch.randn_like(mean)\n        else:\n            return mean\n\n\nclass AutoEncoder(nn.Module):\n    def __init__(self, params: AutoEncoderParams, sample_z: bool = False):\n        super().__init__()\n        self.params = params\n        self.encoder = Encoder(\n            resolution=params.resolution,\n            in_channels=params.in_channels,\n            ch=params.ch,\n            ch_mult=params.ch_mult,\n            num_res_blocks=params.num_res_blocks,\n            z_channels=params.z_channels,\n        )\n        self.decoder = Decoder(\n            resolution=params.resolution,\n            in_channels=params.in_channels,\n            ch=params.ch,\n            out_ch=params.out_ch,\n            ch_mult=params.ch_mult,\n            num_res_blocks=params.num_res_blocks,\n            z_channels=params.z_channels,\n        )\n        self.reg = DiagonalGaussian(sample=sample_z)\n\n        self.scale_factor = params.scale_factor\n        self.shift_factor = params.shift_factor\n\n    def encode(self, x: Tensor) -> Tensor:\n        z = self.reg(self.encoder(x))\n        z = self.scale_factor * (z - self.shift_factor)\n        return z\n\n    def decode(self, z: Tensor) -> Tensor:\n        z = z / self.scale_factor + self.shift_factor\n        return self.decoder(z)\n\n    def forward(self, x: Tensor) -> Tensor:\n        return self.decode(self.encode(x))\n"
  },
  {
    "path": "src/flux/modules/conditioner.py",
    "content": "from torch import Tensor, nn\nfrom transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5Tokenizer\n\n\nclass HFEmbedder(nn.Module):\n    def __init__(self, version: str, max_length: int, **hf_kwargs):\n        super().__init__()\n        self.is_clip = version.startswith(\"openai\")\n        self.max_length = max_length\n        self.output_key = \"pooler_output\" if self.is_clip else \"last_hidden_state\"\n\n        if self.is_clip:\n            self.tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(version, max_length=max_length)\n            self.hf_module: CLIPTextModel = CLIPTextModel.from_pretrained(version, **hf_kwargs)\n        else:\n            self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained(version, max_length=max_length)\n            self.hf_module: T5EncoderModel = T5EncoderModel.from_pretrained(version, **hf_kwargs)\n\n        self.hf_module = self.hf_module.eval().requires_grad_(False)\n\n    def forward(self, text: list[str]) -> Tensor:\n        batch_encoding = self.tokenizer(\n            text,\n            truncation=True,\n            max_length=self.max_length,\n            return_length=False,\n            return_overflowing_tokens=False,\n            padding=\"max_length\",\n            return_tensors=\"pt\",\n        )\n\n        outputs = self.hf_module(\n            input_ids=batch_encoding[\"input_ids\"].to(self.hf_module.device),\n            attention_mask=None,\n            output_hidden_states=False,\n        )\n        return outputs[self.output_key].bfloat16()\n"
  },
  {
    "path": "src/flux/modules/image_embedders.py",
    "content": "import cv2\nimport numpy as np\nimport torch\nfrom einops import rearrange, repeat\nfrom PIL import Image\nfrom safetensors.torch import load_file as load_sft\nfrom torch import nn\nfrom transformers import AutoModelForDepthEstimation, AutoProcessor, SiglipImageProcessor, SiglipVisionModel\n\nfrom flux.util import print_load_warning\n\n\nclass DepthImageEncoder:\n    depth_model_name = \"LiheYoung/depth-anything-large-hf\"\n\n    def __init__(self, device):\n        self.device = device\n        self.depth_model = AutoModelForDepthEstimation.from_pretrained(self.depth_model_name).to(device)\n        self.processor = AutoProcessor.from_pretrained(self.depth_model_name)\n\n    def __call__(self, img: torch.Tensor) -> torch.Tensor:\n        hw = img.shape[-2:]\n\n        img = torch.clamp(img, -1.0, 1.0)\n        img_byte = ((img + 1.0) * 127.5).byte()\n\n        img = self.processor(img_byte, return_tensors=\"pt\")[\"pixel_values\"]\n        depth = self.depth_model(img.to(self.device)).predicted_depth\n        depth = repeat(depth, \"b h w -> b 3 h w\")\n        depth = torch.nn.functional.interpolate(depth, hw, mode=\"bicubic\", antialias=True)\n\n        depth = depth / 127.5 - 1.0\n        return depth\n\n\nclass CannyImageEncoder:\n    def __init__(\n        self,\n        device,\n        min_t: int = 50,\n        max_t: int = 200,\n    ):\n        self.device = device\n        self.min_t = min_t\n        self.max_t = max_t\n\n    def __call__(self, img: torch.Tensor) -> torch.Tensor:\n        assert img.shape[0] == 1, \"Only batch size 1 is supported\"\n\n        img = rearrange(img[0], \"c h w -> h w c\")\n        img = torch.clamp(img, -1.0, 1.0)\n        img_np = ((img + 1.0) * 127.5).numpy().astype(np.uint8)\n\n        # Apply Canny edge detection\n        canny = cv2.Canny(img_np, self.min_t, self.max_t)\n\n        # Convert back to torch tensor and reshape\n        canny = torch.from_numpy(canny).float() / 127.5 - 1.0\n        canny = rearrange(canny, \"h w -> 1 1 h w\")\n        canny = repeat(canny, \"b 1 ... -> b 3 ...\")\n        return canny.to(self.device)\n\n\nclass ReduxImageEncoder(nn.Module):\n    siglip_model_name = \"google/siglip-so400m-patch14-384\"\n\n    def __init__(\n        self,\n        device,\n        redux_path: str,\n        redux_dim: int = 1152,\n        txt_in_features: int = 4096,\n        dtype=torch.bfloat16,\n    ) -> None:\n        super().__init__()\n\n        self.redux_dim = redux_dim\n        self.device = device if isinstance(device, torch.device) else torch.device(device)\n        self.dtype = dtype\n\n        with self.device:\n            self.redux_up = nn.Linear(redux_dim, txt_in_features * 3, dtype=dtype)\n            self.redux_down = nn.Linear(txt_in_features * 3, txt_in_features, dtype=dtype)\n\n            sd = load_sft(redux_path, device=str(device))\n            missing, unexpected = self.load_state_dict(sd, strict=False, assign=True)\n            print_load_warning(missing, unexpected)\n\n            self.siglip = SiglipVisionModel.from_pretrained(self.siglip_model_name).to(dtype=dtype)\n        self.normalize = SiglipImageProcessor.from_pretrained(self.siglip_model_name)\n\n    def __call__(self, x: Image.Image) -> torch.Tensor:\n        imgs = self.normalize.preprocess(images=[x], do_resize=True, return_tensors=\"pt\", do_convert_rgb=True)\n\n        _encoded_x = self.siglip(**imgs.to(device=self.device, dtype=self.dtype)).last_hidden_state\n\n        projected_x = self.redux_down(nn.functional.silu(self.redux_up(_encoded_x)))\n\n        return projected_x\n"
  },
  {
    "path": "src/flux/modules/layers.py",
    "content": "import math\nfrom dataclasses import dataclass\n\nimport torch\nfrom einops import rearrange\nfrom torch import Tensor, nn\n\nfrom flux.math import attention, rope\n\n\nclass EmbedND(nn.Module):\n    def __init__(self, dim: int, theta: int, axes_dim: list[int]):\n        super().__init__()\n        self.dim = dim\n        self.theta = theta\n        self.axes_dim = axes_dim\n\n    def forward(self, ids: Tensor) -> Tensor:\n        n_axes = ids.shape[-1]\n        emb = torch.cat(\n            [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],\n            dim=-3,\n        )\n\n        return emb.unsqueeze(1)\n\n\ndef timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):\n    \"\"\"\n    Create sinusoidal timestep embeddings.\n    :param t: a 1-D Tensor of N indices, one per batch element.\n                      These may be fractional.\n    :param dim: the dimension of the output.\n    :param max_period: controls the minimum frequency of the embeddings.\n    :return: an (N, D) Tensor of positional embeddings.\n    \"\"\"\n    t = time_factor * t\n    half = dim // 2\n    freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(\n        t.device\n    )\n\n    args = t[:, None].float() * freqs[None]\n    embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)\n    if dim % 2:\n        embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)\n    if torch.is_floating_point(t):\n        embedding = embedding.to(t)\n    return embedding\n\n\nclass MLPEmbedder(nn.Module):\n    def __init__(self, in_dim: int, hidden_dim: int):\n        super().__init__()\n        self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)\n        self.silu = nn.SiLU()\n        self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)\n\n    def forward(self, x: Tensor) -> Tensor:\n        return self.out_layer(self.silu(self.in_layer(x)))\n\n\nclass RMSNorm(torch.nn.Module):\n    def __init__(self, dim: int):\n        super().__init__()\n        self.scale = nn.Parameter(torch.ones(dim))\n\n    def forward(self, x: Tensor):\n        x_dtype = x.dtype\n        x = x.float()\n        rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)\n        return (x * rrms).to(dtype=x_dtype) * self.scale\n\n\nclass QKNorm(torch.nn.Module):\n    def __init__(self, dim: int):\n        super().__init__()\n        self.query_norm = RMSNorm(dim)\n        self.key_norm = RMSNorm(dim)\n\n    def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:\n        q = self.query_norm(q)\n        k = self.key_norm(k)\n        return q.to(v), k.to(v)\n\n\nclass SelfAttention(nn.Module):\n    def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False):\n        super().__init__()\n        self.num_heads = num_heads\n        head_dim = dim // num_heads\n\n        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)\n        self.norm = QKNorm(head_dim)\n        self.proj = nn.Linear(dim, dim)\n\n    def forward(self, x: Tensor, pe: Tensor) -> Tensor:\n        qkv = self.qkv(x)\n        q, k, v = rearrange(qkv, \"B L (K H D) -> K B H L D\", K=3, H=self.num_heads)\n        q, k = self.norm(q, k, v)\n        x = attention(q, k, v, pe=pe)\n        x = self.proj(x)\n        return x\n\n\n@dataclass\nclass ModulationOut:\n    shift: Tensor\n    scale: Tensor\n    gate: Tensor\n\n\nclass Modulation(nn.Module):\n    def __init__(self, dim: int, double: bool):\n        super().__init__()\n        self.is_double = double\n        self.multiplier = 6 if double else 3\n        self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)\n\n    def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]:\n        out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)\n\n        return (\n            ModulationOut(*out[:3]),\n            ModulationOut(*out[3:]) if self.is_double else None,\n        )\n\n\nclass DoubleStreamBlock(nn.Module):\n    def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):\n        super().__init__()\n\n        mlp_hidden_dim = int(hidden_size * mlp_ratio)\n        self.num_heads = num_heads\n        self.hidden_size = hidden_size\n        self.img_mod = Modulation(hidden_size, double=True)\n        self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n        self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)\n\n        self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n        self.img_mlp = nn.Sequential(\n            nn.Linear(hidden_size, mlp_hidden_dim, bias=True),\n            nn.GELU(approximate=\"tanh\"),\n            nn.Linear(mlp_hidden_dim, hidden_size, bias=True),\n        )\n\n        self.txt_mod = Modulation(hidden_size, double=True)\n        self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n        self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)\n\n        self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n        self.txt_mlp = nn.Sequential(\n            nn.Linear(hidden_size, mlp_hidden_dim, bias=True),\n            nn.GELU(approximate=\"tanh\"),\n            nn.Linear(mlp_hidden_dim, hidden_size, bias=True),\n        )\n\n    def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:\n        img_mod1, img_mod2 = self.img_mod(vec)\n        txt_mod1, txt_mod2 = self.txt_mod(vec)\n\n        # prepare image for attention\n        img_modulated = self.img_norm1(img)\n        img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift\n        img_qkv = self.img_attn.qkv(img_modulated)\n        img_q, img_k, img_v = rearrange(img_qkv, \"B L (K H D) -> K B H L D\", K=3, H=self.num_heads)\n        img_q, img_k = self.img_attn.norm(img_q, img_k, img_v)\n\n        # prepare txt for attention\n        txt_modulated = self.txt_norm1(txt)\n        txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift\n        txt_qkv = self.txt_attn.qkv(txt_modulated)\n        txt_q, txt_k, txt_v = rearrange(txt_qkv, \"B L (K H D) -> K B H L D\", K=3, H=self.num_heads)\n        txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v)\n\n        # run actual attention\n        q = torch.cat((txt_q, img_q), dim=2)\n        k = torch.cat((txt_k, img_k), dim=2)\n        v = torch.cat((txt_v, img_v), dim=2)\n\n        attn = attention(q, k, v, pe=pe)\n        txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :]\n\n        # calculate the img blocks\n        img = img + img_mod1.gate * self.img_attn.proj(img_attn)\n        img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift)\n\n        # calculate the txt blocks\n        txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn)\n        txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift)\n        return img, txt\n\n\nclass SingleStreamBlock(nn.Module):\n    \"\"\"\n    A DiT block with parallel linear layers as described in\n    https://arxiv.org/abs/2302.05442 and adapted modulation interface.\n    \"\"\"\n\n    def __init__(\n        self,\n        hidden_size: int,\n        num_heads: int,\n        mlp_ratio: float = 4.0,\n        qk_scale: float | None = None,\n    ):\n        super().__init__()\n        self.hidden_dim = hidden_size\n        self.num_heads = num_heads\n        head_dim = hidden_size // num_heads\n        self.scale = qk_scale or head_dim**-0.5\n\n        self.mlp_hidden_dim = int(hidden_size * mlp_ratio)\n        # qkv and mlp_in\n        self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)\n        # proj and mlp_out\n        self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)\n\n        self.norm = QKNorm(head_dim)\n\n        self.hidden_size = hidden_size\n        self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n\n        self.mlp_act = nn.GELU(approximate=\"tanh\")\n        self.modulation = Modulation(hidden_size, double=False)\n\n    def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:\n        mod, _ = self.modulation(vec)\n        x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift\n        qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1)\n\n        q, k, v = rearrange(qkv, \"B L (K H D) -> K B H L D\", K=3, H=self.num_heads)\n        q, k = self.norm(q, k, v)\n\n        # compute attention\n        attn = attention(q, k, v, pe=pe)\n        # compute activation in mlp stream, cat again and run second linear layer\n        output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))\n        return x + mod.gate * output\n\n\nclass LastLayer(nn.Module):\n    def __init__(self, hidden_size: int, patch_size: int, out_channels: int):\n        super().__init__()\n        self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n        self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)\n        self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))\n\n    def forward(self, x: Tensor, vec: Tensor) -> Tensor:\n        shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)\n        x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]\n        x = self.linear(x)\n        return x\n"
  },
  {
    "path": "src/flux/modules/lora.py",
    "content": "import torch\nfrom torch import nn\n\n\ndef replace_linear_with_lora(\n    module: nn.Module,\n    max_rank: int,\n    scale: float = 1.0,\n) -> None:\n    for name, child in module.named_children():\n        if isinstance(child, nn.Linear):\n            new_lora = LinearLora(\n                in_features=child.in_features,\n                out_features=child.out_features,\n                bias=child.bias,\n                rank=max_rank,\n                scale=scale,\n                dtype=child.weight.dtype,\n                device=child.weight.device,\n            )\n\n            new_lora.weight = child.weight\n            new_lora.bias = child.bias if child.bias is not None else None\n\n            setattr(module, name, new_lora)\n        else:\n            replace_linear_with_lora(\n                module=child,\n                max_rank=max_rank,\n                scale=scale,\n            )\n\n\nclass LinearLora(nn.Linear):\n    def __init__(\n        self,\n        in_features: int,\n        out_features: int,\n        bias: bool,\n        rank: int,\n        dtype: torch.dtype,\n        device: torch.device,\n        lora_bias: bool = True,\n        scale: float = 1.0,\n        *args,\n        **kwargs,\n    ) -> None:\n        super().__init__(\n            in_features=in_features,\n            out_features=out_features,\n            bias=bias is not None,\n            device=device,\n            dtype=dtype,\n            *args,\n            **kwargs,\n        )\n\n        assert isinstance(scale, float), \"scale must be a float\"\n\n        self.scale = scale\n        self.rank = rank\n        self.lora_bias = lora_bias\n        self.dtype = dtype\n        self.device = device\n\n        if rank > (new_rank := min(self.out_features, self.in_features)):\n            self.rank = new_rank\n\n        self.lora_A = nn.Linear(\n            in_features=in_features,\n            out_features=self.rank,\n            bias=False,\n            dtype=dtype,\n            device=device,\n        )\n        self.lora_B = nn.Linear(\n            in_features=self.rank,\n            out_features=out_features,\n            bias=self.lora_bias,\n            dtype=dtype,\n            device=device,\n        )\n\n    def set_scale(self, scale: float) -> None:\n        assert isinstance(scale, float), \"scalar value must be a float\"\n        self.scale = scale\n\n    def forward(self, input: torch.Tensor) -> torch.Tensor:\n        base_out = super().forward(input)\n\n        _lora_out_B = self.lora_B(self.lora_A(input))\n        lora_update = _lora_out_B * self.scale\n\n        return base_out + lora_update\n"
  },
  {
    "path": "src/flux/sampling.py",
    "content": "import math\nfrom typing import Callable\n\nimport numpy as np\nimport torch\nfrom einops import rearrange, repeat\nfrom PIL import Image\nfrom torch import Tensor\n\nfrom .model import Flux\nfrom .modules.autoencoder import AutoEncoder\nfrom .modules.conditioner import HFEmbedder\nfrom .modules.image_embedders import CannyImageEncoder, DepthImageEncoder, ReduxImageEncoder\nfrom .util import PREFERED_KONTEXT_RESOLUTIONS\n\n\ndef get_noise(\n    num_samples: int,\n    height: int,\n    width: int,\n    device: torch.device,\n    dtype: torch.dtype,\n    seed: int,\n):\n    return torch.randn(\n        num_samples,\n        16,\n        # allow for packing\n        2 * math.ceil(height / 16),\n        2 * math.ceil(width / 16),\n        dtype=dtype,\n        generator=torch.Generator(device=\"cpu\").manual_seed(seed),\n    ).to(device)\n\n\ndef prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:\n    bs, c, h, w = img.shape\n    if bs == 1 and not isinstance(prompt, str):\n        bs = len(prompt)\n\n    img = rearrange(img, \"b c (h ph) (w pw) -> b (h w) (c ph pw)\", ph=2, pw=2)\n    if img.shape[0] == 1 and bs > 1:\n        img = repeat(img, \"1 ... -> bs ...\", bs=bs)\n\n    img_ids = torch.zeros(h // 2, w // 2, 3)\n    img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]\n    img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]\n    img_ids = repeat(img_ids, \"h w c -> b (h w) c\", b=bs)\n\n    if isinstance(prompt, str):\n        prompt = [prompt]\n    txt = t5(prompt)\n    if txt.shape[0] == 1 and bs > 1:\n        txt = repeat(txt, \"1 ... -> bs ...\", bs=bs)\n    txt_ids = torch.zeros(bs, txt.shape[1], 3)\n\n    vec = clip(prompt)\n    if vec.shape[0] == 1 and bs > 1:\n        vec = repeat(vec, \"1 ... -> bs ...\", bs=bs)\n\n    return {\n        \"img\": img,\n        \"img_ids\": img_ids.to(img.device),\n        \"txt\": txt.to(img.device),\n        \"txt_ids\": txt_ids.to(img.device),\n        \"vec\": vec.to(img.device),\n    }\n\n\ndef prepare_control(\n    t5: HFEmbedder,\n    clip: HFEmbedder,\n    img: Tensor,\n    prompt: str | list[str],\n    ae: AutoEncoder,\n    encoder: DepthImageEncoder | CannyImageEncoder,\n    img_cond_path: str,\n) -> dict[str, Tensor]:\n    # load and encode the conditioning image\n    bs, _, h, w = img.shape\n    if bs == 1 and not isinstance(prompt, str):\n        bs = len(prompt)\n\n    img_cond = Image.open(img_cond_path).convert(\"RGB\")\n\n    width = w * 8\n    height = h * 8\n    img_cond = img_cond.resize((width, height), Image.Resampling.LANCZOS)\n    img_cond = np.array(img_cond)\n    img_cond = torch.from_numpy(img_cond).float() / 127.5 - 1.0\n    img_cond = rearrange(img_cond, \"h w c -> 1 c h w\")\n\n    with torch.no_grad():\n        img_cond = encoder(img_cond)\n        img_cond = ae.encode(img_cond)\n\n    img_cond = img_cond.to(torch.bfloat16)\n    img_cond = rearrange(img_cond, \"b c (h ph) (w pw) -> b (h w) (c ph pw)\", ph=2, pw=2)\n    if img_cond.shape[0] == 1 and bs > 1:\n        img_cond = repeat(img_cond, \"1 ... -> bs ...\", bs=bs)\n\n    return_dict = prepare(t5, clip, img, prompt)\n    return_dict[\"img_cond\"] = img_cond\n    return return_dict\n\n\ndef prepare_fill(\n    t5: HFEmbedder,\n    clip: HFEmbedder,\n    img: Tensor,\n    prompt: str | list[str],\n    ae: AutoEncoder,\n    img_cond_path: str,\n    mask_path: str,\n) -> dict[str, Tensor]:\n    # load and encode the conditioning image and the mask\n    bs, _, _, _ = img.shape\n    if bs == 1 and not isinstance(prompt, str):\n        bs = len(prompt)\n\n    img_cond = Image.open(img_cond_path).convert(\"RGB\")\n    img_cond = np.array(img_cond)\n    img_cond = torch.from_numpy(img_cond).float() / 127.5 - 1.0\n    img_cond = rearrange(img_cond, \"h w c -> 1 c h w\")\n\n    mask = Image.open(mask_path).convert(\"L\")\n    mask = np.array(mask)\n    mask = torch.from_numpy(mask).float() / 255.0\n    mask = rearrange(mask, \"h w -> 1 1 h w\")\n\n    with torch.no_grad():\n        img_cond = img_cond.to(img.device)\n        mask = mask.to(img.device)\n        img_cond = img_cond * (1 - mask)\n        img_cond = ae.encode(img_cond)\n        mask = mask[:, 0, :, :]\n        mask = mask.to(torch.bfloat16)\n        mask = rearrange(\n            mask,\n            \"b (h ph) (w pw) -> b (ph pw) h w\",\n            ph=8,\n            pw=8,\n        )\n        mask = rearrange(mask, \"b c (h ph) (w pw) -> b (h w) (c ph pw)\", ph=2, pw=2)\n        if mask.shape[0] == 1 and bs > 1:\n            mask = repeat(mask, \"1 ... -> bs ...\", bs=bs)\n\n    img_cond = img_cond.to(torch.bfloat16)\n    img_cond = rearrange(img_cond, \"b c (h ph) (w pw) -> b (h w) (c ph pw)\", ph=2, pw=2)\n    if img_cond.shape[0] == 1 and bs > 1:\n        img_cond = repeat(img_cond, \"1 ... -> bs ...\", bs=bs)\n\n    img_cond = torch.cat((img_cond, mask), dim=-1)\n\n    return_dict = prepare(t5, clip, img, prompt)\n    return_dict[\"img_cond\"] = img_cond.to(img.device)\n    return return_dict\n\n\ndef prepare_redux(\n    t5: HFEmbedder,\n    clip: HFEmbedder,\n    img: Tensor,\n    prompt: str | list[str],\n    encoder: ReduxImageEncoder,\n    img_cond_path: str,\n) -> dict[str, Tensor]:\n    bs, _, h, w = img.shape\n    if bs == 1 and not isinstance(prompt, str):\n        bs = len(prompt)\n\n    img_cond = Image.open(img_cond_path).convert(\"RGB\")\n    with torch.no_grad():\n        img_cond = encoder(img_cond)\n\n    img_cond = img_cond.to(torch.bfloat16)\n    if img_cond.shape[0] == 1 and bs > 1:\n        img_cond = repeat(img_cond, \"1 ... -> bs ...\", bs=bs)\n\n    img = rearrange(img, \"b c (h ph) (w pw) -> b (h w) (c ph pw)\", ph=2, pw=2)\n    if img.shape[0] == 1 and bs > 1:\n        img = repeat(img, \"1 ... -> bs ...\", bs=bs)\n\n    img_ids = torch.zeros(h // 2, w // 2, 3)\n    img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]\n    img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]\n    img_ids = repeat(img_ids, \"h w c -> b (h w) c\", b=bs)\n\n    if isinstance(prompt, str):\n        prompt = [prompt]\n    txt = t5(prompt)\n    txt = torch.cat((txt, img_cond.to(txt)), dim=-2)\n    if txt.shape[0] == 1 and bs > 1:\n        txt = repeat(txt, \"1 ... -> bs ...\", bs=bs)\n    txt_ids = torch.zeros(bs, txt.shape[1], 3)\n\n    vec = clip(prompt)\n    if vec.shape[0] == 1 and bs > 1:\n        vec = repeat(vec, \"1 ... -> bs ...\", bs=bs)\n\n    return {\n        \"img\": img,\n        \"img_ids\": img_ids.to(img.device),\n        \"txt\": txt.to(img.device),\n        \"txt_ids\": txt_ids.to(img.device),\n        \"vec\": vec.to(img.device),\n    }\n\n\ndef prepare_kontext(\n    t5: HFEmbedder,\n    clip: HFEmbedder,\n    prompt: str | list[str],\n    ae: AutoEncoder,\n    img_cond_path: str,\n    seed: int,\n    device: torch.device,\n    target_width: int | None = None,\n    target_height: int | None = None,\n    bs: int = 1,\n) -> tuple[dict[str, Tensor], int, int]:\n    # load and encode the conditioning image\n    if bs == 1 and not isinstance(prompt, str):\n        bs = len(prompt)\n\n    img_cond = Image.open(img_cond_path).convert(\"RGB\")\n    width, height = img_cond.size\n    aspect_ratio = width / height\n    # Kontext is trained on specific resolutions, using one of them is recommended\n    _, width, height = min((abs(aspect_ratio - w / h), w, h) for w, h in PREFERED_KONTEXT_RESOLUTIONS)\n    width = 2 * int(width / 16)\n    height = 2 * int(height / 16)\n\n    img_cond = img_cond.resize((8 * width, 8 * height), Image.Resampling.LANCZOS)\n    img_cond = np.array(img_cond)\n    img_cond = torch.from_numpy(img_cond).float() / 127.5 - 1.0\n    img_cond = rearrange(img_cond, \"h w c -> 1 c h w\")\n    img_cond_orig = img_cond.clone()\n\n    with torch.no_grad():\n        img_cond = ae.encode(img_cond.to(device))\n\n    img_cond = img_cond.to(torch.bfloat16)\n    img_cond = rearrange(img_cond, \"b c (h ph) (w pw) -> b (h w) (c ph pw)\", ph=2, pw=2)\n    if img_cond.shape[0] == 1 and bs > 1:\n        img_cond = repeat(img_cond, \"1 ... -> bs ...\", bs=bs)\n\n    # image ids are the same as base image with the first dimension set to 1\n    # instead of 0\n    img_cond_ids = torch.zeros(height // 2, width // 2, 3)\n    img_cond_ids[..., 0] = 1\n    img_cond_ids[..., 1] = img_cond_ids[..., 1] + torch.arange(height // 2)[:, None]\n    img_cond_ids[..., 2] = img_cond_ids[..., 2] + torch.arange(width // 2)[None, :]\n    img_cond_ids = repeat(img_cond_ids, \"h w c -> b (h w) c\", b=bs)\n\n    if target_width is None:\n        target_width = 8 * width\n    if target_height is None:\n        target_height = 8 * height\n\n    img = get_noise(\n        1,\n        target_height,\n        target_width,\n        device=device,\n        dtype=torch.bfloat16,\n        seed=seed,\n    )\n\n    return_dict = prepare(t5, clip, img, prompt)\n    return_dict[\"img_cond_seq\"] = img_cond\n    return_dict[\"img_cond_seq_ids\"] = img_cond_ids.to(device)\n    return_dict[\"img_cond_orig\"] = img_cond_orig\n    return return_dict, target_height, target_width\n\n\ndef time_shift(mu: float, sigma: float, t: Tensor):\n    return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)\n\n\ndef get_lin_function(\n    x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15\n) -> Callable[[float], float]:\n    m = (y2 - y1) / (x2 - x1)\n    b = y1 - m * x1\n    return lambda x: m * x + b\n\n\ndef get_schedule(\n    num_steps: int,\n    image_seq_len: int,\n    base_shift: float = 0.5,\n    max_shift: float = 1.15,\n    shift: bool = True,\n) -> list[float]:\n    # extra step for zero\n    timesteps = torch.linspace(1, 0, num_steps + 1)\n\n    # shifting the schedule to favor high timesteps for higher signal images\n    if shift:\n        # estimate mu based on linear estimation between two points\n        mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)\n        timesteps = time_shift(mu, 1.0, timesteps)\n\n    return timesteps.tolist()\n\n\ndef denoise(\n    model: Flux,\n    # model input\n    img: Tensor,\n    img_ids: Tensor,\n    txt: Tensor,\n    txt_ids: Tensor,\n    vec: Tensor,\n    # sampling parameters\n    timesteps: list[float],\n    guidance: float = 4.0,\n    # extra img tokens (channel-wise)\n    img_cond: Tensor | None = None,\n    # extra img tokens (sequence-wise)\n    img_cond_seq: Tensor | None = None,\n    img_cond_seq_ids: Tensor | None = None,\n):\n    # this is ignored for schnell\n    guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)\n    for t_curr, t_prev in zip(timesteps[:-1], timesteps[1:]):\n        t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)\n        img_input = img\n        img_input_ids = img_ids\n        if img_cond is not None:\n            img_input = torch.cat((img, img_cond), dim=-1)\n        if img_cond_seq is not None:\n            assert (\n                img_cond_seq_ids is not None\n            ), \"You need to provide either both or neither of the sequence conditioning\"\n            img_input = torch.cat((img_input, img_cond_seq), dim=1)\n            img_input_ids = torch.cat((img_input_ids, img_cond_seq_ids), dim=1)\n        pred = model(\n            img=img_input,\n            img_ids=img_input_ids,\n            txt=txt,\n            txt_ids=txt_ids,\n            y=vec,\n            timesteps=t_vec,\n            guidance=guidance_vec,\n        )\n        if img_input_ids is not None:\n            pred = pred[:, : img.shape[1]]\n\n        img = img + (t_prev - t_curr) * pred\n\n    return img\n\n\ndef unpack(x: Tensor, height: int, width: int) -> Tensor:\n    return rearrange(\n        x,\n        \"b (h w) (c ph pw) -> b c (h ph) (w pw)\",\n        h=math.ceil(height / 16),\n        w=math.ceil(width / 16),\n        ph=2,\n        pw=2,\n    )\n"
  },
  {
    "path": "src/flux/trt/__init__.py",
    "content": "from flux.trt.trt_config import ModuleName\nfrom flux.trt.trt_manager import TRTManager\n\n__all__ = [\"TRTManager\", \"ModuleName\"]\n"
  },
  {
    "path": "src/flux/trt/engine/__init__.py",
    "content": "#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom flux.trt.engine.base_engine import BaseEngine, Engine, SharedMemory\nfrom flux.trt.engine.clip_engine import CLIPEngine\nfrom flux.trt.engine.t5_engine import T5Engine\nfrom flux.trt.engine.transformer_engine import TransformerEngine\nfrom flux.trt.engine.vae_engine import VAEDecoder, VAEEncoder, VAEEngine\n\n__all__ = [\n    \"BaseEngine\",\n    \"Engine\",\n    \"SharedMemory\",\n    \"CLIPEngine\",\n    \"TransformerEngine\",\n    \"T5Engine\",\n    \"VAEEngine\",\n    \"VAEDecoder\",\n    \"VAEEncoder\",\n]\n"
  },
  {
    "path": "src/flux/trt/engine/base_engine.py",
    "content": "#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport gc\nfrom abc import ABC, abstractmethod\nfrom collections import OrderedDict\nfrom typing import Dict\n\nimport tensorrt as trt\nimport torch\nfrom polygraphy.backend.common import bytes_from_path\nfrom polygraphy.backend.trt import engine_from_bytes\n\nfrom flux.trt.trt_config import TRTBaseConfig\n\nTRT_LOGGER = trt.Logger(trt.Logger.ERROR)\n\n\nclass SharedMemory(object):\n    def __new__(cls, *args, **kwargs):\n        if not hasattr(cls, \"instance\"):\n            cls.instance = super(SharedMemory, cls).__new__(cls)\n            cls.instance.__init__(*args, **kwargs)\n        return cls.instance\n\n    def __init__(self, size: int, device=torch.device(\"cuda\")):\n        self.allocations = {}\n        self._buffer = torch.empty(\n            size,\n            dtype=torch.uint8,\n            device=device,\n            memory_format=torch.contiguous_format,\n        )\n\n    def resize(self, name: str, size: int):\n        self.allocations[name] = size\n        if max(self.allocations.values()) > self._buffer.numel():\n            self.buffer = self._buffer.resize_(size)\n            torch.cuda.empty_cache()\n\n    def reset(self, name: str):\n        self.allocations.pop(name)\n        new_max = max(self.allocations.values())\n        if new_max < self._buffer.numel():\n            self.buffer = self._buffer.resize_(new_max)\n            torch.cuda.empty_cache()\n\n    def deallocate(self):\n        del self._buffer\n        torch.cuda.empty_cache()\n        self._buffer = torch.empty(\n            1024,\n            dtype=torch.uint8,\n            device=\"cuda\",\n            memory_format=torch.contiguous_format,\n        )\n\n    @property\n    def shared_device_memory(self):\n        return self._buffer.data_ptr()\n\n    def __str__(self):\n        def human_readable_size(size):\n            for unit in [\"B\", \"KiB\", \"MiB\", \"GiB\"]:\n                if size < 1024.0:\n                    return size, unit\n                size /= 1024.0\n            return size, unit\n\n        allocations_str = []\n\n        for name, size_bytes in self.allocations.items():\n            size, unit = human_readable_size(size_bytes)\n            allocations_str.append(f\"\\t{name}: {size:.2f} {unit}\\n\")\n        allocations_output = \"\".join(allocations_str)\n\n        size, unit = human_readable_size(self._buffer.numel())\n        allocations_buffer = f\"{size:.2f} {unit}\"\n        return f\"Shared Memory Allocations: \\n{allocations_output} \\n\\tCurrent: {allocations_buffer}\"\n\n\nTRT_ALLOCATION_POLICY = {\"global\", \"dynamic\"}\nTRT_OFFLOAD_POLICY = \"cpu_buffer\"\n\n\nclass BaseEngine(ABC):\n    @staticmethod\n    def trt_datatype_to_torch(datatype):\n        datatype_mapping = {\n            trt.DataType.BOOL: torch.bool,\n            trt.DataType.UINT8: torch.uint8,\n            trt.DataType.INT8: torch.int8,\n            trt.DataType.INT32: torch.int32,\n            trt.DataType.INT64: torch.int64,\n            trt.DataType.HALF: torch.float16,\n            trt.DataType.FLOAT: torch.float32,\n            trt.DataType.BF16: torch.bfloat16,\n        }\n        if datatype not in datatype_mapping:\n            raise ValueError(f\"No PyTorch equivalent for TensorRT data type: {datatype}\")\n\n        return datatype_mapping[datatype]\n\n    @abstractmethod\n    def cpu(self) -> \"BaseEngine\":\n        pass\n\n    @abstractmethod\n    def cuda(self) -> \"BaseEngine\":\n        pass\n\n    @abstractmethod\n    def to(self, device: str | torch.device) -> \"BaseEngine\":\n        pass\n\n\nclass Engine(BaseEngine):\n    def __init__(\n        self,\n        trt_config: TRTBaseConfig,\n        stream: torch.cuda.Stream,\n        context_memory: SharedMemory | None = None,\n        allocation_policy: str = \"global\",\n    ):\n        self.trt_config = trt_config\n        self.stream = stream\n        self.context = None\n        self.tensors = OrderedDict()\n        self.context_memory = context_memory\n        self.device: torch.device = torch.device(\"cpu\")\n\n        if TRT_OFFLOAD_POLICY == \"cpu_buffer\":\n            self.engine: trt.ICudaEngine | bytes = None\n            self.cpu_engine_buffer: bytes = bytes_from_path(self.trt_config.engine_path)\n        else:\n            self.engine: trt.ICudaEngine | bytes = bytes_from_path(self.trt_config.engine_path)\n\n        assert allocation_policy in TRT_ALLOCATION_POLICY\n        self.allocation_policy = allocation_policy\n        self.current_input_hash = None\n        self.cuda_graph = None\n\n    @abstractmethod\n    def __call__(self, *args, **Kwargs) -> torch.Tensor | dict[str, torch.Tensor] | tuple[torch.Tensor]:\n        pass\n\n    def cpu(self) -> \"Engine\":\n        if self.device == torch.device(\"cpu\"):\n            return self\n        self.deactivate()\n        if TRT_OFFLOAD_POLICY == \"cpu_buffer\":\n            del self.engine\n            return self\n        self.engine = memoryview(self.engine.serialize())\n\n        return self\n\n    def cuda(self) -> \"Engine\":\n        if self.device == torch.device(\"cuda\"):\n            return self\n        buffer = self.cpu_engine_buffer if TRT_OFFLOAD_POLICY == \"cpu_buffer\" else self.engine\n        self.engine = engine_from_bytes(buffer)\n        gc.collect()\n        self.context = self.engine.create_execution_context_without_device_memory()\n        self.context_memory.resize(self.__class__.__name__, self.device_memory_size)\n        self.context.device_memory = self.context_memory.shared_device_memory\n        return self\n\n    def to(self, device: str | torch.device) -> \"Engine\":\n        if not isinstance(device, torch.device):\n            device = torch.device(device)\n        if self.device == device:\n            return self\n        if device == torch.device(\"cpu\"):\n            self.cpu()\n        else:\n            self.cuda()\n        self.device = device\n        return self\n\n    def deactivate(self):\n        del self.context\n        self.context = None\n\n    def allocate_buffers(\n        self,\n        shape_dict: dict[str, tuple],\n        device: str | torch.device = \"cuda\",\n    ):\n        for binding in range(self.engine.num_io_tensors):\n            tensor_name = self.engine.get_tensor_name(binding)\n            tensor_shape = shape_dict[tensor_name]\n\n            if tensor_name in self.tensors and self.tensors[tensor_name].shape == tensor_shape:\n                continue\n\n            if self.engine.get_tensor_mode(tensor_name) == trt.TensorIOMode.INPUT:\n                self.context.set_input_shape(tensor_name, tensor_shape)\n            tensor_dtype = self.trt_datatype_to_torch(self.engine.get_tensor_dtype(tensor_name))\n            tensor = torch.empty(\n                size=tensor_shape,\n                dtype=tensor_dtype,\n                memory_format=torch.contiguous_format,\n            ).to(device=device)\n            self.tensors[tensor_name] = tensor\n\n    def get_dtype(self, tensor_name: str):\n        return self.trt_datatype_to_torch(self.engine.get_tensor_dtype(tensor_name))\n\n    def override_shapes(self, feed_dict: Dict[str, torch.Tensor]):\n        for name, tensor in feed_dict.items():\n            shape = tensor.shape\n            assert tensor.dtype == self.trt_datatype_to_torch(self.engine.get_tensor_dtype(name)), (\n                f\"Debug: Mismatched data types for tensor '{name}'. \"\n                f\"Expected: {self.trt_datatype_to_torch(self.engine.get_tensor_dtype(name))}, \"\n                f\"Found: {tensor.dtype} \"\n                f\"in {self.__class__.__name__}\"\n            )\n            self.context.set_input_shape(name, shape)\n\n        assert self.context.all_binding_shapes_specified\n        self.context.infer_shapes()\n        for idx in range(self.engine.num_io_tensors):\n            name = self.engine.get_tensor_name(idx)\n            dtype = self.trt_datatype_to_torch(self.engine.get_tensor_dtype(name))\n            shape = self.context.get_tensor_shape(name)\n            if -1 in shape:\n                raise Exception(\"Unspecified shape identified for tensor {}: {} \".format(name, shape))\n            self.tensors[name] = torch.zeros(tuple(shape), dtype=dtype, device=self.device).contiguous()\n            self.context.set_tensor_address(name, self.tensors[name].data_ptr())\n\n        if self.allocation_policy == \"dynamic\":\n            self.context_memory.resize(self.__class__.__name__, self.device_memory_size)\n        self.current_input_hash = self.calculate_input_hash(feed_dict)\n\n    def deallocate_buffers(self):\n        if len(self.tensors) == 0:\n            return\n\n        del self.tensors\n        self.tensors = OrderedDict()\n        torch.cuda.empty_cache()\n\n    @property\n    def device_memory_size(self):\n        if self.allocation_policy == \"global\":\n            return self.engine.device_memory_size\n        else:\n            if not self.context.all_binding_shapes_specified:\n                return 0\n            return self.context.update_device_memory_size_for_shapes()\n\n    @staticmethod\n    def calculate_input_hash(feed_dict: Dict[str, torch.Tensor]):\n        return hash(tuple(feed_dict[key].shape for key in sorted(feed_dict.keys())))\n\n    def _capture_cuda_graph(self):\n        self.cuda_graph = torch.cuda.CUDAGraph()\n        s = torch.cuda.Stream()\n        with torch.cuda.graph(self.cuda_graph, stream=s):\n            noerror = self.context.execute_async_v3(s.cuda_stream)\n            if not noerror:\n                raise ValueError(\"ERROR: inference failed.\")\n\n        # self.cuda_graph.replay()\n\n    def infer(\n        self,\n        feed_dict: dict[str, torch.Tensor],\n    ):\n        if self.current_input_hash != self.calculate_input_hash(feed_dict):\n            self.override_shapes(feed_dict)\n\n        self.context.device_memory = self.context_memory.shared_device_memory\n        for name, tensor in feed_dict.items():\n            self.tensors[name].copy_(tensor, non_blocking=True)\n\n        noerror = self.context.execute_async_v3(self.stream.cuda_stream)\n        if not noerror:\n            raise ValueError(\"ERROR: inference failed.\")\n\n        return self.tensors\n\n    def __str__(self):\n        if self.engine is None:\n            return \"Engine has not been initialized\"\n        out = \"\"\n        for idx in range(self.engine.num_io_tensors):\n            name = self.engine.get_tensor_name(idx)\n            mode = self.engine.get_tensor_mode(name)\n            dtype = self.trt_datatype_to_torch(self.engine.get_tensor_dtype(name))\n            shape = self.engine.get_tensor_shape(name)\n            out += f\"\\t{mode.name}: {name}={shape} {dtype.__str__()}\\n\"\n        return out\n"
  },
  {
    "path": "src/flux/trt/engine/clip_engine.py",
    "content": "#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nfrom transformers import CLIPTokenizer\n\nfrom flux.trt.engine import Engine\nfrom flux.trt.trt_config import ClipConfig\n\n\nclass CLIPEngine(Engine):\n    def __init__(self, trt_config: ClipConfig, stream: torch.cuda.Stream, **kwargs):\n        super().__init__(trt_config=trt_config, stream=stream, **kwargs)\n        self.tokenizer = CLIPTokenizer.from_pretrained(\n            \"openai/clip-vit-large-patch14\",\n            max_length=self.trt_config.text_maxlen,\n        )\n\n    @torch.inference_mode()\n    def __call__(\n        self,\n        prompt: list[str],\n    ) -> torch.Tensor:\n        with torch.inference_mode():\n            feed_dict = self.tokenizer(\n                prompt,\n                truncation=True,\n                max_length=self.trt_config.text_maxlen,\n                return_length=False,\n                return_overflowing_tokens=False,\n                padding=\"max_length\",\n                return_tensors=\"pt\",\n            )\n            feed_dict = {\"input_ids\": feed_dict[\"input_ids\"].to(dtype=self.get_dtype(\"input_ids\"))}\n\n            pooled_embeddings = self.infer(feed_dict)[\"pooled_embeddings\"]\n\n        return pooled_embeddings\n"
  },
  {
    "path": "src/flux/trt/engine/t5_engine.py",
    "content": "#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nfrom transformers import T5Tokenizer\n\nfrom flux.trt.engine import Engine\nfrom flux.trt.trt_config import T5Config\n\n\nclass T5Engine(Engine):\n    def __init__(self, trt_config: T5Config, stream: torch.cuda.Stream, **kwargs):\n        super().__init__(trt_config=trt_config, stream=stream, **kwargs)\n        self.tokenizer = T5Tokenizer.from_pretrained(\n            \"google/t5-v1_1-xxl\",\n            max_length=self.trt_config.text_maxlen,\n        )\n\n    @torch.inference_mode()\n    def __call__(\n        self,\n        prompt: list[str],\n    ) -> torch.Tensor:\n        with torch.inference_mode():\n            feed_dict = self.tokenizer(\n                prompt,\n                truncation=True,\n                max_length=self.trt_config.text_maxlen,\n                return_length=False,\n                return_overflowing_tokens=False,\n                padding=\"max_length\",\n                return_tensors=\"pt\",\n            )\n            feed_dict = {\"input_ids\": feed_dict[\"input_ids\"].to(dtype=self.get_dtype(\"input_ids\"))}\n\n            text_embeddings = self.infer(feed_dict)[\"text_embeddings\"]\n\n        return text_embeddings\n"
  },
  {
    "path": "src/flux/trt/engine/transformer_engine.py",
    "content": "#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\n\nfrom flux.trt.engine import Engine\nfrom flux.trt.trt_config import TransformerConfig\n\n\nclass TransformerEngine(Engine):\n    __dd_to_flux__ = {\n        \"hidden_states\": \"img\",\n        \"img_ids\": \"img_ids\",\n        \"encoder_hidden_states\": \"txt\",\n        \"pooled_projections\": \"y\",\n        \"txt_ids\": \"txt_ids\",\n        \"timestep\": \"timesteps\",\n        \"guidance\": \"guidance\",\n        \"latent\": \"latent\",\n    }\n\n    __flux_to_dd__ = {\n        \"img\": \"hidden_states\",\n        \"img_ids\": \"img_ids\",\n        \"txt\": \"encoder_hidden_states\",\n        \"y\": \"pooled_projections\",\n        \"txt_ids\": \"txt_ids\",\n        \"timesteps\": \"timestep\",\n        \"guidance\": \"guidance\",\n        \"latent\": \"latent\",\n    }\n\n    def __init__(self, trt_config: TransformerConfig, stream: torch.cuda.Stream, **kwargs):\n        super().__init__(trt_config=trt_config, stream=stream, **kwargs)\n\n    @property\n    def dd_to_flux(self):\n        return TransformerEngine.__dd_to_flux__\n\n    @property\n    def flux_to_dd(self):\n        return TransformerEngine.__flux_to_dd__\n\n    @torch.inference_mode()\n    def __call__(\n        self,\n        **kwargs,\n    ) -> torch.Tensor:\n        feed_dict = {}\n\n        if self.trt_config.model_name == \"flux-schnell\":\n            # remove guidance\n            kwargs.pop(\"guidance\")\n\n        for tensor_name, tensor_value in kwargs.items():\n            if tensor_name == \"latent\":\n                continue\n            dd_name = self.flux_to_dd[tensor_name]\n            feed_dict[dd_name] = tensor_value.to(dtype=self.get_dtype(dd_name))\n\n        # remove batch dim to match demo-diffusion\n        feed_dict[\"img_ids\"] = feed_dict[\"img_ids\"][0]\n        feed_dict[\"txt_ids\"] = feed_dict[\"txt_ids\"][0]\n\n        latent = self.infer(feed_dict=feed_dict)[\"latent\"]\n\n        return latent\n"
  },
  {
    "path": "src/flux/trt/engine/vae_engine.py",
    "content": "#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\n\nfrom flux.trt.engine.base_engine import BaseEngine, Engine\nfrom flux.trt.trt_config import VAEDecoderConfig, VAEEncoderConfig\n\n\nclass VAEDecoder(Engine):\n    def __init__(self, trt_config: VAEDecoderConfig, stream: torch.cuda.Stream, **kwargs):\n        super().__init__(trt_config=trt_config, stream=stream, **kwargs)\n\n    @torch.inference_mode()\n    def __call__(\n        self,\n        z: torch.Tensor,\n    ) -> torch.Tensor:\n        z = z.to(dtype=self.get_dtype(\"latent\"))\n        z = (z / self.trt_config.scale_factor) + self.trt_config.shift_factor\n        feed_dict = {\"latent\": z}\n        images = self.infer(feed_dict=feed_dict)[\"images\"]\n        return images\n\n\nclass VAEEncoder(Engine):\n    def __init__(self, trt_config: VAEEncoderConfig, stream: torch.cuda.Stream, **kwargs):\n        super().__init__(trt_config=trt_config, stream=stream, **kwargs)\n\n    @torch.inference_mode()\n    def __call__(\n        self,\n        x: torch.Tensor,\n    ) -> torch.Tensor:\n        feed_dict = {\"images\": x.to(dtype=self.get_dtype(\"images\"))}\n        latent = self.infer(feed_dict=feed_dict)[\"latent\"]\n        latent = self.trt_config.scale_factor * (latent - self.trt_config.shift_factor)\n        return latent\n\n\nclass VAEEngine(BaseEngine):\n    def __init__(\n        self,\n        decoder: VAEDecoder,\n        encoder: VAEEncoder | None = None,\n    ):\n        super().__init__()\n        self.decoder = decoder\n        self.encoder = encoder\n\n    def decode(self, z: torch.Tensor) -> torch.Tensor:\n        return self.decoder(z)\n\n    def encode(self, x: torch.Tensor) -> torch.Tensor:\n        assert self.encoder is not None, \"An encoder is needed to encode an image\"\n        return self.encoder(x)\n\n    def cpu(self):\n        self.decoder = self.decoder.cpu()\n        if self.encoder is not None:\n            self.encoder = self.encoder.cpu()\n        return self\n\n    def cuda(self):\n        self.decoder = self.decoder.cuda()\n        if self.encoder is not None:\n            self.encoder = self.encoder.cuda()\n        return self\n\n    def to(self, device):\n        self.decoder = self.decoder.to(device)\n        if self.encoder is not None:\n            self.encoder = self.encoder.to(device)\n        return self\n\n    @property\n    def device_memory_size(self):\n        device_memory = self.decoder.device_memory_size\n        if self.encoder is not None:\n            device_memory = max(device_memory, self.encoder.device_memory_size)\n        return device_memory\n"
  },
  {
    "path": "src/flux/trt/trt_config/__init__.py",
    "content": "#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom flux.trt.trt_config.base_trt_config import ModuleName, TRTBaseConfig, get_config, register_config\nfrom flux.trt.trt_config.clip_trt_config import ClipConfig\nfrom flux.trt.trt_config.t5_trt_config import T5Config\nfrom flux.trt.trt_config.transformer_trt_config import TransformerConfig\nfrom flux.trt.trt_config.vae_trt_config import VAEDecoderConfig, VAEEncoderConfig\n\n__all__ = [\n    \"register_config\",\n    \"get_config\",\n    \"ModuleName\",\n    \"TRTBaseConfig\",\n    \"ClipConfig\",\n    \"T5Config\",\n    \"TransformerConfig\",\n    \"VAEDecoderConfig\",\n    \"VAEEncoderConfig\",\n]\n"
  },
  {
    "path": "src/flux/trt/trt_config/base_trt_config.py",
    "content": "#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport subprocess\nfrom abc import abstractmethod\nfrom collections import defaultdict\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom typing import Any\n\nfrom colored import fore, style\nfrom huggingface_hub import snapshot_download\nfrom tensorrt import __version__ as trt_version\n\n\nclass ModuleName(Enum):\n    CLIP = \"clip\"\n    T5 = \"t5\"\n    TRANSFORMER = \"transformer\"\n    VAE = \"vae\"\n    VAE_ENCODER = \"vae_encoder\"\n\n\nregistry = {}\n\n\n@dataclass\nclass TRTBaseConfig:\n    engine_dir: str\n    precision: str\n    trt_verbose: bool\n    trt_static_batch: bool\n    trt_static_shape: bool\n    model_name: str\n    module_name: ModuleName\n    onnx_path: str = field(init=False)\n    engine_path: str = field(init=False)\n    trt_tf32: bool\n    trt_bf16: bool\n    trt_fp8: bool\n    trt_fp4: bool\n    trt_build_strongly_typed: bool\n    custom_onnx_path: str | None = None\n    trt_update_output_names: list[str] | None = None\n    trt_enable_all_tactics: bool = False\n    trt_timing_cache: str | None = None\n    trt_native_instancenorm: bool = True\n    trt_builder_optimization_level: int = 3\n    trt_precision_constraints: str = \"none\"\n\n    min_batch: int = 1\n    max_batch: int = 4\n\n    @staticmethod\n    def build_trt_engine(\n        engine_path: str,\n        onnx_path: str,\n        strongly_typed=False,\n        tf32=True,\n        bf16=False,\n        fp8=False,\n        fp4=False,\n        input_profile: dict[str, Any] | None = None,\n        update_output_names: list[str] | None = None,\n        enable_refit=False,\n        enable_all_tactics=False,\n        timing_cache: str | None = None,\n        native_instancenorm=True,\n        builder_optimization_level=3,\n        precision_constraints=\"none\",\n        verbose=False,\n    ):\n        \"\"\"\n        Metod used to build a TRT engine from a given set of flags or configurations using polygraphy.\n\n        Args:\n            engine_path (str): Output path used to store the build engine.\n            onnx_path (str): Path containing an onnx model used to generated the engine.\n            strongly_typed (bool): Flag indicating if the engine should be strongly typed.\n            tf32 (bool): Whether to build the engine with TF32 precision enabled.\n            bf16 (bool): Whether to build the engine with BF16 precision enabled.\n            fp8 (bool): Whether to build the engine with FP8 precision enabled. Refer to plain dataype and do not interfer with quantization introduced by modelopt.\n            fp4 (bool): Whether to build the engine with FP4 precision enabled. Refer to plain dataype and do not interfer with quantization introduced by modelopt.\n            input_profile (dict[str, Any]): A set of optimization profiles to add to the configuration. Only needed for networks with dynamic input shapes.\n            update_output_names (list[str]): List of output names to use in the trt engines.\n            enable_refit (bool): Enables the engine to be refitted with new weights after it is built.\n            enable_all_tactics (bool): Enables TRT to leverage all tactics or not.\n            timing_cache (str): A path or file-like object from which to load a tactic timing cache.\n            native_instancenorm (bool): support of instancenorm plugin.\n            builder_optimization_level (int): The builder optimization level.\n            precision_constraints (str):  If set to \"obey\", require that layers execute in specified precisions. If set to \"prefer\", prefer that layers execute in specified precisions but allow TRT to fall back to other precisions if no implementation exists for the requested precision. Otherwise, precision constraints are ignored.\n            verbose (bool): Weather to support verbose output\n\n        Returns:\n            dict[str, Any]: A dictionary representing the input profile configuration.\n        \"\"\"\n        print(f\"Building TensorRT engine for {onnx_path}: {engine_path}\")\n\n        # Base command\n        build_command = [f\"polygraphy convert {onnx_path} --convert-to trt --output {engine_path}\"]\n\n        # Precision flags\n        build_args = [\n            \"--bf16\" if bf16 else \"\",\n            \"--tf32\" if tf32 else \"\",\n            \"--fp8\" if fp8 else \"\",\n            \"--fp4\" if fp4 else \"\",\n            \"--strongly-typed\" if strongly_typed else \"\",\n        ]\n\n        # Additional arguments\n        build_args.extend(\n            [\n                \"--refittable\" if enable_refit else \"\",\n                \"--tactic-sources\" if not enable_all_tactics else \"\",\n                \"--onnx-flags native_instancenorm\" if native_instancenorm else \"\",\n                f\"--builder-optimization-level {builder_optimization_level}\",\n                f\"--precision-constraints {precision_constraints}\",\n            ]\n        )\n\n        # Timing cache\n        if timing_cache:\n            build_args.extend([f\"--load-timing-cache {timing_cache}\", f\"--save-timing-cache {timing_cache}\"])\n\n        # Verbosity setting\n        verbosity = \"extra_verbose\" if verbose else \"error\"\n        build_args.append(f\"--verbosity {verbosity}\")\n\n        # Output names\n        if update_output_names:\n            print(f\"Updating network outputs to {update_output_names}\")\n            build_args.append(f\"--trt-outputs {' '.join(update_output_names)}\")\n\n        # Input profiles\n        if input_profile:\n            profile_args = defaultdict(str)\n            for name, dims in input_profile.items():\n                assert len(dims) == 3\n                profile_args[\"--trt-min-shapes\"] += f\"{name}:{str(list(dims[0])).replace(' ', '')} \"\n                profile_args[\"--trt-opt-shapes\"] += f\"{name}:{str(list(dims[1])).replace(' ', '')} \"\n                profile_args[\"--trt-max-shapes\"] += f\"{name}:{str(list(dims[2])).replace(' ', '')} \"\n\n            build_args.extend(f\"{k} {v}\" for k, v in profile_args.items())\n\n        # Filter out empty strings and join command\n        build_args = [arg for arg in build_args if arg]\n        final_command = \" \\\\\\n\".join(build_command + build_args)\n\n        # Execute command with improved error handling\n        try:\n            print(f\"Engine build command:{fore('yellow')}\\n{final_command}\\n{style('reset')}\")\n            subprocess.run(final_command, check=True, shell=True)\n        except subprocess.CalledProcessError as exc:\n            error_msg = f\"Failed to build TensorRT engine. Error details:\\nCommand: {exc.cmd}\\n\"\n            raise RuntimeError(error_msg) from exc\n\n    @classmethod\n    @abstractmethod\n    def from_args(cls, model_name: str, *args, **kwargs) -> Any:\n        raise NotImplementedError(\"Factory method is missing\")\n\n    @abstractmethod\n    def get_input_profile(\n        self,\n        batch_size: int,\n        image_height: int | None,\n        image_width: int | None,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Generate max and min shape that each input of a TRT engine can have.\n\n        Subclasses must implement this method to return a dictionary that defines\n        the input profile based on the provided parameters. The input profile typically\n        includes details such as the expected shape of input tensors, whether the batch size\n        or image dimensions are fixed, and any additional configuration required by the\n        data processing or model inference pipeline.\n\n        Args:\n            batch_size (int): The number of images per batch.\n            image_height (int): Default height of each image in pixels.\n            image_width (int): Defailt width of each image in pixels.\n            static_batch (bool): Flag indicating if the batch size is fixed (static).\n            static_shape (bool): Flag indicating if the image dimensions are fixed (static).\n\n        Returns:\n            dict[str, Any]: A dictionary representing the input profile configuration.\n\n        Raises:\n            NotImplementedError: If the subclass does not override this abstract method.\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def check_dims(self, *args, **kwargs) -> None | tuple[int, int] | int:\n        \"\"\"helper function that check the dimentions associated to each input of a TRT engine\"\"\"\n        pass\n\n    def _check_batch(self, batch_size):\n        assert (\n            self.min_batch <= batch_size <= self.max_batch\n        ), f\"Batch size {batch_size} must be between {self.min_batch} and {self.max_batch}\"\n\n    def __post_init__(self):\n        self.onnx_path = self._get_onnx_path()\n        self.engine_path = self._get_engine_path()\n        assert os.path.isfile(self.onnx_path), \"onnx_path do not exists: {}\".format(self.onnx_path)\n\n    def _get_onnx_path(self) -> str:\n        if self.custom_onnx_path:\n            return self.custom_onnx_path\n\n        repo_id = self._get_repo_id(self.model_name)\n        snapshot_path = snapshot_download(repo_id, allow_patterns=[f\"{self.module_name.value}.opt/*\"])\n        onnx_model_path = os.path.join(snapshot_path, f\"{self.module_name.value}.opt/model.onnx\")\n        return onnx_model_path\n\n    def _get_engine_path(self) -> str:\n        return os.path.join(\n            self.engine_dir,\n            self.model_name,\n            f\"{self.module_name.value}_{self.precision}.trt_{trt_version}.plan\",\n        )\n\n    @staticmethod\n    def _get_repo_id(model_name: str) -> str:\n        if model_name == \"flux-dev\":\n            return \"black-forest-labs/FLUX.1-dev-onnx\"\n        elif model_name == \"flux-schnell\":\n            return \"black-forest-labs/FLUX.1-schnell-onnx\"\n        elif model_name == \"flux-dev-canny\":\n            return \"black-forest-labs/FLUX.1-Canny-dev-onnx\"\n        elif model_name == \"flux-dev-depth\":\n            return \"black-forest-labs/FLUX.1-Depth-dev-onnx\"\n        elif model_name == \"flux-dev-kontext\":\n            return \"black-forest-labs/FLUX.1-Kontext-dev-onnx\"\n        else:\n            raise ValueError(f\"Unknown model name: {model_name}\")\n\n\ndef register_config(module_name: ModuleName, precision: str):\n    \"\"\"Decorator to register a configuration class with specific flag conditions.\"\"\"\n\n    def decorator(cls):\n        key = f\"module={module_name.value}_dtype={precision}\"\n        registry[key] = cls\n        return cls\n\n    return decorator\n\n\ndef get_config(module_name: ModuleName, precision: str) -> TRTBaseConfig:\n    \"\"\"Retrieve the appropriate configuration instance based on current flags.\"\"\"\n    key = f\"module={module_name.value}_dtype={precision}\"\n    return registry[key]\n"
  },
  {
    "path": "src/flux/trt/trt_config/clip_trt_config.py",
    "content": "#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom dataclasses import dataclass\n\nfrom flux.trt.trt_config.base_trt_config import ModuleName, TRTBaseConfig, register_config\nfrom flux.util import configs\n\n\n@register_config(module_name=ModuleName.CLIP, precision=\"bf16\")\n@dataclass\nclass ClipConfig(TRTBaseConfig):\n    text_maxlen: int | None = None\n    hidden_size: int | None = None\n    trt_tf32: bool = True\n    trt_bf16: bool = False\n    trt_fp8: bool = False\n    trt_fp4: bool = False\n    trt_build_strongly_typed: bool = True\n\n    @classmethod\n    def from_args(\n        cls,\n        model_name: str,\n        **kwargs,\n    ):\n        return cls(\n            text_maxlen=77,\n            hidden_size=configs[model_name].params.vec_in_dim,\n            model_name=model_name,\n            module_name=ModuleName.CLIP,\n            **kwargs,\n        )\n\n    def check_dims(self, batch_size: int) -> None:\n        self._check_batch(batch_size)\n\n    def get_input_profile(\n        self,\n        batch_size: int,\n        image_height=None,\n        image_width=None,\n    ):\n        min_batch = batch_size if self.trt_static_batch else self.min_batch\n        max_batch = batch_size if self.trt_static_batch else self.max_batch\n\n        self.check_dims(batch_size)\n        return {\n            \"input_ids\": [\n                (min_batch, self.text_maxlen),\n                (batch_size, self.text_maxlen),\n                (max_batch, self.text_maxlen),\n            ]\n        }\n"
  },
  {
    "path": "src/flux/trt/trt_config/t5_trt_config.py",
    "content": "#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nfrom dataclasses import dataclass\n\nfrom huggingface_hub import snapshot_download\n\nfrom flux.trt.trt_config.base_trt_config import ModuleName, TRTBaseConfig, register_config\nfrom flux.util import configs\n\n\n@register_config(module_name=ModuleName.T5, precision=\"bf16\")\n@register_config(module_name=ModuleName.T5, precision=\"fp8\")\n@dataclass\nclass T5Config(TRTBaseConfig):\n    text_maxlen: int | None = None\n    hidden_size: int | None = None\n\n    trt_tf32: bool = True\n    trt_bf16: bool = False\n    trt_fp8: bool = False\n    trt_fp4: bool = False\n    trt_build_strongly_typed: bool = True\n\n    @classmethod\n    def from_args(\n        cls,\n        model_name: str,\n        **kwargs,\n    ):\n        return cls(\n            text_maxlen=256 if model_name == \"flux-schnell\" else 512,\n            hidden_size=configs[model_name].params.context_in_dim,\n            model_name=model_name,\n            module_name=ModuleName.T5,\n            **kwargs,\n        )\n\n    def check_dims(self, batch_size: int) -> None:\n        self._check_batch(batch_size)\n\n    def get_input_profile(\n        self,\n        batch_size: int,\n        image_height=None,\n        image_width=None,\n    ):\n        min_batch = batch_size if self.trt_static_batch else self.min_batch\n        max_batch = batch_size if self.trt_static_batch else self.max_batch\n\n        self.check_dims(batch_size)\n        return {\n            \"input_ids\": [\n                (min_batch, self.text_maxlen),\n                (batch_size, self.text_maxlen),\n                (max_batch, self.text_maxlen),\n            ]\n        }\n\n    def _get_onnx_path(self) -> str:\n        if self.custom_onnx_path:\n            return self.custom_onnx_path\n\n        if self.precision == \"fp8\":\n            repo_id = self._get_repo_id(self.model_name)\n            snapshot_path = snapshot_download(repo_id, allow_patterns=[\"t5-fp8.opt/*\"])\n            onnx_model_path = os.path.join(snapshot_path, \"t5-fp8.opt/model.onnx\")\n            return onnx_model_path\n\n        else:\n            return super()._get_onnx_path()\n"
  },
  {
    "path": "src/flux/trt/trt_config/transformer_trt_config.py",
    "content": "#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport os\nimport warnings\nfrom dataclasses import dataclass, field\nfrom math import ceil\n\nfrom huggingface_hub import snapshot_download\n\nfrom flux.trt.trt_config.base_trt_config import ModuleName, TRTBaseConfig, register_config\nfrom flux.util import PREFERED_KONTEXT_RESOLUTIONS, configs\n\n\n@register_config(module_name=ModuleName.TRANSFORMER, precision=\"bf16\")\n@register_config(module_name=ModuleName.TRANSFORMER, precision=\"fp8\")\n@register_config(module_name=ModuleName.TRANSFORMER, precision=\"fp4\")\n@dataclass\nclass TransformerConfig(TRTBaseConfig):\n    guidance_embed: bool | None = None\n    vec_in_dim: int | None = None\n    context_in_dim: int | None = None\n    in_channels: int | None = None\n    out_channels: int | None = None\n\n    min_image_shape: int | None = None\n    max_image_shape: int | None = None\n    default_image_shape: int = 1024\n    compression_factor: int = 8\n    text_maxlen: int | None = None\n\n    min_latent_dim: int = field(init=False)\n    max_latent_dim: int = field(init=False)\n\n    min_context_latent_dim: int = field(init=False)\n    max_context_latent_dim: int = field(init=False)\n\n    trt_tf32: bool = True\n    trt_bf16: bool = False\n    trt_fp8: bool = False\n    trt_fp4: bool = False\n    trt_build_strongly_typed: bool = True\n\n    @classmethod\n    def from_args(\n        cls,\n        model_name,\n        **kwargs,\n    ):\n        if model_name == \"flux-dev-kontext\" and kwargs[\"trt_static_shape\"]:\n            warnings.warn(\"Flux-dev-Kontext does not support static shapes for the encoder.\")\n            kwargs[\"trt_static_shape\"] = False\n\n        if model_name == \"flux-dev-kontext\":\n            min_image_shape = 1008\n            max_image_shape = 1040\n        else:\n            min_image_shape = 768\n            max_image_shape = 1360\n\n        return cls(\n            model_name=model_name,\n            module_name=ModuleName.TRANSFORMER,\n            guidance_embed=configs[model_name].params.guidance_embed,\n            vec_in_dim=configs[model_name].params.vec_in_dim,\n            context_in_dim=configs[model_name].params.context_in_dim,\n            in_channels=configs[model_name].params.in_channels,\n            out_channels=configs[model_name].params.out_channels,\n            text_maxlen=256 if model_name == \"flux-schnell\" else 512,\n            min_image_shape=min_image_shape,\n            max_image_shape=max_image_shape,\n            **kwargs,\n        )\n\n    def _get_onnx_path(self) -> str:\n        if self.custom_onnx_path:\n            return self.custom_onnx_path\n\n        repo_id = self._get_repo_id(self.model_name)\n        typed_model_path = os.path.join(f\"{self.module_name.value}.opt\", self.precision)\n\n        snapshot_path = snapshot_download(repo_id, allow_patterns=[f\"{typed_model_path}/*\"])\n        onnx_model_path = os.path.join(snapshot_path, typed_model_path, \"model.onnx\")\n        return onnx_model_path\n\n    @staticmethod\n    def _get_latent(image_dim: int, compression_factor: int) -> int:\n        return ceil(image_dim / (2 * compression_factor))\n\n    @staticmethod\n    def _get_context_dim(\n        image_height: int,\n        image_width: int,\n        compression_factor: int,\n    ) -> int:\n        seq_len = TransformerConfig._get_latent(\n            image_dim=image_height,\n            compression_factor=compression_factor,\n        ) * TransformerConfig._get_latent(\n            image_dim=image_width,\n            compression_factor=compression_factor,\n        )\n\n        return seq_len\n\n    def __post_init__(self):\n        min_latent_dim = TransformerConfig._get_context_dim(\n            image_height=self.min_image_shape,\n            image_width=self.min_image_shape,\n            compression_factor=self.compression_factor,\n        )\n\n        max_latent_dim = TransformerConfig._get_context_dim(\n            image_height=self.max_image_shape,\n            image_width=self.max_image_shape,\n            compression_factor=self.compression_factor,\n        )\n\n        if self.model_name == \"flux-dev-kontext\":\n            # get min context size\n            _, min_context_height, min_context_width = min(\n                (w * h, w, h) for w, h in PREFERED_KONTEXT_RESOLUTIONS\n            )\n            self.min_context_latent_dim = TransformerConfig._get_context_dim(\n                image_height=min_context_height,\n                image_width=min_context_width,\n                compression_factor=self.compression_factor,\n            )\n\n            # get max context size\n            _, max_context_height, max_context_width = max(\n                (w * h, w, h) for w, h in PREFERED_KONTEXT_RESOLUTIONS\n            )\n            self.max_context_latent_dim = TransformerConfig._get_context_dim(\n                image_height=max_context_height,\n                image_width=max_context_width,\n                compression_factor=self.compression_factor,\n            )\n        else:\n            self.min_context_latent_dim = 0\n            self.max_context_latent_dim = 0\n\n        self.min_latent_dim = min_latent_dim + self.min_context_latent_dim\n        self.max_latent_dim = max_latent_dim + self.max_context_latent_dim\n\n        super().__post_init__()\n\n    def get_minmax_dims(\n        self,\n        batch_size: int,\n        image_height: int,\n        image_width: int,\n    ):\n        min_batch = batch_size if self.trt_static_batch else self.min_batch\n        max_batch = batch_size if self.trt_static_batch else self.max_batch\n\n        # if a model has context: it is always dynamic. target image can be static\n        # or dynamic for every-model\n        min_latent_dim = (\n            self._get_context_dim(\n                image_height=image_height,\n                image_width=image_width,\n                compression_factor=self.compression_factor,\n            )\n            + self.min_context_latent_dim\n        )\n        max_latent_dim = (\n            self._get_context_dim(\n                image_height=image_height,\n                image_width=image_width,\n                compression_factor=self.compression_factor,\n            )\n            + self.max_context_latent_dim\n        )\n\n        # static-shape affects only the target image size\n        min_latent_dim = min_latent_dim if self.trt_static_shape else self.min_latent_dim\n        max_latent_dim = max_latent_dim if self.trt_static_shape else self.max_latent_dim\n\n        return (min_batch, max_batch, min_latent_dim, max_latent_dim)\n\n    def check_dims(\n        self,\n        batch_size: int,\n        image_height: int,\n        image_width: int,\n    ) -> int:\n        self._check_batch(batch_size)\n        assert (\n            image_height % self.compression_factor == 0 or image_width % self.compression_factor == 0\n        ), f\"Image dimensions must be divisible by compression factor {self.compression_factor}\"\n\n        latent_dim = self._get_context_dim(\n            image_height=image_height,\n            image_width=image_width,\n            compression_factor=self.compression_factor,\n        )\n\n        if self.model_name == \"flux-dev-kontext\":\n            # for context models, it is assumed that the optimal context image shape is the same\n            # as target image shape\n            latent_dim = 2 * latent_dim\n\n        assert self.min_latent_dim <= latent_dim <= self.max_latent_dim, \"Image resolution out of boundaries.\"\n        return latent_dim\n\n    def get_input_profile(\n        self,\n        batch_size: int,\n        image_height: int | None,\n        image_width: int | None,\n    ) -> dict[str, list[tuple]]:\n        if self.model_name == \"flux-dev-kontext\":\n            assert not self.trt_static_shape, \"If Flux-dev-kontext then static_shape must be False.\"\n        else:\n            assert isinstance(image_height, int) and isinstance(\n                image_width, int\n            ), \"Only Flux-dev-kontext allows None image shape\"\n\n        image_height = self.default_image_shape if image_height is None else image_height\n        image_width = self.default_image_shape if image_width is None else image_width\n\n        opt_latent_dim = self.check_dims(\n            batch_size=batch_size,\n            image_height=image_height,\n            image_width=image_width,\n        )\n\n        (\n            min_batch,\n            max_batch,\n            min_latent_dim,\n            max_latent_dim,\n        ) = self.get_minmax_dims(\n            batch_size=batch_size,\n            image_height=image_height,\n            image_width=image_width,\n        )\n\n        input_profile = {\n            \"hidden_states\": [\n                (min_batch, min_latent_dim, self.in_channels),\n                (batch_size, opt_latent_dim, self.in_channels),\n                (max_batch, max_latent_dim, self.in_channels),\n            ],\n            \"encoder_hidden_states\": [\n                (min_batch, self.text_maxlen, self.context_in_dim),\n                (batch_size, self.text_maxlen, self.context_in_dim),\n                (max_batch, self.text_maxlen, self.context_in_dim),\n            ],\n            \"pooled_projections\": [\n                (min_batch, self.vec_in_dim),\n                (batch_size, self.vec_in_dim),\n                (max_batch, self.vec_in_dim),\n            ],\n            \"img_ids\": [\n                (min_latent_dim, 3),\n                (opt_latent_dim, 3),\n                (max_latent_dim, 3),\n            ],\n            \"txt_ids\": [\n                (self.text_maxlen, 3),\n                (self.text_maxlen, 3),\n                (self.text_maxlen, 3),\n            ],\n            \"timestep\": [(min_batch,), (batch_size,), (max_batch,)],\n        }\n\n        if self.guidance_embed:\n            input_profile[\"guidance\"] = [(min_batch,), (batch_size,), (max_batch,)]\n\n        return input_profile\n"
  },
  {
    "path": "src/flux/trt/trt_config/vae_trt_config.py",
    "content": "#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport warnings\nfrom dataclasses import dataclass, field\nfrom math import ceil\n\nfrom flux.trt.trt_config.base_trt_config import ModuleName, TRTBaseConfig, register_config\nfrom flux.util import configs\n\n\n@dataclass\nclass VAEBaseConfig(TRTBaseConfig):\n    z_channels: int | None = None\n    scale_factor: float | None = None\n    shift_factor: float | None = None\n\n    default_image_shape: int = 1024\n    compression_factor: int = 8\n    min_image_shape: int | None = None\n    max_image_shape: int | None = None\n\n    min_latent_shape: int = field(init=False)\n    max_latent_shape: int = field(init=False)\n\n    def _get_latent_dim(self, image_dim: int) -> int:\n        return 2 * ceil(image_dim / (2 * self.compression_factor))\n\n    def __post_init__(self):\n        self.min_latent_shape = self._get_latent_dim(self.min_image_shape)\n        self.max_latent_shape = self._get_latent_dim(self.max_image_shape)\n        super().__post_init__()\n\n    def check_dims(\n        self,\n        batch_size: int,\n        image_height: int,\n        image_width: int,\n    ) -> tuple[int, int]:\n        self._check_batch(batch_size)\n        assert (\n            image_height % self.compression_factor == 0 or image_width % self.compression_factor == 0\n        ), f\"Image dimensions must be divisible by compression factor {self.compression_factor}\"\n\n        latent_height = self._get_latent_dim(image_height)\n        latent_width = self._get_latent_dim(image_width)\n\n        assert (\n            self.min_latent_shape <= latent_height <= self.max_latent_shape\n        ), f\"Latent height {latent_height} must be between {self.min_latent_shape} and {self.max_latent_shape}\"\n        assert (\n            self.min_latent_shape <= latent_width <= self.max_latent_shape\n        ), f\"Latent width {latent_width} must be between {self.min_latent_shape} and {self.max_latent_shape}\"\n        return latent_height, latent_width\n\n\n@register_config(module_name=ModuleName.VAE, precision=\"bf16\")\n@dataclass\nclass VAEDecoderConfig(VAEBaseConfig):\n    trt_tf32: bool = True\n    trt_bf16: bool = True\n    trt_fp8: bool = False\n    trt_fp4: bool = False\n    trt_build_strongly_typed: bool = False\n\n    @classmethod\n    def from_args(\n        cls,\n        model_name: str,\n        **kwargs,\n    ):\n        if model_name == \"flux-dev-kontext\":\n            min_image_shape = 672\n            max_image_shape = 1568\n        else:\n            min_image_shape = 768\n            max_image_shape = 1360\n\n        return cls(\n            model_name=model_name,\n            module_name=ModuleName.VAE,\n            z_channels=configs[model_name].ae_params.z_channels,\n            scale_factor=configs[model_name].ae_params.scale_factor,\n            shift_factor=configs[model_name].ae_params.shift_factor,\n            min_image_shape=min_image_shape,\n            max_image_shape=max_image_shape,\n            **kwargs,\n        )\n\n    def get_minmax_dims(\n        self,\n        batch_size: int,\n        image_height: int,\n        image_width: int,\n    ):\n        min_batch = batch_size if self.trt_static_batch else self.min_batch\n        max_batch = batch_size if self.trt_static_batch else self.max_batch\n\n        latent_height = self._get_latent_dim(image_height)\n        latent_width = self._get_latent_dim(image_width)\n\n        min_latent_height = latent_height if self.trt_static_shape else self.min_latent_shape\n        max_latent_height = latent_height if self.trt_static_shape else self.max_latent_shape\n        min_latent_width = latent_width if self.trt_static_shape else self.min_latent_shape\n        max_latent_width = latent_width if self.trt_static_shape else self.max_latent_shape\n\n        return (\n            min_batch,\n            max_batch,\n            min_latent_height,\n            max_latent_height,\n            min_latent_width,\n            max_latent_width,\n        )\n\n    def get_input_profile(\n        self,\n        batch_size: int,\n        image_height: int | None,\n        image_width: int | None,\n    ):\n        assert self.model_name == \"flux-dev-kontext\" or (\n            image_height is not None and image_width is not None\n        ), \"Only Flux-dev-kontext allows None image shape\"\n\n        assert not self.trt_static_shape or (\n            image_height is not None and image_width is not None\n        ), \"If static_shape is True, image_height and image_width must be not None\"\n\n        image_height = self.default_image_shape if image_height is None else image_height\n        image_width = self.default_image_shape if image_width is None else image_width\n\n        latent_height, latent_width = self.check_dims(\n            batch_size=batch_size,\n            image_height=image_height,\n            image_width=image_width,\n        )\n\n        (\n            min_batch,\n            max_batch,\n            min_latent_height,\n            max_latent_height,\n            min_latent_width,\n            max_latent_width,\n        ) = self.get_minmax_dims(\n            batch_size=batch_size,\n            image_height=image_height,\n            image_width=image_width,\n        )\n\n        return {\n            \"latent\": [\n                (min_batch, self.z_channels, min_latent_height, min_latent_width),\n                (batch_size, self.z_channels, latent_height, latent_width),\n                (max_batch, self.z_channels, max_latent_height, max_latent_width),\n            ]\n        }\n\n\n@register_config(module_name=ModuleName.VAE_ENCODER, precision=\"bf16\")\n@dataclass\nclass VAEEncoderConfig(VAEBaseConfig):\n    trt_tf32: bool = True\n    trt_bf16: bool = True\n    trt_fp8: bool = False\n    trt_fp4: bool = False\n    trt_build_strongly_typed: bool = False\n\n    @classmethod\n    def from_args(cls, model_name: str, **kwargs):\n        if model_name == \"flux-dev-kontext\" and kwargs[\"trt_static_shape\"]:\n            warnings.warn(\"Flux-dev-Kontext does not support static shapes for the encoder.\")\n            kwargs[\"trt_static_shape\"] = False\n\n        if model_name == \"flux-dev-kontext\":\n            min_image_shape = 672\n            max_image_shape = 1568\n        else:\n            min_image_shape = 768\n            max_image_shape = 1360\n\n        return cls(\n            model_name=model_name,\n            module_name=ModuleName.VAE_ENCODER,\n            z_channels=configs[model_name].ae_params.z_channels,\n            scale_factor=configs[model_name].ae_params.scale_factor,\n            shift_factor=configs[model_name].ae_params.shift_factor,\n            min_image_shape=min_image_shape,\n            max_image_shape=max_image_shape,\n            **kwargs,\n        )\n\n    def get_minmax_dims(\n        self,\n        batch_size: int,\n        image_height: int,\n        image_width: int,\n    ):\n        min_batch = batch_size if self.trt_static_batch else self.min_batch\n        max_batch = batch_size if self.trt_static_batch else self.max_batch\n\n        min_image_height = image_height if self.trt_static_shape else self.min_image_shape\n        max_image_height = image_height if self.trt_static_shape else self.max_image_shape\n        min_image_width = image_width if self.trt_static_shape else self.min_image_shape\n        max_image_width = image_width if self.trt_static_shape else self.max_image_shape\n\n        return (\n            min_batch,\n            max_batch,\n            min_image_height,\n            max_image_height,\n            min_image_width,\n            max_image_width,\n        )\n\n    def get_input_profile(\n        self,\n        batch_size: int,\n        image_height: int | None,\n        image_width: int | None,\n    ):\n        if self.model_name == \"flux-dev-kontext\":\n            assert (\n                not self.trt_static_shape\n            ), \"Flux-dev-kontext does not support dynamic shapes for the encoder.\"\n        else:\n            assert isinstance(image_height, int) and isinstance(\n                image_width, int\n            ), \"Only Flux-dev-kontext allows None image shape\"\n\n        image_height = self.default_image_shape if image_height is None else image_height\n        image_width = self.default_image_shape if image_width is None else image_width\n\n        self.check_dims(\n            batch_size=batch_size,\n            image_height=image_height,\n            image_width=image_width,\n        )\n\n        (\n            min_batch,\n            max_batch,\n            min_image_height,\n            max_image_height,\n            min_image_width,\n            max_image_width,\n        ) = self.get_minmax_dims(\n            batch_size=batch_size,\n            image_height=image_height,\n            image_width=image_width,\n        )\n\n        return {\n            \"images\": [\n                (min_batch, 3, min_image_height, min_image_width),\n                (batch_size, 3, image_height, image_width),\n                (max_batch, 3, max_image_height, max_image_width),\n            ],\n        }\n"
  },
  {
    "path": "src/flux/trt/trt_manager.py",
    "content": "#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport gc\nimport os\nimport sys\nimport warnings\n\nimport tensorrt as trt\nimport torch\n\nfrom flux.trt.engine import (\n    BaseEngine,\n    CLIPEngine,\n    Engine,\n    SharedMemory,\n    T5Engine,\n    TransformerEngine,\n    VAEDecoder,\n    VAEEncoder,\n    VAEEngine,\n)\nfrom flux.trt.trt_config import (\n    ModuleName,\n    TRTBaseConfig,\n    get_config,\n)\n\nTRT_LOGGER = trt.Logger()\nVALID_TRANSFORMER_PRECISIONS = {\"bf16\", \"fp8\", \"fp4\", \"fp4_svd32\"}\nVALID_T5_PRECISIONS = {\"bf16\", \"fp8\"}\n\n\nclass TRTManager:\n    @property\n    def module_to_engine_class(self) -> dict[ModuleName, type[Engine]]:\n        return {\n            ModuleName.CLIP: CLIPEngine,\n            ModuleName.TRANSFORMER: TransformerEngine,\n            ModuleName.T5: T5Engine,\n            ModuleName.VAE: VAEDecoder,\n            ModuleName.VAE_ENCODER: VAEEncoder,\n        }\n\n    def __init__(\n        self,\n        trt_transformer_precision: str,\n        trt_t5_precision: str,\n        max_batch=2,\n        verbose=False,\n    ):\n        self.max_batch = max_batch\n        self.precisions = self._parse_models_precisions(\n            trt_transformer_precision=trt_transformer_precision,\n            trt_t5_precision=trt_t5_precision,\n        )\n        self.verbose = verbose\n        self.runtime: trt.Runtime = None\n        self.device_memory = SharedMemory(1024)\n\n        assert torch.cuda.is_available(), \"No cuda device available\"\n\n    @staticmethod\n    def _parse_models_precisions(\n        trt_transformer_precision: str, trt_t5_precision: str\n    ) -> dict[ModuleName, str]:\n        precisions = {\n            ModuleName.CLIP: \"bf16\",\n            ModuleName.VAE: \"bf16\",\n            ModuleName.VAE_ENCODER: \"bf16\",\n        }\n\n        assert (\n            trt_transformer_precision in VALID_TRANSFORMER_PRECISIONS\n        ), f\"Invalid precision for flux-transformer `{trt_transformer_precision}`. Possible value are {VALID_TRANSFORMER_PRECISIONS}\"\n        precisions[ModuleName.TRANSFORMER] = (\n            trt_transformer_precision if trt_transformer_precision != \"fp4_svd32\" else \"fp4\"\n        )\n\n        assert (\n            trt_t5_precision in VALID_T5_PRECISIONS\n        ), f\"Invalid precision for T5 `{trt_t5_precision}`. Possible value are {VALID_T5_PRECISIONS}\"\n        precisions[ModuleName.T5] = trt_t5_precision\n        return precisions\n\n    @staticmethod\n    def _parse_custom_onnx_path(custom_onnx_paths: str) -> dict[ModuleName, str]:\n        \"\"\"Parse a string of comma-separated key-value pairs into a dictionary.\n\n        Args:\n            string (str): A string of comma-separated key-value pairs.\n\n        Returns:\n            Dict[str, str]: Parsed dictionary of key-value pairs.\n\n        Example:\n            >>> parse_key_value_pairs(\"key1:value1,key2:value2\")\n            {\"key1\": \"value1\", \"key2\": \"value2\"}\n        \"\"\"\n        parsed = {}\n\n        for key_value_pair in custom_onnx_paths.split(\",\"):\n            if not key_value_pair:\n                continue\n\n            key_value_pair = key_value_pair.split(\":\")\n            if len(key_value_pair) != 2:\n                raise ValueError(f\"Invalid key-value pair: {key_value_pair}. Must have length 2.\")\n            key, value = key_value_pair\n            key = ModuleName(key)\n            parsed[key] = value\n\n        return parsed\n\n    @staticmethod\n    def _create_directories(engine_dir: str):\n        print(f\"[I] Create directory: {engine_dir} if not existing\")\n        os.makedirs(engine_dir, exist_ok=True)\n\n    def _get_trt_configs(\n        self,\n        model_name: str,\n        module_names: set[ModuleName],\n        engine_dir: str,\n        custom_onnx_paths: dict[ModuleName, str],\n        trt_static_batch: bool,\n        trt_static_shape: bool,\n        trt_enable_all_tactics: bool,\n        trt_timing_cache: str | None,\n        trt_native_instancenorm: bool,\n        trt_builder_optimization_level: int,\n        trt_precision_constraints: str,\n        **kwargs,\n    ) -> dict[ModuleName, TRTBaseConfig]:\n        trt_configs = {}\n        for module_name in module_names:\n            config_cls = get_config(module_name=module_name, precision=self.precisions[module_name])\n            custom_onnx_path = custom_onnx_paths.get(module_name, None)\n\n            trt_config = config_cls.from_args(\n                model_name=model_name,\n                max_batch=self.max_batch,\n                custom_onnx_path=custom_onnx_path,\n                engine_dir=engine_dir,\n                trt_verbose=self.verbose,\n                precision=self.precisions[module_name],\n                trt_static_batch=trt_static_batch,\n                trt_static_shape=trt_static_shape,\n                trt_enable_all_tactics=trt_enable_all_tactics,\n                trt_timing_cache=trt_timing_cache,\n                trt_native_instancenorm=trt_native_instancenorm,\n                trt_builder_optimization_level=trt_builder_optimization_level,\n                trt_precision_constraints=trt_precision_constraints,\n                **kwargs,\n            )\n\n            trt_configs[module_name] = trt_config\n\n        if ModuleName.TRANSFORMER in trt_configs and ModuleName.T5 in trt_configs:\n            trt_configs[ModuleName.TRANSFORMER].text_maxlen = trt_configs[ModuleName.T5].text_maxlen\n        else:\n            warnings.warn(\"`text_maxlen` attribute of flux-trasformer is not update. Default value is used.\")\n\n        return trt_configs\n\n    @staticmethod\n    def _build_engine(\n        trt_config: TRTBaseConfig,\n        batch_size: int,\n        image_height: int | None,\n        image_width: int | None,\n    ):\n        already_build = os.path.exists(trt_config.engine_path)\n        if already_build:\n            return\n\n        trt_config.build_trt_engine(\n            engine_path=trt_config.engine_path,\n            onnx_path=trt_config.onnx_path,\n            strongly_typed=trt_config.trt_build_strongly_typed,\n            tf32=trt_config.trt_tf32,\n            bf16=trt_config.trt_bf16,\n            fp8=trt_config.trt_fp8,\n            fp4=trt_config.trt_fp4,\n            input_profile=trt_config.get_input_profile(\n                batch_size=batch_size,\n                image_height=image_height,\n                image_width=image_width,\n            ),\n            enable_all_tactics=trt_config.trt_enable_all_tactics,\n            timing_cache=trt_config.trt_timing_cache,\n            update_output_names=trt_config.trt_update_output_names,\n            builder_optimization_level=trt_config.trt_builder_optimization_level,\n            verbose=trt_config.trt_verbose,\n        )\n\n        TRTManager._clean_memory()\n\n    def load_engines(\n        self,\n        model_name: str,\n        module_names: set[ModuleName],\n        engine_dir: str,\n        trt_image_height: int | None,\n        trt_image_width: int | None,\n        trt_batch_size=1,\n        trt_static_batch=True,\n        trt_static_shape=True,\n        trt_enable_all_tactics=False,\n        trt_timing_cache: str | None = None,\n        trt_native_instancenorm=True,\n        trt_builder_optimization_level=3,\n        trt_precision_constraints=\"none\",\n        custom_onnx_paths=\"\",\n        **kwargs,\n    ) -> dict[ModuleName, BaseEngine]:\n        TRTManager._clean_memory()\n        TRTManager._create_directories(engine_dir)\n        custom_onnx_paths = TRTManager._parse_custom_onnx_path(custom_onnx_paths)\n\n        trt_configs = self._get_trt_configs(\n            model_name,\n            module_names,\n            engine_dir=engine_dir,\n            custom_onnx_paths=custom_onnx_paths,\n            trt_static_batch=trt_static_batch,\n            trt_static_shape=trt_static_shape,\n            trt_enable_all_tactics=trt_enable_all_tactics,\n            trt_timing_cache=trt_timing_cache,\n            trt_native_instancenorm=trt_native_instancenorm,\n            trt_builder_optimization_level=trt_builder_optimization_level,\n            trt_precision_constraints=trt_precision_constraints,\n            **kwargs,\n        )\n\n        # Build TRT engines\n        for module_name, trt_config in trt_configs.items():\n            self._build_engine(\n                trt_config=trt_config,\n                batch_size=trt_batch_size,\n                image_height=trt_image_height,\n                image_width=trt_image_width,\n            )\n\n        self.init_runtime()\n        # load TRT engines\n        engines = {}\n        for module_name, trt_config in trt_configs.items():\n            engine_class = self.module_to_engine_class[module_name]\n            engine = engine_class(\n                trt_config=trt_config,\n                stream=self.stream,\n                context_memory=self.device_memory,\n                allocation_policy=os.getenv(\"TRT_ALLOCATION_POLICY\", \"global\"),\n            )\n            engines[module_name] = engine\n\n        if ModuleName.VAE in engines:\n            engines[ModuleName.VAE] = VAEEngine(\n                decoder=engines.pop(ModuleName.VAE),\n                encoder=engines.pop(ModuleName.VAE_ENCODER, None),\n            )\n        self._clean_memory()\n        return engines\n\n    @staticmethod\n    def _clean_memory():\n        gc.collect()\n        torch.cuda.empty_cache()\n\n    def init_runtime(self):\n        print(\"[I] Init TRT runtime\")\n        self.runtime = trt.Runtime(TRT_LOGGER)\n        enter_fn = type(self.runtime).__enter__\n        enter_fn(self.runtime)\n        self.stream = torch.cuda.current_stream()\n\n    def stop_runtime(self):\n        exit_fn = type(self.runtime).__exit__\n        exit_fn(self.runtime, *sys.exc_info())\n        del self.stream\n        del self.device_memory\n        print(\"[I] Stop TRT runtime\")\n"
  },
  {
    "path": "src/flux/util.py",
    "content": "import getpass\nimport math\nimport os\nfrom dataclasses import dataclass\nfrom pathlib import Path\n\nimport requests\nimport torch\nfrom einops import rearrange\nfrom huggingface_hub import hf_hub_download, login\nfrom imwatermark import WatermarkEncoder\nfrom PIL import ExifTags, Image\nfrom safetensors.torch import load_file as load_sft\n\nfrom flux.model import Flux, FluxLoraWrapper, FluxParams\nfrom flux.modules.autoencoder import AutoEncoder, AutoEncoderParams\nfrom flux.modules.conditioner import HFEmbedder\n\nCHECKPOINTS_DIR = Path(\"checkpoints\")\nCHECKPOINTS_DIR.mkdir(exist_ok=True)\nBFL_API_KEY = os.getenv(\"BFL_API_KEY\")\n\nos.environ.setdefault(\"TRT_ENGINE_DIR\", str(CHECKPOINTS_DIR / \"trt_engines\"))\n(CHECKPOINTS_DIR / \"trt_engines\").mkdir(exist_ok=True)\n\n\ndef ensure_hf_auth():\n    hf_token = os.environ.get(\"HF_TOKEN\")\n    if hf_token:\n        print(\"Trying to authenticate to HuggingFace with the HF_TOKEN environment variable.\")\n        try:\n            login(token=hf_token)\n            print(\"Successfully authenticated with HuggingFace using HF_TOKEN\")\n            return True\n        except Exception as e:\n            print(f\"Warning: Failed to authenticate with HF_TOKEN: {e}\")\n\n    if os.path.exists(os.path.expanduser(\"~/.cache/huggingface/token\")):\n        print(\"Already authenticated with HuggingFace\")\n        return True\n\n    return False\n\n\ndef prompt_for_hf_auth():\n    try:\n        token = getpass.getpass(\"HF Token (hidden input): \").strip()\n        if not token:\n            print(\"No token provided. Aborting.\")\n            return False\n\n        login(token=token)\n        print(\"Successfully authenticated!\")\n        return True\n    except KeyboardInterrupt:\n        print(\"\\nAuthentication cancelled by user.\")\n        return False\n    except Exception as auth_e:\n        print(f\"Authentication failed: {auth_e}\")\n        print(\"Tip: You can also run 'huggingface-cli login' or set HF_TOKEN environment variable\")\n        return False\n\n\ndef get_checkpoint_path(repo_id: str, filename: str, env_var: str) -> Path:\n    \"\"\"Get the local path for a checkpoint file, downloading if necessary.\"\"\"\n    if os.environ.get(env_var) is not None:\n        local_path = os.environ[env_var]\n        if os.path.exists(local_path):\n            return Path(local_path)\n\n        print(\n            f\"Trying to load model {repo_id}, {filename} from environment \"\n            f\"variable {env_var}. But file {local_path} does not exist. \"\n            \"Falling back to default location.\"\n        )\n\n    # Create a safe directory name from repo_id\n    safe_repo_name = repo_id.replace(\"/\", \"_\")\n    checkpoint_dir = CHECKPOINTS_DIR / safe_repo_name\n    checkpoint_dir.mkdir(exist_ok=True)\n\n    local_path = checkpoint_dir / filename\n\n    if not local_path.exists():\n        print(f\"Downloading {filename} from {repo_id} to {local_path}\")\n        try:\n            ensure_hf_auth()\n            hf_hub_download(repo_id=repo_id, filename=filename, local_dir=checkpoint_dir)\n        except Exception as e:\n            if \"gated repo\" in str(e).lower() or \"restricted\" in str(e).lower():\n                print(f\"\\nError: Cannot access {repo_id} -- this is a gated repository.\")\n\n                # Try one more time to authenticate\n                if prompt_for_hf_auth():\n                    # Retry the download after authentication\n                    print(\"Retrying download...\")\n                    hf_hub_download(repo_id=repo_id, filename=filename, local_dir=checkpoint_dir)\n                else:\n                    print(\"Authentication failed or cancelled.\")\n                    print(\"You can also run 'huggingface-cli login' or set HF_TOKEN environment variable\")\n                    raise RuntimeError(f\"Authentication required for {repo_id}\")\n            else:\n                raise e\n\n    return local_path\n\n\ndef download_onnx_models_for_trt(model_name: str, trt_transformer_precision: str = \"bf16\") -> str | None:\n    \"\"\"Download ONNX models for TRT to our checkpoints directory\"\"\"\n    onnx_repo_map = {\n        \"flux-dev\": \"black-forest-labs/FLUX.1-dev-onnx\",\n        \"flux-schnell\": \"black-forest-labs/FLUX.1-schnell-onnx\",\n        \"flux-dev-canny\": \"black-forest-labs/FLUX.1-Canny-dev-onnx\",\n        \"flux-dev-depth\": \"black-forest-labs/FLUX.1-Depth-dev-onnx\",\n        \"flux-dev-redux\": \"black-forest-labs/FLUX.1-Redux-dev-onnx\",\n        \"flux-dev-fill\": \"black-forest-labs/FLUX.1-Fill-dev-onnx\",\n        \"flux-dev-kontext\": \"black-forest-labs/FLUX.1-Kontext-dev-onnx\",\n    }\n\n    if model_name not in onnx_repo_map:\n        return None  # No ONNX repository required for this model\n\n    repo_id = onnx_repo_map[model_name]\n    safe_repo_name = repo_id.replace(\"/\", \"_\")\n    onnx_dir = CHECKPOINTS_DIR / safe_repo_name\n\n    # Map of module names to their ONNX file paths (using specified precision)\n    onnx_file_map = {\n        \"clip\": \"clip.opt/model.onnx\",\n        \"transformer\": f\"transformer.opt/{trt_transformer_precision}/model.onnx\",\n        \"transformer_data\": f\"transformer.opt/{trt_transformer_precision}/backbone.onnx_data\",\n        \"t5\": \"t5.opt/model.onnx\",\n        \"t5_data\": \"t5.opt/backbone.onnx_data\",\n        \"vae\": \"vae.opt/model.onnx\",\n    }\n\n    # If all files exist locally, return the custom_onnx_paths format\n    if onnx_dir.exists():\n        all_files_exist = True\n        custom_paths = []\n        for module, onnx_file in onnx_file_map.items():\n            if module.endswith(\"_data\"):\n                continue  # Skip data files\n            local_path = onnx_dir / onnx_file\n            if not local_path.exists():\n                all_files_exist = False\n                break\n            custom_paths.append(f\"{module}:{local_path}\")\n\n        if all_files_exist:\n            print(f\"ONNX models ready in {onnx_dir}\")\n            return \",\".join(custom_paths)\n\n    # If not all files exist, download them\n    print(f\"Downloading ONNX models from {repo_id} to {onnx_dir}\")\n    print(f\"Using transformer precision: {trt_transformer_precision}\")\n    onnx_dir.mkdir(exist_ok=True)\n\n    # Download all ONNX files\n    for module, onnx_file in onnx_file_map.items():\n        local_path = onnx_dir / onnx_file\n        if local_path.exists():\n            continue  # Already downloaded\n\n        # Create parent directories\n        local_path.parent.mkdir(parents=True, exist_ok=True)\n\n        try:\n            print(f\"Downloading {onnx_file}\")\n            hf_hub_download(repo_id=repo_id, filename=onnx_file, local_dir=onnx_dir)\n        except Exception as e:\n            if \"does not exist\" in str(e).lower() or \"not found\" in str(e).lower():\n                continue\n            elif \"gated repo\" in str(e).lower() or \"restricted\" in str(e).lower():\n                print(f\"Cannot access {repo_id} - requires license acceptance\")\n                print(\"Please follow these steps:\")\n                print(f\"   1. Visit: https://huggingface.co/{repo_id}\")\n                print(\"   2. Log in to your HuggingFace account\")\n                print(\"   3. Accept the license terms and conditions\")\n                print(\"   4. Then retry this command\")\n                raise RuntimeError(f\"License acceptance required for {model_name}\")\n            else:\n                # Re-raise other errors\n                raise\n\n    print(f\"ONNX models ready in {onnx_dir}\")\n\n    # Return the custom_onnx_paths format that TRT expects: \"module1:path1,module2:path2\"\n    # Note: Only return the actual module paths, not the data file\n    custom_paths = []\n    for module, onnx_file in onnx_file_map.items():\n        if module.endswith(\"_data\"):\n            continue  # Skip the data file in the return paths\n        full_path = onnx_dir / onnx_file\n        if full_path.exists():\n            custom_paths.append(f\"{module}:{full_path}\")\n\n    return \",\".join(custom_paths)\n\n\ndef check_onnx_access_for_trt(model_name: str, trt_transformer_precision: str = \"bf16\") -> str | None:\n    \"\"\"Check ONNX access and download models for TRT - returns ONNX directory path\"\"\"\n    return download_onnx_models_for_trt(model_name, trt_transformer_precision)\n\n\ndef track_usage_via_api(name: str, n=1) -> None:\n    \"\"\"\n    Track usage of licensed models via the BFL API for commercial licensing compliance.\n\n    For more information on licensing BFL's models for commercial use and usage reporting,\n    see the README.md or visit: https://dashboard.bfl.ai/licensing/subscriptions?showInstructions=true\n    \"\"\"\n    assert BFL_API_KEY is not None, \"BFL_API_KEY is not set\"\n\n    model_slug_map = {\n        \"flux-dev\": \"flux-1-dev\",\n        \"flux-dev-kontext\": \"flux-1-kontext-dev\",\n        \"flux-dev-fill\": \"flux-tools\",\n        \"flux-dev-depth\": \"flux-tools\",\n        \"flux-dev-canny\": \"flux-tools\",\n        \"flux-dev-canny-lora\": \"flux-tools\",\n        \"flux-dev-depth-lora\": \"flux-tools\",\n        \"flux-dev-redux\": \"flux-tools\",\n        \"flux-dev-krea\": \"flux-1-krea-dev\",\n    }\n\n    if name not in model_slug_map:\n        print(f\"Skipping tracking usage for {name}, as it cannot be tracked. Please check the model name.\")\n        return\n\n    model_slug = model_slug_map[name]\n    url = f\"https://api.bfl.ai/v1/licenses/models/{model_slug}/usage\"\n    headers = {\"x-key\": BFL_API_KEY, \"Content-Type\": \"application/json\"}\n    payload = {\"number_of_generations\": n}\n\n    response = requests.post(url, headers=headers, json=payload)\n    if response.status_code != 200:\n        raise Exception(f\"Failed to track usage: {response.status_code} {response.text}\")\n    else:\n        print(f\"Successfully tracked usage for {name} with {n} generations\")\n\n\ndef save_image(\n    nsfw_classifier,\n    name: str,\n    output_name: str,\n    idx: int,\n    x: torch.Tensor,\n    add_sampling_metadata: bool,\n    prompt: str,\n    nsfw_threshold: float = 0.85,\n    track_usage: bool = False,\n) -> int:\n    fn = output_name.format(idx=idx)\n    print(f\"Saving {fn}\")\n    # bring into PIL format and save\n    x = x.clamp(-1, 1)\n    x = embed_watermark(x.float())\n    x = rearrange(x[0], \"c h w -> h w c\")\n\n    img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())\n    if nsfw_classifier is not None:\n        nsfw_score = [x[\"score\"] for x in nsfw_classifier(img) if x[\"label\"] == \"nsfw\"][0]\n    else:\n        nsfw_score = nsfw_threshold - 1.0\n\n    if nsfw_score < nsfw_threshold:\n        exif_data = Image.Exif()\n        if name in [\"flux-dev\", \"flux-schnell\"]:\n            exif_data[ExifTags.Base.Software] = \"AI generated;txt2img;flux\"\n        else:\n            exif_data[ExifTags.Base.Software] = \"AI generated;img2img;flux\"\n        exif_data[ExifTags.Base.Make] = \"Black Forest Labs\"\n        exif_data[ExifTags.Base.Model] = name\n        if add_sampling_metadata:\n            exif_data[ExifTags.Base.ImageDescription] = prompt\n        img.save(fn, exif=exif_data, quality=95, subsampling=0)\n        if track_usage:\n            track_usage_via_api(name, 1)\n        idx += 1\n    else:\n        print(\"Your generated image may contain NSFW content.\")\n\n    return idx\n\n\n@dataclass\nclass ModelSpec:\n    params: FluxParams\n    ae_params: AutoEncoderParams\n    repo_id: str\n    repo_flow: str\n    repo_ae: str\n    lora_repo_id: str | None = None\n    lora_filename: str | None = None\n\n\nconfigs = {\n    \"flux-dev\": ModelSpec(\n        repo_id=\"black-forest-labs/FLUX.1-dev\",\n        repo_flow=\"flux1-dev.safetensors\",\n        repo_ae=\"ae.safetensors\",\n        params=FluxParams(\n            in_channels=64,\n            out_channels=64,\n            vec_in_dim=768,\n            context_in_dim=4096,\n            hidden_size=3072,\n            mlp_ratio=4.0,\n            num_heads=24,\n            depth=19,\n            depth_single_blocks=38,\n            axes_dim=[16, 56, 56],\n            theta=10_000,\n            qkv_bias=True,\n            guidance_embed=True,\n        ),\n        ae_params=AutoEncoderParams(\n            resolution=256,\n            in_channels=3,\n            ch=128,\n            out_ch=3,\n            ch_mult=[1, 2, 4, 4],\n            num_res_blocks=2,\n            z_channels=16,\n            scale_factor=0.3611,\n            shift_factor=0.1159,\n        ),\n    ),\n    \"flux-dev-krea\": ModelSpec(\n        repo_id=\"black-forest-labs/FLUX.1-Krea-dev\",\n        repo_flow=\"flux1-krea-dev.safetensors\",\n        repo_ae=\"ae.safetensors\",\n        params=FluxParams(\n            in_channels=64,\n            out_channels=64,\n            vec_in_dim=768,\n            context_in_dim=4096,\n            hidden_size=3072,\n            mlp_ratio=4.0,\n            num_heads=24,\n            depth=19,\n            depth_single_blocks=38,\n            axes_dim=[16, 56, 56],\n            theta=10_000,\n            qkv_bias=True,\n            guidance_embed=True,\n        ),\n        ae_params=AutoEncoderParams(\n            resolution=256,\n            in_channels=3,\n            ch=128,\n            out_ch=3,\n            ch_mult=[1, 2, 4, 4],\n            num_res_blocks=2,\n            z_channels=16,\n            scale_factor=0.3611,\n            shift_factor=0.1159,\n        ),\n    ),\n    \"flux-schnell\": ModelSpec(\n        repo_id=\"black-forest-labs/FLUX.1-schnell\",\n        repo_flow=\"flux1-schnell.safetensors\",\n        repo_ae=\"ae.safetensors\",\n        params=FluxParams(\n            in_channels=64,\n            out_channels=64,\n            vec_in_dim=768,\n            context_in_dim=4096,\n            hidden_size=3072,\n            mlp_ratio=4.0,\n            num_heads=24,\n            depth=19,\n            depth_single_blocks=38,\n            axes_dim=[16, 56, 56],\n            theta=10_000,\n            qkv_bias=True,\n            guidance_embed=False,\n        ),\n        ae_params=AutoEncoderParams(\n            resolution=256,\n            in_channels=3,\n            ch=128,\n            out_ch=3,\n            ch_mult=[1, 2, 4, 4],\n            num_res_blocks=2,\n            z_channels=16,\n            scale_factor=0.3611,\n            shift_factor=0.1159,\n        ),\n    ),\n    \"flux-dev-canny\": ModelSpec(\n        repo_id=\"black-forest-labs/FLUX.1-Canny-dev\",\n        repo_flow=\"flux1-canny-dev.safetensors\",\n        repo_ae=\"ae.safetensors\",\n        params=FluxParams(\n            in_channels=128,\n            out_channels=64,\n            vec_in_dim=768,\n            context_in_dim=4096,\n            hidden_size=3072,\n            mlp_ratio=4.0,\n            num_heads=24,\n            depth=19,\n            depth_single_blocks=38,\n            axes_dim=[16, 56, 56],\n            theta=10_000,\n            qkv_bias=True,\n            guidance_embed=True,\n        ),\n        ae_params=AutoEncoderParams(\n            resolution=256,\n            in_channels=3,\n            ch=128,\n            out_ch=3,\n            ch_mult=[1, 2, 4, 4],\n            num_res_blocks=2,\n            z_channels=16,\n            scale_factor=0.3611,\n            shift_factor=0.1159,\n        ),\n    ),\n    \"flux-dev-canny-lora\": ModelSpec(\n        repo_id=\"black-forest-labs/FLUX.1-dev\",\n        repo_flow=\"flux1-dev.safetensors\",\n        repo_ae=\"ae.safetensors\",\n        lora_repo_id=\"black-forest-labs/FLUX.1-Canny-dev-lora\",\n        lora_filename=\"flux1-canny-dev-lora.safetensors\",\n        params=FluxParams(\n            in_channels=128,\n            out_channels=64,\n            vec_in_dim=768,\n            context_in_dim=4096,\n            hidden_size=3072,\n            mlp_ratio=4.0,\n            num_heads=24,\n            depth=19,\n            depth_single_blocks=38,\n            axes_dim=[16, 56, 56],\n            theta=10_000,\n            qkv_bias=True,\n            guidance_embed=True,\n        ),\n        ae_params=AutoEncoderParams(\n            resolution=256,\n            in_channels=3,\n            ch=128,\n            out_ch=3,\n            ch_mult=[1, 2, 4, 4],\n            num_res_blocks=2,\n            z_channels=16,\n            scale_factor=0.3611,\n            shift_factor=0.1159,\n        ),\n    ),\n    \"flux-dev-depth\": ModelSpec(\n        repo_id=\"black-forest-labs/FLUX.1-Depth-dev\",\n        repo_flow=\"flux1-depth-dev.safetensors\",\n        repo_ae=\"ae.safetensors\",\n        params=FluxParams(\n            in_channels=128,\n            out_channels=64,\n            vec_in_dim=768,\n            context_in_dim=4096,\n            hidden_size=3072,\n            mlp_ratio=4.0,\n            num_heads=24,\n            depth=19,\n            depth_single_blocks=38,\n            axes_dim=[16, 56, 56],\n            theta=10_000,\n            qkv_bias=True,\n            guidance_embed=True,\n        ),\n        ae_params=AutoEncoderParams(\n            resolution=256,\n            in_channels=3,\n            ch=128,\n            out_ch=3,\n            ch_mult=[1, 2, 4, 4],\n            num_res_blocks=2,\n            z_channels=16,\n            scale_factor=0.3611,\n            shift_factor=0.1159,\n        ),\n    ),\n    \"flux-dev-depth-lora\": ModelSpec(\n        repo_id=\"black-forest-labs/FLUX.1-dev\",\n        repo_flow=\"flux1-dev.safetensors\",\n        repo_ae=\"ae.safetensors\",\n        lora_repo_id=\"black-forest-labs/FLUX.1-Depth-dev-lora\",\n        lora_filename=\"flux1-depth-dev-lora.safetensors\",\n        params=FluxParams(\n            in_channels=128,\n            out_channels=64,\n            vec_in_dim=768,\n            context_in_dim=4096,\n            hidden_size=3072,\n            mlp_ratio=4.0,\n            num_heads=24,\n            depth=19,\n            depth_single_blocks=38,\n            axes_dim=[16, 56, 56],\n            theta=10_000,\n            qkv_bias=True,\n            guidance_embed=True,\n        ),\n        ae_params=AutoEncoderParams(\n            resolution=256,\n            in_channels=3,\n            ch=128,\n            out_ch=3,\n            ch_mult=[1, 2, 4, 4],\n            num_res_blocks=2,\n            z_channels=16,\n            scale_factor=0.3611,\n            shift_factor=0.1159,\n        ),\n    ),\n    \"flux-dev-redux\": ModelSpec(\n        repo_id=\"black-forest-labs/FLUX.1-Redux-dev\",\n        repo_flow=\"flux1-redux-dev.safetensors\",\n        repo_ae=\"ae.safetensors\",\n        params=FluxParams(\n            in_channels=64,\n            out_channels=64,\n            vec_in_dim=768,\n            context_in_dim=4096,\n            hidden_size=3072,\n            mlp_ratio=4.0,\n            num_heads=24,\n            depth=19,\n            depth_single_blocks=38,\n            axes_dim=[16, 56, 56],\n            theta=10_000,\n            qkv_bias=True,\n            guidance_embed=True,\n        ),\n        ae_params=AutoEncoderParams(\n            resolution=256,\n            in_channels=3,\n            ch=128,\n            out_ch=3,\n            ch_mult=[1, 2, 4, 4],\n            num_res_blocks=2,\n            z_channels=16,\n            scale_factor=0.3611,\n            shift_factor=0.1159,\n        ),\n    ),\n    \"flux-dev-fill\": ModelSpec(\n        repo_id=\"black-forest-labs/FLUX.1-Fill-dev\",\n        repo_flow=\"flux1-fill-dev.safetensors\",\n        repo_ae=\"ae.safetensors\",\n        params=FluxParams(\n            in_channels=384,\n            out_channels=64,\n            vec_in_dim=768,\n            context_in_dim=4096,\n            hidden_size=3072,\n            mlp_ratio=4.0,\n            num_heads=24,\n            depth=19,\n            depth_single_blocks=38,\n            axes_dim=[16, 56, 56],\n            theta=10_000,\n            qkv_bias=True,\n            guidance_embed=True,\n        ),\n        ae_params=AutoEncoderParams(\n            resolution=256,\n            in_channels=3,\n            ch=128,\n            out_ch=3,\n            ch_mult=[1, 2, 4, 4],\n            num_res_blocks=2,\n            z_channels=16,\n            scale_factor=0.3611,\n            shift_factor=0.1159,\n        ),\n    ),\n    \"flux-dev-kontext\": ModelSpec(\n        repo_id=\"black-forest-labs/FLUX.1-Kontext-dev\",\n        repo_flow=\"flux1-kontext-dev.safetensors\",\n        repo_ae=\"ae.safetensors\",\n        params=FluxParams(\n            in_channels=64,\n            out_channels=64,\n            vec_in_dim=768,\n            context_in_dim=4096,\n            hidden_size=3072,\n            mlp_ratio=4.0,\n            num_heads=24,\n            depth=19,\n            depth_single_blocks=38,\n            axes_dim=[16, 56, 56],\n            theta=10_000,\n            qkv_bias=True,\n            guidance_embed=True,\n        ),\n        ae_params=AutoEncoderParams(\n            resolution=256,\n            in_channels=3,\n            ch=128,\n            out_ch=3,\n            ch_mult=[1, 2, 4, 4],\n            num_res_blocks=2,\n            z_channels=16,\n            scale_factor=0.3611,\n            shift_factor=0.1159,\n        ),\n    ),\n}\n\n\nPREFERED_KONTEXT_RESOLUTIONS = [\n    (672, 1568),\n    (688, 1504),\n    (720, 1456),\n    (752, 1392),\n    (800, 1328),\n    (832, 1248),\n    (880, 1184),\n    (944, 1104),\n    (1024, 1024),\n    (1104, 944),\n    (1184, 880),\n    (1248, 832),\n    (1328, 800),\n    (1392, 752),\n    (1456, 720),\n    (1504, 688),\n    (1568, 672),\n]\n\n\ndef aspect_ratio_to_height_width(aspect_ratio: str, area: int = 1024**2) -> tuple[int, int]:\n    width = float(aspect_ratio.split(\":\")[0])\n    height = float(aspect_ratio.split(\":\")[1])\n    ratio = width / height\n    width = round(math.sqrt(area * ratio))\n    height = round(math.sqrt(area / ratio))\n    return 16 * (width // 16), 16 * (height // 16)\n\n\ndef print_load_warning(missing: list[str], unexpected: list[str]) -> None:\n    if len(missing) > 0 and len(unexpected) > 0:\n        print(f\"Got {len(missing)} missing keys:\\n\\t\" + \"\\n\\t\".join(missing))\n        print(\"\\n\" + \"-\" * 79 + \"\\n\")\n        print(f\"Got {len(unexpected)} unexpected keys:\\n\\t\" + \"\\n\\t\".join(unexpected))\n    elif len(missing) > 0:\n        print(f\"Got {len(missing)} missing keys:\\n\\t\" + \"\\n\\t\".join(missing))\n    elif len(unexpected) > 0:\n        print(f\"Got {len(unexpected)} unexpected keys:\\n\\t\" + \"\\n\\t\".join(unexpected))\n\n\ndef load_flow_model(name: str, device: str | torch.device = \"cuda\", verbose: bool = True) -> Flux:\n    # Loading Flux\n    print(\"Init model\")\n    config = configs[name]\n\n    ckpt_path = str(get_checkpoint_path(config.repo_id, config.repo_flow, \"FLUX_MODEL\"))\n\n    with torch.device(\"meta\"):\n        if config.lora_repo_id is not None and config.lora_filename is not None:\n            model = FluxLoraWrapper(params=config.params).to(torch.bfloat16)\n        else:\n            model = Flux(config.params).to(torch.bfloat16)\n\n    print(f\"Loading checkpoint: {ckpt_path}\")\n    # load_sft doesn't support torch.device\n    sd = load_sft(ckpt_path, device=str(device))\n    sd = optionally_expand_state_dict(model, sd)\n    missing, unexpected = model.load_state_dict(sd, strict=False, assign=True)\n    if verbose:\n        print_load_warning(missing, unexpected)\n\n    if config.lora_repo_id is not None and config.lora_filename is not None:\n        print(\"Loading LoRA\")\n        lora_path = str(get_checkpoint_path(config.lora_repo_id, config.lora_filename, \"FLUX_LORA\"))\n        lora_sd = load_sft(lora_path, device=str(device))\n        # loading the lora params + overwriting scale values in the norms\n        missing, unexpected = model.load_state_dict(lora_sd, strict=False, assign=True)\n        if verbose:\n            print_load_warning(missing, unexpected)\n    return model\n\n\ndef load_t5(device: str | torch.device = \"cuda\", max_length: int = 512) -> HFEmbedder:\n    # max length 64, 128, 256 and 512 should work (if your sequence is short enough)\n    return HFEmbedder(\"google/t5-v1_1-xxl\", max_length=max_length, torch_dtype=torch.bfloat16).to(device)\n\n\ndef load_clip(device: str | torch.device = \"cuda\") -> HFEmbedder:\n    return HFEmbedder(\"openai/clip-vit-large-patch14\", max_length=77, torch_dtype=torch.bfloat16).to(device)\n\n\ndef load_ae(name: str, device: str | torch.device = \"cuda\") -> AutoEncoder:\n    config = configs[name]\n    ckpt_path = str(get_checkpoint_path(config.repo_id, config.repo_ae, \"FLUX_AE\"))\n\n    # Loading the autoencoder\n    print(\"Init AE\")\n    with torch.device(\"meta\"):\n        ae = AutoEncoder(config.ae_params)\n\n    print(f\"Loading AE checkpoint: {ckpt_path}\")\n    sd = load_sft(ckpt_path, device=str(device))\n    missing, unexpected = ae.load_state_dict(sd, strict=False, assign=True)\n    print_load_warning(missing, unexpected)\n    return ae\n\n\ndef optionally_expand_state_dict(model: torch.nn.Module, state_dict: dict) -> dict:\n    \"\"\"\n    Optionally expand the state dict to match the model's parameters shapes.\n    \"\"\"\n    for name, param in model.named_parameters():\n        if name in state_dict:\n            if state_dict[name].shape != param.shape:\n                print(\n                    f\"Expanding '{name}' with shape {state_dict[name].shape} to model parameter with shape {param.shape}.\"\n                )\n                # expand with zeros:\n                expanded_state_dict_weight = torch.zeros_like(param, device=state_dict[name].device)\n                slices = tuple(slice(0, dim) for dim in state_dict[name].shape)\n                expanded_state_dict_weight[slices] = state_dict[name]\n                state_dict[name] = expanded_state_dict_weight\n\n    return state_dict\n\n\nclass WatermarkEmbedder:\n    def __init__(self, watermark):\n        self.watermark = watermark\n        self.num_bits = len(WATERMARK_BITS)\n        self.encoder = WatermarkEncoder()\n        self.encoder.set_watermark(\"bits\", self.watermark)\n\n    def __call__(self, image: torch.Tensor) -> torch.Tensor:\n        \"\"\"\n        Adds a predefined watermark to the input image\n\n        Args:\n            image: ([N,] B, RGB, H, W) in range [-1, 1]\n\n        Returns:\n            same as input but watermarked\n        \"\"\"\n        image = 0.5 * image + 0.5\n        squeeze = len(image.shape) == 4\n        if squeeze:\n            image = image[None, ...]\n        n = image.shape[0]\n        image_np = rearrange((255 * image).detach().cpu(), \"n b c h w -> (n b) h w c\").numpy()[:, :, :, ::-1]\n        # torch (b, c, h, w) in [0, 1] -> numpy (b, h, w, c) [0, 255]\n        # watermarking libary expects input as cv2 BGR format\n        for k in range(image_np.shape[0]):\n            image_np[k] = self.encoder.encode(image_np[k], \"dwtDct\")\n        image = torch.from_numpy(rearrange(image_np[:, :, :, ::-1], \"(n b) h w c -> n b c h w\", n=n)).to(\n            image.device\n        )\n        image = torch.clamp(image / 255, min=0.0, max=1.0)\n        if squeeze:\n            image = image[0]\n        image = 2 * image - 1\n        return image\n\n\n# A fixed 48-bit message that was chosen at random\nWATERMARK_MESSAGE = 0b001010101111111010000111100111001111010100101110\n# bin(x)[2:] gives bits of x as str, use int to convert them to 0/1\nWATERMARK_BITS = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]]\nembed_watermark = WatermarkEmbedder(WATERMARK_BITS)\n"
  }
]