File size: 10,433 Bytes
15c46ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
"""Real NExT-GPT inference. No canned responses or replacement model."""
import gc
import json
import os
import re
import sys
import threading
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path

from settings import CODE, MODELS, OUTPUTS, UPSTREAM_COMMIT, WEIGHTS, missing_weights, weight_paths


def build_prompt(prompt, image=None, video=None, audio=None):
    if not prompt or not prompt.strip():
        raise ValueError("请输入文字指令。")
    # Paths are generated by our upload handler; reject markup in text to prevent
    # users from injecting arbitrary server file paths into the legacy parser.
    if re.search(r"</?(?:Image|Video|Audio)>", prompt, re.I):
        raise ValueError("请通过上传组件提供媒体,不要在指令中填写媒体路径标签。")
    parts = ["### Human: "]
    for tag, value in (("Image", image), ("Video", video), ("Audio", audio)):
        if value:
            value = str(Path(value).resolve())
            if "<" in value or ">" in value or not Path(value).is_file():
                raise ValueError("输入媒体文件不存在或路径无效。")
            parts.append(f"<{tag}>{value}</{tag}> ")
    return "".join(parts) + prompt.strip()


def runtime_status():
    try:
        import torch
        gpu = torch.cuda.get_device_name(0) if torch.cuda.is_available() else None
    except ImportError:
        gpu = None
    return {"gpu": gpu, "missing_weights": missing_weights(), "model_loaded": ENGINE.model is not None,
            "upstream_commit": UPSTREAM_COMMIT,
            "inference_verified": False if ENGINE.successful_runs == 0 else True,
            "successful_runs_this_process": ENGINE.successful_runs}


class Engine:
    def __init__(self):
        self.lock = threading.Lock()
        self.model = None
        self.successful_runs = 0

    def load(self):
        if self.model is not None:
            return
        import torch
        if not torch.cuda.is_available():
            raise RuntimeError("当前没有 CUDA GPU,尚不能执行 NExT-GPT 推理。")
        if missing_weights():
            raise RuntimeError("缺少权重:" + ", ".join(missing_weights()) +
                               "。请先运行 python scripts/prepare_weights.py --merge-vicuna")
        import yaml
        sys.path.insert(0, str(CODE))
        from model.anyToImageVideoAudio import NextGPTModel
        with (CODE / "config" / "base.yaml").open(encoding="utf-8") as f:
            args = yaml.safe_load(f)
        with (CODE / "config" / "stage_3.yaml").open(encoding="utf-8") as f:
            args.update({k: v for k, v in yaml.safe_load(f).items() if k != "train"})
        args.update(model="nextgpt", stage=3, mode="test",
                    pretrained_ckpt_path=str(WEIGHTS / "pretrained"))
        for key, name in (("image", "image_diffusion"), ("video", "video_diffusion"), ("audio", "audio_diffusion")):
            local = WEIGHTS / key
            args[name] = str(local) if (local / "model_index.json").is_file() else MODELS[key][0]
        args["resolve_decoder"] = resolve_decoder
        args["low_vram"] = os.getenv("NEXTGPT_LOW_VRAM", "0") == "1"
        model = NextGPTModel(**args)
        delta = torch.load(weight_paths()["nextgpt"], map_location="cpu")
        # The released checkpoint is a delta, so missing frozen keys are expected.
        # Unexpected keys or an empty overlap indicate a wrong checkpoint.
        if not isinstance(delta, dict) or not delta or not set(delta).intersection(model.state_dict()):
            raise RuntimeError("NExT-GPT delta 文件格式或参数名不匹配。")
        result = model.load_state_dict(delta, strict=False)
        if result.unexpected_keys:
            raise RuntimeError(f"delta 中存在未知参数:{result.unexpected_keys[:8]}")
        del delta
        gc.collect()
        model = model.eval().half()
        if args["low_vram"]:
            from accelerate import cpu_offload, disk_offload
            device = torch.device("cuda:0")
            if os.getenv("NEXTGPT_LLM_OFFLOAD", "cpu") == "disk":
                disk_offload(model.llama_model, str(WEIGHTS / "offload"), execution_device=device, offload_buffers=True)
            else:
                cpu_offload(model.llama_model, execution_device=device, offload_buffers=True)
            cpu_offload(model.visual_encoder, execution_device=device, offload_buffers=True)
            for module in (model.llama_proj, model.gen_text_hidden_fcs,
                           model.gen_text_hidden_fcs_video, model.gen_text_hidden_fcs_audio):
                module.to(device)
            self.model = model
        else:
            self.model = model.cuda()

    def run(self, prompt, image=None, video=None, audio=None, steps=30,
            frames=16, seconds=5, seed=13, max_tokens=246):
        text = build_prompt(prompt, image, video, audio)
        if not 10 <= int(steps) <= 50 or int(frames) not in (16, 24, 32):
            raise ValueError("生成步数应为 10–50,视频帧数应为 16、24 或 32。")
        if not 1 <= float(seconds) <= 9 or not 64 <= int(max_tokens) <= 512:
            raise ValueError("音频时长应为 1–9 秒,文本长度应为 64–512 tokens。")
        with self.lock:
            self.load()
            import torch
            import numpy as np
            import random
            torch.manual_seed(int(seed))
            np.random.seed(int(seed))
            random.seed(int(seed))
            run_dir = OUTPUTS / uuid.uuid4().hex
            run_dir.mkdir(parents=True)
            inputs = dict(prompt=text, image_paths=[image] if image else [],
                          video_paths=[video] if video else [], audio_paths=[audio] if audio else [],
                          top_p=0.01, temperature=1.0, max_tgt_len=int(max_tokens), modality_embeds=[],
                          filter_value=-float("inf"), min_word_tokens=10, gen_scale_factor=4.0,
                          max_num_imgs=1, max_num_vids=1, max_num_auds=1, stops_id=[[835]],
                          load_sd=True, generator=torch.Generator(device="cuda").manual_seed(int(seed)),
                          guidance_scale_for_img=7.5, num_inference_steps_for_img=int(steps),
                          guidance_scale_for_vid=7.5, num_inference_steps_for_vid=int(steps),
                          height=320, width=576, num_frames=int(frames),
                          guidance_scale_for_aud=7.5, num_inference_steps_for_aud=int(steps),
                          audio_length_in_s=float(seconds), ENCOUNTERS=1)
            record = dict(started_at=datetime.now(timezone.utc).isoformat(), prompt=prompt,
                          input_modalities=[k for k, v in (("image", image), ("video", video), ("audio", audio)) if v],
                          steps=int(steps), frames=int(frames), seconds=float(seconds), seed=int(seed),
                          upstream_commit=UPSTREAM_COMMIT, model_sources=MODELS,
                          gpu=torch.cuda.get_device_name(0), status="running")
            record.update(low_vram=os.getenv("NEXTGPT_LOW_VRAM", "0") == "1",
                          llm_offload=os.getenv("NEXTGPT_LLM_OFFLOAD", "cpu"))
            start = time.monotonic()
            try:
                torch.cuda.reset_peak_memory_stats()
                with torch.inference_mode():
                    raw = self.model.generate(inputs)
                result = save_outputs(raw, run_dir)
                record.update(status="success", elapsed_seconds=round(time.monotonic()-start, 3),
                              peak_gpu_gib=round(torch.cuda.max_memory_allocated()/2**30, 3),
                              text=result["text"], files=[Path(p).name for p in result["files"]])
                self.successful_runs += 1
            except Exception as exc:
                record.update(status="failed", error=type(exc).__name__ + ": " + str(exc),
                              elapsed_seconds=round(time.monotonic()-start, 3))
                raise
            finally:
                (run_dir / "run.json").write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8")
                gc.collect()
                torch.cuda.empty_cache()
            result["files"].append(str(run_dir / "run.json"))
            return result


def save_outputs(raw, directory):
    import imageio.v2 as imageio
    import scipy.io.wavfile
    result = {"text": "", "images": [], "video": None, "audio": None, "files": []}
    texts = []
    for item in raw:
        if isinstance(item, str):
            texts.append(item)
            continue
        for modality, values in item.items():
            for value in values:
                if isinstance(value, str):
                    texts.append(re.sub(r"\[(?:IMG|VID|AUD)\d+\]", "", value).strip())
                elif modality == "img":
                    for image in value:
                        target = directory / f"image-{len(result['images'])}.png"
                        image.save(target)
                        result["images"].append(str(target))
                        result["files"].append(str(target))
                elif modality == "vid":
                    target = directory / "video.mp4"
                    imageio.mimwrite(str(target), value, fps=8, codec="libx264")
                    result["video"] = str(target)
                    result["files"].append(str(target))
                elif modality == "aud":
                    target = directory / "audio.wav"
                    scipy.io.wavfile.write(target, 16000, value)
                    result["audio"] = str(target)
                    result["files"].append(str(target))
    result["text"] = "\n\n".join(t for t in texts if t)
    target = directory / "response.txt"
    target.write_text(result["text"], encoding="utf-8")
    result["files"].append(str(target))
    return result


ENGINE = Engine()


def resolve_decoder(key):
    """Download the exact decoder only when the LLM actually requests its modality."""
    from huggingface_hub import snapshot_download
    repo, revision = MODELS[key]
    target = WEIGHTS / key
    snapshot_download(repo, revision=revision, local_dir=str(target),
                      allow_patterns=["*.json", "*.txt", "*.bin"],
                      ignore_patterns=["*.fp16.*", "zs2_576w/*"], max_workers=2)
    return str(target)