Auto-scale hardware: CUDA 13 only on cc>=7.5, pin ctranslate2 4.8 (cu12), fp16-less GPUs, CPU threads, llama --fit on >=7 GiB GPUs, CPU-only embeddings
This commit is contained in:
+4
-2
@@ -8,12 +8,14 @@ for sp in site.getsitepackages():
|
|||||||
|
|
||||||
from faster_whisper import WhisperModel
|
from faster_whisper import WhisperModel
|
||||||
|
|
||||||
|
CORES = max(1, (os.cpu_count() or 2) // 2) # ponytail: logical/2 ~ physical cores (no psutil); exact count if hybrid CPUs need it
|
||||||
|
|
||||||
def load_model(name):
|
def load_model(name):
|
||||||
"""CUDA if it really works (probe one decode), else CPU int8."""
|
"""CUDA if it really works (probe one decode), else CPU int8."""
|
||||||
try:
|
try:
|
||||||
m = WhisperModel(name, device="cuda", compute_type="float16")
|
m = WhisperModel(name, device="cuda", compute_type="default")
|
||||||
list(m.transcribe(np.zeros(16000, np.float32))[0])
|
list(m.transcribe(np.zeros(16000, np.float32))[0])
|
||||||
return m, "cuda"
|
return m, "cuda"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("cuda failed, using cpu:", e, flush=True)
|
print("cuda failed, using cpu:", e, flush=True)
|
||||||
return WhisperModel(name, device="cpu", compute_type="int8"), "cpu"
|
return WhisperModel(name, device="cpu", compute_type="int8", cpu_threads=CORES), "cpu"
|
||||||
|
|||||||
+4
-4
@@ -1,13 +1,13 @@
|
|||||||
"""Label who speaks (sherpa-onnx, CPU): run(name) reads out/<name>/transcript.txt -> diar_segments.json + DB lines (speaker-labelled)."""
|
"""Label who speaks (sherpa-onnx, CPU): run(name) reads out/<name>/transcript.txt -> diar_segments.json + DB lines (speaker-labelled)."""
|
||||||
import json, re, subprocess, time
|
import json, os, re, subprocess, time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import db
|
import db
|
||||||
|
|
||||||
M = Path(__file__).parent / "models"
|
M = Path(__file__).parent / "models"
|
||||||
# sherpa-onnx default is 1 thread (>10 min for a 40-min call); 8 threads: ~6 min. CUDA measured slower (>7 min, GPU ~5 W):
|
# sherpa-onnx default is 1 thread (>10 min for a 40-min call); 8 threads: ~6 min on 155H; physical-core count scales to bigger CPUs.
|
||||||
# tiny models + one embedding per segment -> transfer/launch overhead dominates.
|
# CUDA measured slower (>7 min, GPU ~5 W): tiny models + one embedding per segment -> transfer/launch overhead dominates.
|
||||||
THREADS = 8
|
THREADS = max(1, (os.cpu_count() or 2) // 2)
|
||||||
|
|
||||||
|
|
||||||
def roster_size(name, default=5):
|
def roster_size(name, default=5):
|
||||||
|
|||||||
+12
-8
@@ -1,7 +1,8 @@
|
|||||||
# /// script
|
# /// script
|
||||||
# requires-python = ">=3.10,<3.13"
|
# requires-python = ">=3.10,<3.13"
|
||||||
# dependencies = ["prefect>=3", "faster-whisper", "av>=14,<17", "nvidia-cublas-cu12", "nvidia-cudnn-cu12==9.*", "sherpa-onnx", "numpy", "imagehash", "Pillow", "markdown", "openvino-genai", "huggingface_hub"]
|
# dependencies = ["prefect>=3", "faster-whisper", "ctranslate2==4.8.*", "av>=14,<17", "nvidia-cublas-cu12", "nvidia-cudnn-cu12==9.*", "sherpa-onnx", "numpy", "imagehash", "Pillow", "markdown", "openvino-genai", "huggingface_hub"]
|
||||||
# ///
|
# ///
|
||||||
|
# ponytail: ctranslate2 4.8 links cublas64_12 (matches the nvidia-*-cu12 wheels); bump all three together when it moves to CUDA 13
|
||||||
"""Meeting pipeline. uv run --script flow.py <name> [--from STEP] [--speakers N] [--device cuda|npu] [--bench-npu]"""
|
"""Meeting pipeline. uv run --script flow.py <name> [--from STEP] [--speakers N] [--device cuda|npu] [--bench-npu]"""
|
||||||
import os
|
import os
|
||||||
os.environ.setdefault("PREFECT_API_URL", "http://127.0.0.1:4200/api")
|
os.environ.setdefault("PREFECT_API_URL", "http://127.0.0.1:4200/api")
|
||||||
@@ -17,7 +18,7 @@ from prefect.task_runners import ThreadPoolTaskRunner
|
|||||||
import audio, db, diarize, docs, llama, memory, report, shots, speakers, transcribe
|
import audio, db, diarize, docs, llama, memory, report, shots, speakers, transcribe
|
||||||
|
|
||||||
HERE = Path(__file__).parent
|
HERE = Path(__file__).parent
|
||||||
STEPS = ["audio", "transcribe", "diarize", "speakers", "shots", "docs", "report", "memory", "render"]
|
STEPS = ["audio", "transcribe", "diarize", "speakers", "shots", "docs", "report", "memory", "render", "title"]
|
||||||
|
|
||||||
|
|
||||||
def step_status(name, s):
|
def step_status(name, s):
|
||||||
@@ -89,18 +90,21 @@ def meeting(name: str, start_from: str = "audio", speakers: int = 0, model: str
|
|||||||
try:
|
try:
|
||||||
db.upsert_recording(name, flow_run_id=str(flow_run.id))
|
db.upsert_recording(name, flow_run_id=str(flow_run.id))
|
||||||
db.progress_start(name, start_from)
|
db.progress_start(name, start_from)
|
||||||
# shots (slow, one vision call per screen) depend only on the video: keep them when re-running an earlier step; an explicit "shots" run redoes them
|
# shots run every time unless the GUI toggle "Salta schermate" is on
|
||||||
sj, sd = db.out_dir(name) / "shots.json", db.out_dir(name) / "shots"
|
sj = db.out_dir(name) / "shots.json"
|
||||||
try: done = json.loads(sj.read_text(encoding="utf-8"))
|
try: done = json.loads(sj.read_text(encoding="utf-8"))
|
||||||
except (OSError, ValueError): done = []
|
except (OSError, ValueError): done = []
|
||||||
# complete = every referenced frame/crop is still on disk (a run cancelled mid-shots wipes them while shots.json is stale)
|
|
||||||
no_shots = (db.GLOBAL / "skip_shots.txt").exists() # GUI toggle "Salta schermate"
|
no_shots = (db.GLOBAL / "skip_shots.txt").exists() # GUI toggle "Salta schermate"
|
||||||
skip_shots = no_shots or (start_from != "shots" and bool(done) and all((sd / f).exists() for s in done for f in (s.get("file"), s.get("view")) if f))
|
skip_shots = no_shots
|
||||||
if no_shots and not done:
|
if no_shots and not done:
|
||||||
for f in ("shots.json", "glossary.json"): (db.out_dir(name) / f).write_text("[]")
|
for f in ("shots.json", "glossary.json"): (db.out_dir(name) / f).write_text("[]")
|
||||||
db.replace_shots(name, [])
|
db.replace_shots(name, [])
|
||||||
if skip_shots and go("shots"): print("shots skipped" if no_shots else "shots already done: skipped (run from 'shots' to redo)")
|
if skip_shots and go("shots"): print("shots skipped")
|
||||||
if start_from == "render":
|
if start_from == "title":
|
||||||
|
L.ensure(vision=False)
|
||||||
|
report.retitle(name)
|
||||||
|
memory.run(name, link=False)
|
||||||
|
elif start_from == "render":
|
||||||
memory.run(name, link=False)
|
memory.run(name, link=False)
|
||||||
else:
|
else:
|
||||||
if go("audio"): t_audio(name)
|
if go("audio"): t_audio(name)
|
||||||
|
|||||||
+22
-2
@@ -9,6 +9,7 @@ CHOICE = HERE / "out" / "_global" / "llm.txt" # GUI header: "<shots model> <rep
|
|||||||
_Q = ["-ctk", "q8_0", "-ctv", "q8_0", "-fa", "on", "-np", "1"] # KV q8: no measurable loss; V q4 made the 4B loop
|
_Q = ["-ctk", "q8_0", "-ctv", "q8_0", "-fa", "on", "-np", "1"] # KV q8: no measurable loss; V q4 made the 4B loop
|
||||||
_IMG = ["--image-min-tokens", "1024", "--image-max-tokens", "1536"] # 1024 = Qwen-VL grounding min; 1536 cap: same quality as 3.7k, 3x faster
|
_IMG = ["--image-min-tokens", "1024", "--image-max-tokens", "1536"] # 1024 = Qwen-VL grounding min; 1536 cap: same quality as 3.7k, 3x faster
|
||||||
# key -> (label, model, mmproj, vision args (shots), text args (report/ask: no mmproj, more VRAM for layers/batch))
|
# key -> (label, model, mmproj, vision args (shots), text args (report/ask: no mmproj, more VRAM for layers/batch))
|
||||||
|
# Values below are the 4 GB profile; _fit() strips -ngl/-ot/--cpu-moe on >= 7 GiB GPUs.
|
||||||
MODELS = {
|
MODELS = {
|
||||||
# MoE experts in RAM (needs ~48+ GB RAM). Vision: encoder on GPU (CPU encoder was ~100 s/shot), so only 30/40 attention
|
# MoE experts in RAM (needs ~48+ GB RAM). Vision: encoder on GPU (CPU encoder was ~100 s/shot), so only 30/40 attention
|
||||||
# layers fit (-ngl 25 halves gen speed). Text: no encoder -> all layers + -ub 2048 (prompt eval 230 -> 340 tok/s).
|
# layers fit (-ngl 25 halves gen speed). Text: no encoder -> all layers + -ub 2048 (prompt eval 230 -> 340 tok/s).
|
||||||
@@ -24,6 +25,25 @@ MODELS = {
|
|||||||
}
|
}
|
||||||
PORT = 18081
|
PORT = 18081
|
||||||
EMBED, EMBED_PORT = MD / "bge-m3-Q8_0.gguf", 18082
|
EMBED, EMBED_PORT = MD / "bge-m3-Q8_0.gguf", 18082
|
||||||
|
|
||||||
|
@functools.cache
|
||||||
|
def vram_mib():
|
||||||
|
"""Largest NVIDIA GPU's total VRAM in MiB; 0 without NVIDIA driver."""
|
||||||
|
try: return max(int(x) for x in subprocess.run(["nvidia-smi", "--query-gpu=memory.total", "--format=csv,noheader,nounits"],
|
||||||
|
capture_output=True, text=True, timeout=10).stdout.split())
|
||||||
|
except (OSError, ValueError, subprocess.SubprocessError): return 0
|
||||||
|
|
||||||
|
_TUNED = {"-ngl": 1, "-ot": 1, "--cpu-moe": 0} # 4 GB placement flags -> number of values they take
|
||||||
|
def _fit(args, vision):
|
||||||
|
"""GPUs >= 7 GiB: drop the 4 GB hand-tuned layer/expert placement so llama.cpp --fit (default on) fills VRAM.
|
||||||
|
Vision keeps 3 GiB margin: --fit sizes only the LLM, the mmproj encoder loads after it."""
|
||||||
|
if vram_mib() < 7168: return args
|
||||||
|
out, it = [], iter(args)
|
||||||
|
for a in it:
|
||||||
|
if a in _TUNED:
|
||||||
|
for _ in range(_TUNED[a]): next(it)
|
||||||
|
else: out.append(a)
|
||||||
|
return out + (["-fitt", "3072"] if vision else [])
|
||||||
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # corp proxy must not see localhost
|
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # corp proxy must not see localhost
|
||||||
|
|
||||||
PROXY = "http://zproxy.idg.audi.vwg:9400" # corp proxy for internet calls (docs.py twg, cloud LLMs)
|
PROXY = "http://zproxy.idg.audi.vwg:9400" # corp proxy for internet calls (docs.py twg, cloud LLMs)
|
||||||
@@ -164,12 +184,12 @@ def start(vision=True, port=PORT, log="llama.log"):
|
|||||||
"""Start llama-server with current() model; vision=False: text profile (no mmproj). None if already running."""
|
"""Start llama-server with current() model; vision=False: text profile (no mmproj). None if already running."""
|
||||||
if current(vision) in REMOTE: return None
|
if current(vision) in REMOTE: return None
|
||||||
_, model, mmproj, vargs, targs = MODELS[current(vision)]
|
_, model, mmproj, vargs, targs = MODELS[current(vision)]
|
||||||
return _spawn(["-m", str(model), *(["--mmproj", str(mmproj), *vargs] if vision else targs), "--jinja"], port, log)
|
return _spawn(["-m", str(model), *(["--mmproj", str(mmproj), *_fit(vargs, True)] if vision else _fit(targs, False)), "--jinja"], port, log)
|
||||||
|
|
||||||
def start_embed(log="embed.log"):
|
def start_embed(log="embed.log"):
|
||||||
"""bge-m3 embeddings on CPU (never competes with the GPU model). None if already running."""
|
"""bge-m3 embeddings on CPU (never competes with the GPU model). None if already running."""
|
||||||
if not EMBED.exists(): raise FileNotFoundError(f"{EMBED} missing: hf download gpustack/bge-m3-GGUF bge-m3-Q8_0.gguf --local-dir models")
|
if not EMBED.exists(): raise FileNotFoundError(f"{EMBED} missing: hf download gpustack/bge-m3-GGUF bge-m3-Q8_0.gguf --local-dir models")
|
||||||
return _spawn(["-m", str(EMBED), "--embeddings", "--pooling", "cls", "-ngl", "0", "-c", "8192", "-b", "2048", "-ub", "2048"], EMBED_PORT, log)
|
return _spawn(["-m", str(EMBED), "--embeddings", "--pooling", "cls", "-ngl", "0", "-dev", "none", "-c", "8192", "-b", "2048", "-ub", "2048"], EMBED_PORT, log)
|
||||||
|
|
||||||
OMP_BUILD = "https://build.stencil.so/api/products/omp/latest/windows-x86_64?channel=stable"
|
OMP_BUILD = "https://build.stencil.so/api/products/omp/latest/windows-x86_64?channel=stable"
|
||||||
MODELS_YML = """providers:
|
MODELS_YML = """providers:
|
||||||
|
|||||||
+6
-3
@@ -13,12 +13,15 @@ module.exports = {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
// highest CUDA the driver supports ("CUDA Version: 13.0", newer drivers "CUDA UMD Version: 13.4" in nvidia-smi) -> llama.cpp build; no NVIDIA/driver -> CPU build
|
// highest CUDA the driver supports ("CUDA Version: 13.0", newer drivers "CUDA UMD Version: 13.4" in nvidia-smi) -> llama.cpp build; no NVIDIA/driver -> CPU build
|
||||||
|
// CUDA 13 also needs compute capability >= 7.5 (Maxwell/Pascal/Volta dropped, even on R580+ drivers)
|
||||||
method: async (req, ondata, kernel) => {
|
method: async (req, ondata, kernel) => {
|
||||||
let m = null
|
let m = null, cc = 0
|
||||||
try { m = execFileSync("nvidia-smi", { encoding: "utf8" }).match(/CUDA (?:UMD )?Version:\s*(\d+)\.(\d+)/) } catch (e) {}
|
try { m = execFileSync("nvidia-smi", { encoding: "utf8" }).match(/CUDA (?:UMD )?Version:\s*(\d+)\.(\d+)/) } catch (e) {}
|
||||||
|
// lowest GPU wins
|
||||||
|
try { cc = Math.min(...execFileSync("nvidia-smi", ["--query-gpu=compute_cap", "--format=csv,noheader"], { encoding: "utf8" }).trim().split(/\r?\n/).map(Number)) } catch (e) {}
|
||||||
const v = m ? +m[1] * 100 + +m[2] : 0
|
const v = m ? +m[1] * 100 + +m[2] : 0
|
||||||
const build = v >= 1300 ? "cuda-13.4" : v >= 1204 ? "cuda-12.4" : "cpu"
|
const build = v >= 1300 && cc >= 7.5 ? "cuda-13.4" : v >= 1204 ? "cuda-12.4" : "cpu"
|
||||||
ondata({ raw: `CUDA: ${m ? m[1] + "." + m[2] : "none"} -> llama.cpp ${build}\r\n` })
|
ondata({ raw: `CUDA: ${m ? m[1] + "." + m[2] : "none"}, compute ${cc || "?"} -> llama.cpp ${build}\r\n` })
|
||||||
return { build }
|
return { build }
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user