From d2a4537da212fc7db121eea3cb43043f877e2c06 Mon Sep 17 00:00:00 2001 From: yibo Date: Mon, 24 Aug 2026 20:06:11 +0800 Subject: [PATCH] 删除本地 minimax-h3/ 旧代码,已打包备份 --- minimax-h3/API.md | 148 ---------------------------------------------------------------------------------------------------------------------------------------------------- minimax-h3/README.md | 457 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- minimax-h3/api-run.sh | 15 --------------- minimax-h3/api.py | 324 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ minimax-h3/burst-test.py | 57 --------------------------------------------------------- minimax-h3/concurrency-test.py | 44 -------------------------------------------- minimax-h3/direct-backend-test.py | 35 ----------------------------------- minimax-h3/gateway-run.sh | 11 ----------- minimax-h3/gateway-test.py | 52 ---------------------------------------------------- minimax-h3/gateway.py | 128 -------------------------------------------------------------------------------------------------------------------------------- minimax-h3/long15s.sh | 8 -------- minimax-h3/pin-cache.sh | 24 ------------------------ minimax-h3/prompt.txt | 1 - minimax-h3/realrun.sh | 10 ---------- minimax-h3/restart-8010.sh | 11 ----------- minimax-h3/run-verify.sh | 22 ---------------------- minimax-h3/run.sh | 26 -------------------------- minimax-h3/scripts/diag-nan.py | 80 -------------------------------------------------------------------------------- minimax-h3/scripts/diag3.py | 95 ----------------------------------------------------------------------------------------------- minimax-h3/scripts/diag4.py | 91 ------------------------------------------------------------------------------------------- minimax-h3/scripts/download.py | 38 -------------------------------------- minimax-h3/scripts/probe-attention-backend.py | 11 ----------- minimax-h3/scripts/probe-cp.py | 61 ------------------------------------------------------------- minimax-h3/scripts/probe-h3-shapes.py | 32 -------------------------------- minimax-h3/scripts/probe-nf4-fp16.py | 30 ------------------------------ minimax-h3/scripts/probe-turing-caps.py | 39 --------------------------------------- minimax-h3/scripts/probe2.py | 52 ---------------------------------------------------- minimax-h3/scripts/run.sh | 24 ------------------------ minimax-h3/scripts/t2va.py | 227 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- minimax-h3/scripts/test-fp32.py | 39 --------------------------------------- minimax-h3/scripts/test-patch.py | 39 --------------------------------------- minimax-h3/scripts/verify.py | 51 --------------------------------------------------- minimax-h3/start-all.sh | 37 ------------------------------------- minimax-h3/start-gateway.sh | 8 -------- minimax-h3/submit-same.py | 13 ------------- minimax-h3/verify-fixes.py | 43 ------------------------------------------- minimax-h3/watch-8012.sh | 21 --------------------- 37 files changed, 0 insertions(+), 2404 deletions(-) delete mode 100644 minimax-h3/API.md delete mode 100644 minimax-h3/README.md delete mode 100755 minimax-h3/api-run.sh delete mode 100644 minimax-h3/api.py delete mode 100644 minimax-h3/burst-test.py delete mode 100644 minimax-h3/concurrency-test.py delete mode 100644 minimax-h3/direct-backend-test.py delete mode 100755 minimax-h3/gateway-run.sh delete mode 100644 minimax-h3/gateway-test.py delete mode 100644 minimax-h3/gateway.py delete mode 100755 minimax-h3/long15s.sh delete mode 100755 minimax-h3/pin-cache.sh delete mode 100644 minimax-h3/prompt.txt delete mode 100755 minimax-h3/realrun.sh delete mode 100755 minimax-h3/restart-8010.sh delete mode 100755 minimax-h3/run-verify.sh delete mode 100755 minimax-h3/run.sh delete mode 100644 minimax-h3/scripts/diag-nan.py delete mode 100644 minimax-h3/scripts/diag3.py delete mode 100644 minimax-h3/scripts/diag4.py delete mode 100644 minimax-h3/scripts/download.py delete mode 100644 minimax-h3/scripts/probe-attention-backend.py delete mode 100644 minimax-h3/scripts/probe-cp.py delete mode 100644 minimax-h3/scripts/probe-h3-shapes.py delete mode 100644 minimax-h3/scripts/probe-nf4-fp16.py delete mode 100644 minimax-h3/scripts/probe-turing-caps.py delete mode 100644 minimax-h3/scripts/probe2.py delete mode 100755 minimax-h3/scripts/run.sh delete mode 100644 minimax-h3/scripts/t2va.py delete mode 100644 minimax-h3/scripts/test-fp32.py delete mode 100644 minimax-h3/scripts/test-patch.py delete mode 100644 minimax-h3/scripts/verify.py delete mode 100755 minimax-h3/start-all.sh delete mode 100755 minimax-h3/start-gateway.sh delete mode 100644 minimax-h3/submit-same.py delete mode 100644 minimax-h3/verify-fixes.py delete mode 100755 minimax-h3/watch-8012.sh diff --git a/minimax-h3/API.md b/minimax-h3/API.md deleted file mode 100644 index c13013b..0000000 --- a/minimax-h3/API.md +++ /dev/null @@ -1,148 +0,0 @@ -# MiniMax-H3 视频生成 API - -服务在服务器上:`/data/models/minimax-h3/api.py` + `api-run.sh`(本地是副本)。 - -## 为什么是异步任务式,不是同步接口 - -| 事实 | 后果 | -|---|---| -| 模型加载 240 s(首次,fp32 权重从机械盘读;page cache 命中 20 s) | 不能每请求加载 | -| 单条视频 Turbo 4 步约 **7 分钟**,50 步约 **90 分钟** | 同步 HTTP 必然超时 | -| 一条生成占 **12.3 G 显存 + 约 32 G 内存** | 22 G 卡上同时只能跑一条 | - -所以接口是:**提交任务拿 id → 轮询状态 → 下载文件**。并发提交会排队,不会 OOM。 - -## 启动 - -```bash -cd /data/models/minimax-h3 -./api-run.sh 1 8010 # GPU_ID=1, PORT=8010 -# 后台跑: -setsid nohup ./api-run.sh 1 8010 > logs/api.log 2>&1 < /dev/null & -``` - -⚠️ **显存前提**:这条服务常驻约 12.3 G。llm38 跑 256K 上下文时占 57.3 G(四卡各约 14.3 G), -两者在同一张卡上放不下。跑视频前先 `docker stop llm38`(这是测试机,见工作区 `CLAUDE.md`), -或把 H3 放到 llm38 没用满的卡上并自行核算。恢复用 `qwen38-deploy/RESTORE-GPU.md`。 - -## 接口 - -### `GET /health` -```json -{"status":"ok","model":"ready","gpu":"1","queued":0,"running":0} -``` -`status` 在模型加载完成前是 `loading`。**别在 `loading` 时提交任务**——会排队但看不出进度。 - -### `POST /v1/videos` → `202` - -```bash -curl -X POST http://192.168.110.67:8010/v1/videos \ - -H "Content-Type: application/json" \ - -d '{ - "prompt": "一只橘猫趴在洒满阳光的窗台上,慢慢眨眼,尾巴轻轻摆动", - "width": 832, "height": 480, "frames": 124, - "steps": 4, "turbo": true, "seed": 7 - }' -``` - -```json -{"id":"ca0f2f095ddd","status":"queued","queue_position":1, - "eta_seconds":428,"poll":"/v1/videos/ca0f2f095ddd"} -``` - -| 字段 | 默认 | 范围 | 说明 | -|---|---|---|---| -| `prompt` | 必填 | 1–2000 字符 | 中英文都行;含人物台词时用英文引号包住那句 | -| `width` | 832 | 64–**832** | | -| `height` | 480 | 64–**480** | | -| `frames` | 124 | 8–**124** | 24 fps,124 帧 ≈ 5.17 秒 | -| `steps` | 4 | 1–50 | turbo 时应 ≤8 | -| `turbo` | true | | true=4 步蒸馏 LoRA;false=全质量多步 | -| `seed` | 0 | 0–2³¹−1 | 同 seed 同参数结果可复现 | -| `flow_shift` | 自动 | | 不传则 turbo=6.0 / 非 turbo=12.0 | - -**上界不是随手写的**:832×480×124f 是实测跑通的最高档(峰值 12.2 G)。再大在 22 G 卡上 OOM, -所以在入口就挡住,而不是让它跑 7 分钟后崩掉。 - -错误码: -- `422` 参数越界或缺失(pydantic 校验) -- `400` `turbo=true` 且 `steps>8`(Turbo LoRA 是 4 步蒸馏的,多步没意义) - -### `GET /v1/videos/{id}` - -```json -{"id":"ca0f2f095ddd","status":"running","step":0,"total_steps":4, - "elapsed_seconds":132, ...} -``` - -`status`: `queued` → `running` → `done` / `failed`。 -完成后多出 `file`、`size_bytes`、`peak_vram_gb`、`download`。 - -### `GET /v1/videos/{id}/file` -返回 mp4。任务未完成时返回 `409`。 - -### `GET /v1/videos?limit=50` -列出最近任务。 - -## 完整调用示例(Python) - -```python -import time, requests -API = "http://192.168.110.67:8010" - -r = requests.post(f"{API}/v1/videos", json={ - "prompt": "清晨的中式庭院,一位女子坐在长廊上喝茶,阳光透过竹叶", - "steps": 4, "turbo": True, "seed": 42, -}, timeout=30) -r.raise_for_status() -jid = r.json()["id"] -print("任务", jid, "预计", r.json()["eta_seconds"], "秒") - -while True: - j = requests.get(f"{API}/v1/videos/{jid}", timeout=30).json() - if j["status"] in ("done", "failed"): - break - print(j["status"], j.get("elapsed_seconds", 0), "s") - time.sleep(20) - -if j["status"] == "failed": - raise SystemExit("失败: " + j["error"]) - -open(f"{jid}.mp4", "wb").write( - requests.get(f"{API}/v1/videos/{jid}/file", timeout=300).content) -print("已保存", j["size_bytes"], "字节,峰值显存", j["peak_vram_gb"], "G") -``` - -## 服务端会自己验产物 - -**写出文件不等于成功**——fp16 时代踩过:全黑视频照样写出 24 KB 的 mp4 并返回退出码 0。 -所以 worker 在写文件前会检查: - -- 抽 8 帧算像素 `std`,`< 1.0` 判为纯色 → 任务标 `failed` -- 音频张量含非有限值 → 任务标 `failed` - -这两条不通过时**不会**给你一个"成功但没用"的文件。 - -## 任务记录会落盘(2026-08-20 起) - -`JOBS` 曾经只在内存里,进程重启(比如 `h3-console` 弹性调度器切 fl2va/ref2va 分区时的 -kill+restart)就把这张表清空——视频文件在 `outputs/` 没事,但 id→文件路径这层映射没了, -`GET /v1/videos/{id}`、下载都会 404。现在改成每次状态变化都往 sqlite 写一份: - -- 落盘文件是 **`jobs_gpu{GPU_ID}.sqlite3`**(跟 `api.py` 同目录),四张卡各一份,不共享—— - 一个进程只会在同一张 GPU 上起来,per-GPU 分文件天然不会有另一个进程来抢,不用处理 - 跨进程写锁竞争。 -- 进程启动时会把这个文件读回内存,日志能看到 `[api] 从磁盘恢复了 N 条历史任务记录`。 -- **in-flight(`queued`/`running`)的记录没法真正恢复**——GPU 上下文和排队队列本来就不落盘, - 重启后没有任何东西能"接着跑"。这类记录读回来会被**改判为 `failed`**,`error` 字段写明 - "进程重启导致这条任务的执行状态丢失"。只有 `done`/`failed` 这两个终态是完整保留的。 -- 只影响**直接调用 `api.py`/`gateway.py` 的场景**——如果你是通过 `h3-console`(端口 8080) - 提交的任务,即使碰到上面这种真正没法恢复的 in-flight 丢失,console 自己也存了一份 - 影子记录,历史和已完成任务的文件不受影响。 - -## 已知限制 - -- **无鉴权**,和这台机器上其他服务一致。放到公网前必须加。 -- **单 worker 串行**。要并发就每张空闲卡起一个实例(不同 PORT),自己在上层做负载。 -- `turbo=false` 时会 `clear_lora()`,任务结束后再挂回来。**混合提交 turbo/非 turbo 时 - 每次切换都有 LoRA 装卸开销**,批量跑同一种模式更快。 diff --git a/minimax-h3/README.md b/minimax-h3/README.md deleted file mode 100644 index 0dc57c1..0000000 --- a/minimax-h3/README.md +++ /dev/null @@ -1,457 +0,0 @@ -# MiniMax-H3 视频生成部署(4 × RTX 2080 Ti) - -在 `192.168.110.67` 上用 DiffSynth-Studio 跑 MiniMax-H3 FL2VA(文生视频 + 原生立体声)。 - -> **状态(2026-08-18)**:环境已装好并通过全部兼容性实测;模型下载中(33 GB / 6 MB/s); -> 尚未完成首次出片。验收结果见本文末「验收记录」,未填即表示还没跑通。 - -服务器侧根目录 **`/data/models/minimax-h3/`**,本目录是其脚本副本 + 决策记录。 - ---- - -## 一、为什么不能照抄官方示例 - -官方 [MiniMax-H3.md](https://github.com/modelscope/DiffSynth-Studio/blob/main/docs/en/Model_Details/MiniMax-H3.md) -的示例在这台机器上**跑不起来**,有三处必须改。 - -### 1. `torch.bfloat16` → `torch.float16`(致命) - -官方示例的 `vram_config` 与 `torch_dtype` 全用 bf16。sm_75 上实测: - -``` -[ERR] SDPA bfloat16 EFFICIENT_ATTENTION → RuntimeError: No available kernel -[ERR] SDPA bfloat16 FLASH_ATTENTION → RuntimeError: No available kernel -[OK ] SDPA bfloat16 MATH → 只剩朴素实现 -[OK ] SDPA float16 EFFICIENT_ATTENTION → 可用 -``` - -bf16 不是"慢一点",是**没有任何高效 attention kernel**。PyTorch 会静默掉到 MATH 后端, -在 H3 的 ~14,100 token 序列上要物化 `14100 × 14100 × 56` 的注意力矩阵,必然 OOM。 - -FP16 路径实测(真实 H3 形状 S=14100 H=56 D=128): - -``` -SDPA EFFICIENT fp16 → OK, 0.21s -fp16 GEMM 有效算力 → 54.3 TFLOPS (2080Ti fp16 张量核满血) -fp16 深链数值稳定性 → finite -``` - -**注意**:`llm-setup.md` 说 "Turing…不支持 bf16,跑 GGUF 走 llama.cpp 是唯一实际路径" —— -前半句对,后半句对扩散模型不成立。PyTorch + bitsandbytes NF4 在 sm_75 上是通的,见下。 - -### 2. `vram_limit` 取错了下标(会 OOM) - -```python -vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 2 # 官方:[1] = 总显存 -vram_limit=torch.cuda.mem_get_info("cuda")[0] / (1024 ** 3) - 2 # 本机:[0] = 空闲显存 -``` - -`mem_get_info()` 返回 `(free, total)`。这台机器四张卡都有常驻服务(llm38 / embedding / SD / whisper), -按总显存 21.5G 要预算,实际只有 12–15G 可用,必 OOM。 - -### 3. `offload_device="disk"` 不能用 - -`model_inference_low_vram/` 那组示例把权重 offload 到磁盘。本机 `/data` 是 -**7200rpm 机械盘**(HGST HUS726020ALA610,实测顺序读 184 MB/s)。 -NF4 DiT 16 GB,每个去噪步都要过一遍,光 I/O 就 **87 秒/步**。 - -改用 CPU 内存 offload:物理内存 128 GB,可用 123 GB,单 worker 常驻约 32 GB,宽裕。 - ---- - -## 二、attention backend:只用 PyTorch SDPA - -| Backend | sm_75 | 处置 | -|---|---|---| -| FlashAttention 2 / 3 / 4 | ❌ 仅 sm_80–sm_121 | **不装** | -| SageAttention | ❌ 需 sm_80+ | **不装** | -| xFormers | ⚠️ 系统已装 0.0.33,fp16 可用 | 不用(见下) | -| PyTorch SDPA | ✅ EFFICIENT(cutlass)后端 | **采用** | - -DiffSynth 的 `diffsynth/core/attention/attention.py` 里有自动优先级, -**xformers 排在 torch 前面会被自动选中**。实测: - -``` -不设环境变量 → selected = xformers -DIFFSYNTH_ATTENTION_IMPLEMENTATION=torch → selected = torch -``` - -两者 fp16 下都能跑,但锁死 `torch` 保证可复现。`run.sh` 已导出该变量。 - -H3 的 DiT 只用最干净的 attention 调用(无 mask / 无 causal / 无 sliding window, -见 `minimax_h3_dit.py:79`),不会踩 flex_attention 需要 torch.compile 的坑。 - ---- - -## 三、NF4 量化在 Turing 上成立 - -NF4 走 bitsandbytes 的 `Linear4bit`。bitsandbytes 的 4-bit 最低要求正好是 -**sm_75**,2080 Ti 卡在支持线上;其 CMakeLists 的架构列表明确含 `75`。 - -**服务器上原有的 bitsandbytes 0.45.1 是坏的**(在 `~/.local`): - -``` -AttributeError: 'NoneType' object has no attribute 'cquantize_blockwise_fp16_nf4' -``` - -CUDA 动态库没加载上。已在 venv 内装 0.50.1 覆盖。实测通过: - -``` -[OK ] NF4 fp16 forward out=(1024,14336) finite=True rel_err=0.0913 -[OK ] NF4 prequantized reload match=True ← 这正是加载 .safetensors 时走的分支 -``` - ---- - -## 四、多卡:H3 不支持模型并行 - -DiffSynth 的序列并行(`diffsynth/utils/xfuser/`)**只被 `wan_video.py` 和 -`mova_audio_video.py` 引用**;`minimax_h3_audio_video.py` 里零引用 xfuser / torch.distributed。 - -叠加硬件事实(`llm-setup.md` 第 2.2 节):四卡无 P2P(`topo -p2p r` 全 CNS), -GPU0/1 与 GPU2/3 跨 NUMA。 - -> **结论:不要试图把 4×22G 当成一张 88G 卡。** -> 多卡只能做**独立 worker 并发**(每卡一个进程),不能拆单个任务。 - -并发数上限由**内存**而非显存决定:每 worker 常驻约 32 GB(DiT NF4 16 GB + -文本编码器 NF4 14.3 GB + VAE 1.8 GB),128 GB 内存 → **最多 2–3 个 worker**。 - ---- - -## 五、模型与算力 - -DiT 是**稠密 30.9B**(50 层 / hidden 5376 / 56 heads × 128 / ffn 14336,无 MoE)。 -480×832×124 帧 → 视频 latent 35×30×52,patch(1,2,2) → **≈14,100 token**。 -每步约 830 TFLOP。 - -| 文件 | 大小 | -|---|---| -| `minimax-h3-fl2va-nf4.safetensors` | 15.98 GB | -| `minimax-h3-text-encoder-nf4.safetensors`(Qwen3-VL 32B) | 14.27 GB | -| `video_vae_nf4.safetensors` | 1.50 GB | -| `audio_vae_nf4.safetensors` | 0.26 GB | -| `minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors`(LoRA) | 1.29 GB | -| **合计** | **33.3 GB** | - -Turbo LoRA 能叠在 NF4 上——`core/vram/layers.py:445` 的 -`AutoWrappedQuantizedModule(AutoTorchModule, LoRAHotLoadMixin)` 在量化输出**之后**做 -`out += x@A@B`,不需要反量化基座权重。这是最大的性能杠杆: - -| 方案 | 步数 | 单条 5 秒视频(估算) | -|---|---|---| -| NF4 全量 | 50 | 20–35 分钟 | -| NF4 + Turbo LoRA | 4 | **2–4 分钟** | - -> 文件名里的 `bf16` 只是 LoRA 权重的存储精度,加载时会按 `pipe.torch_dtype` 转成 fp16,不影响。 - ---- - -## 六、安装了什么(以及没动什么) - -**全部落在 `/data/models/minimax-h3/`。系统级零改动。** - -- 没装 CUDA、没动驱动(570.153.02 保持)、没碰 `/usr`、没改 `~/.local` -- 系统 `nvcc` 是 11.5,很老,但**推理用不到**——pip 的 torch wheel 自带 CUDA runtime -- venv 用 `--system-site-packages` 复用已验证的 `torch 2.9.0+cu128` - (其 `arch_list` 含 `sm_75`),省 3 GB 下载 -- **只装了 bitsandbytes 0.50.1 + diffsynth(`-e . --no-deps`)**,其余依赖系统已齐 -- **不要设 `PYTHONNOUSERSITE=1`**:`torch` / `transformers` / `av` 都住在 `~/.local`, - 屏蔽掉会连 torch 一起丢。venv 的 site-packages 本来就排在 `~/.local` 前面, - 我们的 bnb 0.50.1 自然覆盖坏掉的 0.45.1 - -### 容器变更(用户已授权,可逆) - -| 容器 | 动作 | 恢复 | -|---|---|---| -| `llm`(旧 llama.cpp,unhealthy 5 天,已被 llm38 取代) | **已停** | `docker start llm` | -| `whisper` | 停后**已恢复** | — | -| `llm38`(Qwen3.8-27B,经 FRP 对外供 `qwen.wudaima.com`) | **全程未碰** | — | - -启动参数完整备份在 `/data/models/minimax-h3/backup/`(`llm.inspect.json` / -`whisper.inspect.json` / `restore-notes.txt`)。两者都是 `restart=unless-stopped`, -手动 stop 不会被自动拉起。 - ---- - -## 七、目录与路径 - -| 用途 | 路径 | -|---|---| -| 根目录 | `/data/models/minimax-h3/` | -| venv | `/data/models/minimax-h3/venv/` | -| DiffSynth 源码 | `/data/models/minimax-h3/DiffSynth-Studio/`(HEAD `0361581`) | -| **模型权重** | `/data/models/minimax-h3/models/` | -| **日志** | `/data/models/minimax-h3/logs/` | -| **输出视频** | `/data/models/minimax-h3/outputs/` | -| 脚本 | `/data/models/minimax-h3/scripts/` | -| 容器备份 | `/data/models/minimax-h3/backup/` | - -## 八、启动命令 - -```bash -cd /data/models/minimax-h3 - -./run.sh 1 # GPU1,Turbo 4-step,480x832x124f(默认) -./run.sh 1 --no-turbo --steps 50 # 全质量 50 步 -./run.sh 2 --prompt "..." --seed 7 -./run.sh 1 --fp32-accum # 若出现 NaN/伪影:关 fp16 累加(约慢一倍) -``` - -多 worker(每卡一个独立进程,**内存上限 2–3 个**): - -```bash -./run.sh 0 --prompt "..." & # GPU0(NUMA0) -./run.sh 1 --prompt "..." & # GPU1(NUMA0) -./run.sh 2 --prompt "..." & # GPU2(NUMA1) -./run.sh 3 --prompt "..." & # GPU3(NUMA1) -``` - -`run.sh` 会按 GPU 编号选 NUMA 节点绑核(GPU0/1→node0,GPU2/3→node1), -但服务器上**没装 `numactl`**,目前这段会自动跳过。装了会更快。 - -## 九、脚本 - -| 脚本 | 作用 | -|---|---| -| `run.sh` | 启动器:设环境变量 + 选 GPU + 落日志 | -| `t2va.py` | 推理主体(fp16 / SDPA / CPU offload) | -| `download.py` | 用 DiffSynth 自己的 `ModelConfig` 下载,保证落盘布局与加载时解析一致 | -| `verify.py` | 逐文件比对字节数 vs ModelScope + 解析 safetensors 头 | -| `probe-turing-caps.py` | sm_75 能力探测(bf16/fp16 × 各 attention 后端) | -| `probe-h3-shapes.py` | 真实 H3 形状下的 attention + GEMM 吞吐 | -| `probe-nf4-fp16.py` | NF4 fp16 前向 + prequantized 重载 | -| `probe-attention-backend.py` | 验证 DiffSynth 实际选中的后端 | - -换硬件或升级 torch/bnb 后,**先跑 probe-* 四个再动别的**。 - -## 十、下载注意 - -出口带宽 **5.9 MB/s 封顶**(`llm-setup.md` 第三节),33 GB 约 **95 分钟**。 - -- 必须 `setsid`,**只用 `nohup` 不够**——SSH 通道关闭时进程仍会被带走(本次踩过) -- **不要开两个下载进程**:并行不会更快(出口带宽是瓶颈),只会争抢同一个 - `._____temp` 分片互相破坏(本次踩过,事后用 `verify.py` 校验) -- ModelScope 可达;HuggingFace / ghcr 不通 - -## 十一、失败时的降级顺序 - -1. fp16 出 NaN → `--fp32-accum`(关 fp16 累加,约慢一倍) -2. 仍不行 → 把 norm / adaln 提到 fp32 -3. 显存不够 → 调小 `--vram-reserve`,或换 pruned 权重 - (`minimax-h3-fl2va-pruned-nf4.safetensors`,9.76 GB / 18.7B,但 **Turbo LoRA 与之不兼容**,层数不同) - ---- - -## ★ 2026-08-18 实测推翻本文档第一节:fp16 是故障本身,不是修复 ★ - -本 README 第一节写「`torch.bfloat16` → `torch.float16`(致命)」,把改用 fp16 当作**必须的修正**。 -**实测结论相反:改成 fp16 才是这条线出不了片的根本原因。** - -### 对照实验(唯一变量是 dtype) - -同分辨率 448×256×28f、同 prompt、同权重、同 Turbo LoRA,只改 `torch_dtype`: - -| | fp32 | fp16 | -|---|---|---| -| 视频像素 | mean=140.9 **std=50.6** max=255 | mean=0 **std=0** max=0 | -| 音频 | **finite=True** | finite=False | -| 生成耗时 | 62s | 40s | -| 峰值显存 | 16.3G | 16.3G | -| 结果 | **正常出片 ✅** | **124 帧纯黑 ❌** | - -模型、权重、管线、Turbo LoRA、VAE 全部正常——**唯一的问题是 fp16 的动态范围装不下这个模型**。 - -### 为什么之前的 probe 没测出来 - -`probe-nf4-fp16.py` / `probe-h3-shapes.py` 用的是**合成小张量**,测的是「NF4 fp16 前向不报错、数值有限」。 -这类测试测不出真实模型在 **50 层残差累积**后的量级。实测 `dit.blocks.0` 输入 absmax 89 → 输出 38176, -逼近 fp16 上限 65504;再往后必然溢出。**「单层不溢出」推不出「50 层不溢出」。** - -### 溢出机理:`.to(x.dtype)` 这个模式在库里反复出现 - -```python -# minimax_h3_dit.py:61-67 -def _modulate_scale_shift(x, shift, scale, indices): - return (x * (1.0 + scale.index_select(0, indices)) + shift.index_select(0, indices)).to(x.dtype) -def _modulate_gate(x, gate, other, indices): - return (x + gate.index_select(0, indices) * other).to(x.dtype) -``` - -库作者自己的注释说「index_select on the AdaLN params can promote the expression」—— -表达式确实被提升到 fp32 算,但**结果又降回 fp16**,恰好丢掉了提升带来的动态范围。 -DiT 有 50 个 block × 每个 2 次 = **100 个这样的降回点**。`condition_proj` 那里是同一个病灶的另一个实例 -(fp32 真值 absmax 79554 > 65504)。 - -### 逐点修 fp16 是行不通的(四条弯路,都实测过) - -1. `--fp32-accum` —— 开关生效(`fp16_reduced_accum` True→False)但**输出逐字节相同**。 - 它管的是 reduced-precision reduction,与这里的溢出无关。README 第十一节把它列为降级第一档,**对此故障不对症**。 -2. 替换 `AutoWrappedLinear.forward` —— 会绕过 `preparing()`/onload 换入机制。 -3. 只替换 `linear_forward`、最后仍 `.to(fp16)` —— **无效**:fp32 算得对,溢出发生在那次类型转换上。 - (自检若只查转换前的张量,会永远显示"正常"——踩过。) -4. 钳位到 65504 再降回 —— **反而更糟**:`blocks.0` 是 `h = x + attn(norm1(x))`, - x 恰好等于 fp16 最大可表示值时再加任何正数立刻变 inf(实测 3.45% 非有限)。钳位不留余量等于自造故障。 - -每修一处,NaN 就移到下一处——因为问题是全局的动态范围,不是某几个点。 - -### 另一个方法教训:诊断配置必须与故障配置逐项一致 - -前几轮诊断用的是中文 prompt「一只橘猫…」,而实际失败的是 `t2va.py` 的**英文默认 prompt**。 -不同文本 → 不同嵌入量级 → 溢出点不同。定位出的路径在真实故障里根本不触发,白跑了几轮。 - -### 退出码不可信 - -原 `t2va.py` 只检查 `audio` 是否非有限,**从不检查 video**,全黑视频照样打印 `[done]` 并返回 **0**。 -已补上 video 的有限性 + 纯色检查(std < 1.0 判失败),坏产物以**退出码 3** 退出。 - ---- - -## 冒烟测试前置检查(2026-08-18 17:59,llm38 切 256K 之后) - -环境侧已全部验证,剩下的唯一变量是权重本身。 - -| 检查项 | 结果 | -|---|---| -| attention 后端 @ 真实 DiT 形状 (1,56,14100,128) fp16 | ✅ SDPA 选中,`finite=True`(xformers 可用但被 env 钉死为 torch) | -| bitsandbytes 版本 | ✅ **0.50.1**(成功压住 `~/.local` 里坏的 0.45.1) | -| NF4 fp16 前向 + 预量化重载 | ✅ `rel_err=0.0913`,reload `match=True` | -| 已落盘 3 文件字节 + safetensors 头 | ✅ video_vae / audio_vae / turbo LoRA 全对 | - -### ⚠️ `t2va.py:47` 的地板值现在是个雷 - -```python -vram_limit = max(6.0, free_gb - args.vram_reserve) -``` - -这个 `6.0` 地板是在**每卡还有 12–15 GB 空闲**时写的。2026-08-18 llm38 上下文提到 256K 后(KV 从 8 GiB 涨到 32 GiB),空闲显存腰斩,地板值开始**反过来盖掉安全余量**: - -| | 空闲 | 实得 `vram_limit` | 余量 | | -|---|---|---|---|---| -| GPU0 | 6.58G | 6.00G | +0.58G | 勉强,无缓冲 | -| **GPU1** | **7.51G** | 6.00G | **+1.51G** | 勉强,最宽裕 → **冒烟测试用这张** | -| GPU2 | 5.25G | 6.00G | **−0.75G** | ❌ **必 OOM**:地板要的比卡上有的还多 | -| GPU3 | 6.59G | 6.00G | +0.59G | 勉强,无缓冲 | - -`--vram-reserve` **调不动这个地板**——`max()` 在外层。 - -### ✅ 正解:跑 H3 之前先停 llm38 - -用户 2026-08-18 明确:**这是测试机,不是生产环境,停 llm38 让路是预期做法**(见工作区 `CLAUDE.md`)。所以上面整张表都不必绕,串行跑就行: - -```bash -docker stop llm38 # 让出约 57 GB -./run.sh 1 ... # 四卡各约 21 GB 空闲 → vram_limit 约 19 G,地板值失效 -docker start llm38 # 跑完起回来,约 15 秒 -``` - -这样测出来的还是**干净数字**(无抢占),比在争抢状态下测更有参考价值。 - -**地板值仍值得修**(低优先级):`max(6.0, ...)` 在放不下时会去要一个不存在的额度而不是报错。真要多负载共存时才会再咬人;目前串行跑绕开了。 - -### 脚本漂移(已修) - -本 README 第九节列了 8 个脚本、并说「换硬件后先跑 probe-* 四个」,但**服务器上原本只有 3 个**(`download.py` / `t2va.py` / `verify.py`),4 个 probe 从没上过服务器,那条指示在服务器上无法执行。已补齐到 `/data/models/minimax-h3/scripts/`。 - -> 另注:`run.sh` 在服务器上位于 `/data/models/minimax-h3/run.sh`(顶层),本地副本放在 `scripts/` 下,两边路径不一致。README 第八节的 `cd /data/models/minimax-h3 && ./run.sh 1` 以服务器为准。 - ---- - -## 验收记录 - -**2026-08-18 22:31 首次成功出片。** 配置:`dtype=fp32` · Turbo 4-step · 832×480×124f · GPU1 · `vram_limit=7.3G` - -### 产物验证(ffprobe + 逐像素 + 音频样本) - -| 项目 | 实测 | -|---|---| -| 文件 | `outputs/t2va_20260818-223136.mp4` **7,859,869 字节 (7.5 MB)** | -| 视频流 | h264 **832×480** · 24 fps · **124 帧** · 5.167 s | -| 实际解码帧数 | **124**(与声明一致,无截断) | -| 像素 | mean 69.33 · **std 57.85** · 全域 0–255 | -| **帧间平均差异** | **16.99** → 真实动态视频,非静止图 | -| 音频流 | aac · **32000 Hz · 双声道** · 163 帧 · 5.175 s | -| 音频电平 | mean **−34.0 dB** · max **−14.9 dB**(静音应为 −91 dB) | -| 音频样本 | absmax 0.1799 · rms 0.0199 · **非零样本 100%** | - -> 验证方法上的教训:`ffmpeg -af volumedetect -f null -` 的输出容易被 grep 漏掉, -> 误报成"无音频流"。**直接用 PyAV 解码样本算 rms** 更可靠。 - -### 性能与显存(fp32,全部实测) - -| 分辨率 | 步数 | 生成耗时 | 每步 | 峰值显存 | 结果 | -|---|---|---|---|---|---| -| 448×256×28f | 4 (turbo) | 62 s | 15.5 s | 16.3 G | ✅ std 50.6 | -| 640×384×61f | 4 (turbo) | 171 s | 42.8 s | 11.4 G | ✅ std 51.7 | -| **832×480×124f** | **4 (turbo)** | **553 s** | **107 s** | **12.2 G** | ✅ std 66.8 | -| 832×480×124f | 4 (turbo),真实 prompt | 556 s | 138.9 s | 12.3 G | ✅ **本次验收** | - -> 同配置两次每步耗时 107 s vs 138.9 s,差异来自并发:验收那次有另一条 50 步任务 -> 在别的卡上同时跑,抢 CPU 与内存带宽(权重 offload 在 CPU 侧)。**单任务跑约 107 s/步。** - -**加载耗时**:首次从机械盘读 fp32 权重 **238 s**;page cache 命中后 fp16 只要 **12–15 s**。 -反复调试时第二次之后极快,不必每次预留 6 分钟。 - -### 与 fp16 的对照(唯一变量是 dtype) - -| | fp32 | fp16 | -|---|---|---| -| 每步耗时 | 107 s | 36.8 s(快 2.9×) | -| 峰值显存 | 12.2 G | 15.9 G | -| **产物** | **正常出片** | **124 帧纯黑 / 音频 NaN** | - -fp16 更快更省显存,但**根本出不了片**。这不是速度取舍,是能用与不能用的区别。详见上一节。 - -### 启动命令(已验证) - -```bash -cd /data/models/minimax-h3 -echo "你的提示词" > prompt.txt # 从文件读,避开多层 shell 引号 -./realrun.sh turbo # Turbo 4-step,全分辨率,约 10 分钟 -./realrun.sh full50 # 50 步全质量,约 90 分钟 -``` - -直接调用也可(`--vram-reserve` 现按 dtype 自适应,fp32 默认 14): - -```bash -./run.sh 1 --prompt "$(cat prompt.txt)" --seed 42 -``` - -> **prompt 必须从文件读。** 直接在 `ssh … bash -c "…"` 里传含引号的 prompt 会被 -> 三层 shell 吃掉,传进去是空串,报错是 -> `RuntimeError: cannot reshape tensor of 0 elements into shape [1, 0, -1, 128]` -> ——看着像 transformers 的 bug,实际是**输入为空**。0 元素张量崩在 reshape 是这个的典型指纹。 - -### 50 步全质量(2026-08-18 23:51 完成,已验收) - -同 prompt、同 seed,`--no-turbo --steps 50`: - -| 项目 | 实测 | -|---|---| -| 文件 | `outputs/t2va_20260818-235141.mp4` **6,726,194 字节 (6.4 MB)** | -| 生成耗时 | **5364 s(89 分钟)· 107.3 s/步** | -| 峰值显存 | **9.1 G**(比 turbo 的 12.3 G 更低——无 LoRA 层) | -| 视频 | h264 832×480 · 24 fps · **124 帧** · 5.167 s | -| 像素 | mean 71.63 · **std 59.68** · 全域 0–255 | -| 帧间平均差异 | **7.366** | -| 音频 | mean **−27.2 dB** · max **−9.2 dB** · 331776 样本 | - -**与 Turbo 4-step 的对比**: - -| | Turbo 4-step | 50 步全质量 | -|---|---|---| -| 耗时 | 556 s | **5364 s(9.6×)** | -| 峰值显存 | 12.3 G | 9.1 G | -| 像素 std | 57.85 | 59.68 | -| 帧间差异 | **16.99** | **7.366** | -| 音频电平 | −34.0 / −14.9 dB | **−27.2 / −9.2 dB** | - -50 步的帧间差异明显更小、音频更响。**帧间差异小不等于质量差**——更多去噪步数带来更平滑的时序连贯性; -Turbo 的 16.99 里有一部分是 4 步蒸馏残留的帧间抖动。哪个观感更好需要人眼判断, -这两条客观指标只能说明**两者都是真实动态视频,且 50 步的时序更稳**。 - -**每步耗时 107.3 s 与单任务 turbo 的 107 s 完全一致**——证明这个数字是这台机器上 -fp32 全分辨率的稳定值,不随步数或 LoRA 变化。 - - - diff --git a/minimax-h3/api-run.sh b/minimax-h3/api-run.sh deleted file mode 100755 index dedc7e0..0000000 --- a/minimax-h3/api-run.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env bash -# 启动 MiniMax-H3 视频 API。用法: ./api-run.sh [GPU_ID] [PORT] [PARTITION] -# PARTITION=fl2va 收首末帧;ref2va 收任意多张参考图。一个进程一个分区,各占一张卡。 -set -uo pipefail -B=/data/models/minimax-h3 -GPU="${1:-1}"; PORT="${2:-8010}"; export H3_PARTITION="${3:-fl2va}" -export CUDA_VISIBLE_DEVICES="$GPU" -export DIFFSYNTH_ATTENTION_IMPLEMENTATION=torch -export DIFFSYNTH_MODEL_BASE_PATH="$B/models" -export MODELSCOPE_CACHE="$B/.mscache" -export PYTORCH_ALLOC_CONF=expandable_segments:True -export PYTHONUNBUFFERED=1 -cd "$B" -echo "[api] GPU=$GPU PORT=$PORT PARTITION=$H3_PARTITION 首次加载约 240 秒(fp32 权重从机械盘读)" -exec "$B/venv/bin/python" -m uvicorn api:app --host 0.0.0.0 --port "$PORT" --workers 1 diff --git a/minimax-h3/api.py b/minimax-h3/api.py deleted file mode 100644 index 3dd52b2..0000000 --- a/minimax-h3/api.py +++ /dev/null @@ -1,324 +0,0 @@ -"""MiniMax-H3 文生视频 HTTP API(异步任务式)。 - -为什么不是同步接口:模型加载 238s、单条视频 7 分钟(50 步 90 分钟), -同步 HTTP 必然超时。所以是「提交任务拿 id → 轮询状态 → 下载文件」。 - -为什么是串行单 worker:一条生成占 ~12.3G 显存 + ~32G CPU 内存, -一张 22G 卡同时只能跑一条。并发提交会排队,不会 OOM。 -""" -import os, sys, time, uuid, threading, queue, traceback, io, sqlite3, urllib.request -from typing import Optional, Literal -from pathlib import Path - -BASE = Path("/data/models/minimax-h3") -OUT = BASE / "outputs"; OUT.mkdir(exist_ok=True) -# 一个进程只跑一个分区。两套权重的 DiT、processor、Turbo LoRA 三样都不同, -# 同进程装两套要么重建 pipe(每次重读 16G 权重),要么常驻 77G 内存。 -# 每卡一个进程本来就是这台机器唯一的并发方式(H3 不支持模型并行),顺手就把分区分开了。 -PARTITION = os.environ.get("H3_PARTITION", "fl2va") -# 没上 GPU 的那部分权重存哪。cpu 是每进程一份 40G 匿名内存,并发被 125G 内存卡在 3 个; -# disk 让权重留在 safetensors 文件里(layers.py 里 offload() 就是 .to("meta")), -# 每次前向从文件读进显存,走 OS 页缓存——多个进程读同一个文件,物理内存里只有一份。 -OFFLOAD = os.environ.get("H3_OFFLOAD", "cpu") -os.environ.setdefault("DIFFSYNTH_ATTENTION_IMPLEMENTATION", "torch") -os.environ.setdefault("DIFFSYNTH_MODEL_BASE_PATH", str(BASE / "models")) -os.environ.setdefault("MODELSCOPE_CACHE", str(BASE / ".mscache")) -os.environ.setdefault("PYTORCH_ALLOC_CONF", "expandable_segments:True") - -import torch -from fastapi import FastAPI, HTTPException -from fastapi.responses import FileResponse -from pydantic import BaseModel, Field, model_validator - -def _rows(width: int, height: int, frames: int) -> float: - """序列行数:潜帧数 x 宽 x 高 / 1024。真正决定显存/算力的量,帧数和分辨率是同一笔预算。""" - latent_frames = (max(frames, 5) - 5) // 17 * 5 + 2 - return latent_frames * width * height / 1024 - -# 22G 卡的显存墙按 rows 算,不是单独卡 frames——实测边界(2026-08-20 long15s.sh): -# 832x480x124f rows=14430 稳定基准;448x256x362f rows=11984、576x320x362f rows=19260 都能跑 -# (后者峰值 14.5G,换入换出吃紧但没崩);640x384x362f rows=25680 OOM(撞到 20.6G)。 -# 20000 卡在 19260(能跑)和 25680(OOM)之间,留安全余量。 -# 支持环境变量覆盖:只用于临时拉高某一个 worker 做边界探测实验,默认值(生产用的这道 -# 安全线)不变——测完记得把起这个 worker 的进程重启回不带这个环境变量的状态。 -ROWS_LIMIT = int(os.environ.get("H3_ROWS_LIMIT", 20000)) - -# ---------------- 任务模型 ---------------- -class GenReq(BaseModel): - prompt: str = Field(min_length=1, max_length=2000) - # 上界取模型自己的默认档 1344x768。pipeline 本身不限分辨率,只把长宽向上取整到 32 的倍数, - # 真正的墙是这张 22G 卡:序列行数按 h*w/1024 每潜帧算,832x480 是 390 行/帧 x 37 帧 = 14430 行, - # 1344x768 是 1008 行/帧 = 37296 行,注意力是平方级,涨 2.6 倍行数就是涨约 6.7 倍算力。 - # 832x480 带三张参考图实测峰值 13.7G,往上哪一档撞墙没测过,超了就是这条任务 failed,不会拖死服务。 - width: int = Field(832, ge=64, le=1344) - height: int = Field(480, ge=64, le=768) - # 上界 362=15s(协议规格上限),是否真能生成看下面 _check_rows——832x480 撞了还是会被拒。 - frames: int = Field(124, ge=8, le=362) - steps: int = Field(4, ge=1, le=50) - turbo: bool = True - seed: int = Field(0, ge=0, le=2**31 - 1) - flow_shift: Optional[float] = None - # 首末帧条件(FL2VA)。给了首帧,这一段就从那张画面长出去——同一间屋子、同一个人。 - # 不给就是纯文生视频,屋子和人由模型自己编,跨条对不上。 - first_frame_url: Optional[str] = None - last_frame_url: Optional[str] = None - # 参考图(Ref2VA)。首帧只管这一段从哪开始,参考图全程参与注意力,管的是「中间别乱改」。 - # 张数没有硬上限,代价是序列变长:一张按 ref_image_short_edge 缩放后折成 token, - # 短边 480 时约 390 行,而目标视频本身才 14430 行。 - reference_image_urls: list[str] = [] - ref_image_short_edge: int = Field(480, ge=64, le=2048) - # CFG 引导强度 / 负面提示词。pipeline 自己默认 cfg_scale=1.0(约等于不引导)、 - # negative_prompt="",我们的代码之前从没传过,一直裸跑默认值。Optional,留空=不覆盖, - # 跟以前行为一样;蒸馏 LoRA(turbo)模型引导太强有时反而出伪影,调高前留意这点。 - cfg_scale: Optional[float] = Field(None, ge=0) - negative_prompt: Optional[str] = Field(None, max_length=2000) - - @model_validator(mode="after") - def _check_rows(self): - rows = _rows(self.width, self.height, self.frames) - if rows > ROWS_LIMIT: - raise ValueError(f"分辨率×帧数超出显存安全上限(rows={rows:.0f} > {ROWS_LIMIT});" - f"降低 frames 或分辨率,例如 448x256/576x320 可到 362 帧,832x480 建议 ≤124 帧") - return self - -class Job(BaseModel): - id: str - status: Literal["queued", "loading", "running", "done", "failed"] - req: GenReq - created_at: float - started_at: Optional[float] = None - finished_at: Optional[float] = None - step: int = 0 - total_steps: int = 0 - file: Optional[str] = None - size_bytes: Optional[int] = None - error: Optional[str] = None - peak_vram_gb: Optional[float] = None - -JOBS: dict[str, Job] = {} -Q: "queue.Queue[str]" = queue.Queue() -LOCK = threading.Lock() -STATE = {"model": "loading", "loaded_at": None, "gpu": os.environ.get("CUDA_VISIBLE_DEVICES", "?")} - -# ---------------- 任务记录落盘 ---------------- -# 之前 JOBS 只在内存里,进程重启(比如 h3-console 的弹性调度器切分区)就把这张表清空—— -# 视频文件在 outputs/ 没事,但 id→文件路径这层映射没了,前端/API 都查不到。改成每次状态变化 -# 都往 sqlite 写一份,进程起来时先读回内存。四个 GPU 各一个进程,按 GPU id 分开的文件, -# 不共享一份——共享一份要处理多进程并发写 sqlite 的锁竞争,没必要:反正一个进程只会在同一张 -# GPU 上起来,per-GPU 的文件天然不会有另一个进程来抢。 -JOBS_DB = BASE / f"jobs_gpu{os.environ.get('CUDA_VISIBLE_DEVICES', 'x')}.sqlite3" -_JOBS_CON = sqlite3.connect(JOBS_DB, check_same_thread=False) -_JOBS_CON.execute( - "CREATE TABLE IF NOT EXISTS jobs (id TEXT PRIMARY KEY, updated_at REAL NOT NULL, data TEXT NOT NULL)" -) -_JOBS_CON.commit() - -def _persist(job: Job): - with LOCK: - _JOBS_CON.execute( - "INSERT INTO jobs (id, updated_at, data) VALUES (?,?,?) " - "ON CONFLICT(id) DO UPDATE SET updated_at=excluded.updated_at, data=excluded.data", - (job.id, time.time(), job.model_dump_json()), - ) - _JOBS_CON.commit() - -def _load_jobs(): - """进程刚起来时把上次落盘的任务记录读回内存。in-flight 的状态没法恢复——Q 是空的, - GPU 上下文也是全新的,没有任何东西能"接着跑"。落盘时正好是 queued/running 的一律 - 改判为 failed 并写清原因,不然它会卡成一条永远显示"运行中"但没有 worker 会再碰的 - 死记录,比直接查不到这个 id 更容易让人误判成"卡住了,再等等"。""" - n = 0 - for (data,) in _JOBS_CON.execute("SELECT data FROM jobs"): - try: - j = Job.model_validate_json(data) - except Exception: - continue # 单条记录损坏不该挡住整个服务启动 - if j.status in ("queued", "running"): - j.status = "failed" - j.error = "进程重启导致这条任务的执行状态丢失(GPU 上下文和排队状态不落盘,无法恢复)" - j.finished_at = j.finished_at or time.time() - JOBS[j.id] = j - n += 1 - if n: - print(f"[api] 从磁盘恢复了 {n} 条历史任务记录({JOBS_DB.name})", flush=True) - -_load_jobs() - -# ---------------- 推理 worker ---------------- -# DiT、processor、Turbo LoRA 三样成套,跨分区混用会对不上层。 -# ref2v 的 Turbo LoRA 只有 v0.1,fl2v 那个是 v1.0 768p——这一项两边成色不同。 -PARTITIONS = { - "fl2va": {"dit": "minimax-h3-fl2va-nf4.safetensors", - "processor": "FL2VA/processor/", - "lora": "minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors"}, - # ref2v 的 bf16 版实测出 124 帧噪点:同尺寸同 seed,挂上它是噪点、摘掉就出画面, - # 换 flow_shift 无效(见 docs/H3 的二分表)。改用 comfyui 版试另一套键名。 - "ref2va": {"dit": "minimax-h3-ref2va-nf4.safetensors", - "processor": "Ref2VA/processor/", - "lora": "minimax_h3_ref2v_turbo_4step_v0.1_comfyui_bf16.safetensors"}, -} - -def _turbo_lora_config(): - from diffsynth.pipelines.minimax_h3_audio_video import ModelConfig - return ModelConfig(model_id="lightx2v/Minimax-h3-Turbo", - origin_file_pattern=PARTITIONS[PARTITION]["lora"]) - -def _build_pipe(): - from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig - part = PARTITIONS[PARTITION] - DT = torch.float32 # fp16 在 sm_75 上出全黑视频,见 README - # 常驻显存里留给权重多少 GB,剩下的全是激活。默认公式是按 832x480 调的(留 14G 给激活,实测峰值 13.7G)。 - # 分辨率往上走就得调低它:1280x720 在默认值下要 22.3G、卡只有 21.49G,差约 1G 撞 OOM; - # 调低后权重多从内存流几趟,慢一点,换来激活空间。用 H3_VRAM_LIMIT 覆盖。 - free = torch.cuda.mem_get_info("cuda")[0] / 1024**3 - vram_limit = float(os.environ.get("H3_VRAM_LIMIT", max(4.0, free - 14.0))) - offload_dt = "disk" if OFFLOAD == "disk" else DT - vc = dict(offload_dtype=offload_dt, offload_device=OFFLOAD, - onload_dtype=offload_dt, onload_device=OFFLOAD, - preparing_dtype=DT, preparing_device="cuda", - computation_dtype=DT, computation_device="cuda") - NF4 = "DiffSynth-Studio/MiniMax-H3-NF4" - pipe = MiniMaxH3Pipeline.from_pretrained( - torch_dtype=DT, device="cuda", - model_configs=[ModelConfig(model_id=NF4, origin_file_pattern=f, **vc) for f in - [part["dit"], "minimax-h3-text-encoder-nf4.safetensors", - "video_vae_nf4.safetensors", "audio_vae_nf4.safetensors"]], - processor_config=ModelConfig(model_id="MiniMax/MiniMax-H3", - origin_file_pattern=part["processor"]), - vram_limit=vram_limit) - pipe.load_lora(pipe.dit, _turbo_lora_config()) - return pipe - -def _fetch_image(url): - from PIL import Image - with urllib.request.urlopen(url, timeout=60) as resp: - return Image.open(io.BytesIO(resp.read())).convert("RGB") - -def _keyframes(req): - """取首末帧图,缩到出片尺寸。都没给就返回 (None, None),pipeline 退回纯文生视频。""" - from PIL import Image - images, indices = [], [] - for index, url in ((0, req.first_frame_url), (-1, req.last_frame_url)): - if url is None: - continue - images.append(_fetch_image(url).resize((req.width, req.height), Image.LANCZOS)) - indices.append(index) - return (images, indices) if images else (None, None) - -def _references(req): - """参考图按请求顺序取下来。尺寸交给 pipeline 按 ref_image_short_edge 归一,这里不动。""" - if not req.reference_image_urls: - return None - return [{"type": "image", "image": _fetch_image(url)} for url in req.reference_image_urls] - -def worker(): - from diffsynth.utils.data.audio_video import write_video_audio - import numpy as np - t0 = time.time() - pipe = _build_pipe() - STATE["model"] = "ready"; STATE["loaded_at"] = time.time() - print(f"[api] 模型就绪,耗时 {time.time()-t0:.0f}s", flush=True) - - while True: - jid = Q.get() - j = JOBS[jid] - try: - j.status = "running"; j.started_at = time.time() - j.total_steps = j.req.steps - _persist(j) - torch.cuda.reset_peak_memory_stats() - fs = j.req.flow_shift if j.req.flow_shift is not None else (6.0 if j.req.turbo else 12.0) - if not j.req.turbo: - pipe.clear_lora() - keyframes, keyframe_indices = _keyframes(j.req) - cfg_scale = j.req.cfg_scale if j.req.cfg_scale is not None else 1.0 - negative_prompt = j.req.negative_prompt if j.req.negative_prompt is not None else "" - video, audio = pipe(prompt=j.req.prompt, negative_prompt=negative_prompt, - height=j.req.height, width=j.req.width, - num_frames=j.req.frames, num_inference_steps=j.req.steps, - seed=j.req.seed, flow_shift=fs, cfg_scale=cfg_scale, - keyframes=keyframes, keyframe_indices=keyframe_indices, - references=_references(j.req), - ref_image_short_edge=j.req.ref_image_short_edge) - # 产物必须验过才算成功——全黑视频也能写出文件(踩过) - a = np.stack([np.asarray(f.convert("RGB"), dtype=np.float32) - for f in video[:: max(1, len(video)//8)]]) - if a.std() < 1.0: - raise RuntimeError(f"生成结果近乎纯色 (std={a.std():.3f}),判为失败") - if torch.is_tensor(audio) and not torch.isfinite(audio).all(): - raise RuntimeError("音频含非有限值,判为失败") - out = OUT / f"api_{jid}.mp4" - write_video_audio(video=video, audio=audio, output_path=str(out), - fps=24, audio_sample_rate=32000) - j.file = str(out); j.size_bytes = out.stat().st_size - j.peak_vram_gb = round(torch.cuda.max_memory_allocated()/1024**3, 2) - j.status = "done" - except Exception as e: - j.status = "failed"; j.error = f"{type(e).__name__}: {e}" - traceback.print_exc() - finally: - j.finished_at = time.time() - _persist(j) - if not j.req.turbo: # 下一个任务可能要 turbo,把 LoRA 挂回去 - try: - pipe.load_lora(pipe.dit, _turbo_lora_config()) - except Exception: - traceback.print_exc() - Q.task_done() - -# ---------------- HTTP ---------------- -app = FastAPI(title="MiniMax-H3 Video API", version="1.0") - -@app.on_event("startup") -def _start(): - threading.Thread(target=worker, daemon=True).start() - -@app.get("/health") -def health(): - return {"status": "ok" if STATE["model"] == "ready" else "loading", - "model": STATE["model"], "gpu": STATE["gpu"], "partition": PARTITION, - "offload": OFFLOAD, "queued": Q.qsize(), - "running": sum(1 for j in JOBS.values() if j.status == "running")} - -@app.post("/v1/videos", status_code=202) -def create(req: GenReq): - if req.turbo and req.steps > 8: - raise HTTPException(400, "turbo 模式步数应 ≤8(LoRA 是 4 步蒸馏的);要多步请传 turbo=false") - jid = uuid.uuid4().hex[:12] - with LOCK: - JOBS[jid] = Job(id=jid, status="queued", req=req, created_at=time.time()) - _persist(JOBS[jid]) # LOCK 外面调用 —— _persist 自己会拿 LOCK,Lock 不可重入,嵌套会死锁 - Q.put(jid) - # 耗时的自变量是序列行数(潜帧数 x 宽 x 高 / 1024),不是分辨率——分辨率和帧数是同一笔预算。 - # 基准点 832x480x124f = 14430 行,4 步实测 692 秒 = 4 x 132 + 163 - #(163 是文本编码 + 参考图编码 + VAE 解码,它也跟帧数走,所以一起按行数缩放)。 - # 回代:1280x736x56f(15640 行)估 749 / 实测 736;832x480x22f(2730 行)估 131 / 实测 96。 - # 注意力是平方级,行数越大这个线性估计偏得越小。 - rows = _rows(req.width, req.height, req.frames) - est = round((req.steps * 132 + 163) * rows / 14430) - return {"id": jid, "status": "queued", "queue_position": Q.qsize(), - "eta_seconds": est, "poll": f"/v1/videos/{jid}"} - -@app.get("/v1/videos/{jid}") -def get(jid: str): - j = JOBS.get(jid) - if not j: raise HTTPException(404, "无此任务") - d = j.model_dump() - if j.status == "running" and j.started_at: - d["elapsed_seconds"] = round(time.time() - j.started_at) - if j.status == "done": - d["download"] = f"/v1/videos/{jid}/file" - return d - -@app.get("/v1/videos/{jid}/file") -def download(jid: str): - j = JOBS.get(jid) - if not j: raise HTTPException(404, "无此任务") - if j.status != "done": raise HTTPException(409, f"任务尚未完成(当前 {j.status})") - return FileResponse(j.file, media_type="video/mp4", filename=f"{jid}.mp4") - -@app.get("/v1/videos") -def listjobs(limit: int = 50): - js = sorted(JOBS.values(), key=lambda x: x.created_at, reverse=True)[:limit] - return {"jobs": [{"id": j.id, "status": j.status, "created_at": j.created_at, - "size_bytes": j.size_bytes, "error": j.error} for j in js]} diff --git a/minimax-h3/burst-test.py b/minimax-h3/burst-test.py deleted file mode 100644 index 71e989a..0000000 --- a/minimax-h3/burst-test.py +++ /dev/null @@ -1,57 +0,0 @@ -"""压并发:12 条同时投给调度层,看三件事。 - -1. 派发会不会打偏——调度层是「读 health 挑最闲的」,同时提交时几个请求可能读到同一份快照。 - 顺序提交测不出这个,必须真并发。 -2. queue_position 和 eta_seconds 在排队时说了什么。 -3. 队列有没有上限、超了会怎样。 -""" -import json, time, urllib.request -from collections import Counter -from concurrent.futures import ThreadPoolExecutor - -GW = "http://127.0.0.1:8000" -N = 12 -SPEC = {"prompt": "一只橘猫趴在洒满阳光的窗台上,慢慢眨眼", "frames": 22, "steps": 4, "turbo": True} - - -def call(path, data=None, timeout=60): - req = urllib.request.Request(GW + path, data=data, - headers={"Content-Type": "application/json"} if data else {}) - with urllib.request.urlopen(req, timeout=timeout) as r: - return json.load(r) - - -def submit(i): - t = time.time() - job = call("/v1/videos", json.dumps(dict(SPEC, seed=100 + i)).encode()) - return i, job, time.time() - t - - -t0 = time.time() -with ThreadPoolExecutor(max_workers=N) as pool: - results = sorted(pool.map(submit, range(N))) -print(f"12 条并发提交耗时 {time.time() - t0:.2f}s\n") - -for i, job, dt in results: - print(f" #{i:<2} {job['backend'][-4:]} queue_position={job['queue_position']} " - f"eta={job['eta_seconds']}s ({dt:.2f}s)") - -spread = Counter(job["backend"][-4:] for _, job, _ in results) -print(f"\n派发分布: {dict(sorted(spread.items()))} 理想是每个 {N // 4} 条") - -ids = [job["id"] for _, job, _ in results] -print("\n--- 轮询") -while True: - time.sleep(30) - states = [call(f"/v1/videos/{jid}") for jid in ids] - c = Counter(s["status"] for s in states) - print(f" {dict(c)}", flush=True) - if all(s["status"] in ("done", "failed") for s in states): - break - -total = time.time() - t0 -print(f"\n12 条全部完成,墙钟 {total:.0f}s") -for s in sorted(states, key=lambda s: s["created_at"]): - took = s["finished_at"] - s["started_at"] - wait = s["started_at"] - s["created_at"] - print(f" {s['id'][:6]} {s['status']} 排队{wait:5.0f}s 执行{took:4.0f}s {s['backend'][-4:]}") diff --git a/minimax-h3/concurrency-test.py b/minimax-h3/concurrency-test.py deleted file mode 100644 index 15ee5ec..0000000 --- a/minimax-h3/concurrency-test.py +++ /dev/null @@ -1,44 +0,0 @@ -"""四张卡同时跑同一条任务,量并发缩水。 - -各端口和自己的单跑基线比:cpu 模式 692s,disk 模式 767s。 -任务规格从 8011 上那条已完成的 826db7b3f08e 原样取,保证四条完全一致。 -""" -import json, time, urllib.request - -# 8010/8011 是三小时前起的,跑的还是加 H3_OFFLOAD 之前的 api.py,/health 里没有 offload 字段, -# 所以模式和基线都写在这里。 -MODE = {8010: "cpu", 8011: "cpu", 8012: "disk", 8013: "disk"} -BASELINE = {"cpu": 692, "disk": 767} - - -def call(port, path, body=None): - url = f"http://127.0.0.1:{port}{path}" - req = urllib.request.Request(url, data=body, - headers={"Content-Type": "application/json"} if body else {}) - with urllib.request.urlopen(req, timeout=60) as r: - return json.load(r) - - -spec = json.dumps(call(8011, "/v1/videos/826db7b3f08e")["req"]).encode() - -jobs = {} -for port, mode in MODE.items(): - jobs[port] = (call(port, "/v1/videos", spec)["id"], mode) - print(f"{port} ({mode}) -> {jobs[port][0]}", flush=True) - -print("--- 四条已同时投出,开始轮询", flush=True) -pending = dict(jobs) -while pending: - time.sleep(60) - for port in list(pending): - jid, mode = pending[port] - j = call(port, f"/v1/videos/{jid}") - if j["status"] in ("done", "failed"): - took = j["finished_at"] - j["started_at"] - base = BASELINE[mode] - print(f"{port} ({mode}) {j['status']} {took:.0f}s 基线{base}s " - f"缩水{(took/base-1)*100:+.1f}% 峰值显存{j.get('peak_vram_gb')}G " - f"{j.get('size_bytes')}字节", flush=True) - del pending[port] - else: - print(f" {port} {j['status']} {j.get('elapsed_seconds', 0)}s", flush=True) diff --git a/minimax-h3/direct-backend-test.py b/minimax-h3/direct-backend-test.py deleted file mode 100644 index 267de73..0000000 --- a/minimax-h3/direct-backend-test.py +++ /dev/null @@ -1,35 +0,0 @@ -"""验直连后端端口这条老路还通不通——调度层是加在旁边的,不该动到它。 - -走的是 API.md 里那段完整调用示例的形状:POST 拿 id → 轮询 → 下载。 -""" -import json, time, urllib.request - -API = "http://127.0.0.1:8010" -SPEC = {"prompt": "一只橘猫趴在洒满阳光的窗台上,慢慢眨眼", "frames": 22, "steps": 4, - "turbo": True, "seed": 99} - - -def call(path, data=None, timeout=60): - req = urllib.request.Request(API + path, data=data, - headers={"Content-Type": "application/json"} if data else {}) - with urllib.request.urlopen(req, timeout=timeout) as r: - return json.load(r) - - -print("health:", call("/health")) -job = call("/v1/videos", json.dumps(SPEC).encode()) -print("提交:", job) - -while True: - time.sleep(20) - j = call(f"/v1/videos/{job['id']}") - print(" ", j["status"], j.get("elapsed_seconds", 0), "s", flush=True) - if j["status"] in ("done", "failed"): - break - -if j["status"] == "failed": - raise SystemExit("失败: " + j["error"]) - -with urllib.request.urlopen(f"{API}/v1/videos/{job['id']}/file", timeout=300) as r: - data = r.read() -print(f"下载 {len(data)} 字节,后端记录 {j['size_bytes']},一致={len(data) == j['size_bytes']}") diff --git a/minimax-h3/gateway-run.sh b/minimax-h3/gateway-run.sh deleted file mode 100755 index f0253a7..0000000 --- a/minimax-h3/gateway-run.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env bash -# 起调度层。用法: ./gateway-run.sh [PORT] -# 后端列表用 H3_BACKENDS 覆盖,默认 8010,8011,8012,8013。 -# 这一层不碰模型也不占显存,秒起秒停,随便重启。 -set -uo pipefail -B=/data/models/minimax-h3 -PORT="${1:-8000}" -export PYTHONUNBUFFERED=1 -cd "$B" -echo "[gateway] PORT=$PORT 后端=${H3_BACKENDS:-8010,8011,8012,8013}" -exec "$B/venv/bin/python" -m uvicorn gateway:app --host 0.0.0.0 --port "$PORT" --workers 1 diff --git a/minimax-h3/gateway-test.py b/minimax-h3/gateway-test.py deleted file mode 100644 index a1ff5fc..0000000 --- a/minimax-h3/gateway-test.py +++ /dev/null @@ -1,52 +0,0 @@ -"""验调度层:往 :8000 投 5 条(比后端多一条),看是不是每卡一条、多出来那条排队。 - -用短任务(22 帧)只是为了快,路由逻辑和长任务完全一样。 -""" -import json, time, urllib.request - -GW = "http://127.0.0.1:8000" -SPEC = {"prompt": "一只橘猫趴在洒满阳光的窗台上,慢慢眨眼,尾巴轻轻摆动", - "width": 832, "height": 480, "frames": 22, "steps": 4, "turbo": True, "seed": 7} - - -def call(path, data=None, timeout=60): - req = urllib.request.Request(GW + path, data=data, - headers={"Content-Type": "application/json"} if data else {}) - with urllib.request.urlopen(req, timeout=timeout) as r: - return json.load(r) - - -ids = [] -for i in range(5): - job = call("/v1/videos", json.dumps(dict(SPEC, seed=7 + i)).encode()) - ids.append(job["id"]) - print(f"第{i+1}条 -> {job['backend']} id={job['id']} 队列位置={job['queue_position']}", flush=True) - -print("\n--- 派发结果") -used = {} -for jid in ids: - b = call(f"/v1/videos/{jid}")["backend"] - used.setdefault(b, []).append(jid) -for b, js in sorted(used.items()): - print(f"{b}: {len(js)} 条 {js}") -print(f"用上了 {len(used)}/4 个后端") - -print("\n--- 轮询到全部完成") -while True: - time.sleep(30) - states = [call(f"/v1/videos/{jid}") for jid in ids] - print(" " + " ".join(f"{s['id'][:6]}:{s['status']}" for s in states), flush=True) - if all(s["status"] in ("done", "failed") for s in states): - break - -print("\n--- 结果") -for s in states: - took = (s["finished_at"] - s["started_at"]) if s.get("started_at") else 0 - print(f"{s['id']} {s['status']} {took:.0f}s {s.get('size_bytes')}字节 {s['backend']}") - -ok = [s for s in states if s["status"] == "done"] -if ok: - with urllib.request.urlopen(f"{GW}/v1/videos/{ok[0]['id']}/file", timeout=300) as r: - data = r.read() - print(f"\n经调度层下载 {ok[0]['id']}: {len(data)} 字节 " - f"(后端记录 {ok[0]['size_bytes']}) 一致={len(data) == ok[0]['size_bytes']}") diff --git a/minimax-h3/gateway.py b/minimax-h3/gateway.py deleted file mode 100644 index 9a1b543..0000000 --- a/minimax-h3/gateway.py +++ /dev/null @@ -1,128 +0,0 @@ -"""四个 H3 实例前面的调度层。 - -api.py 是单 worker 串行,一个进程独占一张卡,所以并发的唯一办法是往不同端口投。 -这一层把「投哪个端口」收掉:对外只有一个地址,接口和 api.py 逐字相同, -调用方原来怎么写现在还怎么写,只把端口换成 8000。 - -自己不存任何状态。任务 id 归哪个后端,问一遍就知道——四个后端一次扫描的代价可以忽略, -换来的是这个进程随时能重启,不丢任何东西(api.py 的 JOBS 本来也在内存里, -调度层再存一份 id→后端 的映射,就是第二个会丢的地方)。 -""" -import os, json, threading, urllib.request, urllib.error -from concurrent.futures import ThreadPoolExecutor - -from fastapi import FastAPI, HTTPException -from fastapi.responses import StreamingResponse - -BACKENDS = [f"http://127.0.0.1:{port.strip()}" for port in - os.environ.get("H3_BACKENDS", "8010,8011,8012,8013").split(",")] -POOL = ThreadPoolExecutor(max_workers=16) -# 最闲的那个后端已经压了这么多条时,再来的提交直接 429 顶回去。 -# 没有这个上限的话队列是无界的:投 1000 条全部返回 202,最后一条两天后才开始跑, -# 调用方却收到「已接受」。宁可当场说满了。默认 4 条 ≈ 45 分钟积压。 -MAX_QUEUE = int(os.environ.get("H3_MAX_QUEUE", "4")) -# 选后端是「读一遍各家队列深度,再往最闲的那个投」。这中间不能插进另一个提交, -# 否则同时来的请求会读到同一份快照、一起挑中同一个后端,全堆在一张卡上。 -# 锁只圈住选 + 投这一段(约 30 毫秒),任务本身要跑十几分钟,序列化的代价可以忽略。 -PICK = threading.Lock() - - -def fetch(url, data=None, timeout=30): - req = urllib.request.Request(url, data=data, - headers={"Content-Type": "application/json"} if data else {}) - with urllib.request.urlopen(req, timeout=timeout) as resp: - return json.load(resp) - - -def health_all(): - def one(backend): - try: - return dict(fetch(backend + "/health", timeout=5), backend=backend) - except Exception as e: - return {"backend": backend, "status": "down", "error": f"{type(e).__name__}: {e}"} - return list(POOL.map(one, BACKENDS)) - - -def find_owner(jid): - """任务归谁,挨个问。后端对陌生 id 返回 404,urlopen 抛异常,接住当没有。""" - def one(backend): - try: - return backend, fetch(f"{backend}/v1/videos/{jid}", timeout=5) - except Exception: - return backend, None - for backend, job in POOL.map(one, BACKENDS): - if job is not None: - return backend, job - raise HTTPException(404, "无此任务") - - -app = FastAPI(title="MiniMax-H3 Gateway", version="1.0") - - -@app.get("/health") -def health(): - backends = health_all() - ready = [b for b in backends if b.get("status") == "ok"] - return {"status": "ok" if ready else "unavailable", - "ready": len(ready), "total": len(backends), - "queued": sum(b.get("queued", 0) for b in ready), - "running": sum(b.get("running", 0) for b in ready), - "backends": backends} - - -# 同步 def,让 FastAPI 把它丢进线程池。写成 async def 会让下面这些阻塞的 HTTP 调用 -# 卡住事件循环——那样确实也能歪打正着地把提交排成队,但任何一个后端卡住, -# 5 秒超时就会连轮询一起堵死。要串行就用锁明说。 -@app.post("/v1/videos", status_code=202) -def create(req: dict): - # 给了首末帧就只能走 fl2va;其余都走 ref2va——ref2va 不给参考图就退回纯文生视频, - # 所以「没有首末帧」这一类不需要再细分。 - want = "fl2va" if (req.get("first_frame_url") or req.get("last_frame_url")) else "ref2va" - with PICK: - candidates = [b for b in health_all() - if b.get("status") == "ok" and b.get("partition") == want] - if not candidates: - raise HTTPException(503, f"没有就绪的 {want} 实例") - # 排队最短的那个。queued 是还在队列里的,running 是正在跑的那条,两个都要算。 - pick = min(candidates, key=lambda b: b["queued"] + b["running"]) - ahead = pick["queued"] + pick["running"] - if ahead >= MAX_QUEUE: - raise HTTPException(429, f"队列满:{len(candidates)} 个 {want} 实例每个都压着 " - f"{ahead} 条(上限 {MAX_QUEUE})。等一会儿再投," - f"或调大 H3_MAX_QUEUE") - try: - job = fetch(pick["backend"] + "/v1/videos", data=json.dumps(req).encode()) - except urllib.error.HTTPError as e: - raise HTTPException(e.code, e.read().decode()) - # eta_seconds 是这一条自己的执行时间,不含排队。前面还压着 ahead 条, - # 真正的等待还要加上它们——它们规格可能不同,这里不替调用方瞎乘。 - return dict(job, backend=pick["backend"], queue_ahead=ahead, poll=f"/v1/videos/{job['id']}") - - -@app.get("/v1/videos/{jid}") -def get(jid: str): - backend, job = find_owner(jid) - return dict(job, backend=backend) - - -@app.get("/v1/videos/{jid}/file") -def download(jid: str): - backend, job = find_owner(jid) - if job["status"] != "done": - raise HTTPException(409, f"任务尚未完成(当前 {job['status']})") - resp = urllib.request.urlopen(f"{backend}/v1/videos/{jid}/file", timeout=300) - return StreamingResponse(resp, media_type="video/mp4", - headers={"Content-Disposition": f'attachment; filename="{jid}.mp4"'}) - - -@app.get("/v1/videos") -def listjobs(limit: int = 50): - def one(backend): - try: - return [dict(j, backend=backend) - for j in fetch(f"{backend}/v1/videos?limit={limit}", timeout=5)["jobs"]] - except Exception: - return [] - jobs = [job for part in POOL.map(one, BACKENDS) for job in part] - jobs.sort(key=lambda j: j["created_at"], reverse=True) - return {"jobs": jobs[:limit]} diff --git a/minimax-h3/long15s.sh b/minimax-h3/long15s.sh deleted file mode 100755 index 8a23033..0000000 --- a/minimax-h3/long15s.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash -# 15 秒(362 帧 = 17*21+5)可行性验证。低分辨率先验证长时长通路,再考虑全分辨率。 -# 用法: ./long15s.sh [额外参数...] -set -uo pipefail -cd /data/models/minimax-h3 -P="$(cat prompt.txt)" -GPU="$1"; F="$2"; W="$3"; H="$4"; shift 4 -./run.sh "$GPU" --frames "$F" --width "$W" --height "$H" --prompt "$P" --seed 42 "$@" diff --git a/minimax-h3/pin-cache.sh b/minimax-h3/pin-cache.sh deleted file mode 100755 index 3392302..0000000 --- a/minimax-h3/pin-cache.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/bash -# 把 H3 权重的页缓存钉住:告诉内核 user.slice 下的 40 G 不许回收。 -# 不钉的话,别的程序一申请大块内存,权重缓存就被丢掉, -# 之后每次前向都要回机械盘 /dev/sdb 读 34.4 G,单条耗时会成倍涨。 -# -# 重跑安全。撤销:sudo rm /etc/systemd/system/user-.slice.d/h3-cache.conf && sudo systemctl daemon-reload -set -e - -echo "需要 admin 密码(sudo 用的是你自己的密码,不是 root 的)" - -sudo mkdir -p /etc/systemd/system/user-.slice.d -printf '[Slice]\nMemoryMin=40G\n' | sudo tee /etc/systemd/system/user-.slice.d/h3-cache.conf > /dev/null -sudo systemctl daemon-reload -sudo systemctl set-property user.slice MemoryMin=40G -sudo systemctl set-property "user-$(id -u).slice" MemoryMin=40G - -echo -echo "=== 生效情况(两行都应该是 42949672960,即 40 G)" -grep -H . /sys/fs/cgroup/user.slice/memory.min -grep -H . "/sys/fs/cgroup/user.slice/user-$(id -u).slice/memory.min" - -echo -echo "=== 当前被保护的量" -grep -H . /sys/fs/cgroup/user.slice/memory.current diff --git a/minimax-h3/prompt.txt b/minimax-h3/prompt.txt deleted file mode 100644 index 7a5977a..0000000 --- a/minimax-h3/prompt.txt +++ /dev/null @@ -1 +0,0 @@ -清晨的中式庭院,一位穿浅蓝色棉麻衬衫的年轻女子坐在木质长廊上,手里捧着一杯冒着热气的茶。她微笑着说 "Good morning, the tea smells wonderful today." 阳光透过竹叶洒在她脸上,微风吹动她的头发,远处有清脆的鸟鸣声。 diff --git a/minimax-h3/realrun.sh b/minimax-h3/realrun.sh deleted file mode 100755 index a2b77b9..0000000 --- a/minimax-h3/realrun.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash -# 真实测试:从文件读 prompt,避开多层 shell 引号 -set -uo pipefail -cd /data/models/minimax-h3 -P="$(cat prompt.txt)" -echo "[prompt] ${#P} 字符: ${P:0:40}..." -case "$1" in - turbo) ./run.sh 1 --prompt "$P" --seed 42 ;; - full50) ./run.sh 2 --no-turbo --steps 50 --prompt "$P" --seed 42 ;; -esac diff --git a/minimax-h3/restart-8010.sh b/minimax-h3/restart-8010.sh deleted file mode 100755 index 86190cc..0000000 --- a/minimax-h3/restart-8010.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env bash -# 重启 8010 的 ref2va 实例,把常驻权重压到 4G 换激活空间,验 1280x720 能不能跑。 -set -uo pipefail -cd /data/models/minimax-h3 -PID=$(ss -lptn "sport = :8010" | grep -o "pid=[0-9]*" | cut -d= -f2 | sort -u) -[ -n "$PID" ] && kill "$PID" -sleep 8 -export H3_VRAM_LIMIT=4 -setsid nohup ./api-run.sh 1 8010 ref2va > logs/api-8010.log 2>&1 < /dev/null & -sleep 12 -pgrep -af uvicorn diff --git a/minimax-h3/run-verify.sh b/minimax-h3/run-verify.sh deleted file mode 100755 index 3da962e..0000000 --- a/minimax-h3/run-verify.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash -# 把调度层临时换成 H3_MAX_QUEUE=1 跑一遍验证,跑完恢复默认。 -set -uo pipefail -cd /data/models/minimax-h3 - -restart_gateway() { - PID=$(ss -lptn "sport = :8000" | grep -o "pid=[0-9]*" | cut -d= -f2 | sort -u) - [ -n "$PID" ] && { kill $PID; sleep 3; } - setsid nohup ./gateway-run.sh 8000 > logs/gateway.log 2>&1 < /dev/null & - sleep 5 -} - -export H3_MAX_QUEUE=1 -restart_gateway -echo "调度层已起,H3_MAX_QUEUE=1" -./venv/bin/python verify-fixes.py - -echo -echo "=== 恢复默认 H3_MAX_QUEUE" -unset H3_MAX_QUEUE -restart_gateway -curl -s http://127.0.0.1:8000/health | grep -o '"ready":[0-9]*' diff --git a/minimax-h3/run.sh b/minimax-h3/run.sh deleted file mode 100755 index 8633631..0000000 --- a/minimax-h3/run.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash -# MiniMax-H3 FL2VA NF4 launcher. usage: ./run.sh [args for t2va.py ...] -# ./run.sh 1 # turbo 4-step, 480x832x124f -# ./run.sh 1 --no-turbo --steps 50 # full quality -# ./run.sh 2 --prompt "..." --seed 7 -set -euo pipefail -B=/data/models/minimax-h3 -GPU="${1:-1}"; shift || true - -export CUDA_VISIBLE_DEVICES="$GPU" -export DIFFSYNTH_ATTENTION_IMPLEMENTATION=torch # sm_75: no flash/sage; pin instead of auto-picking xformers -export DIFFSYNTH_MODEL_BASE_PATH="$B/models" -export MODELSCOPE_CACHE="$B/.mscache" -export PYTHONUNBUFFERED=1 -# 22GB 卡上激活与权重贴着上限,碎片会直接压垮它(实测 reserved-but-unallocated 达 2.49GB) -export PYTORCH_ALLOC_CONF=expandable_segments:True -# NOTE: deliberately NOT setting PYTHONNOUSERSITE -- the venv's site-packages already -# precedes ~/.local in sys.path, so our bitsandbytes 0.50.1 shadows the broken 0.45.1 there. - -# GPU0/1 sit on NUMA0, GPU2/3 on NUMA1 -- keep the CPU-offloaded weights on the near node. -case "$GPU" in 0|1) NODE=0 ;; 2|3) NODE=1 ;; *) NODE="" ;; esac -BIND=(); if [ -n "$NODE" ] && command -v numactl >/dev/null 2>&1; then BIND=(numactl --cpunodebind="$NODE" --membind="$NODE"); fi - -LOG="$B/logs/gpu${GPU}_$(date +%Y%m%d-%H%M%S).log" -echo "[run] GPU=$GPU numa=${NODE:-none} log=$LOG" -"${BIND[@]}" "$B/venv/bin/python" "$B/scripts/t2va.py" "$@" 2>&1 | tee "$LOG" diff --git a/minimax-h3/scripts/diag-nan.py b/minimax-h3/scripts/diag-nan.py deleted file mode 100644 index 280b796..0000000 --- a/minimax-h3/scripts/diag-nan.py +++ /dev/null @@ -1,80 +0,0 @@ -"""定位 NaN 的产生位置:对 dit / text_encoder 挂 forward hook, -找出第一个『输入有限、输出非有限』的模块。""" -import os, sys, time, torch -sys.argv = [sys.argv[0]] -BASE = "/data/models/minimax-h3" -os.environ.setdefault("DIFFSYNTH_ATTENTION_IMPLEMENTATION", "torch") -os.environ.setdefault("DIFFSYNTH_MODEL_BASE_PATH", f"{BASE}/models") -os.environ.setdefault("MODELSCOPE_CACHE", f"{BASE}/.mscache") - -from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig - -DTYPE = torch.float16 -free_gb = torch.cuda.mem_get_info("cuda")[0] / 1024**3 -vram_limit = max(6.0, free_gb - 2.0) -print(f"[env] free={free_gb:.1f}G vram_limit={vram_limit:.1f}G", flush=True) - -vc = dict(offload_dtype=DTYPE, offload_device="cpu", onload_dtype=DTYPE, onload_device="cpu", - preparing_dtype=DTYPE, preparing_device="cuda", - computation_dtype=DTYPE, computation_device="cuda") -NF4 = "DiffSynth-Studio/MiniMax-H3-NF4" -t0 = time.time() -pipe = MiniMaxH3Pipeline.from_pretrained( - torch_dtype=DTYPE, device="cuda", - model_configs=[ - ModelConfig(model_id=NF4, origin_file_pattern="minimax-h3-fl2va-nf4.safetensors", **vc), - ModelConfig(model_id=NF4, origin_file_pattern="minimax-h3-text-encoder-nf4.safetensors", **vc), - ModelConfig(model_id=NF4, origin_file_pattern="video_vae_nf4.safetensors", **vc), - ModelConfig(model_id=NF4, origin_file_pattern="audio_vae_nf4.safetensors", **vc), - ], - processor_config=ModelConfig(model_id="MiniMax/MiniMax-H3", origin_file_pattern="FL2VA/processor/"), - vram_limit=vram_limit) -print(f"[load] {time.time()-t0:.0f}s", flush=True) - -pipe.load_lora(pipe.dit, ModelConfig(model_id="lightx2v/Minimax-h3-Turbo", - origin_file_pattern="minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors")) - -def finite(x): - if torch.is_tensor(x): - return bool(torch.isfinite(x).all()), (float(x.abs().max()) if x.numel() and x.is_floating_point() else None) - return True, None - -hits = [] # 第一个坏掉的模块 -seen = set() -def mk(name): - def hook(mod, inp, out): - if name in seen: return - ok_in = all(finite(t)[0] for t in inp if torch.is_tensor(t)) - outs = out if isinstance(out, (tuple, list)) else (out,) - for o in outs: - ok, mx = finite(o) - if not ok: - seen.add(name) - hits.append((name, type(mod).__name__, ok_in, mx)) - return - return hook - -handles = [] -for tag, mod in (("dit", pipe.dit), ("txt", pipe.text_encoder)): - for n, m in mod.named_modules(): - if n: # 跳过根 - handles.append(m.register_forward_hook(mk(f"{tag}.{n}"))) -print(f"[hook] {len(handles)} 个模块已挂钩", flush=True) - -video, audio = pipe(prompt="一只橘猫在窗台上打哈欠,阳光洒进来", - height=480, width=832, num_frames=124, - num_inference_steps=4, seed=42, flow_shift=6.0) -for h in handles: h.remove() - -print("\n===== 结果 =====", flush=True) -for t, nm in (("video", video), ("audio", audio)): - if torch.is_tensor(nm): - print(f"{t}: shape={tuple(nm.shape)} dtype={nm.dtype} finite={bool(torch.isfinite(nm).all())} " - f"absmax={float(nm.abs().max()) if nm.is_floating_point() else 'n/a'}") - else: - print(f"{t}: type={type(nm)}") -print(f"\n第一批非有限输出的模块(共 {len(hits)},只列前 15):") -for n, cls, ok_in, mx in hits[:15]: - print(f" {n} [{cls}] 输入有限={ok_in} 输出absmax={mx}") -if not hits: - print(" 无 —— dit/text_encoder 内部全程有限,问题在 VAE 解码或后处理") diff --git a/minimax-h3/scripts/diag3.py b/minimax-h3/scripts/diag3.py deleted file mode 100644 index 232d24d..0000000 --- a/minimax-h3/scripts/diag3.py +++ /dev/null @@ -1,95 +0,0 @@ -"""定位 NaN 的产生位置:对 dit / text_encoder 挂 forward hook, -找出第一个『输入有限、输出非有限』的模块。""" -import os, sys, time, torch -sys.argv = [sys.argv[0]] -BASE = "/data/models/minimax-h3" -os.environ.setdefault("DIFFSYNTH_ATTENTION_IMPLEMENTATION", "torch") -os.environ.setdefault("DIFFSYNTH_MODEL_BASE_PATH", f"{BASE}/models") -os.environ.setdefault("MODELSCOPE_CACHE", f"{BASE}/.mscache") - -from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig - -DTYPE = torch.float16 -free_gb = torch.cuda.mem_get_info("cuda")[0] / 1024**3 -vram_limit = max(6.0, free_gb - 2.0) -print(f"[env] free={free_gb:.1f}G vram_limit={vram_limit:.1f}G", flush=True) - -vc = dict(offload_dtype=DTYPE, offload_device="cpu", onload_dtype=DTYPE, onload_device="cpu", - preparing_dtype=DTYPE, preparing_device="cuda", - computation_dtype=DTYPE, computation_device="cuda") -NF4 = "DiffSynth-Studio/MiniMax-H3-NF4" -t0 = time.time() -pipe = MiniMaxH3Pipeline.from_pretrained( - torch_dtype=DTYPE, device="cuda", - model_configs=[ - ModelConfig(model_id=NF4, origin_file_pattern="minimax-h3-fl2va-nf4.safetensors", **vc), - ModelConfig(model_id=NF4, origin_file_pattern="minimax-h3-text-encoder-nf4.safetensors", **vc), - ModelConfig(model_id=NF4, origin_file_pattern="video_vae_nf4.safetensors", **vc), - ModelConfig(model_id=NF4, origin_file_pattern="audio_vae_nf4.safetensors", **vc), - ], - processor_config=ModelConfig(model_id="MiniMax/MiniMax-H3", origin_file_pattern="FL2VA/processor/"), - vram_limit=vram_limit) -print(f"[load] {time.time()-t0:.0f}s", flush=True) - -pipe.load_lora(pipe.dit, ModelConfig(model_id="lightx2v/Minimax-h3-Turbo", - origin_file_pattern="minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors")) - -# 与 t2va.py 一致的修复:整条路径(含 LoRA)抬到 fp32 -def _fp32_all(mod): - mod.computation_dtype = torch.float32 - orig = mod.forward - def fwd(x, *a, **kw): - return orig(x.float(), *a, **kw).to(x.dtype) - mod.forward = fwd -_fp32_all(pipe.dit.condition_proj) -print("[fix ] condition_proj 全路径 -> fp32", flush=True) - -def finite(x): - if torch.is_tensor(x): - return bool(torch.isfinite(x).all()), (float(x.abs().max()) if x.numel() and x.is_floating_point() else None) - return True, None - -hits = [] # 第一个坏掉的模块 -seen = set() -def mk(name): - def hook(mod, inp, out): - if name in seen: return - ok_in = all(finite(t)[0] for t in inp if torch.is_tensor(t)) - outs = out if isinstance(out, (tuple, list)) else (out,) - for o in outs: - ok, mx = finite(o) - if not ok: - seen.add(name) - ins=[float(t.abs().max()) for t in inp if torch.is_tensor(t) and t.is_floating_point() and t.numel()] - hits.append((name, type(mod).__name__, ok_in, mx, max(ins) if ins else None)) - return - return hook - -handles = [] -for tag, mod in (("dit", pipe.dit), ("txt", pipe.text_encoder)): - for n, m in mod.named_modules(): - if n: # 跳过根 - handles.append(m.register_forward_hook(mk(f"{tag}.{n}"))) -print(f"[hook] {len(handles)} 个模块已挂钩", flush=True) - -video, audio = pipe(prompt="一只橘猫在窗台上打哈欠,阳光洒进来", - height=480, width=832, num_frames=124, - num_inference_steps=1, seed=42, flow_shift=6.0) -for h in handles: h.remove() - -print("\n===== 结果 =====", flush=True) -for t, nm in (("video", video), ("audio", audio)): - if torch.is_tensor(nm): - print(f"{t}: shape={tuple(nm.shape)} dtype={nm.dtype} finite={bool(torch.isfinite(nm).all())} " - f"absmax={float(nm.abs().max()) if nm.is_floating_point() else 'n/a'}") - else: - print(f"{t}: type={type(nm)}") -print(f"\n第一批非有限输出的模块(共 {len(hits)},只列前 15):") -print(">>> 真源头(输入有限=True):") -for h in hits: - if h[2]: print(f" ★ {h[0]} [{h[1]}] 输入absmax={h[4]} 输出absmax={h[3]}") -print(">>> 下游受害者(前 5):") -for h in [x for x in hits if not x[2]][:5]: - print(f" {h[0]} [{h[1]}]") -if not hits: - print(" 无 —— dit/text_encoder 内部全程有限,问题在 VAE 解码或后处理") diff --git a/minimax-h3/scripts/diag4.py b/minimax-h3/scripts/diag4.py deleted file mode 100644 index 6106660..0000000 --- a/minimax-h3/scripts/diag4.py +++ /dev/null @@ -1,91 +0,0 @@ -"""用与实际失败运行完全一致的配置定位 NaN:同 prompt、同修复、同显存参数。""" -import os, time, torch -BASE="/data/models/minimax-h3" -os.environ.setdefault("DIFFSYNTH_ATTENTION_IMPLEMENTATION","torch") -os.environ.setdefault("DIFFSYNTH_MODEL_BASE_PATH", f"{BASE}/models") -os.environ.setdefault("MODELSCOPE_CACHE", f"{BASE}/.mscache") -os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF","expandable_segments:True") -from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig - -PROMPT = ("A girl is very happy, she is speaking in english: " - "“I enjoy working with Diffsynth-Studio, it's a perfect framework.”") -DT=torch.float16 -free=torch.cuda.mem_get_info("cuda")[0]/1024**3 -vram_limit=max(6.0, free-5.0) # 与 --vram-reserve 5 一致 -print(f"[env] free={free:.1f}G vram_limit={vram_limit:.1f}G", flush=True) -vc=dict(offload_dtype=DT,offload_device="cpu",onload_dtype=DT,onload_device="cpu", - preparing_dtype=DT,preparing_device="cuda",computation_dtype=DT,computation_device="cuda") -NF4="DiffSynth-Studio/MiniMax-H3-NF4" -pipe=MiniMaxH3Pipeline.from_pretrained(torch_dtype=DT,device="cuda", - model_configs=[ModelConfig(model_id=NF4,origin_file_pattern=p,**vc) for p in - ["minimax-h3-fl2va-nf4.safetensors","minimax-h3-text-encoder-nf4.safetensors", - "video_vae_nf4.safetensors","audio_vae_nf4.safetensors"]], - processor_config=ModelConfig(model_id="MiniMax/MiniMax-H3",origin_file_pattern="FL2VA/processor/"), - vram_limit=vram_limit) -pipe.load_lora(pipe.dit, ModelConfig(model_id="lightx2v/Minimax-h3-Turbo", - origin_file_pattern="minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors")) - -FP16_MAX=65504.0 -def _fix(mod, tag): - mod.computation_dtype = torch.float32 - orig = mod.forward - def fwd(x,*a,**kw): - out = orig(x.float(),*a,**kw) - print(f'[cp] fp32 out absmax={float(out.abs().max()):.1f} finite={bool(torch.isfinite(out).all())} dtype={out.dtype}', flush=True) - return out - mod.forward=fwd -_fix(pipe.dit.condition_proj, "condition_proj") -print("[fix ] condition_proj fp32+clamp 已装", flush=True) - -# 先单独查文本编码器输出——它是整条条件链的源头 -te_out={} -def te_hook(m,i,o): - t = o[0] if isinstance(o,(tuple,list)) else o - if torch.is_tensor(t) and t.is_floating_point(): - te_out["absmax"]=float(t.abs().max()); te_out["finite"]=bool(torch.isfinite(t).all()) - te_out["shape"]=tuple(t.shape); te_out["dtype"]=str(t.dtype) -h_te = pipe.text_encoder.register_forward_hook(te_hook) - -hits=[]; seen=set() -def mk(name): - def hook(mod, inp, out): - if name in seen: return - ok_in = all(bool(torch.isfinite(t).all()) for t in inp if torch.is_tensor(t) and t.is_floating_point()) - outs = out if isinstance(out,(tuple,list)) else (out,) - for o in outs: - if torch.is_tensor(o) and o.is_floating_point() and not torch.isfinite(o).all(): - seen.add(name) - ins=[float(t.abs().max()) for t in inp if torch.is_tensor(t) and t.is_floating_point() and t.numel()] - fin=torch.isfinite(o) - hits.append((name, type(mod).__name__, ok_in, - float(o[fin].abs().max()) if fin.any() else float("nan"), - max(ins) if ins else None, - float((~fin).float().mean())*100)) - return - return hook -handles=[] -for tag,mod in (("dit",pipe.dit),("txt",pipe.text_encoder), - ("vvae",pipe.video_vae),("avae",pipe.audio_vae)): - for n,m in mod.named_modules(): - if n: handles.append(m.register_forward_hook(mk(f"{tag}.{n}"))) -print(f"[hook] {len(handles)} 个模块", flush=True) - -video, audio = pipe(prompt=PROMPT, height=480,width=832,num_frames=124, - num_inference_steps=1, seed=0, flow_shift=6.0) -for h in handles: h.remove() -h_te.remove() - -print("\n===== 结果 =====") -print("[文本编码器输出]", te_out) -import numpy as np -try: - a=np.stack([np.asarray(f.convert("RGB"),dtype=np.float32) for f in video[::20]]) - print(f"[video] frames={len(video)} mean={a.mean():.4f} std={a.std():.4f}") -except Exception as e: - print("[video]", type(video), e) -print(f"[audio] finite={bool(torch.isfinite(audio).all())}") -print(f"\n>>> 真源头(输入有限=True),共 {len([h for h in hits if h[2]])} 个:") -for h in hits: - if h[2]: print(f" ★ {h[0]} [{h[1]}] 输入absmax={h[4]} 有限部分absmax={h[3]} 非有限占比={h[5]:.4f}%") -print(f">>> 受害者总数 {len([h for h in hits if not h[2]])},前 5:") -for h in [x for x in hits if not x[2]][:5]: print(f" {h[0]} [{h[1]}]") diff --git a/minimax-h3/scripts/download.py b/minimax-h3/scripts/download.py deleted file mode 100644 index 842b0a2..0000000 --- a/minimax-h3/scripts/download.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Pre-download MiniMax-H3 NF4 weights via DiffSynth's own ModelConfig, -so the on-disk layout matches exactly what the pipeline later resolves. - -已下过的会被 download_if_necessary() 跳过,重跑是幂等的。 -两个分区:FL2VA 收首末帧,Ref2VA 收任意多张参考图/参考视频, -DiT 与 processor 各一套,VAE 和文本编码器共用。""" -import os, time, traceback -from diffsynth.core.loader import ModelConfig - -JOBS = [ # small first, so a load smoke-test can start early - ("MiniMax/MiniMax-H3", "FL2VA/processor/"), - ("DiffSynth-Studio/MiniMax-H3-NF4", "audio_vae_nf4.safetensors"), - ("DiffSynth-Studio/MiniMax-H3-NF4", "video_vae_nf4.safetensors"), - ("lightx2v/Minimax-h3-Turbo", "minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors"), - ("DiffSynth-Studio/MiniMax-H3-NF4", "minimax-h3-text-encoder-nf4.safetensors"), - ("DiffSynth-Studio/MiniMax-H3-NF4", "minimax-h3-fl2va-nf4.safetensors"), - # Ref2VA:参考图模式。Turbo LoRA 只有 v0.1,FL2V 那个是 v1.0 768p。 - ("MiniMax/MiniMax-H3", "Ref2VA/processor/"), - ("lightx2v/Minimax-h3-Turbo", "minimax_h3_ref2v_turbo_4step_v0.1_bf16.safetensors"), - ("DiffSynth-Studio/MiniMax-H3-NF4", "minimax-h3-ref2va-nf4.safetensors"), - # 上面那个 bf16 版实测出噪点(二分见 docs/H3)。comfyui 版是另一套键名,试它能不能被认。 - ("lightx2v/Minimax-h3-Turbo", "minimax_h3_ref2v_turbo_4step_v0.1_comfyui_bf16.safetensors"), -] - -for i, (mid, pat) in enumerate(JOBS, 1): - t0 = time.time() - print(f"[{i}/{len(JOBS)}] {mid} :: {pat}", flush=True) - for attempt in range(1, 6): - try: - ModelConfig(model_id=mid, origin_file_pattern=pat).download_if_necessary() - print(f" done in {time.time()-t0:.0f}s", flush=True) - break - except Exception: - print(f" attempt {attempt} failed:\n{traceback.format_exc()}", flush=True) - time.sleep(15) - else: - print(f" GIVING UP on {mid}::{pat}", flush=True) -print("ALL DOWNLOADS FINISHED", flush=True) diff --git a/minimax-h3/scripts/probe-attention-backend.py b/minimax-h3/scripts/probe-attention-backend.py deleted file mode 100644 index 62e64d9..0000000 --- a/minimax-h3/scripts/probe-attention-backend.py +++ /dev/null @@ -1,11 +0,0 @@ -import os, sys, torch -from diffsynth.core.attention import attention_forward -A = sys.modules[attention_forward.__module__] -print("DIFFSYNTH_ATTENTION_IMPLEMENTATION env =", os.environ.get("DIFFSYNTH_ATTENTION_IMPLEMENTATION")) -print("selected =", A.ATTENTION_IMPLEMENTATION, - "| xformers=", A.XFORMERS_AVAILABLE, "flash2=", A.FLASH_ATTN_2_AVAILABLE, - "flash3=", A.FLASH_ATTN_3_AVAILABLE, "flash4=", A.FLASH_ATTN_4_AVAILABLE, "sage=", A.SAGE_ATTN_AVAILABLE) -dev="cuda:1" -q=torch.randn(1,56,14100,128,device=dev,dtype=torch.float16) -o=A.attention_forward(q,q,q) -print("[OK] attention_forward fp16 S=14100:", tuple(o.shape), "finite=", bool(torch.isfinite(o).all())) diff --git a/minimax-h3/scripts/probe-cp.py b/minimax-h3/scripts/probe-cp.py deleted file mode 100644 index 85f57ff..0000000 --- a/minimax-h3/scripts/probe-cp.py +++ /dev/null @@ -1,61 +0,0 @@ -"""摸清 dit.condition_proj 的溢出幅度:权重/输入/fp32 参考输出的量级。""" -import os, time, torch -BASE="/data/models/minimax-h3" -os.environ.setdefault("DIFFSYNTH_ATTENTION_IMPLEMENTATION","torch") -os.environ.setdefault("DIFFSYNTH_MODEL_BASE_PATH", f"{BASE}/models") -os.environ.setdefault("MODELSCOPE_CACHE", f"{BASE}/.mscache") -from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig -DT=torch.float16 -free=torch.cuda.mem_get_info("cuda")[0]/1024**3 -vc=dict(offload_dtype=DT,offload_device="cpu",onload_dtype=DT,onload_device="cpu", - preparing_dtype=DT,preparing_device="cuda",computation_dtype=DT,computation_device="cuda") -NF4="DiffSynth-Studio/MiniMax-H3-NF4" -pipe=MiniMaxH3Pipeline.from_pretrained(torch_dtype=DT,device="cuda", - model_configs=[ModelConfig(model_id=NF4,origin_file_pattern=p,**vc) for p in - ["minimax-h3-fl2va-nf4.safetensors","minimax-h3-text-encoder-nf4.safetensors", - "video_vae_nf4.safetensors","audio_vae_nf4.safetensors"]], - processor_config=ModelConfig(model_id="MiniMax/MiniMax-H3",origin_file_pattern="FL2VA/processor/"), - vram_limit=max(6.0,free-2.0)) -pipe.load_lora(pipe.dit, ModelConfig(model_id="lightx2v/Minimax-h3-Turbo", - origin_file_pattern="minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors")) - -cp = pipe.dit.condition_proj -print("[cp] type:", type(cp).__name__) -for n,p_ in cp.named_parameters(recurse=True): - print(f" param {n}: shape={tuple(p_.shape)} dtype={p_.dtype} absmax={float(p_.abs().max()):.4g}") -for n,b in cp.named_buffers(recurse=True): - print(f" buf {n}: {tuple(b.shape)} {b.dtype}") - -cap={} -def hook(m,i,o): - x=i[0] - cap["x"]=x.detach() - cap["o"]=o.detach() if torch.is_tensor(o) else None -h=cp.register_forward_hook(hook) -try: - pipe(prompt="测试", height=480,width=832,num_frames=124, - num_inference_steps=1, seed=42, flow_shift=6.0) -except Exception as e: - print("[gen] 提前中断(预期):", type(e).__name__, str(e)[:120]) -h.remove() - -x=cap.get("x") -if x is None: - print("!! 没抓到输入"); raise SystemExit(1) -print(f"\n[输入] shape={tuple(x.shape)} dtype={x.dtype} absmax={float(x.abs().max()):.6g} " - f"mean={float(x.float().mean()):.4g} std={float(x.float().std()):.4g} finite={bool(torch.isfinite(x).all())}") -o=cap.get("o") -if o is not None: - fin=torch.isfinite(o) - print(f"[fp16 输出] absmax={float(o[fin].abs().max()) if fin.any() else float('nan'):.6g} " - f"非有限占比={100*(~fin).float().mean():.2f}%") - -# fp32 参考 -W=None;B=None -for n,p_ in cp.named_parameters(recurse=True): - if n.endswith("weight"): W=p_ - if n.endswith("bias"): B=p_ -if W is not None: - ref=torch.nn.functional.linear(x.float(), W.float(), B.float() if B is not None else None) - print(f"[fp32 参考] absmax={float(ref.abs().max()):.6g} (fp16 上限 65504)") - print(f" → 超出 fp16 上限的元素占比 {100*(ref.abs()>65504).float().mean():.4f}%") diff --git a/minimax-h3/scripts/probe-h3-shapes.py b/minimax-h3/scripts/probe-h3-shapes.py deleted file mode 100644 index 9317bc7..0000000 --- a/minimax-h3/scripts/probe-h3-shapes.py +++ /dev/null @@ -1,32 +0,0 @@ -import torch, time -dev="cuda:1" -torch.cuda.set_device(dev) -from torch.nn.attention import SDPBackend, sdpa_kernel -S, H, D = 14100, 56, 128 # real H3 shape @ 480x832x124f -for dt in (torch.float16,): - q=k=v=torch.randn(1,H,S,D,device=dev,dtype=dt) - for be,nm in ((SDPBackend.EFFICIENT_ATTENTION,"EFFICIENT"),): - try: - with sdpa_kernel(be): - torch.cuda.synchronize(); t0=time.time() - o=torch.nn.functional.scaled_dot_product_attention(q,k,v) - torch.cuda.synchronize() - print(f"[OK ] SDPA {nm} fp16 S={S} H={H} D={D}: {o.shape} {time.time()-t0:.2f}s peak={torch.cuda.max_memory_allocated(dev)/2**30:.2f}G") - except Exception as e: - print(f"[ERR] SDPA {nm} fp16 D={D}: {type(e).__name__}: {str(e)[:200]}") - del q,k,v - torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats(dev) - -# fp16 GEMM throughput on this card (H3 block-ish shape) -a=torch.randn(14100,5376,device=dev,dtype=torch.float16); b=torch.randn(5376,28672,device=dev,dtype=torch.float16) -for _ in range(2): c=a@b -torch.cuda.synchronize(); t0=time.time() -for _ in range(5): c=a@b -torch.cuda.synchronize() -fl=2*14100*5376*28672*5 -print(f"fp16 GEMM effective: {fl/(time.time()-t0)/1e12:.1f} TFLOPS") -# fp16 overflow sanity on a deep-ish accumulation -x=torch.randn(4096,4096,device=dev,dtype=torch.float16)*4 -y=x -for i in range(20): y=torch.nn.functional.layer_norm(y@x/64,(4096,)) -print("fp16 deep-chain finite:", bool(torch.isfinite(y).all())) diff --git a/minimax-h3/scripts/probe-nf4-fp16.py b/minimax-h3/scripts/probe-nf4-fp16.py deleted file mode 100644 index 128ebb0..0000000 --- a/minimax-h3/scripts/probe-nf4-fp16.py +++ /dev/null @@ -1,30 +0,0 @@ -import os, torch -os.environ.setdefault("DIFFSYNTH_ATTENTION_IMPLEMENTATION","torch") -import bitsandbytes as bnb -print("bnb", bnb.__version__) -dev="cuda:1" -# --- NF4 quantize + forward in FP16 on sm_75 --- -lin = torch.nn.Linear(5376, 14336, bias=False, dtype=torch.float16) -q = bnb.nn.Linear4bit(5376, 14336, bias=False, compute_dtype=torch.float16, quant_type="nf4", compress_statistics=True) -q.weight = bnb.nn.Params4bit(lin.weight.data, requires_grad=False, quant_type="nf4", compress_statistics=True) -q = q.to(dev) -x = torch.randn(1024, 5376, device=dev, dtype=torch.float16) -y = q(x) -ref = torch.nn.functional.linear(x, lin.weight.to(dev)) -err = (y.float()-ref.float()).abs().mean().item()/ref.float().abs().mean().item() -print(f"[OK ] NF4 fp16 forward: out={tuple(y.shape)} dtype={y.dtype} finite={bool(torch.isfinite(y).all())} rel_err={err:.4f}") -# --- prequantized round-trip (what DiffSynth actually does when loading .safetensors) --- -qs = q.weight.quant_state.as_dict(packed=True) -w2 = bnb.nn.Params4bit.from_prequantized(data=q.weight.data, quantized_stats={k:(v.to(dev) if torch.is_tensor(v) else v) for k,v in qs.items()}, requires_grad=False, device=dev) -q2 = bnb.nn.Linear4bit(5376,14336,bias=False,compute_dtype=torch.float16,quant_type="nf4") -q2.weight = w2; q2 = q2.to(dev) -y2 = q2(x) -print(f"[OK ] NF4 prequantized reload: match={torch.allclose(y,y2)} dtype={y2.dtype}") -# --- DiffSynth attention backend selection --- -import sys -from diffsynth.core.attention import attention_forward -A = sys.modules[attention_forward.__module__] -print("ATTENTION_IMPLEMENTATION =", A.ATTENTION_IMPLEMENTATION, - "| xformers_avail =", A.XFORMERS_AVAILABLE, "| flash2 =", A.FLASH_ATTN_2_AVAILABLE, "| sage =", A.SAGE_ATTN_AVAILABLE) -o = A.attention_forward(*[torch.randn(1,56,4096,128,device=dev,dtype=torch.float16)]*3) -print("[OK ] diffsynth attention_forward fp16:", tuple(o.shape), "finite=", bool(torch.isfinite(o).all())) diff --git a/minimax-h3/scripts/probe-turing-caps.py b/minimax-h3/scripts/probe-turing-caps.py deleted file mode 100644 index 1a25568..0000000 --- a/minimax-h3/scripts/probe-turing-caps.py +++ /dev/null @@ -1,39 +0,0 @@ -import torch, subprocess, sys, os -print("torch", torch.__version__, "cuda", torch.version.cuda) -print("arch_list", torch.cuda.get_arch_list()) -print("n_gpu", torch.cuda.device_count()) -for i in range(torch.cuda.device_count()): - free, total = torch.cuda.mem_get_info(i) - p = torch.cuda.get_device_properties(i) - print(f" gpu{i} {p.name} sm_{p.major}{p.minor} free={free/2**30:.1f}G total={total/2**30:.1f}G") - -dev = "cuda:0" -def t(name, fn): - try: - r = fn(); print(f"[OK ] {name}: {r}") - except Exception as e: - print(f"[ERR] {name}: {type(e).__name__}: {str(e)[:180]}") - -t("fp16 matmul", lambda: (torch.randn(512,512,device=dev,dtype=torch.float16) @ torch.randn(512,512,device=dev,dtype=torch.float16)).float().abs().mean().item()) -t("bf16 matmul", lambda: (torch.randn(512,512,device=dev,dtype=torch.bfloat16) @ torch.randn(512,512,device=dev,dtype=torch.bfloat16)).float().abs().mean().item()) -t("bf16 layernorm", lambda: torch.nn.functional.layer_norm(torch.randn(8,512,device=dev,dtype=torch.bfloat16),(512,)).float().abs().mean().item()) - -from torch.nn.attention import SDPBackend, sdpa_kernel -q=lambda dt: torch.randn(1,8,1024,64,device=dev,dtype=dt) -for dt in (torch.float16, torch.bfloat16): - for be in (SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION, SDPBackend.MATH): - def f(dt=dt,be=be): - with sdpa_kernel(be): - return tuple(torch.nn.functional.scaled_dot_product_attention(q(dt),q(dt),q(dt)).shape) - t(f"SDPA {str(dt).split('.')[-1]:9s} {be.name}", f) -def auto(): - return tuple(torch.nn.functional.scaled_dot_product_attention(q(torch.float16),q(torch.float16),q(torch.float16)).shape) -t("SDPA fp16 AUTO", auto) - -print("--- installed pkgs of interest ---") -import importlib.metadata as md -for name in ["transformers","accelerate","diffusers","bitsandbytes","torchao","safetensors","einops","modelscope","av","torchaudio","torchcodec","librosa","peft","xformers","flash_attn","sageattention","imageio","imageio-ffmpeg","numpy"]: - try: print(f" {name}=={md.version(name)}") - except Exception: print(f" {name}: NOT INSTALLED") -print("--- ffmpeg ---") -print(subprocess.run(["bash","-lc","ffmpeg -version 2>&1|head -1; which ffmpeg"],capture_output=True,text=True).stdout) diff --git a/minimax-h3/scripts/probe2.py b/minimax-h3/scripts/probe2.py deleted file mode 100644 index d118cbe..0000000 --- a/minimax-h3/scripts/probe2.py +++ /dev/null @@ -1,52 +0,0 @@ -"""量清楚 condition_proj 的 fp32 真值幅度:决定是局部修还是整条路径抬 fp32。""" -import os, torch, torch.nn.functional as F -BASE="/data/models/minimax-h3" -os.environ.setdefault("DIFFSYNTH_ATTENTION_IMPLEMENTATION","torch") -os.environ.setdefault("DIFFSYNTH_MODEL_BASE_PATH", f"{BASE}/models") -os.environ.setdefault("MODELSCOPE_CACHE", f"{BASE}/.mscache") -from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig -DT=torch.float16 -free=torch.cuda.mem_get_info("cuda")[0]/1024**3 -vc=dict(offload_dtype=DT,offload_device="cpu",onload_dtype=DT,onload_device="cpu", - preparing_dtype=DT,preparing_device="cuda",computation_dtype=DT,computation_device="cuda") -NF4="DiffSynth-Studio/MiniMax-H3-NF4" -pipe=MiniMaxH3Pipeline.from_pretrained(torch_dtype=DT,device="cuda", - model_configs=[ModelConfig(model_id=NF4,origin_file_pattern=p,**vc) for p in - ["minimax-h3-fl2va-nf4.safetensors","minimax-h3-text-encoder-nf4.safetensors", - "video_vae_nf4.safetensors","audio_vae_nf4.safetensors"]], - processor_config=ModelConfig(model_id="MiniMax/MiniMax-H3",origin_file_pattern="FL2VA/processor/"), - vram_limit=max(6.0,free-2.0)) -pipe.load_lora(pipe.dit, ModelConfig(model_id="lightx2v/Minimax-h3-Turbo", - origin_file_pattern="minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors")) - -cp = pipe.dit.condition_proj -class Stop(Exception): pass -res={} -orig_lf = cp.linear_forward -orig_lora = cp.lora_forward -def lf(x, weight, bias): - o32 = F.linear(x.float(), weight.float(), bias.float() if bias is not None else None) - res["x_absmax"]=float(x.abs().max()); res["x_dtype"]=str(x.dtype) - res["lin32_absmax"]=float(o32.abs().max()) - res["lin32_over_fp16"]=float((o32.abs()>65504).float().mean())*100 - res["lin32"]=o32 - return o32 -def lora(x, out): - o = out - for A,B in zip(cp.lora_A_weights, cp.lora_B_weights): - o = o + x.float() @ A.T.to(device=x.device,dtype=torch.float32) @ B.T.to(device=x.device,dtype=torch.float32) - res["n_lora"]=len(cp.lora_A_weights) - res["final32_absmax"]=float(o.abs().max()) - res["final32_over_fp16"]=float((o.abs()>65504).float().mean())*100 - res["p999"]=float(torch.quantile(o.abs().flatten().float(), 0.999)) - raise Stop() -cp.linear_forward=lf; cp.lora_forward=lora -try: - pipe(prompt="一只橘猫在窗台上打哈欠", height=480,width=832,num_frames=124, - num_inference_steps=1, seed=42, flow_shift=6.0) -except Stop: - pass -print("\n===== condition_proj fp32 真值 =====") -for k in ["x_dtype","x_absmax","lin32_absmax","lin32_over_fp16","n_lora","final32_absmax","final32_over_fp16","p999"]: - if k in res: print(f" {k:20s} = {res[k]}") -print(f" fp16 上限 = 65504") diff --git a/minimax-h3/scripts/run.sh b/minimax-h3/scripts/run.sh deleted file mode 100755 index 2ad2789..0000000 --- a/minimax-h3/scripts/run.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env bash -# MiniMax-H3 FL2VA NF4 launcher. usage: ./run.sh [args for t2va.py ...] -# ./run.sh 1 # turbo 4-step, 480x832x124f -# ./run.sh 1 --no-turbo --steps 50 # full quality -# ./run.sh 2 --prompt "..." --seed 7 -set -euo pipefail -B=/data/models/minimax-h3 -GPU="${1:-1}"; shift || true - -export CUDA_VISIBLE_DEVICES="$GPU" -export DIFFSYNTH_ATTENTION_IMPLEMENTATION=torch # sm_75: no flash/sage; pin instead of auto-picking xformers -export DIFFSYNTH_MODEL_BASE_PATH="$B/models" -export MODELSCOPE_CACHE="$B/.mscache" -export PYTHONUNBUFFERED=1 -# NOTE: deliberately NOT setting PYTHONNOUSERSITE -- the venv's site-packages already -# precedes ~/.local in sys.path, so our bitsandbytes 0.50.1 shadows the broken 0.45.1 there. - -# GPU0/1 sit on NUMA0, GPU2/3 on NUMA1 -- keep the CPU-offloaded weights on the near node. -case "$GPU" in 0|1) NODE=0 ;; 2|3) NODE=1 ;; *) NODE="" ;; esac -BIND=(); if [ -n "$NODE" ] && command -v numactl >/dev/null 2>&1; then BIND=(numactl --cpunodebind="$NODE" --membind="$NODE"); fi - -LOG="$B/logs/gpu${GPU}_$(date +%Y%m%d-%H%M%S).log" -echo "[run] GPU=$GPU numa=${NODE:-none} log=$LOG" -"${BIND[@]}" "$B/venv/bin/python" "$B/scripts/t2va.py" "$@" 2>&1 | tee "$LOG" diff --git a/minimax-h3/scripts/t2va.py b/minimax-h3/scripts/t2va.py deleted file mode 100644 index 12df854..0000000 --- a/minimax-h3/scripts/t2va.py +++ /dev/null @@ -1,227 +0,0 @@ -#!/usr/bin/env python -"""MiniMax-H3 FL2VA (NF4) Text -> Video+Audio on RTX 2080 Ti (Turing / sm_75). - -Turing deltas vs the official example (all deliberate): - * FP16 everywhere, never BF16 -- sm_75 has no bf16 SDPA kernel at all - (EFFICIENT and FLASH both report "No available kernel"), so bf16 silently - falls back to the MATH backend and OOMs on a ~14k-token sequence. - * DIFFSYNTH_ATTENTION_IMPLEMENTATION=torch -- FlashAttention 2/3/4 and - SageAttention are sm_80+. xformers works here but would be auto-selected - ahead of torch; pin the backend so runs are reproducible. - * vram_limit from mem_get_info()[0] (FREE) not [1] (TOTAL) -- other processes - share these GPUs. - * offload to "cpu", never "disk" -- /data is a 7200rpm HDD (184 MB/s). -""" -import os, sys, time, argparse - -BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -os.environ.setdefault("DIFFSYNTH_ATTENTION_IMPLEMENTATION", "torch") -os.environ.setdefault("DIFFSYNTH_MODEL_BASE_PATH", os.path.join(BASE, "models")) - -p = argparse.ArgumentParser() -p.add_argument("--prompt", default="A girl is very happy, she is speaking in english: " - "“I enjoy working with Diffsynth-Studio, it's a perfect framework.”") -p.add_argument("--height", type=int, default=480) -p.add_argument("--width", type=int, default=832) -p.add_argument("--frames", type=int, default=124) -p.add_argument("--steps", type=int, default=4) -p.add_argument("--flow-shift", type=float, default=None, help="default 6.0 with turbo, 12.0 without") -p.add_argument("--seed", type=int, default=0) -p.add_argument("--turbo", action="store_true", default=True) -p.add_argument("--no-turbo", dest="turbo", action="store_false") -p.add_argument("--dtype", choices=["fp32","fp16"], default="fp32", - help="fp32=唯一能在 sm_75 上出片的选择(默认);fp16 只用于复现全黑故障") -p.add_argument("--no-fp32-residual", dest="fp32_residual", action="store_false", - help="关闭 DiT 残差流的 fp32 兜底(默认开启;关掉在 sm_75 上会出全黑视频)") -p.add_argument("--no-fp32-cond", dest="fp32_cond", action="store_false", - help="关闭 condition_proj 的 fp32 兜底(默认开启;关掉在 sm_75 上会出全黑视频)") -p.add_argument("--fp32-accum", action="store_true", - help="disable fp16 reduced-precision reduction (~2x slower, use if output is NaN/artifacted)") -p.add_argument("--vram-reserve", type=float, default=None, - help="留给激活的显存(GB)。默认按 dtype 自适应:fp32=14(实测全分辨率峰值 12.2G),fp16=5") -p.add_argument("--out", default=None) -args = p.parse_args() - -import torch -if args.fp32_accum: - torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = False - -from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig -from diffsynth.utils.data.audio_video import write_video_audio - -# dtype 决定这条线能不能出片。实测(2026-08-18, sm_75, 448x256x28f, 唯一变量是 dtype): -# fp32 -> 视频 std=50.6、音频 finite ✅ fp16 -> 124 帧纯黑、音频 NaN ❌ -# 原因是 fp16 的动态范围装不下这个 bf16 训练的模型:dit.blocks.0 输入 absmax 89 -# 已放大到 38176,50 层残差累积后必然突破 fp16 上限 65504。 -# bf16 在 sm_75 上不可用(无硬件支持),所以 fp32 是这张卡上唯一能出片的选择。 -# 保留 --dtype fp16 只为复现/对照,不要用它出片。 -DTYPE = {"fp32": torch.float32, "fp16": torch.float16}[args.dtype] -free_gb = torch.cuda.mem_get_info("cuda")[0] / 1024**3 # [0]=free, official example wrongly uses [1]=total -if args.vram_reserve is None: - # fp32 的激活是 fp16 的两倍,权重要多让位。实测 832x480x124f fp32: - # vram_limit 7.3G 时峰值 12.2G,跑通;vram_limit 19.3G 时 OOM。 - args.vram_reserve = 14.0 if DTYPE is torch.float32 else 5.0 -vram_limit = max(4.0, free_gb - args.vram_reserve) -if vram_limit + 1.0 > free_gb: - print(f"[warn] 空闲显存仅 {free_gb:.1f}G,vram_limit={vram_limit:.1f}G 几乎没有余量," - f"很可能 OOM。先停掉占显存的服务(见 qwen38-deploy/RESTORE-GPU.md)", flush=True) - -prop = torch.cuda.get_device_properties(0) -print(f"[env] GPU={prop.name} sm_{prop.major}{prop.minor} free={free_gb:.1f}G vram_limit={vram_limit:.1f}G", flush=True) -print(f"[env] dtype={DTYPE} attention={os.environ['DIFFSYNTH_ATTENTION_IMPLEMENTATION']} " - f"fp16_reduced_accum={torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction}", flush=True) -assert prop.major == 7, "this script is tuned for Turing; re-check dtype choices on other archs" - -vram_config = dict( - offload_dtype=DTYPE, offload_device="cpu", # not "disk": /data is a spinning HDD - onload_dtype=DTYPE, onload_device="cpu", - preparing_dtype=DTYPE, preparing_device="cuda", - computation_dtype=DTYPE, computation_device="cuda", -) -NF4 = "DiffSynth-Studio/MiniMax-H3-NF4" - -t0 = time.time() -pipe = MiniMaxH3Pipeline.from_pretrained( - torch_dtype=DTYPE, device="cuda", - model_configs=[ - ModelConfig(model_id=NF4, origin_file_pattern="minimax-h3-fl2va-nf4.safetensors", **vram_config), - ModelConfig(model_id=NF4, origin_file_pattern="minimax-h3-text-encoder-nf4.safetensors", **vram_config), - ModelConfig(model_id=NF4, origin_file_pattern="video_vae_nf4.safetensors", **vram_config), - ModelConfig(model_id=NF4, origin_file_pattern="audio_vae_nf4.safetensors", **vram_config), - ], - processor_config=ModelConfig(model_id="MiniMax/MiniMax-H3", origin_file_pattern="FL2VA/processor/"), - vram_limit=vram_limit, -) -print(f"[load] pipeline ready in {time.time()-t0:.0f}s", flush=True) - -if args.turbo: - # LoRA rides on the NF4 layers: AutoWrappedQuantizedModule inherits LoRAHotLoadMixin, - # so lora_forward() adds x@A@B to the quantized output -- no base dequantisation needed. - pipe.load_lora(pipe.dit, ModelConfig( - model_id="lightx2v/Minimax-h3-Turbo", - origin_file_pattern="minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors")) -# --- sm_75 必需:condition_proj 在 fp16 下累加溢出 -> inf -> 全管线 NaN -> 全黑视频 --- -# 实测(2026-08-18):该层输入 absmax≈17808、权重 absmax≈4.66、K=5120, -# fp16 累加器(上限 65504)有 0.04% 的输出溢出成 inf,随后污染下游 999 个模块。 -# 它只是 (1,5120)x(5376,5120) 的一次投影,改走 fp32 的算力开销可忽略。 -# 注意:--fp32-accum 对此无效——溢出发生在累加器量级,不是 reduced-precision reduction。 -def _force_fp32_linear(mod, tag): - """该层在 fp32 里算,且**输出保持 fp32**流入 token_refiner。 - - 实测(2026-08-18, sm_75): - 文本编码器输出 absmax 15328(有限、健康,源头不在它); - condition_proj 的 fp32 真值 absmax 可达 79554,而 fp16 上限 65504。 - 产生的 inf 会污染下游 2985 个模块,最终 124 帧纯黑(且原脚本退出码为 0)。 - 根因是 Turing 无 bf16:模型按 bf16 训练(bf16 有 fp32 的动态范围), - fp16 装不下这条条件路径。 - - 走过的四条弯路,都记下来免得后人重走: - 1) 替换整个 forward —— 绕过 preparing/onload 换入机制。 - 2) 只换 linear_forward、最后仍 `.to(fp16)` —— 无效:fp32 算得对, - 溢出发生在那次类型转换上。自检若只查转换前的张量会永远显示"正常"。 - 3) 钳位到 65504 再降回 fp16 —— **反而更糟**:token_refiner.blocks.0 是 - `h = x + attn(norm1(x))`,x 恰好等于 fp16 最大可表示值时, - 再加任何正数立刻变 inf(实测 3.45% 非有限)。钳位不留余量等于自造故障。 - 4) 输出保持 fp32 但 vram_limit=19.3G —— 数值对了但 CUDA OOM。 - 配 `--vram-reserve 5`(vram_limit 16.3G) + PYTORCH_ALLOC_CONF=expandable_segments:True - 后峰值 17.2G,有余量。 - - 库里 _embed() 在 token_refiner 之后本来就有 `text_embed.to(dtype)`, - 那时已归一化、量级回落,那次转换是安全的。 - 下游 RMSNorm 会因 dtype 不一致发性能警告(非错误),可忽略。 - """ - mod.computation_dtype = torch.float32 - orig = mod.forward - def fwd(x, *a, **kw): - out = orig(x.float(), *a, **kw) - if not torch.isfinite(out).all(): - print(f"[warn] {tag} 即使 fp32 仍非有限", flush=True) - return out # 保持 fp32:既不降回也不钳位 - mod.forward = fwd - return mod - -# --- sm_75 必需 #2:DiT 残差流保持 fp32 --- -# 实测(2026-08-18):dit.blocks.0 输入 absmax 89.25 → 输出 38176,且有极少量元素溢出。 -# 50 个 block × 每个 2 次残差相加 = 100 个溢出点,累积后必然爆 fp16 的 65504。 -# -# 病灶与 condition_proj 同构,见 minimax_h3_dit.py:61-67: -# def _modulate_gate(x, gate, other, indices): -# return (x + gate.index_select(0, indices) * other).to(x.dtype) -# ^^^^^^^^^^ 提升到 fp32 算完又降回 fp16 -# 库作者自己的注释也写了 "index_select on the AdaLN params can promote the expression", -# 但把结果降回 fp16 恰恰丢掉了提升带来的动态范围。 -# -# 做法是标准混合精度:**累加器(残差流)fp32,喂给子模块的张量仍 fp16**。 -# _modulate_gate -> 返回 fp32(它的输出就是残差流,下游是 RMSNorm,容忍混合 dtype) -# _modulate_scale_shift -> 显式返回 fp16(它的输出喂给 attn/mlp 的 Linear4bit,必须是 fp16) -# 额外显存约 300 MB(残差流 (seq,5376) 一份 fp32),实测峰值仍在 16 GB 以内。 -def _patch_dit_residual_fp32(): - from diffsynth.models import minimax_h3_dit as _m - - def _mss(x, shift, scale, indices): - return (x.float() * (1.0 + scale.index_select(0, indices).float()) - + shift.index_select(0, indices).float()).to(torch.float16) - - def _mg(x, gate, other, indices): - # 不降回 fp16:这一份就是残差流 - return x.float() + gate.index_select(0, indices).float() * other.float() - - _m._modulate_scale_shift = _mss - _m._modulate_gate = _mg - print("[fix ] DiT 残差流已切到 fp32(_modulate_gate 不再降回 fp16)", flush=True) - -# 这两个补丁是 fp16 专用的挽救措施(最终证明救不回来,见 README)。 -# fp32 下必须失效,否则强制 .to(float16) 会与 fp32 权重冲突: -# RuntimeError: mat1 and mat2 must have the same dtype, but got Half and Float -if args.fp32_residual and DTYPE is torch.float16: - _patch_dit_residual_fp32() - -if args.fp32_cond and DTYPE is torch.float16: - _force_fp32_linear(pipe.dit.condition_proj, "dit.condition_proj") - print("[fix ] dit.condition_proj 已切到 fp32 计算(规避 sm_75 fp16 累加溢出)", flush=True) - -flow_shift = args.flow_shift if args.flow_shift is not None else (6.0 if args.turbo else 12.0) - -print(f"[gen ] {args.width}x{args.height} {args.frames}f steps={args.steps} " - f"turbo={args.turbo} flow_shift={flow_shift} seed={args.seed}", flush=True) -t1 = time.time() -video, audio = pipe( - prompt=args.prompt, - height=args.height, width=args.width, num_frames=args.frames, - num_inference_steps=args.steps, seed=args.seed, flow_shift=flow_shift, -) -gen_s = time.time() - t1 - -import torch as _t -_bad = [] -if not _t.isfinite(audio if _t.is_tensor(audio) else _t.tensor(0.)).all(): - _bad.append("audio 含非有限值") -# video 是 PIL 帧列表;原脚本从不检查它,导致全黑视频也返回 0 —— 实测踩过 -def _video_stats(v): - import numpy as _np - if _t.is_tensor(v): - a = v.float() - return float(a.mean()), float(a.std()), bool(_t.isfinite(a).all()) - try: - arrs = [_np.asarray(f.convert("RGB"), dtype=_np.float32) for f in v[:: max(1, len(v)//8)]] - a = _np.stack(arrs) - return float(a.mean()), float(a.std()), True - except Exception: - return None, None, True -_mean, _std, _fin = _video_stats(video) -if not _fin: - _bad.append("video 含非有限值") -if _std is not None and _std < 1.0: - _bad.append(f"video 近乎纯色 (std={_std:.3f}, mean={_mean:.3f})") -if _bad: - print("[FAIL] " + ";".join(_bad), flush=True) - -out = args.out or os.path.join(BASE, "outputs", f"t2va_{time.strftime('%Y%m%d-%H%M%S')}.mp4") -os.makedirs(os.path.dirname(out), exist_ok=True) -write_video_audio(video=video, audio=audio, output_path=out, fps=24, audio_sample_rate=32000) - -print(f"[done] generation {gen_s:.0f}s ({gen_s/max(args.steps,1):.1f}s/step), " - f"peak VRAM {torch.cuda.max_memory_allocated()/1024**3:.1f}G", flush=True) -print(f"[out ] {out} ({os.path.getsize(out)/1024**2:.1f} MB)", flush=True) -if _bad: - sys.exit(3) # 不要用退出码 0 报告一个坏产物 diff --git a/minimax-h3/scripts/test-fp32.py b/minimax-h3/scripts/test-fp32.py deleted file mode 100644 index 239fdc5..0000000 --- a/minimax-h3/scripts/test-fp32.py +++ /dev/null @@ -1,39 +0,0 @@ -"""关键对照实验:小分辨率下 fp32 端到端能否出片。 -若 fp32 出片而 fp16 全黑 → 确认是动态范围问题,而非模型/权重/流程问题。 -小分辨率是为了让 fp32 装得下(seq_len 从 ~14100 降到 ~800)。""" -import os, sys, time, torch, numpy as np -BASE="/data/models/minimax-h3" -os.environ.setdefault("DIFFSYNTH_ATTENTION_IMPLEMENTATION","torch") -os.environ.setdefault("DIFFSYNTH_MODEL_BASE_PATH", f"{BASE}/models") -os.environ.setdefault("MODELSCOPE_CACHE", f"{BASE}/.mscache") -os.environ.setdefault("PYTORCH_ALLOC_CONF","expandable_segments:True") -from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig - -DT = torch.float32 if os.environ.get("TEST_DTYPE","fp32")=="fp32" else torch.float16 -H = int(os.environ.get("TEST_H", 256)); W = int(os.environ.get("TEST_W", 448)); F_ = int(os.environ.get("TEST_F", 28)) -print(f"[cfg] dtype={DT} {W}x{H} {F_}f", flush=True) -free=torch.cuda.mem_get_info("cuda")[0]/1024**3 -vc=dict(offload_dtype=DT,offload_device="cpu",onload_dtype=DT,onload_device="cpu", - preparing_dtype=DT,preparing_device="cuda",computation_dtype=DT,computation_device="cuda") -NF4="DiffSynth-Studio/MiniMax-H3-NF4" -t0=time.time() -pipe=MiniMaxH3Pipeline.from_pretrained(torch_dtype=DT,device="cuda", - model_configs=[ModelConfig(model_id=NF4,origin_file_pattern=p,**vc) for p in - ["minimax-h3-fl2va-nf4.safetensors","minimax-h3-text-encoder-nf4.safetensors", - "video_vae_nf4.safetensors","audio_vae_nf4.safetensors"]], - processor_config=ModelConfig(model_id="MiniMax/MiniMax-H3",origin_file_pattern="FL2VA/processor/"), - vram_limit=max(4.0,free-float(os.environ.get("TEST_RESERVE",5)))) -print(f"[load] {time.time()-t0:.0f}s", flush=True) -pipe.load_lora(pipe.dit, ModelConfig(model_id="lightx2v/Minimax-h3-Turbo", - origin_file_pattern="minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors")) - -PROMPT=("A girl is very happy, she is speaking in english: " - "“I enjoy working with Diffsynth-Studio, it's a perfect framework.”") -t1=time.time() -video,audio = pipe(prompt=PROMPT,height=H,width=W,num_frames=F_, - num_inference_steps=4,seed=0,flow_shift=6.0) -print(f"[gen ] {time.time()-t1:.0f}s peak={torch.cuda.max_memory_allocated()/1024**3:.1f}G", flush=True) -a=np.stack([np.asarray(f.convert("RGB"),dtype=np.float32) for f in video[::5]]) -print(f"[video] frames={len(video)} mean={a.mean():.4f} std={a.std():.4f} max={a.max():.1f}", flush=True) -print(f"[audio] finite={bool(torch.isfinite(audio).all())}", flush=True) -print("[VERDICT] " + ("出片正常 ✅" if a.std()>1.0 else "仍为纯色 ❌"), flush=True) diff --git a/minimax-h3/scripts/test-patch.py b/minimax-h3/scripts/test-patch.py deleted file mode 100644 index 8f86fb1..0000000 --- a/minimax-h3/scripts/test-patch.py +++ /dev/null @@ -1,39 +0,0 @@ -import os, torch, torch.nn.functional as F -BASE="/data/models/minimax-h3" -os.environ.setdefault("DIFFSYNTH_ATTENTION_IMPLEMENTATION","torch") -os.environ.setdefault("DIFFSYNTH_MODEL_BASE_PATH", f"{BASE}/models") -os.environ.setdefault("MODELSCOPE_CACHE", f"{BASE}/.mscache") -from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig -DT=torch.float16 -free=torch.cuda.mem_get_info("cuda")[0]/1024**3 -vc=dict(offload_dtype=DT,offload_device="cpu",onload_dtype=DT,onload_device="cpu", - preparing_dtype=DT,preparing_device="cuda",computation_dtype=DT,computation_device="cuda") -NF4="DiffSynth-Studio/MiniMax-H3-NF4" -pipe=MiniMaxH3Pipeline.from_pretrained(torch_dtype=DT,device="cuda", - model_configs=[ModelConfig(model_id=NF4,origin_file_pattern=p,**vc) for p in - ["minimax-h3-fl2va-nf4.safetensors","minimax-h3-text-encoder-nf4.safetensors", - "video_vae_nf4.safetensors","audio_vae_nf4.safetensors"]], - processor_config=ModelConfig(model_id="MiniMax/MiniMax-H3",origin_file_pattern="FL2VA/processor/"), - vram_limit=max(6.0,free-2.0)) -pipe.load_lora(pipe.dit, ModelConfig(model_id="lightx2v/Minimax-h3-Turbo", - origin_file_pattern="minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors")) - -cp = pipe.dit.condition_proj -stats = {"calls":0, "inf_out":0} -orig_lf = cp.linear_forward # 改 linear_forward 而不是 forward: - # 这样 onload/preparing/LoRA 全套机制保持不变 -def lf(x, weight, bias): - stats["calls"] += 1 - out = F.linear(x.float(), weight.float(), bias.float() if bias is not None else None) - if not torch.isfinite(out).all(): stats["inf_out"] += 1 - return out.to(x.dtype) -cp.linear_forward = lf -print("[patch] linear_forward 已替换", flush=True) - -video, audio = pipe(prompt="一只橘猫在窗台上打哈欠", height=480, width=832, - num_frames=124, num_inference_steps=1, seed=42, flow_shift=6.0) -print(f"[stat] condition_proj 被调用 {stats['calls']} 次,其中 fp32 仍非有限 {stats['inf_out']} 次", flush=True) -import numpy as np -a=np.stack([np.asarray(f.convert("RGB"),dtype=np.float32) for f in video[::20]]) -print(f"[video] frames={len(video)} mean={a.mean():.4f} std={a.std():.4f} max={a.max():.1f}", flush=True) -print(f"[audio] finite={bool(torch.isfinite(audio).all())} absmax={float(audio.abs().max()):.4g}", flush=True) diff --git a/minimax-h3/scripts/verify.py b/minimax-h3/scripts/verify.py deleted file mode 100644 index ffceecc..0000000 --- a/minimax-h3/scripts/verify.py +++ /dev/null @@ -1,51 +0,0 @@ -"""Verify every downloaded weight: exact byte size vs ModelScope, and a safetensors header parse.""" -import os, sys, json, struct, urllib.request - -BASE = os.environ.get("DIFFSYNTH_MODEL_BASE_PATH", "/data/models/minimax-h3/models") -WANT = { - "DiffSynth-Studio/MiniMax-H3-NF4": ["minimax-h3-fl2va-nf4.safetensors", - "minimax-h3-ref2va-nf4.safetensors", - "minimax-h3-text-encoder-nf4.safetensors", - "video_vae_nf4.safetensors", "audio_vae_nf4.safetensors"], - "lightx2v/Minimax-h3-Turbo": ["minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors", - "minimax_h3_ref2v_turbo_4step_v0.1_bf16.safetensors"], -} -PROCESSORS = ["MiniMax/MiniMax-H3/FL2VA/processor", "MiniMax/MiniMax-H3/Ref2VA/processor"] - -def remote_sizes(mid): - u = f"https://www.modelscope.cn/api/v1/models/{mid}/repo/files?Recursive=true" - d = json.load(urllib.request.urlopen(u, timeout=60)) - return {f["Path"]: f.get("Size", 0) for f in d.get("Data", {}).get("Files", []) if f.get("Type") == "blob"} - -def header_ok(path): - with open(path, "rb") as f: - n = struct.unpack(" logs/api-8010.log 2>&1 < /dev/null & -setsid nohup ./api-run.sh 2 8011 fl2va > logs/api-8011.log 2>&1 < /dev/null & -setsid nohup ./api-run.sh 0 8012 ref2va > logs/api-8012.log 2>&1 < /dev/null & -setsid nohup ./api-run.sh 3 8013 fl2va > logs/api-8013.log 2>&1 < /dev/null & -setsid nohup ./gateway-run.sh 8000 > logs/gateway.log 2>&1 < /dev/null & - -echo "等后端加载(disk 模式约 20 秒)" -for i in $(seq 1 30); do - sleep 5 - READY=$(curl -s --max-time 5 http://127.0.0.1:8000/health | grep -o '"ready":[0-9]*' | cut -d: -f2) - echo " ready=${READY:-?}/4" - [ "${READY:-0}" = "4" ] && break -done -curl -s http://127.0.0.1:8000/health -echo diff --git a/minimax-h3/start-gateway.sh b/minimax-h3/start-gateway.sh deleted file mode 100755 index 9fdd5f7..0000000 --- a/minimax-h3/start-gateway.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash -set -uo pipefail -cd /data/models/minimax-h3 -PID=$(ss -lptn "sport = :8000" | grep -o "pid=[0-9]*" | cut -d= -f2 | sort -u) -[ -n "$PID" ] && { echo "停旧的 (PID $PID)"; kill "$PID"; sleep 3; } -setsid nohup ./gateway-run.sh 8000 > logs/gateway.log 2>&1 < /dev/null & -sleep 5 -pgrep -af "gateway:app" diff --git a/minimax-h3/submit-same.py b/minimax-h3/submit-same.py deleted file mode 100644 index e2814ae..0000000 --- a/minimax-h3/submit-same.py +++ /dev/null @@ -1,13 +0,0 @@ -"""把 8011 上某条已完成任务的请求原样投给另一个端口,用来做单变量对照。""" -import json, sys, urllib.request - -src_port, dst_port, job_id = sys.argv[1], sys.argv[2], sys.argv[3] - -with urllib.request.urlopen(f"http://127.0.0.1:{src_port}/v1/videos/{job_id}", timeout=30) as r: - req = json.load(r)["req"] - -body = json.dumps(req).encode() -post = urllib.request.Request(f"http://127.0.0.1:{dst_port}/v1/videos", data=body, - headers={"Content-Type": "application/json"}) -with urllib.request.urlopen(post, timeout=30) as r: - print(json.load(r)) diff --git a/minimax-h3/verify-fixes.py b/minimax-h3/verify-fixes.py deleted file mode 100644 index 9ae682b..0000000 --- a/minimax-h3/verify-fixes.py +++ /dev/null @@ -1,43 +0,0 @@ -"""验三处修复:eta 跟帧数走、队列满返回 429、派发仍然分散。 - -跑之前要把调度层的 H3_MAX_QUEUE 调成 1,否则填满默认上限 4 要投 16 条、跑 6 分半。 -用 22 帧的短任务,路由和限流逻辑与长任务完全一样。 -""" -import json, urllib.request, urllib.error -from collections import Counter -from concurrent.futures import ThreadPoolExecutor - -GW = "http://127.0.0.1:8000" -CASES = [ - ("832x480x124f 4步(基准,实测 767s)", {"width": 832, "height": 480, "frames": 124, "steps": 4}), - ("1280x736x56f 4步(实测 736s)", {"width": 1280, "height": 736, "frames": 56, "steps": 4}), - ("832x480x22f 4步(实测 96s)", {"width": 832, "height": 480, "frames": 22, "steps": 4}), -] -SPEC = {"prompt": "一只橘猫趴在洒满阳光的窗台上,慢慢眨眼", "turbo": True} - - -def post(body): - req = urllib.request.Request(GW + "/v1/videos", data=json.dumps(body).encode(), - headers={"Content-Type": "application/json"}) - try: - with urllib.request.urlopen(req, timeout=60) as r: - return r.status, json.load(r) - except urllib.error.HTTPError as e: - return e.code, e.read().decode() - - -print("=== 1. eta 是否跟帧数走(改之前三档全报 691)") -results = [post(dict(SPEC, seed=200 + i, **spec)) for i, (_, spec) in enumerate(CASES)] -for (name, _), (code, body) in zip(CASES, results): - print(f" {name:38} -> eta={body['eta_seconds']}s {body['backend'][-4:]}") - -print("\n=== 2. 队列满是否 429(H3_MAX_QUEUE=1,前 3 条已占 3 张卡)") -with ThreadPoolExecutor(max_workers=4) as pool: - burst = list(pool.map(lambda i: post(dict(SPEC, seed=300 + i, frames=22, steps=4)), range(4))) -for i, (code, body) in enumerate(burst): - detail = body if isinstance(body, str) else f"{body['backend'][-4:]} queue_ahead={body['queue_ahead']}" - print(f" #{i} HTTP {code} {detail}") - -accepted = [b for c, b in results + burst if c == 202] -print(f"\n=== 3. 派发分布: {dict(Counter(b['backend'][-4:] for b in accepted))}") -print(f"接受 {len(accepted)} 条,拒绝 {len(results) + len(burst) - len(accepted)} 条") diff --git a/minimax-h3/watch-8012.sh b/minimax-h3/watch-8012.sh deleted file mode 100755 index c3877b1..0000000 --- a/minimax-h3/watch-8012.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env bash -# 盯 disk offload 那条任务:耗时、内存、以及 rchar/read_bytes—— -# rchar 是所有读(含页缓存命中),read_bytes 是真正落到存储层的。 -# 两者差得越大说明页缓存命中越好;read_bytes 跟着涨就是在读机械盘,方案不成立。 -set -uo pipefail -PID=$(pgrep -f "port 8012") -JOB="$1" -while true; do - S=$(curl -s --max-time 5 "http://127.0.0.1:8012/v1/videos/$JOB") - ST=$(echo "$S" | grep -o '"status":"[a-z]*"' | cut -d'"' -f4) - EL=$(echo "$S" | grep -o '"elapsed_seconds":[0-9]*' | cut -d: -f2) - RC=$(grep "^rchar:" /proc/$PID/io | tr -dc 0-9) - RB=$(grep "^read_bytes:" /proc/$PID/io | tr -dc 0-9) - PD=$(grep "^Private_Dirty:" /proc/$PID/smaps_rollup | tr -dc 0-9) - printf "%s %-8s 已跑%4ss rchar=%6.1fG read_bytes=%6.2fG 私有内存=%5.2fG\n" \ - "$(date +%H:%M:%S)" "$ST" "${EL:-0}" \ - "$(echo "$RC/1073741824" | bc -l)" "$(echo "$RB/1073741824" | bc -l)" \ - "$(echo "$PD/1048576" | bc -l)" - case "$ST" in done|failed) echo "$S"; break;; esac - sleep 60 -done -- libgit2 0.21.4