Spaces:
Runtime error
Runtime error
Upload folder using huggingface_hub
Browse filesFiles changed (10)
- README.md+18-14
- app.py+57-48
- minimax/apps/gradio/state.py+91-15
- minimax/apps/gradio/ui.py+57-17
- minimax/modeling/gguf_runtime.pyAdded+219
- minimax/modeling/loader.py+8-19
- minimax/paths.py+4-1
- minimax/scoring/__init__.py+1
- minimax/scoring/teacher_validate.pyAdded+107
- requirements.txt+5-10
7 unmodified lines8910111213141 unmodified line1617181920212215 unmodified lines3839404142434422 unmodified lines676869707172737475767778798081822 unmodified lines858687887 unmodified linesapp_file: app.pypinned: falselicense: othershort_description: Trained LLM for MiniMax H3 structured video promptstags:- text-generation- video1 unmodified line- minimax- liquid- lfm2- zerogpu---# MiniMax H3 Prompt Enhancer15 unmodified lines| Guesswork about “what sounds good” | Aligned to **MiniMax H3 video prompt writing guidelines** || One free-form paragraph | **Structured output** MiniMax can actually consume |Under the hood: [geocine/minimax-video-prompt-enhancer-350m](https://huggingface.co/geocine/minimax-video-prompt-enhancer-350m) — LoRA SFT on [LiquidAI/LFM2.5-350M](https://huggingface.co/LiquidAI/LFM2.5-350M), trained on teacher rewrites that follow the official MiniMax base/ref prompt schema (T2VA · I2VA · FL2VA · L2VA · full reference).---22 unmodified lines---## ZeroGPURuns on **Hugging Face ZeroGPU** — a GPU spins up only while **Generate** runs.- Visitors use **their** daily HF GPU quota (or PRO credits if they go over).- You must be **logged in** to use ZeroGPU Spaces.- No permanent GPU rental for idle time.---## Model & license| | |2 unmodified lines| Base | [LiquidAI/LFM2.5-350M](https://huggingface.co/LiquidAI/LFM2.5-350M) || License | Liquid **lfm1.0** — read the base card before commercial use |This is a **text prompt specialist**, not a video generator. It writes the brief; MiniMax (or your pipeline) makes the frames.7 unmodified lines8910111213141 unmodified line161718192021222315 unmodified lines394041424344454647484950515253545556575822 unmodified lines8182838485862 unmodified lines899091927 unmodified linesapp_file: app.pypinned: falselicense: othershort_description: MiniMax H3 video prompts via CPU GGUFtags:- text-generation- video1 unmodified line- minimax- liquid- lfm2- llama.cpp- cpu---# MiniMax H3 Prompt Enhancer15 unmodified lines| Guesswork about “what sounds good” | Aligned to **MiniMax H3 video prompt writing guidelines** || One free-form paragraph | **Structured output** MiniMax can actually consume |Under the hood: [geocine/minimax-video-prompt-enhancer-350m](https://huggingface.co/geocine/minimax-video-prompt-enhancer-350m) — LoRA SFT on [LiquidAI/LFM2.5-350M](https://huggingface.co/LiquidAI/LFM2.5-350M), served as **Q4_K_M GGUF** via **llama.cpp** on **CPU**.---## Runtime| | ||--|--|| Backend | **llama.cpp** (`llama-cpp-python`) || Quant | **Q4_K_M** (~219 MB) || Hardware | **CPU** — no ZeroGPU quota, no login required for inference || Typical latency | A few seconds for a short T2VA brief on free CPU |Weights are downloaded from the model repo at boot (or read from `models/` if present).---22 unmodified lines---## Model & license| | |2 unmodified lines| Base | [LiquidAI/LFM2.5-350M](https://huggingface.co/LiquidAI/LFM2.5-350M) || License | Liquid **lfm1.0** — read the base card before commercial use |This is a **text prompt specialist**, not a video generator. It writes the brief; MiniMax (or your pipeline) makes the frames.
123456789106 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071#!/usr/bin/env python3"""Hugging Face ZeroGPU Space — MiniMax Video Prompt Enhancer.Hosts on free ZeroGPU. Visitors spend *their* daily HF GPU quota / creditswhen they click Generate — the host is not billed for continuous GPU rental.Model: geocine/minimax-video-prompt-enhancer-350m"""from __future__ import annotations6 unmodified linesif str(ROOT) not in sys.path:sys.path.insert(0, str(ROOT))import spacesimport torchfrom minimax.apps.gradio import build_appfrom minimax.apps.gradio.state import InferenceSession, ModelBundlefrom minimax.modeling.loader import build_stop_ids, load_model_and_tokenizerfrom minimax.paths import DEFAULT_MODELMODEL_ID = os.environ.get("MODEL_ID", DEFAULT_MODEL)# ---------------------------------------------------------------------------# ZeroGPU: place the model on `cuda` at module level (emulated until a real# GPU is attached inside @spaces.GPU). Visitors pay quota on each Generate.# ---------------------------------------------------------------------------print(f"Loading {MODEL_ID} onto cuda (ZeroGPU)...", flush=True)_model, _tokenizer = load_model_and_tokenizer(MODEL_ID)_stop_ids = build_stop_ids(_tokenizer)_PRELOADED = ModelBundle(path=MODEL_ID, model=_model, tokenizer=_tokenizer, stop_ids=_stop_ids)print(f"Ready on device={next(_model.parameters()).device}", flush=True)_orig_ensure = InferenceSession.ensure_loaded_orig_generate = InferenceSession.generatedef _ensure_preloaded(self, model_path=None):path = str(model_path or self.default_model)if path in {MODEL_ID, DEFAULT_MODEL, "geocine/minimax-video-prompt-enhancer-350m"}:self._bundle = _PRELOADEDreturn _PRELOADEDreturn _orig_ensure(self, model_path)@spaces.GPU(duration=90)def _run_generate(session, kwargs):"""GPU-scoped body — real CUDA is available only here on ZeroGPU."""return _orig_generate(session, **kwargs)def _generate_zerogpu(self, **kwargs):return _run_generate(self, kwargs)InferenceSession.ensure_loaded = _ensure_preloaded # type: ignore[method-assign]InferenceSession.generate = _generate_zerogpu # type: ignore[method-assign]demo = build_app(model_path=MODEL_ID)if __name__ == "__main__":demo.queue(default_concurrency_limit=1)demo.launch()12345678910116 unmodified lines181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980#!/usr/bin/env python3"""Hugging Face Space — MiniMax Video Prompt Enhancer (CPU / GGUF).Serves the fine-tuned 350M model via llama.cpp on CPU. No ZeroGPU quota,no CUDA, no login required for inference.Model weights (Q4_K_M GGUF) are pulled from the Hub at boot unless a localfile is present under models/ or GGUF_PATH is set."""from __future__ import annotations6 unmodified linesif str(ROOT) not in sys.path:sys.path.insert(0, str(ROOT))from huggingface_hub import hf_hub_downloadfrom minimax.apps.gradio import build_appfrom minimax.modeling.gguf_runtime import effective_cpus, resolve_gguf_filefrom minimax.paths import DEFAULT_GGUF_FILE, DEFAULT_GGUF_REPOGGUF_REPO = os.environ.get("GGUF_REPO", DEFAULT_GGUF_REPO)GGUF_FILE = os.environ.get("GGUF_FILE", DEFAULT_GGUF_FILE)LOCAL_MODELS = ROOT / "models"N_THREADS = int(os.environ.get("N_THREADS", "0")) or NoneN_CTX = int(os.environ.get("N_CTX", "4096"))def resolve_model_path() -> str:env = os.environ.get("GGUF_PATH") or os.environ.get("MODEL_ID")if env and (Path(env).exists() or env.endswith(".gguf")):# Absolute/local path, or a bare filename we still try to resolve.p = Path(env)if p.exists():return str(resolve_gguf_file(p) if p.is_dir() else p)if env.endswith(".gguf") and (LOCAL_MODELS / env).is_file():return str(LOCAL_MODELS / env)if LOCAL_MODELS.is_dir() and list(LOCAL_MODELS.glob("*.gguf")):path = str(resolve_gguf_file(LOCAL_MODELS))print(f"[boot] using local GGUF {path}", flush=True)return pathprint(f"[boot] downloading {GGUF_REPO}/{GGUF_FILE} …", flush=True)return hf_hub_download(repo_id=GGUF_REPO, filename=GGUF_FILE)MODEL_PATH = resolve_model_path()print(f"[boot] GGUF={MODEL_PATH} cpus={effective_cpus()} "f"n_threads={N_THREADS or 'auto'} n_ctx={N_CTX}",flush=True,)demo = build_app(model_path=MODEL_PATH,backend="gguf",n_ctx=N_CTX,n_threads=N_THREADS,n_gpu_layers=0,prefer_cpu=True,)# Eager-load so the first visitor is not hit with cold-start download+load only._session = demo._minimax_session # type: ignore[attr-defined]_loaded = _session.ensure_loaded()print(f"[boot] ready path={getattr(_loaded, 'path', MODEL_PATH)} "f"n_threads={getattr(_loaded, 'n_threads', '?')}",flush=True,)if __name__ == "__main__":demo.queue(default_concurrency_limit=1)demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
3 unmodified lines456789101112131485 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312412514 unmodified lines1401411421431441451461471481491501511521531541551561571581591601611623 unmodified linesfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Anyfrom minimax.modeling.generate import generate_onefrom minimax.modeling.loader import build_stop_ids, load_model_and_tokenizerfrom minimax.paths import CHAMPION_DIR, DEFAULT_MODELdef parse_assets(assets_text: str | None) -> list[str] | None:85 unmodified linesmodel: Anytokenizer: Anystop_ids: list[int]class InferenceSession:"""Holds one loaded model; reloads when the path changes."""def __init__(self, default_model: str | Path | None = None) -> None:self.default_model = str(default_model or CHAMPION_DIR)self._bundle: ModelBundle | None = None@propertydef loaded_path(self) -> str | None:return None if self._bundle is None else self._bundle.pathdef ensure_loaded(self, model_path: str | None = None) -> ModelBundle:path = str(model_path or self.default_model)if self._bundle is not None and self._bundle.path == path:return self._bundlemodel, tokenizer = load_model_and_tokenizer(path)stop_ids = build_stop_ids(tokenizer)self._bundle = ModelBundle(path=path, model=model, tokenizer=tokenizer, stop_ids=stop_ids)return self._bundledef generate(14 unmodified linesif not (prompt or "").strip():return "", "Enter a user prompt first."import torchbundle = self.ensure_loaded(model_path)if seed is not None:torch.manual_seed(int(seed))if torch.cuda.is_available():torch.cuda.manual_seed_all(int(seed))text, report = generate_one(bundle.model,bundle.tokenizer,task=task,duration=float(duration),prompt=prompt.strip(),assets=parse_assets(assets_text),stop_ids=bundle.stop_ids,max_new_tokens=max_new_tokens if max_new_tokens and max_new_tokens > 0 else None,temperature=float(temperature),top_k=int(top_k),repetition_penalty=float(repetition_penalty),3 unmodified lines456789101112131415161718192021222385 unmodified lines10911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118214 unmodified lines1971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372383 unmodified linesfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Literalfrom minimax.modeling.generate import generate_onefrom minimax.modeling.gguf_runtime import (GgufBundle,generate_one_gguf,is_gguf_path,load_gguf,resolve_gguf_file,)from minimax.modeling.loader import build_stop_ids, load_model_and_tokenizerfrom minimax.paths import CHAMPION_DIRBackend = Literal["auto", "transformers", "gguf"]def parse_assets(assets_text: str | None) -> list[str] | None:85 unmodified linesmodel: Anytokenizer: Anystop_ids: list[int]backend: str = "transformers"class InferenceSession:"""Holds one loaded model; reloads when the path changes.backend:- auto: use GGUF when the path points at a .gguf (or a dir of them)- gguf: force llama.cpp- transformers: force HF/PyTorch (GPU or CPU)"""def __init__(self,default_model: str | Path | None = None,*,backend: Backend = "auto",n_ctx: int = 4096,n_threads: int | None = None,n_gpu_layers: int = 0,prefer_cpu: bool = False,) -> None:self.default_model = str(default_model or CHAMPION_DIR)self.backend: Backend = backendself.n_ctx = n_ctxself.n_threads = n_threadsself.n_gpu_layers = n_gpu_layersself.prefer_cpu = prefer_cpuself._bundle: ModelBundle | None = Noneself._gguf: GgufBundle | None = None@propertydef loaded_path(self) -> str | None:if self._gguf is not None:return self._gguf.pathreturn None if self._bundle is None else self._bundle.pathdef _pick_backend(self, path: str) -> str:if self.backend == "gguf":return "gguf"if self.backend == "transformers":return "transformers"return "gguf" if is_gguf_path(path) else "transformers"def ensure_loaded(self, model_path: str | None = None) -> ModelBundle | GgufBundle:path = str(Path(model_path or self.default_model))kind = self._pick_backend(path)if kind == "gguf":gguf_path = str(resolve_gguf_file(path))if self._gguf is not None and self._gguf.path == gguf_path:return self._ggufself._bundle = Noneself._gguf = load_gguf(gguf_path,n_ctx=self.n_ctx,n_threads=self.n_threads,n_gpu_layers=self.n_gpu_layers,)return self._ggufif self._bundle is not None and self._bundle.path == path:return self._bundleself._gguf = Nonemodel, tokenizer = load_model_and_tokenizer(path, prefer_cpu=self.prefer_cpu)stop_ids = build_stop_ids(tokenizer)self._bundle = ModelBundle(path=path, model=model, tokenizer=tokenizer, stop_ids=stop_ids, backend="transformers")return self._bundledef generate(14 unmodified linesif not (prompt or "").strip():return "", "Enter a user prompt first."loaded = self.ensure_loaded(model_path)assets = parse_assets(assets_text)mnt = max_new_tokens if max_new_tokens and max_new_tokens > 0 else Noneif isinstance(loaded, GgufBundle):text, report = generate_one_gguf(loaded,task=task,duration=float(duration),prompt=prompt.strip(),assets=assets,max_new_tokens=mnt,temperature=float(temperature),top_k=int(top_k),repetition_penalty=float(repetition_penalty),seed=seed,legacy_labels=bool(legacy_labels),)return text, format_checks(report)import torchif seed is not None:torch.manual_seed(int(seed))if torch.cuda.is_available() and not self.prefer_cpu:torch.cuda.manual_seed_all(int(seed))text, report = generate_one(loaded.model,loaded.tokenizer,task=task,duration=float(duration),prompt=prompt.strip(),assets=assets,stop_ids=loaded.stop_ids,max_new_tokens=mnt,temperature=float(temperature),top_k=int(top_k),repetition_penalty=float(repetition_penalty),
322 unmodified lines323324325326327328329330331332221 unmodified lines554555556557558559560561562563564565566567568569570571572573574575576577578579580581322 unmodified lines"""def build_app(*, model_path: str | Path | None = None):import gradio as grsession = InferenceSession(default_model=model_path or CHAMPION_DIR)default_model = str(session.default_model)theme = gr.themes.Base(221 unmodified linesport: int = 7860,share: bool = False,require_gpu: bool = True,):import torchif require_gpu and not torch.cuda.is_available():raise SystemExit("CUDA is not available — refusing to launch Gradio on CPU. ""Use the minimax-lfm env with a GPU, or pass require_gpu=False.")if torch.cuda.is_available():print(f"GPU: {torch.cuda.get_device_name(0)} (cuda:{torch.cuda.current_device()})",flush=True,)else:print("GPU: none (CPU)", flush=True)demo = build_app(model_path=model_path)session: InferenceSession = demo._minimax_session # type: ignore[attr-defined]bundle = session.ensure_loaded()device = next(bundle.model.parameters()).deviceprint(f"Model loaded: {bundle.path} device={device}", flush=True)if require_gpu and device.type != "cuda":raise SystemExit(f"Model landed on {device}, expected CUDA.")demo.launch(server_name=host, server_port=port, share=share)322 unmodified lines323324325326327328329330331332333334335336337338339340341342343344345346347221 unmodified lines569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621322 unmodified lines"""def build_app(*,model_path: str | Path | None = None,backend: str = "auto",n_ctx: int = 4096,n_threads: int | None = None,n_gpu_layers: int = 0,prefer_cpu: bool = False,):import gradio as grsession = InferenceSession(default_model=model_path or CHAMPION_DIR,backend=backend, # type: ignore[arg-type]n_ctx=n_ctx,n_threads=n_threads,n_gpu_layers=n_gpu_layers,prefer_cpu=prefer_cpu,)default_model = str(session.default_model)theme = gr.themes.Base(221 unmodified linesport: int = 7860,share: bool = False,require_gpu: bool = True,backend: str = "auto",n_ctx: int = 4096,n_threads: int | None = None,n_gpu_layers: int = 0,prefer_cpu: bool = False,):from minimax.modeling.gguf_runtime import GgufBundle, is_gguf_path# GGUF / explicit CPU path never requires CUDA.path = str(model_path or CHAMPION_DIR)if backend == "gguf" or is_gguf_path(path) or prefer_cpu:require_gpu = Falseif require_gpu:import torchif not torch.cuda.is_available():raise SystemExit("CUDA is not available — refusing to launch Gradio on CPU. ""Use a GGUF model, pass --backend gguf, or --cpu / require_gpu=False.")print(f"GPU: {torch.cuda.get_device_name(0)} (cuda:{torch.cuda.current_device()})",flush=True,)else:print("Device: CPU (GGUF/llama.cpp or transformers CPU)", flush=True)demo = build_app(model_path=model_path,backend=backend,n_ctx=n_ctx,n_threads=n_threads,n_gpu_layers=n_gpu_layers,prefer_cpu=prefer_cpu or not require_gpu,)session: InferenceSession = demo._minimax_session # type: ignore[attr-defined]loaded = session.ensure_loaded()if isinstance(loaded, GgufBundle):print(f"Model loaded: {loaded.path} backend=gguf n_threads={loaded.n_threads}",flush=True,)else:device = next(loaded.model.parameters()).deviceprint(f"Model loaded: {loaded.path} backend=transformers device={device}", flush=True)if require_gpu and device.type != "cuda":raise SystemExit(f"Model landed on {device}, expected CUDA.")demo.launch(server_name=host, server_port=port, share=share)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219"""CPU-first GGUF inference via llama-cpp-python.
Mirrors generate_one() postprocess/scoring, but decodes with llama.cpp insteadof transformers — the path we want for free HF Spaces / local no-GPU demos."""
from __future__ import annotations
import osfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any
from ..formatting.envelope import build_user_message, load_systemfrom ..formatting.postprocess import postprocess_generationfrom ..scoring.format_score import default_max_new_tokens, score_format
def effective_cpus() -> int: """Cores available to this process (cgroup-aware, like prompt-routing).""" try: # cgroup v2 raw = open("/sys/fs/cgroup/cpu.max", encoding="utf-8").read().split() if raw and raw[0] != "max": return max(1, round(int(raw[0]) / int(raw[1]))) except (OSError, ValueError): pass try: # cgroup v1 q = int(open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us", encoding="utf-8").read()) p = int(open("/sys/fs/cgroup/cpu/cpu.cfs_period_us", encoding="utf-8").read()) if q > 0: return max(1, q // p) except (OSError, ValueError): pass try: return max(1, len(os.sched_getaffinity(0))) # type: ignore[attr-defined] except AttributeError: return max(1, os.cpu_count() or 1)
def is_gguf_path(path: str | Path) -> bool: p = Path(path) if p.is_file() and p.suffix.lower() == ".gguf": return True if p.is_dir(): return any(p.glob("*.gguf")) return False
def resolve_gguf_file(path: str | Path) -> Path: """Pick a concrete .gguf file from a path or directory.""" p = Path(path) if p.is_file() and p.suffix.lower() == ".gguf": return p if p.is_dir(): # Prefer smaller/faster quants for CPU Spaces when several are present. preferred = ( "Q4_K_M", "Q4_K_S", "Q4_0", "Q5_K_M", "Q5_0", "Q6_K", "Q8_0", "F16", "BF16", "F32", ) files = list(p.glob("*.gguf")) if not files: raise FileNotFoundError(f"No .gguf files in {p}") lower = {f.name.upper(): f for f in files} for tag in preferred: for name, f in lower.items(): if tag in name: return f return sorted(files, key=lambda f: f.stat().st_size)[0] raise FileNotFoundError(f"GGUF path not found: {p}")
@dataclassclass GgufBundle: path: str llm: Any # llama_cpp.Llama n_threads: int
def _sanitize_hf_chat_template(template: str) -> str: """Strip HuggingFace-only Jinja tags that plain jinja2 cannot parse.""" for tag in ( "{%- generation -%}", "{% generation %}", "{%- endgeneration -%}", "{% endgeneration %}", ): template = template.replace(tag, "") return template
def _install_chat_template_sanitizer() -> None: """llama-cpp registers the GGUF-embedded chat template at load time.
LFM2.5's template uses HF ``{% generation %}`` blocks; strip them so load succeeds. We still format prompts ourselves with ChatML below. """ from llama_cpp import llama_chat_format
if getattr(llama_chat_format.Jinja2ChatFormatter, "_minimax_sanitized", False): return orig_init = llama_chat_format.Jinja2ChatFormatter.__init__
def _init(self, template, *args, **kwargs): # type: ignore[no-untyped-def] if isinstance(template, str): template = _sanitize_hf_chat_template(template) return orig_init(self, template, *args, **kwargs)
llama_chat_format.Jinja2ChatFormatter.__init__ = _init # type: ignore[method-assign] llama_chat_format.Jinja2ChatFormatter._minimax_sanitized = True # type: ignore[attr-defined]
def _format_chatml(messages: list[dict[str, str]], *, add_generation_prompt: bool = True) -> str: """LFM2.5 ChatML — BOS is added by llama.cpp when add_bos is enabled in the GGUF.""" parts: list[str] = [] for m in messages: role = m["role"] content = m.get("content") or "" parts.append(f"<|im_start|>{role}\n{content}<|im_end|>\n") if add_generation_prompt: parts.append("<|im_start|>assistant\n") return "".join(parts)
def load_gguf( model: str | Path, *, n_ctx: int = 4096, n_threads: int | None = None, n_gpu_layers: int = 0, verbose: bool = False,) -> GgufBundle: from llama_cpp import Llama
_install_chat_template_sanitizer()
gguf = resolve_gguf_file(model) threads = int(n_threads) if n_threads and n_threads > 0 else effective_cpus() # Leave one core for the web UI when we have headroom. if threads >= 4: threads = max(1, threads - 1)
print( f"[gguf] loading {gguf.name} n_threads={threads} n_ctx={n_ctx} " f"n_gpu_layers={n_gpu_layers}", flush=True, ) llm = Llama( model_path=str(gguf), n_ctx=n_ctx, n_threads=threads, n_threads_batch=threads, n_gpu_layers=n_gpu_layers, verbose=verbose, logits_all=False, embedding=False, chat_format="chatml", ) return GgufBundle(path=str(gguf), llm=llm, n_threads=threads)
def generate_one_gguf( bundle: GgufBundle, *, task: str, duration: float, prompt: str, assets: list[str] | None, max_new_tokens: int | None = None, temperature: float = 0.0, top_k: int = 40, repetition_penalty: float = 1.0, seed: int | None = 42, legacy_labels: bool = False,) -> tuple[str, dict]: messages = [ {"role": "system", "content": load_system(task)}, { "role": "user", "content": build_user_message(task, duration, prompt, assets, legacy=legacy_labels), }, ] mnt = max_new_tokens if max_new_tokens is not None else default_max_new_tokens(task) prompt_text = _format_chatml(messages, add_generation_prompt=True)
# llama.cpp temperature=0 is greedy. temp = float(temperature) do_sample = temp > 0 kwargs: dict[str, Any] = { "prompt": prompt_text, "max_tokens": int(mnt), "temperature": temp if do_sample else 0.0, "repeat_penalty": float(repetition_penalty), "stop": ["<|im_end|>", "<|endoftext|>"], } if do_sample and top_k and top_k > 0: kwargs["top_k"] = int(top_k) if seed is not None: kwargs["seed"] = int(seed)
out = bundle.llm.create_completion(**kwargs) raw = (out["choices"][0]["text"] or "").strip() raw = raw.replace("<|im_end|>", "").replace("<|endoftext|>", "").strip() text = postprocess_generation(raw, task, duration) report = score_format(text, task) report["raw_char_len"] = len(raw) report["max_new_tokens"] = mnt usage = out.get("usage") or {} if usage: report["completion_tokens"] = usage.get("completion_tokens") report["prompt_tokens"] = usage.get("prompt_tokens") return text, report123415 unmodified lines20212223242526272829303132333435363738394041424344454647484950515253"""Model/tokenizer loading — ZeroGPU-friendly (place on cuda at load time)."""from __future__ import annotations15 unmodified linesreturn str(model), Nonedef load_model_and_tokenizer(model: str | Path):"""Load weights onto CUDA.ZeroGPU emulates CUDA at import/startup so ``.to("cuda")`` is required atthe root level; a real GPU is only attached inside ``@spaces.GPU`` calls."""import torchfrom transformers import AutoModelForCausalLM, AutoTokenizermodel_path, adapter_path = resolve_model_dir(model)tokenizer = AutoTokenizer.from_pretrained(adapter_path or model_path, trust_remote_code=True)# bf16 on GPU; ZeroGPU always exposes a cuda device (real or emulated).dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32lm = AutoModelForCausalLM.from_pretrained(model_path,trust_remote_code=True,torch_dtype=dtype,low_cpu_mem_usage=True,)if adapter_path:from peft import PeftModellm = PeftModel.from_pretrained(lm, adapter_path).merge_and_unload()# ZeroGPU docs: place models on cuda at root, not lazily inside @spaces.GPUif torch.cuda.is_available():lm = lm.to("cuda")lm.eval()return lm, tokenizer123415 unmodified lines2021222324252627282930313233343536373839404142"""Model/tokenizer loading and stop-token resolution."""from __future__ import annotations15 unmodified linesreturn str(model), Nonedef load_model_and_tokenizer(model: str | Path, *, prefer_cpu: bool = False):"""Load HF causal LM. Set prefer_cpu=True to force CPU float32 (no CUDA map)."""import torchfrom transformers import AutoModelForCausalLM, AutoTokenizermodel_path, adapter_path = resolve_model_dir(model)tokenizer = AutoTokenizer.from_pretrained(adapter_path or model_path, trust_remote_code=True)use_cuda = torch.cuda.is_available() and not prefer_cpudtype = torch.bfloat16 if use_cuda else torch.float32device_map = "auto" if use_cuda else "cpu"lm = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True, device_map=device_map, torch_dtype=dtype)if adapter_path:from peft import PeftModellm = PeftModel.from_pretrained(lm, adapter_path).merge_and_unload()lm.eval()return lm, tokenizer
16 unmodified lines171819202122232416 unmodified lines"L2VA": PROMPTS / "system_base_l2va.txt",}# Default Hub model for this SpaceDEFAULT_MODEL = "geocine/minimax-video-prompt-enhancer-350m"BASE_MODEL = "LiquidAI/LFM2.5-350M"# Alias used by local app codeCHAMPION_DIR = DEFAULT_MODEL16 unmodified lines171819202122232425262716 unmodified lines"L2VA": PROMPTS / "system_base_l2va.txt",}# Default Hub ids for this SpaceDEFAULT_MODEL = "geocine/minimax-video-prompt-enhancer-350m"DEFAULT_GGUF_REPO = "geocine/minimax-video-prompt-enhancer-350m"DEFAULT_GGUF_FILE = "minimax-video-prompt-enhancer-350m-Q4_K_M.gguf"BASE_MODEL = "LiquidAI/LFM2.5-350M"# Alias used by local app codeCHAMPION_DIR = DEFAULT_MODELGGUF_DIR = ROOT / "models"
5 unmodified lines6785 unmodified linesnormalize_task,score_format,)5 unmodified lines67895 unmodified linesnormalize_task,score_format,)from .teacher_validate import validate_record # noqa: F401
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107"""Structural validation for teacher SFT records (base + full-ref).
Stricter than :mod:`format_score` (which scores model generations): teachergold must additionally keep retention lines for every defined label andbalanced dialogue tags. A gold row that fails here must be fixed by theteacher, never auto-repaired from templates."""
from __future__ import annotations
import re
from ..formatting.instructions import is_canonical_instructionfrom ..formatting.meta_leak import has_instruction_leakfrom ..formatting.ref_repair import BARE_RET_LINE
BASE_FIELDS = [ "integrated_multimodal_description:", "overall_soundscape:", "non_diegetic_music:",]REF_FIELDS = [ "subject_definitions:", "summary:", "retention_analysis:", "detailed_description:", "overall_soundscape:", "non_diegetic_music:",]
def validate_record(rec: dict) -> list[str]: errs: list[str] = [] msgs = rec.get("messages") or [] if len(msgs) != 3: return ["messages must be [system, user, assistant]"] for i, role in enumerate(("system", "user", "assistant")): if msgs[i].get("role") != role: errs.append(f"messages[{i}] role should be {role}") if not (msgs[i].get("content") or "").strip(): errs.append(f"messages[{i}] empty content")
out = msgs[2]["content"] if len(msgs) > 2 else "" mode = rec.get("mode") task = rec.get("task") or ""
if mode == "base": positions = [] for f in BASE_FIELDS: p = out.find(f) if p < 0: errs.append(f"missing {f}") else: positions.append(p) if len(positions) == len(BASE_FIELDS) and positions != sorted(positions): errs.append("base fields out of order") if task in {"I2VA", "FL2VA", "L2VA"}: first_line = out.strip().split("\n", 1)[0].strip() if not is_canonical_instruction(task, first_line): errs.append( f"{task} alignment instruction is not the canonical guide line" ) if "[Shot 1]" not in out: errs.append("missing [Shot 1]") elif mode == "ref": positions = [] for f in REF_FIELDS: p = out.find(f) if p < 0: errs.append(f"missing {f}") else: positions.append(p) if len(positions) == len(REF_FIELDS) and positions != sorted(positions): errs.append("ref fields out of order") if "summary:" in out: sum_part = out.split("summary:", 1)[1].split("retention_analysis:", 1)[0] if not re.search(r"\[[^\]]+\]", sum_part): errs.append("summary missing [task type] prefix") if "[Shot 1]" not in out: errs.append("missing [Shot 1]") if all(f in out for f in ("subject_definitions:", "summary:", "retention_analysis:")): def_block = out.split("subject_definitions:", 1)[1].split("summary:", 1)[0] ret_block = out.split("retention_analysis:", 1)[1].split( "detailed_description:", 1 )[0] for line in def_block.splitlines(): m = re.match(r"<(Subject|Picture|Video|Audio) \d+>", line.strip()) if m: lab = m.group(0) if not any(rl.strip().startswith(lab) for rl in ret_block.splitlines()): errs.append(f"retention missing line for {lab}") for rl in ret_block.splitlines(): if BARE_RET_LINE.match(rl.strip()): errs.append( f"bare retention line (needs ': marker - explanation'): {rl.strip()}" ) else: errs.append("mode must be base or ref")
if out.count("<d>") != out.count("</d>"): errs.append("unbalanced <d> tags") if "[Shot 2]" in out and not re.search(r"At \d{2}:\d{2}\.\d{3}", out): errs.append("multi-shot missing At MM:SS.mmm timestamp") if has_instruction_leak(out): errs.append("instruction/rule language leaked into assistant body")
return errs12345678910# Hugging Face ZeroGPU Space — MiniMax Video Prompt Enhancer# ZeroGPU supports Gradio 4+ and recent PyTorch (see HF ZeroGPU docs).gradio>=4.44.0spaces>=0.30.0torch>=2.1.0transformers>=4.45.0accelerate>=0.33.0safetensors>=0.4.0sentencepiece>=0.2.0protobuf>=4.25.012345# CPU Space — llama.cpp GGUF (no torch / no ZeroGPU)gradio>=4.44.0,<6huggingface_hub>=0.26.0# Prebuilt manylinux wheels on HF Spaces; no CUDA compile needed.llama-cpp-python>=0.3.0
README.md+18-14
app.py+57-48
minimax/apps/gradio/state.py+91-15
minimax/apps/gradio/ui.py+57-17
minimax/modeling/gguf_runtime.pyAdded+219
minimax/modeling/loader.py+8-19
minimax/paths.py+4-1
minimax/scoring/__init__.py+1
minimax/scoring/teacher_validate.pyAdded+107
requirements.txt+5-10