PEFT
Safetensors
MiniMax H3
English
lora
prompt-rewriting
text-to-audio-video
audio-video-generation
Run this model with HF Jobs
Run Momoking/MiniMax-H3-Prompt-Rewriter-LoRA on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Momoking/MiniMax-H3-Prompt-Rewriter-LoRA. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Momoking/MiniMax-H3-Prompt-Rewriter-LoRA on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Momoking/MiniMax-H3-Prompt-Rewriter-LoRA with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use Momoking/MiniMax-H3-Prompt-Rewriter-LoRA with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3.6-27B") model = PeftModel.from_pretrained(base_model, "Momoking/MiniMax-H3-Prompt-Rewriter-LoRA") - Notebooks
- Google Colab
- Kaggle
Duplicate from lightx2v/MiniMax-H3-Prompt-Rewriter-LoRA
Browse filesCo-authored-by: Lightx2v <lightx2v@users.noreply.huggingface.co>
Files changed (7)
- .gitattributesAdded+35
- README.mdAdded+283
- adapter_config.jsonAdded+55
- adapter_model.safetensorsAdded+3
- infer.pyAdded+143
- prompt_template.pyAdded+40
- requirements.txtAdded+5
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283---base_model: Qwen/Qwen3.6-27Blibrary_name: pefttags: - peft - lora - prompt-rewriting - minimax-h3 - text-to-audio-video - audio-video-generationlanguage: - en---
# MiniMax-H3 T2VA Prompt Rewriter LoRA
[](https://github.com/ModelTC/LightX2V)[](https://github.com/ModelTC/LightX2V)[](https://huggingface.co/MiniMaxAI/MiniMax-H3)
An open, local prompt rewriter for **text-to-audio-video (T2VA)** generation with[MiniMax-H3](https://huggingface.co/MiniMaxAI/MiniMax-H3), fine-tuned as a LoRAadapter on top of [Qwen3.6-27B](https://huggingface.co/Qwen/Qwen3.6-27B).
> **Generate the final audio-video with> [LightX2V](https://github.com/ModelTC/LightX2V).** LightX2V provides optimized local> MiniMax-H3 inference, including T2AV and other H3 tasks, memory offloading, tensor and> sequence parallelism, quantized checkpoints, optimized attention/RMSNorm/RoPE kernels,> and feature caching. If this project is useful, please consider giving> **[ModelTC/LightX2V](https://github.com/ModelTC/LightX2V) a star**.
The complete local workflow is:
```textShort prompt ──► this Prompt Rewriter LoRA ──► structured H3 prompt │Official MiniMax-H3 weights ──► LightX2V inference ◄─────┘ │ ▼ synchronized video + audio```
The [official MiniMax-H3 repository](https://huggingface.co/MiniMaxAI/MiniMax-H3)provides the upstream model weights. **LightX2V is the recommended inference entrypoint for the workflow documented here.**
## What it does
The adapter turns a short prompt plus the requested aspect ratio and duration into astructured audio-video description:
```textOriginal prompt + aspect ratio + duration │ ▼ Qwen3.6-27B + this LoRA │ ▼integrated_multimodal_description: [Shot 1] ...overall_soundscape: ...non_diegetic_music: ...```
The rewritten prompt expands shot structure, timing, composition, camera motion,physical action, continuity, synchronized diegetic sound, and non-diegetic music whilepreserving the original intent.
| Component | Purpose | Model ||---|---|---|| Inference framework | Runs MiniMax-H3 locally and generates the final synchronized video and audio | **[ModelTC/LightX2V](https://github.com/ModelTC/LightX2V)** || Generator weights | Upstream MiniMax-H3 model weights consumed by LightX2V | [MiniMaxAI/MiniMax-H3](https://huggingface.co/MiniMaxAI/MiniMax-H3) || Base language model | General instruction-following backbone | [Qwen3.6-27B](https://huggingface.co/Qwen/Qwen3.6-27B) || LoRA adapter | H3-oriented T2VA prompt rewriting | [lightx2v/MiniMax-H3-Prompt-Rewriter-LoRA](https://huggingface.co/lightx2v/MiniMax-H3-Prompt-Rewriter-LoRA) |
## Status and roadmap
- [x] T2VA prompt rewriting- [ ] First/last-frame-to-audio-video (FL2VA) prompt rewriting- [ ] Reference-to-audio-video (Ref2VA) prompt rewriting
## Installation
Clone this repository and install the inference dependencies:
```bashgit clone https://huggingface.co/lightx2v/MiniMax-H3-Prompt-Rewriter-LoRAcd MiniMax-H3-Prompt-Rewriter-LoRApip install -r requirements.txt```
The 27B base model is not included in this adapter repository and will be downloadedfrom Hugging Face on first use. Ensure that the machine has enough GPU/CPU memory forQwen3.6-27B. `device_map="auto"` is used to distribute the model over available devices.
## Rewrite one prompt
```bashpython infer.py \ --prompt "Epic space-opera teaser: a captain watches the last fleet jump away, leaving her alone." \ --duration 10 \ --resolution 16:9 \ --greedy```
Local paths are supported as well:
```bashpython infer.py \ --base-model /path/to/Qwen3.6-27B \ --adapter /path/to/MiniMax-H3-Prompt-Rewriter-LoRA \ --prompt "A red fox walks through a snowy forest at dawn." \ --duration 15 \ --resolution 21:9 \ --output rewritten_prompt.json```
Use `--output result.txt` for plain text or a `.json` path for a record containingthe original prompt, conditions, model IDs, and rewritten prompt.
To run the base-model baseline without the LoRA:
```bashpython infer.py \ --base-only \ --prompt "A red fox walks through a snowy forest at dawn." \ --duration 15 \ --resolution 21:9 \ --greedy```
For fair comparisons, use the same decoding mode and seed for every rewriter. Greedydecoding is the simplest deterministic setting; sampling is enabled when `--greedy`is omitted.
## Generate audio-video with LightX2V
### 1. Install LightX2V
Building from source gives access to the latest MiniMax-H3 integration:
```bashgit clone https://github.com/ModelTC/LightX2V.gitcd LightX2Vuv pip install -v . # or: pip install -v .```
Follow the [LightX2V Quick Start](https://lightx2v-en.readthedocs.io/en/latest/getting_started/quickstart.html)to install the optional optimized attention and quantization operators required by theselected configuration.
### 2. Download the MiniMax-H3 weights
The generator weights come from the upstream[MiniMaxAI/MiniMax-H3](https://huggingface.co/MiniMaxAI/MiniMax-H3) repository:
```bashhf download MiniMaxAI/MiniMax-H3 --local-dir /path/to/MiniMax-H3```
The LoRA in this repository rewrites text; it does not replace or include theMiniMax-H3 generator weights.
### 3. Rewrite the prompt
Run this command from the prompt-rewriter repository:
```bashpython infer.py \ --prompt "A red fox walks through a snowy forest at dawn." \ --duration 15 \ --resolution 16:9 \ --greedy \ --output /tmp/h3_rewritten_prompt.txt```
### 4. Generate synchronized video and audio
Run the rewritten prompt with LightX2V from the `LightX2V` repository root:
```bashsource scripts/base/base.shexport DTYPE=BF16export SENSITIVE_LAYER_DTYPE=FP32
python -m lightx2v.infer \ --model_cls minimax_h3 \ --task t2av \ --model_path /path/to/MiniMax-H3 \ --config_json configs/minimax_h3/minimax_h3_t2av.json \ --prompt "$(</tmp/h3_rewritten_prompt.txt)" \ --save_result_path save_results/minimax_h3_t2av.mp4 \ --seed 42```
The output MP4 contains both video and synchronized stereo audio. Make sure that theduration and aspect ratio in the LightX2V config match the conditions passed to theprompt rewriter. Ready-to-run single-GPU, block-offload, tensor-parallel, and combinedTP+SP examples are available in the**[LightX2V MiniMax-H3 scripts](https://github.com/ModelTC/LightX2V/tree/main/scripts/minimax_h3)**.
For lower-memory or multi-GPU inference, start from one of these configurations:
| Mode | LightX2V example ||---|---|| Single GPU | `configs/minimax_h3/minimax_h3_t2av.json` || Block offload | `configs/minimax_h3/minimax_h3_t2av_block_offload.json` || Sequence parallelism | `configs/minimax_h3/minimax_h3_t2av_sp.json` || Tensor parallelism | `configs/minimax_h3/minimax_h3_t2av_tp.json` || Tensor + sequence parallelism | `configs/minimax_h3/minimax_h3_t2av_tp_sp.json` |
## Qualitative comparison
The following gallery is designed to compare videos generated through[LightX2V](https://github.com/ModelTC/LightX2V) with the same MiniMax-H3 checkpoint andidentical inference settings. Only the prompt-rewriting method should differ.
| Label | Meaning ||---|---|| Original Prompt (No Rewrite) | The raw user prompt is sent directly to MiniMax-H3 || MiniMax Context-IR | The raw prompt is enhanced by the official hosted Context-IR workflow || Qwen3.6-27B Base Rewriter | The same template is used with the base model and no LoRA || **H3-T2VA Context Rewriter LoRA (Ours)** | Qwen3.6-27B with this task-specific LoRA |
### Prompt 1
> **Original prompt:** Epic space-opera theatrical teaser: a female captain stands alone before a massive observation window as the last fleet gathers and jumps away in a blinding flash, the bridge shaking, leaving her behind.
| Original Prompt (No Rewrite) | MiniMax Context-IR | Qwen3.6-27B Base Rewriter | **H3-T2VA Context Rewriter LoRA (Ours)** ||---|---|---|---|| <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/_gF8xSGc7-Z-3Ggsyk6w9.mp4"></video> | <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/haF7Ay70aadZkKfq-at2i.mp4"></video> | <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/Ztp7sdxWxMHLy3Sda6bjT.mp4"></video> | <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/2pFOcxgj_WjvsnRMUcVWO.mp4"></video> |
### Prompt 2
> **Original prompt:** A dynamic TV promo-style video showcasing a group of politicians at a nighttime event illuminated by vibrant neon lights. The politicians, dressed in formal attire, engage in conversations, shake hands, and exchange smiles as they navigate through a bustling room filled with guests. The scene is set in a modern, urban environment with a mix of soft ambient lighting and bright neon signs. The camera alternates between close-ups of expressive faces and wider shots capturing the energetic atmosphere. The visuals include fast-paced cuts and subtle zoom-ins to highlight key interactions and facial expressions, emphasizing the excitement and importance of the political networking event.
| Original Prompt (No Rewrite) | MiniMax Context-IR | Qwen3.6-27B Base Rewriter | **H3-T2VA Context Rewriter LoRA (Ours)** ||---|---|---|---|| <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/9F0i0ZwRT8sST-weN0L_q.mp4"></video> | <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/_QevAfxiAf8_-fuwRibKX.mp4"></video> | <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/xmdrQXfSwNyORY6bkMAZ7.mp4"></video> | <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/fEhON5N5rM6JBLNqcAs1G.mp4"></video> |
### Prompt 3
> **Original prompt:** ASMR video featuring a close-up shot of a young woman's hands. The girl has long, neatly manicured nails and soft, smooth skin. She moves her hands gracefully in front of the camera, focusing on gentle hand movements such as tapping, sliding, and fluttering. The lighting is warm and soft, casting a gentle glow on her hands. The camera remains static but maintains a close-up focus on her hands throughout the sequence. The background is blurred to keep the viewer's attention on the hands. The movements are slow and deliberate, creating a soothing and relaxing atmosphere.
| Original Prompt (No Rewrite) | MiniMax Context-IR | Qwen3.6-27B Base Rewriter | **H3-T2VA Context Rewriter LoRA (Ours)** ||---|---|---|---|| <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/mOQ8QidVn7Fc64UYSBcZR.mp4"></video> | <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/ULjXofNgjvs2aud70jdy8.mp4"></video> | <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/JgjzFsmiMWEfI7P7hERaQ.mp4"></video> | <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/Aze2ErBmM9MtsE7cRNAL5.mp4"></video> |
### Prompt 4
> **Original prompt:** A man in casual attire reaches for a gaming joystick from a shelf in a well-lit electronics store. He is standing in front of a display filled with various gaming consoles and accessories. The store background includes rows of shelves stocked with electronic gadgets, creating a bustling retail atmosphere. The man's posture is upright, with a focused and excited expression as he selects the joystick. The scene captures a close-up mid-shot, emphasizing the man's interaction with the joystick.
| Original Prompt (No Rewrite) | MiniMax Context-IR | Qwen3.6-27B Base Rewriter | **H3-T2VA Context Rewriter LoRA (Ours)** ||---|---|---|---|| <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/PfSo5D_lIe-ERk1yUS5GZ.mp4"></video> | <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/iJkM5xdnfOojBo2gKQyEI.mp4"></video> | <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/mFuOxCyycFw9ZwwiJQM6k.mp4"></video> | <video controls src="https://cdn-uploads.huggingface.co/production/uploads/680de13385293771bc57400b/xnDSTpEpofplVIRCI5eBY.mp4"></video> |
Expected video paths and filenames are documented in[`assets/examples/UPLOAD_LAYOUT.md`](assets/examples/UPLOAD_LAYOUT.md).
## Limitations
- This release supports text-only T2VA prompt rewriting; it does not consume images, videos, or audio references.- It is a learned approximation, not an open-source release or exact replica of the official H3-Context-IR service.- The generated rewrite may add details not explicitly present in a short prompt. Review the result before generation when identity, dialogue, timing, or composition must be exact.- Final quality depends on both prompt rewriting and the MiniMax-H3 inference settings selected in LightX2V.- Use of MiniMax-H3 is governed by the license and acceptable-use terms published in the [official MiniMax-H3 repository](https://huggingface.co/MiniMaxAI/MiniMax-H3).
## Acknowledgements
This project is developed by the[LightX2V](https://github.com/ModelTC/LightX2V) community to make local MiniMax-H3prompt rewriting and audio-video generation easier and more efficient. It is built forthe [MiniMax-H3](https://huggingface.co/MiniMaxAI/MiniMax-H3) audio-video generationmodel and fine-tuned from [Qwen3.6-27B](https://huggingface.co/Qwen/Qwen3.6-27B).
If you use this adapter or the MiniMax-H3 integration, please visit and star**[ModelTC/LightX2V](https://github.com/ModelTC/LightX2V)**, where inference support,performance optimizations, examples, and future task updates are maintained.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455{ "alora_invocation_tokens": null, "alpha_pattern": {}, "arrow_config": null, "auto_mapping": null, "base_model_name_or_path": "Qwen/Qwen3.6-27B", "bias": "none", "corda_config": null, "ensure_weight_tying": false, "eva_config": null, "exclude_modules": null, "fan_in_fan_out": false, "inference_mode": true, "init_lora_weights": true, "layer_replication": null, "layers_pattern": null, "layers_to_transform": null, "loftq_config": {}, "lora_alpha": 512, "lora_bias": false, "lora_dropout": 0.05, "lora_ga_config": null, "megatron_config": null, "megatron_core": "megatron.core", "modules_to_save": null, "monteclora_config": null, "peft_type": "LORA", "peft_version": "0.20.0", "qalora_group_size": 16, "r": 256, "rank_pattern": {}, "revision": null, "target_modules": [ "gate_proj", "v_proj", "down_proj", "k_proj", "out_proj", "q_proj", "in_proj_a", "in_proj_qkv", "o_proj", "up_proj", "in_proj_b", "in_proj_z" ], "target_parameters": null, "task_type": "CAUSAL_LM", "trainable_token_indices": null, "use_bdlora": null, "use_dora": false, "use_qalora": false, "use_rslora": false, "velora_config": null}123version https://git-lfs.github.com/spec/v1oid sha256:19b9d0064115918e72a1e2738d63c383a52fc364e06a3de76be37f525c3dde28size 3735445032123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143#!/usr/bin/env python3"""Rewrite one T2VA prompt with the MiniMax-H3 Prompt Rewriter LoRA."""
from __future__ import annotations
import argparseimport jsonfrom pathlib import Path
import torchimport transformersfrom transformers import AutoTokenizer, set_seed
from prompt_template import build_messages
DEFAULT_BASE_MODEL = "Qwen/Qwen3.6-27B"DEFAULT_ADAPTER = "lightx2v/MiniMax-H3-Prompt-Rewriter-LoRA"RESOLUTIONS = ("21:9", "16:9", "4:3", "1:1", "3:4", "9:16")
def get_model_class(): model_class = getattr(transformers, "AutoModelForImageTextToText", None) if model_class is None: model_class = getattr(transformers, "AutoModelForVision2Seq", None) if model_class is None: raise RuntimeError( "A recent Transformers version with AutoModelForImageTextToText " "support is required. Install the packages in requirements.txt." ) return model_class
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--prompt", required=True, help="Original text prompt to rewrite.") parser.add_argument("--duration", type=int, choices=range(4, 16), default=10, metavar="4..15") parser.add_argument("--resolution", choices=RESOLUTIONS, default="16:9", help="Target aspect ratio.") parser.add_argument("--base-model", default=DEFAULT_BASE_MODEL, help="HF model ID or local base-model path.") parser.add_argument("--adapter", default=DEFAULT_ADAPTER, help="HF model ID or local PEFT adapter path.") parser.add_argument( "--base-only", action="store_true", help="Skip the LoRA and run the Qwen base-model baseline.", ) parser.add_argument("--max-new-tokens", type=int, default=2048) parser.add_argument("--dtype", choices=("bfloat16", "float16", "float32"), default="bfloat16") parser.add_argument("--attn-implementation", choices=("sdpa", "flash_attention_2", "eager"), default="sdpa") parser.add_argument("--temperature", type=float, default=0.7) parser.add_argument("--top-p", type=float, default=0.8) parser.add_argument("--top-k", type=int, default=20) parser.add_argument("--repetition-penalty", type=float, default=1.05) parser.add_argument("--greedy", action="store_true", help="Use deterministic greedy decoding.") parser.add_argument("--seed", type=int, default=42) parser.add_argument( "--output", type=Path, help="Optional output path. A .json file stores conditions and output; other suffixes store plain text.", ) return parser.parse_args()
def input_device(model: torch.nn.Module) -> torch.device: """Return the embedding device, including when Accelerate shards the model.""" embeddings = model.get_input_embeddings() if embeddings is not None and hasattr(embeddings, "weight"): return embeddings.weight.device return next(model.parameters()).device
def main() -> None: args = parse_args() set_seed(args.seed) dtype = getattr(torch, args.dtype)
tokenizer = AutoTokenizer.from_pretrained(args.base_model, trust_remote_code=True) if tokenizer.pad_token_id is None: tokenizer.pad_token = tokenizer.eos_token
model = get_model_class().from_pretrained( args.base_model, torch_dtype=dtype, device_map="auto", low_cpu_mem_usage=True, trust_remote_code=True, attn_implementation=args.attn_implementation, )
if not args.base_only: from peft import PeftModel
model = PeftModel.from_pretrained(model, args.adapter) model.eval()
rendered = tokenizer.apply_chat_template( build_messages(args.prompt, args.resolution, args.duration), tokenize=False, add_generation_prompt=True, enable_thinking=False, ) inputs = tokenizer(rendered, return_tensors="pt", add_special_tokens=False) device = input_device(model) inputs = {name: tensor.to(device) for name, tensor in inputs.items()}
generation_kwargs = { "max_new_tokens": args.max_new_tokens, "do_sample": not args.greedy, "repetition_penalty": args.repetition_penalty, "pad_token_id": tokenizer.pad_token_id, "eos_token_id": tokenizer.eos_token_id, } if not args.greedy: generation_kwargs.update( temperature=args.temperature, top_p=args.top_p, top_k=args.top_k, )
with torch.inference_mode(): generated = model.generate(**inputs, **generation_kwargs) new_tokens = generated[:, inputs["input_ids"].shape[1] :] rewritten_prompt = tokenizer.batch_decode(new_tokens, skip_special_tokens=True)[0].strip()
if args.output is not None: args.output.parent.mkdir(parents=True, exist_ok=True) if args.output.suffix.lower() == ".json": record = { "prompt": args.prompt.strip(), "resolution": args.resolution, "duration": args.duration, "rewritten_prompt": rewritten_prompt, "base_model": args.base_model, "adapter": None if args.base_only else args.adapter, } args.output.write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") else: args.output.write_text(rewritten_prompt + "\n", encoding="utf-8")
print(rewritten_prompt)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940"""Prompt template shared by MiniMax-H3 T2VA prompt-rewriter inference."""
from __future__ import annotations
SYSTEM_PROMPT = """You are a professional prompt rewriter for joint audio-video generation.Rewrite the user's original prompt into one coherent, production-ready multimodal description for the requested output aspect ratio and duration.
Return only these three fields, in this exact order:integrated_multimodal_description: ...overall_soundscape: ...non_diegetic_music: ...
Requirements:- Expand the visual narrative into clearly numbered shots such as [Shot 1], [Shot 2], and include timestamps for cuts after the first shot when useful.- Make the number, timing, and pacing of shots appropriate for the requested duration.- Compose the scene for the requested aspect ratio.- Preserve the user's intent while adding concrete subjects, appearance, environment, lighting, composition, camera movement, physical motion, and temporal continuity.- Keep characters, objects, wardrobe, locations, and spatial relationships consistent across shots.- Describe synchronized diegetic audio in overall_soundscape and external score in non_diegetic_music.- Do not add explanations, Markdown fences, safety commentary, or fields other than the three requested fields."""
def build_messages(prompt: str, resolution: str, duration: int) -> list[dict[str, str]]: """Build the chat messages used during LoRA training and inference.""" prompt = prompt.strip() if not prompt: raise ValueError("prompt must not be empty")
return [ {"role": "system", "content": SYSTEM_PROMPT}, { "role": "user", "content": ( f"resolution: {resolution}\n" f"duration: {duration}s\n" f"original_prompt: {prompt}" ), }, ]12345torch>=2.6transformers>=4.57.1accelerate>=1.10peft>=0.17safetensors>=0.5.gitattributesAdded+35
README.mdAdded+283
adapter_config.jsonAdded+55
adapter_model.safetensorsAdded+3
infer.pyAdded+143
prompt_template.pyAdded+40
requirements.txtAdded+5