├── .gitignore
├── LICENSE
├── README.md
├── controlnet
├── .bentoignore
├── README.md
├── example-image.png
├── hf-logo.png
├── requirements.txt
└── service.py
├── flux-timestep-distilled
├── README.md
├── requirements.txt
└── service.py
├── sd3-medium
├── .bentoignore
├── README.md
├── bentofile.yaml
├── requirements.txt
└── service.py
├── sd3.5-large-turbo
├── .bentoignore
├── README.md
├── bentofile.yaml
├── requirements.txt
└── service.py
├── sd3.5-large
├── .bentoignore
├── README.md
├── bentofile.yaml
├── requirements.txt
└── service.py
├── sdxl-lightning
├── .bentoignore
├── README.md
├── bentofile.yaml
├── requirements.txt
└── service.py
└── sdxl-turbo
├── .bentoignore
├── README.md
├── requirements.txt
└── service.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 | bazel-*
131 |
132 | package-lock.json
133 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
Self-host Diffusion Models with BentoML
3 |
4 |
5 | This repository contains a series of BentoML example projects, demonstrating how to deploy different models in [the Stable Diffusion (SD) family](https://huggingface.co/models?other=stable-diffusion), which is specialized in generating and manipulating images or video clips based on text prompts.
6 |
7 | See [here](https://docs.bentoml.com/en/latest/examples/overview.html) for a full list of BentoML example projects.
8 |
9 | The following guide uses SDXL Turbo as an example.
10 |
11 | ## Prerequisites
12 |
13 | If you want to test the Service locally, we recommend you use an Nvidia GPU with at least 12GB VRAM.
14 |
15 | ## Install dependencies
16 |
17 | ```bash
18 | git clone https://github.com/bentoml/BentoDiffusion.git
19 | cd BentoDiffusion/sdxl-turbo
20 |
21 | # Recommend Python 3.11
22 | pip install -r requirements.txt
23 | ```
24 |
25 | ## Run the BentoML Service
26 |
27 | We have defined a BentoML Service in `service.py`. Run `bentoml serve` in your project directory to start the Service.
28 |
29 | ```bash
30 | $ bentoml serve
31 |
32 | 2024-01-18T18:31:49+0800 [INFO] [cli] Starting production HTTP BentoServer from "service:SDXLTurboService" listening on http://localhost:3000 (Press CTRL+C to quit)
33 | Loading pipeline components...: 100%
34 | ```
35 |
36 | The server is now active at [http://localhost:3000](http://localhost:3000/). You can interact with it using the Swagger UI or in other different ways.
37 |
38 | CURL
39 |
40 | ```bash
41 | curl -X 'POST' \
42 | 'http://localhost:3000/txt2img' \
43 | -H 'accept: image/*' \
44 | -H 'Content-Type: application/json' \
45 | -d '{
46 | "prompt": "A cinematic shot of a baby racoon wearing an intricate italian priest robe.",
47 | "num_inference_steps": 1,
48 | "guidance_scale": 0
49 | }'
50 | ```
51 |
52 | Python client
53 |
54 | ```python
55 | import bentoml
56 |
57 | with bentoml.SyncHTTPClient("http://localhost:3000") as client:
58 | result = client.txt2img(
59 | prompt="A cinematic shot of a baby racoon wearing an intricate italian priest robe.",
60 | num_inference_steps=1,
61 | guidance_scale=0.0
62 | )
63 | ```
64 |
65 | For detailed explanations of the Service code, see [Stable Diffusion XL Turbo](https://docs.bentoml.com/en/latest/use-cases/diffusion-models/sdxl-turbo.html).
66 |
67 | ## Deploy to BentoCloud
68 |
69 | After the Service is ready, you can deploy the application to BentoCloud for better management and scalability. [Sign up](https://www.bentoml.com/) if you haven't got a BentoCloud account.
70 |
71 | Make sure you have [logged in to BentoCloud](https://docs.bentoml.com/en/latest/scale-with-bentocloud/manage-api-tokens.html).
72 |
73 | ```bash
74 | bentoml cloud login
75 | ```
76 |
77 | Deploy it to BentoCloud.
78 |
79 | ```bash
80 | bentoml deploy
81 | ```
82 |
83 | Once the application is up and running on BentoCloud, you can access it via the exposed URL.
84 |
85 | **Note**: For custom deployment in your own infrastructure, use [BentoML to generate an OCI-compliant image](https://docs.bentoml.com/en/latest/get-started/packaging-for-deployment.html).
86 |
87 |
88 | ## Choose another diffusion model
89 |
90 | To deploy a different diffusion model, go to the corresponding subdirectories of this repository.
91 |
92 | - [FLUX.1](flux-timestep-distilled/)
93 | - [Stable Diffusion 3 Medium](sd3-medium/)
94 | - [Stable Diffusion 3.5 Large Turbo](sd3.5-large-turbo/)
95 | - [Stable Diffusion 3.5 Large](sd3.5-large/)
96 | - [Stable Diffusion XL Lightning](sdxl-lightning/)
97 | - [Stable Diffusion XL Turbo](sdxl-turbo/)
98 | - [ControlNet](controlnet/)
--------------------------------------------------------------------------------
/controlnet/.bentoignore:
--------------------------------------------------------------------------------
1 | __pycache__/
2 | venv/
3 |
--------------------------------------------------------------------------------
/controlnet/README.md:
--------------------------------------------------------------------------------
1 |
2 |
Serving SDXL and ControlNet with BentoML
3 |
4 |
5 | ControlNet is a model designed to control image diffusion processes by conditioning them with additional input images, such as canny edges, user sketches, human poses, depth maps, and more. This allows for greater control over image generation by guiding the model with specific inputs, making it easier to generate targeted images.
6 |
7 | This is a BentoML example project, demonstrating how to build an image generation inference API server, using the [SDXL model](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) and [the ControlNet model](https://huggingface.co/diffusers/controlnet-canny-sdxl-1.0).
8 |
9 | See [here](https://docs.bentoml.com/en/latest/examples/overview.html) for a full list of BentoML example projects.
10 |
11 | ## Prerequisites
12 |
13 | If you want to test the Service locally, we recommend you use an Nvidia GPU with at least 12GB VRAM.
14 |
15 | ## Install dependencies
16 |
17 | ```bash
18 | git clone https://github.com/bentoml/BentoDiffusion.git
19 | cd BentoDiffusion/controlnet
20 |
21 | # Recommend Python 3.11
22 | pip install -r requirements.txt
23 | ```
24 |
25 | ## Run the BentoML Service
26 |
27 | We have defined a BentoML Service in `service.py`. Run `bentoml serve` in your project directory to start the Service.
28 |
29 | ```bash
30 | $ bentoml serve
31 |
32 | 2024-01-18T09:43:40+0800 [INFO] [cli] Prometheus metrics for HTTP BentoServer from "service:APIService" can be accessed at http://localhost:3000/metrics.
33 | 2024-01-18T09:43:41+0800 [INFO] [cli] Starting production HTTP BentoServer from "service:APIService" listening on http://localhost:3000 (Press CTRL+C to quit)
34 | ```
35 |
36 | The server is now active at [http://localhost:3000](http://localhost:3000/). You can interact with it using the Swagger UI or in other different ways.
37 |
38 | CURL
39 |
40 | ```bash
41 | curl -X 'POST' \
42 | 'http://localhost:3000/generate' \
43 | -H 'accept: image/*' \
44 | -H 'Content-Type: multipart/form-data' \
45 | -F 'image=@example-image.png;type=image/png' \
46 | -F 'prompt=A young man walking in a park, wearing jeans.' \
47 | -F 'negative_prompt=ugly, disfigured, ill-structured, low resolution' \
48 | -F 'controlnet_conditioning_scale=0.5' \
49 | -F 'num_inference_steps=25'
50 | ```
51 |
52 | Python client
53 |
54 | ```python
55 | import bentoml
56 | from pathlib import Path
57 |
58 | with bentoml.SyncHTTPClient("http://localhost:3000") as client:
59 | result = client.generate(
60 | image=Path("example-image.png"),
61 | prompt="A young man walking in a park, wearing jeans.",
62 | negative_prompt="ugly, disfigured, ill-structure, low resolution",
63 | controlnet_conditioning_scale=0.5,
64 | num_inference_steps=25,
65 | )
66 | ```
67 |
68 | For detailed explanations of the Service code, see [ControlNet](https://docs.bentoml.com/en/latest/examples/controlnet.html).
69 |
70 | ## Deploy to BentoCloud
71 |
72 | After the Service is ready, you can deploy the application to BentoCloud for better management and scalability. [Sign up](https://www.bentoml.com/) if you haven't got a BentoCloud account.
73 |
74 | Make sure you have [logged in to BentoCloud](https://docs.bentoml.com/en/latest/scale-with-bentocloud/manage-api-tokens.html).
75 |
76 | ```bash
77 | bentoml cloud login
78 | ```
79 |
80 | Deploy it to BentoCloud.
81 |
82 | ```bash
83 | bentoml deploy
84 | ```
85 |
86 | Once the application is up and running on BentoCloud, you can access it via the exposed URL.
87 |
88 | **Note**: For custom deployment in your own infrastructure, use [BentoML to generate an OCI-compliant image](https://docs.bentoml.com/en/latest/get-started/packaging-for-deployment.html).
89 |
--------------------------------------------------------------------------------
/controlnet/example-image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bentoml/BentoDiffusion/41a42d606d73697ed9a7bb66c0d6fc879875db18/controlnet/example-image.png
--------------------------------------------------------------------------------
/controlnet/hf-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bentoml/BentoDiffusion/41a42d606d73697ed9a7bb66c0d6fc879875db18/controlnet/hf-logo.png
--------------------------------------------------------------------------------
/controlnet/requirements.txt:
--------------------------------------------------------------------------------
1 | accelerate==0.31.0
2 | bentoml==1.4.11
3 | diffusers==0.29.0
4 | opencv-python==4.10.0.84
5 | pillow==10.3.0
6 | torch==2.6.0
7 | transformers==4.48.0
8 |
--------------------------------------------------------------------------------
/controlnet/service.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 | import typing as t
4 |
5 | import numpy as np
6 | import PIL
7 | from PIL.Image import Image as PIL_Image
8 |
9 | import bentoml
10 |
11 | CONTROLNET_MODEL_ID = "diffusers/controlnet-canny-sdxl-1.0"
12 | VAE_MODEL_ID = "madebyollin/sdxl-vae-fp16-fix"
13 | BASE_MODEL_ID = "stabilityai/stable-diffusion-xl-base-1.0"
14 |
15 |
16 | my_image = bentoml.images.PythonImage(python_version='3.11', distro='debian') \
17 | .system_packages("ffmpeg") \
18 | .requirements_file("requirements.txt")
19 |
20 |
21 | @bentoml.service(
22 | image=my_image,
23 | traffic={"timeout": 600},
24 | workers=1,
25 | labels={'owner': 'bentoml-team', 'project': 'gallery'},
26 | resources={
27 | "gpu": 1,
28 | "gpu_type": "nvidia-l4",
29 | }
30 | )
31 | class ControlNet:
32 | controlnet_path = bentoml.models.HuggingFaceModel(CONTROLNET_MODEL_ID)
33 | vae_path = bentoml.models.HuggingFaceModel(VAE_MODEL_ID)
34 | base_path = bentoml.models.HuggingFaceModel(BASE_MODEL_ID)
35 |
36 | def __init__(self) -> None:
37 |
38 | import torch
39 | from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel, AutoencoderKL
40 |
41 | if torch.cuda.is_available():
42 | self.device = "cuda"
43 | self.dtype = torch.float16
44 | else:
45 | self.device = "cpu"
46 | self.dtype = torch.float32
47 |
48 | self.controlnet = ControlNetModel.from_pretrained(
49 | self.controlnet_path,
50 | torch_dtype=self.dtype,
51 | )
52 |
53 | self.vae = AutoencoderKL.from_pretrained(
54 | self.vae_path,
55 | torch_dtype=self.dtype,
56 | )
57 |
58 | self.pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
59 | self.base_path,
60 | controlnet=self.controlnet,
61 | vae=self.vae,
62 | torch_dtype=self.dtype
63 | ).to(self.device)
64 |
65 | @bentoml.api
66 | def generate(
67 | self,
68 | image: PIL_Image,
69 | prompt: str,
70 | negative_prompt: t.Optional[str] = None,
71 | controlnet_conditioning_scale: t.Optional[float] = 1.0,
72 | num_inference_steps: t.Optional[int] = 50,
73 | guidance_scale: t.Optional[float] = 5.0,
74 | ) -> PIL_Image:
75 | import cv2
76 |
77 | if controlnet_conditioning_scale is None:
78 | controlnet_conditioning_scale = 1.0
79 |
80 | if num_inference_steps is None:
81 | num_inference_steps = 50
82 |
83 | if guidance_scale is None:
84 | guidance_scale = 5.0
85 |
86 | arr = np.array(image)
87 | arr = cv2.Canny(arr, 100, 200)
88 | arr = arr[:, :, None]
89 | arr = np.concatenate([arr, arr, arr], axis=2)
90 | image = PIL.Image.fromarray(arr)
91 | return self.pipe(
92 | prompt,
93 | image=image,
94 | negative_prompt=negative_prompt,
95 | controlnet_conditioning_scale=controlnet_conditioning_scale,
96 | num_inference_steps=num_inference_steps,
97 | guidance_scale=guidance_scale,
98 | ).to_tuple()[0][0]
99 |
--------------------------------------------------------------------------------
/flux-timestep-distilled/README.md:
--------------------------------------------------------------------------------
1 |
2 |
Serving FLUX.1 models with BentoML
3 |
4 |
5 | This is a BentoML example project, demonstrating how to build an image generation inference API server using the [FLUX.1-schnell](https://huggingface.co/black-forest-labs/FLUX.1-schnell), a 12 billion parameter rectified flow transformer capable of generating images from text descriptions.
6 |
7 | See [here](https://docs.bentoml.com/en/latest/examples/overview.html) for a full list of BentoML example projects.
8 |
9 | ## Prerequisites
10 |
11 | To run the Service locally, we recommend you use an Nvidia GPU with at least 32G VRAM.
12 |
13 | ## Install dependencies
14 |
15 | ```bash
16 | git clone https://github.com/bentoml/BentoDiffusion.git
17 | cd BentoDiffusion/flux-timestep-distilled
18 |
19 | # Recommend Python 3.11
20 | pip install -r requirements.txt
21 | ```
22 |
23 | ## Run the BentoML Service
24 |
25 | We have defined a BentoML Service in `service.py`. Run `bentoml serve` in your project directory to start the Service.
26 |
27 | ```bash
28 | $ bentoml serve
29 |
30 | 2024-01-18T18:31:49+0800 [INFO] [cli] Starting production HTTP BentoServer from "service:FluxTimestepDistilled" listening on http://localhost:3000 (Press CTRL+C to quit)
31 | Loading pipeline components...: 100%
32 | ```
33 |
34 | The server is now active at [http://localhost:3000](http://localhost:3000/). You can interact with it using the Swagger UI or in other different ways.
35 |
36 | CURL
37 |
38 | ```bash
39 | curl -X 'POST' \
40 | 'http://localhost:3000/txt2img' \
41 | -H 'accept: image/*' \
42 | -H 'Content-Type: application/json' \
43 | -d '{
44 | "prompt": "A cinematic shot of a baby racoon wearing an intricate italian priest robe.",
45 | }'
46 | ```
47 |
48 | BentoML client
49 |
50 | ```python
51 | import bentoml
52 |
53 | with bentoml.SyncHTTPClient("http://localhost:3000") as client:
54 | result = client.txt2img(
55 | prompt="A cinematic shot of a baby racoon wearing an intricate italian priest robe.",
56 | )
57 | ```
58 |
59 | ## Deploy to BentoCloud
60 |
61 | After the Service is ready, you can deploy the application to BentoCloud for better management and scalability. [Sign up](https://www.bentoml.com/) if you haven't got a BentoCloud account.
62 |
63 | Make sure you have [logged in to BentoCloud](https://docs.bentoml.com/en/latest/scale-with-bentocloud/manage-api-tokens.html).
64 |
65 | ```bash
66 | bentoml cloud login
67 | ```
68 |
69 | Deploy it to BentoCloud.
70 |
71 | ```bash
72 | bentoml deploy
73 | ```
74 |
75 | Once the application is up and running on BentoCloud, you can access it via the exposed URL.
76 |
77 | **Note**: For custom deployment in your own infrastructure, use [BentoML to generate an OCI-compliant image](https://docs.bentoml.com/en/latest/get-started/packaging-for-deployment.html).
78 |
--------------------------------------------------------------------------------
/flux-timestep-distilled/requirements.txt:
--------------------------------------------------------------------------------
1 | accelerate==1.6.0
2 | bentoml==1.4.11
3 | diffusers==0.33.1
4 | pillow==11.2.1
5 | protobuf==6.30.1
6 | sentencepiece==0.2.0
7 | torch==2.6.0
8 | transformers==4.51.0
9 |
--------------------------------------------------------------------------------
/flux-timestep-distilled/service.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 | import bentoml
4 | from PIL.Image import Image
5 |
6 | MODEL_ID = "black-forest-labs/FLUX.1-schnell"
7 |
8 | sample_prompt = "A girl smiling"
9 |
10 |
11 | @bentoml.service(
12 | name="bento-flux-timestep-distilled-service",
13 | image=bentoml.images.Image(python_version="3.11").requirements_file("requirements.txt"),
14 | traffic={"timeout": 300},
15 | envs=[{"name": "HF_TOKEN"}],
16 | resources={"gpu": 1, "gpu_type": "nvidia-a100-80gb"},
17 | )
18 | class FluxTimestepDistilled:
19 | @bentoml.on_startup
20 | def setup_pipeline(self) -> None:
21 | import torch
22 | from diffusers import FluxPipeline
23 |
24 | self.pipe = FluxPipeline.from_pretrained(
25 | MODEL_ID,
26 | torch_dtype=torch.bfloat16,
27 | use_safetensors=True,
28 | )
29 | self.pipe.to("cuda")
30 |
31 | @bentoml.api
32 | def txt2img(self, prompt: str = sample_prompt) -> Image:
33 | # step number to match ckpt file version
34 | num_inference_steps = 4
35 | guidance_scale = 0.0
36 | image = self.pipe(
37 | prompt=prompt,
38 | guidance_scale=guidance_scale,
39 | height=768,
40 | width=1360,
41 | num_inference_steps=num_inference_steps,
42 | max_sequence_length=256,
43 | ).images[0]
44 | return image
45 |
--------------------------------------------------------------------------------
/sd3-medium/.bentoignore:
--------------------------------------------------------------------------------
1 | __pycache__/
2 | *.py[cod]
3 | *$py.class
4 | .ipynb_checkpoints
5 | venv/
6 |
--------------------------------------------------------------------------------
/sd3-medium/README.md:
--------------------------------------------------------------------------------
1 |
2 |
Serving Stable Diffusion 3 Medium with BentoML
3 |
4 |
5 | [Stable Diffusion 3 Medium](https://huggingface.co/stabilityai/stable-diffusion-3-medium) is a Multimodal Diffusion Transformer (MMDiT) text-to-image model that features greatly improved performance in image quality, typography, complex prompt understanding, and resource-efficiency.
6 |
7 | This is a BentoML example project, demonstrating how to build an image generation inference API server, using the Stable Diffusion 3 Medium model. See [here](https://docs.bentoml.com/en/latest/examples/overview.html) for a full list of BentoML example projects.
8 |
9 | ## Prerequisites
10 |
11 | - Accept the conditions to gain access to [Stable Diffusion 3 Medium on Hugging Face](https://huggingface.co/stabilityai/stable-diffusion-3-medium).
12 | - To run the Service locally, we recommend you use an Nvidia GPU with at least 20G VRAM.
13 |
14 | ## Install dependencies
15 |
16 | ```bash
17 | git clone https://github.com/bentoml/BentoDiffusion.git
18 | cd BentoDiffusion/sd3-medium
19 |
20 | # Recommend Python 3.11
21 | pip install -r requirements.txt
22 |
23 | export HF_TOKEN=
24 | ```
25 |
26 | ## Run the BentoML Service
27 |
28 | We have defined a BentoML Service in `service.py`. Run `bentoml serve` in your project directory to start the Service.
29 |
30 | ```bash
31 | $ bentoml serve
32 |
33 | 2024-01-18T18:31:49+0800 [INFO] [cli] Starting production HTTP BentoServer from "service:SD3Medium" listening on http://localhost:3000 (Press CTRL+C to quit)
34 | Loading pipeline components...: 100%
35 | ```
36 |
37 | The server is now active at [http://localhost:3000](http://localhost:3000/). You can interact with it using the Swagger UI or in other different ways.
38 |
39 | CURL
40 |
41 | ```bash
42 | curl -X 'POST' \
43 | 'http://localhost:3000/txt2img' \
44 | -H 'accept: image/*' \
45 | -H 'Content-Type: application/json' \
46 | -d '{
47 | "prompt": "A cat holding a sign that says hello world",
48 | "num_inference_steps": 28,
49 | "guidance_scale": 7.0
50 | }'
51 | ```
52 |
53 | Python client
54 |
55 | ```python
56 | import bentoml
57 |
58 | with bentoml.SyncHTTPClient("http://localhost:3000") as client:
59 | result = client.txt2img(
60 | prompt="A cat holding a sign that says hello world",
61 | num_inference_steps=28,
62 | guidance_scale=7.0
63 | )
64 | ```
65 |
66 | ## Deploy to BentoCloud
67 |
68 | After the Service is ready, you can deploy the application to BentoCloud for better management and scalability. [Sign up](https://www.bentoml.com/) if you haven't got a BentoCloud account.
69 |
70 | Make sure you have [logged in to BentoCloud](https://docs.bentoml.com/en/latest/scale-with-bentocloud/manage-api-tokens.html).
71 |
72 | ```bash
73 | bentoml cloud login
74 | ```
75 |
76 | Create a BentoCloud secret to store the required environment variable and reference it for deployment.
77 |
78 | ```bash
79 | bentoml secret create huggingface HF_TOKEN=$HF_TOKEN
80 |
81 | bentoml deploy --secret huggingface
82 | ```
83 |
84 | Once the application is up and running on BentoCloud, you can access it via the exposed URL.
85 |
86 | **Note**: For custom deployment in your own infrastructure, use [BentoML to generate an OCI-compliant image](https://docs.bentoml.com/en/latest/get-started/packaging-for-deployment.html).
87 |
--------------------------------------------------------------------------------
/sd3-medium/bentofile.yaml:
--------------------------------------------------------------------------------
1 | service: "service:SD3Medium"
2 | labels:
3 | owner: bentoml-team
4 | project: gallery
5 | include:
6 | - "*.py"
7 | python:
8 | requirements_txt: "./requirements.txt"
9 | lock_packages: false
10 | docker:
11 | python_version: "3.11"
12 | envs:
13 | - name: HF_TOKEN
14 |
--------------------------------------------------------------------------------
/sd3-medium/requirements.txt:
--------------------------------------------------------------------------------
1 | accelerate==0.31.0
2 | bentoml==1.4.11
3 | diffusers==0.29.0
4 | peft==0.11.1
5 | pillow==10.3.0
6 | protobuf==5.27.1
7 | sentencepiece==0.2.0
8 | torch==2.6.0
9 | transformers==4.48.0
10 |
--------------------------------------------------------------------------------
/sd3-medium/service.py:
--------------------------------------------------------------------------------
1 | import typing as t
2 | import bentoml
3 | from PIL.Image import Image
4 | from annotated_types import Le, Ge
5 | from typing_extensions import Annotated
6 |
7 |
8 | MODEL_ID = "stabilityai/stable-diffusion-3-medium-diffusers"
9 |
10 | sample_prompt = "A cat holding a sign that says hello world"
11 |
12 | @bentoml.service(
13 | traffic={"timeout": 300},
14 | workers=1,
15 | resources={
16 | "gpu": 1,
17 | "gpu_type": "nvidia-l4",
18 | },
19 | )
20 | class SD3Medium:
21 | def __init__(self) -> None:
22 | import torch
23 | from diffusers import StableDiffusion3Pipeline
24 |
25 | self.pipe = StableDiffusion3Pipeline.from_pretrained(
26 | MODEL_ID,
27 | torch_dtype=torch.float16,
28 | )
29 | self.pipe.to(device="cuda")
30 |
31 | @bentoml.api
32 | def txt2img(
33 | self,
34 | prompt: str = sample_prompt,
35 | negative_prompt: t.Optional[str] = None,
36 | num_inference_steps: Annotated[int, Ge(1), Le(50)] = 28,
37 | guidance_scale: float = 7.0,
38 | ) -> Image:
39 | image = self.pipe(
40 | prompt=prompt,
41 | negative_prompt=negative_prompt,
42 | num_inference_steps=num_inference_steps,
43 | guidance_scale=guidance_scale,
44 | ).images[0]
45 | return image
46 |
--------------------------------------------------------------------------------
/sd3.5-large-turbo/.bentoignore:
--------------------------------------------------------------------------------
1 | __pycache__/
2 | *.py[cod]
3 | *$py.class
4 | .ipynb_checkpoints
5 | venv/
6 |
--------------------------------------------------------------------------------
/sd3.5-large-turbo/README.md:
--------------------------------------------------------------------------------
1 |
2 |
Serving Stable Diffusion 3.5 Large Turbo with BentoML
3 |
4 |
5 | [Stable Diffusion 3.5 Large Turbo](https://huggingface.co/stabilityai/stable-diffusion-3.5-large-turbo) is a Multimodal Diffusion Transformer (MMDiT) text-to-image model with Adversarial Diffusion Distillation (ADD) that features improved performance in image quality, typography, complex prompt understanding, and resource-efficiency, with a focus on fewer inference steps.
6 |
7 | This is a BentoML example project, demonstrating how to build an image generation inference API server, using the Stable Diffusion 3.5 Large Turbo model. See [here](https://docs.bentoml.com/en/latest/examples/overview.html) for a full list of BentoML example projects.
8 |
9 | ## Prerequisites
10 |
11 | - Accept the conditions to gain access to [Stable Diffusion 3.5 Large Turbo on Hugging Face](https://huggingface.co/stabilityai/stable-diffusion-3.5-large-turbo).
12 | - To run the Service locally, you need an Nvidia GPU with at least 32G VRAM.
13 |
14 | ## Install dependencies
15 |
16 | ```bash
17 | git clone https://github.com/bentoml/BentoDiffusion.git
18 | cd BentoDiffusion/sd3.5-large-turbo
19 | pip install -r requirements.txt
20 |
21 | export HF_TOKEN=
22 | ```
23 |
24 | ## Run the BentoML Service
25 |
26 | We have defined a BentoML Service in `service.py`. Run `bentoml serve` in your project directory to start the Service.
27 |
28 | ```bash
29 | $ bentoml serve
30 |
31 | 2024-01-18T18:31:49+0800 [INFO] [cli] Starting production HTTP BentoServer from "service:SD3.5LargeTurbo" listening on http://localhost:3000 (Press CTRL+C to quit)
32 | Loading pipeline components...: 100%
33 | ```
34 |
35 | The server is now active at [http://localhost:3000](http://localhost:3000/). You can interact with it using the Swagger UI or in other different ways.
36 |
37 | CURL
38 |
39 | ```bash
40 | curl -X 'POST' \
41 | 'http://localhost:3000/txt2img' \
42 | -H 'accept: image/*' \
43 | -H 'Content-Type: application/json' \
44 | -d '{
45 | "prompt": "A cat holding a sign that says hello world",
46 | "num_inference_steps": 4
47 | }'
48 | ```
49 |
50 | Python client
51 |
52 | ```python
53 | import bentoml
54 |
55 | with bentoml.SyncHTTPClient("http://localhost:3000") as client:
56 | result = client.txt2img(
57 | prompt="A cat holding a sign that says hello world",
58 | num_inference_steps=4
59 | )
60 | ```
61 |
62 | ## Deploy to BentoCloud
63 |
64 | After the Service is ready, you can deploy the application to BentoCloud for better management and scalability. [Sign up](https://www.bentoml.com/) if you haven't got a BentoCloud account.
65 |
66 | Make sure you have [logged in to BentoCloud](https://docs.bentoml.com/en/latest/scale-with-bentocloud/manage-api-tokens.html).
67 |
68 | ```bash
69 | bentoml cloud login
70 | ```
71 |
72 | Create a BentoCloud secret to store the required environment variable and reference it for deployment.
73 |
74 | ```bash
75 | bentoml secret create huggingface HF_TOKEN=$HF_TOKEN
76 |
77 | bentoml deploy --secret huggingface
78 | ```
79 |
80 | Once the application is up and running on BentoCloud, you can access it via the exposed URL.
81 |
82 | **Note**: For custom deployment in your own infrastructure, use [BentoML to generate an OCI-compliant image](https://docs.bentoml.com/en/latest/get-started/packaging-for-deployment.html).
83 |
--------------------------------------------------------------------------------
/sd3.5-large-turbo/bentofile.yaml:
--------------------------------------------------------------------------------
1 | service: "service:SD35LargeTurbo"
2 | labels:
3 | owner: bentoml-team
4 | project: gallery
5 | include:
6 | - "*.py"
7 | python:
8 | requirements_txt: "./requirements.txt"
9 | lock_packages: false
10 | envs:
11 | - name: HF_TOKEN
12 |
--------------------------------------------------------------------------------
/sd3.5-large-turbo/requirements.txt:
--------------------------------------------------------------------------------
1 | accelerate==1.0.1
2 | bentoml==1.4.11
3 | diffusers==0.31.0
4 | pillow==11.0.0
5 | protobuf==5.28.3
6 | sentencepiece==0.2.0
7 | torch==2.6.0
8 | transformers==4.48.0
9 |
--------------------------------------------------------------------------------
/sd3.5-large-turbo/service.py:
--------------------------------------------------------------------------------
1 | import typing as t
2 | import bentoml
3 | from PIL.Image import Image
4 | from annotated_types import Le, Ge
5 | from typing_extensions import Annotated
6 |
7 |
8 | MODEL_ID = "stabilityai/stable-diffusion-3.5-large-turbo"
9 |
10 | sample_prompt = "A cat holding a sign that says hello world"
11 |
12 | @bentoml.service(
13 | traffic={"timeout": 300},
14 | workers=1,
15 | resources={
16 | "gpu": 1,
17 | "gpu_type": "nvidia-tesla-a100",
18 | },
19 | )
20 | class SD35LargeTurbo:
21 | def __init__(self) -> None:
22 | import torch
23 | from diffusers import StableDiffusion3Pipeline
24 |
25 | self.pipe = StableDiffusion3Pipeline.from_pretrained(
26 | MODEL_ID,
27 | torch_dtype=torch.bfloat16,
28 | )
29 | self.pipe.to(device="cuda")
30 |
31 | @bentoml.api
32 | def txt2img(
33 | self,
34 | prompt: str = sample_prompt,
35 | negative_prompt: t.Optional[str] = None,
36 | num_inference_steps: Annotated[int, Ge(1), Le(10)] = 4,
37 | ) -> Image:
38 | image = self.pipe(
39 | prompt=prompt,
40 | negative_prompt=negative_prompt,
41 | num_inference_steps=num_inference_steps,
42 | guidance_scale=0.0,
43 | ).images[0]
44 | return image
45 |
--------------------------------------------------------------------------------
/sd3.5-large/.bentoignore:
--------------------------------------------------------------------------------
1 | __pycache__/
2 | *.py[cod]
3 | *$py.class
4 | .ipynb_checkpoints
5 | venv/
6 |
--------------------------------------------------------------------------------
/sd3.5-large/README.md:
--------------------------------------------------------------------------------
1 |
2 |
Serving Stable Diffusion 3.5 Large with BentoML
3 |
4 |
5 | [Stable Diffusion 3.5 Large](https://huggingface.co/stabilityai/stable-diffusion-3.5-large) is a Multimodal Diffusion Transformer (MMDiT) text-to-image model that features improved performance in image quality, typography, complex prompt understanding, and resource-efficiency.
6 |
7 | This is a BentoML example project, demonstrating how to build an image generation inference API server, using the Stable Diffusion 3.5 Large model. See [here](https://docs.bentoml.com/en/latest/examples/overview.html) for a full list of BentoML example projects.
8 |
9 | ## Prerequisites
10 |
11 | - Accept the conditions to gain access to [Stable Diffusion 3.5 Large on Hugging Face](https://huggingface.co/stabilityai/stable-diffusion-3.5-large).
12 | - To run the Service locally, you need an Nvidia GPU with at least 20G VRAM.
13 |
14 | ## Install dependencies
15 |
16 | ```bash
17 | git clone https://github.com/bentoml/BentoDiffusion.git
18 | cd BentoDiffusion/sd3.5-large
19 | pip install -r requirements.txt
20 |
21 | export HF_TOKEN=
22 | ```
23 |
24 | ## Run the BentoML Service
25 |
26 | We have defined a BentoML Service in `service.py`. Run `bentoml serve` in your project directory to start the Service.
27 |
28 | ```bash
29 | $ bentoml serve
30 |
31 | 2024-01-18T18:31:49+0800 [INFO] [cli] Starting production HTTP BentoServer from "service:SD35Large" listening on http://localhost:3000 (Press CTRL+C to quit)
32 | Loading pipeline components...: 100%
33 | ```
34 |
35 | The server is now active at [http://localhost:3000](http://localhost:3000/). You can interact with it using the Swagger UI or in other different ways.
36 |
37 | CURL
38 |
39 | ```bash
40 | curl -X 'POST' \
41 | 'http://localhost:3000/txt2img' \
42 | -H 'accept: image/*' \
43 | -H 'Content-Type: application/json' \
44 | -d '{
45 | "prompt": "A cat holding a sign that says hello world",
46 | "num_inference_steps": 40,
47 | "guidance_scale": 4.5
48 | }'
49 | ```
50 |
51 | Python client
52 |
53 | ```python
54 | import bentoml
55 |
56 | with bentoml.SyncHTTPClient("http://localhost:3000") as client:
57 | result = client.txt2img(
58 | prompt="A cat holding a sign that says hello world",
59 | num_inference_steps=40,
60 | guidance_scale=4.5
61 | )
62 | ```
63 |
64 | ## Deploy to BentoCloud
65 |
66 | After the Service is ready, you can deploy the application to BentoCloud for better management and scalability. [Sign up](https://www.bentoml.com/) if you haven't got a BentoCloud account.
67 |
68 | Make sure you have [logged in to BentoCloud](https://docs.bentoml.com/en/latest/scale-with-bentocloud/manage-api-tokens.html).
69 |
70 | ```bash
71 | bentoml cloud login
72 | ```
73 |
74 | Create a BentoCloud secret to store the required environment variable and reference it for deployment.
75 |
76 | ```bash
77 | bentoml secret create huggingface HF_TOKEN=$HF_TOKEN
78 |
79 | bentoml deploy --secret huggingface
80 | ```
81 |
82 | Once the application is up and running on BentoCloud, you can access it via the exposed URL.
83 |
84 | **Note**: For custom deployment in your own infrastructure, use [BentoML to generate an OCI-compliant image](https://docs.bentoml.com/en/latest/get-started/packaging-for-deployment.html).
85 |
--------------------------------------------------------------------------------
/sd3.5-large/bentofile.yaml:
--------------------------------------------------------------------------------
1 | service: "service:SD35Large"
2 | labels:
3 | owner: bentoml-team
4 | project: gallery
5 | include:
6 | - "*.py"
7 | python:
8 | requirements_txt: "./requirements.txt"
9 | lock_packages: false
10 | envs:
11 | - name: HF_TOKEN
12 |
--------------------------------------------------------------------------------
/sd3.5-large/requirements.txt:
--------------------------------------------------------------------------------
1 | accelerate==1.0.1
2 | bentoml==1.4.11
3 | diffusers==0.31.0
4 | pillow==11.0.0
5 | protobuf==5.28.3
6 | sentencepiece==0.2.0
7 | torch==2.6.0
8 | transformers==4.48.0
9 |
--------------------------------------------------------------------------------
/sd3.5-large/service.py:
--------------------------------------------------------------------------------
1 | import typing as t
2 | import bentoml
3 | from PIL.Image import Image
4 | from annotated_types import Le, Ge
5 | from typing_extensions import Annotated
6 |
7 |
8 | MODEL_ID = "stabilityai/stable-diffusion-3.5-large"
9 |
10 | sample_prompt = "A cat holding a sign that says hello world"
11 |
12 | @bentoml.service(
13 | traffic={"timeout": 300},
14 | workers=1,
15 | resources={
16 | "gpu": 1,
17 | "gpu_type": "nvidia-tesla-a100",
18 | },
19 | )
20 | class SD35Large:
21 | def __init__(self) -> None:
22 | import torch
23 | from diffusers import StableDiffusion3Pipeline
24 |
25 | self.pipe = StableDiffusion3Pipeline.from_pretrained(
26 | MODEL_ID,
27 | torch_dtype=torch.bfloat16,
28 | )
29 | self.pipe.to(device="cuda")
30 |
31 | @bentoml.api
32 | def txt2img(
33 | self,
34 | prompt: str = sample_prompt,
35 | negative_prompt: t.Optional[str] = None,
36 | num_inference_steps: Annotated[int, Ge(1), Le(50)] = 40,
37 | guidance_scale: float = 4.5,
38 | ) -> Image:
39 | image = self.pipe(
40 | prompt=prompt,
41 | negative_prompt=negative_prompt,
42 | num_inference_steps=num_inference_steps,
43 | guidance_scale=guidance_scale,
44 | ).images[0]
45 | return image
46 |
--------------------------------------------------------------------------------
/sdxl-lightning/.bentoignore:
--------------------------------------------------------------------------------
1 | __pycache__/
2 | *.py[cod]
3 | *$py.class
4 | .ipynb_checkpoints
5 | venv/
6 |
--------------------------------------------------------------------------------
/sdxl-lightning/README.md:
--------------------------------------------------------------------------------
1 |
2 |
Serving SDXL Lightning with BentoML
3 |
4 |
5 | This is a BentoML example project, demonstrating how to build an image generation inference API server using the [SDXL-Lightning model](https://huggingface.co/ByteDance/SDXL-Lightning), a lightning-fast text-to-image generation model that is able to generate high-quality 1024px images in a few steps.
6 |
7 | See [here](https://docs.bentoml.com/en/latest/examples/overview.html) for a full list of BentoML example projects.
8 |
9 | ## Prerequisites
10 |
11 | To run the Service locally, we recommend you use an Nvidia GPU with at least 16G VRAM.
12 |
13 | ## Install dependencies
14 |
15 | ```bash
16 | git clone https://github.com/bentoml/BentoDiffusion.git
17 | cd BentoDiffusion/sdxl-lightning
18 |
19 | # Recommend Python 3.11
20 | pip install -r requirements.txt
21 |
22 | export HF_TOKEN=
23 | ```
24 |
25 | ## Run the BentoML Service
26 |
27 | We have defined a BentoML Service in `service.py`. Run `bentoml serve` in your project directory to start the Service.
28 |
29 | ```bash
30 | $ bentoml serve
31 |
32 | 2024-01-18T18:31:49+0800 [INFO] [cli] Starting production HTTP BentoServer from "service:SDXLLightning" listening on http://localhost:3000 (Press CTRL+C to quit)
33 | Loading pipeline components...: 100%
34 | ```
35 |
36 | The server is now active at [http://localhost:3000](http://localhost:3000/). You can interact with it using the Swagger UI or in other different ways.
37 |
38 | CURL
39 |
40 | ```bash
41 | curl -X 'POST' \
42 | 'http://localhost:3000/txt2img' \
43 | -H 'accept: image/*' \
44 | -H 'Content-Type: application/json' \
45 | -d '{
46 | "prompt": "A cinematic shot of a baby racoon wearing an intricate italian priest robe.",
47 | "num_inference_steps": 1,
48 | "guidance_scale": 0
49 | }'
50 | ```
51 |
52 | BentoML client
53 |
54 | ```python
55 | import bentoml
56 |
57 | with bentoml.SyncHTTPClient("http://localhost:3000") as client:
58 | result = client.txt2img(
59 | prompt="A cinematic shot of a baby racoon wearing an intricate italian priest robe.",
60 | num_inference_steps=1,
61 | guidance_scale=0.0
62 | )
63 | ```
64 |
65 | ## Deploy to BentoCloud
66 |
67 | After the Service is ready, you can deploy the application to BentoCloud for better management and scalability. [Sign up](https://www.bentoml.com/) if you haven't got a BentoCloud account.
68 |
69 | Make sure you have [logged in to BentoCloud](https://docs.bentoml.com/en/latest/scale-with-bentocloud/manage-api-tokens.html).
70 |
71 | ```bash
72 | bentoml cloud login
73 | ```
74 |
75 | Deploy it to BentoCloud.
76 |
77 | ```bash
78 | bentoml deploy
79 | ```
80 |
81 | Once the application is up and running on BentoCloud, you can access it via the exposed URL.
82 |
83 | **Note**: For custom deployment in your own infrastructure, use [BentoML to generate an OCI-compliant image](https://docs.bentoml.com/en/latest/get-started/packaging-for-deployment.html).
84 |
--------------------------------------------------------------------------------
/sdxl-lightning/bentofile.yaml:
--------------------------------------------------------------------------------
1 | service: "service:SDXLLightning"
2 | labels:
3 | owner: bentoml-team
4 | project: gallery
5 | include:
6 | - "*.py"
7 | python:
8 | requirements_txt: "./requirements.txt"
9 | docker:
10 | python_version: "3.11"
11 |
--------------------------------------------------------------------------------
/sdxl-lightning/requirements.txt:
--------------------------------------------------------------------------------
1 | accelerate==0.31.0
2 | bentoml==1.4.11
3 | diffusers==0.29.0
4 | pillow==10.3.0
5 | torch==2.6.0
6 | transformers==4.48.0
7 |
--------------------------------------------------------------------------------
/sdxl-lightning/service.py:
--------------------------------------------------------------------------------
1 | import bentoml
2 | from PIL.Image import Image
3 | from annotated_types import Le, Ge
4 | from typing_extensions import Annotated
5 |
6 | BASE_MODEL_ID = "stabilityai/stable-diffusion-xl-base-1.0"
7 | REPO = "ByteDance/SDXL-Lightning"
8 | CKPT = "sdxl_lightning_4step_unet.safetensors" # Use the correct ckpt for your step setting!
9 |
10 | sample_prompt = "A girl smiling"
11 |
12 | @bentoml.service(
13 | traffic={"timeout": 300},
14 | workers=1,
15 | resources={
16 | "gpu": 1,
17 | "gpu_type": "nvidia-l4",
18 | },
19 | )
20 | class SDXLLightning:
21 | def __init__(self) -> None:
22 | import torch
23 | from diffusers import (
24 | StableDiffusionXLPipeline,
25 | UNet2DConditionModel,
26 | EulerDiscreteScheduler
27 | )
28 | from huggingface_hub import hf_hub_download
29 | from safetensors.torch import load_file
30 |
31 | self.unet = UNet2DConditionModel.from_config(
32 | BASE_MODEL_ID, subfolder="unet"
33 | ).to("cuda", torch.float16)
34 |
35 | self.unet.load_state_dict(
36 | load_file(hf_hub_download(REPO, CKPT),
37 | device="cuda")
38 | )
39 |
40 | self.pipe = StableDiffusionXLPipeline.from_pretrained(
41 | BASE_MODEL_ID,
42 | unet=self.unet,
43 | torch_dtype=torch.float16,
44 | variant="fp16"
45 | ).to("cuda")
46 |
47 | self.pipe.scheduler = EulerDiscreteScheduler.from_config(
48 | self.pipe.scheduler.config, timestep_spacing="trailing"
49 | )
50 |
51 |
52 | @bentoml.api
53 | def txt2img(self, prompt: str = sample_prompt) -> Image:
54 | # step number to match ckpt file version
55 | num_inference_steps = 4
56 | guidance_scale = 0.0
57 | image = self.pipe(
58 | prompt=prompt,
59 | num_inference_steps=num_inference_steps,
60 | guidance_scale=guidance_scale,
61 | ).images[0]
62 | return image
63 |
--------------------------------------------------------------------------------
/sdxl-turbo/.bentoignore:
--------------------------------------------------------------------------------
1 | __pycache__/
2 | *.py[cod]
3 | *$py.class
4 | .ipynb_checkpoints
5 | venv/
6 |
--------------------------------------------------------------------------------
/sdxl-turbo/README.md:
--------------------------------------------------------------------------------
1 |
2 |
Serving SDXL Turbo with BentoML
3 |
4 |
5 | [Stable Diffusion XL Turbo](https://huggingface.co/stabilityai/sdxl-turbo) is a real-time text-to-image generation model utilizing a novel distillation technique called Adversarial Diffusion Distillation (ADD). This technology enables SDXL Turbo to generate images in a single step, significantly enhancing performance and reducing computational requirements without sacrificing image quality.
6 |
7 | This is a BentoML example project, demonstrating how to build an image generation inference API server, using the SDXL Turbo model. See [here](https://docs.bentoml.com/en/latest/examples/overview.html) for a full list of BentoML example projects.
8 |
9 | ## Prerequisites
10 |
11 | To run the Service locally, we recommend you use an Nvidia GPU with at least 12G VRAM.
12 |
13 | ## Install dependencies
14 |
15 | ```bash
16 | git clone https://github.com/bentoml/BentoDiffusion.git
17 | cd BentoDiffusion/sdxl-turbo
18 |
19 | # Recommend Python 3.11
20 | pip install -r requirements.txt
21 | ```
22 |
23 | ## Run the BentoML Service
24 |
25 | We have defined a BentoML Service in `service.py`. Run `bentoml serve` in your project directory to start the Service.
26 |
27 | ```bash
28 | $ bentoml serve
29 |
30 | 2024-01-18T18:31:49+0800 [INFO] [cli] Starting production HTTP BentoServer from "service:SDXLTurboService" listening on http://localhost:3000 (Press CTRL+C to quit)
31 | Loading pipeline components...: 100%
32 | ```
33 |
34 | The server is now active at [http://localhost:3000](http://localhost:3000/). You can interact with it using the Swagger UI or in other different ways.
35 |
36 | CURL
37 |
38 | ```bash
39 | curl -X 'POST' \
40 | 'http://localhost:3000/txt2img' \
41 | -H 'accept: image/*' \
42 | -H 'Content-Type: application/json' \
43 | -d '{
44 | "prompt": "A cinematic shot of a baby racoon wearing an intricate italian priest robe.",
45 | "num_inference_steps": 1,
46 | "guidance_scale": 0
47 | }'
48 | ```
49 |
50 | Python client
51 |
52 | ```python
53 | import bentoml
54 |
55 | with bentoml.SyncHTTPClient("http://localhost:3000") as client:
56 | result = client.txt2img(
57 | prompt="A cinematic shot of a baby racoon wearing an intricate italian priest robe.",
58 | num_inference_steps=1,
59 | guidance_scale=0.0
60 | )
61 | ```
62 |
63 | For detailed explanations of the Service code, see [Stable Diffusion XL Turbo](https://docs.bentoml.com/en/latest/use-cases/diffusion-models/sdxl-turbo.html).
64 |
65 | ## Deploy to BentoCloud
66 |
67 | After the Service is ready, you can deploy the application to BentoCloud for better management and scalability. [Sign up](https://www.bentoml.com/) if you haven't got a BentoCloud account.
68 |
69 | Make sure you have [logged in to BentoCloud](https://docs.bentoml.com/en/latest/scale-with-bentocloud/manage-api-tokens.html).
70 |
71 | ```bash
72 | bentoml cloud login
73 | ```
74 |
75 | Deploy it to BentoCloud.
76 |
77 | ```bash
78 | bentoml deploy
79 | ```
80 |
81 | Once the application is up and running on BentoCloud, you can access it via the exposed URL.
82 |
83 | **Note**: For custom deployment in your own infrastructure, use [BentoML to generate an OCI-compliant image](https://docs.bentoml.com/en/latest/get-started/packaging-for-deployment.html).
84 |
--------------------------------------------------------------------------------
/sdxl-turbo/requirements.txt:
--------------------------------------------------------------------------------
1 | accelerate==0.31.0
2 | bentoml==1.4.11
3 | diffusers==0.29.0
4 | pillow==10.3.0
5 | torch==2.6.0
6 | transformers==4.48.0
7 |
--------------------------------------------------------------------------------
/sdxl-turbo/service.py:
--------------------------------------------------------------------------------
1 | import bentoml
2 | from PIL.Image import Image
3 | from annotated_types import Le, Ge
4 | from typing_extensions import Annotated
5 |
6 |
7 | MODEL_ID = "stabilityai/sdxl-turbo"
8 |
9 | sample_prompt = "A cinematic shot of a baby racoon wearing an intricate italian priest robe."
10 |
11 | my_image = bentoml.images.PythonImage(python_version="3.11") \
12 | .requirements_file("requirements.txt")
13 |
14 | @bentoml.service(
15 | image=my_image,
16 | traffic={"timeout": 300},
17 | workers=1,
18 | labels={'owner': 'bentoml-team', 'project': 'gallery'},
19 | resources={
20 | "gpu": 1,
21 | "gpu_type": "nvidia-l4",
22 | },
23 | )
24 | class SDXLTurbo:
25 | model_path = bentoml.models.HuggingFaceModel(MODEL_ID)
26 |
27 | def __init__(self) -> None:
28 | from diffusers import AutoPipelineForText2Image
29 | import torch
30 |
31 | self.pipe = AutoPipelineForText2Image.from_pretrained(
32 | self.model_path,
33 | torch_dtype=torch.float16,
34 | variant="fp16",
35 | )
36 | self.pipe.to(device="cuda")
37 |
38 | @bentoml.api
39 | def txt2img(
40 | self,
41 | prompt: str = sample_prompt,
42 | num_inference_steps: Annotated[int, Ge(1), Le(10)] = 1,
43 | guidance_scale: float = 0.0,
44 | ) -> Image:
45 | image = self.pipe(
46 | prompt=prompt,
47 | num_inference_steps=num_inference_steps,
48 | guidance_scale=guidance_scale,
49 | ).images[0]
50 | return image
51 |
--------------------------------------------------------------------------------