Spaces:
Paused
Paused
Update the CyberForge ML service
Browse filesFiles changed (4)
- Dockerfile+10
- app.py+89-11
- file_scan.pyAdded+116
- requirements.txt+8
123456# Python 3.11: the version this image has been built and run withFROM python:3.11-slimWORKDIR /app# Install system dependencies12345678910111213141516# Python 3.11: the version this image has been built and run withFROM python:3.11-slim# GPU runtime, used only when the hardware has a GPU (on CPU hardware the image behaves as# before). llama-cpp-python has no prebuilt CUDA wheel for the pinned version and compiling# it here exceeds the Space build limit, so it is compiled once by# ml-services/gpu_runtime/build_job.py and downloaded from the model repo at a pinned commit.# The CUDA libraries it links come from NVIDIA's own wheels; the driver comes from the host.ARG LLAMA_CUDA_WHEEL=https://huggingface.co/Che237/cyberforge-models/resolve/ef1944b0e4a4a89d638b95c8461528daea4d83a0/runtime/llama_cpp_python-0.3.36-cuda124-linux_x86_64.whlRUN pip install --no-cache-dir --no-deps --target /opt/cuda-pkgs nvidia-cuda-runtime-cu12==12.4.127 nvidia-cublas-cu12==12.4.5.8 nvidia-nccl-cu12==2.21.5 && python -c "import sys,urllib.request,zipfile,os; urllib.request.urlretrieve(sys.argv[1], '/tmp/llama.whl'); zipfile.ZipFile('/tmp/llama.whl').extractall('/opt/llama-cuda'); os.remove('/tmp/llama.whl')" "$LLAMA_CUDA_WHEEL" && test -d /opt/llama-cuda/llama_cpp# On GPU hardware the host's NVIDIA runtime mounts the driver when these are set.ENV NVIDIA_VISIBLE_DEVICES=all NVIDIA_DRIVER_CAPABILITIES=compute,utilityWORKDIR /app# Install system dependencies
66 unmodified lines676869707172737475767778705 unmodified lines78478578678778878913 unmodified lines8038048058068078082 unmodified lines8118128138148158168178188198208218228238248258268278 unmodified lines836837838839840841842843844845846847848849850851377 unmodified lines12291230123112321233123434 unmodified lines126912701271127212731274127512761277127812794 unmodified lines12841285128612871288128912908 unmodified lines1299130013011302130313041305363 unmodified lines16691670167116721673167485 unmodified lines176017611762176317641765621 unmodified lines23872388238923902391239266 unmodified lines# set here; on the free cpu-basic tier (2 vCPU) stay around 2B parameters or the# answers will not fit inside the callers' timeouts.from security_knowledge import ground_prompt, finish_grounded_answer, reference_grammarLOCAL_LLM_REPO = os.environ.get("LOCAL_LLM_REPO", "unsloth/Qwen3.5-2B-GGUF")LOCAL_LLM_REVISION = os.environ.get("LOCAL_LLM_REVISION") or NoneLOCAL_LLM_FILE = os.environ.get("LOCAL_LLM_FILE", "Qwen3.5-2B-Q4_K_M.gguf")LOCAL_LLM_CTX = int(os.environ.get("LOCAL_LLM_CTX", "4096"))LOCAL_LLM_THREADS = int(os.environ.get("LOCAL_LLM_THREADS", "2"))LOCAL_LLM_MAX_TOKENS = int(os.environ.get("LOCAL_LLM_MAX_TOKENS", "320"))LOCAL_LLM_TEMPERATURE = float(os.environ.get("LOCAL_LLM_TEMPERATURE", "0.3"))LOCAL_LLM_MAX_INPUT_CHARS = int(os.environ.get("LOCAL_LLM_MAX_INPUT_CHARS", "2400"))705 unmodified linesdef __init__(self):self.llm = Noneself.error: Optional[str] = Noneself._chatml = Falseself._prefill = ""self._load_lock = threading.Lock()13 unmodified lines"loaded": self.ready,"loading": self._load_lock.locked(),"error": self.error,}def load(self):2 unmodified linesif self.llm is not None or self.error:return self.llmtry:from llama_cpp import Llamatry:path = hf_hub_download(repo_id=LOCAL_LLM_REPO, filename=LOCAL_LLM_FILE, revision=LOCAL_LLM_REVISION, token=HF_TOKEN or None)except Exception:# A stale HF_TOKEN must not block the download of a public modelpath = hf_hub_download(repo_id=LOCAL_LLM_REPO, filename=LOCAL_LLM_FILE, revision=LOCAL_LLM_REVISION, token=False)self._probe(path)# n_threads_batch (prompt processing) defaults to the host's core# count, which a Space container reports far above its 2 vCPUs.llm = Llama(model_path=path, n_ctx=LOCAL_LLM_CTX, n_threads=LOCAL_LLM_THREADS,n_threads_batch=LOCAL_LLM_THREADS, verbose=False)template = str((llm.metadata or {}).get("tokenizer.chat_template", ""))self._chatml = "<|im_start|>" in template# Qwen3.5 answers directly when the assistant turn opens with an8 unmodified linesreturn self.llm@staticmethoddef _probe(path: str) -> None:"""Load the model once in a child process. A native crash there (forexample a CPU instruction the prebuilt wheel needs but this machinelacks) raises here instead of killing the API process."""code = ("import sys; from llama_cpp import Llama; ""m = Llama(model_path=sys.argv[1], n_ctx=256, n_threads=1, n_threads_batch=1, verbose=False); ""m.create_completion('Hi', max_tokens=1)")r = subprocess.run([sys.executable, "-c", code, path], capture_output=True, text=True, timeout=300)if r.returncode != 0:raise RuntimeError(f"llama.cpp probe exited with {r.returncode}: {(r.stderr or '')[-200:]}")377 unmodified linesPUBLIC_PATHS = {"/", "/health"}# These check the owner's Hugging Face token themselves (owner_token below).OWNER_PATHS = {"/api/admin/train", "/api/admin/train/status"}34 unmodified linesreturn await _reply(send, 503, "This service has no service key configured", "SERVICE_KEY_NOT_CONFIGURED")if not service_key_valid(headers.get(SERVICE_KEY_HEADER.encode())):return await _reply(send, 401, "A valid service key is required", "SERVICE_KEY_REQUIRED")stated = headers.get(b"content-length")if stated is not None:try:if int(stated) > ML_MAX_BODY_BYTES:return await _reply(send, 413, f"Request body is over {ML_MAX_BODY_BYTES} bytes", "BODY_TOO_LARGE")except ValueError:return await _reply(send, 400, "Content-Length must be a number", "BAD_CONTENT_LENGTH")received = 04 unmodified linesmessage = await receive()if message["type"] == "http.request":received += len(message.get("body", b""))if received > ML_MAX_BODY_BYTES:raise BodyTooLarge()return message8 unmodified linesexcept BodyTooLarge:if started:raiseawait _reply(send, 413, f"Request body is over {ML_MAX_BODY_BYTES} bytes", "BODY_TOO_LARGE")# Added last, so it runs first: before CORS and every route.363 unmodified linesreturn {**result, "answered": True, "result_kind": "reasoning_text"}CAPABILITIES_SCHEMA = "cyberforge.ml.capabilities.v1"SERVICE_VERSION = "2.0.0"BATCH_MAX_URLS = 2085 unmodified lines"concurrent_generations": 1,},},],"limits": {"max_body_bytes": ML_MAX_BODY_BYTES, "batch_max_urls": BATCH_MAX_URLS},"not_offered": [621 unmodified linesml_loader.initialize()# Load the chat model in the background so the API answers health checks at oncethreading.Thread(target=local_llm.load, name="local-llm-loader", daemon=True).start()logger.info("✅ Services initialized")app = api66 unmodified lines676869707172737475767778798081828384858687888990919293949596705 unmodified lines80280380480580680780880913 unmodified lines8238248258268278288298308312 unmodified lines8348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728 unmodified lines881882883884885886887888889890891892893894895896897898899900901377 unmodified lines1279128012811282128312841285128634 unmodified lines1321132213231324132513261327132813291330133113324 unmodified lines13371338133913401341134213438 unmodified lines1352135313541355135613571358363 unmodified lines1722172317241725172617271728172917301731173217331734173517361737173885 unmodified lines1824182518261827182818291830183118321833183418351836183718381839184018411842621 unmodified lines246424652466246724682469247066 unmodified lines# set here; on the free cpu-basic tier (2 vCPU) stay around 2B parameters or the# answers will not fit inside the callers' timeouts.from security_knowledge import ground_prompt, finish_grounded_answer, reference_grammarfrom file_scan import file_malware, FILE_SCAN_MAX_BYTESLOCAL_LLM_REPO = os.environ.get("LOCAL_LLM_REPO", "unsloth/Qwen3.5-2B-GGUF")LOCAL_LLM_REVISION = os.environ.get("LOCAL_LLM_REVISION") or NoneLOCAL_LLM_FILE = os.environ.get("LOCAL_LLM_FILE", "Qwen3.5-2B-Q4_K_M.gguf")LOCAL_LLM_CTX = int(os.environ.get("LOCAL_LLM_CTX", "4096"))LOCAL_LLM_THREADS = int(os.environ.get("LOCAL_LLM_THREADS", "2"))# The CUDA build of llama.cpp and the CUDA libraries it links (see the Dockerfile).# Used only when the host provides an NVIDIA driver; otherwise the CPU wheel is.LLAMA_CUDA_DIR = os.environ.get("LLAMA_CUDA_DIR", "/opt/llama-cuda")CUDA_LIBS_DIRS = [d for d in os.environ.get("CUDA_LIBS_DIRS", "/opt/cuda-pkgs/nvidia/cuda_runtime/lib:/opt/cuda-pkgs/nvidia/nccl/lib:/opt/cuda-pkgs/nvidia/cublas/lib").split(":") if d]LOCAL_LLM_GPU = os.environ.get("LOCAL_LLM_GPU", "auto").lower() # auto | offdef gpu_runtime_present() -> bool:"""Whether this machine has an NVIDIA driver and the image has the CUDA build."""if LOCAL_LLM_GPU == "off" or not os.path.isdir(os.path.join(LLAMA_CUDA_DIR, "llama_cpp")):return Falsetry:import ctypesctypes.CDLL("libcuda.so.1")return Trueexcept OSError:return FalseLOCAL_LLM_MAX_TOKENS = int(os.environ.get("LOCAL_LLM_MAX_TOKENS", "320"))LOCAL_LLM_TEMPERATURE = float(os.environ.get("LOCAL_LLM_TEMPERATURE", "0.3"))LOCAL_LLM_MAX_INPUT_CHARS = int(os.environ.get("LOCAL_LLM_MAX_INPUT_CHARS", "2400"))705 unmodified linesdef __init__(self):self.llm = Noneself.error: Optional[str] = Noneself.accelerator = "cpu"self.gpu_error: Optional[str] = Noneself._chatml = Falseself._prefill = ""self._load_lock = threading.Lock()13 unmodified lines"loaded": self.ready,"loading": self._load_lock.locked(),"error": self.error,# "cuda" only when the model was actually loaded onto a GPU"accelerator": self.accelerator if self.ready else None,"gpu_error": self.gpu_error,}def load(self):2 unmodified linesif self.llm is not None or self.error:return self.llmtry:try:path = hf_hub_download(repo_id=LOCAL_LLM_REPO, filename=LOCAL_LLM_FILE, revision=LOCAL_LLM_REVISION, token=HF_TOKEN or None)except Exception:# A stale HF_TOKEN must not block the download of a public modelpath = hf_hub_download(repo_id=LOCAL_LLM_REPO, filename=LOCAL_LLM_FILE, revision=LOCAL_LLM_REVISION, token=False)gpu = Falseif gpu_runtime_present():# Try the CUDA build in a child process first; if it cannot load the# model on the GPU, say why and carry on with the CPU wheel.try:self._probe(path, gpu=True)gpu = Trueexcept Exception as e:self.gpu_error = f"{type(e).__name__}: {str(e)[:300]}"logger.error(f"GPU build unusable, using CPU: {self.gpu_error}")if gpu:import ctypesfor lib in ("libcudart.so.12", "libnccl.so.2", "libcublasLt.so.12", "libcublas.so.12"):found = next((os.path.join(d, lib) for d in CUDA_LIBS_DIRS if os.path.exists(os.path.join(d, lib))), lib)ctypes.CDLL(found, mode=ctypes.RTLD_GLOBAL)sys.path.insert(0, LLAMA_CUDA_DIR)else:self._probe(path)from llama_cpp import Llama# n_threads_batch (prompt processing) defaults to the host's core# count, which a Space container reports far above its 2 vCPUs.llm = Llama(model_path=path, n_ctx=LOCAL_LLM_CTX, n_threads=LOCAL_LLM_THREADS,n_threads_batch=LOCAL_LLM_THREADS, n_gpu_layers=-1 if gpu else 0, verbose=False)if gpu:# The first generation on a GPU pays a one-time warm-up of about a minute# (measured on a T4); pay it here, before the model is reported ready.llm.create_completion("Hi", max_tokens=4)self.accelerator = "cuda" if gpu else "cpu"template = str((llm.metadata or {}).get("tokenizer.chat_template", ""))self._chatml = "<|im_start|>" in template# Qwen3.5 answers directly when the assistant turn opens with an8 unmodified linesreturn self.llm@staticmethoddef _probe(path: str, gpu: bool = False) -> None:"""Load the model once in a child process. A native crash there (forexample a CPU instruction the prebuilt wheel needs but this machinelacks, or a CUDA build that cannot reach the GPU) raises here insteadof killing the API process."""code = ("import sys; from llama_cpp import Llama; "f"m = Llama(model_path=sys.argv[1], n_ctx=256, n_threads=1, n_threads_batch=1, n_gpu_layers={-1 if gpu else 0}, verbose=False); ""m.create_completion('Hi', max_tokens=1)")env = dict(os.environ)if gpu:env["PYTHONPATH"] = LLAMA_CUDA_DIR + os.pathsep + env.get("PYTHONPATH", "")env["LD_LIBRARY_PATH"] = os.pathsep.join(CUDA_LIBS_DIRS + [env.get("LD_LIBRARY_PATH", "")])r = subprocess.run([sys.executable, "-c", code, path], capture_output=True, text=True, timeout=300, env=env)if r.returncode != 0:raise RuntimeError(f"llama.cpp probe exited with {r.returncode}: {(r.stderr or '')[-200:]}")377 unmodified linesPUBLIC_PATHS = {"/", "/health"}# The one route that takes a file: its body may be as large as a scanned file.FILE_SCAN_PATH = "/api/v2/file-scan"# These check the owner's Hugging Face token themselves (owner_token below).OWNER_PATHS = {"/api/admin/train", "/api/admin/train/status"}34 unmodified linesreturn await _reply(send, 503, "This service has no service key configured", "SERVICE_KEY_NOT_CONFIGURED")if not service_key_valid(headers.get(SERVICE_KEY_HEADER.encode())):return await _reply(send, 401, "A valid service key is required", "SERVICE_KEY_REQUIRED")limit = FILE_SCAN_MAX_BYTES if path == FILE_SCAN_PATH else ML_MAX_BODY_BYTESstated = headers.get(b"content-length")if stated is not None:try:if int(stated) > limit:return await _reply(send, 413, f"Request body is over {limit} bytes", "BODY_TOO_LARGE")except ValueError:return await _reply(send, 400, "Content-Length must be a number", "BAD_CONTENT_LENGTH")received = 04 unmodified linesmessage = await receive()if message["type"] == "http.request":received += len(message.get("body", b""))if received > limit:raise BodyTooLarge()return message8 unmodified linesexcept BodyTooLarge:if started:raiseawait _reply(send, 413, f"Request body is over {limit} bytes", "BODY_TOO_LARGE")# Added last, so it runs first: before CORS and every route.363 unmodified linesreturn {**result, "answered": True, "result_kind": "reasoning_text"}@api.post("/api/v2/file-scan")async def api_v2_file_scan(request: Request):"""Static malware scoring of one file. Body: the file's bytes (application/octet-stream).Windows programs get a verdict from the trained model; other files are 'unsupported'.The file is parsed, never run, and not kept."""data = await request.body()if not data:return JSONResponse(status_code=400, content={"detail": "the request body is the file's bytes", "code": "FILE_REQUIRED"})return await run_in_threadpool(file_malware.scan, data)CAPABILITIES_SCHEMA = "cyberforge.ml.capabilities.v1"SERVICE_VERSION = "2.0.0"BATCH_MAX_URLS = 2085 unmodified lines"concurrent_generations": 1,},},{"id": "file_malware_pe","kind": "trained_model","readiness": "ready" if file_malware.ready else ("failed" if file_malware.error else "not_loaded"),"reason": file_malware.error or (None if file_malware.ready else "loads in the background after start"),"model": "EMBER2024 benchmark PE classifier (LightGBM), trained by the dataset's authors","applies_to": "Windows programs (PE files); static analysis only, the file is never run","answers_without_model": "unknown","decision_threshold": file_malware.threshold,"measured": file_malware.status().get("holdout"),"routes": [FILE_SCAN_PATH],"limits": {"max_file_bytes": FILE_SCAN_MAX_BYTES},},],"limits": {"max_body_bytes": ML_MAX_BODY_BYTES, "batch_max_urls": BATCH_MAX_URLS},"not_offered": [621 unmodified linesml_loader.initialize()# Load the chat model in the background so the API answers health checks at oncethreading.Thread(target=local_llm.load, name="local-llm-loader", daemon=True).start()threading.Thread(target=file_malware.load, args=(HF_MODEL_REPO, HF_TOKEN), name="file-malware-loader", daemon=True).start()logger.info("✅ Services initialized")app = api
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Static malware scoring of Windows programs (PE files).
The model is the EMBER2024 benchmark PE classifier (LightGBM, Apache-2.0), trained by thedataset's authors, with the `thrember` feature extractor. The file is parsed, never run, andis not kept. The model and its measured decision threshold are loaded from the model repo(file_malware/EMBER2024_PE.model and file_malware/metadata.json, written byml-services/file_malware/evaluate_job.py). Without a measured threshold no verdict is given."""import hashlibimport jsonimport osimport threadingimport timefrom typing import Dict, Optional
FILE_SCAN_SCHEMA = "cyberforge.ml.file_scan.v1"FILE_SCAN_MAX_BYTES = int(os.environ.get("FILE_SCAN_MAX_BYTES", str(26 * 1024 * 1024)))MODEL_FILE = "file_malware/EMBER2024_PE.model"METADATA_FILE = "file_malware/metadata.json"
class FileMalwareModel: def __init__(self): self.booster = None self.extractor = None self.metadata: Dict = {} self.error: Optional[str] = None self._lock = threading.Lock()
@property def ready(self) -> bool: return self.booster is not None and self.threshold is not None
@property def threshold(self) -> Optional[float]: value = self.metadata.get("decision_threshold") return float(value) if isinstance(value, (int, float)) else None
def load(self, repo: str, token: Optional[str] = None): """Load the model once. Safe to call repeatedly; a failure is kept and reported.""" with self._lock: if self.booster is not None or self.error: return try: import lightgbm as lgb import thrember from huggingface_hub import hf_hub_download meta_path = hf_hub_download(repo_id=repo, filename=METADATA_FILE, token=token or None) with open(meta_path, encoding="utf-8") as f: metadata = json.load(f) model_path = hf_hub_download(repo_id=repo, filename=MODEL_FILE, token=token or None) booster = lgb.Booster(model_file=model_path) extractor = thrember.PEFeatureExtractor() if booster.num_feature() != extractor.dim: raise ValueError(f"model expects {booster.num_feature()} features, the extractor gives {extractor.dim}") self.metadata, self.extractor, self.booster = metadata, extractor, booster except Exception as e: self.error = f"{type(e).__name__}: {str(e)[:300]}"
def status(self) -> Dict: holdout = (self.metadata.get("holdout") or {}).get("overall") or {} return { "loaded": self.booster is not None, "error": self.error, "decision_threshold": self.threshold, "source": self.metadata.get("source"), "evaluated_at": self.metadata.get("evaluated_at"), "holdout": {k: holdout.get(k) for k in ("samples", "recall", "false_positive_rate", "precision")} if holdout else None, }
@staticmethod def _parses(data: bytes) -> bool: """Whether the bytes are a well-formed PE file (headers only; nothing is run).""" try: import pefile pefile.PE(data=data, fast_load=True).close() return True except Exception: return False
def scan(self, data: bytes) -> Dict: """Score one file. Verdicts: threat, benign, unsupported (not a Windows program), unknown (the model is unavailable or the file could not be parsed).""" started = time.perf_counter() out = { "schema": FILE_SCAN_SCHEMA, "sha256": hashlib.sha256(data).hexdigest(), "size": len(data), "file_kind": "pe" if data[:2] == b"MZ" else "other", "verdict": "unknown", "verdict_reason": None, "score": None, "decision_threshold": self.threshold, "score_kind": "model score, not a calibrated probability", "engine": "trained_model", "model": "EMBER2024 benchmark PE classifier (LightGBM)", "analysis": "static: the file was parsed, not run", } if out["file_kind"] != "pe": out.update(verdict="unsupported", verdict_reason="not a Windows program (no MZ header); this model covers .exe, .dll and other PE files only", engine=None, model=None) elif not self.ready: out["verdict_reason"] = self.error or "the file malware model is not loaded" elif not self._parses(data): out["verdict_reason"] = "the file starts like a Windows program but is not a valid one; it was not scored" else: try: import numpy as np features = np.asarray(self.extractor.feature_vector(data), dtype=np.float32) score = float(self.booster.predict(features.reshape(1, -1))[0]) out["score"] = round(score, 6) out["verdict"] = "threat" if score >= self.threshold else "benign" out["verdict_reason"] = ("the score is at or above the measured decision threshold" if out["verdict"] == "threat" else "the score is below the measured decision threshold; this is not proof the file is safe") except Exception as e: out["verdict_reason"] = f"the file could not be analysed: {type(e).__name__}: {str(e)[:200]}" out["processing_time_ms"] = round((time.perf_counter() - started) * 1000, 1) return out
file_malware = FileMalwareModel()31 unmodified lines32333435363731 unmodified lines--only-binary llama-cpp-pythonllama-cpp-python==0.3.36# Data handlingdatasets>=2.20.0pyarrow>=17.0.031 unmodified lines323334353637383940414243444531 unmodified lines--only-binary llama-cpp-pythonllama-cpp-python==0.3.36# File malware model (Windows programs): the EMBER2024 feature extractor, pinned to a# commit, and LightGBM for the published classifier. Files are parsed, never run.lightgbm>=4.6.0pefile>=2024.8.26# thrember imports a name that later signify releases removedsignify==0.7.1thrember @ git+https://github.com/FutureComputing4AI/EMBER2024.git@0ef753e81d98bf209f71b03cd331dfc190b5b54d# Data handlingdatasets>=2.20.0pyarrow>=17.0.0
Dockerfile+10
app.py+89-11
file_scan.pyAdded+116
requirements.txt+8