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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import site
|
| 4 |
+
import subprocess
|
| 5 |
+
import json
|
| 6 |
+
|
| 7 |
+
# ββ CUDA Runtime Detection & LD_LIBRARY_PATH Patch ββ
|
| 8 |
+
# ZeroGPU provides NVIDIA drivers but not CUDA toolkit.
|
| 9 |
+
# torch==2.11.0 bundles its own CUDA runtime at site-packages/nvidia/*/lib/
|
| 10 |
+
_CUDA_FOUND = False
|
| 11 |
+
for sp in site.getsitepackages():
|
| 12 |
+
for subdir in ['nvidia/cuda_runtime/lib', 'nvidia/cublas/lib', 'nvidia/cudnn/lib']:
|
| 13 |
+
path = os.path.join(sp, subdir)
|
| 14 |
+
if os.path.isdir(path) and os.path.exists(os.path.join(path, 'libcudart.so.12')):
|
| 15 |
+
os.environ['LD_LIBRARY_PATH'] = path + ':' + os.environ.get('LD_LIBRARY_PATH', '')
|
| 16 |
+
_CUDA_FOUND = True
|
| 17 |
+
print(f"[cuda] Found runtime at: {path}")
|
| 18 |
+
break
|
| 19 |
+
if _CUDA_FOUND:
|
| 20 |
+
break
|
| 21 |
+
|
| 22 |
+
if not _CUDA_FOUND:
|
| 23 |
+
print("[cuda] WARNING: No bundled CUDA runtime found. Will try torch's lib path.")
|
| 24 |
+
try:
|
| 25 |
+
import torch
|
| 26 |
+
torch_lib = os.path.join(os.path.dirname(torch.__file__), 'lib')
|
| 27 |
+
os.environ['LD_LIBRARY_PATH'] = torch_lib + ':' + os.environ.get('LD_LIBRARY_PATH', '')
|
| 28 |
+
print(f"[cuda] Fallback to torch lib: {torch_lib}")
|
| 29 |
+
except Exception as e:
|
| 30 |
+
print(f"[cuda] ERROR: {e}. GPU acceleration may not work!")
|
| 31 |
+
|
| 32 |
+
# ββ Imports (must be AFTER LD_LIBRARY_PATH patch) ββ
|
| 33 |
+
from huggingface_hub import hf_hub_download
|
| 34 |
+
import gradio as gr
|
| 35 |
+
|
| 36 |
+
# Try llama-cpp-python with CUDA, fallback to CPU
|
| 37 |
+
MODEL_REPO = "BugTraceAI/BugTraceAI-CORE-Fast"
|
| 38 |
+
MODEL_FILE = "bugtraceai-core-fast.gguf"
|
| 39 |
+
|
| 40 |
+
print(f"[model] Downloading {MODEL_REPO}/{MODEL_FILE}...")
|
| 41 |
+
model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
|
| 42 |
+
model_size_gb = os.path.getsize(model_path) / 1e9
|
| 43 |
+
print(f"[model] Path: {model_path}")
|
| 44 |
+
print(f"[model] Size: {model_size_gb:.2f} GB")
|
| 45 |
+
|
| 46 |
+
print("[llama] Loading model...")
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
from llama_cpp import Llama
|
| 50 |
+
llm = Llama(
|
| 51 |
+
model_path=model_path,
|
| 52 |
+
n_ctx=8192,
|
| 53 |
+
n_batch=512,
|
| 54 |
+
n_gpu_layers=-1 if _CUDA_FOUND else 0,
|
| 55 |
+
flash_attn=True,
|
| 56 |
+
use_mmap=True,
|
| 57 |
+
use_mlock=False,
|
| 58 |
+
chat_format="chatml",
|
| 59 |
+
verbose=False,
|
| 60 |
+
)
|
| 61 |
+
n_gpu = llm.n_gpu_layers
|
| 62 |
+
print(f"[llama] Loaded OK. GPU layers: {n_gpu}")
|
| 63 |
+
except Exception as e:
|
| 64 |
+
print(f"[llama] ERROR loading with llama-cpp-python: {e}")
|
| 65 |
+
print(f"[llama] Falling back to llama.cpp server binary...")
|
| 66 |
+
|
| 67 |
+
# Download llama-server binary from GitHub releases
|
| 68 |
+
import urllib.request
|
| 69 |
+
LLAMA_BIN_URL = "https://github.com/ggml-org/llama.cpp/releases/download/b9946/llama-b9946-bin-ubuntu-x64.tar.gz"
|
| 70 |
+
bin_tarball = "/tmp/llama-server.tar.gz"
|
| 71 |
+
print(f"[llama-bin] Downloading {LLAMA_BIN_URL}...")
|
| 72 |
+
urllib.request.urlretrieve(LLAMA_BIN_URL, bin_tarball)
|
| 73 |
+
|
| 74 |
+
import tarfile
|
| 75 |
+
with tarfile.open(bin_tarball) as tf:
|
| 76 |
+
tf.extractall("/tmp/llama-bin")
|
| 77 |
+
|
| 78 |
+
llama_server = "/tmp/llama-bin/bin/llama-server"
|
| 79 |
+
os.chmod(llama_server, 0o755)
|
| 80 |
+
|
| 81 |
+
# Start llama-server as subprocess
|
| 82 |
+
server_args = [
|
| 83 |
+
llama_server,
|
| 84 |
+
"-m", model_path,
|
| 85 |
+
"-c", "8192",
|
| 86 |
+
"-b", "512",
|
| 87 |
+
"--port", "8081",
|
| 88 |
+
"--host", "0.0.0.0",
|
| 89 |
+
"-ngl", "99", # all layers to GPU
|
| 90 |
+
"-fa", # flash attention
|
| 91 |
+
"--metrics",
|
| 92 |
+
"--no-webui", # API only
|
| 93 |
+
]
|
| 94 |
+
print(f"[llama-bin] Starting server: {' '.join(server_args)}")
|
| 95 |
+
proc = subprocess.Popen(server_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
| 96 |
+
|
| 97 |
+
# Wait for server to be ready
|
| 98 |
+
import time
|
| 99 |
+
for i in range(30):
|
| 100 |
+
try:
|
| 101 |
+
r = urllib.request.urlopen("http://localhost:8081/health")
|
| 102 |
+
if r.status == 200:
|
| 103 |
+
print("[llama-bin] Server ready!")
|
| 104 |
+
break
|
| 105 |
+
except:
|
| 106 |
+
pass
|
| 107 |
+
time.sleep(1)
|
| 108 |
+
else:
|
| 109 |
+
print("[llama-bin] WARNING: Server may not be ready after 30s")
|
| 110 |
+
|
| 111 |
+
# Wrapper class that calls llama-server API
|
| 112 |
+
class LlamaServerClient:
|
| 113 |
+
def __init__(self, base_url="http://localhost:8081"):
|
| 114 |
+
self.base_url = base_url
|
| 115 |
+
|
| 116 |
+
def create_chat_completion(self, messages, max_tokens=512, temperature=0.7, top_p=0.9):
|
| 117 |
+
body = json.dumps({
|
| 118 |
+
"messages": messages,
|
| 119 |
+
"max_tokens": max_tokens,
|
| 120 |
+
"temperature": temperature,
|
| 121 |
+
"top_p": top_p,
|
| 122 |
+
"stream": False,
|
| 123 |
+
}).encode()
|
| 124 |
+
req = urllib.request.Request(
|
| 125 |
+
f"{self.base_url}/v1/chat/completions",
|
| 126 |
+
data=body,
|
| 127 |
+
headers={"Content-Type": "application/json"}
|
| 128 |
+
)
|
| 129 |
+
resp = urllib.request.urlopen(req, timeout=120)
|
| 130 |
+
return json.loads(resp.read())
|
| 131 |
+
|
| 132 |
+
llm = LlamaServerClient()
|
| 133 |
+
n_gpu = "all (via llama-server subprocess)"
|
| 134 |
+
print(f"[llama-bin] Client ready. GPU layers: {n_gpu}")
|
| 135 |
+
|
| 136 |
+
# ββ Chat Function ββ
|
| 137 |
+
def chat(prompt, max_tokens=512, temperature=0.7):
|
| 138 |
+
response = llm.create_chat_completion(
|
| 139 |
+
messages=[{"role": "user", "content": prompt}],
|
| 140 |
+
max_tokens=max_tokens,
|
| 141 |
+
temperature=temperature,
|
| 142 |
+
top_p=0.9,
|
| 143 |
+
)
|
| 144 |
+
return response["choices"][0]["message"]["content"]
|
| 145 |
+
|
| 146 |
+
# ββ Gradio UI ββ
|
| 147 |
+
demo = gr.Interface(
|
| 148 |
+
fn=chat,
|
| 149 |
+
inputs=[
|
| 150 |
+
gr.Textbox(label="Prompt", lines=5, placeholder="Bug bounty analysis prompt..."),
|
| 151 |
+
gr.Slider(64, 1024, value=512, label="Max tokens"),
|
| 152 |
+
gr.Slider(0.0, 1.5, value=0.7, label="Temperature"),
|
| 153 |
+
],
|
| 154 |
+
outputs=gr.Textbox(label="Response", lines=12),
|
| 155 |
+
title="BugTraceAI Fast 7B β Bug Bounty Copilot",
|
| 156 |
+
description="Security-focused 7B model for vulnerability triage, exploit reasoning, and finding analysis. Runs on ZeroGPU A10G (24 GB).",
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|