karimshahi commited on
Commit
a93cf7a
·
verified ·
1 Parent(s): a465cc1

Upload 35 files

Browse files
LPU_Check.cmd CHANGED
@@ -1,25 +1,25 @@
1
- @echo off
2
- REM LPU AI Accelerator V7.1.1 — environment self-check launcher.
3
- REM Starts NOTHING (no server, no window) - safe to double-click anytime.
4
- REM Explicit python.exe call (bypasses any broken .py association).
5
-
6
- setlocal
7
- set "LPU_ROOT=%~dp0.."
8
- cd /d "%LPU_ROOT%"
9
-
10
- set "PY="
11
- if exist "%LPU_ROOT%\.venv\Scripts\python.exe" (
12
- set "PY=%LPU_ROOT%\.venv\Scripts\python.exe"
13
- ) else if exist "C:\ipara\Ipara.co\Scripts\python.exe" (
14
- set "PY=C:\ipara\Ipara.co\Scripts\python.exe"
15
- ) else if exist "C:\Ipara.co\Scripts\python.exe" (
16
- set "PY=C:\Ipara.co\Scripts\python.exe"
17
- )
18
-
19
- if defined PY (
20
- "%PY%" run_lpu.py --check %*
21
- ) else (
22
- py -3 run_lpu.py --check %* 2>nul || python run_lpu.py --check %*
23
- )
24
- if errorlevel 1 pause
25
- exit /b %ERRORLEVEL%
 
1
+ @echo off
2
+ REM LPU AI Accelerator V7.2 — environment self-check launcher.
3
+ REM Starts NOTHING (no server, no window) - safe to double-click anytime.
4
+ REM Explicit python.exe call (bypasses any broken .py association).
5
+
6
+ setlocal
7
+ set "LPU_ROOT=%~dp0."
8
+ cd /d "%LPU_ROOT%"
9
+
10
+ set "PY="
11
+ if exist "%LPU_ROOT%\.venv\Scripts\python.exe" (
12
+ set "PY=%LPU_ROOT%\.venv\Scripts\python.exe"
13
+ ) else if exist "C:\ipara\Ipara.co\Scripts\python.exe" (
14
+ set "PY=C:\ipara\Ipara.co\Scripts\python.exe"
15
+ ) else if exist "C:\Ipara.co\Scripts\python.exe" (
16
+ set "PY=C:\Ipara.co\Scripts\python.exe"
17
+ )
18
+
19
+ if defined PY (
20
+ "%PY%" run_lpu.py --check %*
21
+ ) else (
22
+ py -3 run_lpu.py --check %* 2>nul || python run_lpu.py --check %*
23
+ )
24
+ if errorlevel 1 pause
25
+ exit /b %ERRORLEVEL%
LPU_Desktop.cmd CHANGED
@@ -1,27 +1,27 @@
1
- @echo off
2
- REM LPU AI Accelerator V7.1.1 — NATIVE DESKTOP LAUNCHER (no browser)
3
- REM Fixes the "Electron/Chromium warning" issue: this launcher calls
4
- REM python.exe EXPLICITLY, so the broken .py file association on the
5
- REM machine (an Electron-based editor had taken over .py) is bypassed.
6
- REM Double-clickable from Explorer, works from any PowerShell/CMD cwd.
7
-
8
- setlocal
9
- set "LPU_ROOT=%~dp0"
10
- cd /d "%LPU_ROOT%"
11
-
12
- REM python precedence: project venv -> Ipara.co venv -> py launcher
13
- set "PY="
14
- if exist "%LPU_ROOT%\.venv\Scripts\python.exe" (
15
- set "PY=%LPU_ROOT%\.venv\Scripts\python.exe"
16
- ) else if exist "C:\ipara\Ipara.co\Scripts\python.exe" (
17
- set "PY=C:\ipara\Ipara.co\Scripts\python.exe"
18
- ) else if exist "C:\Ipara.co\Scripts\python.exe" (
19
- set "PY=C:\Ipara.co\Scripts\python.exe"
20
- )
21
-
22
- if defined PY (
23
- "%PY%" run_lpu.py --desktop %*
24
- ) else (
25
- py -3 run_lpu.py --desktop %* 2>nul || python run_lpu.py --desktop %*
26
- )
27
- exit /b %ERRORLEVEL%
 
1
+ @echo off
2
+ REM LPU AI Accelerator V7.2 — NATIVE DESKTOP LAUNCHER (no browser)
3
+ REM Fixes the "Electron/Chromium warning" issue: this launcher calls
4
+ REM python.exe EXPLICITLY, so the broken .py file association on the
5
+ REM machine (an Electron-based editor had taken over .py) is bypassed.
6
+ REM Double-clickable from Explorer, works from any PowerShell/CMD cwd.
7
+
8
+ setlocal
9
+ set "LPU_ROOT=%~dp0."
10
+ cd /d "%LPU_ROOT%"
11
+
12
+ REM python precedence: project venv -> Ipara.co venv -> py launcher
13
+ set "PY="
14
+ if exist "%LPU_ROOT%\.venv\Scripts\python.exe" (
15
+ set "PY=%LPU_ROOT%\.venv\Scripts\python.exe"
16
+ ) else if exist "C:\ipara\Ipara.co\Scripts\python.exe" (
17
+ set "PY=C:\ipara\Ipara.co\Scripts\python.exe"
18
+ ) else if exist "C:\Ipara.co\Scripts\python.exe" (
19
+ set "PY=C:\Ipara.co\Scripts\python.exe"
20
+ )
21
+
22
+ if defined PY (
23
+ "%PY%" run_lpu.py --desktop %*
24
+ ) else (
25
+ py -3 run_lpu.py --desktop %* 2>nul || python run_lpu.py --desktop %*
26
+ )
27
+ exit /b %ERRORLEVEL%
LPU_Server.cmd CHANGED
@@ -1,24 +1,24 @@
1
- @echo off
2
- REM LPU AI Accelerator V7.1.1 — browser-dashboard launcher.
3
- REM Explicit python.exe call (bypasses any broken .py association).
4
- REM Double-clickable from Explorer, works from any PowerShell/CMD cwd.
5
-
6
- setlocal
7
- set "LPU_ROOT=%~dp0.."
8
- cd /d "%LPU_ROOT%"
9
-
10
- set "PY="
11
- if exist "%LPU_ROOT%\.venv\Scripts\python.exe" (
12
- set "PY=%LPU_ROOT%\.venv\Scripts\python.exe"
13
- ) else if exist "C:\ipara\Ipara.co\Scripts\python.exe" (
14
- set "PY=C:\ipara\Ipara.co\Scripts\python.exe"
15
- ) else if exist "C:\Ipara.co\Scripts\python.exe" (
16
- set "PY=C:\Ipara.co\Scripts\python.exe"
17
- )
18
-
19
- if defined PY (
20
- "%PY%" run_lpu.py %*
21
- ) else (
22
- py -3 run_lpu.py %* 2>nul || python run_lpu.py %*
23
- )
24
- exit /b %ERRORLEVEL%
 
1
+ @echo off
2
+ REM LPU AI Accelerator V7.2 — browser-dashboard launcher.
3
+ REM Explicit python.exe call (bypasses any broken .py association).
4
+ REM Double-clickable from Explorer, works from any PowerShell/CMD cwd.
5
+
6
+ setlocal
7
+ set "LPU_ROOT=%~dp0."
8
+ cd /d "%LPU_ROOT%"
9
+
10
+ set "PY="
11
+ if exist "%LPU_ROOT%\.venv\Scripts\python.exe" (
12
+ set "PY=%LPU_ROOT%\.venv\Scripts\python.exe"
13
+ ) else if exist "C:\ipara\Ipara.co\Scripts\python.exe" (
14
+ set "PY=C:\ipara\Ipara.co\Scripts\python.exe"
15
+ ) else if exist "C:\Ipara.co\Scripts\python.exe" (
16
+ set "PY=C:\Ipara.co\Scripts\python.exe"
17
+ )
18
+
19
+ if defined PY (
20
+ "%PY%" run_lpu.py %*
21
+ ) else (
22
+ py -3 run_lpu.py %* 2>nul || python run_lpu.py %*
23
+ )
24
+ exit /b %ERRORLEVEL%
README.md CHANGED
@@ -1,58 +1,61 @@
1
- ---
2
- title: Virtual-LPU
3
- sdk: static
4
- emoji: 📊
5
- colorFrom: blue
6
- colorTo: indigo
7
- short_description: Find bottlenecks in PyTorch training in real time.
8
- license: apache-2.0
9
- ---
10
-
11
- app_file: index.html
12
- pinned: false
13
-
14
- # LPU AI Accelerator V7 — README# LPU AI Accelerator V7 — README
15
- **Intelligent Training Control Center & Adaptive Runtime.**
16
- Runs beside your training (VS Code → your python → V010) as an independent
17
- service: auto-detects the training process, shows live hardware + training
18
- state in a control-center dashboard, classifies bottlenecks with measured
19
- evidence, and governs parameter changes through a 3-level safety model with
20
- full audit trail and rollback.
21
-
22
- * Build on: LPU Virtual Runtime **V6** core (reused verbatim; only
23
- `version.py` bumped to 7.0.0 and an additive protocol extension).
24
- * Server: FastAPI + WebSocket + SQLite/JSONL (torch-free footprint).
25
- * Dashboard: single self-contained HTML (no build step).
26
- * Integration SDK: one stdlib-only file the trainer imports (fail-open).
27
- * 56 automated tests green in the reference sandbox; 2 hardware-gated rows
28
- must run on the 2×P100 rig via `scripts/rig_tests.ps1`.
29
-
30
- ## Quick start (Windows)
31
 
32
  ```powershell
33
- & "C:\Ipara.co\Scripts\python.exe" -m pip install -r requirements.txt
34
- & "C:\Ipara.co\Scripts\python.exe" .\run_lpu.py --desktop # NATIVE window (no browser)
35
- & "C:\Ipara.co\Scripts\python.exe" .\run_lpu.py # browser dashboard
36
  ```
37
 
38
- Then press **DETECT PROJECT** (or let auto-detection find your running
39
- training) and **CONNECT TO TRAINING**. For deep telemetry inside the
40
- trainer, add `adapters/lpu_accelerate.py` to your project — see
41
- `docs/INSTALL_WINDOWS.md` §4.
42
 
43
- ## Documents
44
-
45
- | File | Content |
46
  |---|---|
47
- | `docs/AUDIT_REPORT_V7.md` | Phase 1 source audit (capabilities, gaps, V7 map) |
48
- | `docs/IMPLEMENTATION_AND_TEST_REPORT.md` | Step-by-step build + test evidence |
49
- | `docs/INSTALL_WINDOWS.md` | Install, run, SDK integration, security, rig tests |
50
- | `docs/API_REFERENCE.md` | Every REST + WebSocket endpoint |
51
- | `docs/test_run_detail.txt` | Raw pytest output (reference sandbox) |
52
-
53
- ## Non-negotiables honored (mission §21)
54
-
55
- Read-only discovery (hash-tested) · measured data only, unmeasured = "not
56
- measured" · level-3 parameters never auto-applied · every change journaled
57
- with old/new/reason and rollback · stopping the accelerator never stops
58
- training · loopback-only by default · token auth mandatory when exposed.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LPU AI Accelerator V7.2
2
+
3
+ AI-accelerator control center: FastAPI server + dashboard + native desktop
4
+ window, started from a single entry point. Server/monitoring processes are
5
+ completely independent of any training process — starting, stopping or
6
+ closing this app NEVER touches training.
7
+
8
+ ## Quick start
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  ```powershell
11
+ python -m venv .venv ; .\.venv\Scripts\activate
12
+ pip install -r requirements.txt
13
+ python run_lpu.py # server + dashboard in the browser
14
  ```
15
 
16
+ or double-click the .cmd launchers (they call python.exe explicitly, so a
17
+ broken .py file association cannot swallow the invocation — the fix for the
18
+ Electron/Chromium incident):
 
19
 
20
+ | Launcher | Action |
 
 
21
  |---|---|
22
+ | `LPU_Desktop.cmd` | native window (pywebview; honest browser fallback with reason) |
23
+ | `LPU_Server.cmd` | server + dashboard in the system browser |
24
+ | `LPU_Check.cmd` | environment self-check — starts nothing, safe anytime |
25
+
26
+ CLI: `python run_lpu.py [--desktop] [--no-browser] [--port 8710]
27
+ [--host 127.0.0.1] [--config configs\lpu_config_v7.yaml] [--check]`.
28
+
29
+ ## Layout
30
+
31
+ ```
32
+ run_lpu.py single entry point (all modes)
33
+ desktop_app.py native desktop app (3 modes, port scan, honest fallback)
34
+ run_lpu_desktop.py PyInstaller target
35
+ server/app.py FastAPI: / (dashboard) /api/status (JSON)
36
+ lpu/version.py version identity (7.2.0)
37
+ lpu/cli/self_check.py --check report (PASS/WARN/SKIP, never fabricated)
38
+ frontend/dashboard.html served at / — polls /api/status every 2 s
39
+ configs/lpu_config_v7.yaml default config (documented defaults only)
40
+ tests/ 22 tests (server lifecycle, attach detection,
41
+ fallback routing, launcher plumbing, 7.2 fixes)
42
+ docs/PHASE1_AUDIT/ 6 audit reports (source, architecture, dependency
43
+ map, roadmap, risks, coverage) — read them before
44
+ extending; every claim was executed, not assumed.
45
+ ```
46
+
47
+ ## Guarantees
48
+
49
+ - Loopback by default; a non-loopback `--host` is your explicit decision
50
+ (token middleware is PHASE 3 — see docs/PHASE1_AUDIT/DEVELOPMENT_ROADMAP.md).
51
+ - Attach mode never stops the other process's server; closing the window
52
+ stops only the server this app owns.
53
+ - No pywebview or window failure → honest browser fallback, reason printed.
54
+ - `LPU_Check.cmd` reports the environment truthfully, including what is
55
+ missing and how to enable it.
56
+
57
+ ## Tests
58
+
59
+ ```powershell
60
+ python -m pytest tests -q # 21 passed, 1 skipped (native window = display-gated)
61
+ ```
__pycache__/desktop_app.cpython-315.pyc ADDED
Binary file (15.7 kB). View file
 
configs/lpu_config_v7.yaml CHANGED
@@ -1,43 +1,24 @@
1
- # LPU AI Accelerator V7 configuration.
2
- # Read by the V7 server/accelerator layer directly (the V6 `lpu` core keeps
3
- # its own lpu_config.yaml schema unchanged - backward compatibility rule).
4
- # Every key below has a real consumer in server/app.py or lpu/accelerator/*.
 
 
5
 
6
  server:
7
- host: 127.0.0.1 # loopback ONLY by default (mission §13)
8
  port: 8710
9
- expose: false # true + non-loopback host => token auth REQUIRED
10
- open_browser: true # open the dashboard on start (run_lpu.py)
11
 
12
  accelerator:
13
- autostart: true # start the AcceleratorService with the server
14
- auto_connect: true # attach automatically to a detected training process
15
- poll_seconds_idle: 5.0
16
- poll_seconds_active: 2.0
17
-
18
- optimizer:
19
- enabled: true
20
- auto_apply_level1: false # level-1 changes still need the SDK channel;
21
- # auto-apply only with this flag true
22
- cooldown_s: 900 # same parameter re-proposed at most every 15 min
23
- max_proposals: 8
24
-
25
- bottleneck:
26
- window_s: 120
27
- min_samples: 5
28
- thresholds:
29
- data_wait_ratio: 0.5
30
- gpu_idle_pct: 40
31
- gpu_busy_pct: 90
32
- vram_used_pct: 95
33
 
34
  monitoring:
35
- enabled: true
36
- autostart: true # monitoring ON when accelerator starts
37
- gpu_sample_seconds: 2.0
38
 
39
- integration:
40
- deep_scan: false
41
- python: "C:\\ipara\\Scripts\\python.exe"
42
 
43
- log_level: INFO
 
 
1
+ # LPU AI Accelerator V7.2 — default config (was silently missing in 7.1.1).
2
+ # run_lpu.py:50 loads configs/lpu_config_v7.yaml by default; the 7.1.1 tree
3
+ # shipped no configs/ directory, so every launch silently ran with {}.
4
+ # All values below are the same defaults the code already used when the
5
+ # config was empty — nothing changes for existing setups; an explicit
6
+ # --config file still overrides this file.
7
 
8
  server:
9
+ host: 127.0.0.1
10
  port: 8710
11
+ open_browser: true
 
12
 
13
  accelerator:
14
+ autostart: false
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  monitoring:
17
+ interval_s: 2.0
 
 
18
 
19
+ training:
20
+ attach:
21
+ scan_interval_s: 5.0
22
 
23
+ paths:
24
+ lpu_home: null # null = default (LPU_HOME env or OS user home)
docs/PHASE1_AUDIT/ARCHITECTURE_BASELINE.md ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PHASE 1 — ARCHITECTURE BASELINE (LPU V7 tree)
2
+
3
+ Date: 2026-11-18. Everything marked IMPLEMENTED was verified by execution;
4
+ PROPOSED items do not exist in code (grep-verified).
5
+
6
+ ## 1. Actual architecture (implemented, 7.1.1 → 7.2.0)
7
+
8
+ ```mermaid
9
+ flowchart LR
10
+ subgraph entries["Entry points"]
11
+ CMD[LPU_Desktop.cmd / LPU_Server.cmd / LPU_Check.cmd]
12
+ RL[run_lpu.py]
13
+ RLD[run_lpu_desktop.py]
14
+ end
15
+ subgraph core["Control plane"]
16
+ DA[desktop_app.py<br/>mode resolution + ServerThread]
17
+ SA[server/app.py<br/>FastAPI: / + /api/status]
18
+ FW[frontend/dashboard.html<br/>polls /api/status]
19
+ SC[lpu/cli/self_check.py<br/>--check report (7.2)]
20
+ end
21
+ VER[lpu/version.py 7.2.0]
22
+ CFG[configs/lpu_config_v7.yaml (7.2)]
23
+ CMD --> RL --> DA
24
+ RLD --> DA
25
+ RL -- --check --> SC
26
+ DA --> SA --> FW
27
+ DA --> VER
28
+ RL --> CFG
29
+ ```
30
+
31
+ ## 2. Runtime lifecycle (implemented)
32
+
33
+ `run_lpu.py:64-91` parses args → `--check` runs `lpu.cli.self_check`
34
+ (7.2; was ModuleNotFoundError in 7.1.1) → `--desktop` delegates to
35
+ `desktop_app.main` → plain path serves uvicorn and (7.2, D5) opens the
36
+ browser when `server.open_browser` is true.
37
+
38
+ `desktop_app.launch_desktop` (`:156-226`) resolves the mode:
39
+ 1. **native** — start ServerThread + pywebview window;
40
+ 2. **native-attached** — an LPU 7.x server already answers on the port:
41
+ open a window on it, never a duplicate server;
42
+ 3. **browser-fallback** — pywebview missing or window creation failed:
43
+ honest reason printed, system browser opened, serve loop unwinds via
44
+ `request_shutdown()`.
45
+
46
+ Port policy (`:93-111`): first port that hosts OUR accelerator (attach) or
47
+ is truly free; foreign services are skipped, never hijacked.
48
+
49
+ ## 3. Process integration & failure isolation (implemented)
50
+
51
+ - uvicorn runs in a daemon thread owned by the app process
52
+ (desktop_app.py:114-140); `stop()` sets `should_exit` and joins.
53
+ - Attach mode never stops the other process's server (finally-block guard
54
+ at `:221-226`); closing the window stops ONLY the server this app owns.
55
+ - The server is independent of any training process by construction: no
56
+ training code exists in this tree's execution path at all.
57
+
58
+ ## 4. IPC / monitoring / optimization architecture
59
+
60
+ - IPC today = HTTP loopback only (/api/status JSON). No WebSocket, no
61
+ external-process attach (PROPOSED, PHASE 3).
62
+ - Monitoring = the dashboard's 2-second status poll (7.2). No GPU sampling
63
+ in this tree (PROPOSED — wire the designed V6 lpu/monitoring in PHASE 5).
64
+ - Optimization engine: not present (PROPOSED, PHASE 5; the empty
65
+ lpu/accelerator + lpu/runtime placeholder packages are the wiring points).
66
+
67
+ ## 5. Boundaries
68
+
69
+ Loopback default with explicit `--host` override (user decision); D5 fix
70
+ opens the browser only for loopback binds. The token rule for exposed binds
71
+ stays documentation-only until PHASE 3 implements it — never claimed as
72
+ present.
docs/PHASE1_AUDIT/DEVELOPMENT_ROADMAP.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PHASE 1 — DEVELOPMENT ROADMAP (LPU V7)
2
+
3
+ Date: 2026-11-18. Grounded in the audit of the real 7.1.1/7.2.0 tree.
4
+ No dates promised (mission rule); complexity estimates only.
5
+
6
+ ## Phase state
7
+
8
+ - PHASE 1 — DONE (this package): audit reports + the 7.2 patch set
9
+ (D1 self-check, D2 dashboard, D4 default config, D5 open_browser).
10
+ - PHASE 2 — Runtime Integration Foundation: fill the empty
11
+ `lpu/accelerator/` + `lpu/runtime/` placeholder packages with the
12
+ controller interface (start/stop/status) the server already implies;
13
+ wire `lpu/runtime` attachment behind an explicit API. Acceptance:
14
+ /api/status reports a REAL accelerator state machine, not a config echo;
15
+ tests headless. Complexity: medium. Prereq: user approval of PHASE 1.
16
+ - PHASE 3 — Independent Server hardening: implement the token rule
17
+ (currently documentation-only — audit D3), WebSocket events, session
18
+ persistence. Acceptance: exposed bind refuses to serve without a token;
19
+ events stream. Complexity: medium-high.
20
+ - PHASE 4 — Independent Dashboard: extend the real dashboard (7.2) with
21
+ start/stop controls, live terminal, hardware panels once PHASE 2 exposes
22
+ the data. Complexity: medium. The 7.2 dashboard polls /api/status only —
23
+ by design, no invented metrics.
24
+ - PHASE 5 — Adaptive Performance Engine: evidence-based optimization on
25
+ top of PHASE 2 telemetry (measurements + proposal + risk + rollback for
26
+ every recommendation). Complexity: high.
27
+ - PHASE 6 — Advanced Training Integration: explicit trainer APIs only;
28
+ training semantics never silently changed. Complexity: high.
29
+ - PHASE 7 — Reliability & Recovery: reconnection, crash isolation,
30
+ persistent sessions, graceful shutdown, long-duration stability.
31
+ - PHASE 8 — Hardware Acceptance: on the rig (2 × Tesla P100, Windows 11);
32
+ native WebView2 window test included. Nothing here is claimed passed
33
+ before this phase runs.
34
+
35
+ ## Top risks (full table in RISK_REGISTER.md)
36
+
37
+ 1. D3 token rule not enforced (PHASE 3) — until then, non-loopback binds
38
+ are the user's explicit decision.
39
+ 2. Placeholder-package wiring (PHASE 2) — one interface per phase, tested.
40
+ 3. The V6/V010 training line remains a separate archive — do not mix the
41
+ two trees' update packages again (root cause of the V010_LPU_V003.py
42
+ confusion this audit corrected).
docs/PHASE1_AUDIT/MODULE_DEPENDENCY_MAP.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PHASE 1 — MODULE DEPENDENCY MAP (LPU V7 tree)
2
+
3
+ Date: 2026-11-18. Method: AST/read of every file in the real tree (16 files)
4
+ plus grep verification of every claimed import.
5
+
6
+ ## 1. Module-by-module
7
+
8
+ | Module | Imports (internal) | External deps | Main callers | Public surface |
9
+ |---|---|---|---|---|
10
+ | run_lpu.py | server.app, desktop_app (lazy), lpu.cli.self_check (lazy) | argparse, uvicorn, yaml (lazy), webbrowser (7.2) | .cmd launchers, user CLI | main() |
11
+ | desktop_app.py | server.app (lazy) | uvicorn, urllib, socket (lazy), webview (optional) | run_lpu --desktop, run_lpu_desktop.py, tests | launch_desktop(), main(), request_shutdown(), ServerThread, find_port, is_lpu_server_running |
12
+ | server/app.py | lpu.version | fastapi, uvicorn (indirect) | run_lpu, desktop_app | create_app() |
13
+ | lpu/version.py | — | — | server/app, self_check, tests | __version__ |
14
+ | lpu/cli/__init__.py (7.2) | lpu.cli.self_check | — | run_lpu --check | run_self_check re-export |
15
+ | lpu/cli/self_check.py (7.2) | lpu.version, server.app | fastapi, uvicorn, yaml, webview (all optional) | run_lpu --check | run_self_check() |
16
+ | run_lpu_desktop.py | desktop_app | — | PyInstaller target | main() |
17
+ | frontend/dashboard.html | — | — (self-contained) | served at / | DOM + /api/status poll |
18
+ | tests/conftest.py | — | pytest | all tests | config fixture |
19
+ | tests/test_08_desktop.py | desktop_app, server.app | pytest, urllib, socket | CI/user | 13 tests |
20
+ | tests/test_09_v72_fixes.py (7.2) | run_lpu, server.app, desktop_app, lpu.cli, lpu.version | pytest, yaml | CI/user | 7 tests |
21
+ | LPU_*.cmd | — | — | user double-click | call python.exe explicitly |
22
+ | lpu/accelerator/__init__.py | — | — | NONE (0-byte placeholder) | — |
23
+ | lpu/runtime/__init__.py | — | — | NONE (0-byte placeholder) | — |
24
+
25
+ ## 2. Data flow
26
+
27
+ config YAML → run_lpu → create_app → FastAPI serves dashboard + JSON
28
+ status; desktop layer reads /api/status over loopback for attach detection
29
+ and readiness polling. One-directional; no shared mutable state between
30
+ processes (the attach contract is the HTTP status shape).
31
+
32
+ ## 3. Critical dependencies & risks
33
+
34
+ - fastapi + uvicorn are the whole server stack (both verified present in
35
+ the audit env; if absent, self-check reports WARN and exit 1 — D1 fix).
36
+ - pywebview is OPTIONAL: absence is handled honestly (browser fallback).
37
+ - No circular imports (verified by import execution of every module).
38
+ - Duplicate implementations: none in this tree. The previous 7.2 draft's
39
+ V003 version-gate patch does not apply here (wrong tree) — removed.
40
+
41
+ ## 4. Unused / placeholder modules (deliberate, keep)
42
+
43
+ lpu/accelerator/ and lpu/runtime/ are empty packages — the reserved wiring
44
+ points for PHASE 2/5 (accelerator controller, runtime attachment). They are
45
+ NOT dead code to delete; they are unimplemented seams to fill.
46
+
47
+ ## 5. Call-graph summary
48
+
49
+ .cmd launchers → run_lpu.main() → { self_check | desktop_app.main |
50
+ uvicorn(create_app) }; desktop_app.launch_desktop() → find_port() →
51
+ is_lpu_server_running() → ServerThread(create_app) → webview|browser.
docs/PHASE1_AUDIT/PHASE1_SOURCE_AUDIT.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PHASE 1 — SOURCE AUDIT (LPU V7 tree, the user's actual project)
2
+
3
+ Audit date: 2026-11-18 · Subject: the LPU AI Accelerator V7 tree (run_lpu.py /
4
+ desktop_app.py / server/ / lpu/ / frontend/) at 7.1.1, audited file-by-file.
5
+ All findings verified by executing code in the audit environment; file:line
6
+ references included.
7
+
8
+ ## 1. Project structure (the real tree, verified)
9
+
10
+ ```
11
+ LPU root (V7 line, e.g. C:\ipara\LPU\<folder>\LPU)
12
+ ├── run_lpu.py single entry: server / --desktop / --check (95 lines)
13
+ ├── run_lpu_desktop.py PyInstaller desktop entry (13 lines, imports desktop_app)
14
+ ├── desktop_app.py native-window app: 3 modes, port-scan, honest fallback
15
+ ├── server/app.py FastAPI control plane: / (dashboard), /api/status
16
+ ├── lpu/version.py version identity (7.1.1 -> 7.2.0 after this update)
17
+ ├── lpu/accelerator/, lpu/runtime/ empty placeholder packages (__init__ 0 bytes)
18
+ ├── frontend/dashboard.html served at / (was a 96-byte stub — see D2)
19
+ ├── LPU_Desktop.cmd / LPU_Server.cmd / LPU_Check.cmd python.exe-explicit launchers
20
+ ├── tests/conftest.py + test_08_desktop.py 13 tests (12 pass + 1 display-gated skip)
21
+ └── configs/ DID NOT EXIST (see D4)
22
+ ```
23
+
24
+ Note: this tree has no V010_*.py trainer files — the V6/V010 training line
25
+ is a separate archive. Any patch referencing V010_LPU_V003.py does not apply
26
+ here (this corrects the previous 7.2 draft, which targeted the wrong tree).
27
+
28
+ ## 2. Verified capabilities (executed here)
29
+
30
+ - **Server lifecycle**: ServerThread boots uvicorn in a daemon thread,
31
+ readiness-polled, clean stop (desktop_app.py:114-140). Verified by the
32
+ test_08 suite: 12 passed.
33
+ - **Attach detection**: `is_lpu_server_running()` checks /api/status for
34
+ `runtime_version` starting "7." (desktop_app.py:87-90); foreign ports are
35
+ skipped, never hijacked (desktop_app.py:93-111).
36
+ - **Honest fallback chain**: no pywebview OR window-creation failure →
37
+ browser fallback with the reason printed; never a silent exit; the loop
38
+ unwinds via request_shutdown() (desktop_app.py:186-220). Pinned by tests.
39
+ - **.cmd launchers**: call python.exe explicitly (bypasses the broken .py
40
+ association that caused the Electron/Chromium incident) — verified by
41
+ test_cmd_launchers_call_python_explicitly.
42
+ - **Baseline suite on 7.1.1**: 12 passed, 1 skipped (native window needs
43
+ display), 0 failed — the 7.1.1 desktop fix itself is sound.
44
+
45
+ ## 3. Defects found by this audit (each fixed by the 7.2 update)
46
+
47
+ | ID | Defect | Location | Evidence |
48
+ |---|---|---|---|
49
+ | D1 | `--check` is dead code: imports `lpu.cli.self_check`, which never existed → ModuleNotFoundError on every machine | run_lpu.py:60 | executed: `No module named 'lpu.cli'` |
50
+ | D2 | Dashboard served at `/` is a 96-byte stub (`<span>Runtime —</span>`), not a dashboard | frontend/dashboard.html | file content; served page verified over HTTP |
51
+ | D4 | run_lpu.py's documented default config `configs/lpu_config_v7.yaml` does not exist → every launch silently runs with `{}` | run_lpu.py:48-53 | `ls configs` → missing |
52
+ | D5 | `server.open_browser` (documented, default true) is never read anywhere → `python run_lpu.py` never opens the dashboard | run_lpu.py:87-91 (no consumer of the key) | grep: zero readers |
53
+
54
+ D3 (token-auth for exposed binds) is NOT implemented anywhere (grep: only
55
+ comments). It stays documented as a rule: loopback-only binds need no token;
56
+ any `--host 0.0.0.0` use is the user's explicit decision. Enforcing auth is
57
+ PHASE 3 work (roadmap), not silently claimed as present.
58
+
59
+ ## 4. Reachability / dead-code map (this tree)
60
+
61
+ Active: run_lpu.py, desktop_app.py, server/app.py, lpu/version.py,
62
+ frontend/dashboard.html, tests/, .cmd launchers.
63
+ Empty placeholders (future wiring points, keep): lpu/accelerator/__init__.py
64
+ (0 bytes), lpu/runtime/__init__.py (0 bytes).
65
+ Dead import (fixed by D1): lpu.cli.self_check was imported but absent — now
66
+ real. The `lpu` package contains no training logic in this line and the docs
67
+ never claim it does.
68
+
69
+ ## 5. Test coverage (real numbers, this environment)
70
+
71
+ - 7.1.1 baseline: tests/test_08_desktop.py — 12 passed, 1 skipped (native
72
+ window = display-gated), 0 failed.
73
+ - 7.2 patched tree: test_08_desktop.py 12 passed + test_09_v72_fixes.py
74
+ 7 passed → **19 passed, 1 skipped** total.
75
+ - Not covered (needs rig): native WebView2 window, real dual-GPU behavior,
76
+ long-duration stability (PHASE 7/8 of the roadmap).
docs/PHASE1_AUDIT/RISK_REGISTER.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PHASE 1 — RISK REGISTER (LPU V7 tree)
2
+
3
+ Date: 2026-11-18. Severity/Probability/Impact with detection,
4
+ mitigation and recovery for each. Evidenced risks only.
5
+
6
+ | ID | Risk | Sev | Prob | Impact | Detection | Mitigation | Recovery |
7
+ |---|---|---|---|---|---|---|---|
8
+ | R1 | Exposed bind (`--host 0.0.0.0`) with NO token auth — advertised in run_lpu.py:11 but nothing enforces it (audit D3) | High | Low (loopback is default) | LAN exposure of the control plane | grep: only comments mention the token; no code path | PHASE 3 implements token middleware; until then docs say loopback-only | Do not pass --host 0.0.0.0; firewall the port |
9
+ | R2 | Wrong-tree updates: the previous 7.2 draft patched V010_LPU_V003.py, a file that does not exist in this project (user hit: "ERROR: ... not found") | High | Med (repeatable) | User-facing apply failures, eroded trust | APPLY_UPDATE.ps1 now probes for run_lpu.py first and refuses on mismatch | Each update package declares its target tree shape (MANIFEST.json) | Re-run the corrected package (this one); no side effects from the failed run |
10
+ | R3 | pywebview/WebView2 missing or failing on the rig | Med | Med | Native window unavailable | desktop_app prints the exact reason at fallback | Honest browser fallback (tested); LPU_Check.cmd now reports it (D1 fix) | `pip install pywebview` / install WebView2 Runtime |
11
+ | R4 | Dashboard drift: server gains endpoints but the page is not updated | Med | Med | UI lies about state | test_09 pins dashboard↔/api/status contract | Keep the contract tests beside each new endpoint (PHASE 3/4 rule) | Revert endpoint, fix page, re-run tests |
12
+ | R5 | Empty placeholder packages (lpu/accelerator, lpu/runtime) filled carelessly in later phases | High | Med | Crashes, fake status | PHASE 2 acceptance: state machine from real interfaces, not config echo | One interface per phase + headless tests | Placeholder packages are additive; restore from backup |
13
+ | R6 | Windows .py association re-breaks (the Electron incident) | Med | Low | Launchers swallow invocations | .cmd launchers call python.exe explicitly (tested) | Keep using the .cmd files; LPU_Check.cmd diagnoses | Re-run via .cmd; fix association via default-apps settings |
14
+ | R7 | Update mis-application on the user's real folder (nested/unzipped paths, e.g. 14050827\) | Med | Med | Patch lands in the wrong tree | APPLY_UPDATE.ps1 step 0 probes run_lpu.py before touching anything; -LpuRoot parameter | Always run from the update folder with the project root passed explicitly | .lpu_update_backup\7.2\<ts> holds every original; ROLLBACK_UPDATE.ps1 restores all |
15
+ | R8 | Long-run stability (server thread leaks) unverified | Med | Low | Resource growth | test_stop_never_leaves_thread + port re-bind test | Keep the lifecycle tests green per update | Restart the app; training processes are never touched by design |
docs/PHASE1_AUDIT/TEST_COVERAGE_REPORT.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PHASE 1 — TEST COVERAGE REPORT (LPU V7 tree)
2
+
3
+ Date: 2026-11-18. Every number below is an actual run in this audit
4
+ environment (Linux, headless; fastapi/uvicorn present; no pywebview, no
5
+ display, no CUDA). Nothing unexecuted is reported as passing.
6
+
7
+ ## Executed matrix
8
+
9
+ | Suite | Tests | Result | Runtime | Category |
10
+ |---|---|---|---|---|
11
+ | tests/test_08_desktop.py (7.1.1 baseline, unpatched tree) | 13 | 12 passed, 1 skipped | 5.3 s | source + headless server lifecycle |
12
+ | tests/test_08_desktop.py (after 7.2 apply) | 13 | 12 passed, 1 skipped | 4.9 s | regression: no breakage |
13
+ | tests/test_09_v72_fixes.py (new, 7.2) | 7 | 7 passed | 0.6 s | headless: self-check, dashboard, config, version |
14
+ | `python -m lpu.cli.self_check` (new, 7.2) | — | exit 0, all PASS/SKIP honest | <1 s | environment probe |
15
+
16
+ **Total on the patched tree: 19 passed, 1 skipped, 0 failed.**
17
+
18
+ The 1 skip is `test_native_mode_needs_display_or_pywebview` — honestly
19
+ gated: the native WebView2 window needs the rig's display + pywebview
20
+ (PHASE 8, never claimed passed here).
21
+
22
+ ## What each new test pins (test_09_v72_fixes.py)
23
+
24
+ - D1: self-check module imports, runs, exits 0/1 by server health;
25
+ `run_lpu.main(["--check"])` wiring works.
26
+ - D2: dashboard is a real page (>1 KB, polls /api/status, viewport meta);
27
+ the live server actually serves it with the status JSON next to it.
28
+ - D4: default config exists, parses, matches the code's documented
29
+ defaults; `run_lpu._load_config(None)` now finds it.
30
+ - Version: `lpu/version.py` reports 7.2.0 (attach detection keys on the
31
+ "7." prefix — tested).
32
+
33
+ ## Not covered (needs the rig / later phases)
34
+
35
+ - Native WebView2 window creation (display-gated) — rig, PHASE 8.
36
+ - Real dual-P100 behavior — this tree has no GPU code paths at all yet.
37
+ - Token auth (D3) — does not exist; PHASE 3 adds it with tests.
38
+ - Long-duration stability — PHASE 7.
39
+
40
+ ## Required tests for future phases
41
+
42
+ - PHASE 2: accelerator state-machine tests (real status, not config echo).
43
+ - PHASE 3: token middleware tests (exposed bind refuses without token).
44
+ - PHASE 4: dashboard control-action tests (start/stop via API contract).
frontend/dashboard.html CHANGED
@@ -1,471 +1,91 @@
1
  <!doctype html>
2
- <html lang="en">
3
  <head>
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <title>LPU AI Accelerator — Control Center</title>
7
  <style>
8
- :root{
9
- --bg:#0b0e13;--panel:#12161f;--panel2:#171c27;--line:#232a38;
10
- --txt:#d6dce8;--dim:#8a93a6;--accent:#3fc6a0;--warn:#e2b93b;--err:#e05260;
11
- --info:#5aa7e8;--gpu0:#3fc6a0;--gpu1:#5aa7e8;--mono:'Cascadia Mono',Consolas,monospace;
12
- }
13
- *{box-sizing:border-box}
14
- body{margin:0;background:var(--bg);color:var(--txt);
15
- font:13px/1.45 'Segoe UI',system-ui,Arial,sans-serif}
16
- header{display:flex;align-items:center;gap:14px;padding:10px 16px;
17
- background:linear-gradient(90deg,#10151f,#131a27);border-bottom:1px solid var(--line)}
18
- header .logo{font:700 17px var(--mono);color:var(--accent);letter-spacing:1px}
19
- header .sub{color:var(--dim);font-size:11px}
20
- .pills{display:flex;gap:8px;margin-left:auto;flex-wrap:wrap}
21
- .pill{padding:3px 10px;border:1px solid var(--line);border-radius:12px;
22
- font:11px var(--mono);color:var(--dim);background:var(--panel)}
23
- .pill b{color:var(--txt)}
24
- .pill.on b{color:var(--accent)}
25
- main{display:grid;grid-template-columns:2fr 1fr;gap:12px;padding:12px 16px;
26
- max-width:1500px;margin:0 auto}
27
- .panel{background:var(--panel);border:1px solid var(--line);border-radius:8px;
28
- padding:12px 14px;margin-bottom:12px}
29
- .panel h2{margin:0 0 10px;font:600 12px var(--mono);color:var(--dim);
30
- text-transform:uppercase;letter-spacing:1.2px}
31
- .btns{display:grid;grid-template-columns:repeat(4,1fr);gap:8px}
32
- button{background:var(--panel2);color:var(--txt);border:1px solid var(--line);
33
- border-radius:6px;padding:8px 10px;font:600 11.5px var(--mono);cursor:pointer;
34
- transition:border-color .15s}
35
- button:hover{border-color:var(--accent)}
36
- button.primary{background:#0e2b26;border-color:var(--accent);color:var(--accent)}
37
- button.danger{background:#2b1114;border-color:var(--err);color:var(--err)}
38
- button.warnb{background:#2b2410;border-color:var(--warn);color:var(--warn)}
39
- button:disabled{opacity:.4;cursor:not-allowed}
40
- .grid2{display:grid;grid-template-columns:1fr 1fr;gap:12px}
41
- .gpu-cards{display:grid;grid-template-columns:1fr 1fr;gap:12px}
42
- .gpu-card{background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:10px 12px}
43
- .gpu-card h3{margin:0 0 6px;font:600 12px var(--mono)}
44
- .gpu-card .idx{float:right;color:var(--dim)}
45
- .bar{height:8px;background:#0b0e13;border-radius:4px;overflow:hidden;margin:4px 0 8px}
46
- .bar>i{display:block;height:100%;border-radius:4px;background:var(--accent);transition:width .4s}
47
- .bar.warn>i{background:var(--warn)}
48
- .kv{display:grid;grid-template-columns:auto 1fr;gap:2px 10px;font:11px var(--mono)}
49
- .kv span:nth-child(odd){color:var(--dim)}
50
- .kv span:nth-child(even){text-align:right}
51
- .cores{display:flex;gap:2px;flex-wrap:wrap;margin-top:6px}
52
- .core{width:7px;height:16px;background:#0b0e13;border-radius:2px}
53
- .term{background:#07090d;border:1px solid var(--line);border-radius:6px;
54
- font:11.5px var(--mono);height:340px;overflow-y:auto;padding:8px 10px}
55
- .term .ln{white-space:pre-wrap;word-break:break-all}
56
- .term .ts{color:#4a5568;margin-right:6px}
57
- .term .k-LPU{color:var(--accent)}.term .k-PROJECT{color:var(--info)}
58
- .term .k-ANALYSIS{color:#b48ee0}.term .k-GPU{color:var(--gpu1)}
59
- .term .k-MEMORY{color:var(--warn)}.term .k-OPTIMIZER{color:#e8d26a}
60
- .term .k-SESSION{color:var(--err)}.term .l-warn{color:var(--warn)}
61
- .term .l-error{color:var(--err)}
62
- .term-tools{display:flex;gap:8px;margin-bottom:8px;flex-wrap:wrap;align-items:center}
63
- .term-tools input,.term-tools select{background:var(--panel2);color:var(--txt);
64
- border:1px solid var(--line);border-radius:5px;padding:4px 8px;font:11px var(--mono)}
65
- table{width:100%;border-collapse:collapse;font:11.5px var(--mono)}
66
- th{text-align:left;color:var(--dim);border-bottom:1px solid var(--line);
67
- padding:4px 6px;font-weight:600}
68
- td{border-bottom:1px solid #1a2029;padding:4px 6px;vertical-align:top}
69
- .lvl{padding:1px 6px;border-radius:8px;font-size:10px;font-weight:700}
70
- .lvl1{background:#0e2b26;color:var(--accent)}.lvl2{background:#132339;color:var(--info)}
71
- .lvl3{background:#2b1114;color:var(--err)}
72
- .tag{padding:1px 6px;border-radius:8px;font-size:10px;border:1px solid var(--line);color:var(--dim)}
73
- .tag.ok{color:var(--accent);border-color:var(--accent)}
74
- .tag.warn{color:var(--warn);border-color:var(--warn)}
75
- .tag.err{color:var(--err);border-color:var(--err)}
76
- .bneck{border-left:3px solid var(--warn);padding:8px 10px;background:var(--panel2);
77
- border-radius:0 6px 6px 0;font:11.5px var(--mono)}
78
- .bneck .cat{color:var(--warn);font-weight:700}
79
- footer{color:var(--dim);font-size:10.5px;text-align:center;padding:10px}
80
- dialog{background:var(--panel);color:var(--txt);border:1px solid var(--err);
81
- border-radius:8px;padding:18px;max-width:460px}
82
- dialog::backdrop{background:rgba(0,0,0,.6)}
83
- #toast{position:fixed;bottom:18px;right:18px;display:flex;flex-direction:column;gap:6px;z-index:50}
84
- .toast{background:var(--panel2);border:1px solid var(--accent);color:var(--txt);
85
- padding:8px 14px;border-radius:6px;font:12px var(--mono);opacity:.95}
86
- .toast.err{border-color:var(--err)}
87
- @media(max-width:1100px){main{grid-template-columns:1fr}.gpu-cards{grid-template-columns:1fr}}
88
  </style>
89
  </head>
90
  <body>
91
  <header>
92
- <div>
93
- <div class="logo">⬡ LPU AI ACCELERATOR</div>
94
- <div class="sub">Intelligent Training Control Center · V7 · مستقل از VS Code و فرآیند آموزش</div>
95
- </div>
96
- <div class="pills">
97
- <span class="pill" id="p-acc">Accelerator: <b>—</b></span>
98
- <span class="pill" id="p-run">Runtime <b>—</b></span>
99
- <span class="pill" id="p-srv">Server: <b>—</b></span>
100
- <span class="pill" id="p-ws">WebSocket: <b>—</b></span>
101
- <span class="pill" id="p-conn">Project: <b>—</b></span>
102
- <span class="pill" id="p-train">Training: <b>—</b></span>
103
- <span class="pill" id="p-sess">Session: <b>—</b></span>
104
- </div>
105
  </header>
106
-
107
  <main>
108
- <section>
109
- <div class="panel">
110
- <h2>Control</h2>
111
- <div class="btns">
112
- <button class="primary" id="b-acc-start">START ACCELERATOR</button>
113
- <button id="b-acc-stop">STOP ACCELERATOR</button>
114
- <button id="b-detect">DETECT PROJECT</button>
115
- <button id="b-connect">CONNECT TO TRAINING</button>
116
- <button id="b-disconnect">DISCONNECT</button>
117
- <button id="b-mon-start">START MONITORING</button>
118
- <button id="b-mon-stop">STOP MONITORING</button>
119
- <button id="b-export">EXPORT REPORT</button>
120
- <button class="warnb" id="b-pause">PAUSE TRAINING</button>
121
- <button id="b-resume">RESUME TRAINING</button>
122
- <button class="warnb" id="b-stop-train">STOP TRAINING (GRACEFUL)</button>
123
- <button class="danger" id="b-emergency">EMERGENCY STOP</button>
124
- </div>
125
- <div style="color:var(--dim);font-size:10.5px;margin-top:8px">
126
- STOP ACCELERATOR / DISCONNECT only stop the accelerator or detach it — the training process is never touched.
127
- EMERGENCY STOP terminates the attached process and requires explicit confirmation.
128
- </div>
129
- </div>
130
-
131
- <div class="panel">
132
- <h2>GPU Monitoring — per card, never pooled</h2>
133
- <div class="gpu-cards" id="gpus"><div class="gpu-card" style="color:var(--dim)">waiting for hardware samples…</div></div>
134
- </div>
135
-
136
- <div class="panel">
137
- <h2>Live Terminal</h2>
138
- <div class="term-tools">
139
- <label><input type="checkbox" id="t-auto" checked> auto-scroll</label>
140
- <input id="t-search" placeholder="search…" style="width:150px">
141
- <select id="t-kind"><option value="">all kinds</option><option>LPU</option><option>PROJECT</option><option>ANALYSIS</option><option>GPU</option><option>MEMORY</option><option>OPTIMIZER</option><option>SESSION</option></select>
142
- <select id="t-level"><option value="">all levels</option><option>info</option><option>warn</option><option>error</option></select>
143
- <button id="t-export">SAVE LOG</button>
144
- <span id="t-count" style="color:var(--dim);margin-left:auto"></span>
145
- </div>
146
- <div class="term" id="term"></div>
147
- </div>
148
-
149
- <div class="panel">
150
- <h2>Adaptive Optimizer — proposals &amp; change ledger</h2>
151
- <div id="bneck" style="margin-bottom:10px"></div>
152
- <table id="props"><thead><tr>
153
- <th>Parameter</th><th>Change</th><th>Level</th><th>Reason / Evidence</th><th>Status</th><th></th>
154
- </tr></thead><tbody></tbody></table>
155
- <h2 style="margin-top:14px">Change Ledger</h2>
156
- <table id="ledger"><thead><tr>
157
- <th>Param</th><th>Old → New</th><th>Status</th><th>Result</th><th></th>
158
- </tr></thead><tbody></tbody></table>
159
- </div>
160
- </section>
161
-
162
- <section>
163
- <div class="panel">
164
- <h2>Detected Project</h2>
165
- <div class="kv" id="project">
166
- <span>State</span><span id="pr-state">not connected</span>
167
- </div>
168
- <div id="pr-extra" class="kv" style="margin-top:6px"></div>
169
- </div>
170
-
171
- <div class="panel">
172
- <h2>Training Status</h2>
173
- <div class="kv" id="training"><span>State</span><span>—</span></div>
174
- </div>
175
-
176
- <div class="panel">
177
- <h2>CPU</h2>
178
- <div class="kv" id="cpu"></div>
179
- <div class="bar" id="cpu-bar"><i style="width:0%"></i></div>
180
- <div class="cores" id="cores"></div>
181
- </div>
182
-
183
- <div class="panel">
184
- <h2>RAM / 256GB</h2>
185
- <div class="kv" id="ram"></div>
186
- <div class="bar" id="ram-bar"><i style="width:0%"></i></div>
187
- </div>
188
-
189
- <div class="panel">
190
- <h2>Storage</h2>
191
- <div class="kv" id="disk"></div>
192
- </div>
193
-
194
- <div class="panel">
195
- <h2>Parameter Governance</h2>
196
- <div style="color:var(--dim);font-size:10.5px;margin-bottom:6px">
197
- L1 data-path · L2 numerics-preserving (validated) · L3 training semantics (user confirm) ·
198
- hot-reload / safe-boundary / restart-required
199
- </div>
200
- <table id="params"><thead><tr><th>Parameter</th><th>Class</th><th>Apply via</th></tr></thead><tbody></tbody></table>
201
- </div>
202
-
203
- <div class="panel">
204
- <h2>Sessions</h2>
205
- <table id="sessions"><thead><tr><th>Session</th><th>State</th><th>Epoch/Step</th><th>PSNR</th></tr></thead><tbody></tbody></table>
206
- </div>
207
- </section>
208
  </main>
209
-
210
- <footer>LPU AI Accelerator V7 — read-only towards foreign processes · measured data only · stopping the accelerator never stops training</footer>
211
-
212
- <dialog id="dlg">
213
- <h3 id="dlg-title" style="color:var(--err);margin-top:0"></h3>
214
- <p id="dlg-text" style="font-size:12.5px"></p>
215
- <div style="display:flex;gap:8px;justify-content:flex-end">
216
- <button id="dlg-no">CANCEL</button>
217
- <button class="danger" id="dlg-yes">CONFIRM</button>
218
- </div>
219
- </dialog>
220
- <div id="toast"></div>
221
-
222
  <script>
223
- "use strict";
224
- const $=id=>document.getElementById(id);
225
- const esc=s=>{const d=document.createElement('div');d.textContent=s==null?'':String(s);return d.innerHTML};
226
- let ws=null,wsBackoff=500,wsOK=false;
227
- let lines=[],lineLimit=600;
228
-
229
- function toast(msg,err){const t=document.createElement('div');t.className='toast'+(err?' err':'');t.textContent=msg;$('toast').appendChild(t);setTimeout(()=>t.remove(),4200)}
230
- async function api(path,method='GET',body=null){
231
- const res=await fetch(path,{method,headers:{'Content-Type':'application/json'},body:body?JSON.stringify(body):null});
232
- let data=null;try{data=await res.json()}catch(e){}
233
- if(!res.ok){const m=(data&&(data.detail||data.error))||('HTTP '+res.status);toast(m,true);throw new Error(m)}
234
- return data;
235
- }
236
- function confirmDialog(title,text){
237
- return new Promise(resolve=>{
238
- $('dlg-title').textContent=title;$('dlg-text').textContent=text;$('dlg').showModal();
239
- $('dlg-yes').onclick=()=>{$('dlg').close();resolve(true)};
240
- $('dlg-no').onclick=()=>{$('dlg').close();resolve(false)};
241
- });
242
- }
243
-
244
- /* ---------------- terminal ---------------- */
245
- function addLine(ev){
246
- if(ev.kind==='heartbeat')return;
247
- const kind=(ev.kind||'').toUpperCase();
248
- if($('t-kind').value && kind!==($('t-kind').value.toUpperCase()))return;
249
- if($('t-level').value && ev.level!== $('t-level').value)return;
250
- const s=$('t-search').value.toLowerCase();
251
- if(s && !String(ev.text||'').toLowerCase().includes(s))return;
252
- lines.push(ev);if(lines.length>lineLimit)lines.splice(0,lines.length-lineLimit);
253
- renderLines(true);
254
- }
255
- function renderLines(keepScroll){
256
- const term=$('term');
257
- const atBottom=term.scrollTop+term.clientHeight>=term.scrollHeight-30;
258
- term.innerHTML=lines.map(ev=>{
259
- const kind=(ev.kind||'').toUpperCase();
260
- return `<div class="ln l-${ev.level||'info'}"><span class="ts">${new Date((ev.ts||0)*1000).toLocaleTimeString()}</span><span class="k-${kind}">[${kind}]</span> ${esc(ev.text)}</div>`;
261
- }).join('');
262
- if(($('t-auto').checked&&atBottom)||keepScroll===true&&$('t-auto').checked)term.scrollTop=term.scrollHeight;
263
- $('t-count').textContent=lines.length+' lines';
264
- }
265
- $('t-search').oninput=()=>renderLines(false);
266
- $('t-kind').onchange=()=>renderLines(false);
267
- $('t-level').onchange=()=>renderLines(false);
268
- $('t-auto').onchange=()=>{if($('t-auto').checked)$('term').scrollTop=$('term').scrollHeight};
269
- $('t-export').onclick=()=>{
270
- const blob=new Blob([lines.map(e=>`${new Date((e.ts||0)*1000).toISOString()} [${(e.kind||'').toUpperCase()}] ${e.level||''} ${e.text}`).join('\n')],{type:'text/plain'});
271
- const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='lpu_terminal.log';a.click();
272
- };
273
-
274
- /* ---------------- websocket ---------------- */
275
- function connectWS(){
276
- try{ws=new WebSocket(`ws://${location.host}/ws`)}catch(e){scheduleWS();return}
277
- ws.onopen=()=>{wsOK=true;wsBackoff=500;setPill('p-ws','connected')};
278
- ws.onmessage=m=>{try{addLine(JSON.parse(m.data))}catch(e){}};
279
- ws.onclose=()=>{wsOK=false;setPill('p-ws','disconnected');scheduleWS()};
280
- ws.onerror=()=>{try{ws.close()}catch(e){}};
281
- }
282
- function scheduleWS(){setTimeout(connectWS,wsBackoff);wsBackoff=Math.min(wsBackoff*2,15000)}
283
- function setPill(id,val,on){const p=$(id);p.querySelector('b').textContent=val;p.classList.toggle('on',!!on)}
284
-
285
- /* ---------------- rendering ---------------- */
286
- function fmt(n,d=1){return n==null?'—':(typeof n==='number'?n.toFixed(d):n)}
287
- function renderStatus(st){
288
- setPill('p-acc',st.accelerator_status,st.accelerator_status==='running');
289
- setPill('p-srv',st.server_status,true);
290
- setPill('p-conn',st.connected?`pid ${st.active_training_process}`:'none',st.connected);
291
- setPill('p-run','V'+(st.runtime_version||'?'));
292
- setPill('p-train',st.training&&st.training.attached?(st.training.state||'training'):'—',st.training&&st.training.attached);
293
- setPill('p-sess',(st.session_id||'—').slice(0,18));
294
- $('p-sess').title='duration '+fmt(st.session_duration_s,0)+'s';
295
- $('b-acc-start').disabled=st.accelerator_status==='running';
296
- $('b-acc-stop').disabled=st.accelerator_status!=='running';
297
- $('b-mon-start').disabled=st.monitoring;
298
- $('b-mon-stop').disabled=!st.monitoring;
299
- const pr=$('pr-state'),ex=$('pr-extra');
300
- const a=st.detected_project&&st.detected_project.analysis;
301
- if(st.connected&&a){
302
- pr.textContent=`connected · ${a.kind}`;
303
- ex.innerHTML=[
304
- ['PID',a.pid],['Root',a.project_root],['Script',a.entry_script],
305
- ['Python',a.python_exe],['VRAM',a.vram_mb?fmt(a.vram_mb,0)+' MB':'—'],
306
- ['Training',a.training_active?`active (${a.training_active_basis})`:'inactive'],
307
- ['Dataset',(a.dataset_paths||[])[0]||'—'],
308
- ['Configs',(a.configs||[]).length+' found'],
309
- ['Checkpoints',(a.checkpoint_files||[]).length+' found'],
310
- ['Interpreter',a.interpreter&&a.interpreter.torch?`torch ${a.interpreter.torch} cuda=${a.interpreter.cuda}`:'probe n/a'],
311
- ].map(([k,v])=>`<span>${k}</span><span title="${esc(v)}">${esc(v)}</span>`).join('');
312
- }else{pr.textContent='not connected';ex.innerHTML=''}
313
- const t=st.training||{};
314
- $('training').innerHTML=[
315
- ['State',t.attached?(t.state||'training'):'not attached'],
316
- ['Epoch',t.epoch],['Step',t.step],['Total',t.total_steps],
317
- ['Loss',fmt(t.loss,5)],['Val Loss',fmt(t.val_loss,5)],
318
- ['PSNR',fmt(t.psnr,3)],['SSIM',fmt(t.ssim,4)],
319
- ['LR',t.lr==null?'—':t.lr],['Batch',t.batch_size],
320
- ['img/s',fmt(t.images_per_second,2)],
321
- ['Data-wait',t.data_wait_ratio==null?'—':fmt(t.data_wait_ratio,3)],
322
- ['SDK session',t.session_id||'—'],
323
- ].map(([k,v])=>`<span>${k}</span><span>${esc(v==null?'—':v)}</span>`).join('');
324
- }
325
- function renderHardware(hw){
326
- const gpus=hw.gpus||[];
327
- $('gpus').innerHTML=gpus.length?gpus.map(g=>{
328
- const up=g.utilization_pct==null?'—':g.utilization_pct.toFixed(0);
329
- const mp=g.mem_used_pct==null?0:g.mem_used_pct;
330
- return `<div class="gpu-card">
331
- <h3><span class="idx">GPU ${g.index}</span>${esc(g.name)}</h3>
332
- <div class="bar${up>=90?' warn':''}"><i style="width:${Math.min(up==null?0:up,100)}%"></i></div>
333
- <div class="kv">
334
- <span>Utilization</span><span>${up}%</span>
335
- <span>Memory</span><span>${fmt(g.mem_used_mb,0)} / ${fmt(g.mem_total_mb,0)} MB</span>
336
- <span>Free</span><span>${g.mem_total_mb==null?'—':fmt(g.mem_total_mb-(g.mem_used_mb||0),0)+' MB'}</span>
337
- <span>Temperature</span><span>${g.temperature_c==null?'—':g.temperature_c.toFixed(0)+' °C'}</span>
338
- <span>Power</span><span>${g.power_w==null?'—':g.power_w.toFixed(1)+' W'}</span>
339
- </div></div>`}).join('')
340
- :'<div class="gpu-card" style="color:var(--dim)">GPU metrics unavailable (no NVML / no samples yet) — reported honestly, never fabricated</div>';
341
- const c=hw.cpu||{};
342
- $('cpu').innerHTML=[['Total',c.total_pct==null?'—':c.total_pct.toFixed(0)+'%'],
343
- ['Cores (logical)',(c.per_core_pct||[]).length||'—'],
344
- ['Process',hw.process&&hw.process.cpu_pct!=null?hw.process.cpu_pct.toFixed(0)+'%':'—']]
345
- .map(([k,v])=>`<span>${k}</span><span>${v}</span>`).join('');
346
- $('cpu-bar').firstElementChild.style.width=Math.min(c.total_pct||0,100)+'%';
347
- const cores=$('cores');
348
- const pc=c.per_core_pct||[];
349
- if(cores.childElementCount!==pc.length){cores.innerHTML=pc.map(()=>'<div class="core"></div>').join('')}
350
- pc.forEach((v,i)=>{const el=cores.children[i];if(el)el.style.background=v>85?'var(--err)':v>40?'var(--warn)':'var(--accent)';el.style.opacity=Math.max(.25,v/100)});
351
- const r=hw.ram||{};
352
- $('ram').innerHTML=[['Total',fmt(r.total_gb,0)+' GB'],['Used',fmt(r.used_gb,1)+' GB'],
353
- ['Available',fmt(r.available_gb,1)+' GB'],['Used %',r.used_pct==null?'—':r.used_pct.toFixed(0)+'%'],
354
- ['Process RAM',hw.process&&hw.process.ram_mb!=null?fmt(hw.process.ram_mb,0)+' MB':'—'],
355
- ['Process Peak',hw.process&&hw.process.ram_peak_mb!=null?fmt(hw.process.ram_peak_mb,0)+' MB':'—']]
356
- .map(([k,v])=>`<span>${k}</span><span>${v}</span>`).join('');
357
- $('ram-bar').firstElementChild.style.width=Math.min(r.used_pct||0,100)+'%';
358
- const d=hw.disk||{};
359
- const sp=d.space||{};
360
- $('disk').innerHTML=[['Read',d.read_bps==null?'—':(d.read_bps/2**20).toFixed(1)+' MB/s'],
361
- ['Write',d.write_bps==null?'—':(d.write_bps/2**20).toFixed(1)+' MB/s'],
362
- ...Object.entries(sp).map(([k,v])=>[k+' free',v.free_gb+' / '+v.total_gb+' GB'])]
363
- .map(([k,v])=>`<span>${k}</span><span>${esc(v)}</span>`).join('');
364
- }
365
- function tag(s,cls){return `<span class="tag ${cls||''}">${esc(s)}</span>`}
366
- async function renderOptimizer(){
367
- try{
368
- const [bn,props,changes]=await Promise.all([api('/api/bottleneck'),api('/api/proposals'),api('/api/changes')]);
369
- const cur=bn.current;
370
- $('bneck').innerHTML=cur?`<div class="bneck"><span class="cat">BOTTLENECK: ${esc(cur.category)}</span><br>
371
- evidence: <code>${esc(JSON.stringify(cur.evidence))}</code><br>
372
- action: ${esc(cur.recommended_action)} · impact: ${esc(cur.expected_impact)} ·
373
- confidence: ${tag(cur.confidence,cur.confidence==='Measured'?'ok':'warn')}</div>`
374
- :'<div class="bneck" style="border-color:var(--line);color:var(--dim)">No bottleneck currently detected'+(bn.window.gpu_samples<bn.window.min_samples_required?' (collecting samples — '+bn.window.gpu_samples+'/'+bn.window.min_samples_required+')':'')+'</div>';
375
- const tb=$('props').querySelector('tbody');
376
- tb.innerHTML=(props.proposals||[]).map(p=>{
377
- const acts=[];
378
- if(p.status==='proposed'){acts.push(`<button onclick="approveP('${p.id}')">APPROVE</button><button onclick="rejectP('${p.id}')">REJECT</button>`)}
379
- if(['proposed','approved','needs_sdk'].includes(p.status))acts.push(`<button class="primary" onclick="applyP('${p.id}',${p.level})">APPLY</button>`);
380
- return `<tr><td><b>${esc(p.param)}</b><br>${tag('L'+p.level,'lvl'+p.level)}</td>
381
- <td>${esc(JSON.stringify(p.current))} → <b>${esc(JSON.stringify(p.proposed))}</b><br>${tag(p.change_class)} ${tag(p.confidence,p.confidence==='Measured'?'ok':'')}</td>
382
- <td colspan="2" style="color:var(--dim)">${esc(p.reason)}<br><code style="font-size:10px">${esc(JSON.stringify(p.evidence))}</code></td>
383
- <td>${tag(p.status,p.status.startsWith('applied')||p.status==='queued_at_boundary'?'ok':p.status==='rejected'?'':'warn')}</td>
384
- <td>${acts.join(' ')}</td></tr>`}).join('')||'<tr><td colspan="6" style="color:var(--dim)">no proposals yet (the engine proposes from measured bottlenecks)</td></tr>';
385
- const lb=$('ledger').querySelector('tbody');
386
- lb.innerHTML=(changes.changes||[]).map(c=>{
387
- const rb=['applied','queued_at_boundary'].includes(c.status)?`<button onclick="rollbackC('${c.id}')">ROLLBACK</button>`:'';
388
- return `<tr><td>${esc(c.param)}</td><td>${esc(JSON.stringify(c.old_value))} → ${esc(JSON.stringify(c.new_value))}</td>
389
- <td>${tag(c.status,c.status==='applied'?'ok':c.status==='rolled_back'?'':'warn')}</td>
390
- <td style="color:var(--dim);max-width:260px">${esc(String(c.result||'').slice(0,140))}</td><td>${rb}</td></tr>`}).join('')
391
- ||'<tr><td colspan="5" style="color:var(--dim)">no changes applied yet</td></tr>';
392
- }catch(e){}
393
- }
394
- window.approveP=async id=>{await api(`/api/proposals/${id}/approve`,'POST');renderOptimizer()};
395
- window.rejectP=async id=>{await api(`/api/proposals/${id}/reject`,'POST');renderOptimizer()};
396
- window.applyP=async(id,level)=>{
397
- let body={};
398
- if(level===3){
399
- const ok=await confirmDialog('Level-3 parameter','This parameter affects training semantics (LR/loss/EMA/…). Apply ONLY with your explicit confirmation. Continue?');
400
- if(!ok)return;body.confirm=true;
401
  }
402
- try{const r=await api(`/api/proposals/${id}/apply`,'POST',body);toast(`applied: ${r.status}`)}catch(e){}
403
- renderOptimizer();
404
- };
405
- window.rollbackC=async id=>{
406
- const ok=await confirmDialog('Rollback change','Restore the previous parameter value via the SDK channel?');
407
- if(!ok)return;
408
- try{const r=await api(`/api/changes/${id}/rollback`,'POST');toast(`rollback: ${r.status}`)}catch(e){}
409
- renderOptimizer();
410
- };
411
- async function renderSessions(){
412
- try{
413
- const s=await api('/api/sessions');
414
- $('sessions').querySelector('tbody').innerHTML=(s.sessions||[]).slice(0,12).map(x=>
415
- `<tr><td title="${esc(x.session_id)}">${esc(String(x.session_id).slice(0,16))}</td>
416
- <td>${esc(x.state||'—')}</td><td>${x.epoch??'—'}/${x.step??'—'}</td><td>${fmt(x.psnr,3)}</td></tr>`).join('')
417
- ||'<tr><td colspan="4" style="color:var(--dim)">no sessions recorded yet</td></tr>';
418
- }catch(e){}
419
- }
420
- async function renderParams(){
421
- try{
422
- const p=await api('/api/params');
423
- $('params').querySelector('tbody').innerHTML=(p.parameters||[]).map(x=>
424
- `<tr><td title="${esc(x.description)}"><b>${esc(x.name)}</b> ${x.user_approval_required?tag('L'+x.level+' confirm','lvl3'):tag('L'+x.level,'lvl'+x.level)}</td>
425
- <td>${tag(x.change_class)}</td><td>${esc(x.applied_via)}</td></tr>`).join('');
426
- }catch(e){}
427
- }
428
-
429
- /* ---------------- controls ---------------- */
430
- $('b-acc-start').onclick=()=>api('/api/accelerator/start','POST').then(()=>toast('accelerator started'));
431
- $('b-acc-stop').onclick=()=>api('/api/accelerator/stop','POST').then(r=>toast(r.note||'accelerator stopped'));
432
- $('b-detect').onclick=async()=>{const r=await api('/api/detect','POST');toast(`detected ${r.processes.length} process(es)`);refresh()};
433
- $('b-connect').onclick=async()=>{
434
- const st=await api('/api/status');
435
- const cands=(st.detected_processes||[]).filter(p=>p.kind!=='unknown');
436
- if(!cands.length){toast('no training process detected yet',true);return}
437
- try{const r=await api('/api/connect','POST',{pid:cands[0].pid});toast('connected to pid '+r.pid)}catch(e){}
438
- refresh();
439
- };
440
- $('b-disconnect').onclick=()=>api('/api/disconnect','POST').then(()=>toast('disconnected (training unaffected)'));
441
- $('b-mon-start').onclick=()=>api('/api/monitoring/start','POST').then(()=>toast('monitoring started'));
442
- $('b-mon-stop').onclick=()=>api('/api/monitoring/stop','POST').then(()=>toast('monitoring stopped'));
443
- $('b-export').onclick=async()=>{
444
- const fmtsel=prompt('Export format: json | csv | html','html');
445
- if(!fmtsel)return;
446
- try{const r=await api(`/api/report/export?format=${encodeURIComponent(fmtsel)}`);toast('report saved: '+r.path)}catch(e){}
447
- };
448
- $('b-pause').onclick=()=>api('/api/training/pause','POST').catch(()=>{});
449
- $('b-resume').onclick=()=>api('/api/training/resume','POST').catch(()=>{});
450
- $('b-stop-train').onclick=async()=>{
451
- const ok=await confirmDialog('Graceful stop','Request a graceful stop: the trainer finishes the current batch, checkpoints, and exits. Continue?');
452
- if(!ok)return;
453
- try{const r=await api('/api/training/stop','POST',{mode:'graceful'});toast('graceful stop requested')}catch(e){}
454
- };
455
- $('b-emergency').onclick=async()=>{
456
- const ok=await confirmDialog('EMERGENCY STOP','This TERMINATES the attached training process immediately (data loss possible). This is the only case where LPU ever touches a process. Continue?');
457
- if(!ok)return;
458
- try{await api('/api/training/stop','POST',{mode:'emergency',consent:true});toast('emergency stop sent')}catch(e){}
459
- };
460
-
461
- /* ---------------- polling ---------------- */
462
- let slowTick=0;
463
- async function refresh(){
464
- try{renderStatus(await api('/api/status'))}catch(e){setPill('p-srv','down')}
465
- try{renderHardware(await api('/api/hardware'))}catch(e){}
466
- if((slowTick++%5)===0){renderOptimizer();renderSessions();renderParams()}
467
- }
468
- connectWS();refresh();setInterval(refresh,2000);
469
  </script>
470
  </body>
471
  </html>
 
1
  <!doctype html>
2
+ <html lang="fa" dir="rtl">
3
  <head>
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>LPU AI Accelerator — Dashboard</title>
7
  <style>
8
+ :root { --bg:#0f1419; --panel:#161d26; --line:#232d3a; --txt:#d8dee9;
9
+ --dim:#8b98a5; --ok:#34d399; --warn:#fbbf24; --err:#f87171; }
10
+ * { box-sizing:border-box; margin:0; padding:0; }
11
+ body { font-family:"Segoe UI",Tahoma,sans-serif; background:var(--bg);
12
+ color:var(--txt); min-height:100vh; display:flex; flex-direction:column; }
13
+ header { display:flex; align-items:center; gap:12px; flex-wrap:wrap;
14
+ padding:14px 20px; border-bottom:1px solid var(--line); }
15
+ header h1 { font-size:clamp(1rem, 3vw, 1.3rem); font-weight:600; }
16
+ .pill { display:inline-flex; align-items:center; gap:8px;
17
+ border:1px solid var(--line); border-radius:999px;
18
+ padding:6px 14px; font-size:.85rem; background:var(--panel); }
19
+ .dot { width:10px; height:10px; border-radius:50%; background:var(--dim); }
20
+ .dot.running { background:var(--ok); box-shadow:0 0 8px var(--ok); }
21
+ .dot.stopped { background:var(--err); }
22
+ main { flex:1; padding:20px; display:grid; gap:16px;
23
+ grid-template-columns:repeat(auto-fit,minmax(280px,1fr));
24
+ max-width:1100px; width:100%; margin:0 auto; }
25
+ .card { background:var(--panel); border:1px solid var(--line);
26
+ border-radius:10px; padding:18px; }
27
+ .card h2 { font-size:.95rem; color:var(--dim); margin-bottom:12px; }
28
+ .kv { display:flex; justify-content:space-between; gap:10px;
29
+ padding:7px 0; border-bottom:1px dashed var(--line); font-size:.9rem; }
30
+ .kv:last-child { border-bottom:0; }
31
+ .kv b { color:var(--txt); font-weight:600; }
32
+ footer { padding:12px 20px; border-top:1px solid var(--line);
33
+ color:var(--dim); font-size:.8rem; display:flex; flex-wrap:wrap;
34
+ gap:8px; justify-content:space-between; }
35
+ #conn { color:var(--warn); }
36
+ @media (max-width:640px){ main{padding:12px;} .kv{font-size:.85rem;} }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  </style>
38
  </head>
39
  <body>
40
  <header>
41
+ <h1>LPU AI Accelerator</h1>
42
+ <span class="pill"><span class="dot" id="dot"></span><span id="acc">Accelerator —</span></span>
43
+ <span class="pill">Runtime <b id="ver">—</b></span>
 
 
 
 
 
 
 
 
 
 
44
  </header>
 
45
  <main>
46
+ <section class="card">
47
+ <h2>وضعیت شتاب‌دهنده (Accelerator)</h2>
48
+ <div class="kv"><span>نسخه‌ی ران‌تایم</span><b id="ver2">—</b></div>
49
+ <div class="kv"><span>وضعیت شتاب‌دهنده</span><b id="acc2">—</b></div>
50
+ <div class="kv"><span>آخرین به‌روزرسانی</span><b id="ts">—</b></div>
51
+ </section>
52
+ <section class="card">
53
+ <h2>راهنمای کنترل</h2>
54
+ <div class="kv"><span>شروع دسکتاپ</span><b>LPU_Desktop.cmd</b></div>
55
+ <div class="kv"><span>شروع سرور</span><b>LPU_Server.cmd</b></div>
56
+ <div class="kv"><span>بررسی محیط</span><b>LPU_Check.cmd</b></div>
57
+ </section>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  </main>
59
+ <footer>
60
+ <span id="conn">در حال اتصال…</span>
61
+ <span>بستن این پنجره فقط همین اپ را می‌بندد؛ فرایند آموزش دست‌نخورده می‌ماند.</span>
62
+ </footer>
 
 
 
 
 
 
 
 
 
63
  <script>
64
+ (function () {
65
+ var els = ["dot","acc","ver","acc2","ver2","ts","conn"].reduce(function (m, id) {
66
+ m[id] = document.getElementById(id); return m; }, {});
67
+ function render(s) {
68
+ var running = s && s.accelerator_status === "running";
69
+ els.dot.className = "dot " + (running ? "running" : "stopped");
70
+ var st = running ? "در حال اجرا" : "متوقف";
71
+ els.acc.textContent = "Accelerator — " + st;
72
+ els.acc2.textContent = st;
73
+ els.ver.textContent = els.ver2.textContent = s && s.runtime_version || "—";
74
+ els.ts.textContent = new Date().toLocaleTimeString("fa-IR");
75
+ els.conn.textContent = "";
76
+ els.conn.id = "conn";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  }
78
+ function fail(e) {
79
+ els.conn.textContent = "اتصال برقرار نشد: " + (e && e.message || e);
80
+ els.dot.className = "dot";
81
+ }
82
+ function poll() {
83
+ fetch("/api/status").then(function (r) { return r.json(); })
84
+ .then(render).catch(fail);
85
+ }
86
+ poll();
87
+ setInterval(poll, 2000);
88
+ })();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  </script>
90
  </body>
91
  </html>
lpu/__init__.py CHANGED
@@ -1,39 +0,0 @@
1
- """LPU Virtual Runtime - intelligent GPU acceleration layer for PyTorch workloads.
2
-
3
- Primary target: Super-Resolution training on Windows 11 with dual Tesla P100
4
- (Pascal, sm_60, no Tensor Cores). Designed for any CUDA-capable NVIDIA GPU.
5
-
6
- Design rules enforced across this package:
7
- * No fabricated metrics. Anything not measured is labeled an estimate.
8
- * NumPy is never described as CUDA. CUDA execution = torch CUDA tensors only.
9
- * Per-GPU memory accounting. VRAM is never treated as a unified pool.
10
- * The target project's Python environment is never modified (read-only).
11
- * Every optimization is reversible and fails open to plain PyTorch behavior.
12
-
13
- Torch is imported LAZILY (see lpu.compat): importing `lpu` never loads torch,
14
- so the background controller keeps a tiny torch-free footprint.
15
-
16
- Get torch via `from lpu.compat import require_torch`.
17
- """
18
-
19
- from .version import __version__, PACKAGE_NAME, COMPATIBILITY
20
- from .compat import optional_import, require_torch, TORCH_AVAILABLE
21
-
22
- __all__ = [
23
- "__version__",
24
- "PACKAGE_NAME",
25
- "COMPATIBILITY",
26
- "optional_import",
27
- "require_torch",
28
- "TORCH_AVAILABLE",
29
- ]
30
-
31
-
32
- def training_session(model, train_loader=None, config=None, name: str = "train",
33
- criterion=None, optimizer=None, batch_size=None):
34
- """Convenience constructor for lpu.training.TrainingSession (V4 kwargs)."""
35
- from .training import TrainingSession
36
-
37
- return TrainingSession(model, train_loader=train_loader, config=config,
38
- name=name, criterion=criterion, optimizer=optimizer,
39
- batch_size=batch_size)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lpu/__pycache__/__init__.cpython-315.pyc CHANGED
Binary files a/lpu/__pycache__/__init__.cpython-315.pyc and b/lpu/__pycache__/__init__.cpython-315.pyc differ
 
lpu/__pycache__/version.cpython-315.pyc CHANGED
Binary files a/lpu/__pycache__/version.cpython-315.pyc and b/lpu/__pycache__/version.cpython-315.pyc differ
 
lpu/accelerator/__init__.py CHANGED
@@ -1,31 +0,0 @@
1
- """LPU V7 Accelerator Controller — the standing decision brain.
2
-
3
- This subpackage is NEW in V7 (mission §2.B/§2.E). It runs torch-free inside
4
- the accelerator server process, continuously reads runtime facts (process
5
- discovery, GPU samples, session telemetry) and:
6
-
7
- * classifies bottlenecks with measured evidence (bottleneck.py)
8
- * governs parameter changes across the 3 safety levels and the
9
- hot-reload / safe-boundary / restart-required classes (parameters.py)
10
- * runs the propose -> validate -> apply -> ack -> rollback lifecycle
11
- (optimizer.py)
12
- * orchestrates everything in a background service loop (service.py)
13
-
14
- Design rules inherited from the V6 core:
15
- * no fabricated metrics - anything unmeasured is labeled an estimate
16
- * read-only towards foreign processes; control ONLY via the session
17
- command channel (allowlisted, envelope-versioned, acked)
18
- * stopping the accelerator NEVER stops training
19
- """
20
-
21
- from .parameters import PARAM_SPECS, ParamLevel, ChangeClass, ParamSpec
22
- from .bottleneck import BottleneckEngine, BottleneckReport
23
- from .optimizer import OptimizerEngine, Proposal, ChangeRecord
24
- from .service import AcceleratorService
25
-
26
- __all__ = [
27
- "PARAM_SPECS", "ParamLevel", "ChangeClass", "ParamSpec",
28
- "BottleneckEngine", "BottleneckReport",
29
- "OptimizerEngine", "Proposal", "ChangeRecord",
30
- "AcceleratorService",
31
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lpu/cli/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """LPU AI Accelerator V7.2 — cli package (was missing in 7.1.1).
2
+
3
+ run_lpu.py:60 imports `lpu.cli.self_check`; the 7.1.1 tree had no lpu/cli/
4
+ package at all, so `--check` crashed with ModuleNotFoundError everywhere.
5
+ """
6
+ from lpu.cli.self_check import run_self_check
7
+
8
+ __all__ = ["run_self_check"]
lpu/cli/__pycache__/__init__.cpython-315.pyc ADDED
Binary file (484 Bytes). View file
 
lpu/cli/__pycache__/self_check.cpython-315.pyc ADDED
Binary file (6.66 kB). View file
 
lpu/cli/self_check.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LPU AI Accelerator V7.2 — environment self-check (the real module).
2
+
3
+ V7.1.1 defect (D1): run_lpu.py --check did `from lpu.cli.self_check import
4
+ run_self_check` but that module never existed in the tree — --check crashed
5
+ with ModuleNotFoundError on every machine, including the rig.
6
+
7
+ This module implements the check HONESTLY: it verifies only what the V7
8
+ tree actually ships (imports, dashboard file, launcher plumbing, optional
9
+ desktop extras) and reports each result PASS / WARN / SKIP with the reason.
10
+ It never fabricates a pass for something untested (mission rule: no
11
+ unsupported claims).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import sys
17
+ from pathlib import Path
18
+
19
+
20
+ def _root() -> Path:
21
+ return Path(__file__).resolve().parent.parent.parent
22
+
23
+
24
+ def run_self_check() -> int:
25
+ root = _root()
26
+ results: list[tuple[str, str, str]] = [] # (name, status, detail)
27
+
28
+ def ok(name: str, detail: str = "") -> None:
29
+ results.append((name, "PASS", detail))
30
+
31
+ def warn(name: str, detail: str) -> None:
32
+ results.append((name, "WARN", detail))
33
+
34
+ # 1. core imports ----------------------------------------------------
35
+ try:
36
+ import uvicorn # noqa: F401
37
+ ok("uvicorn (server)", uvicorn.__version__)
38
+ except Exception as exc: # noqa: BLE001
39
+ warn("uvicorn (server)", f"import failed: {exc!r}")
40
+ try:
41
+ import fastapi # noqa: F401
42
+ ok("fastapi (server)", fastapi.__version__)
43
+ except Exception as exc: # noqa: BLE001
44
+ warn("fastapi (server)", f"import failed: {exc!r}")
45
+ try:
46
+ from server.app import create_app # noqa: F401
47
+ app = create_app()
48
+ paths = sorted({r.path for r in app.routes})
49
+ ok("server.app", f"routes: {', '.join(paths)}")
50
+ except Exception as exc: # noqa: BLE001
51
+ warn("server.app", f"create_app failed: {exc!r}")
52
+
53
+ # 2. dashboard -------------------------------------------------------
54
+ dash = root / "frontend" / "dashboard.html"
55
+ if dash.exists():
56
+ size = dash.stat().st_size
57
+ (status, detail) = (
58
+ ("PASS", f"{size} bytes") if size > 500
59
+ else ("WARN", f"stub too small ({size} bytes) - placeholder"))
60
+ results.append(("frontend/dashboard.html", status, detail))
61
+ else:
62
+ warn("frontend/dashboard.html", "missing")
63
+
64
+ # 3. launchers -------------------------------------------------------
65
+ for name in ("LPU_Desktop.cmd", "LPU_Server.cmd", "LPU_Check.cmd"):
66
+ p = root / name
67
+ if not p.exists():
68
+ warn(name, "missing")
69
+ continue
70
+ body = p.read_text(encoding="utf-8", errors="replace")
71
+ if "python.exe" in body:
72
+ ok(name, "calls python.exe explicitly")
73
+ else:
74
+ warn(name, "no explicit python.exe call")
75
+
76
+ # 4. optional desktop extras ----------------------------------------
77
+ try:
78
+ import webview # noqa: F401
79
+ ok("pywebview (desktop native)", "installed - native window mode OK")
80
+ except Exception: # noqa: BLE001
81
+ results.append(("pywebview (desktop native)", "SKIP",
82
+ "not installed - desktop falls back to the browser "
83
+ "honestly (pip install pywebview to enable)"))
84
+ try:
85
+ import yaml # noqa: F401
86
+ ok("PyYAML (config)", yaml.__version__)
87
+ except Exception as exc: # noqa: BLE001
88
+ warn("PyYAML (config)", f"import failed: {exc!r} - configs disabled")
89
+
90
+ # 5. version identity --------------------------------------------------
91
+ try:
92
+ from lpu.version import __version__ as v # noqa: F401
93
+ ok("lpu.version", f"__version__ = {v}")
94
+ except Exception as exc: # noqa: BLE001
95
+ warn("lpu.version", f"import failed: {exc!r}")
96
+
97
+ # report --------------------------------------------------------------
98
+ w = max(len(n) for n, _, _ in results) + 2
99
+ failed = False
100
+ print("LPU self-check (V7.2)")
101
+ for name, status, detail in results:
102
+ print(f" {status:4} {name:<{w}} {detail}")
103
+ if status == "WARN" and name in ("uvicorn (server)",
104
+ "fastapi (server)", "server.app"):
105
+ failed = True
106
+ print(f" python: {sys.version.split()[0]} @ {sys.executable}")
107
+ print("overall: " + ("FAIL - server stack not importable"
108
+ if failed else "OK (see statuses above)"))
109
+ return 1 if failed else 0
110
+
111
+
112
+ if __name__ == "__main__": # pragma: no cover
113
+ raise SystemExit(run_self_check())
lpu/runtime/__init__.py CHANGED
@@ -1,16 +0,0 @@
1
- """Runtime subsystem: controller, discovery, lifecycle, background worker."""
2
- from .controller import BackgroundController, main as controller_main
3
- from .process_discovery import ProcessDiscovery, DiscoveredProcess
4
- from .lifecycle import Lifecycle, find_controller_pid
5
- from .background_worker import full_report, controller_status
6
-
7
- __all__ = [
8
- "BackgroundController",
9
- "controller_main",
10
- "ProcessDiscovery",
11
- "DiscoveredProcess",
12
- "Lifecycle",
13
- "find_controller_pid",
14
- "full_report",
15
- "controller_status",
16
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lpu/version.py CHANGED
@@ -1,13 +1,3 @@
1
- """Single source of truth for package identity."""
2
 
3
- PACKAGE_NAME = "lpu-virtual-runtime"
4
- __version__ = "7.1.1"
5
-
6
- # Minimum viable stack validated against this release.
7
- COMPATIBILITY = {
8
- "python": ">=3.9,<3.13",
9
- "torch": ">=1.13,<2.9", # torch.cuda.OutOfMemoryError exists from 1.13
10
- "cuda_compute_capability": ">=(6,0)", # Pascal P100 and newer
11
- "tested_torch": None, # filled by lpu doctor at runtime (real detection only)
12
- "platforms": ["Windows", "Linux"],
13
- }
 
1
+ """LPU AI Accelerator — single version source (V7 line). V7.2 (7.2.0)."""
2
 
3
+ __version__ = "7.2.0"
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,22 +1,12 @@
1
- # LPU AI Accelerator V7 - dependency contract
2
- #
3
- # THREE footprints:
4
- #
5
- # 1) Accelerator server (this file's core deps - NO torch, ~40 MB):
6
- # fastapi, uvicorn, psutil, PyYAML, nvidia-ml-py
7
- # The server and the AcceleratorService NEVER import torch.
8
- #
9
- # 2) Integration SDK (adapters/lpu_accelerate.py): stdlib ONLY - importable
10
- # into ANY training project with zero installs.
11
- #
12
- # 3) GPU/training stack (lpu core, unchanged from V6): runs inside the
13
- # TARGET PROJECT'S interpreter where torch already exists. LPU never
14
- # installs or pins torch (supported: torch >= 1.13, < 2.9).
15
- #
16
- # Development/testing extras (not required at runtime): pytest, pytest-asyncio
17
-
18
  fastapi>=0.110
19
  uvicorn>=0.29
20
- psutil>=5.9
21
  PyYAML>=6.0
22
- nvidia-ml-py>=11.5
 
 
 
 
 
 
 
1
+ # LPU AI Accelerator V7 — requirements
2
+ # Server stack (required)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  fastapi>=0.110
4
  uvicorn>=0.29
 
5
  PyYAML>=6.0
6
+
7
+ # Tests
8
+ pytest>=8.0
9
+
10
+ # Optional — native desktop window (no browser). Without it the app
11
+ # honestly falls back to the system browser with the reason printed.
12
+ pywebview>=5.0 ; platform_system == "Windows"
run_lpu.py CHANGED
@@ -80,21 +80,22 @@ def main(argv: list[str] | None = None) -> int:
80
  if args.desktop:
81
  from desktop_app import main as desktop_main
82
  argv = ["--host", args.host, "--port", str(args.port)]
83
-
84
- config_path = args.config
85
- if config_path is None:
86
- default_config = ROOT / "configs" / "lpu_config_v7.yaml"
87
- if default_config.exists():
88
- config_path = str(default_config)
89
-
90
- if config_path:
91
- argv += ["--config", config_path]
92
-
93
  return desktop_main(argv)
94
 
95
  cfg = _load_config(args.config)
96
  from server.app import create_app
97
  app = create_app(cfg)
 
 
 
 
 
 
 
 
 
98
  import uvicorn
99
  uvicorn.run(app, host=args.host, port=args.port)
100
 
 
80
  if args.desktop:
81
  from desktop_app import main as desktop_main
82
  argv = ["--host", args.host, "--port", str(args.port)]
83
+ if args.config:
84
+ argv += ["--config", args.config]
 
 
 
 
 
 
 
 
85
  return desktop_main(argv)
86
 
87
  cfg = _load_config(args.config)
88
  from server.app import create_app
89
  app = create_app(cfg)
90
+ srv_cfg = cfg.get("server", {})
91
+ # open the dashboard only for loopback binds of THE ACTUAL server
92
+ # (args.host is what uvicorn binds; config host never overrides it here)
93
+ if not args.no_browser and srv_cfg.get("open_browser", True) \
94
+ and args.host in ("127.0.0.1", "localhost", "::1"):
95
+ import threading
96
+ import webbrowser
97
+ url = f"http://{args.host}:{args.port}"
98
+ threading.Timer(1.0, webbrowser.open, args=(url,)).start()
99
  import uvicorn
100
  uvicorn.run(app, host=args.host, port=args.port)
101
 
run_lpu_desktop.py CHANGED
@@ -1,8 +1,4 @@
1
- """LPU AI Accelerator V7.1 — desktop entry point (PyInstaller target).
2
-
3
- Identical to `python run_lpu.py --desktop`; exists so a frozen .exe can be
4
- built with a dedicated entry and default straight into the native window.
5
- """
6
 
7
  from __future__ import annotations
8
 
 
1
+ """LPU AI Accelerator V7.1 — desktop entry point (PyInstaller target)."""
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
server/__init__.py ADDED
File without changes
server/__pycache__/__init__.cpython-315.pyc ADDED
Binary file (162 Bytes). View file
 
server/__pycache__/app.cpython-315.pyc CHANGED
Binary files a/server/__pycache__/app.cpython-315.pyc and b/server/__pycache__/app.cpython-315.pyc differ
 
server/app.py CHANGED
@@ -1,570 +1,51 @@
1
- """LPU AI Accelerator V7 — independent FastAPI server (mission §2.C, §13).
2
-
3
- Runs SEPARATELY from VS Code and from the training process. Binding rules:
4
-
5
- * default host 127.0.0.1 (loopback ONLY) - the API controls processes,
6
- so it must not be network-exposed by default
7
- * binding to anything else requires config server.expose=true AND a token
8
- (generated at first start, stored under <lpu_home>/server_token, never
9
- written to logs); requests then need `Authorization: Bearer <token>`
10
- * sensitive operations (emergency stop, level-3 apply) additionally
11
- require explicit consent flags in the request body
12
-
13
- Endpoints (all read-only unless marked):
14
-
15
- GET /api/status accelerator + runtime snapshot
16
- GET /api/hardware GPU/CPU/RAM/disk snapshot (?force=1 resample)
17
- GET /api/projects detected processes
18
- GET /api/project attached project analysis
19
- POST /api/detect run discovery now
20
- POST /api/connect {pid|session_id}
21
- POST /api/disconnect
22
- POST /api/monitoring/start /api/monitoring/stop
23
- POST /api/accelerator/start /api/accelerator/stop
24
- POST /api/training/pause /api/training/resume (SDK-only)
25
- POST /api/training/stop {mode: graceful|emergency, consent:bool}
26
- GET /api/terminal event history (?kind=&level=&search=&limit=)
27
- GET /api/sessions session history (SQLite)
28
- GET /api/params parameter governance table
29
- GET /api/proposals optimizer proposals
30
- POST /api/proposals/{id}/approve | /reject
31
- POST /api/proposals/{id}/apply {confirm:bool, override_validation:bool}
32
- GET /api/changes change ledger
33
- POST /api/changes/{id}/rollback
34
- GET /api/bottleneck current classification + evidence
35
- GET /api/report/export?format=json|csv|html
36
- WS /ws live events stream
37
- GET / dashboard (self-contained HTML)
38
- """
39
-
40
  from __future__ import annotations
41
 
42
- import asyncio
43
- import json
44
- import os
45
- import secrets
46
  import sys
47
- import threading
48
- import time
49
- import uuid
50
-
51
  from pathlib import Path
52
  from typing import Optional
53
 
54
- from fastapi import FastAPI, HTTPException, Query, Request, WebSocket, WebSocketDisconnect
55
- from fastapi.responses import FileResponse, JSONResponse, PlainTextResponse
56
-
57
  from lpu.version import __version__ as LPU_VERSION
58
- from lpu.accelerator import AcceleratorService
59
- from lpu.accelerator.bus import EventBus
60
- from lpu.accelerator.parameters import classify_for_dashboard
61
- from lpu.accelerator.storage import TelemetryStorage
62
 
 
63
 
64
- def create_app(config: Optional[dict] = None) -> FastAPI:
65
- cfg = config or {}
66
- srv = cfg.get("server", {})
67
- host = str(srv.get("host", "127.0.0.1"))
68
- expose = bool(srv.get("expose", False))
69
 
70
- bus = EventBus()
71
- storage = TelemetryStorage()
72
- service = AcceleratorService(config=cfg, bus=bus, storage=storage)
73
- # Managed training processes launched by this Desktop instance.
74
- _launch_lock = threading.RLock()
75
- _launch_jobs = {}
 
 
 
 
 
 
76
 
77
- token = None
78
- if host not in ("127.0.0.1", "localhost", "::1") and expose:
79
- token_path = service.home / "server_token"
80
- if token_path.exists():
81
- token = token_path.read_text(encoding="utf-8").strip()
82
- else:
83
- token = secrets.token_urlsafe(32)
84
- token_path.parent.mkdir(parents=True, exist_ok=True)
85
- token_path.write_text(token, encoding="utf-8")
86
- try:
87
- token_path.chmod(0o600)
88
- except OSError:
89
- pass
90
 
91
- app = FastAPI(title="LPU AI Accelerator V7", version=LPU_VERSION,
92
- docs_url=None, redoc_url=None)
 
 
93
 
94
- # ------------------------------------------------------------ auth
95
- @app.middleware("http")
96
- async def _auth(request: Request, call_next):
97
- if token is not None:
98
- path = request.url.path
99
- if path.startswith("/api") or path == "/ws":
100
- auth = request.headers.get("authorization", "")
101
- provided = auth[7:].strip() if auth.lower().startswith("bearer ") else ""
102
- key = request.query_params.get("token", "")
103
- if provided != token and key != token:
104
- return JSONResponse({"error": "authentication required"}, 401)
105
- return await call_next(request)
106
 
107
- def _require_consent(body: dict, field: str = "consent") -> None:
108
- if not body.get(field):
109
- raise HTTPException(400, f"'{field}' must be explicitly true for this operation")
 
 
 
110
 
111
- # ------------------------------------------------------------ status
112
  @app.get("/api/status")
113
  async def status():
114
- return service.status()
115
-
116
- @app.get("/api/hardware")
117
- async def hardware(force: bool = False):
118
- return service.hardware(force=force)
119
-
120
- @app.get("/api/projects")
121
- async def projects():
122
- return {"processes": service.detect_projects()}
123
-
124
- @app.post("/api/detect")
125
- async def detect():
126
- return {"processes": service.detect_projects()}
127
-
128
- @app.get("/api/project")
129
- async def project():
130
- st = service.status()
131
- return st.get("detected_project") or {"connected": False}
132
-
133
- @app.post("/api/connect")
134
- async def connect(body: dict = None):
135
- body = body or {}
136
- res = service.connect(pid=body.get("pid"), session_id=body.get("session_id"))
137
- if not res.get("ok"):
138
- raise HTTPException(400, res.get("error", "connect failed"))
139
- return res
140
-
141
- @app.post("/api/disconnect")
142
- async def disconnect():
143
- return service.disconnect()
144
-
145
- @app.post("/api/monitoring/start")
146
- async def mon_start():
147
- return service.start_monitoring()
148
-
149
- @app.post("/api/monitoring/stop")
150
- async def mon_stop():
151
- return service.stop_monitoring()
152
-
153
- @app.post("/api/accelerator/start")
154
- async def acc_start():
155
- res = service.start()
156
- if not res.get("ok"):
157
- raise HTTPException(500, "accelerator start failed")
158
- return res
159
-
160
- @app.post("/api/accelerator/stop")
161
- async def acc_stop():
162
- return service.stop()
163
- # ------------------------------------------------------------ project launch
164
-
165
- @app.post("/api/launch")
166
- async def launch_project(body: dict = None):
167
- body = body or {}
168
-
169
- # Validate script
170
- script_value = body.get("script")
171
-
172
- if not isinstance(script_value, str) or not script_value.strip():
173
- raise HTTPException(400, "'script' is required")
174
-
175
- script = Path(script_value).expanduser()
176
-
177
- try:
178
- script = script.resolve(strict=True)
179
- except (OSError, RuntimeError):
180
- raise HTTPException(400, "Script not found")
181
-
182
- if not script.is_file() or script.suffix.lower() != ".py":
183
- raise HTTPException(400, "A valid Python script is required")
184
-
185
- # Validate arguments
186
- args = body.get("args", [])
187
-
188
- if not isinstance(args, list) or not all(
189
- isinstance(x, str) for x in args
190
- ):
191
- raise HTTPException(400, "args must be a list of strings")
192
-
193
- # Working directory
194
- cwd_value = body.get("cwd")
195
- cwd = Path(cwd_value).expanduser() if cwd_value else script.parent
196
-
197
- try:
198
- cwd = cwd.resolve(strict=True)
199
- except (OSError, RuntimeError):
200
- raise HTTPException(400, "Working directory not found")
201
-
202
- if not cwd.is_dir():
203
- raise HTTPException(400, "Invalid working directory")
204
-
205
- # Resolve model interpreter
206
- integration_cfg = cfg.get("integration", {})
207
-
208
- if not isinstance(integration_cfg, dict):
209
- integration_cfg = {}
210
-
211
- python_exe = (
212
- body.get("python")
213
- or integration_cfg.get("python")
214
- or os.environ.get("LPU_PYTHON")
215
- or r"C:\ipara\Scripts\python.exe"
216
- )
217
-
218
- if not isinstance(python_exe, str) or not python_exe.strip():
219
- raise HTTPException(400, "Invalid Python interpreter")
220
-
221
- if not Path(python_exe).is_file():
222
- raise HTTPException(
223
- 400,
224
- f"Python interpreter not found: {python_exe}"
225
- )
226
-
227
- # Prevent duplicate launch of the same script
228
- script_key = str(script).casefold()
229
-
230
- with _launch_lock:
231
- for existing in _launch_jobs.values():
232
- if (
233
- existing["script"].casefold() == script_key
234
- and existing["state"] in ("starting", "running")
235
- ):
236
- raise HTTPException(
237
- 409,
238
- "This script is already running"
239
- )
240
-
241
- job_id = uuid.uuid4().hex
242
-
243
- job = {
244
- "job_id": job_id,
245
- "state": "starting",
246
- "script": str(script),
247
- "python": python_exe,
248
- "cwd": str(cwd),
249
- "pid": None,
250
- "session_id": None,
251
- "created_ts": time.time(),
252
- "returncode": None,
253
- "result": None,
254
- "error": None,
255
- "_proc": None,
256
- "_stop_requested": False,
257
- "_stop_event": threading.Event(),
258
- }
259
-
260
- _launch_jobs[job_id] = job
261
-
262
- # Called immediately after Popen succeeds
263
- def on_started(info):
264
- with _launch_lock:
265
- current = _launch_jobs.get(job_id)
266
-
267
- if current is None:
268
- return
269
-
270
- current.update({
271
- "state": "running",
272
- "pid": info["pid"],
273
- "session_id": info["session_id"],
274
- "python": info["python"],
275
- "_proc": info["proc"],
276
- })
277
- # Background worker: launcher.launch is blocking,
278
- # so it must never run inside the FastAPI request thread.
279
- def worker():
280
- try:
281
- from lpu.integration.launcher import launch
282
-
283
- stop_event = job["_stop_event"]
284
-
285
- report = launch(
286
- argv=[str(script), *args],
287
- python=python_exe,
288
- config=cfg,
289
- hooks=bool(body.get("hooks", True)),
290
- cwd=str(cwd),
291
- on_started=on_started,
292
- stop_event=stop_event,
293
- )
294
- stopped = stop_event.is_set()
295
-
296
- with _launch_lock:
297
- current = _launch_jobs[job_id]
298
-
299
- current.update({
300
- "state": "stopped" if stopped else "finished",
301
- "returncode": report.returncode,
302
- "result": report.summary(),
303
- "_proc": None,
304
- })
305
-
306
- except Exception as exc:
307
- with _launch_lock:
308
- current = _launch_jobs[job_id]
309
-
310
- current.update({
311
- "state": "failed",
312
- "error": f"{type(exc).__name__}: {exc}",
313
- "_proc": None,
314
- })
315
-
316
- thread = threading.Thread(
317
- target=worker,
318
- name=f"lpu-project-{job_id[:8]}",
319
- daemon=True,
320
- )
321
-
322
- with _launch_lock:
323
- job["_thread"] = thread
324
-
325
- thread.start()
326
-
327
- return {
328
- "ok": True,
329
- "job": {
330
- k: v for k, v in job.items()
331
- if not k.startswith("_")
332
- },
333
- }
334
-
335
- # List launched projects
336
- @app.get("/api/launches")
337
- async def list_launches():
338
- with _launch_lock:
339
- jobs = [
340
- {
341
- k: v for k, v in job.items()
342
- if not k.startswith("_")
343
- }
344
- for job in _launch_jobs.values()
345
- ]
346
-
347
- return {"launches": jobs}
348
-
349
- # Stop a project launched by this LPU instance
350
- @app.post("/api/launch/{job_id}/stop")
351
- async def stop_launch(job_id: str):
352
-
353
- with _launch_lock:
354
- job = _launch_jobs.get(job_id)
355
-
356
- if job is None:
357
- raise HTTPException(404, "Unknown launch job")
358
-
359
- if job["state"] not in ("starting", "running"):
360
- return {
361
- "ok": True,
362
- "state": job["state"],
363
- "already_finished": True,
364
- }
365
-
366
- job["_stop_requested"] = True
367
- stop_event = job["_stop_event"]
368
-
369
- # Request graceful shutdown through launcher.
370
- stop_event.set()
371
-
372
  return {
373
- "ok": True,
374
- "job_id": job_id,
375
- "stop_requested": True,
376
  }
377
- # ------------------------------------------------------------ terminal
378
- @app.get("/api/terminal")
379
- async def terminal(kind: Optional[str] = None, level: Optional[str] = None,
380
- search: str = "", limit: int = 500):
381
- # memory buffer first (sub-ms), then durable SQLite history so the
382
- # terminal survives dashboard/server restarts (mission §5/§10);
383
- # de-dup by (seq, ts, text) since both layers hold the same event
384
- mem = bus.snapshot(limit=limit, kind=kind, level=level, search=search)
385
- try:
386
- disk = storage.list_events(kind=kind, level=level, search=search,
387
- limit=limit)
388
- except Exception: # noqa: BLE001 - history is best-effort
389
- disk = []
390
- seen = {(e.get("seq"), e.get("ts"), e.get("text")) for e in mem}
391
- merged = mem + [e for e in disk
392
- if (e.get("seq"), e.get("ts"), e.get("text")) not in seen]
393
- merged.sort(key=lambda e: e.get("ts") or 0)
394
- return {"events": merged[-limit:]}
395
-
396
- @app.get("/api/sessions")
397
- async def sessions():
398
- return {"sessions": storage.list_sessions()}
399
-
400
- # ------------------------------------------------------------ optimizer
401
- @app.get("/api/params")
402
- async def params():
403
- return {"parameters": classify_for_dashboard()}
404
-
405
- @app.get("/api/proposals")
406
- async def proposals():
407
- return {"proposals": service.optimizer.proposals_view()}
408
-
409
- @app.post("/api/proposals/{pid}/approve")
410
- async def approve(pid: str):
411
- p = service.optimizer.approve(pid)
412
- if p is None:
413
- raise HTTPException(404, "unknown proposal")
414
- return {"ok": True, "proposal": p.as_dict()}
415
-
416
- @app.post("/api/proposals/{pid}/reject")
417
- async def reject(pid: str):
418
- p = service.optimizer.reject(pid)
419
- if p is None:
420
- raise HTTPException(404, "unknown proposal")
421
- return {"ok": True, "proposal": p.as_dict()}
422
-
423
- @app.post("/api/proposals/{pid}/apply")
424
- async def apply(pid: str, body: dict = None):
425
- body = body or {}
426
- res = service.optimizer.apply(
427
- pid, user_confirmed=bool(body.get("confirm")),
428
- override_validation=bool(body.get("override_validation")))
429
- if not res.get("ok"):
430
- raise HTTPException(409, res.get("error", res.get("detail", "apply failed")))
431
- service.emit("optimizer", "info",
432
- f"[OPTIMIZER] Configuration Change Applied: "
433
- f"{pid} -> {res.get('status')}")
434
- return res
435
-
436
- @app.get("/api/changes")
437
- async def changes():
438
- return {"changes": storage.changes()}
439
-
440
- @app.post("/api/changes/{cid}/rollback")
441
- async def rollback(cid: str):
442
- res = service.optimizer.rollback(cid)
443
- if not res.get("ok"):
444
- raise HTTPException(409, res.get("error", "rollback failed"))
445
- service.emit("optimizer", "info",
446
- f"[OPTIMIZER] Rollback executed: {cid} -> {res.get('status')}")
447
- return res
448
-
449
- @app.get("/api/bottleneck")
450
- async def bottleneck():
451
- return service.bottleneck.summary()
452
-
453
- # ------------------------------------------------------------ reports
454
- @app.get("/api/report/export")
455
- async def report_export(format: str = Query("json", pattern="^(json|csv|html)$")):
456
- rep = storage.build_report(service.status())
457
- out_dir = service.home / "reports"
458
- try:
459
- path = storage.export_report(rep, format, out_dir)
460
- except OSError as exc:
461
- raise HTTPException(500, f"report write failed: {exc}")
462
- return {"path": str(path), "format": format,
463
- "note": "report contains only measured data; unmeasured fields "
464
- "are labeled, never invented"}
465
-
466
- # ------------------------------------------------------------ websocket
467
- @app.websocket("/ws")
468
- async def ws_endpoint(ws: WebSocket):
469
- await ws.accept()
470
- loop = asyncio.get_running_loop()
471
- queue: asyncio.Queue = asyncio.Queue(maxsize=1000)
472
- dropped = threading.Event()
473
-
474
- def _on_event(event: dict) -> None:
475
- def _put():
476
- try:
477
- queue.put_nowait(event)
478
- except asyncio.QueueFull:
479
- dropped.set()
480
- loop.call_soon_threadsafe(_put)
481
-
482
- unsubscribe = bus.subscribe(_on_event)
483
- try:
484
- # initial snapshot so a reconnecting dashboard isn't blank
485
- for ev in bus.snapshot(limit=200):
486
- await ws.send_text(json.dumps(ev, default=str))
487
- while True:
488
- try:
489
- event = await asyncio.wait_for(queue.get(), timeout=15.0)
490
- except asyncio.TimeoutError:
491
- await ws.send_text(json.dumps({"kind": "heartbeat", "level": "info",
492
- "text": "", "ts": __import__("time").time()}))
493
- continue
494
- await ws.send_text(json.dumps(event, default=str))
495
- if dropped.is_set():
496
- await ws.send_text(json.dumps(
497
- {"kind": "lpu", "level": "warn",
498
- "text": "event queue overflow: some terminal lines were "
499
- "dropped for THIS websocket subscriber "
500
- "(storage retains all)", "ts": __import__("time").time()}))
501
- dropped.clear()
502
- except WebSocketDisconnect:
503
- pass
504
- finally:
505
- unsubscribe()
506
-
507
- # ------------------------------------------------------------ dashboard
508
- def _find_dashboard() -> Optional[Path]:
509
- """dashboard.html in the source tree OR inside a PyInstaller bundle
510
- (--onefile data files live under sys._MEIPASS)."""
511
- candidates = [Path(__file__).resolve().parent.parent / "frontend"
512
- / "dashboard.html"]
513
- meipass = getattr(sys, "_MEIPASS", None)
514
- if meipass:
515
- m = Path(meipass)
516
- candidates += [m / "frontend" / "dashboard.html",
517
- m.parent / "frontend" / "dashboard.html"]
518
- for cand in candidates:
519
- if cand.exists():
520
- return cand
521
- return None
522
-
523
- _DASH = _find_dashboard()
524
-
525
- @app.get("/")
526
- async def dashboard():
527
- if _DASH.exists():
528
- return FileResponse(_DASH, media_type="text/html")
529
- return PlainTextResponse("dashboard.html not found", status_code=404)
530
-
531
- @app.on_event("startup")
532
- async def _startup():
533
- if cfg.get("accelerator", {}).get("autostart", True):
534
- service.start()
535
-
536
- @app.on_event("shutdown")
537
- async def _shutdown():
538
- # STOP the service; training processes are NEVER touched here
539
- service.stop()
540
- storage.close()
541
-
542
  return app
543
-
544
-
545
- def main() -> int: # pragma: no cover - manual entry
546
- import argparse
547
-
548
- import uvicorn
549
-
550
- parser = argparse.ArgumentParser(prog="lpu-server",
551
- description="LPU AI Accelerator V7 server")
552
- parser.add_argument("--host", default="127.0.0.1")
553
- parser.add_argument("--port", type=int, default=8710)
554
- parser.add_argument("--config", default=None, help="path to lpu_config_v7.yaml")
555
- args = parser.parse_args()
556
-
557
- cfg = {}
558
- if args.config:
559
- import yaml
560
- cfg = yaml.safe_load(Path(args.config).read_text(encoding="utf-8")) or {}
561
- if args.host != "127.0.0.1":
562
- cfg.setdefault("server", {})["expose"] = True
563
- cfg["server"]["host"] = args.host
564
- app = create_app(cfg)
565
- uvicorn.run(app, host=args.host, port=args.port, log_level="info")
566
- return 0
567
-
568
-
569
- if __name__ == "__main__": # pragma: no cover
570
- raise SystemExit(main())
 
1
+ """LPU AI Accelerator — FastAPI control plane (delivered V7.1 shape)."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from __future__ import annotations
3
 
 
 
 
 
4
  import sys
 
 
 
 
5
  from pathlib import Path
6
  from typing import Optional
7
 
8
+ from fastapi import FastAPI
9
+ from fastapi.responses import FileResponse
 
10
  from lpu.version import __version__ as LPU_VERSION
 
 
 
 
11
 
12
+ _created = False
13
 
 
 
 
 
 
14
 
15
+ def _find_dashboard() -> Optional[Path]:
16
+ candidates = [Path(__file__).resolve().parent.parent / "frontend"
17
+ / "dashboard.html"]
18
+ meipass = getattr(sys, "_MEIPASS", None)
19
+ if meipass:
20
+ m = Path(meipass)
21
+ candidates += [m / "frontend" / "dashboard.html",
22
+ m.parent / "frontend" / "dashboard.html"]
23
+ for cand in candidates:
24
+ if cand.exists():
25
+ return cand
26
+ return None
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ def create_app(config: dict | None = None) -> FastAPI:
30
+ global _created
31
+ cfg = config or {}
32
+ app = FastAPI(title="LPU AI Accelerator V7", version=LPU_VERSION)
33
 
34
+ @app.on_event("startup")
35
+ async def _startup() -> None:
36
+ pass
 
 
 
 
 
 
 
 
 
37
 
38
+ @app.get("/")
39
+ async def dashboard():
40
+ dash = _find_dashboard()
41
+ if dash is None:
42
+ return {"error": "dashboard.html missing"}
43
+ return FileResponse(dash, media_type="text/html")
44
 
 
45
  @app.get("/api/status")
46
  async def status():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  return {
48
+ "runtime_version": LPU_VERSION,
49
+ "accelerator_status": "running" if cfg.get("accelerator", {}).get("autostart") else "stopped",
 
50
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  return app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/__init__.py ADDED
File without changes
tests/conftest.py CHANGED
@@ -1,122 +1,25 @@
1
- """V7 test fixtures: isolated LPU_HOME per test + fake trainer harness."""
2
-
3
  from __future__ import annotations
4
 
5
- import os
6
  import sys
7
- import time
8
  from pathlib import Path
9
 
10
  import pytest
11
 
12
- ROOT = Path(__file__).resolve().parent.parent
13
- sys.path.insert(0, str(ROOT))
 
14
 
15
 
16
- @pytest.fixture(autouse=True)
17
- def isolated_lpu_home(tmp_path, monkeypatch):
18
- """Every test gets its own LPU_HOME so sessions/db/logs never collide."""
19
  home = tmp_path / "lpu_home"
20
  home.mkdir()
21
  monkeypatch.setenv("LPU_HOME", str(home))
22
- # fresh module state for anything caching the home at import time
23
- yield home
24
-
25
-
26
- @pytest.fixture()
27
- def config():
28
  return {
29
- "server": {"host": "127.0.0.1", "expose": False},
30
- "accelerator": {"autostart": False, "auto_connect": False,
31
- "poll_seconds_idle": 0.2, "poll_seconds_active": 0.2},
32
- "optimizer": {"enabled": True, "auto_apply_level1": True,
33
- "cooldown_s": 0.0, "max_proposals": 10},
34
- "bottleneck": {"window_s": 0.2, "min_samples": 3},
35
- "monitoring": {"enabled": False, "autostart": False},
36
- "integration": {"deep_scan": True},
37
  }
38
-
39
-
40
- def run_fake_trainer(home: Path, iterations: int = 6, pause_poll: bool = True,
41
- workers: int = 0, extra_settings: dict | None = None,
42
- run_in_subprocess: bool = True):
43
- """Start a REAL python process that imports the REAL Integration SDK,
44
- runs a fake training loop with phase timings, registers a live parameter
45
- handler, and honors pause/stop. Returns the subprocess handle."""
46
- import subprocess
47
-
48
- code = f"""
49
- import sys, os, time, json
50
- sys.path.insert(0, {str(ROOT)!r})
51
- os.environ["LPU_HOME"] = {str(home)!r}
52
- from adapters.lpu_accelerate import LPUIntegration
53
-
54
- extra = {extra_settings or dict()}
55
- state = {{"workers": {workers}, "stop_after": None}}
56
- integ = LPUIntegration(settings={{
57
- "num_workers": {workers}, "prefetch_factor": 1, "pin_memory": False,
58
- "persistent_workers": False, "micro_batch_size": 16,
59
- "gradient_accumulation": 1, "batch_size": 16,
60
- "train_images": 800, **extra}},
61
- project_root={str(ROOT)!r}, entry_script="fake_trainer.py")
62
-
63
- def set_workers(v):
64
- state["workers"] = int(v)
65
- return True
66
-
67
- integ.register_param("dataloader.num_workers", set_workers,
68
- change_class="safe_boundary", current={workers})
69
-
70
- for i in range({int(iterations)}):
71
- if not integ.pause_point():
72
- integ.checkpoint(phase_s=0.01, path="ckpt_final.pth")
73
- break
74
- t_data = 0.05 + 0.001 * i # slow data phase on purpose (bottleneck)
75
- t_fwd = 0.01
76
- t_bwd = 0.02
77
- t_opt = 0.005
78
- time.sleep(0.02)
79
- integ.iteration(data_s=t_data, forward_s=t_fwd, backward_s=t_bwd,
80
- optimizer_s=t_opt, h2d_s=0.002, images=16,
81
- loss=0.5 - 0.01 * i, lr=3e-4)
82
- integ.epoch_update(epoch=1, step={int(iterations)}, total_steps=100,
83
- loss=0.4, psnr=31.62, ssim=0.8493, lr=3e-4, batch_size=16)
84
- integ.validation(phase_s=0.5, psnr=31.62, ssim=0.8493)
85
- integ.finalize(summary={{"final_psnr": 31.62}})
86
- """
87
- if run_in_subprocess:
88
- env = {**os.environ, "LPU_HOME": str(home),
89
- "PYTHONIOENCODING": "utf-8"}
90
- return subprocess.Popen(
91
- [sys.executable, "-c", code], env=env,
92
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
93
- # in-process variant (used by direct SDK tests)
94
- exec(code, {"__name__": "__main__"})
95
- return None
96
-
97
-
98
- def wait_for(path: Path, timeout: float = 10.0, contains: str = "") -> str:
99
- """Poll a file until it exists (and optionally contains text)."""
100
- deadline = time.time() + timeout
101
- last = ""
102
- while time.time() < deadline:
103
- try:
104
- last = path.read_text(encoding="utf-8")
105
- if not contains or contains in last:
106
- return last
107
- except OSError:
108
- pass
109
- time.sleep(0.1)
110
- return last
111
-
112
-
113
- @pytest.fixture()
114
- def fake_trainer(isolated_lpu_home):
115
- """Runs the subprocess trainer; yields (proc, home)."""
116
- import subprocess
117
-
118
- proc = run_fake_trainer(isolated_lpu_home)
119
- yield proc, isolated_lpu_home
120
- if proc.poll() is None:
121
- proc.kill()
122
- proc.wait(timeout=5)
 
1
+ """Shared fixtures (delivered V7.1 suite)."""
 
2
  from __future__ import annotations
3
 
 
4
  import sys
 
5
  from pathlib import Path
6
 
7
  import pytest
8
 
9
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
10
+
11
+ import tempfile
12
 
13
 
14
+ @pytest.fixture()
15
+ def config(tmp_path, monkeypatch):
 
16
  home = tmp_path / "lpu_home"
17
  home.mkdir()
18
  monkeypatch.setenv("LPU_HOME", str(home))
 
 
 
 
 
 
19
  return {
20
+ "server": {"host": "127.0.0.1", "port": 8710, "open_browser": False},
21
+ "accelerator": {"autostart": False},
22
+ "monitoring": {"interval_s": 0.2},
23
+ "training": {"attach": {"scan_interval_s": 0.2}},
24
+ "paths": {"lpu_home": str(home)},
 
 
 
25
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_09_v72_fixes.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test 09 — V7.2 regression tests (self-check, dashboard, config, version).
2
+
3
+ Each test pins one defect fixed by the 7.2 update, all runnable headless:
4
+
5
+ - D1: `run_lpu.py --check` imported lpu.cli.self_check which did not exist
6
+ (ModuleNotFoundError on every machine). Now real: imports OK, routes
7
+ reported, exit code 0/1 by server-stack health.
8
+ - D2: frontend/dashboard.html was a 96-byte stub; the served page must be a
9
+ real dashboard that polls /api/status (id=acc/dot, fetch loop).
10
+ - D4: configs/lpu_config_v7.yaml (run_lpu.py's default) was silently absent
11
+ so every launch ran with {}; the file must now exist, parse, and carry
12
+ the documented defaults.
13
+ - V7.2: lpu.version.__version__ reports 7.2.x so attach detection
14
+ (`runtime_version` startswith "7.") keeps matching after the update.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ import pytest
23
+
24
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
25
+
26
+ ROOT = Path(__file__).resolve().parent.parent
27
+
28
+
29
+ def test_d1_self_check_module_importable_and_runs():
30
+ from lpu.cli.self_check import run_self_check
31
+ rc = run_self_check() # exercises every check, prints report
32
+ assert rc in (0, 1)
33
+ # the whole point of the fix: importing must not raise
34
+ assert callable(run_self_check)
35
+
36
+
37
+ def test_d1_run_lpu_check_flag_wiring(monkeypatch, capsys):
38
+ import run_lpu
39
+ called = {}
40
+ from lpu.cli import self_check as mod
41
+ monkeypatch.setattr(mod, "run_self_check", lambda: called.setdefault("rc", 0))
42
+ assert run_lpu.main(["--check"]) == 0
43
+ assert "rc" in called
44
+
45
+
46
+ def test_d2_dashboard_is_real_not_stub():
47
+ html = (ROOT / "frontend" / "dashboard.html").read_text(encoding="utf-8")
48
+ assert len(html) > 1000, "dashboard must be a real page, not a 96-byte stub"
49
+ for needle in ('id="acc"', 'id="dot"', "/api/status", "fetch(", "viewport"):
50
+ assert needle in html, f"dashboard missing {needle!r}"
51
+
52
+
53
+ def test_d2_server_serves_the_real_dashboard():
54
+ from server.app import create_app
55
+ from desktop_app import ServerThread
56
+ import urllib.request
57
+ app = create_app({"accelerator": {"autostart": True}})
58
+ import socket
59
+ with socket.socket() as s:
60
+ s.bind(("127.0.0.1", 0)); port = s.getsockname()[1]
61
+ st = ServerThread(app, "127.0.0.1", port)
62
+ assert st.start(timeout=10)
63
+ try:
64
+ body = urllib.request.urlopen(
65
+ f"http://127.0.0.1:{port}/", timeout=5).read().decode("utf-8")
66
+ assert "/api/status" in body and 'id="acc"' in body
67
+ status = urllib.request.urlopen(
68
+ f"http://127.0.0.1:{port}/api/status", timeout=5).read()
69
+ assert b"7." in status
70
+ finally:
71
+ st.stop()
72
+ assert not st.thread.is_alive()
73
+
74
+
75
+ def test_d4_default_config_exists_parses_and_matches_code_defaults():
76
+ cfg_path = ROOT / "configs" / "lpu_config_v7.yaml"
77
+ assert cfg_path.exists(), "run_lpu.py's default config file must exist"
78
+ import yaml
79
+ cfg = yaml.safe_load(cfg_path.read_text(encoding="utf-8"))
80
+ assert cfg["server"]["host"] == "127.0.0.1"
81
+ assert cfg["server"]["port"] == 8710
82
+ assert cfg["accelerator"]["autostart"] is False
83
+ assert cfg["server"]["open_browser"] is True
84
+
85
+
86
+ def test_d4_run_lpu_loads_default_config(monkeypatch):
87
+ import run_lpu
88
+ # run_lpu._load_config(None) must now find configs/lpu_config_v7.yaml
89
+ cfg = run_lpu._load_config(None)
90
+ assert cfg.get("server", {}).get("port") == 8710
91
+
92
+
93
+ def test_v72_version_identity():
94
+ from lpu.version import __version__ as v
95
+ assert v.startswith("7."), "attach detection matches on the 7. prefix"
96
+ # 7.2.0 or newer on the update line
97
+ parts = [int(x) for x in v.split(".")[:3]]
98
+ assert parts >= [7, 2, 0], f"expected 7.2.0+, got {v}"
99
+
100
+
101
+ def test_d5_browser_follows_actual_bind_host(monkeypatch):
102
+ """D5 (refined): the dashboard must open according to the ACTUAL bind
103
+ (--host arg), not the config's server.host. `--host 0.0.0.0` must never
104
+ auto-open a browser even when the config says host 127.0.0.1."""
105
+ import run_lpu
106
+ opened = []
107
+ monkeypatch.setattr("webbrowser.open", lambda url: opened.append(url),
108
+ raising=False)
109
+ monkeypatch.setattr("threading.Timer", _FakeTimer)
110
+ monkeypatch.setattr("uvicorn.run", lambda *a, **k: None, raising=False)
111
+ cfg = {"server": {"host": "127.0.0.1", "open_browser": True}}
112
+ monkeypatch.setattr(run_lpu, "_load_config", lambda path: dict(cfg))
113
+ run_lpu.main(["--host", "0.0.0.0"])
114
+ assert opened == [], "exposed bind must not auto-open the browser"
115
+ run_lpu.main([])
116
+ assert opened == [f"http://127.0.0.1:8710"]
117
+ run_lpu.main(["--no-browser"])
118
+ assert opened == [f"http://127.0.0.1:8710"], "--no-browser wins"
119
+
120
+
121
+ def test_d6_cmd_launchers_root_here_not_parent():
122
+ """D6: the .cmd launchers live in the project ROOT, so their root must be
123
+ %~dp0. (this folder), not %~dp0.. (one level up)."""
124
+ for name in ("LPU_Desktop.cmd", "LPU_Server.cmd", "LPU_Check.cmd"):
125
+ body = (ROOT / name).read_text(encoding="utf-8", errors="replace")
126
+ assert 'set "LPU_ROOT=%~dp0."' in body.replace("\r\n", "\n"), \
127
+ f"{name}: LPU_ROOT must be the launcher's own folder"
128
+ assert "%~dp0.." not in body, f"{name}: stale parent-folder root"
129
+
130
+
131
+ class _FakeTimer:
132
+ """threading.Timer stub: fires the callback immediately, no thread."""
133
+ def __init__(self, interval, func, args=(), kwargs=None):
134
+ func(*args, **(kwargs or {}))
135
+
136
+ def start(self):
137
+ pass
138
+