Spaces:
Running on Zero
Running on Zero
Add NAG so the Krea 2 negative prompt works (guidance above 1 turns it on)
Browse filesFiles changed (2)
- app.py+471-456
- krea_nag.pyAdded+124
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456import jsonimport osimport randomimport reimport threadingfrom pathlib import Pathimport spaces # must come before torch / diffusersimport gradio as grimport torchfrom huggingface_hub import hf_hub_downloadfrom safetensors.torch import load_filefrom modeling_llm_adapter import AnimaLLMAdapter # noqa: F401 (needed to load the adapter)from pipeline import AnimaTextToImagePipelinefrom lora_hooks import LoraStorefrom anima_lora import LORAS as ANIMA_LORAS, download_lora, lora_prompt, parse_lora_stackfrom krea_characters import CHARACTERS, character_prompt, download_characterfrom ref_adapter import generate_with_reference, load_adapterHERE = Path(__file__).parentKREA = "Krea-2 Uncensored (Turbo merge)"ANIMA = "Anima V1"NOVA = "Nova Anime AM (v6.0 2.9B)"MODELS = [KREA, ANIMA, NOVA]MAX_SEED = 2**31 - 1FREE_TIER_CAP = 120 # seconds a free Hugging Face account may request per GPU callHF_TOKEN = os.environ.get("HF_TOKEN") # the Space owner's token: only needed to download the gated Krea 2 weights# ---------------------------------------------------------------------------# Anima V1 (CircleStone Labs). The diffusers copy holds the preview weights, so load that pipeline# and swap in the official V1 checkpoint (ComfyUI key names -> diffusers key names).# ---------------------------------------------------------------------------ANIMA_PIPE_ID = "CalamitousFelicitousness/Anima-sdnext-diffusers"ANIMA_CKPT_REPO = "circlestone-labs/Anima"ANIMA_CKPT_FILE = "split_files/diffusion_models/anima-base-v1.0.safetensors"_BLOCK_MAP = {"self_attn.q_proj": "attn1.to_q","self_attn.k_proj": "attn1.to_k","self_attn.v_proj": "attn1.to_v","self_attn.output_proj": "attn1.to_out.0","self_attn.q_norm": "attn1.norm_q","self_attn.k_norm": "attn1.norm_k","cross_attn.q_proj": "attn2.to_q","cross_attn.k_proj": "attn2.to_k","cross_attn.v_proj": "attn2.to_v","cross_attn.output_proj": "attn2.to_out.0","cross_attn.q_norm": "attn2.norm_q","cross_attn.k_norm": "attn2.norm_k","mlp.layer1": "ff.net.0.proj","mlp.layer2": "ff.net.2","adaln_modulation_self_attn.1": "norm1.linear_1","adaln_modulation_self_attn.2": "norm1.linear_2","adaln_modulation_cross_attn.1": "norm2.linear_1","adaln_modulation_cross_attn.2": "norm2.linear_2","adaln_modulation_mlp.1": "norm3.linear_1","adaln_modulation_mlp.2": "norm3.linear_2",}_TOP_MAP = {"net.x_embedder.proj.1.weight": "patch_embed.proj.weight","net.t_embedding_norm.weight": "time_embed.norm.weight","net.final_layer.adaln_modulation.1.weight": "norm_out.linear_1.weight","net.final_layer.adaln_modulation.2.weight": "norm_out.linear_2.weight","net.final_layer.linear.weight": "proj_out.weight",}def remap_anima_checkpoint(state_dict):"""Split a ComfyUI-format Anima checkpoint into diffusers transformer keys and LLM-adapter keys."""transformer, adapter, skipped = {}, {}, []for key, value in state_dict.items():if key.startswith("net.blocks."):block_n, module_key = key[len("net.blocks."):].split(".", 1)core, suffix = module_key, ""for tail in (".weight", ".bias"):if module_key.endswith(tail):core, suffix = module_key[: -len(tail)], tailif core in _BLOCK_MAP:transformer[f"transformer_blocks.{block_n}.{_BLOCK_MAP[core]}{suffix}"] = valueelse:skipped.append(key)elif key.startswith("net.llm_adapter."):adapter[key[len("net.llm_adapter."):]] = valueelif key in _TOP_MAP:transformer[_TOP_MAP[key]] = valueelse:match = re.match(r"net\.t_embedder\.\d+\.(linear_[12]\.weight)", key)if match:transformer[f"time_embed.t_embedder.{match.group(1)}"] = valueelse:skipped.append(key) # net.pos_embedder.* buffers: diffusers computes rotary embeddings itselfreturn transformer, adapter, skippedanima_pipe = AnimaTextToImagePipeline.from_pretrained(ANIMA_PIPE_ID, torch_dtype=torch.bfloat16, trust_remote_code=True)_tr, _ad, _skipped = remap_anima_checkpoint(load_file(hf_hub_download(ANIMA_CKPT_REPO, ANIMA_CKPT_FILE)))_missing, _unexpected = anima_pipe.transformer.load_state_dict(_tr, strict=False)_missing = [k for k in _missing if not k.endswith(".bias")] # the checkpoint is weight-only; biases start at zero_ad_missing, _ad_unexpected = anima_pipe.llm_adapter.load_state_dict(_ad, strict=False)print(f"[boot] anima transformer missing={len(_missing)} unexpected={len(_unexpected)} skipped={len(_skipped)}", flush=True)print(f"[boot] anima adapter missing={len(_ad_missing)} unexpected={len(_ad_unexpected)}", flush=True)if _missing or _unexpected or _ad_missing or _ad_unexpected:raise RuntimeError(f"Anima V1 checkpoint did not map cleanly: transformer missing {_missing[:5]} unexpected {_unexpected[:5]}; "f"adapter missing {_ad_missing[:5]} unexpected {_ad_unexpected[:5]}")# Models stay in CPU memory; generate() moves only the selected one to the GPU, because all of them together do not fit# the free ZeroGPU slice.# Optional reference-image adapter for Anima (ElectronGirl/anima-ref-adapter v2). It stays inactive unless a reference is# given, so a failure here only disables the reference option and never plain Anima or Krea.ref_adapter_error = Nonetry:load_adapter(anima_pipe.transformer)print("[boot] Anima reference adapter loaded", flush=True)except Exception as exc: # noqa: BLE001ref_adapter_error = f"The Anima reference adapter is unavailable on this Space: {exc}"print(f"[boot] {ref_adapter_error}", flush=True)# ---------------------------------------------------------------------------# Nova Anime AM v6.0 (2.9B), an Anima fine-tune from Civitai kept in a private model repo. It has 40 transformer blocks# instead of Anima V1's 28 and its own LLM adapter; the text encoder, tokenizers, VAE and scheduler are shared with# Anima V1. A failure here only disables this model.# ---------------------------------------------------------------------------nova_pipe = Nonenova_error = Nonetry:import copyfrom diffusers import CosmosTransformer3DModel_nova_state = load_file(hf_hub_download("asdasdadadsss/nova-anime-am", "novaAnimeAM_v6029B.safetensors", token=HF_TOKEN))_nova_state = {k.replace("model.diffusion_model.", "net.", 1): v for k, v in _nova_state.items()}_nova_tr, _nova_ad, _nova_skipped = remap_anima_checkpoint(_nova_state)del _nova_state_nova_layers = 1 + max(int(k.split(".")[1]) for k in _nova_tr if k.startswith("transformer_blocks."))_nova_transformer = CosmosTransformer3DModel.from_config(anima_pipe.transformer.config, num_layers=_nova_layers).to(torch.bfloat16)_nm, _nu = _nova_transformer.load_state_dict(_nova_tr, strict=False)_nm = [k for k in _nm if not k.endswith(".bias")]_nova_adapter = copy.deepcopy(anima_pipe.llm_adapter)_nam, _nau = _nova_adapter.load_state_dict(_nova_ad, strict=False)print(f"[boot] nova layers={_nova_layers} missing={len(_nm)} unexpected={len(_nu)} skipped={len(_nova_skipped)} "f"adapter missing={len(_nam)} unexpected={len(_nau)}", flush=True)if _nm or _nu or _nam or _nau:raise RuntimeError(f"Nova checkpoint did not map cleanly: missing {_nm[:5]} unexpected {_nu[:5]} adapter {_nam[:3]} {_nau[:3]}")nova_pipe = AnimaTextToImagePipeline(text_encoder=anima_pipe.text_encoder, tokenizer=anima_pipe.tokenizer, t5_tokenizer=anima_pipe.t5_tokenizer,llm_adapter=_nova_adapter, transformer=_nova_transformer.eval(), vae=anima_pipe.vae,scheduler=copy.deepcopy(anima_pipe.scheduler),)print("[boot] Nova Anime AM loaded", flush=True)except Exception as exc: # noqa: BLE001nova_error = f"Nova Anime AM is unavailable on this Space: {exc}"print(f"[boot] {nova_error}", flush=True)# ---------------------------------------------------------------------------# Krea 2 Turbo uncensored merge (Quiho/Krea2_NSFW_Uncensored_Complete): a Krea 2 Turbo based transformer plus an# abliterated Qwen3-VL text encoder, converted from ComfyUI FP8 files to bf16 (see krea_merge.py). Configs, tokenizer and# VAE come from the gated krea/Krea-2-Turbo repo (Krea 2 Community License), so HF_TOKEN must have accepted it.# A failure here must not take Anima down, so it is reported when someone picks the model.# ---------------------------------------------------------------------------# Allowlist: id -> (repo, file, ComfyUI-style key names). Only these ids are accepted from callers.KREA_LORAS = {"krea-distill-4step": ("lvladikov/Krea2-Turbo-Distill-4step-LoRA", "krea2_turbo_4step_rank_64_lora.safetensors", False),"krea-realism": ("gokaygokay/Krea-2-Realism-LoRA", "krea2_realism_lora.safetensors", True),"krea-nicegirls": ("asdasdadadsss/krea-loras", "nicegirls_krea2.safetensors", True),"krea-melancholy": ("asdasdadadsss/krea-loras", "melancholy_krea2.safetensors", True),"krea-masterpiece": ("asdasdadadsss/krea-loras", "masterpiece_krea2.safetensors", True),"krea-mavis-dracula": ("asdasdadadsss/krea-loras", "mavis_dracula_krea2.safetensors", True),"krea-figurecrafter": ("asdasdadadsss/krea-loras", "krea_figurecrafter.safetensors", True),"krea-sxz-arcane": ("asdasdadadsss/krea-loras", "krea_sxz_arcane.safetensors", True),"krea-christy": ("asdasdadadsss/krea-loras", "christy_krea2.safetensors", True),"krea-lowki": ("asdasdadadsss/krea-loras", "lowki_krea2.safetensors", True),"krea-lowki-face": ("asdasdadadsss/krea-loras", "lowki_face_krea2.safetensors", True),"krea-lowki-v3": ("asdasdadadsss/krea-loras", "lowki_v3_krea2.safetensors", True),"krea-bulgogi": ("asdasdadadsss/krea-loras", "bulgogi_krea2.safetensors", True),}KREA_LOCAL_CATALOG = json.loads((HERE / "krea_local_loras.json").read_text(encoding="utf-8"))KREA_LOCAL_LORAS = {item["id"]: item for item in KREA_LOCAL_CATALOG["loras"]}if KREA_LOCAL_LORAS.keys() & (KREA_LORAS.keys() | CHARACTERS.keys() | ANIMA_LORAS.keys()):raise ValueError("Duplicate local Krea LoRA ID")krea_loras_loaded = []LORAS = LoraStore() # parsed on the CPU, attached per requestkrea_pipe = Nonekrea_error = Nonetry:if not HF_TOKEN:raise RuntimeError("The Space has no HF_TOKEN secret, so the gated Krea 2 config files cannot be downloaded.")from krea_merge import load_krea_mergekrea_pipe = load_krea_merge(HF_TOKEN)print("[boot] Krea 2 uncensored merge loaded", flush=True)for _id, (_repo, _file, _comfy) in KREA_LORAS.items():try:LORAS.register(_id, hf_hub_download(_repo, _file, token=HF_TOKEN), _comfy)LORAS.prepare(_id)krea_loras_loaded.append(_id)print(f"[boot] Krea LoRA loaded: {_id}", flush=True)except Exception as lora_exc: # noqa: BLE001print(f"[boot] Krea LoRA {_id} unavailable: {lora_exc}", flush=True)except Exception as exc: # noqa: BLE001krea_error = f"The Krea 2 merge is unavailable on this Space: {exc}"print(f"[boot] {krea_error}", flush=True)# Anima / Nova LoRAs (anima_loras.json): downloaded and parsed on the CPU, and only offered when every layer fits the model.ANIMA_LORA_MODELS = {"anima-v1": ANIMA, "nova-anime": NOVA}anima_loras_loaded = []for _id, _item in ANIMA_LORAS.items():try:LORAS.register(_id, download_lora(_id, HF_TOKEN), "anima")_pipes = {"anima-v1": anima_pipe, "nova-anime": nova_pipe}_problems = [f"{_m}: {_p}" for _m in _item["models"] if _pipes[_m] is not None for _p in LORAS.problems(_pipes[_m].transformer, _id)]if _problems:raise RuntimeError(f"{len(_problems)} layers do not fit, e.g. {_problems[:2]}")anima_loras_loaded.append(_id)print(f"[boot] Anima LoRA loaded: {_id}", flush=True)except Exception as lora_exc: # noqa: BLE001print(f"[boot] Anima LoRA {_id} unavailable: {lora_exc}", flush=True)print("[boot] models ready: Anima V1" + (", Krea-2 merge" if krea_pipe else ""), flush=True)_lock = threading.Lock()def activate(model):"""Put the selected pipeline on the GPU and every other one back on the CPU. The ZeroGPU worker can be reused, so aprevious call's model may still be on the GPU, and all of them together do not fit."""pipes = {KREA: krea_pipe, ANIMA: anima_pipe, NOVA: nova_pipe}for name, pipe in pipes.items():if pipe is not None and name != model:pipe.to("cpu")torch.cuda.empty_cache()pipes[model].to("cuda")KREA_SAMPLERS = ("euler", "unipc")_krea_schedulers = {}def krea_scheduler(name):"""The scheduler object for a Krea sampler. Euler is the checkpoint's own; UniPC (second order) is built from the sameflow-matching settings, so it follows the same resolution-aware sigma schedule the pipeline asks for."""if name not in KREA_SAMPLERS:raise gr.Error(f"Unknown Krea sampler '{name}'. Choose one of: {', '.join(KREA_SAMPLERS)}.")_krea_schedulers.setdefault("euler", krea_pipe.scheduler)if name not in _krea_schedulers:try:from diffusers import UniPCMultistepSchedulerbase = _krea_schedulers["euler"].configsched = UniPCMultistepScheduler(num_train_timesteps=base.get("num_train_timesteps", 1000), prediction_type="flow_prediction", use_flow_sigmas=True,use_dynamic_shifting=True, time_shift_type="exponential", solver_order=2, lower_order_final=True,shift_terminal=base.get("shift_terminal"),)sched.register_to_config(**{k: base[k] for k in ("base_image_seq_len", "max_image_seq_len", "base_shift", "max_shift") if k in base})_krea_schedulers[name] = schedexcept Exception as exc: # noqa: BLE001raise gr.Error(f"The {name} sampler could not be set up: {exc}") from excreturn _krea_schedulers[name]def krea_estimate(steps, width, height):"""GPU seconds a Krea 2 Turbo call needs: a 12B model whose cost grows faster than the pixel count."""megapixels = int(width) * int(height) / (1024 * 1024)return 25 + int(steps) * 1.6 * megapixels ** 1.3def anima_estimate(steps, width, height, has_reference):"""About 0.5 s per step at 1 megapixel plus an allowance for moving the models to the GPU. With a reference everystep runs three model passes over a longer sequence, plus one extra pass to encode the reference."""megapixels = int(width) * int(height) / (1024 * 1024)if has_reference:return 30 + int(steps) * megapixels * 0.7 * 3.2return 25 + int(steps) * megapixels * 0.7def get_duration(model, prompt, negative_prompt, steps, guidance, width, height, seed, randomize_seed, lora_weight,ref_image=None, ref_guidance=4.5, lora_name="", lora_stack=None, sampler="euler", lazy_lora_files=None):megapixels = int(width) * int(height) / (1024 * 1024)if model == KREA:estimate = krea_estimate(steps, width, height)elif model == NOVA:estimate = anima_estimate(steps, width, height, False) * 1.5 # 40 blocks instead of 28elif model == ANIMA:estimate = anima_estimate(steps, width, height, ref_image is not None)else:estimate = 15 + int(steps) * megapixels * 0.4return int(min(FREE_TIER_CAP, max(20, estimate)))@spaces.GPU(duration=get_duration)def generate_gpu(model, prompt, negative_prompt, steps, guidance, width, height, seed, randomize_seed, lora_weight,ref_image=None, ref_guidance=4.5, lora_name="", lora_stack=None, sampler="euler", lazy_lora_files=None):if not str(prompt).strip():raise gr.Error("Enter a prompt.")if model == KREA and krea_pipe is None:raise gr.Error(krea_error or "The Krea 2 merge is unavailable on this Space.")if model == KREA and lora_name and lora_name not in krea_loras_loaded and lora_name not in CHARACTERS and lora_name not in KREA_LOCAL_LORAS:raise gr.Error(f"The Krea LoRA '{lora_name}' is not available on this Space.")if model == NOVA and nova_pipe is None:raise gr.Error(nova_error or "Nova Anime AM is unavailable on this Space.")# generate() has already validated and prepared the LoRAs; a direct call falls back to the single LoRA.stack = lora_stack if lora_stack is not None else ([(lora_name, float(lora_weight))] if lora_name else [])seed = random.randint(0, MAX_SEED) if randomize_seed or seed is None or int(seed) < 0 else int(seed)with _lock:activate(model)if model == KREA:width = max(256, min(2048, round(int(width) / 16) * 16)) # the transformer patches 16-pixel blocksheight = max(256, min(2048, round(int(height) / 16) * 16))steps = max(1, min(int(steps), 24))if krea_estimate(steps, width, height) > FREE_TIER_CAP - 8:raise gr.Error("This size and step count need more GPU time than a free account's 120 s window. Lower the steps or the size.")# Distilled: guidance 0 turns classifier-free guidance off, so the negative prompt is unused too.krea_pipe.scheduler = krea_scheduler(sampler or "euler") # set on every call, so Euler comes back after a UniPC run# ZeroGPU workers can start with only the registrations made at boot.for lora_id, (path, comfy) in (lazy_lora_files or {}).items():if not LORAS.known(lora_id):LORAS.register(lora_id, path, comfy)with LORAS.use_many(krea_pipe.transformer, stack):image = krea_pipe(prompt=str(prompt),height=height,width=width,num_inference_steps=steps,guidance_scale=0.0,generator=torch.Generator("cuda").manual_seed(seed),).images[0]elif model in (ANIMA, NOVA):width = max(256, min(1536, int(width) // 16 * 16)) # the Anima VAE/patching needs multiples of 16height = max(256, min(1536, int(height) // 16 * 16))if ref_image is not None and model == ANIMA:if ref_adapter_error:raise gr.Error(ref_adapter_error)if anima_estimate(steps, width, height, True) > FREE_TIER_CAP - 8:raise gr.Error("A reference image needs about 3x the GPU time of a plain image, so this size and step count ""do not fit a free account's 120 s window. Lower the steps or the size.")with LORAS.use_many(anima_pipe.transformer, stack): # the LoRA also shapes the reference pass; no-op without oneimage = generate_with_reference(anima_pipe, ref_image, prompt, negative_prompt or "", height, width, int(steps), float(guidance),ref_guidance=max(1.0, min(float(ref_guidance), 10.0)),generator=torch.Generator("cuda").manual_seed(seed),)return image, seedpipe = nova_pipe if model == NOVA else anima_pipewith LORAS.use_many(pipe.transformer, stack): # no-op without a LoRAimage = pipe(prompt=prompt,negative_prompt=negative_prompt or None,height=height,width=width,num_inference_steps=int(steps),guidance_scale=float(guidance),generator=torch.Generator("cuda").manual_seed(seed),).images[0]return image, seeddef lora_fits(lora_name, model):"""True when the catalog lists `lora_name` for this Space model."""return any(ANIMA_LORA_MODELS[model_id] == model for model_id in ANIMA_LORAS.get(lora_name, {}).get("models", ()))def generate(model, prompt, negative_prompt, steps, guidance, width, height, seed, randomize_seed, lora_weight,ref_image=None, ref_guidance=4.5, lora_name="", lora_stack="", sampler="euler"):if not str(prompt).strip():raise gr.Error("Enter a prompt.")try:# A filled stack replaces the single LoRA menu; otherwise the menu and strength behave as before.stack = parse_lora_stack(lora_stack) if str(lora_stack or "").strip() else ([(lora_name, float(lora_weight))] if lora_name else [])except ValueError as exc:raise gr.Error(str(exc)) from exclazy_lora_files = {}if stack:if model == KREA:if krea_pipe is None:raise gr.Error(krea_error or "The Krea 2 merge is unavailable on this Space.")for _id, _ in stack:if _id not in CHARACTERS and _id not in krea_loras_loaded and _id not in KREA_LOCAL_LORAS:raise gr.Error(f"The Krea LoRA '{_id}' is not available on this Space.")else:for _id, _ in stack:if _id not in anima_loras_loaded or not lora_fits(_id, model):raise gr.Error(f"The LoRA '{_id}' is not available for {model}.")try:# Download and validate the LoRAs before reserving a GPU.for _id, _ in stack:if _id in CHARACTERS:LORAS.register(_id, download_character(_id, token=HF_TOKEN), True)elif _id in KREA_LOCAL_LORAS:if not LORAS.known(_id):path = hf_hub_download(KREA_LOCAL_CATALOG["repo"], KREA_LOCAL_LORAS[_id]["file"], token=HF_TOKEN)LORAS.register(_id, path, True)problems = LORAS.problems(krea_pipe.transformer, _id)if problems:raise ValueError(f"{_id} has incompatible Krea layers: {', '.join(problems)}")LORAS.prepare(_id)if model == KREA and (_id in CHARACTERS or _id in KREA_LOCAL_LORAS):lazy_lora_files[_id] = LORAS.registration(_id)except Exception as exc:raise gr.Error(f"Could not load the selected LoRA: {exc}") from excfor _id, _ in stack:prompt = character_prompt(_id, prompt) if _id in CHARACTERS else lora_prompt(_id, prompt)local_trigger = KREA_LOCAL_LORAS.get(_id, {}).get("trigger")if local_trigger and not re.search(r"(?<!\w)" + re.escape(local_trigger) + r"(?!\w)", str(prompt), re.I):prompt = f"{local_trigger}, {prompt}"return generate_gpu(model, prompt, negative_prompt, steps, guidance, width, height, seed, randomize_seed,lora_weight, ref_image, ref_guidance, lora_name, stack, sampler, lazy_lora_files)with gr.Blocks(title="Image Models") as demo:gr.Markdown("# Image Models\nKrea 2 Turbo (Krea, 12B, 8 steps, Krea 2 Community License), Anima V1 (CircleStone Labs, ""Danbooru-style tags, non-commercial model licence).")model = gr.Dropdown(MODELS, value=ANIMA, label="Model")prompt = gr.Textbox(label="Prompt", lines=3, value="masterpiece, best quality, newest, safe, 1girl, solo, long hair, smile")negative = gr.Textbox(label="Negative prompt (not used by Krea)", lines=2, value="worst quality, low quality, score_1, score_2, score_3, blurry, jpeg artifacts, sepia")with gr.Row():steps = gr.Slider(1, 60, value=30, step=1, label="Steps (Krea: 8)")guidance = gr.Slider(1, 20, value=4.5, step=0.5, label="Guidance scale (Anima 4-5, Nova 4-6, Krea ignores it)")with gr.Row():width = gr.Slider(256, 2048, value=832, step=64, label="Width")height = gr.Slider(256, 2048, value=1216, step=64, label="Height")krea_labels = {"krea-lowki": "Lowki_Explicit", "krea-lowki-face": "Lowki", "krea-lowki-v3": "Lowki V3", "krea-bulgogi": "Bulgogi"}with gr.Row():seed = gr.Number(value=-1, precision=0, label="Seed (-1 = random)")randomize = gr.Checkbox(value=True, label="Randomize seed")lora_weight = gr.Slider(0, 1.5, value=1.0, step=0.05, label="LoRA strength", visible=False)lora_name_input = gr.Dropdown([("None", ""), *((krea_labels.get(name, name), name) for name in KREA_LORAS), *((item["label"], name) for name, item in KREA_LOCAL_LORAS.items()), *((item["label"], name) for name, item in CHARACTERS.items()), *((item["label"], name) for name, item in ANIMA_LORAS.items())], value="", label="LoRA (empty = none)", visible=False)lora_stack_input = gr.Textbox(label="LoRA stack (optional, up to 3: id:strength, id:strength; replaces the menu)", value="", visible=False)with gr.Row():ref_image = gr.Image(label="Reference image (Anima only, optional)", type="pil", sources=["upload"])ref_guidance = gr.Slider(1, 10, value=4.5, step=0.5, label="Reference guidance (Anima with a reference image)")button = gr.Button("Generate", variant="primary")out_image = gr.Image(label="Image", type="filepath", format="png")out_seed = gr.Number(label="Used seed", precision=0)button.click(generate,[model, prompt, negative, steps, guidance, width, height, seed, randomize, lora_weight, ref_image, ref_guidance, lora_name_input, lora_stack_input],[out_image, out_seed],api_name="generate",)# A second, API-only endpoint that also takes the Krea sampler. The Generate button and the endpoint above are unchanged, so# older copies of the app keep working; the app only calls this one when a sampler other than Euler is chosen.sampler_input = gr.Dropdown([("Euler (default)", "euler"), ("UniPC", "unipc")], value="euler", label="Krea sampler", visible=False)sampler_button = gr.Button("Generate with sampler", visible=False)sampler_button.click(generate,[model, prompt, negative, steps, guidance, width, height, seed, randomize, lora_weight, ref_image, ref_guidance, lora_name_input, lora_stack_input, sampler_input],[out_image, out_seed],api_name="generate_sampler",)demo.queue(max_size=20).launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471import contextlibimport jsonimport osimport randomimport reimport threadingfrom pathlib import Pathimport spaces # must come before torch / diffusersimport gradio as grimport torchfrom huggingface_hub import hf_hub_downloadfrom safetensors.torch import load_filefrom modeling_llm_adapter import AnimaLLMAdapter # noqa: F401 (needed to load the adapter)from pipeline import AnimaTextToImagePipelinefrom lora_hooks import LoraStorefrom anima_lora import LORAS as ANIMA_LORAS, download_lora, lora_prompt, parse_lora_stackfrom krea_characters import CHARACTERS, character_prompt, download_characterfrom krea_nag import krea_nagfrom ref_adapter import generate_with_reference, load_adapterHERE = Path(__file__).parentKREA = "Krea-2 Uncensored (Turbo merge)"ANIMA = "Anima V1"NOVA = "Nova Anime AM (v6.0 2.9B)"MODELS = [KREA, ANIMA, NOVA]MAX_SEED = 2**31 - 1FREE_TIER_CAP = 120 # seconds a free Hugging Face account may request per GPU callHF_TOKEN = os.environ.get("HF_TOKEN") # the Space owner's token: only needed to download the gated Krea 2 weights# ---------------------------------------------------------------------------# Anima V1 (CircleStone Labs). The diffusers copy holds the preview weights, so load that pipeline# and swap in the official V1 checkpoint (ComfyUI key names -> diffusers key names).# ---------------------------------------------------------------------------ANIMA_PIPE_ID = "CalamitousFelicitousness/Anima-sdnext-diffusers"ANIMA_CKPT_REPO = "circlestone-labs/Anima"ANIMA_CKPT_FILE = "split_files/diffusion_models/anima-base-v1.0.safetensors"_BLOCK_MAP = {"self_attn.q_proj": "attn1.to_q","self_attn.k_proj": "attn1.to_k","self_attn.v_proj": "attn1.to_v","self_attn.output_proj": "attn1.to_out.0","self_attn.q_norm": "attn1.norm_q","self_attn.k_norm": "attn1.norm_k","cross_attn.q_proj": "attn2.to_q","cross_attn.k_proj": "attn2.to_k","cross_attn.v_proj": "attn2.to_v","cross_attn.output_proj": "attn2.to_out.0","cross_attn.q_norm": "attn2.norm_q","cross_attn.k_norm": "attn2.norm_k","mlp.layer1": "ff.net.0.proj","mlp.layer2": "ff.net.2","adaln_modulation_self_attn.1": "norm1.linear_1","adaln_modulation_self_attn.2": "norm1.linear_2","adaln_modulation_cross_attn.1": "norm2.linear_1","adaln_modulation_cross_attn.2": "norm2.linear_2","adaln_modulation_mlp.1": "norm3.linear_1","adaln_modulation_mlp.2": "norm3.linear_2",}_TOP_MAP = {"net.x_embedder.proj.1.weight": "patch_embed.proj.weight","net.t_embedding_norm.weight": "time_embed.norm.weight","net.final_layer.adaln_modulation.1.weight": "norm_out.linear_1.weight","net.final_layer.adaln_modulation.2.weight": "norm_out.linear_2.weight","net.final_layer.linear.weight": "proj_out.weight",}def remap_anima_checkpoint(state_dict):"""Split a ComfyUI-format Anima checkpoint into diffusers transformer keys and LLM-adapter keys."""transformer, adapter, skipped = {}, {}, []for key, value in state_dict.items():if key.startswith("net.blocks."):block_n, module_key = key[len("net.blocks."):].split(".", 1)core, suffix = module_key, ""for tail in (".weight", ".bias"):if module_key.endswith(tail):core, suffix = module_key[: -len(tail)], tailif core in _BLOCK_MAP:transformer[f"transformer_blocks.{block_n}.{_BLOCK_MAP[core]}{suffix}"] = valueelse:skipped.append(key)elif key.startswith("net.llm_adapter."):adapter[key[len("net.llm_adapter."):]] = valueelif key in _TOP_MAP:transformer[_TOP_MAP[key]] = valueelse:match = re.match(r"net\.t_embedder\.\d+\.(linear_[12]\.weight)", key)if match:transformer[f"time_embed.t_embedder.{match.group(1)}"] = valueelse:skipped.append(key) # net.pos_embedder.* buffers: diffusers computes rotary embeddings itselfreturn transformer, adapter, skippedanima_pipe = AnimaTextToImagePipeline.from_pretrained(ANIMA_PIPE_ID, torch_dtype=torch.bfloat16, trust_remote_code=True)_tr, _ad, _skipped = remap_anima_checkpoint(load_file(hf_hub_download(ANIMA_CKPT_REPO, ANIMA_CKPT_FILE)))_missing, _unexpected = anima_pipe.transformer.load_state_dict(_tr, strict=False)_missing = [k for k in _missing if not k.endswith(".bias")] # the checkpoint is weight-only; biases start at zero_ad_missing, _ad_unexpected = anima_pipe.llm_adapter.load_state_dict(_ad, strict=False)print(f"[boot] anima transformer missing={len(_missing)} unexpected={len(_unexpected)} skipped={len(_skipped)}", flush=True)print(f"[boot] anima adapter missing={len(_ad_missing)} unexpected={len(_ad_unexpected)}", flush=True)if _missing or _unexpected or _ad_missing or _ad_unexpected:raise RuntimeError(f"Anima V1 checkpoint did not map cleanly: transformer missing {_missing[:5]} unexpected {_unexpected[:5]}; "f"adapter missing {_ad_missing[:5]} unexpected {_ad_unexpected[:5]}")# Models stay in CPU memory; generate() moves only the selected one to the GPU, because all of them together do not fit# the free ZeroGPU slice.# Optional reference-image adapter for Anima (ElectronGirl/anima-ref-adapter v2). It stays inactive unless a reference is# given, so a failure here only disables the reference option and never plain Anima or Krea.ref_adapter_error = Nonetry:load_adapter(anima_pipe.transformer)print("[boot] Anima reference adapter loaded", flush=True)except Exception as exc: # noqa: BLE001ref_adapter_error = f"The Anima reference adapter is unavailable on this Space: {exc}"print(f"[boot] {ref_adapter_error}", flush=True)# ---------------------------------------------------------------------------# Nova Anime AM v6.0 (2.9B), an Anima fine-tune from Civitai kept in a private model repo. It has 40 transformer blocks# instead of Anima V1's 28 and its own LLM adapter; the text encoder, tokenizers, VAE and scheduler are shared with# Anima V1. A failure here only disables this model.# ---------------------------------------------------------------------------nova_pipe = Nonenova_error = Nonetry:import copyfrom diffusers import CosmosTransformer3DModel_nova_state = load_file(hf_hub_download("asdasdadadsss/nova-anime-am", "novaAnimeAM_v6029B.safetensors", token=HF_TOKEN))_nova_state = {k.replace("model.diffusion_model.", "net.", 1): v for k, v in _nova_state.items()}_nova_tr, _nova_ad, _nova_skipped = remap_anima_checkpoint(_nova_state)del _nova_state_nova_layers = 1 + max(int(k.split(".")[1]) for k in _nova_tr if k.startswith("transformer_blocks."))_nova_transformer = CosmosTransformer3DModel.from_config(anima_pipe.transformer.config, num_layers=_nova_layers).to(torch.bfloat16)_nm, _nu = _nova_transformer.load_state_dict(_nova_tr, strict=False)_nm = [k for k in _nm if not k.endswith(".bias")]_nova_adapter = copy.deepcopy(anima_pipe.llm_adapter)_nam, _nau = _nova_adapter.load_state_dict(_nova_ad, strict=False)print(f"[boot] nova layers={_nova_layers} missing={len(_nm)} unexpected={len(_nu)} skipped={len(_nova_skipped)} "f"adapter missing={len(_nam)} unexpected={len(_nau)}", flush=True)if _nm or _nu or _nam or _nau:raise RuntimeError(f"Nova checkpoint did not map cleanly: missing {_nm[:5]} unexpected {_nu[:5]} adapter {_nam[:3]} {_nau[:3]}")nova_pipe = AnimaTextToImagePipeline(text_encoder=anima_pipe.text_encoder, tokenizer=anima_pipe.tokenizer, t5_tokenizer=anima_pipe.t5_tokenizer,llm_adapter=_nova_adapter, transformer=_nova_transformer.eval(), vae=anima_pipe.vae,scheduler=copy.deepcopy(anima_pipe.scheduler),)print("[boot] Nova Anime AM loaded", flush=True)except Exception as exc: # noqa: BLE001nova_error = f"Nova Anime AM is unavailable on this Space: {exc}"print(f"[boot] {nova_error}", flush=True)# ---------------------------------------------------------------------------# Krea 2 Turbo uncensored merge (Quiho/Krea2_NSFW_Uncensored_Complete): a Krea 2 Turbo based transformer plus an# abliterated Qwen3-VL text encoder, converted from ComfyUI FP8 files to bf16 (see krea_merge.py). Configs, tokenizer and# VAE come from the gated krea/Krea-2-Turbo repo (Krea 2 Community License), so HF_TOKEN must have accepted it.# A failure here must not take Anima down, so it is reported when someone picks the model.# ---------------------------------------------------------------------------# Allowlist: id -> (repo, file, ComfyUI-style key names). Only these ids are accepted from callers.KREA_LORAS = {"krea-distill-4step": ("lvladikov/Krea2-Turbo-Distill-4step-LoRA", "krea2_turbo_4step_rank_64_lora.safetensors", False),"krea-realism": ("gokaygokay/Krea-2-Realism-LoRA", "krea2_realism_lora.safetensors", True),"krea-nicegirls": ("asdasdadadsss/krea-loras", "nicegirls_krea2.safetensors", True),"krea-melancholy": ("asdasdadadsss/krea-loras", "melancholy_krea2.safetensors", True),"krea-masterpiece": ("asdasdadadsss/krea-loras", "masterpiece_krea2.safetensors", True),"krea-mavis-dracula": ("asdasdadadsss/krea-loras", "mavis_dracula_krea2.safetensors", True),"krea-figurecrafter": ("asdasdadadsss/krea-loras", "krea_figurecrafter.safetensors", True),"krea-sxz-arcane": ("asdasdadadsss/krea-loras", "krea_sxz_arcane.safetensors", True),"krea-christy": ("asdasdadadsss/krea-loras", "christy_krea2.safetensors", True),"krea-lowki": ("asdasdadadsss/krea-loras", "lowki_krea2.safetensors", True),"krea-lowki-face": ("asdasdadadsss/krea-loras", "lowki_face_krea2.safetensors", True),"krea-lowki-v3": ("asdasdadadsss/krea-loras", "lowki_v3_krea2.safetensors", True),"krea-bulgogi": ("asdasdadadsss/krea-loras", "bulgogi_krea2.safetensors", True),}KREA_LOCAL_CATALOG = json.loads((HERE / "krea_local_loras.json").read_text(encoding="utf-8"))KREA_LOCAL_LORAS = {item["id"]: item for item in KREA_LOCAL_CATALOG["loras"]}if KREA_LOCAL_LORAS.keys() & (KREA_LORAS.keys() | CHARACTERS.keys() | ANIMA_LORAS.keys()):raise ValueError("Duplicate local Krea LoRA ID")krea_loras_loaded = []LORAS = LoraStore() # parsed on the CPU, attached per requestkrea_pipe = Nonekrea_error = Nonetry:if not HF_TOKEN:raise RuntimeError("The Space has no HF_TOKEN secret, so the gated Krea 2 config files cannot be downloaded.")from krea_merge import load_krea_mergekrea_pipe = load_krea_merge(HF_TOKEN)print("[boot] Krea 2 uncensored merge loaded", flush=True)for _id, (_repo, _file, _comfy) in KREA_LORAS.items():try:LORAS.register(_id, hf_hub_download(_repo, _file, token=HF_TOKEN), _comfy)LORAS.prepare(_id)krea_loras_loaded.append(_id)print(f"[boot] Krea LoRA loaded: {_id}", flush=True)except Exception as lora_exc: # noqa: BLE001print(f"[boot] Krea LoRA {_id} unavailable: {lora_exc}", flush=True)except Exception as exc: # noqa: BLE001krea_error = f"The Krea 2 merge is unavailable on this Space: {exc}"print(f"[boot] {krea_error}", flush=True)# Anima / Nova LoRAs (anima_loras.json): downloaded and parsed on the CPU, and only offered when every layer fits the model.ANIMA_LORA_MODELS = {"anima-v1": ANIMA, "nova-anime": NOVA}anima_loras_loaded = []for _id, _item in ANIMA_LORAS.items():try:LORAS.register(_id, download_lora(_id, HF_TOKEN), "anima")_pipes = {"anima-v1": anima_pipe, "nova-anime": nova_pipe}_problems = [f"{_m}: {_p}" for _m in _item["models"] if _pipes[_m] is not None for _p in LORAS.problems(_pipes[_m].transformer, _id)]if _problems:raise RuntimeError(f"{len(_problems)} layers do not fit, e.g. {_problems[:2]}")anima_loras_loaded.append(_id)print(f"[boot] Anima LoRA loaded: {_id}", flush=True)except Exception as lora_exc: # noqa: BLE001print(f"[boot] Anima LoRA {_id} unavailable: {lora_exc}", flush=True)print("[boot] models ready: Anima V1" + (", Krea-2 merge" if krea_pipe else ""), flush=True)_lock = threading.Lock()def activate(model):"""Put the selected pipeline on the GPU and every other one back on the CPU. The ZeroGPU worker can be reused, so aprevious call's model may still be on the GPU, and all of them together do not fit."""pipes = {KREA: krea_pipe, ANIMA: anima_pipe, NOVA: nova_pipe}for name, pipe in pipes.items():if pipe is not None and name != model:pipe.to("cpu")torch.cuda.empty_cache()pipes[model].to("cuda")KREA_SAMPLERS = ("euler", "unipc")_krea_schedulers = {}def krea_scheduler(name):"""The scheduler object for a Krea sampler. Euler is the checkpoint's own; UniPC (second order) is built from the sameflow-matching settings, so it follows the same resolution-aware sigma schedule the pipeline asks for."""if name not in KREA_SAMPLERS:raise gr.Error(f"Unknown Krea sampler '{name}'. Choose one of: {', '.join(KREA_SAMPLERS)}.")_krea_schedulers.setdefault("euler", krea_pipe.scheduler)if name not in _krea_schedulers:try:from diffusers import UniPCMultistepSchedulerbase = _krea_schedulers["euler"].configsched = UniPCMultistepScheduler(num_train_timesteps=base.get("num_train_timesteps", 1000), prediction_type="flow_prediction", use_flow_sigmas=True,use_dynamic_shifting=True, time_shift_type="exponential", solver_order=2, lower_order_final=True,shift_terminal=base.get("shift_terminal"),)sched.register_to_config(**{k: base[k] for k in ("base_image_seq_len", "max_image_seq_len", "base_shift", "max_shift") if k in base})_krea_schedulers[name] = schedexcept Exception as exc: # noqa: BLE001raise gr.Error(f"The {name} sampler could not be set up: {exc}") from excreturn _krea_schedulers[name]def nag_strength(guidance, negative_prompt):"""Krea NAG strength: the Guidance slider above 1 (1 is off), and only with a negative prompt to push away from."""return max(0.0, min(float(guidance) - 1.0, 8.0)) if str(negative_prompt or "").strip() else 0.0def krea_estimate(steps, width, height, nag=False):"""GPU seconds a Krea 2 Turbo call needs: a 12B model whose cost grows faster than the pixel count."""megapixels = int(width) * int(height) / (1024 * 1024)return 25 + int(steps) * 1.6 * megapixels ** 1.3 * (1.3 if nag else 1) # NAG adds a negative text streamdef anima_estimate(steps, width, height, has_reference):"""About 0.5 s per step at 1 megapixel plus an allowance for moving the models to the GPU. With a reference everystep runs three model passes over a longer sequence, plus one extra pass to encode the reference."""megapixels = int(width) * int(height) / (1024 * 1024)if has_reference:return 30 + int(steps) * megapixels * 0.7 * 3.2return 25 + int(steps) * megapixels * 0.7def get_duration(model, prompt, negative_prompt, steps, guidance, width, height, seed, randomize_seed, lora_weight,ref_image=None, ref_guidance=4.5, lora_name="", lora_stack=None, sampler="euler", lazy_lora_files=None):megapixels = int(width) * int(height) / (1024 * 1024)if model == KREA:estimate = krea_estimate(steps, width, height, nag_strength(guidance, negative_prompt) > 0)elif model == NOVA:estimate = anima_estimate(steps, width, height, False) * 1.5 # 40 blocks instead of 28elif model == ANIMA:estimate = anima_estimate(steps, width, height, ref_image is not None)else:estimate = 15 + int(steps) * megapixels * 0.4return int(min(FREE_TIER_CAP, max(20, estimate)))@spaces.GPU(duration=get_duration)def generate_gpu(model, prompt, negative_prompt, steps, guidance, width, height, seed, randomize_seed, lora_weight,ref_image=None, ref_guidance=4.5, lora_name="", lora_stack=None, sampler="euler", lazy_lora_files=None):if not str(prompt).strip():raise gr.Error("Enter a prompt.")if model == KREA and krea_pipe is None:raise gr.Error(krea_error or "The Krea 2 merge is unavailable on this Space.")if model == KREA and lora_name and lora_name not in krea_loras_loaded and lora_name not in CHARACTERS and lora_name not in KREA_LOCAL_LORAS:raise gr.Error(f"The Krea LoRA '{lora_name}' is not available on this Space.")if model == NOVA and nova_pipe is None:raise gr.Error(nova_error or "Nova Anime AM is unavailable on this Space.")# generate() has already validated and prepared the LoRAs; a direct call falls back to the single LoRA.stack = lora_stack if lora_stack is not None else ([(lora_name, float(lora_weight))] if lora_name else [])seed = random.randint(0, MAX_SEED) if randomize_seed or seed is None or int(seed) < 0 else int(seed)with _lock:activate(model)if model == KREA:width = max(256, min(2048, round(int(width) / 16) * 16)) # the transformer patches 16-pixel blocksheight = max(256, min(2048, round(int(height) / 16) * 16))steps = max(1, min(int(steps), 24))nag_scale = nag_strength(guidance, negative_prompt)if krea_estimate(steps, width, height, nag_scale > 0) > FREE_TIER_CAP - 8:raise gr.Error("This size and step count need more GPU time than a free account's 120 s window. Lower the steps or the size.")# Distilled: guidance 0 turns classifier-free guidance off, so a plain negative prompt does nothing; NAG# (krea_nag.py) steers the image tokens away from it in attention space instead.krea_pipe.scheduler = krea_scheduler(sampler or "euler") # set on every call, so Euler comes back after a UniPC run# ZeroGPU workers can start with only the registrations made at boot.for lora_id, (path, comfy) in (lazy_lora_files or {}).items():if not LORAS.known(lora_id):LORAS.register(lora_id, path, comfy)with LORAS.use_many(krea_pipe.transformer, stack):nag = contextlib.nullcontext()if nag_scale > 0:with torch.no_grad():neg_embeds, neg_mask = krea_pipe.encode_prompt(prompt=[str(negative_prompt).strip()], device="cuda")nag = krea_nag(krea_pipe.transformer, neg_embeds, neg_mask, nag_scale)with nag:image = krea_pipe(prompt=str(prompt),height=height,width=width,num_inference_steps=steps,guidance_scale=0.0,generator=torch.Generator("cuda").manual_seed(seed),).images[0]elif model in (ANIMA, NOVA):width = max(256, min(1536, int(width) // 16 * 16)) # the Anima VAE/patching needs multiples of 16height = max(256, min(1536, int(height) // 16 * 16))if ref_image is not None and model == ANIMA:if ref_adapter_error:raise gr.Error(ref_adapter_error)if anima_estimate(steps, width, height, True) > FREE_TIER_CAP - 8:raise gr.Error("A reference image needs about 3x the GPU time of a plain image, so this size and step count ""do not fit a free account's 120 s window. Lower the steps or the size.")with LORAS.use_many(anima_pipe.transformer, stack): # the LoRA also shapes the reference pass; no-op without oneimage = generate_with_reference(anima_pipe, ref_image, prompt, negative_prompt or "", height, width, int(steps), float(guidance),ref_guidance=max(1.0, min(float(ref_guidance), 10.0)),generator=torch.Generator("cuda").manual_seed(seed),)return image, seedpipe = nova_pipe if model == NOVA else anima_pipewith LORAS.use_many(pipe.transformer, stack): # no-op without a LoRAimage = pipe(prompt=prompt,negative_prompt=negative_prompt or None,height=height,width=width,num_inference_steps=int(steps),guidance_scale=float(guidance),generator=torch.Generator("cuda").manual_seed(seed),).images[0]return image, seeddef lora_fits(lora_name, model):"""True when the catalog lists `lora_name` for this Space model."""return any(ANIMA_LORA_MODELS[model_id] == model for model_id in ANIMA_LORAS.get(lora_name, {}).get("models", ()))def generate(model, prompt, negative_prompt, steps, guidance, width, height, seed, randomize_seed, lora_weight,ref_image=None, ref_guidance=4.5, lora_name="", lora_stack="", sampler="euler"):if not str(prompt).strip():raise gr.Error("Enter a prompt.")try:# A filled stack replaces the single LoRA menu; otherwise the menu and strength behave as before.stack = parse_lora_stack(lora_stack) if str(lora_stack or "").strip() else ([(lora_name, float(lora_weight))] if lora_name else [])except ValueError as exc:raise gr.Error(str(exc)) from exclazy_lora_files = {}if stack:if model == KREA:if krea_pipe is None:raise gr.Error(krea_error or "The Krea 2 merge is unavailable on this Space.")for _id, _ in stack:if _id not in CHARACTERS and _id not in krea_loras_loaded and _id not in KREA_LOCAL_LORAS:raise gr.Error(f"The Krea LoRA '{_id}' is not available on this Space.")else:for _id, _ in stack:if _id not in anima_loras_loaded or not lora_fits(_id, model):raise gr.Error(f"The LoRA '{_id}' is not available for {model}.")try:# Download and validate the LoRAs before reserving a GPU.for _id, _ in stack:if _id in CHARACTERS:LORAS.register(_id, download_character(_id, token=HF_TOKEN), True)elif _id in KREA_LOCAL_LORAS:if not LORAS.known(_id):path = hf_hub_download(KREA_LOCAL_CATALOG["repo"], KREA_LOCAL_LORAS[_id]["file"], token=HF_TOKEN)LORAS.register(_id, path, True)problems = LORAS.problems(krea_pipe.transformer, _id)if problems:raise ValueError(f"{_id} has incompatible Krea layers: {', '.join(problems)}")LORAS.prepare(_id)if model == KREA and (_id in CHARACTERS or _id in KREA_LOCAL_LORAS):lazy_lora_files[_id] = LORAS.registration(_id)except Exception as exc:raise gr.Error(f"Could not load the selected LoRA: {exc}") from excfor _id, _ in stack:prompt = character_prompt(_id, prompt) if _id in CHARACTERS else lora_prompt(_id, prompt)local_trigger = KREA_LOCAL_LORAS.get(_id, {}).get("trigger")if local_trigger and not re.search(r"(?<!\w)" + re.escape(local_trigger) + r"(?!\w)", str(prompt), re.I):prompt = f"{local_trigger}, {prompt}"return generate_gpu(model, prompt, negative_prompt, steps, guidance, width, height, seed, randomize_seed,lora_weight, ref_image, ref_guidance, lora_name, stack, sampler, lazy_lora_files)with gr.Blocks(title="Image Models") as demo:gr.Markdown("# Image Models\nKrea 2 Turbo (Krea, 12B, 8 steps, Krea 2 Community License), Anima V1 (CircleStone Labs, ""Danbooru-style tags, non-commercial model licence).")model = gr.Dropdown(MODELS, value=ANIMA, label="Model")prompt = gr.Textbox(label="Prompt", lines=3, value="masterpiece, best quality, newest, safe, 1girl, solo, long hair, smile")negative = gr.Textbox(label="Negative prompt (Krea: only while the guidance slider is above 1)", lines=2, value="worst quality, low quality, score_1, score_2, score_3, blurry, jpeg artifacts, sepia")with gr.Row():steps = gr.Slider(1, 60, value=30, step=1, label="Steps (Krea: 8)")guidance = gr.Slider(1, 20, value=4.5, step=0.5, label="Guidance scale (Anima 4-5, Nova 4-6, Krea: 1 = off, above 1 = NAG strength guidance - 1, so 5 is a good start)")with gr.Row():width = gr.Slider(256, 2048, value=832, step=64, label="Width")height = gr.Slider(256, 2048, value=1216, step=64, label="Height")krea_labels = {"krea-lowki": "Lowki_Explicit", "krea-lowki-face": "Lowki", "krea-lowki-v3": "Lowki V3", "krea-bulgogi": "Bulgogi"}with gr.Row():seed = gr.Number(value=-1, precision=0, label="Seed (-1 = random)")randomize = gr.Checkbox(value=True, label="Randomize seed")lora_weight = gr.Slider(0, 1.5, value=1.0, step=0.05, label="LoRA strength", visible=False)lora_name_input = gr.Dropdown([("None", ""), *((krea_labels.get(name, name), name) for name in KREA_LORAS), *((item["label"], name) for name, item in KREA_LOCAL_LORAS.items()), *((item["label"], name) for name, item in CHARACTERS.items()), *((item["label"], name) for name, item in ANIMA_LORAS.items())], value="", label="LoRA (empty = none)", visible=False)lora_stack_input = gr.Textbox(label="LoRA stack (optional, up to 3: id:strength, id:strength; replaces the menu)", value="", visible=False)with gr.Row():ref_image = gr.Image(label="Reference image (Anima only, optional)", type="pil", sources=["upload"])ref_guidance = gr.Slider(1, 10, value=4.5, step=0.5, label="Reference guidance (Anima with a reference image)")button = gr.Button("Generate", variant="primary")out_image = gr.Image(label="Image", type="filepath", format="png")out_seed = gr.Number(label="Used seed", precision=0)button.click(generate,[model, prompt, negative, steps, guidance, width, height, seed, randomize, lora_weight, ref_image, ref_guidance, lora_name_input, lora_stack_input],[out_image, out_seed],api_name="generate",)# A second, API-only endpoint that also takes the Krea sampler. The Generate button and the endpoint above are unchanged, so# older copies of the app keep working; the app only calls this one when a sampler other than Euler is chosen.sampler_input = gr.Dropdown([("Euler (default)", "euler"), ("UniPC", "unipc")], value="euler", label="Krea sampler", visible=False)sampler_button = gr.Button("Generate with sampler", visible=False)sampler_button.click(generate,[model, prompt, negative, steps, guidance, width, height, seed, randomize, lora_weight, ref_image, ref_guidance, lora_name_input, lora_stack_input, sampler_input],[out_image, out_seed],api_name="generate_sampler",)demo.queue(max_size=20).launch()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124"""Normalized Attention Guidance (NAG) for the Krea 2 transformer, so a negative prompt works on the Turbo model.
Turbo is distilled for guidance 0 (no classifier-free guidance), so a normal negative prompt does nothing. NAG works inattention space instead: every block also runs the negative prompt's text tokens, and the image tokens' attention outputis pushed away from what the negative text would give (equations 7-10 of the NAG paper), then normalised and blendedback. The image state is shared, so the cost is one extra text stream, far less than a second full pass.
Ported from iljung1106/ComfyUI-Krea2-NAG (MIT) to diffusers' Krea2Transformer2DModel. With phi or alpha at 0 it isnumerically the stock forward pass."""
import contextlib
import torchimport torch.nn.functional as Ffrom diffusers.models.attention_dispatch import dispatch_attention_fnfrom diffusers.models.embeddings import apply_rotary_embfrom diffusers.models.modeling_outputs import Transformer2DModelOutput
def nag_blend(positive, negative, phi, tau, alpha): """Push `positive` away from `negative` by phi, cap the L1 growth at tau, then mix alpha of it back in.""" z_pos = positive.float() guided = z_pos + float(phi) * (z_pos - negative.float()) eps = torch.finfo(torch.float32).eps pos_norm = z_pos.abs().sum(dim=-1, keepdim=True).clamp_min(eps) guided_norm = guided.abs().sum(dim=-1, keepdim=True).clamp_min(eps) ratio = guided_norm / pos_norm guided = guided * (ratio.clamp_max(float(tau)) / ratio) return (float(alpha) * guided + (1.0 - float(alpha)) * z_pos).to(positive.dtype)
def _raw_attention(attn, hidden_states, rotary, mask): """The attention output before the sigmoid gate and the output projection, plus the gate.""" query = attn.norm_q(attn.to_q(hidden_states).unflatten(-1, (attn.num_heads, attn.head_dim))) key = attn.norm_k(attn.to_k(hidden_states).unflatten(-1, (attn.num_kv_heads, attn.head_dim))) value = attn.to_v(hidden_states).unflatten(-1, (attn.num_kv_heads, attn.head_dim)) gate = attn.to_gate(hidden_states) query = apply_rotary_emb(query, rotary, sequence_dim=1) key = apply_rotary_emb(key, rotary, sequence_dim=1) groups = attn.num_heads // attn.num_kv_heads if groups > 1: key = key.repeat_interleave(groups, dim=2) value = value.repeat_interleave(groups, dim=2) out = dispatch_attention_fn(query, key, value, attn_mask=mask) return out.flatten(2, 3), gate
def _nag_block(block, pos_text, neg_text, image, temb_mod, pos_rotary, neg_rotary, pos_mask, neg_mask, phi, tau, alpha): """One transformer block over [positive text | image] and [negative text | the same image]; only the first goes on.""" modulation = temb_mod.unflatten(-1, (6, -1)) + block.scale_shift_table prescale, preshift, pregate, postscale, postshift, postgate = modulation.unbind(-2) pos_len, neg_len = pos_text.shape[1], neg_text.shape[1]
pos = torch.cat([pos_text, image], dim=1) neg = torch.cat([neg_text, image], dim=1) pos_raw, pos_gate = _raw_attention(block.attn, (1.0 + prescale) * block.norm1(pos) + preshift, pos_rotary, pos_mask) neg_raw, neg_gate = _raw_attention(block.attn, (1.0 + prescale) * block.norm1(neg) + preshift, neg_rotary, neg_mask)
guided = nag_blend(pos_raw[:, pos_len:], neg_raw[:, neg_len:], phi, tau, alpha) pos_raw = torch.cat([pos_raw[:, :pos_len], guided], dim=1) pos_attn = block.attn.to_out[0](pos_raw * torch.sigmoid(pos_gate)) neg_attn = block.attn.to_out[0](neg_raw[:, :neg_len] * torch.sigmoid(neg_gate[:, :neg_len]))
pos = pos + pregate * pos_attn neg_text = neg_text + pregate * neg_attn pos = pos + postgate * block.ff((1.0 + postscale) * block.norm2(pos) + postshift) neg_text = neg_text + postgate * block.ff((1.0 + postscale) * block.norm2(neg_text) + postshift) return pos[:, :pos_len], neg_text, pos[:, pos_len:]
def _masks(text_mask, image_len): """The text-fusion key mask and the full-sequence key mask, as the stock forward builds them.""" if text_mask is None: return None, None image_mask = text_mask.new_ones((text_mask.shape[0], image_len)) return text_mask[:, None, None, :], torch.cat([text_mask, image_mask], dim=1)[:, None, None, :]
def nag_forward(transformer, negative_embeds, negative_mask, phi, tau, alpha, hidden_states, encoder_hidden_states, timestep, position_ids, encoder_attention_mask=None, attention_kwargs=None, return_dict=True): """Krea2Transformer2DModel.forward with a negative-prompt text stream guiding the image tokens.""" image_len = hidden_states.shape[1] pos_len, neg_len = encoder_hidden_states.shape[1], negative_embeds.shape[1]
temb = transformer.time_embed(timestep, dtype=hidden_states.dtype) temb_mod = transformer.time_mod_proj(F.gelu(temb, approximate="tanh"))
pos_fusion_mask, pos_mask = _masks(encoder_attention_mask, image_len) neg_fusion_mask, neg_mask = _masks(negative_mask, image_len) pos_text = transformer.txt_in(transformer.text_fusion(encoder_hidden_states, attention_mask=pos_fusion_mask)) neg_text = transformer.txt_in(transformer.text_fusion(negative_embeds, attention_mask=neg_fusion_mask)) image = transformer.img_in(hidden_states)
image_ids = position_ids[pos_len:] neg_ids = torch.cat([position_ids.new_zeros((neg_len, 3)), image_ids], dim=0) pos_rotary = transformer.rotary_emb(position_ids) neg_rotary = pos_rotary if neg_len == pos_len else transformer.rotary_emb(neg_ids)
for block in transformer.transformer_blocks: pos_text, neg_text, image = _nag_block( block, pos_text, neg_text, image, temb_mod, pos_rotary, neg_rotary, pos_mask, neg_mask, phi, tau, alpha )
output = transformer.final_layer(image, temb) if not return_dict: return (output,) return Transformer2DModelOutput(sample=output)
@contextlib.contextmanagerdef krea_nag(transformer, negative_embeds, negative_mask, phi, tau=2.5, alpha=0.25): """Route the transformer's forward through NAG for the block, then restore it, even when generation fails.""" def forward(hidden_states, encoder_hidden_states, timestep, position_ids, encoder_attention_mask=None, attention_kwargs=None, return_dict=True): return nag_forward(transformer, negative_embeds, negative_mask, phi, tau, alpha, hidden_states, encoder_hidden_states, timestep, position_ids, encoder_attention_mask, attention_kwargs, return_dict)
transformer.forward = forward try: yield finally: transformer.__dict__.pop("forward", None)app.py+471-456
krea_nag.pyAdded+124