diff --git a/app/common.py b/app/common.py index b38ee02..1eac167 100644 --- a/app/common.py +++ b/app/common.py @@ -8,12 +8,14 @@ for sp in site.getsitepackages(): 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): """CUDA if it really works (probe one decode), else CPU int8.""" 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]) return m, "cuda" except Exception as e: 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" diff --git a/app/diarize.py b/app/diarize.py index f453096..5531b8c 100644 --- a/app/diarize.py +++ b/app/diarize.py @@ -1,13 +1,13 @@ """Label who speaks (sherpa-onnx, CPU): run(name) reads out//transcript.txt -> diar_segments.json + DB lines (speaker-labelled).""" -import json, re, subprocess, time +import json, os, re, subprocess, time from pathlib import Path import numpy as np import db 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): -# tiny models + one embedding per segment -> transfer/launch overhead dominates. -THREADS = 8 +# 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. +# CUDA measured slower (>7 min, GPU ~5 W): tiny models + one embedding per segment -> transfer/launch overhead dominates. +THREADS = max(1, (os.cpu_count() or 2) // 2) def roster_size(name, default=5): diff --git a/app/flow.py b/app/flow.py index 3c69fb4..1bf1a4d 100644 --- a/app/flow.py +++ b/app/flow.py @@ -1,7 +1,8 @@ # /// script # 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 [--from STEP] [--speakers N] [--device cuda|npu] [--bench-npu]""" import os 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 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): @@ -89,18 +90,21 @@ def meeting(name: str, start_from: str = "audio", speakers: int = 0, model: str try: db.upsert_recording(name, flow_run_id=str(flow_run.id)) 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 - sj, sd = db.out_dir(name) / "shots.json", db.out_dir(name) / "shots" + # shots run every time unless the GUI toggle "Salta schermate" is on + sj = db.out_dir(name) / "shots.json" try: done = json.loads(sj.read_text(encoding="utf-8")) 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" - 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: for f in ("shots.json", "glossary.json"): (db.out_dir(name) / f).write_text("[]") 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 start_from == "render": + if skip_shots and go("shots"): print("shots skipped") + 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) else: if go("audio"): t_audio(name) diff --git a/app/llama.py b/app/llama.py index 87a5ef1..e7a2ab8 100644 --- a/app/llama.py +++ b/app/llama.py @@ -9,6 +9,7 @@ CHOICE = HERE / "out" / "_global" / "llm.txt" # GUI header: " (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 = { # 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). @@ -24,6 +25,25 @@ MODELS = { } PORT = 18081 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 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.""" if current(vision) in REMOTE: return None _, 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"): """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") - 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" MODELS_YML = """providers: diff --git a/install.js b/install.js index cddd079..0f33e01 100644 --- a/install.js +++ b/install.js @@ -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 + // CUDA 13 also needs compute capability >= 7.5 (Maxwell/Pascal/Volta dropped, even on R580+ drivers) 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) {} + // 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 build = v >= 1300 ? "cuda-13.4" : v >= 1204 ? "cuda-12.4" : "cpu" - ondata({ raw: `CUDA: ${m ? m[1] + "." + m[2] : "none"} -> llama.cpp ${build}\r\n` }) + 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"}, compute ${cc || "?"} -> llama.cpp ${build}\r\n` }) return { build } } },