umer-wasim commited on
Commit
fbb1758
·
verified ·
1 Parent(s): f1bdfc3

Desktop app 0.4.0 (Ask the assistant about this report), audit-aware chat search, v0.4 pipeline, converter for 1.5B

Browse files
app/main.cjs CHANGED
@@ -227,3 +227,23 @@ ipcMain.handle('report:save', async (event, { html, evidenceText, hostname, mode
227
  });
228
 
229
  ipcMain.handle('report:show', (event, filePath) => shell.showItemInFolder(filePath));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  });
228
 
229
  ipcMain.handle('report:show', (event, filePath) => shell.showItemInFolder(filePath));
230
+
231
+ // The Devseis security assistant (the Space's chat page) in an app window, with this audit attached.
232
+ // The report is handed over inside the app (the page's local storage); the page never uploads it.
233
+ const CHAT_URL = 'https://devseis-endpoint-auditor.static.hf.space/index.html';
234
+ let chatWindow = null;
235
+ ipcMain.handle('chat:open', async (event, evidenceText) => {
236
+ if (chatWindow && !chatWindow.isDestroyed()) chatWindow.close();
237
+ chatWindow = new BrowserWindow({ width: 1000, height: 820, minWidth: 420, minHeight: 560, title: 'Devseis Security Assistant',
238
+ webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true } });
239
+ chatWindow.webContents.setWindowOpenHandler(({ url }) => (url.startsWith('blob:') ? { action: 'allow' } : (shell.openExternal(url), { action: 'deny' })));
240
+ try {
241
+ await chatWindow.loadURL(CHAT_URL);
242
+ await chatWindow.webContents.executeJavaScript(`localStorage.setItem('devseis.lastAudit', ${JSON.stringify(evidenceText)}); true`);
243
+ await chatWindow.loadURL(`${CHAT_URL}?from=app#audit`);
244
+ return { opened: true };
245
+ } catch (error) {
246
+ if (!chatWindow.isDestroyed()) chatWindow.close();
247
+ return { opened: false, error: `The assistant needs an internet connection the first time (${error.message}).` };
248
+ }
249
+ });
app/package.json CHANGED
@@ -1,7 +1,7 @@
1
  {
2
  "name": "devseis-endpoint-auditor",
3
  "productName": "Devseis Endpoint Auditor",
4
- "version": "0.3.0",
5
  "description": "Read-only endpoint audit for ISO 27001, GDPR and the EU AI Act, with a local AI auditor.",
6
  "author": {
7
  "name": "Devseis",
 
1
  {
2
  "name": "devseis-endpoint-auditor",
3
  "productName": "Devseis Endpoint Auditor",
4
+ "version": "0.4.0",
5
  "description": "Read-only endpoint audit for ISO 27001, GDPR and the EU AI Act, with a local AI auditor.",
6
  "author": {
7
  "name": "Devseis",
app/preload.cjs CHANGED
@@ -14,4 +14,5 @@ contextBridge.exposeInMainWorld('devseis', {
14
  },
15
  saveReport: options => ipcRenderer.invoke('report:save', options),
16
  showInFolder: filePath => ipcRenderer.invoke('report:show', filePath),
 
17
  });
 
14
  },
15
  saveReport: options => ipcRenderer.invoke('report:save', options),
16
  showInFolder: filePath => ipcRenderer.invoke('report:show', filePath),
17
+ openChat: evidenceText => ipcRenderer.invoke('chat:open', evidenceText),
18
  });
app/renderer/app.js CHANGED
@@ -231,6 +231,7 @@ $('cancel').addEventListener('click', () => stopped('Audit cancelled', 'Nothing
231
  $('restart').addEventListener('click', showApproval);
232
  $('again').addEventListener('click', showApproval);
233
  $('save-again').addEventListener('click', () => save('choose'));
 
234
  $('save-docs').addEventListener('click', () => save('auto'));
235
  $('save-choose').addEventListener('click', () => save('choose'));
236
  prepare();
 
231
  $('restart').addEventListener('click', showApproval);
232
  $('again').addEventListener('click', showApproval);
233
  $('save-again').addEventListener('click', () => save('choose'));
234
+ $('ask-chat').addEventListener('click', () => { if (lastReport) window.devseis.openChat(lastReport.evidenceText); });
235
  $('save-docs').addEventListener('click', () => save('auto'));
236
  $('save-choose').addEventListener('click', () => save('choose'));
237
  prepare();
app/renderer/index.html CHANGED
@@ -55,6 +55,7 @@
55
  <div class="actions">
56
  <button class="secondary" id="again">Run another audit</button>
57
  <button class="primary" id="save-again">Save report as PDF</button>
 
58
  </div>
59
  <p class="muted" id="saved-note"></p>
60
  </section>
 
55
  <div class="actions">
56
  <button class="secondary" id="again">Run another audit</button>
57
  <button class="primary" id="save-again">Save report as PDF</button>
58
+ <button class="secondary" id="ask-chat">💬 Ask the assistant about this report</button>
59
  </div>
60
  <p class="muted" id="saved-note"></p>
61
  </section>
mobile/test/webllm-test.cjs CHANGED
@@ -14,10 +14,13 @@ app.whenReady().then(async () => {
14
  const info = await js(`loadModel(${JSON.stringify(modelUrl)})`);
15
  console.log('loaded', JSON.stringify(info));
16
  const examples = fs.readFileSync(testFile, 'utf8').trim().split('\n').map(JSON.parse);
17
- const pick = [...examples.filter(e => e.meta.task === 'finding').slice(0, count - 2), ...examples.filter(e => e.meta.task === 'summary').slice(0, 1), ...examples.filter(e => e.meta.task === 'ai_classification').slice(0, 1)];
 
 
18
  let ok = 0;
19
  for (const e of pick) {
20
- const r = await Promise.race([js(`ask(${JSON.stringify(e.meta.task)}, ${JSON.stringify(e.messages[1].content)}, ${useSchema === 'schema'})`),
 
21
  new Promise(res => setTimeout(() => res({ seconds: 240, problems: ['timeout after 240 s'], reply: '' }), 240000))]);
22
  if (!r.problems.length) ok++;
23
  if (process.env.FULL) console.log('FULL REPLY:', r.reply.length, 'chars\n' + r.reply.slice(-700));
 
14
  const info = await js(`loadModel(${JSON.stringify(modelUrl)})`);
15
  console.log('loaded', JSON.stringify(info));
16
  const examples = fs.readFileSync(testFile, 'utf8').trim().split('\n').map(JSON.parse);
17
+ const chats = examples.filter(e => e.meta.task === 'chat');
18
+ const nChat = chats.length ? Math.floor(count / 2) : 0;
19
+ const pick = [...examples.filter(e => e.meta.task === 'finding').slice(0, count - 2 - nChat), ...examples.filter(e => e.meta.task === 'summary').slice(0, 1), ...examples.filter(e => e.meta.task === 'ai_classification').slice(0, 1), ...chats.slice(0, nChat)];
20
  let ok = 0;
21
  for (const e of pick) {
22
+ const arg = e.meta.task === 'chat' ? JSON.stringify(e.messages.slice(0, -1)) : JSON.stringify(e.messages[1].content);
23
+ const r = await Promise.race([js(`ask(${JSON.stringify(e.meta.task)}, ${arg}, ${useSchema === 'schema'})`),
24
  new Promise(res => setTimeout(() => res({ seconds: 240, problems: ['timeout after 240 s'], reply: '' }), 240000))]);
25
  if (!r.problems.length) ok++;
26
  if (process.env.FULL) console.log('FULL REPLY:', r.reply.length, 'chars\n' + r.reply.slice(-700));
mobile/test/webllm-test.html CHANGED
@@ -3,18 +3,27 @@
3
  // Loads a Devseis auditor model build in WebLLM and answers prompts given by mobile/test/webllm-test.cjs.
4
  import * as webllm from '../../app/node_modules/@mlc-ai/web-llm/lib/index.js';
5
  import { SYSTEM_PROMPT, groundingProblems, ANSWER_SCHEMAS } from '../../app/renderer/auditor-core.js';
 
6
  window.loadModel = async (modelUrl) => {
7
  const adapter = await navigator.gpu.requestAdapter();
8
  const f16 = adapter.features.has('shader-f16');
9
  const named = (modelUrl.match(/q0f16|q4f16_1|q4f32_1/) || [])[0];
10
  const quant = named || (f16 ? 'q4f16_1' : 'q4f32_1');
11
- const base = webllm.prebuiltAppConfig.model_list.find(m => m.model_id === `Qwen2.5-0.5B-Instruct-${quant}-MLC`);
 
12
  const url = modelUrl.replace('{quant}', quant);
13
  const custom = { ...base, model: url, model_id: 'devseis-test-' + quant };
14
  window.engine = await webllm.CreateMLCEngine(custom.model_id, { appConfig: { ...webllm.prebuiltAppConfig, model_list: [custom] } });
15
  return { quant, url };
16
  };
 
17
  window.ask = async (task, prompt, useSchema) => {
 
 
 
 
 
 
18
  const t = performance.now();
19
  const r = await window.engine.chat.completions.create({ messages: [{ role: 'system', content: SYSTEM_PROMPT }, { role: 'user', content: prompt }],
20
  temperature: 0, max_tokens: 900, ...(useSchema ? { response_format: { type: 'json_object', schema: JSON.stringify(ANSWER_SCHEMAS[task]) } } : {}) });
 
3
  // Loads a Devseis auditor model build in WebLLM and answers prompts given by mobile/test/webllm-test.cjs.
4
  import * as webllm from '../../app/node_modules/@mlc-ai/web-llm/lib/index.js';
5
  import { SYSTEM_PROMPT, groundingProblems, ANSWER_SCHEMAS } from '../../app/renderer/auditor-core.js';
6
+ import { chatProblems } from '../../app/renderer/knowledge.js';
7
  window.loadModel = async (modelUrl) => {
8
  const adapter = await navigator.gpu.requestAdapter();
9
  const f16 = adapter.features.has('shader-f16');
10
  const named = (modelUrl.match(/q0f16|q4f16_1|q4f32_1/) || [])[0];
11
  const quant = named || (f16 ? 'q4f16_1' : 'q4f32_1');
12
+ const size = /1\.5b/i.test(modelUrl) ? '1.5B' : '0.5B';
13
+ const base = webllm.prebuiltAppConfig.model_list.find(m => m.model_id === `Qwen2.5-${size}-Instruct-${quant}-MLC`);
14
  const url = modelUrl.replace('{quant}', quant);
15
  const custom = { ...base, model: url, model_id: 'devseis-test-' + quant };
16
  window.engine = await webllm.CreateMLCEngine(custom.model_id, { appConfig: { ...webllm.prebuiltAppConfig, model_list: [custom] } });
17
  return { quant, url };
18
  };
19
+ // task 'chat': messages = the full chat messages (system + user); otherwise prompt = report prompt.
20
  window.ask = async (task, prompt, useSchema) => {
21
+ if (task === 'chat') {
22
+ const t0 = performance.now();
23
+ const r = await window.engine.chat.completions.create({ messages: prompt, temperature: 0, max_tokens: 700 });
24
+ const reply = r.choices[0].message.content;
25
+ return { seconds: Math.round((performance.now() - t0) / 1000), problems: chatProblems(prompt[prompt.length - 1].content, reply), reply };
26
+ }
27
  const t = performance.now();
28
  const r = await window.engine.chat.completions.create({ messages: [{ role: 'system', content: SYSTEM_PROMPT }, { role: 'user', content: prompt }],
29
  temperature: 0, max_tokens: 900, ...(useSchema ? { response_format: { type: 'json_object', schema: JSON.stringify(ANSWER_SCHEMAS[task]) } } : {}) });
training/evaluate.py CHANGED
@@ -28,6 +28,21 @@ from transformers import AutoModelForCausalLM, AutoTokenizer # noqa: E402
28
  ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
29
  sys.path.insert(0, os.path.join(ROOT, "training"))
30
  from check_faithfulness import check as grounding_problems # noqa: E402
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
 
33
  def pick(examples, count, seed):
@@ -93,9 +108,17 @@ def main():
93
  output = model.generate(prompt_ids, max_new_tokens=args.max_new_tokens, do_sample=False,
94
  pad_token_id=tokenizer.eos_token_id)
95
  reply = tokenizer.decode(output[0, prompt_ids.shape[1]:], skip_special_tokens=True).strip()
96
- target = json.loads(example["messages"][-1]["content"])
97
  row = totals.setdefault(task, {"n": 0, "json": 0, "grounded": 0, "fields": 0})
98
  row["n"] += 1
 
 
 
 
 
 
 
 
 
99
  try:
100
  answer = json.loads(reply)
101
  row["json"] += 1
 
28
  ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
29
  sys.path.insert(0, os.path.join(ROOT, "training"))
30
  from check_faithfulness import check as grounding_problems # noqa: E402
31
+ from build_chat import check_chat # noqa: E402
32
+
33
+ CITE = __import__("re").compile(r"\[(\d+)\]")
34
+ REFUSAL = __import__("re").compile(r"can only help|don't have reliable information|won't guess|can't see your device", __import__("re").I)
35
+
36
+
37
+ def chat_scores(example, reply):
38
+ """Chat answers: grounded = citations exist and numbers appear in the sources; correct = cites the reference's
39
+ passage, or (for questions the reference declines) declines without citations."""
40
+ graded = {"messages": example["messages"][:-1] + [{"role": "assistant", "content": reply}]}
41
+ grounded = not check_chat(graded)
42
+ target = example["messages"][-1]["content"]
43
+ want, got = set(CITE.findall(target)), set(CITE.findall(reply))
44
+ correct = bool(want & got) if want else (not got and bool(REFUSAL.search(reply)))
45
+ return grounded, correct
46
 
47
 
48
  def pick(examples, count, seed):
 
108
  output = model.generate(prompt_ids, max_new_tokens=args.max_new_tokens, do_sample=False,
109
  pad_token_id=tokenizer.eos_token_id)
110
  reply = tokenizer.decode(output[0, prompt_ids.shape[1]:], skip_special_tokens=True).strip()
 
111
  row = totals.setdefault(task, {"n": 0, "json": 0, "grounded": 0, "fields": 0})
112
  row["n"] += 1
113
+ if task == "chat":
114
+ grounded, correct = chat_scores(example, reply)
115
+ row["json"] += 1 # chat is plain text: counted as well-formed
116
+ row["grounded"] += grounded
117
+ row["fields"] += correct
118
+ saved.append({"task": task, "meta": example["meta"], "reply": reply})
119
+ print(f"[{number}/{len(examples)}] {task:<18} {time.time() - started:6.0f}s", flush=True)
120
+ continue
121
+ target = json.loads(example["messages"][-1]["content"])
122
  try:
123
  answer = json.loads(reply)
124
  row["json"] += 1
training/mlc_quantize.py CHANGED
@@ -134,12 +134,12 @@ def write(tensors, ref_dir, out_dir):
134
  shutil.copy(os.path.join(ref_dir, name), out_dir)
135
 
136
 
137
- def verify(quant):
138
  """Convert the base model and compare with mlc-ai's build: layout must match exactly, scales bit-exactly, values >= 99%."""
139
- ref = os.path.join(MODELS, "mlc-ref", quant)
140
  dtype = np.float32 if quant == "q4f32_1" else np.float16
141
  _, recs = records(ref)
142
- tensors = build(load_hf(os.path.join(MODELS, "Qwen2.5-0.5B-Instruct")), dtype, quantized=not quant.startswith("q0"))
143
  check_layout(tensors, recs)
144
  if quant.startswith("q0"):
145
  present = [(s, r) for s, r in recs if os.path.exists(os.path.join(ref, s["dataPath"]))]
@@ -171,12 +171,14 @@ def main():
171
  parser.add_argument("--verify", action="store_true", help="compare a conversion of the base model with mlc-ai's build")
172
  parser.add_argument("--model", help="merged model folder (model.safetensors)")
173
  parser.add_argument("--out", help="output folder")
 
 
174
  args = parser.parse_args()
175
  if args.verify:
176
- raise SystemExit(0 if verify(args.quant) else 1)
177
  dtype = np.float32 if args.quant == "q4f32_1" else np.float16
178
  tensors = build(load_hf(args.model), dtype, quantized=not args.quant.startswith("q0"))
179
- write(tensors, os.path.join(MODELS, "mlc-ref", args.quant), args.out)
180
  print(f"wrote {args.out}")
181
 
182
 
 
134
  shutil.copy(os.path.join(ref_dir, name), out_dir)
135
 
136
 
137
+ def verify(quant, ref_root=None, base=None):
138
  """Convert the base model and compare with mlc-ai's build: layout must match exactly, scales bit-exactly, values >= 99%."""
139
+ ref = os.path.join(ref_root or os.path.join(MODELS, "mlc-ref"), quant)
140
  dtype = np.float32 if quant == "q4f32_1" else np.float16
141
  _, recs = records(ref)
142
+ tensors = build(load_hf(base or os.path.join(MODELS, "Qwen2.5-0.5B-Instruct")), dtype, quantized=not quant.startswith("q0"))
143
  check_layout(tensors, recs)
144
  if quant.startswith("q0"):
145
  present = [(s, r) for s, r in recs if os.path.exists(os.path.join(ref, s["dataPath"]))]
 
171
  parser.add_argument("--verify", action="store_true", help="compare a conversion of the base model with mlc-ai's build")
172
  parser.add_argument("--model", help="merged model folder (model.safetensors)")
173
  parser.add_argument("--out", help="output folder")
174
+ parser.add_argument("--ref", help="folder with mlc-ai reference builds per quantization (default training/models/mlc-ref, 0.5B)")
175
+ parser.add_argument("--base", help="--verify: original base model folder matching --ref")
176
  args = parser.parse_args()
177
  if args.verify:
178
+ raise SystemExit(0 if verify(args.quant, args.ref, args.base) else 1)
179
  dtype = np.float32 if args.quant == "q4f32_1" else np.float16
180
  tensors = build(load_hf(args.model), dtype, quantized=not args.quant.startswith("q0"))
181
+ write(tensors, os.path.join(args.ref or os.path.join(MODELS, "mlc-ref"), args.quant), args.out)
182
  print(f"wrote {args.out}")
183
 
184
 
training/pipeline-v0.4.sh ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Unattended finish of model v0.4 (Qwen2.5-1.5B, chat + reports): wait for training, evaluate, merge, convert,
3
+ # GPU check, publish models + dataset v0.4, switch the chat to v0.4, push the Space.
4
+ # Resumable: finished stages leave training/pipeline-v0.4/<stage>.done. Log: training/pipeline-v0.4/pipeline.log
5
+ cd "$(dirname "$0")/.."
6
+ set -o pipefail
7
+ D=training/pipeline-v0.4; mkdir -p $D
8
+ PY=training/.venv/bin/python
9
+ BASE=training/models/Qwen2.5-1.5B-Instruct
10
+ stage() { [ -f "$D/$1.done" ] && { echo "== $1 already done"; return 1; }; echo "== $1 start $(date '+%F %H:%M')"; return 0; }
11
+ done_() { touch "$D/$1.done"; echo "== $1 done $(date '+%F %H:%M')"; }
12
+ EXCL=(--exclude "synthetic/out/*" --exclude "synthetic/out-v0.2/*" --exclude "synthetic/out-v0.3/*" --exclude "training/out/*" --exclude "training/out-v0.2/*"
13
+ --exclude "training/out-v0.3/*" --exclude "training/out-v0.4/*" --exclude "training/.venv/*" --exclude "training/models/*" --exclude "training/pipeline/*"
14
+ --exclude "training/pipeline-v0.4/*" --exclude "training/eval/*.jsonl" --exclude "training/eval/*.log" --exclude "app/node_modules/*" --exclude "app/dist/*"
15
+ --exclude "vulndb/cache/*" --exclude "vulndb/out/*" --exclude "**/.DS_Store" --exclude "**/__pycache__/*")
16
+ {
17
+ while pgrep -f "train_lora.py --base training/models/Qwen2.5-1.5B-Instruct" >/dev/null; do sleep 60; done
18
+ test -f training/models/auditor-lora-v0.4/final/adapter_model.safetensors || { echo "== FAILED: no final v0.4 adapter"; tail -5 training/models/train-v0.4.log; exit 1; }
19
+
20
+ if stage eval; then
21
+ caffeinate -i $PY -u training/evaluate.py --base $BASE --data training/out-v0.4/test.jsonl --count 60 --save training/eval/base-v0.4.jsonl --results training/eval/base-v0.4.json | grep -v "^\[" &&
22
+ caffeinate -i $PY -u training/evaluate.py --base $BASE --data training/out-v0.4/test.jsonl --count 60 --adapter training/models/auditor-lora-v0.4/final --save training/eval/v0.4.jsonl --results training/eval/v0.4.json | grep -v "^\[" &&
23
+ done_ eval || { echo "== FAILED eval"; exit 1; }
24
+ fi
25
+ if stage merge; then
26
+ $PY training/merge_lora.py --base $BASE --adapter training/models/auditor-lora-v0.4/final --out training/models/devseis-auditor-1.5b-v0.4 && done_ merge || { echo "== FAILED merge"; exit 1; }
27
+ fi
28
+ if stage convert; then
29
+ for q in q4f16_1 q4f32_1; do
30
+ $PY training/mlc_quantize.py --model training/models/devseis-auditor-1.5b-v0.4 --quant $q --ref training/models/mlc-ref-1.5b --out training/models/mlc/devseis-auditor-1.5b-v0.4-$q-MLC || { echo "== FAILED convert $q"; exit 1; }
31
+ done
32
+ done_ convert
33
+ fi
34
+ if stage webllm_check; then
35
+ pgrep -f "http.server 8765" >/dev/null || (python3 -m http.server 8765 --bind 127.0.0.1 >/dev/null 2>&1 &)
36
+ ln -sfn ../../mlc/devseis-auditor-1.5b-v0.4-q4f16_1-MLC training/models/mlc-serve/resolve/v0.4-1.5b-q4f16_1
37
+ echo "-- WebLLM v0.4 1.5B q4f16_1 (report and chat)"
38
+ app/node_modules/.bin/electron mobile/test/webllm-test.cjs "http://127.0.0.1:8765/training/models/mlc-serve/resolve/v0.4-1.5b-q4f16_1/" training/out-v0.4/test.jsonl 10 schema 2>&1 | grep -E "grounded|RESULT|FAILED|loaded"
39
+ done_ webllm_check
40
+ fi
41
+ if stage publish; then
42
+ $PY training/publish_model.py --size 1.5b --version v0.4 --dataset-revision v0.4 --merged training/models/devseis-auditor-1.5b-v0.4 \
43
+ --adapter training/models/auditor-lora-v0.4/final --base-eval training/eval/base-v0.4.json --model-eval training/eval/v0.4.json \
44
+ --train-log training/models/train-v0.4.log && done_ publish || { echo "== FAILED publish"; exit 1; }
45
+ fi
46
+ if stage dataset; then
47
+ TMP=$(mktemp -d); mkdir -p $TMP/data && cp training/out-v0.4/*.jsonl $TMP/data/ &&
48
+ hf upload Devseis/endpoint-auditor-synthetic $TMP/data data --repo-type dataset --commit-message "v0.4.0: report tasks + 1,286 grounded chat examples (Devseis Security Assistant)" &&
49
+ hf repos tag create Devseis/endpoint-auditor-synthetic v0.4 --repo-type dataset -m "Training data v0.4 (used for model v0.4, 1.5B chat + reports)" ; rm -rf $TMP; done_ dataset
50
+ fi
51
+ if stage switch_chat; then
52
+ $PY - <<'PY' && hf upload Devseis/endpoint-auditor . . --repo-type space "${EXCL[@]}" --commit-message "Security assistant uses the fine-tuned Devseis model v0.4 (1.5B)" && done_ switch_chat || { echo "== FAILED switch_chat"; exit 1; }
53
+ import json
54
+ p = "app/model-version.json"; d = json.load(open(p)); d["chat"]["version"] = "v0.4"
55
+ json.dump(d, open(p, "w"), indent=2); open(p, "a").write("\n"); print("chat model -> v0.4")
56
+ PY
57
+ fi
58
+ echo "== ALL DONE $(date '+%F %H:%M')"
59
+ } >> "$D/pipeline.log" 2>&1
training/publish_model.py CHANGED
@@ -25,10 +25,13 @@ from huggingface_hub import HfApi
25
 
26
  ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27
  ORG = "Devseis"
 
28
  NAME = "endpoint-auditor-0.5b"
29
  QUANTS = ["q0f16", "q4f16_1", "q4f32_1"]
 
30
  NOTES = {
31
  "v0.1": "Pilot: 988 balanced examples from dataset v0.1 (Windows, Linux, macOS). Proves the pipeline; superseded by v0.3.",
 
32
  "v0.3": "First full release: balanced examples from dataset v0.3 (Windows, Linux, macOS, iPhone, Android; real CVEs; evidence labels; computed summary scores).",
33
  }
34
 
@@ -54,6 +57,9 @@ def training_facts(log_path):
54
  steps = re.findall(r"^step (\d+)/(\d+)", text, re.M)
55
  if steps:
56
  facts["steps"] = steps[-1][1]
 
 
 
57
  vals = re.findall(r"validation loss ([\d.]+)", text)
58
  final = re.search(r"Final validation loss: ([\d.]+)", text)
59
  facts["val_loss"] = final.group(1) if final else (vals[-1] if vals else "")
@@ -62,21 +68,21 @@ def training_facts(log_path):
62
 
63
  def card(kind, version, args, base_eval, model_eval, facts, quant=None):
64
  dataset = f"{ORG}/endpoint-auditor-synthetic"
65
- header = ["---", "license: apache-2.0", "base_model: Qwen/Qwen2.5-0.5B-Instruct", f"datasets:\n- {dataset}", "language:\n- en",
66
  "tags:\n- security\n- compliance\n- iso27001\n- gdpr\n- eu-ai-act\n- endpoint-security\n- lora" + ("\n- mlc-llm\n- web-llm" if quant else ""),
67
  f"library_name: {'mlc-llm' if quant else 'transformers'}", "pipeline_tag: text-generation", "---", ""]
68
- title = f"# Devseis Endpoint Auditor 0.5B ({version})" + (f" — {quant} for WebLLM / MLC" if quant else "")
69
  usage = (f"""## Use in the browser (WebLLM)
70
 
71
  ```js
72
  import {{ CreateMLCEngine, prebuiltAppConfig }} from "@mlc-ai/web-llm";
73
- const base = prebuiltAppConfig.model_list.find(m => m.model_id === "Qwen2.5-0.5B-Instruct-{quant}-MLC");
74
  const appConfig = {{ model_list: [{{ ...base, model: "https://huggingface.co/{ORG}/{NAME}-{quant}-MLC/resolve/{version}/",
75
- model_id: "devseis-auditor-0.5b-{version}-{quant}" }}] }};
76
- const engine = await CreateMLCEngine("devseis-auditor-0.5b-{version}-{quant}", {{ appConfig }});
77
  ```
78
 
79
- Same architecture as Qwen2.5-0.5B-Instruct, so WebLLM's prebuilt Qwen2.5-0.5B {quant} runtime library is reused; only the weights differ.
80
  Use constrained decoding with the answer schemas in `app/renderer/auditor-core.js` (`ANSWER_SCHEMAS`):
81
  `response_format: {{ type: "json_object", schema: JSON.stringify(ANSWER_SCHEMAS[task]) }}`. Measured on held-out prompts,
82
  4-bit builds produce invalid JSON without it (0 of 6 grounded) and grounded answers with it (5 of 6; the sixth was cut by
@@ -94,10 +100,8 @@ tok = AutoTokenizer.from_pretrained(repo, revision="{version}")
94
  model = AutoModelForCausalLM.from_pretrained(repo, revision="{version}")
95
  ```
96
 
97
- The LoRA adapter alone is in `lora/` (apply it to `Qwen/Qwen2.5-0.5B-Instruct` with PEFT). Browser builds:
98
- [{ORG}/{NAME}-q0f16-MLC](https://huggingface.co/{ORG}/{NAME}-q0f16-MLC) (desktop),
99
- [{ORG}/{NAME}-q4f16_1-MLC](https://huggingface.co/{ORG}/{NAME}-q4f16_1-MLC) (phones) and
100
- [{ORG}/{NAME}-q4f32_1-MLC](https://huggingface.co/{ORG}/{NAME}-q4f32_1-MLC).
101
  """)
102
  body = f"""{title}
103
 
@@ -125,10 +129,10 @@ prompt in that file. Tasks: `finding`, `summary`, `ai_classification`; the model
125
 
126
  | | |
127
  |---|---|
128
- | Base model | [Qwen/Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct) (Apache-2.0) |
129
  | Data | [{dataset}](https://huggingface.co/datasets/{dataset}) revision `{args.dataset_revision}` (synthetic, CC BY 4.0) |
130
  | Examples | {facts.get('examples', '?')} balanced over task, OS and status ({facts.get('tokens', '?')} tokens) |
131
- | Method | LoRA r=16, alpha=32 (8.8 M trainable parameters), lr 2e-4, 1 epoch, {facts.get('steps', '?')} steps of 8 examples |
132
  | Hardware | CPU only: a 4-core Intel MacBook Pro (PyTorch 2.2, eager attention) |
133
  | Final validation loss | {facts.get('val_loss', '?')} |
134
 
@@ -137,7 +141,7 @@ prompt in that file. Tasks: `finding`, `summary`, `ai_classification`; the model
137
  Held-out test examples (`training/evaluate.py`, greedy decoding). *Grounded* = passes the same faithfulness check the app
138
  uses; *fields match* = check id / status / risk (findings), score and top gaps (summaries), tools and approval flags (AI).
139
 
140
- **Base model (Qwen2.5-0.5B-Instruct, not fine-tuned):**
141
 
142
  {table(base_eval)}
143
 
@@ -148,7 +152,7 @@ uses; *fields match* = check id / status / risk (findings), score and top gaps (
148
  ## Limitations
149
 
150
  - Trained on synthetic evidence; real-world wording varies. The app's grounding check and template fallback guard the report.
151
- - 0.5B parameters: it phrases and selects retrieved facts well; it is not reliable for arithmetic or ranking, so the app
152
  supplies scores and top gaps from code.
153
  - Not legal advice and not a certification. ISO 27001 control titles are cited; the standard's text is not reproduced.
154
 
@@ -159,7 +163,7 @@ Apache-2.0, by **Devseis**. Please credit "Devseis Endpoint Auditor by Devseis".
159
  ```bibtex
160
  @software{{devseis_endpoint_auditor_model_2026,
161
  author = {{{{Devseis}}}},
162
- title = {{Devseis Endpoint Auditor 0.5B}},
163
  year = {{2026}},
164
  version = {{{version}}},
165
  url = {{https://huggingface.co/{ORG}/{NAME}}}
@@ -194,7 +198,10 @@ def main():
194
  parser.add_argument("--base-eval")
195
  parser.add_argument("--model-eval")
196
  parser.add_argument("--train-log")
 
197
  args = parser.parse_args()
 
 
198
  load = lambda p: json.load(open(p)) if p and os.path.exists(p) else None
199
  base_eval, model_eval = load(args.base_eval), load(args.model_eval)
200
  facts = training_facts(args.train_log)
@@ -212,7 +219,7 @@ def main():
212
  shutil.copy(src, os.path.join(full, "eval", name))
213
  publish(api, f"{ORG}/{NAME}", full, args.version, card("full", args.version, args, base_eval, model_eval, facts), message)
214
  for quant in QUANTS:
215
- folder = os.path.join(args.mlc_root, f"devseis-auditor-0.5b-{args.version}-{quant}-MLC")
216
  if not os.path.exists(os.path.join(folder, "tensor-cache.json")):
217
  print(f"skipped {quant}: {folder} has no tensor-cache.json")
218
  continue
 
25
 
26
  ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27
  ORG = "Devseis"
28
+ SIZE = "0.5b" # set by --size
29
  NAME = "endpoint-auditor-0.5b"
30
  QUANTS = ["q0f16", "q4f16_1", "q4f32_1"]
31
+ SIZES = {"0.5b": ["q0f16", "q4f16_1", "q4f32_1"], "1.5b": ["q4f16_1", "q4f32_1"]}
32
  NOTES = {
33
  "v0.1": "Pilot: 988 balanced examples from dataset v0.1 (Windows, Linux, macOS). Proves the pipeline; superseded by v0.3.",
34
+ "v0.4": "Qwen2.5-1.5B fine-tuned for chat and reports in one model: the v0.3 report tasks plus 1,286 grounded chat examples (answers from the Devseis knowledge base with [n] citations; declines off-topic questions; answers from the user's own audit). Powers the Devseis Security Assistant.",
35
  "v0.3": "First full release: balanced examples from dataset v0.3 (Windows, Linux, macOS, iPhone, Android; real CVEs; evidence labels; computed summary scores).",
36
  }
37
 
 
57
  steps = re.findall(r"^step (\d+)/(\d+)", text, re.M)
58
  if steps:
59
  facts["steps"] = steps[-1][1]
60
+ t = re.search(r"trainable params: ([\d,]+)", text)
61
+ if t:
62
+ facts["trainable"] = f"{int(t.group(1).replace(',', '')) / 1e6:.1f} M"
63
  vals = re.findall(r"validation loss ([\d.]+)", text)
64
  final = re.search(r"Final validation loss: ([\d.]+)", text)
65
  facts["val_loss"] = final.group(1) if final else (vals[-1] if vals else "")
 
68
 
69
  def card(kind, version, args, base_eval, model_eval, facts, quant=None):
70
  dataset = f"{ORG}/endpoint-auditor-synthetic"
71
+ header = ["---", "license: apache-2.0", f"base_model: Qwen/Qwen2.5-{SIZE.upper()}-Instruct", f"datasets:\n- {dataset}", "language:\n- en",
72
  "tags:\n- security\n- compliance\n- iso27001\n- gdpr\n- eu-ai-act\n- endpoint-security\n- lora" + ("\n- mlc-llm\n- web-llm" if quant else ""),
73
  f"library_name: {'mlc-llm' if quant else 'transformers'}", "pipeline_tag: text-generation", "---", ""]
74
+ title = f"# Devseis Endpoint Auditor {SIZE.upper()} ({version})" + (f" — {quant} for WebLLM / MLC" if quant else "")
75
  usage = (f"""## Use in the browser (WebLLM)
76
 
77
  ```js
78
  import {{ CreateMLCEngine, prebuiltAppConfig }} from "@mlc-ai/web-llm";
79
+ const base = prebuiltAppConfig.model_list.find(m => m.model_id === "Qwen2.5-{SIZE.upper()}-Instruct-{quant}-MLC");
80
  const appConfig = {{ model_list: [{{ ...base, model: "https://huggingface.co/{ORG}/{NAME}-{quant}-MLC/resolve/{version}/",
81
+ model_id: "devseis-auditor-{SIZE}-{version}-{quant}" }}] }};
82
+ const engine = await CreateMLCEngine("devseis-auditor-{SIZE}-{version}-{quant}", {{ appConfig }});
83
  ```
84
 
85
+ Same architecture as Qwen2.5-{SIZE.upper()}-Instruct, so WebLLM's prebuilt Qwen2.5-{SIZE.upper()} {quant} runtime library is reused; only the weights differ.
86
  Use constrained decoding with the answer schemas in `app/renderer/auditor-core.js` (`ANSWER_SCHEMAS`):
87
  `response_format: {{ type: "json_object", schema: JSON.stringify(ANSWER_SCHEMAS[task]) }}`. Measured on held-out prompts,
88
  4-bit builds produce invalid JSON without it (0 of 6 grounded) and grounded answers with it (5 of 6; the sixth was cut by
 
100
  model = AutoModelForCausalLM.from_pretrained(repo, revision="{version}")
101
  ```
102
 
103
+ The LoRA adapter alone is in `lora/` (apply it to `Qwen/Qwen2.5-{SIZE.upper()}-Instruct` with PEFT). Browser builds:
104
+ {', '.join(f'[{ORG}/{NAME}-{q}-MLC](https://huggingface.co/{ORG}/{NAME}-{q}-MLC)' for q in QUANTS)}.
 
 
105
  """)
106
  body = f"""{title}
107
 
 
129
 
130
  | | |
131
  |---|---|
132
+ | Base model | [Qwen/Qwen2.5-{SIZE.upper()}-Instruct](https://huggingface.co/Qwen/Qwen2.5-{SIZE.upper()}-Instruct) (Apache-2.0) |
133
  | Data | [{dataset}](https://huggingface.co/datasets/{dataset}) revision `{args.dataset_revision}` (synthetic, CC BY 4.0) |
134
  | Examples | {facts.get('examples', '?')} balanced over task, OS and status ({facts.get('tokens', '?')} tokens) |
135
+ | Method | LoRA r=16, alpha=32 ({facts.get('trainable', '?')} trainable parameters), lr 2e-4, 1 epoch, {facts.get('steps', '?')} steps of 8 examples |
136
  | Hardware | CPU only: a 4-core Intel MacBook Pro (PyTorch 2.2, eager attention) |
137
  | Final validation loss | {facts.get('val_loss', '?')} |
138
 
 
141
  Held-out test examples (`training/evaluate.py`, greedy decoding). *Grounded* = passes the same faithfulness check the app
142
  uses; *fields match* = check id / status / risk (findings), score and top gaps (summaries), tools and approval flags (AI).
143
 
144
+ **Base model (Qwen2.5-{SIZE.upper()}-Instruct, not fine-tuned):**
145
 
146
  {table(base_eval)}
147
 
 
152
  ## Limitations
153
 
154
  - Trained on synthetic evidence; real-world wording varies. The app's grounding check and template fallback guard the report.
155
+ - {SIZE.upper()} parameters: it phrases and selects retrieved facts well; it is not reliable for arithmetic or ranking, so the app
156
  supplies scores and top gaps from code.
157
  - Not legal advice and not a certification. ISO 27001 control titles are cited; the standard's text is not reproduced.
158
 
 
163
  ```bibtex
164
  @software{{devseis_endpoint_auditor_model_2026,
165
  author = {{{{Devseis}}}},
166
+ title = {{Devseis Endpoint Auditor {SIZE.upper()}}},
167
  year = {{2026}},
168
  version = {{{version}}},
169
  url = {{https://huggingface.co/{ORG}/{NAME}}}
 
198
  parser.add_argument("--base-eval")
199
  parser.add_argument("--model-eval")
200
  parser.add_argument("--train-log")
201
+ parser.add_argument("--size", default="0.5b", choices=sorted(SIZES))
202
  args = parser.parse_args()
203
+ global SIZE, NAME, QUANTS
204
+ SIZE, NAME, QUANTS = args.size, f"endpoint-auditor-{args.size}", SIZES[args.size]
205
  load = lambda p: json.load(open(p)) if p and os.path.exists(p) else None
206
  base_eval, model_eval = load(args.base_eval), load(args.model_eval)
207
  facts = training_facts(args.train_log)
 
219
  shutil.copy(src, os.path.join(full, "eval", name))
220
  publish(api, f"{ORG}/{NAME}", full, args.version, card("full", args.version, args, base_eval, model_eval, facts), message)
221
  for quant in QUANTS:
222
+ folder = os.path.join(args.mlc_root, f"devseis-auditor-{SIZE}-{args.version}-{quant}-MLC")
223
  if not os.path.exists(os.path.join(folder, "tensor-cache.json")):
224
  print(f"skipped {quant}: {folder} has no tensor-cache.json")
225
  continue