Run this model with HF Jobs
Run ApacheOne/SD15_no_vae_dwd_trained on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/ApacheOne/SD15_no_vae_dwd_trained. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/ApacheOne/SD15_no_vae_dwd_trained on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use ApacheOne/SD15_no_vae_dwd_trained with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use ApacheOne/SD15_no_vae_dwd_trained with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("ApacheOne/SD15_no_vae_dwd_trained", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- Draw Things
- DiffusionBee
Upload VAE-free DreamShaper DWD model and 20 prompt examples
Browse filesFiles changed (34)
- .gitattributes+20
- LICENSEAdded+82
- README.mdAdded+205
- dreamshaper_dwd.pyAdded+749
- dwd_inference.ptAdded+3
- examples/01-storm-lighthouse.pngAdded
- examples/02-cat-by-the-window.pngAdded
- examples/03-desert-observatory.pngAdded
- examples/04-mountain-climber.pngAdded
- examples/05-tea-and-ceramics.pngAdded
- examples/06-greenhouse-on-mars.pngAdded
- examples/07-night-market.pngAdded
- examples/08-jewel-beetle.pngAdded
- examples/09-forest-in-watercolor.pngAdded
- examples/10-art-nouveau-garden.pngAdded
- examples/11-pixel-village.pngAdded
- examples/12-clockmaker's-shop.pngAdded
- examples/13-oil-painted-harbor.pngAdded
- examples/14-concrete-atrium.pngAdded
- examples/15-goldfish-above-the-city.pngAdded
- examples/16-orbital-repair.pngAdded
- examples/17-last-train-home.pngAdded
- examples/18-fashion-portrait.pngAdded
- examples/19-arctic-fox.pngAdded
- examples/20-underwater-ruins.pngAdded
- scheduler/scheduler_config.jsonAdded+22
- text_encoder/config.jsonAdded+24
- text_encoder/model.safetensorsAdded+3
- tokenizer/merges.txtAdded
- tokenizer/special_tokens_map.jsonAdded+30
- tokenizer/tokenizer_config.jsonAdded+31
- tokenizer/vocab.jsonAdded
- unet/config.jsonAdded+68
- unet/diffusion_pytorch_model.safetensorsAdded+3
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363738394041424344454647484950515253545532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textexamples/01-storm-lighthouse.png filter=lfs diff=lfs merge=lfs -textexamples/02-cat-by-the-window.png filter=lfs diff=lfs merge=lfs -textexamples/03-desert-observatory.png filter=lfs diff=lfs merge=lfs -textexamples/04-mountain-climber.png filter=lfs diff=lfs merge=lfs -textexamples/05-tea-and-ceramics.png filter=lfs diff=lfs merge=lfs -textexamples/06-greenhouse-on-mars.png filter=lfs diff=lfs merge=lfs -textexamples/07-night-market.png filter=lfs diff=lfs merge=lfs -textexamples/08-jewel-beetle.png filter=lfs diff=lfs merge=lfs -textexamples/09-forest-in-watercolor.png filter=lfs diff=lfs merge=lfs -textexamples/10-art-nouveau-garden.png filter=lfs diff=lfs merge=lfs -textexamples/11-pixel-village.png filter=lfs diff=lfs merge=lfs -textexamples/12-clockmaker's-shop.png filter=lfs diff=lfs merge=lfs -textexamples/13-oil-painted-harbor.png filter=lfs diff=lfs merge=lfs -textexamples/14-concrete-atrium.png filter=lfs diff=lfs merge=lfs -textexamples/15-goldfish-above-the-city.png filter=lfs diff=lfs merge=lfs -textexamples/16-orbital-repair.png filter=lfs diff=lfs merge=lfs -textexamples/17-last-train-home.png filter=lfs diff=lfs merge=lfs -textexamples/18-fashion-portrait.png filter=lfs diff=lfs merge=lfs -textexamples/19-arctic-fox.png filter=lfs diff=lfs merge=lfs -textexamples/20-underwater-ruins.png filter=lfs diff=lfs merge=lfs -text
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors
CreativeML Open RAIL-Mdated August 22, 2022
Section I: PREAMBLE
Multimodal generative models are being widely adopted and used, and have the potential to transform the way artists, among other individuals, conceive and benefit from AI or ML technologies as a tool for content creation.
Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations.
In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the Model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for art and content generation.
Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this License aims to strike a balance between both in order to enable responsible open-science in the field of AI.
This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
NOW THEREFORE, You and Licensor agree as follows:
1. Definitions
- "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.- "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.- "Output" means the results of operating a Model as embodied in informational content resulting therefrom.- "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.- "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.- "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any.- "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access.- "Licensor" means the copyright owner or entity authorized by the copyright owner that is granting the License, including the persons or entities that may have rights in the Model and/or distributing the Model.- "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, image generator.- "Third Parties" means individuals or legal entities that are not under common control with Licensor or You.- "Contribution" means any work of authorship, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model 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 Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."- "Contributor" means Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model.
Section II: INTELLECTUAL PROPERTY RIGHTS
Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model.3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, 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 Model 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 Model and/or Complementary Material or a Contribution incorporated within the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Work shall terminate as of the date such litigation is asserted or filed.
Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions:Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material.You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;You must cause any modified files to carry prominent notices stating that You changed the files;You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model.You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. - for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5).6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License.
Section IV: OTHER PROVISIONS
7. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License, update the Model through electronic means, or modify the Output of the Model based on updates. You shall undertake reasonable efforts to use the latest version of the Model.8. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors.9. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model and the Complementary Material (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 Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License.10. 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 Model and the Complementary Material (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.11. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material 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.12. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
END OF TERMS AND CONDITIONS
Attachment A
Use Restrictions
You agree not to use the Model or Derivatives of the Model:- In any way that violates any applicable national, federal, state, local or international law or regulation;- For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;- To generate or disseminate verifiably false information and/or content with the purpose of harming others;- To generate or disseminate personal identifiable information that can be used to harm an individual;- To defame, disparage or otherwise harass others;- For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;- For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;- To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;- For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories;- To provide medical advice and medical results interpretation;- To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205---license: creativeml-openrail-mbase_model: Lykon/dreamshaper-8-lcmpipeline_tag: text-to-imagetags:- stable-diffusion- lcm- dwd---
# SD15 no-VAE DWD
DreamShaper 8 LCM adapted for direct pixel prediction with DWD. The final LCMevaluation predicts Oklab pixel patches and converts them to RGB. The exportcontains the U-Net, trained EMA tail and pixel head, CLIP text encoder, tokenizer,and LCM scheduler. Text-to-image inference runs without a VAE.
| Setting | Value || --- | --- || Training updates | 10,000 || Gallery resolution | 512×512 || LCM evaluations | 8 || Gallery CFG | 2 |
## Run inference
With PyTorch and torchvision installed, run the commands below. For a privaterepo, sign in first with `hf auth login`.
```bashpip install diffusers==0.35.2 transformers==4.57.6 accelerate==1.11.0hf download ApacheOne/SD15_no_vae_dwd_trained dreamshaper_dwd.py dwd_inference.pt --local-dir ./sd15_dwdpython ./sd15_dwd/dreamshaper_dwd.py infer --checkpoint ./sd15_dwd/dwd_inference.pt --prompt "An old stone lighthouse by a stormy sea" --guidance 2 --seed 42 --output lighthouse.png```
The first inference run fetches the model components from this repo.
## Example images
### Storm lighthouse

**Prompt** — A real-life photo of an old stone lighthouse by a stormy sea, crashing waves, dark blue clouds
**Seed** — `42`
### Cat by the window

**Prompt** — A realistic photo of a ginger cat on a wooden windowsill, raindrops on the glass, soft gray daylight
**Seed** — `43`
### Desert observatory

**Prompt** — A wide landscape photograph of a white astronomical observatory in a red desert, distant mountains, golden hour
**Seed** — `44`
### Mountain climber

**Prompt** — An outdoor action photograph of a rock climber on a granite wall, a red jacket, dramatic morning sunlight
**Seed** — `45`
### Tea and ceramics

**Prompt** — A still life photograph of a handmade blue ceramic teapot and two cups, oak table, gentle window light
**Seed** — `46`
### Greenhouse on Mars

**Prompt** — A cinematic concept painting of an astronaut tending a lush greenhouse on Mars, red dunes beyond the glass
**Seed** — `47`
### Night market

**Prompt** — A documentary street photograph of a busy night market in the rain, warm food stalls, neon reflections on wet pavement
**Seed** — `48`
### Jewel beetle

**Prompt** — A macro photograph of an iridescent green jewel beetle on a leaf, tiny water droplets, sharp insect details
**Seed** — `49`
### Forest in watercolor

**Prompt** — A delicate watercolor illustration of mushrooms and ferns on a forest floor, muted colors, textured paper
**Seed** — `50`
### Art nouveau garden

**Prompt** — An art nouveau illustration of white lilies, dragonflies, and flowing gold curves on a dark teal background
**Seed** — `51`
### Pixel village

**Prompt** — A 16-bit pixel art scene of a snowy mountain village, warm windows, fir trees, purple evening sky
**Seed** — `52`
### Clockmaker's shop

**Prompt** — An isometric 3D clay render of a tiny clockmaker's workshop, brass gears, tools, pastel colors
**Seed** — `53`
### Oil-painted harbor

**Prompt** — An impressionist oil painting of fishing boats in a quiet harbor at dawn, thick brushstrokes and peach-colored light
**Seed** — `54`
### Concrete atrium

**Prompt** — Architectural photography of a brutalist concrete atrium, geometric stairs, a beam of sun and long shadows
**Seed** — `55`
### Goldfish above the city

**Prompt** — A surreal illustration of a giant goldfish floating above a quiet city at twilight, glowing translucent fins
**Seed** — `56`
### Orbital repair

**Prompt** — A detailed science-fiction illustration of two astronauts repairing a satellite above Earth, bright rim lighting
**Seed** — `57`
### Last train home

**Prompt** — An anime-style illustration of a quiet passenger on a late train, blue night outside the window, warm carriage lights
**Seed** — `58`
### Fashion portrait

**Prompt** — An editorial fashion photograph of an adult model in a sculptural ivory coat, pale studio background, crisp side light
**Seed** — `59`
### Arctic fox

**Prompt** — A wildlife photograph of an arctic fox in fresh snow, pale blue shadows, sharp white fur and curious eyes
**Seed** — `60`
### Underwater ruins

**Prompt** — A fantasy environment painting of sunken stone ruins with fish, sea grass and shafts of turquoise sunlight
**Seed** — `61`
## Credits
- Base checkpoint: [Lykon/dreamshaper-8-lcm](https://huggingface.co/Lykon/dreamshaper-8-lcm)- Method: [Decoding Without a Decoder](https://arxiv.org/abs/2611.22287)- Model license: [CreativeML Open RAIL-M](LICENSE)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749"""Train a DWD pixel head and one SD 1.5 ResNet on DreamShaper 8 LCM."""import argparsefrom contextlib import contextmanagerfrom copy import deepcopyimport importlibimport jsonimport mathfrom pathlib import Pathimport sysimport timefrom threading import Event, Threadfrom typing import NamedTuplefrom urllib.request import urlretrieve
import torchfrom torch import nnfrom torch.nn import functional as Ffrom torch.utils.data import DataLoader, Dataset, Subsetfrom PIL import Image, ImageOpsfrom torchvision.transforms.functional import pil_to_tensorfrom tqdm.auto import tqdm
MODEL = "Lykon/dreamshaper-8-lcm"RAE_REVISION = "a4d18c4db766419cbe7cb8c02cd9f7ceb0ec9041"DINO_WEIGHTS = ( "https://dl.fbaipublicfiles.com/dino/dino_deitsmall8_pretrain/" "dino_deitsmall8_pretrain.pth")
def time_label(seconds): seconds = int(seconds) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) return f"{hours}:{minutes:02d}:{seconds:02d}" if hours else f"{minutes}:{seconds:02d}"
@contextmanagerdef progress_heartbeat(label, *, interval=30.0): """Print the current phase when no work unit has finished recently.""" finished = Event() started = time.monotonic() state = (label, started)
def mark(new_label=None): nonlocal state state = (new_label or state[0], time.monotonic())
def report_wait(): last_report = started while not finished.wait(min(interval, 1.0)): message, since = state now = time.monotonic() if now - max(since, last_report) >= interval: tqdm.write(f"Still working · {message} · {time_label(now - since)} elapsed") last_report = now
reporter = Thread(target=report_wait, daemon=True) reporter.start() try: yield mark finally: finished.set() reporter.join()
@contextmanagerdef activity(label): tqdm.write(f"{label}…") started = time.monotonic() with progress_heartbeat(label): yield tqdm.write(f"{label} · done in {time_label(time.monotonic() - started)}")
RGB_TO_LMS = ( (0.4122214708, 0.5363325363, 0.0514459929), (0.2119034982, 0.6806995451, 0.1073969566), (0.0883024619, 0.2817188376, 0.6299787005),)LMS_ROOT_TO_LAB = ( (0.2104542553, 0.7936177850, -0.0040720468), (1.9779984951, -2.4285922050, 0.4505937099), (0.0259040371, 0.7827717662, -0.8086757660),)LAB_TO_LMS_ROOT = ( (1.0, 0.3963377774, 0.2158037573), (1.0, -0.1055613458, -0.0638541728), (1.0, -0.0894841775, -1.2914855480),)LMS_TO_RGB = ( (4.0767416621, -3.3077115913, 0.2309699292), (-1.2684380046, 2.6097574011, -0.3413193965), (-0.0041960863, -0.7034186147, 1.7076147010),)
def color_matrix(x, matrix): return torch.einsum("ij,bjhw->bihw", x.new_tensor(matrix), x)
def rgb_to_oklab(rgb): """Convert sRGB [-1, 1] to normalized Oklab: (2L-1, a/0.4, b/0.4).""" srgb = rgb.float().add(1).mul(0.5).clamp(0, 1) linear = torch.where( srgb <= 0.04045, srgb / 12.92, ((srgb + 0.055) / 1.055).pow(2.4) ) roots = color_matrix(linear, RGB_TO_LMS).clamp_min(0).pow(1 / 3) l, a, b = color_matrix(roots, LMS_ROOT_TO_LAB).unbind(dim=1) return torch.stack((2 * l - 1, a / 0.4, b / 0.4), dim=1)
def oklab_to_rgb(oklab): """Return sRGB in [-1, 1] nominal range, without clipping out-of-gamut values.""" l, a, b = oklab.float().unbind(dim=1) lab = torch.stack(((l + 1) * 0.5, a * 0.4, b * 0.4), dim=1) lms = color_matrix(lab, LAB_TO_LMS_ROOT).pow(3) linear = color_matrix(lms, LMS_TO_RGB) srgb = torch.where( linear <= 0.0031308, 12.92 * linear, 1.055 * linear.clamp_min(0.0031308).pow(1 / 2.4) - 0.055, ) return srgb.mul(2).sub(1)
class PrefixCache(NamedTuple): hidden: torch.Tensor temb: torch.Tensor cond: torch.Tensor
class PrefixFinished(Exception): pass
class DreamShaperDWD(nn.Module): def __init__(self, unet): super().__init__() self.unet = unet.eval().requires_grad_(False) stage = unet.up_blocks[-1] if not getattr(stage, "has_cross_attention", False) or stage.upsamplers: raise ValueError("Expected DreamShaper's final cross-attention up block.")
weight = unet.conv_out.weight self.tuned = nn.ModuleDict({ "resnet": deepcopy(stage.resnets[-1]), "norm": deepcopy(unet.conv_norm_out), "denoise": deepcopy(unet.conv_out), "pixels": nn.Conv2d(weight.shape[1], 3 * 8 * 8, kernel_size=1), }).to(device=weight.device, dtype=torch.float32).requires_grad_(True)
@torch.no_grad() def frozen_prefix(self, zt, t, cond): weight = self.unet.conv_in.weight cond = cond.detach().to(weight) t = t.to(device=weight.device, dtype=torch.long) cache = None
def capture(_module, args): nonlocal cache hidden, temb = args cache = PrefixCache(hidden, temb, cond) raise PrefixFinished
last_resnet = self.unet.up_blocks[-1].resnets[-1] with last_resnet.register_forward_pre_hook(capture): try: self.unet(zt.to(weight), t, encoder_hidden_states=cond) except PrefixFinished: return cache raise RuntimeError("Final ResNet was not reached.")
def _features(self, cache, resnet, norm): hidden = resnet(cache.hidden, cache.temb) attention = self.unet.up_blocks[-1].attentions[-1] hidden = attention( hidden.to(cache.cond.dtype), encoder_hidden_states=cache.cond, return_dict=False, )[0] return self.unet.conv_act(norm(hidden))
@torch.no_grad() def original_features(self, cache): return self._features( cache, self.unet.up_blocks[-1].resnets[-1], self.unet.conv_norm_out, )
@torch.no_grad() def original_tail(self, cache): return self.unet.conv_out(self.original_features(cache))
def tuned_tail(self, cache, *, render=False): hidden = cache.hidden mixed = hidden.is_cuda and hidden.dtype == torch.bfloat16 with torch.autocast("cuda", dtype=torch.bfloat16, enabled=mixed): features = self._features(cache, self.tuned["resnet"], self.tuned["norm"]) if render: return F.pixel_shuffle(self.tuned["pixels"](features), 8) return self.tuned["denoise"](features)
class PatchLeastSquares: """Streaming fit of hidden features plus a bias against normalized Oklab patches."""
def __init__(self, channels, device): self.xx = torch.zeros(channels + 1, channels + 1, dtype=torch.float64, device=device) self.xy = torch.zeros(channels + 1, 192, dtype=torch.float64, device=device)
@torch.no_grad() def update(self, features, rgb, rows_per_image, generator=None): targets = F.pixel_unshuffle(rgb_to_oklab(rgb), 8) x = features.flatten(2).transpose(1, 2) y = targets.flatten(2).transpose(1, 2) rows = min(rows_per_image, x.shape[1]) if rows < x.shape[1]: indices = torch.randperm(x.shape[1], device=x.device, generator=generator)[:rows] x, y = x[:, indices], y[:, indices] x = x.flatten(0, 1).double() y = y.flatten(0, 1).double() x = F.pad(x, (0, 1), value=1) self.xx.addmm_(x.T, x) self.xy.addmm_(x.T, y)
@torch.no_grad() def apply(self, head, ridge=1e-6): xx = self.xx.clone() diagonal = xx.diagonal()[:-1] diagonal.add_(diagonal.mean().clamp_min(1e-12) * ridge) coefficients = torch.linalg.solve(xx.cpu(), self.xy.cpu()) head.weight.copy_(coefficients[:-1].T.reshape_as(head.weight)) head.bias.copy_(coefficients[-1])
class ImageCaptionDataset(Dataset): def __init__(self, root, size): self.root = Path(root) self.size = size metadata = self.root / "metadata.jsonl" if metadata.is_file(): with metadata.open(encoding="utf-8") as stream: rows = [json.loads(line) for line in stream if line.strip()] self.items = [(self.root / row["file_name"], row["text"]) for row in rows] else: self.items = [ (path, path.with_suffix(".txt").read_text(encoding="utf-8").strip()) for path in sorted(self.root.rglob("*")) if path.suffix.lower() in {".jpg", ".jpeg", ".png", ".webp"} and path.with_suffix(".txt").is_file() ] if not self.items: raise ValueError("Provide captioned images with sidecar .txt files or metadata.jsonl.") for path, caption in self.items: if not path.is_file() or not isinstance(caption, str) or not caption.strip(): raise ValueError(f"Invalid image or caption for {path}")
def __len__(self): return len(self.items)
def __getitem__(self, index): path, caption = self.items[index] with Image.open(path) as image: image = ImageOps.exif_transpose(image).convert("RGB") image = ImageOps.fit(image, (self.size, self.size), Image.Resampling.LANCZOS) pixels = pil_to_tensor(image) return pixels, caption
def training_batches(dataset, batch_size, start, seed, workers): batches_per_epoch = math.ceil(len(dataset) / batch_size) epoch, skip = divmod(start, batches_per_epoch) while True: generator = torch.Generator().manual_seed(seed + epoch) order = torch.randperm(len(dataset), generator=generator).tolist() loader = DataLoader( Subset(dataset, order[skip * batch_size:]), batch_size=batch_size, num_workers=workers, pin_memory=torch.cuda.is_available(), generator=generator, ) yield from loader epoch += 1 skip = 0
@torch.no_grad()def text_embeddings(tokenizer, encoder, captions): tokens = tokenizer( list(captions), padding="max_length", truncation=True, max_length=tokenizer.model_max_length, return_tensors="pt", ) return encoder(tokens.input_ids.to(encoder.device))[0]
@torch.no_grad()def encode_batch(pixels, captions, vae, tokenizer, encoder): rgb = pixels.to(vae.device, dtype=torch.float32, non_blocking=True).div_(127.5).sub_(1) z = vae.encode(rgb).latent_dist.mode() * vae.config.scaling_factor return rgb, z, text_embeddings(tokenizer, encoder, captions)
def add_noise(scheduler, z, t, generator=None): noise = torch.randn(z.shape, dtype=z.dtype, device=z.device, generator=generator) return scheduler.add_noise(z, noise, t)
def crop_positions(image, crop_size=256, count=2): h, w = image.shape[-2:] crop_size = min(crop_size, h, w) tops = torch.randint(h - crop_size + 1, (count,)).tolist() lefts = torch.randint(w - crop_size + 1, (count,)).tolist() return [(top, left, crop_size) for top, left in zip(tops, lefts)]
def crop_batch(image, positions): return torch.cat([ image[..., y:y + size, x:x + size] for y, x, size in positions ])
def download_once(url, path): if not path.is_file(): path.parent.mkdir(parents=True, exist_ok=True) partial = path.with_suffix(path.suffix + ".part") with tqdm(desc=path.name, unit="B", unit_scale=True, mininterval=0.5) as bar: def advance(blocks, chunk_size, total): if total > 0: bar.total = total done = blocks * chunk_size if bar.total is not None: done = min(done, bar.total) bar.update(max(0, done - bar.n))
urlretrieve(url, partial, reporthook=advance) partial.replace(path)
def make_discriminator(cache_dir, device): """Load the RAE DINO-S/8 projected discriminator at a pinned revision.""" cache_dir = Path(cache_dir).resolve() package = cache_dir / "dwd_rae_discriminator" package.mkdir(parents=True, exist_ok=True) (package / "__init__.py").touch() base = f"https://raw.githubusercontent.com/bytetriper/RAE/{RAE_REVISION}" for name in ("dinodisc.py", "utils.py"): download_once(f"{base}/src/disc/{name}", package / name) download_once(f"{base}/LICENSE", package / "LICENSE") weights = cache_dir / "dino_s8.pth" download_once(DINO_WEIGHTS, weights) sys.path.insert(0, str(cache_dir)) try: implementation = importlib.import_module("dwd_rae_discriminator.dinodisc") finally: sys.path.pop(0)
def sdpa(query, key, value, scale, attn_mask=None, dropout_p=0.0): return F.scaled_dot_product_attention( query, key, value, attn_mask=attn_mask, dropout_p=dropout_p, scale=scale, )
implementation.slow_attn = sdpa disc = implementation.DinoDisc( device=device, dino_ckpt_path=str(weights), ks=9, recipe="S_8", ).to(device) disc.dino_proxy[0].original_input_size = 256 return disc
def discriminator_logits(disc, pixels): with torch.autocast( "cuda", dtype=torch.bfloat16, enabled=pixels.is_cuda and torch.cuda.is_bf16_supported(), ): return disc(pixels.clamp(-1, 1)).float()
def pixel_loss(pred, target, perceptual): l1 = F.l1_loss(pred, target) lp = perceptual(pred.clamp(-1, 1), target).mean() return l1 + lp, l1, lp
def adaptive_adversarial_weight(reconstruction, adversarial, pred): rec_grad, = torch.autograd.grad(reconstruction, pred, retain_graph=True) adv_grad, = torch.autograd.grad(adversarial, pred, retain_graph=True) weight = rec_grad.detach().norm() / (adv_grad.detach().norm() + 1e-4) return weight.clamp(max=1e4)
def training_step(model, scheduler, optimizer, perceptual, rgb, z, cond, t_pix, trajectory_weight, disc=None, disc_optimizer=None, generator_gan=False): optimizer.zero_grad(set_to_none=True) steps = scheduler.timesteps[:-1] indices = torch.randint(len(steps), (z.shape[0],), device=z.device) t_traj = steps[indices]
cache = model.frozen_prefix(add_noise(scheduler, z, t_traj), t_traj, cond) u_ref = model.original_tail(cache) u = model.tuned_tail(cache) trajectory = F.mse_loss(u.float(), u_ref.float()) (trajectory_weight * trajectory).backward()
cache = model.frozen_prefix(add_noise(scheduler, z, t_pix), t_pix, cond) pred = oklab_to_rgb(model.tuned_tail(cache, render=True)) reconstruction, l1, lp = pixel_loss(pred, rgb, perceptual) metrics = {"traj": trajectory.detach(), "l1": l1.detach(), "lpips": lp.detach()} generator_loss = reconstruction
if disc is not None: positions = crop_positions(rgb) if generator_gan: disc.eval().requires_grad_(False) fake_score = discriminator_logits(disc, crop_batch(pred, positions)) gan = F.softplus(-fake_score).mean() weight = adaptive_adversarial_weight(reconstruction, gan, pred) generator_loss = reconstruction + weight * gan metrics.update(gan=gan.detach(), gan_weight=weight.detach())
generator_loss.backward()
if disc is not None: disc.train().requires_grad_(True) disc_optimizer.zero_grad(set_to_none=True) real = crop_batch(rgb, positions) fake = crop_batch(pred.detach(), positions) real_score, fake_score = discriminator_logits(disc, torch.cat((real, fake))).chunk(2) d_loss = 0.5 * (F.relu(1 - real_score).mean() + F.relu(1 + fake_score).mean()) d_loss.backward() disc_optimizer.step() metrics["disc"] = d_loss.detach()
optimizer.step() return metrics
@torch.no_grad()def update_ema(ema, current, step, gamma=7): keep = (1 - 1 / step) ** (1 + gamma) for name, average in ema.items(): average.lerp_(current[name].detach(), 1 - keep)
def save_checkpoint(path, step, run, model, ema, optimizer, disc, disc_optimizer): device = model.unet.conv_in.weight.device payload = { "step": step, "run": run, "tail": model.tuned.state_dict(), "ema": ema, "optimizer": optimizer.state_dict(), "disc": None if disc is None else disc.state_dict(), "disc_optimizer": None if disc_optimizer is None else disc_optimizer.state_dict(), "rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, } partial = path.with_suffix(".pt.part") torch.save(payload, partial) partial.replace(path)
def load_base(model_id, device, *, vae_required): from diffusers import AutoencoderKL, LCMScheduler, UNet2DConditionModel from transformers import CLIPTextModel, CLIPTokenizer
dtype = torch.bfloat16 if device.type == "cuda" and torch.cuda.is_bf16_supported() else torch.float32 with activity("Loading DreamShaper U-Net"): unet = UNet2DConditionModel.from_pretrained( model_id, subfolder="unet", torch_dtype=dtype, use_safetensors=True, ).to(device).eval() with activity("Loading CLIP text encoder and tokenizer"): encoder = CLIPTextModel.from_pretrained( model_id, subfolder="text_encoder", torch_dtype=dtype, use_safetensors=True, ).to(device).eval().requires_grad_(False) tokenizer = CLIPTokenizer.from_pretrained(model_id, subfolder="tokenizer") with activity("Loading LCM scheduler"): scheduler = LCMScheduler.from_pretrained(model_id, subfolder="scheduler") vae = None if vae_required: with activity("Loading the training VAE"): vae = AutoencoderKL.from_pretrained( model_id, subfolder="vae", torch_dtype=torch.float32, use_safetensors=True, ).to(device).eval().requires_grad_(False) return DreamShaperDWD(unet), scheduler, tokenizer, encoder, vae
@torch.no_grad()def initialize_head(model, scheduler, dataset, vae, tokenizer, encoder, args, device): generator = torch.Generator(device=device).manual_seed(args.seed) order = torch.randperm(len(dataset), generator=torch.Generator().manual_seed(args.seed)) indices = order[:args.fit_images].tolist() loader = DataLoader(Subset(dataset, indices), batch_size=args.batch, num_workers=args.workers) fit = PatchLeastSquares(model.tuned["pixels"].in_channels, device) with tqdm(total=len(indices), desc="Least-squares fit", unit="image", mininterval=0.5) as bar: with progress_heartbeat("encoding images for least squares") as mark: next_log = 250 for pixels, captions in loader: mark(f"least-squares image {bar.n + 1:,}/{len(indices):,}") rgb, z, cond = encode_batch(pixels, captions, vae, tokenizer, encoder) t = scheduler.timesteps[-1].expand(z.shape[0]) cache = model.frozen_prefix(add_noise(scheduler, z, t, generator), t, cond) fit.update(model.original_features(cache), rgb, args.fit_rows, generator) bar.update(z.shape[0]) mark(f"least squares · {bar.n:,}/{len(indices):,} images complete") if bar.n >= next_log or bar.n == len(indices): tqdm.write(f"Least squares · {bar.n:,}/{len(indices):,} images") next_log = bar.n + 250 with activity("Solving for pixel-head weights"): fit.apply(model.tuned["pixels"])
def generator_optimizer(model): return torch.optim.Adam( [ {"params": model.tuned["resnet"].parameters()}, {"params": model.tuned["norm"].parameters()}, {"params": model.tuned["denoise"].parameters()}, {"params": model.tuned["pixels"].parameters(), "lr": 5e-4}, ], lr=1e-4, betas=(0.9, 0.95), )
def make_gan(run_dir, device): disc = make_discriminator(run_dir / "dependencies", device) optimizer = torch.optim.Adam(disc.parameters(), lr=2e-4, betas=(0.9, 0.95)) return disc, optimizer
def train(args, device): import lpips
torch.manual_seed(args.seed) with activity("Reading the image/caption manifest"): dataset = ImageCaptionDataset(args.data, args.size) print(f"Training device · {torch.cuda.get_device_name(device) if device.type == 'cuda' else 'CPU'}", flush=True) run_dir = Path(args.out) run_dir.mkdir(parents=True, exist_ok=True) latest = run_dir / "latest.pt" if latest.exists() and not args.resume: raise FileExistsError(f"{latest} exists. Use --resume or choose another --out.")
run = { name: getattr(args, name) for name in ( "model", "sampling_steps", "size", "seed", "batch", "trajectory_weight", "gan_start", "gan_warmup", ) } checkpoint = None if args.resume: with activity(f"Reading {latest.name} for resume"): checkpoint = torch.load(latest, map_location="cpu", weights_only=True) if checkpoint["run"] != run: raise ValueError("Resume requires the same model, resolution, and training settings.")
model, scheduler, tokenizer, encoder, vae = load_base(args.model, device, vae_required=True) scheduler.set_timesteps(args.sampling_steps, device=device) optimizer = generator_optimizer(model) base_rates = [group["lr"] for group in optimizer.param_groups] with activity("Loading LPIPS"): perceptual = lpips.LPIPS(net="alex", verbose=False).to(device).eval().requires_grad_(False) disc = disc_optimizer = None
if checkpoint is None: print(f"{len(dataset)} captioned images, {device}, LCM grid {scheduler.timesteps.tolist()}", flush=True) initialize_head(model, scheduler, dataset, vae, tokenizer, encoder, args, device) ema = {name: value.detach().clone() for name, value in model.tuned.state_dict().items()} start = 0 with activity(f"Saving {latest.name} after head fitting"): save_checkpoint(latest, start, run, model, ema, optimizer, disc, disc_optimizer) else: start = checkpoint["step"] model.tuned.load_state_dict(checkpoint["tail"]) optimizer.load_state_dict(checkpoint["optimizer"]) ema = {name: value.to(device) for name, value in checkpoint["ema"].items()} if checkpoint["disc"] is not None: with activity("Loading the DINO discriminator for resume"): disc, disc_optimizer = make_gan(run_dir, device) disc.load_state_dict(checkpoint["disc"]) disc_optimizer.load_state_dict(checkpoint["disc_optimizer"]) torch.set_rng_state(checkpoint["rng"]) if device.type == "cuda" and checkpoint["cuda_rng"] is not None: torch.cuda.set_rng_state(checkpoint["cuda_rng"], device) del checkpoint print(f"Resumed at step {start}", flush=True)
batches = training_batches(dataset, args.batch, start, args.seed, args.workers) begun = time.monotonic() last_metrics = begun with tqdm(total=args.steps, initial=start, desc="Training", unit="step", mininterval=0.5) as bar: with progress_heartbeat("waiting for the first training update") as mark: for step in range(start + 1, args.steps + 1): if disc is None and args.gan_start and step >= args.gan_start - args.gan_warmup: message = f"Step {step:,} · loading DINO discriminator for warmup" mark(message) tqdm.write(message) disc, disc_optimizer = make_gan(run_dir, device)
if args.gan_start and step == args.gan_start: tqdm.write(f"Step {step:,} · adaptive generator GAN loss enabled")
ramp = min(1.0, step / 200) for group, rate in zip(optimizer.param_groups, base_rates): group["lr"] = rate * ramp
mark(f"training step {step:,}/{args.steps:,} · reading the next batch") pixels, captions = next(batches) rgb, z, cond = encode_batch(pixels, captions, vae, tokenizer, encoder) t_pix = scheduler.timesteps[-1].expand(z.shape[0]) mark(f"training step {step:,}/{args.steps:,} · forward/backward") metrics = training_step( model, scheduler, optimizer, perceptual, rgb, z, cond, t_pix, args.trajectory_weight, disc, disc_optimizer, generator_gan=bool(args.gan_start and step >= args.gan_start), ) update_ema(ema, model.tuned.state_dict(), step)
now = time.monotonic() milestone = step == start + 1 or step % 25 == 0 or step == args.steps if milestone or now - last_metrics >= 2.0: values = torch.stack(list(metrics.values())).float().cpu().tolist() elapsed = time.monotonic() - begun seconds_per_step = elapsed / (step - start) eta = (args.steps - step) * seconds_per_step losses = " ".join(f"{name}={value:.4f}" for name, value in zip(metrics, values)) bar.set_postfix_str(losses, refresh=False) last_metrics = now if milestone: tqdm.write( f"Step {step:,}/{args.steps:,} · {losses} · {seconds_per_step:.2f} s/step" f" · elapsed {time_label(elapsed)} · ETA {time_label(eta)}" ) bar.update() mark(f"training step {step:,}/{args.steps:,} complete")
if step % args.save_every == 0 or step == args.steps: message = f"Step {step:,} · saving {latest.name}" mark(message) tqdm.write(message) saved_at = time.monotonic() save_checkpoint(latest, step, run, model, ema, optimizer, disc, disc_optimizer) mark() tqdm.write(f"Step {step:,} · checkpoint saved in {time_label(time.monotonic() - saved_at)}") print(f"Training time this session · {time_label(time.monotonic() - begun)}", flush=True) print(f"Checkpoint: {latest}", flush=True)
@torch.no_grad()def render(model, scheduler, cond, uncond, guidance, size, steps, generator): weight = model.unet.conv_in.weight device = weight.device scheduler.set_timesteps(steps, device=device) z = torch.randn( (cond.shape[0], model.unet.config.in_channels, size // 8, size // 8), generator=generator, device=device, dtype=weight.dtype, ) * scheduler.init_noise_sigma use_cfg = guidance > 1.0 embeds = torch.cat((uncond, cond)) if use_cfg else cond with tqdm(total=steps, desc="LCM inference", unit="step", mininterval=0.3) as bar: with progress_heartbeat("running LCM inference") as mark: for index, t in enumerate(scheduler.timesteps[:-1], 1): mark(f"LCM evaluation {index}/{steps}") x = torch.cat((z, z)) if use_cfg else z x = scheduler.scale_model_input(x, t) cache = model.frozen_prefix(x, t, embeds) result = model.tuned_tail(cache).to(z.dtype) if use_cfg: unconditional, conditional = result.chunk(2) result = unconditional + guidance * (conditional - unconditional) z = scheduler.step(result, t, z, generator=generator).prev_sample if device.type == "cuda": torch.cuda.synchronize(device) bar.update() mark(f"LCM evaluation {steps}/{steps} · rendering pixels") t = scheduler.timesteps[-1] cache = model.frozen_prefix(scheduler.scale_model_input(z, t), t, cond) rgb = oklab_to_rgb(model.tuned_tail(cache, render=True)).clamp(-1, 1) if device.type == "cuda": torch.cuda.synchronize(device) bar.update() return rgb
def infer(args, device): with activity(f"Reading {Path(args.checkpoint).name} for inference"): checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) run = checkpoint["run"] model, scheduler, tokenizer, encoder, _ = load_base(run["model"], device, vae_required=False) model.tuned.load_state_dict(checkpoint["ema"]) cond = text_embeddings(tokenizer, encoder, [args.prompt]) uncond = text_embeddings(tokenizer, encoder, [args.negative]) if args.guidance > 1 else None generator = torch.Generator(device=device).manual_seed(args.seed) rgb = render( model, scheduler, cond, uncond, args.guidance, run["size"], run["sampling_steps"], generator, ) image = rgb[0].permute(1, 2, 0).add(1).mul(127.5).round().byte().cpu().numpy() output = Path(args.output) output.parent.mkdir(parents=True, exist_ok=True) Image.fromarray(image).save(output) print(f"Image: {output}", flush=True)
def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) subcommands = parser.add_subparsers(dest="mode", required=True) train_parser = subcommands.add_parser("train") train_parser.add_argument("--data", required=True) train_parser.add_argument("--out", required=True) train_parser.add_argument("--model", default=MODEL) train_parser.add_argument("--steps", type=int, default=10000) train_parser.add_argument("--sampling-steps", type=int, default=8) train_parser.add_argument("--size", type=int, default=512) train_parser.add_argument("--batch", type=int, default=1) train_parser.add_argument("--fit-images", type=int, default=10000) train_parser.add_argument("--fit-rows", type=int, default=256) train_parser.add_argument("--trajectory-weight", type=float, default=10.0) train_parser.add_argument("--gan-start", type=int, default=8000, help="Use 0 to disable GAN.") train_parser.add_argument("--gan-warmup", type=int, default=1000) train_parser.add_argument("--workers", type=int, default=2) train_parser.add_argument("--save-every", type=int, default=250) train_parser.add_argument("--seed", type=int, default=42) train_parser.add_argument("--resume", action="store_true") infer_parser = subcommands.add_parser("infer") infer_parser.add_argument("--checkpoint", required=True) infer_parser.add_argument("--prompt", required=True) infer_parser.add_argument("--negative", default="") infer_parser.add_argument("--output", required=True) infer_parser.add_argument("--guidance", type=float, default=2.0) infer_parser.add_argument("--seed", type=int, default=42) args = parser.parse_args(argv) device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if args.mode == "train": if args.size < 64 or args.size % 64 or args.sampling_steps < 2: parser.error("Train at a multiple of 64 pixels with at least two LCM evaluations.") if min(args.batch, args.steps, args.fit_images, args.fit_rows, args.save_every) < 1: parser.error("Batch, steps, fit-images, fit-rows and save-every must be positive.") if args.workers < 0 or args.gan_start < 0 or args.gan_warmup < 0: parser.error("Workers, GAN start, and GAN warmup must be nonnegative.") if args.gan_start and args.gan_start <= args.gan_warmup: parser.error("GAN generator start must be later than the warmup length.") if not math.isfinite(args.trajectory_weight) or args.trajectory_weight < 0: parser.error("Trajectory weight must be finite and nonnegative.") train(args, device) else: if not math.isfinite(args.guidance) or args.guidance < 1: parser.error("Guidance must be finite and at least 1.") infer(args, device)
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:3ca91ed61fa49e6fa2e82d7cdaeb88abd3b2209addd3c456ef2f6b8dd5158b92size 1383135712345678910111213141516171819202122{ "_class_name": "LCMScheduler", "_diffusers_version": "0.35.2", "beta_end": 0.012, "beta_schedule": "scaled_linear", "beta_start": 0.00085, "clip_sample": false, "clip_sample_range": 1.0, "dynamic_thresholding_ratio": 0.995, "num_train_timesteps": 1000, "original_inference_steps": 50, "prediction_type": "epsilon", "rescale_betas_zero_snr": false, "sample_max_value": 1.0, "set_alpha_to_one": false, "skip_prk_steps": true, "steps_offset": 1, "thresholding": false, "timestep_scaling": 10.0, "timestep_spacing": "leading", "trained_betas": null}123456789101112131415161718192021222324{ "architectures": [ "CLIPTextModel" ], "attention_dropout": 0.0, "bos_token_id": 0, "dropout": 0.0, "dtype": "bfloat16", "eos_token_id": 2, "hidden_act": "quick_gelu", "hidden_size": 768, "initializer_factor": 1.0, "initializer_range": 0.02, "intermediate_size": 3072, "layer_norm_eps": 1e-05, "max_position_embeddings": 77, "model_type": "clip_text_model", "num_attention_heads": 12, "num_hidden_layers": 12, "pad_token_id": 1, "projection_dim": 768, "transformers_version": "4.57.6", "vocab_size": 49408}123version https://git-lfs.github.com/spec/v1oid sha256:f4cd3ce4bb3b1a289493631d7e6f2f700a1ec0c62e80a54a03ca1cdbbd823789size 246144352123456789101112131415161718192021222324252627282930{ "bos_token": { "content": "<|startoftext|>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }, "eos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }, "unk_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }}12345678910111213141516171819202122232425262728293031{ "add_prefix_space": false, "added_tokens_decoder": { "49406": { "content": "<|startoftext|>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": true }, "49407": { "content": "<|endoftext|>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": true } }, "bos_token": "<|startoftext|>", "clean_up_tokenization_spaces": true, "do_lower_case": true, "eos_token": "<|endoftext|>", "errors": "replace", "extra_special_tokens": {}, "model_max_length": 77, "pad_token": "<|endoftext|>", "tokenizer_class": "CLIPTokenizer", "unk_token": "<|endoftext|>"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768{ "_class_name": "UNet2DConditionModel", "_diffusers_version": "0.35.2", "_name_or_path": "Lykon/dreamshaper-8-lcm", "act_fn": "silu", "addition_embed_type": null, "addition_embed_type_num_heads": 64, "addition_time_embed_dim": null, "attention_head_dim": 8, "attention_type": "default", "block_out_channels": [ 320, 640, 1280, 1280 ], "center_input_sample": false, "class_embed_type": null, "class_embeddings_concat": false, "conv_in_kernel": 3, "conv_out_kernel": 3, "cross_attention_dim": 768, "cross_attention_norm": null, "down_block_types": [ "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D" ], "downsample_padding": 1, "dropout": 0.0, "dual_cross_attention": false, "encoder_hid_dim": null, "encoder_hid_dim_type": null, "flip_sin_to_cos": true, "freq_shift": 0, "in_channels": 4, "layers_per_block": 2, "mid_block_only_cross_attention": null, "mid_block_scale_factor": 1, "mid_block_type": "UNetMidBlock2DCrossAttn", "norm_eps": 1e-05, "norm_num_groups": 32, "num_attention_heads": null, "num_class_embeds": null, "only_cross_attention": false, "out_channels": 4, "projection_class_embeddings_input_dim": null, "resnet_out_scale_factor": 1.0, "resnet_skip_time_act": false, "resnet_time_scale_shift": "default", "reverse_transformer_layers_per_block": null, "sample_size": 64, "time_cond_proj_dim": null, "time_embedding_act_fn": null, "time_embedding_dim": null, "time_embedding_type": "positional", "timestep_post_act": null, "transformer_layers_per_block": 1, "up_block_types": [ "UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D" ], "upcast_attention": null, "use_linear_projection": false}123version https://git-lfs.github.com/spec/v1oid sha256:3cae075430aa1fcdf3da87ec6695502bc4807a2be863b8d6ae01511694ff9070size 1719125992.gitattributes+20
LICENSEAdded+82
README.mdAdded+205
dreamshaper_dwd.pyAdded+749
dwd_inference.ptAdded+3
examples/01-storm-lighthouse.pngAdded

Large File Pointer Details
- SHA256: 095785a596cb5124c47f66a692e6513fc44c52496e1e79e05ff7b4a91315309f
- Pointer size: 131 Bytes
- Size of remote file: 435 kB
examples/02-cat-by-the-window.pngAdded

Large File Pointer Details
- SHA256: 65ce86fe64e08fdd39957c30dc90adcc50ef9071a3c5cc8304f7ec32627723a9
- Pointer size: 131 Bytes
- Size of remote file: 427 kB
examples/03-desert-observatory.pngAdded

Large File Pointer Details
- SHA256: aceca447ba9f49af211fef8b2123dd88134f33cd9032b8265e71fc2c781aba92
- Pointer size: 131 Bytes
- Size of remote file: 434 kB
examples/04-mountain-climber.pngAdded

Large File Pointer Details
- SHA256: 1979a1035bdb308890bd5ea971410276ed5caa454f230bc63b8516ede1c01e99
- Pointer size: 131 Bytes
- Size of remote file: 473 kB
examples/05-tea-and-ceramics.pngAdded

Large File Pointer Details
- SHA256: f2c78fefaa55e695575560e8e99b7c28a63b2ebf18bc9d99edc3f7a777a14961
- Pointer size: 131 Bytes
- Size of remote file: 420 kB
examples/06-greenhouse-on-mars.pngAdded

Large File Pointer Details
- SHA256: a5b37b4f68b8fb3b8b699340662ef81cf69e81c823e821687558f6818aa42da3
- Pointer size: 131 Bytes
- Size of remote file: 435 kB
examples/07-night-market.pngAdded

Large File Pointer Details
- SHA256: 26fce53f4796c676861d22e39160228df7f5376c59b92b0ad69a4706c9ed0de3
- Pointer size: 131 Bytes
- Size of remote file: 433 kB
examples/08-jewel-beetle.pngAdded

Large File Pointer Details
- SHA256: 4eecf397aeebb8f3bf0930fcd00f6c04544332dbee5959f720e3bf4a42976857
- Pointer size: 131 Bytes
- Size of remote file: 465 kB
examples/09-forest-in-watercolor.pngAdded

Large File Pointer Details
- SHA256: e724be24ea9ce3a60dde33f1948b192c0627e05150abf8c3ad6b5c33cd24ed0d
- Pointer size: 131 Bytes
- Size of remote file: 496 kB
examples/10-art-nouveau-garden.pngAdded

Large File Pointer Details
- SHA256: d195e415c27f396e80883255e2c6c39f56ce8d79d1f71f0e6dd7178b7bb74cb2
- Pointer size: 131 Bytes
- Size of remote file: 508 kB
examples/11-pixel-village.pngAdded
Large File Pointer Details
- SHA256: 632a9c6a7666bd84da58a402de19d5701dfc450abafdc328af60efff2de8426f
- Pointer size: 131 Bytes
- Size of remote file: 460 kB
examples/12-clockmaker's-shop.pngAdded

Large File Pointer Details
- SHA256: fb504219f24dcac28ee6e68f3601e1bae6ef466ce33e8163e243d9dabfcb33ba
- Pointer size: 131 Bytes
- Size of remote file: 450 kB
examples/13-oil-painted-harbor.pngAdded

Large File Pointer Details
- SHA256: 89bba1cd8d9972b3d892bd55f1fe53751fba94f45d085a35f1d3938e5c58a84a
- Pointer size: 131 Bytes
- Size of remote file: 457 kB
examples/14-concrete-atrium.pngAdded

Large File Pointer Details
- SHA256: e5c7fbc5d85f2a19074e78f59967ab0b450ef2b4456260b26f970f3094b358e4
- Pointer size: 131 Bytes
- Size of remote file: 421 kB
examples/15-goldfish-above-the-city.pngAdded

Large File Pointer Details
- SHA256: 0705d137111aa01f4a4bd4b7416bdd9b2ae5eeac8f16db3d3bcbbc7c84c50c09
- Pointer size: 131 Bytes
- Size of remote file: 443 kB
examples/16-orbital-repair.pngAdded

Large File Pointer Details
- SHA256: ad37f87047c198479573d2088cc50af75627428cdca2d2e9ab44751dcc5a64c5
- Pointer size: 131 Bytes
- Size of remote file: 430 kB
examples/17-last-train-home.pngAdded

Large File Pointer Details
- SHA256: 54bb75a6cb0c6bdc1bf65364ab75aa4afb0858b84b5a26d788a08ca0c93ef414
- Pointer size: 131 Bytes
- Size of remote file: 383 kB
examples/18-fashion-portrait.pngAdded

Large File Pointer Details
- SHA256: 9f3719dc24ee7855a9eb94686ea6c32a35e3d216edccbdcd81eb7ba9f4a5b23c
- Pointer size: 131 Bytes
- Size of remote file: 439 kB
examples/19-arctic-fox.pngAdded

Large File Pointer Details
- SHA256: c51563be401f4487ef1a656534faad1fba8d6b5d915e5594288d32cc8ff05c34
- Pointer size: 131 Bytes
- Size of remote file: 454 kB
examples/20-underwater-ruins.pngAdded

Large File Pointer Details
- SHA256: cb077115aaec40c4e3b3d167e1d5a04a96ea79687fdf61dcc35765a632c60877
- Pointer size: 131 Bytes
- Size of remote file: 474 kB
scheduler/scheduler_config.jsonAdded+22
text_encoder/config.jsonAdded+24
text_encoder/model.safetensorsAdded+3
tokenizer/merges.txtAdded
tokenizer/special_tokens_map.jsonAdded+30
tokenizer/tokenizer_config.jsonAdded+31
tokenizer/vocab.jsonAdded
unet/config.jsonAdded+68
unet/diffusion_pytorch_model.safetensorsAdded+3