mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
raea cloud ingest: index jobs on Modal (ingest.py index_job, POST/GET /v1/index-jobs) on an L4 (EmbeddingGemma 2 at fp16 on CUDA 13; build/Dockerfile.gpu), the search-words server on the CPU, gpu_probe to check the GPU; docs/cloud-ingest.feature IG8 now raea's indexer into turbopuffer, Enterprise only (raea cloud is Enterprise only, Shane 11-24), with IG6 and IG9 marked built
This commit is contained in:
1 parent
4e12541984
commit
96adb3ecfb
2 files changed
+138
-6
No files matched your search
@@ -51,6 +51,8 @@ Feature: raea cloud: a synced folder is pictured, understood, embedded and organ
|
||||
a final cut, a brief, a script, a logo, a voiceover, a reference; its subject; its client or brand; its format,
|
||||
9x16 or 16x9; its length), and for each tag who said it and why
|
||||
Scenario: IG6. raea's model reads first; the workspace's agent when there's none
|
||||
(built 11-24 with raea's model as a vision model on OpenRouter, tagger.ts: description, role, client, tags with
|
||||
why, on the item and its turbopuffer rows; raea ask's clef model takes its place when it's deployed)
|
||||
Given the workspace's plan has raea's ask model (raea ask, docs/ask.feature: clef-omni on the plan's pool)
|
||||
Then the files are read by it, batched, the spend on the pool
|
||||
Otherwise they are read by the workspace's own connected agent on raea cloud's box (Claude Code on its Claude, or
|
||||
@@ -60,13 +62,20 @@ Feature: raea cloud: a synced folder is pictured, understood, embedded and organ
|
||||
When someone removes or changes a tag, or moves a file to another folder
|
||||
Then raea never puts it back, and the next files like it are read with that correction in the prompt
|
||||
|
||||
Rule: every file is embedded by its kind, once
|
||||
Scenario: IG8. Embeddings run on Modal, in raea's own models
|
||||
Then pictures and video frames are embedded by SigLIP 2 (the model raea index uses on the Mac, so a desktop's and
|
||||
the cloud's vectors compare), sounds by CLAP, and words (documents, transcripts, descriptions) by the text model
|
||||
search already uses; on Modal (sdk/cloud/deploy/modal, beside the render farm), a GPU only while there's work
|
||||
And a vector is kept per file version and model, never made twice, and dropped with its file
|
||||
Rule: every file is embedded by its kind, once, into turbopuffer (Enterprise)
|
||||
Scenario: IG8. raea's own library indexer runs on Modal and writes to turbopuffer
|
||||
Then each file is indexed by the desktop's own indexer (apps/app host/library/index-file.ts, in the cloud
|
||||
indexer's image: EmbeddingGemma 2 for pictures, shots, sound and words, TransNetV2 cuts, Whisper; a document's
|
||||
text in windows), as a job on Modal (ingest.py index_job, any length), so a desktop's and the cloud's vectors
|
||||
compare; EmbeddingGemma 2 on a GPU (RAEA_INDEX_GPU=L4: fp16, CUDA 13) while there's work, else the CPU at q8
|
||||
And its rows go to turbopuffer in raea-api's layout, one namespace a workspace (raea-cloud-<workspace>.
|
||||
embeddinggemma-2@768), a row per segment and modality, replaced when the file is indexed again
|
||||
And only an Enterprise workspace is indexed in the cloud (raea cloud is Enterprise only, Shane 11-24); the raea
|
||||
app's Pro and Team plans embed on their own computers and keep their index in turbopuffer through raea-api,
|
||||
Free on the Mac
|
||||
(built 11-24: index-run.ts, tools/library-index cloud.ts, cloud-cli.ts, cloud-server.ts)
|
||||
Scenario: IG9. Search finds a file by what's in it
|
||||
(built 11-24: search.ts deep, turbopuffer's nearest segments, a hit's at {t0, t1})
|
||||
When the person searches "girl laughing on a street corner, vertical"
|
||||
Then the words are matched against pictures and frames (SigLIP's text tower), descriptions and transcripts, and
|
||||
tags, fused into one ranking; a hit says where in a video it is
|
||||
|
||||
@@ -4,6 +4,12 @@
|
||||
#
|
||||
# MODAL_PROFILE=raea modal deploy deploy/modal/ingest.py
|
||||
#
|
||||
# indexer (its own URL, raea--raea-ingest-indexer…): raea's library indexer (tools/library-index cloud-server.ts, the
|
||||
# desktop's indexFile in the cloud indexer's image: EmbeddingGemma 2 for pictures, shots, sound and words, TransNetV2
|
||||
# cuts, Whisper base): POST /v1/index {url, name, kind} -> {fragment, posters}; POST /v1/embed {texts} -> query
|
||||
# vectors. raea cloud writes the fragments to turbopuffer in raea-api's layout (IG8). Before deploying, bundle it:
|
||||
# tools/library-index/cloud-build.sh
|
||||
#
|
||||
# POST /v1/frame {url, at?} a video's frame as a JPEG 640 px on its long side; at is where, as a fraction of its
|
||||
# length (0.1 when left out: past a fade from black, before the end card). IG4
|
||||
# GET /healthz
|
||||
@@ -17,6 +23,9 @@ import tempfile
|
||||
|
||||
import modal
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
LIB = os.path.abspath(os.path.join(HERE, "..", "..", "..", "..", "tools", "library-index"))
|
||||
|
||||
app = modal.App("raea-ingest", image=modal.Image.debian_slim(python_version="3.12").apt_install("ffmpeg").pip_install("fastapi[standard]"))
|
||||
secret = modal.Secret.from_name("raea-ingest")
|
||||
|
||||
@@ -60,6 +69,32 @@ def api():
|
||||
if req.headers.get("authorization", "").removeprefix("Bearer ") != token:
|
||||
raise HTTPException(401, "a raea ingest token is needed (Authorization: Bearer)")
|
||||
|
||||
@web.post("/v1/index-jobs")
|
||||
async def submit(req: Request):
|
||||
check(req)
|
||||
b = await req.json()
|
||||
if not isinstance(b.get("url"), str) or not b["url"].startswith("https://"):
|
||||
raise HTTPException(400, "url is the file's https address")
|
||||
if b.get("kind") not in ("video", "image", "audio", "doc"):
|
||||
raise HTTPException(400, "kind is one of video, image, audio, doc")
|
||||
call = await index_job.spawn.aio(b["url"], str(b.get("name") or "file"), b["kind"])
|
||||
return {"id": call.object_id}
|
||||
|
||||
@web.get("/v1/index-jobs/{job}")
|
||||
async def collect(job: str, req: Request):
|
||||
check(req)
|
||||
try:
|
||||
out = await modal.FunctionCall.from_id(job).get.aio(timeout=0)
|
||||
except modal.exception.FunctionTimeoutError:
|
||||
return {"state": "failed", "error": "the file took over an hour"}
|
||||
except (TimeoutError, modal.exception.TimeoutError):
|
||||
return {"state": "running"}
|
||||
except Exception as e:
|
||||
return {"state": "failed", "error": str(e)[:300]}
|
||||
if out.get("error"):
|
||||
return {"state": "failed", **out}
|
||||
return {"state": "done", **out}
|
||||
|
||||
@web.get("/healthz")
|
||||
def healthz():
|
||||
return PlainTextResponse("ok")
|
||||
@@ -92,3 +127,91 @@ def api():
|
||||
return Response(jpg, media_type="image/jpeg")
|
||||
|
||||
return web
|
||||
|
||||
|
||||
# the index jobs' GPU: an L4 by default (EmbeddingGemma 2 at fp16 on CUDA 13: loaded in 6 s, a batch in under one);
|
||||
# RAEA_INDEX_GPU= (empty) at deploy for the CPU at q8
|
||||
GPU = os.environ.get("RAEA_INDEX_GPU", "L4") or None
|
||||
|
||||
# the cloud indexer's own image (tools/library-index/Dockerfile: Node, ffmpeg, EmbeddingGemma 2's and Whisper's weights
|
||||
# baked in) on CUDA 13 with cuDNN 9 (onnxruntime-node 1.30's CUDA provider links CUDA 13, though its package says cuda12), its fp16 weights for the GPU beside the q8
|
||||
# ones, pdftotext for documents and the raea cloud server. EmbeddingGemma 2 (the fingerprints: pictures, shots, sound,
|
||||
# words) runs on the GPU; Whisper, TransNetV2's cuts and ffmpeg on the CPU beside it
|
||||
def indexer_image_for(gpu):
|
||||
return (
|
||||
# on a GPU, build/Dockerfile.gpu (cloud-build.sh: the CUDA 13 base and fp16 weights written in; Modal's builds
|
||||
# don't take a build argument in FROM, so BASE as an argument left a plain Ubuntu without CUDA)
|
||||
modal.Image.from_dockerfile(os.path.join(LIB, "build", "Dockerfile.gpu") if gpu else os.path.join(LIB, "Dockerfile"), context_dir=LIB, add_python="3.12")
|
||||
.apt_install("poppler-utils")
|
||||
.env({"RAEA_LIBRARY_DEVICE": "cuda", "RAEA_LIBRARY_DTYPE": "fp16"} if gpu else {})
|
||||
.add_local_file(os.path.join(LIB, "build", "cloud-server.mjs"), "/app/cloud-server.mjs")
|
||||
.add_local_file(os.path.join(LIB, "build", "cloud-cli.mjs"), "/app/cloud-cli.mjs")
|
||||
)
|
||||
|
||||
|
||||
# index jobs on the GPU when there is one; the search-words server on the CPU (a query is one short text, seconds on a
|
||||
# CPU, and a GPU held five minutes for it isn't worth it; q8 and fp16 vectors of the same model compare)
|
||||
indexer_image = indexer_image_for(GPU)
|
||||
server_image = indexer_image_for(None)
|
||||
|
||||
|
||||
# one file indexed as a job (tools/library-index cloud-cli.ts), for a file of any length: raea cloud submits it through
|
||||
# the API's POST /v1/index-jobs and collects it with GET /v1/index-jobs/ID on its next alarm (index-run.ts)
|
||||
@app.function(image=indexer_image, gpu=GPU, cpu=4, memory=16384, timeout=3600, max_containers=12, scaledown_window=120)
|
||||
def index_job(url: str, name: str, kind: str) -> dict:
|
||||
import json
|
||||
import subprocess as sp
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
inp, out = os.path.join(d, "in.json"), os.path.join(d, "out.json")
|
||||
with open(inp, "w") as f:
|
||||
json.dump({"url": url, "name": name, "kind": kind}, f)
|
||||
r = sp.run(["node", "/app/cloud-cli.mjs", inp, out], cwd="/app", capture_output=True, text=True, timeout=3500)
|
||||
if r.returncode != 0 or not os.path.exists(out):
|
||||
return {"error": f"the indexer stopped ({r.returncode}): {(r.stderr or '')[-300:]}"}
|
||||
with open(out) as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
# a GPU only while there's work: five idle minutes and the container goes
|
||||
@app.function(image=server_image, cpu=4, memory=12288, secrets=[secret], timeout=3600, scaledown_window=300)
|
||||
@modal.concurrent(max_inputs=4)
|
||||
@modal.web_server(8080, startup_timeout=180)
|
||||
def indexer():
|
||||
import subprocess as sp
|
||||
|
||||
sp.Popen(["node", "/app/cloud-server.mjs"], cwd="/app", env={**os.environ, "PORT": "8080"})
|
||||
|
||||
|
||||
# the GPU checked: RAEA_INDEX_GPU=L4 MODAL_PROFILE=raea modal run deploy/modal/ingest.py::gpu_probe. EmbeddingGemma 2
|
||||
# loaded on the GPU at fp16 and two texts embedded, each step timed
|
||||
PROBE = """
|
||||
const t0 = Date.now(), log = (...a) => console.log(`[${((Date.now() - t0) / 1000).toFixed(1)}s]`, ...a)
|
||||
const tf = await import("@huggingface/transformers")
|
||||
tf.env.cacheDir = "/models"
|
||||
const id = "onnx-community/embeddinggemma-2-ONNX"
|
||||
const p = await tf.AutoProcessor.from_pretrained(id)
|
||||
log("model fp16 on", process.env.RAEA_LIBRARY_DEVICE)
|
||||
const m = await tf.AutoModel.from_pretrained(id, { dtype: "fp16", device: process.env.RAEA_LIBRARY_DEVICE || "cpu" })
|
||||
log("loaded")
|
||||
for (let k = 0; k < 2; k++) { const o = await m(await p(["a white rabbit in a forest", "a quarterly sales spreadsheet"])); log("two texts", o.sentence_embedding.dims, o.sentence_embedding.tolist()[0].slice(0, 3)) }
|
||||
process.exit(0)
|
||||
"""
|
||||
|
||||
|
||||
@app.function(image=indexer_image, gpu=GPU, cpu=4, memory=16384, timeout=900)
|
||||
def gpu_probe() -> str:
|
||||
import subprocess as sp
|
||||
|
||||
def run(cmd: str, t: int = 600) -> str:
|
||||
r = sp.run(["bash", "-c", cmd], capture_output=True, text=True, timeout=t, cwd="/app")
|
||||
return (r.stdout + r.stderr)[-3000:]
|
||||
|
||||
out = run("nvidia-smi | grep -o 'CUDA Version: [0-9.]*'; nvidia-smi --query-gpu=name --format=csv,noheader")
|
||||
out += run("echo CUDA_VERSION=$CUDA_VERSION NV_CUDA=$NV_CUDA_LIB_VERSION LD=$LD_LIBRARY_PATH; ls -d /usr/local/cuda* 2>&1; find / -xdev \\( -name 'libcublas.so*' -o -name 'libcudart.so*' -o -name 'libcudnn.so*' \\) 2>/dev/null | head; cat /etc/os-release | head -2")
|
||||
out += run("ldd node_modules/onnxruntime-node/bin/napi-v*/linux/x64/libonnxruntime_providers_cuda.so | grep 'not found' || echo 'cuda provider: every library found'")
|
||||
with open("/app/probe.mjs", "w") as f:
|
||||
f.write(PROBE)
|
||||
out += run("node probe.mjs 2>&1 | cut -c1-300")
|
||||
print(out)
|
||||
return out
|
||||
Reference in new issue
Block a user