Test3lora / app.py
observantdistressed's picture
Remove concurrency_limit — no request queue, memory cleanup retained
995d272 verified
Raw History Blame Contribute Delete
118 kB
"""MiniMax-H3 `t2va` / `fl2va`, split deployment — the denoising half."""
from __future__ import annotations
import glob
import json
import os
import re
import shutil
import struct
import tempfile
import threading
import time
import traceback
from functools import cache
# Before anything that could initialize CUDA: `import spaces` patches `torch.cuda` so the 72 GiB load can happen at
# startup rather than on GPU time.
import spaces
import gradio as gr
MODEL_REPO = os.environ.get("H3_MODEL_REPO", "MiniMaxAI/MiniMax-H3")
CONDITIONER_SPACE = os.environ.get("H3_CONDITIONER", "multimodalart/qwen3vl-conditioner")
# `pack` places the transformer at startup, `lazy` moves everything on the first GPU call, `offload` hands placement to
# `ComponentsManager.enable_auto_cpu_offload`.
PLACEMENT = os.environ.get("H3_PLACEMENT", "pack").lower()
# cuDNN's fused attention is 10-20% faster than the SDPA default on this pool and needs nothing installed.
ATTENTION = os.environ.get("H3_ATTENTION", "_native_cudnn").lower()
GPU_SIZE = os.environ.get("H3_GPU_SIZE", "xlarge")
# larryvrh distillation LoRA (diffusers conversion): A/B factors stored on CPU, merged on-demand inside @spaces.GPU.
TURBO_LORA_REPO = os.environ.get("H3_TURBO_LORA", "InstantX/MiniMax-H3-Turbo-Lora-Diffusers")
TURBO_LORA_FILE = "minimax_h3_turbo_4step_ckpt500_diffusers.safetensors"
TURBO_LORA_SCALE = 1.0 # alpha == rank
# NSFW / anatomy LoRAs (ComfyUI format, converted at load). Lazy: downloaded + converted on CPU in generate(),
# merged on GPU inside @spaces.GPU only when selected. Standard LoRA only — LoKR (.lokr_w1/.lokr_w2) is unsupported.
NSFW_LORA_CONFIGS = {
"nsfw_innie": {
"repo": "Hearmeman/minimax-h3-loras",
"file": "HMInnie_v1_e50.safetensors",
"scale": 1.0,
"label": "NSFW Innie Pussy (HMInnie V1)",
"trigger": "inniepussy",
"desc": "Renders the vulva as a neat 'innie' — labia tucked in with no protruding inner lips. Use for close-up genital shots where you want a clean, compact vulva look. Not for scenes needing prominent outer labia or detailed pussy anatomy — pair with HMPussy for that.",
},
"nsfw_penis": {
"repo": "observantdistressed/plora-h3", # CivitAI "Penis Lora - H3" v1.1, mirrored to HF
"file": "PLORA_H3_V2-step00006300.safetensors",
"scale": 0.7,
"label": "NSFW Penis (Penis Lora - H3 v1.1)",
"trigger": "PENISLORA",
"format": "kohya",
"desc": "Adds a detailed, erect penis to male subjects — the core anatomy LoRA for any scene with a visible penis. Use whenever a penis is in frame. Not for solo female scenes, and don't stack it with HMPenis v2.0 (same purpose, conflicting weights).",
},
"nsfw_dildo": {
"repo": "EllaPriest45/MinimaxH3_Actions", # CivitAI "Dildoing" model 2903074, backup repo
"file": "Dildoing - MinimaxH3 - pumping a dildo insider her vagina.safetensors",
"scale": 0.7,
"label": "NSFW Dildoing (Dildo Insertion)",
"trigger": "pumping a dildo insider her vagina",
"desc": "Makes dildo insertion read naturally — the toy slides into the vagina with proper depth and motion instead of clipping or floating. Use for any dildo penetration scene. Not for scenes without a dildo, and don't combine it with other insertion LoRAs at full strength.",
},
# Motion/action adapter — auto-loaded (not user-selectable) whenever any anatomy LoRA is on, so the
# anatomy renders sharply AND the act moves naturally. The Hearmeman README says to stack anatomy
# adapters underneath this action adapter.
"nsfw_aio": {
"repo": "Hearmeman/minimax-h3-loras",
"file": "HMNSFW-AIO-V2.5.safetensors",
"scale": 0.7,
"label": "HMNSFW AIO V2.5 (motion)",
"trigger": "hmmotion",
"desc": "Motion/action adapter that makes anatomy LoRAs move naturally during sex acts — auto-loaded whenever any NSFW LoRA is selected. Use stacked underneath anatomy LoRAs for sharp rendering plus natural motion. Not for standalone use; it's a motion enhancer, not an anatomy fix.",
},
# ── EllaPriest45/MinimaxH3_Actions catalog (t2va-compatible, standard LoRA only) ──
# 93 LoRAs, classified by header inspection: 80 ComfyUI + 13 kohya. LoKR, I2V, REF2V, R2V, FL2VA excluded.
# Triggers/scales extracted from the CivitAI filenames (best effort — refine per-LoRA as needed).
'nsfw_ahegao_face': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Ahegao Face - MinimaxH3 - She is making the ahegao face - eyes rolled back and tongue hanging out.safetensors',
"scale": 0.7,
"label": 'Ahegao Face',
"trigger": 'ahegao face',
"desc": "Makes the subject's face contort into the ahegao expression — eyes rolled back, tongue hanging out — for intense reaction shots. Use during orgasm or overstimulation scenes. Not for normal expressions or dialogue scenes; it overrides the face.",
},
'nsfw_all_tied_up': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'All Tied Up - MinimaxH3 - 0.8str.safetensors',
"scale": 0.8,
"label": 'All Tied Up',
"trigger": 'all tied up',
"desc": "Renders the subject bound and restrained, with rope or ties visible and functional. Use for bondage and restraint scenes. Not for scenes where the subject needs to move freely; it locks them into restraint poses.",
},
'nsfw_astro_nsfw': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Astro NSFW - MinimaxH3 - improves human movement and anatomy.safetensors',
"scale": 0.7,
"label": 'Astro NSFW',
"trigger": 'astro nsfw',
"format": "kohya",
"desc": "General NSFW quality enhancer that improves human movement and anatomy in explicit scenes. Use as a base layer on top of specific anatomy or act LoRAs. Not a specific act LoRA — don't expect it to produce a particular act on its own.",
},
'nsfw_auto_cunnilingus': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Auto-Cunnilingus - MinimaxH3 - She performs oral sex on herself.She licks her vulva.safetensors',
"scale": 0.7,
"label": 'Auto-Cunnilingus',
"trigger": 'She performs oral sex on herself.She licks her vulva',
"desc": "Makes the subject perform oral sex on herself — licking her own vulva. Use for self-cunnilingus scenes. Not for partnered cunnilingus; that's a different act with its own LoRAs.",
},
'nsfw_beanflk_masturbation_finger_insertion_au': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'BEANFLK - Masturbation & Finger Insertion + Audio - MinimaxH3 - BEANFLK,0.4str.safetensors',
"scale": 0.4,
"label": 'BEANFLK - Masturbation & Finger Insertion + Audio',
"trigger": 'BEANFLK',
"desc": "Masturbation with finger insertion, plus audio cues for the act. Use for solo fingering scenes. Not for scenes without finger penetration; the audio may not fit non-masturbation content.",
},
'nsfw_bunny_general_motion_continuity_repair': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'BUNNY General Motion Continuity Repair - MinimaxH3 - for dynamic scenes,bunny_crisp_motion,resmultistep+simple,euler+beta,0.9str,stage1,0.6str,stage2,0.25str.safetensors',
"scale": 0.9,
"label": 'BUNNY General Motion Continuity Repair',
"trigger": 'bunny_crisp_motion',
"desc": "Repairs motion continuity in dynamic scenes — reduces warping and keeps movement coherent across frames. Use for fast-action or high-motion shots. Not for slow, static scenes where it adds little.",
},
'nsfw_better_motion': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Better Motion - MinimaxH3 - 720x1280,15-30steps,0.2-0.4str.safetensors',
"scale": 0.3,
"label": 'Better Motion',
"trigger": 'better motion',
"desc": "General motion-quality LoRA that makes movement smoother and more natural. Use as a base enhancer for any scene. Not for specific acts; it's a motion polish, not an action generator.",
},
'nsfw_better_titfuck_v0_95': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Better Titfuck v0.95 - MinimaxH3 - res_multistep+simple,titjob,titfuck.safetensors',
"scale": 0.7,
"label": 'Better Titfuck v0.95',
"trigger": 'titjob,titfuck',
"desc": "Makes titfuck scenes read properly — breasts wrap around the penis with realistic motion. Use for titjob/titfuck scenes. Not for other sex acts; it specializes in breast-on-penis action.",
},
'nsfw_blowjob_v3_0': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Blowjob v3.0 - MinimaxH3 - bl0w_j0b.safetensors',
"scale": 0.7,
"label": 'Blowjob v3.0',
"trigger": 'bl0w_j0b',
"desc": "Core blowjob LoRA — makes oral sex on a penis read naturally with proper head motion. Use for blowjob scenes. Not for scenes without a visible penis; it won't do anything useful.",
},
'nsfw_blowjob_wearing_thong': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Blowjob wearing Thong - MinimaxH3 - blowjob_wearing_thong.safetensors',
"scale": 0.7,
"label": 'Blowjob wearing Thong',
"trigger": 'blowjob_wearing_thong',
"desc": "Blowjob variant where the performer keeps a thong on. Use for thong-clad blowjob scenes. Not for nude blowjobs — the thong is part of the concept.",
},
'nsfw_bluebella_nova_lingerie': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Bluebella Nova Lingerie - MinimaxH3 - She is wearing COLOR Bluebella Nova Lingerie.safetensors',
"scale": 0.7,
"label": 'Bluebella Nova Lingerie',
"trigger": 'She is wearing COLOR Bluebella Nova Lingerie',
"format": "kohya",
"desc": "Renders the subject wearing the Bluebella Nova lingerie set — a specific lace-and-straps design. Use for scenes featuring this exact lingerie. Not for other outfits; it's tied to this one garment.",
},
'nsfw_boob_physics': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Boob Physics - MinimaxH3 - jiggle,grab,massage,bounce.safetensors',
"scale": 0.7,
"label": 'Boob Physics',
"trigger": 'jiggle,grab,massage,bounce',
"desc": "Adds natural breast motion — jiggle, bounce, and sway during movement. Use for any scene with breast movement. Not for static shots; it only shows when there's motion.",
},
'nsfw_bustywomen': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'BustyWomen - MinimaxH3 - 0.75-1str.safetensors',
"scale": 0.88,
"label": 'BustyWomen',
"trigger": 'busty women',
"desc": "Makes female subjects busty — fuller, larger breasts. Use when you want a well-endowed figure. Not for flat-chested or petite figures; it conflicts with tiny-breast LoRAs.",
},
'nsfw_button_pop': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Button pop - MinimaxH3 - 0.2-0.5str,butt0n_p0p.safetensors',
"scale": 0.35,
"label": 'Button pop',
"trigger": 'butt0n_p0p',
"desc": "Makes buttons pop off clothing under strain — a clothing-failure effect. Use for scenes where a tight top bursts open. Not for general scenes; it's a specific gag/effect.",
},
'nsfw_cameltoe_v2_0': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Cameltoe v2.0 - MinimaxH3 - cameltoe.safetensors',
"scale": 0.7,
"label": 'Cameltoe v2.0',
"trigger": 'cameltoe',
"desc": "Renders a visible cameltoe through tight clothing. Use for scenes with tight bottoms. Not for nude scenes; it needs clothing to show through.",
},
'nsfw_can_t_stop_shaking': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": "Can't Stop Shaking! - MinimaxH3 - endface1,endbody1.safetensors",
"scale": 0.7,
"label": "Can't Stop Shaking!",
"trigger": 'endface1,endbody1',
"desc": "Makes the subject shake uncontrollably — body and face tremors, often during intense stimulation. Use for overstimulation and orgasm scenes. Not for calm scenes; it adds constant shaking.",
},
'nsfw_chasing_blowjob_v1_2': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Chasing blowjob v1.2 - MinimaxH3 - The girl performs a blowjob.safetensors',
"scale": 0.7,
"label": 'Chasing blowjob v1.2',
"trigger": 'The girl performs a blowjob',
"desc": "Blowjob where the performer chases the penis — active, eager head movement. Use for enthusiastic blowjob scenes. Not for slow or gentle oral; it's an energetic variant.",
},
'nsfw_combat_base_v2_0': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Combat BASE v2.0 - MinimaxH3 - prfight2,prfin1,res_multistep+simple,euler+beta.safetensors',
"scale": 0.7,
"label": 'Combat BASE v2.0',
"trigger": 'prfight2,prfin1',
"desc": "Base LoRA for fight and combat scenes — wrestling, grappling, and physical struggle. Use for combat or struggle scenes. Not for sex acts; it's a fight-motion base.",
},
'nsfw_cum_swallow': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Cum Swallow - MinimaxH3 - TADAA,0.4str.safetensors',
"scale": 0.4,
"label": 'Cum Swallow',
"trigger": 'TADAA',
"desc": "Makes the subject swallow cum after a facial or oral scene — the swallowing action reads clearly. Use for cum-swallow endings. Not for scenes without a cumshot; it needs the setup.",
},
'nsfw_cumshot': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Cumshot - MinimaxH3 - 20steps,euler+beta,0.85str.safetensors',
"scale": 0.85,
"label": 'Cumshot',
"trigger": 'cumshot',
"desc": "Renders a visible cumshot — ejaculation with realistic volume and motion. Use for cumshot scenes. Not for non-ejaculation scenes; it forces the act.",
},
'nsfw_deeper_hold_it': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Deeper... Hold It. - MinimaxH3 - oralmove1,oraldetail1,0.8str.safetensors',
"scale": 0.8,
"label": 'Deeper... Hold It.',
"trigger": 'oralmove1,oraldetail1',
"desc": "Oral-sex detail LoRA — deep-throat motion and oral detail. Use for deep oral scenes. Not for shallow kissing or foreplay; it's oral-specific.",
},
'nsfw_dildo_masturbation_v2_0': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Dildo Masturbation v2.0 - MinimaxH3 - She slide a dildo in and out of her pussy.safetensors',
"scale": 0.7,
"label": 'Dildo Masturbation v2.0',
"trigger": 'She slide a dildo in and out of her pussy',
"desc": "Makes solo dildo masturbation read naturally — the subject slides a dildo in and out of her pussy. Use for solo dildo scenes. Not for partnered penetration; it's solo-focused.",
},
'nsfw_disney_style_renaissance_era': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Disney Style - Renaissance Era - MinimaxH3 - In the style of Disney animation.safetensors',
"scale": 0.7,
"label": 'Disney Style - Renaissance Era',
"trigger": 'In the style of Disney animation',
"format": "kohya",
"desc": "Applies a Disney Renaissance-era animation style — the classic 90s hand-drawn look. Use for stylized or animated scenes. Not for photorealistic content; it fights realism.",
},
'nsfw_drone_shot': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Drone Shot - MinimaxH3 - dr0nesh0t.safetensors',
"scale": 0.7,
"label": 'Drone Shot',
"trigger": 'dr0nesh0t',
"desc": "Adds a drone-style aerial camera shot — high-angle and sweeping. Use for establishing or overhead shots. Not for close-up intimate scenes; it pulls the camera away.",
},
'nsfw_facial_cumshot_v0_1': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Facial CumShot v0.1 - MinimaxH3 - cmst.safetensors',
"scale": 0.7,
"label": 'Facial CumShot v0.1',
"trigger": 'cmst',
"desc": "Renders a facial cumshot — cum landing on the face. Use for facial scenes. Not for internal or swallow endings; it's face-specific.",
},
'nsfw_faster_harder_shake_harder_v0_2': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Faster! Harder! Shake Harder! v0.2 - MinimaxH3 - dynv2.safetensors',
"scale": 0.7,
"label": 'Faster! Harder! Shake Harder! v0.2',
"trigger": 'dynv2',
"desc": "Makes the subject move faster and harder — intense, vigorous motion. Use for rough or fast scenes. Not for gentle or slow scenes; it escalates intensity.",
},
'nsfw_fetish_submission_chain_teddy': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Fetish Submission Chain Teddy - MinimaxH3 - She is wearing a red latex fetish submission chain teddy.Her hands are bound in front of her.safetensors',
"scale": 0.7,
"label": 'Fetish Submission Chain Teddy',
"trigger": 'She is wearing a red latex fetish submission chain teddy',
"desc": "Renders the subject in a red latex fetish submission chain teddy, with her hands bound in front. Use for latex or bondage outfit scenes. Not for casual outfits; it's a specific fetish garment.",
},
'nsfw_fingering': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Fingering - MinimaxH3 - 0.8-1str.safetensors',
"scale": 0.9,
"label": 'Fingering',
"trigger": 'fingering',
"desc": "Makes fingering scenes read naturally — fingers inside the vagina with realistic motion. Use for manual stimulation scenes. Not for scenes without hand-on-genital contact.",
},
'nsfw_framerush': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'FrameRush - MinimaxH3 - lights.safetensors',
"scale": 0.7,
"label": 'FrameRush',
"trigger": 'lights',
"desc": "Camera and lighting effect LoRA — adds a rushed, dynamic frame feel. Use for energetic camera work. Not for stable, slow shots.",
},
'nsfw_furry_enhancer_video_v1_5': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Furry Enhancer Video v1.5 - MinimaxH3 - 0.6-0.7str.safetensors',
"scale": 0.65,
"label": 'Furry Enhancer Video v1.5',
"trigger": 'furry enhancer',
"desc": "Enhances furry and anthro characters in video — fur texture and anthro anatomy. Use for furry content. Not for human subjects; it will fur-ify them.",
},
'nsfw_futanari_transformation_futanarization_v': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Futanari transformation (Futanarization) v5.1 - MinimaxH3 - futanaei transformation,futanaei transformation.safetensors',
"scale": 0.7,
"label": 'Futanari transformation (Futanarization) v5.1',
"trigger": 'futanaei transformation',
"desc": "Renders futanari transformation — a female subject gaining a penis. Use for futanari or transformation scenes. Not for standard male-female scenes; it changes anatomy.",
},
'nsfw_grindtime': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Grindtime - MinimaxH3 - grindtime,a woman performing continuous rhythmic gyrating hip motion while having sex,front-rear-side view.safetensors',
"scale": 0.7,
"label": 'Grindtime',
"trigger": 'grindtime',
"desc": "Makes the subject perform continuous rhythmic hip grinding during sex — front, rear, and side views. Use for grinding or riding scenes. Not for static poses; it's a motion LoRA.",
},
'nsfw_h3_footjob_v0': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": "H3 Footjob v0 - MinimaxH3 - a photoealistic video depicting a woman sitting in front of the viewer.the camera angle is a male pov.the viewer's penis is exposed.the woman is performing a footjob.h3fj.safetensors",
"scale": 0.7,
"label": 'H3 Footjob v0',
"trigger": 'h3fj',
"desc": "POV footjob LoRA — the subject strokes a penis with her feet from a male POV. Use for footjob scenes. Not for scenes without a visible penis and feet; it's a specific POV setup.",
},
'nsfw_hmbreasts_v2_0': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'HMBreasts v2.0 - MinimaxH3 - tits,seeds2+ddim_uniform,8stepsturbolora.safetensors',
"scale": 0.7,
"label": 'HMBreasts v2.0',
"trigger": 'tits',
"desc": "Hearmeman breast LoRA — renders attractive, natural breasts. Use for breast-focused scenes. Not for flat-chested figures; it conflicts with tiny-breast LoRAs.",
},
'nsfw_hmmasturbation_squirting_and_female_mast': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'HMMasturbation - Squirting and Female Masturbation - MinimaxH3 - hmmasturbation,euler+simple,12steps,shift6,turbo lora 0.5str,use hmpussy at 0.4-0.8str.safetensors',
"scale": 0.6,
"label": 'HMMasturbation - Squirting and Female Masturbation',
"trigger": 'hmmasturbation',
"desc": "Hearmeman masturbation LoRA — solo masturbation with squirting. Use for solo scenes with squirting. Not for partnered sex; it's solo-focused.",
},
'nsfw_hmpenis_v2_0': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'HMPenis v2.0 - MinimaxH3 - penis,0.9str.safetensors',
"scale": 0.9,
"label": 'HMPenis v2.0',
"trigger": 'penis',
"desc": "Hearmeman penis LoRA — detailed erect penis anatomy. Use for any scene with a visible penis. Not for solo female scenes, and don't stack it with the dedicated penis LoRA (same purpose).",
},
'nsfw_hmpussy_v1_0': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'HMPussy v1.0 - MinimaxH3 - pussy,0.9str.safetensors',
"scale": 0.9,
"label": 'HMPussy v1.0',
"trigger": 'pussy',
"desc": "Hearmeman pussy LoRA — detailed vulva anatomy. Use for close-up genital shots. Not for scenes where the vulva isn't visible; it only affects what's in frame.",
},
'nsfw_hmsquirt_squirting_v0_1': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'HMSquirt - Squirting v0.1 - MinimaxH3 - euler+simple,hmsquirt,12steps,6shift,turbolora 0.5str.safetensors',
"scale": 0.5,
"label": 'HMSquirt - Squirting v0.1',
"trigger": 'hmsquirt',
"desc": "Hearmeman squirting LoRA — makes squirting read clearly during stimulation. Use for squirting scenes. Not for dry scenes; it forces the effect.",
},
'nsfw_hand_in_panties_masturbation': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Hand in Panties Masturbation - MinimaxH3 - 0.7str,She has her hand in her panties,She slides her hand in her panties.She rubs her vagina.safetensors',
"scale": 0.7,
"label": 'Hand in Panties Masturbation',
"trigger": 'She has her hand in her panties,She slides her hand in her panties.She rubs her vagina',
"desc": "Makes the subject slide her hand into her panties and rub herself. Use for clothed masturbation scenes. Not for nude masturbation; the panties are part of the concept.",
},
'nsfw_hip_gyration': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Hip Gyration - MinimaxH3 - gyrating her hips,0.8str.safetensors',
"scale": 0.8,
"label": 'Hip Gyration',
"trigger": 'gyrating her hips',
"desc": "Makes the subject gyrate her hips rhythmically — circular hip motion. Use for grinding or dancing scenes. Not for static poses; it's a motion LoRA.",
},
'nsfw_hip_sway_dance': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Hip Sway Dance - MinimaxH3 - dancing with arms in front.safetensors',
"scale": 0.7,
"label": 'Hip Sway Dance',
"trigger": 'dancing with arms in front',
"desc": "Dance LoRA — the subject dances with arms in front, swaying her hips. Use for dance scenes. Not for sex acts; it's a dance-motion LoRA.",
},
'nsfw_hitachi_magic_wand_vibrator': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Hitachi Magic Wand Vibrator - MinimaxH3 - using a Hitachi Magic Wand vibrator.safetensors',
"scale": 0.7,
"label": 'Hitachi Magic Wand Vibrator',
"trigger": 'using a Hitachi Magic Wand vibrator',
"desc": "Renders the subject using a Hitachi Magic Wand vibrator — the toy and its use read clearly. Use for vibrator scenes. Not for scenes without the toy; it won't add anything.",
},
'nsfw_holi_festival_of_colors': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Holi Festival of Colors - MinimaxH3 - Festival_of_Colors,multicolored smoke,multicolored paint,multicolored powder.safetensors',
"scale": 0.7,
"label": 'Holi Festival of Colors',
"trigger": 'Festival_of_Colors',
"desc": "Holi festival effect — multicolored smoke, paint, and powder. Use for colorful festival scenes. Not for NSFW acts; it's a visual-effects LoRA.",
},
'nsfw_huge_breasts_large_breasts': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Huge Breasts - Large Breasts - MinimaxH3 - bigsloppytits,huge-massive-enormous saggy breasts-bust,nip_protruding-flat-soft,areola_large-wide-medium-small.safetensors',
"scale": 0.7,
"label": 'Huge Breasts - Large Breasts',
"trigger": 'bigsloppytits',
"desc": "Renders huge, saggy breasts — massive with large areolas. Use for extreme-breast scenes. Not for natural or petite figures; it goes big.",
},
'nsfw_icy_ass_smacking': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Icy Ass Smacking - MinimaxH3 - icyslap.safetensors',
"scale": 0.7,
"label": 'Icy Ass Smacking',
"trigger": 'icyslap',
"desc": "Makes ass-smacking read naturally — the slap and the resulting jiggle. Use for spanking scenes. Not for non-spanking scenes; it forces the action.",
},
'nsfw_icy_twerk_pro_max_v2_0': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Icy Twerk Pro MAX v2.0 - MinimaxH3 - icytwerk.safetensors',
"scale": 0.7,
"label": 'Icy Twerk Pro MAX v2.0',
"trigger": 'icytwerk',
"desc": "Twerk LoRA — vigorous twerking with strong ass motion. Use for twerk scenes. Not for slow or gentle movement; it's high-energy.",
},
'nsfw_innie_pussy': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Innie Pussy - MinimaxH3.safetensors',
"scale": 0.7,
"label": 'Innie Pussy',
"trigger": 'inniepussy',
"format": "kohya",
"desc": "Innie pussy variant (kohya format) — a clean, tucked vulva look. Use for close-up genital shots wanting a neat innie. Not for scenes needing prominent labia; same caveat as the dedicated innie LoRA.",
},
'nsfw_jav_moans_audio_only': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'JAV moans audio only - MinimaxH3 - jpnMoans.safetensors',
"scale": 0.7,
"label": 'JAV moans audio only',
"trigger": 'jpnMoans',
"format": "kohya",
"desc": "Audio LoRA — adds JAV-style moans to the soundtrack. Use for scenes where you want Japanese AV-style vocalizations. Not for scenes with dialogue; it's audio-only.",
},
'nsfw_jiggle_walk': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'JIGGLE WALK - MinimaxH3 - JGLWLK.safetensors',
"scale": 0.7,
"label": 'JIGGLE WALK',
"trigger": 'JGLWLK',
"desc": "Makes the subject walk with a pronounced jiggle — breast and body bounce while walking. Use for walking scenes. Not for static or lying-down scenes; it needs locomotion.",
},
'nsfw_kaku_table_humping': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'KAKU - Table Humping - MinimaxH3 - 0.4-0.5str,KAKU,euler+simple.safetensors',
"scale": 0.45,
"label": 'KAKU - Table Humping',
"trigger": 'KAKU',
"desc": "Makes the subject hump a table or surface — grinding against furniture. Use for table-humping scenes. Not for partnered sex; it's a solo furniture act.",
},
'nsfw_lesbian_cunnilingus_v2_0': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Lesbian Cunnilingus v2.0 - MinimaxH3.safetensors',
"scale": 0.7,
"label": 'Lesbian Cunnilingus v2.0',
"trigger": 'lesbian cunnilingus',
"desc": "Lesbian cunnilingus — one woman performs oral sex on another. Use for lesbian oral scenes. Not for solo or hetero scenes; it's a partnered female act.",
},
'nsfw_licking_penis_and_testicles_nsfw_v1_2': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Licking Penis and Testicles (NSFW) v1.2 - MinimaxH3 - licking penis,licking testicles,licking penis tip,Only works if penis and testicles are in view.safetensors',
"scale": 0.7,
"label": 'Licking Penis and Testicles (NSFW) v1.2',
"trigger": 'licking penis,licking testicles,licking penis tip',
"desc": "Makes the subject lick a penis and testicles — detailed oral attention. Use for oral scenes focused on the penis and testicles. Only works if the penis and testicles are in view.",
},
'nsfw_mini_dick_fix_penis_helper': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Mini Dick Fix - Penis Helper - MinimaxH3 - 3r3kt (but not really needed).safetensors',
"scale": 0.7,
"label": 'Mini Dick Fix - Penis Helper',
"trigger": '3r3kt',
"desc": "Fixes the 'mini dick' problem — makes the penis render at a realistic size instead of shrinking. Use alongside any penis LoRA. Not a standalone anatomy LoRA; it's a helper.",
},
'nsfw_missionary_sex_pov': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Missionary Sex - POV - MinimaxH3 - having missionary sex.safetensors',
"scale": 0.7,
"label": 'Missionary Sex - POV',
"trigger": 'having missionary sex',
"desc": "Missionary sex from the male POV — the act reads naturally from above. Use for missionary scenes. Not for other positions; it's position-specific.",
},
'nsfw_moawxx_female_pleasure_moans_body_writhi': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Moawxx - Female Pleasure Moans + Body Writhing v0.1 2000e - MinimaxH3 - moawxx,0.6-0.85str.safetensors',
"scale": 0.72,
"label": 'Moawxx - Female Pleasure Moans + Body Writhing v0.1 2000e',
"trigger": 'moawxx',
"desc": "Moawxx pleasure LoRA — female moans plus body writhing during stimulation. Use for pleasure and orgasm scenes. Not for calm scenes; it adds audible and visible arousal.",
},
'nsfw_moawxx_female_pleasure_moans_body_writhi_2': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Moawxx - Female Pleasure Moans + Body Writhing v0.1 2500e - MinimaxH3 - moawxx,0.6-0.85str.safetensors',
"scale": 0.72,
"label": 'Moawxx - Female Pleasure Moans + Body Writhing v0.1 2500e',
"trigger": 'moawxx',
"desc": "Moawxx pleasure LoRA — female moans plus body writhing during stimulation (2500e training variant). Use for pleasure and orgasm scenes. Not for calm scenes; it adds audible and visible arousal.",
},
'nsfw_moawxx_female_pleasure_moans_body_writhi_3': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Moawxx - Female Pleasure Moans + Body Writhing v0.1 2750e - MinimaxH3 - moawxx,0.6-0.85str.safetensors',
"scale": 0.72,
"label": 'Moawxx - Female Pleasure Moans + Body Writhing v0.1 2750e',
"trigger": 'moawxx',
"desc": "Moawxx pleasure LoRA — female moans plus body writhing during stimulation (2750e training variant). Use for pleasure and orgasm scenes. Not for calm scenes; it adds audible and visible arousal.",
},
'nsfw_mystic_xxx_v2_0': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Mystic XXX v2.0 - MinimaxH3 - 0.7str.safetensors',
"scale": 0.7,
"label": 'Mystic XXX v2.0',
"trigger": 'mystic xxx',
"desc": "General NSFW enhancer — improves overall explicitness and scene quality. Use as a base on top of specific act LoRAs. Not a specific act; it's a general boost.",
},
'nsfw_natural_sagging_breasts': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Natural Sagging Breasts - MinimaxH3 - She has naturally sagging breasts.safetensors',
"scale": 0.7,
"label": 'Natural Sagging Breasts',
"trigger": 'She has naturally sagging breasts',
"desc": "Renders naturally sagging breasts — realistic gravity and shape. Use for mature or natural figures. Not for perky or enhanced breasts; it adds sag.",
},
'nsfw_natural_saggy_boobs': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Natural Saggy Boobs - MinimaxH3 - hugesaggytits,shirt-lift titty drop,bra unhook from behind,then drop.safetensors',
"scale": 0.7,
"label": 'Natural Saggy Boobs',
"trigger": 'hugesaggytits',
"desc": "Saggy boobs with specific reveal actions — shirt-lift titty drop and bra unhook from behind. Use for breast-reveal scenes. Not for clothed scenes; it's about the reveal.",
},
'nsfw_nipple_play': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Nipple Play - MinimaxH3 - flicks her own nipples,gently pinch and slowly roll her own beautifully formed,fully erect,firm and symmetrical nipples.safetensors',
"scale": 0.7,
"label": 'Nipple Play',
"trigger": 'nipple play',
"desc": "Makes the subject play with her nipples — flicking, pinching, and rolling them. Use for nipple-play scenes. Not for scenes without breast focus; it centers on the nipples.",
},
'nsfw_pjslide_pussyjob': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'PJSLIDE - Pussyjob - MinimaxH3 - 0.5str,PJSLIDE,add HMPenis lora at 0.5str.safetensors',
"scale": 0.5,
"label": 'PJSLIDE - Pussyjob',
"trigger": 'PJSLIDE',
"desc": "Pussyjob LoRA — the penis slides along the vulva. Use for pussyjob scenes; the author recommends adding the penis LoRA at 0.5 strength alongside it. Not for penetration scenes; it's a sliding act.",
},
'nsfw_pk_parasyte_turbo_clean_up_the_models_vi': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'PK Parasyte Turbo (clean up the models visuals and audio) - MinimaxH3 - 3.5-5str,6-8steps,8-3 shift,euler+simple.safetensors',
"scale": 4.25,
"label": 'PK Parasyte Turbo (clean up the models visuals and audio)',
"trigger": 'PK Parasyte Turbo',
"desc": "Turbo LoRA that cleans up model visuals and audio — improves overall quality at low step counts. Use with turbo mode (6-8 steps, high strength 3.5-5). Not for standard 25-step generation; it's tuned for turbo.",
},
'nsfw_pov_missionary_insertion_v0_7': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'POV Missionary Insertion v0.7 - MinimaxH3.safetensors',
"scale": 0.7,
"label": 'POV Missionary Insertion v0.7',
"trigger": 'missionary insertion',
"format": "kohya",
"desc": "POV missionary insertion — the insertion moment reads clearly from the male POV. Use for missionary insertion scenes. Not for other positions; it's position-specific.",
},
'nsfw_passionate_kissing': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Passionate Kissing - MinimaxH3 - They kiss passionately,1str.safetensors',
"scale": 1.0,
"label": 'Passionate Kissing',
"trigger": 'They kiss passionately',
"desc": "Makes passionate kissing read naturally — lip contact and head motion. Use for kissing scenes. Not for oral or sex acts; it's kissing-specific.",
},
'nsfw_photorealistic_image_generator': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Photorealistic Image Generator - MinimaxH3 - ph0t0r34l.safetensors',
"scale": 0.7,
"label": 'Photorealistic Image Generator',
"trigger": 'ph0t0r34l',
"format": "kohya",
"desc": "Pushes output toward photorealism — more realistic textures and lighting. Use for photorealistic scenes. Not for stylized or animated content; it fights the style.",
},
'nsfw_pillow_humping': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Pillow Humping - MinimaxH3 - She is straddling a pillow.She is humping the pillow.safetensors',
"scale": 0.7,
"label": 'Pillow Humping',
"trigger": 'She is straddling a pillow.She is humping the pillow',
"desc": "Makes the subject straddle and hump a pillow — solo grinding on a pillow. Use for pillow-humping scenes. Not for partnered sex; it's a solo act.",
},
'nsfw_pokies': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Pokies - MinimaxH3 - covered nipples,pokies.safetensors',
"scale": 0.7,
"label": 'Pokies',
"trigger": 'covered nipples,pokies',
"format": "kohya",
"desc": "Renders visible nipple outlines through clothing — pokies. Use for clothed scenes with tight tops. Not for nude scenes; it needs clothing.",
},
'nsfw_polyhedron_perfect_eyes_perfect_skin_per': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Polyhedron Perfect Eyes - Perfect Skin - Perfect Hands T2VA - MinimaxH3 - perfe8ct,perfect hands,perfect skin,perfect eyes.safetensors',
"scale": 0.7,
"label": 'Polyhedron Perfect Eyes - Perfect Skin - Perfect Hands T2VA',
"trigger": 'perfe8ct',
"desc": "Quality enhancer for eyes, skin, and hands — fixes common rendering flaws. Use as a general quality boost for any scene. Not for specific acts; it's a detail fixer.",
},
'nsfw_realism_people': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Realism People - MinimaxH3 - r34l1sm,0.6-1str.safetensors',
"scale": 0.8,
"label": 'Realism People',
"trigger": 'r34l1sm',
"desc": "Makes people look more realistic — natural proportions and skin. Use for photorealistic human scenes. Not for stylized content; it fights the style.",
},
'nsfw_sexgod_after_midnight_sexytime_r64': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'SexGod After Midnight Sexytime R64 - MinimaxH3 - euler+beta.safetensors',
"scale": 0.7,
"label": 'SexGod After Midnight Sexytime R64',
"trigger": 'sexgod',
"format": "kohya",
"desc": "SexGod base LoRA — general NSFW scene quality. Use as a base enhancer on top of specific act LoRAs. Not a specific act; it's a general boost.",
},
'nsfw_sexgod_s_naughtytimes_v2_0_pruned_rank25': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": "SexGod's NaughtyTimes v2.0 pruned rank256 - MinimaxH3.safetensors",
"scale": 0.7,
"label": "SexGod's NaughtyTimes v2.0 pruned rank256",
"trigger": 'naughtytimes',
"format": "kohya",
"desc": "SexGod's NaughtyTimes — general NSFW scene enhancer (rank-256 pruned). Use as a base enhancer. Not act-specific; pair it with act LoRAs.",
},
'nsfw_sexgod_s_naughtytimes_v2_0_pruned_rank51': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": "SexGod's NaughtyTimes v2.0 pruned rank512 - MinimaxH3.safetensors",
"scale": 0.7,
"label": "SexGod's NaughtyTimes v2.0 pruned rank512",
"trigger": 'naughtytimes',
"format": "kohya",
"desc": "SexGod's NaughtyTimes — general NSFW scene enhancer (rank-512 pruned, slightly higher capacity). Use as a base enhancer. Pick one of the two NaughtyTimes variants; don't stack both.",
},
'nsfw_she_struts': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'She Struts - MinimaxH3 - she struts.safetensors',
"scale": 0.7,
"label": 'She Struts',
"trigger": 'she struts',
"desc": "Makes the subject strut — confident walking with attitude. Use for walk or entrance scenes. Not for static scenes; it needs locomotion.",
},
'nsfw_sideview_deepthroat_gag_audio': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'SideView Deepthroat Gag Audio - MinimaxH3.safetensors',
"scale": 0.7,
"label": 'SideView Deepthroat Gag Audio',
"trigger": 'deepthroat',
"format": "kohya",
"desc": "Side-view deepthroat with gag audio — the gag reflex reads and sounds. Use for deepthroat scenes. Not for gentle oral; it's intense.",
},
'nsfw_skin_tight_bottoms_cameltoe': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Skin Tight Bottoms (Cameltoe) - MinimaxH3 - cameltoe,0.9str.safetensors',
"scale": 0.9,
"label": 'Skin Tight Bottoms (Cameltoe)',
"trigger": 'cameltoe',
"desc": "Skin-tight bottoms with a visible cameltoe. Use for tight-clothing scenes. Not for nude scenes; it needs the clothing.",
},
'nsfw_slop_twerk_v0_2_epoch6': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": "Slop Twerk v0.2 Epoch6 - MinimaxH3 - twerks causing her ass to jiggle and shake,0.5-1str,0.5 STR if you don't want Asians in T2V.safetensors",
"scale": 0.75,
"label": 'Slop Twerk v0.2 Epoch6',
"trigger": 'twerk',
"desc": "Twerk LoRA with strong ass jiggle and shake. Use for twerk scenes. Note: use 0.5 strength if you don't want Asian subjects in text-to-video.",
},
'nsfw_slop_bounce': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Slop bounce - MinimaxH3 - breasts bounce,shake,jiggle,sway.safetensors',
"scale": 0.7,
"label": 'Slop bounce',
"trigger": 'breasts bounce',
"desc": "Breast bounce, shake, jiggle, and sway during movement. Use for any scene with breast motion. Not for static shots; it only shows with movement.",
},
'nsfw_snow_white_lingerie': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Snow White Lingerie - MinimaxH3 - She is wearing slutty snow white lingerie.safetensors',
"scale": 0.7,
"label": 'Snow White Lingerie',
"trigger": 'She is wearing slutty snow white lingerie',
"desc": "Renders the subject in slutty Snow White lingerie. Use for scenes featuring this specific outfit. Not for other outfits; it's tied to this garment.",
},
'nsfw_strapon_dildo_v0_1': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Strapon Dildo v0.1 - MinimaxH3 - She is wearing a strapon dildo.safetensors',
"scale": 0.7,
"label": 'Strapon Dildo v0.1',
"trigger": 'She is wearing a strapon dildo',
"desc": "Makes the subject wear and use a strapon dildo. Use for strapon scenes. Not for scenes without the toy; it won't add anything.",
},
'nsfw_synth_pussy_v0_5': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Synth Pussy v0.5 - MinimaxH3.safetensors',
"scale": 0.7,
"label": 'Synth Pussy v0.5',
"trigger": 'synth pussy',
"format": "kohya",
"desc": "Synth pussy — a stylized or synthetic vulva rendering. Use for stylized genital shots. Not for photorealistic anatomy; it's a stylized look.",
},
'nsfw_the_orgasm_button': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'The Orgasm button - MinimaxH3 - Remoteorgasm.safetensors',
"scale": 0.7,
"label": 'The Orgasm button',
"trigger": 'Remoteorgasm',
"desc": "Remote-control orgasm — the subject reacts to a remote trigger. Use for orgasm-control scenes. Not for natural orgasms; it's the remote-control concept.",
},
'nsfw_thumb_finger_puppets': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Thumb-Finger puppets - MinimaxH3 - A thumb person.safetensors',
"scale": 0.7,
"label": 'Thumb-Finger puppets',
"trigger": 'A thumb person',
"desc": "Thumb-finger puppets — a 'thumb person' novelty effect. Use for puppet or novelty scenes. Not for realistic content; it's a gag.",
},
'nsfw_thumbinbutt': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'ThumbInButt - MinimaxH3 - thum1n8utt,the man inserts his right thumb in her anus causing the woman to moan with pleasure.safetensors',
"scale": 0.7,
"label": 'ThumbInButt',
"trigger": 'thum1n8utt',
"desc": "Makes the man insert his thumb into the woman's anus, causing a pleasure moan. Use for anal-fingering scenes. Not for non-anal scenes; it forces the action.",
},
'nsfw_tiddies_and_realism_slider_vbeta': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Tiddies and Realism Slider vBeta - MinimaxH3 - 0.4-2str.safetensors',
"scale": 1.2,
"label": 'Tiddies and Realism Slider vBeta',
"trigger": 'tiddies and realism',
"desc": "Slider LoRA — adjust breast size and realism on a scale (0.4-2 strength; 1.2 is a good default). Use to fine-tune breast size. Not a fixed anatomy LoRA; it's a continuous slider.",
},
'nsfw_tiny_breasts_flat_chest': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Tiny Breasts - Flat Chest - MinimaxH3 - She is flat chested,she has a flat chest.safetensors',
"scale": 0.7,
"label": 'Tiny Breasts - Flat Chest',
"trigger": 'She is flat chested,she has a flat chest',
"desc": "Renders a flat chest or tiny breasts. Use for petite figures. Not for busty figures; it conflicts with breast-size LoRAs.",
},
'nsfw_tiny_panties': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Tiny Panties - MinimaxH3 - She is wearing tiny panties.safetensors',
"scale": 0.7,
"label": 'Tiny Panties',
"trigger": 'She is wearing tiny panties',
"desc": "Renders the subject in tiny panties — minimal coverage. Use for lingerie scenes. Not for nude scenes; the panties are the point.",
},
'nsfw_torpedo_tits_t2v': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Torpedo Tits T2V - MinimaxH3 - torpedo tits,a 20 year old woman,wearing nothing shows off her medium sized torpedo tit breasts.safetensors',
"scale": 0.7,
"label": 'Torpedo Tits T2V',
"trigger": 'torpedo tits',
"desc": "Torpedo-shaped breasts — a specific conical breast shape. Use for torpedo-tit scenes. Not for natural shapes; it imposes the torpedo look.",
},
'nsfw_transition_boomsplitro': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Transition BoomSplitRo - MinimaxH3 - ysp_spliroa12 a woman. hard cut with no smooth transition, jumps straight into spitroast.safetensors',
"scale": 0.7,
"label": 'Transition BoomSplitRo',
"trigger": 'ysp_spliroa12',
"format": "kohya",
"desc": "Hard-cut transition straight into a spitroast scene — no smooth transition. Use for abrupt scene changes. Not for continuous scenes; it's a cut effect.",
},
'nsfw_transition_f2v_instant_cut_to_things': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Transition F2V - Instant Cut to Things - MinimaxH3 - ysp_smshcut.safetensors',
"scale": 0.7,
"label": 'Transition F2V - Instant Cut to Things',
"trigger": 'ysp_smshcut',
"format": "kohya",
"desc": "Instant cut transition to a new scene. Use for abrupt scene changes. Not for continuous scenes; it's a cut effect.",
},
'nsfw_tribtime': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Tribtime - MinimaxH3 - tribtime.safetensors',
"scale": 0.7,
"label": 'Tribtime',
"trigger": 'tribtime',
"desc": "Tribbing — scissoring or grinding between two women. Use for tribadism scenes. Not for solo scenes; it needs two partners.",
},
'nsfw_upskirt_helper_v0_1': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Upskirt Helper v0.1 - MinimaxH3 - upsk1rt_panties,upsk1rt_no_panties.safetensors',
"scale": 0.7,
"label": 'Upskirt Helper v0.1',
"trigger": 'upsk1rt_panties,upsk1rt_no_panties',
"format": "kohya",
"desc": "Upskirt view — with or without panties. Use for upskirt shots. Not for nude scenes; it needs a skirt.",
},
'nsfw_whispering': {
"repo": "EllaPriest45/MinimaxH3_Actions",
"file": 'Whispering - MinimaxH3 - 0.7str,she whisper XYZ.safetensors',
"scale": 0.7,
"label": 'Whispering',
"trigger": 'she whisper XYZ',
"desc": "Makes the subject whisper — replace XYZ in the trigger with what she whispers. Use for whispering scenes. Not for loud or vocal scenes; it's a quiet effect.",
},
}
# LoRAs that overlap in purpose and fight each other when stacked. The description box warns whenever 2+ from a
# group are selected. Groups may overlap (e.g. a deepthroat LoRA is both a blowjob act and an audio LoRA).
LORA_CONFLICT_GROUPS = {
"penis anatomy": ["nsfw_penis", "nsfw_hmpenis_v2_0"],
"innie pussy": ["nsfw_innie", "nsfw_innie_pussy"],
"breast size/shape": ["nsfw_bustywomen", "nsfw_tiny_breasts_flat_chest", "nsfw_huge_breasts_large_breasts",
"nsfw_torpedo_tits_t2v", "nsfw_tiddies_and_realism_slider_vbeta",
"nsfw_natural_sagging_breasts", "nsfw_natural_saggy_boobs"],
"breast motion": ["nsfw_boob_physics", "nsfw_slop_bounce", "nsfw_jiggle_walk"],
"cameltoe": ["nsfw_cameltoe_v2_0", "nsfw_skin_tight_bottoms_cameltoe"],
"twerk": ["nsfw_icy_twerk_pro_max_v2_0", "nsfw_slop_twerk_v0_2_epoch6"],
"squirting": ["nsfw_hmmasturbation_squirting_and_female_mast", "nsfw_hmsquirt_squirting_v0_1"],
"blowjob act": ["nsfw_blowjob_v3_0", "nsfw_blowjob_wearing_thong", "nsfw_chasing_blowjob_v1_2",
"nsfw_sideview_deepthroat_gag_audio", "nsfw_deeper_hold_it",
"nsfw_licking_penis_and_testicles_nsfw_v1_2"],
"cumshot": ["nsfw_cumshot", "nsfw_facial_cumshot_v0_1"],
"scene transition": ["nsfw_transition_boomsplitro", "nsfw_transition_f2v_instant_cut_to_things"],
"moans (same LoRA, different training epochs)": ["nsfw_moawxx_female_pleasure_moans_body_writhi",
"nsfw_moawxx_female_pleasure_moans_body_writhi_2",
"nsfw_moawxx_female_pleasure_moans_body_writhi_3"],
"SexGod NaughtyTimes (same LoRA, different ranks)": ["nsfw_sexgod_s_naughtytimes_v2_0_pruned_rank25",
"nsfw_sexgod_s_naughtytimes_v2_0_pruned_rank51"],
"general NSFW enhancer": ["nsfw_astro_nsfw", "nsfw_mystic_xxx_v2_0",
"nsfw_sexgod_after_midnight_sexytime_r64",
"nsfw_sexgod_s_naughtytimes_v2_0_pruned_rank25",
"nsfw_sexgod_s_naughtytimes_v2_0_pruned_rank51"],
"visual style": ["nsfw_disney_style_renaissance_era", "nsfw_photorealistic_image_generator",
"nsfw_realism_people"],
"missionary POV": ["nsfw_missionary_sex_pov", "nsfw_pov_missionary_insertion_v0_7"],
"dildo": ["nsfw_dildo", "nsfw_dildo_masturbation_v2_0", "nsfw_strapon_dildo_v0_1"],
"audio": ["nsfw_jav_moans_audio_only", "nsfw_whispering", "nsfw_sideview_deepthroat_gag_audio"],
"hip motion": ["nsfw_grindtime", "nsfw_hip_gyration"],
}
# Must stay identical to the conditioner's table: the *label* goes over the wire, so a canvas that half does not know
# is rejected there and surfaces as a failure here.
CANVASES = {
# 16:9
"960x544 · 16:9 fast": (544, 960),
"1024x576 · 16:9 fast": (576, 1024),
"1152x640 · 16:9": (640, 1152),
"1280x704 · 16:9": (704, 1280),
"1344x768 · 16:9 full": (768, 1344),
# 9:16
"544x960 · 9:16 fast": (960, 544),
"640x1152 · 9:16": (1152, 640),
"768x1344 · 9:16 full": (1344, 768),
# 1:1
"544x544 · 1:1 fast": (544, 544),
"768x768 · 1:1 full": (768, 768),
# 4:3 / 3:4
"768x576 · 4:3 fast": (576, 768),
"1024x768 · 4:3 full": (768, 1024),
"576x768 · 3:4 fast": (768, 576),
"768x1024 · 3:4 full": (1024, 768),
# 21:9
"1152x512 · 21:9 fast": (512, 1152),
"1536x672 · 21:9 full": (672, 1536),
}
DEFAULT_CANVAS = "960x544 · 16:9 fast"
FPS, FRAMES_PER_CHUNK, LATENTS_PER_CHUNK = 24, 17, 5
# It is the *snapped* frame count the ceiling has to hold for: 15 s is 360 frames, which rounds up to 362, i.e.
# 15.083 s, and is refused.
MIN_UI_DURATION, MAX_UI_DURATION = 2, 14
def snap_frames(seconds: float) -> int:
"""The frame count MiniMax-H3's video VAE can decode: the next `17 * n + 5` at 24 fps."""
frames = max(1, round(float(seconds) * FPS))
while frames % FRAMES_PER_CHUNK != LATENTS_PER_CHUNK:
frames += 1
return frames
def lower_duration_floor(seconds: float = MIN_UI_DURATION) -> None:
"""Let the pipeline generate below its 5 s floor. 56 frames (2.33 s) is fine on the released checkpoint."""
from diffusers.modular_pipelines.minimax_h3.modular_pipeline import MiniMaxH3ModularPipeline
MiniMaxH3ModularPipeline.min_duration = property(lambda self: float(seconds))
PIPE = None
MANAGER = None
LOAD_ERROR: str | None = None
LOADED_IN: float | None = None
TURBO_AVAILABLE: bool = False
_TURBO_LoRA: list | None = None # list of (module, A, B) tuples — A/B factors on CPU, tiny footprint
_TURBO_merged = False
_NSFW_LoRA: dict[str, list] = {} # key -> list of (module, A, B) tuples, A/B on CPU
_NSFW_merged: set[str] = set()
_CUSTOM_LoRA: dict[tuple[str, str], list] = {} # (repo, file) -> list of (module, A, B) tuples, A/B on CPU
_CUSTOM_merged: set[tuple[str, str]] = set()
def _convert_comfyui_h3_lora(sd):
"""Convert ComfyUI-format MiniMax-H3 LoRA keys to the module-tree keys the loader navigates.
ComfyUI keys look like `diffusion_model.blocks.N.attn.out_proj.lora_A.weight` (and
`diffusion_model.token_refiner.blocks.N.attn.out_proj.lora_A.weight` for the token refiner). The diffusers module
tree uses `transformer_blocks.N.attn.to_out.0` / `token_refiner.refiner_blocks.N.attn.to_out.0`, `attn.to_q/to_k/to_v`
(fused `qkv_proj` split 3-way), and `ff.net.0.proj` / `ff.net.2` (for `mlp.fc1` / `mlp.fc2`).
"""
out = {}
for k, v in sd.items():
k = k.removeprefix("diffusion_model.").removeprefix("transformer.")
parts = k.split(".")
# Main blocks: [blocks, N, attn|mlp, target, lora_A|B, weight]
# Token refiner: [token_refiner, blocks, N, attn|mlp, target, lora_A|B, weight]
if parts[0] == "token_refiner":
prefix = "token_refiner.refiner_blocks."
block, layer, target = parts[2], parts[3], parts[4]
suffix = ".".join(parts[5:]) # e.g. "lora_A.weight"
else:
prefix = "transformer_blocks."
block, layer, target = parts[1], parts[2], parts[3]
suffix = ".".join(parts[4:]) # e.g. "lora_A.weight"
# Some ComfyUI exports also carry kohya-style `.alpha` scalars (alpha == rank here, so a no-op).
# Skip any non-lora_A/B key so metadata never reaches the shape-sensitive qkv split below.
if suffix not in ("lora_A.weight", "lora_B.weight"):
continue
if layer == "attn":
if target == "out_proj":
out[f"{prefix}{block}.attn.to_out.0.{suffix}"] = v
elif target == "qkv_proj":
if suffix == "lora_A.weight":
# A is shared across q/k/v
for name in ("to_q", "to_k", "to_v"):
out[f"{prefix}{block}.attn.{name}.lora_A.weight"] = v
else: # lora_B.weight — split the rows 3-way into q/k/v
head_dim = v.shape[0] // 3
for i, name in enumerate(("to_q", "to_k", "to_v")):
out[f"{prefix}{block}.attn.{name}.lora_B.weight"] = v[i * head_dim:(i + 1) * head_dim]
elif layer == "mlp":
if target == "fc1":
out[f"{prefix}{block}.ff.net.0.proj.{suffix}"] = v
elif target == "fc2":
out[f"{prefix}{block}.ff.net.2.{suffix}"] = v
return out
def _convert_kohya_h3_lora(sd):
"""Convert kohya/musubi-tuner-format MiniMax-H3 LoRA keys to ComfyUI format, then to module-tree keys.
kohya keys look like `lora_unet_blocks_N_attn_out_proj.lora_down.weight` / `.lora_up.weight` / `.alpha`
(also `attn_qkv_proj`, `mlp_fc1`, `mlp_fc2`). Some exports are hybrids: the ComfyUI-style prefix
(`diffusion_model.blocks.N.attn.out_proj`) with kohya-style suffixes — the prefix is already the
ComfyUI layout, so only the suffix needs renaming. We first rename to the ComfyUI layout the loader
understands (`diffusion_model.blocks.N.attn.out_proj.lora_A/lora_B.weight`), folding the per-module
`alpha/rank` factor into the `lora_up` (B) tensor so the loader's `B @ A * scale` stays correct, then
hand off to `_convert_comfyui_h3_lora`. kohya has no `token_refiner` keys — those are simply absent.
"""
import torch
comfy = {}
alphas: dict[str, float] = {}
# First pass: collect alpha factors (alpha/rank) per module base name. `.alpha` is a 0-dim
# scalar tensor (ndim == 0), so the rank must come from the lora_down weight's shape[0].
for k, v in sd.items():
if k.endswith(".alpha"):
base = k[: -len(".alpha")]
_down = sd.get(f"{base}.lora_down.weight")
rank = _down.shape[0] if _down is not None else float(v)
alphas[base] = float(v) / float(rank)
for k, v in sd.items():
if k.endswith(".alpha"):
continue
if k.endswith(".lora_down.weight"):
base = k[: -len(".lora_down.weight")]
lora = "lora_A"
elif k.endswith(".lora_up.weight"):
base = k[: -len(".lora_up.weight")]
lora = "lora_B"
else:
continue
if base.startswith("diffusion_model.") or base.startswith("transformer."):
# Hybrid export: ComfyUI-style prefix with kohya-style suffixes
# (diffusion_model.blocks.N.attn.out_proj.lora_down.weight). The prefix is already the
# ComfyUI layout — only the suffix needs renaming. token_refiner keys, if any, flow
# through unchanged too.
comfy_key = f"{base}.{lora}.weight"
else:
# base: lora_unet_blocks_N_attn_out_proj -> diffusion_model.blocks.N.attn.out_proj
parts = base.split("_")
# parts: [lora, unet, blocks, N, attn, out, proj] (mlp_fc1 -> [.., mlp, fc1])
if len(parts) < 6:
continue # unknown key shape — skip rather than crash
block = parts[3]
layer = parts[4]
target = "_".join(parts[5:])
comfy_key = f"diffusion_model.blocks.{block}.{layer}.{target}.{lora}.weight"
if lora == "lora_B" and base in alphas:
v = v * alphas[base]
comfy[comfy_key] = v
return _convert_comfyui_h3_lora(comfy)
def _apply_turbo():
"""Merge LoRA into transformer weights using A/B factors.
The precomputed delta (B @ A) is ~57 MB per module × 363 = ~20 GB — far more GPU memory
than is free after the transformer is unpacked (~14 GB on an 80 GB card). Instead we store
the LoRA factors A (~2.6 MB) and B (~2.6 MB) per module — total ~1.2 GB — and compute
the delta on-the-fly: mod.weight += B @ A * scale. Peak extra GPU memory is one temporary
delta tensor (~57 MB), freed each iteration.
A/B factors stay CPU-resident in `_TURBO_LoRA`; local CUDA copies are made per merge so the
store is never mutated and no CUDA memory is held between requests.
"""
global _TURBO_merged, _TURBO_LoRA
if _TURBO_merged or _TURBO_LoRA is None:
return
_t0 = time.time()
for mod, A, B in _TURBO_LoRA:
# delta = B @ A is temporary (~57 MB), freed next iteration — never stored simultaneously.
mod.weight.data += (B.to("cuda", non_blocking=True) @ A.to("cuda", non_blocking=True)) * TURBO_LORA_SCALE
_elapsed = time.time() - _t0
_TURBO_merged = True
_log(f"turbo LoRA merged ({len(_TURBO_LoRA)} modules in {_elapsed:.2f}s)")
def _remove_turbo():
"""Restore base weights by undoing the LoRA merge. Idempotent: only acts when `_TURBO_merged`,
and rolls back in reverse order so a partial failure leaves the fewest modules touched."""
global _TURBO_merged
if not _TURBO_merged or _TURBO_LoRA is None:
return
_t0 = time.time()
_done = 0
try:
for mod, A, B in reversed(_TURBO_LoRA):
mod.weight.data -= (B.to("cuda", non_blocking=True) @ A.to("cuda", non_blocking=True)) * TURBO_LORA_SCALE
_done += 1
except Exception as _e:
_log(f"turbo LoRA partial unmerge ({_done}/{len(_TURBO_LoRA)}): {_e}", "ERROR")
raise
_elapsed = time.time() - _t0
_TURBO_merged = False
import torch as _torch
_torch.cuda.empty_cache()
_log(f"turbo LoRA removed ({len(_TURBO_LoRA)} modules in {_elapsed:.2f}s)")
# ── Debug logging ──────────────────────────────────────────────────────────────
def _log(msg, level="INFO"):
"""Timestamped line to the Space logs (stdout). Levels: DEBUG / INFO / WARN / ERROR."""
print(f"[gen][{time.strftime('%H:%M:%S')}][{level}] {msg}", flush=True)
# ── Memory / OOM diagnostics ───────────────────────────────────────────────────
# The Space has a history of OOM crashes. A hard kill leaves no traceback, so the phase
# logs + bucket dumps below are the only evidence. `_log_mem` snapshots GPU + CPU at phase
# boundaries; `_debug_dump` persists diagnostics to the bucket under /data/debug;
# `_oom_dump` captures a CUDA OOM (traceback + torch memory summary) before re-raising.
# `H3_MEM_SAMPLE_INTERVAL` (s, 0 = off) drives the in-generation sampler thread.
_DEBUG_DIR = os.environ.get("H3_DEBUG_DIR", "/data/debug")
_MEM_SAMPLE_INTERVAL = float(os.environ.get("H3_MEM_SAMPLE_INTERVAL", "5"))
def _mem_info():
"""Compact GPU + CPU memory snapshot for the logs. Never raises."""
_parts = []
try:
import torch
if torch.cuda.is_available():
_free, _total = torch.cuda.mem_get_info()
_parts.append(
f"gpu_alloc={torch.cuda.memory_allocated() / 2**30:.2f}G "
f"gpu_resv={torch.cuda.memory_reserved() / 2**30:.2f}G "
f"gpu_max={torch.cuda.max_memory_allocated() / 2**30:.2f}G "
f"gpu_free={_free / 2**30:.2f}G/{_total / 2**30:.2f}G"
)
except Exception:
pass
try:
import psutil
_parts.append(f"rss={psutil.Process().memory_info().rss / 2**30:.2f}G")
except Exception:
try:
with open("/proc/self/status") as _f:
for _line in _f:
if _line.startswith("VmRSS:"):
_parts.append(f"rss={int(_line.split()[1]) / 2**20:.2f}G")
break
except Exception:
pass
return " ".join(_parts) or "mem=n/a"
def _log_mem(tag):
"""Log a memory snapshot under the greppable `MEM` level."""
_log(f"{tag}: {_mem_info()}", "MEM")
def _debug_dump(tag, text):
"""Persist a diagnostic to the bucket debug folder (/data/debug). Never raises."""
try:
os.makedirs(_DEBUG_DIR, exist_ok=True)
_path = os.path.join(_DEBUG_DIR, f"{tag}_{time.strftime('%Y%m%d_%H%M%S')}.txt")
_body = (
f"=== {tag} @ {time.strftime('%Y-%m-%d %H:%M:%S')} ===\n"
f"{_mem_info()}\n"
f"{text}\n"
)
_tmp = _path + ".tmp"
with open(_tmp, "w", encoding="utf-8") as _f:
_f.write(_body)
os.replace(_tmp, _path)
try:
shutil.copyfile(_path, os.path.join(_DEBUG_DIR, f"{tag}_latest.txt"))
except OSError:
pass
_log(f"debug dump written: {_path}")
except Exception as _e:
_log(f"debug dump failed ({_e}); see logs", "WARN")
def _oom_dump(tag, exc, extra=""):
"""Capture a CUDA OOM: exception + context + torch memory summary, saved to the bucket."""
_text = [f"exception: {type(exc).__name__}: {exc}"]
if extra:
_text.append(extra)
_text.append(traceback.format_exc())
try:
import torch
if torch.cuda.is_available():
_text.append(torch.cuda.memory_summary())
except Exception:
pass
_debug_dump(f"oom_{tag}", "\n".join(_text))
_log(f"OOM captured ({tag}): {exc}", "ERROR")
# ── Bucket-backed LoRA cache ───────────────────────────────────────────────────
# Every downloaded LoRA is copied into the mounted bucket (/data) so a Space restart
# loads it from the bucket instead of re-downloading it. Falls back to the HF cache
# whenever the bucket isn't mounted or a write fails. `H3_LORA_CACHE_DIR` overrides
# the mount path (used by tests).
_LORA_CACHE_DIR = os.environ.get("H3_LORA_CACHE_DIR", "/data/loras")
def _lora_cache_path(repo, file):
"""Bucket path for a (repo, file) LoRA, or None if the bucket isn't usable."""
try:
os.makedirs(_LORA_CACHE_DIR, exist_ok=True)
_probe = os.path.join(_LORA_CACHE_DIR, ".probe")
with open(_probe, "w") as _f:
_f.write("ok")
os.remove(_probe)
except Exception:
return None
_key = re.sub(r"[^A-Za-z0-9._-]", "_", f"{repo.replace('/', '__')}__{file}")
return os.path.join(_LORA_CACHE_DIR, _key)
def _fetch_lora_file(repo, file):
"""Local path to a LoRA .safetensors, preferring the bucket cache over a fresh download."""
from huggingface_hub import hf_hub_download
_cached = _lora_cache_path(repo, file)
if _cached and os.path.exists(_cached):
try:
with open(_cached, "rb") as _f:
_n = struct.unpack("<Q", _f.read(8))[0]
json.loads(_f.read(_n))
_log(f"LoRA cache hit: {repo}/{file} ({os.path.getsize(_cached) / 1e6:.0f} MB)")
return _cached
except Exception:
_log(f"LoRA cache corrupt, re-downloading: {repo}/{file}", "WARN")
try:
os.remove(_cached)
except OSError:
pass
_t0 = time.time()
_path = hf_hub_download(repo, file)
_log(f"LoRA downloaded: {repo}/{file} ({os.path.getsize(_path) / 1e6:.0f} MB in {time.time() - _t0:.0f}s)")
if _cached:
try:
_tmp = _cached + ".tmp"
with open(_path, "rb") as _src, open(_tmp, "wb") as _dst:
shutil.copyfileobj(_src, _dst, 1024 * 1024)
os.replace(_tmp, _cached)
_log(f"LoRA cached to bucket: {repo}/{file}")
except Exception as _e:
_log(f"LoRA bucket cache write failed ({_e}); using HF cache", "WARN")
return _path
def _ensure_nsfw_lora_loaded(key):
"""Download + convert + store a lazy NSFW LoRA's A/B factors on CPU. No-op if already loaded."""
if key in _NSFW_LoRA:
return
cfg = NSFW_LORA_CONFIGS[key]
import torch
from safetensors.torch import load_file as _load_lora
_t0 = time.time()
_log(f"loading NSFW LoRA {key} from {cfg['repo']} ...")
_path = _fetch_lora_file(cfg["repo"], cfg["file"])
_raw = _load_lora(_path)
if cfg.get("format") == "kohya":
_sd = _convert_kohya_h3_lora(_raw)
else:
_sd = _convert_comfyui_h3_lora(_raw)
_pairs: dict[str, dict[str, torch.Tensor]] = {}
for _k, _v in _sd.items():
if ".lora_A." in _k:
_pairs.setdefault(_k.split(".lora_A.")[0], {})["A"] = _v
elif ".lora_B." in _k:
_pairs.setdefault(_k.split(".lora_B.")[0], {})["B"] = _v
_loaded = []
for _base, _pair in _pairs.items():
if "A" not in _pair or "B" not in _pair:
continue
_parts = _base.split(".")
_obj = PIPE.transformer
for _p in _parts:
_obj = _obj[int(_p)] if _p.isdigit() else getattr(_obj, _p)
_loaded.append((_obj, _pair["A"].to(_obj.weight.dtype), _pair["B"].to(_obj.weight.dtype)))
del _sd, _pairs
import gc as _gc; _gc.collect()
_NSFW_LoRA[key] = _loaded
_log(f"NSFW LoRA {key} parsed ({len(_loaded)} modules in {time.time() - _t0:.1f}s)")
def _ensure_custom_lora_loaded(repo, file):
"""Download + convert + store a user-supplied Hugging Face LoRA's A/B factors on CPU. No-op if already loaded."""
key = (repo, file)
if key in _CUSTOM_LoRA:
return
import torch
from safetensors.torch import load_file as _load_lora
_t0 = time.time()
_log(f"loading custom LoRA {repo}/{file} ...")
try:
_path = _fetch_lora_file(repo, file)
_raw = _load_lora(_path)
except Exception as _e:
raise gr.Error(f"Couldn't fetch custom LoRA `{repo}/{file}`: {_e}")
_has_comfy = any(".lora_A." in _k for _k in _raw)
_has_kohya = any(".lora_down.weight" in _k or _k.startswith("lora_unet_") for _k in _raw)
if _has_comfy:
_sd = _convert_comfyui_h3_lora(_raw)
elif _has_kohya:
_sd = _convert_kohya_h3_lora(_raw)
else:
raise gr.Error(f"`{repo}/{file}` doesn't look like a MiniMax-H3 LoRA (no lora_A/lora_down keys found).")
_pairs: dict[str, dict[str, torch.Tensor]] = {}
for _k, _v in _sd.items():
if ".lora_A." in _k:
_pairs.setdefault(_k.split(".lora_A.")[0], {})["A"] = _v
elif ".lora_B." in _k:
_pairs.setdefault(_k.split(".lora_B.")[0], {})["B"] = _v
_loaded = []
for _base, _pair in _pairs.items():
if "A" not in _pair or "B" not in _pair:
continue
_parts = _base.split(".")
_obj = PIPE.transformer
for _p in _parts:
_obj = _obj[int(_p)] if _p.isdigit() else getattr(_obj, _p)
_loaded.append((_obj, _pair["A"].to(_obj.weight.dtype), _pair["B"].to(_obj.weight.dtype)))
if not _loaded:
raise gr.Error(f"`{repo}/{file}` converted to no usable modules — is it a MiniMax-H3 LoRA?")
del _sd, _pairs, _raw
import gc as _gc; _gc.collect()
_CUSTOM_LoRA[key] = _loaded
_log(f"custom LoRA {repo}/{file} parsed ({len(_loaded)} modules in {time.time() - _t0:.1f}s)")
def _parse_hf_link(url):
"""Parse a Hugging Face repo or file link into (repo, file). `file` is None for a bare repo link."""
url = (url or "").strip().split("?")[0].split("#")[0]
if not url:
raise gr.Error("Paste a Hugging Face link first.")
if not url.startswith("http"):
parts = [p for p in url.split("/") if p]
if len(parts) >= 2:
return parts[0] + "/" + parts[1], "/".join(parts[2:]) or None
raise gr.Error(f"Couldn't parse `{url}` as a Hugging Face repo link.")
if "huggingface.co" not in url:
raise gr.Error("Only Hugging Face links are supported (huggingface.co).")
parts = [p for p in url.split("huggingface.co", 1)[1].strip("/").split("/") if p]
if parts and parts[0] in ("spaces", "models", "datasets"):
parts = parts[1:] # https://huggingface.co/spaces/Owner/Repo → Owner/Repo
if len(parts) < 2:
raise gr.Error(f"Couldn't parse `{url}` as a Hugging Face repo link.")
repo = parts[0] + "/" + parts[1]
if len(parts) == 2:
return repo, None
if parts[2] in ("resolve", "tree", "blob"):
if len(parts) == 4 and parts[2] in ("tree", "blob"):
return repo, None # tree/main or blob/main with no subpath → treat as a repo link
if len(parts) < 5:
raise gr.Error(f"Couldn't parse a filename from `{url}`.")
if parts[3] != "main":
raise gr.Error("Only `main`-branch links are supported — use a `resolve/main/...` link.")
return repo, "/".join(parts[4:])
return repo, "/".join(parts[2:])
def _resolve_repo_file(repo):
"""Pick the single .safetensors file of a repo link; error if there isn't exactly one."""
from huggingface_hub import list_repo_files
try:
files = [f for f in list_repo_files(repo) if f.endswith(".safetensors")]
except Exception as _e:
raise gr.Error(f"Couldn't list files in `{repo}`: {_e}")
if len(files) == 1:
return files[0]
if not files:
raise gr.Error(f"No .safetensors files found in `{repo}`.")
raise gr.Error(f"`{repo}` has multiple .safetensors files — paste a direct file link instead: "
+ ", ".join(files[:5]) + ("…" if len(files) > 5 else ""))
def _download_custom_lora(url, scale=1.0, trigger=""):
"""Download + verify a user-supplied Hugging Face LoRA and report status. Loads it for the next Generate."""
try:
repo, file = _parse_hf_link(url)
if file is None:
file = _resolve_repo_file(repo)
_ensure_custom_lora_loaded(repo, file)
except gr.Error as _e:
return gr.update(value=f"**❌ {_e}**", visible=True)
except Exception as _e:
return gr.update(value=f"**❌ Unexpected error loading the LoRA: {_e}**", visible=True)
n = len(_CUSTOM_LoRA[(repo, file)])
note = f" (scale {scale:g}" + (f", trigger `{trigger}`)" if trigger else ")")
return gr.update(
value=f"**✅ Loaded `{repo}/{file}`** — {n} modules, will apply on Generate{note}.",
visible=True,
)
def _apply_lora(key, scale, store, merged):
"""Merge a loaded LoRA into transformer weights on GPU. A/B factors stay CPU-resident in
`store`; local CUDA copies are made per merge so the store is never mutated."""
if key in merged or key not in store:
return
_t0 = time.time()
for _mod, _A, _B in store[key]:
_mod.weight.data += (_B.to("cuda", non_blocking=True) @ _A.to("cuda", non_blocking=True)) * scale
merged.add(key)
_log(f"LoRA {key} merged ({len(store[key])} modules in {time.time() - _t0:.2f}s)")
def _remove_lora(key, scale, store, merged):
"""Undo a LoRA merge. Idempotent: only acts when `key` is in `merged`, and rolls back in
reverse order so a partial failure leaves the fewest modules touched."""
if key not in merged or key not in store:
return
_t0 = time.time()
_done = 0
try:
for _mod, _A, _B in reversed(store[key]):
_mod.weight.data -= (_B.to("cuda", non_blocking=True) @ _A.to("cuda", non_blocking=True)) * scale
_done += 1
except Exception as _e:
_log(f"LoRA {key} partial unmerge ({_done}/{len(store[key])}): {_e}", "ERROR")
raise
merged.discard(key)
import torch as _torch
_torch.cuda.empty_cache()
_log(f"LoRA {key} removed ({len(store[key])} modules in {time.time() - _t0:.2f}s)")
def _apply_nsfw(key):
_apply_lora(key, NSFW_LORA_CONFIGS[key]["scale"], _NSFW_LoRA, _NSFW_merged)
def _remove_nsfw(key):
_remove_lora(key, NSFW_LORA_CONFIGS[key]["scale"], _NSFW_LoRA, _NSFW_merged)
def _apply_custom(key, scale):
_apply_lora(key, scale, _CUSTOM_LoRA, _CUSTOM_merged)
def _remove_custom(key, scale):
_remove_lora(key, scale, _CUSTOM_LoRA, _CUSTOM_merged)
def status() -> str:
if LOAD_ERROR:
return LOAD_ERROR
if PIPE is None:
return f"Loading `{MODEL_REPO}` (transformer + VAEs, 77.3 GB). Watch the Space logs."
import h3_aoti
return (
f"Ready · transformer + VAEs **bfloat16, unquantized** · placement `{PLACEMENT}` · attention `{ATTENTION}` · "
f"{h3_aoti.status()} · loaded in {LOADED_IN:.0f}s · conditioner `{CONDITIONER_SPACE}`"
)
def load_models() -> str | None:
"""Load the denoising half at startup.
`MiniMaxH3GeneratorBlocks` declares `transformer`, `vae`, `audio_vae`, the two schedulers and `video_processor`,
so `load_components` fetches exactly those subfolders — `text_encoder/` and `transformer_ref/` are never touched.
Both autoencoders carry `_keep_in_fp32_modules` over every module and stay float32: a bfloat16 audio VAE decodes
the soundtrack roughly 20 dB too quiet.
"""
global PIPE, MANAGER, LOAD_ERROR, LOADED_IN
if PIPE is not None or LOAD_ERROR is not None:
return LOAD_ERROR
started = time.time()
try:
_log_mem("startup begin")
import torch
from diffusers import ComponentsManager
from h3_split_blocks import MiniMaxH3GeneratorBlocks
lower_duration_floor()
manager = ComponentsManager()
blocks = MiniMaxH3GeneratorBlocks()
_log(f"loading {[c.name for c in blocks.expected_components]} from {MODEL_REPO} ...")
pipe = blocks.init_pipeline(MODEL_REPO, components_manager=manager, collection="h3")
pipe.load_components(dtype=torch.bfloat16)
pipe.transformer.set_attention_backend(ATTENTION)
_log(f"components loaded in {time.time() - started:.0f}s")
_log_mem("startup components loaded")
if TURBO_LORA_REPO:
from safetensors.torch import load_file as _load_lora
_t0 = time.time()
_log(f"loading turbo LoRA from {TURBO_LORA_REPO} ...")
_lora_path = _fetch_lora_file(TURBO_LORA_REPO, TURBO_LORA_FILE)
_lora_sd = _load_lora(_lora_path)
# Group LoRA A/B pairs by target module name.
_lora_pairs: dict[str, dict[str, torch.Tensor]] = {}
for _k, _v in _lora_sd.items():
if ".lora_A." in _k:
_base = _k.split(".lora_A.")[0]
_lora_pairs.setdefault(_base, {})["A"] = _v
elif ".lora_B." in _k:
_base = _k.split(".lora_B.")[0]
_lora_pairs.setdefault(_base, {})["B"] = _v
# Store LoRA A/B factors on CPU (~1.2 GB total). The full delta (B @ A) would be
# ~20 GB and overflow GPU memory when moved to CUDA inside @spaces.GPU (~14 GB free).
# Instead _apply_turbo computes the delta on-the-fly: one temporary ~57 MB tensor
# per module, freed each iteration.
global TURBO_AVAILABLE, _TURBO_LoRA
_TURBO_LoRA = []
for _base_name, _pair in _lora_pairs.items():
if "A" not in _pair or "B" not in _pair:
continue
_base_name = _base_name.removeprefix("transformer.")
_parts = _base_name.split(".")
_obj = pipe.transformer
for _p in _parts:
_obj = _obj[int(_p)] if _p.isdigit() else getattr(_obj, _p)
_A = _pair["A"].to(_obj.weight.dtype) # (rank, in_features)
_B = _pair["B"].to(_obj.weight.dtype) # (out_features, rank)
_TURBO_LoRA.append((_obj, _A, _B))
del _lora_sd, _lora_pairs
import gc as _gc; _gc.collect()
TURBO_AVAILABLE = True
_log(f"turbo LoRA parsed ({len(_TURBO_LoRA)} modules in {time.time() - _t0:.0f}s, merge pending)")
if _TURBO_LoRA:
_m, _A, _B = _TURBO_LoRA[0]
_log(f" sample: module={type(_m).__name__}, "
f"A.shape={_A.shape}, B.shape={_B.shape}, "
f"A.device={_A.device}, dtype={_A.dtype}")
_log_mem("startup turbo lora parsed")
# Still startup, still free: an AoTI package carries no weights and opens its archive lazily inside the GPU
# worker. Off unless `H3_AOTI=1`.
import h3_aoti
h3_aoti.maybe_load(pipe.transformer)
if PLACEMENT == "pack":
# Scoped to the transformer. `spaces` packs every startup-resident CUDA tensor into a second on-disk copy,
# and packing all 77.3 GB busts the 150 GB storage quota; the 61.7 GB transformer alone fits. The ~10 GB of
# fp32 VAEs move on the first GPU call instead.
pipe.transformer.to("cuda")
import gc as _gc
_gc.collect()
torch.cuda.empty_cache()
_log_mem("startup transformer packed")
if PLACEMENT == "offload":
manager.enable_auto_cpu_offload(device="cuda")
_arm_decode_hooks(pipe)
PIPE, MANAGER = pipe, manager
LOADED_IN = time.time() - started
_log(f"ready in {LOADED_IN:.0f}s")
_log_mem("startup ready")
_dump_text = [f"placement={PLACEMENT}, attention={ATTENTION}, model={MODEL_REPO}"]
try:
import torch as _torch
if _torch.cuda.is_available():
_dump_text.append(_torch.cuda.memory_summary())
except Exception:
pass
_debug_dump("startup", "\n".join(_dump_text))
if _lora_cache_path("probe", "probe.safetensors"):
_log(f"LoRA bucket cache ready: {_LORA_CACHE_DIR}")
else:
_log(f"LoRA bucket cache unavailable ({_LORA_CACHE_DIR} not writable); using HF cache only", "WARN")
except Exception as error:
traceback.print_exc()
LOAD_ERROR = f"**Loading `{MODEL_REPO}` failed** after {time.time() - started:.0f}s: `{type(error).__name__}: {error}`"
return LOAD_ERROR
def _arm_decode_hooks(pipe):
"""Make the offload hooks fire for the two VAEs.
`enable_auto_cpu_offload` wraps `forward`, and the decode blocks call `vae.decode(...)` directly, so the hook
never runs and the VAE is still on the host when the latents arrive on the card.
"""
for name in ("vae", "audio_vae"):
module = getattr(pipe, name)
inner = module.decode
def armed(*args, _module=module, _decode=inner, **kwargs):
hook = getattr(_module, "_hf_hook", None)
if hook is not None:
hook.pre_forward(_module)
return _decode(*args, **kwargs)
module.decode = armed
@cache
def conditioner():
"""The other half, over the gradio API. `gradio_client` attaches the caller's own ZeroGPU token per call, so the
conditioner's booking is billed to whoever asked for the video."""
from gradio_client import Client
return Client(CONDITIONER_SPACE)
def encode_remote(prompt, image_path, last_image_path, canvas, num_frames, rewrite_prompt=False):
"""`/encode` on the conditioner Space: a safetensors file holding `prompt_embeds` + `text_token_tags`, with the
resolved `height` / `width` / `num_frames` in its metadata, plus the plan. `canvas` is the label.
The cached `Client` is dropped and rebuilt on a failed call (the conditioner may have restarted
or the connection dropped); one retry before giving up."""
from gradio_client import handle_file
from safetensors import safe_open
_t0 = time.time()
_log(f"encode_remote: conditioning on {CONDITIONER_SPACE} (canvas={canvas}, {num_frames}f, "
f"rewrite={rewrite_prompt}, image={bool(image_path)}, last_image={bool(last_image_path)}) ...")
for _attempt in (1, 2):
try:
path, plan = conditioner().predict(
prompt=prompt,
image_path=handle_file(image_path) if image_path else None,
last_image_path=handle_file(last_image_path) if last_image_path else None,
canvas=canvas,
num_frames=num_frames,
rewrite_prompt=bool(rewrite_prompt),
api_name="/encode",
)
break
except Exception:
conditioner.cache_clear()
if _attempt == 2:
raise
_log("encode_remote: conditioner call failed; reconnecting ...", "WARN")
time.sleep(2)
with safe_open(path, framework="pt") as handle:
metadata = handle.metadata()
_log(f"encode_remote: done in {time.time() - _t0:.0f}s "
f"({plan.get('num_text_tokens')} tokens, {metadata.get('height')}x{metadata.get('width')}, "
f"{metadata.get('num_frames')}f)")
_log_mem("encode_remote done")
_embeds = handle.get_tensor("prompt_embeds")
_tags = handle.get_tensor("text_token_tags")
try:
os.remove(path)
except OSError:
pass
return _embeds, _tags, metadata, plan
# Seconds of GPU one request needs, from the packed video rows it is about to denoise: linear in the rows for the
# matmuls, quadratic for the attention, against the AoTI block package this Space runs.
_DUR_B, _DUR_C = 1.1745e-4, 3.8396e-9
# The two resident decoders and the mux, which scale with the output rather than with the step count.
_DECODE_BASE, _DECODE_PER_DEFAULT_CANVAS, _DEFAULT_CANVAS_PIXELS = 15, 15, 960 * 544 * 124
# `pack` mode: only the ~10 GB of VAEs move on a cold worker.
_PLACEMENT_ALLOWANCE, _PAD = 12, 10
def get_duration(prompt_embeds, text_token_tags, image, last_image, height, width, num_frames, steps, seed, *a, **k):
height, width, num_frames, steps = int(height), int(width), int(num_frames), int(steps)
latent_frames = (num_frames - LATENTS_PER_CHUNK) // FRAMES_PER_CHUNK * LATENTS_PER_CHUNK + 2
patches = (height // 32) * (width // 32)
rows = latent_frames * patches + (int(image is not None) + int(last_image is not None)) * patches
denoise = steps * (_DUR_B * rows + _DUR_C * rows**2)
decode = _DECODE_BASE + _DECODE_PER_DEFAULT_CANVAS * (height * width * num_frames) / _DEFAULT_CANVAS_PIXELS
_dur = max(60, int(denoise + decode) + _PLACEMENT_ALLOWANCE + _PAD)
_log(f"get_duration: {width}x{height}, {num_frames}f, {steps} steps, rows={rows} -> {_dur}s "
f"(denoise {denoise:.0f}s + decode {decode:.0f}s + {_PLACEMENT_ALLOWANCE + _PAD}s allowance)")
return _dur
@spaces.GPU(duration=get_duration, size=GPU_SIZE)
def _generate(prompt_embeds, text_token_tags, image, last_image, height, width, num_frames, steps, seed, turbo=False, nsfw_keys=(), custom_loras=()):
"""The only thing on GPU time: the packed-sequence denoise loop and the two decoders.
Only the three generated outputs come back — a `@spaces.GPU` return crosses a process boundary by pickling, and
the full `PipelineState` still holds the packed latents, the rotary grid and the row indices on the card.
"""
import torch
_t0 = time.time()
_log(f"_generate ENTER: turbo={turbo}, TURBO_AVAILABLE={TURBO_AVAILABLE}, "
f"_TURBO_merged={_TURBO_merged}, steps={steps}, {width}x{height}, {num_frames}f, "
f"nsfw={tuple(nsfw_keys)}, custom={[(r, f) for r, f, _s in custom_loras]}")
_log_mem("_generate ENTER")
# Intra-phase memory sampler: a hard OOM kill leaves no traceback, so the last sampler
# lines before the crash are the only evidence of where memory grew. Queries only.
_stop_sampler = threading.Event()
def _sampler():
while not _stop_sampler.wait(_MEM_SAMPLE_INTERVAL):
_log_mem("sampler")
if _MEM_SAMPLE_INTERVAL > 0:
threading.Thread(target=_sampler, daemon=True).start()
try:
if PLACEMENT == "lazy":
PIPE.to("cuda")
elif PLACEMENT == "pack":
PIPE.vae.to("cuda")
PIPE.audio_vae.to("cuda")
_log_mem("_generate VAEs on cuda")
# Merge LoRA inside @spaces.GPU where the real weights are live on CUDA (in pack mode,
# ZeroGPU unpacks the real transformer weights before calling this function).
if turbo and TURBO_AVAILABLE:
_log("_generate: calling _apply_turbo ...")
_apply_turbo()
_log("_generate: _apply_turbo done")
for _key in nsfw_keys:
_apply_nsfw(_key)
for _repo, _file, _scale in custom_loras:
_apply_custom((_repo, _file), _scale)
_log_mem("_generate LoRAs merged")
_log(f"_generate: starting PIPE (steps={steps}) ...")
_log_mem("_generate before PIPE")
state = PIPE(
prompt_embeds=prompt_embeds.to("cuda"),
text_token_tags=text_token_tags,
image=image,
last_image=last_image,
height=height,
width=width,
num_frames=num_frames,
num_inference_steps=int(steps),
generator=torch.Generator("cpu").manual_seed(int(seed) if int(seed) >= 0 else torch.randint(0, 2**32, (1,)).item()),
)
_log(f"_generate: PIPE done in {time.time() - _t0:.0f}s")
_log_mem("_generate after PIPE")
# Pull the outputs out of the state before the finally block drops it: the state still holds
# the packed latents, rotary grid and row indices on the card.
_videos = state.get("videos")[0]
_audio = state.get("audio")[0].cpu()
_sampling_rate = state.get("sampling_rate")
except torch.cuda.OutOfMemoryError as _e:
_oom_dump("generate", _e, f"request: {width}x{height}, {num_frames}f, steps={steps}, "
f"turbo={turbo}, nsfw={tuple(nsfw_keys)}, "
f"custom={[(r, f) for r, f, _s in custom_loras]}")
raise
finally:
_stop_sampler.set()
# Each unmerge is attempted independently so one failure can't leave the others merged.
for _repo, _file, _scale in custom_loras:
try:
_remove_custom((_repo, _file), _scale)
except Exception as _e:
_log(f"custom LoRA unmerge failed for {_repo}/{_file}: {_e}", "ERROR")
for _key in nsfw_keys:
try:
_remove_nsfw(_key)
except Exception as _e:
_log(f"NSFW LoRA unmerge failed for {_key}: {_e}", "ERROR")
if turbo and TURBO_AVAILABLE:
try:
_remove_turbo()
except Exception as _e:
_log(f"turbo LoRA unmerge failed: {_e}", "ERROR")
# Aggressive worker-side release: drop the packed state and hand every cached CUDA block back
# so the worker's GPU + RSS footprint is flat between requests.
try:
del state
except Exception:
pass
import gc as _gc
_gc.collect()
torch.cuda.empty_cache()
_log_mem("_generate EXIT")
_log(f"_generate EXIT: {(time.time() - _t0):.0f}s total (denoise + decode)")
return _videos, _audio, _sampling_rate
def _generate_impl(prompt, image_path=None, last_image_path=None, canvas=DEFAULT_CANVAS, duration=5, steps=25, seed=-1, upsample=False, turbo=False, nsfw_lora_keys=(), custom_lora_url="", custom_lora_scale=1.0, custom_lora_trigger="", progress=gr.Progress(track_tqdm=True)):
"""The request pipeline: LoRA prep → remote conditioning → @spaces.GPU denoise → mux."""
if LOAD_ERROR:
raise gr.Error(LOAD_ERROR)
if PIPE is None:
raise gr.Error("The denoiser is still loading.")
if not prompt or not prompt.strip():
raise gr.Error("MiniMax-H3 always takes a prompt, keyframes or not.")
from PIL import Image, ImageOps
from diffusers.utils import encode_video
num_frames = snap_frames(duration)
if turbo and TURBO_AVAILABLE:
steps = 7 # 7 sigma points → 6 transformer evaluations (sweet spot for larryvrh v4-step600-EMA)
# LoRAs the user selected via the catalog dropdown; the AIO motion adapter is auto-loaded whenever any is on.
nsfw_keys = tuple(k for k in (nsfw_lora_keys or ()) if k in NSFW_LORA_CONFIGS)
# User-supplied LoRA from the custom URL box: parse the link and require it was downloaded & verified.
custom = []
if custom_lora_url and str(custom_lora_url).strip():
_repo, _file = _parse_hf_link(custom_lora_url)
if _file is None:
_file = _resolve_repo_file(_repo)
if (_repo, _file) not in _CUSTOM_LoRA:
raise gr.Error(f"`{_repo}/{_file}` isn't downloaded yet — press 'Download & Verify' first.")
try:
_scale = float(custom_lora_scale) if custom_lora_scale not in (None, "") else 1.0
except (TypeError, ValueError):
raise gr.Error("Custom LoRA scale must be a number.")
if not 0.01 <= _scale <= 4.0:
raise gr.Error("Custom LoRA scale must be between 0.01 and 4.")
_trigger = str(custom_lora_trigger or "").strip()
custom = [(_repo, _file, _scale, _trigger)]
if nsfw_keys or custom:
nsfw_keys += ("nsfw_aio",)
for _key in nsfw_keys:
_ensure_nsfw_lora_loaded(_key)
for _key in nsfw_keys:
# The trigger token must be in the prompt text for the conditioner to encode the LoRA's concept.
prompt = f"{prompt}, {NSFW_LORA_CONFIGS[_key]['trigger']}"
for _repo, _file, _scale, _trigger in custom:
if _trigger:
prompt = f"{prompt}, {_trigger}"
progress(0.0, desc=f"Upsampling the prompt on {CONDITIONER_SPACE} ..." if upsample else f"Conditioning on {CONDITIONER_SPACE} ...")
conditioned = time.time()
prompt_embeds, text_token_tags, metadata, plan = encode_remote(
prompt, image_path, last_image_path, canvas, num_frames, rewrite_prompt=upsample
)
condition_seconds = time.time() - conditioned
_log_mem("after conditioning")
height, width, num_frames = (int(metadata[key]) for key in ("height", "width", "num_frames"))
refined = plan.get("refined_prompt") or ""
def keyframe(path):
# The conditioning latents encoded here have to be of the image the conditioner looked at, which it prepares
# exactly this way.
return ImageOps.exif_transpose(Image.open(path)).convert("RGB") if path else None
progress(0.1, desc=f"Denoising {steps} steps at {width}x{height}, {num_frames} frames ...")
started = time.time()
frames, audio, sampling_rate = _generate(
prompt_embeds,
text_token_tags,
keyframe(image_path),
keyframe(last_image_path),
height,
width,
num_frames,
steps,
seed,
turbo,
nsfw_keys=nsfw_keys,
custom_loras=[(r, f, s) for r, f, s, _t in custom],
)
generate_seconds = time.time() - started
directory = os.path.join(tempfile.gettempdir(), "h3-outputs")
os.makedirs(directory, exist_ok=True)
# Rotate: keep only the newest _MAX_OUTPUTS MP4s so /tmp never fills up.
_MAX_OUTPUTS = 25
for _f in sorted(glob.glob(os.path.join(directory, "*.mp4")), key=os.path.getmtime)[:-_MAX_OUTPUTS]:
try:
os.remove(_f)
except OSError:
pass
path = os.path.join(directory, f"h3-{int(time.time() * 1000)}.mp4")
encode_video(frames, fps=FPS, output_path=path, audio=audio, audio_sample_rate=sampling_rate)
_log_mem("after mux")
# The frames list and audio tensor are the last big main-process objects; drop them now.
del frames, audio
import gc as _gc
_gc.collect()
lora_note = " · LoRA: " + ", ".join(NSFW_LORA_CONFIGS[k]["trigger"] for k in nsfw_keys) if nsfw_keys else ""
lora_label_text = "**LoRAs applied:** " + ", ".join(NSFW_LORA_CONFIGS[k]["label"] for k in nsfw_keys) if nsfw_keys else ""
if custom:
_custom_note = ", ".join(f"{r}/{f} (×{s:g})" for r, f, s, _t in custom)
lora_note = (lora_note + " · custom: " + _custom_note) if lora_note else " · custom: " + _custom_note
lora_label_text = (lora_label_text + " · " + _custom_note) if lora_label_text else "**LoRAs applied:** " + _custom_note
report = (
f"`{width}x{height}`, {num_frames} frames ({num_frames / FPS:.3f} s), {int(steps)} steps · "
f"conditioner {condition_seconds:.0f}s ({plan['num_text_tokens']} tokens"
f"{', upsampled' if refined else ''}) · "
f"denoise + decode {generate_seconds:.0f}s ({generate_seconds / int(steps):.1f} s/step) · seed {int(seed)}"
f"{lora_note}"
)
_log(report)
return path, report, refined, gr.update(visible=bool(refined)), gr.DownloadButton(value=path, visible=True), gr.update(value=lora_label_text, visible=bool(nsfw_keys) or bool(custom))
def generate(prompt, image_path=None, last_image_path=None, canvas=DEFAULT_CANVAS, duration=5, steps=25, seed=-1, upsample=False, turbo=False, nsfw_lora_keys=(), custom_lora_url="", custom_lora_scale=1.0, custom_lora_trigger="", progress=gr.Progress(track_tqdm=True)):
"""One request. `upsample` is last among the pre-existing positional args, so a positional API client that
predates it is unaffected; the custom-LoRA args come after it.
Logs the full request to the Space logs, then runs the pipeline. Any failure is logged with a full
traceback before it reaches the UI.
"""
_log(f"generate ENTER: prompt={prompt!r:.120}, canvas={canvas}, duration={duration}s -> {snap_frames(duration)}f, "
f"steps={steps}, seed={seed}, upsample={upsample}, turbo={turbo}, "
f"nsfw={tuple(nsfw_lora_keys or ())}, custom_url={custom_lora_url!r}, "
f"custom_scale={custom_lora_scale}, custom_trigger={custom_lora_trigger!r}")
_t_req = time.time()
try:
return _generate_impl(
prompt, image_path, last_image_path, canvas, duration, steps, seed, upsample, turbo,
nsfw_lora_keys, custom_lora_url, custom_lora_scale, custom_lora_trigger, progress,
)
except gr.Error as _e:
_log(f"generate rejected: {_e}", "WARN")
raise
except Exception as _e:
_log(f"generate FAILED after {time.time() - _t_req:.0f}s:\n{traceback.format_exc()}", "ERROR")
try:
import torch as _torch
if isinstance(_e, _torch.cuda.OutOfMemoryError):
_oom_dump("request", _e)
except Exception:
pass
raise
def export_last_frame(video_path):
"""Extract the last frame from a generated video and return it as an image file."""
if not video_path:
raise gr.Error("No video to extract from.")
import subprocess, tempfile
out = os.path.join(tempfile.gettempdir(), f"h3-lastframe-{int(time.time() * 1000)}.png")
result = subprocess.run(
["ffmpeg", "-sseof", "-0.1", "-i", video_path, "-frames:v", "1", "-y", out],
capture_output=True, text=True,
)
if result.returncode != 0:
raise gr.Error(f"ffmpeg failed: {result.stderr[-300:]}")
return out
def _fit_keyframe(image_path, current_canvas):
"""Cover-crop an uploaded keyframe to the closest supported aspect ratio and select that ratio's smallest
(fastest) canvas, unless the user already picked a matching ratio."""
if not image_path:
return gr.update(), gr.update()
from PIL import Image as _Image
img = _Image.open(image_path)
aspect = img.width / img.height
fastest = {}
for label, (h, w) in CANVASES.items():
r = w / h
if r not in fastest or w * h < fastest[r][1][0] * fastest[r][1][1]:
fastest[r] = (label, (h, w))
ratio = min(fastest, key=lambda r: abs(r - aspect))
label, (h, w) = fastest[ratio]
cur_h, cur_w = CANVASES[current_canvas]
if abs(cur_w / cur_h - aspect) <= abs(ratio - aspect):
label = current_canvas
h, w = cur_h, cur_w
target = w / h
if abs(img.width / img.height - target) <= 1e-3:
return gr.update(value=image_path), gr.update(value=label)
if img.width / img.height > target:
new_w = int(img.height * target)
left = (img.width - new_w) // 2
img = img.crop((left, 0, left + new_w, img.height))
else:
new_h = int(img.width / target)
top = (img.height - new_h) // 2
img = img.crop((0, top, img.width, top + new_h))
img.save(image_path)
return gr.update(value=image_path), gr.update(value=label)
load_models()
INTRO = """# minimax h3 turbo + lora's
<div align="center">
<a href="https://huggingface.co/MiniMaxAI/MiniMax-H3" target="_blank" rel="noopener"><strong>[ model ]</strong></a> &nbsp;
<a href="https://www.minimax.io/blog/minimax-h3" target="_blank" rel="noopener"><strong>[ blog ]</strong></a> &nbsp;
<a href="https://huggingface.co/spaces/multimodalart/minimax-h3-reference" target="_blank" rel="noopener"><strong>[ reference to video ]</strong></a>
</div>
**MiniMax-H3** is a 33B parameter state of the art video generation model that produces video and a
fully synchronized soundtrack (ambience, foley, speech).
**Turbo mode** (optional) applies the [larryvrh distillation LoRA](https://huggingface.co/InstantX/MiniMax-H3-Turbo-Lora-Diffusers)
at generation time, reducing inference from 25 steps to 7 for ~4× faster generation with minimal quality loss.
"""
CSS = """
.main.fillable { max-width: 1250px !important; }
/* ── Root gradient background ── */
.dark .gradio-container {
background: linear-gradient(135deg, #0a1628 0%, #0d2137 25%, #0f2b3a 50%, #0e3330 75%, #0a2a1f 100%) !important;
color: #e8f0f8 !important;
min-height: 100vh;
/* ── Override Gradio's CSS variables for dark theme ── */
--background-fill-primary: rgba(10, 22, 40, 0.6) !important;
--background-fill-secondary: rgba(10, 22, 40, 0.4) !important;
--block-background-fill: rgba(10, 22, 40, 0.5) !important;
--block-border-color: rgba(79, 195, 247, 0.15) !important;
--block-label-text-color: #a8c4d8 !important;
--block-title-text-color: #a8c4d8 !important;
--background-text-color: #e0edf5 !important;
--body-text-color: #e0edf5 !important;
--body-text-color-subdued: #8aa8bc !important;
--border-color-primary: rgba(79, 195, 247, 0.15) !important;
--color-accent: #26a69a !important;
--color-accent-soft: rgba(38, 166, 154, 0.15) !important;
--button-primary-background-fill: linear-gradient(135deg, #0288d1 0%, #00897b 50%, #2e7d32 100%) !important;
--button-primary-text-color: #ffffff !important;
--button-secondary-background-fill: rgba(255, 255, 255, 0.06) !important;
--button-secondary-border-color: rgba(255, 255, 255, 0.1) !important;
--button-secondary-text-color: #b0c8dc !important;
--input-background-fill: rgba(10, 22, 40, 0.6) !important;
--input-background-fill-focus: rgba(10, 22, 40, 0.7) !important;
--input-border-color: rgba(79, 195, 247, 0.15) !important;
--input-border-color-focus: rgba(79, 195, 247, 0.45) !important;
--slider-color: #26a69a !important;
--accordion-border-color: rgba(255, 255, 255, 0.06) !important;
}
/* ── Intro markdown ── */
.gradio-container .prose h1,
.gradio-container .prose h2 {
background: linear-gradient(135deg, #4fc3f7, #26a69a) !important;
-webkit-background-clip: text !important;
-webkit-text-fill-color: transparent !important;
background-clip: text !important;
}
.gradio-container .prose {
color: #c8dde8 !important;
}
.gradio-container .prose a {
color: #4dd0e1 !important;
}
/* ── Glass card panels (no backdrop-filter on .block — it traps fixed-position dropdown popups) ── */
.gradio-container .block {
background: rgba(255, 255, 255, 0.04) !important;
border: 1px solid rgba(255, 255, 255, 0.08) !important;
border-radius: 14px !important;
box-shadow: 0 4px 30px rgba(0, 0, 0, 0.25), inset 0 1px 0 rgba(255,255,255,0.05) !important;
}
/* ── Text / Number inputs (Gradio 6: label.container > .input-container > textarea/input) ── */
.gradio-container label.container textarea,
.gradio-container label.container input[type="text"],
.gradio-container input[type="number"] {
background: rgba(10, 22, 40, 0.6) !important;
border: 1px solid rgba(79, 195, 247, 0.15) !important;
color: #e0edf5 !important;
border-radius: 10px !important;
}
.gradio-container label.container textarea:focus,
.gradio-container label.container input[type="text"]:focus,
.gradio-container input[type="number"]:focus {
border-color: rgba(79, 195, 247, 0.45) !important;
box-shadow: 0 0 0 2px rgba(79, 195, 247, 0.12) !important;
}
/* ── Labels (Gradio 6: BlockTitle renders <span data-testid="block-info">) ── */
.gradio-container [data-testid="block-info"],
.gradio-container label {
color: #a8c4d8 !important;
font-weight: 500 !important;
}
/* ── Slider track ── */
.gradio-container input[type="range"] {
accent-color: #26a69a !important;
}
/* ── Checkbox (Gradio 6: <label class="checkbox-container"> → <input> + <span class="label-text">) ── */
.gradio-container .checkbox-container {
color: #c0d4e4 !important;
}
.gradio-container .checkbox-container .label-text {
color: #c0d4e4 !important;
}
/* ── Dropdown (Gradio 6: div.container > div.wrap > div.wrap-inner > input[role="combobox"]) ── */
.gradio-container .wrap {
background: rgba(10, 22, 40, 0.6) !important;
border: 1px solid rgba(79, 195, 247, 0.15) !important;
border-radius: 10px !important;
}
.gradio-container .wrap:focus-within {
border-color: rgba(79, 195, 247, 0.45) !important;
box-shadow: 0 0 0 2px rgba(79, 195, 247, 0.12) !important;
}
.gradio-container .wrap-inner input[role="combobox"] {
color: #e0edf5 !important;
background: transparent !important;
}
/* Dropdown popup options (Gradio 6: <ul class="options"> with position:fixed) */
.gradio-container ul.options {
background: rgba(10, 22, 40, 0.95) !important;
border: 1px solid rgba(79, 195, 247, 0.25) !important;
border-radius: 10px !important;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5) !important;
z-index: 1000 !important;
}
.gradio-container ul.options li.item {
color: #e0edf5 !important;
}
.gradio-container ul.options li.item:hover,
.gradio-container ul.options li.item.active {
background: rgba(79, 195, 247, 0.15) !important;
}
/* ── Image upload area ── */
.gradio-container .image-container,
.gradio-container .upload-container {
background: rgba(10, 22, 40, 0.35) !important;
border: 2px dashed rgba(79, 195, 247, 0.2) !important;
border-radius: 12px !important;
}
.gradio-container .image-container:hover,
.gradio-container .upload-container:hover {
border-color: rgba(38, 166, 154, 0.5) !important;
}
/* ── Video output ── */
.gradio-container video {
border-radius: 12px !important;
border: 1px solid rgba(255,255,255,0.06) !important;
}
/* ── Generate button — hero gradient ── */
.gradio-container .lg.primary,
.gradio-container button.primary,
.gradio-container button.lg.primary {
background: linear-gradient(135deg, #0288d1 0%, #00897b 50%, #2e7d32 100%) !important;
color: #ffffff !important;
border: none !important;
border-radius: 12px !important;
font-weight: 700 !important;
letter-spacing: 0.03em !important;
text-transform: uppercase !important;
box-shadow: 0 4px 20px rgba(0, 137, 123, 0.35), 0 0 40px rgba(2, 136, 209, 0.15) !important;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
position: relative;
overflow: hidden;
}
.gradio-container .lg.primary::before {
content: "";
position: absolute;
inset: 0;
background: linear-gradient(135deg, rgba(255,255,255,0.15) 0%, transparent 50%, rgba(255,255,255,0.05) 100%);
pointer-events: none;
}
.gradio-container .lg.primary:hover,
.gradio-container button.primary:hover {
box-shadow: 0 6px 28px rgba(0, 137, 123, 0.5), 0 0 60px rgba(2, 136, 209, 0.25) !important;
transform: translateY(-1px) !important;
}
/* ── Secondary buttons ── */
.gradio-container button.secondary,
.gradio-container button.lg.secondary {
background: rgba(255, 255, 255, 0.06) !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
color: #b0c8dc !important;
}
.gradio-container button.secondary:hover {
background: rgba(255, 255, 255, 0.1) !important;
border-color: rgba(79, 195, 247, 0.3) !important;
}
/* ── Accordion (Gradio 6: Index.svelte adds "gr-accordion" to elem_classes; header is <button class="label-wrap">) ── */
.gradio-container .gr-accordion {
background: rgba(255, 255, 255, 0.03) !important;
border: 1px solid rgba(255, 255, 255, 0.06) !important;
border-radius: 12px !important;
}
.gradio-container .gr-accordion .label-wrap {
color: #a8c4d8 !important;
font-weight: 600 !important;
}
.gradio-container .gr-accordion .label-wrap:hover {
color: #4fc3f7 !important;
}
.gradio-container .gr-accordion [data-testid="accordion-content"] {
padding-top: var(--size-2, 8px) !important;
}
/* ── Examples ── */
.gradio-container .examples {
background: rgba(10, 22, 40, 0.3) !important;
border: 1px solid rgba(255, 255, 255, 0.06) !important;
border-radius: 12px !important;
}
/* ── Markdown output ── */
.gradio-container .prose {
color: #b8ccda !important;
}
.gradio-container .prose code {
background: rgba(79, 195, 247, 0.1) !important;
color: #4dd0e1 !important;
border-radius: 4px !important;
padding: 2px 6px !important;
}
/* ── Scrollbar ── */
.gradio-container ::-webkit-scrollbar {
width: 6px !important;
}
.gradio-container ::-webkit-scrollbar-track {
background: rgba(0,0,0,0.2) !important;
}
.gradio-container ::-webkit-scrollbar-thumb {
background: rgba(79, 195, 247, 0.3) !important;
border-radius: 3px !important;
}
"""
def _lora_descriptions(keys):
"""Markdown of each selected LoRA's label + description, plus conflict warnings; hidden when nothing is selected."""
keys = tuple(k for k in (keys or ()) if k in NSFW_LORA_CONFIGS)
if not keys:
return gr.update(visible=False)
blocks = [f"**{NSFW_LORA_CONFIGS[k]['label']}** — {NSFW_LORA_CONFIGS[k]['desc']}" for k in keys]
conflicts = []
for group, members in LORA_CONFLICT_GROUPS.items():
hit = [k for k in keys if k in members]
if len(hit) > 1:
conflicts.append(f"**{group}**: " + " + ".join(NSFW_LORA_CONFIGS[k]['label'] for k in hit))
if conflicts:
blocks.append("**⚠️ Conflicts:** " + " ".join(conflicts)
+ " — these overlap in purpose and may fight each other; consider picking one from each group.")
return gr.update(value="\n\n".join(blocks), visible=True)
with gr.Blocks(title="minimax h3 turbo + lora's") as demo:
gr.Markdown(INTRO)
with gr.Row():
with gr.Column():
prompt = gr.Textbox(
label="Prompt",
lines=3,
value="A red fox trotting through a snowy pine forest at dawn, snow crunching underfoot",
)
with gr.Row():
upsample = gr.Checkbox(label="Upsample prompt", value=False)
turbo = gr.Checkbox(label="Turbo (7-step LoRA)", value=False,
visible=TURBO_AVAILABLE,
info="Apply larryvrh distillation LoRA, reduce steps from 25 to 7")
with gr.Accordion("NSFW LoRAs", open=False):
nsfw_lora_keys = gr.Dropdown(
label="Select LoRAs to apply",
choices=[(cfg["label"], key) for key, cfg in NSFW_LORA_CONFIGS.items() if key != "nsfw_aio"],
value=[],
multiselect=True,
filterable=True,
info="Searchable — type to filter. Selected LoRAs show as removable tags; their trigger tokens are auto-appended to the prompt. The HMNSFW AIO motion adapter auto-loads whenever any LoRA is selected.",
)
lora_desc = gr.Markdown(visible=False)
with gr.Accordion("Custom LoRA (Hugging Face)", open=False):
gr.Markdown("Paste a Hugging Face link — a repo page or a direct `.safetensors` file link — then press "
"**Download & Verify**. The verified LoRA is applied on Generate. "
"ComfyUI and kohya formats are auto-detected.")
custom_lora_url = gr.Textbox(
label="HF repo or .safetensors link",
placeholder="https://huggingface.co/Owner/Repo or https://huggingface.co/Owner/Repo/resolve/main/file.safetensors",
)
with gr.Row():
custom_lora_scale = gr.Number(label="Scale", value=1.0, minimum=0.01, maximum=4.0, step=0.1)
custom_lora_trigger = gr.Textbox(label="Trigger (optional)",
placeholder="Auto-appended to the prompt if given")
custom_lora_btn = gr.Button("Download & Verify", size="sm")
custom_lora_status = gr.Markdown(visible=False)
with gr.Row():
image = gr.Image(label="First frame (optional)", type="filepath")
last_image = gr.Image(label="Last frame (optional)", type="filepath")
run = gr.Button("Generate", variant="primary")
with gr.Accordion("Advanced options", open=False):
canvas = gr.Dropdown(label="Canvas", choices=list(CANVASES), value=DEFAULT_CANVAS)
duration = gr.Slider(label="Duration (s)", minimum=MIN_UI_DURATION, maximum=MAX_UI_DURATION, step=1, value=5)
steps = gr.Slider(label="Steps", minimum=7, maximum=40, step=1, value=25)
seed = gr.Number(label="Seed (−1 = random)", value=-1, precision=0)
with gr.Column():
video = gr.Video(label="Video + soundtrack")
with gr.Row():
last_frame_btn = gr.Button("Export Last Frame", size="sm")
download_btn = gr.DownloadButton("Download Video", size="sm", visible=False)
last_frame_output = gr.Image(label="Last frame")
lora_label = gr.Markdown(visible=False)
report = gr.Markdown(visible=False)
# An output, so it can be revealed only for a request that asked for a rewrite.
with gr.Accordion("Upsampled prompt", open=False, visible=False) as upsampled_panel:
upsampled = gr.Textbox(show_label=False, lines=8, interactive=False)
image.upload(_fit_keyframe, [image, canvas], [image, canvas])
run.click(
generate,
[prompt, image, last_image, canvas, duration, steps, seed, upsample, turbo, nsfw_lora_keys,
custom_lora_url, custom_lora_scale, custom_lora_trigger],
[video, report, upsampled, upsampled_panel, download_btn, lora_label],
api_name="generate",
)
custom_lora_btn.click(_download_custom_lora,
[custom_lora_url, custom_lora_scale, custom_lora_trigger],
[custom_lora_status])
nsfw_lora_keys.change(_lora_descriptions, [nsfw_lora_keys], [lora_desc])
last_frame_btn.click(
export_last_frame,
[video],
[last_frame_output],
)
download_btn.click(
lambda: gr.Info("Downloading video..."),
[],
[],
)
if __name__ == "__main__":
demo.launch(show_error=True, theme=gr.themes.Base(), css=CSS)