/ Модель

Характеристики

Лицензия
Своя лицензия
Базовая модель
LTX-2.3
Опубликована
24 июн 2026

Lightricks-LTX-2-DISTILLED-10-Eros

Видео из изображенияИзображение, текст → видео3 профессии
55 944скачиваний за 30 дней20лайковвеса обновлены12 ноя 2026

Описание модели

Составлено на русском по карточке модели и метаданным Hugging Face

10 Eros — доработанная на основе LTX-2.3 модель для генерации видео по изображению и текстовому описанию с настройкой на откровенный контент.

10 Eros — пользовательская доработка видеомодели LTX-2.3, опубликованная под названием Sulphur 2. Она предназначена для генерации видео по изображению и текстовому описанию; автор также заявляет поддержку генерации только по тексту в семействе моделей. В карточке Hugging Face основная задача указана как image-to-video, а связь с Lightricks/LTX-2.3 отмечена как дообучение. Репозиторий содержит веса safetensors; README описывает варианты чекпойнта и рекомендации по использованию с LoRA, но официальная инструкция по запуску ещё готовится.

Автор сообщает об изменениях в версиях 1.2–1.5, направленных на управление движением, следование подробным промптам и стабильность структуры видео. Для хороших результатов нужны детальные инструкции и уточнение промпта; README также предупреждает, что некоторые LoRA могут ухудшать работу модели. Модель описана как uncensored и рассчитана на генерацию откровенного контента. Лицензия в метаданных указана как other, конкретные условия использования в предоставленных данных не раскрыты.

Сценарии применения

  • создание видео по исходному изображению и описанию движения
  • анимация персонажей и сцен по первому кадру
  • генерация откровенных видео по текстовому промпту
  • создание видео с управляемой композицией и движением

Ограничения

Результат чувствителен к качеству и детализации промпта; автор рекомендует уточнять инструкции, а некоторые LoRA могут ухудшить тонкую настройку модели. Официальные инструкции по запуску ещё готовятся, а конкретные условия лицензии в доступных данных не раскрыты.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

carefull with DMD on some of these Sulphur 2

An uncensored video generation model based on LTX 2.3 supporting both t2v and i2v natively, as well as all of the other ltx 2.3 formats.

Follow us on X

Join our Discord

Support the next version of the project, even just a few dollars would go a long way: Kofi

As a note, official inference for the model is coming soon.


Get Started: To get started with the model, I recommend downloading either of the dev versions, (fp8mixed or bf16) and downloading the distill lora provided. By the way, I'm aware the workflows contain sulphur_final right now, just use the lora or use the full models, don't use both at the same time.

This model contains a prompt enhancer. The easiest way to get started with the prompt enhancer is by using it on lmstudio. The way to accomplish this is by going to your model folder inside lmstudio, then opening it up in your file explorer. Create a folder named "Sulphur", then a folder inside that called "promptenhancer". Inside that folder, place the gguf file and the mmproj file. Once you've done that, you should be able to load the prompt enhancer in lmstudio. There is no system prompt for it, just send the text (and an image) you'd like to be enhanced.

*As a note, this readme will contain better setup instructions and how to train on top of the model soon.


Links

Credits

Funders

  • Anonymous funder #1 — Supported the original Sulphur
  • Anonymous funder #2 — Made Sulphur 2 possible; this model wouldn't exist without them

Thank you to everyone who contributed.

10 Eros

v1.5 Changelog: 1.4 and DMD only struggled with one thing, explicit motion and anatomy that was easy to access in version 1.2 and sulphur. All that data is still inside the model; versions 1.2, 1.3, 1.4, and 1.5 are almost all the same model. The difference is how the attn_2 and attn_1 gates are handled. 1.5 is 1.4 with a linear ramp across the gates to open up those explicit details from sulphur like they are on version 1.2's blocks. It still mostly maintains 1.4's base model style prompting and more stable outputs and structure. Because it is a hybrid of a model made for DMD and a model made for LTX distilled lora use, it goes best with a hybrid lora to make use of the motion vareity. Currently the hybrid block DMD lora here seems to work nicely: https://huggingface.co/TenStrip/LTX2.3_DMD_Lora/blob/main/LTX2.3_DMD_hybrid_v2.safetensors or these ones: https://huggingface.co/maximsobolev275/LTX2.3-DMD-Distill-Lora-Hybrids

1.5 INT8 with hybrid v2 merge: https://huggingface.co/CornLogic/10EROS-INT8/tree/main

1.5 INT8 quality version: https://huggingface.co/LokkenJP/10EROS_1.5_fp8_exp_learned

v1.4 Changelog: Built off 1.3 and bringing back explicit prompting and motion hopefully without any kind of anatomy redraw or negative tendency. Still requires intense prompt refinement. This version is set up to be trained on to fix it into a real base, it doesn't depict anatomy well but it also isn't confused by it which is priority for the first lora passes I'll do. Use lora stacks to improve it if needed.

v1.3 Changelog: Only designed to work with DMD lora on a workflow like my V5 DMD. https://huggingface.co/TenStrip/LTX2.3-10Eros_Workflows/blob/main/10Eros_10SNodes_I2V_Basic_DMD_V5.json

Full remix aimed at the way the original beta functioned. Any Lora for 2.3 that exists for the attempted concept should be used and is reccomended. For further versions I train my own anatomy patches but I couldn't work with the subtitles and general overexcitement of the older versions going forward. The over-sulphur issues like ghost anatomy and subtitles should be greatly diminished while actual explicit motions and prompting stay at a comparable level. Prompting is 100% more important and should be approached like it is in the base 22b dev model, strict and descriptive and directive.

v1.2 Changelog: Leveraged tuned connector data to reduce face drift and aid long prompts/director. Also using sulphur EXP weights on top of v1 to hone the most explicit motions. All common issues like mistaken extra anatomy, subtitles, unexpected transitions, etc all still present from v1.

https://huggingface.co/TenStrip/LTX2.3-10Eros_Workflows

Quants: https://huggingface.co/vantagewithai/LTX2.3-10Eros-GGUF/tree/main

Nodes: https://github.com/TenStrip/10S-Comfy-nodes

Reliant on https://huggingface.co/SulphurAI/Sulphur-2-base This is a different merge attempt for ideal I2V use. It uses layer scaled merges of different steps, it's not a straight weight merge. It behaves much nicer than lora load and respects prompt. Prompt should be enhanced, LTX has very little self reasoning and input when it is conditioned, first frame and all following motions, evolutions, and audio must be commanded-you will get nothing if you don't ask it.

BF16 loads as a checkpoint with clip and VAEs.

Fp8_mixed_learned is the better FP8 version and is a full checkpoint as well, quant by S1LV3RC01N.

Kijai split files are for 10Eros FP8 Transformer version, but it has a different structure and variance. That one goes inside diffusion_models: https://huggingface.co/Kijai/LTX2.3_comfy/tree/main

!!! Larger distilled Loras will harm the model's fine tune, try the cond_safe ones: https://huggingface.co/TenStrip/LTX2.3_Distilled_Lora_1.1_Experiments/tree/main

For prompt enhancement, try this foreword in Grok or Uncensored LLM:

Generate a video scene script with a description based on the attached image for an LLM that has a tokenizer that uses interleaved attention to support long-context understanding that is fed into a multimodal video model. Strict specification, follow up to the word: No timestamps. No unnecessary embellishment. Output only plain English text and make it a copy box.

First, describe the image initial scene in concise natural language; subject(s), subject(s) appearance, subject(s) composition and pose, background, and context.

Next, formulate a naturally evolving scenario that would take place describing every moving body part, composition change, and manipulation from the uploaded initial frame that would be reflected in the video models post-latent evolution output. If the image is explicit or sexual in nature, use full anatomical terminology and spice it up slightly with visually representable erotic themes.

Center the prompt around this basic idea: [ concept ]

interweave this dialogue or sound concept into the scene with descriptions of voice tone followed by the lines delivered in quotations, in a temporal sequence between or during motions. Dialogue should be concise and non-rambling as it will take away from video quality: [ dialogue ]

Inside that prompt describe only notable audio and audio queues, both normal and explicit; background noise as well as foley and natural sounds. In a temporal sequence paired with coinciding motions. In the case of absent dialogue or soundscapes and only if background music is fitting; describe a fitting genre and melodic tone with matching mood.

Output only text following above instruction. Follow-up suggestions should be on the topic of expanding or changing motion or dialogue from the output text.

from huggingface_hub import hf_hub_download
import os
HF_TOKEN = os.environ.get("HF_TOKEN")
vanilla_base_path = hf_hub_download(
    repo_id="ibyteohdear/Lightricks-LTX-2.3",
    filename="ltx-2.3-22b-dev.safetensors", # or sulphur
    token=HF_TOKEN,
    cache_dir="/tmp/hf_cache"
)

lora_path = hf_hub_download(
    repo_id="ibyteohdear/Lightricks-LTX-2.3",
    filename="10Eros_v1.2_bf16.safetensors",
    token=HF_TOKEN,
    cache_dir="/tmp/hf_cache"
)
!pip install -q safetensors tqdm

import torch
from safetensors import safe_open
from safetensors.torch import save_file
from tqdm import tqdm
import os

base_path = vanilla_base_path
fine_path = lora_path

out_path = "/content/out/LTX_10Eros_LoRA_r768.safetensors"

rank = 768
device = "cuda"

os.makedirs("/content/out", exist_ok=True)

lora = {}

with safe_open(base_path, framework="pt", device="cpu") as base_f, \
     safe_open(fine_path, framework="pt", device="cpu") as fine_f:

    keys = list(fine_f.keys())

    targets = [
        k for k in keys
        if k.startswith("model.diffusion_model.")
        and k.endswith(".weight")
        and "norm" not in k.lower()
        and "bias" not in k.lower()
    ]

    print("Extracting", len(targets), "layers")

    for key in tqdm(targets):

        base = base_f.get_tensor(key)
        fine = fine_f.get_tensor(key)

        # Only LoRA-compatible matrices
        if base.ndim != 2:
            continue

        delta = (fine - base).float().to(device)

        # SVD
        U, S, Vh = torch.linalg.svd(delta, full_matrices=False)

        r = min(rank, S.shape[0])

        U = U[:, :r]
        S = S[:r]
        Vh = Vh[:r, :]

        # LoRA convention
        A = Vh
        B = U @ torch.diag(S)

        name = key

        lora[f"{name}.lora_A.weight"] = A.cpu().to(torch.bfloat16)
        lora[f"{name}.lora_B.weight"] = B.cpu().to(torch.bfloat16)


save_file(lora, out_path)

print("Saved:", out_path)
print("Tensors:", len(lora))
from huggingface_hub import HfApi
api = HfApi()
DEST_REPO = "ibyteohdear/Lightricks-LTX-2.3"
output_filename = "/content/out/LTX_10Eros_LoRA_r768.safetensors"

api.upload_file(
    path_or_fileobj=output_filename,
    path_in_repo="10Eros_v12.1_r768.safetensors",
    repo_id=DEST_REPO,
    token=HF_TOKEN,
)
print("Pipeline execution complete.")

import spaces 
import os 
import sys 
import torch 
import shutil 
from huggingface_hub import hf_hub_download, snapshot_download
from safetensors.torch import load_file, save_file, safe_open

HF_TOKEN = os.environ.get("HF_TOKEN")
BASE = "/tmp/hf" 

@spaces.GPU(duration=600) 
def run_pipeline(): 

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    
    # 1. Download base weights (The complete 46.1 GB flat file)
    print("Downloading base BF16 checkpoint...")
    vanilla_base_path = hf_hub_download(
        repo_id="ibyteohdear/Lightricks-LTX-2.3",
        filename="ltx-2.3-22b-distilled-1.1.safetensors",
        token=HF_TOKEN,
        cache_dir="/tmp/hf_cache"
    )
    
    # 2. Download LoRA
    print("Downloading LoRA weights...")
    lora_path = hf_hub_download(
        repo_id="ibyteohdear/Lightricks-LTX-2.3",
        filename="10Eros_v14_r768.safetensors",
        token=HF_TOKEN,
        cache_dir="/tmp/hf_cache"
    )
    
    # 4. Load the entire original 46.1 GB dictionary into RAM memory
    print("Loading tensors into RAM...")
    base_state_dict = load_file(vanilla_base_path, device="cpu")
    
    # 5. Load LoRA weights
    lora_state_dict = load_file(lora_path, device="cpu")
    
    # 6. Apply LoRA updates directly onto matching base keys
    print("Starting LoRA fusion loop...")
    baked_count = 0
    added_count = 0
    skipped_count = 0
    lora_strength = 1.0

    print("Example LoRA keys:")
    for k in list(lora_state_dict.keys())[:10]:
        print(k)

    print("\nExample Base keys:")
    for k in list(base_state_dict.keys())[:10]:
        print(k)

    matches = 0
    total = 0
    
    for k in lora_state_dict:
        if ".lora_A.weight" in k:
            total += 1
            prefix = k.replace(".lora_A.weight","")
            candidates = [
                prefix,
                prefix+".weight",
                prefix.replace("diffusion_model.",""),
                prefix.replace("model.diffusion_model.","")+".weight"
            ]
    
            if any(x in base_state_dict for x in candidates):
                matches += 1
    
    print(f"Compatible LoRA layers: {matches}/{total}")

    # Scan the LoRA dictionary keys
    for lora_key in list(lora_state_dict.keys()):
        # Path variation A: Standard low-rank naming (.lora_down / .lora_up)
        if ".lora_down.weight" in lora_key:
            prefix = lora_key.split(".lora_down.weight")[0]
            down_key = f"{prefix}.lora_down.weight"
            up_key = f"{prefix}.lora_up.weight"
    
            if up_key in lora_state_dict:
                target_base_key = prefix
                
                # CRITICAL: Only touch the base model if the key exists there natively!
                if target_base_key in base_state_dict:
                    try:
                        W_base = base_state_dict[target_base_key].to(
                            device=device,
                            dtype=torch.bfloat16
                        )
                        
                        A = lora_state_dict[a_key].to(
                            device=device,
                            dtype=torch.bfloat16
                        )
                        
                        B = lora_state_dict[b_key].to(
                            device=device,
                            dtype=torch.bfloat16
                        )
                        
                        rank = A.shape[0]   # usually rank dimension
                        alpha = 768         # replace if metadata gives another value
                        
                        scale = alpha / rank
                        
                        delta_W = torch.matmul(B, A) * scale
                        
                        base_state_dict[target_base_key] = (
                            W_base + delta_W
                        ).cpu()
                    except Exception as e:
                        print(f"Failed to bake layer {target_base_key}: {e}")
                        skipped_count += 1
                else:
                    skipped_count += 1

        # Path variation B: Low-rank dimension naming (.lora_A / .lora_B)
        elif ".lora_A.weight" in lora_key:
            prefix = lora_key.split(".lora_A.weight")[0]
            a_key = f"{prefix}.lora_A.weight"
            b_key = f"{prefix}.lora_B.weight"
            
            if b_key not in lora_state_dict:
                continue
                
            target_base_key = prefix
            
            if target_base_key in base_state_dict:
                try:
                    W_base = base_state_dict[target_base_key].to(
                        device=device,
                        dtype=torch.bfloat16
                    )
                    
                    A = lora_state_dict[a_key].to(
                        device=device,
                        dtype=torch.bfloat16
                    )
                    
                    B = lora_state_dict[b_key].to(
                        device=device,
                        dtype=torch.bfloat16
                    )
                    
                    rank = A.shape[0]
                    alpha = 768   # replace after checking metadata
                    scale = alpha / rank
                    
                    delta_W = torch.matmul(B, A) * scale
                    
                    if delta_W.shape != W_base.shape:
                        print("SHAPE FAIL:", target_base_key, W_base.shape, delta_W.shape)
                        skipped_count += 1
                        continue
                    
                    base_state_dict[target_base_key] = (
                        W_base + delta_W
                    ).cpu()
                    
                    baked_count += 1
                except Exception as e:
                    print(f"Failed to bake layer {target_base_key}: {e}")
                    skipped_count += 1
            else:
                skipped_count += 1

    # --- PROOF & LOGGING REGION ---
    print("\n==================================================")
    print("                FUSION VERIFICATION               ")
    print("==================================================")
    print(f" Successfully Baked Layers  : {baked_count}")
    print(f" Newly Injected Multi-Layers: {added_count}")
    print(f" Skipped / Mismatched Keys  : {skipped_count}")
    print("==================================================")
    
    if baked_count == 0 and added_count == 0:
        print("❌ CRITICAL WARNING: Zero operations were completed. Output will be unmodified!")
        return
    else:
        print("✅ SUCCESS: BF16 loop fusion complete.\n")
    
    # 7. Extract the original header metadata so the inference app knows the exact shapes
    try:
        with safe_open(vanilla_base_path, framework="pt", device="cpu") as f:
            original_metadata = f.metadata()
    except Exception as e:
        original_metadata = None
    
    # 8. DISK MANAGEMENT: Wipe cache down to free disk space before exporting
    print("Cleaning cache directory...")
    try:
        if os.path.exists("/tmp/hf_cache"):
            shutil.rmtree("/tmp/hf_cache")
    except Exception as e:
        pass
    
    # 9. Write out and upload file
    from huggingface_hub import HfApi
    api = HfApi()
    
    DEST_REPO = "ibyteohdear/Lightricks-LTX-2.3"
    output_filename = "/tmp/LTX2.3_DISTILLED_BAKED.safetensors"
    
    print("Saving the new baked safetensors file...")
    if original_metadata:
        save_file(base_state_dict, output_filename, metadata=original_metadata)
    else:
        save_file(base_state_dict, output_filename)
    
    print(f"Uploading target file to Hugging Face: {DEST_REPO}...")
    api.upload_file(
        path_or_fileobj=output_filename,
        path_in_repo="LTX2.3_DISTILLED-1.1_BAKED_LTX_10Eros_v14_r768.safetensors",
        repo_id=DEST_REPO,
        token=HF_TOKEN,
    )
    print("Pipeline execution complete.")

if __name__ == "__main__": 
    run_pipeline()


import spaces 
import os 
import sys 
import torch 
import shutil 
from huggingface_hub import hf_hub_download, snapshot_download
from safetensors.torch import load_file, save_file, safe_open

HF_TOKEN = os.environ.get("HF_TOKEN")
BASE = "/tmp/hf" 

@spaces.GPU(duration=600) 
def run_pipeline(): 

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    
    # 1. Download base weights (The complete 46.1 GB flat file)
    print("Downloading base BF16 checkpoint...")
    vanilla_base_path = hf_hub_download(
        repo_id="SulphurAI/Sulphur-2-base",
        filename="sulphur_distil_bf16.safetensors",
        token=HF_TOKEN,
        cache_dir="/tmp/hf_cache"
    )
    
    # 2. Download LoRA
    print("Downloading LoRA weights...")
    lora_path = hf_hub_download(
        repo_id="ibyteohdear/Lightricks-LTX-2-10Eros-lora",
        filename="10Eros_S_v12_r256.safetensors",
        token=HF_TOKEN,
        cache_dir="/tmp/hf_cache"
    )
    
    # 4. Load the entire original 46.1 GB dictionary into RAM memory
    print("Loading tensors into RAM...")
    base_state_dict = load_file(vanilla_base_path, device="cpu")
    
    # 5. Load LoRA weights
    lora_state_dict = load_file(lora_path, device="cpu")
    
    # 6. Apply LoRA updates directly onto matching base keys
    print("Starting LoRA fusion loop...")
    baked_count = 0
    added_count = 0
    skipped_count = 0
    lora_strength = 1.0

    print("Example LoRA keys:")
    for k in list(lora_state_dict.keys())[:10]:
        print(k)

    print("\nExample Base keys:")
    for k in list(base_state_dict.keys())[:10]:
        print(k)

    matches = 0
    total = 0
    
    for k in lora_state_dict:
        if ".lora_A.weight" in k:
            total += 1
            prefix = k.replace(".lora_A.weight","")
            candidates = [
                prefix,
                prefix+".weight",
                prefix.replace("diffusion_model.",""),
                prefix.replace("model.diffusion_model.","")+".weight"
            ]
    
            if any(x in base_state_dict for x in candidates):
                matches += 1
    
    print(f"Compatible LoRA layers: {matches}/{total}")

    STYLE_LAYERS = [
        "to_q",
        "to_k",
        "to_v",
        "to_out",
        "ff.net.0.proj",
        "ff.net.2"
    ]

    # Your logic inside the loop:
    for lora_key in list(lora_state_dict.keys()):
        # Path variation A: Standard low-rank naming (.lora_down / .lora_up)
        if ".lora_down.weight" in lora_key:
            prefix = lora_key.split(".lora_down.weight")[0]
            down_key = f"{prefix}.lora_down.weight"
            up_key = f"{prefix}.lora_up.weight"
    
            if up_key in lora_state_dict:
                target_base_key = prefix

                if not any(x in target_base_key for x in STYLE_LAYERS):
                    skipped_count += 1
                    continue
                
                # CRITICAL: Only touch the base model if the key exists there natively!
                if target_base_key in base_state_dict:
                    try:
                        W_base = base_state_dict[target_base_key].to(
                            device=device,
                            dtype=torch.bfloat16
                        )
                        
                        A = lora_state_dict[a_key].to(
                            device=device,
                            dtype=torch.bfloat16
                        )
                        
                        B = lora_state_dict[b_key].to(
                            device=device,
                            dtype=torch.bfloat16
                        )
                        
                        rank = A.shape[0]   # usually rank dimension
                        alpha = 256         # replace if metadata gives another value
                        
                        scale = alpha / rank
                        
                        delta_W = torch.matmul(B, A) * scale
                        
                        base_state_dict[target_base_key] = (
                            W_base + delta_W
                        ).cpu()
                    except Exception as e:
                        print(f"Failed to bake layer {target_base_key}: {e}")
                        skipped_count += 1
                else:
                    skipped_count += 1

        # Path variation B: Low-rank dimension naming (.lora_A / .lora_B)
        elif ".lora_A.weight" in lora_key:
            prefix = lora_key.split(".lora_A.weight")[0]
            a_key = f"{prefix}.lora_A.weight"
            b_key = f"{prefix}.lora_B.weight"
            
            if b_key not in lora_state_dict:
                continue
                
            target_base_key = prefix

            if not any(x in target_base_key for x in STYLE_LAYERS):
                skipped_count += 1
                continue
                                    
            if target_base_key in base_state_dict:
                try:
                    W_base = base_state_dict[target_base_key].to(
                        device=device,
                        dtype=torch.bfloat16
                    )
                    
                    A = lora_state_dict[a_key].to(
                        device=device,
                        dtype=torch.bfloat16
                    )
                    
                    B = lora_state_dict[b_key].to(
                        device=device,
                        dtype=torch.bfloat16
                    )
                    
                    rank = A.shape[0]
                    alpha = 256   # replace after checking metadata
                    scale = alpha / rank
                    
                    delta_W = torch.matmul(B, A) * scale
                    
                    if delta_W.shape != W_base.shape:
                        print("SHAPE FAIL:", target_base_key, W_base.shape, delta_W.shape)
                        skipped_count += 1
                        continue
                    
                    base_state_dict[target_base_key] = (
                        W_base + delta_W
                    ).cpu()
                    
                    baked_count += 1
                except Exception as e:
                    print(f"Failed to bake layer {target_base_key}: {e}")
                    skipped_count += 1
            else:
                skipped_count += 1

    # --- PROOF & LOGGING REGION ---
    print("\n==================================================")
    print("                FUSION VERIFICATION               ")
    print("==================================================")
    print(f" Successfully Baked Layers  : {baked_count}")
    print(f" Newly Injected Multi-Layers: {added_count}")
    print(f" Skipped / Mismatched Keys  : {skipped_count}")
    print("==================================================")
    
    if baked_count == 0 and added_count == 0:
        print("❌ CRITICAL WARNING: Zero operations were completed. Output will be unmodified!")
        return
    else:
        print("✅ SUCCESS: BF16 loop fusion complete.\n")
    
    # 7. Extract the original header metadata so the inference app knows the exact shapes
    try:
        with safe_open(vanilla_base_path, framework="pt", device="cpu") as f:
            original_metadata = f.metadata()
    except Exception as e:
        original_metadata = None
    
    # 8. DISK MANAGEMENT: Wipe cache down to free disk space before exporting
    print("Cleaning cache directory...")
    try:
        if os.path.exists("/tmp/hf_cache"):
            shutil.rmtree("/tmp/hf_cache")
    except Exception as e:
        pass
    
    # 9. Write out and upload file
    from huggingface_hub import HfApi
    api = HfApi()
    
    DEST_REPO = "ibyteohdear/Lightricks-LTX-2-DISTILLED-10-Eros"
    output_filename = "/tmp/LTX2.3_DISTILLED_BAKED.safetensors"
    
    print("Saving the new baked safetensors file...")
    if original_metadata:
        save_file(base_state_dict, output_filename, metadata=original_metadata)
    else:
        save_file(base_state_dict, output_filename)
    
    print(f"Uploading target file to Hugging Face: {DEST_REPO}...")
    api.upload_file(
        path_or_fileobj=output_filename,
        path_in_repo="LTX2.3_DISTILLED_BAKED_LTX_SULPHUR_STYLE_IS_10Eros_v12_r256.safetensors",
        repo_id=DEST_REPO,
        token=HF_TOKEN,
    )
    print("Pipeline execution complete.")

if __name__ == "__main__": 
    run_pipeline()

import os
import sys
import torch
import shutil
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file, save_file, safe_open

HF_TOKEN = os.environ.get("HF_TOKEN")

def run_pipeline():
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    
    # ============== CONFIG ==============
    # 10Eros: style at 0.85 (first pass)
    FIRST_LORA_REPO = "ibyteohdear/Lightricks-LTX-2-10Eros-lora"
    FIRST_LORA_FILE = "10Eros_v15_r512.safetensors"
    
    # Sulphur: audio at 0.9, everything else at 0.9 (second pass, only skipped)
    SECOND_LORA_REPO = "ibyteohdear/Lightricks-LTX-2-10Eros-lora"
    SECOND_LORA_FILE = "10Eros_v15_r256.safetensors"
    #SECOND_LORA_FILE = "Sulphur_r256.safetensors"

    # Base model
    BASE_REPO = "ibyteohdear/Lightricks-LTX-2"
    BASE_FILE = "ltx-2.5-22b-dev-transformer-bf16.safetensors"
    
    # Output
    DEST_REPO = "ibyteohdear/Lightricks-LTX-2"
    OUTPUT_FILENAME = "LTX2.5_DEV_85_STYLE_10Eros_15_r512_audio_r256_rest_0.safetensors"
    # ===================================
    
    # 1. Download base weights
    print("Downloading base BF16 checkpoint...")
    vanilla_base_path = hf_hub_download(
        repo_id=BASE_REPO,
        filename=BASE_FILE,
        token=HF_TOKEN,
        cache_dir="/tmp/hf_cache"
    )
    
    # 2. Download first LoRA
    print("Downloading first LoRA weights...")
    first_lora_path = hf_hub_download(
        repo_id=FIRST_LORA_REPO,
        filename=FIRST_LORA_FILE,
        token=HF_TOKEN,
        cache_dir="/tmp/hf_cache"
    )
    
    # 3. Download second LoRA
    print("Downloading second LoRA weights...")
    second_lora_path = hf_hub_download(
        repo_id=SECOND_LORA_REPO,
        filename=SECOND_LORA_FILE,
        token=HF_TOKEN,
        cache_dir="/tmp/hf_cache"
    )
    
    # 4. Load tensors into RAM
    print("Loading base tensors into RAM...")
    base_state_dict = load_file(vanilla_base_path, device="cpu")
    
    # 5. Load LoRA weights
    print("Loading first LoRA weights...")
    first_lora_state_dict = load_file(first_lora_path, device="cpu")
    
    print("Loading second LoRA weights...")
    second_lora_state_dict = load_file(second_lora_path, device="cpu")
    
    # 6. PASS 1: Apply 10Eros — ONLY style layers at 0.85
    print("\n" + "="*60)
    print("PASS 1: 10Eros — style layers at 0.85")
    print("="*60)
    
    AUDIO_PRESERVE_LAYERS = [
        "audio_attn1",
        "audio_attn2",
        "audio_ff",
        "audio_to_video_attn",
        "video_to_audio_attn",
    ]

    STYLE_LAYERS = [
        "to_q",
        "to_k",
        "to_v",
        "to_out",
        "ff.net.0.proj",
        "ff.net.2"
    ]

    pass1_baked = 0
    pass1_skipped = []
    pass1_processed_keys = set()  # Track keys we actually modified
    
    for lora_key in list(first_lora_state_dict.keys()):
        # Identify keys and weights based on naming pattern
        if ".lora_down.weight" in lora_key:
            prefix = lora_key.split(".lora_down.weight")[0]
            down_key = f"{prefix}.lora_down.weight"
            up_key = f"{prefix}.lora_up.weight"
            if up_key not in first_lora_state_dict:
                continue
            target_base_key = prefix
            a_weight_key = down_key
            b_weight_key = up_key
            
        elif ".lora_A.weight" in lora_key:
            prefix = lora_key.split(".lora_A.weight")[0]
            a_key = f"{prefix}.lora_A.weight"
            b_key = f"{prefix}.lora_B.weight"
            if b_key not in first_lora_state_dict:
                continue
            target_base_key = prefix
            a_weight_key = a_key
            b_weight_key = b_key
        else:
            continue

        # PASS 1: Only style layers
        is_style = any(style_layer in target_base_key for style_layer in STYLE_LAYERS)

        if not is_style:
            pass1_skipped.append(target_base_key)
            continue

        layer_strength = 0.85
                                
        if target_base_key in base_state_dict:
            try:
                W_base = base_state_dict[target_base_key].to(device=device, dtype=torch.bfloat16)
                A = first_lora_state_dict[a_weight_key].to(device=device, dtype=torch.bfloat16)
                B = first_lora_state_dict[b_weight_key].to(device=device, dtype=torch.bfloat16)
                
                rank = A.shape[0]
                alpha = 512
                scale = (alpha / rank) * layer_strength
                
                delta_W = torch.matmul(B, A) * scale
                
                if delta_W.shape != W_base.shape:
                    print(f"SHAPE FAIL: {target_base_key} {W_base.shape} {delta_W.shape}")
                    pass1_skipped.append(target_base_key)
                    continue
                
                base_state_dict[target_base_key] = (W_base + delta_W).cpu()
                pass1_baked += 1
                pass1_processed_keys.add(target_base_key)  # Mark as processed
                
            except Exception as e:
                print(f"Failed to bake layer {target_base_key}: {e}")
                pass1_skipped.append(target_base_key)
        else:
            pass1_skipped.append(target_base_key)

    print(f"\nPass 1 complete: {pass1_baked} baked, {len(pass1_skipped)} skipped")
    
    # 7. PASS 2: Apply Sulphur — ONLY to keys that were skipped in Pass 1
    print("\n" + "="*60)
    print("PASS 2: Sulphur — skipped keys only (audio 0.9, rest 0.9)")
    print("="*60)
    
    # Strict: only process keys that Pass 1 skipped
    eligible_set = set(pass1_skipped)
    
    pass2_baked = 0
    pass2_skipped = 0
    pass2_notfound = 0
    pass2_overlap_blocked = 0  # Track keys we blocked to prevent overlap

    for lora_key in list(second_lora_state_dict.keys()):
        # Identify keys and weights based on naming pattern
        if ".lora_down.weight" in lora_key:
            prefix = lora_key.split(".lora_down.weight")[0]
            down_key = f"{prefix}.lora_down.weight"
            up_key = f"{prefix}.lora_up.weight"
            if up_key not in second_lora_state_dict:
                continue
            target_base_key = prefix
            a_weight_key = down_key
            b_weight_key = up_key
            
        elif ".lora_A.weight" in lora_key:
            prefix = lora_key.split(".lora_A.weight")[0]
            a_key = f"{prefix}.lora_A.weight"
            b_key = f"{prefix}.lora_B.weight"
            if b_key not in second_lora_state_dict:
                continue
            target_base_key = prefix
            a_weight_key = a_key
            b_weight_key = b_key
        else:
            continue
        
        # STRICT: Skip if this key was already processed in Pass 1
        if target_base_key in pass1_processed_keys:
            pass2_overlap_blocked += 1
            continue
        
        # STRICT: Skip if this key was NOT in Pass 1's skip list
        if target_base_key not in eligible_set:
            pass2_skipped += 1
            continue
        
        # Determine strength: 0.9 for audio, 0.85 for everything else
        is_audio = any(audio_layer in target_base_key for audio_layer in AUDIO_PRESERVE_LAYERS)
        layer_strength = 0.85 if is_audio else 0
        
        if target_base_key in base_state_dict:
            try:
                W_base = base_state_dict[target_base_key].to(device=device, dtype=torch.bfloat16)
                A = second_lora_state_dict[a_weight_key].to(device=device, dtype=torch.bfloat16)
                B = second_lora_state_dict[b_weight_key].to(device=device, dtype=torch.bfloat16)
                
                rank = A.shape[0]
                alpha = 256
                scale = (alpha / rank) * layer_strength
                
                delta_W = torch.matmul(B, A) * scale
                
                if delta_W.shape != W_base.shape:
                    print(f"SHAPE FAIL: {target_base_key} {W_base.shape} {delta_W.shape}")
                    pass2_skipped += 1
                    continue
                
                base_state_dict[target_base_key] = (W_base + delta_W).cpu()
                pass2_baked += 1
                
            except Exception as e:
                print(f"Failed to bake layer {target_base_key}: {e}")
                pass2_skipped += 1
        else:
            print(f"Key not in base: {target_base_key}")
            pass2_notfound += 1

    print(f"\nPass 2 complete: {pass2_baked} baked, {pass2_skipped} skipped, {pass2_notfound} not in base, {pass2_overlap_blocked} overlap-blocked")

    # 8. Final verification
    print("\n" + "="*60)
    print("FINAL VERIFICATION")
    print("="*60)
    print(f"Pass 1 (10Eros style 0.85):   {pass1_baked} baked")
    print(f"Pass 2 (Sulphur 0.9):         {pass2_baked} baked")
    print(f"Total modified:               {pass1_baked + pass2_baked}")
    print(f"Still unprocessed:            {len(pass1_skipped) - pass2_baked}")
    print(f"Overlap blocked (safety):     {pass2_overlap_blocked}")
    
    if pass2_baked > len(pass1_skipped):
        print("\nERROR: Pass 2 baked more than were skipped! Overlap occurred.")
    elif pass2_baked < len(pass1_skipped):
        print(f"\nWARNING: {len(pass1_skipped) - pass2_baked} skipped keys were not found in second LoRA")
    
    # 9. Extract original header metadata
    try:
        with safe_open(vanilla_base_path, framework="pt", device="cpu") as f:
            original_metadata = f.metadata()
    except Exception as e:
        original_metadata = None
        print(f"Could not read metadata: {e}")
    
    # 10. Cleanup cache
    print("\nCleaning cache directory...")
    try:
        if os.path.exists("/tmp/hf_cache"):
            shutil.rmtree("/tmp/hf_cache")
    except Exception as e:
        pass
    
    # 11. Write out and upload
    from huggingface_hub import HfApi
    api = HfApi()
    
    output_path = "/tmp/LTX2.5_DISTILLED_COMBO_BAKED.safetensors"
    
    print(f"\nSaving to {output_path}...")
    if original_metadata:
        save_file(base_state_dict, output_path, metadata=original_metadata)
    else:
        save_file(base_state_dict, output_path)
    
    print(f"Uploading to {DEST_REPO}...")
    api.upload_file(
        path_or_fileobj=output_path,
        path_in_repo=OUTPUT_FILENAME,
        repo_id=DEST_REPO,
        token=HF_TOKEN,
    )
    print("Pipeline execution complete.")

if __name__ == "__main__":
    run_pipeline()



Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм

Нельзя запустить

Модели «картинка → видео» пока не запускаются.

Ревизия весов
f2e19b7

0 моделей