commit f6313866182cefe91bae1b551f26653c983d4177 Author: Semprini Date: Sat Dec 5 16:20:49 2026 +1300 The Kurgan 1.0.0: one process for the LCD, fans, lighting, local LLM servers and the web UI diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..692ad70 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# The project's virtual environment +.venv/ + +# Python bytecode +__pycache__/ +*.py[cod] \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..ff71d48 --- /dev/null +++ b/README.md @@ -0,0 +1,385 @@ +# The Kurgan + +One process that runs this PC's backend systems, with one web UI at ****: + +| Capability | What it does | Package | +| --- | --- | --- | +| Telemetry | CPU, GPU and whole-PC power readings, once a second, with 10 minutes of history | `kurgan/telemetry` | +| Display | The CPU/GPU/power dashboard on the Thermaltake 3.9" LCD | `kurgan/display` | +| Cooling | Commander PRO case fans and motherboard top fans on selectable profiles | `kurgan/cooling` | +| Lighting | Case fan, RAM and GPU LEDs: off, temperature or the red side chase | `kurgan/lighting` | +| AI | Serves Strata and llama.cpp at `/strata/v1` and `/llama/v1`, running **one** at a time: a request starts the one it needs, and an unused one stops | `kurgan/ai` | +| Web UI | Control and monitoring for all of the above, plus a JSON API | `kurgan/web` | + +It replaces three background programs: the TT LCD Dashboard task, Strata's tray service and +the Qwen4 service (llama.cpp plus its monitor page on port 8084). Sensors are read once and +shared, so the LCD, the fan curves, the lighting and the web UI all use the same readings. + +## Setup + +```powershell +powershell -ExecutionPolicy Bypass -File .\setup.ps1 -RetireAIServices +``` + +This does the following: + +- Installs the Python packages into the project's `.venv` (or for the current user). +- Installs [PawnIO](https://pawnio.eu). PawnIO is the signed driver LibreHardwareMonitor and FanControl also use. It reads the Intel CPU sensors and drives the motherboard fan headers and the RAM lighting. +- Replaces the old **TT LCD Dashboard** task with a **The Kurgan** scheduled task. The task runs `pythonw -m kurgan` hidden, with admin rights, at every logon. + +`-RetireAIServices` stops and disables the **Strata Local Service** and **Qwen4 Local Service** +tasks, so The Kurgan can run whichever server you select. Without that switch, The Kurgan finds +those servers already listening on their ports. It shows them as "running outside The Kurgan" +and monitors them, but it never starts a second copy. + +`uninstall.ps1` removes the task. `uninstall.ps1 -RestoreAIServices` also re-enables and starts +the two LLM service tasks. `-RemovePawnIO` uninstalls PawnIO. + +Admin rights are needed for these readings and controls: + +- CPU temperature and power +- The motherboard top fans +- The RAM lighting + +Without admin rights those show `--` or stay idle, and everything else works. The LLM servers +always run as a normal user at medium integrity, never elevated, even though The Kurgan itself +is elevated (see `kurgan/ai/launcher.py`). The web UI shows each server's integrity level. + +## Web UI + +Open it from the tray icon (left-click, or **Open The Kurgan** in its menu) or browse to +. It only listens on 127.0.0.1. The page refreshes once a second while it +is visible. Every chart has a **Table** button that shows the same numbers as a table. + +- **System**: CPU and GPU temperature, load, clock and power; GPU memory; the LCD's state. Charts show whole-PC power (stacked: other, CPU, GPU) and temperatures over the last 10 minutes. +- **Cooling**: the fan profile selector; each fan group's duty, temperature and RPMs; fan speeds over time; and the selected profile's curves, with a dot for each group's current operating point. Hover over a profile to preview its curves. +- **Lighting**: a mode selector per zone (case fans, RAM, GPU), the zone's status, and the shared chase speed. +- **AI**: pick Strata (and its model), llama.cpp or None; requests to either address also pick it. Then see the server's process, model, context size, live request progress and token speeds, and when it will stop if unused; load or unload the model; GPU memory over time; and recent requests. + +Every choice is saved immediately in `%LOCALAPPDATA%\Kurgan\settings.json` and restored at the +next start. + +### JSON API + +| Request | Body / result | +| --- | --- | +| `GET /api/state` | Everything live (what the UI polls) | +| `GET /api/history` | The last 10 minutes of telemetry and fan duty | +| `GET /api/config` | Fan profiles and LCD theme thresholds | +| `POST /api/lighting` | `{"zone": "case_fans"\|"memory"\|"gpu", "mode": "off"\|"temperature"\|"chase"}` | +| `POST /api/cooling/profile` | `{"profile": "quiet"\|"balanced"\|"performance"\|"full"}` | +| `POST /api/ai/active` | `{"backend": "strata"\|"llama"\|null, "variant": "q5"\|"iq3"}` (variant: Strata only, optional) | +| `POST /api/ai/model` | `{"action": "load"\|"unload"}` | +| any `/strata/...`, `/llama/...` | Passed to that LLM server (see [AI](#ai-strata-and-llamacpp)) | + +POSTs to `/api/...` need `Content-Type: application/json` and an `X-Kurgan: 1` header. A web page on another +site can't send that header without a CORS preflight, which this server never answers. Requests +must also name `127.0.0.1:` or `localhost:` as the Host, which blocks DNS rebinding. +There is no other authentication: any program already running on this PC as you can use the API. + +```powershell +curl.exe -s -X POST -H "Content-Type: application/json" -H "X-Kurgan: 1" ` + -d '{\"profile\":\"quiet\"}' http://127.0.0.1:8080/api/cooling/profile +``` + +## Settings + +`%LOCALAPPDATA%\Kurgan\settings.json`, created on the first start: + +```json +{ + "cooling": {"profile": "balanced", "gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5]}, + "lighting": {"case_fans": "chase", "memory": "off", "gpu": "off"}, + "ai": {"active": "strata", "strata_model": "q5", "idle_stop_minutes": 40}, + "web": {"port": 8080} +} +``` + +On the first start, The Kurgan imports the TT LCD Dashboard's fan ports and RAM and GPU lighting +modes from `%LOCALAPPDATA%\TTLcdDashboard`. The old task's `--rgb-side-chase` becomes +`case_fans: chase`. The file is checked strictly. An invalid file stops The Kurgan with a message, +rather than starting without fan control. A failed save leaves the previous setting in place, +both in memory and on disk. + +`idle_stop_minutes` is how long a server may go unused before The Kurgan stops it (0 = never, +up to 1440). The `ai` section also accepts these optional keys, for when an install moves: + +- `strata_root` (default `D:\AI\Strata`) and `strata_port` (8082, internal) +- `llama_server` (llama.cpp **b12977**), `llama_presets`, `llama_model` and `llama_port` (8083, internal) + +See `kurgan/ai/config.py`. Restart The Kurgan after editing the file by hand. + +Command-line lighting options such as `--rgb-side-chase` apply to that run only. The UI marks +them "this run only"; choosing a mode in the UI saves it. + +Log: `%LOCALAPPDATA%\Kurgan\kurgan.log` + +## AI: Strata and llama.cpp + +Point OpenAI-compatible clients at The Kurgan: + +| Server | Base URL | Chat page | Model | +| --- | --- | --- | --- | +| Strata | `http://127.0.0.1:8080/strata/v1` | | OrcaRouter Qwen3.8 Flash Next, Q5_K_M or IQ3_XXS (selectable) | +| llama.cpp | `http://127.0.0.1:8080/llama/v1` | | Qwen4 35B-A3B UD-Q5_K_XL | + +No API key is needed. Clients that insist on one can send any key. + +Only one server runs at a time, so the two never share the RTX 4090's 24 GB. A request starts the +server it is addressed to. If the other server is running, it is stopped first: + +- If the other server is busy (a request in progress, a reply being generated, or a model + loading), the new request waits until it finishes, for up to 10 minutes, rather than + cutting it off. +- Stopping means stopping completely: every process in its job object has ended and its port + has closed. Only then does the other server start. +- A request that has to start its server waits for it. A swap takes a few seconds, plus the model's + load time (about 45 s for either model). Give clients a generous timeout. + +A server nobody has used for `idle_stop_minutes` (40) is stopped, and the UI shows **None**. The next +request starts it again. Choosing a server in the UI starts it straight away. If a request is +in progress there, the UI asks before switching. + +How the proxy behaves (`kurgan/web/proxy.py`): + +- Replies stream through as they are generated. +- A client that hangs up (a timeout, or a cancel) is noticed within a second, even while its request is still waiting: it gives up its place, so it never makes the servers swap, and the server is told to drop it. The log says how long the client waited and at which stage. +- Clients' own timeouts must allow for the waits above. opencode, for example, gives up after 5 minutes without a reply unless its provider options set `headerTimeout`. +- `GET /v1/models` is answered by The Kurgan while a server is stopped, so a client that lists the + models of both doesn't make them swap. +- Requests from web pages of other sites are refused, as for the UI's own API. + +Behind the proxy each server listens on its own port on 127.0.0.1. Clients shouldn't use these +ports: requests sent straight to them don't start or keep a server running. + +| Server | Internal port | What The Kurgan runs | +| --- | --- | --- | +| Strata | 8082 | `kurgan/ai/strata_host.py`, using Strata's own `terminal\.venv` | +| llama.cpp | 8083, under `/llama` | `llama-server.exe` b12977 in router mode, from the Qwen4 service's `presets.ini`, with `--api-prefix /llama` and its API key (`sk-local`), which the proxy supplies | + +Strata's optional API-monitor page (`/api-monitor`) uses absolute paths, so it doesn't work under +`/strata/`. The Kurgan's own AI section shows the same requests. + +Both start with no model in memory. The model loads on the first request, or when you press +**Load model**. Strata unloads it after 2000 s idle; llama.cpp sleeps after its preset's idle +time. Strata is stopped gracefully through a named event, and gets 45 s to finish. llama.cpp +is ended through its job object. Each server gets the same environment its own service gave it: +Strata runs with `GGML_CUDA_DISABLE_GRAPHS=1`, and llama.cpp runs without it. Both use OpenBLAS's +default threading, not the single-thread pin The Kurgan uses for itself. + +Live progress comes from different places: + +- **Strata**: its `/metrics` endpoint. +- **llama.cpp**: its log. Polling `/slots` would reset the idle timer. + +Logs: + +- `%LOCALAPPDATA%\Kurgan\logs\strata-host.log`, plus Strata's own `D:\AI\Strata\logs\local-service-*.log` +- `%LOCALAPPDATA%\Kurgan\logs\llama-server.log` (the previous run's log is kept as `.prev`) + +A server that exits on its own is restarted after 5 seconds. After 5 exits within 5 minutes, +The Kurgan waits 5 minutes before trying again, and the UI shows why. + +**Updating Strata**: Strata's `LOCAL-SERVICE-HANDOFF.md` assumes its own tray service. Once that +service is retired, select **None** in the UI before updating Strata, then select Strata again. +Until the update is finished, don't send requests to `/strata/`: any one of them starts Strata again. +The Kurgan starts `strata_host.py` with Strata's own `server.main`, so the update procedure +otherwise stays the same. + +## Cooling + +### Profiles + +| Profile | GPU-side case fans | CPU-side case fans | Top fans | +| --- | --- | --- | --- | +| Quiet | 35% to 45 C, 100% at 75 C | 35% to 55 C, 100% at 85 C | start 55 C, stop below 50 C | +| **Balanced** (the original curves) | 40% to 40 C, 50% at 50 C, 65% at 60 C, 100% at 70 C | 40% to 50 C, 50% at 60 C, 65% at 70 C, 100% at 80 C | start 50 C, stop below 45 C; 30% at 50 C, 60% at 60 C, 100% at 70 C | +| Performance | 50% to 35 C, 100% at 65 C | 50% to 45 C, 100% at 75 C | start 45 C, stop below 40 C | +| Full speed | 100% | 100% | 100% | + +The exact points are in `kurgan/cooling/profiles.py`. Duty between points is interpolated. +A profile change raises speeds at once. Lower speeds follow the usual ramp-down: they wait 10 +seconds after the last rise, then fall at most 2 points per second. These fail-safes apply in +every profile: + +- Fans run at 100% on start-up. +- They run at 100% after a polling gap of over 5 seconds. +- They run at 100% when a temperature is missing or invalid. +- A group runs at 100% when one of its fans is below 200 RPM after its 10-second spin-up. +- The top fans are held at 100% while either case-fan group runs at 85% or more. They are released once both groups are at 65% or less. + +### Ports and channels + +On this machine, identification confirmed these mappings: + +- Commander PRO PWM ports **1-3 are the CPU side** and **4-6 the GPU side**. This is separate from the RGB chain order. +- The two top extractors are on **SYS_FAN1 and SYS_FAN4** (NCT6687D PWM channels 2 and 5). +- The CPU cooler is on CPU_FAN1 (channel 0), which is never touched. + +The mapping is in `settings.json`. To identify or change it, first exit The Kurgan from its +tray menu, then run: + +```powershell +.\.venv\Scripts\python.exe -m kurgan.cooling.control --identify 1,2,3 # these ports to 100%; watch which side speeds up +.\.venv\Scripts\python.exe -m kurgan.cooling.control --save-ports 4,5,6 # GPU side +.\.venv\Scripts\python.exe -m kurgan.cooling.control --save-cpu-ports 1,2,3 # CPU side (GPU side first) +.\.venv\Scripts\python.exe -m kurgan.cooling.board_fans --probe # read-only motherboard headers (admin) +.\.venv\Scripts\python.exe -m kurgan.cooling.board_fans --identify 2,5 # hold channels at 100% (admin) +.\.venv\Scripts\python.exe -m kurgan.cooling.board_fans --auto 2,5 # hand them back to the BIOS (admin) +.\.venv\Scripts\python.exe -m kurgan.cooling.control --save-top-channels 2,5 +``` + +`--identify` leaves the selected group at 100%, rather than guessing its previous profile. Do not +guess the port mapping. `--gpu-fan-ports 4,5,6` overrides the saved ports for one run, and +`--no-gpu-fan-control` turns fan control off for one run. + +**Controller ownership:** exit iCUE, FanControl and other Commander PRO tools. If you run OpenRGB, +disable its **Corsair Commander Pro** and **Corsair Lighting Node Core** detectors in both +`%APPDATA%\OpenRGB\OpenRGB.json` and `C:\Program Files\OpenRGB\service_config\OpenRGB.json`. While +another tool has a device, The Kurgan leaves that device alone and says so in the UI. The top fans +share LibreHardwareMonitor's ISA-bus mutex, so don't let another tool control the same headers. +On exit the case fans are left at 100% and the top fans go back to the BIOS Smart Fan curve. + +This is software control, not a hardware thermal safeguard. It can't guarantee a speed change +after a USB failure, a forced process kill or a system hang, and the Commander PRO may keep its +last duty. Verify temperatures and fan rotation under your real workloads. Only SYS_FAN4 reports +RPM, so there is no stall detection on the top fans. + +## Lighting + +| Zone | Device | Modes | +| --- | --- | --- | +| Case fans | Corsair Lighting Node CORE (`1B1C:0C1A`), six QL120 fans on header 1 | off, temperature, red side chase | +| RAM | Four Corsair Dominator Platinum DDR5 sticks, over the Intel SMBus through PawnIO (admin) | off, temperature, red side chase | +| GPU | ASUS ROG STRIX RTX 4090 LED row, over NVIDIA's `nvapi64.dll` | off, red side chase | + +- **Off**: the case fans return to the CORE's own hardware effect. The RAM is held dark while The Kurgan runs; black frames are refreshed every 5 s, and the stored effects are untouched. The GPU's previous direct colours and mode are restored. +- **Temperature**: + - Case fans: the CPU-side fans follow CPU temperature and the GPU-side fans follow GPU temperature. They are green below `--temp-warn` (50 C), yellow up to `--temp-hot` (80 C), and red above. + - RAM: the hotter of CPU and GPU blends from dark red `(24, 0, 0)` to warm orange `(255, 48, 0)`. +- **Red side chase**: warm-orange heads with four fading trail LEDs over dark red. All three zones share one power-paced clock, so they stay in step. The pace is 150 ms per LED at 150 W or less, speeding up evenly to 25 ms at 550 W or more (`--rgb-chase-*`). + - Case fans: the CPU route is bottom → middle → top → middle, and the GPU side is mirrored. + - RAM: two mirrored heads visit sticks 4 → 3 → 2 → 1 → 2 → 3 once per fan cycle. + - GPU: one head runs front to back and back again once per cycle. + +Calibrated case-fan outer-ring indices (zero-based within each 34-LED fan: hub 0-9, outer ring +10-21, inner ring 22-33): + +| Chain fan | Location | Outer ring left / right of 12 | +| --- | --- | --- | +| 1 | GPU bottom | 16 / 17 | +| 2 | GPU middle | 16 / 17 | +| 3 | GPU top | 16 / 17 | +| 4 | CPU top | 19 / 20 | +| 5 | CPU bottom | 10 / 11 | +| 6 | CPU middle | 19 / 20 | + +The CORE needs a keep-alive every 5 seconds or it drops back to its hardware effect. Updates on +every device are capped at about 22 per second. The CORE and the LCD share a Genesys USB 2.0 hub, +and heavier traffic once hung the LCD firmware until it was power-cycled. If the LCD repeatedly +reports a handshake timeout (opcode `0x85`), set the case fans to off. Then safely power-cycle +the LCD and check the cable, power and hub routing before re-enabling the chase. Do not unplug +internal cables while the PC is powered. + +The RAM controllers are at `0x18`-`0x1B`, top to bottom. They are written directly over SMBus +with PawnIO's I801 module (PawnIO Modules 0.2.12; its LGPL source and licence are in +`kurgan/hardware/pawnio/`). RAM control never changes the stored lighting effects. The GPU driver +is restricted to PCI `10DE:2684`, subsystem `1043:8932`, with supported ENE firmware at I2C +`0x67`. It never sends ENE's save-to-flash command. Exit ASUS lighting software, iCUE and OpenRGB +before using either. + +**NVIDIA services:** + +- Keep `NVDisplay.ContainerLocalSystem` running. With it disabled, the card stayed in P0 at full clocks (about 63 W) when idle. +- Its `nvgwls.exe` plugin is blocked instead, because it repeatedly loaded the GPU at about 270 W. The block is an Image File Execution Options `Debugger` value under `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\nvgwls.exe`; delete that key to undo it. +- `NvContainerLocalSystem`, `FvSvc` and the NVIDIA App self-update task remain disabled. Driver updates may re-enable them. + +## Display + +The Thermaltake 3.9" bar LCD (USB `264A:233D`, 480×128) needs no TT RGB Plus. The GPU is on the +left and the CPU on the right, matching the case; all gauges fill clockwise. + +| Element | Shows | +| --- | --- | +| Outer gauges | CPU package temperature (20–100 °C), GPU temperature (20–90 °C) | +| Inner gauges | CPU and GPU load % | +| MHz readouts | CPU effective clock, GPU graphics clock | +| Centre tank | Total power, full = the PSU rating (1000 W). From the bottom: other (copper), CPU (blue), GPU (aqua). Each tick is 10% | +| TOTAL readout | CPU + GPU + other, in watts | +| Bottom readouts | The three tank layers: GPU W, other W, CPU W | + +The background is `kurgan/display/background.png`, loaded once at start-up; restart after +replacing it. The panel falls back to its own screen if it gets no frame for a few seconds. When +the LCD is unplugged or the PC sleeps, The Kurgan reconnects; everything else keeps running. + +## Where the watts come from + +All figures are DC watts, i.e. load on the power supply; wall draw is roughly 8–12% higher. + +| Part | Source | +| --- | --- | +| CPU | Measured: the package's energy counter (RAPL), via PawnIO | +| GPU | Measured: board power from NVIDIA (the whole card, including its fans and lighting) | +| CPU regulator losses | Derived: CPU watts × 11% | +| Memory | Estimated per module (4 × DDR5): 2.5 W idle to 5.5 W, scaled by CPU load | +| Drives | Estimated from each drive's activity and rated power (Lexar NQ790 3.5 W, Kingston KC3000 8.8 W; the USB hard drive as bus-powered, spun down after 10 minutes idle) | +| Case fans | Estimated from the Commander PRO's fan speeds (about 2 W per fan at 1500 rpm) | +| Motherboard & chipset | Fixed 15 W | +| Motherboard-header fans/pump | Fixed 5 W | +| USB devices & RGB lighting | Fixed 12 W | + +The estimates are in `PowerModel` in `kurgan/telemetry/sensors.py`. + +## Running by hand + +```powershell +Stop-ScheduledTask "The Kurgan" # only one copy runs at a time +.\.venv\Scripts\python.exe -m kurgan # console, Ctrl+C to stop +.\.venv\Scripts\python.exe -m kurgan --preview x.png # render one LCD frame from live sensors +$env:KURGAN_DATA_DIR = "$env:TEMP\kurgan-demo" +.\.venv\Scripts\python.exe -m kurgan --demo --port 18080 # simulated hardware; separate settings +Start-ScheduledTask "The Kurgan" # back to the hidden, elevated copy +``` + +In demo mode the LLM servers use ports 18082 and 18083, but they are real servers. +`python -m kurgan --help` lists the LCD and lighting options. To make one permanent, add it to the +task's arguments. Lighting modes are better chosen in the UI. + +| Tool | Use | +| --- | --- | +| `python -m kurgan.telemetry.sensors` | Print the live readings and power breakdown (exit The Kurgan first: one program at a time should poll the Commander PRO) | +| `python -m kurgan.display.renderer demo.png` | Render the LCD with fixed demo values | +| `python -m kurgan.display.tt_lcd` | LCD test card | +| `python -m kurgan.tray` | Show a test tray icon for 20 seconds | + +Tests: `.\.venv\Scripts\python.exe -m unittest discover -s tests` + +## Layout + +```text +kurgan/ + app.py wires the capabilities together; command line; single instance + settings.py settings.json: defaults, strict validation, atomic saves, legacy import + paths.py, theme.py, tray.py, demo.py (simulated hardware for --demo) + telemetry/ sensors.py (CPU/GPU/system power), readings.py, service.py (sampling + history) + display/ tt_lcd.py (panel HID protocol), renderer.py, service.py (LCD loop), background.png + cooling/ profiles.py, control.py (case-fan groups, top-fan curve), board_fans.py (NCT6687D) + lighting/ case_fans.py (CORE patterns + shared chase clock), lighting_node.py, memory.py, gpu.py, service.py + ai/ config.py, launcher.py (non-elevated child processes in job objects), + backends.py (Strata, llama.cpp), service.py (one-at-a-time supervisor), strata_host.py + web/ server.py (API), static/ (index.html, app.js, style.css) + hardware/ hid.py (Windows HID), pawnio/ (signed PawnIO modules, LGPL-2.1) +tests/ unittest suites +docs/ design references and research notes +lcd_dashboard.py compatibility shim for the old "TT LCD Dashboard" task until setup.ps1 is re-run +``` + +## LCD protocol notes + +The panel protocol was worked out by [ttlcd](https://github.com/bekindpleaserewind/ttlcd), +[thermaltaked](https://github.com/GregDuhamel/thermaltaked) and +[Tower-500-LCD-Controller](https://github.com/JohnathanKong/Tower-500-LCD-Controller). This is an +independent implementation. + +- Interface 0: commands (440-byte reports). Handshake `85 87 85 87 84 81`, brightness `12`, heartbeat `82`. +- Interface 1: frames (1024-byte reports). A baseline JPEG in 1020-byte chunks: header `08 count 00 80`, then `08 index 00 00`. diff --git a/docs/design/CPU Example.png b/docs/design/CPU Example.png new file mode 100644 index 0000000..a582f1b Binary files /dev/null and b/docs/design/CPU Example.png differ diff --git a/docs/research/notes/Uncensored local LLM alternatives/deepseek.md b/docs/research/notes/Uncensored local LLM alternatives/deepseek.md new file mode 100644 index 0000000..a8c5843 --- /dev/null +++ b/docs/research/notes/Uncensored local LLM alternatives/deepseek.md @@ -0,0 +1,290 @@ +# DeepSeek uncensored/abliterated models as a replacement for Qwen3.8-Flash-Next (as of 2026-12-03) + +Target hardware: RTX 4090 24 GB, i7-14700, 128 GB DDR5, fast NVMe, Windows 10. Current model: orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF Q5_K_M (~120 GB) in Strata v0.2.24. Also available: llama.cpp b12774 (CUDA 12.4) with -ot / --n-cpu-moe. + +Research note: most sources below are Hugging Face model cards, GitHub pages, and third-party blogs/aggregators, read via fetch summaries. Uploaders' refusal and quality numbers are their own and were not independently reproduced. Anything dated before Oct 2026 is marked **(older)**. + +## 1. Latest DeepSeek open-weight releases (as of Dec 2026): sizes, active params, context + +### Takeaway +The newest DeepSeek open weights are **DeepSeek-V4.1-Flash** (around Sep 10, 2026) and its revision **V4.1-Flash-1017** (Oct 17, 2026). Each is a 763B checkpoint: a ~552B MoE backbone plus a ~196B "Engram" n-gram lookup table, with 1M context and roughly 8–16B active parameters. No R2, no "Lite", and no V4.1-Pro open weights were found. The smaller V4-Flash family (284–304B, 13B active) is older (Jun–Aug 2026). V4-Pro (1.6–1.7T) is far too large for this machine. + +### Cited Findings +- The deepseek-ai Hugging Face org lists: DeepSeek-V4.1-Flash-1017 (763B, updated "23 days ago", so about Nov 10), DeepSeek-V4.1-Flash (763B, Oct 16), DeepSeek-V4-Flash-Vision-Exp (305B, Sep 1), DeepSeek-V4-Pro-0813 (1.7T, Aug 13), DeepSeek-V4-Flash-0731 (304B, Aug 1), V4-Flash-DSpark and V4-Pro-DSpark (Jul 4), and in collections DeepSeek-V4-Flash (291B, Jun 22), V4-Pro (1.6T, Jun 22), V4-Flash-Base (292B, Apr 27) and V4-Pro-Base (1.6T, Apr 27). **No R2 or Lite model appears.** — [HF deepseek-ai](https://huggingface.co/deepseek-ai) +- V4.1-Flash release is dated **September 10, 2026**, with the **V4.1-Flash-1017** revision on **October 17, 2026**. Backbone 552B, plus a separate 196B Engram conditional memory read sparsely by token lookup. Active parameters are **8B during prefill and 16B during decoding**, context **1M**, FP8 precision. — [Morph](https://www.morphllm.com/deepseek-v4-1-flash); [DeepInfra](https://deepinfra.com/blog/deepseek-v4-1-flash-model-overview-integration); [SiliconFlow](https://www.siliconflow.com/models/deepseek-v4-1-flash); [Learn AI wiki](https://ai.miraheze.org/wiki/DeepSeek_V4.1_Flash). Artificial Analysis lists 552B total and 16B active, leaving out Engram — [Artificial Analysis](https://artificialanalysis.ai/models/deepseek-v4-1-flash) +- ISTA-DASLab's numbers, as relayed by OpenClaw: **763.2B total, 384 routed experts per layer, 6 active per token, backbone 551.9B, Engram 196.6B**. The base model was released 2026-10-17. — [OpenClaw DC](https://openclawdc.com/blog/deepseek-v4-1-flash-gsq-rco-quants/) +- orcarouter's model card gives the architecture: 763B MoE (748.5B weights in the GGUF files), 384 routed experts (top-6) + 1 shared, a 197B Engram n-gram memory at layers 1 and 14, 40 layers, hidden size 5120, compressed sparse attention, context 1,048,576, vocab 129,280. — [orcarouter V4.1-Flash-1017 abliterated GGUF](https://huggingface.co/orcarouter/DeepSeek-V4.1-Flash-1017-abliterated-GGUF) +- Unsloth gives backbone 552B, Engram 196B, maximum context 1,048,576. Thinking is on by default (`reasoning_effort` 75; low=50, medium=62, high=75, max=100; `{"enable_thinking":false}` turns it off). Recommended sampling is temp 1.0, top-p 1.0, top-k 0, min-p 0. — [Unsloth guide](https://unsloth.ai/docs/models/deepseek-v4.1-flash) +- **(older)** V4-Flash: 284B total, 13B activated. — [Learn AI wiki](https://ai.miraheze.org/wiki/DeepSeek_V4.1_Flash); [DeepSeek-V4 paper (arXiv)](https://arxiv.org/pdf/2606.19348). The huihui-ai card also gives 284B for V4-Flash-0731 (GGUF arch `deepseek4`) — [huihui V4-Flash-0731 GGUF](https://huggingface.co/huihui-ai/Huihui-DeepSeek-V4-Flash-0731-abliterated-GGUF) +- DeepSeek's official benchmarks, 1017 vs the original V4.1-Flash: HLE (no tools) 42.6 vs 36.8; Terminal-Bench 4.0 42.3 vs 31.2; DeepSWE v1.1 77.0 vs 74.2; ProgramBench 29.1 vs 20.3; NL2Repo 68.2 vs 65.4; Automation-Bench 60.5 vs 54.8; Apex Bench 72.1 vs 64.6. — [Unsloth guide](https://unsloth.ai/docs/models/deepseek-v4.1-flash) +- V4.1-Flash-1017 is multimodal (text + image input). — [Artificial Analysis comparison](https://artificialanalysis.ai/models/comparisons/deepseek-v4-1-flash-1017-vs-qwen3-8-flash-next) +- For reference, the current model Qwen3.8-Flash-Next (released Aug 26, 2026) is a 125B main model + 51B n-gram embedding (about 176–180B total including MTP), with **6B active**, 262K native context (1M with YaRN), under the qwen-community-1.0 license. — [Qwen HF](https://huggingface.co/Qwen/Qwen3.8-Flash-Next); [FoneArena](https://www.fonearena.com/blog/490674/qwen3-8-flash-features.html/amp) + +### Inferences +- The only DeepSeek candidates that matter are **V4.1-Flash-1017** (newest and strongest, but huge) and **V4-Flash-0731** (older, about 2.5x smaller, much easier to fit). V4-Pro is out of reach. +- V4.1-Flash uses about 16B active parameters while decoding against Qwen3.8-Flash-Next's 6B, so per-token memory traffic is roughly 2–3x higher at the same bit width. Expect noticeably slower decoding on the same hardware. + +### Gaps +- No official DeepSeek model card was fetched directly. Dates and parameter splits come from HF listings plus third-party write-ups, which disagree slightly (552B vs 551.9B backbone; 196B vs 197B Engram; "8–16B active" vs "6 of 384 experts"). +- No evidence found of a V4.1-Pro open release, an R2, or a Lite model. The absence on the HF page is the only evidence. + +## 2. Uncensored / abliterated / Heretic versions on Hugging Face + +### Takeaway +Many refusal-removed builds exist for both V4-Flash and V4.1-Flash-1017, but only a few are **GGUFs small enough for 24 GB + 128 GB**: +- (a) **Abiray/DeepSeek-V4.1-Flash-1017-Uncensored-GSQ-RCO-IQ2_XXS-GGUF**: 138.6 GB backbone + 110.6 GB Engram kept on SSD. Highest fidelity to the stock 2-bit quant. +- (b) **huihui-ai/Huihui-DeepSeek-V4.1-Flash-1017-abliterated-GGUF**: patches for Unsloth UD-IQ1_S/IQ1_M/IQ2_XXS and the Strata GSQ-RCO quant. Weak abliteration with no evidence. +- (c) **orcarouter/DeepSeek-V4.1-Flash-1017-abliterated-GGUF Mix-128G**: fits, but its card calls it heavily degraded. The good Mix-256G needs about 256 GB. +- (d) **Older, V4-Flash-0731**: huihui-ai Q2_K (97.6 GB) and audreyt/CyberNeurova Q2_K (~81 GB). These fit fully in RAM+VRAM. + +The best-documented abliteration is orcarouter's (refusals 0.874 → 0.074, MMLU unchanged), but its fitting quant is poor. + +### Cited Findings +**V4.1-Flash-1017 / V4.1-Flash, GGUF:** +- **orcarouter/DeepSeek-V4.1-Flash-1017-abliterated-GGUF** (same publisher as the user's current Qwen model): + - Method: refusal direction orthogonalized out of every residual-writing matrix. + - Quantization: per-layer mixed precision chosen by a KLD-measured knapsack search, with a 614k-token imatrix. + - Refusal on 500 harmful prompts: **0.874 base → 0.074** (JBB 0.95→0.03, AdvBench 0.99→0.15, SimpleSafetyTests 1.0→0.12). + - Over-refusal on 350 benign prompts: 0.069 → 0.006. + - MMLU (n=300): 0.910 → 0.920. + - These figures come from the unquantized checkpoint. + - Builds: **Mix-256G** (346.5 GB download, 235.8 GB in memory, 3.36 bpw, KLD 0.051, top-1 93.7%, PPL +2.4%) and **Mix-128G** (225.0 GB download, **114.0 GB in memory**, 1.59 bpw, **KLD 0.520, top-1 78.5%, PPL +54.7%**; the card calls it heavily degraded). + - Engram is a separate 110.6 GB IQ4_NL shard read from disk (48 rows/token). + - Runtime: llama.cpp **PR #30817** (tested at commit b72050d03; the card says "not in llama.cpp master yet") or Ollama ≥ v0.40.16. LM Studio is not compatible. + - 183,405 downloads/month, 525 likes. No explicit date; the collection was "updated 20 days ago". + - — [orcarouter HF](https://huggingface.co/orcarouter/DeepSeek-V4.1-Flash-1017-abliterated-GGUF) +- **Abiray/DeepSeek-V4.1-Flash-1017-Uncensored-GSQ-RCO-IQ2_XXS-GGUF**: + - A weight-baked abliteration of ISTA-DASLab's GSQ-RCO IQ2_XXS. It modifies 86 residual-writing tensors (80 dense + 6 expert) and credits AtomicChat's EN+RU refusal directions. + - Fidelity against the stock IQ2_XXS (llama-perplexity b12017): mean KLD 0.0095, top-1 agreement 98.4%, PPL 2.486 vs 2.354. + - **No refusal-rate numbers.** + - Files: backbone 138.58 GB (5 shards), Engram `DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf` 110.60 GB (shared with upstream, must be hard/symlinked as shard 6), mmproj 0.97 GB. + - Runtime: llama.cpp b11870+ (b12017+ referenced), or Strata 0.2.8 (engine 0.1.54) with `--family deepseek41 --model ist-das-2.00bpw`. The card warns Strata's hardcoded file-size check may reject it. + - Has an "Update (October 2026)" section. 350,618 downloads/month, 142 likes. + - — [Abiray HF](https://huggingface.co/Abiray/DeepSeek-V4.1-Flash-1017-Uncensored-GSQ-RCO-IQ2_XXS-GGUF) +- **huihui-ai/Huihui-DeepSeek-V4.1-Flash-1017-abliterated-GGUF**: + - Abliteration done in GGUF with llama.cpp's cvector tooling. Only the 18 `attn_output_b` tensors in layers 11–28 were ablated; experts untouched. + - Shipped mostly as **patches** against Unsloth UD-IQ1_S (233 GB) / UD-IQ1_M (250 GB) / UD-IQ2_XXS / UD-Q2_K_XL, against the Strata/ISTA GSQ-RCO quant (patch-Strata-GSQ-RCO-Coder), and against Maya. + - **No refusal or quality evidence.** Requires llama.cpp b11870+. Collection "updated Oct 27". 176,958 downloads/month. + - — [huihui V4.1 HF](https://huggingface.co/huihui-ai/Huihui-DeepSeek-V4.1-Flash-1017-abliterated-GGUF) +- **Adolphsson/DeepSeek-V4.1-Flash-UNCENSORED-GGUF**: requantized to GGUF from dealignai's FP8 uncensored checkpoint. The uncensoring itself is dealignai's (details not fetched). — [Adolphsson HF](https://huggingface.co/Adolphsson/DeepSeek-V4.1-Flash-UNCENSORED-GGUF) (search snippet only) + +**V4.1-Flash-1017 / V4.1-Flash, safetensors only (not directly usable on this PC):** +- **distributedcognition/DeepSeek-V4.1-Flash-1017-abliterated**: + - Projected, norm-preserving biprojected abliteration of `attn.wo_b` + shared-expert `w2`, layers 4–36, scale 3.0. Directions transferred from their earlier V4.1-Flash build. + - Keyword refusals 99 → 46/100, but an LLM judge found 0 true refusals (53 compliant, 47 partial/hedged). + - KL 0.093. GSM8K spot check 19/20 → 18/20. + - FP8/FP4 safetensors for 8-GPU torchrun or SGLang. + - — [distributedcognition HF](https://huggingface.co/distributedcognition/DeepSeek-V4.1-Flash-1017-abliterated) +- **s-zaizen/DeepSeek-V4.1-Flash-Abliterated**: built with Heretic tooling, 24/100 refusals on Heretic's keyword metric. No GGUF mentioned. — [s-zaizen HF](https://huggingface.co/s-zaizen/DeepSeek-V4.1-Flash-Abliterated) (search snippet only) + +**V4-Flash (older, Jun–Aug 2026):** +- **huihui-ai/Huihui-DeepSeek-V4-Flash-0731-abliterated-GGUF**: + - "Crude proof-of-concept" abliteration without TransformerLens; experts untouched. + - **Q2_K 97.6 GB**, MXFP4 156 GB. The Q4 got stronger ablation than the Q2. + - Runs in llama.cpp ("use latest") or antirez's ds4 fork. No refusal or quality data. Collection updated Oct 27. + - — [huihui V4-Flash-0731 HF](https://huggingface.co/huihui-ai/Huihui-DeepSeek-V4-Flash-0731-abliterated-GGUF) +- **huihui-ai/Huihui-DeepSeek-V4-Flash-abliterated-GGUF** (base V4-Flash, UD-IQ1_M from Unsloth) and **huihui-ai/Huihui-DeepSeek-V4-Flash-abliterated-ds4-GGUF**. — [huihui V4-Flash HF](https://huggingface.co/huihui-ai/Huihui-DeepSeek-V4-Flash-abliterated-GGUF) (search snippet only) +- **audreyt/CyberNeurova-DeepSeek-V4-Flash-abliterated-GGUF**: Q2_K of about 81 GB. — [audreyt HF](https://huggingface.co/audreyt/CyberNeurova-DeepSeek-V4-Flash-abliterated-GGUF) (search snippet only) +- **prem-research/DeepSeek-V4-Flash-0731-abliterated**: + - ARA (Arbitrary-Rank Ablation, LBFGS) on layers 17–36: attention o_b_proj, shared-expert down_proj, and the down_proj of the top-8 most-routed experts. + - Refusals **69% → 3%** on 800 held-out prompts. KL **0.044**. No capability benchmarks. + - FP8/FP4 safetensors for vLLM/SGLang TP2. 383,612 downloads/month. + - — [prem-research HF](https://huggingface.co/prem-research/DeepSeek-V4-Flash-0731-abliterated) +- **cebeuq/DeepSeek-V4-Flash-0731-abliterated**: edits only the attention output projections; claims coding, tool-calling and long-context retrieval are intact. About 167 GB, for vLLM on 2x DGX Spark. — [cebeuq HF](https://huggingface.co/cebeuq/DeepSeek-V4-Flash-0731-abliterated) (search snippet only) +- Also: lovesenko/DeepSeek-V4-Flash-DSpark-Abliterated, drowzeys/DeepSeek-V4-Flash-DSpark-Abliterated-Uncensored, apetersson/DeepSeek-V4-Flash-Vision-Exp-Abliterated. — [lovesenko](https://huggingface.co/lovesenko/DeepSeek-V4-Flash-DSpark-Abliterated); [drowzeys](https://huggingface.co/drowzeys/DeepSeek-V4-Flash-DSpark-Abliterated-Uncensored); [apetersson](https://huggingface.co/apetersson/DeepSeek-V4-Flash-Vision-Exp-Abliterated) (search snippets only) + +**Behavioural test of uncensored V4.1 builds (hosted):** +- Obscurify.ai tested six uncensored V4.1-Flash variants (0910, 1017, thinking/non-thinking) on 12 prompts (mature fiction, satire, one-sided essays, health questions, awareness-training scenarios), benchmarked Nov 6, 2026: + - **No build refused anything.** Full answers ranged from 9 to 12 of 12. + - "No answer" cases came from thinking builds exhausting 3,000 reasoning tokens. + - It does not name the HF repos behind the builds and has no China-topic test. + - — [Obscurify](https://obscurify.ai/deepseek-uncensored) +- A news write-up reports "31 builds" of uncensored V4.1-Flash on HF. — [Tech Insider](https://tech-insider.org/deepseek-v4-1-flash-uncensored-abliterated-huggingface-2026/) (title only, not fetched) + +### Inferences +- **Best fit for this PC, best evidence:** the Abiray IQ2_XXS uncensored GGUF. It is nearly identical to the stock ISTA IQ2_XXS (KLD 0.0095 vs stock), and ISTA's IQ2_XXS is the quant ISTA rates as about 100% of base on AIME/GPQA/LCB. Its weak point is that it publishes no refusal-rate measurement, so refusal removal should be spot-checked. +- orcarouter has the most rigorous abliteration evidence, but its 128 GB build (KLD 0.52, PPL +55%) is much worse than the ISTA/Unsloth 1–2-bit mixes at similar size. Do not pick Mix-128G over Abiray or a huihui-patched Unsloth quant. +- huihui-ai's V4.1 patches ablate only 18 attention tensors. distributedcognition's similar narrow edit left many hedged "partial" answers, so expect residual hedging. +- V4-Flash-0731 Q2_K abliterated builds (81–98 GB) are the "comfortable fit" option, but they are an older and weaker model family. + +### Gaps +- Not fetched: Adolphsson/dealignai's method, s-zaizen's Heretic details, and the "pqhaz/DeepSeek-V4.1-Flash-1017-heretic" (510 GB, 38 attention tensors, Heretic-style) repo, which appeared only in a search summary with no URL. +- No independent refusal benchmark compares these GGUFs at low bit width. All refusal numbers are self-reported and mostly measured on unquantized checkpoints. +- Exact upload dates are missing on most cards. Only "Oct 2026" update notes and collection dates (Oct 27; about mid-Nov) are visible. + +## 3. llama.cpp support, quants that fit 128 GB RAM + 24 GB VRAM, and speeds + +### Takeaway +DeepSeek V4.1-Flash (`deepseek41`) support was merged into llama.cpp master on **Oct 25, 2026 (PR #31086, about build b11870)**. Engram-table loading (`--ple`) needs **b12233+ (PR #31185)**, so the user's **b12774 should qualify**. That is an inference: the build was not tested. With the Engram table memory-mapped from NVMe, the **non-Engram part** of Unsloth **UD-IQ1_S (122.4 GB)** fits in 24 GB VRAM + 128 GB RAM. **UD-IQ1_M (139.8 GB)** and ISTA/Abiray **IQ2_XXS (~138 GB backbone)** fit only tightly. Nothing larger fits without streaming experts from SSD. Expect roughly **5–10 tok/s decode in llama.cpp** (inferred; no 4090 + 128 GB report found). Strata's engine and forks report 9–31 tok/s on 12 GB GPUs using expert-streaming and expert-skipping tricks. + +### Cited Findings +**Support status:** +- PR #31086 ("model: DSV4.1 flash") was merged to master by am17an on **Oct 25, 2026** (commit 74bca39). It adds the `deepseek41` arch, Engram support (in-graph row gathering), a DSpark drafter and mtmd vision. Reviewer pwilkin "had to add a small patch to adapt the GSQ GGUFs". — [llama.cpp PR #31086](https://github.com/ggml-org/llama.cpp/pull/31086) +- Build b11870 landed Oct 25, 2026 with the `deepseek41` arch. — [HighVRAM Hardware Watch](https://highvramhardwarewatch.com/deepseek-v4-1-flash-llama-cpp-249gb/) +- The earlier PR #28696 only added conversion, and noted that llama.cpp then had no Engram support. — [llama.cpp PR #28696](https://github.com/ggml-org/llama.cpp/pull/28696) (search snippet) +- **Conflict:** + - Unsloth's guide says to build from **PR #30817**. It says `--ple` needs **b12233+ (PR #31185)**, and that **MXFP8 Engram tables (UD-Q3_K_XL/Q4_K_XL/Q8_K_XL) are misread silently by newer builds** and need the #30817 build. — [Unsloth guide](https://unsloth.ai/docs/models/deepseek-v4.1-flash) + - orcarouter's card says its GGUFs need PR #30817 and are "not in llama.cpp master yet". — [orcarouter](https://huggingface.co/orcarouter/DeepSeek-V4.1-Flash-1017-abliterated-GGUF) + - ISTA's card (as relayed on Oct 25) said its GSQ-RCO GGUFs "do not run in llama.cpp yet" because of metadata and Engram-layout mismatches. — [OpenClaw DC](https://openclawdc.com/blog/deepseek-v4-1-flash-gsq-rco-quants/) + - Abiray's card, by contrast, says its GSQ-RCO-based build runs in llama.cpp b11870+/b12017+. — [Abiray](https://huggingface.co/Abiray/DeepSeek-V4.1-Flash-1017-Uncensored-GSQ-RCO-IQ2_XXS-GGUF) +- An ik_llama.cpp feature request for V4.1-Flash exists (#2438). Status not checked. — [ik_llama.cpp #2438](https://github.com/ikawrakow/ik_llama.cpp/issues/2438) + +**Quant sizes (Unsloth DeepSeek-V4.1-Flash-1017-GGUF):** + +| Quant | Total disk | Engram on SSD | Rest (RAM+VRAM) | Unsloth's RAM+VRAM rec. | +|---|---|---|---|---| +| UD-IQ1_S | 233.0 GB | 110.6 GB (IQ4_NL) | 122.4 GB | 128–145 GB | +| UD-IQ1_M | 250.4 GB | 110.6 GB (IQ4_NL) | 139.8 GB | 128–145 GB | +| UD-IQ2_XXS | 300.5 GB | 135.2 GB (Q5_K) | 165.3 GB | 176–205 GB | +| UD-Q2_K_XL | 334.8 GB | 135.2 GB (Q5_K) | 199.6 GB | 176–205 GB | +| UD-IQ3_XXS | 394.7 GB | 161.3 GB | 233.5 GB | 256–290 GB | +| UD-Q4_K_XL | 500.7 GB | 202.8 GB (MXFP8) | 297.9 GB | 305 GB | + +- Engram can stay on SSD via mmap; keep `--load-mode mmap --lazy-mode on`. The example uses `--override-tensor "per_layer_token_embd.weight=CPU"`. **The guide does not mention `--n-cpu-moe`.** — [Unsloth guide](https://unsloth.ai/docs/models/deepseek-v4.1-flash) +- Unsloth's 6-benchmark average: Q8_K_XL 87.68, Q2_K_XL 87.49, IQ2_XXS 86.63, **IQ1_M 85.55, IQ1_S 83.53**. Aider pass@1: IQ2_XXS 44.38, IQ1_M 42.13, IQ1_S 36.52. — [Unsloth guide](https://unsloth.ai/docs/models/deepseek-v4.1-flash) +- Unsloth's X post: "1-bit retain ~88.2% accuracy while shrinking size from 508GB to 250GB… Run on a 128GB+ RAM device". — [Unsloth on X](https://x.com/UnslothAI/status/2112212605930778830) + +**ISTA-DASLab GSQ-RCO GGUFs (published 2026-10-23, MIT):** +- Sizes (GiB): IQ1_M backbone 112.43 + Engram 103.00 (= 215.43); IQ2_XXS 128.75 + 103.00 (= 231.74); IQ2_XS 144.57 + 103.00 (= 247.57). +- The page says that with a **24 GB NVIDIA GPU + 128 GB RAM, "IQ1_M and IQ2_XXS fit resident; IQ2_XS does not"**. +- Strata's measurements against the original: IQ1_M PPL +21% (KL 0.217, prose +53%), IQ2_XXS PPL +15.5% (KL 0.170), IQ2_XS +7.3% (KL 0.107). ISTA's own scores: IQ1_M 98.7% and IQ2_XXS 100% of base on AIME25/GPQA-D/LCBv6. +- — [OpenClaw DC](https://openclawdc.com/blog/deepseek-v4-1-flash-gsq-rco-quants/) + +**Speeds (none on exactly RTX 4090 + 128 GB DDR5):** +- llama.cpp (PR #31086 review), pwilkin on **R9700 + RTX 5060 + 128 GB RAM**: ~31.3 tok/s prompt (8.3K tokens), **~6.6 tok/s decode**. Offload configuration not stated. — [llama.cpp PR #31086](https://github.com/ggml-org/llama.cpp/pull/31086) +- llama.cpp, orcarouter Mix-256G, CPU only (64 threads of a 192-core server): ~52 tok/s prompt, ~10 tok/s generation. — [orcarouter](https://huggingface.co/orcarouter/DeepSeek-V4.1-Flash-1017-abliterated-GGUF) +- DSX runtime on 2x RTX 3090 + 128 GB DDR4 + NVMe: 30–37 tok/s output, 334–508 tok/s prompt. — [HighVRAM](https://highvramhardwarewatch.com/deepseek-v4-1-flash-llama-cpp-249gb/) +- Strata engine (author's figures): RTX 3060 12 GB 9–11 tok/s, RTX 5070 12 GB 4–6 tok/s. Strata's "Faster" mode uses 5 of 6 experts on ≤16 GB cards. — [OpenClaw DC](https://openclawdc.com/blog/deepseek-v4-1-flash-gsq-rco-quants/) +- kuu-Strata-fork (Strata v0.2.12 base, Windows 11) on **RTX 5070 12 GB + 64 GB DDR5-5600 + PCIe 4 NVMe**, ISTA IQ2_XS with 5/6 experts + DSpark drafter + 128K ctx: + - About 31 tok/s short replies, 35.8 tok/s code, 209–792 tok/s prompt (vs upstream as installed: 6.7 / 4.6–4.9 tok/s). + - Quality cost: KL vs 6-expert full run 0.057 (precise) / 0.183 (fast). GPQA-D 89.4–89.9% vs 90.4% listed. HumanEval 94.5–95.7%. + - — [kuu-Strata-fork](https://github.com/midokino/kuu-Strata-fork) +- Strata 0.2.13 + dsv41 engine on an **RTX 5090 Laptop (24 GiB)**: about 19 tok/s steady-state decode at 256K context (0.1.55 engine 20.8 tok/s vs 0.1.59 17.4 tok/s). That user said IST-DAS 2.00 bpw needs about 240 GB RAM and recommended ≥255 GiB. — [Strata issue #6048](https://github.com/Niko1221/Strata/issues/6048) +- **(older model)** V4-Flash, CPU-only Xeon with 123 GiB RAM, UD-IQ3_XXS: 5.61 tok/s generation, 12.33 tok/s prompt. — [computingforgeeks](https://computingforgeeks.com/run-deepseek-v4-flash-locally/) (search snippet only; page returned 403) +- Some "VRAM calculator" sites claim a 4090 cannot run V4.1-Flash at any quant, or quote ~7 GB at Q4_K_M. These are unreliable and contradict the measured reports above. — [willitrunai](https://willitrunai.com/models/deepseek-v4.1-flash) (search snippet only) + +### Inferences +- **Recommended llama.cpp path for this PC:** Unsloth **UD-IQ1_S** or **UD-IQ1_M** (IQ4_NL Engram, so `--ple` on b12233+ applies and the MXFP8 misread bug does not), plus the matching huihui-ai abliteration patch. Alternatively, the **Abiray IQ2_XXS** uncensored GGUF. In both cases: + - Keep Engram mmapped from NVMe; do not use `--mlock` or `--no-mmap`. + - Put attention, shared experts and dense layers on the 4090. + - Use `-ot` / `--n-cpu-moe` to keep the routed experts in RAM. + - Use a modest context (KV for compressed sparse attention is small per the V4.1 KV-compression paper, but not verified here). +- Budget check: 128 GB RAM minus Windows/desktop (~8–12 GB) leaves about 116 GB, plus about 22 GB usable VRAM = ~138 GB. **UD-IQ1_S (122 GB) fits with room for context. UD-IQ1_M (140 GB) and IQ2_XXS (~138 GB) are borderline** and would likely page some experts from NVMe through the OS page cache, lowering speed. The ISTA page's "fits resident" claim for IQ2_XXS conflicts with the RTX 5090 Laptop user's "~240 GB RAM" figure, which probably counts the Engram file as RAM. +- Speed estimate (inference): decode reads about 16B active params per token. At ~2 bits, mostly from dual-channel DDR5 (~80–90 GB/s), this gives a theoretical ceiling in the low teens of tok/s. Real llama.cpp results on similar setups (6.6 tok/s on 128 GB with R9700+5060; ~10 tok/s CPU-only server) suggest **~5–10 tok/s** for the 4090 + 128 GB DDR5. That is likely slower than the user's current 6B-active Qwen3.8 Q5_K_M. +- The Strata engine (0.2.13 or forks) is clearly faster than mainline llama.cpp on consumer GPUs for this model (19–31 tok/s reported). Part of the gain comes from expert-skipping and drafters that cost some quality. + +### Gaps +- No r/LocalLLaMA (or other) speed report found for exactly RTX 4090 + 128 GB DDR5 with V4.1-Flash in llama.cpp. Searches of Reddit returned nothing relevant. +- Not verified that b12774 loads the Abiray/ISTA GSQ-RCO layout or orcarouter's #30817-layout GGUFs without patches. Sources conflict. +- Not verified whether `--n-cpu-moe` names the `deepseek41` expert tensors correctly; `-ot` regex patterns may be needed. +- V4-Flash (`deepseek4`) llama.cpp merge status was not checked directly. huihui says "use latest llama.cpp". + +## 4. Why Strata dropped DeepSeek after 0.2.13, and running 0.2.13 side by side + +### Takeaway +DeepSeek V4.1-Flash support was removed in Strata **0.2.14 (about Nov 11–15, 2026)** with **no stated reason**. The maintainer (Nov 19) said only that DeepSeek "will come back to Strata soon". Community guesses point to friction over a Project Maya-derived engine (maintenance burden and attribution) but are unconfirmed. Running a **frozen 0.2.13 + strata-dsv41 0.1.59** beside 0.2.24 is possible: users have done side-by-side copies and git worktrees. But the official downgrade path replaces the install, Windows steps are untested by the maintainer, and auto-update must be blocked. It is workable but fragile. A dedicated Windows fork (kuu-Strata-fork) or plain llama.cpp is cleaner. + +### Cited Findings +- docs/DEEPSEEK41.md: "Strata no longer runs DeepSeek V4.1-Flash"; 0.2.13 was the last release that could set it up and start it. Users are told to pick a Qwen model. Existing downloads stay on disk, and Strata shows their folder and size for deletion. **No reason given.** — [Strata DEEPSEEK41.md](https://github.com/Niko1221/Strata/blob/main/docs/DEEPSEEK41.md) +- Release notes for 0.2.18–0.2.21 say the frozen DeepSeek **0.1.59** engines "stay on the 0.2.13 release" (Windows, Linux, Mac), and the update feed downloads them from there. 0.2.23 fixed a bug (#7042) where an Inkling preset was "refused as DeepSeek". The latest release is 0.2.24 (Dec 2), which adds Hy4-Flash and Inkling work. — [Strata releases](https://github.com/Niko1221/Strata/releases) +- Issue #6048 (Nov 15): + - After 0.2.14 (engine 0.1.60), DeepSeek models show "no longer supported", and rolling back only the engine to 0.1.59 does not fix it. The refusal comes from the Control layer (Control 0.1.63 exits before the engine starts). + - Workarounds: + - Full rollback to 0.2.13 Control + engine 0.1.59, deleting `active.json`/`state.json`. + - A "frozen 2.13 copy alongside the current version" (AutoItProjects). + - A git worktree of 0.2.13 (commit 712fec6b4) as control layer with strata-dsv41 0.1.59 (jie3000, Nov 21). + - Forks: strata-dsv41, PolyStrata, project-maya, basalt. + - Commit ac306af removed DeepSeek mentions. + - — [Strata issue #6048](https://github.com/Niko1221/Strata/issues/6048) +- Issue #6072 (Nov 16, "Why was deepseek removed without any warning?"): + - Closed "not planned" on Nov 19. The maintainer says DeepSeek "will come back to Strata soon" and that 0.2.13 is the last version that runs it. + - Downgrade steps (Windows: uninstall then install 0.2.13 without data removal). **Tested only on Linux.** + - To stay on it, avoid "Update Strata" and set `STRATA_UPDATE_CHECK=0`. + - Supported hardware on 0.2.13 includes RTX 30/40/50. + - Community theories: a dispute with the Project Maya fork over MoE support, code porting and attribution (prefaced "I guess"), or the maintenance overhead of keeping the Project Maya import current. Neither was confirmed. + - Project Maya reached Strata-like speeds with `--experts 5`, `--ssd-cache auto`, `--ssd-policy lfu` (3070 8 GB: ~3+ tok/s; 3060 12 GB: ~2.3 → ~8 tok/s). + - — [Strata issue #6072](https://github.com/Niko1221/Strata/issues/6072) +- One write-up dates the removal commit to November 11, 2026. A downstream fork PR is titled "upstream Strata removed the DeepSeek engine". LocalAI removed its Strata DeepSeek entries when updating to Strata v0.2.15. — [marchah/Proxmox PR #144](https://github.com/marchah/Proxmox/pull/144); [LocalAI PR #13265](https://github.com/mudler/LocalAI/pull/13265) (search snippets) +- Issue #5894 reports a 10x prefill regression in the dsv41 chunked-prefill path between engine 0.1.49.2 and 0.1.59.1 (2220 → 225 tok/s at 131K, 2x PRO 6000). — [Strata issue #5894](https://github.com/Niko1221/Strata/issues/5894) (title only) +- The Strata dsv41 engine used ISTA-DASLab GSQ-RCO GGUFs (`--family deepseek41 --model ist-das-2.00bpw`). The Abiray uncensored IQ2_XXS is designed as a drop-in, but the file-size check may reject it. huihui-ai offers a patch for the Strata GSQ-RCO "Coder" quant. — [Abiray](https://huggingface.co/Abiray/DeepSeek-V4.1-Flash-1017-Uncensored-GSQ-RCO-IQ2_XXS-GGUF); [huihui V4.1](https://huggingface.co/huihui-ai/Huihui-DeepSeek-V4.1-Flash-1017-abliterated-GGUF) +- kuu-Strata-fork: an unofficial Windows fork of Strata v0.2.12 that keeps `src/dsv41` / `strata-dsv41.exe`, tuned for a 12 GB GPU + 64 GB RAM (see speeds above). Building needs CUDA 13 + VS 2022 Build Tools. It does not cover abliterated builds or 24 GB/128 GB configs. — [kuu-Strata-fork](https://github.com/midokino/kuu-Strata-fork) + +### Inferences +- **Side by side:** technically feasible, but the risk is shared state. Both versions use Control state files (`active.json`/`state.json`) and an updater. A frozen 0.2.13 copy could auto-update or clash with 0.2.24's model registry. On Windows this path is untested by the maintainer. A self-contained fork (kuu-Strata-fork, Windows-tuned) or llama.cpp-server is the more sensible way to try DeepSeek without endangering the working Qwen setup. +- Because the maintainer says DeepSeek "will come back soon", waiting for upstream re-support is a reasonable option. No date was given. +- The 0.1.59 engine shows decode regressions vs 0.1.55 on a 24 GB laptop GPU (17.4 vs 20.8 tok/s), and a reported prefill regression. The frozen 0.2.13 package is not the best-performing Strata DeepSeek engine. + +### Gaps +- No maintainer statement of the actual reason for removal was found. +- Exact strata-dsv41 0.1.59 asset filenames on the 0.2.13 release page were not visible (the releases page fetch truncated before 0.2.13). +- No report found of a user running 0.2.13 side by side with 0.2.2x on Windows specifically. + +## 5. Benchmarks vs Qwen3.8-Flash-Next (knowledge, reasoning, coding, creative writing, tool use) + +### Takeaway +At full precision, **DeepSeek V4.1-Flash-1017 is moderately stronger than Qwen3.8-Flash-Next** on Artificial Analysis: Intelligence Index 32 (max) / 29 (high) vs 28. The clearest leads are in agentic/tool use, terminal coding and hard reasoning. It also hallucinates less (AA-Omniscience 1 vs −12). The 1–2-bit quants needed to fit this PC remove part of that lead: Unsloth IQ1_M is about 2.4% below Q8 on their average, and Strata measured prose PPL +53% at IQ1_M. The net local gain over a Q5_K_M Qwen3.8 is therefore modest and uncertain. No creative-writing comparison was found. + +### Cited Findings +- Artificial Analysis, V4.1 Flash 1017 (max / high / non-reasoning) vs Qwen3.8-Flash-Next: + +| Metric | DS max | DS high | Qwen3.8 | DS non-reasoning | +|---|---|---|---|---| +| Intelligence Index | 32 | 29 | 28 | 19 | +| AutomationBench-AA (agentic/tool use) | 66.6% | 68.5% | 55.9% | 48.8% | +| Terminal-Bench 4.1 | 32.3% | 29.8% | 24.2% | 9.1% | +| FrontierCode-AA 2.0 | 28.2% | 16.8% | 27.1% | 6.1% | +| HLE-Diamond | 25.3% | 20.8% | 16.3% | 7.1% | +| CritPt v2 (Hard) | 25.0% | 27.5% | 24.5% | 1.0% | +| AA-Omniscience v1.1 | 1 | 2 | −12 | 2 | +| AA-Briefcase (Elo) | 1570 | 1415 | 1567 | 1429 | + + Context: 1M vs 256K. Hosted output speed 161 vs 85 tok/s. Time to first answer token 43.6 s (max) vs 75.0 s. — [Artificial Analysis comparison](https://artificialanalysis.ai/models/comparisons/deepseek-v4-1-flash-1017-vs-qwen3-8-flash-next) +- Novita (V4.1-Flash Max vs Qwen3.8-Flash-Next): DeepSWE v1.1 **74.2% vs 58.7%**, HLE 36.8% vs 35.9%, GPQA Diamond 90.9% vs 91.7% (Qwen ahead). The DeepSeek official scores use reasoning_effort=100. Respan gives GPQA 93.2% (DeepSeek) vs 91.7%. LLM-Stats composite 50.4 vs 47.5 (1017). — [Novita](https://novita.ai/compare/deepseek-vs-qwen); [Respan](https://www.respan.ai/models/compare/deepseek-v4-1-flash-1017-vs-qwen3-8-flash-next); [LLM-Stats](https://llm-stats.com/models/compare/deepseek-v4.1-flash-1017-vs-qwen3.8-flash-next) (search-summary figures, not fetched directly; GPQA sources conflict) +- Quant penalty: + - Unsloth 6-benchmark average: IQ1_M 85.55 and IQ1_S 83.53 vs 87.68 at Q8. Aider: IQ1_S 36.5 vs IQ2_XXS 44.4. — [Unsloth guide](https://unsloth.ai/docs/models/deepseek-v4.1-flash) + - ISTA: IQ1_M 98.7%, IQ2_XXS 100% of base on AIME25/GPQA-D/LCB v6. Strata: IQ1_M PPL +21% (prose +53%), IQ2_XXS +15.5%. — [OpenClaw DC](https://openclawdc.com/blog/deepseek-v4-1-flash-gsq-rco-quants/) + - kuu fork IQ2_XS with 5/6 experts: GPQA-D 89.4–89.9%, HumanEval 94.5–95.7%. — [kuu-Strata-fork](https://github.com/midokino/kuu-Strata-fork) +- Abliteration penalty (unquantized): orcarouter MMLU 0.910 → 0.920. distributedcognition GSM8K 19/20 → 18/20. prem-research (V4-Flash-0731) KL 0.044. — [orcarouter](https://huggingface.co/orcarouter/DeepSeek-V4.1-Flash-1017-abliterated-GGUF); [distributedcognition](https://huggingface.co/distributedcognition/DeepSeek-V4.1-Flash-1017-abliterated); [prem-research](https://huggingface.co/prem-research/DeepSeek-V4-Flash-0731-abliterated) +- Obscurify's security test: the best uncensored V4.1 build (1017 thinking) solved all 8 script-checked tasks; "Flash Uncensored" solved 7. — [Obscurify](https://obscurify.ai/deepseek-uncensored) + +### Inferences +- **Reasoning/knowledge:** DeepSeek leads on HLE and is less prone to hallucination. GPQA is roughly a tie. +- **Coding/agentic/tool use:** DeepSeek has a clear lead (DeepSWE +15 pts, Terminal-Bench +8, AutomationBench +11). This is the strongest reason to switch. +- **Creative writing:** no data. The large prose-PPL hit at IQ1_M (+53%) suggests low-bit DeepSeek may write worse prose than a Q5_K_M Qwen, but that is speculative. +- At the quants that fit (1–2 bit), much of DeepSeek's lead on reasoning benchmarks seems to survive (ISTA 98.7–100%). Fluency and long-form text are more at risk. The Q5_K_M Qwen runs near full quality. +- DeepSeek's thinking mode at "max" is token-hungry. Combined with ~5–10 tok/s local decode, long reasoning answers could take many minutes. + +### Gaps +- No creative-writing or roleplay benchmark (EQ-Bench Creative, etc.) comparing V4.1-Flash with Qwen3.8-Flash-Next was found. +- No benchmark of the **abliterated + 1–2-bit** combination against the user's **uncensored Q5_K_M Qwen3.8**. +- No direct benchmark of the older V4-Flash-0731 against Qwen3.8-Flash-Next was gathered. + +## 6. Are DeepSeek base models already lightly censored? China-specific vs general refusals, and whether uncensoring is needed + +### Takeaway +Stock DeepSeek V4/V4.1 is **not lightly censored**. It refuses most clearly harmful prompts (~70–99% depending on the test) and shows **strong, deterministic China-political censorship** (Tiananmen, criticism of Xi, Taiwan), which became stronger in the official V4-Flash-0731 release. Over-refusal on benign prompts is low (~7%). Uncensoring is therefore needed for general refusals. Abliteration removes those effectively per uploader tests, but no measurement shows it removes **China-political** slant. No R1-1776-style political de-biasing post-train of V4/V4.1 was found. + +### Cited Findings +- CTGT (Aug 5, 2026) **(older)**, comparing V4-Flash preview with V4-Flash-0731 on 152 matched sensitive/control prompt pairs judged by a four-judge panel: + - China-sensitive censorship **57.4 → 63.8**; non-China control censorship **25.4 → 19.8**. + - Mean matched gap +32.0 → +44.0. Sensitive side more censored in 79% → 88% of pairs. + - "The production build is therefore more forthcoming than its preview on everything except China-sensitive topics." + - Comparison: GPT-OSS-120B gap +3.9. + - — [CTGT](https://www.ctgt.ai/research/v4-flash-0731-drift) +- An independent test of V4-Flash found refusals deterministic and confined to Tiananmen and criticism of Xi (5/5 in both languages), plus recitation of official lines on Taiwan ("an inalienable part of China since ancient times") and Xinjiang. — [Strait Signal (Ed Moon)](https://theeastandback.substack.com/p/deepseek-censorship-testing-on-strait) (search snippet only) +- General-harm refusals of stock models: + - V4.1-Flash-1017 weighted harmful refusal 0.874 and benign over-refusal 0.069. — [orcarouter](https://huggingface.co/orcarouter/DeepSeek-V4.1-Flash-1017-abliterated-GGUF) + - V4-Flash-0731: 69% refusal on 800 harmful prompts. — [prem-research](https://huggingface.co/prem-research/DeepSeek-V4-Flash-0731-abliterated) + - V4.1-Flash-1017: 99/100 keyword refusals. — [distributedcognition](https://huggingface.co/distributedcognition/DeepSeek-V4.1-Flash-1017-abliterated) +- Obscurify says official DeepSeek models deflect politically sensitive topics and refuse some everyday edge-case requests. Uncensored V4.1 builds refused none of its 12 prompts. — [Obscurify](https://obscurify.ai/deepseek-uncensored) +- A report on a locally run altered V4.1-Flash-1017 says the edit removes refusals across topics, but its political effects are unmeasured. — search summary only, source not identified; see [Cornford and Cross](https://cornfordandcross.com/digital-ai-art/one-switch-for-safety-and-censorship-inside-local-deepseek/) (not fetched; attribution uncertain) +- **(older, 2025)** On R1: Multiverse's "R1 Slim" claimed to remove Chinese censorship, and a Tufts researcher cautioned such claims may be overstated. The China Media Project found an uncensored R1 still repeats Party-state disinformation on red-line issues such as Taiwan. — [MIT Technology Review](https://www.technologyreview.com/2025/11/19/1128119/quantum-physicists-compress-and-deconsor-deepseekr1/); [China Media Project](https://chinamediaproject.org/2025/06/24/deepseeks-democratic-deficit/) + +### Inferences +- For the user's purpose (an uncensored local assistant), stock V4.1-Flash is **not** credibly low-refusal. An abliterated build is required. +- Abliteration targets the refusal direction. It will likely stop outright refusals on China topics, but trained-in framing (reciting official positions) is a content bias, not a refusal, and probably persists, as it did with uncensored R1. If China-political neutrality matters, Qwen-family models likely have similar issues. That comparison was not researched here. + +### Gaps +- No R1-1776-style (Perplexity) political de-censoring post-train for V4 or V4.1 was found. +- No measurement of China-topic behaviour for any abliterated V4.1 build was found. +- No CTGT-style China-censorship measurement for V4.1-Flash or 1017 (only V4-Flash) was found. diff --git a/docs/research/notes/Uncensored local LLM alternatives/other_families.md b/docs/research/notes/Uncensored local LLM alternatives/other_families.md new file mode 100644 index 0000000..27df963 --- /dev/null +++ b/docs/research/notes/Uncensored local LLM alternatives/other_families.md @@ -0,0 +1,253 @@ +# Uncensored open-weight LLMs outside Qwen/DeepSeek for RTX 4090 24 GB + 128 GB DDR5 (as of 2026-12-03) + +Scope notes for the report writer: +- Hardware budget: 24 GB VRAM + 128 GB RAM, about 152 GB in total. The user's current Qwen3.8-Flash-Next Q5_K_M is about 120 GB, so roughly 135 GB of weights is the practical ceiling before KV cache, OS and the Engram/vision side files. (Inference, not a measured limit.) +- Reference point: Artificial Analysis lists **Qwen3.8-Flash-Next** as 176B total / 6B active, released 26 Aug 2026, with an **Intelligence Index of 28 (v5.0.2)**, ranked #13 of 36 — [AA model page](https://artificialanalysis.ai/models/qwen3-8-flash-next). An AA comparison page surfaced by search showed 29 — [AA GLM vs Qwen comparison](https://artificialanalysis.ai/models/comparisons/glm-5-3-flash-vs-qwen3-8-flash-next). Treat it as 28 to 29. Older index versions gave much larger numbers (40 to 56), so mixing index versions is not valid. +- Hugging Face repo dates, sizes, downloads and architecture tags below come from the HF API (`/api/models/?blobs=true` and `/api/models?search=…&sort=createdAt`), queried 2026-12-03. Downloads and likes are given only as adoption signals. + +## 1. Tencent Hy4-Flash: uncensored versions, formats, capability vs Qwen3.8-Flash-Next, base refusal behaviour + +### Takeaway +Hy4-Flash (220B total, about 12B active, released 17 Nov 2026) has the richest set of refusal-removed builds of any non-Qwen model that fits this machine. Among them is a **drop-in Heretic Strata SQ-128 pack (113.65 GB)** for the user's current Strata setup. There are also several uncensored GGUFs with measured refusal rates, but the GGUFs need a patched llama.cpp. On capability it looks roughly on par with Qwen3.8-Flash-Next: better on agentic, office and computer-use work, worse on coding and speed. No independent leaderboard has scored it yet. The stock model refuses most harmful prompts (73 to 100%). + +### Cited Findings +**Base model** +- tencent/Hy4-flash was created on HF 2026-11-17. It has 220B total parameters, including 64B of "Engram" lookup parameters, with about 12B active per token (text 11.3B + vision 0.43B). That leaves 155.5B excluding Engram, ViT and the DFly2 drafter. It has 1M context, a built-in 0.85B DFly2 speculative drafter, image input, and the Tencent Hy License (custom "other"), not Apache/MIT — [tencent/Hy4-flash](https://huggingface.co/tencent/Hy4-flash) +- On its internal WorkIndex, Tencent reports Hy4-flash at 42.1 vs 39.7 for Hy4-preview, at 1/13 of Hy4-preview's cost per task — [tencent/Hy4-flash](https://huggingface.co/tencent/Hy4-flash) +- Base-model knowledge scores (5-shot): Hy4-flash-Base reaches MMLU 88.7, MMLU-Pro 71.1, SuperGPQA 57.8 and SimpleQA 37.5. DeepSeek-V4-flash-Base reaches 89.7 / 68.6 / 52.5 / 31.3 on the same tests — [tencent/Hy4-flash](https://huggingface.co/tencent/Hy4-flash) +- Hy4-flash is **absent from Artificial Analysis**: the `hy4-flash` model page returned 404, and the open-weights list shows only the full Hy4 (774B/50B) at Intelligence Index 35 — [AA open-source list](https://artificialanalysis.ai/models/open-source) +- **Head-to-head with Qwen3.8-Flash-Next (aggregators, lower confidence):** + - LLM Stats gives a composite of Hy4 flash 41 vs Qwen3.8-Flash-Next 47 — [llm-stats](https://llm-stats.com/models/compare/hy4-flash-vs-qwen3.8-flash-next) + - Canitrun, reading Tencent's table, has Hy4 flash ahead on OSWorld 2.1 (68.1 vs 58.8) and APEX-Agents (63.1 vs 57.6). It has Qwen ahead by 10.3 points on Terminal-Bench 4.0 and 6 points on ProgramBench — [canitrun.dev](https://canitrun.dev/models/compare/hy4-flash-vs-qwen3.8-flash-next/) + - In a hands-on video, Flash-Next ran at about 43 tok/s vs 29 tok/s for Hy4, with total task times about equal — [samuelgregory.co.uk video](https://www.samuelgregory.co.uk/videos/hy4-flash-vs-qwen-38-flash-next) +- **Base refusal behaviour:** + - The original Q4_K_M refuses 85.0% of HarmBench-200 with thinking off — [hletrd/Hy4-flash-Uncensored-GGUF](https://huggingface.co/hletrd/Hy4-flash-Uncensored-GGUF) + - Stock Hy4-flash refused 100/100 harmful prompts — [trohrbaugh/Hy4-flash-heretic-FP8](https://huggingface.co/trohrbaugh/Hy4-flash-heretic-FP8) + - The unpatched Strata SQ-64 pack gave 73 full refusals, 26 partial and 1 compliant out of 100 — [narzh49/Hy4-Flash-Heretic-Strata](https://huggingface.co/narzh49/Hy4-Flash-Heretic-Strata) + +**Uncensored builds (all created between 19 and 28 Nov 2026)** + +| Repo | Format / sizes | Method | Refusal and quality evidence | Runtime | +|---|---|---|---|---| +| [narzh49/Hy4-Flash-Heretic-Strata](https://huggingface.co/narzh49/Hy4-Flash-Heretic-Strata) (2026-11-27; 2 likes, ~0 downloads) | `.strata` **SQ-64 62.03 GB, SQ-128 113.65 GB**. Also needs Strata's unchanged `Hy4-Flash-Engram-Q8.strata` and `Hy4-Flash-Vision.strata` | Heretic edit from trohrbaugh/Hy4-flash-heretic: 102 tensors in layers 8–41 replaced, with the 68 BF16 expert/shared tensors applied as deltas and re-encoded S8_K | On SQ-64, refusals went from 73 full / 26 partial / 1 compliant to **1 full / 41 partial / 58 compliant**. "No capability benchmark on either pack." | Strata: `strata launch --family hy4-flash --model SQ-64 --model-path …`. Not an official Strata or Tencent release | +| [trohrbaugh/Hy4-flash-heretic-FP8](https://huggingface.co/trohrbaugh/Hy4-flash-heretic-FP8) (BF16 parent: trohrbaugh/Hy4-flash-heretic) | FP8/BF16 safetensors | Heretic (refusal-direction ablation) | Refused 100/100 → **2/100**, but **24/100 got a "sanitized substitute"** (for example a baking-soda "bomb"). Thinking mode was not measured. 0/100 benign prompts refused | vLLM on H200. Needs about 256 GB host RAM (Engram 127 GB BF16 pinned), so it does not fit this PC in this format | +| [hletrd/Hy4-flash-Uncensored-GGUF](https://huggingface.co/hletrd/Hy4-flash-Uncensored-GGUF) (2026-11-28) | IQ2_XXS-E4 83.1, IQ2_M-E4 91.9, IQ3_XXS-E4 100.5, IQ3_M-E4 108.1, **Q3_K_M-E4 114.2, IQ4_XS-E4 122.6**, Q4_K_S 155.5, Q4_K_M 161.2, Q5_K_M 176.7 GB. No vision projector or DFly2 | One refusal direction removed | HarmBench-200 (thinking off): 10.5% refused at Q4_K_M vs 85.0% for the original. Alpaca-100 false refusals: 1–3%. At IQ4_XS, held-out KL vs BF16 is 0.238 (top-1 85.4%), against 0.171 (87.7%) for the original IQ4_XS | **Requires llama.cpp PR #32517** | +| [mrfakename/Hy4-flash-abliterated](https://huggingface.co/mrfakename/Hy4-flash-abliterated) + [-GGUF](https://huggingface.co/mrfakename/Hy4-flash-abliterated-GGUF) (2026-11-28) | BF16; GGUF IQ4_XS ~123 GB, Q4_K_M ~161, Q6_K ~193, Q8_0 ~230 GB. Also an **`abliteration-lora.gguf` that applies the edit to any stock GGUF via `--lora`** | Lucid toolkit: rank-1 directional ablation, gain-corrected for sandwich norms, with a 100-trial multi-objective search | Refusals 4/100 in chat and 6/100 in think mode. Harmless first-token KL is 0.233, which the author calls higher than usual (0.05 on Ling-3.2-air). In think mode the model reasons longer: 44/100 replies were unfinished at 768 tokens, vs 2–4 for the original | llama.cpp; see the repo for which builds load Hy4 GGUFs | +| [alesha-pro/Hy4-flash-Uncensored-GGUF](https://huggingface.co/alesha-pro/Hy4-flash-Uncensored-GGUF) (2026-11-19; ~157k downloads) | Q3_K set 150 GB (86.2 GB trunk + 63.4 GB Engram) or IQ2_XXS set 115 GB, plus a 1.04 GB mmproj | Stock weights plus a 4 KB refusal-direction vector projected out of the residual stream at runtime (`HY4F_ABLATE`) | Refusals went from 139 to **32** on AdvBench + JailbreakBench (146 prompts, thinking off) and from 22 to **3** on 24 prompts with thinking on. Top token matches stock 85.7% (two stock runs agree 88.3%), median KL 0.014. "Most refusals are gone, not all." | Runs on the author's "Project Maya" branch, a Strata-based fork (built with `-DSTRATA_ENABLE_CUDA=ON`) | +| [orcarouter/Hy4-flash-abliterated-GGUF](https://huggingface.co/orcarouter/Hy4-flash-abliterated-GGUF) (2026-11-21; gated; ~62k downloads) | "Mix-128G" set of about 138 GB total, plus Mix-256G | Unknown (card is gated) | Not visible | GGUF | + +- Other uncensored Hy4 repos were not examined: dealign/Hy4-UNCENSORED-JANGHT2.4, IndrasMirror/Hy4-flash-XQ-Uncensored, Fuxfantx/Hy4-flash-Uncensored-Compact and marc-in-berlin/Hy4-flash-abliterated-oQ8e-mtp (MLX) — [HF search "uncensored"](https://huggingface.co/api/models?search=uncensored&sort=createdAt&direction=-1) +- **Strata stock packs:** Hy4-Flash SQ-64 is 62.0 GB (64 GB RAM + 8 GB GPU), SQ-96 is 89.6 GB and SQ-128 is 113.7 GB (128 GB RAM), each with a 67.6 GB Engram shard on SSD. The Strata models doc lists no abliterated or heretic Hy4 option, and no tok/s on a 4090 — [Strata docs/MODELS.md](https://github.com/Niko1221/Strata/blob/main/docs/MODELS.md) +- **llama.cpp status:** + - PR #32517 ("Model : add hy_v4_flash support", opened 2026-11-18) is **closed without being merged**, per the GitHub API on 2026-12-03 — [PR #32517](https://github.com/ggml-org/llama.cpp/pull/32517) + - An aggregator says that, as of late November, GGUFs need a build from that branch — [orcarouter blog / search summary](https://www.orcarouter.ai/blog/tencent-hy4-flash-local-gguf) + - AngelSlim's own GGUF uses a different arch tag (`hy_v4_next_dfly`) and ships its own llama.cpp patch — [AngelSlim/Hy4-flash-GGUF](https://huggingface.co/AngelSlim/Hy4-flash-GGUF) + - The user's build b12774 was published 2026-11-26 — [release b12774](https://github.com/ggml-org/llama.cpp/releases/tag/b12774) +- **Speed reports:** + - 1× RTX 3090 on the Project Maya engine: Q3_K decodes at 37–54 tok/s with 1,510 tok/s prefill, using 137 GiB RAM (78 GiB with Engram on NVMe). IQ2 with Engram on NVMe decodes at 54–68 tok/s using 45 GiB RAM — [alesha-pro](https://huggingface.co/alesha-pro/Hy4-flash-Uncensored-GGUF) + - RTX 4090D about 58 tok/s through Strata offload, per an aggregator — [besthub.dev](https://www.besthub.dev/articles/hy4-flash-quantized-410gib-125gib-24gb-gpu-hits-58-tok-s-via-offload-can-your-hardware-run-it-bb307e2e2d98) + - llama.cpp on an M5 Max 128 GB: Q3_K about 47–50 tok/s, Q4_K_M about 44–48 tok/s. DGX Spark with patched llama.cpp and MTP: about 34.7 tok/s — [search summary of AngelSlim card](https://huggingface.co/AngelSlim/Hy4-flash-GGUF); [outsmartchad DGX Spark repo](https://github.com/outsmartchad/hy4-flash-single-dgx-spark-llamacpp) +- AngelSlim reports its Q3_K within 0.5 points of BF16 on its own test suites (as quoted by alesha-pro) — [alesha-pro](https://huggingface.co/alesha-pro/Hy4-flash-Uncensored-GGUF) + +### Inferences +- **Strata:** narzh49's SQ-128 heretic pack (113.65 GB) is the lowest-friction swap. It is the same pack size the user already runs, with the Heretic edit written in. Two risks: nobody has benchmarked its capability, and it has almost no downloads yet. Its own test shows 41% "partial refusals", so it is less fully uncensored than the GGUF abliterations. +- **llama.cpp:** hletrd **IQ4_XS-E4 (122.6 GB)** or Q3_K_M-E4 (114.2 GB) are the closest in size to the user's 120 GB Qwen file. mrfakename's IQ4_XS (~123 GB) is the alternative. Both need a Hy4-capable llama.cpp, i.e. the unmerged PR #32517 branch or AngelSlim's patch, so plain b12774 will probably not load `hy_v4_flash` GGUFs. Users should verify this against the build they already use for AngelSlim's Q4_K_M. +- mrfakename's abliteration LoRA could in principle uncensor the user's existing AngelSlim GGUF without a new download. AngelSlim uses a different arch tag (`hy_v4_next_dfly` vs `hy_v4_flash`), so that compatibility is untested. +- On capability, Hy4-flash is plausibly on par with Qwen3.8-Flash-Next overall: stronger on agentic, office and computer use, and on knowledge per the base MMLU-Pro and SimpleQA. It is weaker on terminal coding and runs about 2× the active parameters, so it is slower per token. + +### Gaps +- No independent (Artificial Analysis or LMArena) score for Hy4-flash, and no benchmark of any uncensored Hy4 build on capability tasks (only refusal rates and KL). +- No measured llama.cpp tok/s on an RTX 4090 + 128 GB DDR5 for Hy4-flash GGUFs. +- Whether a replacement for PR #32517 has been merged into mainline could not be confirmed. A title search for "hy4" found only the merged Hy4-preview conversion refactor, #28451. +- The orcarouter abliterated GGUF card is gated, so its method and metrics are unknown. + +## 2. Inkling 2 Mini (Thinking Machines): uncensored versions and capability + +### Takeaway +Inkling 2 Mini (26.4B total, 5.4B effective active, looped transformer, Apache-2.0, released 20 Nov 2026) has dozens of abliterated, Heretic and "Unbound" builds, including Strata-format ones. It fits entirely in 24 GB VRAM, so it is fast. But independent scoring puts it **well below Qwen3.8-Flash-Next**: AA Index v5.0 of 20.1, against 28. It is a speed and agentic-coding option, not a like-for-like replacement. + +### Cited Findings +- **Release and architecture:** released November 20, 2026. Text + image in, 1M context. A looped transformer: "three passes, there are 5.4B effective active parameters per token." Officially supported by llama.cpp and Unsloth GGUFs — [thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini) +- **Vendor benchmark table** (Inkling 2 Mini vs Qwen3.8-27B): + - AA Index (v5.0): 20.1 vs 20.1. For context, the same table gives Gemma 4 31B 4.4 and Nemotron 3.5 Super VL 13.6. + - SWE-bench Verified (bash only): 79.2% vs 77.8% + - DeepSWE v1.1: 48.2% vs 42.2% + - Terminal Bench v2.1: 71.6% vs 73.0% + - BrowseComp: 79.0% vs 61.6% + - MCP Atlas: 82.7% vs 77.3% + - HLE-Diamond: 15.2% vs 15.3% + - LongBench v2: 66.9% vs 52.3% + - [thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini) +- **Safety tuning:** Thinking Machines applied "an extra phase of alignment training using on-policy distillation", so the stock model is safety-tuned — [thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini) +- **Bigger sibling:** Inkling 2 Small (594B / 17B) scores AA 31, but it is far too large for 152 GB at usable quants — [AA open-source list](https://artificialanalysis.ai/models/open-source). No uncensored Small build appeared in HF searches. +- **Uncensored builds:** + - [huihui-ai/Huihui-Inkling-2-Mini-abliterated](https://huggingface.co/huihui-ai/Huihui-Inkling-2-Mini-abliterated) and [-GGUF](https://huggingface.co/huihui-ai/Huihui-Inkling-2-Mini-abliterated-GGUF) (2026-12-01; ~17.6k downloads). Method: Sumandora's remove-refusals-with-transformers abliteration; no refusal statistics published. GGUFs: Unsloth UD-Q4_K_XL ~18 GB, UD-Q8_K_XL ~23 GB, Q8_0 ~28 GB, BF16 ~53 GB. + - [Abiray/Inkling-2-Mini-Unbound-Uncensored-v3.1-GSQ-RCO-GGUF](https://huggingface.co/Abiray/Inkling-2-Mini-Unbound-Uncensored-v3.1-GSQ-RCO-GGUF) (2026-11-29; 114 likes, ~22k downloads). Based on nokeepai/Inkling-2-Mini-Unbound v3.1, which claims 0/263 refusals and 87.8% useful answers on held-out sensitive requests with thinking on. IQ3_S is 11.64 GB with KLD 0.042 vs the Unbound Q8_0. The card points to a newer sibling, Abiray/Inkling-2-Mini-Uncensored-Ortho-GGUF. + - Heretic builds include [darrellbest/Inkling-2-Mini-Heretic-GGUF](https://huggingface.co/darrellbest/Inkling-2-Mini-Heretic-GGUF) and mradermacher/Inkling-2-Mini-Heretic-i1-GGUF. + - Strata-format uncensored packs include paralaif/Inkling-2-Mini-Uncensored-pi-Strata, Sidetwack/Inkling-2-Mini-Strata-CHiPS-Abliterated and tatshitcrazy2/Inkling-2-Mini-abliterated-Strata-bucket (unexamined). + - Sources for the last two items: [HF searches: abliterated / heretic / uncensored](https://huggingface.co/api/models?search=Inkling&sort=createdAt&direction=-1) +- **llama.cpp support:** mainline support is active. inkling2 graph and clip PRs #32948 and #32940 were merged on 24–25 Nov 2026 — [PR #32948](https://github.com/ggml-org/llama.cpp/pull/32948) +- **Strata packs:** SQ-20 is 19.4 GB (for 24 GB GPUs), and Unsloth UD-Q4_K_XL is 17.6 GB. The doc gives no 4090 tok/s — [Strata docs/MODELS.md](https://github.com/Niko1221/Strata/blob/main/docs/MODELS.md) + +### Inferences +- An uncensored Inkling 2 Mini at Q6/Q8 (23–28 GB) would sit almost entirely in the 4090's VRAM. It would likely be several times faster than any 120 GB MoE offload setup. On AA it matches Qwen3.8-27B, not Qwen3.8-Flash-Next, so expect a knowledge and reasoning downgrade, offset by strong agentic coding and long-context scores. +- huihui's abliteration publishes no refusal or KL numbers. The Unbound/Abiray line publishes more evidence, but it is a community LoRA plus graft chain, so its quality risk is higher. + +### Gaps +- No independent measurement of capability loss for any uncensored Inkling 2 Mini build. +- No published 4090 tok/s for Inkling 2 Mini. + +## 3. Other families (GLM, Kimi, MiniMax, Mistral, gpt-oss, Llama, Gemma, Nemotron, Hermes, ERNIE, Ling, Seed-OSS, StepFun, new Oct–Dec 2026) that fit 24 GB + 128 GB with uncensored variants + +### Takeaway +Besides Hy4-Flash, three fit with uncensored GGUFs: **GLM-5.3-Flash** (AA 28, equal to Qwen3.8-Flash-Next, but only at 2–3 bits on this machine), **Ling-3.2-air** (124B/5.5B, fits at Q6_K, with a well-measured abliteration but unverified capability) and **Mistral Small 4 119B** (older, March 2026, with measured capability loss). The strongest new model by AA score that is roughly the right size, **ERNIE 5.5 Flash Preview** (AA 31), cannot be used yet: there is no llama.cpp support and no abliterated GGUF. MiMo-V2.6-Flash has a high-quality uncensored GGUF but is too big at 167 GB. Kimi K3.1, Ergo, Mistral Large 4, Step-5 and MiniMax M3.1-Flash are too large. + +### Cited Findings +**Candidates that fit (uncensored variant exists)** + +| Model (vendor, base release) | Size / license | Uncensored repo(s), date, method | Refusal / quality evidence | GGUF sizes that fit | llama.cpp status | Capability evidence | +|---|---|---|---|---|---|---| +| **GLM-5.3-Flash** (Zhipu/zai-org, HF 2026-08-25) | 320B total / 18B active, multimodal, hybrid sparse + linear attention, MIT — [zai-org/GLM-5.3-Flash](https://huggingface.co/zai-org/GLM-5.3-Flash) | [kcarly/Huihui-GLM-5.3-Flash-abliterated-GGUF](https://huggingface.co/kcarly/Huihui-GLM-5.3-Flash-abliterated-GGUF) (2026-12-01; card titled huihui-ai/Huihui-GLM-5.3-Flash-abliterated-GGUF), huihui abliteration (Sumandora method). Others: takmal/GLM-5.3-Flash-Uncensored-4.0bpw-h6-exl3, CanadaApollo6/GLM-5.3-Flash-Uncensored-M3TiS-v2, masudbro07 FP8, DmitryDB/GLM-5.3-Flash-apex-flash-1-abliterated-Maya-GGUF — [HF search](https://huggingface.co/api/models?search=abliterated&sort=createdAt&direction=-1) | None published by huihui | UD-IQ1_S 93, UD-IQ2_XXS 102, **UD-Q2_K_XL 109, UD-IQ3_XXS 120**, UD-Q3_K_XL 148, UD-IQ4_XS 157 GB — [kcarly GGUF](https://huggingface.co/kcarly/Huihui-GLM-5.3-Flash-abliterated-GGUF) | `glm5-next` support merged 2026-09-30 ([PR #27773](https://github.com/ggml-org/llama.cpp/pull/27773)), so it is in b12774. The huihui card also links an Unsloth branch. | AA: GLM-5.3-Flash **28** vs Qwen3.8-Flash-Next 29 on the comparison page — [AA comparison](https://artificialanalysis.ai/models/comparisons/glm-5-3-flash-vs-qwen3-8-flash-next). Baidu's table has GLM-5.3-Flash at Terminal-Bench 4.0 35.8, DeepSWE 63.4, HLE 39.9, MCP-Atlas 78.8 — [baidu/ERNIE-5.5-Flash-Preview](https://huggingface.co/baidu/ERNIE-5.5-Flash-Preview) | +| **Ling-3.2-air** (inclusionAI / Ant, HF 2026-11-23) | 124B total / 5.5B active (128B in safetensors), multimodal, MIT — [inclusionAI/Ling-3.2-air](https://huggingface.co/inclusionAI/Ling-3.2-air) | [mrfakename/Ling-3.2-air-abliterated](https://huggingface.co/mrfakename/Ling-3.2-air-abliterated) + [-GGUF](https://huggingface.co/mrfakename/Ling-3.2-air-abliterated-GGUF) (2026-11-27), Lucid rank-1 directional ablation. Also mradermacher/Ling-3.2-air-abliterated(-i1)-GGUF and dealignai Ling-3.2-Air ABLITERATED/UNCENSORED MXFP4/FP8 | Refusals **3/100 in chat, 4/100 in think mode, harmless KL 0.051**, the lowest-damage edit among these. Includes a rank-1 `abliteration-lora.gguf` for stock GGUFs | IQ4_XS 71, Q4_K_M 80, **Q6_K 111**, Q8_0 136 GB | `bailingmoe3` support merged 2026-08-17 ([PR #26608](https://github.com/ggml-org/llama.cpp/pull/26608)). A convert-side fix for the VL MLA RoPE permutation is still open ([PR #33360](https://github.com/ggml-org/llama.cpp/pull/33360), 2026-11-30). | Vendor chart compares it with Qwen3.8-Flash-Next, Qwen3.8-27B and others, but the scores are only in an image. Aggregator: [ai-tldr search snippet](https://ai-tldr.dev/models/ling-3-2-air/). Its predecessor Ling 3.0 Flash scored below Qwen3.8-Flash-Next on AA (38 vs 56 on an older index version) — [AA comparison](https://artificialanalysis.ai/models/comparisons/qwen3-8-flash-next-vs-ling-3-0-flash) | +| **Mistral Small 4 119B** (Mistral, `Mistral-Small-4-119B-2603` = March 2026, **older**) | 119.4B MoE, 128 experts top-4 + 1 shared, Apache-2.0 | [brutalai/mistral-small-4-119b-abliterated](https://huggingface.co/brutalai/mistral-small-4-119b-abliterated) (FP8) + [-GGUF](https://huggingface.co/brutalai/mistral-small-4-119b-abliterated-GGUF) (2026-12-02). Direct edit of the attention output projections only. | Harmful prompts answered went from 10 to **71/100**, refused from 84 to 25/100, and XSTest false refusals from 16 to 10 of 250. **LiveCodeBench fell from 66 to 53 of 175**; IFBench rose from 106 to 110 | Q4_K_M 72, Q5_K_M 85, Q8_0 126 GB | GGUF arch `deepseek2` (MLA), so mainline loads it | No AA score found | +| **Inkling 2 Mini** | see §2 | see §2 | see §2 | 11–28 GB | mainline | AA 20.1 | + +**Strong or new models that do not currently work for this user** +- **ERNIE 5.5 Flash Preview** (Baidu, HF 2026-11-23, Apache-2.0): + - 280B total / 14B active, 1M context. Routed experts are natively MXFP4 (W4A8 quantization-aware training). Baidu calls it an intermediate post-training checkpoint — [baidu/ERNIE-5.5-Flash-Preview](https://huggingface.co/baidu/ERNIE-5.5-Flash-Preview) + - **AA Intelligence Index 31**, above Qwen3.8-Flash-Next's 28–29 — [AA open-source list](https://artificialanalysis.ai/models/open-source) + - Baidu's table: Terminal-Bench 4.0 46.5, DeepSWE 71.2, HLE 46.4, MCP-Atlas 84.6 (GLM-5.3-Flash: 35.8 / 63.4 / 39.9 / 78.8) + - Uncensored builds are safetensors only: dealignai/ERNIE-5.5-Flash-Preview-ABLITERATED-MXFP4 (2026-11-26) and -NVFP4 (2026-11-28) — [HF search](https://huggingface.co/api/models?search=abliterated&sort=createdAt&direction=-1) + - The llama.cpp PR "model : add ERNIE 5.5" (#31925, opened 2026-11-09) is **still open** — [PR #31925](https://github.com/ggml-org/llama.cpp/pull/31925) +- **MiMo-V2.6-Flash-RL** (Xiaomi, HF 2026-09-21, MIT): + - 309B / 15B active, 1M context + - [hletrd/MiMo-V2.6-Flash-RL-Uncensored-GGUF](https://huggingface.co/hletrd/MiMo-V2.6-Flash-RL-Uncensored-GGUF) (2026-12-02): HarmBench-200 refusals 0.0% vs 92.5% original, held-out KL 0.0088 (top-1 96.4%), a very clean edit + - **MXFP4 only, 167.37 GB**, which is over the 152 GB budget + - The card's quickstart uses `--cpu-moe` and says it needs "llama.cpp v0.5.0 or newer" + - No AA score found for Flash; MiMo-V2.6-Pro (1T) scores 30 — [AA open-source list](https://artificialanalysis.ai/models/open-source) +- **MiniMax-M3.1-Flash** (MiniMax, HF 2026-10-17): + - About 428B total / 23B active, 1M context, multimodal — [MiniMaxAI/MiniMax-M3.1-Flash](https://huggingface.co/MiniMaxAI/MiniMax-M3.1-Flash) + - llama.cpp "support MiniMax-M3.1" was merged 2026-11-15 — [PR #32301](https://github.com/ggml-org/llama.cpp/pull/32301) + - **No uncensored or abliterated build appeared** in the latest 200 results for "abliterated", "uncensored" or "heretic" on HF + - Too big except at about 2 bits (inference) +- **Kimi K3.1 Pro** (Moonshot, HF 2026-11-02): AA 47, but 2.8T / 104B. Abliterated builds exist (logitshq/Kimi-K3.1-Pro-Abliterated, AMAImedia MXFP4, bboy3334 IQ2_XXS) but are far beyond 152 GB — [AA](https://artificialanalysis.ai/models/open-source); [HF search](https://huggingface.co/api/models?search=abliterated&sort=createdAt&direction=-1). Kimi-Linear-48B-A3B (Oct 2025, **older**) has ashwin-sreedhar/Kimi-Linear-48B-A3B-Instruct-abliterated-v2-bf16 (2026-12-01). +- **Amazon Ergo** (new): 1.1T / 55B, AA 38. [OpenUncensored/Ergo-Uncensored](https://huggingface.co/OpenUncensored/Ergo-Uncensored) (2026-12-01) cut refusals from 100 to 2/100 (thinking off) and from 99 to 0/100 (thinking on), with MMLU-300 falling from 83.0% to 79.3%. At 626 GB MXFP4 it does not fit. +- **Mistral Large 4 1T-A52B** (2026-09-30): AA 26. bigfat/Huihui-Mistral-Large-4-1T-A52B-abliterated-GGUF exists but does not fit — [AA](https://artificialanalysis.ai/models/open-source) +- **StepFun:** + - Step-3.7-Flash (2026-05-23, Apache-2.0): 198B / about 11B active, 256K context. The card lists llama.cpp support via StepFun's own fork, plus official GGUFs — [stepfun-ai/Step-3.7-Flash](https://huggingface.co/stepfun-ai/Step-3.7-Flash). No uncensored build found. + - Step-5-Preview (2026-09-20) is 604B, too big — [HF API](https://huggingface.co/api/models?author=stepfun-ai&sort=createdAt&direction=-1) + +**Smaller or older families (fit easily, uncensored builds exist, but clearly weaker than Qwen3.8-Flash-Next)** +- **gpt-oss** (OpenAI): there have been no new open-weight chat LLMs since gpt-oss-20b/120b (2025-08-04, **older**). The only later releases are gpt-oss-safeguard (2025-09) and privacy-filter (2026-04) — [HF API openai](https://huggingface.co/api/models?author=openai&sort=createdAt&direction=-1). Fresh abliterated builds: ashwin-sreedhar/GPT-OSS-120B-abliterated-v2-bf16 (2026-12-02) and -20B (2026-12-01) — [HF search](https://huggingface.co/api/models?search=abliterated&sort=createdAt&direction=-1) +- **Llama** (Meta): the newest meta-llama LLMs on HF are Llama 4 Scout/Maverick (April 2025, **older**); no Oct–Dec 2026 release — [HF API meta-llama](https://huggingface.co/api/models?author=meta-llama&sort=createdAt&direction=-1) +- **Gemma 4** (Google): many Heretic and abliterated builds exist, e.g. [llmfan46/gemma-4-31B-it-uncensored-heretic-v2-GGUF](https://huggingface.co/llmfan46/gemma-4-31B-it-uncensored-heretic-v2-GGUF) and 26B-A4B heretic GGUFs (late Nov 2026) — [HF search heretic](https://huggingface.co/api/models?search=heretic&sort=createdAt&direction=-1). The Inkling card lists Gemma 4 31B at **AA v5.0 4.4** — [Inkling-2-Mini card](https://huggingface.co/thinkingmachines/Inkling-2-Mini) +- **Nemotron** (NVIDIA): Nemotron 3.5 Super VL (124.5B / 12B) scores AA 14 — [AA](https://artificialanalysis.ai/models/open-source). t2fn/Nemotron-3.5-Lightning-30B-A3B-heretic (2026-11-30) exists — [HF search heretic](https://huggingface.co/api/models?search=heretic&sort=createdAt&direction=-1) +- **Hermes / Nous:** + - The newest Hermes is Hermes-4.3-36B (2025-11, **older**) + - NousResearch/Arete-27B (2026-11-06) is a **Qwen3.8-27B fine-tune**, so it is excluded as Qwen-family — [HF API Nous](https://huggingface.co/api/models?author=NousResearch&sort=createdAt&direction=-1) +- **Seed-OSS** (ByteDance): no new open chat LLM from ByteDance-Seed in Oct–Dec 2026 on HF; recent uploads are research artifacts (Cola2, SAEs, etc.) — [HF API ByteDance-Seed](https://huggingface.co/api/models?author=ByteDance-Seed&sort=createdAt&direction=-1) +- **Other new Nov 2026 open models with abliterated GGUFs, all small:** + - GigaChat4-37B-A4B (Sber): [skyzer4ever/GigaChat4-37B-A4B-abliterated-GGUF](https://huggingface.co/skyzer4ever/GigaChat4-37B-A4B-abliterated-GGUF), IQ4_XS 21 / Q4_K_M 24 / Q8_0 41 GB + - Muse Glimmer 30B (AA v5.0 6.3 per the Inkling card) + - IBM granite-4.2 3B/8B abliterated + - Ornith-1.5-35B-A3B, which Strata says shares the Qwen3.6 architecture, so treat it as likely Qwen-derived + - Sources: [HF search](https://huggingface.co/api/models?search=abliterated&sort=createdAt&direction=-1); [Strata docs](https://github.com/Niko1221/Strata/blob/main/docs/MODELS.md) +- **Qwen-derived, excluded:** "Signal-2-Flash-Next-Gyro-Abliterated-GGUF" (125.7B, GGUF arch `qwen4exp`, Q2_0 130 GB) — [onemunanoyo repo](https://huggingface.co/onemunanoyo/Signal-2-Flash-Next-Gyro-Abliterated-GGUF) +- **Unclear provenance:** "apex-flash-1" (cantina-security) is a 321B GLM-5.3-Flash-sized model with an abliterated NVFP4 build ([kadiraltan/apex-flash-1-abliterated-NVFP4](https://huggingface.co/kadiraltan/apex-flash-1-abliterated-NVFP4), 2026-12-03). Its base and capability were not verified. + +### Inferences +- "Credibly low-refusal out of the box" does not apply to any of the strong 2026 candidates. Measured stock refusal rates are high: Mistral Small 4 refuses 84/100 harmful prompts, MiMo 92.5%, Hy4 85–100%, Ergo 99–100%. A refusal-edited build is needed in every case. +- GLM-5.3-Flash is the only verified **AA-parity** model with an uncensored GGUF that loads in mainline llama.cpp. To fit, it needs about 2.7–3 bpw (UD-Q2_K_XL 109 GB or UD-IQ3_XXS 120 GB), against the user's Qwen at Q5. Its 18B active (vs 6B for Qwen) makes it much slower. The huihui abliteration publishes no KL or refusal metrics. +- Ling-3.2-air is the best-documented abliteration (KL 0.051) and fits at Q6_K. With 5.5B active it should be comparable in speed to Qwen3.8-Flash-Next, but with about 30% fewer total parameters (124B vs 176B). Expect a step down in knowledge unless inclusionAI's chart says otherwise; that is unverified. +- ERNIE 5.5 Flash Preview is the model to watch. Once PR #31925 merges, someone would need to convert dealignai's abliterated MXFP4 weights to GGUF. At about 280B with MXFP4 experts it would be roughly 150 GB or more (estimate), so it may still not fit. + +### Gaps +- No AA (v5) scores were found for Hy4-flash, Ling-3.2-air, MiniMax-M3.1-Flash, MiMo-V2.6-Flash, Step-3.7-Flash, Mistral Small 4 or gpt-oss-120b on the current index version. +- Ling-3.2-air's vendor benchmark scores are only in an image. The ai-tldr page returned 403. +- No capability benchmarks (MMLU, coding, etc.) were published for the huihui GLM-5.3-Flash abliteration. +- LMArena and LiveBench were not checked within the tool budget. +- No Reddit r/LocalLLaMA threads from Oct–Dec 2026 were found by search for these specific uncensored builds. + +## 4. llama.cpp support, fitting quants and reported speed with MoE offload on a 24 GB GPU + +### Takeaway +In mainline llama.cpp b12774 (published 2026-11-26), GLM-5.3-Flash, Ling-3.2-air (bailingmoe3), Mistral Small 4 (deepseek2 arch), Inkling 2 Mini and MiniMax-M3.1 load. Hy4-Flash `hy_v4_flash` GGUFs need an unmerged PR branch or AngelSlim's patch, and ERNIE 5.5 is unsupported. Measured 24 GB offload speeds are sparse. For Hy4-Flash on Strata-type engines with one 24 GB card, reports are about 37–68 tok/s. For GLM-5.3-Flash on llama.cpp with a 4090 + 128 GB, reports are about 6–12 tok/s. + +### Cited Findings +- b12774 was published 2026-11-26T09:13Z — [release b12774](https://github.com/ggml-org/llama.cpp/releases/tag/b12774) +- **Support status** (GitHub API, 2026-12-03): + - GLM-5.3-Flash `glm5-next`: merged 2026-09-30 — [#27773](https://github.com/ggml-org/llama.cpp/pull/27773) + - BailingMoE3 (Ling): merged 2026-08-17 — [#26608](https://github.com/ggml-org/llama.cpp/pull/26608) + - MiniMax-M3.1: merged 2026-11-15 — [#32301](https://github.com/ggml-org/llama.cpp/pull/32301) + - inkling2 fixes: merged 2026-11-24/25 — [#32948](https://github.com/ggml-org/llama.cpp/pull/32948) + - Hy4-flash: PR closed unmerged — [#32517](https://github.com/ggml-org/llama.cpp/pull/32517) + - ERNIE 5.5: PR open — [#31925](https://github.com/ggml-org/llama.cpp/pull/31925) +- **GLM-5.3-Flash speeds:** + - One tester with a 24 GB RTX 4090 and 128 GB DDR5 reported about 300 tok/s prefill and **6–9 tok/s generation** on IQ3_S at 256K context. This is anecdotal and described as the only consumer data point. Search summaries attribute it to these guides: [modemguides](https://www.modemguides.com/blogs/ai-infrastructure/run-glm-5-3-flash-locally-hardware-reality-check), [deai.org](https://www.deai.org/news/run-glm-5-3-flash-llama-cpp) + - A 24 GB L4 + 128 GB RAM reached about 12 tok/s on UD-Q2_K_XL. One headline claims "up to 17.5 tok/s on a 24 GB GPU" — [wpnews](https://wpnews.pro/news/run-glm-5-3-flash-on-a-24-gb-gpu-at-up-to-17-5-tokens-s) + - Sources disagree on when glm5-next support landed. The GitHub API shows it merged 2026-09-30. +- **Hy4-Flash speeds:** see §1. Highlights: 1× 3090 Q3_K at 37–54 tok/s on Project Maya, and a 4090D at about 58 tok/s via Strata offload (aggregator). +- **MiMo-V2.6-Flash uncensored:** the card's quickstart uses `--cpu-moe`. At 167 GB the file exceeds RAM + VRAM, so it would page from NVMe (inference) — [hletrd MiMo](https://huggingface.co/hletrd/MiMo-V2.6-Flash-RL-Uncensored-GGUF) +- **Ling-3.2-air:** no 24 GB offload benchmark was found. Vultr documents Q5_K_M, Q4_K_M, IQ3_M and IQ3_S GGUFs, but only tested SGLang on cloud GPUs — [Vultr docs](https://docs.vultr.com/models/inclusionai-ling-32/ling-3.2-air.md) +- **General offload guidance:** keep `-ngl` at all layers and tune `--n-cpu-moe`. This mostly costs prompt-processing speed, not generation — [search summary of HF offload guide](https://huggingface.co/blog/Doctor-Shotgun/llamacpp-moe-offload-guide) + +### Inferences +- Expected relative decode speed on this rig scales with active parameters: Ling-3.2-air (5.5B) ≈ Qwen3.8-Flash-Next (6B) > Hy4-Flash (~12B) > ERNIE (14B) > GLM-5.3-Flash (18B). This is an inference, not measured. +- The fitting quant for each candidate, at roughly the user's current 120 GB: + +| Model | Fitting quant | Size | +|---|---|---| +| Hy4-Flash | hletrd IQ4_XS-E4 or mrfakename IQ4_XS | ~123 GB | +| Hy4-Flash | Strata heretic SQ-128 | 113.65 GB | +| GLM-5.3-Flash | UD-Q2_K_XL / UD-IQ3_XXS | 109 / 120 GB | +| Ling-3.2-air | Q6_K | 111 GB | +| Mistral Small 4 | Q8_0 / Q5_K_M | 126 / 85 GB | + +### Gaps +- No controlled llama.cpp tok/s on a 4090 + 128 GB DDR5 for any of the uncensored non-Qwen candidates. +- Hy4-Flash GGUF support in b12774 is unconfirmed: the user reportedly runs AngelSlim's GGUF, so they may have a patched build. + +## 5. Which candidates are plausibly at least as capable as Qwen3.8-Flash-Next (knowledge, reasoning, coding, writing, tool use)? + +### Takeaway +Only **Hy4-Flash** and **GLM-5.3-Flash** have evidence of rough parity among models that fit and have uncensored builds. Hy4-Flash is stronger on agentic, office and knowledge work and weaker on coding. GLM-5.3-Flash ties on AA but must be squeezed to 2–3 bits here. **ERNIE 5.5 Flash Preview** scores higher (AA 31) but is not runnable locally yet. Ling-3.2-air, Inkling 2 Mini, Mistral Small 4, gpt-oss, Gemma 4 and Nemotron are likely below Qwen3.8-Flash-Next. + +### Cited Findings +- **AA Intelligence Index v5** (latest available): + +| Model | AA score | Fits this PC? | +|---|---|---| +| Qwen3.8-Flash-Next | 28 ([AA](https://artificialanalysis.ai/models/qwen3-8-flash-next)) or 29 ([AA comparison](https://artificialanalysis.ai/models/comparisons/glm-5-3-flash-vs-qwen3-8-flash-next)) | current model | +| GLM-5.3-Flash | 28 | yes, at 2–3 bits | +| ERNIE 5.5 Flash Preview | 31 ([AA](https://artificialanalysis.ai/models/open-source)) | no | +| Inkling 2 Small | 31 | no | +| Hy4 (full) | 35 | no | +| Inkling 2 Mini | 20.1 (vendor-reported AA v5.0, [card](https://huggingface.co/thinkingmachines/Inkling-2-Mini)) | yes | +| Qwen3.8-27B | 20 | (Qwen, reference) | +| Nemotron 3.5 Super VL | 14 | yes | +| Gemma 4 31B | 4.4 (per Inkling card) | yes | + +- **Hy4-Flash vs Qwen3.8-Flash-Next:** + - LLM Stats composite: 41 vs 47 — [llm-stats](https://llm-stats.com/models/compare/hy4-flash-vs-qwen3.8-flash-next) + - Hy4-Flash leads on OSWorld 2.1 (68.1 vs 58.8) and APEX-Agents (63.1 vs 57.6). Qwen leads Terminal-Bench 4.0 by 10.3 and ProgramBench by 6 — [canitrun](https://canitrun.dev/models/compare/hy4-flash-vs-qwen3.8-flash-next/) +- **Quality cost of uncensoring:** + - Mistral Small 4 abliterated lost about 20% on LiveCodeBench (66 → 53 of 175) — [brutalai](https://huggingface.co/brutalai/mistral-small-4-119b-abliterated) + - Ergo-Uncensored lost 3.7 points on MMLU-300 — [OpenUncensored](https://huggingface.co/OpenUncensored/Ergo-Uncensored) + - Hy4 abliterations show KL of 0.014 (runtime vector, alesha-pro), 0.233 (mrfakename) and about +0.07 held-out KL over the matching stock quant (hletrd IQ4_XS) — [alesha-pro](https://huggingface.co/alesha-pro/Hy4-flash-Uncensored-GGUF), [mrfakename](https://huggingface.co/mrfakename/Hy4-flash-abliterated), [hletrd](https://huggingface.co/hletrd/Hy4-flash-Uncensored-GGUF) + - Ling-3.2-air abliteration KL is 0.051 — [mrfakename Ling](https://huggingface.co/mrfakename/Ling-3.2-air-abliterated) + - MiMo uncensored held-out KL is 0.0088 — [hletrd MiMo](https://huggingface.co/hletrd/MiMo-V2.6-Flash-RL-Uncensored-GGUF) + +### Inferences +- **Ranking for this user** (judgement from the evidence above): + 1. **Hy4-Flash uncensored.** In Strata, use narzh49's heretic SQ-128 (113.65 GB). In llama.cpp, use hletrd IQ4_XS-E4 (122.6 GB) or mrfakename IQ4_XS on a Hy4-capable build. Hy4-Flash is roughly peer-level with Qwen3.8-Flash-Next, with different strengths, and the user already runs it. + 2. **GLM-5.3-Flash huihui-abliterated UD-Q2_K_XL / UD-IQ3_XXS.** AA parity at full precision, but heavy quantization and about 6–12 tok/s make it likely to feel worse than the user's Q5 Qwen in practice. + 3. **Ling-3.2-air abliterated Q6_K** (111 GB). Best-documented, low-damage abliteration, and fast. Its capability relative to Qwen3.8-Flash-Next is unverified and likely lower. + 4. **Inkling 2 Mini uncensored** (≤28 GB, all in VRAM). Fastest, and strong at agentic coding, but about AA 20 vs 28. + 5. **Mistral Small 4 abliterated** (older, measured coding loss). Fallback only. +- **Watch list:** ERNIE 5.5 Flash (pending llama.cpp PR #31925 and a GGUF of the abliterated weights), MiniMax-M3.1-Flash (no uncensored build yet) and MiMo-V2.6-Flash (needs a smaller-than-MXFP4 uncensored quant, under about 135 GB). +- **Writing quality:** no source in this research measured creative or writing quality for any candidate. Treat it as unknown. + +### Gaps +- No apples-to-apples benchmark of any uncensored non-Qwen build against Qwen3.8-Flash-Next (uncensored or stock). +- No writing or creative-writing leaderboard data was gathered. LMArena and EQ-Bench were not checked within the tool budget. +- The capability effect of Heretic/abliteration on Hy4-Flash knowledge and reasoning is unmeasured. Only refusal rates and KL are published. diff --git a/docs/research/notes/Uncensored local LLM alternatives/qwen38_family.md b/docs/research/notes/Uncensored local LLM alternatives/qwen38_family.md new file mode 100644 index 0000000..e71c3f0 --- /dev/null +++ b/docs/research/notes/Uncensored local LLM alternatives/qwen38_family.md @@ -0,0 +1,451 @@ +# Uncensored / abliterated models in the Qwen 3.8 family (and close Qwen-architecture relatives): options to replace orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF Q5_K_M, as of 2026-12-03 + +Scope notes for the report writer: +- Target machine: RTX 4090 24 GB, i7-14700, 128 GB DDR5, Windows 10. Engines: Strata v0.2.24 (streams MoE experts from RAM/SSD) and llama.cpp b12774 (CUDA 12.4). +- Hugging Face mostly shows relative dates ("updated N days ago"). Calendar dates below marked "~" are converted from those using 2026-12-03 as today, so they are approximate. Several OrcaRouter repos show "Updated 1 day ago" across the whole org. That looks like a bulk model-card edit, not a new model. +- No benchmarks were run for these notes. All capability and refusal numbers are self-reported on model cards unless stated otherwise. + +## Q1. Are there newer or better uncensored versions of Qwen3.8-Flash-Next than OrcaRouter's? (candidates, newest first) + +### Takeaway +OrcaRouter has published no v2 or revision of the Flash-Next weights. Its promised "dynamic-precision" requants have not been confirmed released. The newest credible alternatives are: +- huihui-ai's **abliterated-v2 GGUF** (~Nov 9, 2026), built on Unsloth UD quants, which are a Strata-native family. +- alesha-pro's **runtime refusal-projection kit on the ISTA-DASLab GSQ-RCO packs**, which is Strata-native, has the best-documented KL and refusal measurements, and is the kit the new Looped adapter recommends. +- trohrbaugh's **Heretic** build, which has the best published KL (0.116) but is BF16 safetensors only. + +Most other recent uploads are niche: pruned roleplay builds, fine-tunes that lose capability, or packs for other engines. + +### Cited Findings +**Base model context** +- Qwen/Qwen3.8-Flash-Next was released Aug 26, 2026 under license `qwen-community-1.0`. It is billed as "an experimental preview of the architecture that will underpin Qwen4." [llm-stats](https://llm-stats.com/blog/research/qwen3.8-flash-next-launch) + - About 180B stored parameters: 125B total / 6B active, plus a 51B n-gram (PLE) embedding table and a 4B MTP head. + - 48 layers. 512 experts, 10 routed + 1 shared. + - Gated DeltaNet + Qwen Sparse Attention. + - 262,144 native context, 1M with YaRN. +- Self-reported base benchmarks: LiveCodeBench v6 91.9, GPQA Diamond 91.7, SWE-bench Pro 62.5, IFBench 81.3. [llm-stats](https://llm-stats.com/blog/research/qwen3.8-flash-next-launch) + +**Candidates (newest first where dates are known)** + +1. **huihui-ai/Huihui-Qwen3.8-Flash-Next-abliterated-v2-GGUF** (collection shows this item "24 days ago", ~Nov 9, 2026) + - 1,303,007 downloads last month, 330 likes. [HF](https://huggingface.co/huihui-ai/Huihui-Qwen3.8-Flash-Next-abliterated-v2-GGUF); [collection](https://huggingface.co/collections/huihui-ai/qwen38-abliterated) + - What changed from v1: "the ablation emphasis has been adjusted, and none of the experts have been ablated." It was rebuilt with an imatrix (`imatrix_micro3.gguf` / `calibration3.txt`), and PPL "decreased slightly". No numbers are given. + - Method: abliteration, described by the author as a "crude, proof-of-concept implementation" without TransformerLens. + - No refusal, KL or benchmark numbers are published. + - GGUFs are derived from `unsloth/Qwen3.8-Flash-Next-GGUF`. Listed sizes: + - IQ2_XS 68.2 GB, IQ3_XXS 76 GB, IQ3_S 83.7 GB + - UD-IQ4_XS 93.7 GB, UD-Q4_K_XL (page shows "223 GB", likely a display artifact; Unsloth's UD-Q4_K_XL is 111 GB) + - UD-Q5_K_XL 158 GB, UD-Q6_K_XL 169 GB, Q8_0 188 GB + - Tested with llama.cpp b11540. The card says the unsloth/Swift series "supports the latest versions of both Strata and llama.cpp". + - Strata SHA256-verifies Unsloth files. The card suggests patching `verify_sha256` to return immediately, which skips the integrity check. [HF](https://huggingface.co/huihui-ai/Huihui-Qwen3.8-Flash-Next-abliterated-v2-GGUF) + +2. **huihui-ai/Huihui-Qwen3.8-Flash-Next-abliterated-GGUF (v1)**, updated Oct 11, 2026; BF16 safetensors `Huihui-Qwen3.8-Flash-Next-abliterated` updated Oct 1, 2026 + - 176,240 downloads last month, 224 likes. + - Sizes: IQ2_XS 68.2 GB, IQ3_XXS 76 GB, UD-IQ4_XS 93.7 GB, UD-Q4_K_XL 111 GB, Q8_0 188 GB, BF16 354 GB. + - No refusal or KL numbers. [HF](https://huggingface.co/huihui-ai/Huihui-Qwen3.8-Flash-Next-abliterated-GGUF); [collection](https://huggingface.co/collections/huihui-ai/qwen38-abliterated) + +3. **alesha-pro/Qwen3.8-Flash-Next-abliterated-GSQ-RCO-Strata-GGUF** (collection "Updated Oct 7"; 356,858 downloads last month) + - Not baked weights. The ISTA-DASLab GSQ-RCO GGUFs are left unchanged, and Strata projects out a refusal direction at runtime (`h = h - (h·r) r`). The direction is extracted from the huihui-ai checkpoint and shipped as a 480 KB `Huihui-Qwen3.8-Flash-Next-refusal-direction-r.gguf`. + - Refusals (10 prompts, thinking off/on): + - Original: 10/10, 9/10 (IQ3_S) + - This vector, layers 4-44: 0/10, 0/10 on both IQ3_S and IQ2_XS + - "Strata's bundled vector": 1/10, 0/10 + - KL to BF16 Huihui: + - IQ3_S: original 0.0834, with vector 0.0738 + - IQ2_XS: original 0.2025, with vector 0.1923 + - Reference noise floor: 0.013-0.021 + - Perplexity: IQ3_S 2.525, 2.527 with vector (reference 2.565). + - Agent coding 5/5. Needle-in-a-haystack at 32K/115K: 6/6. + - Sizes: Q2_0 66.4 GB, IQ2_XS 68.0 GB, IQ3_XXS 75.8 GB, IQ3_S 83.6 GB. Each includes a 28.8 GB n-gram table shard. + - Plain llama.cpp loads the files, but its `--control-vector` has no projection mode, so there they behave as the censored original. + - Tested on Strata 0.1.38. [HF](https://huggingface.co/alesha-pro/Qwen3.8-Flash-Next-abliterated-GSQ-RCO-Strata-GGUF) + +4. **trohrbaugh/Qwen3.8-Flash-Next-heretic** (no date shown) + - Made with "Heretic (custom fork) v1.3.0+custom". + - KL divergence 0.1160. Refusals 0/100, against 99/100 for the original. + - Published as BF16 safetensors only (177B). The model tree lists 3 quantized derivatives but doesn't name them. + - 365 downloads last month. [HF](https://huggingface.co/trohrbaugh/Qwen3.8-Flash-Next-heretic) + +5. **mr-andrey-isachenko/Tenet-Qwen3.8-Flash-Next-125B-A6B-Abliterated-Unslop-v3-GGUF** (collection updated "about 9 hours ago"; 10,263 downloads last month) + - A de-refusal plus "de-slop" fine-tune ("Lancet-engine surgical", "bi-projected norm-preserving subspace surgery"). + - Card's own scores, Base → Tenet: + - GPQA Diamond 0.42 → 0.35 + - MMLU-Pro 0.59 → 0.51 + - IFEval strict 0.71 → 0.67 + - MATH-500 0.43 → 0.53 + - GSM8K 0.93 → 0.97 + - Sizes: Q2_K 85.06 GB, IQ3_M 94.27 GB, IQ4_XS 103.34 GB, Q4_K_M 123.03 GB, Q5_K_M 137.85 GB, Q6_K 169.99 GB. + - Apache-2.0. [HF](https://huggingface.co/mr-andrey-isachenko/Tenet-Qwen3.8-Flash-Next-125B-A6B-Abliterated-Unslop-v3-GGUF) + +6. **FangZhangTNS/Qwen3.8-Flash-Next-REAP-Pruned-Abliterated-EN-Writing-RP-V2-GGUF** (plus a ZH twin) (collection updated "about 11 hours ago") + - REAP pruning from 512 to 256 or 192 experts, deliberately removing "coding and non-English experts". + - Abliteration comes from huihui v2 non-expert tensors. + - Sizes: k256-IQ4_XS 62.73 GiB, k256-IQ3_S 59.55 GiB, k192-IQ4_XS 55.08 GiB, k192-IQ3_S 52.70 GiB. + - Ships Strata STRP profiles. Measured on Strata 0.1.63: 48.7 t/s (k256-IQ3_S). + - Blind writing/RP Elo: k256 is statistically at parity with the unpruned 512 anchor. k192 drops to ~1410-1420. [HF](https://huggingface.co/FangZhangTNS/Qwen3.8-Flash-Next-REAP-Pruned-Abliterated-EN-Writing-RP-V2-GGUF) + +7. **Other recent uploads** (all within ~1 day of 2026-12-03, unverified; card details not fetched unless noted) [HF search](https://huggingface.co/models?search=Qwen3.8-Flash-Next&sort=modified) + - `jcgamingonlinux/Qwen3.8-Flash-Next-Uncensored-IK3K-Avalon-GGUF` (113B) + - `Shockem/Qwen3.8-Flash-Next-UD-abliterated-IQ3_XXS-Q8PLE-Basalt` + - `tiraisoft/Qwen3.8-Flash-Next-GSQ-RCO-abliterated-Basalt`. A 70.8 GB pack for the separate "Basalt" engine that requires "an NVIDIA Blackwell GPU (sm_120)", so it will not run on a 4090. [HF](https://huggingface.co/tiraisoft/Qwen3.8-Flash-Next-GSQ-RCO-abliterated-Basalt) + - `quocbao747/Qwen3.8-Flash-Next-Uncensored-NVFP4-2xGB10` (targets 2× DGX Spark) + +8. **Older derivative or other-hardware builds** + - `cygnal/Qwen3.8-Flash-Next-Uncensored-IQ4XS-NGQ4-GGUF` is a requant of the OrcaRouter build. + - `andrevp/Qwen3.8-Flash-Next-exl3-3.05bpw-heretic` is EXL3 with Heretic stored as a small separate file. + - `johnlockejrr/Swift-1.5-Qwen3.8-Flash-Next-heretic-HGN` is Heretic V2 on the Swift 1.5 post-train, built for AMD Strix Halo. + - [search summary](https://huggingface.co/andrevp/Qwen3.8-Flash-Next-exl3-3.05bpw-heretic); [johnlockejrr](https://huggingface.co/johnlockejrr/Swift-1.5-Qwen3.8-Flash-Next-heretic-HGN); [cygnal](https://huggingface.co/cygnal/Qwen3.8-Flash-Next-Uncensored-IQ4XS-NGQ4-GGUF) + +9. **Maximilian228 OrcaRouter NVFP4-GPTQ Strata pack** (name truncated in source as "Maximilian228/OrcaRouter-…-Strata") + - One user reported it working in Strata at 38-44 tok/s decode on an RTX 4070 SUPER 12 GB + 96 GB DDR5-6400, with 0/5 Russian prompts refused. [OrcaRouter discussion #20](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/20) + - The related non-uncensored `Maximilian228/Qwen3.8-Flash-Next-NVFP4-GPTQ-Strata` claims 93.6% top-token agreement, against 92.9% for NVIDIA ModelOpt NVFP4. It needs Windows and NVIDIA driver 580 or newer. [mixpeek listing](https://mixpeek.com/model/Maximilian228/Qwen3.8-Flash-Next-NVFP4-GPTQ-Strata); [alphasignal](https://alphasignal.ai/model/maximilian228-s-qwen3-125b-squeeze-runs-on-a-12-gb-consumer-gpu) + +10. **Searched and not found:** no Flash-Next uncensored GGUFs from bartowski, mradermacher or unsloth appeared on page 1 of a 1,709-result search sorted by recently modified. No Josiefied, Hermes or mlabonne Flash-Next variants appeared either. [HF search](https://huggingface.co/models?search=Qwen3.8-Flash-Next&sort=modified) + +11. **Third-party runtime LoRA.** An AGI Hunt write-up says its author compared Heretic, OrcaRouter and huihui v1/v2. The author then trained a small runtime LoRA on huihui v2 that reportedly beat base on Aider Polyglot with fewer tokens and no runaway loops. The page returned 403, so only the search snippet was seen. [AGI Hunt (snippet only)](https://agihunt.info/p/1a1e1c5ec396edd478f2f767b38) + +### Inferences +- **No strictly newer OrcaRouter Flash-Next model exists.** The "newer" options are other people's builds. +- **The most Strata-native uncensored routes** are: + - (a) GSQ-RCO or Unsloth packs plus Strata's runtime refusal projection (bundled vector, or alesha-pro's vector). + - (b) huihui v2's Unsloth-derived UD files. + - Both avoid the OrcaRouter manual `iq_pack.py --compat-bf16` conversion. The Strata docs say that conversion "does not recover the original BF16 checkpoint or its quality." +- **Fit on 24 GB + 128 GB:** huihui v2 UD-Q4_K_XL (~111 GB) fits fully in RAM+VRAM. UD-Q5_K_XL (158 GB) exceeds 152 GB of combined memory. It would need Strata's SSD streaming, or the ~28.8 GB PLE table left on disk. +- **Tenet v3 trades off general reasoning.** Its own table shows GPQA -0.08 and MMLU-Pro -0.07. Its base scores (GPQA 0.42) are far below Qwen's reported 91.7, so its harness differs, but the relative drop is still a warning. +- **REAP-pruned builds are only for writing and roleplay**, because coding experts are removed. + +### Gaps +- No independent head-to-head (KL, refusal, or capability) of OrcaRouter vs huihui v1/v2 vs Heretic for Flash-Next was found. The only comparison claim (AGI Hunt) was inaccessible (HTTP 403). +- huihui v2 publishes no refusal or KL numbers. Its exact upload date is not shown. +- I could not confirm the exact repo name of the Maximilian228 OrcaRouter NVFP4 Strata pack. +- The trohrbaugh Heretic build's GGUF derivatives are unnamed. +- Release dates for the Tenet v3, FangZhangTNS, jcgamingonlinux and Shockem builds are not shown on the pages. + +## Q2. What does OrcaRouter say about how it was uncensored and about quality loss? What does the community say? + +### Takeaway +OrcaRouter's build is a classic abliteration: the refusal direction is orthogonalized out of the residual stream, with the MTP head treated consistently. +- **Claims:** refusals fall from 64-100% to 0-3.3%, with capability "within ±2 pts" of base. +- **Missing:** no KL divergence or per-benchmark numbers for Flash-Next, although KLD/PPL were promised on Sep 15. +- **Community issues found:** + - a metadata bug, fixed Sep 10, that requires re-downloading shard 00001 of any quant pulled before then; + - a near-uniform quant layout that runs slower than Unsloth's dynamic quants; + - template-driven infinite reasoning loops; + - a recent (~Nov 29) checksum-duplication report on the Q6_K and Q8_0 shards. + +### Cited Findings +**Model card** +- Method: "orthogonalizing the refusal direction out of the residual stream" (abliteration). Base is `Qwen/Qwen3.8-Flash-Next`, architecture `qwen4exp`. [HF card](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF) +- Refusals: harmful-prompt refusal drops from 64-100% (base) to ~0-3.3%. Benign over-refusal "stays near 0%". [HF card](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF) +- Capability: "within ±2 pts of the base" on MMLU-Pro, GSM8K and CMMLU-style checks. No per-benchmark numbers and no KL divergence are given. Vision (mmproj) and multi-turn tool calling are described as verified. [HF card](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF) +- The BF16 repo says the MTP head's residual writers were abliterated consistently, so speculative decoding still works. It also warns that fine-tuning on refusal-heavy data can partly re-introduce refusals. [HF](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored) +- For comparison, OrcaRouter's sister 27B card gives detailed numbers. Base FP8 → uncensored: + - MMLU-Pro 77.6 → 76.8 + - GSM8K 90.0 → 88.7 + - CMMLU 81.4 → 80.8 + - MMLU 84.3 → 84.7 + - Refusal on AdvBench 99% → 0%, HarmBench 98.7% → 2.7% + - The card warns of "small additional degradation at lower quants (most visible at Q2_K / Q3)". + - [HF 27B GGUF](https://huggingface.co/orcarouter/Qwen3.8-27B-Uncensored-GGUF) +- Body-text quant sizes: Q4_K_M ~110 GB, Q5_K_S ~117 GB, Q5_K_M ~125 GB, Q6_K ~168 GB, Q8_0 ~188 GB, IQ4_XS ~97 GB, IQ3_XXS ~73 GB. + - MTP draft ~4 GB. `IQ4_XS-MTP` and `Q8_0-MTP` embed the head and need the llama.cpp PR #30592 build. + - 420,983 downloads last month, 1.6k likes. + - [HF card](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF) + +**Community discussions** +- **KLD/PPL request.** Discussion #13 (Sep 14) asked for KLD/PPL per quant. OrcaRouter replied "will add it" (Sep 15). No values appear in the thread. The same user noted that Q5_K_M is effectively "6.1bit average really due to the Q8 parts". [discussion #13](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/13) +- **Speed regression vs Unsloth.** Discussion #12 (Sep 9-11): on an RTX 5060 Ti 16 GB + 64 GB, the OrcaRouter IQ4_XS ran at ~4-6 t/s against ~20-40 t/s for Unsloth UD-IQ4_XS. + - OrcaRouter found a real metadata bug: `qwen4exp.attention.compress_ratios` was all zeros, from converter/transformers version skew. + - They re-uploaded shard 00001 of each quant on Sep 10. Weight tensors are byte-identical. + - They said the remaining gap comes from the quant recipe. Unsloth keeps attention and shared experts at Q8_0 with IQ3_S routed experts; OrcaRouter uses a "near-uniform 4-bit layout". + - They announced a planned "dynamic-precision build" with an imatrix. As of an Oct 19 comment, release was unconfirmed. + - OrcaRouter also noted that `--lazy-mode`, `--moe-expert-cache-size` and similar flags come from a downstream fork. On mainline, use `-ngl 99 --n-cpu-moe ...` or `-ot`. + - [discussion #12](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/12) +- **Infinite loops.** Discussion #7 (Aug 31 / Sep 1) reported loops on Q3_K_S in LM Studio. + - OrcaRouter blamed the upstream chat template, not abliteration. The template defaults to xhigh reasoning effort, and the base model tends not to close its reasoning block. + - Suggested fixes: `reasoning_effort` low or `enable_thinking=false`, and `repeat_penalty` ~1.1 or DRY sampling for Q2/Q3. + - [discussion #7](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/7) +- **Checksum duplication.** Discussion #21 (~Nov 29): "Two files in different quants (2 of 5 in both Q6_K and Q8_0) have the same checksum". This is a possible integrity issue; no replies were visible. [discussions list](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions) +- **OrcaRouter org listing.** It shows Flash-Next Uncensored in BF16, GGUF, MLX, FP8 and NVFP4, all "Updated 1 day ago". No v2, imatrix or dynamic Flash-Next repo was visible (10 of 52 models shown). [orcarouter org](https://huggingface.co/orcarouter) + +### Inferences +- The user's Q5_K_M (~125 GB, effectively ~6.1 bpw) probably carries little extra abliteration loss beyond the base model's own quantization error. This is unverified because no KL has been published. +- If the user downloaded before Sep 10, 2026, shard 00001 of Q5_K_M has the zeroed `compress_ratios` metadata and should be re-pulled. The files on disk should be checked against the current repo hashes. + +### Gaps +- No published KL divergence or per-benchmark Flash-Next numbers from OrcaRouter. +- Whether the dynamic-precision requant was ever released is unknown. +- The content of discussion #21 was not read beyond its title. +- "Infinite loop" anecdotes were not quantified. + +## Q3. What is the "Qwen 3.8 looping" model? + +### Takeaway +It is not an official Qwen release. It is a set of community **recurrent-depth ("looped") adapters** for frozen Qwen3.8 bases. The core layers run 2-3 times per token, and depth can be switched at runtime (T=1 is identical to stock). There are two strands: + +| | Looped-Qwen3.8-Flash-Next | Looped-Qwen3.8-27B | +|---|---|---| +| Repo | `alesha-pro/Looped-Qwen3.8-Flash-Next` | `sliderforthewin/Looped-Qwen3.8-27B` (and others) | +| Released | v1 on ~Dec 2, 2026 | linked paper dated Oct 1 | +| Adapter | 268 MB, 70.2M params | 240 MB | +| Strata | fork branch; upstream PR #7673 still a draft | — | +| llama.cpp | no mainline support | — | + +Neither adapter is uncensored itself, but both have uncensored pairings: +- Flash-Next adapter + alesha-pro's abliterated GSQ-RCO kit (runtime projection), in the Strata fork. +- jakeatx's Swift-1.5-Uncensored 27B looped GGUFs, which need the llamAmpere fork. + +### Cited Findings +**Looped-Qwen3.8-Flash-Next (alesha-pro)** +- Released as "v1 (Stage 2 RLVR, 268 MB adapter + full 64k paired eval)" ~1 day before 2026-12-03. [HF tree](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next/tree/main); [search summary incl. zerohour](https://zerohour.day/item/f81eabfffb448531e96325ce99d4096069da54ea) +- Architecture: a recurrent-depth overlay on frozen Flash-Next. + - Core layers 16-31 run T=2 or T=3 passes in a 4-stream workspace, with a per-pass cross-mixer. + - LoRAs on the core (GDN, QSA, MoE router, shared expert) and coda LoRAs on layers 32-39. + - "268 MB FP32 overlay", 70.2M params (0.056% of base), "Zero base-weight edits". MIT license. + - Training: 1,200 steps of distillation plus 200 steps of GSPO RLVR. + - [HF](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next) +- Benchmarks, base → looped (vLLM FP8 on H200, 64k cap): + - LiveCodeBench v6 77.71% → 85.71% + - GPQA-Diamond 91.41% → 91.41% + - AIME 2025 96.67% → 93.33% + - HumanEval+ Direct 84.15% → 79.88% + - Total over 731 items 84.68% → 85.64%, with -34.2% tokens + - [HF](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next) +- At a 24k cap: LCB v6 57.5% → 77.5% (T=2) / 82.5% (T=3), and AIME 2025 80.0% → 90.0%. [HF](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next) +- Engine support: a Strata CUDA fork (branch `feat/looped-qwen4exp`, `--loop-adapter ckpt_final.safetensors --loop-passes 2`) and a vLLM 0.34+ plugin. llama.cpp and transformers are not mentioned. [HF](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next) +- The card recommends `alesha-pro/Qwen3.8-Flash-Next-abliterated-GSQ-RCO-Strata-GGUF` as the uncensored kit to pair with `--loop-adapter`. [HF](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next) +- Consumer speeds (Strata + RAM offload + DFlash2, 512 tokens): + - 1× RTX 3090, T=1: 132.6 tok/s decode + - 1× RTX 3090, T=2: 90.5-92.1 tok/s decode, 1,205 tok/s prefill + - 2× RTX 3090, T=2: 98-100 tok/s decode + - [HF](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next) + +**Strata upstream status (all Dec 1-3, 2026)** +- PR #7673 is a **draft** "opt-in Looped Qwen3.8-Flash-Next recurrent-depth adapter" by Dave3991 (Dec 2). [PR #7673](https://github.com/Niko1221/Strata/pull/7673) + - Flags: `--loop-adapter`, `--loop-passes`, LoopCD options, and per-request `loop_passes`. CUDA/HIP only. + - Incompatible with `--batch > 0` and `--pipeline-windows`. + - Tested on Unsloth UD-Q4_K_XL; a commenter also tested IQ3_S. + - Author-reported RTX 3090 numbers: 101.8 tok/s (T=1) vs 72.3 tok/s (T=2) in a full-RAM run; 37.5 tok/s at T=2 on a forced cache miss. + - No maintainer review. A Dec 3 static analysis lists 7 possible bugs (sidecar `loop_config` not read, T≥4 clamp, and others). +- Issues #7693 (Dec 2, "Looped Qwen 3.8 Flash Next: Less Thinking, Better Quality"; reporter on an RTX 5090 laptop 24 GB + 128 GB) and #7715 (Dec 3) request support. No maintainer response yet. [issue #7693](https://github.com/Niko1221/Strata/issues/7693); [issue search](https://github.com/Niko1221/Strata/issues?q=uncensored+OR+abliterated+OR+loop+OR+orca) +- Issue #7693 links `sliderforthewin/Looped-Qwen3.8-Flash-Next` while the PR uses `alesha-pro/Looped-Qwen3.8-Flash-Next`. This naming discrepancy is unresolved. [issue #7693](https://github.com/Niko1221/Strata/issues/7693) +- Splash (incoai) issue #935 also requests a `--loop-adapter` for Flash-Next. [splash #935](https://github.com/incoai/splash/issues/935) + +**Looped-Qwen3.8-27B (dense)** +- `sliderforthewin/Looped-Qwen3.8-27B`: layers 24-39 wrapped in a gated adapter of 62.85M params (~240 MB). T=1 matches stock; T=2/T=3 give 80/96 effective layers. +- Paper: arXiv 2610.02185, dated Oct 1. +- Results, stock → looped: + - LiveCodeBench v6 72.6% → 73.1% (T=2) / 78.9% (T=3); best 85.0% (v3.1) + - MMLU-Pro 82.2% → 80.0% (T=2) / 83.2% (T=3) + - GPQA Diamond 86.9% → 80.8-82.3% + - "53%-69% fewer `` tokens" +- Engines: mlx-serve, vLLM 0.34+, mlx-lm. GGUF and llama.cpp are not mentioned. MIT license. +- [HF](https://huggingface.co/sliderforthewin/Looped-Qwen3.8-27B) +- Strata issue #7609 and PR #7610 (Dec 1) add Looped 27B support; both are open. [issue search](https://github.com/Niko1221/Strata/issues?q=uncensored+OR+abliterated+OR+loop+OR+orca) + +**Uncensored looped 27B (jakeatx)** +- `jakeatx/qwen3.8-27b-Swift1.5-Uncensored-ATX-AI4-Looped-GGUF`: Swift 1.5 27B "uncensored, refusal-reduced" plus Jason Titus's Looped v3.1 adapter (133.8 MiB F16). +- Single file of 13.56 GiB. Requires **llamAmpere v0.8+**; "stock llama.cpp do[es] not know the loop keys". +- KL vs stock at 2-3 passes is 0.0089. +- RTX 3090 decode: 119.0 tok/s (1 pass) vs 79.6 tok/s (3 passes). +- Quality: 40/50 vs 39/50 (AIME 2025 + LiveCodeBench, one run), described as "no measurable gain". +- [HF](https://huggingface.co/jakeatx/qwen3.8-27b-Swift1.5-Uncensored-ATX-AI4-Looped-GGUF) +- A sibling `jakeatx/qwen3.8-27b-Swift1.5-Uncensored-ATX-12GB-3.0bpw-Looped-GGUF` also exists. [HF search](https://huggingface.co/models?search=Qwen3.8-27B%20uncensored&sort=modified) + +### Inferences +- Looping is mainly a **reasoning-efficiency** feature (fewer think tokens), not a big quality jump. Gains concentrate in LiveCodeBench, and some benchmarks regress (AIME, HumanEval+ Direct, GPQA on 27B). It costs about 30-40% of decode tok/s. +- For this user it is only usable through a non-mainline Strata fork or branch right now. It is not available in their Strata 0.2.24 or llama.cpp b12774. +- The uncensored path is alesha-pro's runtime-projection kit plus the adapter. + +### Gaps +- No RTX 4090 numbers for any looped model. +- No independent benchmark replication. +- Unknown whether the Flash-Next adapter behaves correctly on top of weight-abliterated bases (OrcaRouter, huihui); only the runtime-projection pairing is documented. +- The exact upload date of sliderforthewin/Looped-Qwen3.8-27B is not shown. + +## Q4. Other Qwen 3.8 family releases from Oct-Dec 2026 with uncensored versions that fit 24 GB VRAM + 128 GB RAM + +### Takeaway +No new official Qwen 3.8 open-weight models appeared in Oct-Dec 2026. The family remains: +- Qwen3.8-27B dense (Aug 14) +- Qwen3.8-2.4T-A95B "Max" (Aug 12/13; far too large) +- Qwen3.8-Flash-Next (Aug 26) + +Qwen4-Max (Nov 2026) is API-only, with smaller Qwen4 open weights promised but undated. The Oct-Dec activity is community work: uncensored 27B builds, Coder-style derivatives, and looped adapters. The cleanest documented uncensored 27B alternative to the user's DavidAU-style merge is **orcarouter/Qwen3.8-27B-Uncensored-GGUF**. + +### Cited Findings +**Official releases** +- Qwen3.8 open weights (all August 2026): + - Qwen3.8-27B: dense multimodal, Apache 2.0, 262K context, Aug 14. + - Qwen3.8-2.4T-A95B: separate Max license, Aug 12/13 (sources disagree). + - Qwen3.8-Flash-Next: Aug 26. + - No November Qwen3.8 release was found. [the-decoder](https://the-decoder.com/alibabas-qwen-team-releases-qwen-3-8-models-with-open-weights-under-the-apache-2-0-license/); [llm-stats Max](https://llm-stats.com/blog/research/qwen3-8-max-open-weights); [Qwen on X](https://x.com/Alibaba_Qwen/status/2088280182356611304) +- Qwen4-Max is reported as API-only (Nov 16, 2026 report), with smaller Qwen4 open weights promised but undated. One single source claims Apache 2.0 weights by Dec 20, 2026; uncorroborated. [The New Stack](https://thenewstack.io/qwen4-max-alibaba-open-weights/?p=22843746); [local-ai-zone deep dive](https://local-ai-zone.github.io/blog/qwen-4-deep-dive.html); [Wikipedia](https://en.wikipedia.org/wiki/Qwen) + +**Community derivatives** +- "Coder": ISTA-DASLab's Flash-Next Coder IQ1_M keeps 256 of 512 experts per layer, is tuned for code, and "is weaker outside code". It is a Strata-supported variant. No uncensored version was found. [Strata MODELS.md](https://github.com/Niko1221/Strata/blob/main/docs/MODELS.md) + +**Uncensored Qwen3.8-27B options** (fit entirely in 24 GB VRAM at Q4-Q6; llama.cpp) +- **orcarouter/Qwen3.8-27B-Uncensored-GGUF** (141,029 downloads last month, 2.04k likes; collection "Updated 20 days ago", ~Nov 13) + - Abliteration. Refusals, base FP8 → this model: AdvBench 99% → 0%, HarmBench 98.7% → 2.7%. XSTest over-refusal 5.6% → 0.4%. + - Capability: MMLU-Pro 77.6 → 76.8, GSM8K 90.0 → 88.7. + - Sizes: Q4_K_M 16.8 GB, Q5_K_M 18.2 GB, Q6_K 20.9 GB, Q8_0 27.1 GB, IQ4_XS 15.3 GB. + - MTP head embedded in the GGUF; mmproj 0.9 GB. Needs the llama.cpp `qwen35` hybrid-GDN + MTP support "merged 2026-05". + - [HF](https://huggingface.co/orcarouter/Qwen3.8-27B-Uncensored-GGUF) +- **huihui-ai/Huihui-Qwen3.8-27B-abliterated-GGUF** (4,673,144 downloads last month, 2.47k likes; patch files updated Nov 11, 2026) + - Abliteration of layers 22-52 (17-52 for UD). "MTP and visual has not been modified". + - Sizes: Q4_K_M 16.6 GB, UD-Q5_K_XL 20.7 GB, Q6_K 22.4 GB, Q8_0 29 GB. + - No refusal or KL numbers. + - [HF](https://huggingface.co/huihui-ai/Huihui-Qwen3.8-27B-abliterated-GGUF) +- **huihui-ai/Huihui-Qwen3.8-27B-Coder390-EfficientThink-abliterated(-GGUF)**, Oct 11/14, 2026. [collection](https://huggingface.co/collections/huihui-ai/qwen38-abliterated) +- **Many very recent 27B uncensored uploads** (most updated within 1-2 days of Dec 3) [HF search](https://huggingface.co/models?search=Qwen3.8-27B%20uncensored&sort=modified) + - `philbert440/Qwen3.8-27B-Uncensored-Cyber-GGUF` (614k) + - `OpenferenceLabs/Qwen3.8-27B-Uncensored-GGUF` + - `mradermacher/Qwen3.8-27B-Uncensored-Heretic-Native-MTP-Preserved-v2-i1-GGUF` + - `ajgazin/Swift-1.5-Qwen3.8-27B-Uncensored-Dynamic-MTP-GGUF` + - `DocPerez/Qwen3.8-27B-Uncensored-hermes-Q4_K_M-GGUF` + - `Cdfee/Qwen3.8-27B-Heretic-Abliterated-Uncensored-GGUF` + - DavidAU-style named merges such as `thedhruvsoni/Qwen3.8-27B-TURBO-Fable-Cold-Fusion-735-882-Heretic-Uncensored-NEO-CODER-MAX-MTP-GGUF` and `blistfulagony/...-Turbo-Brilliance-50x-AGI-NEO-GGUF`. The first appears to be a sibling of the user's current TurboFCFusion model; not verified. + +**Base capability comparison** (different harnesses, from the looped-adapter cards) +- Flash-Next base: LCB v6 77.71%, GPQA 91.41%, AIME 2025 96.67%. [alesha-pro](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next) +- 27B base: LCB v6 72.6%, GPQA 86.9%, AIME 2025 90.0%, MMLU-Pro 82.2%. [sliderforthewin](https://huggingface.co/sliderforthewin/Looped-Qwen3.8-27B) + +### Inferences +- The 27B dense fits entirely in the 4090 at Q4_K_M to Q6_K, so it will be much faster per token at long context than Flash-Next with RAM offload. Flash-Next is moderately stronger (roughly +5 pts on LCB/GPQA and +6 on AIME in the comparable looped-card harnesses). This is an inference, not a controlled test. +- orcarouter's 27B card is the best-documented uncensored 27B (measured refusal and capability deltas). The user's DavidAU-style merge has no such numbers. + +### Gaps +- No uncensored VL-only, Plus or Max-class 3.8 open weights that fit this hardware. +- No independent evaluations of the many 27B merges. +- Qwen4 small open weights: no date confirmed as of 2026-12-03. + +## Q5. Uncensored Qwen3.6-35B-A3B / Ornith-1.5-35B-A3B variants and how they compare + +### Takeaway +Plenty exist, all third-party: +- **Qwen3.6:** Heretic (llmfan46 MTP-preserved, Youssofal), huihui abliterated MTP GGUF, and others. +- **Ornith-1.5:** huihui abliterated via mradermacher GGUF, OS-Software Heretic-ja, and Ollama abliterated builds. + +They are 3B-active models and almost certainly weaker than Flash-Next (6B active of 125B). No benchmark numbers for them were found in this session to quantify the gap. + +### Cited Findings +- Qwen3.6-35B-A3B uncensored builds: + - `llmfan46/Qwen3.6-35B-A3B-uncensored-heretic-Native-MTP-Preserved-GGUF` + - `SC117/...-APEX-GGUF` + - `Youssofal/Qwen3.6-35B-A3B-Abliterated-Heretic-GGUF` (Q8_0/Q6_K/Q4_K_M) + - `IIEleven11/...-BF16-Q8_0-GGUF` (updated Apr 16) + - `huihui-ai/Huihui-Qwen3.6-35B-A3B-abliterated` and `-MTP-GGUF` (quants down to Q2_K) + - `wangzhang/Qwen3.6-35B-A3B-abliterated` + - [search results](https://huggingface.co/llmfan46/Qwen3.6-35B-A3B-uncensored-heretic-Native-MTP-Preserved-GGUF); [huihui MTP GGUF](https://huggingface.co/huihui-ai/Huihui-Qwen3.6-35B-A3B-abliterated-MTP-GGUF); [Youssofal](https://huggingface.co/Youssofal/Qwen3.6-35B-A3B-Abliterated-Heretic-GGUF) +- Ornith-1.5-35B-A3B uncensored builds: [search results](https://alphasignal.ai/model/mradermacher-ships-huihui-ornith-35b-uncensored-for-local-gpu-runners); [featherless heretic-ja](https://featherless.ai/models/OS-Software/Ornith-1.5-35B-A3B-heretic-ja); [ollama](https://ollama.com/codecraftersllc/ornith-1.5-35b-a3b-abliterated) + - mradermacher GGUFs of Huihui-Ornith-1.5-35B-A3B-abliterated, ~13.3 GB (Q2_K) to 37.9 GB (Q8_0) + - `OS-Software/Ornith-1.5-35B-A3B-heretic-ja`, made with Heretic and Arbitrary-Rank Ablation + - `3MPER0RR/Ornith-1.5-35B-A3B-3MPER0RR-abliterated`, built on the huihui base + - `codecraftersllc/ornith-1.5-35b-a3b-abliterated` (Ollama, Q3_K_M; ~1 week old) +- Strata support: + - Qwen3.6-35B-A3B (`--family qwen36`) only with Unsloth GGUFs (UD-Q4_K_XL, UD-Q6_K_XL, Q8_0). + - Ornith-1.5 (`--family ornith`) with plain Q4_K_M/Q5_K_M/Q6_K/Q8_0. The docs say it uses "the same architecture as Qwen3.6". The 122B Ornith models are not included. + - [Strata MODELS.md](https://github.com/Niko1221/Strata/blob/main/docs/MODELS.md) + +### Inferences +- They are useful only as fast, fully-in-VRAM uncensored options; Q4_K_M is around 20 GB, inferred from the Q8_0 size of 37.9 GB. They are not a capability upgrade over Flash-Next. +- An abliterated Ornith-1.5 GGUF in one of the plain quant types Strata accepts (Q4_K_M-Q8_0) may load under `--family ornith`, since the architecture is identical. This is untested. + +### Gaps +- No benchmark numbers for Qwen3.6-35B-A3B or Ornith-1.5 vs Flash-Next were retrieved. +- No refusal or KL data for these uncensored variants were read. +- Strata loading of abliterated Ornith/Qwen3.6 GGUFs is unverified. + +## Q6. Which candidates run in Strata, and which need llama.cpp? Any llama.cpp support issues? + +### Takeaway +**Strata-native:** +- ISTA-DASLab GSQ-RCO packs plus runtime refusal projection (alesha-pro vector, or Strata's bundled vector via `--experimental-speed-projection`). This route is documented and measured. +- Unsloth-derived huihui v2 UD files. The card claims Strata compatibility, but SHA verification must be bypassed. + +**Strata, manual:** OrcaRouter needs a manual `iq_pack.py --compat-bf16` pack. Officially only IQ3_XXS is validated, and IQ3_M is unsupported. + +**Strata, unmerged branches only:** the looped adapters. + +**Not Strata:** Tenet, Heretic BF16, Basalt (Blackwell-only) and EXL3 builds. Uncensored 27B dense models need llama.cpp; Strata has no Qwen3.8-27B family. + +**llama.cpp:** mainline has supported `qwen4exp` since 2026-08-27. MTP-embedded OrcaRouter quants need PR #30592, and looped 27B needs the llamAmpere fork. + +### Cited Findings +**Strata** +- Supported Flash-Next packs: [Strata README](https://github.com/Niko1221/Strata); [MODELS.md](https://github.com/Niko1221/Strata/blob/main/docs/MODELS.md) + - ISTA-DASLab Q2_0/IQ2_XS/IQ3_XXS/IQ3_S, and Coder IQ1_M + - Unsloth UD-IQ4_XS/UD-Q4_K_XL/UD-Q5_K_XL/UD-Q6_K_XL/Q8_0 + - Gyro-S/M, Swift 1.5, NVFP4 (3 variants) + - OrcaRouter Uncensored IQ3_XXS ("not an installer option") + - The release files are named Strata-0.2.24. Q5_K_M is not listed for Qwen3.8. +- ORCA.md (measured 2026-09-27): [ORCA.md](https://github.com/Niko1221/Strata/blob/main/docs/ORCA.md) + - "IQ3_XXS is the only validated Orca quantization" (85.20 GB). IQ3_M is unsupported because of Q5_0 expert down matrices. + - Manual pack: `iq_pack.py --gguf --out packs/orca-iq3_xxs --compat-bf16`, which expands some tensors to BF16. The docs say this "does not recover the original BF16 checkpoint or its quality". + - Needs about 49.8 GiB free RAM for the expert arena. + - One measurement on an RTX 5090: 77.7 tok/s. + - "MTP draft acceptance and speed are unmeasured for this fine-tune". +- A user reported that Strata 0.2.8 rejected the OrcaRouter IQ4_XS GGUF, while a Maximilian228 NVFP4-GPTQ OrcaRouter pack worked. [discussion #20](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/20) +- Runtime refusal projection in Strata: [alesha-pro kit](https://huggingface.co/alesha-pro/Qwen3.8-Flash-Next-abliterated-GSQ-RCO-Strata-GGUF); [gopenai/Medium (secondary)](https://blog.gopenai.com/the-censorship-switch-strata-hid-in-its-own-repo-cc0e4085aa9e) + - Setup flag `--experimental-speed-projection `. + - Engine flags `--control-vector-scaled ...:1.0 --control-vector-layer-range 4 44 --cvec-mode project --cvec-dir per-layer`. + - Can be disabled per request with `"experimental_speed_projection": false`. + - The kit's table includes "Strata's bundled vector" (1/10 and 0/10 refusals). + - A Medium post says the feature has existed in the repo since late September and does not touch weights. It is not described in README or MODELS.md. +- huihui v2 says the Unsloth and Swift series "supports the latest versions of both Strata and llama.cpp", but Strata SHA256-verifies Unsloth files. [HF](https://huggingface.co/huihui-ai/Huihui-Qwen3.8-Flash-Next-abliterated-v2-GGUF) +- FangZhangTNS REAP-abliterated builds ship Strata STRP profiles and were speed-tested on Strata 0.1.63. [HF](https://huggingface.co/FangZhangTNS/Qwen3.8-Flash-Next-REAP-Pruned-Abliterated-EN-Writing-RP-V2-GGUF) +- An open Strata issue, #7685 (Dec 2), requests support for `orcarouter/Hy4-flash-abliterated-GGUF` mixed-precision files. This shows OrcaRouter also released an abliterated Tencent Hy4-Flash, a different architecture that Strata supports natively in its own format. [issue search](https://github.com/Niko1221/Strata/issues?q=uncensored+OR+abliterated+OR+loop+OR+orca) + +**llama.cpp** +- `qwen4exp` support was merged 2026-08-27 (PR #27742, follow-up #27880). LM Studio failed with "unknown architecture 'qwen4_exp'" until it updated. [OrcaRouter card](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF) +- MTP-embedded quants need the PR #30592 build (stacked on #27836). Non-MTP quants load on mainline. [OrcaRouter card](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF) +- Discussion #17 requests an MTP draft "compatible with current llama.cpp upstream", which suggests drift between the draft file and upstream. [discussions list](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions) +- Mainline offload flags: `-ngl 99 --n-cpu-moe ...` or `-ot`. `--moe-expert-cache-size` and `--lazy-mode` are from a downstream fork. [discussion #12](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/12) +- Keep the PLE (`per_layer_token_embd`) table off the GPU. With it on CUDA0, decode reportedly fell from 108.5 to 1.95 tok/s. Secondary source, compiled from model cards and community data. [dev.to](https://dev.to/alanwest/how-to-run-qwen38-flash-next-locally-39-toks-on-24gb-of-vram-plus-96gb-ram-12ca) +- Qwen3.8-27B GGUFs need the `qwen35` hybrid-GDN + MTP/`nextn` support merged 2026-05. [orcarouter 27B](https://huggingface.co/orcarouter/Qwen3.8-27B-Uncensored-GGUF) + +### Inferences +- The user is running OrcaRouter Q5_K_M in Strata 0.2.24, but the docs validate only IQ3_XXS. Either newer Strata handles K-quants via the manual pack, or the user's setup is undocumented. This discrepancy is worth flagging. +- A lower-friction Strata route to an uncensored Flash-Next is Unsloth UD-Q4_K_XL or GSQ-RCO IQ3_S (both first-class installer packs) plus the refusal-projection vector. This keeps the official quant recipe, which other users found faster than OrcaRouter's uniform layout. + +### Gaps +- The `--experimental-speed-projection` feature is not described in the README or MODELS.md pages fetched. Its existence rests on the alesha-pro card and a secondary Medium post. +- Whether Strata 0.2.24 accepts OrcaRouter Q5_K_M or huihui v2 files without patches was not confirmed from Strata docs. + +## Q7. Reported speeds on a 24 GB GPU + system RAM + +### Takeaway +No RTX 4090-specific numbers were found. The closest data: + +| Setup | Model / quant | Engine | Decode | +|---|---|---|---| +| RTX 3090 24 GB + 125 GB RAM | GSQ-RCO IQ3_S (abliterated via projection) | Strata | ~58 tok/s | +| RTX 3090 24 GB + 125 GB RAM | GSQ-RCO IQ2_XS (abliterated via projection) | Strata | ~84 tok/s | +| Simulated 24 GB + 96 GB DDR5 | Unsloth UD-IQ4_XS | llama.cpp | ~39 tok/s (secondary source) | +| RTX 4070S 12 GB + 96 GB | OrcaRouter IQ4_XS | LM Studio | 26 tok/s | +| RTX 4070S 12 GB + 96 GB | OrcaRouter NVFP4 pack | Strata | 38-44 tok/s | + +The 3090 figures are at 4-32K context. Looped T=2 costs roughly 30% of decode speed. + +### Cited Findings +- alesha-pro kit, RTX 3090 at 300 W, EPYC 7642, 125 GB RAM, peak VRAM 23.8 GB: [HF](https://huggingface.co/alesha-pro/Qwen3.8-Flash-Next-abliterated-GSQ-RCO-Strata-GGUF) + - IQ3_S: 58.1 / 59.0 / 46.6 / 39.5 tok/s at 4K / 32K / 131K / 261K prompts. First token 4.6 s at 4K, 74.2 s at 131K. + - IQ2_XS: 84.2 / 87.1 / 79.6 / 47.3 tok/s. + - Experts in RAM: IQ3_S 50 GB, IQ2_XS 35.5 GB. + - Agent sessions: 46-54 tok/s (IQ3_S). +- Looped Flash-Next, 1× RTX 3090 (Strata fork + RAM offload + DFlash2): T=1 132.6 tok/s, T=2 90.5-92.1 tok/s. [alesha-pro looped](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next) + - The Strata PR author's numbers are lower: 101.8 (T=1) vs 72.3 (T=2), and 37.5 tok/s at T=2 on a cache miss. [PR #7673](https://github.com/Niko1221/Strata/pull/7673) +- llama.cpp, UD-IQ4_XS, simulated 24 GB VRAM + 96 GB DDR5: 39.01 tok/s. With all experts in RAM (8 GB tier): 35.69 tok/s. Prefill with `--load-mode none`: 746.7 tok/s (vs 400.4 with mmap). The author compiled these and did not run them first-hand. [dev.to](https://dev.to/alanwest/how-to-run-qwen38-flash-next-locally-39-toks-on-24gb-of-vram-plus-96gb-ram-12ca) +- OrcaRouter IQ4_XS on RTX 4070 SUPER 12 GB + 96 GB DDR5-6400 (LM Studio): 160-190 tok/s prompt processing, 26 tok/s decode. The OrcaRouter NVFP4 Strata pack on the same machine: 38-44 tok/s. [discussion #20](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/20) +- OrcaRouter IQ4_XS on RTX 5060 Ti 16 GB + 64 GB: ~4-6 t/s, vs Unsloth UD-IQ4_XS ~20-40 t/s on the same setup (downstream llama.cpp fork flags). [discussion #12](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/12) +- OrcaRouter IQ3_XXS in Strata on an RTX 5090 32 GB + 128 GB: 77.7 tok/s (one 111-token measurement). [ORCA.md](https://github.com/Niko1221/Strata/blob/main/docs/ORCA.md) +- FangZhangTNS REAP k256-IQ3_S in Strata 0.1.63: 48.7 t/s ("47G+16G" setup). [HF](https://huggingface.co/FangZhangTNS/Qwen3.8-Flash-Next-REAP-Pruned-Abliterated-EN-Writing-RP-V2-GGUF) +- Looped Swift-1.5 uncensored 27B (llamAmpere) on RTX 3090: 119.0 tok/s (1 pass) vs 79.6 tok/s (3 passes) at a 3K prompt. [HF](https://huggingface.co/jakeatx/qwen3.8-27b-Swift1.5-Uncensored-ATX-AI4-Looped-GGUF) + +### Inferences +- An RTX 4090 with DDR5 and an i7-14700 should match or beat these 3090 figures, but RAM bandwidth (DDR5 dual-channel vs EPYC 8-channel) may dominate for experts held in RAM. This is unmeasured. +- Q5_K_M-class files (~125 GB) leave far less of the expert set cacheable in VRAM than IQ3_S (83.6 GB), so expect lower decode than the 3090 IQ3_S figures. + +### Gaps +- No first-hand RTX 4090 + 128 GB DDR5 measurements for any Flash-Next uncensored build. +- No speed data for huihui v2 UD-Q5_K_XL or for OrcaRouter Q5_K_M in Strata. diff --git a/docs/research/notes/Uncensored local LLM alternatives/uncensoring_quality_rankings.md b/docs/research/notes/Uncensored local LLM alternatives/uncensoring_quality_rankings.md new file mode 100644 index 0000000..1a8c914 --- /dev/null +++ b/docs/research/notes/Uncensored local LLM alternatives/uncensoring_quality_rankings.md @@ -0,0 +1,498 @@ +# How uncensoring methods affect quality, and which uncensored local models rank best (as of 2026-12-03) + +Scope: cross-cutting evidence for picking an uncensored model to replace orcarouter/Qwen3.8-Flash-Next-Uncensored (Q5_K_M, about 125 GB) on an RTX 4090 24 GB, 128 GB DDR5 and i7-14700 rig. Model-family deep dives (Qwen 3.8, DeepSeek, others) are covered by other researchers. + +**Note on the main data source.** Most leaderboard numbers below come from the raw UGI Leaderboard data file, `ugi-leaderboard-data.csv`: https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv. The file is 698 KB and was last changed about 2026-11-28. I read the whole file in seven chunks through a summarising fetch tool. The leaderboard web page would not render, and a direct download failed on this machine. Values were copied exactly by the tool, but a few could still be misread, so spot-check any number that drives a decision. + +UGI column meanings, taken from the column names and leaderboard write-ups: +- **UGI**: the overall uncensored-intelligence score. +- **W/10**: willingness to answer, out of 10. +- **NatInt**: the leaderboard's general-intelligence and knowledge score. + +The leaderboard often tests a model twice: with a "thinking prefill" (`` prefill) and without thinking. The two scores can differ by about 10 points, so compare like with like. + +--- + +## Q1. Uncensoring methods in use in late 2026, and how much capability each loses + +### Takeaway +Capability loss depends mostly on how carefully a method was tuned for a specific model, not on the method's name. +- **Well-tuned edits keep capability.** Good KL-optimised Heretic runs and norm-preserving ("Derestricted"/MPOA) runs usually stay within about ±2 NatInt points of the base model, and sometimes score above it. +- **Careless edits lose a lot.** Older one-shot abliterations, aggressive Heretic settings and many "uncensored" fine-tunes can lose 5–20 NatInt points. Maths (GSM8K) is the most fragile capability. +- **Big MoE edits lose more.** The largest-MoE uncensored releases on the board lost 8–14 NatInt points. + +### Cited Findings + +**Method landscape and tooling status (recent)** +- Heretic (p-e-w) co-minimises refusals and KL divergence from the original model, using a TPE optimiser (Optuna). [Heretic GitHub](https://github.com/p-e-w/heretic) +- Heretic 2.x options: + - The default modifier is now "Arbitrary-Rank Ablation (ARA)". Its explanatory preprint is listed as "will be available soon". + - The classic directional-ablation modifier supports projected abliteration and norm preservation (MPOA), with a flexible per-layer weight kernel. + - It claims support for "several different MoE architectures" without naming them. + - It can write reproducibility manifests (`reproduce.json`). + - 1.x configs are not compatible with 2.x. + + [Heretic GitHub](https://github.com/p-e-w/heretic) +- **RECENT (Nov 2026):** The Heretic repository was archived (read-only) on 2026-11-28. A news report says creator Philipp Emanuel Weidmann announced in GitHub issue #601 that his work on the project has ended, and named no successor. The archive date is confirmed on the repo page; the reason rests on a single article. [Heretic GitHub](https://github.com/p-e-w/heretic); [Let's Data Science](https://letsdatascience.com/news/heretic-creator-archives-repository-and-ends-work-on-project-a6d4c226) +- Norm-preserving biprojected abliteration (NPBA, grimjim/Jim Lai, 2025-11-06) changes only the direction of each weight row and keeps its magnitude. It edits `self_attn.o_proj` and `mlp.down_proj`. [grimjim HF blog](https://huggingface.co/blog/grimjim/norm-preserving-biprojected-abliteration) +- The jim-plus llm-abliteration README warns that some models do not respond well to norm preservation. [jim-plus/llm-abliteration](https://github.com/jim-plus/llm-abliteration/) (via search summary) +- ArliAI's "Derestricted" models, including GLM-4.6-Derestricted-v3, use NPBA. The model card claims to avoid a "Safety Tax" and possibly improve reasoning, but gives no refusal, KL or benchmark numbers. [ArliAI/GLM-4.6-Derestricted-v3](https://huggingface.co/ArliAI/GLM-4.6-Derestricted-v3) +- Other variant names seen on UGI in 2026, with no independent quality papers found for any of them: + - "null-space abliterated" (jwest33) + - "gabliterated" (Goekdeniz-Guelmez) + - "SOMbliterated" / "SOMPOA" + - "ARA-heresy" and "PaperWitch-heresy" (MuXodious) + - "OBLITERATUS" + - Abliterix "Expert-Granular Abliteration" + + [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) + +**Classic abliteration (FailSpy / mlabonne / huihui-ai): older evidence** +- **mlabonne (June 2024):** after abliterating Daredevil-8B, "we observe a performance drop in the ablated version across all benchmarks". A DPO fine-tune on orpo-dpo-mix-40k (NeuralDaredevil-8B-abliterated) "allowed us to recover most of the performance drop", except GSM8K, which "doesn't improve". The exact scores are only in images. [mlabonne HF blog](https://huggingface.co/blog/mlabonne/abliteration) +- **Heretic v1.0.1 README**, gemma-3-12b-it (97/100 refusals originally): + + | Model | Refusals | KL divergence | + |---|---|---| + | mlabonne abliterated-v2 | 3/100 | 1.04 | + | huihui-ai abliterated | 3/100 | 0.45 | + | Heretic | 3/100 | 0.16 | + + Same refusal suppression at much lower KL. [Heretic README v1.0.1](https://raw.githubusercontent.com/p-e-w/heretic/v1.0.1/README.md) +- **Cross-check on the current UGI CSV.** NatInt for the same three gemma-3-12b models follows the KL order. Base 18.72; Heretic 15.68; huihui 12.11; mlabonne-v2 8.16. Lower KL went with less intelligence loss. [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) + +**Heretic: independent paper (older, Dec 2025)** +- **Young, arXiv 2512.13655 v2.** Heretic's KL across 8 models ranged from 0.043 to 1.646. For example: + - Qwen3-8B: KL 0.210, 25/100 refusals + - Qwen2.5-7B: KL 1.646, 42/100 refusals + + KL and remaining refusals correlated at r = 0.87. [arXiv 2512.13655v2](https://arxiv.org/html/2512.13655v2) +- **Mean benchmark change versus base** (DeepSeek-7B, Mistral-7B, Yi-1.5-9B): + + | Tool | MMLU | GSM8K | HellaSwag | + |---|---|---|---| + | Heretic | −0.78 | −7.81 | −0.56 | + | DECCP | −0.61 | −0.13 | −0.25 | + | ErisForge | −0.12 | −0.28 | −0.08 | + + The largest swing was Yi-1.5-9B GSM8K: 70.89% (base) → 52.08% with Heretic (−18.81 pp), versus 72.40% with DECCP. The paper calls GSM8K the most sensitive capability. [arXiv 2512.13655v2](https://arxiv.org/html/2512.13655v2) +- **Caveats in that paper:** + - Single runs. + - Only three models were benchmarked. + - No MoE models. + - Its marker-based refusal heuristic underestimated compliance: 72.2% ASR by markers versus 95.7% by a classifier across 900 responses. + + [arXiv 2512.13655v2](https://arxiv.org/html/2512.13655v2) +- Tool compatibility across 16 models: Heretic 16/16, DECCP 11/16, ErisForge 9/16, FailSpy 5/16. [arXiv 2512.13655v2](https://arxiv.org/html/2512.13655v2) + +**Norm-preserving / projected abliteration (Nov 2025; author-run)** +- grimjim's own UGI runs on Gemma-3-12B: + + | Variant | UGI | NatInt | + |---|---|---| + | Baseline | 19.58 | 18.72 | + | Standard abliterated | 32.08 | 18.64 | + | NPBA | 32.61 | 21.33 | + + Single model, author-run. [grimjim HF blog](https://huggingface.co/blog/grimjim/norm-preserving-biprojected-abliteration) +- The current UGI CSV agrees on direction for the grimjim Gemma-3-12B series: + + | Variant | UGI | NatInt | + |---|---|---| + | Abliterated | 39.32 | 18.65 | + | Projection | 39.11 | 19.21 | + | Biprojected | 37.79 | 21.06 | + | Norm-preserved biprojected | 40.09 | 21.33 | + + UGI was evidently rescaled since 2025 (32.61 → 40.09 for the same model), so compare only within one snapshot. [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) + +**Base → uncensored NatInt deltas from the current UGI CSV** (same prompt mode; "pf" = thinking prefill, "nt" = no-think). [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) + +gpt-oss-120b (base NatInt 33.68, W/10 2.0): + +| Variant | Method | NatInt | Δ | W/10 | +|---|---|---|---|---| +| huihui abliterated | classic | 16.72 | −17.0 | 5.2 | +| kldzj heretic | Heretic | 33.41 | −0.3 | 9.5 | +| ArliAI Derestricted | NPBA | 35.7 | +2.0 | 9.2 | +| MuXodious tainted-heresy | Heretic variant | 32.25 | −1.4 | 9.2 | +| michaelwaves amoral | fine-tune | 12.08 | −21.6 | 5.0 | + +Gemma-3-27b-it (base NatInt 34.45): + +| Variant | NatInt | Δ | +|---|---|---| +| YanLabs normpreserve | 34.1 | −0.35 | +| coder3101 heretic-v2 | 33.54 | −0.9 | +| mlabonne abliterated | 29.6 | −4.85 | +| summykai abliterated + DPO | 29.8 | DPO did not restore NatInt | +| TeeZee heretic | 24.59 | −9.9 | +| nidum "Uncensored" fine-tune | 20.48 | −14 | + +Llama-3.3-70B-Instruct (base NatInt 31.37, W/10 4.0): + +| Variant | NatInt | Δ | +|---|---|---| +| huihui abliterated | 33.54 | +2.2 | +| TeeZee heretic | 32.42 | +1.0 | +| NPBA (vprilepskii) | 29.41 | −2.0 | +| TeeZee heretic-v2 | 24.99 | −6.4 | + +Qwen3.5-27B, thinking prefill (base NatInt 35.83): + +| Variant | NatInt | Δ | +|---|---|---| +| Bobi099 heretic | 35.49 | −0.3 | +| llmfan46 heretic-v3 | 34.82 | −1.0 | +| coder3101 heretic | 33.84 | −2.0 | +| ArliAI Derestricted | 28.66 | −7.2 | +| huihui abliterated | 23.05 | −12.8 | +| llmfan46 heretic-v2 | 24.87 | −11.0 | + +Qwen3.5-35B-A3B MoE, thinking prefill (base NatInt 33.09): + +| Variant | NatInt | Δ | +|---|---|---| +| llmfan46 uncensored-heretic | 35.61 | +2.5 | +| llmfan46 heretic-v2 | 34.25 | +1.2 | +| Li101 Uncensored-Aggressive | 30.14 | −3.0 | +| ArliAI Derestricted | 28.11 | −5.0 | +| wangzhang abliterated | 23.13 | −10.0 | +| huihui abliterated | 22.26 | −10.8 | +| coder3101 heretic | 19.95 | −13.1 | + +Gemma-4-31B-it (base NatInt 38.91 pf / 34.36 nt): + +| Variant | NatInt | Δ | +|---|---|---| +| coder3101 heretic | 36.53 pf / 35.64 nt | −2.4 / +1.3 | +| llmfan46 uncensored-heretic | 36.41 pf | −2.5 | +| DavidAU DECKARD-HERETIC (merge/fine-tune) | 33.14 pf | −5.8 | + +Gemma-4-26B-A4B MoE (base NatInt 34.31 pf): most uncensored variants land between 33.3 and 35.7 pf. +- huihui abliterated 33.95 +- coder3101 heretic 33.34 +- llmfan46 ultra 35.71 +- MuXodious SOMPOA 34.5 + +Large MoE uncensored releases lost the most: + +| Model | Base NatInt | Uncensored variant | NatInt | Δ | +|---|---|---|---|---| +| Qwen3.5-397B-A17B | 47.78 pf / 41.01 nt | trohrbaugh heretic | 39.48 pf / 33.25 nt | −8.3 / −7.8 | +| GLM-4.6 | 44.94 (reasoning) / 41.7 (no reasoning) | ArliAI Derestricted-v3 | 30.93 pf / 30.43 nt | about −11 to −14 | + +GLM-4.5-Air (base NatInt 33.3 think / 32.18 nothink): ArliAI Derestricted scored 36.62 think (+3.3) but 27.46 nothink (−4.7). + +Releases that end up worse than their base on every axis: +- llmfan46 GLM-4.7-Flash-ultimate-uncensored-heretic: UGI 14.3–15.35, W/10 1.8–2.5. The base GLM-4.7-Flash scored UGI 21.11–33.75. +- llmfan46 Mistral-Small-3.2-24B ultra-uncensored-heretic: UGI 4.38, NatInt 5.09. Its base, Mistral-Small-3.2-24B-Instruct-2506, scored UGI 40.43, NatInt 23.93. + +**Fine-tune / DPO "uncensored" models (Dolphin, Hermes, Josiefied): mostly older data** +- Dolphin3.0-Mistral-24B: UGI 35.25, W/10 5.8, NatInt 21.16. That is below its base, Mistral-Small-24B-Instruct-2501 (UGI 39.01, W/10 6.5, NatInt 25.87). The huihui abliteration of the same base scored UGI 44.24, W/10 7.5, NatInt 23.91. [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) +- Dolphin-Mistral-24B-Venice-Edition: UGI 40.79, W/10 7.8, NatInt 24.41. [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) +- Hermes is not very uncensored on UGI: + - Hermes-4-70B: W/10 3.2, NatInt 29.88 + - Hermes-4-405B: W/10 4.8 + - Hermes-4.3-36B: W/10 6.2 + + A Heretic pass on Hermes-4-70B raised W/10 only to 3.8 and cut NatInt to 27.54. [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) +- Josiefied (abliteration plus fine-tune): Qwen3-30B-A3B-abliterated-v2 scored NatInt 14.76 nt / 16.13 think, versus Qwen3-30B-A3B base 15.9 nt / 19.19 think, with W/10 7.8–8.2. [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) +- Fine-tunes that "jailbreak" gpt-oss-20b collapsed: + - aoxo gpt-oss-20b-uncensored: NatInt 2.44 + - michaelwaves amoral: NatInt 6.4 + - EeeLM NSFW: NatInt 9.43 + + Heretic/Derestricted versions of the same model scored about 17–24 (ArliAI 18.31; MuXodious RichardErkhov-heresy 22.52 with W/10 10.0). [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) + +**Merges (DavidAU-style; 2026 entries)** +- DavidAU/gemma-3-12b-it-vl-Polaris-GLM-4.7-Flash-VAR-Thinking-Instruct-Heretic-Uncensored: UGI 19.15, W/10 3.8, NatInt 18.6. Despite "Uncensored" in the name, that is essentially the base gemma-3-12b (UGI 20.89, W/10 3.0, NatInt 18.72). [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) +- DavidAU/Qwen3.5-9B-Claude-4.6-HighIQ-THINKING-HERETIC-UNCENSORED: + - No-think: UGI 18.19, W/10 2.8, NatInt 15.29 + - Prefill: UGI 30.32, W/10 6.5, NatInt 22.93 + - Base Qwen3.5-9B prefill: NatInt 30.98, so the merge lost about 8 points + - Plain abliterations of the 9B (huihui, trohrbaugh heretic-v2) reached W/10 9.0–9.5 + + [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) +- DavidAU/gemma-4-31B-it-The-DECKARD-HERETIC-UNCENSORED-Thinking (2026-06-14) is a strong exception: UGI 59.89 pf, W/10 10.0, NatInt 33.14. [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) +- Llama-3.3-70B community merges/fine-tunes rank high on UGI with NatInt at or above base. For example, KaraKaraWitch Golddiamondgold-Paperbliteration-L33-70b scored UGI 58.93, NatInt 35.32. [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) + +**Post-training to remove topic-specific censorship (Perplexity R1-1776, Feb 2025; older)** +- Perplexity fine-tuned DeepSeek-R1 on curated Q&A covering about 300 CCP-censored topics. Across MMLU, DROP, MATH-500 and AIME 2024, scores moved by a few tenths of a point, except AIME 2024: 79.8% versus 80.96%. [DeepLearning.AI The Batch](https://www.deeplearning.ai/the-batch/perplexity-launches-uncensored-version-of-deepseek-r1-ai-model) +- R1-1776-Distill-Llama-70B versus R1-Distill-Llama-70B: + + | Measure | Original | R1-1776 | + |---|---|---| + | MMLU | 88.52 | 88.40 | + | MATH-500 | 94.5 | 94.8 | + | AIME 2024 | 70 | 70 | + | Censorship score | 80.53 | 0.2 | + + [perplexity-ai/r1-1776-distill-llama-70b](https://huggingface.co/perplexity-ai/r1-1776-distill-llama-70b) +- Note: this targets political censorship, not general harmful-request refusals. + +**The user's current model (vendor claims, Aug 2026)** +- OrcaRouter Qwen3.8-Flash-Next-Uncensored: + - Base: about 176B total / 6B active; 48 layers (36 Gated DeltaNet + 12 full attention); 10-of-512 experts routed. + - Method: abliteration applied to 149 residual-writer tensors. Router, n-gram embedding table and vision tower were untouched. + - Claimed refusals: 64–100% → about 0–3.3%. Claimed capability within ±2 points on MMLU-Pro, GSM8K and CMMLU-style checks. + - Not independently reproduced. The GGUF omits the MTP head and needs an unmerged llama.cpp PR (#27742). The largest GGUF tier is Q5_K_M, about 125 GB. + + [OrcaRouter blog](https://www.orcarouter.ai/blog/qwen3-8-flash-next-uncensored); [Ollama listing](https://ollama.com/orcarouter/Qwen3.8-Flash-Next-Uncensored) + +### Inferences +- Rough ranking of methods by expected capability retention, taking the best-tuned release of each on the same base: well-tuned Heretic / MPOA / NPBA (about 0 to −3 NatInt) ≥ classic abliteration (0 to −17; huihui-style varies widely) > aggressive "ultra/ultimate" Heretic configs and generic "uncensored" SFT fine-tunes (often −5 to −20, sometimes collapse). R1-1776-style targeted post-training is near-lossless, but solves a different problem (political topics). +- The producer matters more than the method label. The same Heretic tool gave −0.3 and −13.1 NatInt on Qwen3.5 bases depending on who ran it and with what settings. Judge individual uploads, not method names. +- The thinking-prefill versus no-think scores often differ by 5–10 UGI or NatInt points. A model's "quality" depends on whether you run it with reasoning on. +- GSM8K/maths is the most damage-sensitive area in both the 2024 (mlabonne) and 2025 (arXiv 2512.13655) evidence. Test maths and multi-step reasoning first when evaluating a candidate. + +### Gaps +- No peer-reviewed study benchmarks ARA (Heretic 2.x default), SOMPOA, null-space or Abliterix's expert-granular method against base models. The ARA preprint was "coming soon" when Heretic was archived. +- No independent MMLU-Pro/GPQA before-and-after numbers were found for any 2026 large-MoE uncensored model. UGI NatInt is the only consistent cross-model capability proxy, and it is a single leaderboard's private test. +- mlabonne's 2024 benchmark tables are images; exact numbers not extracted. +- The UGI CSV has a "Repetition Interrupts" column, which may proxy looping, but I did not extract its values. + +--- + +## Q2. Current UGI leaderboard top entries, and which fit 24 GB VRAM + 128 GB RAM + +### Takeaway +On the UGI data as of about 2026-11-28, the top open-weight model is ArliAI/GLM-4.6-Derestricted-v3 (UGI 69.82; 355B-A32B). It fits this rig only at about 2.7–2.9 bits per weight, and it shows a large NatInt drop versus base GLM-4.6. + +The strongest entries that fit comfortably are: +- **Gemma-4-31B Heretic builds** (UGI about 65–66, NatInt about 36.5). These fit in VRAM alone. +- **Qwen3-VL-235B-A22B-Thinking-heretic** (58.08). +- **gpt-oss-120b Heretic variants** (51–54). +- **GLM-4.5-Air-Derestricted** (53.33). + +Qwen3.8-Flash-Next (OrcaRouter or any other uncensored build) is **not listed**. The only Qwen3.8 rows are base Qwen3.8-27B, tested 2026-11-26. + +### Cited Findings +- **Snapshot (2026-11-29):** + - #1 overall: xai/grok-4.20-multi-agent-beta-0309 (UGI 70.00, W/10 6.5, NatInt 56.34) + - #2 overall and top open-weight: ArliAI/GLM-4.6-Derestricted-v3 with `` prefill (UGI 69.82, W/10 8.8, NatInt 30.93) + - Top Heretic: coder3101/gemma-4-31B-it-heretic, thinking prefill (UGI 65.69) + - The UGI data file was last changed 2026-11-28, with 54 rows tested in November 2026 + + [abliterator.ai leaderboard guide](https://abliterator.ai/uncensored-llm-leaderboard) +- **Open-weight rows with UGI ≥ 55**, sorted by UGI. Memory-fit estimates are my own arithmetic (see Inferences). [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) + + | Model (mode) | Total / active params | UGI | W/10 | NatInt | Tested | Uncensored? | Fits this rig? | + |---|---|---|---|---|---|---|---| + | ArliAI/GLM-4.6-Derestricted-v3 (`` prefill) | 355B / 32B | 69.82 | 8.8 | 30.93 | 2026-03-02 | NPBA | Only at about 2.7–2.9 bpw (~120–130 GB); 32B active → slow | + | ArliAI/GLM-4.6-Derestricted-v3 (no-think) | 355B / 32B | 65.91 | 9.8 | 30.43 | 2026-03-02 | NPBA | same | + | darkc0de/XORTRON.CriminalComputing.LARGE.2026.3 | 123B dense | 66.16 | 8.2 | 36.87 | 2026-02-23 | fine-tune/merge | Q4 about 75 GB fits, but dense 123B is mostly in RAM → very slow | + | coder3101/gemma-4-31B-it-heretic (thought prefill) | 31B dense | 65.69 | 10.0 | 36.53 | 2026-04-12 | Heretic | Yes, Q4–Q5 fully in 24 GB VRAM | + | DeepSeek-V3.2-Speciale (base) | 671B / 37B | 65.37 | 4.8 | 53.02 | 2025-12-03 | no | No | + | llmfan46/gemma-4-31B-it-uncensored-heretic (prefill) | 31B dense | 64.99 | 10.0 | 36.41 | 2026-04-16 | Heretic | Yes | + | DeepSeek-V4-Pro (reasoning on; base) | 1.6T / 49B | 62.26 | 3.2 | 67.03 | 2026-04-26 | no | No | + | DavidAU gemma-4-31B DECKARD-HERETIC (prefill) | 31B dense | 59.89 | 10.0 | 33.14 | 2026-06-14 | Heretic + merge | Yes | + | SicariusSicariiStuff/Assistant_Pepe_70B | 70B dense | 59.52 | 9.5 | 35.25 | 2026-04-05 | fine-tune | Yes, Q4 about 42 GB with partial offload; slow | + | mistralai/Mistral-Large-Instruct-2411 (base) | 123B dense | 59.23 | 7.5 | 36.21 | 2025-09-30 | no | Q4 fits; slow | + | deepseek-ai/DeepSeek-V4-Flash (reasoning off; base) | 284B / 13B | 59.21 | 7.2 | 47.94 | 2026-04-26 | no (natively fairly willing) | Only at about 3 bpw (IQ3_XXS ~109 GB to Q3_K_M ~139 GB) | + | KaraKaraWitch/Golddiamondgold-Paperbliteration-L33-70b | 70B dense | 58.93 | 8.8 | 35.32 | 2026-02-22 | abliteration + merge | Yes (slow) | + | zai-org/GLM-5.2 (reasoning on; base) | 744B / 40B | 58.91 | 2.8 | 55.21 | 2026-06-21 | no | No | + | zai-org/GLM-4.5 (reasoning off; base) | 355B / 32B | 58.64 | 4.8 | 38.72 | 2025-10-02 | no | 2-bit only | + | Mistral-Large-3-675B (reasoning on; base) | 675B / 41B | 58.55 | 6.8 | 38.79 | 2025-12-06 | no | No | + | scrunter/Qwen3-VL-235B-A22B-Thinking-heretic | 235B / 22B | 58.08 | 9.2 | 33.7 | 2026-03-01 | Heretic | Yes at IQ4_XS (~125 GB) or Q3_K_M (~115 GB) | + | aifeifei798/Qwen3.5-Queen-27B (prefill) | 27B dense | 57.73 | 10.0 | 33.58 | 2026-05-03 | fine-tune | Yes, in VRAM | + | TheDrummer/Behemoth-X-123B-v2 | 123B dense | 57.19 | 8.2 | 34.67 | 2025-09-29 | fine-tune | Q4 fits; slow | + | DeepSeek-V3 / V3.1-Terminus (base, no reasoning) | 671B / 37B | 56.96 / 57.58 | 6.2 / 6.0 | 45.7 / 47.61 | 2025-09/10 | no | No | + | trohrbaugh/Qwen3.5-397B-A17B-heretic (no-think / prefill) | 397B / 17B | 56.44 / 56.19 | 9.5 / 10.0 | 33.25 / 39.48 | 2026-03-21 | Heretic | Only at about 2–2.7 bpw (IQ2_XXS ~102 GB to IQ2_M ~134 GB) | + | TareksGraveyard/Stylizer-V2-LLaMa-70B | 70B dense | 56.66 | 7.8 | 28.84 | 2025-10-11 | fine-tune | Yes (slow) | + | BruhzWater/Sapphira-L3.3-70b-0.1 | 70B dense | 56.03 | 8.0 | 30.94 | 2025-09-19 | fine-tune | Yes (slow) | + +- **Other uncensored MoE rows that fit easily** [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv): + + | Model | Params | UGI | W/10 | NatInt | Notes | + |---|---|---|---|---|---| + | MuXodious/gpt-oss-120b-tainted-heresy | 120B / 5.1B | 53.81 | 9.2 | 32.25 | | + | ArliAI/GLM-4.5-Air-Derestricted (thinking) | 106B / 12B | 53.33 | 8.8 | 36.62 | | + | jbeslt/gpt-oss-120b-heretic | 120B / 5.1B | 51.12 | 9.5 | 30.73 | | + | huihui-ai Huihui-gemma-4-26B-A4B-it-abliterated (prefill) | 26B / 4B | 53.15 | 10.0 | 33.95 | | + | MuXodious gemma-4-26B-A4B-it-SOMPOA-heresy (prefill) | 26B / 4B | 54.01 | 9.5 | 34.5 | | + | llmfan46 Qwen3.6-35B-A3B-uncensored-heretic (prefill) | 35B / 3B | 50.9 | 10.0 | 31.62 | | + | huihui-ai Qwen3-Next-80B-A3B-Instruct-abliterated | 80B / 3B | 41.81 | 8.5 | 27.28 | | + +- **Qwen3.8 status:** + - Qwen/Qwen3.8-27B (base) was tested 2026-11-26: UGI 22.71 nt / 28.6 pf, W/10 2.8 / 3.8, NatInt 28.28 / 26.57. + - No Qwen3.8-Flash-Next, orcarouter or Qwen3.8 uncensored rows exist in the data file. + + [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) +- **Most recent rows (tested 2026-11-26/27):** + - Qwen3.5-35B-A3B variants: llmfan46 ultra-uncensored-heretic 49.16 pf; Li101 Uncensored-Aggressive 47.55 pf / 45.93 nt; wangzhang abliterated 42.45 pf + - gemma-4-26B-A4B variants: huihui abliterated 53.15 pf; coder3101 heretic 51.72 pf; TrevorJS 48.05 pf + - Inkling-2-Mini (26B / 3.4B) uncensored variants: 37–46 + + No new large-MoE uncensored model entered the top ranks in Oct–Nov 2026. [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) +- **Other leaderboards** (as described by abliterator.ai, 2026-12-02): + - SpeechMap: % of 2,120 contested speech prompts answered; dated 2026-10-14. + - OpenUncensored: run by an API seller; top "DeepSeek V4.1 Flash 1017 Uncensored" at 81.0, measured 2026-11-08. + - DarkGPT: composite of UGI, MMLU-Pro, IFEval, EQ-Bench and downloads; top is GLM-4.6-Derestricted-v3 at 91.4. + - audn-ai/refusal-benchmark: 519 prompts; vendor-run. + - uncensoredllm.ai: ranked by price, not quality. + - llmindex.net and unrestricted.ai: mirror UGI, sometimes stale. + + [abliterator.ai](https://abliterator.ai/uncensored-llm-leaderboard) + +### Inferences +- **Fit arithmetic** (my estimates, using typical llama.cpp bits per weight: IQ2_XXS 2.06, IQ2_M 2.7, IQ3_XXS 3.06, Q3_K_M 3.9, IQ4_XS 4.25, Q4_K_M 4.85, Q5_K_M 5.7): + - The user's current 176B model at Q5_K_M is about 125 GB, which matches OrcaRouter's figure. That sets a proven budget of about 125–135 GB of weights on this rig. + - Within that budget: GLM-4.6 (357B) is about 2.7–2.9 bpw, Qwen3.5-397B about 2.1–2.7 bpw, DeepSeek-V4-Flash (284B) about 3.0–3.8 bpw, and Qwen3-VL-235B about 3.9–4.25 bpw. +- **Speed** (inference, not measured): per-token cost scales with active parameters. Against the current 6B-active model, GLM-4.6-Derestricted (32B active) would be several times slower, and dense 70B/123B models much slower again on a 24 GB card. gpt-oss-120b (5.1B active) and GLM-4.5-Air (12B active) should be comparable or moderately slower. +- **"At least as capable" is not shown by any fitting uncensored entry.** Two things stand out: + - The highest-NatInt open models that fit are base, not uncensored. DeepSeek-V4-Flash scores NatInt 47.94 and has fairly high native willingness (W/10 7.2 with reasoning off). Qwen3.5-397B base scores 47.78 but only fits at about 2 bits. + - Every uncensored entry that fits scores NatInt ≤ about 39.5. GLM-4.6-Derestricted's high UGI comes from willingness (W/10 8.8–9.8), while its NatInt (about 31) is well below base GLM-4.6 (about 42–45). +- **Practical shortlist** for "uncensored and fits", by evidence strength: + 1. Gemma-4-31B Heretic (coder3101 or llmfan46): high UGI, small NatInt loss, runs fully on GPU. + 2. Qwen3-VL-235B-A22B-Thinking-heretic at IQ4_XS/Q3. + 3. GLM-4.5-Air-Derestricted at Q6–Q8. + 4. gpt-oss-120b Derestricted or Heretic (ArliAI: NatInt 35.7, above base). + 5. GLM-4.6-Derestricted-v3, only if 2-bit quality and slow decoding are acceptable. + + DeepSeek-V4-Flash base (or a future uncensored derivative) is the capability pick if its native willingness is enough; other researchers cover DeepSeek. +- The current OrcaRouter model cannot be ranked against these on UGI. A direct comparison needs the user's own tests (Q5). + +### Gaps +- No UGI row exists for Qwen3.8-Flash-Next (base or uncensored), so there is no third-party capability or willingness figure for the user's current model. +- I could not render the live UGI page. Leaderboard ordering is reconstructed from the raw CSV via a summarising fetch; a few values may be misread. +- XORTRON.CriminalComputing.2026.27B.Instruct shows UGI/NatInt identical to Bobi099/Qwen3.5-27B-heretic (50.67/27.47 nt; 54.37/35.49 pf). That could be duplicate weights or an extraction artifact; unverified. +- GGUF availability and quality for the 2–3-bit fits (GLM-4.6-Derestricted, Qwen3.5-397B-heretic, DeepSeek-V4-Flash) were not checked. Low-bit quantisation adds its own capability loss on top of the uncensoring edit. + +--- + +## Q3. r/LocalLLaMA community recommendations (Oct–Dec 2026) for 24 GB GPU + 128 GB RAM + +### Takeaway +I could not retrieve any r/LocalLLaMA threads: search engines returned none, and Reddit blocks direct fetches. The only recommendations found are SEO-style guide sites with unclear method. Some of their picks (for example Dolphin 3.0 Mistral 24B) are contradicted by UGI data. + +### Cited Findings +- Guide sites (Nov 2026) recommend for 24 GB: + - "Qwen 3.8-27B abliterated" (Q4_K_M about 16.8 GB) + - Qwen 3.6-27B abliterated as fallback + - Dolphin 3.0 Mistral 24B + + For larger memory they suggest 70B-class models (Hermes 4 70B, huihui llama3.3-abliterated:70b). Methods are unclear, and none names a best uncensored model for 128 GB RAM. [localaimaster](https://localaimaster.com/blog/best-uncensored-local-llms); [yourunai](https://www.yourunai.com/uncensored-ai/best-models); [deepentresearch](https://deepentresearch.com/en/journal/uncensored-models) (search-summary level only; not fetched) +- Other guides list as popular picks: Gemma 4 26B-A4B Heretic (MoE, about 16.8 GB at Q4_K_M), GLM-4.7-Flash Heretic, and GLM 5.1 Heretic for 48 GB+. [locallyuncensored.com](https://locallyuncensored.com/blog/abliterated-models-guide.html); [pinkerton-ai](https://pinkerton-ai.com/blog/best-uncensored-llms-2026) (search-summary level; unverified) +- UGI contradicts the Dolphin pick: Dolphin3.0-Mistral-24B (UGI 35.25, W/10 5.8, NatInt 21.16) scores below its own base and below plain abliterations of that base. Hermes-4-70B has W/10 of only 3.2. [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) +- On tool calling: one guide advertises a Gemma 4 31B Heretic GGUF "with tool calling" and an agent-tagged Qwen 14B abliterated build. This is vendor-style marketing; no tool-calling evaluations were found. [locallyuncensored.com](https://locallyuncensored.com/blog/abliterated-models-guide.html) (search summary) + +### Inferences +- Without the Reddit threads, the closest proxy for "community consensus" is what the community submits to and scores well on UGI in 2026. That is Heretic/MPOA/Derestricted builds of Gemma-4 (31B, 26B-A4B), Qwen3.5/3.6 (27B, 35B-A3B), gpt-oss-120b and GLM-4.5-Air/4.6. Frequent uploaders include coder3101, llmfan46, MuXodious, ArliAI, huihui-ai and trohrbaugh. +- Complaints that abliterated models get "dumber" are supported by the NatInt data, for specific uploads (Q1 tables). Claims about looping and tool-calling loss have no quantitative support in what I found. + +### Gaps +- No Oct–Dec 2026 r/LocalLLaMA thread content was retrieved. Consensus picks, complaints (looping, tool-calling breakage) and any community view of the OrcaRouter model remain unverified. +- No tool-calling benchmark (for example BFCL) results for uncensored versus base models were found. + +--- + +## Q4. Is MoE abliteration less effective or more damaging than dense abliteration? Qwen3.x MoE evidence + +### Takeaway +Evidence from 2026 says refusal in MoE models is spread across attention, dense, shared-expert and routed-expert writers. Abliteration that misses the routed experts, which are often stored as fused 3D tensors, leaves much of the refusal in place while appearing to succeed. + +When all writers are edited, single-direction ablation does work on a 320B MoE with no significant benchmark change. Results on Qwen3.x MoE are mixed: some uploads keep or improve NatInt, others lose 8–13 points. No study compares MoE and dense directly. + +### Cited Findings +- **arXiv 2609.09793**, "How Fragile Is Safety Alignment at Frontier Scale? A Single-Direction Attack on a 320B MoE" (GLM-5.3-Flash: 320B / 18B active, 288 routed experts, top-8 routing, 1 shared expert; date not shown in the fetched text, likely Sept 2026 from the arXiv number): + - Editing attention, dense and expert writers separately removed 0.039, 0.016 and 0.148 of refusal respectively. Editing all three together removed 0.776, so the effect is strongly non-additive. + - Name-matching implementations that reach attention plus dense and shared projections, but miss the 12,384 routed-expert matrices inside fused 3D tensors, removed only 0.066. + - Refusal fell from 0.97 to 0.08 (MaliciousInstruct) and 0.97 to 0.131 (AdvBench), but only from 0.993 to 0.380 on StrongREJECT. + - XSTest false refusal went from 0.024 to 0.000. + - MMLU, MMLU-Pro, CMMLU and GSM8K moved by no more than 1.0 point. + - Category residue (violence, sexual, hate) survived up to rank-12 subspaces. + - The router was not edited, because it does not write to the residual stream. + + [HF Papers 2609.09793](https://huggingface.co/papers/2609.09793) +- **arXiv 2606.04160 v3** (2026-10-20, Marbut et al.): activation steering on GPT-OSS-20B, Mixtral 8x7B and OLMoE. Findings: + - Refusal is "distributed unevenly across the MoE LLM architecture rather than governed by a single unified mechanism". + - A single expert recovers 78% of full steering effect when free to choose its location. + - Routing-identified "safety experts" are not reliable predictors of effective steering directions. + - No Qwen models; no capability benchmarks; steering, not weight abliteration. + + [arXiv 2606.04160](https://arxiv.org/html/2606.04160) +- **Abliterix (v1.1.0, 2026-04-10)** argues for "Expert-Granular Abliteration": project the direction out of all expert `down_proj` slices, plus router suppression. + - It claims "dense-only abliteration leaves ~30% of refusals routed through untouched experts" on Gemma 4 26B-A4B. + - Reported results: Qwen3.5-35B-A3B 3/200 refusals at KL 0.0035; Qwen3.5-122B-A10B 1/200 at KL 0.0115. + - It also warns that model cards "routinely claim near-perfect scores" that "are not reproducible", citing one model claiming 3/100 that measured 60/100 in its pipeline. + - All tool-author claims. + + [Abliterix on PyPI](https://pypi.org/project/abliterix/1.1.0/) +- **wangzhang/Qwen3.6-35B-A3B-abliterated (Abliterix):** + - Rank-1 LoRA on attention o_proj and MLP down_proj + - EGA across all 256 expert down_proj slices per layer + - Router bias −2.10 on top-10 "safety experts" + - 100/100 → 7/100 refusals (Gemini-3-flash judge), KL 0.0189 + - Only 24/50 optimisation trials completed + - Author claims "refusal signal on MoE models lives in the expert path, not attention projections" + + [HF model card](https://huggingface.co/wangzhang/Qwen3.6-35B-A3B-abliterated) +- Despite low reported KL, the related wangzhang/Qwen3.5-35B-A3B-abliterated scored NatInt 23.13 pf / 20.32 nt on UGI, versus base 33.09 / 24.97. That run was not necessarily the same configuration as Abliterix's reported KL 0.0035 run. [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) +- **UGI NatInt deltas for Qwen-family MoE uploads** (pf / nt) [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv): + + | Base | Upload | Δ NatInt | + |---|---|---| + | Qwen3.5-35B-A3B | llmfan46 uncensored-heretic | +2.5 / +2.75 | + | Qwen3.5-35B-A3B | coder3101 heretic | −13.1 / −8.6 | + | Qwen3.5-35B-A3B | huihui | −10.8 / −8.5 | + | Qwen3.6-35B-A3B | llmfan46 | +0.6 / +3.0 | + | Qwen3-Next-80B-A3B | huihui | −1.0 | + | Qwen3.5-397B-A17B | trohrbaugh heretic | −8.3 / −7.8 | + | Qwen3-30B-A3B | Josiefied | −3.1 / −1.1 | + + Comparable dense Qwen3.5-27B uploads ranged from −0.3 (best) to −12.8 (huihui). +- An anecdotal LessWrong post describes a 4-bit MoE that still refused after many safety experts were suppressed, because attention independently detected harm. Search-summary level; not fetched. [LessWrong "Gatebreaker"](https://www.lesswrong.com/posts/BqdCKefiTiyoAF7Fy/gatebreaker-topological-ablation-and-multi-pathway-safety) +- Llama-3 era (older): newer llm-abliteration versions added MoE support (Mixtral, DeepSeek-MoE), but arXiv 2512.13655 evaluated no MoE models. [arXiv 2512.13655v2](https://arxiv.org/html/2512.13655v2) +- Expert pruning (a different MoE surgery) was very damaging on UGI: cerebras GLM-4.5-Air-REAP-82B scored NatInt 18.28 versus base 33.3, and MiniMax-M2-REAP 12.22 versus base 31.76. [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) + +### Inferences +- MoE abliteration is not inherently less effective, but it is easier to get wrong. Tools that match tensor names can silently skip fused routed-expert weights, producing models that still refuse much more than their cards claim. Tools that do hit every expert give themselves more ways to damage the model, and results vary widely by uploader. +- For the user's current model: OrcaRouter says it edited 149 residual-writer tensors in a 48-layer model. That is roughly three writer groups per layer (attention or DeltaNet out-proj, shared-expert down, fused routed-expert down) plus a few extras. It is consistent with all-writer coverage like the GLM-5.3 paper, but this is my inference from the count, not something OrcaRouter states. +- The large-MoE uncensored releases on UGI (Qwen3.5-397B heretic, GLM-4.6-Derestricted) lost 8–14 NatInt points, more than the best dense ones. Small-sample and confounded: large models are often abliterated in 4-bit or with fewer optimiser trials. + +### Gaps +- No controlled MoE-versus-dense comparison exists (same family, same tool, same budget). +- No Qwen3.8-Flash-Next-specific abliteration analysis or third-party measurement was found. +- The GLM-5.3 paper's per-benchmark Table 6 and authors/date were not in the fetched text. + +--- + +## Q5. Practical checks to compare an uncensored model against the current one + +### Takeaway +Use three layers of checks. +1. **Refusal rate on a fixed harmful set**, scored by an LLM judge (not keyword markers), plus a false-refusal set. +2. **KL divergence**, but only against each model's own base at the same quantisation; it is not meaningful across different model families. +3. **Short benchmark batteries** weighted toward maths, reasoning and your real tasks. GSM8K is the canary. + +Always test with thinking on and off. + +### Cited Findings +- **Heretic built-in comparison:** `heretic --model google/gemma-3-12b-it --evaluate-model p-e-w/gemma-3-12b-it-heretic` reproduces refusal counts and KL versus the original. The repo is archived but still runnable. [Heretic README v1.0.1](https://raw.githubusercontent.com/p-e-w/heretic/v1.0.1/README.md); [Heretic GitHub](https://github.com/p-e-w/heretic) +- **llama.cpp KL measurement (GGUF-native, fits this rig):** + 1. Run `llama-perplexity` on the reference model with `--kl-divergence-base .kld` to save its logits. + 2. Run the candidate with the same `--kl-divergence-base` file plus `--kl-divergence`. + + It reports mean KLD, PPL ratio, mean Δp, Δp percentiles, RMS Δp and "Same top p" (top-token agreement). The convention is Wikitext-2 (`scripts/get-wikitext-2.sh`). Logit files are large: 11 GiB for LLaMA 2, 37 GiB for LLaMA 3 vocab. [llama.cpp perplexity README](https://github.com/ggml-org/llama.cpp/blob/master/tools/perplexity/README.md) +- **Refusal test sets used in 2026 research:** MaliciousInstruct, AdvBench, JailbreakBench, HarmBench, StrongREJECT, SimpleSafetyTests and ForbiddenQuestions, with XSTest for false refusals on safe prompts. StrongREJECT and SimpleSafetyTests kept the most residual refusal after MoE abliteration. [HF Papers 2609.09793](https://huggingface.co/papers/2609.09793) +- **Judge refusals with an LLM, not keywords:** + - Keyword markers undercounted compliance (72.2% versus 95.7% classifier). [arXiv 2512.13655v2](https://arxiv.org/html/2512.13655v2) + - Abliterix uses an LLM judge with 150-token generations, because 30–50-token checks miss delayed refusals. Its author reports claimed "3/100" models measuring 60/100. [wangzhang card](https://huggingface.co/wangzhang/Qwen3.6-35B-A3B-abliterated); [Abliterix](https://pypi.org/project/abliterix/1.1.0/) +- **Benchmarks:** GSM8K was the most damage-sensitive in independent testing (up to −18.8 pp). MMLU and HellaSwag barely moved. [arXiv 2512.13655v2](https://arxiv.org/html/2512.13655v2) +- **Prompt mode:** UGI shows thinking-prefill versus no-think differences of up to about 10 UGI points for the same weights; for example, coder3101 gemma-4-31B heretic scored 56.38 plain and 65.69 with prefill. [UGI CSV](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv) + +### Inferences +Suggested protocol for this rig. These are my recommendations; the tools named are standard, but no source here benchmarks this exact workflow. + +1. **Refusals.** Take about 100–200 prompts drawn from HarmBench/StrongREJECT/AdvBench, plus about 100 XSTest safe prompts. Generate at least 150 tokens, with thinking on and off. Score refusals with an LLM judge. Run the current OrcaRouter model and each candidate through llama.cpp `llama-server`. +2. **Capability.** Run a short lm-evaluation-harness battery against the OpenAI-compatible `llama-server` endpoint: GSM8K (or a 200-item subset), MMLU-Pro subset, IFEval. Add 20–30 of your own real tasks, including tool-calling or JSON-format prompts and long multi-turn chats to catch looping. +3. **Damage from the edit.** + - For each candidate, compute llama.cpp KL against its own base model at the same quant. As a rough reference, Heretic-era good results were KL about 0.01–0.2, and above about 1 was clearly damaging (from the Q1 numbers). + - For the OrcaRouter model, compare against base Qwen3.8-Flash-Next at Q5_K_M, if the base GGUF exists for the same unmerged llama.cpp PR. + - Within one model family, compare "Same top p" and mean Δp. +4. **Speed.** Measure tokens/s at your real context length, since candidates with 13–32B active parameters will be slower than the current 6B-active model. + +### Gaps +- No public, standardised harness combines refusal, KL and capability for GGUF MoE models. The user has to assemble one. +- Heretic's KL computation details (which token positions, which prompt set) were not stated in the README fetched, so Heretic KL and llama.cpp KL numbers are not directly comparable. +- Heretic's default harmful/harmless datasets were not confirmed from the README fetched. diff --git a/docs/research/reports/Uncensored local LLM alternatives.md b/docs/research/reports/Uncensored local LLM alternatives.md new file mode 100644 index 0000000..de757ca --- /dev/null +++ b/docs/research/reports/Uncensored local LLM alternatives.md @@ -0,0 +1,138 @@ +# Few fitting models beat your uncensored Flash-Next + +No uncensored model that fits a 24 GB RTX 4090 plus 128 GB of RAM has been shown to be clearly more capable than your OrcaRouter Qwen3.8-Flash-Next Q5_K_M at a usable speed. The one stronger model is **DeepSeek V4.1-Flash-1017**. It beats Qwen3.8-Flash-Next on Artificial Analysis (Intelligence Index 32 vs 28, and 66.6% vs 55.9% on agentic tool use), but it fits only at about 2 bits. Its best-fitting uncensored build publishes no refusal rates, Strata dropped DeepSeek in 0.2.14, and llama.cpp should decode it at roughly 5–10 tok/s, against your 37. **The "Qwen 3.8 looping" model is real, but it is not a Qwen release.** It is a 268 MB recurrent-depth adapter from a community developer (alesha-pro, v1 posted about Dec 2). It adds 8 points on LiveCodeBench and uses a third fewer reasoning tokens, at the cost of about 30% of decode speed. It runs only on a draft Strata branch, not in your Strata 0.2.24 or llama.cpp b12774. Tencent's Hy4-Flash and Zhipu's GLM-5.3-Flash are peers with different strengths rather than upgrades, and everything else that fits is a step down. The best first move is a better-measured build of the model you already run. alesha-pro's Strata kit uses ISTA-DASLab's unmodified GSQ-RCO IQ3_S quant (83.6 GB) and removes the refusal direction at runtime. It measured 0/10 refusals with no added divergence, and it is the base the looped adapter is designed to pair with. Add DeepSeek in llama.cpp as a slow second model for hard agentic or coding work. Your download is newer than OrcaRouter's Sep 10 shard fix, so nothing needs re-downloading. Nearly every refusal and quality figure below is the uploader's own claim, and the main uncensored leaderboard does not list Flash-Next, so your own side-by-side tests should decide. + +## Your OrcaRouter build is sound, but its quality claim is unmeasured + +Your copy of orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF is in good shape. OrcaRouter found that the first shard of every quant had a zeroed `qwen4exp.attention.compress_ratios` field, caused by mismatched converter versions. It re-uploaded shard 00001 on **Sep 10**; the weights were unchanged ([OrcaRouter discussion #12](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/12)). Your Nov 5–6 download already has the fix. The only open integrity report, from about Nov 29, flags duplicate checksums in the **Q6_K and Q8_0** shards, not Q5_K_M ([discussions list](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions)). There is no v2. As of Oct 19 there was still no confirmed release of the "dynamic-precision" imatrix requant OrcaRouter announced in September ([discussion #12](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/12)), and none of the models visible on its org page is a new Flash-Next build ([orcarouter on HF](https://huggingface.co/orcarouter)). Strata's documentation is behind your setup: ORCA.md still calls IQ3_XXS (85.20 GB) "the only validated Orca quantization" ([Strata ORCA.md](https://github.com/Niko1221/Strata/blob/main/docs/ORCA.md)). Your measurements today are therefore the only record of how Q5_K_M behaves on engine 0.1.72: a 50 s cold load, 1,345 MiB of VRAM free, and **37 tok/s**. They are the bar every candidate must clear. Your three 44.5 GB shards, about 133 GB in all, also show the file size this machine is known to handle. + +OrcaRouter used classic abliteration: it "orthogonaliz[ed] the refusal direction out of the residual stream" ([model card](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF)). Its blog says it edited **149 tensors that write to the residual stream** and left the router, n-gram table and vision tower alone ([OrcaRouter blog](https://www.orcarouter.ai/blog/qwen3-8-flash-next-uncensored)). It claims harmful-prompt refusals drop from 64–100% to about 0–3.3%, and that capability stays "within ±2 pts" of base on MMLU-Pro, GSM8K and CMMLU-style checks. It gives no per-benchmark numbers and no KL divergence ([model card](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF)). On Sep 14 a user asked for per-quant KL divergence and perplexity; OrcaRouter replied "will add it", and no figures have appeared in that thread ([discussion #13](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/13)). The same thread points out that Q5_K_M averages about **6.1 bits per weight** because parts of it are stored at Q8, so quantization loss in your file is small. OrcaRouter's 27B card does publish numbers: MMLU-Pro 77.6 → 76.8, GSM8K 90.0 → 88.7, and HarmBench refusals 98.7% → 2.7% ([Qwen3.8-27B card](https://huggingface.co/orcarouter/Qwen3.8-27B-Uncensored-GGUF)). That suggests a careful process. Spread over 48 layers, 149 tensors is about three per layer. That fits an edit that covers the routed experts as well as attention, which matters for the next section. This is my inference; OrcaRouter does not list the tensors. + +Two quirks matter before you compare anything. First, reports of endless reasoning loops trace back to the upstream chat template, which defaults to xhigh reasoning effort. OrcaRouter recommends setting `reasoning_effort` to low or `enable_thinking=false`, plus `repeat_penalty` around 1.1 or DRY sampling at low quants ([discussion #7](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/7)). Second, OrcaRouter accepts that its near-uniform quant layout runs slower than Unsloth's dynamic layout, which keeps attention and shared experts at Q8_0. One user with a 16 GB card measured 4–6 tok/s on OrcaRouter's IQ4_XS against 20–40 tok/s on Unsloth's ([discussion #12](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/12)). Rebuilds of the same model on official quant recipes could therefore run faster than your current setup. + +## The uploader matters more than the method, and MoE edits fail quietly + +The raw data behind the UGI leaderboard is the largest public record of how uncensoring changes model quality. It shows the same method giving very different results in different hands ([UGI data](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv)). On gpt-oss-120b (base NatInt, the leaderboard's intelligence score, 33.68), huihui-ai's classic abliteration lost **17.0 points**. kldzj's Heretic run lost 0.3, and ArliAI's norm-preserving "Derestricted" build gained 2.0. On the Qwen3.5-35B-A3B MoE, two Heretic uploads landed at +2.5 (llmfan46) and **−13.1** (coder3101), and huihui-ai's abliteration lost 10.8. Damage tracks KL divergence. On gemma-3-12b, Heretic, huihui and mlabonne builds had KL divergences of 0.16, 0.45 and 1.04 ([Heretic README](https://raw.githubusercontent.com/p-e-w/heretic/v1.0.1/README.md)). Their NatInt scores fall in the same order: 15.68, 12.11 and 8.16, against a base of 18.72 ([UGI data](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv)). Maths breaks first. An independent study found Heretic cut Yi-1.5-9B's GSM8K score from **70.89% to 52.08%** while MMLU barely moved ([arXiv 2512.13655](https://arxiv.org/html/2512.13655v2)). The Heretic repository was archived on Nov 28, so its tooling will get no further fixes ([Heretic GitHub](https://github.com/p-e-w/heretic)). + +Mixture-of-experts (MoE) models add a failure that is easy to miss. A study on GLM-5.3-Flash (320B, 288 routed experts) edited attention, dense layers and experts separately. Each edit alone removed only 0.039, 0.016 and 0.148 of the refusal behaviour; editing all three together removed 0.776 ([arXiv 2609.09793](https://huggingface.co/papers/2609.09793)). The routed experts are stored as fused 3D tensors. Tools that pick tensors by name and miss them removed just **0.066**. With every writer edited, MMLU, MMLU-Pro, CMMLU and GSM8K moved by no more than 1.0 point, so a thorough MoE edit can be almost free. The candidates in this report show the same pattern. Mistral Small 4's attention-only edit still refused 25/100 harmful prompts ([brutalai](https://huggingface.co/brutalai/mistral-small-4-119b-abliterated)). distributedcognition's narrow DeepSeek edit left 47/100 hedged answers ([distributedcognition](https://huggingface.co/distributedcognition/DeepSeek-V4.1-Flash-1017-abliterated)). The Hy4-Flash Heretic Strata pack gave partial refusals on 41/100 ([narzh49](https://huggingface.co/narzh49/Hy4-Flash-Heretic-Strata)). huihui-ai's Flash-Next v2 deliberately ablates no experts, and its DeepSeek V4.1 patch touches only 18 attention tensors. Assume both leave some refusals until someone measures them. Model cards are not reliable on this point. The author of the Abliterix tool reports a model whose card claimed 3/100 refusals that measured 60/100 in his own tests ([Abliterix](https://pypi.org/project/abliterix/1.1.0/)). + +## Same-model rebuilds lead, and looping is not ready + +Qwen released no new open-weight 3.8 models in October–December. Qwen4-Max is API-only, and the smaller Qwen4 open weights have been promised without a date ([The New Stack](https://thenewstack.io/qwen4-max-alibaba-open-weights/?p=22843746)). Every Flash-Next alternative is therefore a different edit or quant of the same 125B-total, 6B-active base, which reports LiveCodeBench v6 91.9 and GPQA Diamond 91.7 ([llm-stats](https://llm-stats.com/blog/research/qwen3.8-flash-next-launch)). With the base fixed, the builds differ only in edit quality, quant precision and whether your runtimes can load them. + +| Build (exact repo) | Quants and sizes | Runs on your PC | Method and evidence | Verdict vs current | +| --- | --- | --- | --- | --- | +| **Current:** [orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF) | Q5_K_M ~125 GB per card (your shards ~133 GB) | Strata 0.2.24 (measured); mainline llama.cpp for non-MTP quants | Abliteration of 149 residual-stream tensors; self-reported 0–3.3% refusals, ±2 pts; no KL | Baseline | +| [alesha-pro/Qwen3.8-Flash-Next-abliterated-GSQ-RCO-Strata-GGUF](https://huggingface.co/alesha-pro/Qwen3.8-Flash-Next-abliterated-GSQ-RCO-Strata-GGUF) | Q2_0 66.4, IQ2_XS 68.0, IQ3_XXS 75.8, **IQ3_S 83.6 GB** (each includes a 28.8 GB n-gram shard), plus a 480 KB refusal vector | Strata only. llama.cpp loads the files but runs them censored | Unmodified ISTA-DASLab weights; refusal direction removed at runtime in layers 4–44. Refusals 10/10 → **0/10** with thinking off and 9/10 → 0/10 with it on. KL to the BF16 reference fell 0.083 → 0.074 at IQ3_S. Agent coding 5/5, needle-in-a-haystack 6/6 | Same model, better evidence, lower precision | +| [huihui-ai/Huihui-Qwen3.8-Flash-Next-abliterated-v2-GGUF](https://huggingface.co/huihui-ai/Huihui-Qwen3.8-Flash-Next-abliterated-v2-GGUF) (~Nov 9) | IQ2_XS 68.2, IQ3_S 83.7, UD-IQ4_XS 93.7, UD-Q4_K_XL ~111, UD-Q5_K_XL 158, Q8_0 188 GB | llama.cpp; Strata only after patching out its SHA-256 check | Abliteration with no experts touched. Card says "PPL decreased slightly"; no refusal, KL or benchmark numbers. 1.3M downloads a month | Unmeasured; likely leaves some refusals | +| [trohrbaugh/Qwen3.8-Flash-Next-heretic](https://huggingface.co/trohrbaugh/Qwen3.8-Flash-Next-heretic) | BF16 safetensors only (177B parameters) | Neither, unless you convert it yourself | Heretic fork; KL 0.116; refusals 99/100 → 0/100 | Best-measured permanent weight edit, but no named GGUF | +| [mr-andrey-isachenko/Tenet-Qwen3.8-Flash-Next-125B-A6B-Abliterated-Unslop-v3-GGUF](https://huggingface.co/mr-andrey-isachenko/Tenet-Qwen3.8-Flash-Next-125B-A6B-Abliterated-Unslop-v3-GGUF) | Q2_K 85.06 to Q5_K_M 137.85 GB | llama.cpp | Abliteration plus a "de-slop" fine-tune. Own card: GPQA 0.42 → 0.35, MMLU-Pro 0.59 → 0.51 | Loses capability | +| [FangZhangTNS/Qwen3.8-Flash-Next-REAP-Pruned-Abliterated-EN-Writing-RP-V2-GGUF](https://huggingface.co/FangZhangTNS/Qwen3.8-Flash-Next-REAP-Pruned-Abliterated-EN-Writing-RP-V2-GGUF) | k256-IQ4_XS 62.73 GiB down to k192-IQ3_S 52.70 GiB | Strata (48.7 tok/s on 0.1.63) | Coding and non-English experts pruned; huihui v2 abliteration. Writing Elo at parity for k256 | Writing and roleplay only | +| [tiraisoft/Qwen3.8-Flash-Next-GSQ-RCO-abliterated-Basalt](https://huggingface.co/tiraisoft/Qwen3.8-Flash-Next-GSQ-RCO-abliterated-Basalt) | 70.8 GB | Needs a Blackwell (sm_120) GPU | — | Will not run on a 4090 | + +The alesha-pro kit is the strongest option built on the same model, because its edit is not baked into the weights. Strata removes each hidden state's component along a refusal direction (`h = h − (h·r) r`). The direction was extracted from huihui-ai's BF16 checkpoint ([alesha-pro kit](https://huggingface.co/alesha-pro/Qwen3.8-Flash-Next-abliterated-GSQ-RCO-Strata-GGUF)). That has three benefits. The quant stays ISTA-DASLab's official recipe, which Strata's installer supports directly ([Strata MODELS.md](https://github.com/Niko1221/Strata/blob/main/docs/MODELS.md)). Measured divergence did not rise; it fell slightly. And the edit can be switched off for a single request with `"experimental_speed_projection": false`, which gives you a censored and an uncensored model on identical weights for a clean comparison. On an RTX 3090 with an EPYC 7642 and 125 GB of RAM, IQ3_S decoded at **58.1 tok/s at a 4K prompt** and 46.6 tok/s at 131K, with 50 GB of experts held in RAM ([alesha-pro kit](https://huggingface.co/alesha-pro/Qwen3.8-Flash-Next-abliterated-GSQ-RCO-Strata-GGUF)). Your dual-channel DDR5 has less bandwidth than eight-channel EPYC memory, so treat that figure as a ceiling. Still, the file is about 50 GB smaller than yours. + +The costs are real. This is a 3-bit quant replacing a ~6-bit one, and its KL of 0.074–0.083 is well above the 0.013–0.021 noise floor, so the precision loss is measurable. The refusal test used only 10 prompts, and the kit was tested on Strata 0.1.38, not your engine 0.1.72. The `--experimental-speed-projection` setup flag that turns on Strata's own bundled vector does not appear in Strata's README or MODELS.md; its existence rests on the kit card and a secondary write-up ([gopenai](https://blog.gopenai.com/the-censorship-switch-strata-hid-in-its-own-repo-cc0e4085aa9e)). If 3 bits is too low, the same vector should transfer to Unsloth's UD-Q4_K_XL (111 GB), because it is a direction in the base model's residual stream rather than a property of one quant. That is my inference, and nobody has published refusal numbers for that pairing. + +A different repack keeps OrcaRouter's own edit and may be faster. One user ran a Maximilian228 NVFP4-GPTQ Strata repack of the OrcaRouter weights at **38–44 tok/s** on an RTX 4070 SUPER 12 GB with 96 GB of DDR5, refusing 0 of 5 test prompts ([discussion #20](https://huggingface.co/orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF/discussions/20)). That card is weaker than yours yet beat your 37 tok/s. However, the exact repo name could not be confirmed. Its non-uncensored sibling reports 93.6% top-token agreement with the original and needs driver 580 or newer, which your 616.56 meets ([mixpeek](https://mixpeek.com/model/Maximilian228/Qwen3.8-Flash-Next-NVFP4-GPTQ-Strata)). It trades precision for speed against your ~6-bit file. + +The dense Qwen3.8-27B is a fast fallback, not an upgrade. [orcarouter/Qwen3.8-27B-Uncensored-GGUF](https://huggingface.co/orcarouter/Qwen3.8-27B-Uncensored-GGUF) has the best-documented edit of the 27B builds, and its Q5_K_M (18.2 GB) or Q6_K (20.9 GB) fits entirely in VRAM under llama.cpp. But Qwen3.8-27B scores 20.1 on Artificial Analysis v5.0 according to Thinking Machines' comparison table ([Inkling 2 Mini card](https://huggingface.co/thinkingmachines/Inkling-2-Mini)); Artificial Analysis lists Flash-Next at 28 ([AA](https://artificialanalysis.ai/models/qwen3-8-flash-next)). The 27B also trails on LiveCodeBench (72.6% vs 77.71%), GPQA (86.9% vs 91.41%) and AIME 2025 (90.0% vs 96.67%) in the looped adapters' test setups ([sliderforthewin](https://huggingface.co/sliderforthewin/Looped-Qwen3.8-27B); [alesha-pro looped](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next)). + +### The looping model is a community adapter that trades speed for accuracy + +The model behind the rumour is [alesha-pro/Looped-Qwen3.8-Flash-Next](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next), posted as "v1 (Stage 2 RLVR)" about a day before this report. It is not a new model. It is a 268 MB FP32 add-on with 70.2M parameters (0.056% of the base) that makes layers 16–31 of the unchanged Flash-Next run two or three times per token. It was trained with 1,200 steps of distillation plus 200 steps of reinforcement learning; with one pass (T=1) it is identical to stock, and it is MIT-licensed. Strata issue #7693 links to a different repo, sliderforthewin/Looped-Qwen3.8-Flash-Next, and nobody has explained the discrepancy ([issue #7693](https://github.com/Niko1221/Strata/issues/7693)). Download only from the repo the Strata pull request uses. + +| Benchmark (vLLM FP8, 64k reasoning budget) | Stock Flash-Next | Looped | +| --- | --- | --- | +| LiveCodeBench v6 | 77.71% | **85.71%** | +| GPQA Diamond | 91.41% | 91.41% | +| AIME 2025 | 96.67% | 93.33% | +| HumanEval+ Direct | 84.15% | 79.88% | +| All 731 items | 84.68% | 85.64%, using 34.2% fewer tokens | + +With the reasoning budget capped at 24k tokens, the gains grow: LiveCodeBench rises from 57.5% to 77.5% at two passes and 82.5% at three, and AIME 2025 from 80.0% to 90.0% ([alesha-pro looped](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next)). So the adapter's main effect is to reach answers in fewer reasoning tokens. With a generous budget it gives a coding gain and small losses elsewhere. On an RTX 3090 with experts in RAM, the author measured 132.6 tok/s at one pass and about 91 tok/s at two. The Strata pull request's author measured 101.8 vs 72.3 tok/s, dropping to 37.5 tok/s at two passes when the expert cache missed ([PR #7673](https://github.com/Niko1221/Strata/pull/7673)). Losing about 30% of decode speed while generating 34% fewer tokens leaves the time per answer roughly unchanged, with +8 on LiveCodeBench. That is my arithmetic from the author's figures; it has not been measured on a 4090. + +Neither of your runtimes can use the adapter. It needs a Strata CUDA fork branch (`feat/looped-qwen4exp`, run with `--loop-adapter ckpt_final.safetensors --loop-passes 2`) or a vLLM plugin; llama.cpp is not supported ([alesha-pro looped](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next)). Upstream Strata PR #7673, opened Dec 2, is still a draft. It is CUDA/HIP only, does not work with `--batch > 0` or `--pipeline-windows`, and has had no maintainer review; a Dec 3 code review lists seven possible bugs ([PR #7673](https://github.com/Niko1221/Strata/pull/7673)). The adapter does not remove refusals by itself. Its card recommends pairing it with the alesha-pro GSQ-RCO kit, and nobody has tested it on models with baked-in edits like OrcaRouter's, so you cannot simply add it to your current model. The uncensored looped 27B, [jakeatx/qwen3.8-27b-Swift1.5-Uncensored-ATX-AI4-Looped-GGUF](https://huggingface.co/jakeatx/qwen3.8-27b-Swift1.5-Uncensored-ATX-AI4-Looped-GGUF) (13.56 GiB), needs a llama.cpp fork called llamAmpere (v0.8+). Its author found "no measurable gain" (40/50 vs 39/50). Wait for PR #7673 to merge. Moving to the alesha-pro kit now puts you on the path the adapter expects. + +## DeepSeek V4.1-Flash-1017 is the one real upgrade, at a fraction of the speed + +DeepSeek's newest open weights are V4.1-Flash (Sep 10) and its revision V4.1-Flash-1017 (Oct 17). There are no R2, Lite or V4.1-Pro open weights on Hugging Face ([deepseek-ai on HF](https://huggingface.co/deepseek-ai); [Morph](https://www.morphllm.com/deepseek-v4-1-flash)). The checkpoint is 763B. About 552B of that is the MoE model itself (384 routed experts, 6 active per token, plus 1 shared). The other ~196B is an "Engram" n-gram table that is read by token lookup. Context is 1M tokens, and 8B parameters are active during prompt processing and **16B during decoding** ([Morph](https://www.morphllm.com/deepseek-v4-1-flash); [orcarouter V4.1 card](https://huggingface.co/orcarouter/DeepSeek-V4.1-Flash-1017-abliterated-GGUF)). That is about 2.7 times Flash-Next's 6B. At full precision it is the only model in reach that is clearly stronger: + +| Artificial Analysis metric | V4.1-Flash-1017, max effort | V4.1-Flash-1017, high effort | Qwen3.8-Flash-Next | +| --- | --- | --- | --- | +| Intelligence Index | **32** | 29 | 28 | +| AutomationBench-AA (agentic, tool use) | 66.6% | 68.5% | 55.9% | +| Terminal-Bench 4.1 | 32.3% | 29.8% | 24.2% | +| HLE-Diamond | 25.3% | 20.8% | 16.3% | +| FrontierCode-AA 2.0 | 28.2% | 16.8% | 27.1% | +| AA-Omniscience v1.1 | 1 | 2 | −12 | + +The source is [Artificial Analysis](https://artificialanalysis.ai/models/comparisons/deepseek-v4-1-flash-1017-vs-qwen3-8-flash-next). DeepSeek leads on agentic work, terminal coding and hard reasoning, and it makes fewer confident factual errors (the Omniscience row). GPQA is roughly a tie; sources disagree (90.9–93.2% vs 91.7%) ([Novita](https://novita.ai/compare/deepseek-vs-qwen); [Respan](https://www.respan.ai/models/compare/deepseek-v4-1-flash-1017-vs-qwen3-8-flash-next)). No creative-writing comparison was found. + +The problem is quantization. To fit, DeepSeek has to run at 1–2 bits, with the Engram table memory-mapped from NVMe instead of loaded into RAM. Unsloth's UD-IQ1_S is 233.0 GB on disk, of which 122.4 GB must sit in RAM and VRAM. UD-IQ1_M is 250.4 GB with 139.8 GB resident. UD-IQ2_XXS needs 165.3 GB resident, which is too much ([Unsloth guide](https://unsloth.ai/docs/models/deepseek-v4.1-flash)). ISTA-DASLab says its own IQ1_M and IQ2_XXS quants fit resident on a 24 GB GPU plus 128 GB of RAM, and IQ2_XS does not ([OpenClaw DC](https://openclawdc.com/blog/deepseek-v4-1-flash-gsq-rco-quants/)). The quality evidence is mixed. ISTA scores its IQ2_XXS at 100% of base on AIME25, GPQA-D and LiveCodeBench v6, and IQ1_M at 98.7%. Strata's measurements show perplexity up 15.5% at IQ2_XXS (KL 0.170) and prose perplexity up 53% at IQ1_M ([OpenClaw DC](https://openclawdc.com/blog/deepseek-v4-1-flash-gsq-rco-quants/)). Unsloth's benchmark average falls from 87.68 at Q8 to 86.63 at IQ2_XXS, 85.55 at IQ1_M and 83.53 at IQ1_S, and its Aider coding score from 44.38 at IQ2_XXS to 36.52 at IQ1_S ([Unsloth guide](https://unsloth.ai/docs/models/deepseek-v4.1-flash)). Reasoning benchmarks survive at 2 bits, while prose and code editing degrade at 1 bit. IQ2_XXS is the lowest quant worth using. + +| Build (exact repo) | Quant and size | Runtime on your PC | Method and evidence | Verdict | +| --- | --- | --- | --- | --- | +| [Abiray/DeepSeek-V4.1-Flash-1017-Uncensored-GSQ-RCO-IQ2_XXS-GGUF](https://huggingface.co/Abiray/DeepSeek-V4.1-Flash-1017-Uncensored-GSQ-RCO-IQ2_XXS-GGUF) | IQ2_XXS: 138.58 GB model (5 shards) + 110.60 GB IQ4_NL Engram file, linked in as shard 6 + 0.97 GB mmproj | Card says llama.cpp b11870+, so b12774 should load it (untested). Strata only up to 0.2.13, and its file-size check may reject it | Permanent abliteration of 86 tensors (80 dense, 6 expert) using AtomicChat's English and Russian directions. KL divergence 0.0095 and 98.4% top-token agreement vs the stock IQ2_XXS. **No refusal rates** | Best fit and fidelity | +| [huihui-ai/Huihui-DeepSeek-V4.1-Flash-1017-abliterated-GGUF](https://huggingface.co/huihui-ai/Huihui-DeepSeek-V4.1-Flash-1017-abliterated-GGUF) | Patches for Unsloth UD-IQ1_S (233.0 GB, 122.4 GB resident), UD-IQ1_M (250.4 / 139.8 GB) and others | llama.cpp b11870+ | 18 `attn_output_b` tensors in layers 11–28; experts untouched; no evidence | Most memory headroom; likely leaves some refusals; 1-bit quality loss | +| [orcarouter/DeepSeek-V4.1-Flash-1017-abliterated-GGUF](https://huggingface.co/orcarouter/DeepSeek-V4.1-Flash-1017-abliterated-GGUF) | Mix-128G: 225.0 GB download, 114.0 GB resident. Mix-256G: 346.5 / 235.8 GB | llama.cpp PR #30817 build (not in master) or Ollama ≥ 0.40.16 | On the unquantized model: refusals 0.874 → 0.074 over 500 prompts, false refusals 0.069 → 0.006, MMLU 0.910 → 0.920. Mix-128G: KL 0.520, 78.5% top-token agreement, perplexity +54.7% | Best-measured edit, but the quant that fits is badly degraded | +| [huihui-ai/Huihui-DeepSeek-V4-Flash-0731-abliterated-GGUF](https://huggingface.co/huihui-ai/Huihui-DeepSeek-V4-Flash-0731-abliterated-GGUF) | Q2_K 97.6 GB | llama.cpp (latest) | Author calls it a "crude" abliteration; experts untouched; no data | Older 284B, 13B-active model; fits easily | +| [audreyt/CyberNeurova-DeepSeek-V4-Flash-abliterated-GGUF](https://huggingface.co/audreyt/CyberNeurova-DeepSeek-V4-Flash-abliterated-GGUF) | Q2_K ~81 GB | llama.cpp | No details seen beyond the search snippet | Older model | +| [prem-research/DeepSeek-V4-Flash-0731-abliterated](https://huggingface.co/prem-research/DeepSeek-V4-Flash-0731-abliterated) | FP8/FP4 safetensors | vLLM or SGLang, not your PC | Arbitrary-Rank Ablation in layers 17–36, including the 8 most-used experts; refusals 69% → 3% over 800 prompts; KL 0.044 | Best V4-Flash edit, wrong format | + +llama.cpp is the realistic runtime. Support for this architecture (`deepseek41`) was merged on Oct 25 in PR #31086, around build b11870 ([llama.cpp PR #31086](https://github.com/ggml-org/llama.cpp/pull/31086)). Loading the Engram table (`--ple`) needs b12233 or later ([Unsloth guide](https://unsloth.ai/docs/models/deepseek-v4.1-flash)), so b12774 qualifies on paper, but nobody has reported running it. Sources disagree on whether ISTA's GSQ-RCO files load. On Oct 25 ISTA said they "do not run in llama.cpp yet". The reviewer who merged PR #31086 added a small patch for them, and Abiray says its build runs on b11870+ ([OpenClaw DC](https://openclawdc.com/blog/deepseek-v4-1-flash-gsq-rco-quants/); [PR #31086](https://github.com/ggml-org/llama.cpp/pull/31086); [Abiray](https://huggingface.co/Abiray/DeepSeek-V4.1-Flash-1017-Uncensored-GSQ-RCO-IQ2_XXS-GGUF)). Unsloth warns that newer builds silently misread MXFP8 Engram tables, which ship with UD-Q3_K_XL and larger. Abiray and Unsloth's UD-IQ1 quants use IQ4_NL tables, so they are not affected. Keep the Engram file memory-mapped (no `--mlock` or `--no-mmap`) and use `--override-tensor "per_layer_token_embd.weight=CPU"` ([Unsloth guide](https://unsloth.ai/docs/models/deepseek-v4.1-flash)). Abiray's Engram file has to appear as shard 6. On Windows, a hard link (`mklink /H`, same volume) avoids storing 110 GB twice. + +Strata is closed to DeepSeek for now. Version 0.2.14, released in mid-November, removed DeepSeek support with no stated reason. On Nov 19 the maintainer said it "will come back to Strata soon" ([Strata DEEPSEEK41.md](https://github.com/Niko1221/Strata/blob/main/docs/DEEPSEEK41.md); [issue #6072](https://github.com/Niko1221/Strata/issues/6072)). Users have run 0.2.13 with its frozen 0.1.59 engine next to newer versions, using frozen copies or git worktrees. But the official downgrade replaces your install, its Windows steps have only been tested on Linux, auto-update has to be blocked with `STRATA_UPDATE_CHECK=0`, and both versions share `active.json` and `state.json`. The 0.1.59 engine is also slower than 0.1.55: 17.4 vs 20.8 tok/s on a 24 GB laptop GPU ([issue #6048](https://github.com/Niko1221/Strata/issues/6048)). Another option is [kuu-Strata-fork](https://github.com/midokino/kuu-Strata-fork), a Windows fork of 0.2.12 that keeps the DeepSeek engine. It reached about 31 tok/s on short replies on an RTX 5070 12 GB with 64 GB of RAM by using five of the six experts and adding a draft model, at a KL cost of 0.057–0.183. It has to be built with CUDA 13 and VS 2022, outside the CUDA 12.4 toolchain you use, and it does not cover the uncensored builds. + +Nobody has reported llama.cpp speeds on a 4090 with 128 GB of RAM. The merge reviewer measured **6.6 tok/s** decode on an R9700 plus RTX 5060 with 128 GB ([PR #31086](https://github.com/ggml-org/llama.cpp/pull/31086)). A CPU-only server using 64 threads reached about 10 tok/s ([orcarouter V4.1 card](https://huggingface.co/orcarouter/DeepSeek-V4.1-Flash-1017-abliterated-GGUF)). My estimate for your machine is 5–10 tok/s, roughly 4–7 times slower than now. Thinking is on by default at effort 75 ([Unsloth guide](https://unsloth.ai/docs/models/deepseek-v4.1-flash)), and in Obscurify's tests the thinking builds sometimes used up their 3,000-token reasoning budget before answering ([Obscurify](https://obscurify.ai/deepseek-uncensored)). Hard prompts will take minutes. You do need an uncensored build: stock 1017 refuses 87.4% of harmful prompts on a weighted score ([orcarouter V4.1 card](https://huggingface.co/orcarouter/DeepSeek-V4.1-Flash-1017-abliterated-GGUF)). China-political bias is a separate issue. CTGT found that V4-Flash-0731's censorship of China-sensitive prompts rose from 57.4 to 63.8 while censorship of other topics fell from 25.4 to 19.8 ([CTGT](https://www.ctgt.ai/research/v4-flash-0731-drift)). With R1, an uncensored build stopped refusing but still repeated Party-state framing on Taiwan ([China Media Project](https://chinamediaproject.org/2025/06/24/deepseeks-democratic-deficit/)). Nobody has measured China-topic behaviour for any abliterated V4.1 build. + +## Hy4-Flash and GLM-5.3-Flash are peers; the rest step down + +Tencent's [Hy4-flash](https://huggingface.co/tencent/Hy4-flash) was released Nov 17. It has 220B parameters (64B of them in an Engram lookup table) with about 12B active per token, 1M context, a built-in draft model and image input, under Tencent's own licence. Artificial Analysis has not scored it; it lists only the full Hy4 at 35 ([AA open-source list](https://artificialanalysis.ai/models/open-source)). Aggregators disagree. LLM Stats gives Hy4-Flash a composite of 41 against 47 for Flash-Next ([llm-stats](https://llm-stats.com/models/compare/hy4-flash-vs-qwen3.8-flash-next)). Canitrun, reading Tencent's table, has Hy4-Flash ahead on OSWorld 2.1 (68.1 vs 58.8) and APEX-Agents (63.1 vs 57.6), and Flash-Next ahead by 10.3 points on Terminal-Bench 4.0 and 6 on ProgramBench ([canitrun](https://canitrun.dev/models/compare/hy4-flash-vs-qwen3.8-flash-next/)). In a hands-on video Flash-Next ran at about 43 tok/s and Hy4-Flash at 29, with equal total task times ([samuelgregory.co.uk](https://www.samuelgregory.co.uk/videos/hy4-flash-vs-qwen-38-flash-next)). An aggregator reports about 58 tok/s on a 4090D using Strata ([besthub](https://www.besthub.dev/articles/hy4-flash-quantized-410gib-125gib-24gb-gpu-hits-58-tok-s-via-offload-can-your-hardware-run-it-bb307e2e2d98)). Strata 0.2.24 itself added Hy4-Flash ([Strata releases](https://github.com/Niko1221/Strata/releases)). Its stock packs are SQ-64 (62.0 GB), SQ-96 (89.6 GB) and SQ-128 (113.7 GB), each with a 67.6 GB Engram shard kept on SSD ([Strata MODELS.md](https://github.com/Niko1221/Strata/blob/main/docs/MODELS.md)). The stock model refuses 85% of the HarmBench-200 prompts ([hletrd](https://huggingface.co/hletrd/Hy4-flash-Uncensored-GGUF)), and 100/100 in another test ([trohrbaugh](https://huggingface.co/trohrbaugh/Hy4-flash-heretic-FP8)). + +| Build (exact repo) | Quant and size | Runtime on your PC | Method and evidence | Verdict | +| --- | --- | --- | --- | --- | +| [narzh49/Hy4-Flash-Heretic-Strata](https://huggingface.co/narzh49/Hy4-Flash-Heretic-Strata) (Nov 27) | SQ-64 62.03 GB, **SQ-128 113.65 GB**; also needs Strata's stock Engram-Q8 and Vision packs | Strata 0.2.24 (`--family hy4-flash --model-path …`) | Heretic edit of 102 tensors in layers 8–41, taken from trohrbaugh's BF16 Heretic build. On SQ-64: 73 full refusals, 26 partial, 1 compliant → 1 / 41 / 58. No capability benchmark; almost no downloads | Only one that loads in your Strata unchanged | +| [hletrd/Hy4-flash-Uncensored-GGUF](https://huggingface.co/hletrd/Hy4-flash-Uncensored-GGUF) (Nov 28) | IQ3_M-E4 108.1, Q3_K_M-E4 114.2, **IQ4_XS-E4 122.6 GB** | Only on llama.cpp PR #32517, which was closed without merging | One refusal direction removed. HarmBench-200 refusals 85.0% → 10.5% at Q4_K_M; 1–3% false refusals; at IQ4_XS, KL vs BF16 is 0.238 against 0.171 for the stock quant | Best GGUF evidence, but no runtime | +| [mrfakename/Hy4-flash-abliterated-GGUF](https://huggingface.co/mrfakename/Hy4-flash-abliterated-GGUF) (Nov 28) | IQ4_XS ~123 GB, plus a small `abliteration-lora.gguf` | A llama.cpp build that supports Hy4 | Single-direction ablation tuned over 100 trials. Refusals 4/100 in chat and 6/100 with thinking; KL 0.233. Thinking replies run long: 44/100 unfinished at 768 tokens vs 2–4 for stock ([card](https://huggingface.co/mrfakename/Hy4-flash-abliterated)) | Long-winded when thinking | +| [alesha-pro/Hy4-flash-Uncensored-GGUF](https://huggingface.co/alesha-pro/Hy4-flash-Uncensored-GGUF) (Nov 19) | IQ2_XXS set 115 GB; Q3_K set 150 GB (86.2 GB model + 63.4 GB Engram) | Project Maya fork only | 4 KB vector applied at runtime. Refusals 139 → 32 of 146 prompts (thinking off), 22 → 3 of 24 (thinking on); median KL 0.014 | Least damage, but needs a fork | +| [orcarouter/Hy4-flash-abliterated-GGUF](https://huggingface.co/orcarouter/Hy4-flash-abliterated-GGUF) (Nov 21, gated) | Mix-128G ~138 GB | GGUF; Strata support requested in [issue #7685](https://github.com/Niko1221/Strata/issues?q=uncensored+OR+abliterated+OR+loop+OR+orca) | Card is gated; method unknown | Unknown | + +The Hy4 builds with better evidence are stuck in runtimes you don't have. The llama.cpp pull request for Hy4-Flash (#32517) was closed without merging ([PR #32517](https://github.com/ggml-org/llama.cpp/pull/32517)). AngelSlim's own GGUF uses a different architecture tag, `hy_v4_next_dfly`, with its own llama.cpp patch ([AngelSlim](https://huggingface.co/AngelSlim/Hy4-flash-GGUF)). mrfakename's LoRA file could in principle be applied to a stock GGUF with `--lora`, but nobody has tested it against AngelSlim's architecture tag. Choose Hy4-Flash if computer-use and office-agent work matter more to you than coding, and expect the Strata pack to give partial answers. + +**GLM-5.3-Flash** ([zai-org](https://huggingface.co/zai-org/GLM-5.3-Flash), 320B total, 18B active, MIT licence) ties Flash-Next on Artificial Analysis (28 vs 29 on the comparison page) ([AA comparison](https://artificialanalysis.ai/models/comparisons/glm-5-3-flash-vs-qwen3-8-flash-next)). Its uncensored GGUF is [kcarly/Huihui-GLM-5.3-Flash-abliterated-GGUF](https://huggingface.co/kcarly/Huihui-GLM-5.3-Flash-abliterated-GGUF) (Dec 1). It fits at **UD-Q2_K_XL (109 GB) or UD-IQ3_XXS (120 GB)**; UD-Q3_K_XL (148 GB) is too large. It uses huihui-ai's usual method and publishes no refusal or KL numbers. Mainline llama.cpp has supported GLM-5.3-Flash since Sep 30 ([PR #27773](https://github.com/ggml-org/llama.cpp/pull/27773)), so b12774 loads it. One unverified report gives 6–9 tok/s on a 4090 with 128 GB of DDR5 at IQ3_S ([modemguides](https://www.modemguides.com/blogs/ai-infrastructure/run-glm-5-3-flash-locally-hardware-reality-check)), and a 24 GB L4 reached about 12 tok/s at UD-Q2_K_XL ([wpnews](https://wpnews.pro/news/run-glm-5-3-flash-on-a-24-gb-gpu-at-up-to-17-5-tokens-s)). It matches Flash-Next on paper but has to run at about 3 bits with three times the active parameters, so in practice it will feel worse. The MoE refusal study above used this exact model, so a thorough edit is achievable, but nobody has shown that huihui's edit reaches the fused expert tensors. + +Three newer models are worth watching. **ERNIE 5.5 Flash Preview** (280B total, 14B active) scores 31 on Artificial Analysis, above Flash-Next ([AA open-source list](https://artificialanalysis.ai/models/open-source); [Baidu](https://huggingface.co/baidu/ERNIE-5.5-Flash-Preview)). Its only uncensored versions are dealignai safetensors in MXFP4 and NVFP4, and llama.cpp support (PR #31925) is still open ([PR #31925](https://github.com/ggml-org/llama.cpp/pull/31925)). [hletrd/MiMo-V2.6-Flash-RL-Uncensored-GGUF](https://huggingface.co/hletrd/MiMo-V2.6-Flash-RL-Uncensored-GGUF) has the cleanest edit found: HarmBench refusals 92.5% → 0.0% at KL 0.0088. But it comes only as a 167.37 GB MXFP4 file, more than your combined 152 GB of RAM and VRAM. MiniMax-M3.1-Flash runs in llama.cpp ([PR #32301](https://github.com/ggml-org/llama.cpp/pull/32301)) but has no uncensored build yet. + +Everything else that fits is weaker. [mrfakename/Ling-3.2-air-abliterated-GGUF](https://huggingface.co/mrfakename/Ling-3.2-air-abliterated-GGUF) (124B total, 5.5B active) fits at Q6_K (111 GB) and has the least-damaging documented edit: 3/100 refusals in chat, 4/100 with thinking, KL 0.051 ([mrfakename Ling](https://huggingface.co/mrfakename/Ling-3.2-air-abliterated)). Its capability relative to Flash-Next is unverified. Inkling 2 Mini scores 20.1, the same as Qwen3.8-27B ([Inkling 2 Mini card](https://huggingface.co/thinkingmachines/Inkling-2-Mini)), even in strong builds such as [Abiray/Inkling-2-Mini-Unbound-Uncensored-v3.1-GSQ-RCO-GGUF](https://huggingface.co/Abiray/Inkling-2-Mini-Unbound-Uncensored-v3.1-GSQ-RCO-GGUF) (IQ3_S 11.64 GB). Abliterating Mistral Small 4 dropped its LiveCodeBench score from 66 to 53 of 175 problems ([brutalai](https://huggingface.co/brutalai/mistral-small-4-119b-abliterated)). The UGI leaderboard's top entries that fit are older-generation models. coder3101/gemma-4-31B-it-heretic scores UGI 65.69 with NatInt 36.53. ArliAI/GLM-4.6-Derestricted-v3 scores UGI 69.82, but its NatInt of 30.93 is well below base GLM-4.6's ~42–45, and it has 32B active parameters ([UGI data](https://huggingface.co/spaces/DontPlanToEnd/UGI-Leaderboard/resolve/main/ugi-leaderboard-data.csv)). UGI does not list Flash-Next, and its knowledge-heavy NatInt disagrees sharply with Artificial Analysis. Thinking Machines' table puts Gemma 4 31B at 4.4 on Artificial Analysis v5.0 ([Inkling 2 Mini card](https://huggingface.co/thinkingmachines/Inkling-2-Mini)). Those UGI leaders are the best-documented uncensored models, but that is not evidence that they match Flash-Next. + +## Try the projection build first, then DeepSeek + +Keep the OrcaRouter Q5_K_M as your daily model until a candidate beats it in your own tests. In order of expected value for this machine: + +| Rank | Candidate and files | Runtime | Why it ranks here | Main risk | +| --- | --- | --- | --- | --- | +| 1 | alesha-pro GSQ-RCO **IQ3_S (83.6 GB)** + `Huihui-Qwen3.8-Flash-Next-refusal-direction-r.gguf` (480 KB) | Strata 0.2.24 | Same model; best-measured uncensoring; can be switched off per request; ~50 GB smaller; the base the looped adapter is designed for | 3-bit precision; refusal test of only 10 prompts; flag undocumented; tested on engine 0.1.38 | +| 2 | Abiray DeepSeek-V4.1-Flash-1017 GSQ-RCO **IQ2_XXS** (138.58 GB + 110.60 GB Engram on NVMe) | llama.cpp b12774 | The only candidate that measures stronger (32 vs 28; +11 points on agentic tool use) | ~5–10 tok/s; no refusal rates; tight on RAM; China-topic framing | +| 3 | narzh49 Hy4-Flash-Heretic-Strata **SQ-128 (113.65 GB)** + stock Engram and Vision packs | Strata 0.2.24 | Drop-in; stronger on agentic, office and computer-use tasks | 41% partial refusals; no capability data; weaker coding; slower | +| 4 | kcarly Huihui-GLM-5.3-Flash-abliterated **UD-IQ3_XXS (120 GB)** | llama.cpp b12774 | Ties on Artificial Analysis; supported in mainline llama.cpp | 6–9 tok/s; ~3 bits; no refusal or KL data | +| 5 | Looped-Qwen3.8-Flash-Next adapter on top of rank 1 | Strata, once PR #7673 merges | +8 LiveCodeBench in about the same time per answer | Draft code with seven flagged bugs | + +Skip huihui-ai's Flash-Next v2: it publishes no measurements, ablates no experts, and needs Strata's SHA-256 check disabled. Skip the Tenet v3 and REAP builds, which lose capability or have their coding experts pruned. Skip orcarouter's DeepSeek Mix-128G (KL 0.520, perplexity +54.7%). Keep Qwen3.8-27B, Inkling 2 Mini, Ling-3.2-air and Mistral Small 4 only as fast fallbacks. Downloading ranks 1–3 takes roughly 450–520 GB of NVMe, depending on whether you already have the stock Hy4 Engram and Vision packs. + +The comparison plan below uses the measures recent studies rely on: refusal sets scored by an LLM judge, because keyword matching counted 72.2% compliance where a classifier found 95.7% ([arXiv 2512.13655](https://arxiv.org/html/2512.13655v2)); replies of at least 150 tokens, because shorter checks miss refusals that come late in the answer ([Abliterix](https://pypi.org/project/abliterix/1.1.0/)); and llama.cpp's built-in KL-divergence tool ([llama.cpp perplexity README](https://github.com/ggml-org/llama.cpp/blob/master/tools/perplexity/README.md)). + +| Step | What to run on this PC | What decides it | +| --- | --- | --- | +| 1. Freeze a baseline | Leave the OrcaRouter files and Strata profile untouched. Repeat today's measurements (cold load, free VRAM, decode tok/s) at a 4K prompt and at your usual long context, with thinking on and off. Fix the sampler settings using OrcaRouter's loop advice (`reasoning_effort` low or `enable_thinking=false`, `repeat_penalty` ~1.1). | Every candidate is scored against these numbers | +| 2. Refusals | 100–200 prompts from HarmBench, StrongREJECT and AdvBench, plus about 100 safe XSTest prompts that test for over-refusal ([arXiv 2609.09793](https://huggingface.co/papers/2609.09793)). Generate at least 150 tokens and score with a judge model other than the one under test. For rank 1, run the set with `"experimental_speed_projection"` on and off to confirm the vector works. Add a few China-political prompts for DeepSeek. | Refusals and over-refusals no worse than baseline | +| 3. Capability | lm-evaluation-harness against llama-server's OpenAI-compatible endpoint, or the same prompts sent through Strata. Start with a 200-item GSM8K subset, the early warning for edit damage, then MMLU-Pro and IFEval subsets. Add 20–30 of your real tasks, including tool-call and JSON prompts and one long multi-turn chat to catch loops. | GSM8K within ~2 points of baseline; your own tasks equal or better | +| 4. KL against the same base | For Flash-Next builds that llama.cpp can load, save reference logits with `llama-perplexity --kl-divergence-base` on Wikitext-2, then run each candidate with `--kl-divergence`. Compare mean KLD and "Same top p" (how often the top token matches). Using your Q5_K_M as the reference measures distance from what you have now. alesha-pro packs run without the projection in llama.cpp, so this tests their quant only. Keep the PLE table on CPU, since one report saw decode fall to 1.95 tok/s with it on the GPU ([dev.to](https://dev.to/alanwest/how-to-run-qwen38-flash-next-locally-39-toks-on-24gb-of-vram-plus-96gb-ram-12ca)). Logit files run to tens of GB, so write them to NVMe. | Lower KLD wins among builds of the same base; never compare across families | +| 5. Speed and fit | Same prompts and context lengths. Record prompt and decode tok/s, cold load time, and free RAM and VRAM. For DeepSeek in llama.cpp: `-ngl 99`, routed experts on CPU via `-ot` or `--n-cpu-moe`, the Engram file memory-mapped, `per_layer_token_embd.weight=CPU`, and 16–32K context to start. | Whether the quality gain is worth the speed loss for your work | +| 6. Keep runtimes separate | Test Strata candidates in your existing 0.2.24 install and DeepSeek only in llama.cpp b12774. Don't install Strata 0.2.13 alongside: the versions share state files and the Windows downgrade path is untested ([issue #6048](https://github.com/Niko1221/Strata/issues/6048)). | Your working setup is never at risk | + +## Conclusion + +On this machine, the bigger choice is now how a model is uncensored, not which model family to pick. Runtime refusal vectors keep the edit separate from the quant. Examples are alesha-pro's vectors for Flash-Next and Hy4-Flash, Strata's bundled vector, and mrfakename's LoRA file. You keep the best official quant, can switch the edit off for any request, and can reuse it when a new add-on such as the looped adapter arrives. Edits baked into the weights tie you to one uploader's quant, as OrcaRouter's slower layout and DeepSeek's degraded Mix-128G show. The best uncensored local setups in 2027 will probably be small vectors and adapters applied to official quants, not new uploads of whole models. + +Memory bandwidth sets the capability ceiling here, not disk or RAM capacity. Every model that matches or beats Flash-Next and fits in 152 GB uses 12–18B active parameters, two to three times Flash-Next's 6B. On dual-channel DDR5, each step up in capability costs roughly 1.5–7 times in decode speed. Flash-Next's small active size is why it reaches 37 tok/s at near-full precision on this machine, so switching to another family now is a poor trade. The real upgrades depend on things that have not happened yet: Strata PR #7673 merging, DeepSeek returning to Strata, ERNIE 5.5 Flash getting llama.cpp support, and Qwen4's smaller open weights shipping. A refusal-and-capability test harness built now will let you judge each of them in an afternoon. diff --git a/kurgan/__init__.py b/kurgan/__init__.py new file mode 100644 index 0000000..23713b0 --- /dev/null +++ b/kurgan/__init__.py @@ -0,0 +1,23 @@ +"""The Kurgan: one local service for this PC's backend systems. + +Capabilities (one subpackage each): + telemetry CPU/GPU/whole-PC power sensing, sampled once a second for everything else + display the Thermaltake 3.9" LCD dashboard + cooling Commander PRO case fans and motherboard top fans, with selectable profiles + lighting Lighting Node CORE fan LEDs, Dominator DDR5 RAM and ASUS GPU LEDs + ai the local LLM servers (Strata or llama.cpp), one at a time + web the control UI and JSON API on 127.0.0.1 +Shared: hardware (Win32 HID, PawnIO modules), settings, theme, tray. +""" + +APP_NAME = "The Kurgan" +__version__ = "1.0.0" + +import os as _os + +# Before numpy is imported anywhere: OpenBLAS otherwise commits ~750 MB of per-thread buffers on +# this 28-thread CPU, which The Kurgan never uses (its numpy work is a few tiny vectors). The +# marker lets the AI launcher give the LLM servers the default back. +if "OPENBLAS_NUM_THREADS" not in _os.environ: + _os.environ["OPENBLAS_NUM_THREADS"] = "1" + _os.environ["KURGAN_PINNED_OPENBLAS"] = "1" diff --git a/kurgan/__main__.py b/kurgan/__main__.py new file mode 100644 index 0000000..f2c24c8 --- /dev/null +++ b/kurgan/__main__.py @@ -0,0 +1,7 @@ +"""python -m kurgan""" + +import sys + +from kurgan.app import main + +sys.exit(main()) diff --git a/kurgan/ai/__init__.py b/kurgan/ai/__init__.py new file mode 100644 index 0000000..2217b5f --- /dev/null +++ b/kurgan/ai/__init__.py @@ -0,0 +1 @@ +"""AI: the local LLM servers (Strata or llama.cpp), one running at a time.""" diff --git a/kurgan/ai/backends.py b/kurgan/ai/backends.py new file mode 100644 index 0000000..834b456 --- /dev/null +++ b/kurgan/ai/backends.py @@ -0,0 +1,497 @@ +"""The two LLM servers: how to start and stop each one, and how to watch it. + +Both monitors report the same shape, so the web UI shows either one the same way: + model: {"state": offline|unloaded|loading|idle|sleeping|reading|generating|failed, "detail", "id", "context"} + live: the request in progress: {"phase", "progress", "read", "total", "generated", "tok_s", "elapsed"} + requests: the latest finished requests, newest first + averages: prompt-reading and generation speed over those requests +Polling never wakes a model: Strata's /health and /metrics and llama-server's /models and +/metrics don't count as use. llama's live progress comes from its log, because polling +/slots would reset its idle timer. +""" + +from __future__ import annotations + +import collections +import ctypes +import ctypes.wintypes as wt +import json +import logging +import os +import re +import threading +import time +import urllib.error +import urllib.request +from datetime import datetime + +from kurgan import paths +from kurgan.ai import config + +log = logging.getLogger(__name__) +LOG_DIR = os.path.join(paths.DATA_DIR, "logs") +KEEP_REQUESTS = 20 + +_k32 = ctypes.WinDLL("kernel32", use_last_error=True) +_k32.OpenEventW.argtypes, _k32.OpenEventW.restype = [wt.DWORD, wt.BOOL, wt.LPCWSTR], wt.HANDLE +_k32.SetEvent.argtypes, _k32.SetEvent.restype = [wt.HANDLE], wt.BOOL +_k32.CloseHandle.argtypes = [wt.HANDLE] +EVENT_MODIFY_STATE = 0x2 + + +def http(method: str, url: str, body: dict | None = None, headers: dict | None = None, + timeout: float = 3) -> tuple[int, bytes]: + data = None if body is None else json.dumps(body).encode() + request = urllib.request.Request(url, data=data, method=method, headers={ + **({"Content-Type": "application/json"} if body is not None else {}), **(headers or {})}) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + return response.status, response.read() + except urllib.error.HTTPError as e: + return e.code, e.read() + + +def _clock(epoch: float | None) -> str | None: + return None if epoch is None else datetime.fromtimestamp(epoch).strftime("%H:%M:%S") + + +def _rate(tokens: float, ms: float) -> float | None: + return round(tokens / ms * 1000, 1) if ms and tokens else None + + +class Backend: + key = "" # also its path on The Kurgan's web server: // + label = "" + stop_timeout = 10.0 + + def __init__(self, settings): + self.settings = settings + self.lock = threading.Lock() + self.status: dict = self.offline() + self.public = "http://127.0.0.1:8080" # The Kurgan's web server; set by the service + + # -- configuration + @property + def port(self) -> int: + """Where the server listens, on 127.0.0.1, behind The Kurgan.""" + raise NotImplementedError + + @property + def prefix(self) -> str: + """The path the server itself serves under ("" = the root).""" + return "" + + def proxy_headers(self) -> dict: + """Headers The Kurgan's proxy sets on every request it passes to this server.""" + return {} + + def variants(self) -> list[dict]: + return [] + + def variant(self) -> str | None: + return None + + def model_label(self) -> str: + raise NotImplementedError + + def model_ids(self) -> list[str]: + """The model ids its /v1/models lists (answered by The Kurgan while the server is stopped).""" + raise NotImplementedError + + def links(self) -> dict: + return {"chat": f"{self.public}/{self.key}/", "api": f"{self.public}/{self.key}/v1", + "internal": f"http://127.0.0.1:{self.port}{self.prefix}/"} + + def check_files(self) -> str | None: + """A reason it can't start (missing file), or None.""" + return None + + # -- process + def command(self) -> tuple[list[str], str, str]: + """(argv, working directory, log file for stdout/stderr).""" + raise NotImplementedError + + def before_start(self) -> None: + pass + + def request_stop(self, child) -> None: + child.kill() + + # -- monitoring + @staticmethod + def offline() -> dict: + return {"model": {"state": "offline", "detail": "", "id": None, "context": None}, + "live": None, "requests": [], "averages": {"prefill_tps": None, "decode_tps": None, "requests": 0}} + + def poll(self) -> None: + raise NotImplementedError + + def mark_offline(self) -> None: + with self.lock: + self.status = self.offline() + + def snapshot(self) -> dict: + with self.lock: + return json.loads(json.dumps(self.status)) + + def load(self) -> None: + raise NotImplementedError + + def unload(self) -> None: + raise NotImplementedError + + +class StrataBackend(Backend): + key = "strata" + label = "Strata" + stop_timeout = 45.0 # Strata's own --shutdown-timeout is 30 s + + def __init__(self, settings): + super().__init__(settings) + self._stop_name: str | None = None + self._starts = 0 + + @property + def root(self) -> str: + return self.settings.get("ai", "strata_root", config.STRATA_ROOT) + + @property + def port(self) -> int: + return self.settings.get("ai", "strata_port", config.STRATA_PORT) + + def variant(self) -> str: + return self.settings.get("ai", "strata_model") + + def variants(self) -> list[dict]: + return [{"key": k, "label": label} for k, (label, _, _) in config.STRATA_MODELS.items()] + + def model_label(self) -> str: + return config.STRATA_MODELS[self.variant()][0] + + def model_ids(self) -> list[str]: + return [config.STRATA_MODELS[self.variant()][2]] + + def _python(self) -> str: + return os.path.join(self.root, "terminal", ".venv", "Scripts", "pythonw.exe") + + def check_files(self) -> str | None: + config_file = os.path.join(self.root, "terminal", config.STRATA_MODELS[self.variant()][1]) + for path in (self._python(), config_file): + if not os.path.exists(path): + return f"Not found: {path}" + return None + + def command(self) -> tuple[list[str], str, str]: + self._starts += 1 + self._stop_name = f"Local\\KurganStrataStop-{os.getpid()}-{self._starts}" + host = os.path.join(paths.PACKAGE_DIR, "ai", "strata_host.py") + argv = [self._python(), host, "--root", self.root, "--config", config.STRATA_MODELS[self.variant()][1], + "--port", str(self.port), "--idle-unload", str(config.STRATA_IDLE_UNLOAD), + "--stop-event", self._stop_name] + return argv, os.path.join(self.root, "terminal"), os.path.join(LOG_DIR, "strata-host.log") + + def request_stop(self, child) -> None: + """Ask Strata to shut down cleanly; the service kills it if it takes too long.""" + handle = _k32.OpenEventW(EVENT_MODIFY_STATE, False, self._stop_name) if self._stop_name else None + if not handle: + log.warning("Strata's stop event isn't available; ending it instead") + child.kill() + return + try: + _k32.SetEvent(handle) + finally: + _k32.CloseHandle(handle) + + def _url(self, path: str) -> str: + return f"http://127.0.0.1:{self.port}{path}" + + def poll(self) -> None: + code, body = http("GET", self._url("/health")) + if code != 200: + raise ValueError(f"/health returned HTTP {code}") + health = json.loads(body) + code, body = http("GET", self._url("/metrics"), headers={"Accept": "application/json"}) + metrics = json.loads(body) if code == 200 else {} + live_in = metrics.get("live") or {} + state = live_in.get("state") or ("idle" if health.get("loaded") else "unloaded") + live = None + if state in ("reading", "generating"): + read, total = live_in.get("prompt_read"), live_in.get("prompt_total") + live = {"phase": state, "read": read, "total": total or live_in.get("prompt_tokens"), + "progress": round(read / total, 3) if read is not None and total else None, + "generated": live_in.get("generated"), "tok_s": live_in.get("tok_s"), + "elapsed": live_in.get("elapsed_s"), "queued": live_in.get("queued")} + requests = [] + for r in (metrics.get("requests") or [])[:KEEP_REQUESTS]: + prompt, reused = r.get("prompt_tokens") or 0, r.get("reused") or 0 + requests.append({"time": _clock(r.get("time")), "status": r.get("finish") or "ok", + "prompt": prompt, "reused": reused, "output": r.get("output_tokens") or 0, + "prefill_tps": _rate(prompt - reused, r.get("prompt_ms") or 0), + "decode_tps": r.get("decode_tok_s"), "duration": r.get("duration_s")}) + totals = metrics.get("totals") or {} + engine = metrics.get("engine") or {} + status = { + "model": {"state": state, "detail": "", "id": health.get("model"), + "context": health.get("max_context"), "engine": engine.get("version")}, + "live": live, "requests": requests, + "averages": {"prefill_tps": _rate((totals.get("prompt_tokens") or 0) - (totals.get("reused") or 0), + totals.get("prompt_ms") or 0), + "decode_tps": _rate(totals.get("output_tokens") or 0, totals.get("decode_ms") or 0), + "requests": totals.get("requests") or 0}, + } + with self.lock: + self.status = status + + def load(self) -> None: + code, body = http("POST", self._url("/load"), {}, timeout=600) + log.info("Strata load: HTTP %s %s", code, body[:200]) + if code != 200: + raise RuntimeError(_error_text(body) or f"Strata load failed (HTTP {code})") + + def unload(self) -> None: + code, body = http("POST", self._url("/unload"), {}, timeout=120) + log.info("Strata unload: HTTP %s %s", code, body[:200]) + if code == 409: + raise RuntimeError("Strata is answering a request; unload it when it finishes.") + if code != 200: + raise RuntimeError(_error_text(body) or f"Strata unload failed (HTTP {code})") + + +def _error_text(body: bytes) -> str | None: + try: + error = json.loads(body).get("error") + return error.get("message") if isinstance(error, dict) else str(error) if error else None + except (ValueError, AttributeError): + return None + + +# --- llama.cpp log parsing (ported from the Qwen4 service) ------------------------------- + +RE_START = re.compile(r"task (\d+) \| processing task") +RE_PREFILL = re.compile(r"task (\d+) \| prompt processing, n_tokens =\s*(\d+), progress =\s*([\d.]+), " + r"t =\s*([\d.]+) s / ([\d.]+) tokens per second") +RE_GEN = re.compile(r"task (\d+) \| n_gen =\s*(\d+), tg =\s*([\d.]+) t/s, tg_3s =\s*([\d.]+) t/s") +RE_PROMPT_DONE = re.compile(r"task (\d+) \| prompt eval time =\s*([\d.]+) ms /\s*(\d+) tokens.*?([\d.]+) tokens per second") +RE_EVAL_DONE = re.compile(r"task (\d+) \|\s+eval time =\s*([\d.]+) ms /\s*(\d+) tokens.*?([\d.]+) tokens per second") +RE_STOP = re.compile(r"task (\d+) \| stop processing: n_tokens =\s*(\d+), truncated = (\d)") + + +class LlamaLog: + """Follows llama-server's log for the request in progress and the finished ones.""" + + def __init__(self) -> None: + self.lock = threading.Lock() + self.current: dict | None = None + self.requests: collections.deque[dict] = collections.deque(maxlen=KEEP_REQUESTS) + + def feed(self, line: str, now: float | None = None) -> None: + now = time.time() if now is None else now + with self.lock: + if match := RE_START.search(line): + self.current = {"start": now, "phase": "reading", "progress": 0.0, "read": 0, "generated": 0, + "prefill_tps": None, "decode_tps": None} + return + current = self.current + if current is None: + return + if match := RE_PREFILL.search(line): + current.update(phase="reading", read=int(match[2]), progress=float(match[3]), + prefill_tps=float(match[5])) + elif match := RE_GEN.search(line): + current.update(phase="generating", generated=int(match[2]), decode_tps=float(match[4])) + elif match := RE_PROMPT_DONE.search(line): + current.update(prompt_ms=float(match[2]), read=int(match[3]), prefill_final=float(match[4])) + elif match := RE_EVAL_DONE.search(line): + current.update(decode_ms=float(match[2]), generated=int(match[3]), decode_final=float(match[4])) + elif match := RE_STOP.search(line): + context = int(match[2]) + read, generated = current.get("read", 0), current.get("generated", 0) + cached = max(0, context - read - generated) + self.requests.appendleft({ + "time": datetime.fromtimestamp(now).strftime("%H:%M:%S"), + "status": "truncated" if match[3] == "1" else "ok", + "prompt": cached + read, "reused": cached, "output": generated, + "prefill_tps": current.get("prefill_final"), "decode_tps": current.get("decode_final"), + "duration": round(now - current["start"], 1), + "prompt_ms": current.get("prompt_ms", 0.0), "decode_ms": current.get("decode_ms", 0.0), + }) + self.current = None + + def reset(self) -> None: + with self.lock: + self.current = None + + def snapshot(self) -> tuple[dict | None, list[dict], dict]: + with self.lock: + requests = list(self.requests) + current = dict(self.current) if self.current else None + live = None + if current: + live = {"phase": current["phase"], "progress": current.get("progress"), "read": current.get("read"), + "total": None, "generated": current.get("generated"), + "tok_s": current.get("decode_tps") if current["phase"] == "generating" else current.get("prefill_tps"), + "elapsed": round(time.time() - current["start"], 1), "queued": None} + prompt_ms = sum(r["prompt_ms"] for r in requests) + decode_ms = sum(r["decode_ms"] for r in requests) + averages = {"prefill_tps": _rate(sum(r["prompt"] - r["reused"] for r in requests), prompt_ms), + "decode_tps": _rate(sum(r["output"] for r in requests), decode_ms), + "requests": len(requests)} + public = [{k: v for k, v in r.items() if k not in ("prompt_ms", "decode_ms")} for r in requests] + return live, public, averages + + def follow(self, path_fn, stop: threading.Event) -> None: + """Tail the file path_fn() returns, reopening it when it is replaced or truncated.""" + handle, identity, buffer, path = None, None, b"", None + while not stop.is_set(): + try: + wanted = path_fn() + if wanted != path: + if handle: + handle.close() + handle, identity, buffer, path = None, None, b"", wanted + stat = os.stat(path) + if handle is None or (stat.st_ino, stat.st_ctime_ns) != identity or stat.st_size < handle.tell(): + if handle: + handle.close() + handle = open(path, "rb") + if identity is None: + handle.seek(0, os.SEEK_END) # don't replay an old log when first attaching + identity, buffer = (stat.st_ino, stat.st_ctime_ns), b"" + chunk = handle.read() + except (OSError, TypeError): + chunk = b"" + if not chunk: + stop.wait(0.5) + continue + buffer += chunk + *lines, buffer = buffer.split(b"\n") + for line in lines: + self.feed(line.decode("utf-8", "replace")) + if handle: + handle.close() + + +class LlamaBackend(Backend): + key = "llama" + label = "llama.cpp" + stop_timeout = 10.0 + LEGACY_LOG = r"D:\AI\models\qwen4-35b-a3b\service\logs\llama-server.log" # while the Qwen4 service runs it + + def __init__(self, settings): + super().__init__(settings) + self.logparser = LlamaLog() + self.owned = False # set by the service: True when The Kurgan started the running server + self.load_started: float | None = None + self.last_load_seconds: float | None = None + + @property + def port(self) -> int: + return self.settings.get("ai", "llama_port", config.LLAMA_PORT) + + @property + def server(self) -> str: + return self.settings.get("ai", "llama_server", config.LLAMA_SERVER) + + @property + def presets(self) -> str: + return self.settings.get("ai", "llama_presets", config.LLAMA_PRESETS) + + @property + def model(self) -> str: + return self.settings.get("ai", "llama_model", config.LLAMA_MODEL) + + @property + def prefix(self) -> str: + # The Qwen4 service's own server (before it was retired) serves from the root. + return config.LLAMA_PREFIX if self.owned else "" + + def proxy_headers(self) -> dict: + # The proxy is the gate (see kurgan/web/proxy.py), so clients there need no key; the key + # stays on the server's own port, where a web page could otherwise reach it. + return {"Authorization": f"Bearer {config.LLAMA_API_KEY}"} + + def model_label(self) -> str: + return config.LLAMA_LABEL if self.model == config.LLAMA_MODEL else self.model + + def model_ids(self) -> list[str]: + return [self.model] + + @property + def log_path(self) -> str: + return os.path.join(LOG_DIR, "llama-server.log") + + def current_log(self) -> str: + return self.log_path if self.owned else self.LEGACY_LOG + + def check_files(self) -> str | None: + for path in (self.server, self.presets): + if not os.path.exists(path): + return f"Not found: {path}" + return None + + def before_start(self) -> None: + os.makedirs(LOG_DIR, exist_ok=True) + try: + if os.path.exists(self.log_path): + os.replace(self.log_path, os.path.join(LOG_DIR, "llama-server.prev.log")) + except OSError as e: + log.warning("Could not rotate llama-server.log: %s", e) + self.logparser.reset() + + def command(self) -> tuple[list[str], str, str]: + argv = [self.server, "--models-preset", self.presets, "--models-max", "1", "--host", "127.0.0.1", + "--port", str(self.port), "--api-prefix", config.LLAMA_PREFIX, "--api-key", config.LLAMA_API_KEY, + "--metrics"] + return argv, os.path.dirname(self.presets), self.log_path + + def _api(self, path: str, body: dict | None = None, timeout: float = 3) -> tuple[int, bytes]: + return http("GET" if body is None else "POST", f"http://127.0.0.1:{self.port}{self.prefix}{path}", body, + {"Authorization": f"Bearer {config.LLAMA_API_KEY}"}, timeout) + + def _model_entry(self) -> dict: + code, body = self._api("/models") + if code != 200: + raise ValueError(f"/models returned HTTP {code}") + return next(m for m in json.loads(body)["data"] if m["id"] == self.model) + + def poll(self) -> None: + entry = self._model_entry() + state = entry["status"]["value"] + live, requests, averages = self.logparser.snapshot() + if state == "loading" and self.load_started is None: + self.load_started = time.time() + elif state != "loading" and self.load_started is not None: + if state == "loaded": + self.last_load_seconds = round(time.time() - self.load_started, 1) + self.load_started = None + if state == "loaded": + state = live["phase"] if live else "idle" + else: + live = None + detail = entry["status"].get("failed_reason", "") if state == "failed" else "" + if state == "loading" and self.load_started: + detail = f"{time.time() - self.load_started:.0f} s" + status = {"model": {"state": state, "detail": detail, "id": self.model, "context": 262144, + "last_load_seconds": self.last_load_seconds}, + "live": live, "requests": requests, "averages": averages} + with self.lock: + self.status = status + + def load(self) -> None: + if self._model_entry()["status"]["value"] == "sleeping": + # A sleeping instance only wakes on a task, so restart it to load immediately. + self._api("/models/unload", {"model": self.model}, timeout=30) + for _ in range(60): + if self._model_entry()["status"]["value"] == "unloaded": + break + time.sleep(0.5) + code, body = self._api("/models/load", {"model": self.model}, timeout=30) + log.info("llama load: HTTP %s %s", code, body[:200]) + if code != 200: + raise RuntimeError(_error_text(body) or f"llama.cpp load failed (HTTP {code})") + + def unload(self) -> None: + code, body = self._api("/models/unload", {"model": self.model}, timeout=30) + log.info("llama unload: HTTP %s %s", code, body[:200]) + if code != 200: + raise RuntimeError(_error_text(body) or f"llama.cpp unload failed (HTTP {code})") diff --git a/kurgan/ai/config.py b/kurgan/ai/config.py new file mode 100644 index 0000000..d7611aa --- /dev/null +++ b/kurgan/ai/config.py @@ -0,0 +1,35 @@ +"""Defaults for the two local LLM servers. Paths and ports can be overridden in settings.json ("ai"). + +Clients reach both through The Kurgan's web server: http://127.0.0.1:8080/strata/v1 and +http://127.0.0.1:8080/llama/v1 (see kurgan/web/proxy.py). The ports below are where each server +listens on 127.0.0.1 behind it; clients shouldn't use them directly. +""" + +import os + +BACKENDS = ("strata", "llama") # also each server's path on The Kurgan's web server: /strata/, /llama/ + +# A server nobody has used for this long is stopped; the next request starts it again (0 = never). +IDLE_STOP_MINUTES = 40 + +# Strata (github.com/Niko1221/Strata), a git clone with its own venv in terminal\. +STRATA_ROOT = r"D:\AI\Strata" +STRATA_PORT = 8082 +STRATA_MODELS = { # key: (label, run config in terminal\, model id it serves) + "q5": ("OrcaRouter Qwen3.8 Flash Next Q5_K_M", "strata-orca-q5_k_m.json", + "orcarouter-qwen3.8-flash-next-uncensored-q5_k_m"), + "iq3": ("OrcaRouter Qwen3.8 Flash Next IQ3_XXS", "strata-orca-iq3_xxs.json", + "orcarouter-qwen3.8-flash-next-uncensored-iq3_xxs"), +} +STRATA_DEFAULT_MODEL = "q5" +STRATA_IDLE_UNLOAD = 2000 # seconds idle before the model leaves VRAM; it reloads on the next request + +# llama.cpp's llama-server in router mode, with the model defined in a presets file. +LLAMA_SERVER = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs", "llama.cpp", "b12977", + "llama-server.exe") +LLAMA_PRESETS = r"D:\AI\models\qwen4-35b-a3b\service\presets.ini" +LLAMA_MODEL = "qwen4-35b-a3b-q5" +LLAMA_LABEL = "Qwen4 35B-A3B UD-Q5_K_XL" +LLAMA_PORT = 8083 +LLAMA_API_KEY = "sk-local" +LLAMA_PREFIX = "/llama" # --api-prefix: llama-server serves its API and chat page under this path diff --git a/kurgan/ai/launcher.py b/kurgan/ai/launcher.py new file mode 100644 index 0000000..bb453a3 --- /dev/null +++ b/kurgan/ai/launcher.py @@ -0,0 +1,449 @@ +"""Start the AI servers as ordinary, non-elevated processes, even though The Kurgan runs elevated. + +The Kurgan needs admin rights for PawnIO (CPU sensors, top fans, RAM lighting), but the LLM +servers never did: they ran from non-elevated tasks before. How a server is started: + +- The Kurgan elevated (the normal case): with a copy of the desktop shell's (Explorer's) own + token, through CreateProcessWithTokenW. The server is then exactly what Explorer would have + started: medium integrity, not elevated, in the desktop's logon session. +- No desktop shell yet (just after logon; see desktop_ready) or The Kurgan not elevated (tests, + --demo): a "normal user" token from the Safer API (Administrators made deny-only, admin + privileges removed, medium integrity). Windows still counts that token as part of the elevated + logon session, so the shell's token is preferred. + +Each server gets its own job object that kills everything in it when The Kurgan closes the +job, including the model processes the server starts itself; a crashed Kurgan leaves no +orphan holding VRAM or a port. stdout/stderr go to a log file. The Safer path passes an explicit +handle list, so only the log and NUL handles are inherited. CreateProcessWithTokenW can't take +one; Python makes its handles non-inheritable, and launches are serialised, so in practice the +same two are all the child gets. +""" + +from __future__ import annotations + +import ctypes +import ctypes.wintypes as wt +import logging +import os +import subprocess +import threading + +log = logging.getLogger(__name__) + +_k32 = ctypes.WinDLL("kernel32", use_last_error=True) +_adv = ctypes.WinDLL("advapi32", use_last_error=True) + +SAFER_SCOPEID_USER = 2 +SAFER_LEVELID_NORMALUSER = 0x20000 +SAFER_LEVEL_OPEN = 1 +TOKEN_INTEGRITY_LEVEL = 25 +TOKEN_ELEVATION = 20 +SE_GROUP_INTEGRITY = 0x20 +MEDIUM_INTEGRITY_SID = "S-1-16-8192" + +CREATE_SUSPENDED = 0x4 +CREATE_NEW_PROCESS_GROUP = 0x200 +CREATE_UNICODE_ENVIRONMENT = 0x400 +EXTENDED_STARTUPINFO_PRESENT = 0x80000 +CREATE_NO_WINDOW = 0x08000000 +STARTF_USESHOWWINDOW, STARTF_USESTDHANDLES = 0x1, 0x100 +SW_HIDE = 0 +PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x20002 +JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000 +JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9 +GENERIC_READ, GENERIC_WRITE = 0x80000000, 0x40000000 +FILE_APPEND_DATA = 0x4 +SYNCHRONIZE = 0x100000 +FILE_SHARE_ALL = 0x7 +OPEN_EXISTING, OPEN_ALWAYS = 3, 4 +INVALID_HANDLE = wt.HANDLE(-1).value +WAIT_OBJECT_0, WAIT_TIMEOUT = 0, 0x102 +STILL_ACTIVE = 259 +PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 +TOKEN_QUERY = 0x8 +TOKEN_ASSIGN_PRIMARY, TOKEN_DUPLICATE, TOKEN_ADJUST_DEFAULT, TOKEN_ADJUST_SESSIONID = 0x1, 0x2, 0x80, 0x100 +SECURITY_IMPERSONATION, TOKEN_PRIMARY = 2, 1 +ERROR_INVALID_PARAMETER = 87 + + +class SecurityAttributes(ctypes.Structure): + _fields_ = [("nLength", wt.DWORD), ("lpSecurityDescriptor", wt.LPVOID), ("bInheritHandle", wt.BOOL)] + + +class StartupInfo(ctypes.Structure): + _fields_ = [("cb", wt.DWORD), ("lpReserved", wt.LPWSTR), ("lpDesktop", wt.LPWSTR), ("lpTitle", wt.LPWSTR), + ("dwX", wt.DWORD), ("dwY", wt.DWORD), ("dwXSize", wt.DWORD), ("dwYSize", wt.DWORD), + ("dwXCountChars", wt.DWORD), ("dwYCountChars", wt.DWORD), ("dwFillAttribute", wt.DWORD), + ("dwFlags", wt.DWORD), ("wShowWindow", wt.WORD), ("cbReserved2", wt.WORD), + ("lpReserved2", ctypes.c_void_p), ("hStdInput", wt.HANDLE), ("hStdOutput", wt.HANDLE), + ("hStdError", wt.HANDLE)] + + +class StartupInfoEx(ctypes.Structure): + _fields_ = [("StartupInfo", StartupInfo), ("lpAttributeList", ctypes.c_void_p)] + + +class ProcessInformation(ctypes.Structure): + _fields_ = [("hProcess", wt.HANDLE), ("hThread", wt.HANDLE), ("dwProcessId", wt.DWORD), + ("dwThreadId", wt.DWORD)] + + +class SidAndAttributes(ctypes.Structure): + _fields_ = [("Sid", ctypes.c_void_p), ("Attributes", wt.DWORD)] + + +class BasicLimits(ctypes.Structure): + _fields_ = [("PerProcessUserTimeLimit", ctypes.c_int64), ("PerJobUserTimeLimit", ctypes.c_int64), + ("LimitFlags", wt.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t), + ("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wt.DWORD), + ("Affinity", ctypes.c_size_t), ("PriorityClass", wt.DWORD), ("SchedulingClass", wt.DWORD)] + + +class ExtendedLimits(ctypes.Structure): + _fields_ = [("BasicLimitInformation", BasicLimits), ("IoInfo", ctypes.c_uint64 * 6), + ("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t), + ("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)] + + +_adv.SaferCreateLevel.argtypes = [wt.DWORD, wt.DWORD, wt.DWORD, ctypes.POINTER(wt.HANDLE), wt.LPVOID] +_adv.SaferCreateLevel.restype = wt.BOOL +_adv.SaferComputeTokenFromLevel.argtypes = [wt.HANDLE, wt.HANDLE, ctypes.POINTER(wt.HANDLE), wt.DWORD, wt.LPVOID] +_adv.SaferComputeTokenFromLevel.restype = wt.BOOL +_adv.SaferCloseLevel.argtypes = [wt.HANDLE] +_adv.SaferCloseLevel.restype = wt.BOOL +_adv.ConvertStringSidToSidW.argtypes = [wt.LPCWSTR, ctypes.POINTER(ctypes.c_void_p)] +_adv.ConvertStringSidToSidW.restype = wt.BOOL +_adv.GetLengthSid.argtypes = [ctypes.c_void_p] +_adv.GetLengthSid.restype = wt.DWORD +_adv.SetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD] +_adv.SetTokenInformation.restype = wt.BOOL +_adv.GetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD, ctypes.POINTER(wt.DWORD)] +_adv.GetTokenInformation.restype = wt.BOOL +_adv.GetSidSubAuthorityCount.argtypes = [ctypes.c_void_p] +_adv.GetSidSubAuthorityCount.restype = ctypes.POINTER(ctypes.c_ubyte) +_adv.GetSidSubAuthority.argtypes = [ctypes.c_void_p, wt.DWORD] +_adv.GetSidSubAuthority.restype = ctypes.POINTER(wt.DWORD) +_adv.OpenProcessToken.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.HANDLE)] +_adv.OpenProcessToken.restype = wt.BOOL +_adv.CreateProcessAsUserW.argtypes = [wt.HANDLE, wt.LPCWSTR, wt.LPWSTR, wt.LPVOID, wt.LPVOID, wt.BOOL, wt.DWORD, + wt.LPVOID, wt.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(ProcessInformation)] +_adv.CreateProcessAsUserW.restype = wt.BOOL +_k32.LocalFree.argtypes = [wt.HLOCAL] +_k32.LocalFree.restype = wt.HLOCAL +_k32.CloseHandle.argtypes = [wt.HANDLE] +_k32.CloseHandle.restype = wt.BOOL +_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.POINTER(SecurityAttributes), wt.DWORD, + wt.DWORD, wt.HANDLE] +_k32.CreateFileW.restype = wt.HANDLE +_k32.CreateJobObjectW.argtypes = [wt.LPVOID, wt.LPCWSTR] +_k32.CreateJobObjectW.restype = wt.HANDLE +_k32.SetInformationJobObject.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD] +_k32.SetInformationJobObject.restype = wt.BOOL +_k32.AssignProcessToJobObject.argtypes = [wt.HANDLE, wt.HANDLE] +_k32.AssignProcessToJobObject.restype = wt.BOOL +_k32.TerminateJobObject.argtypes = [wt.HANDLE, wt.UINT] +_k32.TerminateJobObject.restype = wt.BOOL +_k32.TerminateProcess.argtypes = [wt.HANDLE, wt.UINT] +_k32.TerminateProcess.restype = wt.BOOL +_k32.ResumeThread.argtypes = [wt.HANDLE] +_k32.ResumeThread.restype = wt.DWORD +_k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD] +_k32.WaitForSingleObject.restype = wt.DWORD +_k32.GetExitCodeProcess.argtypes = [wt.HANDLE, ctypes.POINTER(wt.DWORD)] +_k32.GetExitCodeProcess.restype = wt.BOOL +_k32.InitializeProcThreadAttributeList.argtypes = [ctypes.c_void_p, wt.DWORD, wt.DWORD, ctypes.POINTER(ctypes.c_size_t)] +_k32.InitializeProcThreadAttributeList.restype = wt.BOOL +_k32.UpdateProcThreadAttribute.argtypes = [ctypes.c_void_p, wt.DWORD, ctypes.c_size_t, wt.LPVOID, ctypes.c_size_t, + wt.LPVOID, wt.LPVOID] +_k32.UpdateProcThreadAttribute.restype = wt.BOOL +_k32.DeleteProcThreadAttributeList.argtypes = [ctypes.c_void_p] +_k32.DeleteProcThreadAttributeList.restype = None +_k32.OpenProcess.argtypes = [wt.DWORD, wt.BOOL, wt.DWORD] +_k32.OpenProcess.restype = wt.HANDLE +_k32.GetCurrentProcess.restype = wt.HANDLE +_adv.DuplicateTokenEx.argtypes = [wt.HANDLE, wt.DWORD, wt.LPVOID, ctypes.c_int, ctypes.c_int, ctypes.POINTER(wt.HANDLE)] +_adv.DuplicateTokenEx.restype = wt.BOOL +_adv.CreateProcessWithTokenW.argtypes = [wt.HANDLE, wt.DWORD, wt.LPCWSTR, wt.LPWSTR, wt.DWORD, wt.LPVOID, wt.LPCWSTR, + ctypes.c_void_p, ctypes.POINTER(ProcessInformation)] +_adv.CreateProcessWithTokenW.restype = wt.BOOL +_u32 = ctypes.WinDLL("user32", use_last_error=True) +_u32.GetShellWindow.restype = wt.HWND +_u32.GetWindowThreadProcessId.argtypes = [wt.HWND, ctypes.POINTER(wt.DWORD)] +_u32.GetWindowThreadProcessId.restype = wt.DWORD + +_launch_lock = threading.Lock() + + +def _check(ok, what: str): + if not ok: + raise ctypes.WinError(ctypes.get_last_error(), f"{what} failed") + return ok + + +def _normal_user_token() -> wt.HANDLE: + """A primary token like this process's, minus admin rights, at medium integrity.""" + level, token = wt.HANDLE(), wt.HANDLE() + _check(_adv.SaferCreateLevel(SAFER_SCOPEID_USER, SAFER_LEVELID_NORMALUSER, SAFER_LEVEL_OPEN, + ctypes.byref(level), None), "SaferCreateLevel") + try: + _check(_adv.SaferComputeTokenFromLevel(level, None, ctypes.byref(token), 0, None), + "SaferComputeTokenFromLevel") + finally: + _adv.SaferCloseLevel(level) + sid = ctypes.c_void_p() + try: + _check(_adv.ConvertStringSidToSidW(MEDIUM_INTEGRITY_SID, ctypes.byref(sid)), "ConvertStringSidToSid") + label = SidAndAttributes(sid, SE_GROUP_INTEGRITY) + _check(_adv.SetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, ctypes.byref(label), + ctypes.sizeof(label) + _adv.GetLengthSid(sid)), "SetTokenInformation") + except OSError: + _k32.CloseHandle(token) + raise + finally: + if sid: + _k32.LocalFree(sid) + return token + + +def _describe_token(token: wt.HANDLE) -> dict: + size = wt.DWORD() + _adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, None, 0, ctypes.byref(size)) + buf = ctypes.create_string_buffer(size.value) + _check(_adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, buf, size, ctypes.byref(size)), + "GetTokenInformation(IntegrityLevel)") + sid = SidAndAttributes.from_buffer(buf).Sid + rid = _adv.GetSidSubAuthority(sid, _adv.GetSidSubAuthorityCount(sid)[0] - 1)[0] + elevated = wt.DWORD() + _check(_adv.GetTokenInformation(token, TOKEN_ELEVATION, ctypes.byref(elevated), 4, ctypes.byref(size)), + "GetTokenInformation(Elevation)") + names = {0x1000: "low", 0x2000: "medium", 0x2100: "medium-plus", 0x3000: "high", 0x4000: "system"} + return {"integrity": names.get(rid, hex(rid)), "elevated": bool(elevated.value)} + + +def token_info(process_handle=None) -> dict: + """{"integrity": "medium"|"high"|..., "elevated": bool} for a process (default: this one).""" + token = wt.HANDLE() + handle = process_handle if process_handle is not None else _k32.GetCurrentProcess() + _check(_adv.OpenProcessToken(handle, TOKEN_QUERY, ctypes.byref(token)), "OpenProcessToken") + try: + return _describe_token(token) + finally: + _k32.CloseHandle(token) + + +_ELEVATED: bool | None = None + + +def elevated() -> bool: + global _ELEVATED + if _ELEVATED is None: + _ELEVATED = token_info()["elevated"] + return _ELEVATED + + +def _desktop_token() -> wt.HANDLE | None: + """A primary copy of the desktop shell's token, or None if there is no (non-elevated) shell.""" + hwnd = _u32.GetShellWindow() + if not hwnd: + return None + pid = wt.DWORD() + _u32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) + process = _k32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid.value) + if not process: + return None + shell, token = wt.HANDLE(), wt.HANDLE() + try: + if not _adv.OpenProcessToken(process, TOKEN_DUPLICATE | TOKEN_QUERY, ctypes.byref(shell)): + return None + try: + _check(_adv.DuplicateTokenEx(shell, TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE + | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID, None, + SECURITY_IMPERSONATION, TOKEN_PRIMARY, ctypes.byref(token)), + "DuplicateTokenEx") + finally: + _k32.CloseHandle(shell) + finally: + _k32.CloseHandle(process) + if _describe_token(token)["elevated"]: # someone runs Explorer elevated: no better than our own + _k32.CloseHandle(token) + return None + return token + + +def desktop_ready() -> bool: + """True once servers can be started with the desktop's own token (always true when not elevated).""" + if not elevated(): + return True + token = _desktop_token() + if token is None: + return False + _k32.CloseHandle(token) + return True + + +def _inheritable(path: str, access: int, disposition: int) -> wt.HANDLE: + sa = SecurityAttributes(ctypes.sizeof(SecurityAttributes), None, True) + handle = _k32.CreateFileW(path, access, FILE_SHARE_ALL, ctypes.byref(sa), disposition, 0x80, None) + if handle == INVALID_HANDLE or not handle: + raise ctypes.WinError(ctypes.get_last_error(), f"Opening {path} failed") + return handle + + +def _environment_block(env: dict[str, str]) -> ctypes.Array: + items = sorted(env.items(), key=lambda kv: kv[0].upper()) + text = "".join(f"{k}={v}\0" for k, v in items) + "\0" + return ctypes.create_unicode_buffer(text, len(text)) + + +def child_environment(extra: dict[str, str] | None = None) -> dict[str, str]: + env = dict(os.environ) + # The Kurgan pins OpenBLAS to one thread for itself (see kurgan/__init__.py); the servers get the default. + if env.get("KURGAN_PINNED_OPENBLAS") == "1": + env.pop("OPENBLAS_NUM_THREADS", None) + env.pop("KURGAN_PINNED_OPENBLAS", None) + env.update(extra or {}) + return env + + +class ChildProcess: + """A launched server: poll/wait/kill like subprocess.Popen, plus the job it runs in.""" + + def __init__(self, pid: int, process: wt.HANDLE, job: wt.HANDLE, argv: list[str]): + self.pid = pid + self.argv = argv + self._process = process + self._job = job + self.returncode: int | None = None + try: + self.token = token_info(process) + except OSError as e: + log.warning("Could not read the token of process %s: %s", pid, e) + self.token = {"integrity": "unknown", "elevated": None} + + def poll(self) -> int | None: + return self.wait(0) + + def wait(self, timeout: float | None = None) -> int | None: + if self.returncode is not None: + return self.returncode + if self._process is None: + return None + ms = 0xFFFFFFFF if timeout is None else max(0, int(timeout * 1000)) + if _k32.WaitForSingleObject(self._process, ms) != WAIT_OBJECT_0: + return None + code = wt.DWORD() + _check(_k32.GetExitCodeProcess(self._process, ctypes.byref(code)), "GetExitCodeProcess") + self.returncode = code.value + return self.returncode + + def kill(self) -> None: + """End the server and everything it started.""" + if self._job: + _k32.TerminateJobObject(self._job, 1) + elif self._process: + _k32.TerminateProcess(self._process, 1) + + def close(self) -> None: + """Release the handles; closing the job also kills anything still in it.""" + for name in ("_process", "_job"): + handle = getattr(self, name) + if handle: + _k32.CloseHandle(handle) + setattr(self, name, None) + + def __del__(self): + try: + self.close() + except Exception: + pass + + +def launch(argv: list[str], cwd: str, log_path: str | None, env: dict[str, str] | None = None, + contained: bool = True) -> ChildProcess: + """Start argv as a normal user, windowless, with stdout/stderr appended to log_path (None: discarded). + + contained: put it in its own kill-on-close job (servers). Without it the process outlives + the returned handle (used to open the browser).""" + if log_path is not None: + os.makedirs(os.path.dirname(log_path), exist_ok=True) + with _launch_lock: + desktop = _desktop_token() if elevated() else None + token = desktop or _normal_user_token() + job = out = nul = None + attributes = None + try: + if contained: + job = _check(_k32.CreateJobObjectW(None, None), "CreateJobObject") + limits = ExtendedLimits() + limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + _check(_k32.SetInformationJobObject(job, JOB_OBJECT_EXTENDED_LIMIT_INFORMATION, + ctypes.byref(limits), ctypes.sizeof(limits)), + "SetInformationJobObject") + out = (_inheritable(log_path, FILE_APPEND_DATA | SYNCHRONIZE, OPEN_ALWAYS) if log_path is not None + else _inheritable("NUL", GENERIC_WRITE, OPEN_EXISTING)) + nul = _inheritable("NUL", GENERIC_READ, OPEN_EXISTING) + command = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv)) + block = _environment_block(env if env is not None else child_environment()) + flags = CREATE_SUSPENDED | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_PROCESS_GROUP + pi = ProcessInformation() + + if desktop: + info = StartupInfo() + info.cb = ctypes.sizeof(StartupInfo) + info.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW + info.wShowWindow = SW_HIDE + info.hStdInput, info.hStdOutput, info.hStdError = nul, out, out + ok = _adv.CreateProcessWithTokenW(token, 0, None, command, flags, block, cwd, + ctypes.byref(info), ctypes.byref(pi)) + if not ok and ctypes.get_last_error() == ERROR_INVALID_PARAMETER: + # Not every creation flag is accepted here; SW_HIDE still hides a console window. + ok = _adv.CreateProcessWithTokenW(token, 0, None, command, flags & ~CREATE_NO_WINDOW, block, + cwd, ctypes.byref(info), ctypes.byref(pi)) + _check(ok, f"Starting {argv[0]}") + else: + size = ctypes.c_size_t() + _k32.InitializeProcThreadAttributeList(None, 1, 0, ctypes.byref(size)) + attributes = ctypes.create_string_buffer(size.value) + _check(_k32.InitializeProcThreadAttributeList(attributes, 1, 0, ctypes.byref(size)), + "InitializeProcThreadAttributeList") + handles = (wt.HANDLE * 2)(out, nul) + _check(_k32.UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles, + ctypes.sizeof(handles), None, None), + "UpdateProcThreadAttribute") + info = StartupInfoEx() + info.StartupInfo.cb = ctypes.sizeof(StartupInfoEx) + info.StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW + info.StartupInfo.wShowWindow = SW_HIDE + info.StartupInfo.hStdInput, info.StartupInfo.hStdOutput, info.StartupInfo.hStdError = nul, out, out + info.lpAttributeList = ctypes.cast(attributes, ctypes.c_void_p) + _check(_adv.CreateProcessAsUserW(token, None, command, None, None, True, + flags | EXTENDED_STARTUPINFO_PRESENT, block, cwd, + ctypes.byref(info), ctypes.byref(pi)), f"Starting {argv[0]}") + if job and not _k32.AssignProcessToJobObject(job, pi.hProcess): + error = ctypes.WinError(ctypes.get_last_error(), "AssignProcessToJobObject failed") + _k32.TerminateProcess(pi.hProcess, 1) + _k32.CloseHandle(pi.hThread) + _k32.CloseHandle(pi.hProcess) + raise error + _k32.ResumeThread(pi.hThread) + _k32.CloseHandle(pi.hThread) + child = ChildProcess(pi.dwProcessId, pi.hProcess, job, argv) + job = None # owned by the child object now + log.info("Started %s (pid %s, %s token, %s integrity%s)", os.path.basename(argv[0]), child.pid, + "desktop" if desktop else "restricted", child.token["integrity"], + ", ELEVATED" if child.token["elevated"] else "") + return child + finally: + if attributes is not None: + _k32.DeleteProcThreadAttributeList(attributes) + for handle in (out, nul, job, token): + if handle: + _k32.CloseHandle(handle) + + +def open_url(url: str) -> None: + """Open a web page in the default browser as the normal user, never elevated.""" + rundll = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "rundll32.exe") + child = launch([rundll, "url.dll,FileProtocolHandler", url], cwd=os.path.dirname(rundll), log_path=None, + contained=False) + child.close() diff --git a/kurgan/ai/service.py b/kurgan/ai/service.py new file mode 100644 index 0000000..ef6ad99 --- /dev/null +++ b/kurgan/ai/service.py @@ -0,0 +1,459 @@ +"""AI service: runs one LLM server at a time and swaps between them. + +The selected server (settings "ai.active") is started as a normal-user child process and +restarted if it crashes (5 crashes within 5 minutes pause restarts for 5 minutes). Swapping +stops the running server completely first, so the two never share the GPU's memory. + +Servers are also started on demand: a request through The Kurgan's web server +(/strata/..., /llama/...; see kurgan/web/proxy.py) selects its server and waits until it +answers. If the other server is busy (a request in flight, a reply being generated or a model +loading), the request waits for it to finish rather than cutting it off. A server nobody has +used for ai.idle_stop_minutes is stopped. + +A server already listening on a port that The Kurgan didn't start (for example Strata's or +the Qwen4 service's own tray, before they are retired) is shown as "external": it is +monitored but never started, stopped or duplicated. +""" + +from __future__ import annotations + +import collections +import ctypes +import ctypes.wintypes as wt +import logging +import os +import socket +import threading +import time + +from kurgan.ai import launcher +from kurgan.ai.backends import Backend, LlamaBackend, StrataBackend +from kurgan.ai.config import BACKENDS +from kurgan.settings import Settings + +log = logging.getLogger(__name__) + +_iphlp = ctypes.WinDLL("iphlpapi") +_k32 = ctypes.WinDLL("kernel32", use_last_error=True) +_iphlp.GetExtendedTcpTable.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.DWORD), wt.BOOL, wt.ULONG, ctypes.c_int, + wt.ULONG] +_iphlp.GetExtendedTcpTable.restype = wt.DWORD +_k32.OpenProcess.argtypes, _k32.OpenProcess.restype = [wt.DWORD, wt.BOOL, wt.DWORD], wt.HANDLE +_k32.QueryFullProcessImageNameW.argtypes = [wt.HANDLE, wt.DWORD, wt.LPWSTR, ctypes.POINTER(wt.DWORD)] +_k32.QueryFullProcessImageNameW.restype = wt.BOOL +_k32.CloseHandle.argtypes = [wt.HANDLE] + + +def port_in_use(port: int) -> bool: + with socket.socket() as probe: + probe.settimeout(0.3) + return probe.connect_ex(("127.0.0.1", port)) == 0 + + +def port_owner(port: int) -> tuple[int, str] | None: + """(pid, executable name) of the process listening on 127.0.0.1:port, if any.""" + size = wt.DWORD(0) + _iphlp.GetExtendedTcpTable(None, ctypes.byref(size), False, 2, 3, 0) # AF_INET, TCP_TABLE_OWNER_PID_LISTENER + buf = ctypes.create_string_buffer(size.value) + if _iphlp.GetExtendedTcpTable(buf, ctypes.byref(size), False, 2, 3, 0) != 0: + return None + count = ctypes.c_uint32.from_buffer(buf).value + row = ctypes.c_uint32 * 6 # state, local addr, local port, remote addr, remote port, pid + for i in range(count): + state, _addr, lport, _raddr, _rport, pid = row.from_buffer(buf, 4 + i * ctypes.sizeof(row)) + if ((lport & 0xFF) << 8 | (lport >> 8) & 0xFF) == port: + name = "?" + handle = _k32.OpenProcess(launcher.PROCESS_QUERY_LIMITED_INFORMATION, False, pid) + if handle: + try: + text, length = ctypes.create_unicode_buffer(1024), wt.DWORD(1024) + if _k32.QueryFullProcessImageNameW(handle, 0, text, ctypes.byref(length)): + name = os.path.basename(text.value) + finally: + _k32.CloseHandle(handle) + return pid, name + return None + + +class Slot: + """One backend and the process The Kurgan runs for it.""" + + def __init__(self, backend: Backend): + self.backend = backend + self.child: launcher.ChildProcess | None = None + self.variant: str | None = None + self.started_at: float | None = None + self.stopping = False + self.external: tuple[int, str] | None = None + self.crashes: collections.deque[float] = collections.deque(maxlen=5) + self.hold_until = 0.0 + self.restarts = 0 + self.error: str | None = None + self.reachable = False + + +class RouteError(Exception): + """A request for a server that can't be served now; status is the HTTP status to answer with.""" + + def __init__(self, message: str, status: int = 503): + super().__init__(message) + self.status = status + + +BUSY_STATES = ("loading", "reading", "generating") +CLIENT_GONE = 499 # RouteError status: the client hung up while waiting (nginx's "client closed request") + + +class AiService: + BUSY_WAIT = 600.0 # how long a request waits for the other server to finish before giving up + READY_WAIT = 120.0 # how long it waits for its own server to start answering + + def __init__(self, settings: Settings, backends: list[Backend] | None = None): + self.settings = settings + backends = backends or [StrataBackend(settings), LlamaBackend(settings)] + self.slots = {b.key: Slot(b) for b in backends} + self._wake = threading.Event() + self._lock = threading.Lock() + self._cv = threading.Condition() # guards inflight/last_used; notified when a request ends + self.inflight = {key: 0 for key in self.slots} + self.last_used = {key: time.monotonic() for key in self.slots} + self.transition: str | None = None + self.action: str | None = None # "Loading model..." while a load/unload request runs + self.message: str | None = None + self._stop: threading.Event | None = None + self._born = time.monotonic() + + def set_public_url(self, url: str) -> None: + """The Kurgan's web server, which the links in the UI point to.""" + for slot in self.slots.values(): + slot.backend.public = url.rstrip("/") + + # -- requests from the web UI (any thread) + + def set_active(self, key: str | None, variant: str | None = None) -> None: + if key is not None and key not in self.slots: + raise ValueError(f"Unknown AI backend {key!r}") + changes: dict = {"active": key} + if variant is not None: + changes["strata_model"] = variant + self.settings.update("ai", **changes) # validates the variant + log.info("AI backend selected: %s%s", key or "none", f" ({variant})" if variant else "") + if key is not None: + with self._cv: + self.last_used[key] = time.monotonic() # a full idle period before it can stop + self._wake.set() + + # -- requests through the web server (any thread) + + def _busy(self, key: str) -> bool: + """Serving or about to serve: a request in flight here, or a reply/model load in progress.""" + if self.inflight[key]: + return True + status = self.slots[key].backend.status + return bool(status.get("live")) or status["model"]["state"] in BUSY_STATES + + def claim(self, key: str, gone=None) -> Backend: + """Reserve key's server for one request: select it (stopping the other once that is idle) + and wait until it answers. Always pair with release(key). gone(), if given, says whether + the client has hung up; then the wait ends without switching anything.""" + if key not in self.slots: + raise RouteError(f"Unknown AI server {key!r}", 404) + slot = self.slots[key] + deadline = time.monotonic() + self.BUSY_WAIT + with self._cv: + while True: + active = self.settings.get("ai", "active") + if active == key or slot.external is not None: + break + other = self.slots[active] if active else None + if gone is not None and gone(): + raise RouteError(f"while waiting for {other.backend.label} to finish" if other is not None + else f"before {slot.backend.label} was started", CLIENT_GONE) + if other is None or other.external is not None or not self._busy(active): + try: + self.settings.update("ai", active=key) + except OSError as e: + raise RouteError(f"Couldn't save the AI selection: {e}", 500) from None + log.info("%s requested by a client%s", slot.backend.label, + f"; stopping {other.backend.label}" if other is not None and other.child else "") + self._wake.set() + break + if time.monotonic() >= deadline: + raise RouteError(f"{other.backend.label} is still busy with another request; try again later.") + self._cv.wait(1.0) + self.inflight[key] += 1 + self.last_used[key] = time.monotonic() + try: + self._wait_ready(key, slot, gone) + except BaseException: + self.release(key) + raise + return slot.backend + + def _wait_ready(self, key: str, slot: Slot, gone=None) -> None: + start = time.monotonic() + while True: + running = slot.external is not None or (slot.child is not None and not slot.stopping) + if running and port_in_use(slot.backend.port): + return + if self._stop is not None and self._stop.is_set(): + raise RouteError("The Kurgan is shutting down") + if gone is not None and gone(): + raise RouteError(f"while waiting for {slot.backend.label} to start", CLIENT_GONE) + waited = time.monotonic() - start + if slot.external is None and self.settings.get("ai", "active") != key and waited > 3: + raise RouteError(f"{slot.backend.label} was switched off in The Kurgan") + if slot.child is None and slot.error and waited > 3: + raise RouteError(slot.error) + if waited >= self.READY_WAIT: + raise RouteError(f"{slot.backend.label} didn't start within {self.READY_WAIT:.0f} s") + time.sleep(0.25) + + def release(self, key: str) -> None: + with self._cv: + self.inflight[key] = max(0, self.inflight[key] - 1) + self.last_used[key] = time.monotonic() + self._cv.notify_all() + + def running(self, key: str) -> bool: + """The server answers now (started by The Kurgan or not).""" + slot = self.slots[key] + return slot.reachable and (slot.external is not None or (slot.child is not None and not slot.stopping)) + + def model_action(self, action: str) -> None: + """Load or unload the model of the running server (in the background).""" + key = self.settings.get("ai", "active") + if key is None or action not in ("load", "unload"): + raise ValueError("No AI backend is selected" if key is None else f"Unknown action {action!r}") + slot = self.slots[key] + if not slot.reachable: + raise ValueError(f"{slot.backend.label} isn't running yet") + if self.action: + raise ValueError(f"Busy: {self.action}") + self.action = f"{'Loading' if action == 'load' else 'Unloading'} {slot.backend.label} model" + + def run(): + try: + getattr(slot.backend, action)() + self.message = None + except Exception as e: + log.warning("%s failed: %s", self.action, e) + self.message = f"{self.action} failed: {e}" + finally: + self.action = None + + threading.Thread(target=run, name=f"ai-{action}", daemon=True).start() + + # -- worker threads + + def start(self, stop: threading.Event) -> list[threading.Thread]: + self._stop = stop + threads = [threading.Thread(target=self.run, args=(stop,), name="ai-supervisor", daemon=True), + threading.Thread(target=self.monitor, args=(stop,), name="ai-monitor", daemon=True)] + llama = self.slots.get("llama") + if llama is not None and isinstance(llama.backend, LlamaBackend): + threads.append(threading.Thread(target=llama.backend.logparser.follow, + args=(llama.backend.current_log, stop), name="llama-log", daemon=True)) + for thread in threads: + thread.start() + return threads + + def monitor(self, stop: threading.Event) -> None: + while not stop.is_set(): + for slot in self.slots.values(): + running = slot.child is not None or slot.external is not None + if not running: + slot.reachable = False + slot.backend.mark_offline() + continue + try: + slot.backend.poll() + slot.reachable = True + except (OSError, ValueError, KeyError, StopIteration) as e: + slot.reachable = False + slot.backend.mark_offline() + log.debug("%s poll failed: %s", slot.backend.label, e) + stop.wait(1.5) + + def run(self, stop: threading.Event) -> None: + try: + while not stop.is_set(): + try: + self._reconcile(stop) + except Exception: + log.exception("AI supervisor error") + self._wake.wait(1.0) + self._wake.clear() + finally: + for slot in self.slots.values(): + if slot.child is not None: + self._stop_slot(slot, "The Kurgan is exiting") + + def _idle_check(self, active: str | None) -> str | None: + """Stop the selected server once nobody has used it for ai.idle_stop_minutes.""" + minutes = self.settings.get("ai", "idle_stop_minutes") + if not active or not minutes: + return active + slot = self.slots[active] + if slot.child is None or slot.stopping: + return active + with self._cv: + if self._busy(active): + self.last_used[active] = time.monotonic() + return active + if time.monotonic() - self.last_used[active] < minutes * 60: + return active + try: + self.settings.update("ai", active=None) + except OSError as e: + log.warning("Couldn't save the AI selection: %s", e) + return active + log.info("%s unused for %d minutes; stopping it until the next request", slot.backend.label, minutes) + return None + + def _reconcile(self, stop: threading.Event) -> None: + active = self._idle_check(self.settings.get("ai", "active")) + for slot in self.slots.values(): + self._check_exit(slot) + # Stop whatever isn't selected first, so the selected server gets the GPU to itself. + for key, slot in self.slots.items(): + if slot.child is not None and key != active: + self._stop_slot(slot, "switching" if active else "none selected") + for key, slot in self.slots.items(): + slot.external = None + if slot.child is None and port_in_use(slot.backend.port): + slot.external = port_owner(slot.backend.port) or (0, "unknown program") + if active is None or stop.is_set(): + self.transition = None + return + slot = self.slots[active] + if slot.child is not None and slot.variant != slot.backend.variant(): + self._stop_slot(slot, "changing model") + if slot.child is not None or slot.external is not None: + self.transition = None + return + if time.monotonic() < slot.hold_until: + return + # At logon The Kurgan can be up before Explorer; give the desktop up to 2 minutes so the + # server gets the desktop's own token (see launcher.py) rather than the fallback. + if time.monotonic() - self._born < 120 and not launcher.desktop_ready(): + self.transition = f"Waiting for the desktop to start {slot.backend.label}" + return + problem = slot.backend.check_files() + if problem: + slot.error = problem + return + self._start_slot(slot) + + def _check_exit(self, slot: Slot) -> None: + if slot.child is None or slot.stopping: + return + code = slot.child.poll() + if code is None: + return + slot.child.close() + slot.child = None + slot.restarts += 1 + slot.crashes.append(time.monotonic()) + if len(slot.crashes) == slot.crashes.maxlen and slot.crashes[-1] - slot.crashes[0] < 300: + slot.error = f"{slot.backend.label} keeps exiting (code {code}); retrying in 5 minutes. See its log." + slot.hold_until = time.monotonic() + 300 + slot.crashes.clear() + else: + slot.error = f"{slot.backend.label} exited (code {code}); restarting." + slot.hold_until = time.monotonic() + 5 + log.error(slot.error) + + def _start_slot(self, slot: Slot) -> None: + backend = slot.backend + self.transition = f"Starting {backend.label}" + backend.before_start() + argv, cwd, log_path = backend.command() + try: + slot.child = launcher.launch(argv, cwd, log_path) + except OSError as e: + slot.error = f"Could not start {backend.label}: {e}" + slot.hold_until = time.monotonic() + 30 + log.error(slot.error) + self.transition = None + return + if isinstance(backend, LlamaBackend): + backend.owned = True + with self._cv: + self.last_used[backend.key] = time.monotonic() + slot.variant = backend.variant() + slot.started_at = time.time() + slot.error = None + self.transition = None + + def _stop_slot(self, slot: Slot, why: str) -> None: + child, backend = slot.child, slot.backend + if child is None: + return + self.transition = f"Stopping {backend.label} ({why})" + log.info("Stopping %s (%s)", backend.label, why) + slot.stopping = True + try: + backend.request_stop(child) + if child.wait(backend.stop_timeout) is None: + log.warning("%s didn't stop within %.0f s; ending it", backend.label, backend.stop_timeout) + child.kill() + child.wait(10) + deadline = time.monotonic() + 10 # the port and VRAM are free once every process in the job is gone + while port_in_use(backend.port) and time.monotonic() < deadline: + time.sleep(0.25) + finally: + child.kill() + child.close() + slot.child = None + slot.stopping = False + slot.started_at = None + slot.reachable = False + if isinstance(backend, LlamaBackend): + backend.owned = False + backend.mark_offline() + self.transition = None + + # -- state for the UI + + def snapshot(self) -> dict: + active = self.settings.get("ai", "active") + minutes = self.settings.get("ai", "idle_stop_minutes") + now = time.monotonic() + with self._cv: + inflight = dict(self.inflight) + idle_in = {key: max(0, round(minutes * 60 - (now - self.last_used[key]))) + for key, slot in self.slots.items() + if minutes and key == active and slot.child is not None and not self._busy(key)} + backends = [] + for key, slot in self.slots.items(): + b = slot.backend + if slot.child is not None: + process = "stopping" if slot.stopping else ("running" if slot.reachable else "starting") + elif slot.external is not None: + process = "external" + else: + process = "stopped" + backends.append({ + "key": key, "label": b.label, "model_label": b.model_label(), "port": b.port, + "variants": b.variants(), "variant": b.variant(), "links": b.links(), + "process": process, "pid": slot.child.pid if slot.child else (slot.external[0] if slot.external else None), + "external_program": slot.external[1] if slot.external else None, + "token": slot.child.token if slot.child else None, + "uptime": round(time.time() - slot.started_at) if slot.started_at else None, + "restarts": slot.restarts, "error": slot.error, + "route": f"/{key}/", "inflight": inflight[key], "idle_stop_in": idle_in.get(key), + **b.snapshot(), + }) + others = [s.backend.label for k, s in self.slots.items() if k != active and s.external is not None] + warning = None + if others: + names, one = " and ".join(others), len(others) == 1 + warning = (f"{names} {'is' if one else 'are'} also running outside The Kurgan, so they may share " + "the GPU's memory." if active else + f"{names} {'is' if one else 'are'} running outside The Kurgan, from " + f"{'its own startup task' if one else 'their own startup tasks'}. Run setup.ps1 -RetireAIServices " + f"to let The Kurgan manage {'it' if one else 'them'}.") + return {"active": active, "backends_order": list(BACKENDS), "transition": self.transition, + "action": self.action, "message": self.message, "warning": warning, + "idle_stop_minutes": minutes, "backends": backends} diff --git a/kurgan/ai/strata_host.py b/kurgan/ai/strata_host.py new file mode 100644 index 0000000..ca558cf --- /dev/null +++ b/kurgan/ai/strata_host.py @@ -0,0 +1,104 @@ +"""Runs Strata's OpenAI-compatible server for The Kurgan. + +Started by The Kurgan with Strata's own venv (terminal\\.venv\\Scripts\\pythonw.exe), not +imported by it. Does what Strata's local-service-tray.py did, without the tray icon: +the same environment, arguments, logs and single-instance mutex. The Kurgan asks it to stop +by setting the named event given in --stop-event; Strata then shuts down cleanly (finishing +or cancelling the current request within --shutdown-timeout) and ends its engine processes. +""" + +from __future__ import annotations + +import _thread +import argparse +import contextlib +import ctypes +from ctypes import wintypes as wt +from datetime import datetime, timezone +import json +import logging +import os +from pathlib import Path +import sys +import threading + +LOG = logging.getLogger("kurgan-strata") +K32 = ctypes.WinDLL("kernel32", use_last_error=True) +K32.CreateEventW.argtypes, K32.CreateEventW.restype = [wt.LPVOID, wt.BOOL, wt.BOOL, wt.LPCWSTR], wt.HANDLE +K32.CreateMutexW.argtypes, K32.CreateMutexW.restype = [wt.LPVOID, wt.BOOL, wt.LPCWSTR], wt.HANDLE +K32.WaitForSingleObject.argtypes, K32.WaitForSingleObject.restype = [wt.HANDLE, wt.DWORD], wt.DWORD +K32.CloseHandle.argtypes = [wt.HANDLE] + + +def watch_stop(event: int, stopping: threading.Event) -> None: + while K32.WaitForSingleObject(event, 1000) != 0: + pass + LOG.info("The Kurgan asked Strata to stop") + stopping.set() + _thread.interrupt_main() + + +def run(root: Path, config_name: str, port: int, idle_unload: int, stop_name: str) -> int: + home = root / "terminal" + sys.path.insert(0, str(home)) + os.chdir(home) + from serve import lifeline, server + + config = home / config_name + with config.open(encoding="utf-8-sig") as source: + model_id = json.load(source)["model_name"] + # Same name as Strata's own tray uses, so the two can never serve one port at once. + mutex = K32.CreateMutexW(None, False, f"Local\\StrataLocalService-{port}") + if not mutex: + raise ctypes.WinError(ctypes.get_last_error()) + if ctypes.get_last_error() == 183: + K32.CloseHandle(mutex) + raise RuntimeError(f"Strata is already running for port {port}.") + stop_event = K32.CreateEventW(None, True, False, stop_name) + if not stop_event: + K32.CloseHandle(mutex) + raise ctypes.WinError(ctypes.get_last_error()) + stopping = threading.Event() + threading.Thread(target=watch_stop, args=(stop_event, stopping), name="kurgan-stop", daemon=True).start() + try: + LOG.info("Starting Strata API for %s at 127.0.0.1:%s (The Kurgan, pid %s)", model_id, port, os.getpid()) + os.environ["GGML_CUDA_DISABLE_GRAPHS"] = "1" + os.environ["STRATA_NO_CONSOLE"] = "1" + return server.main([ + "--engine", "strata", "--config", str(config), "--host", "127.0.0.1", + "--port", str(port), "--lazy", "--idle-unload", str(idle_unload), "--shutdown-timeout", "30", + ]) + except KeyboardInterrupt: + return 0 + finally: + lifeline.end_children() + K32.CloseHandle(stop_event) + K32.CloseHandle(mutex) + LOG.info("Strata stopped") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--config", required=True, help="run config file name in terminal\\") + parser.add_argument("--port", type=int, required=True) + parser.add_argument("--idle-unload", type=int, default=2000) + parser.add_argument("--stop-event", required=True) + args = parser.parse_args() + logs = args.root / "logs" + logs.mkdir(exist_ok=True) + stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S-%f") + logging.basicConfig(filename=logs / "local-service-task.log", level=logging.INFO, + format="%(asctime)s %(levelname)s %(message)s") + with (logs / f"local-service-stdout-{stamp}.log").open("w", encoding="utf-8", buffering=1) as stdout, \ + (logs / f"local-service-stderr-{stamp}.log").open("w", encoding="utf-8", buffering=1) as stderr, \ + contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + try: + return run(args.root, args.config, args.port, args.idle_unload, args.stop_event) + except (OSError, ValueError, KeyError, RuntimeError): + LOG.exception("Strata startup failed") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/kurgan/app.py b/kurgan/app.py new file mode 100644 index 0000000..cd67c80 --- /dev/null +++ b/kurgan/app.py @@ -0,0 +1,416 @@ +"""The Kurgan: one process for the LCD, fans, lighting, the local LLM servers and the web UI. + +Run: python -m kurgan (console, Ctrl+C to stop) +Hidden: pythonw -m kurgan (what the "The Kurgan" startup task runs, elevated) +Preview: python -m kurgan --preview x.png (render one LCD frame from live sensors and exit) + +Needs admin rights for PawnIO (CPU temperature/power, motherboard top fans, RAM lighting); +without them those parts show "--" or stay idle and everything else works. The LLM servers +are always started without admin rights (see kurgan/ai/launcher.py). +""" + +from __future__ import annotations + +import argparse +import collections +import ctypes +import logging +import logging.handlers +import math +import os +import sys +import threading +import time + +from kurgan import APP_NAME, __version__, paths + +log = logging.getLogger("kurgan") +INSTANCE_MUTEXES = ("Local\\TheKurgan", "Local\\TTLcdDashboard") # the second keeps an old dashboard copy out +DEMO_MUTEXES = ("Local\\TheKurganDemo",) + + +def _setup_logging(verbose: bool) -> None: + os.makedirs(paths.DATA_DIR, exist_ok=True) + handlers: list[logging.Handler] = [ + logging.handlers.RotatingFileHandler(paths.LOG_PATH, maxBytes=1_000_000, backupCount=2, encoding="utf-8") + ] + if sys.stderr is not None: + handlers.append(logging.StreamHandler()) + logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO, handlers=handlers, + format="%(asctime)s %(levelname)s %(name)s: %(message)s") + + +def _single_instance(names=INSTANCE_MUTEXES) -> list | None: + k32 = ctypes.WinDLL("kernel32", use_last_error=True) + k32.CreateMutexW.restype = ctypes.c_void_p + k32.CloseHandle.argtypes = [ctypes.c_void_p] + handles = [] + for name in names: + handle = k32.CreateMutexW(None, False, name) + if not handle or ctypes.get_last_error() in (183, 5): # ERROR_ALREADY_EXISTS, ERROR_ACCESS_DENIED + for h in handles + ([handle] if handle else []): + k32.CloseHandle(h) + return None + handles.append(handle) + return handles + + +def _message_box(text: str) -> None: + try: + ctypes.WinDLL("user32").MessageBoxW(None, text, APP_NAME, 0x10 | 0x10000) + except Exception: + pass + + +def _parse_color(text: str) -> tuple[int, int, int]: + text = text.lstrip("#") + return tuple(int(text[i:i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value] + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + from kurgan.cooling.control import parse_ports + + ap = argparse.ArgumentParser(prog="python -m kurgan", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--port", type=int, help="web UI port (default: settings.json web.port, 8080)") + ap.add_argument("--no-ai", action="store_true", help="don't start or watch the LLM servers") + ap.add_argument("--no-lcd", action="store_true", help="don't drive the LCD (sensors keep running)") + ap.add_argument("--no-tray", action="store_true", help="don't show the notification-area icon") + ap.add_argument("--preview", metavar="PNG", help="render one LCD frame from live sensors to a PNG and exit") + ap.add_argument("--demo", action="store_true", + help="simulated sensors and devices, no LCD (set KURGAN_DATA_DIR for separate settings)") + # LCD + ap.add_argument("--interval", type=float, default=1.0, help="seconds between sensor reads/LCD frames (max 2)") + ap.add_argument("--brightness", type=int, default=100, help="LCD backlight 0-100") + ap.add_argument("--rotate180", action="store_true", help="flip the image if the panel is mounted upside down") + ap.add_argument("--accent", default="e81c2c", help="LCD title colour as hex") + ap.add_argument("--psu-watts", type=float, default=1000.0, help="power supply rating; fills the power tank") + ap.add_argument("--cpu-temp-max", type=float, default=100.0) + ap.add_argument("--gpu-temp-max", type=float, default=90.0) + ap.add_argument("--temp-warn", type=float, default=50.0, help="gauges and lighting turn yellow here") + ap.add_argument("--temp-hot", type=float, default=80.0, help="gauges and lighting turn red above this") + ap.add_argument("--load-warn", type=float, default=50.0) + ap.add_argument("--load-hot", type=float, default=80.0) + ap.add_argument("--gpu-load", choices=("windows", "nvml"), default="windows") + ap.add_argument("--same-direction", action="store_true", help=argparse.SUPPRESS) + # Lighting: these override the saved mode for this run only (the web UI saves it). + fans = ap.add_mutually_exclusive_group() + fans.add_argument("--rgb-temperature", action="store_true", help="case fan LEDs: temperature (this run)") + fans.add_argument("--rgb-side-chase", action="store_true", help="case fan LEDs: red side chase (this run)") + memory = ap.add_mutually_exclusive_group() + memory.add_argument("--rgb-memory-temperature", action="store_true", help="RAM: temperature (this run)") + memory.add_argument("--rgb-memory-side-chase", action="store_true", help="RAM: red side chase (this run)") + memory.add_argument("--rgb-memory-off", action="store_true", help="RAM: off (this run)") + gpu = ap.add_mutually_exclusive_group() + gpu.add_argument("--rgb-gpu-side-chase", action="store_true", help="GPU LEDs: red side chase (this run)") + gpu.add_argument("--rgb-gpu-off", action="store_true", help="GPU LEDs: off (this run)") + ap.add_argument("--rgb-chase-step-ms", type=float, default=150.0, help="ms per chase LED at idle power") + ap.add_argument("--rgb-chase-fast-ms", type=float, default=25.0, help="ms per chase LED at full power") + ap.add_argument("--rgb-chase-idle-watts", type=float, default=150.0) + ap.add_argument("--rgb-chase-full-watts", type=float, default=550.0) + # Cooling + fan_options = ap.add_mutually_exclusive_group() + fan_options.add_argument("--gpu-fan-ports", type=parse_ports, metavar="1,2,3", + help="override the saved GPU-side Commander PRO ports for this run") + fan_options.add_argument("--no-gpu-fan-control", action="store_true", + help="disable case/top fan control for this run") + ap.add_argument("-v", "--verbose", action="store_true") + args = ap.parse_args(argv) + for name in ("rgb_chase_step_ms", "rgb_chase_fast_ms"): + if not math.isfinite(getattr(args, name)) or getattr(args, name) < 20: + ap.error(f"--{name.replace('_', '-')} must be finite and at least 20") + if args.rgb_chase_fast_ms > args.rgb_chase_step_ms: + ap.error("--rgb-chase-fast-ms can't be slower than --rgb-chase-step-ms") + if not (math.isfinite(args.rgb_chase_idle_watts) and math.isfinite(args.rgb_chase_full_watts) + and args.rgb_chase_full_watts > args.rgb_chase_idle_watts): + ap.error("--rgb-chase-full-watts must be above --rgb-chase-idle-watts") + if args.preview and args.gpu_fan_ports: + ap.error("--preview cannot be combined with --gpu-fan-ports") + args.interval = max(0.25, min(2.0, args.interval)) + return args + + +def lighting_overrides(args: argparse.Namespace) -> dict[str, str]: + overrides = {} + if args.rgb_temperature or args.rgb_side_chase: + overrides["case_fans"] = "temperature" if args.rgb_temperature else "chase" + if args.rgb_memory_temperature or args.rgb_memory_side_chase or args.rgb_memory_off: + overrides["memory"] = ("temperature" if args.rgb_memory_temperature else + "chase" if args.rgb_memory_side_chase else "off") + if args.rgb_gpu_side_chase or args.rgb_gpu_off: + overrides["gpu"] = "chase" if args.rgb_gpu_side_chase else "off" + return overrides + + +class Kurgan: + """Owns the capabilities and answers the web UI and the tray.""" + + def __init__(self, args: argparse.Namespace, settings): + from kurgan.cooling.control import CaseFanControl, TopFanCurve + from kurgan.cooling.profiles import PROFILES + from kurgan.display.renderer import DashboardRenderer + from kurgan.display.service import DisplayService + from kurgan.lighting.service import LightingService + from kurgan.telemetry.sensors import CpuSensors, GpuSensors, SystemPower + from kurgan.telemetry.service import Telemetry + from kurgan.theme import Theme + + self.args = args + self.settings = settings + self.started = time.time() + self.stop = threading.Event() + self.theme = Theme(accent=_parse_color(args.accent), cpu_temp_range=(20.0, args.cpu_temp_max), + gpu_temp_range=(20.0, args.gpu_temp_max), psu_watts=max(100.0, args.psu_watts), + temp_warn=args.temp_warn, temp_hot=args.temp_hot, + load_warn=args.load_warn, load_hot=args.load_hot) + hw = None + if args.demo: + from kurgan import demo + hw = demo.hardware() + self.system = hw["system"] if hw else SystemPower() + self.telemetry = Telemetry(hw["cpu"] if hw else CpuSensors(), + hw["gpu"] if hw else GpuSensors(load_source=args.gpu_load), + self.system, args.interval) + self.display = None if (args.no_lcd or hw) else DisplayService( + DashboardRenderer(self.theme, rotate180=args.rotate180), self.telemetry, args.brightness) + + cooling = settings.section("cooling") + self.fan_note = None + self.fans: CaseFanControl | None = None + gpu_ports = None if args.no_gpu_fan_control else (args.gpu_fan_ports or cooling.get("gpu_ports")) + if gpu_ports: + top = cooling.get("top_channels") + top_curve = None + if top: + top_curve = TopFanCurve(tuple(top), board_factory=hw["board"]) if hw else TopFanCurve(tuple(top)) + self.fans = CaseFanControl(self.system.fans, tuple(gpu_ports), + tuple(cooling.get("cpu_ports") or ()) or None, top_curve, + profile=PROFILES[cooling["profile"]], sensors=hw["fan_sensors"] if hw else None) + self.system.fans.controlled = True + else: + self.fan_note = ("Fan control is off for this run (--no-gpu-fan-control)." if args.no_gpu_fan_control + else "Fan control isn't set up: save the Commander PRO ports first (see README).") + + self.lighting = LightingService( + settings, self.theme, + (args.rgb_chase_step_ms / 1000, args.rgb_chase_fast_ms / 1000, + args.rgb_chase_idle_watts, args.rgb_chase_full_watts), + lighting_overrides(args), **(hw["lighting"] if hw else {})) + self.ai = None + if not args.no_ai: + from kurgan.ai.service import AiService + self.ai = AiService(settings) + self.web = None + self.tray = None + self._threads: list[threading.Thread] = [] + self.fan_history: collections.deque[tuple] = collections.deque(maxlen=self.telemetry._history.maxlen) + self.telemetry.subscribe(self._on_sample) + + # -- lifecycle + + def _fan_row(self, t: float) -> tuple: + cpu, top = self.fans.cpu, self.fans.top + return (round(t, 1), self.fans.gpu.duty, None if cpu is None else cpu.duty, None if top is None else top.duty) + + def _on_sample(self, sample) -> None: + p = sample.power + self.lighting.on_telemetry(sample.cpu.temp, sample.gpu.temp, p.total) + if self.fans is not None: + self.fan_history.append(self._fan_row(sample.t)) + if self.tray is not None: + fmt = lambda v: "--" if v is None else f"{v:.0f}" + self.tray.set_tooltip(f"{APP_NAME}\nTotal {fmt(p.total)} W: CPU {fmt(p.cpu)}, " + f"GPU {fmt(p.gpu)}, other {fmt(p.other)}") + + def _thread(self, name: str, target, *args) -> None: + thread = threading.Thread(target=target, args=args, name=name, daemon=True) + thread.start() + self._threads.append(thread) + + def start(self, port: int, tray: bool) -> None: + from kurgan.web.server import WebServer + + self._thread("telemetry", self.telemetry.run, self.stop) + if self.fans is not None: + self._thread("case-fans", self.fans.run, self.stop) + self.lighting.start(self.stop) + if self.display is not None: + self._thread("display", self.display.run, self.stop) + if self.ai is not None: + self.ai.set_public_url(f"http://127.0.0.1:{port}") + self._threads += self.ai.start(self.stop) + try: + self.web = WebServer(self, port) + self.web.start() + except OSError as e: + log.error("Web UI unavailable on port %s: %s", port, e) + if tray: + self._start_tray() + + def _start_tray(self) -> None: + from kurgan.tray import TrayIcon, make_icon + + try: + icon = make_icon(os.path.join(paths.DATA_DIR, "tray.ico"), + [self.theme.other_color, self.theme.cpu_color, self.theme.gpu_color]) + self.tray = TrayIcon(APP_NAME, icon, on_exit=self.stop.set, + on_open=self.open_ui if self.web else None, status_lines=self.tray_lines) + self.tray.start() + except Exception: + log.exception("Tray icon unavailable") + self.tray = None + + def open_ui(self) -> None: + from kurgan.ai.launcher import open_url + + try: + open_url(self.web.url) + except OSError: + log.exception("Couldn't open the browser") + + def wait(self) -> None: + try: + while not self.stop.wait(1): + pass + except KeyboardInterrupt: + self.stop.set() + + def close(self) -> None: + self.stop.set() + if self.web is not None: + self.web.close() + if self.tray is not None: + self.tray.close() + deadline = time.monotonic() + 60 # Strata may take up to ~45 s to shut down cleanly + for thread in self._threads: + thread.join(max(0.1, deadline - time.monotonic())) + self.lighting.join() + self.system.fans.close() + + # -- the web UI's API + + def config(self) -> dict: + from kurgan.cooling.profiles import PROFILES + + return {"app": APP_NAME, "version": __version__, + "profiles": [p.as_dict() for p in PROFILES.values()], + "theme": {"temp_warn": self.theme.temp_warn, "temp_hot": self.theme.temp_hot, + "psu_watts": self.theme.psu_watts}} + + def state(self) -> dict: + from kurgan.ai.launcher import token_info + + try: + me = token_info() + except OSError: + me = None + return { + "app": {"name": APP_NAME, "version": __version__, "uptime": round(time.time() - self.started), + "pid": os.getpid(), "token": me}, + "telemetry": self.telemetry.snapshot(), + "display": self.display.snapshot() if self.display else {"status": "Off (--no-lcd)", "connected": False}, + "cooling": ({**self.fans.snapshot(), "note": None, "row": self.fan_history[-1] if self.fan_history else None} + if self.fans is not None + else {"profile": self.settings.get("cooling", "profile"), "groups": [], "top": None, + "note": self.fan_note, "row": None}), + "lighting": self.lighting.snapshot(), + "ai": self.ai.snapshot() if self.ai else None, + } + + def history(self) -> dict: + return {**self.telemetry.history(), + "fans": {"series": ("t", "gpu_duty", "cpu_duty", "top_duty"), "rows": list(self.fan_history)}} + + def set_lighting(self, zone: str, mode: str) -> None: + self.lighting.set_mode(zone, mode) + + def set_fan_profile(self, key: str) -> None: + from kurgan.cooling.profiles import PROFILES + + if key not in PROFILES: + raise ValueError(f"Unknown fan profile {key!r}") + self.settings.update("cooling", profile=key) + if self.fans is not None: + self.fans.apply_profile(PROFILES[key]) + + def set_ai(self, backend: str | None, variant: str | None) -> None: + if self.ai is None: + raise ValueError("AI management is off for this run (--no-ai)") + self.ai.set_active(backend, variant) + + def ai_model(self, action: str) -> None: + if self.ai is None: + raise ValueError("AI management is off for this run (--no-ai)") + self.ai.model_action(action) + + # -- tray + + def tray_lines(self) -> list[str]: + lines = [] + if self.display is not None: + lines.append(self.display.status) + if self.fans is not None: + profile = self.fans.profile.name + groups = ", ".join(f"{g.name} {g.duty}%" for g in self.fans.groups) + top = f", top {self.fans.top.duty}%" if self.fans.top is not None else "" + lines.append(f"Fans: {profile} ({groups}{top})") + elif self.fan_note: + lines.append("Fans: not controlled") + modes = {z["key"]: z["mode"] for z in self.lighting.snapshot()["zones"]} + lines.append(f"Lighting: case fans {modes['case_fans']}, RAM {modes['memory']}, GPU {modes['gpu']}") + if self.ai is not None: + ai = self.ai.snapshot() + active = next((b for b in ai["backends"] if b["key"] == ai["active"]), None) + if active is None: + lines.append("AI: none selected") + else: + lines.append(f"AI: {active['label']} - {active['process']}, model {active['model']['state']}") + if self.web is not None: + lines.append(f"Web UI: {self.web.url}") + return lines + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv) + _setup_logging(args.verbose) + from kurgan.settings import Settings, SettingsError + + if args.preview: + from kurgan.display.renderer import DashboardRenderer + from kurgan.telemetry.sensors import CpuSensors, GpuSensors, SystemPower + from kurgan.theme import Theme + + from kurgan.telemetry.service import Telemetry + telemetry = Telemetry(CpuSensors(), GpuSensors(load_source=args.gpu_load), SystemPower()) + telemetry.read() + time.sleep(1.0) # let counters and the energy meter accumulate + sample = telemetry.read() + theme = Theme(accent=_parse_color(args.accent), psu_watts=max(100.0, args.psu_watts)) + DashboardRenderer(theme, rotate180=args.rotate180).render(sample.cpu, sample.gpu, sample.power).save( + args.preview) + print(f"Wrote {args.preview}") + return 0 + + mutexes = _single_instance(DEMO_MUTEXES if args.demo else INSTANCE_MUTEXES) + if mutexes is None: + log.error("Another copy of The Kurgan (or the TT LCD Dashboard) is already running") + return 1 + try: + settings = Settings(seed={"lighting": lighting_overrides(args)}) + except (OSError, SettingsError) as e: + log.error("Invalid settings; refusing to start: %s", e) + _message_box(f"The Kurgan didn't start: its settings are invalid.\n\n{e}\n\nLog: {paths.LOG_PATH}") + return 1 + port = args.port or settings.get("web", "port") + log.info("Starting %s %s (pid %s)", APP_NAME, __version__, os.getpid()) + try: + app = Kurgan(args, settings) + except ValueError: + log.exception("Invalid configuration; refusing to start") + return 1 + app.start(port, tray=not args.no_tray) + app.wait() + log.info("Stopping") + app.close() + log.info("Stopped") + return 0 diff --git a/kurgan/cooling/__init__.py b/kurgan/cooling/__init__.py new file mode 100644 index 0000000..2c5c8b5 --- /dev/null +++ b/kurgan/cooling/__init__.py @@ -0,0 +1 @@ +"""Cooling: Commander PRO case fans and motherboard top fans on selectable profiles.""" diff --git a/kurgan/cooling/board_fans.py b/kurgan/cooling/board_fans.py new file mode 100644 index 0000000..7060c00 --- /dev/null +++ b/kurgan/cooling/board_fans.py @@ -0,0 +1,276 @@ +"""MSI motherboard fan headers on the Nuvoton NCT6687D Super I/O, through PawnIO's signed LpcIO module. + +Register layout and the fan-configuration handshake follow LibreHardwareMonitor's Nct677X.cs. +Needs PawnIO and administrator rights. Run ``python board_fans.py --probe`` to list the headers. +""" + +from __future__ import annotations + +import argparse +import ctypes +import ctypes.wintypes as wt +import os +import struct +import threading +import time + +from kurgan.hardware import PAWNIO_DIR + + +_k32 = ctypes.WinDLL("kernel32", use_last_error=True) +_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE] +_k32.CreateFileW.restype = wt.HANDLE +_k32.DeviceIoControl.argtypes = [wt.HANDLE, wt.DWORD, ctypes.c_void_p, wt.DWORD, ctypes.c_void_p, wt.DWORD, + ctypes.POINTER(wt.DWORD), ctypes.c_void_p] +_k32.DeviceIoControl.restype = wt.BOOL +_k32.CloseHandle.argtypes = [wt.HANDLE] +_k32.CreateMutexW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.LPCWSTR] +_k32.CreateMutexW.restype = wt.HANDLE +_k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD] +_k32.WaitForSingleObject.restype = wt.DWORD +_k32.ReleaseMutex.argtypes = [wt.HANDLE] + + +class PawnIo: + DEVICE = r"\\?\GLOBALROOT\Device\PawnIO" + IOCTL_LOAD_BINARY = 0xA1B22084 + IOCTL_EXECUTE_FN = 0xA1B22104 + + def __init__(self, module: str): + h = _k32.CreateFileW(self.DEVICE, 0xC0000000, 0x3, None, 3, 0, None) + if h == wt.HANDLE(-1).value: + err = ctypes.get_last_error() + reason = "run as administrator" if err == 5 else "is PawnIO installed?" + raise OSError(f"Cannot open PawnIO ({ctypes.FormatError(err).strip()}; {reason})") + self.handle = h + with open(module, "rb") as f: + blob = f.read() + ret = wt.DWORD() + if not _k32.DeviceIoControl(h, self.IOCTL_LOAD_BINARY, blob, len(blob), None, 0, ctypes.byref(ret), None): + err = ctypes.get_last_error() + self.close() + raise OSError(f"PawnIO refused {os.path.basename(module)}: {ctypes.FormatError(err).strip()}") + + def execute(self, fn: str, args: tuple[int, ...] = (), out: int = 0) -> tuple[int, ...]: + inbuf = fn.encode().ljust(32, b"\x00") + struct.pack(f"<{len(args)}q", *args) + outbuf = ctypes.create_string_buffer(8 * out) + ret = wt.DWORD() + if not _k32.DeviceIoControl(self.handle, self.IOCTL_EXECUTE_FN, inbuf, len(inbuf), outbuf, 8 * out, + ctypes.byref(ret), None): + raise OSError(f"PawnIO {fn} failed: {ctypes.FormatError(ctypes.get_last_error()).strip()}") + return struct.unpack(f"<{out}Q", outbuf.raw) + + def close(self) -> None: + if self.handle: + _k32.CloseHandle(self.handle) + self.handle = None + + +class Nct6687: + """NCT6687D EC: 16 RPM inputs; PWM channels 0-7 are CPU, pump, then system fans 1-6.""" + + MODULE = os.path.join(PAWNIO_DIR, "LpcIO.bin") + ISA_MUTEX = "Global\\Access_ISABUS.HTP.Method" # shared with LibreHardwareMonitor/FanControl + CHANNELS = 8 + PAGE, INDEX, DATA = 4, 5, 6 + RPM, PWM_OUT, MODE, REQUEST, COMMAND = 0x140, 0x160, 0xA00, 0xA01, 0xA28 + CFG_REQUEST, CFG_COMPLETE = 0x80, 0x40 + + def __init__(self): + self._lock = threading.RLock() + self._mutex = _k32.CreateMutexW(None, False, self.ISA_MUTEX) + if not self._mutex: + raise OSError(f"Cannot open the ISA bus mutex: {ctypes.FormatError(ctypes.get_last_error()).strip()}") + self.io: PawnIo | None = None + try: + self.io = PawnIo(self.MODULE) + with self._bus(): + self.base, self.slot = self._detect() + except Exception: + self.close() + raise + + def close(self) -> None: + if self.io is not None: + self.io.close() + self.io = None + if self._mutex: + _k32.CloseHandle(self._mutex) + self._mutex = None + + def _bus(self): + nct = self + + class _Held: + def __enter__(self): + nct._lock.acquire() + if _k32.WaitForSingleObject(nct._mutex, 500) not in (0, 0x80): # WAIT_OBJECT_0, WAIT_ABANDONED + nct._lock.release() + raise OSError("ISA bus busy (another hardware monitor is holding it)") + + def __exit__(self, *exc): + _k32.ReleaseMutex(nct._mutex) + nct._lock.release() + + return _Held() + + def _detect(self) -> tuple[int, int]: + assert self.io is not None + for slot, reg in ((0, 0x2E), (1, 0x4E)): + self.io.execute("ioctl_select_slot", (slot,)) + self.io.execute("ioctl_pio_outb", (reg, 0x87)) + self.io.execute("ioctl_pio_outb", (reg, 0x87)) + chip = self.io.execute("ioctl_superio_inb", (0x20,), 1)[0] + rev = self.io.execute("ioctl_superio_inb", (0x21,), 1)[0] + if (chip, rev) != (0xD5, 0x92): + if chip not in (0, 0xFF): + self.io.execute("ioctl_pio_outb", (reg, 0xAA)) + continue + self.io.execute("ioctl_find_bars") + self.io.execute("ioctl_superio_outb", (0x07, 0x0B)) # hardware-monitor logical device + base = self.io.execute("ioctl_superio_inw", (0x60,), 1)[0] + time.sleep(0.001) + verify = self.io.execute("ioctl_superio_inw", (0x60,), 1)[0] + self.io.execute("ioctl_pio_outb", (reg, 0xAA)) + if base != verify or base < 0x100 or base in (0xFFFF,): + raise OSError(f"NCT6687D at 0x{reg:X} reported an invalid base address 0x{base:X}") + return base & 0xFFF8, slot + raise OSError("No Nuvoton NCT6687D Super I/O found (expected on MSI 600/700-series boards)") + + def _out(self, port: int, value: int) -> None: + assert self.io is not None + self.io.execute("ioctl_pio_outb", (self.base + port, value)) + + def _in(self, port: int) -> int: + assert self.io is not None + return self.io.execute("ioctl_pio_inb", (self.base + port,), 1)[0] + + def _claim_page(self) -> None: + deadline = time.monotonic() + 0.5 + while self._in(self.PAGE) != 0xFF: + if time.monotonic() >= deadline: + self._out(self.PAGE, 0xFF) # stale owner: force access, as LibreHardwareMonitor does + return + time.sleep(0.001) + + def read(self, address: int) -> int: + self._claim_page() + self._out(self.PAGE, address >> 8) + self._out(self.INDEX, address & 0xFF) + value = self._in(self.DATA) + self._out(self.PAGE, 0xFF) + return value + + def write(self, address: int, value: int) -> None: + self._claim_page() + self._out(self.PAGE, address >> 8) + self._out(self.INDEX, address & 0xFF) + self._out(self.DATA, value & 0xFF) + self._out(self.PAGE, 0xFF) + + def rpms(self) -> list[int]: + """RPM of all 16 tachometer inputs.""" + with self._bus(): + return [(self.read(self.RPM + 2 * i) << 8) | self.read(self.RPM + 2 * i + 1) for i in range(16)] + + def duties(self) -> list[int]: + """Current output duty (0-100%) of PWM channels 0-7.""" + with self._bus(): + return [round(self.read(self.PWM_OUT + i) / 2.55) for i in range(self.CHANNELS)] + + def manual_mask(self) -> int: + with self._bus(): + return self.read(self.MODE) + + def _check_channels(self, channels: tuple[int, ...]) -> int: + if not channels or any(c not in range(self.CHANNELS) for c in channels): + raise ValueError(f"PWM channels must be 0-{self.CHANNELS - 1}") + mask = 0 + for c in channels: + mask |= 1 << c + return mask + + def set_manual(self, channels: tuple[int, ...], duty: int) -> None: + """Override the BIOS curve with a fixed duty on these channels.""" + mask = self._check_channels(channels) + if not 0 <= duty <= 100: + raise ValueError("duty must be 0-100") + with self._bus(): + self.write(self.REQUEST, self.CFG_REQUEST) + time.sleep(0.05) + self.write(self.MODE, self.read(self.MODE) | mask) + for c in channels: + self.write(self.COMMAND + c, round(duty * 2.55)) + self.write(self.REQUEST, self.CFG_COMPLETE) + time.sleep(0.05) + + def set_auto(self, channels: tuple[int, ...]) -> None: + """Hand these channels back to the BIOS Smart Fan curve.""" + mask = self._check_channels(channels) + with self._bus(): + self.write(self.REQUEST, self.CFG_REQUEST) + time.sleep(0.05) + self.write(self.MODE, self.read(self.MODE) & ~mask & 0xFF) + self.write(self.REQUEST, self.CFG_COMPLETE) + time.sleep(0.05) + + +def parse_channels(text: str) -> tuple[int, ...]: + try: + channels = tuple(sorted({int(c) for c in text.split(",")})) + except ValueError as e: + raise argparse.ArgumentTypeError("Use comma-separated PWM channels, e.g. 2,5") from e + if not channels or any(c not in range(Nct6687.CHANNELS) for c in channels): + raise argparse.ArgumentTypeError(f"PWM channels must be 0-{Nct6687.CHANNELS - 1}") + return channels + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + action = ap.add_mutually_exclusive_group(required=True) + action.add_argument("--probe", action="store_true", help="read-only listing of the fan headers") + action.add_argument("--identify", type=parse_channels, metavar="2,5", + help="hold these PWM channels at 100%% (until --auto) to see which fans they drive") + action.add_argument("--auto", type=parse_channels, metavar="2,5", + help="return these PWM channels to the BIOS Smart Fan curve") + ap.add_argument("--out", help="also write the report to this file") + args = ap.parse_args() + lines: list[str] = [] + try: + nct = Nct6687() + try: + if args.identify: + nct.set_manual(args.identify, 100) + time.sleep(5) + lines.append(f"Channels {args.identify} held at 100% until --auto") + elif args.auto: + nct.set_auto(args.auto) + time.sleep(3) + lines.append(f"Channels {args.auto} returned to the BIOS curve") + with nct._bus(): + regs = {a: nct.read(a) for a in (0x180, nct.MODE, nct.REQUEST)} + commands = [nct.read(nct.COMMAND + i) for i in range(nct.CHANNELS)] + temps = [nct.read(0x100 + 2 * i) for i in range(7)] + rpms, duties = nct.rpms(), nct.duties() + lines.append(f"NCT6687D slot {nct.slot}, base 0x{nct.base:X}") + lines.append("init 0x180=0x%02X manual mask 0xA00=0x%02X request 0xA01=0x%02X" % tuple(regs.values())) + lines.append("temps 0x100..: " + ", ".join(str(struct.unpack('b', bytes([t]))[0]) for t in temps)) + for i in range(nct.CHANNELS): + lines.append(f"PWM ch{i}: out {duties[i]:3d}% command {commands[i]:3d} " + f"manual {'yes' if regs[nct.MODE] >> i & 1 else 'no'}") + for i, rpm in enumerate(rpms): + lines.append(f"RPM reg 0x{nct.RPM + 2 * i:03X}: {rpm}") + finally: + nct.close() + except Exception as e: + lines.append(f"ERROR: {type(e).__name__}: {e}") + report = "\n".join(lines) + print(report) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + f.write(report + "\n") + return 1 if report.startswith("ERROR") or "\nERROR" in report else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/kurgan/cooling/control.py b/kurgan/cooling/control.py new file mode 100644 index 0000000..edc6368 --- /dev/null +++ b/kurgan/cooling/control.py @@ -0,0 +1,389 @@ +"""Opt-in temperature control of Commander PRO PWM ports: the GPU-side group follows GPU +temperature and an optional CPU-side group follows CPU temperature. Optional motherboard +header fans follow the hotter of the two (stopped while cool) and run at 100% while either +group works hard.""" + +from __future__ import annotations + +import argparse +import collections +import logging +import math +import threading +import time + +from kurgan.cooling.board_fans import Nct6687, parse_channels +from kurgan.cooling.profiles import BALANCED, FanProfile +from kurgan.hardware.hid import HidError +from kurgan.telemetry.sensors import CommanderPro, GpuSensors, IntelPackage + +log = logging.getLogger(__name__) +# The Balanced profile's curves (the original ones); the active profile can replace them at runtime. +CURVE, CPU_CURVE, TOP_CURVE = BALANCED.gpu_curve, BALANCED.cpu_curve, BALANCED.top_curve +CPU_AVERAGE = 5 # seconds of CPU package temperature averaged, so momentary spikes don't surge the fans +BOOST_ON, BOOST_OFF = 85, 65 # case fan duty (either side) that starts / ends the top-fan boost +TOP_START, TOP_STOP = BALANCED.top_start, BALANCED.top_stop # top fans start at / stop below (C) ... +TOP_STOP_HOLD = 30 # ... once it has stayed below the stop temperature for this many seconds +TOP_KICK, TOP_KICK_SECONDS = 40, 3 # spin-up duty when starting from stopped + + +def parse_ports(text: str) -> tuple[int, ...]: + try: + ports = tuple(int(p.strip()) for p in text.split(",")) + except ValueError as e: + raise argparse.ArgumentTypeError("Use three comma-separated ports, e.g. 1,2,3") from e + if len(ports) != 3 or len(set(ports)) != 3 or any(p not in range(1, 7) for p in ports): + raise argparse.ArgumentTypeError("Specify exactly three distinct Commander PRO ports (1-6)") + return ports + + +def _curve_duty(curve: tuple[tuple[int, int], ...], temp: float | None) -> int: + if temp is None or not math.isfinite(temp) or not 0 <= temp <= 110: + return 100 + for (t0, d0), (t1, d1) in zip(curve, curve[1:]): + if temp <= t1: + return math.ceil(d0 + max(0, temp - t0) * (d1 - d0) / (t1 - t0)) + return 100 + + +def gpu_duty(temp: float | None) -> int: + return _curve_duty(CURVE, temp) + + +def cpu_duty(temp: float | None) -> int: + return _curve_duty(CPU_CURVE, temp) + + +class TopFanCurve: + """Motherboard header fans on their own curve from the hotter of CPU/GPU, stopped while cool. + + They are also held at 100% while either case fan group works hard; on exit the BIOS curve + takes over again.""" + + RETRY = 30.0 + + def __init__(self, channels: tuple[int, ...], board_factory=Nct6687, profile: FanProfile = BALANCED): + self.channels = parse_channels(",".join(map(str, channels))) + self.curve, self.start, self.stop = profile.top_curve, profile.top_start, profile.top_stop + self.temp: float | None = None + self._mask = sum(1 << c for c in self.channels) + self._factory = board_factory + self.board: Nct6687 | None = None + self.boosted = False + self.running = False + self.duty = 0 + self.status = "Starting" + self._retry_at = 0.0 + self._written: int | None = None + self._kick_until = 0.0 + self._cool_since: float | None = None + self._last_rise = 0.0 + self._last_update: float | None = None + + def apply_profile(self, profile: FanProfile) -> None: + self.curve, self.start, self.stop = profile.top_curve, profile.top_start, profile.top_stop + + def _status(self, text: str, warning: bool = False) -> None: + if text != self.status: + (log.warning if warning else log.info)("Top fans: %s", text) + self.status = text + + def snapshot(self) -> dict: + return {"channels": list(self.channels), "temp": self.temp, "duty": self.duty, "running": self.running, + "boosted": self.boosted, "status": self.status, + "failsafe": self.status.startswith(("FAILSAFE", "UNAVAILABLE"))} + + def close(self) -> None: + if self.board is not None: + self.board.close() + self.board = None + self._written = None + + def _target(self, case_duty: int, temp: float | None, now: float) -> tuple[int, str]: + self.boosted = case_duty >= BOOST_ON or (self.boosted and case_duty > BOOST_OFF) + if temp is None or not math.isfinite(temp) or not 0 <= temp <= 110: + self.running, self._cool_since = True, None + return 100, "FAILSAFE 100%: temperature unavailable" + if not self.running and (temp >= self.start or self.boosted): + self.running, self._cool_since = True, None + self._kick_until = now + TOP_KICK_SECONDS + elif self.running and temp < self.stop and not self.boosted: + self._cool_since = now if self._cool_since is None else self._cool_since + if now - self._cool_since >= TOP_STOP_HOLD: + self.running, self._cool_since = False, None + else: + self._cool_since = None + if not self.running: + return 0, f"{temp:.0f} C, stopped (start at {self.start} C)" + target = _curve_duty(self.curve, temp) + if self.boosted: + target = 100 + if now < self._kick_until: + target = max(target, TOP_KICK) + return target, f"{temp:.0f} C, {{duty}}%" + (f" (case fans >= {BOOST_ON}%)" if self.boosted else "") + + def update(self, case_duty: int, temp: float | None, now: float) -> None: + self.temp = temp + target, text = self._target(case_duty, temp, now) + elapsed = 0 if self._last_update is None else min(2, max(0, now - self._last_update)) + self._last_update = now + if target == 0 or target >= self.duty: + if target > self.duty: + self._last_rise = now + self.duty = target + elif now - self._last_rise >= 10: + self.duty = max(target, self.duty - int(2 * elapsed)) + if self.board is None and now < self._retry_at: + return + try: + if self.board is None: + self.board = self._factory() + # Compared every poll, so a firmware reset (e.g. after sleep) or a crash is corrected. + if self.duty != self._written or self.board.manual_mask() & self._mask != self._mask: + self.board.set_manual(self.channels, self.duty) + self._written = self.duty + self._status(text.format(duty=self.duty), warning=text.startswith("FAILSAFE")) + except (OSError, ValueError) as e: + self._status(f"UNAVAILABLE ({e}); BIOS curve keeps control", warning=True) + self.close() + self._retry_at = now + self.RETRY + + def release(self) -> None: + try: + if self.board is None: + self.board = self._factory() + self.board.set_auto(self.channels) + self.boosted = self.running = False + except (OSError, ValueError): + log.exception("Cannot return top fans to the BIOS curve") + finally: + self.close() + + +class CaseFanGroup: + """Three Commander PRO ports following one temperature: immediate rises, slow falls, failsafe 100%.""" + + def __init__(self, name: str, curve, commander: CommanderPro, ports: tuple[int, ...]): + self.name = name + self.curve = curve + self.ports = parse_ports(",".join(map(str, ports))) + self.commander = commander + self.status = "Starting" + self.duty = 100 + self.temp: float | None = None + self.rpms: dict[int, int] = {} + self._last_update: float | None = None + self._last_rise = 0.0 + self._started: float | None = None + + def set_status(self, text: str, warning: bool = False) -> None: + if text != self.status: + (log.warning if warning else log.info)("%s case fans: %s", self.name, text) + self.status = text + + def snapshot(self) -> dict: + return {"name": self.name, "ports": list(self.ports), "temp": self.temp, "duty": self.duty, + "rpms": {str(p): self.rpms.get(p) for p in self.ports}, "status": self.status, + "failsafe": self.status.startswith(("FAILSAFE", "CONTROL ERROR"))} + + def update(self, temp: float | None, now: float) -> None: + self.temp = temp + target = _curve_duty(self.curve, temp) + invalid = temp is None or not math.isfinite(temp) or not 0 <= temp <= 110 + if self._last_update is None or now - self._last_update > 5: + self.duty = 100 + self._last_rise = now + self._started = now + elapsed = 0 if self._last_update is None else min(2, max(0, now - self._last_update)) + if target >= self.duty: + if target > self.duty or invalid: + self._last_rise = now + self.duty = target + elif now - self._last_rise >= 10: + self.duty = max(target, self.duty - int(2 * elapsed)) + self._last_update = now + rpms = self.rpms = self.commander.set_duty(self.ports, self.duty) + if self._started is not None and now - self._started >= 10: + stalled = [p for p in self.ports if rpms.get(p, 0) < 200] + if stalled: + self.duty = 100 + self._last_rise = now + self.commander.set_duty(self.ports, 100) + self.set_status(f"FAILSAFE 100%: no/low RPM on ports {stalled}", warning=True) + return + if invalid: + self.set_status(f"FAILSAFE 100%: {self.name} temperature unavailable", warning=True) + else: + self.set_status(f"{self.name} {temp:.0f} C, {self.duty}% PWM; " + + ", ".join(f"{p}: {rpms.get(p, 0)} rpm" for p in self.ports)) + + def failsafe(self) -> None: + self.duty = 100 + self._last_update = None + try: + self.commander.set_duty(self.ports, 100) + except (OSError, HidError): + log.exception("Cannot set %s case fans to failsafe 100%%; controller unavailable", self.name) + + +class CpuTemperature: + """CPU package temperature averaged over CPU_AVERAGE readings; None while unavailable.""" + + def __init__(self, factory=IntelPackage): + self._factory = factory + self.pkg: IntelPackage | None = None + self._retry_at = 0.0 + self._recent: collections.deque[float] = collections.deque(maxlen=CPU_AVERAGE) + + def read(self, now: float) -> float | None: + if self.pkg is None and now >= self._retry_at: + try: + self.pkg = self._factory() + except Exception as e: # PawnIO missing, not admin, ... + log.warning("CPU temperature unavailable for fan control: %s", e) + self._retry_at = now + 60 + temp = None + if self.pkg is not None: + try: + temp = self.pkg.temperature() + except OSError as e: + log.warning("CPU temperature read failed, will retry: %s", e) + self.close() + if temp is None: + self._recent.clear() + return None + self._recent.append(temp) + return sum(self._recent) / len(self._recent) + + def close(self) -> None: + if self.pkg is not None: + self.pkg.msr.close() + self.pkg = None + + +class CaseFanControl: + def __init__(self, commander: CommanderPro, gpu_ports: tuple[int, ...], + cpu_ports: tuple[int, ...] | None = None, top: TopFanCurve | None = None, + profile: FanProfile = BALANCED, sensors=None): + """sensors: (GPU sensor factory, CPU temperature factory), for tests and --demo.""" + self.commander = commander + self.profile = profile + self._sensors = sensors or (lambda: GpuSensors(load_source="nvml"), CpuTemperature) + self.gpu = CaseFanGroup("GPU", profile.gpu_curve, commander, gpu_ports) + self.cpu = CaseFanGroup("CPU", profile.cpu_curve, commander, cpu_ports) if cpu_ports else None + if self.cpu is not None and set(self.cpu.ports) & set(self.gpu.ports): + raise ValueError("CPU-side and GPU-side ports must not overlap") + self.groups = [g for g in (self.gpu, self.cpu) if g is not None] + self.top = top + if top is not None: + top.apply_profile(profile) + + def apply_profile(self, profile: FanProfile) -> None: + """Switch curves; rises take effect on the next poll, falls follow the usual slow ramp-down.""" + self.gpu.curve = profile.gpu_curve + if self.cpu is not None: + self.cpu.curve = profile.cpu_curve + if self.top is not None: + self.top.apply_profile(profile) + self.profile = profile + log.info("Fan profile: %s", profile.name) + + def snapshot(self) -> dict: + return {"profile": self.profile.key, "groups": [g.snapshot() for g in self.groups], + "top": None if self.top is None else self.top.snapshot()} + + @property + def status(self) -> str: + return self.gpu.status + + def update(self, gpu_temp: float | None, now: float, cpu_temp: float | None = None) -> None: + self.gpu.update(gpu_temp, now) + if self.cpu is not None: + self.cpu.update(cpu_temp, now) + if self.top is not None: + temps = [gpu_temp] + ([cpu_temp] if self.cpu is not None else []) + valid = all(t is not None and math.isfinite(t) and 0 <= t <= 110 for t in temps) + self.top.update(max(g.duty for g in self.groups), max(temps) if valid else None, now) + + def failsafe(self) -> None: + for g in self.groups: + g.failsafe() + + def _error(self, text: str) -> None: + for g in self.groups: + g.set_status(text, warning=True) + + def run(self, stop: threading.Event) -> None: + gpu_factory, cpu_factory = self._sensors + cpu_temp = cpu_factory() if self.cpu is not None else None + try: + gpu = gpu_factory() + while not stop.is_set(): + now = time.monotonic() + try: + self.update(gpu.read().temp, now, cpu_temp.read(now) if cpu_temp else None) + except (OSError, HidError) as e: + self._error(f"CONTROL ERROR: {e}") + self.failsafe() + self.commander.close() + if self.top is not None: + self.top.update(100, None, time.monotonic()) + stop.wait(1) + except Exception: + log.exception("Case fan worker failed") + self._error("CONTROL ERROR: fan worker stopped; check dashboard.log") + finally: + self.failsafe() + self.commander.close() + if self.top is not None: + self.top.release() + if cpu_temp is not None: + cpu_temp.close() + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + action = ap.add_mutually_exclusive_group(required=True) + action.add_argument("--identify", type=parse_ports, metavar="1,2,3", + help="raise these three ports to 100%% to identify their physical side") + action.add_argument("--save-ports", type=parse_ports, metavar="4,5,6", + help="save identified GPU-side ports for dashboard startup") + action.add_argument("--save-cpu-ports", type=parse_ports, metavar="1,2,3", + help="save identified CPU-side ports (follow CPU temperature)") + action.add_argument("--save-top-channels", type=parse_channels, metavar="2,5", + help="save motherboard PWM channels (see board_fans.py) for the top-fan curve") + args = ap.parse_args() + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") + if args.save_ports or args.save_cpu_ports or args.save_top_channels: + from kurgan.settings import Settings, SettingsError + + try: + settings = Settings() + if args.save_ports: + settings.update("cooling", gpu_ports=list(args.save_ports)) + elif args.save_cpu_ports: + settings.update("cooling", cpu_ports=list(args.save_cpu_ports)) + else: + settings.update("cooling", top_channels=list(args.save_top_channels)) + except (OSError, SettingsError): + log.exception("Cannot save fan configuration") + return 1 + print(f"Saved {settings.section('cooling')} to {settings.path}. Restart The Kurgan to apply it.") + return 0 + commander = CommanderPro() + try: + rpms = commander.set_duty(args.identify, 100) + print(f"Ports {args.identify} set to 100%. They will stay at 100% after this test.") + time.sleep(5) + rpms = commander.set_duty(args.identify, 100) + print("RPMs: " + ", ".join(f"{p}: {rpm}" for p, rpm in rpms.items())) + return 0 + except (OSError, HidError) as e: + log.error("Identification failed: %s", e) + return 1 + finally: + commander.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/kurgan/cooling/profiles.py b/kurgan/cooling/profiles.py new file mode 100644 index 0000000..6fcf48a --- /dev/null +++ b/kurgan/cooling/profiles.py @@ -0,0 +1,90 @@ +"""Selectable fan profiles: one set of temperature -> PWM duty curves for each fan group. + +Every profile keeps the fail-safes in control.py (100% when a temperature is missing, a fan +stalls or the controller fails), the slow ramp-down, and the top-fan boost while either +case-fan group runs at 85% or more. Only the curves and the top fans' start/stop +temperatures differ. + +Curves are (temperature C, duty %) points: below the first point the duty is the first +point's, between points it is interpolated, and at or above the last point it is 100%. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +Curve = tuple[tuple[int, int], ...] + + +@dataclass(frozen=True) +class FanProfile: + key: str + name: str + description: str + gpu_curve: Curve # GPU-side Commander PRO fans, from GPU temperature + cpu_curve: Curve # CPU-side Commander PRO fans, from 5-second-averaged CPU package temperature + top_curve: Curve # motherboard top fans while running, from the hotter of CPU/GPU + top_start: int # top fans start at this temperature ... + top_stop: int # ... and stop after 30 s below this one + + def as_dict(self) -> dict: + return {"key": self.key, "name": self.name, "description": self.description, + "gpu_curve": self.gpu_curve, "cpu_curve": self.cpu_curve, "top_curve": self.top_curve, + "top_start": self.top_start, "top_stop": self.top_stop} + + +def validate_curve(curve: Curve) -> None: + if len(curve) < 2: + raise ValueError("a curve needs at least two points") + temps = [t for t, _ in curve] + duties = [d for _, d in curve] + if any(b <= a for a, b in zip(temps, temps[1:])): + raise ValueError("curve temperatures must rise") + if any(b < a for a, b in zip(duties, duties[1:])): + raise ValueError("curve duties must not fall as temperature rises") + if not all(0 <= t <= 110 for t in temps) or not all(0 <= d <= 100 for d in duties): + raise ValueError("curve points must be 0-110 C and 0-100%") + if duties[-1] != 100: + raise ValueError("every curve must reach 100%") + + +QUIET = FanProfile( + "quiet", "Quiet", + "Lower fan speeds; each group reaches 100% about 5 C later than Balanced.", + gpu_curve=((45, 35), (55, 45), (65, 65), (75, 100)), + cpu_curve=((55, 35), (65, 45), (75, 65), (85, 100)), + top_curve=((55, 30), (65, 60), (75, 100)), + top_start=55, top_stop=50, +) +BALANCED = FanProfile( + "balanced", "Balanced", + "The original curves: GPU-side fans reach 100% at 70 C, CPU-side fans at 80 C.", + gpu_curve=((40, 40), (50, 50), (60, 65), (70, 100)), + cpu_curve=((50, 40), (60, 50), (70, 65), (80, 100)), + top_curve=((50, 30), (60, 60), (70, 100)), + top_start=50, top_stop=45, +) +PERFORMANCE = FanProfile( + "performance", "Performance", + "Higher speeds for long AI or gaming loads; each group reaches 100% 5 C earlier than Balanced.", + gpu_curve=((35, 50), (45, 60), (55, 80), (65, 100)), + cpu_curve=((45, 50), (55, 60), (65, 80), (75, 100)), + top_curve=((45, 40), (55, 70), (65, 100)), + top_start=45, top_stop=40, +) +FULL = FanProfile( + "full", "Full speed", + "Every controlled fan at 100%, including the top fans.", + gpu_curve=((0, 100), (110, 100)), + cpu_curve=((0, 100), (110, 100)), + top_curve=((0, 100), (110, 100)), + top_start=0, top_stop=0, +) + +PROFILES: dict[str, FanProfile] = {p.key: p for p in (QUIET, BALANCED, PERFORMANCE, FULL)} +DEFAULT_PROFILE = BALANCED.key + +for _profile in PROFILES.values(): + for _curve in (_profile.gpu_curve, _profile.cpu_curve, _profile.top_curve): + validate_curve(_curve) + assert _profile.top_stop <= _profile.top_start diff --git a/kurgan/demo.py b/kurgan/demo.py new file mode 100644 index 0000000..df3fab1 --- /dev/null +++ b/kurgan/demo.py @@ -0,0 +1,126 @@ +"""Simulated sensors and devices for `python -m kurgan --demo`. + +Lets the web UI and the AI swapping be worked on while the real Kurgan owns the hardware: +nothing here touches USB, PawnIO, the SMBus or NVAPI. Run it with its own data folder and +web port, e.g. + + $env:KURGAN_DATA_DIR = "$env:TEMP\\kurgan-demo"; python -m kurgan --demo --port 18080 --no-tray +""" + +from __future__ import annotations + +import math +import threading +import time + +from kurgan.telemetry.readings import PowerReadings, Readings + +_T0 = time.monotonic() + + +def _wave(period: float, phase: float = 0.0) -> float: + """0..1, slowly rising and falling.""" + return 0.5 + 0.5 * math.sin((time.monotonic() - _T0) * 2 * math.pi / period + phase) + + +class FakeCpu: + status = "simulated" + + def read(self) -> Readings: + load = 5 + 70 * _wave(150) ** 3 + return Readings(temp=38 + 0.5 * load, load=load, clock=1200 + 40 * load, power=15 + 1.6 * load) + + +class FakeGpu: + def read(self) -> Readings: + load = 2 + 95 * _wave(90, 1.0) ** 4 + return Readings(temp=34 + 0.42 * load, load=load, clock=210 + 26 * load, power=18 + 4.2 * load) + + def memory(self) -> tuple[int, int]: + return int((1.4 + 18 * _wave(300, 2.0)) * 2**30), 24 * 2**30 + + +class FakeCommander: + controlled = False + + def __init__(self): + self.duty = {p: 100 for p in range(1, 7)} + + def _rpm(self, port: int) -> int: + return int(525 + 9.75 * self.duty[port]) + + def read(self) -> list[int]: + return [self._rpm(p) for p in range(1, 7)] + + def set_duty(self, ports, duty: int) -> dict[int, int]: + for p in ports: + self.duty[p] = duty + return {p: self._rpm(p) for p in ports} + + def close(self) -> None: + pass + + +class FakeSystem: + def __init__(self): + self.fans = FakeCommander() + + def read(self, cpu: Readings, gpu: Readings) -> PowerReadings: + parts = {"Motherboard & chipset": 15.0, "Memory (4 modules)": 10 + 0.1 * (cpu.load or 0), + "Case fans (6, Commander PRO)": sum(2 * (r / 1500) ** 2.5 for r in self.fans.read()), + "USB devices & RGB lighting (fixed)": 12.0} + return PowerReadings(cpu=cpu.power, gpu=gpu.power, other=sum(parts.values()), parts=parts) + + +class FakeBoard: + def __init__(self): + self.mask = 0 + + def manual_mask(self) -> int: + return self.mask + + def set_manual(self, channels, duty: int) -> None: + self.mask |= sum(1 << c for c in channels) + + def set_auto(self, channels) -> None: + self.mask &= ~sum(1 << c for c in channels) + + def close(self) -> None: + pass + + +class FakeCpuTemperature: + def read(self, now: float) -> float: + return FakeCpu().read().temp + + def close(self) -> None: + pass + + +class FakeLights: + """Stands in for a lighting worker: reports which pattern it would be running.""" + + def __init__(self, device: str): + self.device = device + self.status = "off" + + def set_temperature(self, cpu_temp, gpu_temp=None) -> None: + pass + + def set_power(self, total_watts) -> None: + pass + + def run(self, stop: threading.Event, *events: threading.Event) -> None: + names = ("temperature", "chase") if len(events) == 2 else ("chase",) + while not stop.is_set(): + active = [n for n, e in zip(names, events) if e.is_set()] + self.status = f"{active[0].capitalize()} on the {self.device} (simulated)" if active else "off" + stop.wait(0.2) + + +def hardware() -> dict: + return { + "cpu": FakeCpu(), "gpu": FakeGpu(), "system": FakeSystem(), "board": FakeBoard, + "fan_sensors": (FakeGpu, FakeCpuTemperature), + "lighting": {"rgb": FakeLights("case fans"), "memory": FakeLights("RAM"), "gpu": FakeLights("GPU")}, + } diff --git a/kurgan/display/__init__.py b/kurgan/display/__init__.py new file mode 100644 index 0000000..b3b69a4 --- /dev/null +++ b/kurgan/display/__init__.py @@ -0,0 +1 @@ +"""Display: the GPU | CPU dashboard on the Thermaltake 3.9\" bar LCD.""" diff --git a/kurgan/display/background.png b/kurgan/display/background.png new file mode 100644 index 0000000..b4d7406 Binary files /dev/null and b/kurgan/display/background.png differ diff --git a/kurgan/display/renderer.py b/kurgan/display/renderer.py new file mode 100644 index 0000000..b92d44b --- /dev/null +++ b/kurgan/display/renderer.py @@ -0,0 +1,614 @@ +"""Renders the GPU | CPU dashboard for the Thermaltake 3.9" bar LCD (480x128). + +Left half is the GPU; the right half is the same layout mirrored horizontally +for the CPU, with all gauges filling clockwise. The centre column shows the whole PC's power draw +against the power supply's rating, stacked as other (bottom), CPU, GPU (top). +The supplied red-panel background sits behind the procedural instruments. +Everything is rendered at SS x resolution and then downsampled, +which gives clean anti-aliasing on the small panel. + + [GPU]---------------------[ TOTAL W ]---------------------[CPU] + temp gauge load gauge | tank | load gauge temp gauge + [ MHz ]-------[# GPU W] [# other W] [# CPU W]-------[ MHz ] +""" + +from __future__ import annotations + +import math +import os +import numpy as np +from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont + +from kurgan.telemetry.readings import PowerReadings, Readings +from kurgan.theme import Theme + +W, H = 480, 128 +SS = 4 # supersampling factor + +FONT_FILE = os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts", "bahnschrift.ttf") +FALLBACK_FONT = os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts", "segoeuib.ttf") + + +# ----------------------------------------------------------------------------- layout +# All coordinates are in panel pixels for the GPU (left) half. The CPU half is +# produced by mirroring x around the centre line. + +R_GAUGE = 48.0 +R_FACE = 41.0 +ARC_R_OUT = 38.5 +ARC_W = 6.0 +ARC_START = 150.0 # degrees, 0 = 3 o'clock, clockwise +ARC_SWEEP = 240.0 +G_TEMP = (52.0, 66.0) +G_LOAD = (152.0, 66.0) +DIGIT_CY = 62.0 +UNIT_CY = 88.0 + +TITLE_BOX = (80.0, 2.0, 124.0, 16.0) +MHZ_BOX = (74.0, 112.0, 130.0, 126.0) +PART_BOX = (170.0, 112.0, 212.0, 126.0) # this half's watts (CPU or GPU) + +# Centre column (drawn once, not mirrored) +TOTAL_BOX = (206.0, 2.0, 274.0, 16.0) +OTHER_BOX = (218.0, 112.0, 262.0, 126.0) +TANK_X0, TANK_X1 = 222.0, 258.0 +CAP_TOP = (17.0, 24.0) +CAP_BOT = (97.0, 108.0) +GLASS_X0, GLASS_X1 = TANK_X0 + 3.0, TANK_X1 - 3.0 +GLASS_Y0, GLASS_Y1 = CAP_TOP[1], CAP_BOT[0] + +PIPE_T = 6.0 +_GY = math.sqrt(R_GAUGE ** 2 - 24.0 ** 2) # where x = cx - 24 meets the bezel +PIPES = [ + [(28.0, G_TEMP[1] + _GY), (28.0, 119.0), (MHZ_BOX[0], 119.0)], # temp gauge -> MHz box + [(MHZ_BOX[2], 119.0), (PART_BOX[0], 119.0)], # MHz box -> watt box + [(28.0, G_TEMP[1] - _GY), (28.0, 9.0), (TITLE_BOX[0], 9.0)], # temp gauge -> title + [(TITLE_BOX[2], 9.0), (TOTAL_BOX[0], 9.0)], # title -> total box +] +TANK_PIPE = [(W / 2, CAP_BOT[1]), (W / 2, OTHER_BOX[1])] # tank -> other box +JUNCTION_PIPE = [(G_TEMP[0] + R_GAUGE - 4, 66.0), (G_LOAD[0] - R_GAUGE + 4, 66.0)] +RIVETS = [(6.0, 6.0), (6.0, 122.0)] + +COPPER = [ + (1.00, (64, 30, 16)), + (0.84, (112, 56, 30)), + (0.66, (156, 82, 48)), + (0.46, (196, 116, 72)), + (0.26, (228, 156, 110)), + (0.09, (252, 212, 178)), +] + +# 5x7 dot-matrix glyphs +GLYPHS = { + "0": [".###.", "#...#", "#...#", "#...#", "#...#", "#...#", ".###."], + "1": ["..#..", ".##..", "..#..", "..#..", "..#..", "..#..", ".###."], + "2": [".###.", "#...#", "....#", "...#.", "..#..", ".#...", "#####"], + "3": ["#####", "...#.", "..#..", "...#.", "....#", "#...#", ".###."], + "4": ["...#.", "..##.", ".#.#.", "#..#.", "#####", "...#.", "...#."], + "5": ["#####", "#....", "####.", "....#", "....#", "#...#", ".###."], + "6": ["..##.", ".#...", "#....", "####.", "#...#", "#...#", ".###."], + "7": ["#####", "....#", "...#.", "..#..", ".#...", ".#...", ".#..."], + "8": [".###.", "#...#", "#...#", ".###.", "#...#", "#...#", ".###."], + "9": [".###.", "#...#", "#...#", ".####", "....#", "...#.", ".##.."], + "-": [".....", ".....", ".....", ".###.", ".....", ".....", "....."], +} + + +# ----------------------------------------------------------------------------- helpers + +def _s(v: float) -> float: + return v * SS + + +def _font(size_px: float, style: str = "Bold") -> ImageFont.FreeTypeFont: + try: + f = ImageFont.truetype(FONT_FILE, round(size_px * SS)) + f.set_variation_by_name(style) + return f + except Exception: + return ImageFont.truetype(FALLBACK_FONT, round(size_px * SS)) + + +def _grid(x0: float, y0: float, x1: float, y1: float): + ix0 = max(0, int(math.floor(x0 * SS))) + iy0 = max(0, int(math.floor(y0 * SS))) + ix1 = min(W * SS, int(math.ceil(x1 * SS))) + iy1 = min(H * SS, int(math.ceil(y1 * SS))) + xs = (np.arange(ix0, ix1) + 0.5) / SS + ys = (np.arange(iy0, iy1) + 0.5) / SS + X, Y = np.meshgrid(xs, ys) + return ix0, iy0, X, Y + + +def _paste(canvas: Image.Image, ix0: int, iy0: int, rgb: np.ndarray, alpha: np.ndarray) -> None: + arr = np.dstack([np.clip(rgb, 0, 255), np.clip(alpha, 0, 1) * 255]).astype(np.uint8) + canvas.alpha_composite(Image.fromarray(arr, "RGBA"), (ix0, iy0)) + + +def _rrect_mask(X, Y, x0, y0, x1, y1, r): + cx = np.clip(X, x0 + r, x1 - r) + cy = np.clip(Y, y0 + r, y1 - r) + return ((X - cx) ** 2 + (Y - cy) ** 2 <= r * r) & (X >= x0) & (X <= x1) & (Y >= y0) & (Y <= y1) + + +def _mix(lo, hi, t): + lo = np.asarray(lo, dtype=float) + hi = np.asarray(hi, dtype=float) + return lo + (hi - lo) * np.asarray(t)[..., None] + + +def _cyl_shade(u, hl=0.33, width=0.2, ambient=0.18): + """Cylinder lighting profile across a tube, u in 0..1.""" + u = np.clip(u, 0, 1) + body = np.sin(np.pi * u) ** 0.6 + spec = np.exp(-((u - hl) / width) ** 2) + return np.clip(ambient + 0.55 * body + 0.45 * spec, 0, 1) + + +def cyl_rect(canvas, x0, y0, x1, y1, across, lo, hi, radius=0.0, hl=0.33, width=0.2, ambient=0.18): + ix0, iy0, X, Y = _grid(x0, y0, x1, y1) + u = (X - x0) / (x1 - x0) if across == "x" else (Y - y0) / (y1 - y0) + rgb = _mix(lo, hi, _cyl_shade(u, hl, width, ambient)) + mask = _rrect_mask(X, Y, x0, y0, x1, y1, radius) if radius else (X >= x0) & (X <= x1) & (Y >= y0) & (Y <= y1) + _paste(canvas, ix0, iy0, rgb, mask.astype(float)) + + +def dome(canvas, cx, cy, rad, tint=(205, 205, 212)): + ix0, iy0, X, Y = _grid(cx - rad - 1, cy - rad - 1, cx + rad + 1, cy + rad + 1) + d = np.hypot(X - cx, Y - cy) / rad + hl = np.exp(-(((X - cx + rad * 0.35) ** 2 + (Y - cy + rad * 0.35) ** 2) / (rad * 0.45) ** 2)) + v = 0.18 + 0.30 * np.sqrt(np.clip(1 - d ** 2, 0, 1)) + 0.65 * hl + rgb = _mix((0, 0, 0), tint, np.clip(v, 0, 1.2)) + ring = np.clip((d - 0.82) / 0.18, 0, 1) + rgb = rgb * (1 - 0.55 * ring[..., None]) + _paste(canvas, ix0, iy0, rgb, (d <= 1).astype(float)) + + +def _fillet(points, radius=5.0, steps=10): + """Round the corners of a polyline with quadratic Bezier curves.""" + pts = [np.array(p, dtype=float) for p in points] + if len(pts) < 3: + return [tuple(p) for p in pts] + out = [tuple(pts[0])] + for i in range(1, len(pts) - 1): + p0, p1, p2 = pts[i - 1], pts[i], pts[i + 1] + d1, d2 = np.linalg.norm(p0 - p1), np.linalg.norm(p2 - p1) + r = min(radius, d1 / 2, d2 / 2) + a = p1 + (p0 - p1) / d1 * r + b = p1 + (p2 - p1) / d2 * r + for t in np.linspace(0, 1, steps): + q = (1 - t) ** 2 * a + 2 * (1 - t) * t * p1 + t ** 2 * b + out.append(tuple(q)) + out.append(tuple(pts[-1])) + return out + + +def _extend(points, amount=2.0): + """Push both ends of a polyline outward so pipes tuck under their fittings.""" + pts = [np.array(p, dtype=float) for p in points] + for end, nxt in ((0, 1), (-1, -2)): + v = pts[end] - pts[nxt] + n = np.linalg.norm(v) + if n: + pts[end] = pts[end] + v / n * amount + return [tuple(p) for p in pts] + + +class _Half: + """Coordinate mapping for one half; mirror=True maps the layout onto the right.""" + + def __init__(self, mirror: bool): + self.mirror = mirror + + def x(self, x: float) -> float: + return W - x if self.mirror else x + + def pt(self, p): + return (self.x(p[0]), p[1]) + + def box(self, b): + xa, xb = sorted((self.x(b[0]), self.x(b[2]))) + return (xa, b[1], xb, b[3]) + + +# ----------------------------------------------------------------------------- renderer + +class DashboardRenderer: + def __init__(self, theme: Theme | None = None, rotate180: bool = False): + self.theme = theme or Theme() + self.rotate180 = rotate180 + self.halves = (_Half(False), _Half(True)) + self.f_title = _font(11, "Bold") + self.f_unit = _font(9, "SemiBold") + self.f_value = _font(10.5, "Bold SemiCondensed") + self.f_small = _font(7, "SemiBold SemiCondensed") + self._static = self._build_static() + self._glass = self._build_glass_overlay() + self._dome_light, self._dome_shade = self._build_dome_overlay() + + # ------------------------------------------------------------------ static art + + def _build_static(self) -> Image.Image: + canvas = self._plate() + self._shadows(canvas) + for half in self.halves: + for pipe in PIPES: + self._pipe(canvas, [half.pt(p) for p in pipe]) + self._pipe(canvas, [half.pt(p) for p in JUNCTION_PIPE]) + self._pipe(canvas, TANK_PIPE) + + for half in self.halves: + for g in (G_TEMP, G_LOAD): + self._gauge(canvas, half.x(g[0]), g[1]) + for b in (MHZ_BOX, PART_BOX, TITLE_BOX): + self._box(canvas, half.box(b)) + self._tank(canvas) + self._box(canvas, TOTAL_BOX) + self._box(canvas, OTHER_BOX) + + for half in self.halves: + for pipe in PIPES: + pts = [half.pt(p) for p in pipe] + self._coupler(canvas, pts[0], pts[1]) + self._coupler(canvas, pts[-1], pts[-2]) + self._nut(canvas, half.x((JUNCTION_PIPE[0][0] + JUNCTION_PIPE[1][0]) / 2), 66.0) + self._coupler(canvas, TANK_PIPE[0], TANK_PIPE[1]) + self._coupler(canvas, TANK_PIPE[1], TANK_PIPE[0]) + for x, y in RIVETS: + for half in self.halves: + dome(canvas, half.x(x), y, 2.3) + + draw = ImageDraw.Draw(canvas) + glow = Image.new("RGB", canvas.size, (0, 0, 0)) + gdraw = ImageDraw.Draw(glow) + for i, half in enumerate(self.halves): + b = half.box(TITLE_BOX) + c = (_s((b[0] + b[2]) / 2), _s((b[1] + b[3]) / 2 + 0.4)) + gdraw.text(c, self.theme.titles[i], font=self.f_title, fill=self.theme.accent, anchor="mm") + for g, unit in ((G_TEMP, "\u00b0C"), (G_LOAD, "%")): + draw.text((_s(half.x(g[0])), _s(UNIT_CY)), unit, font=self.f_unit, + fill=(196, 196, 200), anchor="mm") + glow = glow.filter(ImageFilter.GaussianBlur(_s(2.2))) + rgb = ImageChops.screen(canvas.convert("RGB"), glow) + canvas = rgb.convert("RGBA") + draw = ImageDraw.Draw(canvas) + for i, half in enumerate(self.halves): + b = half.box(TITLE_BOX) + c = (_s((b[0] + b[2]) / 2), _s((b[1] + b[3]) / 2 + 0.4)) + draw.text(c, self.theme.titles[i], font=self.f_title, fill=self.theme.accent, anchor="mm") + return canvas + + def _plate(self) -> Image.Image: + path = os.path.join(os.path.dirname(__file__), "background.png") + with Image.open(path) as background: + return background.convert("RGBA").resize((W * SS, H * SS), Image.Resampling.LANCZOS) + + def _shadows(self, canvas: Image.Image) -> None: + mask = Image.new("L", canvas.size, 0) + d = ImageDraw.Draw(mask) + for half in self.halves: + for g in (G_TEMP, G_LOAD): + cx, cy = half.x(g[0]), g[1] + d.ellipse([_s(cx - R_GAUGE), _s(cy - R_GAUGE), _s(cx + R_GAUGE), _s(cy + R_GAUGE)], fill=255) + for b in (MHZ_BOX, PART_BOX, TITLE_BOX): + d.rectangle([_s(v) for v in half.box(b)], fill=255) + for pipe in PIPES: + d.line([(_s(x), _s(y)) for x, y in _fillet([half.pt(p) for p in pipe])], + fill=255, width=round(_s(PIPE_T)), joint="curve") + for b in (TOTAL_BOX, OTHER_BOX, (TANK_X0, CAP_TOP[0], TANK_X1, CAP_BOT[1])): + d.rectangle([_s(v) for v in b], fill=255) + d.line([(_s(x), _s(y)) for x, y in TANK_PIPE], fill=255, width=round(_s(PIPE_T))) + mask = mask.filter(ImageFilter.GaussianBlur(_s(2.4))) + shifted = Image.new("L", canvas.size, 0) + shifted.paste(mask, (round(_s(1.4)), round(_s(2.0)))) + shade = np.asarray(shifted, dtype=float)[..., None] / 255 + arr = np.asarray(canvas, dtype=float).copy() + arr[..., :3] *= 1 - 0.75 * shade + canvas.paste(Image.fromarray(arr.astype(np.uint8), "RGBA")) + + def _pipe(self, canvas, points) -> None: + pts = _fillet(_extend(points, 2.5)) + d = ImageDraw.Draw(canvas) + for frac, col in COPPER: + off = -0.13 * PIPE_T * (1 - frac) if frac < 0.9 else 0.0 + d.line([(_s(x + off), _s(y + off)) for x, y in pts], fill=col, + width=max(1, round(_s(PIPE_T * frac))), joint="curve") + + def _coupler(self, canvas, end, toward) -> None: + horizontal = abs(end[0] - toward[0]) > abs(end[1] - toward[1]) + x, y = end + half_len, half_w = 1.7, PIPE_T / 2 + 1.0 + if horizontal: + cyl_rect(canvas, x - half_len, y - half_w, x + half_len, y + half_w, "y", + (10, 10, 12), (170, 170, 176), radius=0.6) + else: + cyl_rect(canvas, x - half_w, y - half_len, x + half_w, y + half_len, "x", + (10, 10, 12), (170, 170, 176), radius=0.6) + + def _nut(self, canvas, x, y) -> None: + hw, hh = 3.4, PIPE_T / 2 + 2.2 + cyl_rect(canvas, x - hw, y - hh, x + hw, y + hh, "y", (12, 12, 14), (190, 190, 196), radius=0.8) + d = ImageDraw.Draw(canvas) + for fx in (-1.15, 1.15): + d.line([(_s(x + fx), _s(y - hh + 0.4)), (_s(x + fx), _s(y + hh - 0.4))], + fill=(20, 20, 22), width=round(_s(0.45))) + + def _gauge(self, canvas, cx, cy) -> None: + ix0, iy0, X, Y = _grid(cx - R_GAUGE - 1, cy - R_GAUGE - 1, cx + R_GAUGE + 1, cy + R_GAUGE + 1) + dx, dy = X - cx, Y - cy + r = np.hypot(dx, dy) + phi = np.arctan2(dy, dx) + light = np.cos(phi - math.radians(225)) + t = np.clip((r - R_FACE) / (R_GAUGE - R_FACE), 0, 1) + prof = np.sin(t * np.pi) + v = 0.17 + 0.16 * prof + 0.20 * light * (0.35 + 0.65 * prof) + v += 0.30 * np.exp(-((R_GAUGE - 0.7 - r) / 0.45) ** 2) * (0.45 + 0.55 * light) + v -= 0.12 * np.exp(-((r - R_FACE - 0.5) / 0.6) ** 2) + v += 0.018 * np.sin(r * SS * 2.2) + face = 0.03 + 0.05 * (1 - r / R_FACE) ** 2 + face = face * (0.45 + 0.55 * np.clip((R_FACE - r) / 3.5, 0, 1)) + val = np.where(r < R_FACE, face, v) + rgb = _mix((0, 0, 0), (238, 240, 246), np.clip(val, 0, 1)) + _paste(canvas, ix0, iy0, rgb, (r <= R_GAUGE).astype(float)) + + d = ImageDraw.Draw(canvas) + # arc groove + for rad, width, col in ((ARC_R_OUT + 0.8, ARC_W + 1.6, (54, 54, 58)), (ARC_R_OUT, ARC_W, (20, 20, 22))): + bb = [_s(cx - rad), _s(cy - rad), _s(cx + rad), _s(cy + rad)] + d.arc(bb, ARC_START, ARC_START + ARC_SWEEP, fill=col, width=round(_s(width))) + # bolts on the bezel + for a in (45, 135, 225, 315): + ar = math.radians(a) + dome(canvas, cx + 44.5 * math.cos(ar), cy + 44.5 * math.sin(ar), 1.7, tint=(170, 170, 178)) + + def _tank(self, canvas) -> None: + x0, x1 = TANK_X0, TANK_X1 + chrome = ((22, 22, 25), (236, 236, 242)) + # glass background + cyl_rect(canvas, GLASS_X0, GLASS_Y0 - 1, GLASS_X1, GLASS_Y1 + 1, "x", (6, 6, 8), (40, 40, 46), + hl=0.3, width=0.25) + # end caps with grooves + for y0, y1 in (CAP_TOP, CAP_BOT): + cyl_rect(canvas, x0, y0, x1, y1, "x", *chrome, radius=1.4) + d = ImageDraw.Draw(canvas) + for gy in (CAP_TOP[0] + 2.4, 100.5, 105.0): + d.line([(_s(x0 + 0.6), _s(gy)), (_s(x1 - 0.6), _s(gy))], fill=(30, 30, 34, 200), width=round(_s(0.6))) + for y0, y1 in ((CAP_TOP[1] - 2.2, CAP_TOP[1]), (CAP_BOT[0], CAP_BOT[0] + 2.2)): + cyl_rect(canvas, x0 + 1, y0, x1 - 1, y1, "x", (10, 10, 12), (110, 110, 116)) + + def _build_glass_overlay(self) -> Image.Image: + layer = Image.new("RGBA", (W * SS, H * SS), (0, 0, 0, 0)) + gx0, gx1 = GLASS_X0, GLASS_X1 + ix0, iy0, X, Y = _grid(gx0, GLASS_Y0, gx1, GLASS_Y1) + u = (X - gx0) / (gx1 - gx0) + a = 0.38 * np.exp(-((u - 0.24) / 0.04) ** 2) + 0.12 * np.exp(-((u - 0.80) / 0.04) ** 2) + edge = np.exp(-(u / 0.05) ** 2) + np.exp(-((1 - u) / 0.05) ** 2) + top_shadow = np.clip(1 - (Y - GLASS_Y0) / 3.0, 0, 1) + rgb = np.where((edge > 0.3)[..., None], 0.0, 255.0) * np.ones(3) + alpha = np.maximum(a, np.maximum(0.55 * edge, 0.65 * top_shadow)) + rgb = np.where((top_shadow * 0.65 > a)[..., None], 0.0, rgb) + _paste(layer, ix0, iy0, rgb, alpha) + # scale: a tick every 10% of the power supply's rating, a longer one at 50% + d = ImageDraw.Draw(layer) + span = GLASS_Y1 - GLASS_Y0 + for i in range(1, 10): + y = GLASS_Y1 - span * i / 10 + length = 3.5 if i == 5 else 2.0 + for xa, xb in ((gx0 + 1.5, gx0 + 1.5 + length), (gx1 - 1.5 - length, gx1 - 1.5)): + d.line([(_s(xa), _s(y)), (_s(xb), _s(y))], fill=(230, 230, 235, 130), width=round(_s(0.5))) + return layer + + def _build_dome_overlay(self) -> tuple[np.ndarray, np.ndarray]: + """Reflections of a glass dome over each gauge face, lit from the top left. + + Returns panel-sized (H, W, 1) maps: `light` is screened over the finished + frame (so it also sits over the glowing arcs and digits) and `shade` multiplies it. + """ + light = np.zeros((H * SS, W * SS)) + shade = np.ones((H * SS, W * SS)) + rad = R_FACE - 0.2 + for half in self.halves: + for g in (G_TEMP, G_LOAD): + cx, cy = half.x(g[0]), g[1] + ix0, iy0, X, Y = _grid(cx - rad - 1, cy - rad - 1, cx + rad + 1, cy + rad + 1) + u, v = (X - cx) / rad, (Y - cy) / rad + r = np.hypot(u, v) + inside = np.clip((1 - r) * rad * 1.5, 0, 1) + # broad crescent sheen: inside the dome but outside a circle offset to the lower right + inner = np.hypot(u - 0.10, v - 0.20) / 0.93 + crescent = np.clip((inner - 1) * 9, 0, 1) * np.clip((0.98 - r) * 25, 0, 1) + towards = np.clip(0.55 - 0.75 * (u * 0.55 + v * 0.83), 0, 1) + sheen = 0.42 * crescent * towards + # window highlight up and to the left + a, b = (u + v + 0.95) / 1.414, (v - u + 0.18) / 1.414 + spot = 0.75 * np.exp(-(a / 0.07) ** 2 - (b / 0.30) ** 2) + 0.12 * np.exp(-(a / 0.22) ** 2 - (b / 0.45) ** 2) + # faint bounce along the lower-right rim + ang = np.arctan2(v, u) + bounce = 0.13 * np.exp(-((r - 0.93) / 0.035) ** 2) * np.clip(np.cos(ang - math.radians(60)), 0, 1) ** 2 + haze = 0.04 * (1 - r ** 2).clip(0, 1) + hi = (np.maximum(sheen, spot) + bounce + haze) * inside + dark = 1 - 0.30 * np.clip((r - 0.80) / 0.20, 0, 1) ** 2 * inside + sl = (slice(iy0, iy0 + hi.shape[0]), slice(ix0, ix0 + hi.shape[1])) + light[sl] = np.maximum(light[sl], hi) + shade[sl] = np.minimum(shade[sl], dark) + + def small(m: np.ndarray) -> np.ndarray: + img = Image.fromarray(np.clip(m * 255, 0, 255).astype(np.uint8), "L") + return np.asarray(img.resize((W, H), Image.Resampling.BOX), dtype=float)[..., None] / 255 + + return small(light), small(shade) + + def _box(self, canvas, b) -> None: + x0, y0, x1, y1 = b + ix0, iy0, X, Y = _grid(x0, y0, x1, y1) + t = (Y - y0) / (y1 - y0) + frame = _mix((40, 40, 44), (215, 215, 222), np.clip(1.05 - 1.1 * t, 0, 1)) + _paste(canvas, ix0, iy0, frame, _rrect_mask(X, Y, x0, y0, x1, y1, 2.2).astype(float)) + i = 1.4 + inner = _mix((4, 4, 5), (20, 20, 23), t) + inner_shadow = np.clip((Y - (y0 + i)) / 2.0, 0, 1) + inner = inner * (0.4 + 0.6 * inner_shadow)[..., None] + _paste(canvas, ix0, iy0, inner, _rrect_mask(X, Y, x0 + i, y0 + i, x1 - i, y1 - i, 1.2).astype(float)) + + # ------------------------------------------------------------------ dynamic + + def render(self, cpu: Readings, gpu: Readings, power: PowerReadings | None = None) -> Image.Image: + if power is None: + power = PowerReadings(cpu=cpu.power, gpu=gpu.power) + canvas = self._static.copy() + glow = Image.new("RGB", canvas.size, (0, 0, 0)) + draw = ImageDraw.Draw(canvas) + gdraw = ImageDraw.Draw(glow) + th = self.theme + + for half, rd, temp_range in ((self.halves[0], gpu, th.gpu_temp_range), + (self.halves[1], cpu, th.cpu_temp_range)): + reverse = half.mirror and th.mirror_gauge_direction + # gauges + gauges = ( + (G_TEMP, rd.temp, *temp_range, th.temp_warn, th.temp_hot), + (G_LOAD, rd.load, 0.0, 100.0, th.load_warn, th.load_hot), + ) + for g, value, lo, hi, warn, hot in gauges: + cx, cy = half.x(g[0]), g[1] + frac = None if value is None else min(1.0, max(0.0, (value - lo) / (hi - lo))) + if frac: + self._arc_fill(draw, gdraw, cx, cy, frac, reverse, th.level_color(value, warn, hot)) + self._digits(draw, gdraw, cx, DIGIT_CY, value) + self._readout(draw, half.box(MHZ_BOX), rd.clock, "MHz") + + # power column: stacked tank, its parts along the bottom, the sum on top + self._liquid(canvas, power) + draw = ImageDraw.Draw(canvas) + self._readout(draw, self.halves[0].box(PART_BOX), power.gpu, "W", swatch=th.gpu_color) + self._readout(draw, self.halves[1].box(PART_BOX), power.cpu, "W", swatch=th.cpu_color) + self._readout(draw, OTHER_BOX, power.other, "W", swatch=th.other_color) + self._readout(draw, TOTAL_BOX, power.total, "W", prefix="TOTAL") + + small = canvas.convert("RGB").resize((W, H), Image.LANCZOS) + g_small = glow.resize((W, H), Image.BOX).filter(ImageFilter.GaussianBlur(2.0)) + g_small = Image.eval(g_small, lambda v: min(255, int(v * 0.85))) + out = ImageChops.screen(small, g_small) + arr = np.asarray(out, dtype=float) * self._dome_shade + arr += (255 - arr) * self._dome_light + out = Image.fromarray(np.clip(arr, 0, 255).astype(np.uint8), "RGB") + if self.rotate180: + out = out.transpose(Image.ROTATE_180) + return out + + def _arc_fill(self, draw, gdraw, cx, cy, frac, reverse, acc) -> None: + sweep = ARC_SWEEP * frac + if reverse: + end = ARC_START + ARC_SWEEP + start = end - sweep + else: + start, end = ARC_START, ARC_START + sweep + dark = tuple(int(c * 0.55) for c in acc) + light = tuple(min(255, int(c + (255 - c) * 0.45)) for c in acc) + layers = ( + (ARC_R_OUT - 0.3, ARC_W - 0.6, dark), + (ARC_R_OUT - 0.9, ARC_W - 1.8, acc), + (ARC_R_OUT - 1.9, 1.1, light), + ) + for rad, width, col in layers: + bb = [_s(cx - rad), _s(cy - rad), _s(cx + rad), _s(cy + rad)] + draw.arc(bb, start, end, fill=col, width=round(_s(width))) + bb = [_s(cx - ARC_R_OUT), _s(cy - ARC_R_OUT), _s(cx + ARC_R_OUT), _s(cy + ARC_R_OUT)] + gdraw.arc(bb, start, end, fill=acc, width=round(_s(ARC_W))) + + def _digits(self, draw, gdraw, cx, cy, value) -> None: + text = "--" if value is None else str(int(round(value))) + pitch = 4.0 if len(text) <= 2 else 3.2 # 3 digits ("100") need a finer grid to fit + gap = pitch + total = len(text) * 5 * pitch + (len(text) - 1) * gap + left = cx - total / 2 + top = cy - 7 * pitch / 2 + rad = pitch * 0.40 + for i, ch in enumerate(text): + glyph = GLYPHS.get(ch, GLYPHS["-"]) + for row in range(7): + for col in range(5): + x = left + i * (5 * pitch + gap) + col * pitch + pitch / 2 + y = top + row * pitch + pitch / 2 + bb = [_s(x - rad), _s(y - rad), _s(x + rad), _s(y + rad)] + if glyph[row][col] == "#": + draw.ellipse(bb, fill=(248, 248, 250)) + gdraw.ellipse(bb, fill=(150, 150, 155)) + else: + draw.ellipse(bb, fill=(30, 30, 33)) + + def _liquid(self, canvas, power: PowerReadings) -> None: + """Stack other / CPU / GPU from the bottom of the glass, scaled to the PSU rating.""" + th = self.theme + gx0, gx1 = GLASS_X0, GLASS_X1 + span = GLASS_Y1 - GLASS_Y0 + layers = ((power.other, th.other_color), (power.cpu, th.cpu_color), (power.gpu, th.gpu_color)) + base = GLASS_Y1 + tops: list[tuple[float, tuple[int, int, int]]] = [] + for watts, acc in layers: + if not watts or watts <= 0 or base <= GLASS_Y0: + continue + top = max(GLASS_Y0, base - span * watts / th.psu_watts) + lo = tuple(int(c * 0.22) for c in acc) + hi = tuple(min(255, int(c + (255 - c) * 0.12)) for c in acc) + cyl_rect(canvas, gx0, top, gx1, base, "x", lo, hi, hl=0.32, width=0.24, ambient=0.12) + tops.append((top, acc)) + base = top + d = ImageDraw.Draw(canvas) + # a dark gap between layers, then a bright meniscus on the top one + for top, _ in tops[:-1]: + d.line([(_s(gx0), _s(top)), (_s(gx1), _s(top))], fill=(6, 6, 8), width=round(_s(0.5))) + if tops: + top, acc = tops[-1] + d.line([(_s(gx0 + 0.5), _s(top + 0.3)), (_s(gx1 - 0.5), _s(top + 0.3))], + fill=tuple(min(255, int(c + (255 - c) * 0.5)) for c in acc), width=round(_s(0.7))) + # glass reflections and scale on top of the liquid + ix0 = int(math.floor(gx0 * SS)) + iy0 = int(math.floor(GLASS_Y0 * SS)) + box = (ix0, iy0, int(math.ceil(gx1 * SS)), int(math.ceil(GLASS_Y1 * SS))) + canvas.alpha_composite(self._glass.crop(box), (ix0, iy0)) + + def _readout(self, draw, b, value, unit, swatch=None, prefix=None) -> None: + """Value + unit centred in a box, optionally led by a colour swatch or a small label.""" + x0, y0, x1, y1 = b + text = "--" if value is None else f"{value:.0f}" + gap = 1.2 + wv = self.f_value.getlength(text) / SS + wu = self.f_small.getlength(unit) / SS + lead = 0.0 + if swatch is not None: + lead = 4.0 + 2.6 + elif prefix: + lead = self.f_small.getlength(prefix) / SS + 2.6 + start = (x0 + x1) / 2 - (lead + wv + gap + wu) / 2 + cy = (y0 + y1) / 2 + 0.3 + if swatch is not None: + draw.rounded_rectangle([_s(start), _s(cy - 3.6), _s(start + 4.0), _s(cy + 3.4)], + radius=_s(1.0), fill=swatch) + elif prefix: + draw.text((_s(start), _s(cy + 1.0)), prefix, font=self.f_small, fill=(170, 170, 176), anchor="lm") + start += lead + draw.text((_s(start), _s(cy)), text, font=self.f_value, fill=(245, 245, 248), anchor="lm") + draw.text((_s(start + wv + gap), _s(cy + 1.0)), unit, font=self.f_small, fill=(170, 170, 176), anchor="lm") + + +if __name__ == "__main__": + import argparse + import time + + ap = argparse.ArgumentParser(description="Render a preview of the dashboard to PNG") + ap.add_argument("out", nargs="?", default="preview.png") + ap.add_argument("--zoom", type=int, default=3) + args = ap.parse_args() + + t0 = time.perf_counter() + r = DashboardRenderer() + t1 = time.perf_counter() + img = r.render(Readings(49, 11, 3114, 36.2), Readings(76, 88, 2700, 313), + PowerReadings(cpu=36.2, gpu=313, other=78)) + t2 = time.perf_counter() + print(f"static build {1000 * (t1 - t0):.0f} ms, frame {1000 * (t2 - t1):.0f} ms") + img.save(args.out) + if args.zoom > 1: + root, ext = os.path.splitext(args.out) + img.resize((W * args.zoom, H * args.zoom), Image.NEAREST).save(f"{root}_x{args.zoom}{ext}") diff --git a/kurgan/display/service.py b/kurgan/display/service.py new file mode 100644 index 0000000..d9d66fe --- /dev/null +++ b/kurgan/display/service.py @@ -0,0 +1,94 @@ +"""Display service: keeps the Thermaltake 3.9" LCD showing the latest telemetry. + +Reconnects after sleep, unplugging or a firmware hang. The panel falls back to its own +screen if it gets no frame for a few seconds, so a frame goes out at least every 1.5 s even +if telemetry stalls. +""" + +from __future__ import annotations + +import logging +import threading +import time + +from kurgan.display.renderer import DashboardRenderer +from kurgan.display.tt_lcd import LcdError, LcdNotFound, ThermaltakeLcd, encode_jpeg +from kurgan.telemetry.readings import PowerReadings, Readings +from kurgan.telemetry.service import Telemetry + +log = logging.getLogger(__name__) + + +class DisplayService: + def __init__(self, renderer: DashboardRenderer, telemetry: Telemetry, brightness: int = 100): + self.renderer = renderer + self.telemetry = telemetry + self.brightness = brightness + self.status = "Starting" + self.connected = False + self.frames = 0 + + def _set_status(self, text: str, connected: bool) -> None: + self.status, self.connected = text, connected + + def render(self, sample=None): + if sample is None: + return self.renderer.render(Readings(), Readings(), PowerReadings()) + return self.renderer.render(sample.cpu, sample.gpu, sample.power) + + def run(self, stop: threading.Event) -> None: + lcd: ThermaltakeLcd | None = None + last_heartbeat = 0.0 + missed_acks = 0 + waiting_logged = False + seq = 0 + while not stop.is_set(): + try: + if lcd is None: + lcd = ThermaltakeLcd(brightness=self.brightness) + lcd.open() + log.info("LCD connected") + self._set_status("LCD connected", True) + waiting_logged = False + missed_acks = 0 + sample = self.telemetry.wait_newer(seq, timeout=1.5) + if stop.is_set(): + break + seq = sample.seq if sample is not None else seq + t0 = time.monotonic() + if lcd.send_jpeg(encode_jpeg(self.render(sample))): + missed_acks = 0 + self.frames += 1 + else: + missed_acks += 1 + if missed_acks >= 5: + raise LcdError("LCD stopped acknowledging frames") + if t0 - last_heartbeat >= 2.0: + lcd.heartbeat() + last_heartbeat = t0 + except LcdNotFound: + if not waiting_logged: + log.info("Waiting for the LCD to appear...") + self._set_status("Waiting for the LCD...", False) + waiting_logged = True + lcd = None + stop.wait(3) + except (LcdError, OSError) as e: + log.warning("LCD error, reconnecting: %s", e) + self._set_status("LCD error, reconnecting...", False) + if lcd is not None: + lcd.close() + lcd = None + stop.wait(3) + except Exception: + log.exception("Unexpected LCD error; retrying") + if lcd is not None: + lcd.close() + lcd = None + stop.wait(5) + if lcd is not None: + lcd.close() + self._set_status("Stopped", False) + + def snapshot(self) -> dict: + return {"status": self.status, "connected": self.connected, "frames": self.frames} diff --git a/kurgan/display/tt_lcd.py b/kurgan/display/tt_lcd.py new file mode 100644 index 0000000..cf82724 --- /dev/null +++ b/kurgan/display/tt_lcd.py @@ -0,0 +1,179 @@ +"""Driver for the Thermaltake 3.9" bar LCD (USB 264A:233D, 480x128) on Windows. + +Talks to the panel through the stock Windows HID driver using only ctypes. + +Protocol (as documented by the ttlcd, thermaltaked and Tower-500-LCD-Controller +projects): + * Interface 0 (MI_00) is the command channel: 440-byte reports. + handshake : 85, 87, 85, 87, 84, 81 each as [op, 01, 00, 80], each acknowledged + brightness : [12, 01, 00, 80, percent] + heartbeat : [82, 01, 00, 80] (every ~2 s) + * Interface 1 (MI_01) is the frame channel: 1024-byte reports carrying a + baseline JPEG split into 1020-byte chunks. + first packet : [08, packet_count, 00, 80] + data + next packets : [08, index, 00, 00] + data + One acknowledgement arrives after the whole frame. + * No report IDs are used, so every write is prefixed with a 0x00 byte. + * If no frame arrives for a few seconds the panel goes back to its own screen. +""" + +from __future__ import annotations + +import math +import threading + +from kurgan.hardware.hid import HidChannel, HidError, hid_device_paths + +VENDOR_ID = 0x264A +PRODUCT_ID = 0x233D +WIDTH = 480 +HEIGHT = 128 + +COMMAND_SIZE = 440 +FRAME_PACKET_SIZE = 1024 +FRAME_DATA_SIZE = FRAME_PACKET_SIZE - 4 +MAX_FRAME_PACKETS = 255 + +HANDSHAKE_OPCODES = (0x85, 0x87, 0x85, 0x87, 0x84, 0x81) +OP_HEARTBEAT = 0x82 +OP_BRIGHTNESS = 0x12 +OP_FRAME = 0x08 + +REPLY_TIMEOUT_MS = 2000 + + +# The panel's own errors share the HID layer's exception, so callers catch one type. +LcdError = HidError + + +class LcdNotFound(LcdError): + pass + + +def find_interfaces() -> dict[int, str]: + """Return {interface_number: device_path} for the panel's HID interfaces.""" + found: dict[int, str] = {} + for path in hid_device_paths(VENDOR_ID, PRODUCT_ID): + low = path.lower() + if "&mi_00" in low: + found[0] = path + elif "&mi_01" in low: + found[1] = path + return found + + +def _command(*prefix: int) -> bytes: + return bytes(prefix).ljust(COMMAND_SIZE, b"\x00") + + +def frame_packets(jpeg: bytes) -> list[bytes]: + if not (jpeg[:2] == b"\xff\xd8" and jpeg[-2:] == b"\xff\xd9"): + raise LcdError("Frame is not a complete JPEG") + count = math.ceil(len(jpeg) / FRAME_DATA_SIZE) + if not 1 <= count <= MAX_FRAME_PACKETS: + raise LcdError(f"JPEG too large ({len(jpeg)} bytes)") + packets = [] + for index in range(count): + chunk = jpeg[index * FRAME_DATA_SIZE:(index + 1) * FRAME_DATA_SIZE] + header = bytes((OP_FRAME, count, 0x00, 0x80)) if index == 0 else bytes((OP_FRAME, index, 0x00, 0x00)) + packets.append((header + chunk).ljust(FRAME_PACKET_SIZE, b"\x00")) + return packets + + +class ThermaltakeLcd: + """Open with `with ThermaltakeLcd() as lcd:` then call send_jpeg() at least every 2 s.""" + + def __init__(self, brightness: int = 100): + self.brightness = max(0, min(100, int(brightness))) + self.command: HidChannel | None = None + self.frame: HidChannel | None = None + self._lock = threading.Lock() + + def open(self) -> None: + paths = find_interfaces() + if 0 not in paths or 1 not in paths: + raise LcdNotFound("Thermaltake 3.9\" LCD (264A:233D) not found") + self.command = HidChannel(paths[0], COMMAND_SIZE) + try: + self.frame = HidChannel(paths[1], FRAME_PACKET_SIZE) + self._handshake() + except Exception: + self.close() + raise + + def close(self) -> None: + for ch in (self.frame, self.command): + if ch is not None: + ch.close() + self.frame = self.command = None + + def __enter__(self) -> "ThermaltakeLcd": + self.open() + return self + + def __exit__(self, *exc) -> None: + self.close() + + def _handshake(self) -> None: + assert self.command and self.frame + self.frame.drain() + self.command.drain() + with self._lock: + for op in HANDSHAKE_OPCODES: + self.command.send(_command(op, 0x01, 0x00, 0x80)) + if self.command.read(REPLY_TIMEOUT_MS) is None: + raise LcdError(f"No reply to handshake opcode 0x{op:02X}") + self.command.send(_command(OP_BRIGHTNESS, 0x01, 0x00, 0x80, self.brightness)) + + def set_brightness(self, percent: int) -> None: + self.brightness = max(0, min(100, int(percent))) + with self._lock: + self.command.send(_command(OP_BRIGHTNESS, 0x01, 0x00, 0x80, self.brightness)) + + def heartbeat(self) -> None: + with self._lock: + self.command.drain() + self.command.send(_command(OP_HEARTBEAT, 0x01, 0x00, 0x80)) + + def send_jpeg(self, jpeg: bytes) -> bool: + """Send one JPEG frame. Returns True if the panel acknowledged it.""" + packets = frame_packets(jpeg) + self.frame.drain() + for packet in packets: + self.frame.send(packet) + return self.frame.read(REPLY_TIMEOUT_MS) is not None + + +def encode_jpeg(image, quality: int = 90) -> bytes: + """Encode a 480x128 PIL image as a baseline JPEG the panel accepts.""" + import io + + if image.size != (WIDTH, HEIGHT): + raise ValueError(f"Frame must be {WIDTH}x{HEIGHT}, got {image.size}") + out = io.BytesIO() + image.convert("RGB").save(out, format="JPEG", quality=quality, optimize=True, + progressive=False, subsampling=0) + return out.getvalue() + + +if __name__ == "__main__": + # Quick hardware test: draws a test card for a few seconds. + import time + from PIL import Image, ImageDraw + + print("Interfaces:", find_interfaces()) + with ThermaltakeLcd() as lcd: + print(f"Handshake OK. Report lengths: cmd out={lcd.command.output_len} in={lcd.command.input_len}, " + f"frame out={lcd.frame.output_len} in={lcd.frame.input_len}") + for i in range(8): + img = Image.new("RGB", (WIDTH, HEIGHT), (10, 10, 14)) + d = ImageDraw.Draw(img) + for x, col in enumerate([(220, 30, 40), (40, 200, 60), (40, 90, 230), (240, 240, 240)]): + d.rectangle([x * 120, 0, x * 120 + 119, 30], fill=col) + d.rectangle([0, 0, WIDTH - 1, HEIGHT - 1], outline=(255, 255, 0)) + d.text((10, 50), f"LEFT test frame {i + 1}/8", fill=(255, 255, 255), font_size=24) + d.text((400, 100), "RIGHT", fill=(255, 255, 255), font_size=16) + ack = lcd.send_jpeg(encode_jpeg(img)) + print(f"frame {i + 1}: ack={ack}") + lcd.heartbeat() + time.sleep(1) diff --git a/kurgan/hardware/__init__.py b/kurgan/hardware/__init__.py new file mode 100644 index 0000000..64dd2d2 --- /dev/null +++ b/kurgan/hardware/__init__.py @@ -0,0 +1,6 @@ +"""Low-level device access shared by the capabilities: Win32 HID and the PawnIO modules.""" + +import os + +# PawnIO's signed kernel modules (PawnIO.Modules 0.2.12, LGPL-2.1): Intel MSR, Super I/O, SMBus. +PAWNIO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pawnio") diff --git a/kurgan/hardware/hid.py b/kurgan/hardware/hid.py new file mode 100644 index 0000000..c7ec5b5 --- /dev/null +++ b/kurgan/hardware/hid.py @@ -0,0 +1,244 @@ +"""Overlapped Win32 HID access shared by every USB device The Kurgan drives +(the Thermaltake LCD, the Corsair Commander PRO and the Lighting Node CORE). + +Uses only ctypes and the stock Windows HID driver. +""" + +from __future__ import annotations + +import ctypes +import ctypes.wintypes as wt + + +class HidError(Exception): + """A HID device could not be opened, written or read.""" + + +# --------------------------------------------------------------------------- Win32 + +_setupapi = ctypes.WinDLL("setupapi", use_last_error=True) +_hid = ctypes.WinDLL("hid", use_last_error=True) +_k32 = ctypes.WinDLL("kernel32", use_last_error=True) + +_INVALID_HANDLE = wt.HANDLE(-1).value +_DIGCF_PRESENT = 0x02 +_DIGCF_DEVICEINTERFACE = 0x10 +_GENERIC_READ = 0x80000000 +_GENERIC_WRITE = 0x40000000 +_FILE_SHARE_READ = 0x01 +_FILE_SHARE_WRITE = 0x02 +_OPEN_EXISTING = 3 +_FILE_FLAG_OVERLAPPED = 0x40000000 +_ERROR_IO_PENDING = 997 +_ERROR_NO_MORE_ITEMS = 259 +_WAIT_OBJECT_0 = 0 +_WAIT_TIMEOUT = 0x102 + + +class _GUID(ctypes.Structure): + _fields_ = [ + ("Data1", wt.DWORD), + ("Data2", wt.WORD), + ("Data3", wt.WORD), + ("Data4", ctypes.c_ubyte * 8), + ] + + +class _SP_DEVICE_INTERFACE_DATA(ctypes.Structure): + _fields_ = [ + ("cbSize", wt.DWORD), + ("InterfaceClassGuid", _GUID), + ("Flags", wt.DWORD), + ("Reserved", ctypes.c_size_t), + ] + + +class _HIDP_CAPS(ctypes.Structure): + _fields_ = [ + ("Usage", wt.USHORT), + ("UsagePage", wt.USHORT), + ("InputReportByteLength", wt.USHORT), + ("OutputReportByteLength", wt.USHORT), + ("FeatureReportByteLength", wt.USHORT), + ("Reserved", wt.USHORT * 17), + ("Counts", wt.USHORT * 10), + ] + + +class _OVERLAPPED(ctypes.Structure): + _fields_ = [ + ("Internal", ctypes.c_size_t), + ("InternalHigh", ctypes.c_size_t), + ("Offset", wt.DWORD), + ("OffsetHigh", wt.DWORD), + ("hEvent", wt.HANDLE), + ] + + +_hid.HidD_GetHidGuid.argtypes = [ctypes.POINTER(_GUID)] +_hid.HidD_GetHidGuid.restype = None +_hid.HidD_GetPreparsedData.argtypes = [wt.HANDLE, ctypes.POINTER(ctypes.c_void_p)] +_hid.HidD_GetPreparsedData.restype = wt.BOOLEAN +_hid.HidD_FreePreparsedData.argtypes = [ctypes.c_void_p] +_hid.HidD_FreePreparsedData.restype = wt.BOOLEAN +_hid.HidP_GetCaps.argtypes = [ctypes.c_void_p, ctypes.POINTER(_HIDP_CAPS)] +_hid.HidP_GetCaps.restype = ctypes.c_long +_hid.HidD_FlushQueue.argtypes = [wt.HANDLE] +_hid.HidD_FlushQueue.restype = wt.BOOLEAN + +_setupapi.SetupDiGetClassDevsW.argtypes = [ctypes.POINTER(_GUID), wt.LPCWSTR, wt.HWND, wt.DWORD] +_setupapi.SetupDiGetClassDevsW.restype = wt.HANDLE +_setupapi.SetupDiEnumDeviceInterfaces.argtypes = [ + wt.HANDLE, ctypes.c_void_p, ctypes.POINTER(_GUID), wt.DWORD, + ctypes.POINTER(_SP_DEVICE_INTERFACE_DATA), +] +_setupapi.SetupDiEnumDeviceInterfaces.restype = wt.BOOL +_setupapi.SetupDiGetDeviceInterfaceDetailW.argtypes = [ + wt.HANDLE, ctypes.POINTER(_SP_DEVICE_INTERFACE_DATA), ctypes.c_void_p, wt.DWORD, + ctypes.POINTER(wt.DWORD), ctypes.c_void_p, +] +_setupapi.SetupDiGetDeviceInterfaceDetailW.restype = wt.BOOL +_setupapi.SetupDiDestroyDeviceInfoList.argtypes = [wt.HANDLE] +_setupapi.SetupDiDestroyDeviceInfoList.restype = wt.BOOL + +_k32.CreateFileW.argtypes = [ + wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE, +] +_k32.CreateFileW.restype = wt.HANDLE +_k32.CreateEventW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.BOOL, wt.LPCWSTR] +_k32.CreateEventW.restype = wt.HANDLE +_k32.CloseHandle.argtypes = [wt.HANDLE] +_k32.CloseHandle.restype = wt.BOOL +_k32.WriteFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.POINTER(_OVERLAPPED)] +_k32.WriteFile.restype = wt.BOOL +_k32.ReadFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.POINTER(_OVERLAPPED)] +_k32.ReadFile.restype = wt.BOOL +_k32.GetOverlappedResult.argtypes = [wt.HANDLE, ctypes.POINTER(_OVERLAPPED), ctypes.POINTER(wt.DWORD), wt.BOOL] +_k32.GetOverlappedResult.restype = wt.BOOL +_k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD] +_k32.WaitForSingleObject.restype = wt.DWORD +_k32.CancelIoEx.argtypes = [wt.HANDLE, ctypes.POINTER(_OVERLAPPED)] +_k32.CancelIoEx.restype = wt.BOOL +_k32.ResetEvent.argtypes = [wt.HANDLE] +_k32.ResetEvent.restype = wt.BOOL + + +def _winerr(what: str) -> HidError: + code = ctypes.get_last_error() + return HidError(f"{what} failed: [{code}] {ctypes.FormatError(code).strip()}") + + +def hid_device_paths(vendor_id: int, product_id: int) -> list[str]: + """Device paths of every present HID interface with this USB vendor/product ID.""" + guid = _GUID() + _hid.HidD_GetHidGuid(ctypes.byref(guid)) + hdev = _setupapi.SetupDiGetClassDevsW( + ctypes.byref(guid), None, None, _DIGCF_PRESENT | _DIGCF_DEVICEINTERFACE + ) + if hdev == _INVALID_HANDLE: + raise _winerr("SetupDiGetClassDevs") + found: list[str] = [] + needle = f"vid_{vendor_id:04x}&pid_{product_id:04x}" + try: + index = 0 + while True: + ifdata = _SP_DEVICE_INTERFACE_DATA() + ifdata.cbSize = ctypes.sizeof(ifdata) + if not _setupapi.SetupDiEnumDeviceInterfaces(hdev, None, ctypes.byref(guid), index, ctypes.byref(ifdata)): + if ctypes.get_last_error() == _ERROR_NO_MORE_ITEMS: + break + raise _winerr("SetupDiEnumDeviceInterfaces") + index += 1 + required = wt.DWORD(0) + _setupapi.SetupDiGetDeviceInterfaceDetailW(hdev, ctypes.byref(ifdata), None, 0, ctypes.byref(required), None) + buf = ctypes.create_string_buffer(required.value + 2) + # SP_DEVICE_INTERFACE_DETAIL_DATA_W.cbSize: 8 on 64-bit, 6 on 32-bit + ctypes.c_uint32.from_buffer(buf).value = 8 if ctypes.sizeof(ctypes.c_void_p) == 8 else 6 + if not _setupapi.SetupDiGetDeviceInterfaceDetailW(hdev, ctypes.byref(ifdata), buf, required, None, None): + continue + path = ctypes.wstring_at(ctypes.addressof(buf) + 4) + if needle in path.lower(): + found.append(path) + finally: + _setupapi.SetupDiDestroyDeviceInfoList(hdev) + return found + + +class HidChannel: + """One HID interface opened for overlapped I/O.""" + + def __init__(self, path: str, payload_size: int): + self.path = path + self.handle = _k32.CreateFileW( + path, _GENERIC_READ | _GENERIC_WRITE, _FILE_SHARE_READ | _FILE_SHARE_WRITE, + None, _OPEN_EXISTING, _FILE_FLAG_OVERLAPPED, None, + ) + if self.handle == _INVALID_HANDLE: + raise _winerr(f"Opening {path}") + try: + caps = _HIDP_CAPS() + pp = ctypes.c_void_p() + if not _hid.HidD_GetPreparsedData(self.handle, ctypes.byref(pp)): + raise _winerr("HidD_GetPreparsedData") + try: + _hid.HidP_GetCaps(pp, ctypes.byref(caps)) + finally: + _hid.HidD_FreePreparsedData(pp) + self.output_len = caps.OutputReportByteLength + self.input_len = caps.InputReportByteLength + if self.output_len != payload_size + 1: + raise HidError( + f"Unexpected output report length {self.output_len} on {path} " + f"(expected {payload_size + 1}); is this the right device?" + ) + self._wevent = _k32.CreateEventW(None, True, False, None) + self._revent = _k32.CreateEventW(None, True, False, None) + except Exception: + _k32.CloseHandle(self.handle) + raise + + def close(self) -> None: + for h in (getattr(self, "_wevent", None), getattr(self, "_revent", None), self.handle): + if h: + _k32.CloseHandle(h) + self.handle = None + + def send(self, payload: bytes, timeout_ms: int = 1000) -> None: + data = bytes(1) + payload + if len(data) < self.output_len: + data += bytes(self.output_len - len(data)) + buf = ctypes.create_string_buffer(data, self.output_len) + ov = _OVERLAPPED() + ov.hEvent = self._wevent + _k32.ResetEvent(self._wevent) + written = wt.DWORD(0) + if not _k32.WriteFile(self.handle, buf, self.output_len, None, ctypes.byref(ov)): + if ctypes.get_last_error() != _ERROR_IO_PENDING: + raise _winerr("WriteFile") + if _k32.WaitForSingleObject(self._wevent, timeout_ms) != _WAIT_OBJECT_0: + _k32.CancelIoEx(self.handle, ctypes.byref(ov)) + _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(written), True) + raise HidError(f"HID write timed out on {self.path}") + if not _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(written), True): + raise _winerr("WriteFile (completion)") + + def read(self, timeout_ms: int) -> bytes | None: + """Read one input report, or None on timeout.""" + buf = ctypes.create_string_buffer(self.input_len) + ov = _OVERLAPPED() + ov.hEvent = self._revent + _k32.ResetEvent(self._revent) + got = wt.DWORD(0) + if not _k32.ReadFile(self.handle, buf, self.input_len, None, ctypes.byref(ov)): + if ctypes.get_last_error() != _ERROR_IO_PENDING: + raise _winerr("ReadFile") + if _k32.WaitForSingleObject(self._revent, timeout_ms) == _WAIT_TIMEOUT: + _k32.CancelIoEx(self.handle, ctypes.byref(ov)) + ok = _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(got), True) + return buf.raw[: got.value] if ok and got.value else None + if not _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(got), True): + raise _winerr("ReadFile (completion)") + return buf.raw[: got.value] + + def drain(self) -> None: + _hid.HidD_FlushQueue(self.handle) diff --git a/kurgan/hardware/pawnio/COPYING.LGPL-2.1 b/kurgan/hardware/pawnio/COPYING.LGPL-2.1 new file mode 100644 index 0000000..4362b49 --- /dev/null +++ b/kurgan/hardware/pawnio/COPYING.LGPL-2.1 @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/kurgan/hardware/pawnio/IntelMSR.bin b/kurgan/hardware/pawnio/IntelMSR.bin new file mode 100644 index 0000000..67f18d9 Binary files /dev/null and b/kurgan/hardware/pawnio/IntelMSR.bin differ diff --git a/kurgan/hardware/pawnio/LpcIO.bin b/kurgan/hardware/pawnio/LpcIO.bin new file mode 100644 index 0000000..d80aa0b Binary files /dev/null and b/kurgan/hardware/pawnio/LpcIO.bin differ diff --git a/kurgan/hardware/pawnio/SmbusI801.bin b/kurgan/hardware/pawnio/SmbusI801.bin new file mode 100644 index 0000000..359621e Binary files /dev/null and b/kurgan/hardware/pawnio/SmbusI801.bin differ diff --git a/kurgan/hardware/pawnio/SmbusI801.p b/kurgan/hardware/pawnio/SmbusI801.p new file mode 100644 index 0000000..500ad7e --- /dev/null +++ b/kurgan/hardware/pawnio/SmbusI801.p @@ -0,0 +1,1024 @@ +// PawnIO Modules - Modules for various hardware to be used with PawnIO. +// Copyright (C) 2025 Steve-Tech +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +// +// SPDX-License-Identifier: LGPL-2.1-or-later + +#include + +#include "sleepmode.inc" + +// PawnIO i801 Driver +// Many parts of this was ported from the Linux kernel codebase. +// See https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/i2c/busses/i2c-i801.c + +#define PCI_VENDOR_ID_INTEL 0x8086 + +/* + * Data for SMBus Messages + */ +#define I2C_SMBUS_BLOCK_MAX 32 /* As specified in SMBus standard */ +#define I2C_SMBUS_ADDR_MAX 0x7F /* Addressing is 7 bit */ + +/* i2c_smbus_xfer read or write markers */ +#define I2C_SMBUS_READ 1 +#define I2C_SMBUS_WRITE 0 + +/* SMBus transaction types (size parameter in the above functions) + Note: these no longer correspond to the (arbitrary) PIIX4 internal codes! */ +#define I2C_SMBUS_QUICK 0 +#define I2C_SMBUS_BYTE 1 +#define I2C_SMBUS_BYTE_DATA 2 +#define I2C_SMBUS_WORD_DATA 3 +#define I2C_SMBUS_PROC_CALL 4 +#define I2C_SMBUS_BLOCK_DATA 5 +#define I2C_SMBUS_I2C_BLOCK_BROKEN 6 +#define I2C_SMBUS_BLOCK_PROC_CALL 7 /* SMBus 2.0 */ +#define I2C_SMBUS_I2C_BLOCK_DATA 8 + +/* I801 SMBus address offsets */ +#define SMBHSTSTS (0 + i801_smba) +#define SMBHSTCNT (2 + i801_smba) +#define SMBHSTCMD (3 + i801_smba) +#define SMBHSTADD (4 + i801_smba) +#define SMBHSTDAT0 (5 + i801_smba) +#define SMBHSTDAT1 (6 + i801_smba) +#define SMBBLKDAT (7 + i801_smba) +#define SMBPEC (8 + i801_smba) /* ICH3 and later */ +#define SMBAUXSTS (12 + i801_smba) /* ICH4 and later */ +#define SMBAUXCTL (13 + i801_smba) /* ICH4 and later */ +#define SMBSLVSTS (16 + i801_smba) /* ICH3 and later */ +#define SMBSLVCMD (17 + i801_smba) /* ICH3 and later */ +#define SMBNTFDADD (20 + i801_smba) /* ICH3 and later */ + +/* PCI Address Constants */ +#define PCICMD 0x004 +#define SMBMBAR 0x010 +#define SMB_BASE 0x020 +#define SMBHSTCFG 0x040 +#define TCOBASE 0x050 +#define TCOCTL 0x054 + +#define SMBMBAR_SIZE 0x18 + +#define PCICMD_MMBIT 0x02 + +/* Host configuration bits for SMBHSTCFG */ +#define SMBHSTCFG_HST_EN BIT(0) +#define SMBHSTCFG_SMB_SMI_EN BIT(1) +#define SMBHSTCFG_I2C_EN BIT(2) +#define SMBHSTCFG_SPD_WD BIT(4) + +/* Auxiliary status register bits, ICH4+ only */ +#define SMBAUXSTS_CRCE BIT(0) +#define SMBAUXSTS_STCO BIT(1) + +/* Auxiliary control register bits, ICH4+ only */ +#define SMBAUXCTL_CRC BIT(0) +#define SMBAUXCTL_E32B BIT(1) + +/* I801 command constants */ +#define I801_QUICK 0x00 +#define I801_BYTE 0x04 +#define I801_BYTE_DATA 0x08 +#define I801_WORD_DATA 0x0C +#define I801_PROC_CALL 0x10 +#define I801_BLOCK_DATA 0x14 +#define I801_I2C_BLOCK_DATA 0x18 /* ICH5 and later */ +#define I801_BLOCK_PROC_CALL 0x1C + +/* I801 Host Control register bits */ +#define SMBHSTCNT_INTREN BIT(0) +#define SMBHSTCNT_KILL BIT(1) +#define SMBHSTCNT_LAST_BYTE BIT(5) +#define SMBHSTCNT_START BIT(6) +#define SMBHSTCNT_PEC_EN BIT(7) /* ICH3 and later */ + +/* I801 Hosts Status register bits */ +#define SMBHSTSTS_BYTE_DONE BIT(7) +#define SMBHSTSTS_INUSE_STS BIT(6) +#define SMBHSTSTS_SMBALERT_STS BIT(5) +#define SMBHSTSTS_FAILED BIT(4) +#define SMBHSTSTS_BUS_ERR BIT(3) +#define SMBHSTSTS_DEV_ERR BIT(2) +#define SMBHSTSTS_INTR BIT(1) +#define SMBHSTSTS_HOST_BUSY BIT(0) + +#define STATUS_ERROR_FLAGS (SMBHSTSTS_FAILED | SMBHSTSTS_BUS_ERR | \ + SMBHSTSTS_DEV_ERR) + +#define STATUS_FLAGS (SMBHSTSTS_BYTE_DONE | SMBHSTSTS_INTR | \ + STATUS_ERROR_FLAGS) + +#define SMBUS_LEN_SENTINEL (I2C_SMBUS_BLOCK_MAX + 1) + +// A 32 byte block process at 10MHz is 62.3ms, 80ms should be plenty +#define MAX_TIMEOUT 80 + +// PCI slot addresses +// In order of most to least common +new pci_addresses[4][3] = [ + [0x00, 0x1f, 0x4], + [0x00, 0x1f, 0x3], + [0x00, 0x1f, 0x1], + [0x80, 0x1f, 0x4], + // These are only used by a few server boards + // which PawnIO is very unlikely to be running on + /* [0x00, 0x0f, 0x0], + // These are also secondary addresses, which aren't handled by this driver + [0x00, 0x11, 0x1], + [0x00, 0x11, 0x3], + [0x03, 0x00, 0x3], + [0x03, 0x00, 0x4], */ +]; + +new pci_addr[3]; +new VA:i801_smba; +new i801_io_smba = 0; +new write_protection_enabled; + +NTSTATUS:i801_init() +{ + new NTSTATUS:status; + new pci_config; + new bool:found = false; + + for (new i; i < sizeof pci_addresses; i++) { + // Check the vendor ID + status = pci_config_read_word(pci_addresses[i][0], pci_addresses[i][1], pci_addresses[i][2], 0x00, pci_config); + if (!NT_SUCCESS(status) || pci_config != PCI_VENDOR_ID_INTEL) + continue; + // Check the device class is SMBUS (Base 0Ch, Sub 05h) + status = pci_config_read_word(pci_addresses[i][0], pci_addresses[i][1], pci_addresses[i][2], 0x0A, pci_config); + if (!NT_SUCCESS(status) || pci_config != 0x0c05) + continue; + // Check the device ID + status = pci_config_read_word(pci_addresses[i][0], pci_addresses[i][1], pci_addresses[i][2], 0x02, pci_config); + if (!NT_SUCCESS(status)) + continue; + pci_addr = pci_addresses[i]; + found = true; + break; + } + + if (!found) + return STATUS_NOT_SUPPORTED; + + // Check SMBus is enabled + status = pci_config_read_byte(pci_addr[0], pci_addr[1], pci_addr[2], SMBHSTCFG, pci_config); + if (!NT_SUCCESS(status) || !(pci_config & SMBHSTCFG_HST_EN)) + return STATUS_NOT_SUPPORTED; + + write_protection_enabled = (pci_config & SMBHSTCFG_SPD_WD) != 0; + + // Get SMBus memory base address + // Bit 0 indicates memory or IO mapping (0 indicating memory mapped) + status = pci_config_read_qword(pci_addr[0], pci_addr[1], pci_addr[2], SMBMBAR, pci_config); + if (!NT_SUCCESS(status) || (pci_config & 0x1)) + return STATUS_NOT_SUPPORTED; + + // Bits 1-2 indicates address range (10b for 64-bit, otherwise 32-bit). + // Decode the width before masking: only a 64-bit BAR owns the upper dword, + // for a 32-bit one it belongs to whatever register follows. + new bar_type = pci_config & 0x6; + if (bar_type == 0b000) + pci_config &= 0xffffffff; + else if (bar_type != 0b100) + // 1 MB below (01b) and reserved (11b) types aren't supported + return STATUS_NOT_SUPPORTED; + + // An unassigned BAR reads back as nothing but its type bits, so the raw + // value can be nonzero while the base masks down to physical address zero. + // Mapping that would point every later access at low physical memory. + new smba_pa = pci_config & 0xffffffffffffff00; + if (smba_pa == 0) + return STATUS_NOT_SUPPORTED; + + // Map MMIO space + i801_smba = io_space_map(smba_pa, SMBMBAR_SIZE); + if (i801_smba == NULL) { + debug_print(''Failed to map MMIO space\n''); + return STATUS_IO_DEVICE_ERROR; + } + + // Get SMBus IO base address to use for identification (bit 0 = 1 indicating IO mapped) + status = pci_config_read_dword(pci_addr[0], pci_addr[1], pci_addr[2], SMB_BASE, pci_config); + if (NT_SUCCESS(status) && (pci_config & 0x1)) + i801_io_smba = pci_config & 0xffe0; + + return STATUS_SUCCESS; +} + +NTSTATUS:i801_get_block_len(&len) +{ + virtual_read_byte(SMBHSTDAT0, len); + + if (len < 1 || len > I2C_SMBUS_BLOCK_MAX) { + len = 0; + debug_print(''Illegal SMBus block read size %u\n'', len); + return STATUS_DEVICE_PROTOCOL_ERROR; + } + + return STATUS_SUCCESS; +} + +// Make sure the SMBus host is ready to start transmitting. +NTSTATUS:i801_check_pre() +{ + new hststs; + + virtual_read_byte(SMBHSTSTS, hststs); + if (hststs & SMBHSTSTS_HOST_BUSY) { + debug_print(''SMBus is busy, can't use it!\n''); + return STATUS_DEVICE_BUSY; + } + + hststs &= STATUS_FLAGS; + if (hststs) { + debug_print(''Clearing status flags (%x)\n'', hststs); + virtual_write_byte(SMBHSTSTS, hststs); + } + + return STATUS_SUCCESS; +} + +i801_kill() { + // In byte-by-byte block mode the controller keeps SMBCLK low while + // BYTE_DONE is set. A pending BYTE_DONE must be acknowledged before + // KILL can release HOST_BUSY reliably. + new hststs; + virtual_read_byte(SMBHSTSTS, hststs); + if (hststs & SMBHSTSTS_BYTE_DONE) + virtual_write_byte(SMBHSTSTS, SMBHSTSTS_BYTE_DONE); + + // try to stop the current command + virtual_write_byte(SMBHSTCNT, SMBHSTCNT_KILL); + microsleep(1000); + virtual_write_byte(SMBHSTCNT, 0); + + // Check if it worked + virtual_read_byte(SMBHSTSTS, hststs); + if ((hststs & SMBHSTSTS_HOST_BUSY) || + !(hststs & SMBHSTSTS_FAILED)) + debug_print(''Failed terminating the transaction\n''); +} + +NTSTATUS:i801_hststs_to_ntstatus(hststs) +{ + new NTSTATUS:status = STATUS_SUCCESS; + + if (hststs & SMBHSTSTS_FAILED) { + status = STATUS_IO_DEVICE_ERROR; + debug_print(''Transaction failed\n''); + } + if (hststs & SMBHSTSTS_DEV_ERR) { + status = STATUS_NO_SUCH_DEVICE; + debug_print(''No response\n''); + } + if (hststs & SMBHSTSTS_BUS_ERR) { + status = STATUS_RETRY; + debug_print(''Lost arbitration\n''); + } + + return status; +} + +NTSTATUS:i801_wait_intr(&hststs, size) +{ + // 100 khz period in microseconds + const clock_us = 10; + + // Don't wait more than MAX_TIMEOUT ms for the transaction to complete + new deadline = get_tick_count() + MAX_TIMEOUT; + + // 10 start bits (start + slave address + rd/wr + ack) + // 9 bits per byte (byte + ack) + microsleep_long((10 + (9 * size)) * clock_us); + do { + // Only check for result once per clock cycle + // Also allows for 1 stop bit + microsleep_short(clock_us); + virtual_read_byte(SMBHSTSTS, hststs); + + if (!(hststs & SMBHSTSTS_HOST_BUSY) && + (hststs & (STATUS_ERROR_FLAGS | SMBHSTSTS_INTR))) { + hststs &= STATUS_ERROR_FLAGS; + return STATUS_SUCCESS; + } + } while (get_tick_count() < deadline); + + return STATUS_IO_TIMEOUT; +} + +NTSTATUS:i801_transaction(xact, &hststs, size) +{ + new old_hstcnt; + virtual_read_byte(SMBHSTCNT, old_hstcnt); + virtual_write_byte(SMBHSTCNT, old_hstcnt & ~SMBHSTCNT_INTREN); + + virtual_write_byte(SMBHSTCNT, xact | SMBHSTCNT_START); + + new NTSTATUS:status = i801_wait_intr(hststs, size); + // restore previous HSTCNT, enabling interrupts if previously enabled + virtual_write_byte(SMBHSTCNT, old_hstcnt); + return status; +} + +// Wait for a single byte to be transferred in byte-by-byte block mode. +// Returns STATUS_SUCCESS; hststs is set to the error flags (0 = no error). +NTSTATUS:i801_wait_byte_done(&hststs) +{ + const clock_us = 10; // one clock cycle at 100 kHz + + new deadline = get_tick_count() + MAX_TIMEOUT; + + do { + microsleep_short(clock_us); + virtual_read_byte(SMBHSTSTS, hststs); + } while ((hststs & (STATUS_ERROR_FLAGS | SMBHSTSTS_BYTE_DONE)) == 0 && (get_tick_count() < deadline)); + + if ((hststs & (STATUS_ERROR_FLAGS | SMBHSTSTS_BYTE_DONE)) == 0) + return STATUS_IO_TIMEOUT; + + hststs &= STATUS_ERROR_FLAGS; + return STATUS_SUCCESS; +} + +// Byte-by-byte block transaction for I2C_SMBUS_I2C_BLOCK_DATA. +// Unlike i801_block_transaction_by_block this does NOT use block-buffer mode (E32B). +// The caller must already have written SMBHSTADD and SMBHSTDAT1 (read offset) or +// SMBHSTCMD (write offset) before calling this function. +// in[0] = number of bytes to transfer +// in[1..] = bytes to write (write path only) +// out[0] = number of bytes transferred +// out[1..] = bytes read (read path only) +NTSTATUS:i801_i2c_blk_byte_by_byte(read_write, in[33], out[33], &hststs) +{ + new NTSTATUS:status = i801_check_pre(); + if (!NT_SUCCESS(status)) + return status; + + new len = in[0]; + + if (read_write == I2C_SMBUS_WRITE) { + virtual_write_byte(SMBHSTDAT0, len); + virtual_write_byte(SMBBLKDAT, in[1]); + } + + new smbcmd; + if (read_write == I2C_SMBUS_READ) + smbcmd = I801_I2C_BLOCK_DATA; + else + smbcmd = I801_BLOCK_DATA; + + // LAST_BYTE has to be visible before BYTE_DONE for the previous byte is + // acknowledged. For a one-byte read it therefore has to be set before START. + if (len == 1 && read_write == I2C_SMBUS_READ) + smbcmd |= SMBHSTCNT_LAST_BYTE; + + virtual_write_byte(SMBHSTCNT, smbcmd | SMBHSTCNT_START); + + for (new i = 1; i <= len; i++) { + new NTSTATUS:byte_status = i801_wait_byte_done(hststs); + if (!NT_SUCCESS(byte_status)) + return byte_status; + if (hststs) + return i801_hststs_to_ntstatus(hststs); + + if (read_write == I2C_SMBUS_READ) { + virtual_read_byte(SMBBLKDAT, out[i]); + + // Program LAST_BYTE while the controller is still paused on the + // penultimate BYTE_DONE. Clearing BYTE_DONE then starts the last byte. + if (i == len - 1) + virtual_write_byte(SMBHSTCNT, smbcmd | SMBHSTCNT_LAST_BYTE); + } + + if (read_write == I2C_SMBUS_WRITE && i + 1 <= len) + virtual_write_byte(SMBBLKDAT, in[i + 1]); + + // signal SMBBLKDAT ready + virtual_write_byte(SMBHSTSTS, SMBHSTSTS_BYTE_DONE); + } + + out[0] = len; + + status = i801_wait_intr(hststs, len); + return status; +} + +NTSTATUS:i801_block_transaction_by_block(read_write, command, in[33], out[33], &hststs) +{ + hststs = 0; + new NTSTATUS:status, len, xact; + // We don't know the return size, so lets just wait the minimum amount of time + // write lacks repeated address + new size = 2 + read_write; + + switch (command) { + case I2C_SMBUS_BLOCK_PROC_CALL: + xact = I801_BLOCK_PROC_CALL; + case I2C_SMBUS_BLOCK_DATA: + xact = I801_BLOCK_DATA; + default: + return STATUS_NOT_SUPPORTED; + } + + /* Set block buffer mode */ + new smbauxctl; + virtual_read_byte(SMBAUXCTL, smbauxctl); + virtual_write_byte(SMBAUXCTL, smbauxctl | SMBAUXCTL_E32B); + + if (read_write == I2C_SMBUS_WRITE) { + len = in[0]; + size += len; + virtual_write_byte(SMBHSTDAT0, len); + new smbhstcnt; + virtual_read_byte(SMBHSTCNT, smbhstcnt); + for (new i = 0; i < len; i++) + virtual_write_byte(SMBBLKDAT, in[i+1]); + } + + // size = command + count + address (read only) + data... + status = i801_transaction(xact, hststs, size); + if (!NT_SUCCESS(status)) { + goto cleanup; + } + + if (hststs) { + status = STATUS_SUCCESS; // the transaction succeeded, but we got an error back + goto cleanup; + } + + if (read_write == I2C_SMBUS_READ || + command == I2C_SMBUS_BLOCK_PROC_CALL) { + status = i801_get_block_len(len); + if (!NT_SUCCESS(status)) { + goto cleanup; + } + + out[0] = len; + new hstcnt; + virtual_read_byte(SMBHSTCNT, hstcnt); + for (new i = 0; i < len; i++) + virtual_read_byte(SMBBLKDAT, out[i + 1]); + } +cleanup: + virtual_read_byte(SMBAUXCTL, smbauxctl); + virtual_write_byte(SMBAUXCTL, smbauxctl & ~SMBAUXCTL_E32B); + return status; +} + +Void:i801_set_hstadd(addr, read_write) +{ + virtual_write_byte(SMBHSTADD, ((addr & 0x7f) << 1) | (read_write & 0x01)); +} + +NTSTATUS:i801_simple_transaction(addr, hstcmd, read_write, command, in, &out, &hststs) +{ + new xact, size = command; + + switch (command) { + case I2C_SMBUS_QUICK: + { + i801_set_hstadd(addr, read_write); + xact = I801_QUICK; + } + case I2C_SMBUS_BYTE: + { + i801_set_hstadd(addr, read_write); + if (read_write == I2C_SMBUS_WRITE) + virtual_write_byte(SMBHSTCMD, hstcmd); + xact = I801_BYTE; + } + case I2C_SMBUS_BYTE_DATA: + { + i801_set_hstadd(addr, read_write); + if (read_write == I2C_SMBUS_WRITE) + virtual_write_byte(SMBHSTDAT0, in); + virtual_write_byte(SMBHSTCMD, hstcmd); + xact = I801_BYTE_DATA; + size += read_write; + } + case I2C_SMBUS_WORD_DATA: + { + i801_set_hstadd(addr, read_write); + if (read_write == I2C_SMBUS_WRITE) { + virtual_write_byte(SMBHSTDAT0, in & 0xff); + virtual_write_byte(SMBHSTDAT1, (in & 0xff00) >>> 8); + } + virtual_write_byte(SMBHSTCMD, hstcmd); + xact = I801_WORD_DATA; + size += read_write; + } + case I2C_SMBUS_PROC_CALL: + { + i801_set_hstadd(addr, read_write); + virtual_write_byte(SMBHSTDAT0, in & 0xff); + virtual_write_byte(SMBHSTDAT1, (in & 0xff00) >>> 8); + virtual_write_byte(SMBHSTCMD, hstcmd); + read_write = I2C_SMBUS_READ; + xact = I801_PROC_CALL; + } + default: + { + debug_print(''Unsupported transaction %d\n'', command); + return STATUS_NOT_SUPPORTED; + } + } + + new NTSTATUS:status = i801_transaction(xact, hststs, size); + if (!NT_SUCCESS(status)) + return status; + + + if (!hststs && read_write != I2C_SMBUS_WRITE) { + switch (command) { + case I2C_SMBUS_BYTE, I2C_SMBUS_BYTE_DATA: + { + virtual_read_byte(SMBHSTDAT0, out); + } + case I2C_SMBUS_WORD_DATA, I2C_SMBUS_PROC_CALL: + { + virtual_read_word(SMBHSTDAT0, out); + } + } + } + + return STATUS_SUCCESS; +} + +NTSTATUS:i801_smbus_block_transaction(addr, hstcmd, read_write, command, in[33], out[33], &hststs) +{ + if (read_write == I2C_SMBUS_READ && command == I2C_SMBUS_BLOCK_DATA) + /* Mark block length as invalid */ + out[0] = SMBUS_LEN_SENTINEL; + else if (in[0] < 1 || in[0] > I2C_SMBUS_BLOCK_MAX) + return STATUS_INVALID_PARAMETER; + + if (command == I2C_SMBUS_BLOCK_PROC_CALL) + /* Needs to be flagged as write transaction */ + i801_set_hstadd(addr, I2C_SMBUS_WRITE); + else + i801_set_hstadd(addr, read_write); + + // For I2C block reads the ICH5 datasheet (p.240) requires the offset/command + // byte to be written to SMBHSTDAT1 instead of SMBHSTCMD. + if (command == I2C_SMBUS_I2C_BLOCK_DATA && read_write == I2C_SMBUS_READ) + virtual_write_byte(SMBHSTDAT1, hstcmd); + else + virtual_write_byte(SMBHSTCMD, hstcmd); + + // I2C block data uses byte-by-byte mode; SMBus block and proc-call use block-buffer mode. + if (command == I2C_SMBUS_I2C_BLOCK_DATA) + return i801_i2c_blk_byte_by_byte(read_write, in, out, hststs); + + // if (priv->features & FEATURE_BLOCK_BUFFER) + // return i801_block_transaction_by_block(data, read_write, command); + // else + // return i801_block_transaction_byte_by_byte(data, read_write, command); + return i801_block_transaction_by_block(read_write, command, in, out, hststs); +} + +NTSTATUS:i801_inuse(bool:inuse) +{ + if (inuse) { + // Wait for device to be unlocked by BIOS/ACPI + // Linux doesn't do this, since some BIOSes might not unlock it + new deadline = get_tick_count() + MAX_TIMEOUT; + new is_inuse; + virtual_read_byte(SMBHSTSTS, is_inuse); + is_inuse &= SMBHSTSTS_INUSE_STS; + while (is_inuse && (get_tick_count() < deadline)) { + microsleep(250); + virtual_read_byte(SMBHSTSTS, is_inuse); + is_inuse &= SMBHSTSTS_INUSE_STS; + } + + if (is_inuse) { + debug_print(''SMBus device is in use by BIOS/ACPI\n''); + return STATUS_IO_TIMEOUT; + } + return STATUS_SUCCESS; + } else { + // Unlock the SMBus device for use by BIOS/ACPI, and clear status flags + // if not done already. + virtual_write_byte(SMBHSTSTS, SMBHSTSTS_INUSE_STS | STATUS_FLAGS); + return STATUS_SUCCESS; + } +} + +NTSTATUS:i801_access_simple(addr, read_write, command, size, in, &out) +{ + new NTSTATUS:status, hststs, smbauxctl; + new bool:acquired = false; + + status = i801_inuse(true); + if (!NT_SUCCESS(status)) + goto unlock; + + // INUSE_STS is ours only past this point, so only now may we release it + acquired = true; + + status = i801_check_pre(); + if (!NT_SUCCESS(status)) + goto unlock; + + status = virtual_read_byte(SMBAUXCTL, smbauxctl); + if (!NT_SUCCESS(status)) + goto unlock; + + status = virtual_write_byte(SMBAUXCTL, smbauxctl & (~SMBAUXCTL_CRC)); + if (!NT_SUCCESS(status)) + goto unlock; + + switch (size) { + case I2C_SMBUS_QUICK, I2C_SMBUS_BYTE, I2C_SMBUS_BYTE_DATA, I2C_SMBUS_WORD_DATA, I2C_SMBUS_PROC_CALL: + status = i801_simple_transaction(addr, command, read_write, size, in, out, hststs); + default: + { + debug_print(''Unsupported simple transaction %d\n'', size); + status = STATUS_NOT_SUPPORTED; + goto unlock; + } + } + + + if (!NT_SUCCESS(status)) { + i801_kill(); + goto unlock; + } + + status = i801_hststs_to_ntstatus(hststs); + +unlock: + if (acquired) + i801_inuse(false); + + return status; +} + +NTSTATUS:i801_access_block(addr, read_write, command, size, in[33], out[33]) +{ + new NTSTATUS:status, hststs, smbauxctl; + new bool:acquired = false; + + status = i801_inuse(true); + if (!NT_SUCCESS(status)) + goto unlock; + + // INUSE_STS is ours only past this point, so only now may we release it + acquired = true; + + status = i801_check_pre(); + if (!NT_SUCCESS(status)) + goto unlock; + + status = virtual_read_byte(SMBAUXCTL, smbauxctl); + if (!NT_SUCCESS(status)) + goto unlock; + + status = virtual_write_byte(SMBAUXCTL, smbauxctl & (~SMBAUXCTL_CRC)); + if (!NT_SUCCESS(status)) + goto unlock; + + switch (size) { + case I2C_SMBUS_BLOCK_DATA, I2C_SMBUS_BLOCK_PROC_CALL, I2C_SMBUS_I2C_BLOCK_DATA: + status = i801_smbus_block_transaction(addr, command, read_write, size, in, out, hststs); + default: + { + debug_print(''Unsupported block transaction %d\n'', size); + status = STATUS_NOT_SUPPORTED; + goto unlock; + } + } + + if (!NT_SUCCESS(status)) { + i801_kill(); + goto unlock; + } + + status = i801_hststs_to_ntstatus(hststs); + +unlock: + if (acquired) + i801_inuse(false); + + return status; +} + +/// Identify the SMBus controller. +/// +/// @param in Unused +/// @param in_size Unused +/// @param out [0] = Type of the SMBus controller, [1] = I/O Base address, [2] = PCI Identifiers +/// @param out_size Must be 3 +/// @return An NTSTATUS +DEFINE_IOCTL_SIZED(ioctl_identity, 0, 3) { + new NTSTATUS:status; + + out[0] = CHAR4_CONST('i', '8', '0', '1'); + + out[1] = i801_io_smba; + + // Read the PCI vendor/device ID + new pci_ids; + status = pci_config_read_dword(pci_addr[0], pci_addr[1], pci_addr[2], 0x00, pci_ids); + if (!NT_SUCCESS(status)) + return status; + + // Read the PCI subsystem vendor/device ID + new pci_subsys_ids; + status = pci_config_read_dword(pci_addr[0], pci_addr[1], pci_addr[2], 0x2C, pci_subsys_ids); + if (!NT_SUCCESS(status)) + return status; + + out[2] = pci_ids | (pci_subsys_ids << 32); + + return STATUS_SUCCESS; +} + +/// Set the SMBus clock frequency. +/// +/// @param in [0] = Frequency in Hz or -1 for no change +/// @param in_size Must be 1 +/// @param out [0] = Previous frequency in Hz +/// @param out_size Must be 1 +/// @note The i801 SMBus controller use a fixed clock frequency of 100kHz. +/// @return An NTSTATUS +DEFINE_IOCTL_SIZED(ioctl_clock_freq, 1, 1) { + new new_freq = in[0]; + if (new_freq != -1) { + return STATUS_NOT_SUPPORTED; + } + + out[0] = 100000; + + return STATUS_SUCCESS; +} + +/// Get the SMBus SPD write protection status from host config. +/// +/// @param in [0] Unused +/// @param in_size Unused +/// @param out [0] = SPD write protection status (0 = disabled, 1 = enabled) +/// @param out_size Must be 1 +/// @return An NTSTATUS +DEFINE_IOCTL_SIZED(ioctl_write_protection, 0, 1) { + out[0] = write_protection_enabled; + + return STATUS_SUCCESS; +} + +/// SMBus transfer. +/// +/// Performs a transfer of data over the SMBus using the specified command. +/// I2C_SMBUS_QUICK (protocol 0) only requires the address and read/write parameters, command must be left as 0. +/// I2C_SMBUS_BYTE (1), I2C_SMBUS_BYTE_DATA (2), and I2C_SMBUS_WORD_DATA (3) require the address, read/write, command, and data (write only) parameters. +/// I2C_SMBUS_PROC_CALL (4) requires the address, command, and data parameters. +/// I2C_SMBUS_BLOCK_DATA (5) requires the address, read/write, command, data parameters. +/// I2C_SMBUS_BLOCK_PROC_CALL (7) requires the address, command, data parameters. +/// +/// @param in [0] = Address, [1] = Read(1)/Write(0), [2] = Command, [3] = Protocol, [4..9] Data +/// @param in_size Must be between 4 and 9 +/// @param out [0..5] = Length then Data (byte packed) +/// @param out_size Must be between 0 and 5 +/// @return An NTSTATUS +/// @warning You should acquire the "\BaseNamedObjects\Access_SMBUS.HTP.Method" mutant before calling this +DEFINE_IOCTL(ioctl_smbus_xfer) { + if (in_size < 4) + return STATUS_BUFFER_TOO_SMALL; + + new address = in[0]; + new read_write = in[1]; + new command = in[2]; + new hstcmd = in[3]; + + // Validate before any PCI or controller change. Only the low bit of the + // direction reaches SMBHSTADD, while the rest of the driver compares the + // whole value against I2C_SMBUS_WRITE, so e.g. 2 would start a write and + // then be read back as if it were a read. The value also lands in the + // transfer time estimate, where a large one turns into a huge busy wait. + if (read_write != I2C_SMBUS_READ && read_write != I2C_SMBUS_WRITE) + return STATUS_INVALID_PARAMETER; + + // Anything wider than 7 bits would silently alias a different slave + if (address < 0 || address > I2C_SMBUS_ADDR_MAX) + return STATUS_INVALID_PARAMETER; + + new NTSTATUS:status; + new pci_cmd_original; + new bool:pci_cmd_enabled_here = false; + + status = pci_config_read_word(pci_addr[0], pci_addr[1], pci_addr[2], PCICMD, pci_cmd_original); + if (!NT_SUCCESS(status)) + return status; + + //PCI CMD memory decoding not enabled + if (0 == (pci_cmd_original & PCICMD_MMBIT)) + { + //Enable it for the duration of this call + status = pci_config_write_word(pci_addr[0], pci_addr[1], pci_addr[2], PCICMD, pci_cmd_original | PCICMD_MMBIT); + if (!NT_SUCCESS(status)) + return status; + + pci_cmd_enabled_here = true; + } + + switch (hstcmd) { + case I2C_SMBUS_QUICK: + { + new unused; + status = i801_access_simple(address, read_write, command, hstcmd, 0, unused); + } + case I2C_SMBUS_BYTE, I2C_SMBUS_BYTE_DATA, I2C_SMBUS_WORD_DATA: + { + new unused; + if (read_write == I2C_SMBUS_WRITE) { + if (in_size < 5) { + status = STATUS_BUFFER_TOO_SMALL; + goto getout; + } + + new data = in[4]; + + status = i801_access_simple(address, read_write, command, hstcmd, data, unused); + } else { + // read_write == I2C_SMBUS_READ + if (out_size < 1) { + status = STATUS_BUFFER_TOO_SMALL; + goto getout; + } + + status = i801_access_simple(address, read_write, command, hstcmd, unused, out[0]); + } + } + case I2C_SMBUS_BLOCK_DATA: + { + if (read_write == I2C_SMBUS_WRITE) { + // 4 parameters, 5 cells of data + if (in_size < (4 + 5)) { + status = STATUS_BUFFER_TOO_SMALL; + goto getout; + } + + new in_data[I2C_SMBUS_BLOCK_MAX + 1]; + unpack_bytes_le(in, in_data, I2C_SMBUS_BLOCK_MAX + 1, 4 * 8, 0); + + new unused[I2C_SMBUS_BLOCK_MAX + 1]; + + status = i801_access_block(address, read_write, command, hstcmd, in_data, unused); + } else { + // read_write == I2C_SMBUS_READ + if (out_size < 5) { + status = STATUS_BUFFER_TOO_SMALL; + goto getout; + } + + new unused[I2C_SMBUS_BLOCK_MAX + 1]; + new out_data[I2C_SMBUS_BLOCK_MAX + 1]; + + status = i801_access_block(address, read_write, command, hstcmd, unused, out_data); + + if (!NT_SUCCESS(status)) + goto getout; + + out[0] = out_data[0]; + pack_bytes_le(out_data, out, I2C_SMBUS_BLOCK_MAX, 1, 8); + } + } + case I2C_SMBUS_I2C_BLOCK_DATA: + { + if (read_write == I2C_SMBUS_WRITE) { + // 4 parameters + 5 cells of packed data (length byte + up to 32 bytes) + if (in_size < (4 + 5)) { + status = STATUS_BUFFER_TOO_SMALL; + goto getout; + } + + new in_data[I2C_SMBUS_BLOCK_MAX + 1]; + unpack_bytes_le(in, in_data, I2C_SMBUS_BLOCK_MAX + 1, 4 * 8, 0); + + new unused[I2C_SMBUS_BLOCK_MAX + 1]; + + status = i801_access_block(address, read_write, command, hstcmd, in_data, unused); + } else { + // read_write == I2C_SMBUS_READ + // in[4] = requested byte count (set by caller) + if (in_size < 5) { + status = STATUS_BUFFER_TOO_SMALL; + goto getout; + } + + if (out_size < 5) { + status = STATUS_BUFFER_TOO_SMALL; + goto getout; + } + + new in_data[I2C_SMBUS_BLOCK_MAX + 1]; + in_data[0] = in[4]; // requested length + + new out_data[I2C_SMBUS_BLOCK_MAX + 1]; + + status = i801_access_block(address, read_write, command, hstcmd, in_data, out_data); + + if (!NT_SUCCESS(status)) + goto getout; + + out[0] = out_data[0]; + pack_bytes_le(out_data, out, I2C_SMBUS_BLOCK_MAX, 1, 8); + } + } + case I2C_SMBUS_PROC_CALL: + { + if (in_size < 5) { + status = STATUS_BUFFER_TOO_SMALL; + goto getout; + } + + if (out_size < 1) { + status = STATUS_BUFFER_TOO_SMALL; + goto getout; + } + + new data = in[4]; + + status = i801_access_simple(address, read_write, command, hstcmd, data, out[0]); + } + case I2C_SMBUS_BLOCK_PROC_CALL: + { + // 4 parameters, 5 cells of data + if (in_size < (4 + 5)) { + status = STATUS_BUFFER_TOO_SMALL; + goto getout; + } + + if (out_size < 5) { + status = STATUS_BUFFER_TOO_SMALL; + goto getout; + } + + new in_data[I2C_SMBUS_BLOCK_MAX + 1]; + unpack_bytes_le(in, in_data, I2C_SMBUS_BLOCK_MAX + 1, 4 * 8, 0); + + new out_data[I2C_SMBUS_BLOCK_MAX + 1]; + + status = i801_access_block(address, I2C_SMBUS_WRITE, command, I2C_SMBUS_BLOCK_PROC_CALL, in_data, out_data); + + if (!NT_SUCCESS(status)) + goto getout; + + out[0] = out_data[0]; + pack_bytes_le(out_data, out, I2C_SMBUS_BLOCK_MAX, 1, 8); + } + default: + { + debug_print(''Unsupported transaction %d\n'', hstcmd); + status = STATUS_NOT_SUPPORTED; + } + } + +getout: + //Undo only the bit we set, and only if we were the ones to set it. + //Re-read rather than rewriting the whole word from the entry snapshot, + //so an unrelated change made meanwhile isn't clobbered. + if (pci_cmd_enabled_here) + { + new pci_cmd_current; + new NTSTATUS:restore_status = pci_config_read_word(pci_addr[0], pci_addr[1], pci_addr[2], PCICMD, pci_cmd_current); + if (NT_SUCCESS(restore_status)) + restore_status = pci_config_write_word(pci_addr[0], pci_addr[1], pci_addr[2], PCICMD, pci_cmd_current & ~PCICMD_MMBIT); + + //Leaving decoding enabled is worth reporting even if the transfer worked + if (NT_SUCCESS(status) && !NT_SUCCESS(restore_status)) + status = restore_status; + } + + return status; +} + +NTSTATUS:main() { + if (get_arch() != ARCH_X64) + return STATUS_NOT_SUPPORTED; + + return i801_init(); +} + +public NTSTATUS:unload() { + if (i801_smba != NULL) + io_space_unmap(i801_smba, SMBMBAR_SIZE); + return STATUS_SUCCESS; +} diff --git a/kurgan/hardware/pawnio/sleepmode.inc b/kurgan/hardware/pawnio/sleepmode.inc new file mode 100644 index 0000000..44f2e84 --- /dev/null +++ b/kurgan/hardware/pawnio/sleepmode.inc @@ -0,0 +1,52 @@ +#include + +const SleepMode: { + SleepMode_AlwaysBusy = 0, + SleepMode_ShortBusy = 1, + SleepMode_AlwaysSleep = 2, + + SleepMode_Max, +}; + +static SleepMode:g_sleep_mode = SleepMode_AlwaysBusy; + +/// Set sleep mode. +/// @param mode Sleep mode to set +stock Void:set_sleep_mode(SleepMode:mode) { + g_sleep_mode = mode; +} + +/// Short sleep for a given number of microseconds. +/// @param us Microseconds to sleep +stock Void:microsleep_short(us) { + switch (g_sleep_mode) { + case SleepMode_AlwaysBusy, SleepMode_ShortBusy: + microsleep2(us); + case SleepMode_AlwaysSleep: + microsleep(us); + } +} + +/// Long sleep for a given number of microseconds. +/// @param us Microseconds to sleep +stock Void:microsleep_long(us) { + switch (g_sleep_mode) { + case SleepMode_AlwaysBusy: + microsleep2(us); + case SleepMode_ShortBusy, SleepMode_AlwaysSleep: + microsleep(us); + } +} + +#if !defined(NO_SLEEPMODE_IOCTL) + +DEFINE_IOCTL_SIZED(ioctl_set_sleep_mode, 1, 0) { + new SleepMode:mode = SleepMode:in[0]; + if (mode < SleepMode_AlwaysBusy || mode >= SleepMode_Max) { + return STATUS_INVALID_PARAMETER; + } + set_sleep_mode(mode); + return STATUS_SUCCESS; +} + +#endif diff --git a/kurgan/lighting/__init__.py b/kurgan/lighting/__init__.py new file mode 100644 index 0000000..ac4d359 --- /dev/null +++ b/kurgan/lighting/__init__.py @@ -0,0 +1 @@ +"""Lighting: Lighting Node CORE fan LEDs, Dominator DDR5 RAM and ASUS GPU LEDs.""" diff --git a/kurgan/lighting/case_fans.py b/kurgan/lighting/case_fans.py new file mode 100644 index 0000000..8ca734d --- /dev/null +++ b/kurgan/lighting/case_fans.py @@ -0,0 +1,276 @@ +"""Opt-in temperature lighting and calibrated QL120 side chase on the Lighting Node CORE. + +Header 1 of the CORE holds the six QL120 case fans (34 LEDs each, 204 in total); header 2 is +left alone. The node is driven directly over HID (see lighting_node.py), so no OpenRGB is needed. +""" + +from __future__ import annotations + +import logging +import math +import threading +import time +from typing import Callable + +from kurgan.theme import Theme +from kurgan.lighting.lighting_node import MAX_LEDS, LightingNodeBusy, LightingNodeCore + +log = logging.getLogger(__name__) + +_RETRY_SECONDS = 10.0 +_FAN_TOP_RIGHT = (17, 17, 17, 20, 11, 20) +_CHASE_EASE_SECONDS = 1.0 +# The CORE shares a USB 2.0 hub with the LCD; flooding it hung the LCD firmware, so cap +# frames at ~22/s and let a fast chase advance more than one LED per frame instead. +MIN_CHASE_FRAME_SECONDS = 0.045 +CHASE_POLL_SECONDS = 0.02 + + +def _side_chase_route(cpu_side: bool) -> tuple[int, ...]: + fans = (4, 5, 3) if cpu_side else (0, 1, 2) # bottom, middle, top; zero-based chain + # Clock positions 0 and 11 flank 12; 5 and 6 flank 6. + segments = ( + (0, range(12)), + (1, range(5, -1, -1)), + (2, range(6, 18)), + (1, range(11, 5, -1)), + ) + route = [] + for position, clock_positions in segments: + for clock in clock_positions: + if not cpu_side: + clock = 11 - clock + led = 10 + (_FAN_TOP_RIGHT[fans[position]] - 10 + clock) % 12 + route.append(fans[position] * 34 + led) + return tuple(route) + + +_SIDE_CHASE_ROUTES = (_side_chase_route(True), _side_chase_route(False)) +SIDE_CHASE_CYCLE_STEPS = len(_SIDE_CHASE_ROUTES[0]) +# Bottom fan at 6 o'clock; the top fan reaches 12 o'clock half a cycle later. +SIDE_CHASE_BOTTOM_STEP = 6 +_LEDS_PER_SIDE = 3 * 34 # chain fans 0-2 are the GPU side, 3-5 the CPU side + + +def side_chase_color(strength: float) -> tuple[int, int, int]: + """Blend the dark-red ring base into the warm-orange chase head (strength 0-1).""" + return (round(24 + 231 * strength), round(48 * strength), 0) + + +def side_chase_frame(step: int) -> list[tuple[int, int, int]]: + """Render mirrored sides, with each inner ring reflected left-to-right.""" + colors = [(48, 0, 0) if index % 34 < 10 else (24, 0, 0) for index in range(204)] + for route in _SIDE_CHASE_ROUTES: + for age in range(5): + strength = (5 - age) / 5 + color = side_chase_color(strength) + outer = route[(step - age) % len(route)] + fan, local = divmod(outer, 34) + right_of_top = _FAN_TOP_RIGHT[fan] + clock = (local - right_of_top) % 12 + inner = fan * 34 + 22 + (right_of_top - 10 + 11 - clock) % 12 + colors[outer] = colors[inner] = color + return colors + + +class ChaseTiming: + """Elapsed-time chase phase with power-dependent speed and gradual acceleration.""" + + def __init__(self, step_seconds: float = 0.15, fast_step_seconds: float = 0.025, + watts: tuple[float, float] = (150.0, 550.0)): + for step in (step_seconds, fast_step_seconds): + if not math.isfinite(step) or step < 0.02: + raise ValueError("Chase step must be finite and at least 0.02 seconds") + if fast_step_seconds > step_seconds: + raise ValueError("Fast chase step can't be slower than the idle step") + if not all(math.isfinite(w) for w in watts) or watts[1] <= watts[0]: + raise ValueError("Chase power range must be finite and increasing") + self.step_seconds = step_seconds + self.fast_step_seconds = fast_step_seconds + self.watts = watts + self._lock = threading.Lock() + self._power: float | None = None + self.reset() + + def reset(self, phase: float = 0.0) -> None: + with self._lock: + self.last_time: float | None = None + self.phase = phase + self.rate = 0.0 + + def set_power(self, total_watts: float | None) -> None: + with self._lock: + self._power = total_watts + + def rate_for(self, total_watts: float | None) -> float: + slow, fast = 1 / self.step_seconds, 1 / self.fast_step_seconds + if total_watts is None or not math.isfinite(total_watts): + return slow + lo, hi = self.watts + t = min(1.0, max(0.0, (total_watts - lo) / (hi - lo))) + return slow + t * (fast - slow) + + def sample(self, now: float) -> tuple[float, float]: + with self._lock: + target = self.rate_for(self._power) + if self.last_time is None: + self.last_time, self.rate = now, target + dt = max(0.0, now - self.last_time) + self.last_time = max(now, self.last_time) + self.rate += (target - self.rate) * min(1.0, dt / _CHASE_EASE_SECONDS) + self.phase += self.rate * dt + return self.phase, self.rate + + def step(self, now: float) -> int: + return int(self.sample(now)[0]) + + +class RGBLighting: + """Run a selected pattern on the Lighting Node CORE; hand it back to its hardware effect when off.""" + + def __init__(self, theme: Theme, chase_step_seconds: float = 0.15, chase_fast_step_seconds: float = 0.025, + chase_watts: tuple[float, float] = (150.0, 550.0), + node_factory: Callable[[], LightingNodeCore] = LightingNodeCore, *, + chase_timing: ChaseTiming | None = None): + """The side chase runs at `chase_step_seconds` per LED at or below the first + `chase_watts` total system power, speeding up to `chase_fast_step_seconds` at the second.""" + self._owns_chase_timing = chase_timing is None + self._chase_timing = (chase_timing if chase_timing is not None + else ChaseTiming(chase_step_seconds, chase_fast_step_seconds, chase_watts)) + self.theme = theme + self.chase_step_seconds = chase_step_seconds + self.chase_fast_step_seconds = chase_fast_step_seconds + self.chase_watts = chase_watts + self.node: LightingNodeCore | None = None + self.status = "off" + self._node_factory = node_factory + self._retry_at = 0.0 + self._last_error: str | None = None + self._pattern: str | None = None + self._last_chase_step: int | None = None + self._last_frame_time = -math.inf + self._cpu_temp: float | None = None + self._gpu_temp: float | None = None + self._power: float | None = None + self._lock = threading.Lock() + + def set_temperature(self, cpu_temp: float | None, gpu_temp: float | None = None) -> None: + with self._lock: + self._cpu_temp = cpu_temp + self._gpu_temp = gpu_temp + + def set_power(self, total_watts: float | None) -> None: + with self._lock: + self._power = total_watts + self._chase_timing.set_power(total_watts) + + def chase_rate(self, total_watts: float | None) -> float: + """LEDs per second for a given total system power (idle pace when unknown).""" + return self._chase_timing.rate_for(total_watts) + + def run(self, stop: threading.Event, temperature_enabled: threading.Event, + side_chase_enabled: threading.Event) -> None: + """Own all Lighting Node access on one worker, independent of LCD and sensor timing.""" + try: + while not stop.is_set(): + with self._lock: + cpu_temp, gpu_temp = self._cpu_temp, self._gpu_temp + self.update(cpu_temp, temperature_enabled.is_set(), side_chase=side_chase_enabled.is_set(), + gpu_temp=gpu_temp) + stop.wait(CHASE_POLL_SECONDS) + finally: + self.close() + + def update(self, cpu_temp: float | None, enabled: bool, *, side_chase: bool = False, + gpu_temp: float | None = None) -> None: + pattern = "side-chase" if side_chase else "temperature" if enabled else None + if pattern != self._pattern: + self._pattern = pattern + if self._owns_chase_timing: + self._chase_timing.reset() + self._last_chase_step = None + if pattern is None: + self.close() + if pattern is None: + return + if self.node is None: + if time.monotonic() < self._retry_at: + return + try: + node = self._node_factory() + node.open() + except LightingNodeBusy as e: + self._fail(e, str(e)) + return + except Exception as e: + self._fail(e, "Lighting Node CORE unavailable") + return + self.node = node + self._last_error = None + log.info("Lighting Node CORE opened (firmware %s)", node.firmware) + try: + if pattern == "side-chase": + self._apply_side_chase() + else: + self._apply_temperature(cpu_temp, gpu_temp) + self.node.keepalive() + except Exception as e: + self._fail(e, "Lighting Node CORE connection lost") + + def close(self) -> None: + """Hand the fans back to the node's own effect.""" + node, self.node = self.node, None + self._last_chase_step = None + if node is not None: + try: + node.close() + except Exception: + log.exception("Couldn't release the Lighting Node CORE") + self._set_status("off") + + def _apply_temperature(self, cpu_temp: float | None, gpu_temp: float | None = None) -> None: + """Colour each side's three fans by its own part's temperature, like the LCD gauges.""" + assert self.node is not None + if cpu_temp is None and gpu_temp is None: + self._set_status("Temperature lighting waiting for temperatures") + return + # A side whose sensor is unavailable borrows the other side's reading. + cpu = cpu_temp if cpu_temp is not None else gpu_temp + gpu = gpu_temp if gpu_temp is not None else cpu_temp + th = self.theme + gpu_color = th.level_color(gpu, th.temp_warn, th.temp_hot) + cpu_color = th.level_color(cpu, th.temp_warn, th.temp_hot) + self.node.show(0, [gpu_color] * _LEDS_PER_SIDE + [cpu_color] * (MAX_LEDS - _LEDS_PER_SIDE)) + self._set_status(f"Temperature lighting active (GPU {gpu:.0f} \u00b0C, CPU {cpu:.0f} \u00b0C)") + + def _apply_side_chase(self) -> None: + assert self.node is not None + with self._lock: + power = self._power + now = time.monotonic() + step = self._chase_timing.step(now) + if step != self._last_chase_step and now - self._last_frame_time >= MIN_CHASE_FRAME_SECONDS: + self.node.show(0, side_chase_frame(step)) + self._last_chase_step = step + self._last_frame_time = now + watts = "" if power is None else f" at {power:.0f} W" + self._set_status(f"Red side chase active ({1000 / self._chase_timing.rate:.0f} ms/LED{watts})") + + def _fail(self, error: Exception, status: str) -> None: + node, self.node = self.node, None + if node is not None: + try: + node.close() + except Exception: + pass + self._last_chase_step = None + self._retry_at = time.monotonic() + _RETRY_SECONDS + self._set_status(status) + message = str(error) or type(error).__name__ + if message != self._last_error: + log.warning("RGB lighting unavailable: %s", message, exc_info=not isinstance(error, LightingNodeBusy)) + self._last_error = message + + def _set_status(self, status: str) -> None: + if status != self.status: + self.status = status \ No newline at end of file diff --git a/kurgan/lighting/gpu.py b/kurgan/lighting/gpu.py new file mode 100644 index 0000000..43ab4cf --- /dev/null +++ b/kurgan/lighting/gpu.py @@ -0,0 +1,253 @@ +"""Direct ASUS RTX 4090 lighting through NVIDIA's I2C API (no USB traffic).""" + +from __future__ import annotations + +import ctypes +import logging +import math +import os +import threading +import time +from typing import Callable, Protocol + +from kurgan.lighting.case_fans import ( + CHASE_POLL_SECONDS, MIN_CHASE_FRAME_SECONDS, ChaseTiming, + SIDE_CHASE_BOTTOM_STEP, SIDE_CHASE_CYCLE_STEPS, side_chase_color, +) +from kurgan.telemetry.sensors import _process_names, corsair_software_running + +log = logging.getLogger(__name__) +Rgb = tuple[int, int, int] +_U8, _U32 = ctypes.c_uint8, ctypes.c_uint32 +_GPU_DEVICE = 0x268410DE +_GPU_SUBSYSTEM = 0x89321043 +_CONTROLLER_ADDRESS = 0x67 +_FIRMWARE = ("AUMA0-E6K5-0107", "AUMA0-E6K5-1110", "AUMA0-E6K5-1111") + + +class _I2cInfo(ctypes.Structure): + _fields_ = [ + ("version", _U32), ("display_mask", _U32), + ("ddc", _U8), ("address", _U8), + ("register", ctypes.POINTER(_U8)), ("register_size", _U32), + ("data", ctypes.POINTER(_U8)), ("size", _U32), + ("speed", _U32), ("speed_khz", _U32), + ("port", _U8), ("port_set", _U32), + ] + + +class NvidiaI2c: + def __init__(self) -> None: + name = "nvapi64.dll" if ctypes.sizeof(ctypes.c_void_p) == 8 else "nvapi.dll" + self._dll = ctypes.CDLL(os.path.join(os.environ["SystemRoot"], "System32", name)) + self._query = self._dll.nvapi_QueryInterface + self._query.argtypes = [_U32] + self._query.restype = ctypes.c_void_p + self._check(self._function(0x0150E828)(), "Initialize") + enum = self._function(0xE5AC921F, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_int32)) + identity = self._function(0x2DDFB66E, ctypes.c_void_p, *([ctypes.POINTER(_U32)] * 4)) + handles = (ctypes.c_void_p * 64)() + count = ctypes.c_int32() + self._check(enum(handles, ctypes.byref(count)), "EnumPhysicalGPUs") + matches = [] + for handle in handles[:count.value]: + device, subsystem, revision, extended = (_U32() for _ in range(4)) + self._check(identity(handle, ctypes.byref(device), ctypes.byref(subsystem), + ctypes.byref(revision), ctypes.byref(extended)), "GetPCIIdentifiers") + if device.value == _GPU_DEVICE and subsystem.value == _GPU_SUBSYSTEM: + matches.append(handle) + if len(matches) != 1: + raise OSError(f"Expected one ASUS RTX 4090 (2684:8932), found {len(matches)}") + self._handle = matches[0] + arguments = (ctypes.c_void_p, ctypes.POINTER(_I2cInfo), ctypes.POINTER(_U32)) + self._read = self._function(0x4D7B0709, *arguments) + self._write = self._function(0x283AC65A, *arguments) + + def _function(self, identifier: int, *arguments): + address = self._query(identifier) + if not address: + raise OSError(f"NVIDIA API function 0x{identifier:08X} unavailable") + return ctypes.CFUNCTYPE(ctypes.c_int32, *arguments)(address) + + @staticmethod + def _check(status: int, operation: str) -> None: + if status != 0: + raise OSError(f"NVIDIA {operation} failed (status {status})") + + def transfer(self, command: int, data: bytes, *, read: bool = False) -> bytes: + register = (_U8 * 1)(command) + buffer = (_U8 * len(data)).from_buffer_copy(data) + info = _I2cInfo() + info.version = ctypes.sizeof(_I2cInfo) | (3 << 16) + info.address = _CONTROLLER_ADDRESS << 1 + info.register, info.register_size = register, 1 + info.data, info.size = buffer, len(data) + info.speed = 0xFFFF + info.port, info.port_set = 1, 1 + unknown = _U32() + operation = self._read if read else self._write + self._check(operation(self._handle, ctypes.byref(info), ctypes.byref(unknown)), "I2C transfer") + if info.size != len(data): + raise OSError(f"NVIDIA I2C transferred {info.size} bytes; expected {len(data)}") + return bytes(buffer) + + +class AsusGpuLeds: + def __init__(self, bus_factory: Callable[[], NvidiaI2c] = NvidiaI2c) -> None: + self._factory = bus_factory + self._bus: NvidiaI2c | None = None + self.led_count = 0 + self._original_direct = 0 + self._original_colors: tuple[Rgb, ...] = () + self._shown: tuple[Rgb, ...] | None = None + self._claimed = False + + def _select(self, register: int) -> None: + assert self._bus is not None + self._bus.transfer(0, register.to_bytes(2, "big")) + + def _read_register(self, register: int) -> int: + self._select(register) + assert self._bus is not None + return self._bus.transfer(0x81, bytes(1), read=True)[0] + + def _write_register(self, register: int, value: int) -> None: + self._select(register) + assert self._bus is not None + self._bus.transfer(1, bytes((value,))) + + def open(self) -> None: + if any("lightingservice" in name or "armoury" in name or "aura" in name + for name in _process_names()): + raise OSError("GPU lighting busy: exit ASUS lighting software") + if corsair_software_running("ASUS ROG STRIX GeForce RTX 4090 Gaming OC", fan_tools=False): + raise OSError("GPU lighting busy: exit other RGB software") + self._bus = self._factory() + version = bytes(self._read_register(0x1000 + i) for i in range(16)).split(b"\0", 1)[0] + if version.decode("ascii", errors="replace") not in _FIRMWARE: + raise OSError(f"Unsupported GPU LED firmware: {version!r}") + self.led_count = self._read_register(0x1C03) + if not 1 <= self.led_count <= 32: + raise OSError(f"Unexpected GPU LED count: {self.led_count}") + self._original_direct = self._read_register(0x8020) + if self._original_direct not in (0, 1): + raise OSError(f"Unexpected GPU direct-mode state: {self._original_direct}") + raw = [self._read_register(0x8100 + i) for i in range(self.led_count * 3)] + self._original_colors = tuple((raw[i], raw[i + 2], raw[i + 1]) + for i in range(0, len(raw), 3)) + log.info("GPU lighting identified: %s, %d LEDs", version.decode("ascii"), self.led_count) + + def _write_colors(self, colors: tuple[Rgb, ...], previous: tuple[Rgb, ...] | None) -> None: + assert self._bus is not None + for led, (red, green, blue) in enumerate(colors): + if previous is not None and colors[led] == previous[led]: + continue + self._select(0x8100 + led * 3) + self._bus.transfer(3, bytes((3, red, blue, green))) + + def show_frame(self, colors: tuple[Rgb, ...]) -> None: + if len(colors) != self.led_count or any( + len(color) != 3 or any(type(value) is not int or not 0 <= value <= 255 for value in color) + for color in colors): + raise ValueError("GPU frame must contain one valid RGB triplet per LED") + self._claimed = True + self._write_colors(colors, self._shown) + if self._shown is None: + self._write_register(0x8020, 1) + self._write_register(0x80A0, 1) + self._shown = colors + + def close(self) -> None: + try: + if self._claimed: + try: + self._write_colors(self._original_colors, None) + finally: + self._write_register(0x8020, self._original_direct) + self._write_register(0x80A0, 1) + finally: + self._bus = None + self._shown = None + self._claimed = False + + +def gpu_chase_frame(phase: float, led_count: int) -> tuple[Rgb, ...]: + if led_count < 1: + raise ValueError("GPU must have at least one LED") + if led_count == 1: + return (side_chase_color(1),) + route = tuple(range(led_count - 1, -1, -1)) + tuple(range(1, led_count - 1)) + step = math.floor((phase - SIDE_CHASE_BOTTOM_STEP) * len(route) / SIDE_CHASE_CYCLE_STEPS) + colors = [side_chase_color(0)] * led_count + for age in range(min(4, led_count - 1), -1, -1): + colors[route[(step - age) % len(route)]] = side_chase_color((5 - age) / 5) + return tuple(colors) + + +class _GpuDriver(Protocol): + led_count: int + def open(self) -> None: ... + def show_frame(self, colors: tuple[Rgb, ...]) -> None: ... + def close(self) -> None: ... + + +class GpuLighting: + def __init__(self, chase_timing: ChaseTiming, + driver_factory: Callable[[], _GpuDriver] = AsusGpuLeds) -> None: + self.status = "off" + self._clock = chase_timing + self._factory = driver_factory + self._driver: _GpuDriver | None = None + self._retry_at = 0.0 + self._last_frame_at = -math.inf + self._last_frame: tuple[Rgb, ...] | None = None + + def _status(self, status: str) -> None: + if status != self.status: + log.info("GPU lighting: %s", status) + self.status = status + + def close(self) -> None: + driver, self._driver = self._driver, None + self._last_frame = None + self._last_frame_at = -math.inf + if driver is not None: + try: + driver.close() + except OSError: + log.exception("Couldn't restore GPU lighting state") + + def update(self, enabled: bool) -> None: + if not enabled: + self.close() + self._status("off") + return + now = time.monotonic() + if self._driver is None and now < self._retry_at: + return + try: + if self._driver is None: + self._driver = self._factory() + self._driver.open() + phase, _ = self._clock.sample(now) + frame = gpu_chase_frame(phase, self._driver.led_count) + if frame != self._last_frame and now - self._last_frame_at >= MIN_CHASE_FRAME_SECONDS: + self._driver.show_frame(frame) + self._last_frame, self._last_frame_at = frame, now + self._status(f"Red chase active ({self._driver.led_count} LEDs)") + except OSError as error: + log.warning("GPU lighting unavailable: %s", error) + self.close() + self._retry_at = now + 10 + self._status(f"unavailable: {error}") + + def run(self, stop: threading.Event, enabled: threading.Event) -> None: + try: + while not stop.is_set(): + self.update(enabled.is_set()) + stop.wait(CHASE_POLL_SECONDS) + except Exception: + log.exception("GPU lighting worker failed") + self._status("worker stopped; check dashboard.log") + finally: + self.close() diff --git a/kurgan/lighting/lighting_node.py b/kurgan/lighting/lighting_node.py new file mode 100644 index 0000000..a430eda --- /dev/null +++ b/kurgan/lighting/lighting_node.py @@ -0,0 +1,146 @@ +"""Corsair Lighting Node CORE (1B1C:0C1A) driven directly over Windows HID. + +Each command is a 64-byte output report answered by a 16-byte input report whose first +byte is 0 on success. LED colours go 50 at a time, one packet per colour channel, and only +appear after a commit. The node returns to its stored hardware effect if it hears nothing +for about 20 s in software mode, so `keepalive()` re-commits every few seconds. +""" + +from __future__ import annotations + +import ctypes +import time + +from kurgan.telemetry.sensors import corsair_software_running +from kurgan.hardware.hid import HidChannel, hid_device_paths + +VID, PID = 0x1B1C, 0x0C1A +OP_FIRMWARE, OP_DIRECT, OP_COMMIT, OP_PORT_STATE = 0x02, 0x32, 0x33, 0x38 +PORT_HARDWARE, PORT_SOFTWARE = 0x01, 0x02 +LEDS_PER_PACKET = 50 +MAX_LEDS = 204 +KEEPALIVE_SECONDS = 5.0 + +_k32 = ctypes.WinDLL("kernel32", use_last_error=True) +_k32.CreateMutexW.argtypes = [ctypes.c_void_p, ctypes.c_bool, ctypes.c_wchar_p] +_k32.CreateMutexW.restype = ctypes.c_void_p +_k32.CloseHandle.argtypes = [ctypes.c_void_p] +_ERROR_ALREADY_EXISTS = 183 + + +class LightingNodeBusy(OSError): + pass + + +def direct_packets(channel: int, colors: list[tuple[int, int, int]], + previous: list[tuple[int, int, int]] | None = None) -> list[bytes]: + """Direct-colour packets for `colors`, skipping chunks whose colour channel is unchanged.""" + packets = [] + for start in range(0, len(colors), LEDS_PER_PACKET): + chunk = colors[start:start + LEDS_PER_PACKET] + old = None if previous is None else previous[start:start + LEDS_PER_PACKET] + for component in range(3): + values = bytes(color[component] for color in chunk) + if old is not None and values == bytes(color[component] for color in old): + continue + packets.append(bytes((OP_DIRECT, channel, start, len(chunk), component)) + values) + return packets + + +class LightingNodeCore: + """Open with `with LightingNodeCore() as node:` and call `show()` or `keepalive()` regularly.""" + + def __init__(self) -> None: + self.ch: HidChannel | None = None + self.firmware = "" + self._mutex: int | None = None + self._software: set[int] = set() + self._shown: dict[int, list[tuple[int, int, int]]] = {} + self._last_commit = 0.0 + + def __enter__(self) -> "LightingNodeCore": + self.open() + return self + + def __exit__(self, *exc) -> None: + self.close() + + def open(self) -> None: + if self.ch is not None: + return + if corsair_software_running("Corsair Lighting Node Core", fan_tools=False): + raise LightingNodeBusy("Lighting Node CORE busy: exit iCUE, or disable OpenRGB's " + "Corsair Lighting Node Core detector") + ctypes.set_last_error(0) + mutex = _k32.CreateMutexW(None, False, "Local\\TTLcdLightingNode") + if not mutex or ctypes.get_last_error() == _ERROR_ALREADY_EXISTS: + if mutex: + _k32.CloseHandle(mutex) + raise LightingNodeBusy("Lighting Node CORE is in use by another dashboard process") + self._mutex = mutex + try: + paths = hid_device_paths(VID, PID) + if len(paths) != 1: + raise OSError(f"Expected one Lighting Node CORE, found {len(paths)}") + self.ch = HidChannel(paths[0], 64) + reply = self._cmd(OP_FIRMWARE) + self.firmware = ".".join(str(b) for b in reply[2:5]) + except Exception: + self.close() + raise + + def close(self) -> None: + if self.ch is not None: + try: + self.release() + except OSError: + pass + self.ch.close() + self.ch = None + if self._mutex is not None: + _k32.CloseHandle(self._mutex) + self._mutex = None + + def show(self, channel: int, colors: list[tuple[int, int, int]]) -> None: + """Display `colors` on header `channel` (0 or 1), sending only what changed.""" + if channel not in (0, 1) or not 0 < len(colors) <= MAX_LEDS: + raise ValueError("Channel must be 0 or 1 with 1-204 LEDs") + if channel not in self._software: + self._cmd(OP_PORT_STATE, channel, PORT_SOFTWARE) + self._software.add(channel) + self._shown.pop(channel, None) + previous = self._shown.get(channel) + if previous is not None and len(previous) != len(colors): + previous = None + packets = direct_packets(channel, colors, previous) + for packet in packets: + self._cmd(*packet) + if packets: + self._commit() + self._shown[channel] = list(colors) + + def keepalive(self) -> None: + if self._software and time.monotonic() - self._last_commit >= KEEPALIVE_SECONDS: + self._commit() + + def release(self) -> None: + """Hand every header back to the node's stored hardware effect.""" + for channel in sorted(self._software): + self._cmd(OP_PORT_STATE, channel, PORT_HARDWARE) + self._software.clear() + self._shown.clear() + + def _commit(self) -> None: + self._cmd(OP_COMMIT, 0xFF) + self._last_commit = time.monotonic() + + def _cmd(self, *payload: int) -> bytes: + ch = self.ch + if ch is None: + raise OSError("Lighting Node CORE is not open") + ch.drain() + ch.send(bytes(payload)) + reply = ch.read(300) + if not reply or len(reply) < 2 or reply[1] != 0: # [report id, status, ...] + raise OSError(f"Lighting Node CORE didn't accept command 0x{payload[0]:02X}") + return reply diff --git a/kurgan/lighting/memory.py b/kurgan/lighting/memory.py new file mode 100644 index 0000000..33daa07 --- /dev/null +++ b/kurgan/lighting/memory.py @@ -0,0 +1,428 @@ +"""Direct, temporary RGB control for Corsair Dominator Platinum DDR5 memory.""" + +from __future__ import annotations + +import ctypes +import ctypes.wintypes as wt +import logging +import math +import os +import struct +import threading +import time +from contextlib import contextmanager +from typing import Callable, Generator, Protocol, Sequence + +from kurgan.theme import Theme +from kurgan.lighting.case_fans import ( + CHASE_POLL_SECONDS, MIN_CHASE_FRAME_SECONDS, ChaseTiming, + SIDE_CHASE_BOTTOM_STEP, SIDE_CHASE_CYCLE_STEPS, side_chase_color, +) +from kurgan.telemetry.sensors import corsair_software_running + +from kurgan.hardware import PAWNIO_DIR + +log = logging.getLogger(__name__) + +_PAWNIO_DLL = os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "PawnIO", "PawnIOLib.dll") +_SMBUS_MODULE = os.path.join(PAWNIO_DIR, "SmbusI801.bin") +_ADDRESSES = (0x18, 0x19, 0x1A, 0x1B) +_LED_COUNT = 12 +_KEEPALIVE_SECONDS = 5.0 +_RETRY_SECONDS = 10.0 +_BLACK = (0, 0, 0) +_CELL = ctypes.c_uint64 +_STATUS_ACCESS_DENIED = 0xC0000022 +_STATUS_NO_SUCH_DEVICE = 0xC000000E +_WAIT_OBJECT_0 = 0 +_WAIT_ABANDONED = 0x80 +Rgb = tuple[int, int, int] +MemoryFrame = tuple[tuple[Rgb, ...], ...] + +# Identification colours confirmed physical sticks 1-4 as addresses 0x18-0x1B. +_CHASE_ROUTE = tuple((stick, led) + for stick, inward in ((3, True), (2, False), (1, True), + (0, False), (1, True), (2, False)) + for led in (range(6) if inward else range(5, -1, -1))) +_CHASE_BOTTOM_STEP = 5 + + +def _solid_frame(color: Rgb) -> MemoryFrame: + return ((color,) * _LED_COUNT,) * len(_ADDRESSES) + + +def memory_chase_frame(step: int) -> MemoryFrame: + """Two mirrored heads travel up and down without repeating either end stick.""" + colors = [[side_chase_color(0)] * _LED_COUNT for _ in _ADDRESSES] + for age in range(4, -1, -1): + stick, led = _CHASE_ROUTE[(step - age) % len(_CHASE_ROUTE)] + colors[stick][led] = colors[stick][_LED_COUNT - 1 - led] = side_chase_color((5 - age) / 5) + return tuple(tuple(stick) for stick in colors) + + +def memory_chase_step(fan_phase: float) -> int: + return math.floor(_CHASE_BOTTOM_STEP + + (fan_phase - SIDE_CHASE_BOTTOM_STEP) * len(_CHASE_ROUTE) / SIDE_CHASE_CYCLE_STEPS) + + +class MemoryLightingBusy(OSError): + """Raised when another RGB application owns Corsair memory lighting.""" + + +class _MemoryLightingDriver(Protocol): + def open(self) -> None: ... + + def show(self, color: tuple[int, int, int]) -> None: ... + + def show_frame(self, colors: MemoryFrame, *, force: bool = False) -> None: ... + + def close(self) -> None: ... + + +def _crc8(data: bytes) -> int: + crc = 0 + for byte in data: + crc ^= byte + for _ in range(8): + crc = ((crc << 1) ^ (0x07 if crc & 0x80 else 0)) & 0xFF + return crc + + +def _rgb_bytes(color: Sequence[object]) -> bytes: + channels = [channel for channel in color if isinstance(channel, int) and not isinstance(channel, bool)] + if (len(color) != 3 or len(channels) != 3 + or any(not 0 <= channel <= 255 for channel in channels)): + raise ValueError("RGB channels must be integers from 0 to 255") + return bytes(channels) + + +def _led_packet(colors: Sequence[Sequence[object]]) -> bytes: + if len(colors) != _LED_COUNT: + raise ValueError("Each RAM stick requires exactly 12 LED colours") + payload = bytes((_LED_COUNT,)) + b"".join(_rgb_bytes(color) for color in colors) + return payload + bytes((_crc8(payload),)) + + +def _check_ntstatus(operation: str, status: int) -> None: + if status < 0: + value = status & 0xFFFFFFFF + if value == _STATUS_ACCESS_DENIED: + raise OSError(f"{operation}: PawnIO access denied; run the dashboard as administrator") + if value == _STATUS_NO_SUCH_DEVICE: + raise OSError(f"{operation}: no response from the RAM lighting controller") + raise OSError(f"{operation}: NTSTATUS 0x{value:08X}") + + +class PawnIoSmbus: + """Minimal, synchronized access to the four supported Corsair DDR5 RGB controllers.""" + + def __init__(self) -> None: + self._dll = None + self._handle = wt.HANDLE() + self._mutex = None + self._kernel32 = None + self._last_packets: dict[int, bytes] = {} + + def open(self) -> None: + if self._handle.value: + return + if not hasattr(ctypes, "WinDLL"): + raise OSError("Corsair RAM lighting requires Windows and PawnIO") + if corsair_software_running("Corsair DRAM", fan_tools=False): + raise MemoryLightingBusy("RAM lighting busy: exit iCUE or disable OpenRGB's Corsair DRAM detector") + + try: + dll = ctypes.WinDLL(_PAWNIO_DLL, use_last_error=True) + dll.pawnio_open_nt.argtypes = [ctypes.POINTER(wt.HANDLE)] + dll.pawnio_load_nt.argtypes = [wt.HANDLE, ctypes.c_char_p, ctypes.c_size_t] + dll.pawnio_execute_nt.argtypes = [ + wt.HANDLE, ctypes.c_char_p, ctypes.POINTER(_CELL), ctypes.c_size_t, + ctypes.POINTER(_CELL), ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t), + ] + dll.pawnio_execute_nt.restype = ctypes.c_int32 + dll.pawnio_close_nt.argtypes = [wt.HANDLE] + + handle = wt.HANDLE() + _check_ntstatus("Opening PawnIO", dll.pawnio_open_nt(ctypes.byref(handle))) + self._dll, self._handle = dll, handle + with open(_SMBUS_MODULE, "rb") as module_file: + module = module_file.read() + _check_ntstatus("Loading the PawnIO I801 SMBus module", + dll.pawnio_load_nt(handle, module, len(module))) + + k32 = ctypes.WinDLL("kernel32", use_last_error=True) + k32.CreateMutexW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.LPCWSTR] + k32.CreateMutexW.restype = wt.HANDLE + k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD] + k32.WaitForSingleObject.restype = wt.DWORD + k32.ReleaseMutex.argtypes = [wt.HANDLE] + k32.CloseHandle.argtypes = [wt.HANDLE] + self._kernel32 = k32 + self._mutex = k32.CreateMutexW(None, False, r"Global\Access_SMBUS.HTP.Method") + if not self._mutex: + raise ctypes.WinError(ctypes.get_last_error()) + with self._bus(): + _, _, pci_ids = self._execute(b"ioctl_identity", count=3) + if pci_ids & 0xFFFF != 0x8086: + raise OSError(f"Expected an Intel SMBus controller, found PCI IDs 0x{pci_ids:016X}") + self._verify_controllers() + except Exception: + self.close() + raise + + def close(self) -> None: + self._last_packets.clear() + if self._mutex is not None: + if self._kernel32 is None: + raise OSError("Cannot close SMBus mutex: kernel32 was not initialized") + if not self._kernel32.CloseHandle(self._mutex): + raise ctypes.WinError(ctypes.get_last_error()) + self._mutex = None + if self._handle.value and self._dll is not None: + handle, self._handle = self._handle, wt.HANDLE() + dll, self._dll = self._dll, None + _check_ntstatus("Closing PawnIO", dll.pawnio_close_nt(handle)) + + def show(self, color: tuple[int, int, int]) -> None: + self.show_frame(_solid_frame(color), force=True) + + def show_frame(self, colors: MemoryFrame, *, force: bool = False) -> None: + if len(colors) != len(_ADDRESSES): + raise ValueError("RAM frames require exactly four sticks in physical top-to-bottom order") + packets = tuple(_led_packet(stick) for stick in colors) + with self._bus(): + for address, packet in zip(_ADDRESSES, packets): + if not force and self._last_packets.get(address) == packet: + continue + self._write_block(address, 0x31, packet[:32]) + time.sleep(0.001) + self._write_block(address, 0x32, packet[32:]) + self._last_packets[address] = packet + + @contextmanager + def _bus(self) -> Generator[None, None, None]: + if self._mutex is None or self._kernel32 is None: + raise OSError("PawnIO SMBus is not open") + result = self._kernel32.WaitForSingleObject(self._mutex, 500) + if result == _WAIT_ABANDONED: + self._kernel32.ReleaseMutex(self._mutex) + raise OSError("The previous SMBus owner exited without releasing the bus") + if result != _WAIT_OBJECT_0: + raise OSError(f"Could not acquire the SMBus mutex (wait result 0x{result:08X})") + try: + yield + finally: + if not self._kernel32.ReleaseMutex(self._mutex): + raise ctypes.WinError(ctypes.get_last_error()) + + def _execute(self, operation: bytes, args: tuple[int, ...] = (), count: int = 0) -> tuple[int, ...]: + if self._dll is None or not self._handle.value: + raise OSError("PawnIO SMBus is not open") + in_buffer = (_CELL * len(args))(*args) + out_buffer = (_CELL * count)() + written = ctypes.c_size_t() + status = self._dll.pawnio_execute_nt( + self._handle, operation, in_buffer, len(in_buffer), out_buffer, len(out_buffer), + ctypes.byref(written), + ) + _check_ntstatus(operation.decode(), status) + if written.value != count: + raise OSError(f"{operation.decode()}: expected {count} output cells, got {written.value}") + return tuple(out_buffer) + + def _read_byte(self, address: int, register: int) -> int: + return self._execute(b"ioctl_smbus_xfer", (address, 1, register, 2), 1)[0] + + def _write_byte(self, address: int, register: int, value: int) -> None: + self._execute(b"ioctl_smbus_xfer", (address, 0, register, 2, value)) + + def _write_block(self, address: int, register: int, data: bytes) -> None: + if not 0 < len(data) <= 32: + raise ValueError("SMBus block data must contain 1 to 32 bytes") + packed = (bytes((len(data),)) + data).ljust(40, b"\x00") + self._execute(b"ioctl_smbus_xfer", + (address, 0, register, 5, *struct.unpack("<5Q", packed))) + + def _read_buffer(self, address: int, selector: int, index: int, length: int) -> bytes: + self._write_byte(address, selector, index) + self._write_byte(address, 0x21, 0) + data = bytes(self._read_byte(address, 0x40) for _ in range(length)) + actual = self._read_byte(address, 0x42) + expected = _crc8(data) + if actual != expected: + raise OSError(f"RAM controller 0x{address:02X} buffer CRC mismatch " + f"(0x{actual:02X} != 0x{expected:02X})") + return data + + def _verify_controllers(self) -> None: + for address in _ADDRESSES: + signature = self._read_byte(address, 0x43) + revision = self._read_byte(address, 0x44) + if signature not in (0x1A, 0x1B, 0x1C) or revision not in (1, 3, 4): + raise OSError(f"Unrecognized RAM lighting controller at 0x{address:02X}") + info = self._read_buffer(address, 0x61, 0, 32) + vendor = int.from_bytes(info[0:2], "little") + product = int.from_bytes(info[2:4], "little") + protocol = info[28] + if (vendor, product, protocol) != (0x1B1C, 0x0601, 4): + raise OSError(f"Unsupported RAM at 0x{address:02X}: " + f"{vendor:04X}:{product:04X}, RGB protocol {protocol}") + log.info("Corsair Dominator Platinum DDR5 detected at SMBus address 0x%02X", address) + + +class MemoryLighting: + """Run temperature colours or the mirrored RAM chase; disabled mode holds black.""" + + def __init__(self, theme: Theme, driver_factory: Callable[[], _MemoryLightingDriver] = PawnIoSmbus, + chase_timing: ChaseTiming | None = None): + if not (math.isfinite(theme.temp_warn) and math.isfinite(theme.temp_hot) + and theme.temp_hot > theme.temp_warn): + raise ValueError("RAM temperature range must be finite and increasing") + self.theme = theme + self.status = "off" + self._driver_factory = driver_factory + self._driver: _MemoryLightingDriver | None = None + self._retry_at = 0.0 + self._last_error: str | None = None + self._last_frame: MemoryFrame | None = None + self._last_frame_at = -math.inf + self._last_keepalive_at = -math.inf + self._touched = False + self._temperatures: tuple[float | None, float | None] = (None, None) + self._power: float | None = None + self._pattern: str | None = None + self._owns_chase_timing = chase_timing is None + self._chase_timing = chase_timing if chase_timing is not None else ChaseTiming() + if self._owns_chase_timing: + self._chase_timing.reset(SIDE_CHASE_BOTTOM_STEP) + + def run(self, stop: threading.Event, enabled: threading.Event, + side_chase: threading.Event | None = None) -> None: + try: + while not stop.is_set(): + cpu_temp, gpu_temp = self._temperatures + self.update(cpu_temp, enabled.is_set(), gpu_temp=gpu_temp, + side_chase=side_chase.is_set() if side_chase is not None else False) + stop.wait(CHASE_POLL_SECONDS) + except Exception: + log.exception("RAM lighting worker failed") + self._set_status("RAM lighting worker stopped; check dashboard.log") + finally: + self.close() + + def set_temperature(self, cpu_temp: float | None, gpu_temp: float | None = None) -> None: + self._temperatures = (cpu_temp, gpu_temp) + + def set_power(self, total_watts: float | None) -> None: + self._power = total_watts + self._chase_timing.set_power(total_watts) + + def update(self, cpu_temp: float | None, enabled: bool, *, gpu_temp: float | None = None, + side_chase: bool = False) -> None: + now = time.monotonic() + pattern = "chase" if side_chase else "temperature" if enabled else None + if pattern != self._pattern: + self._pattern = pattern + if self._owns_chase_timing: + self._chase_timing.reset(SIDE_CHASE_BOTTOM_STEP) + self._last_frame_at = -math.inf + readings = [(temp, source) for temp, source in ((cpu_temp, "CPU"), (gpu_temp, "GPU")) + if temp is not None and math.isfinite(temp)] + reading = max(readings, key=lambda item: item[0]) if readings else None + color = None + if reading is not None: + strength = min(1.0, max(0.0, (reading[0] - self.theme.temp_warn) + / (self.theme.temp_hot - self.theme.temp_warn))) + color = side_chase_color(strength) + + if side_chase: + phase, rate = self._chase_timing.sample(now) + target = memory_chase_frame(memory_chase_step(phase)) + elif enabled and color is None: + if self._driver is None and not self._touched: + self._set_status("RAM temperature lighting waiting for CPU/GPU temperature") + return + target = self._last_frame + if target is None: + self._set_status("RAM temperature lighting waiting for CPU/GPU temperature") + return + elif enabled: + assert color is not None + target = _solid_frame(color) + else: + target = _solid_frame(_BLACK) + + if self._driver is None: + if now < self._retry_at: + return + try: + driver = self._driver_factory() + driver.open() + except OSError as error: + self._fail(error) + return + self._driver = driver + self._last_error = None + log.info("RAM lighting SMBus opened") + + assert target is not None + keepalive = now - self._last_keepalive_at >= _KEEPALIVE_SECONDS + if ((target != self._last_frame or keepalive) + and (not side_chase or now - self._last_frame_at >= MIN_CHASE_FRAME_SECONDS)): + try: + self._driver.show_frame(target, force=keepalive) + except OSError as error: + self._fail(error) + return + self._last_frame = target + self._last_frame_at = now + if keepalive: + self._last_keepalive_at = now + self._touched = True + + if side_chase: + watts = "" if self._power is None else f" at {self._power:.0f} W" + self._set_status(f"RAM red side chase active ({SIDE_CHASE_CYCLE_STEPS / rate:.1f} s/cycle{watts})") + elif enabled and color is None: + self._set_status("RAM temperature lighting waiting for CPU/GPU temperature") + elif enabled: + assert reading is not None + self._set_status(f"RAM temperature lighting active ({reading[1]} {reading[0]:.0f} \u00b0C)") + else: + self._set_status("RAM lighting off") + + def close(self) -> None: + driver, self._driver = self._driver, None + if driver is not None: + if self._touched: + try: + driver.show(_BLACK) + except OSError: + log.exception("Couldn't leave RAM lighting dark") + try: + driver.close() + except OSError: + log.exception("Couldn't release the RAM lighting SMBus") + self._last_frame = None + self._last_keepalive_at = -math.inf + self._set_status("off") + + def _fail(self, error: OSError) -> None: + driver, self._driver = self._driver, None + if driver is not None: + try: + driver.close() + except OSError: + log.exception("Couldn't close the failed RAM lighting SMBus") + self._last_frame = None + self._last_keepalive_at = -math.inf + self._retry_at = time.monotonic() + _RETRY_SECONDS + message = str(error) or type(error).__name__ + self._set_status(message) + if message != self._last_error: + log.warning("RAM lighting unavailable: %s", message, exc_info=not isinstance(error, MemoryLightingBusy)) + self._last_error = message + + def _set_status(self, status: str) -> None: + if status != self.status: + self.status = status diff --git a/kurgan/lighting/service.py b/kurgan/lighting/service.py new file mode 100644 index 0000000..f4fa41c --- /dev/null +++ b/kurgan/lighting/service.py @@ -0,0 +1,108 @@ +"""Lighting service: one worker per device, one mode per zone, saved in settings.json. + +Zones and their modes (see kurgan.settings.LIGHTING_MODES): + case_fans Lighting Node CORE QL120 LEDs: off (hardware effect), temperature, chase + memory Dominator DDR5: off (held dark while running), temperature, chase + gpu ASUS RTX 4090 LED row: off (its own effect), chase + +The three chases share one power-paced clock, so they stay in step. +""" + +from __future__ import annotations + +import logging +import threading + +from kurgan.lighting.case_fans import SIDE_CHASE_BOTTOM_STEP, ChaseTiming, RGBLighting +from kurgan.lighting.gpu import GpuLighting +from kurgan.lighting.memory import MemoryLighting +from kurgan.settings import LIGHTING_MODES, Settings +from kurgan.theme import Theme + +log = logging.getLogger(__name__) + +ZONE_LABELS = {"case_fans": "Case fan LEDs", "memory": "RAM", "gpu": "GPU"} +MODE_LABELS = {"off": "Off", "temperature": "Temperature", "chase": "Red side chase"} + + +class LightingService: + def __init__(self, settings: Settings, theme: Theme, chase: tuple[float, float, float, float], + overrides: dict[str, str] | None = None, *, rgb=None, memory=None, gpu=None): + """chase: (idle s/LED, full-power s/LED, idle watts, full watts). + overrides: modes for this run only (CLI flags), not saved.""" + self._settings = settings + self._lock = threading.Lock() + self._events = {zone: {mode: threading.Event() for mode in modes if mode != "off"} + for zone, modes in LIGHTING_MODES.items()} + self._overridden = set(overrides or ()) + modes = settings.section("lighting") + modes.update(overrides or {}) + self._modes: dict[str, str] = {} + for zone, mode in modes.items(): + self._apply(zone, mode) + step, fast, idle_w, full_w = chase + self.timing = ChaseTiming(step, fast, (idle_w, full_w)) + self.timing.reset(SIDE_CHASE_BOTTOM_STEP) + self.rgb = rgb or RGBLighting(theme, step, fast, (idle_w, full_w), chase_timing=self.timing) + self.memory = memory or MemoryLighting(theme, chase_timing=self.timing) + self.gpu = gpu or GpuLighting(self.timing) + self._threads: list[threading.Thread] = [] + self._power: float | None = None + + def _apply(self, zone: str, mode: str) -> None: + events = self._events[zone] + # Clear the old pattern before setting the new one, as the tray always did. + for name, event in events.items(): + if name != mode: + event.clear() + if mode != "off": + events[mode].set() + self._modes[zone] = mode + + def start(self, stop: threading.Event) -> None: + e = self._events + for name, target, args in ( + ("case-fan-lighting", self.rgb.run, (stop, e["case_fans"]["temperature"], e["case_fans"]["chase"])), + ("memory-lighting", self.memory.run, (stop, e["memory"]["temperature"], e["memory"]["chase"])), + ("gpu-lighting", self.gpu.run, (stop, e["gpu"]["chase"]))): + thread = threading.Thread(target=target, args=args, name=name, daemon=True) + thread.start() + self._threads.append(thread) + + def join(self) -> None: + for thread in self._threads: + thread.join() + + def on_telemetry(self, cpu_temp: float | None, gpu_temp: float | None, total_watts: float | None) -> None: + self._power = total_watts + self.rgb.set_temperature(cpu_temp, gpu_temp) + self.rgb.set_power(total_watts) + self.memory.set_temperature(cpu_temp, gpu_temp) + self.memory.set_power(total_watts) + + def mode(self, zone: str) -> str: + return self._modes[zone] + + def set_mode(self, zone: str, mode: str) -> None: + """Save first, then switch, so a failed save leaves the lighting as it was.""" + if zone not in LIGHTING_MODES or mode not in LIGHTING_MODES[zone]: + raise ValueError(f"Unknown lighting {zone!r} mode {mode!r}") + with self._lock: + self._settings.update("lighting", **{zone: mode}) + self._overridden.discard(zone) + self._apply(zone, mode) + log.info("%s lighting: %s", ZONE_LABELS[zone], mode) + + def statuses(self) -> dict[str, str]: + return {"case_fans": self.rgb.status, "memory": self.memory.status, "gpu": self.gpu.status} + + def snapshot(self) -> dict: + statuses = self.statuses() + # The eased rate once a chase is running; the target rate for the current power until then. + rate = self.timing.rate or self.timing.rate_for(self._power) + chasing = "chase" in self._modes.values() + return {"chase_ms_per_led": round(1000 / rate) if chasing else None, + "zones": [{"key": zone, "label": ZONE_LABELS[zone], "mode": self._modes[zone], + "modes": [{"key": m, "label": MODE_LABELS[m]} for m in modes], + "status": statuses[zone], "this_run_only": zone in self._overridden} + for zone, modes in LIGHTING_MODES.items()]} diff --git a/kurgan/paths.py b/kurgan/paths.py new file mode 100644 index 0000000..b877c54 --- /dev/null +++ b/kurgan/paths.py @@ -0,0 +1,16 @@ +"""Where The Kurgan keeps its settings and logs.""" + +import os + +_LOCAL = os.environ.get("LOCALAPPDATA", os.path.expanduser("~")) + +# KURGAN_DATA_DIR moves settings and logs elsewhere (used by --demo runs next to the real service). +DATA_DIR = os.environ.get("KURGAN_DATA_DIR") or os.path.join(_LOCAL, "Kurgan") +LOG_PATH = os.path.join(DATA_DIR, "kurgan.log") +SETTINGS_PATH = os.path.join(DATA_DIR, "settings.json") + +# The TT LCD Dashboard's folder; its fan and lighting settings are imported once on first start. +LEGACY_DIR = os.path.join(_LOCAL, "TTLcdDashboard") + +PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__)) +PROJECT_DIR = os.path.dirname(PACKAGE_DIR) diff --git a/kurgan/settings.py b/kurgan/settings.py new file mode 100644 index 0000000..64e4388 --- /dev/null +++ b/kurgan/settings.py @@ -0,0 +1,220 @@ +"""The Kurgan's settings: one JSON file, validated when loaded and before every save. + +%LOCALAPPDATA%\\Kurgan\\settings.json, for example: + + { + "cooling": {"gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5], + "profile": "balanced"}, + "lighting": {"case_fans": "chase", "memory": "off", "gpu": "off"}, + "ai": {"active": "strata", "strata_model": "q5", "idle_stop_minutes": 40}, + "web": {"port": 8080} + } + +The fan port mapping is written by `python -m kurgan.cooling.control --save-ports ...`; the +rest by the web UI. An invalid file stops The Kurgan from starting rather than silently +dropping fan control. On first start the TT LCD Dashboard's settings are imported. +""" + +from __future__ import annotations + +import argparse +import copy +import json +import logging +import os +import threading + +from kurgan import paths +from kurgan.ai import config as ai_config +from kurgan.cooling.profiles import DEFAULT_PROFILE, PROFILES + +log = logging.getLogger(__name__) + +LIGHTING_MODES = { + "case_fans": ("off", "temperature", "chase"), # Lighting Node CORE (QL120 fan LEDs) + "memory": ("off", "temperature", "chase"), # Dominator Platinum DDR5 + "gpu": ("off", "chase"), # ASUS ROG STRIX RTX 4090 +} +DEFAULT_WEB_PORT = 8080 + +DEFAULTS = { + "cooling": {"profile": DEFAULT_PROFILE}, + "lighting": {zone: "off" for zone in LIGHTING_MODES}, + "ai": {"active": None, "strata_model": ai_config.STRATA_DEFAULT_MODEL, + "idle_stop_minutes": ai_config.IDLE_STOP_MINUTES}, + "web": {"port": DEFAULT_WEB_PORT}, +} +_OPTIONAL = { + "cooling": {"gpu_ports", "cpu_ports", "top_channels"}, + "lighting": set(), + "ai": {"strata_root", "strata_port", "llama_server", "llama_presets", "llama_model", "llama_port"}, + "web": set(), +} + + +class SettingsError(ValueError): + pass + + +def _ports(value, where: str) -> list[int]: + from kurgan.cooling.control import parse_ports + + if not isinstance(value, list) or any(type(v) is not int for v in value): + raise SettingsError(f"{where} must be an array of integers") + try: + return list(parse_ports(",".join(map(str, value)))) + except argparse.ArgumentTypeError as e: + raise SettingsError(f"{where}: {e}") from None + + +def _port_number(value, where: str) -> int: + if type(value) is not int or not 1024 <= value <= 65535: + raise SettingsError(f"{where} must be a TCP port number 1024-65535") + return value + + +def validate(data: object) -> dict: + """Return a normalised copy with defaults filled in, or raise SettingsError.""" + if not isinstance(data, dict): + raise SettingsError("settings must be a JSON object") + unknown = set(data) - set(DEFAULTS) + if unknown: + raise SettingsError(f"unknown section(s): {', '.join(sorted(unknown))}") + out = copy.deepcopy(DEFAULTS) + for section, values in data.items(): + if not isinstance(values, dict): + raise SettingsError(f"{section} must be an object") + bad = set(values) - set(DEFAULTS[section]) - _OPTIONAL[section] + if bad: + raise SettingsError(f"{section}: unknown setting(s): {', '.join(sorted(bad))}") + out[section].update(values) + + cooling = out["cooling"] + if cooling["profile"] not in PROFILES: + raise SettingsError(f"cooling.profile must be one of {', '.join(PROFILES)}") + if ("cpu_ports" in cooling or "top_channels" in cooling) and "gpu_ports" not in cooling: + raise SettingsError("cooling: save the GPU-side ports (gpu_ports) first") + for key in ("gpu_ports", "cpu_ports"): + if key in cooling: + cooling[key] = _ports(cooling[key], f"cooling.{key}") + if set(cooling.get("cpu_ports", ())) & set(cooling.get("gpu_ports", ())): + raise SettingsError("cooling: cpu_ports and gpu_ports must not overlap") + if "top_channels" in cooling: + from kurgan.cooling.board_fans import parse_channels + + value = cooling["top_channels"] + if not isinstance(value, list) or any(type(v) is not int for v in value): + raise SettingsError("cooling.top_channels must be an array of integers") + try: + cooling["top_channels"] = list(parse_channels(",".join(map(str, value)))) + except argparse.ArgumentTypeError as e: + raise SettingsError(f"cooling.top_channels: {e}") from None + + for zone, modes in LIGHTING_MODES.items(): + if out["lighting"][zone] not in modes: + raise SettingsError(f"lighting.{zone} must be one of {', '.join(modes)}") + + ai = out["ai"] + if ai["active"] is not None and ai["active"] not in ai_config.BACKENDS: + raise SettingsError(f"ai.active must be null or one of {', '.join(ai_config.BACKENDS)}") + if ai["strata_model"] not in ai_config.STRATA_MODELS: + raise SettingsError(f"ai.strata_model must be one of {', '.join(ai_config.STRATA_MODELS)}") + if type(ai["idle_stop_minutes"]) is not int or not 0 <= ai["idle_stop_minutes"] <= 1440: + raise SettingsError("ai.idle_stop_minutes must be 0 (never) to 1440") + for key in ("strata_root", "llama_server", "llama_presets", "llama_model"): + if key in ai and (not isinstance(ai[key], str) or not ai[key]): + raise SettingsError(f"ai.{key} must be a non-empty string") + for key in ("strata_port", "llama_port"): + if key in ai: + _port_number(ai[key], f"ai.{key}") + if ai.get("strata_port", ai_config.STRATA_PORT) == ai.get("llama_port", ai_config.LLAMA_PORT): + raise SettingsError("ai: Strata and llama.cpp need different ports") + _port_number(out["web"]["port"], "web.port") + return out + + +def write_json_atomic(path: str, data: dict) -> None: + os.makedirs(os.path.dirname(path), exist_ok=True) + temporary = path + ".tmp" + try: + with open(temporary, "w", encoding="utf-8") as stream: + json.dump(data, stream, indent=2) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.remove(temporary) + + +def _legacy(legacy_dir: str) -> dict: + """The TT LCD Dashboard's fan-control.json, memory-lighting.json and gpu-lighting.json.""" + data: dict = {} + + def read(name: str): + try: + with open(os.path.join(legacy_dir, name), encoding="utf-8") as stream: + return json.load(stream) + except FileNotFoundError: + return None + except ValueError as e: + raise SettingsError(f"{legacy_dir}\\{name}: {e}") from None + + fans = read("fan-control.json") + if fans is not None: + if not isinstance(fans, dict) or not set(fans) <= {"gpu_ports", "cpu_ports", "top_channels"}: + raise SettingsError(f"{legacy_dir}\\fan-control.json has unexpected contents") + data["cooling"] = dict(fans) + for name, zone in (("memory-lighting.json", "memory"), ("gpu-lighting.json", "gpu")): + mode = read(name) + if mode is not None: + if not isinstance(mode, dict) or set(mode) != {"mode"}: + raise SettingsError(f"{legacy_dir}\\{name} has unexpected contents") + data.setdefault("lighting", {})[zone] = mode["mode"] + return data + + +class Settings: + """Thread-safe: the web server, the tray and the CLI all go through update().""" + + def __init__(self, path: str = paths.SETTINGS_PATH, legacy_dir: str | None = paths.LEGACY_DIR, + seed: dict | None = None): + """seed: values applied only when the file is first created (e.g. the old task's CLI flags).""" + self.path = path + self._lock = threading.RLock() + self.created = False + try: + with open(path, encoding="utf-8") as stream: + raw = json.load(stream) + except FileNotFoundError: + raw = _legacy(legacy_dir) if legacy_dir else {} + for section, values in (seed or {}).items(): + raw.setdefault(section, {}).update(values) + self.created = True + except ValueError as e: + raise SettingsError(f"{path}: {e}") from None + try: + self._data = validate(raw) + except SettingsError as e: + raise SettingsError(f"{path}: {e}") from None + if self.created: + write_json_atomic(path, self._data) + log.info("Created %s%s", path, " from the TT LCD Dashboard's settings" if raw else "") + + def section(self, name: str) -> dict: + with self._lock: + return copy.deepcopy(self._data[name]) + + def get(self, section: str, key: str, default=None): + with self._lock: + return copy.deepcopy(self._data[section].get(key, default)) + + def update(self, section: str, **changes) -> None: + """Validate and save; on any error nothing changes, in memory or on disk.""" + with self._lock: + data = copy.deepcopy(self._data) + data[section].update(changes) + data = validate(data) + write_json_atomic(self.path, data) + self._data = data diff --git a/kurgan/telemetry/__init__.py b/kurgan/telemetry/__init__.py new file mode 100644 index 0000000..379d241 --- /dev/null +++ b/kurgan/telemetry/__init__.py @@ -0,0 +1 @@ +"""Telemetry: CPU, GPU and whole-PC power readings, sampled once for every consumer.""" diff --git a/kurgan/telemetry/readings.py b/kurgan/telemetry/readings.py new file mode 100644 index 0000000..64bb5f1 --- /dev/null +++ b/kurgan/telemetry/readings.py @@ -0,0 +1,27 @@ +"""Sensor readings shared by the LCD, lighting, cooling and the web UI.""" + +from __future__ import annotations + +from dataclasses import dataclass, field + + +@dataclass +class Readings: + temp: float | None = None # deg C + load: float | None = None # percent + clock: float | None = None # MHz + power: float | None = None # W + + +@dataclass +class PowerReadings: + cpu: float | None = None # W, CPU package (measured) + gpu: float | None = None # W, graphics card board power (measured) + other: float | None = None # W, rest of the PC (partly measured, partly estimated) + parts: dict[str, float] = field(default_factory=dict) # what makes up `other` + + @property + def total(self) -> float | None: + if self.cpu is None or self.gpu is None or self.other is None: + return None + return self.cpu + self.gpu + self.other diff --git a/kurgan/telemetry/sensors.py b/kurgan/telemetry/sensors.py new file mode 100644 index 0000000..ade8e80 --- /dev/null +++ b/kurgan/telemetry/sensors.py @@ -0,0 +1,877 @@ +"""Hardware readings for the dashboard (Windows). + +CPU load / clock : Windows performance counters (no admin needed) +CPU temp / power : Intel MSRs via the PawnIO driver (needs PawnIO installed and admin) +GPU load : Windows GPU Engine counters, i.e. the Task Manager figure (NVML as fallback) +GPU temp etc. : NVIDIA NVML (nvidia-ml-py) +Everything else : SystemPower, which adds up the rest of the PC. Fan speeds come from a Corsair + Commander PRO, drive activity from performance counters, drive ratings from the + NVMe drives themselves and the memory layout from the BIOS (SMBIOS). Parts with no + sensor at all use the fixed figures in PowerModel. + +Run `python sensors.py` for a live breakdown of where the watts go. +""" + +from __future__ import annotations + +import ctypes +import ctypes.wintypes as wt +import json +import logging +import os +import struct +import threading +import time +from dataclasses import dataclass + +from kurgan.hardware import PAWNIO_DIR +from kurgan.hardware.hid import HidChannel, hid_device_paths +from kurgan.telemetry.readings import PowerReadings, Readings + +log = logging.getLogger(__name__) + + +# ----------------------------------------------------------------------------- PDH + +class _PdhValue(ctypes.Structure): + _fields_ = [("CStatus", wt.DWORD), ("_pad", wt.DWORD), ("doubleValue", ctypes.c_double)] + + +class _PdhItem(ctypes.Structure): + _fields_ = [("szName", wt.LPWSTR), ("FmtValue", _PdhValue)] + + +PDH_FMT_DOUBLE = 0x00000200 +PDH_FMT_NOCAP100 = 0x00008000 +PDH_MORE_DATA = 0x800007D2 +_pdh_dll = None + + +def _pdh(): + global _pdh_dll + if _pdh_dll is None: + p = ctypes.WinDLL("pdh") + p.PdhOpenQueryW.argtypes = [wt.LPCWSTR, ctypes.c_size_t, ctypes.POINTER(wt.HANDLE)] + p.PdhAddEnglishCounterW.argtypes = [wt.HANDLE, wt.LPCWSTR, ctypes.c_size_t, ctypes.POINTER(wt.HANDLE)] + p.PdhCollectQueryData.argtypes = [wt.HANDLE] + p.PdhGetFormattedCounterValue.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.DWORD), + ctypes.POINTER(_PdhValue)] + p.PdhGetFormattedCounterArrayW.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.DWORD), + ctypes.POINTER(wt.DWORD), ctypes.c_void_p] + p.PdhGetFormattedCounterArrayW.restype = wt.DWORD + _pdh_dll = p + return _pdh_dll + + +def _pdh_query() -> wt.HANDLE: + q = wt.HANDLE() + if _pdh().PdhOpenQueryW(None, 0, ctypes.byref(q)) != 0: + raise OSError("PdhOpenQuery failed") + return q + + +class PerfCounters: + def __init__(self, paths: dict[str, str]): + self._pdh = _pdh() + self.query = _pdh_query() + self.counters: dict[str, wt.HANDLE] = {} + for name, path in paths.items(): + h = wt.HANDLE() + if self._pdh.PdhAddEnglishCounterW(self.query, path, 0, ctypes.byref(h)) == 0: + self.counters[name] = h + else: + log.warning("Performance counter unavailable: %s", path) + self._pdh.PdhCollectQueryData(self.query) + + def sample(self) -> dict[str, float | None]: + self._pdh.PdhCollectQueryData(self.query) + out: dict[str, float | None] = {} + for name, h in self.counters.items(): + v = _PdhValue() + st = self._pdh.PdhGetFormattedCounterValue(h, PDH_FMT_DOUBLE | PDH_FMT_NOCAP100, None, ctypes.byref(v)) + out[name] = v.doubleValue if st == 0 else None + return out + + +class PdhArray: + """Every instance of a wildcard counter, e.g. \\PhysicalDisk(*)\\% Idle Time.""" + + def __init__(self, path: str): + self._pdh = _pdh() + self.query = _pdh_query() + self.counter = wt.HANDLE() + if self._pdh.PdhAddEnglishCounterW(self.query, path, 0, ctypes.byref(self.counter)) != 0: + raise OSError(f"Performance counter unavailable: {path}") + self._pdh.PdhCollectQueryData(self.query) + + def sample(self) -> list[tuple[str, float]] | None: + self._pdh.PdhCollectQueryData(self.query) + fmt = PDH_FMT_DOUBLE | PDH_FMT_NOCAP100 + size, count = wt.DWORD(0), wt.DWORD(0) + st = self._pdh.PdhGetFormattedCounterArrayW(self.counter, fmt, ctypes.byref(size), ctypes.byref(count), None) + if st != PDH_MORE_DATA or not size.value: + return None + buf = (ctypes.c_byte * size.value)() + if self._pdh.PdhGetFormattedCounterArrayW(self.counter, fmt, ctypes.byref(size), ctypes.byref(count), buf) != 0: + return None + # from_buffer, not ctypes.cast: cast makes buf reference itself, so each ~100 KB buffer + # (GPU Engine has hundreds of instances) waited for the cycle collector instead of being freed here. + items = (_PdhItem * count.value).from_buffer(buf) + return [(items[i].szName, items[i].FmtValue.doubleValue) for i in range(count.value) + if items[i].FmtValue.CStatus in (0, 1)] # PDH_CSTATUS_VALID_DATA / NEW_DATA + + +# ----------------------------------------------------------------------------- GPU load as Task Manager shows it + +def nvidia_adapter_luid() -> str | None: + """LUID of the NVIDIA adapter as it appears in GPU Engine counter names ("0xHHHHHHHH_0xLLLLLLLL").""" + + class LUID(ctypes.Structure): + _fields_ = [("LowPart", wt.DWORD), ("HighPart", wt.LONG)] + + class DESC1(ctypes.Structure): + _fields_ = [("Description", wt.WCHAR * 128), ("VendorId", wt.UINT), ("DeviceId", wt.UINT), + ("SubSysId", wt.UINT), ("Revision", wt.UINT), ("DedicatedVideoMemory", ctypes.c_size_t), + ("DedicatedSystemMemory", ctypes.c_size_t), ("SharedSystemMemory", ctypes.c_size_t), + ("AdapterLuid", LUID), ("Flags", wt.UINT)] + + class GUID(ctypes.Structure): + _fields_ = [("a", wt.DWORD), ("b", wt.WORD), ("c", wt.WORD), ("d", ctypes.c_ubyte * 8)] + + def vcall(obj, index, restype, *argtypes): + vtbl = ctypes.cast(obj, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents + return ctypes.WINFUNCTYPE(restype, ctypes.c_void_p, *argtypes)(vtbl[index]) + + iid_factory1 = GUID(0x770AAE78, 0xF26F, 0x4DBA, (ctypes.c_ubyte * 8)(0xA8, 0x29, 0x25, 0x3C, 0x83, 0xD1, 0xB3, 0x87)) + factory = ctypes.c_void_p() + if ctypes.WinDLL("dxgi").CreateDXGIFactory1(ctypes.byref(iid_factory1), ctypes.byref(factory)) != 0: + return None + best = None + try: + i = 0 + while True: + adapter = ctypes.c_void_p() + # IDXGIFactory1::EnumAdapters1 (vtable 12) + if vcall(factory, 12, ctypes.c_long, wt.UINT, ctypes.POINTER(ctypes.c_void_p))(factory, i, ctypes.byref(adapter)) != 0: + break + desc = DESC1() + # IDXGIAdapter1::GetDesc1 (vtable 10) + vcall(adapter, 10, ctypes.c_long, ctypes.POINTER(DESC1))(adapter, ctypes.byref(desc)) + vcall(adapter, 2, wt.ULONG)(adapter) # Release + if desc.VendorId == 0x10DE and (best is None or desc.DedicatedVideoMemory > best[0]): + luid = f"0x{desc.AdapterLuid.HighPart & 0xFFFFFFFF:08X}_0x{desc.AdapterLuid.LowPart:08X}" + best = (desc.DedicatedVideoMemory, luid) + i += 1 + finally: + vcall(factory, 2, wt.ULONG)(factory) + return best[1] if best else None + + +class GpuEngineLoad: + """GPU utilisation computed the way Task Manager does it. + + Windows reports, per process and per GPU engine, how much of the time that engine had + work. Task Manager adds the processes up per engine and shows the busiest engine. NVML + instead reports the time a kernel was actually executing, which reads ~10% lower for + queue-heavy workloads. + """ + + def __init__(self, luid: str): + self.luid = f"luid_{luid}".lower() + self.counter = PdhArray(r"\GPU Engine(*)\Utilization Percentage") + + def sample(self) -> float | None: + items = self.counter.sample() + if items is None: + return None + engines: dict[str, float] = {} + for name, value in items: + name = name.lower() + pos = name.find(self.luid) + if pos < 0: + continue + key = name[pos:] # luid_..._phys_N_eng_N_engtype_X (drops the pid_ prefix) + engines[key] = engines.get(key, 0.0) + value + if not engines: + return 0.0 + return min(100.0, max(engines.values())) + + +# ----------------------------------------------------------------------------- PawnIO / Intel MSR + +class IntelMsr: + """Reads Intel MSRs through PawnIO's signed IntelMSR module.""" + + DEVICE = r"\\?\GLOBALROOT\Device\PawnIO" + IOCTL_LOAD_BINARY = (41394 << 16) | (0x821 << 2) # 0xA1B22084 + IOCTL_EXECUTE_FN = (41394 << 16) | (0x841 << 2) # 0xA1B22104 + MODULE = os.path.join(PAWNIO_DIR, "IntelMSR.bin") + + def __init__(self): + k32 = ctypes.WinDLL("kernel32", use_last_error=True) + k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE] + k32.CreateFileW.restype = wt.HANDLE + k32.DeviceIoControl.argtypes = [wt.HANDLE, wt.DWORD, ctypes.c_void_p, wt.DWORD, ctypes.c_void_p, wt.DWORD, + ctypes.POINTER(wt.DWORD), ctypes.c_void_p] + k32.DeviceIoControl.restype = wt.BOOL + k32.CloseHandle.argtypes = [wt.HANDLE] + k32.GetCurrentThread.restype = wt.HANDLE + k32.SetThreadAffinityMask.argtypes = [wt.HANDLE, ctypes.c_size_t] + k32.SetThreadAffinityMask.restype = ctypes.c_size_t + self._k32 = k32 + h = k32.CreateFileW(self.DEVICE, 0xC0000000, 0x3, None, 3, 0, None) + if h == wt.HANDLE(-1).value: + err = ctypes.get_last_error() + reason = "run as administrator" if err == 5 else "is PawnIO installed?" + raise OSError(f"Cannot open PawnIO ({ctypes.FormatError(err).strip()}; {reason})") + self.handle = h + with open(self.MODULE, "rb") as f: + blob = f.read() + buf = ctypes.create_string_buffer(blob, len(blob)) + ret = wt.DWORD() + if not k32.DeviceIoControl(h, self.IOCTL_LOAD_BINARY, buf, len(blob), None, 0, ctypes.byref(ret), None): + err = ctypes.get_last_error() + k32.CloseHandle(h) + raise OSError(f"PawnIO refused the IntelMSR module: {ctypes.FormatError(err).strip()}") + + def close(self) -> None: + if self.handle: + self._k32.CloseHandle(self.handle) + self.handle = None + + def read(self, msr: int, cpu: int | None = None) -> int: + name = b"ioctl_read_msr".ljust(32, b"\x00") + inbuf = ctypes.create_string_buffer(name + struct.pack("> 16) & 0xFF + self.tjmax = tjmax if 60 <= tjmax <= 125 else 100 + unit_bits = (self.msr.read(self.MSR_RAPL_POWER_UNIT) >> 8) & 0x1F + self.energy_unit = 1.0 / (1 << unit_bits) + self._last_energy = self.msr.read(self.MSR_PKG_ENERGY_STATUS) & 0xFFFFFFFF + self._last_time = time.perf_counter() + log.info("PawnIO OK: TjMax %d C, energy unit %.3g J", self.tjmax, self.energy_unit) + + def temperature(self) -> float | None: + v = self.msr.read(self.MSR_PACKAGE_THERM_STATUS, cpu=0) + readout = (v >> 16) & 0x7F # degrees below TjMax + # Bit 31 ("reading valid") is documented for the per-core MSR; not every CPU sets it + # for the package MSR, so also accept any non-zero readout. + if not (v & 0x80000000) and readout == 0: + return None + return float(self.tjmax - readout) + + def power(self) -> float | None: + now = time.perf_counter() + e = self.msr.read(self.MSR_PKG_ENERGY_STATUS) & 0xFFFFFFFF + dt = now - self._last_time + if dt < 0.05: + return None + delta = (e - self._last_energy) & 0xFFFFFFFF + self._last_energy, self._last_time = e, now + return delta * self.energy_unit / dt + + +# ----------------------------------------------------------------------------- CPU + +class CpuSensors: + def __init__(self): + base = r"\Processor Information(_Total)" + self.pdh = PerfCounters({ + "utility": base + r"\% Processor Utility", + "time": base + r"\% Processor Time", + "perf": base + r"\% Processor Performance", + "freq": base + r"\Processor Frequency", + }) + self.pkg: IntelPackage | None = None + self._pkg_error: str | None = None + self._next_pkg_attempt = 0.0 + self._try_pkg() + + def _try_pkg(self) -> None: + if self.pkg or time.monotonic() < self._next_pkg_attempt: + return + try: + self.pkg = IntelPackage() + self._pkg_error = None + except Exception as e: # PawnIO missing, not admin, non-Intel CPU, ... + if str(e) != self._pkg_error: + log.warning("CPU temperature/power unavailable: %s", e) + self._pkg_error = str(e) + self._next_pkg_attempt = time.monotonic() + 60 + + @property + def status(self) -> str: + return "ok" if self.pkg else (self._pkg_error or "not started") + + def read(self) -> Readings: + s = self.pdh.sample() + load = s.get("utility") + if load is None: + load = s.get("time") + if load is not None: + load = max(0.0, min(100.0, load)) + clock = None + if s.get("perf") is not None and s.get("freq"): + clock = s["freq"] * s["perf"] / 100.0 + temp = power = None + self._try_pkg() + if self.pkg: + try: + temp = self.pkg.temperature() + power = self.pkg.power() + except OSError as e: + log.warning("MSR read failed, will retry: %s", e) + self.pkg.msr.close() + self.pkg = None + return Readings(temp=temp, load=load, clock=clock, power=power) + + +# ----------------------------------------------------------------------------- GPU + +class GpuSensors: + def __init__(self, index: int = 0, load_source: str = "windows"): + """load_source: "windows" = same figure as Task Manager, "nvml" = NVIDIA's kernel-busy figure.""" + import pynvml + + self.nv = pynvml + self.index = index + self.handle = None + self._last_sample_ts = 0 + self.engine_load: GpuEngineLoad | None = None + if load_source == "windows": + try: + luid = nvidia_adapter_luid() + if luid is None: + raise OSError("no NVIDIA adapter found via DXGI") + self.engine_load = GpuEngineLoad(luid) + log.info("GPU load from Windows GPU engine counters (adapter %s)", luid) + except Exception as e: + log.warning("Task Manager-style GPU load unavailable, using NVML: %s", e) + self._connect() + + def _connect(self) -> None: + try: + self.nv.nvmlInit() + self.handle = self.nv.nvmlDeviceGetHandleByIndex(self.index) + limit = self.nv.nvmlDeviceGetEnforcedPowerLimit(self.handle) / 1000.0 + log.info("GPU: %s, power limit %.0f W", self.nv.nvmlDeviceGetName(self.handle), limit) + except Exception as e: + log.warning("NVIDIA GPU unavailable: %s", e) + self.handle = None + + def _get(self, fn, *args): + try: + return fn(self.handle, *args) + except Exception: + return None + + def _utilization(self) -> float | None: + """Average GPU load since the previous call. + + nvmlDeviceGetUtilizationRates only covers the driver's last ~1/6 s window, so a + bursty workload can read 3% for one update while the whole second averaged 80%. + The driver's sample buffer (about 6 samples/s) gives the true average instead. + """ + nv = self.nv + try: + _, samples = nv.nvmlDeviceGetSamples(self.handle, nv.NVML_GPU_UTILIZATION_SAMPLES, + self._last_sample_ts) + if samples: + self._last_sample_ts = max(s.timeStamp for s in samples) + values = [s.sampleValue.uiVal for s in samples] + return sum(values) / len(values) + except Exception: + pass + util = self._get(nv.nvmlDeviceGetUtilizationRates) + return None if util is None else float(util.gpu) + + def memory(self) -> tuple[int, int] | None: + """(used, total) bytes of graphics memory, or None while the GPU is unavailable.""" + if self.handle is None: + return None + info = self._get(self.nv.nvmlDeviceGetMemoryInfo) + return None if info is None else (int(info.used), int(info.total)) + + def read(self) -> Readings: + if self.handle is None: + self._connect() + if self.handle is None: + return Readings() + nv = self.nv + temp = self._get(nv.nvmlDeviceGetTemperature, nv.NVML_TEMPERATURE_GPU) + util = None + if self.engine_load is not None: + try: + util = self.engine_load.sample() + except Exception as e: + log.debug("GPU engine counters failed: %s", e) + if util is None: + util = self._utilization() + # Board power: everything on the card, including its fans, lighting and memory. + power = self._get(nv.nvmlDeviceGetPowerUsage) + clock = self._get(nv.nvmlDeviceGetClockInfo, nv.NVML_CLOCK_GRAPHICS) + if temp is None and util is None and power is None: + # driver reset or similar: reconnect next time + try: + nv.nvmlShutdown() + except Exception: + pass + self.handle = None + return Readings( + temp=None if temp is None else float(temp), + load=util, + clock=None if clock is None else float(clock), + power=None if power is None else power / 1000.0, + ) + + +# ----------------------------------------------------------------------------- rest of the system + +@dataclass +class PowerModel: + """Figures for the parts of the PC that have no power sensor. + + These are typical values for the hardware in this PC (MSI PRO Z790-P, DDR5, PCIe 4.0 + NVMe, Corsair 120 mm RGB fans); edit them to suit. Everything is DC watts, i.e. load on + the power supply, not draw from the wall (which is ~8-12% higher for an 80 Plus Gold unit). + """ + + motherboard: float = 15.0 # chipset (~6 W on Z790), audio, LAN, Wi-Fi, Super I/O + cpu_vrm_efficiency: float = 0.90 # the board's CPU regulators lose ~10% of what the package draws + ddr5_dimm: tuple[float, float] = (2.5, 5.5) # W per DIMM: idle, flat out (scaled by CPU load) + ddr4_dimm: tuple[float, float] = (1.5, 3.5) + fan_idle: float = 0.3 # W per case fan: electronics, plus... + fan_full: float = 1.7 # ...this much more at fan_ref_rpm (scales with rpm^2.5) + fan_ref_rpm: float = 1500.0 + board_fans: float = 5.0 # CPU cooler fans/pump on motherboard headers (speeds not readable) + usb_and_lighting: float = 12.0 # RGB on fans/RAM/board, keyboard, mouse, webcam, this LCD + hdd_idle_minutes: float = 10.0 # assume a hard drive has spun down after this long without I/O + + +_k32 = ctypes.WinDLL("kernel32", use_last_error=True) +_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE] +_k32.CreateFileW.restype = wt.HANDLE +_k32.DeviceIoControl.argtypes = [wt.HANDLE, wt.DWORD, ctypes.c_void_p, wt.DWORD, ctypes.c_void_p, wt.DWORD, + ctypes.POINTER(wt.DWORD), ctypes.c_void_p] +_k32.DeviceIoControl.restype = wt.BOOL +_k32.CloseHandle.argtypes = [wt.HANDLE] +_k32.GetSystemFirmwareTable.argtypes = [wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD] +_k32.GetSystemFirmwareTable.restype = wt.UINT +_k32.CreateToolhelp32Snapshot.argtypes = [wt.DWORD, wt.DWORD] +_k32.CreateToolhelp32Snapshot.restype = wt.HANDLE +_k32.CreateMutexW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.LPCWSTR] +_k32.CreateMutexW.restype = wt.HANDLE + + +class _PROCESSENTRY32W(ctypes.Structure): + _fields_ = [("dwSize", wt.DWORD), ("cntUsage", wt.DWORD), ("th32ProcessID", wt.DWORD), + ("th32DefaultHeapID", ctypes.c_size_t), ("th32ModuleID", wt.DWORD), ("cntThreads", wt.DWORD), + ("th32ParentProcessID", wt.DWORD), ("pcPriClassBase", ctypes.c_long), ("dwFlags", wt.DWORD), + ("szExeFile", wt.WCHAR * 260)] + + +_k32.Process32FirstW.argtypes = [wt.HANDLE, ctypes.POINTER(_PROCESSENTRY32W)] +_k32.Process32NextW.argtypes = [wt.HANDLE, ctypes.POINTER(_PROCESSENTRY32W)] + + +def _process_names() -> list[str]: + snap = _k32.CreateToolhelp32Snapshot(0x2, 0) # TH32CS_SNAPPROCESS + if snap == wt.HANDLE(-1).value: + raise OSError("Cannot enumerate processes to check Commander PRO ownership") + names: list[str] = [] + try: + entry = _PROCESSENTRY32W() + entry.dwSize = ctypes.sizeof(entry) + ok = _k32.Process32FirstW(snap, ctypes.byref(entry)) + while ok: + names.append(entry.szExeFile.lower()) + ok = _k32.Process32NextW(snap, ctypes.byref(entry)) + finally: + _k32.CloseHandle(snap) + return names + + +def corsair_software_running(openrgb_detector: str, fan_tools: bool = True) -> bool: + """True if iCUE (or, with `fan_tools`, FanControl) runs, or a running OpenRGB may drive the device. + + Corsair controllers' replies don't say which request they answer, so sharing one with other + software risks swapped replies. OpenRGB counts as released only when the named detector is + disabled in both the app's and the Windows service's settings. + """ + names = _process_names() + if any("icue" in n or "corsair" in n or (fan_tools and "fancontrol" in n) for n in names): + return True + if not any("openrgb" in n for n in names): + return False + configs = [os.path.join(os.environ.get("APPDATA", ""), "OpenRGB", "OpenRGB.json"), + os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "OpenRGB", + "service_config", "OpenRGB.json")] + try: + configs = [c for c in configs if os.path.exists(c)] + if not configs: + raise OSError("no OpenRGB settings found") + for config in configs: + with open(config, encoding="utf-8") as f: + settings = json.load(f) + if settings["Detectors"]["detectors"][openrgb_detector] is not False: + log.warning("OpenRGB %s detector is enabled in %s", openrgb_detector, config) + return True + return False + except (OSError, ValueError, KeyError, TypeError) as e: + log.warning("Cannot verify OpenRGB has released %s: %s", openrgb_detector, e) + return True + + +_MEMORY_TYPES = {0x18: "DDR3", 0x1A: "DDR4", 0x1E: "LPDDR4", 0x22: "DDR5", 0x23: "LPDDR5"} + + +def memory_modules() -> list[tuple[str, float]]: + """(type, GB) for each installed memory module, from the SMBIOS type 17 records.""" + rsmb = 0x52534D42 + size = _k32.GetSystemFirmwareTable(rsmb, 0, None, 0) + if not size: + return [] + buf = ctypes.create_string_buffer(size) + if _k32.GetSystemFirmwareTable(rsmb, 0, buf, size) != size: + return [] + length = struct.unpack_from("= 0x13: + raw_size = struct.unpack_from("= 0x20: + mb = struct.unpack_from(" None: + if note != self._note: + log.info("Commander PRO: %s", note) + self._note = note + + def _cmd(self, op: int, *args: int) -> bytes: + ch = self.ch + if ch is None: + raise OSError("Commander PRO is not open") + ch.drain() + ch.send(bytes((op, *args))) + r = ch.read(300) + if not r or len(r) < 4 or r[1] != 0: # [report id, status, data...] + raise OSError(f"no reply to command 0x{op:02X}") + return r + + def close(self) -> None: + with self._lock: + if self.ch is not None: + self.ch.close() + self.ch = None + if self._mutex is not None: + _k32.CloseHandle(self._mutex) + self._mutex = None + + def _corsair_software_running(self) -> bool: + return corsair_software_running("Corsair Commander Pro") + + def _open(self) -> None: + if self.ch is not None: + return + ctypes.set_last_error(0) + mutex = _k32.CreateMutexW(None, False, "Local\\TTLcdCommanderPro") + err = ctypes.get_last_error() + if not mutex or err == 183: + if mutex: + _k32.CloseHandle(mutex) + raise OSError("Commander PRO is in use by another dashboard/sensor process") + self._mutex = mutex + try: + paths = hid_device_paths(self.VID, self.PID) + if len(paths) != 1: + raise OSError(f"Expected one Commander PRO interface, found {len(paths)}") + self.ch = HidChannel(paths[0], 63) + modes = self._cmd(self.CMD_FAN_MODES) + if len(modes) < 8: + raise OSError("Incomplete Commander PRO fan modes reply") + self.ports = [p for p in range(self.PORTS) if modes[2 + p] in (1, 2)] + except Exception: + self.close() + raise + + def set_duty(self, ports: tuple[int, ...], duty: int) -> dict[int, int]: + """Set only the selected one-based PWM ports; return fresh one-based RPMs.""" + if (not ports or len(set(ports)) != len(ports) + or any(p not in range(1, 7) for p in ports) or not 0 <= duty <= 100): + raise ValueError("Fan ports must be unique values 1-6 and duty must be 0-100") + with self._lock: + if self._corsair_software_running(): + self.close() + raise OSError("Commander PRO busy: exit iCUE/FanControl, or disable OpenRGB's " + "Corsair Commander Pro detector and restart OpenRGB") + self._open() + modes = self._cmd(self.CMD_FAN_MODES) + if len(modes) < 8 or any(modes[p + 1] != 2 for p in ports): + raise OSError("Every selected fan port must have a connected PWM fan") + for p in ports: + self._cmd(0x23, p - 1, duty) + for p in self.ports: + r = self._cmd(self.CMD_FAN_RPM, p) + self.rpm[p] = (r[2] << 8) | r[3] + return {p + 1: rpm for p, rpm in self.rpm.items()} + + def read(self) -> list[int]: + """RPM of each connected fan (the last known values while iCUE has the device).""" + with self._lock: + if self.controlled: + return list(self.rpm.values()) + return self._read() + + def _read(self) -> list[int]: + now = time.monotonic() + if now >= self._next_check: + self._next_check = now + self.RECHECK + if self._corsair_software_running(): + self.close() + self._say("iCUE is running, leaving the device to it") + elif self.ch is None: + try: + self._open() + self._say(f"reading {len(self.ports)} fans (ports {', '.join(str(p + 1) for p in self.ports)})") + except Exception as e: + self.close() + self._say(f"unavailable ({e})") + if self.ch is not None: + try: + for p in self.ports: + r = self._cmd(self.CMD_FAN_RPM, p) + self.rpm[p] = (r[2] << 8) | r[3] + except Exception as e: + self.close() + self._say(f"lost ({e}), retrying in {self.RECHECK:.0f} s") + return [self.rpm[p] for p in self.ports if p in self.rpm] + + +@dataclass +class _Disk: + name: str + kind: str # nvme, ssd, hdd, usb-hdd, usb-ssd, flash, virtual + idle: float # W + active: float # W when busy 100% of the time + standby: float | None = None # W once a hard drive spins down + last_io: float = 0.0 + + +class StoragePower: + """Drive power estimated from each drive's activity (% of time busy, from Windows).""" + + IOCTL_STORAGE_QUERY_PROPERTY = 0x2D1400 + BUS_USB, BUS_NVME = 7, 17 + BUS_VIRTUAL = (14, 15, 16) # VHD, file-backed, Storage Spaces + + def __init__(self, model: PowerModel): + self.model = model + self.idle_time = PdhArray(r"\PhysicalDisk(*)\% Idle Time") + self.disks: dict[int, _Disk] = {} + + def _query(self, h, property_id: int, extra: bytes, out_size: int) -> bytes | None: + q = struct.pack(" float | None: + """Max power of power state 0 from the drive's Identify Controller data.""" + # STORAGE_PROTOCOL_SPECIFIC_DATA: NVMe, Identify, CNS 1 (controller), data right after it, 4 KiB + spec = struct.pack("<10I", 3, 1, 1, 0, 40, 4096, 0, 0, 0, 0) + raw = self._query(h, 49, spec + bytes(4096), 8 + 40 + 4096) # StorageAdapterProtocolSpecificProperty + if not raw or len(raw) < 8 + 40: + return None + off = 8 + struct.unpack_from(" _Disk: + m = self.model + h = _k32.CreateFileW(f"\\\\.\\PhysicalDrive{number}", 0, 0x3, None, 3, 0, None) + if h == wt.HANDLE(-1).value: + return _Disk(f"disk {number}", "unknown", 1.0, 3.0) + try: + desc = self._query(h, 0, b"", 1024) or b"" # StorageDeviceProperty + bus = struct.unpack_from("= 32 else 0 + removable = len(desc) > 10 and desc[10] != 0 + name = f"disk {number}" + if len(desc) >= 20: + pid_off = struct.unpack_from(" 8 else None + if bus in self.BUS_VIRTUAL: + return _Disk(name, "virtual", 0.0, 0.0) + if bus == self.BUS_NVME: + mx = self._nvme_max_power(h) or 7.0 + return _Disk(f"{name} (max {mx:.1f} W)", "nvme", min(1.5, max(0.3, 0.15 * mx)), 0.8 * mx) + if bus == self.BUS_USB: + if removable: + return _Disk(name, "flash", 0.1, 0.5) + if spinning is False: + return _Disk(name, "usb-ssd", 0.3, 2.0) + return _Disk(name, "usb-hdd", 1.5, 2.5, standby=0.2) # bus-powered 2.5" drive + if spinning: + return _Disk(name, "hdd", 5.0, 7.5, standby=0.8) + return _Disk(name, "ssd", 0.5, 3.0) + finally: + _k32.CloseHandle(h) + + def read(self) -> list[tuple[str, float]]: + now = time.monotonic() + out = [] + for inst, idle_pct in self.idle_time.sample() or []: + head = inst.split(" ", 1)[0] + if not head.isdigit(): + continue # _Total + number = int(head) + disk = self.disks.get(number) + if disk is None: + disk = self.disks[number] = self._probe(number) + disk.last_io = now + log.info("Drive %d: %s [%s] %.1f-%.1f W", number, disk.name, disk.kind, disk.idle, disk.active) + busy = min(1.0, max(0.0, 1.0 - idle_pct / 100.0)) + if busy > 0.002: + disk.last_io = now + if disk.standby is not None and now - disk.last_io > 60 * self.model.hdd_idle_minutes: + watts = disk.standby + else: + watts = disk.idle + (disk.active - disk.idle) * busy + out.append((disk.name, watts)) + return out + + +class SystemPower: + """Everything that isn't the CPU package or the graphics card, in watts.""" + + def __init__(self, model: PowerModel | None = None): + self.model = model or PowerModel() + self.dimms = memory_modules() + self.fans = CommanderPro() + try: + self.storage: StoragePower | None = StoragePower(self.model) + except OSError as e: + log.warning("Drive activity unavailable: %s", e) + self.storage = None + kinds = sorted({k for k, _ in self.dimms}) + log.info("Memory: %d module(s) %s, %.0f GB", len(self.dimms), "/".join(kinds), + sum(gb for _, gb in self.dimms)) + + def read(self, cpu: Readings, gpu: Readings) -> PowerReadings: + m = self.model + parts: dict[str, float] = {"Motherboard & chipset": m.motherboard} + if cpu.power is not None: + parts["CPU regulator losses"] = cpu.power * (1.0 / m.cpu_vrm_efficiency - 1.0) + if self.dimms: + load = (cpu.load or 0.0) / 100.0 + w = 0.0 + for kind, _gb in self.dimms: + idle, full = m.ddr4_dimm if kind in ("DDR4", "DDR3", "LPDDR4") else m.ddr5_dimm + w += idle + (full - idle) * load + parts[f"Memory ({len(self.dimms)} modules)"] = w + if self.storage is not None: + try: + drives = self.storage.read() + except Exception as e: + log.debug("Drive activity failed: %s", e) + drives = [] + for name, w in drives: + parts[f"Drive: {name}"] = w + rpms = self.fans.read() + if rpms: + parts[f"Case fans ({len(rpms)}, Commander PRO)"] = sum( + m.fan_idle + m.fan_full * (r / m.fan_ref_rpm) ** 2.5 for r in rpms if r > 0) + parts["Motherboard-header fans/pump (fixed)"] = m.board_fans + parts["USB devices & RGB lighting (fixed)"] = m.usb_and_lighting + return PowerReadings(cpu=cpu.power, gpu=gpu.power, other=sum(parts.values()), parts=parts) + + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") + cpu, gpu, system = CpuSensors(), GpuSensors(), SystemPower() + for _ in range(3): + time.sleep(1) + c, g = cpu.read(), gpu.read() + p = system.read(c, g) + print("CPU", c) + print("GPU", g) + for name, w in p.parts.items(): + print(f" {w:6.1f} W {name}") + fmt = lambda v: "--" if v is None else f"{v:.0f} W" + print(f" CPU {fmt(p.cpu)} + GPU {fmt(p.gpu)} + other {fmt(p.other)} = total {fmt(p.total)}") + print("CPU temp/power status:", cpu.status) diff --git a/kurgan/telemetry/service.py b/kurgan/telemetry/service.py new file mode 100644 index 0000000..bb5c291 --- /dev/null +++ b/kurgan/telemetry/service.py @@ -0,0 +1,120 @@ +"""Telemetry service: reads every sensor once a second on one thread and shares the result. + +The LCD, the lighting, the tray tooltip and the web UI all use these samples, so the hardware +is polled once however many things are watching. (The fan worker keeps its own temperature +reads on purpose: cooling must not depend on any other worker staying healthy.) +""" + +from __future__ import annotations + +import collections +import logging +import threading +import time +from dataclasses import dataclass, field +from typing import Callable + +from kurgan.telemetry.readings import PowerReadings, Readings + +log = logging.getLogger(__name__) + +HISTORY_SECONDS = 600 +SERIES = ("t", "cpu_temp", "gpu_temp", "cpu_load", "gpu_load", "cpu_w", "gpu_w", "other_w", "total_w", "vram_used") + + +@dataclass +class Sample: + seq: int + t: float # time.time() + cpu: Readings = field(default_factory=Readings) + gpu: Readings = field(default_factory=Readings) + power: PowerReadings = field(default_factory=PowerReadings) + vram: tuple[int, int] | None = None # (used, total) bytes + + def row(self) -> tuple: + return (round(self.t, 1), _r(self.cpu.temp), _r(self.gpu.temp), _r(self.cpu.load), _r(self.gpu.load), + _r(self.power.cpu), _r(self.power.gpu), _r(self.power.other), _r(self.power.total), + None if self.vram is None else self.vram[0]) + + +def _r(value: float | None, digits: int = 1) -> float | None: + return None if value is None else round(value, digits) + + +class Telemetry: + def __init__(self, cpu, gpu, system, interval: float = 1.0): + self.cpu, self.gpu, self.system = cpu, gpu, system + self.interval = interval + self._cond = threading.Condition() + self._latest: Sample | None = None + self._history: collections.deque[tuple] = collections.deque(maxlen=int(HISTORY_SECONDS / interval)) + self._listeners: list[Callable[[Sample], None]] = [] + self._seq = 0 + + def subscribe(self, listener: Callable[[Sample], None]) -> None: + self._listeners.append(listener) + + def read(self) -> Sample: + c, g = self.cpu.read(), self.gpu.read() + p = self.system.read(c, g) + self._seq += 1 + return Sample(self._seq, time.time(), c, g, p, self.gpu.memory()) + + def run(self, stop: threading.Event) -> None: + while not stop.is_set(): + t0 = time.monotonic() + try: + sample = self.read() + except Exception: + log.exception("Sensor read failed; retrying") + stop.wait(5) + continue + with self._cond: + self._latest = sample + self._history.append(sample.row()) + self._cond.notify_all() + if sample.seq == 5: # once the counters have settled + fmt = lambda v: "--" if v is None else f"{v:.0f}" + p = sample.power + log.info("Power: CPU %s + GPU %s + other %s = %s W; other = %s", fmt(p.cpu), fmt(p.gpu), + fmt(p.other), fmt(p.total), ", ".join(f"{k} {v:.1f}" for k, v in p.parts.items())) + for listener in self._listeners: + try: + listener(sample) + except Exception: + log.exception("Telemetry listener %r failed", listener) + stop.wait(max(0.0, self.interval - (time.monotonic() - t0))) + with self._cond: + self._cond.notify_all() + + @property + def latest(self) -> Sample | None: + with self._cond: + return self._latest + + def wait_newer(self, seq: int, timeout: float) -> Sample | None: + """The first sample after `seq`, or the latest one (possibly None) after `timeout`.""" + with self._cond: + self._cond.wait_for(lambda: self._latest is not None and self._latest.seq > seq, timeout) + return self._latest + + def snapshot(self) -> dict: + s = self.latest + if s is None: + return {"seq": 0} + return { + "seq": s.seq, "t": s.t, + "cpu": {"temp": _r(s.cpu.temp), "load": _r(s.cpu.load), "clock": _r(s.cpu.clock, 0), "power": _r(s.cpu.power)}, + "gpu": {"temp": _r(s.gpu.temp), "load": _r(s.gpu.load), "clock": _r(s.gpu.clock, 0), "power": _r(s.gpu.power), + "vram_used": None if s.vram is None else s.vram[0], + "vram_total": None if s.vram is None else s.vram[1]}, + "power": {"cpu": _r(s.power.cpu), "gpu": _r(s.power.gpu), "other": _r(s.power.other), + "total": _r(s.power.total), + "parts": {k: round(v, 1) for k, v in s.power.parts.items()}}, + "row": s.row(), + } + + def history(self) -> dict: + with self._cond: + rows = list(self._history) + return {"series": SERIES, "rows": rows, "interval": self.interval} diff --git a/kurgan/theme.py b/kurgan/theme.py new file mode 100644 index 0000000..d88841d --- /dev/null +++ b/kurgan/theme.py @@ -0,0 +1,36 @@ +"""Colours and thresholds shared by the LCD, the case/RAM lighting and the tray icon.""" + +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass +class Theme: + accent: tuple[int, int, int] = (232, 28, 44) + cpu_temp_range: tuple[float, float] = (20.0, 100.0) + gpu_temp_range: tuple[float, float] = (20.0, 90.0) + psu_watts: float = 1000.0 # fills the power tank + # Optional mirrored direction on the right; by default all gauges fill clockwise. + mirror_gauge_direction: bool = False + titles: tuple[str, str] = ("GPU", "CPU") + # Gauges are green below *_warn, yellow from *_warn to *_hot, red above. + temp_warn: float = 50.0 # deg C + temp_hot: float = 80.0 + load_warn: float = 50.0 # percent + load_hot: float = 80.0 + cool_color: tuple[int, int, int] = (38, 204, 72) + warm_color: tuple[int, int, int] = (244, 192, 22) + hot_color: tuple[int, int, int] = (232, 28, 44) + # Power tank layers. Kept clear of the gauges' green/yellow/red, and checked to stay + # distinguishable with colour-blindness against the dark glass. + cpu_color: tuple[int, int, int] = (57, 135, 229) # blue + gpu_color: tuple[int, int, int] = (25, 158, 112) # aqua + other_color: tuple[int, int, int] = (217, 89, 38) # copper orange + + def level_color(self, value: float, warn: float, hot: float) -> tuple[int, int, int]: + if value < warn: + return self.cool_color + if value <= hot: + return self.warm_color + return self.hot_color diff --git a/kurgan/tray.py b/kurgan/tray.py new file mode 100644 index 0000000..da7d550 --- /dev/null +++ b/kurgan/tray.py @@ -0,0 +1,407 @@ +"""Notification-area icon for The Kurgan. + +The tooltip shows the power draw; the menu shows each capability's status and has +"Open The Kurgan" (the web UI), "Start with Windows" and "Exit". Clicking the icon with the +left button opens the web UI directly. + +"Start with Windows" switches the logon trigger of "The Kurgan" scheduled task (installed by +setup.ps1) on or off. The task itself stays enabled, so it can still be started by hand, +with admin rights and no UAC prompt: Start-ScheduledTask "The Kurgan" + +The Kurgan usually runs elevated while Explorer doesn't, so Windows would drop Explorer's +clicks on the icon; the window explicitly accepts those messages (ChangeWindowMessageFilterEx). +""" + +from __future__ import annotations + +import ctypes +import ctypes.wintypes as wt +import logging +import subprocess +import threading + +log = logging.getLogger(__name__) + +TASK_NAME = "The Kurgan" +LEGACY_TASK_NAME = "TT LCD Dashboard" # until setup.ps1 re-registers the task + + +# ----------------------------------------------------------------------------- startup task + +def _powershell(script: str) -> str: + r = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script], + capture_output=True, text=True, timeout=60, creationflags=subprocess.CREATE_NO_WINDOW) + if r.returncode != 0: + lines = [ln.strip() for ln in (r.stderr or r.stdout).splitlines() if ln.strip()] + raise RuntimeError(lines[0] if lines else f"PowerShell exited with code {r.returncode}") + return r.stdout.strip() + + +_QUERY = """ +$t = Get-ScheduledTask -TaskName '%TASK%' -ErrorAction SilentlyContinue +if (-not $t) { 'missing' } +elseif ($t.State -ne 'Disabled' -and @($t.Triggers | Where-Object { + $_.CimClass.CimClassName -eq 'MSFT_TaskLogonTrigger' -and $_.Enabled }).Count) { 'on' } +else { 'off' } +""" + +_SET = """ +$ErrorActionPreference = 'Stop' +$t = Get-ScheduledTask -TaskName '%TASK%' +$n = 0 +foreach ($tr in $t.Triggers) { + if ($tr.CimClass.CimClassName -eq 'MSFT_TaskLogonTrigger') { $tr.Enabled = %ON%; $n++ } +} +if (-not $n) { throw 'The startup task has no logon trigger; run setup.ps1 again.' } +Set-ScheduledTask -InputObject $t | Out-Null +if (%ON% -and $t.State -eq 'Disabled') { Enable-ScheduledTask -TaskName '%TASK%' | Out-Null } +""" + + +def _task_state(name: str) -> str: + return _powershell(_QUERY.replace("%TASK%", name)) + + +def startup_task() -> str | None: + """The installed startup task's name, preferring The Kurgan's own.""" + for name in (TASK_NAME, LEGACY_TASK_NAME): + if _task_state(name) != "missing": + return name + return None + + +def autostart_enabled() -> bool | None: + """True/False: the startup task does/doesn't run at logon. None: it isn't installed.""" + name = startup_task() + return None if name is None else _task_state(name) == "on" + + +def set_autostart(on: bool) -> None: + name = startup_task() + if name is None: + raise RuntimeError("The startup task isn't installed; run setup.ps1.") + _powershell(_SET.replace("%TASK%", name).replace("%ON%", "$true" if on else "$false")) + + +# ----------------------------------------------------------------------------- icon image + +def make_icon(path: str, layers: list[tuple[int, int, int]]) -> str: + """Draw a small version of the dashboard's power tank and save it as a .ico file. + + layers: colours from the bottom up (other, CPU, GPU). + """ + from PIL import Image, ImageDraw + + s = 256 + img = Image.new("RGBA", (s, s), (0, 0, 0, 0)) + d = ImageDraw.Draw(img) + chrome, dark = (206, 206, 212, 255), (20, 20, 24, 255) + x0, x1 = 52, 204 # glass + d.rectangle([x0, 30, x1, 226], fill=dark) + y = 226 + for h, c in zip((50, 42, 56), layers): # bottom up + d.rectangle([x0, y - h, x1, y], fill=c + (255,)) + y -= h + d.rectangle([x0, y - 3, x1, y + 3], fill=dark) + hl = Image.new("RGBA", (s, s), (0, 0, 0, 0)) + ImageDraw.Draw(hl).rectangle([x0 + 22, 36, x0 + 40, 222], fill=(255, 255, 255, 70)) + img.alpha_composite(hl) + d = ImageDraw.Draw(img) + for y0, y1 in ((4, 40), (216, 252)): # end caps + d.rounded_rectangle([28, y0, 228, y1], radius=12, fill=chrome) + d.rectangle([28, (y0 + y1) // 2 - 2, 228, (y0 + y1) // 2 + 2], fill=(120, 120, 128, 255)) + img.save(path, sizes=[(16, 16), (20, 20), (24, 24), (32, 32), (40, 40), (48, 48), (64, 64)]) + return path + + +# ----------------------------------------------------------------------------- Win32 + +_u32 = ctypes.WinDLL("user32", use_last_error=True) +_shell32 = ctypes.WinDLL("shell32", use_last_error=True) +_k32 = ctypes.WinDLL("kernel32", use_last_error=True) + +LRESULT = ctypes.c_ssize_t +WNDPROC = ctypes.WINFUNCTYPE(LRESULT, wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM) + +WM_NULL, WM_DESTROY, WM_CLOSE, WM_TIMER = 0x0000, 0x0002, 0x0010, 0x0113 +WM_LBUTTONUP, WM_RBUTTONUP = 0x0202, 0x0205 +WM_TRAY = 0x8000 + 1 # WM_APP + 1: Explorer -> us, mouse events on the icon +WM_TRAY_TIP = 0x8000 + 2 # WM_APP + 2: main thread -> us, tooltip changed +NIM_ADD, NIM_MODIFY, NIM_DELETE = 0, 1, 2 +NIF_MESSAGE, NIF_ICON, NIF_TIP = 0x1, 0x2, 0x4 +MF_STRING, MF_GRAYED, MF_CHECKED, MF_SEPARATOR = 0x0, 0x1, 0x8, 0x800 +TPM_RIGHTBUTTON, TPM_NONOTIFY, TPM_RETURNCMD = 0x2, 0x80, 0x100 +MB_ICONWARNING, MB_SETFOREGROUND = 0x30, 0x10000 +MSGFLT_ALLOW = 1 +RETRY_TIMER = 1 + + +class WNDCLASSEXW(ctypes.Structure): + _fields_ = [("cbSize", wt.UINT), ("style", wt.UINT), ("lpfnWndProc", WNDPROC), ("cbClsExtra", ctypes.c_int), + ("cbWndExtra", ctypes.c_int), ("hInstance", wt.HINSTANCE), ("hIcon", wt.HICON), + ("hCursor", wt.HANDLE), ("hbrBackground", wt.HBRUSH), ("lpszMenuName", wt.LPCWSTR), + ("lpszClassName", wt.LPCWSTR), ("hIconSm", wt.HICON)] + + +class NOTIFYICONDATAW(ctypes.Structure): + _fields_ = [("cbSize", wt.DWORD), ("hWnd", wt.HWND), ("uID", wt.UINT), ("uFlags", wt.UINT), + ("uCallbackMessage", wt.UINT), ("hIcon", wt.HICON), ("szTip", wt.WCHAR * 128), + ("dwState", wt.DWORD), ("dwStateMask", wt.DWORD), ("szInfo", wt.WCHAR * 256), + ("uVersion", wt.UINT), ("szInfoTitle", wt.WCHAR * 64), ("dwInfoFlags", wt.DWORD), + ("guidItem", ctypes.c_byte * 16), ("hBalloonIcon", wt.HICON)] + + +_u32.RegisterClassExW.argtypes = [ctypes.POINTER(WNDCLASSEXW)] +_u32.RegisterClassExW.restype = wt.ATOM +_u32.CreateWindowExW.argtypes = [wt.DWORD, wt.LPCWSTR, wt.LPCWSTR, wt.DWORD, ctypes.c_int, ctypes.c_int, + ctypes.c_int, ctypes.c_int, wt.HWND, wt.HMENU, wt.HINSTANCE, wt.LPVOID] +_u32.CreateWindowExW.restype = wt.HWND +_u32.DefWindowProcW.argtypes = [wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM] +_u32.DefWindowProcW.restype = LRESULT +_u32.GetMessageW.argtypes = [ctypes.POINTER(wt.MSG), wt.HWND, wt.UINT, wt.UINT] +_u32.GetMessageW.restype = wt.BOOL +_u32.TranslateMessage.argtypes = [ctypes.POINTER(wt.MSG)] +_u32.DispatchMessageW.argtypes = [ctypes.POINTER(wt.MSG)] +_u32.DispatchMessageW.restype = LRESULT +_u32.PostMessageW.argtypes = [wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM] +_u32.PostMessageW.restype = wt.BOOL +_u32.PostQuitMessage.argtypes = [ctypes.c_int] +_u32.DestroyWindow.argtypes = [wt.HWND] +_u32.RegisterWindowMessageW.argtypes = [wt.LPCWSTR] +_u32.RegisterWindowMessageW.restype = wt.UINT +_u32.ChangeWindowMessageFilterEx.argtypes = [wt.HWND, wt.UINT, wt.DWORD, wt.LPVOID] +_u32.ChangeWindowMessageFilterEx.restype = wt.BOOL +_u32.LoadImageW.argtypes = [wt.HINSTANCE, wt.LPCWSTR, wt.UINT, ctypes.c_int, ctypes.c_int, wt.UINT] +_u32.LoadImageW.restype = wt.HANDLE +_u32.DestroyIcon.argtypes = [wt.HICON] +_u32.CreatePopupMenu.restype = wt.HMENU +_u32.AppendMenuW.argtypes = [wt.HMENU, wt.UINT, ctypes.c_size_t, wt.LPCWSTR] +_u32.TrackPopupMenu.argtypes = [wt.HMENU, wt.UINT, ctypes.c_int, ctypes.c_int, ctypes.c_int, wt.HWND, wt.LPVOID] +_u32.TrackPopupMenu.restype = ctypes.c_int +_u32.DestroyMenu.argtypes = [wt.HMENU] +_u32.GetCursorPos.argtypes = [ctypes.POINTER(wt.POINT)] +_u32.SetForegroundWindow.argtypes = [wt.HWND] +_u32.SetTimer.argtypes = [wt.HWND, ctypes.c_size_t, wt.UINT, wt.LPVOID] +_u32.SetTimer.restype = ctypes.c_size_t +_u32.KillTimer.argtypes = [wt.HWND, ctypes.c_size_t] +_u32.MessageBoxW.argtypes = [wt.HWND, wt.LPCWSTR, wt.LPCWSTR, wt.UINT] +_shell32.Shell_NotifyIconW.argtypes = [wt.DWORD, ctypes.POINTER(NOTIFYICONDATAW)] +_shell32.Shell_NotifyIconW.restype = wt.BOOL +_k32.GetModuleHandleW.argtypes = [wt.LPCWSTR] +_k32.GetModuleHandleW.restype = wt.HMODULE + + +def _is_admin() -> bool: + try: + return bool(_shell32.IsUserAnAdmin()) + except Exception: + return False + + +class TrayIcon: + """Notification-area icon on its own thread. + + status_lines() is called when the menu opens; on_open/on_exit are called from the tray thread.""" + + CLASS_NAME = "KurganTray" + ID_OPEN, ID_AUTOSTART, ID_EXIT = 1, 2, 3 + + def __init__(self, title: str, icon_path: str, on_exit, on_open=None, status_lines=None): + self.title = title + self.icon_path = icon_path + self.on_exit = on_exit + self.on_open = on_open + self.status_lines = status_lines or (lambda: []) + self._tip = title + self._hwnd = None + self._hicon = None + self._shown = False + self._autostart: bool | None = None + self._autostart_known = False + self._msg_taskbar = _u32.RegisterWindowMessageW("TaskbarCreated") + self._wndproc = WNDPROC(self._proc) # keep a reference: Windows calls it + self._thread = threading.Thread(target=self._run, name="tray", daemon=True) + + # -- called from other threads + + def start(self) -> None: + self._thread.start() + threading.Thread(target=self._refresh_autostart, name="tray-autostart", daemon=True).start() + + def set_tooltip(self, text: str) -> None: + text = text[:127] + if text != self._tip: + self._tip = text + if self._hwnd: + _u32.PostMessageW(self._hwnd, WM_TRAY_TIP, 0, 0) + + def close(self) -> None: + if self._hwnd: + _u32.PostMessageW(self._hwnd, WM_CLOSE, 0, 0) + self._thread.join(timeout=3) + + # -- tray thread + + def _run(self) -> None: + try: + try: + _u32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4)) # per-monitor v2: crisp menu and icon + except Exception: + pass + hinst = _k32.GetModuleHandleW(None) + wc = WNDCLASSEXW() + wc.cbSize = ctypes.sizeof(wc) + wc.lpfnWndProc = self._wndproc + wc.hInstance = hinst + wc.lpszClassName = self.CLASS_NAME + _u32.RegisterClassExW(ctypes.byref(wc)) # fails harmlessly if already registered + # A hidden top-level window: message-only windows miss the TaskbarCreated broadcast. + hwnd = _u32.CreateWindowExW(0, self.CLASS_NAME, self.title, 0, 0, 0, 0, 0, None, None, hinst, None) + if not hwnd: + raise OSError(f"CreateWindowEx failed: {ctypes.FormatError(ctypes.get_last_error()).strip()}") + for msg in (WM_TRAY, self._msg_taskbar): + _u32.ChangeWindowMessageFilterEx(hwnd, msg, MSGFLT_ALLOW, None) + size = _u32.GetSystemMetrics(49) # SM_CXSMICON + self._hicon = _u32.LoadImageW(None, self.icon_path, 1, size, size, 0x10) # IMAGE_ICON, LR_LOADFROMFILE + self._hwnd = hwnd + self._add() + msg = wt.MSG() + while _u32.GetMessageW(ctypes.byref(msg), None, 0, 0) > 0: + _u32.TranslateMessage(ctypes.byref(msg)) + _u32.DispatchMessageW(ctypes.byref(msg)) + except Exception: + log.exception("Tray icon failed") + finally: + if self._hicon: + _u32.DestroyIcon(self._hicon) + self._hwnd = None + + def _notify(self, op: int) -> bool: + nid = NOTIFYICONDATAW() + nid.cbSize = ctypes.sizeof(nid) + nid.hWnd = self._hwnd + nid.uID = 1 + nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP + nid.uCallbackMessage = WM_TRAY + nid.hIcon = self._hicon + nid.szTip = self._tip + return bool(_shell32.Shell_NotifyIconW(op, ctypes.byref(nid))) + + def _add(self) -> None: + """Add the icon; at logon the taskbar may not exist yet, so keep retrying.""" + self._shown = self._notify(NIM_ADD) or self._notify(NIM_MODIFY) + if self._shown: + _u32.KillTimer(self._hwnd, RETRY_TIMER) + log.info("Tray icon shown") + else: + _u32.SetTimer(self._hwnd, RETRY_TIMER, 5000, None) + + def _proc(self, hwnd, msg, wparam, lparam): + try: + if msg == WM_TRAY: + event = lparam & 0xFFFF + if event == WM_LBUTTONUP and self.on_open is not None: + self.on_open() + elif event in (WM_LBUTTONUP, WM_RBUTTONUP): + self._menu() + return 0 + if msg == WM_TRAY_TIP: + if self._shown: + self._notify(NIM_MODIFY) + return 0 + if msg == self._msg_taskbar or (msg == WM_TIMER and wparam == RETRY_TIMER): + self._add() # Explorer restarted (or the taskbar wasn't up yet) + return 0 + if msg == WM_CLOSE: + self._notify(NIM_DELETE) + _u32.DestroyWindow(hwnd) + return 0 + if msg == WM_DESTROY: + _u32.PostQuitMessage(0) + return 0 + except Exception: + log.exception("Tray icon message %#x failed", msg) + return _u32.DefWindowProcW(hwnd, msg, wparam, lparam) + + def _menu(self) -> None: + cmd = 0 + m = _u32.CreatePopupMenu() + try: + _u32.AppendMenuW(m, MF_STRING | MF_GRAYED, 0, self.title) + try: + lines = list(self.status_lines()) + except Exception: + log.exception("Tray status failed") + lines = [] + for line in lines: + _u32.AppendMenuW(m, MF_STRING | MF_GRAYED, 0, line[:120]) + _u32.AppendMenuW(m, MF_SEPARATOR, 0, None) + if self.on_open is not None: + _u32.AppendMenuW(m, MF_STRING, self.ID_OPEN, f"Open {self.title}") + if not self._autostart_known: + _u32.AppendMenuW(m, MF_STRING | MF_GRAYED, self.ID_AUTOSTART, "Start with Windows (checking...)") + elif self._autostart is None: + _u32.AppendMenuW(m, MF_STRING | MF_GRAYED, self.ID_AUTOSTART, + "Start with Windows (run setup.ps1 first)") + else: + _u32.AppendMenuW(m, MF_STRING | (MF_CHECKED if self._autostart else 0), self.ID_AUTOSTART, + "Start with Windows") + _u32.AppendMenuW(m, MF_SEPARATOR, 0, None) + _u32.AppendMenuW(m, MF_STRING, self.ID_EXIT, "Exit") + pt = wt.POINT() + _u32.GetCursorPos(ctypes.byref(pt)) + _u32.SetForegroundWindow(self._hwnd) # otherwise the menu doesn't close when clicking elsewhere + cmd = _u32.TrackPopupMenu(m, TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON, pt.x, pt.y, 0, + self._hwnd, None) + _u32.PostMessageW(self._hwnd, WM_NULL, 0, 0) + finally: + _u32.DestroyMenu(m) + if cmd == self.ID_EXIT: + log.info("Exit chosen from the tray menu") + self.on_exit() + elif cmd == self.ID_OPEN: + self.on_open() + elif cmd == self.ID_AUTOSTART: + self._toggle_autostart() + + def _refresh_autostart(self) -> None: + try: + self._autostart = autostart_enabled() + except Exception as e: + log.warning("Couldn't read the startup task: %s", e) + self._autostart = None + self._autostart_known = True + + def _toggle_autostart(self) -> None: + want = not self._autostart + try: + set_autostart(want) + log.info("Start with Windows turned %s", "on" if want else "off") + except Exception as e: + log.warning("Couldn't change Start with Windows: %s", e) + hint = "" if _is_admin() else ( + "\n\nChanging this needs admin rights. The Kurgan has them when its startup task " + "starts it (Start-ScheduledTask \"The Kurgan\").") + _u32.MessageBoxW(self._hwnd, f"Couldn't turn Start with Windows {'on' if want else 'off'}.\n\n{e}{hint}", + self.title, MB_ICONWARNING | MB_SETFOREGROUND) + self._refresh_autostart() # show what the task really says now + + +if __name__ == "__main__": + # Quick check: show the icon for 20 s with a test tooltip. + import os + import tempfile + import time + + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") + print("Start with Windows:", autostart_enabled()) + path = make_icon(os.path.join(tempfile.gettempdir(), "kurgan_tray_test.ico"), + [(217, 89, 38), (57, 135, 229), (25, 158, 112)]) + done = threading.Event() + tray = TrayIcon("The Kurgan (test)", path, on_exit=done.set, status_lines=lambda: ["Test run"]) + tray.start() + for i in range(20): + tray.set_tooltip(f"The Kurgan (test)\n{i} s") + if done.wait(1): + break + tray.close() diff --git a/kurgan/web/__init__.py b/kurgan/web/__init__.py new file mode 100644 index 0000000..ade3c9b --- /dev/null +++ b/kurgan/web/__init__.py @@ -0,0 +1 @@ +"""Web: the control UI and its JSON API, on 127.0.0.1 only.""" diff --git a/kurgan/web/proxy.py b/kurgan/web/proxy.py new file mode 100644 index 0000000..19368c2 --- /dev/null +++ b/kurgan/web/proxy.py @@ -0,0 +1,284 @@ +"""The LLM servers' addresses on The Kurgan's web server: /strata/... and /llama/... + + http://127.0.0.1:8080/strata/v1 OpenAI-compatible base URL for Strata + http://127.0.0.1:8080/llama/v1 ... for llama.cpp (no API key needed; any key is accepted) + http://127.0.0.1:8080/strata/ each server's own chat page (and everything else it serves) + http://127.0.0.1:8080/llama/ + +A request starts its server if it isn't running (see AiService.claim, which also stops the other +server once that one is idle) and the reply is streamed back as it is generated. A client that +hangs up (a timeout, or the user cancelling) is noticed within a second, even while it is still +waiting: its place is given up and the connection to the server closed, which stops the work on +it. The log then says how long the client waited and at what stage. GET .../v1/models is +answered here while a server is stopped, so a client listing the models of both doesn't make +them swap. + +Security: the web server's Host check applies (DNS rebinding). A request carrying an Origin +header other than this server's comes from another site's page and is refused, as is anything +else a browser marks cross-site except opening a page. Pages of this server (the chat pages) are +let through with the Origin removed, so each server treats them like any local client. +llama-server keeps its API key on its own port, and this proxy supplies it, so neither server +asks clients here for a key. +""" + +from __future__ import annotations + +import http.client +import json +import logging +import re +import select +import socket +import time + +log = logging.getLogger(__name__) + +ROUTE = re.compile(r"^/(strata|llama)(/[^?#]*)?(\?.*)?$") +MAX_BODY = 64 * 1024 * 1024 # images and very long prompts are big, but not this big +CONNECT_TIMEOUT = 10.0 +READ_TIMEOUT = 1800.0 # between bytes: a model load plus a long prompt can take minutes +REQUEST_SKIP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", + "transfer-encoding", "upgrade", "host", "content-length", "origin", "expect"} +RESPONSE_SKIP = {"connection", "keep-alive", "proxy-authenticate", "te", "trailer", "transfer-encoding", + "upgrade", "server", "date"} + + +class BodyError(Exception): + def __init__(self, message: str, status: int): + super().__init__(message) + self.status = status + + +def match(path: str) -> tuple[str, str | None] | None: + """("llama", "/v1/models?x") for "/llama/v1/models?x"; ("llama", None) for "/llama"; None otherwise.""" + m = ROUTE.match(path) + if m is None: + return None + rest = m[2] + return m[1], None if rest is None else rest + (m[3] or "") + + +def _error(handler, status: int, message: str) -> None: + body = json.dumps({"error": {"message": message, "type": "kurgan"}}).encode() + handler.send_response(status) + handler.send_header("Content-Type", "application/json") + handler.send_header("Content-Length", str(len(body))) + handler.send_header("Cache-Control", "no-store") + handler.send_header("Connection", "close") + handler.end_headers() + handler.close_connection = True + if handler.command != "HEAD": + handler.wfile.write(body) + + +def _read_body(handler) -> bytes | None: + """The request body (Content-Length or chunked), None if there is none.""" + if handler.headers.get("Transfer-Encoding", "").lower() == "chunked": + parts, total = [], 0 + while True: + line = handler.rfile.readline(1024) + try: + size = int(line.split(b";")[0].strip(), 16) + except ValueError: + raise BodyError("malformed chunked body", 400) from None + if size == 0: + while handler.rfile.readline(1024) not in (b"\r\n", b"\n", b""): # trailers + pass + return b"".join(parts) + total += size + if total > MAX_BODY: + raise BodyError("request body too large", 413) + parts.append(handler.rfile.read(size)) + handler.rfile.readline(8) + length = handler.headers.get("Content-Length") + if length is None: + return None + try: + length = int(length) + except ValueError: + raise BodyError("bad Content-Length", 400) from None + if length < 0: + raise BodyError("bad Content-Length", 400) + if length > MAX_BODY: + remaining = min(length, 1024 * 1024) # read a little so the client sees the answer; beyond that, give up + while remaining > 0: + chunk = handler.rfile.read(min(remaining, 65536)) + if not chunk: + break + remaining -= len(chunk) + raise BodyError("request body too large", 413) + return handler.rfile.read(length) + + +def _models(handler, backend, rest: str) -> None: + """OpenAI's model list, without starting the server.""" + path = rest.split("?", 1)[0].rstrip("/") + models = [{"id": m, "object": "model", "created": 0, "owned_by": backend.key} for m in backend.model_ids()] + if path == "/v1/models": + data = {"object": "list", "data": models} + else: + wanted = path[len("/v1/models/"):] + data = next((m for m in models if m["id"] == wanted), None) + if data is None: + _error(handler, 404, f"model {wanted!r} not found") + return + body = json.dumps(data).encode() + handler.send_response(200) + handler.send_header("Content-Type", "application/json") + handler.send_header("Content-Length", str(len(body))) + handler.send_header("Connection", "close") + handler.end_headers() + handler.close_connection = True + handler.wfile.write(body) + + +def _location(value: str, backend) -> str: + """Map a redirect from the server's own address onto its path here.""" + internal = f"http://127.0.0.1:{backend.port}" + if value.startswith(internal): + value = value[len(internal):] or "/" + if not value.startswith("/"): + return value + if backend.prefix and value.startswith(backend.prefix): + value = value[len(backend.prefix):] or "/" + return f"/{backend.key}{value}" + + +class ClientGone(Exception): + """The client closed its connection (it timed out or was cancelled); args[0] says when.""" + + +def client_gone(handler) -> bool: + """True once the client has closed its connection. The request has been read in full by + then, so a readable socket with nothing to read means the client hung up.""" + sock = handler.connection + try: + readable, _, _ = select.select([sock], [], [], 0) + return bool(readable) and sock.recv(1, socket.MSG_PEEK) == b"" + except (OSError, ValueError): + return True + + +def handle(handler, ai, hosts: set[str], origins: set[str]) -> None: + """Serve one request for /strata/... or /llama/... (handler is a BaseHTTPRequestHandler).""" + started = time.monotonic() + try: + _serve(handler, ai, hosts, origins, started) + except (ClientGone, ConnectionError) as e: + handler.close_connection = True + when = e.args[0] if isinstance(e, ClientGone) else "before its answer was sent" + log.info("%s %s: the client gave up after %.0f s, %s", handler.command, handler.path, + time.monotonic() - started, when) + + +def _serve(handler, ai, hosts: set[str], origins: set[str], started: float) -> None: + key, rest = match(handler.path) + try: + body = _read_body(handler) # before any answer: unread data would reset the connection on Windows + except BodyError as e: + _error(handler, e.status, str(e)) + return + if handler.headers.get("Host") not in hosts: + _error(handler, 403, "forbidden host") + return + origin = handler.headers.get("Origin") + if origin is not None and origin not in origins: + _error(handler, 403, f"web pages of {origin} may not use The Kurgan's AI servers") + return + # An or + + +
+
+ +

THE KURGAN

+
+ +
+ --W + whole PC +
+
+
+ + +
+ +
+

System

+
+
+
CPU
+
--°C
+
 
+
+
+
GPU
+
--°C
+
 
+
+
+
GPU memory
+
--
+
+
+
+
LCD
+
--
+
 
+
+
+
+
+
+
+
+ + +
+

Cooling

+
+
+
+

Fan profile

+

Applies to the Commander PRO case fans and the motherboard top fans. Fail-safes stay on in every profile.

+
+
+
+
+

+
+
+
+
+
+
+
+
+ + +
+

Lighting

+
+

+
+ + +
+

AI

+
+
+
+

Local LLM server

+

One runs at a time, so they never share the GPU's memory. A request to either one's address starts it, once the other has finished what it's doing; switching stops the other completely first.

+

+
+
+
+
+
+
+
+
+
+
+

Recent requests

+

Newest first

+
+
+
+
+
+ + + diff --git a/kurgan/web/static/style.css b/kurgan/web/static/style.css new file mode 100644 index 0000000..ab1101e --- /dev/null +++ b/kurgan/web/static/style.css @@ -0,0 +1,277 @@ +/* The Kurgan - control UI. Dark by default; a selected light theme follows the OS setting. */ + +:root { + color-scheme: dark; + --page: #0b0b0b; + --surface: #191919; + --surface-2: #222222; + --raised: #2a2a2a; + --text: #efefef; + --text-2: #9c9c9c; + --grid: #303030; + --axis: #474747; + --border: rgba(255, 255, 255, 0.10); + --brand: #e81c2c; + --select-bg: #efefef; + --select-text: #0b0b0b; + /* series: validated together (dataviz validator, dark surface #191919) */ + --cpu: #338ced; + --gpu: #00a888; + --other: #e76624; + --top: #e76624; + /* status: reserved for state, always with an icon and a word */ + --good: #0aac23; + --warning: #fbb315; + --serious: #f18a59; + --critical: #dc3c3d; + --meter-track: #2c2c2c; + --meter-fill: #9c9c9c; + --font: system-ui, -apple-system, "Segoe UI", sans-serif; +} + +@media (prefers-color-scheme: light) { + :root { + color-scheme: light; + --page: #f9f9f9; + --surface: #ffffff; + --surface-2: #f3f3f3; + --raised: #e9e9e9; + --text: #191919; + --text-2: #666666; + --grid: #e7e7e7; + --axis: #c2c2c2; + --border: rgba(11, 11, 11, 0.10); + --brand: #c4121f; + --select-bg: #191919; + --select-text: #ffffff; + --cpu: #257de0; + --gpu: #00b894; + --other: #f47230; + --top: #f47230; + --meter-track: #e7e7e7; + --meter-fill: #666666; + } +} + +* { box-sizing: border-box; } +html { scroll-behavior: smooth; scroll-padding-top: 76px; } +body { + margin: 0; + background: var(--page); + color: var(--text); + font: 14px/1.45 var(--font); +} +a { color: inherit; } +button, select, input { font: inherit; color: inherit; } +[hidden] { display: none !important; } + +/* ---------------------------------------------------------------- header */ +.masthead { + position: sticky; top: 0; z-index: 10; + display: flex; align-items: center; gap: 24px; flex-wrap: wrap; + padding: 10px 24px; + background: color-mix(in srgb, var(--page) 92%, transparent); + backdrop-filter: blur(6px); + border-bottom: 1px solid var(--border); +} +.brand { display: flex; align-items: center; gap: 10px; } +.brand svg { width: 22px; height: 22px; } +.brand h1 { + margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.22em; color: var(--brand); +} +.masthead nav { display: flex; gap: 4px; } +.masthead nav a { + text-decoration: none; color: var(--text-2); padding: 4px 10px; border-radius: 6px; +} +.masthead nav a:hover, .masthead nav a:focus-visible { background: var(--surface-2); color: var(--text); } +.hero { margin-left: auto; display: flex; align-items: baseline; gap: 6px; } +.hero-value { font-size: 48px; font-weight: 600; line-height: 1; } +.hero-unit { font-size: 18px; font-weight: 600; } +.hero-label { color: var(--text-2); margin-left: 4px; } +.meta { color: var(--text-2); font-size: 13px; display: flex; gap: 14px; flex-wrap: wrap; } + +.banner { + margin: 12px 24px 0; padding: 10px 14px; border-radius: 8px; + background: var(--surface); border: 1px solid var(--border); + display: flex; gap: 10px; align-items: flex-start; +} +.banner .note { margin: 0; font-size: 14px; } + +/* ---------------------------------------------------------------- layout */ +main { padding: 8px 24px 40px; max-width: 1480px; margin: 0 auto; } +section { margin-top: 28px; } +section > h2 { + font-size: 13px; font-weight: 600; letter-spacing: 0.12em; text-transform: uppercase; + color: var(--text-2); margin: 0 0 12px; +} +.grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(420px, 1fr)); gap: 16px; margin-top: 16px; } +.grid3 { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; margin-top: 16px; } +.card { + background: var(--surface); border: 1px solid var(--border); border-radius: 10px; + padding: 16px 18px; margin: 0; min-width: 0; +} +.card h3 { margin: 0 0 2px; font-size: 15px; font-weight: 600; } +.card .sub { color: var(--text-2); font-size: 13px; margin: 0 0 12px; } +.row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } +.spacer { flex: 1; } +.muted { color: var(--text-2); } +.num { font-variant-numeric: tabular-nums; } + +/* ---------------------------------------------------------------- stat tiles */ +.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; } +.tile .label { color: var(--text-2); font-size: 13px; display: flex; align-items: center; gap: 6px; } +.tile .value { font-size: 30px; font-weight: 600; line-height: 1.15; margin-top: 2px; } +.tile .value small { font-size: 15px; font-weight: 600; margin-left: 2px; } +.tile .detail { color: var(--text-2); font-size: 13px; margin-top: 4px; } +.key { display: inline-block; width: 10px; height: 10px; border-radius: 2px; flex: none; } +.key.line { width: 14px; height: 2px; border-radius: 1px; } + +/* ---------------------------------------------------------------- meters */ +.meter { height: 8px; border-radius: 4px; background: var(--meter-track); overflow: hidden; margin-top: 8px; } +.meter > span { display: block; height: 100%; border-radius: 4px; background: var(--meter-fill); width: 0; transition: width .4s; } +.meter.cpu > span { background: var(--cpu); } +.meter.gpu > span { background: var(--gpu); } +.meter.top > span { background: var(--top); } +.meter.warning > span { background: var(--warning); } +.meter.critical > span { background: var(--critical); } + +/* ---------------------------------------------------------------- controls */ +.seg { + display: inline-flex; background: var(--surface-2); border-radius: 8px; padding: 3px; gap: 2px; + border: 1px solid var(--border); flex-wrap: wrap; +} +.seg label { position: relative; } +.seg input { position: absolute; opacity: 0; inset: 0; margin: 0; cursor: pointer; } +.seg span { + display: block; padding: 6px 14px; border-radius: 6px; color: var(--text-2); cursor: pointer; + white-space: nowrap; user-select: none; +} +.seg label:hover span { color: var(--text); background: var(--raised); } +.seg input:checked + span { background: var(--select-bg); color: var(--select-text); font-weight: 600; } +.seg input:focus-visible + span { outline: 2px solid var(--text); outline-offset: 1px; } +.seg.busy { opacity: 0.6; pointer-events: none; } + +.btn { + border: 1px solid var(--border); background: var(--surface-2); border-radius: 8px; + padding: 7px 14px; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; +} +.btn:hover:not(:disabled) { background: var(--raised); } +.btn:disabled { opacity: 0.5; cursor: default; } +.btn:focus-visible { outline: 2px solid var(--text); outline-offset: 1px; } +select { + background: var(--surface-2); border: 1px solid var(--border); border-radius: 6px; padding: 4px 8px; +} + +/* ---------------------------------------------------------------- status */ +.pill { + display: inline-flex; align-items: center; gap: 6px; padding: 2px 10px; border-radius: 999px; + background: var(--surface-2); border: 1px solid var(--border); font-size: 13px; white-space: nowrap; +} +.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text-2); flex: none; } +.dot.good { background: var(--good); } +.dot.busy { background: var(--cpu); } +.dot.warning { background: var(--warning); } +.dot.critical { background: var(--critical); } +.note { display: flex; gap: 8px; align-items: flex-start; font-size: 13px; margin-top: 10px; } +.note svg { flex: none; width: 16px; height: 16px; margin-top: 1px; } +.note.warning svg { color: var(--warning); } +.note.critical svg { color: var(--critical); } +.note.info svg { color: var(--text-2); } + +/* ---------------------------------------------------------------- fan groups */ +.fan-head { display: flex; align-items: baseline; gap: 8px; } +.fan-duty { font-size: 30px; font-weight: 600; line-height: 1.1; } +.fan-ports { display: flex; gap: 14px; margin-top: 10px; color: var(--text-2); font-size: 13px; flex-wrap: wrap; } +.fan-ports b { color: var(--text); font-weight: 600; } +.profile-desc { color: var(--text-2); margin: 10px 0 0; font-size: 13px; } + +/* ---------------------------------------------------------------- lighting */ +.zone .status { color: var(--text-2); font-size: 13px; margin-top: 10px; min-height: 19px; } + +/* ---------------------------------------------------------------- AI */ +.backends { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; } +.choice { + position: relative; display: block; border: 1px solid var(--border); border-radius: 10px; + padding: 12px 14px; background: var(--surface-2); cursor: pointer; +} +.choice:hover { background: var(--raised); } +.choice input[type=radio] { position: absolute; opacity: 0; } +.choice:has(input[type=radio]:checked) { border-color: var(--text); box-shadow: inset 0 0 0 1px var(--text); } +.choice:has(input[type=radio]:focus-visible) { outline: 2px solid var(--text); outline-offset: 2px; } +.choice .name { font-weight: 600; display: flex; align-items: center; gap: 8px; } +.choice .what { color: var(--text-2); font-size: 13px; margin-top: 2px; } +.choice .state { margin-top: 8px; } +.choice select { margin-top: 8px; max-width: 100%; } +.check { + margin-left: auto; width: 18px; height: 18px; border-radius: 50%; border: 2px solid var(--axis); + display: inline-grid; place-items: center; +} +.choice:has(input[type=radio]:checked) .check { border-color: var(--text); background: var(--text); } +.choice:has(input[type=radio]:checked) .check::after { + content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--surface); +} +.backends.busy { opacity: 0.6; pointer-events: none; } +.kv { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 12px 0 0; font-size: 13px; } +.kv dt { color: var(--text-2); } +.kv dd { margin: 0; overflow-wrap: anywhere; } +.live { margin-top: 14px; padding: 12px; border-radius: 8px; background: var(--surface-2); } +.live .meter > span { background: var(--cpu); } +.speeds { display: flex; gap: 28px; margin-top: 14px; flex-wrap: wrap; } +.speeds .value { font-size: 24px; font-weight: 600; } +.speeds .label { color: var(--text-2); font-size: 13px; } +code { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font-size: 12.5px; } + +/* ---------------------------------------------------------------- tables */ +table { width: 100%; border-collapse: collapse; font-size: 13px; } +th { text-align: left; font-weight: 600; color: var(--text-2); padding: 6px 8px; border-bottom: 1px solid var(--axis); } +td { padding: 6px 8px; border-bottom: 1px solid var(--grid); } +td.r, th.r { text-align: right; font-variant-numeric: tabular-nums; } +.table-wrap { overflow-x: auto; } + +/* ---------------------------------------------------------------- charts */ +.chart-head { display: flex; align-items: flex-start; gap: 12px; flex-wrap: wrap; } +.chart-head h3 { margin: 0; } +.legend { display: flex; gap: 14px; flex-wrap: wrap; color: var(--text-2); font-size: 13px; margin-top: 4px; } +.legend span { display: inline-flex; align-items: center; gap: 6px; } +.table-toggle { margin-left: auto; font-size: 12.5px; padding: 4px 10px; } +.plot { position: relative; margin-top: 10px; } +.plot svg { display: block; width: 100%; height: 210px; overflow: visible; touch-action: none; } +.plot .grid line { stroke: var(--grid); stroke-width: 1; } +.plot .baseline { stroke: var(--axis); stroke-width: 1; } +.plot .tick { fill: var(--text-2); font-size: 11px; font-variant-numeric: tabular-nums; } +.plot .ref { stroke: var(--axis); stroke-width: 1; } +.plot .ref-label { fill: var(--text-2); font-size: 11px; } +.plot .series-line { fill: none; stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; } +.plot .series-area { opacity: 0.12; } +.plot .cross { stroke: var(--text-2); stroke-width: 1; } +.plot .marker { stroke: var(--surface); stroke-width: 2; } +.plot .end-label { fill: var(--text); font-size: 12px; font-weight: 600; } +.plot.stale { opacity: 0.45; } +.chart-table { margin-top: 10px; max-height: 260px; overflow: auto; } + +.tooltip { + position: fixed; z-index: 20; pointer-events: none; min-width: 150px; + background: var(--surface-2); border: 1px solid var(--border); border-radius: 8px; + padding: 8px 10px; font-size: 13px; box-shadow: 0 4px 16px rgba(0, 0, 0, 0.35); +} +.tooltip .when { color: var(--text-2); margin-bottom: 4px; } +.tooltip .tip-row { display: flex; align-items: center; gap: 8px; } +.tooltip .tip-row b { font-weight: 600; min-width: 56px; font-variant-numeric: tabular-nums; } +.tooltip .tip-row span:last-child { color: var(--text-2); } + +footer { color: var(--text-2); font-size: 12.5px; padding: 0 24px 28px; max-width: 1480px; margin: 0 auto; } + +@media (max-width: 720px) { + .masthead { padding: 10px 14px; gap: 12px; } + main { padding: 8px 14px 32px; } + .hero-value { font-size: 36px; } + .grid2 { grid-template-columns: 1fr; } +} +@media (prefers-reduced-motion: reduce) { + html { scroll-behavior: auto; } + .meter > span { transition: none; } +} + +/* the server card sits at the top of its row instead of stretching beside the chart */ +#ai-active { align-self: start; } +.pills { display: inline-flex; gap: 6px; flex-wrap: wrap; } diff --git a/lcd_dashboard.py b/lcd_dashboard.py new file mode 100644 index 0000000..e9355c6 --- /dev/null +++ b/lcd_dashboard.py @@ -0,0 +1,14 @@ +"""Compatibility entry point for the old "TT LCD Dashboard" startup task. + +This project is now The Kurgan: run `python -m kurgan`. Running setup.ps1 again replaces the +old task with "The Kurgan" task, after which this file can be deleted. +""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from kurgan.app import main # noqa: E402 + +sys.exit(main()) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..efa5590 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +pillow>=10.1 +numpy>=1.26 +nvidia-ml-py>=12.0 diff --git a/setup.ps1 b/setup.ps1 new file mode 100644 index 0000000..6f307c2 --- /dev/null +++ b/setup.ps1 @@ -0,0 +1,116 @@ +# Sets up The Kurgan: +# 1. installs the Python packages it needs (into the project's .venv if there is one) +# 2. installs PawnIO (signed driver used by LibreHardwareMonitor) for CPU sensors, top fans and RAM lighting +# 3. replaces the old "TT LCD Dashboard" startup task with "The Kurgan" (hidden, admin rights, at logon) +# 4. with -RetireAIServices: stops and disables the "Strata Local Service" and "Qwen4 Local Service" +# tasks, so The Kurgan runs whichever LLM server you select (re-enable them with uninstall.ps1) +# 5. starts The Kurgan; the web UI is at http://127.0.0.1:8080/ +# +# Run from a normal PowerShell window: +# powershell -ExecutionPolicy Bypass -File .\setup.ps1 [-RetireAIServices] +# It asks for administrator rights (UAC) itself. + +param([switch]$Elevated, [string]$PythonW, [switch]$RetireAIServices) + +$ErrorActionPreference = 'Stop' +$TaskName = 'The Kurgan' +$LegacyTaskName = 'TT LCD Dashboard' +$AITasks = 'Strata Local Service', 'Qwen4 Local Service' +$Here = $PSScriptRoot + +$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole( + [Security.Principal.WindowsBuiltInRole]::Administrator) + +if (-not $isAdmin) { + # Prefer the project's own .venv; otherwise use whichever python is on PATH. + $venvPython = Join-Path $Here '.venv\Scripts\python.exe' + if (Test-Path $venvPython) { + $python = $venvPython + } else { + $python = (Get-Command python -ErrorAction Stop).Source + } + $inVenv = (& $python -c "import sys; print(int(sys.prefix != sys.base_prefix))") -eq '1' + $pipArgs = if ($inVenv) { @() } else { @('--user') } + $pythonw = Join-Path (Split-Path $python) 'pythonw.exe' + if (-not (Test-Path $pythonw)) { throw "pythonw.exe not found next to $python" } + + Write-Host "Installing Python packages into $(Split-Path (Split-Path $python))..." -ForegroundColor Cyan + & $python -m pip install @pipArgs --quiet --disable-pip-version-check -r (Join-Path $Here 'requirements.txt') + if ($LASTEXITCODE -ne 0) { throw "pip install failed" } + + Write-Host "Requesting administrator rights for PawnIO and the startup task..." -ForegroundColor Cyan + $argList = "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" -Elevated -PythonW `"$pythonw`"" + if ($RetireAIServices) { $argList += ' -RetireAIServices' } + $p = Start-Process powershell -Verb RunAs -ArgumentList $argList -Wait -PassThru + exit $p.ExitCode +} + +function Stop-Matching([scriptblock]$Filter) { + Get-CimInstance Win32_Process | Where-Object $Filter | + ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } +} + +try { + if (-not $PythonW) { + $venvPythonW = Join-Path $Here '.venv\Scripts\pythonw.exe' + $PythonW = if (Test-Path $venvPythonW) { $venvPythonW } else { + Join-Path (Split-Path (Get-Command python -ErrorAction Stop).Source) 'pythonw.exe' } + } + + # --- PawnIO ------------------------------------------------------------------------- + $pawn = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\PawnIO' -ErrorAction SilentlyContinue + if ($pawn) { + Write-Host "PawnIO $($pawn.DisplayVersion) already installed." -ForegroundColor Green + } else { + Write-Host "Installing PawnIO via winget..." -ForegroundColor Cyan + winget install --id namazso.PawnIO --exact --silent --accept-source-agreements --accept-package-agreements + if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne 3010) { throw "winget install of PawnIO failed ($LASTEXITCODE)" } + } + + # --- stop any copy that is already running (an LLM server it started ends with it) ----- + foreach ($name in $TaskName, $LegacyTaskName) { Stop-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue } + Stop-Matching { $_.Name -like 'python*.exe' -and ($_.CommandLine -like '*lcd_dashboard.py*' -or + $_.CommandLine -like '*-m kurgan*') } + Unregister-ScheduledTask -TaskName $LegacyTaskName -Confirm:$false -ErrorAction SilentlyContinue + + # --- the LLM servers' own startup tasks ------------------------------------------------ + if ($RetireAIServices) { + foreach ($name in $AITasks) { + if (Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue) { + Stop-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue + Disable-ScheduledTask -TaskName $name | Out-Null + Write-Host "Disabled '$name'." -ForegroundColor Green + } + } + # Their trays, and the llama.cpp server the Qwen4 service started. + Stop-Matching { $_.CommandLine -like '*local-service-tray.py*' -or $_.CommandLine -like '*qwen4-service.pyw*' -or + ($_.Name -eq 'llama-server.exe' -and $_.CommandLine -like '*qwen4-35b-a3b\service\presets.ini*') } + } + + # --- scheduled task ------------------------------------------------------------------ + $user = [Security.Principal.WindowsIdentity]::GetCurrent().Name + $action = New-ScheduledTaskAction -Execute $PythonW -Argument '-m kurgan' -WorkingDirectory $Here + $trigger = New-ScheduledTaskTrigger -AtLogOn -User $user + $principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Highest + $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries ` + -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 5 -RestartInterval (New-TimeSpan -Minutes 1) ` + -MultipleInstances IgnoreNew -StartWhenAvailable + Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Principal $principal ` + -Settings $settings -Description 'The Kurgan: LCD dashboard, fans, lighting and the local LLM server' ` + -Force | Out-Null + Start-ScheduledTask -TaskName $TaskName + Write-Host "Done. '$TaskName' is running and will start at every logon." -ForegroundColor Green + Write-Host "Web UI: http://127.0.0.1:8080/ Log: $env:LOCALAPPDATA\Kurgan\kurgan.log" + if (-not $RetireAIServices) { + $running = $AITasks | Where-Object { (Get-ScheduledTask -TaskName $_ -ErrorAction SilentlyContinue).State -eq 'Running' } + if ($running) { + Write-Host "Still running on their own: $($running -join ', '). The Kurgan only watches them;" -ForegroundColor Yellow + Write-Host "run setup.ps1 -RetireAIServices to let The Kurgan run and swap them." -ForegroundColor Yellow + } + } +} catch { + Write-Host "Setup failed: $_" -ForegroundColor Red + Read-Host "Press Enter to close" + exit 1 +} +Start-Sleep -Seconds 4 diff --git a/tests/test_ai.py b/tests/test_ai.py new file mode 100644 index 0000000..dc6bf6c --- /dev/null +++ b/tests/test_ai.py @@ -0,0 +1,350 @@ +import os +import tempfile +import threading +import unittest +from unittest.mock import patch + +from kurgan.ai import launcher +from kurgan.ai.backends import Backend, LlamaLog +from kurgan.ai.service import CLIENT_GONE, AiService, RouteError +from kurgan.settings import Settings + +LLAMA_REQUEST = """\ +slot launch_slot_: id 0 | task 12 | processing task +slot update_slots: id 0 | task 12 | prompt processing, n_tokens = 2048, progress = 0.5, t = 1.2 s / 1706.7 tokens per second +slot update_slots: id 0 | task 12 | prompt processing, n_tokens = 4096, progress = 1.0, t = 2.4 s / 1706.7 tokens per second +slot process_toke: id 0 | task 12 | n_gen = 100, tg = 95.2 t/s, tg_3s = 97.1 t/s +slot print_timing: id 0 | task 12 | prompt eval time = 2400.00 ms / 4096 tokens ( 0.59 ms per token, 1706.67 tokens per second) +slot print_timing: id 0 | task 12 | eval time = 5000.00 ms / 500 tokens ( 10.00 ms per token, 100.00 tokens per second) +slot release: id 0 | task 12 | stop processing: n_tokens = 5096, truncated = 0 +""" + + +class LlamaLogTest(unittest.TestCase): + def test_request_in_progress_and_finished(self): + parser = LlamaLog() + lines = LLAMA_REQUEST.splitlines() + for line in lines[:2]: + parser.feed(line, now=1000.0) + live, requests, _ = parser.snapshot() + self.assertEqual((live["phase"], live["progress"], live["read"], live["tok_s"]), ("reading", 0.5, 2048, 1706.7)) + self.assertEqual(requests, []) + parser.feed(lines[3], now=1003.0) + live, _, _ = parser.snapshot() + self.assertEqual((live["phase"], live["generated"], live["tok_s"]), ("generating", 100, 97.1)) + for line in lines[4:]: + parser.feed(line, now=1008.0) + live, requests, averages = parser.snapshot() + self.assertIsNone(live) + self.assertEqual(len(requests), 1) + r = requests[0] + self.assertEqual((r["status"], r["prompt"], r["reused"], r["output"], r["duration"]), ("ok", 4596, 500, 500, 8.0)) + self.assertEqual((r["prefill_tps"], r["decode_tps"]), (1706.67, 100.0)) + self.assertEqual(averages, {"prefill_tps": 1706.7, "decode_tps": 100.0, "requests": 1}) + + def test_unrelated_lines_and_lines_before_a_task_are_ignored(self): + parser = LlamaLog() + parser.feed("srv log_server_r: request: GET /models 127.0.0.1 200") + parser.feed("slot update_slots: id 0 | task 3 | n_gen = 5, tg = 1.0 t/s, tg_3s = 1.0 t/s") + self.assertEqual(parser.snapshot(), (None, [], {"prefill_tps": None, "decode_tps": None, "requests": 0})) + + +class FakeChild: + def __init__(self, argv): + self.argv = argv + self.pid = 4000 + len(argv[0]) + self.token = {"integrity": "medium", "elevated": False} + self.code = None + + def poll(self): + return self.code + + def wait(self, timeout=None): + return self.code + + def kill(self): + if self.code is None: + self.code = 1 + + def close(self): + pass + + +class FakeBackend(Backend): + stop_timeout = 0.1 + + def __init__(self, settings, key, port, events): + self.key, self.label, self._port, self.events = key, key.capitalize(), port, events + super().__init__(settings) + + @property + def port(self): + return self._port + + def variant(self): + return self.settings.get("ai", "strata_model") if self.key == "strata" else None + + def model_label(self): + return f"{self.key} model" + + def command(self): + return [self.key], ".", None + + def request_stop(self, child): + self.events.append(("stop", self.key)) + child.code = 0 + + +class AiServiceTest(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + self.settings = Settings(os.path.join(self.dir.name, "settings.json"), None) + self.events = [] + self.children = [] + self.service = AiService(self.settings, [FakeBackend(self.settings, "strata", 18082, self.events), + FakeBackend(self.settings, "llama", 18083, self.events)]) + self.external_ports = set() + self.clock = [1000.0] + + def launch(argv, cwd, log_path): + self.events.append(("start", argv[0])) + self.children.append(FakeChild(argv)) + return self.children[-1] + + for target, fake in (("kurgan.ai.service.launcher.launch", launch), + ("kurgan.ai.service.port_in_use", lambda port: port in self.external_ports), + ("kurgan.ai.service.port_owner", lambda port: (1234, "pythonw.exe")), + ("kurgan.ai.service.time.monotonic", lambda: self.clock[0])): + patcher = patch(target, side_effect=fake) + patcher.start() + self.addCleanup(patcher.stop) + self.stop = threading.Event() + + def reconcile(self): + self.service._reconcile(self.stop) + + def processes(self): + return {b["key"]: b["process"] for b in self.service.snapshot()["backends"]} + + def test_swapping_stops_the_running_server_before_starting_the_other(self): + self.reconcile() + self.assertEqual(self.events, []) + self.service.set_active("llama") + self.reconcile() + self.service.set_active("strata", "iq3") + self.reconcile() + self.assertEqual(self.events, [("start", "llama"), ("stop", "llama"), ("start", "strata")]) + self.assertEqual(self.settings.get("ai", "strata_model"), "iq3") + self.service.set_active("strata", "q5") # another Strata model: restart it + self.reconcile() + self.service.set_active(None) + self.reconcile() + self.assertEqual(self.events[3:], [("stop", "strata"), ("start", "strata"), ("stop", "strata")]) + self.assertEqual(self.processes(), {"strata": "stopped", "llama": "stopped"}) + + def test_unknown_backend_or_variant_is_rejected_and_not_saved(self): + with self.assertRaises(ValueError): + self.service.set_active("ollama") + with self.assertRaises(ValueError): + self.service.set_active("strata", "q8") + self.assertIsNone(self.settings.get("ai", "active")) + + def test_crashes_restart_after_a_pause_and_repeated_crashes_hold_off(self): + self.service.set_active("llama") + self.reconcile() + for crash in range(4): + self.children[-1].code = 3 + self.reconcile() + self.assertEqual(len(self.children), crash + 1, "no restart during the 5 s pause") + self.assertIn("exited (code 3); restarting", self.service.snapshot()["backends"][1]["error"]) + self.clock[0] += 6 + self.reconcile() + self.assertEqual(len(self.children), crash + 2) + self.children[-1].code = 3 + self.reconcile() + self.clock[0] += 60 + self.reconcile() + self.assertEqual(len(self.children), 5) + self.assertIn("keeps exiting", self.service.snapshot()["backends"][1]["error"]) + self.clock[0] += 300 + self.reconcile() + self.assertEqual(len(self.children), 6) + + def test_a_server_started_elsewhere_is_watched_not_duplicated(self): + self.external_ports.add(18082) + self.service.set_active("strata") + self.reconcile() + self.assertEqual(self.events, []) + snap = self.service.snapshot() + self.assertEqual((snap["backends"][0]["process"], snap["backends"][0]["pid"]), ("external", 1234)) + self.service.set_active("llama") + self.reconcile() + self.assertEqual(self.events, [("start", "llama")]) + self.assertIn("Strata is also running outside The Kurgan", self.service.snapshot()["warning"]) + self.service.set_active(None) + self.reconcile() + self.assertIn("Strata is running outside The Kurgan, from its own startup task", + self.service.snapshot()["warning"]) + + def claim_in_background(self, key): + result = {} + + def run(): + try: + result["backend"] = self.service.claim(key) + except Exception as e: + result["error"] = e + + thread = threading.Thread(target=run, daemon=True) + thread.start() + return thread, result + + def serve(self, key, port): + """Let the supervisor start key's server and have it 'listen'.""" + for _ in range(100): + if self.settings.get("ai", "active") == key: + break + threading.Event().wait(0.02) + self.reconcile() + self.external_ports.add(port) + + def test_a_request_starts_its_server_once_the_other_is_idle(self): + self.service.set_active("llama") + self.reconcile() + thread, result = self.claim_in_background("strata") + self.serve("strata", 18082) + thread.join(5) + self.assertEqual(result["backend"].key, "strata") + self.assertEqual(self.events, [("start", "llama"), ("stop", "llama"), ("start", "strata")]) + self.assertEqual(self.service.inflight["strata"], 1) + self.service.release("strata") + self.assertEqual(self.service.inflight["strata"], 0) + # The selected server's own requests go straight through. + self.assertEqual(self.service.claim("strata").key, "strata") + self.service.release("strata") + + def test_a_request_waits_while_the_other_server_is_busy(self): + self.service.set_active("llama") + self.reconcile() + self.external_ports.add(18083) + self.service.claim("llama") # a reply in progress + thread, result = self.claim_in_background("strata") + thread.join(0.3) + self.assertTrue(thread.is_alive()) + self.assertEqual(self.settings.get("ai", "active"), "llama") + self.service.release("llama") + self.external_ports.discard(18083) + self.serve("strata", 18082) + thread.join(5) + self.assertEqual(result["backend"].key, "strata") + + def test_a_request_gives_up_if_the_other_server_stays_busy(self): + self.service.set_active("llama") + self.reconcile() + self.external_ports.add(18083) + self.service.claim("llama") + thread, result = self.claim_in_background("strata") + thread.join(0.2) + self.clock[0] += AiService.BUSY_WAIT + 1 + with self.service._cv: + self.service._cv.notify_all() + thread.join(5) + self.assertIn("still busy", str(result["error"])) + self.assertEqual(self.service.inflight, {"strata": 0, "llama": 1}) + + def test_a_request_whose_client_hangs_up_never_switches_servers(self): + self.service.set_active("llama") + self.reconcile() + self.external_ports.add(18083) + self.service.claim("llama") # llama busy + hung_up = threading.Event() + result = {} + + def run(): + try: + self.service.claim("strata", gone=hung_up.is_set) + except RouteError as e: + result["error"] = e + + thread = threading.Thread(target=run, daemon=True) + thread.start() + thread.join(0.2) + hung_up.set() + self.service.release("llama") # llama now idle: a live request would switch here + thread.join(5) + self.assertEqual((result["error"].status, str(result["error"])), (CLIENT_GONE, "while waiting for Llama to finish")) + self.assertEqual(self.settings.get("ai", "active"), "llama") + self.assertEqual(self.service.inflight, {"strata": 0, "llama": 0}) + + # Hanging up while its own server starts also gives the place back. + self.external_ports.clear() # llama's port closes when it stops + self.service.set_active(None) + self.reconcile() + answers = iter([False] + [True] * 10) # still there when it asks for llama; gone while it starts + with self.assertRaises(RouteError) as caught: + self.service.claim("llama", gone=lambda: next(answers)) + self.assertEqual((caught.exception.status, str(caught.exception)), (CLIENT_GONE, "while waiting for Llama to start")) + self.assertEqual(self.service.inflight["llama"], 0) + + def test_an_unused_server_stops_after_the_idle_time(self): + self.service.set_active("llama") + self.reconcile() + self.assertEqual(self.service.snapshot()["backends"][1]["idle_stop_in"], 40 * 60) + self.clock[0] += 39 * 60 + self.reconcile() + self.assertEqual(self.processes()["llama"], "starting") + self.assertEqual(self.service.snapshot()["backends"][1]["idle_stop_in"], 60) + self.service.inflight["llama"] = 1 # a long request keeps it running + self.clock[0] += 5 * 60 + self.reconcile() + self.assertEqual(self.processes()["llama"], "starting") + self.service.release("llama") + self.clock[0] += 40 * 60 + 1 + self.reconcile() + self.assertEqual(self.processes()["llama"], "stopped") + self.assertIsNone(self.settings.get("ai", "active")) + self.settings.update("ai", idle_stop_minutes=0) # never + self.service.set_active("llama") + self.reconcile() + self.clock[0] += 24 * 3600 + self.reconcile() + self.assertEqual(self.processes()["llama"], "starting") + + +class LauncherTest(unittest.TestCase): + def test_child_runs_as_a_normal_user_with_its_output_logged(self): + with tempfile.TemporaryDirectory() as directory: + log_path = os.path.join(directory, "logs", "child.log") + child = launcher.launch(["cmd.exe", "/d", "/c", "echo hello from the child& exit 7"], directory, log_path) + try: + self.assertEqual(child.wait(10), 7) + self.assertEqual(child.token, {"integrity": "medium", "elevated": False}) + finally: + child.close() + with open(log_path, encoding="utf-8", errors="replace") as f: + self.assertIn("hello from the child", f.read()) + + def test_kill_ends_the_whole_job(self): + with tempfile.TemporaryDirectory() as directory: + child = launcher.launch(["cmd.exe", "/d", "/c", "ping -n 30 127.0.0.1"], directory, None) + try: + self.assertIsNone(child.poll()) + child.kill() + self.assertIsNotNone(child.wait(10)) + finally: + child.close() + + def test_pinned_openblas_setting_is_not_passed_on(self): + with patch.dict(os.environ, {"OPENBLAS_NUM_THREADS": "1", "KURGAN_PINNED_OPENBLAS": "1"}): + env = launcher.child_environment({"EXTRA": "x"}) + self.assertNotIn("OPENBLAS_NUM_THREADS", env) + self.assertNotIn("KURGAN_PINNED_OPENBLAS", env) + self.assertEqual(env["EXTRA"], "x") + with patch.dict(os.environ, {"OPENBLAS_NUM_THREADS": "4"}): + os.environ.pop("KURGAN_PINNED_OPENBLAS", None) + self.assertEqual(launcher.child_environment()["OPENBLAS_NUM_THREADS"], "4") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py new file mode 100644 index 0000000..12c1043 --- /dev/null +++ b/tests/test_dashboard.py @@ -0,0 +1,79 @@ +import unittest +from unittest.mock import patch + +from PIL import Image + +from kurgan.display.renderer import DashboardRenderer, H, MHZ_BOX, PART_BOX, SS, W +from kurgan.telemetry.readings import PowerReadings, Readings + + +class DashboardLayoutTest(unittest.TestCase): + def test_background_is_fitted_and_gauges_are_drawn_on_top(self): + background = Image.new("RGB", (20, 10), (160, 12, 24)) + with patch("kurgan.display.renderer.Image.open", side_effect=lambda path: background.copy()) as opened: + renderer = DashboardRenderer() + plate = renderer._plate() + self.assertTrue(opened.call_args.args[0].endswith("background.png")) + self.assertEqual(renderer._static.size, (W * SS, H * SS)) + self.assertEqual(plate.getpixel((240 * SS, 10 * SS))[:3], (160, 12, 24)) + self.assertNotEqual(renderer._static.getpixel((52 * SS, 66 * SS))[:3], (160, 12, 24)) + + def test_inner_gauges_leave_clear_gaps_to_power_tank(self): + renderer = DashboardRenderer() + plate = renderer._plate() + for x in (211, 269): + with self.subTest(x=x): + position = (x * SS, 66 * SS) + for actual, background in zip(renderer._static.getpixel(position), plate.getpixel(position)): + self.assertAlmostEqual(actual, background, delta=3) + + def test_device_readings_ranges_and_power_follow_swapped_sides(self): + renderer = DashboardRenderer() + cpu = Readings(temp=80, load=25, clock=4200, power=85) + gpu = Readings(temp=55, load=75, clock=2700, power=300) + power = PowerReadings(cpu=85, gpu=300, other=40) + with patch.object(renderer, "_arc_fill") as arcs, \ + patch.object(renderer, "_digits") as digits, \ + patch.object(renderer, "_readout") as readouts: + renderer.render(cpu, gpu, power) + + self.assertEqual( + [call.args[2:6] for call in arcs.call_args_list], + [(52.0, 66.0, 0.5, False), (152.0, 66.0, 0.75, False), + (428.0, 66.0, 0.75, False), (328.0, 66.0, 0.25, False)], + ) + self.assertEqual( + [call.args[2:] for call in digits.call_args_list], + [(52.0, 62.0, 55), (152.0, 62.0, 75), + (428.0, 62.0, 80), (328.0, 62.0, 25)], + ) + self.assertEqual( + [call.args[1:] for call in readouts.call_args_list[:4]], + [(renderer.halves[0].box(MHZ_BOX), 2700, "MHz"), + (renderer.halves[1].box(MHZ_BOX), 4200, "MHz"), + (renderer.halves[0].box(PART_BOX), 300, "W"), + (renderer.halves[1].box(PART_BOX), 85, "W")], + ) + self.assertEqual(readouts.call_args_list[2].kwargs["swatch"], renderer.theme.gpu_color) + self.assertEqual(readouts.call_args_list[3].kwargs["swatch"], renderer.theme.cpu_color) + + def test_glass_domes_reflect_upper_left_of_each_gauge_and_keep_digits_clear(self): + renderer = DashboardRenderer() + readings = Readings(temp=60, load=50, clock=3000, power=100) + with_glass = renderer.render(readings, readings) + renderer._dome_light[:] = 0 + renderer._dome_shade[:] = 1 + bare = renderer.render(readings, readings) + + def lum(img, xy): + return sum(img.getpixel(xy)) + + for cx in (52, 152, 328, 428): + with self.subTest(gauge=cx): + self.assertGreater(lum(with_glass, (cx - 16, 43)), lum(bare, (cx - 16, 43)) + 150) + self.assertLess(abs(lum(with_glass, (cx, 62)) - lum(bare, (cx, 62))), 40) + self.assertEqual(with_glass.getpixel((240, 4)), bare.getpixel((240, 4))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_fan_control.py b/tests/test_fan_control.py new file mode 100644 index 0000000..5291eb1 --- /dev/null +++ b/tests/test_fan_control.py @@ -0,0 +1,320 @@ +import argparse +import contextlib +import threading +import unittest +from unittest.mock import Mock, call, mock_open, patch + +from kurgan.cooling.board_fans import Nct6687 +from kurgan.cooling.control import CaseFanControl, CpuTemperature, TopFanCurve, cpu_duty, gpu_duty, parse_ports +from kurgan.telemetry.sensors import CommanderPro, corsair_software_running + + +class FanCurveTest(unittest.TestCase): + def test_cpu_curve_and_failsafe(self): + for temp, expected in ((30, 40), (50, 40), (60, 50), (70, 65), (75, 83), (80, 100), + (88, 100), (100, 100), (None, 100), (float("nan"), 100)): + with self.subTest(temp=temp): + self.assertEqual(cpu_duty(temp), expected) + + def test_temperature_curve_and_failsafe(self): + for temp, expected in ((20, 40), (40, 40), (50, 50), (55, 58), (60, 65), + (68, 93), (70, 100), (75, 100), (95, 100), + (None, 100), (float("nan"), 100), + (float("inf"), 100), (-1, 100), (111, 100)): + with self.subTest(temp=temp): + self.assertEqual(gpu_duty(temp), expected) + + def test_only_three_distinct_physical_ports_are_accepted(self): + self.assertEqual(parse_ports(" 4, 6, 5 "), (4, 6, 5)) + for text in ("", "1,2", "1,2,3,4", "1,1,2", "0,1,2", "4,5,7", "a,2,3"): + with self.subTest(text=text): + with self.assertRaises(argparse.ArgumentTypeError): + parse_ports(text) + + +class TopFanCurveTest(unittest.TestCase): + def setUp(self): + self.board = Mock(spec=Nct6687) + self.mask = 0 + self.duties = [] + self.board.manual_mask.side_effect = lambda: self.mask + + def manual(ch, duty): + self.mask |= 0x24 + self.duties.append(duty) + self.board.set_manual.side_effect = manual + self.board.set_auto.side_effect = lambda ch: setattr(self, "mask", self.mask & ~0x24) + self.top = TopFanCurve((2, 5), board_factory=lambda: self.board) + + def test_stopped_while_cool_kicks_on_start_and_follows_curve(self): + self.top.update(40, 44, 0) + self.assertEqual((self.top.duty, self.mask), (0, 0x24)) + self.top.update(40, 49, 1) + self.assertEqual(self.top.duty, 0) # below the start point + self.top.update(40, 50, 2) + self.assertEqual(self.top.duty, 40) # spin-up kick + self.top.update(40, 55, 5) + self.assertEqual(self.top.duty, 45) + for now, temp, duty in ((6, 60, 60), (7, 65, 80), (8, 70, 100), (9, 90, 100)): + self.top.update(40, temp, now) + self.assertEqual(self.top.duty, duty) + + def test_stop_has_hysteresis_and_hold_time(self): + self.top.update(40, 52, 0) + for now in range(3, 40): + self.top.update(40, 46, now) # between stop and start: keeps running at minimum + self.assertEqual(self.top.duty, 30) + self.top.update(40, 44, 40) + self.top.update(40, 44, 69) + self.assertEqual(self.top.duty, 30) + self.top.update(40, 44, 70) + self.assertEqual(self.top.duty, 0) + + def test_falls_slowly_and_case_fan_boost_forces_full_speed(self): + self.top.update(40, 70, 0) + self.top.update(40, 60, 5) + self.assertEqual(self.top.duty, 100) # holds after a rise + self.top.update(40, 60, 11) + self.assertEqual(self.top.duty, 96) # 2% per second + self.top.update(85, 40, 12) + self.assertEqual((self.top.duty, self.top.boosted), (100, True)) + self.top.update(66, 40, 13) + self.assertTrue(self.top.boosted) + self.top.update(65, 40, 14) + self.assertFalse(self.top.boosted) + + def test_invalid_temperature_is_failsafe_full_speed(self): + with self.assertLogs("kurgan.cooling.control", level="WARNING"): + self.top.update(40, None, 0) + self.assertEqual(self.top.duty, 100) + self.assertIn("FAILSAFE", self.top.status) + + def test_firmware_reset_is_corrected(self): + self.top.update(40, 40, 0) + self.top.update(40, 40, 1) + self.assertEqual(self.board.set_manual.call_count, 1) # unchanged duty is not rewritten + self.mask = 0x04 # one channel reverted to the BIOS after sleep + self.top.update(40, 40, 2) + self.assertEqual(self.board.set_manual.call_count, 2) + + def test_unavailable_board_reports_and_retries_later(self): + factory = Mock(side_effect=OSError("run as administrator")) + top = TopFanCurve((2, 5), board_factory=factory) + with self.assertLogs("kurgan.cooling.control", level="WARNING"): + top.update(100, 60, 0) + self.assertIn("UNAVAILABLE", top.status) + top.update(100, 60, 10) + self.assertEqual(factory.call_count, 1) + factory.side_effect = None + factory.return_value = self.board + top.update(100, 60, 31) + self.board.set_manual.assert_called_once_with((2, 5), 100) + + def test_gpu_worker_drives_top_fans_and_releases_them_on_exit(self): + commander = Mock(spec=CommanderPro) + commander.set_duty.return_value = {p: 900 for p in range(1, 7)} + control = CaseFanControl(commander, (4, 5, 6), None, self.top) + control.update(40, 0) # startup runs the case fans at 100% + self.assertTrue(self.top.boosted) + stop = threading.Event() + stop.set() + with patch("kurgan.cooling.control.GpuSensors"): + control.run(stop) + self.assertEqual(self.mask, 0) + self.board.close.assert_called() + + def test_top_fans_follow_the_hotter_side(self): + commander = Mock(spec=CommanderPro) + commander.set_duty.return_value = {p: 900 for p in range(1, 7)} + control = CaseFanControl(commander, (4, 5, 6), (1, 2, 3), self.top) + for now in range(70): # startup boost ends, then the top fans stop after the hold time + control.update(40, now, 44) + self.assertEqual((control.gpu.duty, control.cpu.duty, self.top.boosted), (40, 40, False)) + self.assertEqual(self.top.duty, 0) + control.update(40, 70, 60) # CPU hotter than GPU + self.assertEqual(self.top.duty, 60) + control.update(40, 71, None) + self.assertEqual(self.top.duty, 100) + + def test_cpu_side_follows_cpu_temperature_and_can_boost_alone(self): + commander = Mock(spec=CommanderPro) + commander.set_duty.return_value = {p: 900 for p in range(1, 7)} + control = CaseFanControl(commander, (4, 5, 6), (1, 2, 3), self.top) + for now in range(40): + control.update(40, now, 50) + self.assertEqual((control.gpu.duty, control.cpu.duty), (40, 40)) + self.assertFalse(self.top.boosted) + commander.set_duty.assert_any_call((1, 2, 3), 40) + control.update(40, 40, 78) # CPU hot, GPU cool + commander.set_duty.assert_any_call((1, 2, 3), 93) + self.assertEqual(control.gpu.duty, 40) + self.assertTrue(self.top.boosted) + control.update(40, 41, None) + self.assertIn("FAILSAFE", control.cpu.status) + self.assertNotIn("FAILSAFE", control.gpu.status) + with self.assertRaises(ValueError): + CaseFanControl(commander, (4, 5, 6), (1, 2, 4)) + + def test_cpu_temperature_is_averaged_and_gaps_are_not(self): + pkg = Mock() + pkg.temperature.side_effect = [50, 90, None, 60] + cpu = CpuTemperature(factory=lambda: pkg) + self.assertEqual(cpu.read(0), 50) + self.assertEqual(cpu.read(1), 70) + self.assertIsNone(cpu.read(2)) + self.assertEqual(cpu.read(3), 60) + + +class Nct6687ControlTest(unittest.TestCase): + def test_override_uses_config_handshake_and_keeps_other_channels(self): + nct = Nct6687.__new__(Nct6687) + nct._bus = contextlib.nullcontext + nct.read = Mock(return_value=0x01) + nct.write = Mock() + with patch("kurgan.cooling.board_fans.time.sleep"): + nct.set_manual((2, 5), 100) + self.assertEqual(nct.write.call_args_list, [ + call(0xA01, 0x80), call(0xA00, 0x25), call(0xA2A, 255), call(0xA2D, 255), call(0xA01, 0x40)]) + nct.write.reset_mock() + nct.read.return_value = 0x25 + nct.set_auto((2, 5)) + self.assertEqual(nct.write.call_args_list, [call(0xA01, 0x80), call(0xA00, 0x01), call(0xA01, 0x40)]) + with self.assertRaises(ValueError): + nct.set_manual((8,), 100) + + +class FanWorkerTest(unittest.TestCase): + def setUp(self): + self.commander = Mock(spec=CommanderPro) + self.commander.set_duty.return_value = {p: 900 for p in range(1, 7)} + self.control = CaseFanControl(self.commander, (4, 5, 6)) + + def settle(self, temp=50): + for now in range(36): + self.control.update(temp, now) + + def test_rises_immediately_and_falls_slowly_after_hold(self): + self.control.update(40, 0) + self.commander.set_duty.assert_called_with((4, 5, 6), 100) + self.control.update(40, 9) + self.commander.set_duty.assert_called_with((4, 5, 6), 100) + for now in range(10, 45): + self.control.update(50, now) + self.commander.set_duty.assert_called_with((4, 5, 6), 50) + self.control.update(68, 45) + self.commander.set_duty.assert_called_with((4, 5, 6), 93) + for now in range(46, 55): + self.control.update(40, now) + self.commander.set_duty.assert_called_with((4, 5, 6), 93) + self.control.update(40, 55) + self.commander.set_duty.assert_called_with((4, 5, 6), 91) + + def test_missing_sensor_and_delayed_worker_use_full_speed(self): + self.settle() + self.control.update(None, 36) + self.commander.set_duty.assert_called_with((4, 5, 6), 100) + self.assertIn("FAILSAFE", self.control.status) + for now in range(37, 73): + self.control.update(50, now) + self.commander.set_duty.assert_called_with((4, 5, 6), 50) + self.control.update(40, 85) + self.commander.set_duty.assert_called_with((4, 5, 6), 100) + + def test_stalled_selected_fan_forces_full_speed_but_other_side_does_not(self): + self.commander.set_duty.return_value = {1: 0, 4: 900, 5: 900, 6: 900} + self.settle() + self.assertNotIn("FAILSAFE", self.control.status) + self.commander.set_duty.return_value = {4: 900, 5: 0, 6: 900} + self.control.update(50, 36) + self.commander.set_duty.assert_called_with((4, 5, 6), 100) + self.assertIn("FAILSAFE", self.control.status) + self.assertIn("[5]", self.control.status) + + def test_exit_leaves_selected_ports_at_full_speed_even_without_lcd(self): + stop = threading.Event() + stop.set() + with patch("kurgan.cooling.control.GpuSensors"): + self.control.run(stop) + self.commander.set_duty.assert_called_once_with((4, 5, 6), 100) + self.commander.close.assert_called_once() + + def test_worker_error_is_visible_and_attempts_failsafe(self): + stop = threading.Event() + gpu = Mock() + gpu.read.side_effect = RuntimeError("sensor failure") + with patch("kurgan.cooling.control.GpuSensors", return_value=gpu): + with self.assertLogs("kurgan.cooling.control", level="ERROR"): + self.control.run(stop) + self.assertIn("CONTROL ERROR", self.control.status) + self.commander.set_duty.assert_called_once_with((4, 5, 6), 100) + + +class CommanderControlTest(unittest.TestCase): + def setUp(self): + self.commander = CommanderPro() + self.commander.ports = list(range(6)) + self.commander.ch = Mock() + self.commander._corsair_software_running = Mock(return_value=False) + self.commander._open = Mock() + + def reply(self, op, *args): + if op == 0x20: + return bytes((0, 0, 2, 2, 2, 2, 2, 2)) + if op == 0x21: + return bytes((0, 0, 3, 132)) # 900 RPM + return bytes(4) + + def test_only_confirmed_side_receives_duty_commands(self): + self.commander._cmd = Mock(side_effect=self.reply) + rpms = self.commander.set_duty((4, 5, 6), 81) + writes = [c.args for c in self.commander._cmd.call_args_list if c.args[0] == 0x23] + self.assertEqual(writes, [(0x23, 3, 81), (0x23, 4, 81), (0x23, 5, 81)]) + self.assertEqual(rpms, {p: 900 for p in range(1, 7)}) + self.commander.controlled = True + self.commander._cmd.reset_mock() + self.assertEqual(self.commander.read(), [900] * 6) + self.commander._cmd.assert_not_called() + + def test_disconnected_or_dc_port_rejected_before_any_write(self): + for modes in (bytes((0, 0, 2, 2, 0, 2, 2, 2)), + bytes((0, 0, 2, 2, 1, 2, 2, 2)), bytes(4)): + self.commander._cmd = Mock(return_value=modes) + with self.assertRaises(OSError): + self.commander.set_duty((1, 2, 3), 80) + self.commander._cmd.assert_called_once_with(0x20) + + def test_competing_software_prevents_all_usb_writes(self): + self.commander._corsair_software_running.return_value = True + self.commander._cmd = Mock() + with self.assertRaisesRegex(OSError, "busy"): + self.commander.set_duty((1, 2, 3), 100) + self.commander._cmd.assert_not_called() + self.assertIsNone(self.commander.ch) + + def test_openrgb_counts_as_released_only_when_detector_disabled_everywhere(self): + commander = CommanderPro() + disabled = '{"Detectors":{"detectors":{"Corsair Commander Pro":false}}}' + configs = {"user": disabled, "service": disabled} + + def fake_open(path, *args, **kwargs): + return mock_open(read_data=configs["service" if "service_config" in path else "user"])() + + with patch("kurgan.telemetry.sensors._process_names", return_value=["openrgb.exe"]), \ + patch("kurgan.telemetry.sensors.os.path.exists", return_value=True), \ + patch("builtins.open", side_effect=fake_open): + self.assertFalse(commander._corsair_software_running()) + configs["service"] = disabled.replace("false", "true") + with self.assertLogs("kurgan.telemetry.sensors", level="WARNING"): + self.assertTrue(commander._corsair_software_running()) + with patch("kurgan.telemetry.sensors._process_names", return_value=["openrgb.exe"]), \ + patch("kurgan.telemetry.sensors.os.path.exists", return_value=True), \ + patch("builtins.open", side_effect=OSError("missing config")): + with self.assertLogs("kurgan.telemetry.sensors", level="WARNING"): + self.assertTrue(commander._corsair_software_running()) + with patch("kurgan.telemetry.sensors._process_names", return_value=["fancontrol.exe"]): + self.assertTrue(commander._corsair_software_running()) + self.assertFalse(corsair_software_running("Corsair Lighting Node Core", fan_tools=False)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_gpu_lighting.py b/tests/test_gpu_lighting.py new file mode 100644 index 0000000..068c0e4 --- /dev/null +++ b/tests/test_gpu_lighting.py @@ -0,0 +1,113 @@ +import unittest +from unittest.mock import Mock, patch + +from kurgan.lighting.gpu import ( + AsusGpuLeds, GpuLighting, NvidiaI2c, gpu_chase_frame, +) +from kurgan.lighting.case_fans import ChaseTiming, side_chase_color + + +class FakeBus(NvidiaI2c): + def __init__(self, firmware=b"AUMA0-E6K5-1110"): + self.register = 0 + self.values = {0x1000 + i: value for i, value in enumerate(firmware.ljust(16, b"\0"))} + self.values[0x1C03] = 4 + self.values[0x8020] = 0 + self.writes = [] + + def transfer(self, command, data, *, read=False): + if command == 0: + self.register = int.from_bytes(data, "big") + elif read: + return bytes((self.values.get(self.register, 0),)) + else: + self.writes.append((self.register, command, data)) + return data + + +class GpuTransportTest(unittest.TestCase): + def setUp(self): + self.conflict = patch("kurgan.lighting.gpu.corsair_software_running", return_value=False) + self.conflict.start() + self.addCleanup(self.conflict.stop) + self.processes = patch("kurgan.lighting.gpu._process_names", return_value=[]) + self.processes.start() + self.addCleanup(self.processes.stop) + + def test_direct_colors_use_rbg_order_skip_unchanged_and_restore_without_saving(self): + bus = FakeBus() + driver = AsusGpuLeds(lambda: bus) + driver.open() + self.assertEqual(bus.writes, []) + colors = ((24, 0, 0), (255, 48, 0), (24, 0, 0), (24, 0, 0)) + driver.show_frame(colors) + self.assertEqual(bus.writes[1], (0x8103, 3, bytes((3, 255, 0, 48)))) + self.assertEqual(bus.writes[-2:], [(0x8020, 1, b"\x01"), (0x80A0, 1, b"\x01")]) + bus.writes.clear() + driver.show_frame(colors) + self.assertEqual(bus.writes, []) + driver.show_frame((colors[0], colors[0], colors[2], colors[3])) + self.assertEqual(bus.writes, [(0x8103, 3, bytes((3, 24, 0, 0)))]) + driver.close() + self.assertEqual(bus.writes[-2:], [(0x8020, 1, b"\x00"), (0x80A0, 1, b"\x01")]) + self.assertFalse(any(data == b"\xaa" for _, _, data in bus.writes)) + + def test_unknown_firmware_and_invalid_frames_do_not_write_lighting_registers(self): + bus = FakeBus(b"UNKNOWN") + driver = AsusGpuLeds(lambda: bus) + with self.assertRaises(OSError): + driver.open() + self.assertEqual(bus.writes, []) + bus = FakeBus() + driver = AsusGpuLeds(lambda: bus) + driver.open() + with self.assertRaises(ValueError): + driver.show_frame(((256, 0, 0),) * 4) + self.assertEqual(bus.writes, []) + + +class GpuChaseTest(unittest.TestCase): + def test_row_reverses_at_each_end_once_per_shared_cycle(self): + for count in (4, 30): + route_length = 2 * (count - 1) + heads = [] + for step in range(route_length + 1): + phase = 6 + step * 36 / route_length + 0.000001 + frame = gpu_chase_frame(phase, count) + heads.append(frame.index(side_chase_color(1))) + self.assertEqual(heads, list(range(count - 1, -1, -1)) + list(range(1, count))) + self.assertEqual(gpu_chase_frame(6, count), gpu_chase_frame(42, count)) + + def test_worker_joins_shared_clock_caps_writes_and_releases_on_off(self): + clock = ChaseTiming() + clock.reset(6) + clock.set_power(550) + driver = Mock() + driver.led_count = 4 + lighting = GpuLighting(clock, lambda: driver) + writes = [] + for tick in range(101): + now = 100 + tick * 0.01 + before = driver.show_frame.call_count + with patch("kurgan.lighting.gpu.time.monotonic", return_value=now): + lighting.update(True) + if driver.show_frame.call_count != before: + writes.append(now) + self.assertAlmostEqual(clock.phase, 46) + self.assertTrue(all(b - a >= 0.045 for a, b in zip(writes, writes[1:]))) + lighting.update(False) + driver.close.assert_called_once() + self.assertEqual(lighting.status, "off") + + def test_connection_failure_is_visible_and_retries_after_backoff(self): + driver = Mock() + driver.open.side_effect = OSError("GPU busy") + factory = Mock(return_value=driver) + lighting = GpuLighting(ChaseTiming(), factory) + with patch("kurgan.lighting.gpu.time.monotonic", return_value=100), \ + self.assertLogs("kurgan.lighting.gpu", level="WARNING"): + lighting.update(True) + with patch("kurgan.lighting.gpu.time.monotonic", return_value=105): + lighting.update(True) + factory.assert_called_once() + self.assertEqual(lighting.status, "unavailable: GPU busy") diff --git a/tests/test_lighting_service.py b/tests/test_lighting_service.py new file mode 100644 index 0000000..ad88f34 --- /dev/null +++ b/tests/test_lighting_service.py @@ -0,0 +1,78 @@ +import os +import tempfile +import unittest +from unittest.mock import patch + +from kurgan.lighting.service import LightingService +from kurgan.settings import Settings +from kurgan.theme import Theme + + +class FakeWorker: + status = "running" + + def set_temperature(self, cpu, gpu): + pass + + def set_power(self, watts): + pass + + +class LightingServiceTest(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + self.settings = Settings(os.path.join(self.dir.name, "settings.json"), None) + + def service(self, overrides=None): + return LightingService(self.settings, Theme(), (0.15, 0.025, 150.0, 550.0), overrides, + rgb=FakeWorker(), memory=FakeWorker(), gpu=FakeWorker()) + + def active(self, service, zone): + return sorted(mode for mode, event in service._events[zone].items() if event.is_set()) + + def test_saved_modes_start_and_switch_exclusively(self): + self.settings.update("lighting", memory="temperature") + service = self.service() + self.assertEqual(self.active(service, "memory"), ["temperature"]) + service.set_mode("memory", "chase") + self.assertEqual(self.active(service, "memory"), ["chase"]) + self.assertEqual(self.active(service, "case_fans"), []) + service.set_mode("memory", "off") + self.assertEqual(self.active(service, "memory"), []) + self.assertEqual(Settings(self.settings.path, None).get("lighting", "memory"), "off") + + def test_failed_save_leaves_the_lights_as_they_were(self): + service = self.service() + service.set_mode("gpu", "chase") + with patch("kurgan.settings.os.replace", side_effect=OSError("disk full")), self.assertRaises(OSError): + service.set_mode("gpu", "off") + self.assertEqual(service.mode("gpu"), "chase") + self.assertEqual(self.active(service, "gpu"), ["chase"]) + + def test_unknown_zone_or_mode_is_rejected(self): + service = self.service() + for zone, mode in (("gpu", "temperature"), ("keyboard", "off"), ("memory", "rainbow")): + with self.subTest(zone=zone, mode=mode), self.assertRaises(ValueError): + service.set_mode(zone, mode) + + def test_command_line_overrides_are_for_this_run_until_chosen(self): + service = self.service({"case_fans": "chase"}) + zone = service.snapshot()["zones"][0] + self.assertEqual((zone["key"], zone["mode"], zone["this_run_only"]), ("case_fans", "chase", True)) + self.assertEqual(self.settings.get("lighting", "case_fans"), "off") + service.set_mode("case_fans", "chase") + self.assertFalse(service.snapshot()["zones"][0]["this_run_only"]) + self.assertEqual(self.settings.get("lighting", "case_fans"), "chase") + + def test_chase_speed_is_reported_only_while_a_chase_runs(self): + service = self.service() + self.assertIsNone(service.snapshot()["chase_ms_per_led"]) + service.set_mode("gpu", "chase") + self.assertEqual(service.snapshot()["chase_ms_per_led"], 150) # idle pace before any power reading + service.on_telemetry(50, 50, 550.0) + self.assertEqual(service.snapshot()["chase_ms_per_led"], 25) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_memory_lighting.py b/tests/test_memory_lighting.py new file mode 100644 index 0000000..1531c24 --- /dev/null +++ b/tests/test_memory_lighting.py @@ -0,0 +1,383 @@ +import unittest +import threading +from unittest.mock import Mock, patch + +from kurgan.theme import Theme +from kurgan.lighting.memory import ( + MemoryFrame, MemoryLighting, PawnIoSmbus, _crc8, _led_packet, _rgb_bytes, + _solid_frame, memory_chase_frame, memory_chase_step, +) +from kurgan.lighting.case_fans import ChaseTiming, RGBLighting, side_chase_frame + + +class FakeDriver: + def __init__(self): + self.open_count = 0 + self.closed = 0 + self.frames: list[MemoryFrame] = [] + self.forced: list[bool] = [] + + def open(self): + self.open_count += 1 + + def show(self, color): + self.frames.append(_solid_frame(color)) + + def show_frame(self, colors, *, force=False): + self.frames.append(colors) + self.forced.append(force) + + def close(self): + self.closed += 1 + + +class MemoryLightingTest(unittest.TestCase): + def setUp(self): + self.theme = Theme() + self.driver = FakeDriver() + self.lighting = MemoryLighting(self.theme, driver_factory=lambda: self.driver) + + def test_disabled_start_keeps_ram_dark(self): + self.lighting.update(40, False) + self.assertEqual(self.lighting.status, "RAM lighting off") + self.assertEqual(self.driver.open_count, 1) + self.assertEqual(self.driver.frames, [_solid_frame((0, 0, 0))]) + + def test_temperature_control_updates_all_modules_and_stays_dark_when_disabled(self): + color = (24, 0, 0) + hot = (255, 48, 0) + with patch("kurgan.lighting.memory.time.monotonic", return_value=100.0): + self.lighting.update(40, True) + self.assertEqual(self.driver.open_count, 1) + self.assertEqual(self.driver.frames, [_solid_frame(color)]) + self.assertEqual(self.lighting.status, "RAM temperature lighting active (CPU 40 °C)") + + with patch("kurgan.lighting.memory.time.monotonic", return_value=101.0): + self.lighting.update(85, True) + self.assertEqual(self.driver.frames, [_solid_frame(color), _solid_frame(hot)]) + + with patch("kurgan.lighting.memory.time.monotonic", return_value=102.0): + self.lighting.update(85, False) + self.assertEqual(self.driver.frames[-1], _solid_frame((0, 0, 0))) + self.assertEqual(self.lighting.status, "RAM lighting off") + + with patch("kurgan.lighting.memory.time.monotonic", return_value=107.0): + self.lighting.update(None, False) + self.assertEqual(self.driver.frames, [_solid_frame(c) for c in (color, hot, (0, 0, 0), (0, 0, 0))]) + + self.lighting.close() + self.assertEqual(self.driver.frames[-1], _solid_frame((0, 0, 0))) + self.assertEqual(self.driver.closed, 1) + + def test_missing_temperature_neither_claims_the_bus_nor_replaces_a_live_color(self): + with patch("kurgan.lighting.memory.time.monotonic", return_value=100.0): + self.lighting.update(None, True) + self.assertEqual(self.lighting.status, "RAM temperature lighting waiting for CPU/GPU temperature") + self.assertEqual(self.driver.open_count, 0) + + with patch("kurgan.lighting.memory.time.monotonic", return_value=101.0): + self.lighting.update(60, True) + color = self.driver.frames[-1] + with patch("kurgan.lighting.memory.time.monotonic", return_value=102.0): + self.lighting.update(None, True) + self.assertEqual(self.driver.frames, [color]) + self.assertEqual(self.lighting.status, "RAM temperature lighting waiting for CPU/GPU temperature") + + def test_red_orange_ramp_uses_hottest_valid_sensor_and_clamps_at_thresholds(self): + cases = ( + (40, 35, (24, 0, 0), "CPU 40"), + (40, 65, (140, 24, 0), "GPU 65"), + (80, 65, (255, 48, 0), "CPU 80"), + (60, 95, (255, 48, 0), "GPU 95"), + (None, 50, (24, 0, 0), "GPU 50"), + (float("nan"), 65, (140, 24, 0), "GPU 65"), + (65, float("inf"), (140, 24, 0), "CPU 65"), + ) + for cpu, gpu, expected, source in cases: + with self.subTest(cpu=cpu, gpu=gpu): + self.lighting.update(cpu, True, gpu_temp=gpu) + self.assertEqual(self.driver.frames[-1], _solid_frame(expected)) + self.assertIn(source, self.lighting.status) + self.lighting.update(float("nan"), True, gpu_temp=float("inf")) + self.assertEqual(self.driver.frames[-1], _solid_frame((140, 24, 0))) + self.assertEqual(self.lighting.status, "RAM temperature lighting waiting for CPU/GPU temperature") + + def test_worker_uses_both_temperatures_from_sensor_handoff(self): + stop, enabled = Mock(), Mock() + stop.is_set.side_effect = [False, True] + enabled.is_set.return_value = True + self.lighting.set_temperature(40, 80) + self.lighting.run(stop, enabled) + self.assertEqual(self.driver.frames, [_solid_frame((255, 48, 0)), _solid_frame((0, 0, 0))]) + + def test_invalid_temperature_range_is_rejected(self): + for warn, hot in ((80, 80), (90, 80), (float("nan"), 80), (50, float("inf"))): + with self.subTest(warn=warn, hot=hot), self.assertRaises(ValueError): + MemoryLighting(Theme(temp_warn=warn, temp_hot=hot)) + + def test_failed_connection_retries_after_backoff(self): + factory = Mock(side_effect=[OSError("PawnIO denied"), self.driver]) + self.lighting = MemoryLighting(self.theme, driver_factory=factory) + with patch("kurgan.lighting.memory.time.monotonic", return_value=100.0): + with self.assertLogs("kurgan.lighting.memory", level="WARNING"): + self.lighting.update(40, True) + self.assertEqual(self.lighting.status, "PawnIO denied") + with patch("kurgan.lighting.memory.time.monotonic", return_value=105.0): + self.lighting.update(40, True) + self.assertEqual(factory.call_count, 1) + with patch("kurgan.lighting.memory.time.monotonic", return_value=110.0): + self.lighting.update(40, True) + self.assertEqual(factory.call_count, 2) + self.assertEqual(len(self.driver.frames), 1) + + def test_chase_uses_elapsed_time_with_capped_writes_and_power_acceleration(self): + self.lighting.set_power(550) + with patch("kurgan.lighting.memory.time.monotonic", return_value=100): + self.lighting.update(None, False, side_chase=True) + for index in range(1, 50): + with patch("kurgan.lighting.memory.time.monotonic", return_value=100 + index * 0.01): + self.lighting.update(None, False, side_chase=True) + with patch("kurgan.lighting.memory.time.monotonic", return_value=100.5): + self.lighting.update(None, False, side_chase=True) + self.assertGreaterEqual(len(self.driver.frames), 10) + self.assertLessEqual(len(self.driver.frames), 12) + self.assertAlmostEqual(self.lighting._chase_timing.phase, 26) + self.assertIn(self.driver.frames[-1], tuple(memory_chase_frame(step) for step in range(23, 26))) + self.assertEqual(self.lighting.status, "RAM red side chase active (0.9 s/cycle at 550 W)") + + self.lighting = MemoryLighting(self.theme, lambda: self.driver) + self.lighting.set_power(150) + with patch("kurgan.lighting.memory.time.monotonic", return_value=200): + self.lighting.update(None, False, side_chase=True) + with patch("kurgan.lighting.memory.time.monotonic", return_value=200.5): + self.lighting.update(None, False, side_chase=True) + self.lighting.set_power(550) + with patch("kurgan.lighting.memory.time.monotonic", return_value=200.6): + self.lighting.update(None, False, side_chase=True) + self.assertAlmostEqual(self.lighting._chase_timing.rate, 10) + self.assertAlmostEqual(self.lighting._chase_timing.phase, 6 + 13 / 3) + + def test_pattern_switches_and_off_bypass_chase_frame_cap(self): + with patch("kurgan.lighting.memory.time.monotonic", return_value=100): + self.lighting.update(None, False, side_chase=True) + with patch("kurgan.lighting.memory.time.monotonic", return_value=100.01): + self.lighting.update(65, True) + with patch("kurgan.lighting.memory.time.monotonic", return_value=100.02): + self.lighting.update(None, False) + with patch("kurgan.lighting.memory.time.monotonic", return_value=100.03): + self.lighting.update(None, False, side_chase=True) + self.assertEqual(self.driver.frames, [ + memory_chase_frame(5), _solid_frame((140, 24, 0)), + _solid_frame((0, 0, 0)), memory_chase_frame(5), + ]) + with patch("kurgan.lighting.memory.time.monotonic", return_value=105.03): + self.lighting.update(None, False, side_chase=True) + self.assertTrue(self.driver.forced[-1]) + self.lighting.close() + self.assertEqual(self.driver.frames[-1], _solid_frame((0, 0, 0))) + + def test_fast_chase_worker_avoids_large_position_jumps_with_fan_refresh_budget(self): + now = [100.0] + stop = Mock() + stop.is_set.side_effect = lambda: now[0] > 101 + stop.wait.side_effect = lambda delay: now.__setitem__(0, now[0] + delay) + chase = threading.Event() + chase.set() + self.lighting.set_power(550) + writes = [] + show_frame = self.driver.show_frame + + def record(colors, *, force=False): + writes.append((now[0], int(self.lighting._chase_timing.phase))) + show_frame(colors, force=force) + + with patch("kurgan.lighting.memory.time.monotonic", side_effect=lambda: now[0]), \ + patch.object(self.driver, "show_frame", side_effect=record): + self.lighting.run(stop, threading.Event(), chase) + self.assertGreaterEqual(len(writes), 16) + self.assertLessEqual(len(writes), 23) + self.assertTrue(all(b[0] - a[0] >= 0.045 for a, b in zip(writes, writes[1:]))) + self.assertLessEqual(max(b[1] - a[1] for a, b in zip(writes, writes[1:])), 3) + self.assertGreaterEqual(writes[-1][1], 42) + + def test_worker_accepts_chase_without_temperature_readings(self): + stop = Mock() + stop.is_set.side_effect = [False, True] + chase = threading.Event() + chase.set() + self.lighting.run(stop, threading.Event(), chase) + self.assertEqual(self.driver.frames, [memory_chase_frame(5), _solid_frame((0, 0, 0))]) + + def test_moving_chase_still_refreshes_unchanged_sticks_every_five_seconds(self): + for index in range(11): + with patch("kurgan.lighting.memory.time.monotonic", return_value=100 + index * 0.5): + self.lighting.update(None, False, side_chase=True) + self.assertEqual(self.driver.forced, [True] + [False] * 9 + [True]) + +class MemoryChaseTest(unittest.TestCase): + def test_mirrored_heads_follow_six_visits_without_repeating_end_sticks(self): + positions = ( + (0, 3, 0), (5, 3, 5), (6, 2, 5), (11, 2, 0), + (12, 1, 0), (17, 1, 5), (18, 0, 5), (23, 0, 0), + (24, 1, 0), (29, 1, 5), (30, 2, 5), (35, 2, 0), + (36, 3, 0), (41, 3, 5), + ) + for step, stick, left in positions: + with self.subTest(step=step): + frame = memory_chase_frame(step) + heads = [(row, led) for row, colors in enumerate(frame) + for led, color in enumerate(colors) if color == (255, 48, 0)] + self.assertEqual(heads, [(stick, left), (stick, 11 - left)]) + for step in range(36): + frame = memory_chase_frame(step) + self.assertEqual(len(frame), 4) + for colors in frame: + self.assertEqual(len(colors), 12) + self.assertEqual(colors[:6], colors[6:][::-1]) + self.assertEqual(frame, memory_chase_frame(step + 36)) + + def test_four_led_fading_trail_matches_fan_palette(self): + frame = memory_chase_frame(10) + self.assertEqual(frame[2][1:6], ((255, 48, 0), (209, 38, 0), (163, 29, 0), + (116, 19, 0), (70, 10, 0))) + self.assertEqual(frame[3], ((24, 0, 0),) * 12) + + +class SharedChaseTest(unittest.TestCase): + def setUp(self): + self.clock = ChaseTiming(0.125) + self.clock.reset(6) + self.node = Mock() + self.node.firmware = "0.9.16" + self.driver = FakeDriver() + self.fans = RGBLighting(Theme(), node_factory=lambda: self.node, chase_timing=self.clock) + self.memory = MemoryLighting(Theme(), lambda: self.driver, self.clock) + self.fans.set_power(150) + + def test_whole_cycles_share_physical_bottom_and_top_anchors(self): + for index, (now, fan_step, ram_step) in enumerate(((100, 6, 5), (102.25, 24, 23), (104.5, 42, 41))): + with self.subTest(now=now), patch("time.monotonic", return_value=now): + if index % 2: + self.memory.update(None, False, side_chase=True) + self.fans.update(None, False, side_chase=True) + else: + self.fans.update(None, False, side_chase=True) + self.memory.update(None, False, side_chase=True) + self.assertEqual(self.node.show.call_args.args[1], side_chase_frame(fan_step)) + self.assertEqual(self.driver.frames[-1], memory_chase_frame(ram_step)) + self.assertEqual(self.memory.status, "RAM red side chase active (4.5 s/cycle)") + + def test_joining_and_switching_patterns_never_resets_shared_phase(self): + with patch("time.monotonic", return_value=100): + self.fans.update(None, False, side_chase=True) + with patch("time.monotonic", return_value=102.25): + self.fans.update(None, False, side_chase=True) + self.memory.update(None, False, side_chase=True) + self.assertEqual(self.driver.frames[-1], memory_chase_frame(23)) + with patch("time.monotonic", return_value=102.26): + self.memory.update(65, True) + with patch("time.monotonic", return_value=102.75): + self.fans.update(None, False, side_chase=True) + self.memory.update(None, False, side_chase=True) + self.assertEqual(self.clock.phase, 28) + self.assertEqual(self.driver.frames[-1], memory_chase_frame(memory_chase_step(28))) + with patch("time.monotonic", return_value=103): + self.fans.update(None, False) + with patch("time.monotonic", return_value=103.5): + self.memory.update(None, False, side_chase=True) + self.assertEqual(self.clock.phase, 34) + + def test_out_of_order_worker_timestamps_do_not_double_count_elapsed_time(self): + self.clock.sample(100) + self.clock.sample(100.5) + phase, _ = self.clock.sample(100.25) + self.assertEqual(phase, 10) + phase, _ = self.clock.sample(101) + self.assertEqual(phase, 14) + + def test_load_change_has_one_acceleration_and_phase_for_both_patterns(self): + with patch("time.monotonic", return_value=100): + self.fans.update(None, False, side_chase=True) + self.memory.update(None, False, side_chase=True) + self.memory.set_power(550) + with patch("time.monotonic", return_value=100.5): + self.memory.update(None, False, side_chase=True) + self.fans.update(None, False, side_chase=True) + self.assertEqual(self.clock.rate, 24) + self.assertEqual(self.clock.phase, 18) + self.assertEqual(self.node.show.call_args.args[1], side_chase_frame(18)) + self.assertEqual(self.driver.frames[-1], memory_chase_frame(17)) + + +class CorsairDramPacketTest(unittest.TestCase): + def test_direct_packet_contains_twelve_rgb_leds_and_crc8(self): + color = (12, 34, 56) + packet = _led_packet((color,) * 12) + payload = bytes((12,)) + bytes(color) * 12 + self.assertEqual(len(packet), 38) + self.assertEqual(packet[:-1], payload) + self.assertEqual(packet[-1], _crc8(payload)) + self.assertEqual(_crc8(b"123456789"), 0xF4) + + def test_direct_frame_only_writes_all_four_controllers_without_saving_effects(self): + bus = PawnIoSmbus() + calls = [] + bus._write_block = lambda address, register, data: calls.append((address, register, data)) + with patch("kurgan.lighting.memory.PawnIoSmbus._bus"): + bus.show((255, 0, 0)) + self.assertEqual([call[:2] for call in calls], + [(address, register) for address in (0x18, 0x19, 0x1A, 0x1B) + for register in (0x31, 0x32)]) + self.assertTrue(all(len(data) == size for (_, _, data), size + in zip(calls, (32, 6) * 4))) + for index in range(0, len(calls), 2): + self.assertEqual(calls[index][2] + calls[index + 1][2], _led_packet(((255, 0, 0),) * 12)) + + def test_smbus_block_write_encodes_payload_length_and_zero_padding(self): + bus = PawnIoSmbus() + bus._execute = Mock() + data = bytes(range(32)) + bus._write_block(0x1B, 0x31, data) + operation, args = bus._execute.call_args.args + packed = b"".join(cell.to_bytes(8, "little") for cell in args[4:]) + self.assertEqual(operation, b"ioctl_smbus_xfer") + self.assertEqual(args[:4], (0x1B, 0, 0x31, 5)) + self.assertEqual(packed, bytes((32,)) + data + bytes(7)) + + def test_invalid_rgb_values_are_rejected(self): + for color in ((-1, 0, 0), (0, 256, 0), (1.5, 0, 0), (1, 2)): + with self.subTest(color=color), self.assertRaises(ValueError): + _rgb_bytes(color) + + def test_per_led_packets_and_only_changed_sticks_are_written(self): + frame = memory_chase_frame(0) + packet = _led_packet(frame[3]) + self.assertEqual(packet[:-1], bytes((12,)) + bytes(channel for color in frame[3] for channel in color)) + self.assertEqual(packet[-1], _crc8(packet[:-1])) + bus = PawnIoSmbus() + bus._write_block = Mock() + with patch("kurgan.lighting.memory.PawnIoSmbus._bus"): + bus.show_frame(frame) + self.assertEqual(bus._write_block.call_count, 8) + bus._write_block.reset_mock() + bus.show_frame(frame) + bus._write_block.assert_not_called() + changed = frame[:3] + (((255, 0, 0),) * 12,) + bus.show_frame(changed) + self.assertEqual([c.args[:2] for c in bus._write_block.call_args_list], [(0x1B, 0x31), (0x1B, 0x32)]) + bus._write_block.reset_mock() + bus.show_frame(changed, force=True) + self.assertEqual(bus._write_block.call_count, 8) + + def test_invalid_frame_is_rejected_before_any_hardware_write(self): + bus = PawnIoSmbus() + bus._write_block = Mock() + frame = _solid_frame((0, 0, 0)) + for invalid in (frame[:3], frame[:3] + (frame[3][:11],)): + with self.subTest(frame=invalid), self.assertRaises(ValueError): + bus.show_frame(invalid) + bus._write_block.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_profiles.py b/tests/test_profiles.py new file mode 100644 index 0000000..6294688 --- /dev/null +++ b/tests/test_profiles.py @@ -0,0 +1,80 @@ +import unittest +from unittest.mock import Mock + +from kurgan.cooling import control +from kurgan.cooling.board_fans import Nct6687 +from kurgan.cooling.control import CaseFanControl, TopFanCurve +from kurgan.cooling.profiles import BALANCED, FULL, PERFORMANCE, PROFILES, QUIET, validate_curve + + +class ProfileTest(unittest.TestCase): + def test_balanced_keeps_the_original_curves(self): + self.assertEqual(control.CURVE, ((40, 40), (50, 50), (60, 65), (70, 100))) + self.assertEqual(control.CPU_CURVE, ((50, 40), (60, 50), (70, 65), (80, 100))) + self.assertEqual((control.TOP_START, control.TOP_STOP), (50, 45)) + self.assertEqual(list(PROFILES), ["quiet", "balanced", "performance", "full"]) + + def test_profiles_are_ordered_quiet_to_full_at_every_temperature(self): + for temp in range(0, 111, 5): + for side in ("gpu_curve", "cpu_curve", "top_curve"): + duties = [control._curve_duty(getattr(p, side), temp) for p in (QUIET, BALANCED, PERFORMANCE, FULL)] + with self.subTest(temp=temp, side=side): + self.assertEqual(duties, sorted(duties)) + + def test_invalid_curves_are_rejected(self): + for curve in (((50, 100),), ((50, 40), (50, 100)), ((40, 60), (60, 50), (70, 100)), + ((40, 40), (60, 90)), ((-5, 40), (60, 100))): + with self.subTest(curve=curve), self.assertRaises(ValueError): + validate_curve(curve) + + +class ProfileSwitchTest(unittest.TestCase): + def setUp(self): + self.commander = Mock() + self.commander.set_duty.side_effect = lambda ports, duty: {p: 1200 for p in ports} + board = Mock(spec=Nct6687) + board.manual_mask.return_value = 0x24 + self.top = TopFanCurve((2, 5), board_factory=lambda: board) + self.fans = CaseFanControl(self.commander, (4, 5, 6), (1, 2, 3), top=self.top, profile=BALANCED) + self.now = 0.0 + + def run_for(self, seconds, gpu=60.0, cpu=60.0): + for _ in range(seconds): + self.now += 1 + self.fans.update(gpu, self.now, cpu) + + def test_rises_apply_at_once_and_falls_ramp_down(self): + self.run_for(40) + self.assertEqual((self.fans.gpu.duty, self.fans.cpu.duty), (65, 50)) + self.fans.apply_profile(PERFORMANCE) + self.run_for(1) + self.assertEqual((self.fans.gpu.duty, self.fans.cpu.duty), (90, 70)) + self.fans.apply_profile(QUIET) + self.run_for(9) + self.assertEqual(self.fans.gpu.duty, 90) # held 10 s after the last rise + self.run_for(30) + self.assertEqual((self.fans.gpu.duty, self.fans.cpu.duty), (55, 40)) + + def test_top_fans_take_the_profile_start_temperature(self): + self.fans.apply_profile(QUIET) + self.run_for(90, gpu=45, cpu=40) # start-up boost, ramp-down, then 30 s below Quiet's 50 C stop + self.assertFalse(self.top.running) + self.fans.apply_profile(PERFORMANCE) # starts the top fans at 45 C + self.run_for(1, gpu=45, cpu=40) + self.assertTrue(self.top.running) + self.fans.apply_profile(FULL) + self.run_for(1, gpu=30, cpu=30) + self.assertEqual((self.fans.gpu.duty, self.fans.cpu.duty, self.top.duty), (100, 100, 100)) + + def test_snapshot_names_the_profile_and_each_group(self): + self.run_for(1) + self.fans.apply_profile(PERFORMANCE) + snap = self.fans.snapshot() + self.assertEqual(snap["profile"], "performance") + self.assertEqual([g["name"] for g in snap["groups"]], ["GPU", "CPU"]) + self.assertEqual(snap["groups"][0]["rpms"], {"4": 1200, "5": 1200, "6": 1200}) + self.assertEqual(snap["top"]["channels"], [2, 5]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_proxy.py b/tests/test_proxy.py new file mode 100644 index 0000000..21c9c43 --- /dev/null +++ b/tests/test_proxy.py @@ -0,0 +1,310 @@ +import http.client +import json +import socket +import threading +import time +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from types import SimpleNamespace +from unittest.mock import patch + +from kurgan.ai.service import CLIENT_GONE, RouteError +from kurgan.web import proxy +from kurgan.web.server import WebServer + + +def free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +class Upstream: + """A stand-in LLM server: records each request; /stream sends one event, waits, then another.""" + + def __init__(self): + self.requests = [] + self.release_stream = threading.Event() + self.release_slow = threading.Event() + upstream = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def _any(self): + length = int(self.headers.get("Content-Length", "0")) + body = self.rfile.read(length) if length else b"" + upstream.requests.append({"method": self.command, "path": self.path, + "headers": dict(self.headers.items()), "body": body}) + if self.path.endswith("/stream"): + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + self.wfile.write(b"data: one\n\n") + self.wfile.flush() + upstream.release_stream.wait(5) + self.wfile.write(b"data: two\n\n") + return + if self.path.endswith("/slow"): # a queued request: nothing until the server gets to it + upstream.release_slow.wait(10) + if self.path.endswith("/moved"): + self.send_response(302) + self.send_header("Location", f"http://127.0.0.1:{upstream.port}{upstream.prefix}/elsewhere") + self.send_header("Content-Length", "0") + self.end_headers() + return + data = json.dumps({"path": self.path}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + do_GET = do_POST = do_DELETE = do_HEAD = _any + + self.prefix = "" + self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.httpd.daemon_threads = True + self.httpd.handle_error = lambda request, address: None # a reply to a dropped request fails; expected + self.port = self.httpd.server_address[1] + threading.Thread(target=self.httpd.serve_forever, daemon=True).start() + + def close(self): + self.release_stream.set() + self.release_slow.set() + self.httpd.shutdown() + self.httpd.server_close() + + +class FakeBackend: + def __init__(self, key, port, prefix, model): + self.key, self.label, self.port, self.prefix, self.model = key, key.capitalize(), port, prefix, model + + def model_ids(self): + return [self.model] + + def proxy_headers(self): + return {"Authorization": "Bearer sk-local"} if self.key == "llama" else {} + + +class FakeAi: + def __init__(self, backends): + self.slots = {b.key: SimpleNamespace(backend=b) for b in backends} + self.up = {b.key: True for b in backends} + self.calls = [] + self.error = None + self.wait_for_client = False # act like a claim waiting for the other server + + def running(self, key): + return self.up[key] + + def claim(self, key, gone=None): + self.calls.append(("claim", key)) + if self.error is not None: + raise self.error + deadline = time.monotonic() + 10 + while self.wait_for_client and time.monotonic() < deadline: + if gone(): + raise RouteError("while waiting for Strata to finish", CLIENT_GONE) + time.sleep(0.05) + return self.slots[key].backend + + def release(self, key): + self.calls.append(("release", key)) + + +class FakeApp: + def __init__(self, ai): + self.ai = ai + + def state(self): + return {"ok": True} + + +class ProxyTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.upstream = Upstream() + cls.upstream.prefix = "/llama" + cls.llama = FakeBackend("llama", cls.upstream.port, "/llama", "qwen") + cls.strata = FakeBackend("strata", cls.upstream.port, "", "orca") + cls.ai = FakeAi([cls.strata, cls.llama]) + cls.port = free_port() + cls.server = WebServer(FakeApp(cls.ai), cls.port) + cls.server.start() + + @classmethod + def tearDownClass(cls): + cls.server.close() + cls.upstream.close() + + def setUp(self): + self.upstream.requests.clear() + self.ai.calls.clear() + self.ai.up = {"strata": True, "llama": True} + self.ai.error = None + self.ai.wait_for_client = False + self.llama.port = self.upstream.port + self.upstream.release_slow.clear() + + def request(self, method, path, body=None, headers=None, chunked=False): + connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10) + try: + base = {"Host": f"127.0.0.1:{self.port}", **(headers or {})} + connection.request(method, path, body=body, headers=base, encode_chunked=chunked) + response = connection.getresponse() + return response.status, dict(response.getheaders()), response.read() + finally: + connection.close() + + def test_a_request_is_relayed_under_the_server_s_own_path(self): + body = json.dumps({"model": "qwen", "messages": []}).encode() + status, _, raw = self.request("POST", "/llama/v1/chat/completions?x=1", body, + {"Content-Type": "application/json", "Authorization": "Bearer whatever", + "Origin": f"http://127.0.0.1:{self.port}"}) + self.assertEqual(status, 200) + self.assertEqual(json.loads(raw), {"path": "/llama/v1/chat/completions?x=1"}) + seen = self.upstream.requests[0] + self.assertEqual((seen["method"], seen["body"]), ("POST", body)) + self.assertEqual(seen["headers"]["Host"], f"127.0.0.1:{self.upstream.port}") + self.assertEqual(seen["headers"]["Authorization"], "Bearer sk-local") # the server's key, whatever was sent + self.assertNotIn("Origin", seen["headers"]) # our own page: the server sees a plain local client + self.assertEqual(self.ai.calls, [("claim", "llama"), ("release", "llama")]) + + self.assertEqual(json.loads(self.request("GET", "/strata/")[2]), {"path": "/"}) # Strata serves from the root + self.assertNotIn("Authorization", self.upstream.requests[-1]["headers"]) + self.assertEqual(json.loads(self.request("DELETE", "/strata/v1/x")[2]), {"path": "/v1/x"}) + + def test_a_chunked_request_body_is_passed_on_whole(self): + status, _, _ = self.request("POST", "/strata/v1/completions", iter([b'{"prompt":', b'"hi"}']), + {"Content-Type": "application/json"}, chunked=True) + self.assertEqual(status, 200) + seen = self.upstream.requests[0] + self.assertEqual((seen["body"], seen["headers"]["Content-Length"]), (b'{"prompt":"hi"}', "15")) + + def test_bare_route_redirects_and_redirects_are_mapped_back(self): + status, headers, _ = self.request("GET", "/llama") + self.assertEqual((status, headers["Location"]), (308, "/llama/")) + self.assertEqual(self.ai.calls, []) + status, headers, _ = self.request("GET", "/llama/moved") + self.assertEqual((status, headers["Location"]), (302, "/llama/elsewhere")) + + def test_other_sites_are_refused_before_anything_starts(self): + refused = ({"Origin": "https://attacker.example"}, {"Origin": "null"}, + {"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Dest": "image"}, + {"Host": "attacker.example"}) + for headers in refused: + with self.subTest(headers=headers): + status, _, raw = self.request("POST", "/llama/v1/chat/completions", b"{}", headers) + self.assertEqual(status, 403) + self.assertIn("error", json.loads(raw)) + self.assertEqual((self.ai.calls, self.upstream.requests), ([], [])) + # Following a link from another site to the chat page is fine. + status, _, _ = self.request("GET", "/llama/", headers={"Sec-Fetch-Site": "cross-site", + "Sec-Fetch-Dest": "document"}) + self.assertEqual(status, 200) + + def test_model_list_is_answered_here_while_the_server_is_stopped(self): + self.ai.up["llama"] = False + status, _, raw = self.request("GET", "/llama/v1/models") + self.assertEqual(status, 200) + self.assertEqual([m["id"] for m in json.loads(raw)["data"]], ["qwen"]) + self.assertEqual(json.loads(self.request("GET", "/llama/v1/models/qwen")[2])["id"], "qwen") + self.assertEqual(self.request("GET", "/llama/v1/models/other")[0], 404) + self.assertEqual((self.ai.calls, self.upstream.requests), ([], [])) + self.ai.up["llama"] = True # running: the server answers for itself + self.assertEqual(json.loads(self.request("GET", "/llama/v1/models")[2]), {"path": "/llama/v1/models"}) + + def test_errors_are_reported_openai_style(self): + self.ai.error = RouteError("Strata is still busy with another request", 503) + status, _, raw = self.request("POST", "/llama/v1/chat/completions", b"{}") + self.assertEqual((status, json.loads(raw)["error"]["message"]), (503, "Strata is still busy with another request")) + self.assertEqual(self.ai.calls, [("claim", "llama")]) # a failed claim releases itself + + self.ai.error = None + self.ai.calls.clear() + self.llama.port = free_port() # nothing listening + status, _, raw = self.request("POST", "/llama/v1/chat/completions", b"{}") + self.assertEqual(status, 502) + self.assertIn("isn't answering", json.loads(raw)["error"]["message"]) + self.assertEqual(self.ai.calls, [("claim", "llama"), ("release", "llama")]) + + with patch.object(proxy, "MAX_BODY", 10): + self.assertEqual(self.request("POST", "/llama/v1/chat/completions", b"x" * 11)[0], 413) + + def test_replies_are_streamed_as_they_are_generated(self): + self.upstream.release_stream.clear() + connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10) + try: + connection.request("POST", "/llama/v1/stream", b"{}", {"Host": f"127.0.0.1:{self.port}"}) + response = connection.getresponse() + self.assertEqual(response.getheader("Content-Type"), "text/event-stream") + self.assertEqual(response.read1(1024), b"data: one\n\n") # before the server sends the rest + self.upstream.release_stream.set() + self.assertEqual(response.read(), b"data: two\n\n") + finally: + connection.close() + self.assertEqual(self.ai.calls, [("claim", "llama"), ("release", "llama")]) + + def hang_up_after_sending(self, path): + """Send a request, then close the connection without reading the reply.""" + sock = socket.create_connection(("127.0.0.1", self.port), timeout=5) + sock.sendall(f"POST {path} HTTP/1.1\r\nHost: 127.0.0.1:{self.port}\r\nContent-Type: application/json\r\n" + f"Content-Length: 2\r\n\r\n{{}}".encode()) + time.sleep(0.3) + sock.close() + + def wait_for_log(self, logs, text): + deadline = time.monotonic() + 5 + while time.monotonic() < deadline and not any(text in line for line in logs.output): + time.sleep(0.05) + return [line for line in logs.output if text in line] + + def test_a_client_that_hangs_up_while_queued_is_noticed_and_the_server_told(self): + with self.assertLogs("kurgan.web", "INFO") as logs: + self.hang_up_after_sending("/llama/v1/slow") + lines = self.wait_for_log(logs, "gave up") + self.assertEqual(len(lines), 1) + self.assertRegex(lines[0], r"POST /llama/v1/slow: the client gave up after [01] s, before Llama started its reply") + self.assertEqual(self.ai.calls, [("claim", "llama"), ("release", "llama")]) # before the server answered + self.assertFalse(any("ERROR" in line for line in logs.output)) + + def test_a_client_that_hangs_up_while_waiting_for_its_server_gives_up_its_place(self): + self.ai.wait_for_client = True + with self.assertLogs("kurgan.web", "INFO") as logs: + self.hang_up_after_sending("/strata/v1/chat/completions") + lines = self.wait_for_log(logs, "gave up") + self.assertRegex(lines[0], r"the client gave up after [01] s, while waiting for Strata to finish") + self.assertEqual(self.ai.calls, [("claim", "strata")]) # nothing reserved, so nothing to release + self.assertEqual(self.upstream.requests, []) + + def test_other_methods_elsewhere_are_not_allowed(self): + self.assertEqual(self.request("DELETE", "/api/state")[0], 405) + self.assertEqual(self.request("PUT", "/api/lighting", b"{}")[0], 405) + self.assertEqual(self.request("OPTIONS", "/api/state")[0], 405) + + def test_without_ai_management_the_routes_say_so(self): + port = free_port() + server = WebServer(SimpleNamespace(), port) + server.start() + try: + connection = http.client.HTTPConnection("127.0.0.1", port, timeout=5) + connection.request("GET", "/llama/v1/models", headers={"Host": f"127.0.0.1:{port}"}) + response = connection.getresponse() + self.assertEqual(response.status, 503) + self.assertIn("--no-ai", json.loads(response.read())["error"]["message"]) + connection.close() + finally: + server.close() + + def test_match(self): + self.assertEqual(proxy.match("/llama/v1/models?x=1"), ("llama", "/v1/models?x=1")) + self.assertEqual(proxy.match("/strata"), ("strata", None)) + self.assertEqual(proxy.match("/strata?x"), ("strata", None)) + self.assertIsNone(proxy.match("/stratax/v1")) + self.assertIsNone(proxy.match("/api/state")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_rgb_lighting.py b/tests/test_rgb_lighting.py new file mode 100644 index 0000000..db5b151 --- /dev/null +++ b/tests/test_rgb_lighting.py @@ -0,0 +1,254 @@ +import unittest +from unittest.mock import patch + +from kurgan.theme import Theme +from kurgan.lighting.lighting_node import LightingNodeBusy, LightingNodeCore, direct_packets +from kurgan.lighting.case_fans import RGBLighting, _SIDE_CHASE_ROUTES, side_chase_frame + + +class FakeChannel: + def __init__(self): + self.sent: list[bytes] = [] + self.closed = False + + def drain(self): + pass + + def send(self, payload): + self.sent.append(payload) + + def read(self, timeout_ms): + return bytes((0, 0, 0, 9, 16)) + bytes(12) + + def close(self): + self.closed = True + + +def open_node() -> tuple[LightingNodeCore, FakeChannel]: + node, ch = LightingNodeCore(), FakeChannel() + node.ch = ch + return node, ch + + +class LightingNodeProtocolTest(unittest.TestCase): + def test_packets_split_colour_channels_in_fifties_and_skip_unchanged(self): + colors = [(i % 256, 2, 3) for i in range(204)] + packets = direct_packets(0, colors) + self.assertEqual([p[:5] for p in packets[:3]], + [bytes((0x32, 0, 0, 50, c)) for c in range(3)]) + self.assertEqual(packets[0][5:], bytes(range(50))) + self.assertEqual(packets[-1][:5], bytes((0x32, 0, 200, 4, 2))) + self.assertEqual(len(packets), 15) + changed = list(colors) + changed[120] = (0, 2, 3) + self.assertEqual(direct_packets(0, changed, colors), [direct_packets(0, changed)[6]]) + + def test_show_takes_software_control_once_then_sends_only_changes(self): + node, ch = open_node() + frame = side_chase_frame(0) + with patch("kurgan.lighting.lighting_node.time.monotonic", return_value=10.0): + node.show(0, frame) + self.assertEqual(ch.sent[0], bytes((0x38, 0, 0x02))) + self.assertEqual(len(ch.sent), 1 + 15 + 1) + self.assertEqual(ch.sent[-1], bytes((0x33, 0xFF))) + ch.sent.clear() + node.show(0, frame) + self.assertEqual(ch.sent, []) + node.show(0, side_chase_frame(1)) + self.assertTrue(0 < len(ch.sent) - 1 <= 10) # only changed red/green chunks + commit, no port state + self.assertTrue(all(p[0] == 0x32 and p[4] in (0, 1) for p in ch.sent[:-1])) + + def test_keepalive_recommits_and_close_returns_to_hardware_effect(self): + node, ch = open_node() + with patch("kurgan.lighting.lighting_node.time.monotonic", return_value=10.0): + node.show(0, [(1, 2, 3)] * 204) + ch.sent.clear() + with patch("kurgan.lighting.lighting_node.time.monotonic", return_value=14.0): + node.keepalive() + self.assertEqual(ch.sent, []) + with patch("kurgan.lighting.lighting_node.time.monotonic", return_value=15.5): + node.keepalive() + self.assertEqual(ch.sent, [bytes((0x33, 0xFF))]) + node.close() + self.assertEqual(ch.sent[-1], bytes((0x38, 0, 0x01))) + self.assertTrue(ch.closed) + + def test_rejected_command_raises(self): + node, ch = open_node() + ch.read = lambda timeout_ms: bytes((0, 1)) + bytes(15) + with self.assertRaisesRegex(OSError, "0x38"): + node.show(0, [(0, 0, 0)]) + + def test_steps_aside_for_competing_corsair_software_before_opening(self): + with patch("kurgan.lighting.lighting_node.corsair_software_running", return_value=True) as running, \ + patch("kurgan.lighting.lighting_node.hid_device_paths") as paths: + with self.assertRaises(LightingNodeBusy): + LightingNodeCore().open() + running.assert_called_once_with("Corsair Lighting Node Core", fan_tools=False) + paths.assert_not_called() + + +class FakeNode: + def __init__(self): + self.opened = 0 + self.closed = 0 + self.frames: list[list[tuple[int, int, int]]] = [] + self.firmware = "0.9.16" + + def open(self): + self.opened += 1 + + def close(self): + self.closed += 1 + + def show(self, channel, colors): + assert channel == 0 + self.frames.append(list(colors)) + + def keepalive(self): + pass + + +class RGBLightingTest(unittest.TestCase): + def setUp(self): + self.node = FakeNode() + self.lighting = RGBLighting(Theme(), node_factory=lambda: self.node) + + def test_temperature_colours_each_side_by_its_own_part_and_releases_when_off(self): + theme = Theme() + color = lambda t: theme.level_color(t, theme.temp_warn, theme.temp_hot) + self.lighting.update(40, True, gpu_temp=85) + self.assertEqual(self.node.frames[-1], [color(85)] * 102 + [color(40)] * 102) + for led in _SIDE_CHASE_ROUTES[0]: # the CPU-side chase route lies in the CPU colour half + self.assertEqual(self.node.frames[-1][led], color(40)) + self.assertEqual(self.lighting.status, "Temperature lighting active (GPU 85 \u00b0C, CPU 40 \u00b0C)") + self.lighting.update(85, True) # no GPU reading: GPU side follows the CPU + self.assertEqual(self.node.frames[-1], [color(85)] * 204) + self.lighting.update(85, False) + self.assertEqual(self.node.closed, 1) + self.assertIsNone(self.lighting.node) + self.assertEqual(self.lighting.status, "off") + + def test_busy_or_failed_node_retries_later_without_spinning(self): + self.node.open = lambda: (_ for _ in ()).throw(LightingNodeBusy("Lighting Node CORE busy: exit iCUE")) + with patch("kurgan.lighting.case_fans.time.monotonic", return_value=100.0): + self.lighting.update(40, True) + self.assertEqual(self.lighting.status, "Lighting Node CORE busy: exit iCUE") + self.node.open = lambda: None + with patch("kurgan.lighting.case_fans.time.monotonic", return_value=105.0): + self.lighting.update(40, True) + self.assertEqual(self.node.frames, []) + with patch("kurgan.lighting.case_fans.time.monotonic", return_value=111.0): + self.lighting.update(40, True) + self.assertEqual(len(self.node.frames), 1) + self.node.show = lambda channel, colors: (_ for _ in ()).throw(OSError("unplugged")) + with self.assertLogs("kurgan.lighting.case_fans", level="WARNING"): + self.lighting.update(90, True) + self.assertEqual(self.lighting.status, "Lighting Node CORE connection lost") + self.assertIsNone(self.lighting.node) + + def test_chase_uses_elapsed_time(self): + for now, expected in ((100.0, 1), (100.05, 1), (100.31, 2)): + with patch("kurgan.lighting.case_fans.time.monotonic", return_value=now): + self.lighting.update(None, False, side_chase=True) + self.assertEqual(len(self.node.frames), expected) + self.assertEqual(self.node.frames, [side_chase_frame(0), side_chase_frame(2)]) + self.lighting.update(None, False) + self.assertEqual(self.node.closed, 1) + def test_chase_cpu_route_and_mirrored_gpu_route(self): + cpu, gpu = _SIDE_CHASE_ROUTES + expected_cpu = ( + list(range(147, 158)) + [146] + + [183, 182, 181, 180, 191, 190] + + list(range(116, 124)) + list(range(112, 116)) + + list(range(189, 183, -1)) + ) + self.assertEqual(list(cpu), expected_cpu) + for route in (cpu, gpu): + self.assertEqual(len(route), 36) + self.assertEqual(len(set(route)), 36) + self.assertTrue(all(10 <= index % 34 < 22 for index in route)) + # Compare physical clock positions, not raw indices, because mounts differ. + cpu_right = {4: 11, 5: 20, 3: 20} + gpu_fan = {4: 0, 5: 1, 3: 2} + for cpu_led, gpu_led in zip(cpu, gpu): + fan, local = divmod(cpu_led, 34) + self.assertEqual(gpu_led // 34, gpu_fan[fan]) + cpu_clock = (local - cpu_right[fan]) % 12 + gpu_clock = (gpu_led % 34 - 17) % 12 + self.assertEqual(gpu_clock, 11 - cpu_clock) + + def test_chase_has_one_head_per_side_and_four_fading_trail_leds(self): + for step in (0, 1, 12, 18, 30, 35, 36, 1000): + with self.subTest(step=step): + frame = side_chase_frame(step) + self.assertEqual(len(frame), 204) + for route in _SIDE_CHASE_ROUTES: + lit = {led: frame[led] for led in route if frame[led] != (24, 0, 0)} + expected = { + route[(step - age) % 36]: color + for age, color in enumerate(((255, 48, 0), (209, 38, 0), (163, 29, 0), + (116, 19, 0), (70, 10, 0))) + } + self.assertEqual(lit, expected) + inner_lit = { + index: frame[index] + for fan in {led // 34 for led in route} + for index in range(fan * 34 + 22, fan * 34 + 34) + if frame[index] != (24, 0, 0) + } + self.assertEqual(len(inner_lit), 5) + for outer, color in expected.items(): + fan, local = divmod(outer, 34) + right = (17, 17, 17, 20, 11, 20)[fan] + outer_clock = (local - right) % 12 + inner = next(index for index, value in inner_lit.items() if value == color) + self.assertEqual(inner // 34, fan) + inner_clock = (inner % 34 - 22 - (right - 10)) % 12 + self.assertEqual(inner_clock, 11 - outer_clock) + for index, color in enumerate(frame): + if index % 34 < 10: + self.assertEqual(color, (48, 0, 0)) + self.assertEqual(side_chase_frame(0), side_chase_frame(36)) + + def test_chase_speeds_up_with_power_without_jumping(self): + self.assertAlmostEqual(self.lighting.chase_rate(None), 1 / 0.15) + self.assertAlmostEqual(self.lighting.chase_rate(100), 1 / 0.15) + self.assertAlmostEqual(self.lighting.chase_rate(350), (1 / 0.15 + 1 / 0.025) / 2) + self.assertAlmostEqual(self.lighting.chase_rate(900), 1 / 0.025) + + steps = [] + + def tick(now, watts=None): + if watts is not None: + self.lighting.set_power(watts) + with patch("kurgan.lighting.case_fans.time.monotonic", return_value=now): + self.lighting.update(None, False, side_chase=True) + steps.append(self.lighting._last_chase_step) + + self.lighting.set_power(120) + tick(100.0) + for i in range(1, 31): # 1.5 s at idle: 10 LEDs + tick(100.0 + i * 0.05) + self.assertEqual(steps[-1], 10) + for i in range(1, 121): # power jumps to 600 W for 6 s + tick(101.5 + i * 0.05, 600) + self.assertEqual(max(b - a for a, b in zip(steps, steps[1:])), 2) + self.assertGreater(steps[-1] - steps[30], 180) # mostly at 40 LEDs/s once eased in + self.assertEqual(self.lighting.status, "Red side chase active (25 ms/LED at 600 W)") + + def test_fast_chase_caps_core_frames_but_keeps_its_speed(self): + self.lighting.set_power(900) + self.lighting._chase_timing.rate = 40.0 + with patch("kurgan.lighting.case_fans.time.monotonic", return_value=100.0): + self.lighting.update(None, False, side_chase=True) + self.lighting._chase_timing.rate = 40.0 + for i in range(1, 101): # polled every 10 ms for 1 s + with patch("kurgan.lighting.case_fans.time.monotonic", return_value=100.0 + i * 0.01): + self.lighting.update(None, False, side_chase=True) + self.assertLessEqual(len(self.node.frames), 23) + self.assertIn(self.lighting._last_chase_step, (39, 40)) + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/tests/test_settings.py b/tests/test_settings.py new file mode 100644 index 0000000..497e8a0 --- /dev/null +++ b/tests/test_settings.py @@ -0,0 +1,103 @@ +import json +import os +import tempfile +import unittest +from unittest.mock import patch + +from kurgan.settings import DEFAULTS, Settings, SettingsError, validate + + +class ValidateTest(unittest.TestCase): + def test_empty_file_gets_defaults(self): + self.assertEqual(validate({}), DEFAULTS) + + def test_fan_ports_are_checked_like_the_command_line(self): + ok = validate({"cooling": {"gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [5, 2]}}) + self.assertEqual(ok["cooling"]["top_channels"], [2, 5]) + for cooling in ({"gpu_ports": [4, 5]}, {"gpu_ports": [4, 4, 5]}, {"gpu_ports": [4, 5, 7]}, + {"gpu_ports": "4,5,6"}, {"gpu_ports": [4, 5, 6.0]}, + {"cpu_ports": [1, 2, 3]}, # CPU side without the GPU side + {"gpu_ports": [4, 5, 6], "cpu_ports": [3, 4, 1]}, # overlap + {"gpu_ports": [4, 5, 6], "top_channels": [9]}, + {"profile": "turbo"}): + with self.subTest(cooling=cooling), self.assertRaises(SettingsError): + validate({"cooling": cooling}) + + def test_lighting_modes_follow_each_zone(self): + self.assertEqual(validate({"lighting": {"memory": "chase"}})["lighting"]["memory"], "chase") + for lighting in ({"gpu": "temperature"}, {"case_fans": "rainbow"}, {"keyboard": "off"}): + with self.subTest(lighting=lighting), self.assertRaises(SettingsError): + validate({"lighting": lighting}) + + def test_ai_choices_and_ports(self): + self.assertEqual(validate({"ai": {"active": "llama"}})["ai"]["active"], "llama") + for ai in ({"active": "ollama"}, {"strata_model": "q8"}, {"strata_port": 80}, + {"strata_port": 9000, "llama_port": 9000}, {"llama_server": ""}): + with self.subTest(ai=ai), self.assertRaises(SettingsError): + validate({"ai": ai}) + + def test_unknown_sections_and_keys_are_errors_not_ignored(self): + for data in ([], {"extra": {}}, {"web": {"port": 8080, "host": "0.0.0.0"}}, {"web": 8080}): + with self.subTest(data=data), self.assertRaises(SettingsError): + validate(data) + + +class SettingsFileTest(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + self.path = os.path.join(self.dir.name, "Kurgan", "settings.json") + self.legacy = os.path.join(self.dir.name, "TTLcdDashboard") + os.makedirs(self.legacy) + + def write_legacy(self, name, data): + with open(os.path.join(self.legacy, name), "w", encoding="utf-8") as f: + json.dump(data, f) + + def test_first_start_imports_the_dashboard_settings_and_the_seed(self): + self.write_legacy("fan-control.json", {"gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5]}) + self.write_legacy("memory-lighting.json", {"mode": "temperature"}) + self.write_legacy("gpu-lighting.json", {"mode": "off"}) + settings = Settings(self.path, self.legacy, seed={"lighting": {"case_fans": "chase"}}) + self.assertTrue(settings.created) + self.assertEqual(settings.section("cooling"), {"profile": "balanced", "gpu_ports": [4, 5, 6], + "cpu_ports": [1, 2, 3], "top_channels": [2, 5]}) + self.assertEqual(settings.section("lighting"), {"case_fans": "chase", "memory": "temperature", "gpu": "off"}) + with open(self.path, encoding="utf-8") as f: + self.assertEqual(json.load(f)["lighting"]["case_fans"], "chase") + + def test_seed_applies_only_when_the_file_is_created(self): + Settings(self.path, None).update("lighting", case_fans="temperature") + settings = Settings(self.path, None, seed={"lighting": {"case_fans": "chase"}}) + self.assertFalse(settings.created) + self.assertEqual(settings.get("lighting", "case_fans"), "temperature") + + def test_corrupt_legacy_or_settings_file_stops_startup(self): + self.write_legacy("memory-lighting.json", {"mode": "rainbow"}) + with self.assertRaises(SettingsError): + Settings(self.path, self.legacy) + os.makedirs(os.path.dirname(self.path)) + with open(self.path, "w", encoding="utf-8") as f: + f.write("{not json") + with self.assertRaises(SettingsError): + Settings(self.path, self.legacy) + + def test_invalid_or_failed_update_changes_nothing(self): + settings = Settings(self.path, None) + settings.update("cooling", profile="quiet") + with self.assertRaises(SettingsError): + settings.update("cooling", profile="turbo") + with patch("kurgan.settings.os.replace", side_effect=OSError("denied")), self.assertRaises(OSError): + settings.update("cooling", profile="performance") + self.assertEqual(settings.get("cooling", "profile"), "quiet") + self.assertEqual(Settings(self.path, None).get("cooling", "profile"), "quiet") + self.assertEqual(sorted(os.listdir(os.path.dirname(self.path))), ["settings.json"]) + + def test_returned_sections_are_copies(self): + settings = Settings(self.path, None) + settings.section("lighting")["memory"] = "chase" + self.assertEqual(settings.get("lighting", "memory"), "off") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_web.py b/tests/test_web.py new file mode 100644 index 0000000..be39872 --- /dev/null +++ b/tests/test_web.py @@ -0,0 +1,132 @@ +import http.client +import json +import socket +import unittest + +from kurgan.web.server import WebServer + + +class FakeApp: + def __init__(self): + self.calls = [] + + def state(self): + return {"ok": True} + + def history(self): + return {"rows": []} + + def config(self): + return {"profiles": []} + + def set_lighting(self, zone, mode): + self.calls.append(("lighting", zone, mode)) + if mode == "rainbow": + raise ValueError("Unknown lighting mode") + + def set_fan_profile(self, profile): + self.calls.append(("profile", profile)) + if profile == "full-disk": + raise OSError("disk full") + + def set_ai(self, backend, variant): + self.calls.append(("ai", backend, variant)) + + def ai_model(self, action): + self.calls.append(("model", action)) + + +def free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +class WebServerTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.app = FakeApp() + cls.port = free_port() + cls.server = WebServer(cls.app, cls.port) + cls.server.start() + + @classmethod + def tearDownClass(cls): + cls.server.close() + + def setUp(self): + self.app.calls.clear() + + def request(self, method, path, body=None, headers=None, host=None): + connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5) + try: + data = body if isinstance(body, (bytes, type(None))) else json.dumps(body).encode() + base = {"Host": host or f"127.0.0.1:{self.port}"} + if method == "POST": + base.update({"Content-Type": "application/json", "X-Kurgan": "1"}) + base.update(headers or {}) + connection.request(method, path, body=data, headers={k: v for k, v in base.items() if v is not None}) + response = connection.getresponse() + return response.status, response.getheader("Content-Type"), response.read() + finally: + connection.close() + + def test_api_and_ui_are_served(self): + status, kind, body = self.request("GET", "/api/state") + self.assertEqual((status, json.loads(body)), (200, {"ok": True})) + status, kind, body = self.request("GET", "/", host=f"localhost:{self.port}") + self.assertEqual(status, 200) + self.assertTrue(kind.startswith("text/html")) + self.assertIn(b"THE KURGAN", body) + status, kind, _ = self.request("GET", "/static/app.js") + self.assertEqual(status, 200) + self.assertIn("javascript", kind) + + def test_only_files_in_static_are_served(self): + for path in ("/static/../server.py", "/static/..%2Fserver.py", "/static/missing.js", "/server.py"): + with self.subTest(path=path): + self.assertEqual(self.request("GET", path)[0], 404) + + def test_foreign_host_is_refused(self): # DNS rebinding + self.assertEqual(self.request("GET", "/api/state", host="attacker.example")[0], 403) + self.assertEqual(self.request("POST", "/api/ai/model", {"action": "load"}, host="attacker.example")[0], 403) + self.assertEqual(self.app.calls, []) + + def test_posts_need_the_header_json_and_our_origin(self): + refused = (({"X-Kurgan": None}, 403), ({"Origin": "https://attacker.example"}, 403), + ({"Content-Type": "text/plain"}, 415)) + for headers, expected in refused: + with self.subTest(headers=headers): + status, _, _ = self.request("POST", "/api/cooling/profile", {"profile": "quiet"}, headers) + self.assertEqual(status, expected) + self.assertEqual(self.app.calls, []) + status, _, body = self.request("POST", "/api/cooling/profile", {"profile": "quiet"}, + {"Origin": f"http://127.0.0.1:{self.port}"}) + self.assertEqual((status, json.loads(body)), (200, {"ok": True})) + self.assertEqual(self.app.calls, [("profile", "quiet")]) + + def test_bad_bodies_and_failures_report_errors(self): + cases = (("/api/lighting", {"zone": "gpu"}, 400, "mode is required"), + ("/api/lighting", {"zone": "gpu", "mode": "rainbow"}, 400, "Unknown lighting mode"), + ("/api/lighting", [1, 2], 400, "JSON object"), + ("/api/lighting", b"{nope", 400, None), + ("/api/lighting", b"x" * 20000, 400, "oversized"), + ("/api/ai/active", {"backend": 3}, 400, "string or null"), + ("/api/cooling/profile", {"profile": "full-disk"}, 500, "disk full"), + ("/api/fans", {"x": 1}, 404, None)) + for path, body, expected, message in cases: + with self.subTest(path=path, body=body): + status, _, raw = self.request("POST", path, body) + self.assertEqual(status, expected) + if message: + self.assertIn(message, json.loads(raw)["error"]) + + def test_ai_choice_allows_none(self): + status, _, _ = self.request("POST", "/api/ai/active", {"backend": None}) + self.assertEqual(status, 200) + self.request("POST", "/api/ai/active", {"backend": "strata", "variant": "iq3"}) + self.assertEqual(self.app.calls, [("ai", None, None), ("ai", "strata", "iq3")]) + + +if __name__ == "__main__": + unittest.main() diff --git a/uninstall.ps1 b/uninstall.ps1 new file mode 100644 index 0000000..8db19c2 --- /dev/null +++ b/uninstall.ps1 @@ -0,0 +1,37 @@ +# Removes The Kurgan's startup task and stops it (an LLM server it started stops with it). +# -RestoreAIServices re-enables and starts the "Strata Local Service" and "Qwen4 Local Service" tasks +# -RemovePawnIO also uninstalls PawnIO (leave it if LibreHardwareMonitor or FanControl uses it) +# Settings stay in %LOCALAPPDATA%\Kurgan. +param([switch]$RemovePawnIO, [switch]$RestoreAIServices) + +$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole( + [Security.Principal.WindowsBuiltInRole]::Administrator) +if (-not $isAdmin) { + $extra = '' + if ($RemovePawnIO) { $extra += ' -RemovePawnIO' } + if ($RestoreAIServices) { $extra += ' -RestoreAIServices' } + Start-Process powershell -Verb RunAs -Wait -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"$extra" + exit +} + +foreach ($name in 'The Kurgan', 'TT LCD Dashboard') { + Stop-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue + Unregister-ScheduledTask -TaskName $name -Confirm:$false -ErrorAction SilentlyContinue +} +Get-CimInstance Win32_Process -Filter "Name like 'python%.exe'" | + Where-Object { $_.CommandLine -like '*lcd_dashboard.py*' -or $_.CommandLine -like '*-m kurgan*' } | + ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } +Write-Host "Removed 'The Kurgan'." -ForegroundColor Green + +if ($RestoreAIServices) { + Start-Sleep -Seconds 2 # let the LLM server's port close + foreach ($name in 'Strata Local Service', 'Qwen4 Local Service') { + if (Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue) { + Enable-ScheduledTask -TaskName $name | Out-Null + Start-ScheduledTask -TaskName $name + Write-Host "Re-enabled '$name'." -ForegroundColor Green + } + } +} +if ($RemovePawnIO) { winget uninstall --id namazso.PawnIO --exact --silent } +Start-Sleep -Seconds 3