Here is the exact **"smoking gun"** timeline extracted from your system logs (`journalctl -b -1`), along with the diagnosis of your hardware display layout.

---

### 🔍 The Smoking Gun: Exact Timeline of Events

Your laptop has a **Hybrid Graphics Architecture**:
* **Internal Laptop Screen (`eDP-2`)**: Wired directly to **Intel UHD iGPU** (`card2`).
* **MSI External Monitor (`DP-1`)**: Wired directly to **NVIDIA RTX 4050 dGPU** (`card1`).

Here is what happened step-by-step leading to the freeze:

| Timestamp | Event / Log Entry | What Was Happening Under the Hood |
| :--- | :--- | :--- |
| **~20:00** | Ollama Batch Queries | Ollama ran batch inference, fully saturating the NVIDIA RTX 4050 VRAM and compute units. |
| **~20:45** | Ollama finished | Ollama completed. The NVIDIA dGPU entered a runtime low-power state (Power Management / D3 state), but with leftover driver context locks. |
| **20:57:34** | `org.gnome.ScreenSaver WakeUpScreen` | The laptop was idle/screen-locked. At 20:57:34, a screen wake event occurred (keyboard/mouse input or notification). |
| **20:57:35** | `gnome-shell: Launching DING...` | GNOME Shell attempted to wake up and re-initialize display outputs via `nvidia-modeset` for the MSI monitor wired to the NVIDIA dGPU. |
| **20:58:00** | `nvkms_ioctl_from_kapi_try_pmlock` **Deadlock** | The `nvidia-modeset` kernel module got hung trying to wake up / mode-set the dGPU output. It locked the `pmlock` semaphore and stopped responding. |
| **20:58:16** | `libinput error: Touch jump discarded` | You moved the touchpad trying to revive the frozen screen. |
| **20:59:34** | `systemd-logind: Power key pressed short` | You pressed the laptop power button to force a shutdown. `systemd` tried to terminate the session, but GNOME Shell was permanently stuck waiting for the NVIDIA display lock (`KMS thread blocked >245s`). |
| **21:02:10** | Hard cutoff / Reboot | System remained frozen until power was cut. |

---

### 🖥️ Should the MSI External Monitor Be Connected to Intel or NVIDIA GPU?

#### **Connecting to Intel iGPU (Recommended for LLM / AI Workloads)**
If you connect your MSI monitor to a port routed through the **Intel iGPU** (e.g. standard HDMI or Thunderbolt/USB-C connected to CPU/Intel):
* **Desktop Stability:** Both your laptop screen and the MSI monitor are rendered by the Intel iGPU. Your desktop GUI will **never freeze**, even if NVIDIA crashes or hangs during Ollama runs.
* **Dedicated AI Compute:** The NVIDIA GPU becomes a pure compute device (headless CUDA accelerator). Ollama gets exclusive access to the dGPU without sharing VRAM or display modesetting locks with GNOME / Wayland.

#### **Connecting to NVIDIA dGPU (Current Setup)**
* Because the MSI monitor is plugged directly into a port wired to the RTX 4050, **GNOME Shell relies on `nvidia-modeset` to drive that monitor**.
* Any driver power-state transition or lockup during/after Ollama runs will instantly freeze the external monitor and crash GNOME's display manager.

---

### 💡 Recommendations to Avoid Future Freezes

1. **Option A (Hardware Fix):**
   If your laptop has another DisplayPort / USB-C / HDMI port that is wired to the **Intel GPU**, plug the MSI monitor into that port.

2. **Option B (Disable NVIDIA Runtime Power Management for Display):**
   If you must use the NVIDIA-wired port, prevent the NVIDIA dGPU from entering deep power saving after Ollama finishes by enabling persistence mode:
   ```bash
   sudo nvidia-smi -pm 1
   ```

3. **Option C (Reserve VRAM in Ollama):**
   Set `OLLAMA_NUM_PARALLEL=1` and ensure Ollama leaves ~1.5–2GB of VRAM free for the display driver:
   ```bash
   export OLLAMA_NUM_PARALLEL=1
   ```

---

Yes, running `sudo nvidia-smi -pm 1` is an excellent first step! 

While waiting for your HDMI cable to arrive tomorrow, here is the **3-step configuration** to safely make your NVIDIA RTX 4050 handle **both** the MSI display and heavy Ollama LLM batch queries without crashing:

---

### Step 1: Enable NVIDIA Persistence Mode

Run this command in your terminal:
```bash
sudo nvidia-smi -pm 1
```

* **What it does:** Prevents the NVIDIA GPU driver from going into deep runtime power-saving (`D3hot`/`D3cold`) when Ollama finishes. This completely eliminates the sleep/wake-up driver deadlock (`nvkms_ioctl_from_kapi_try_pmlock`) when GNOME tries to refresh the MSI display.
* **To make it permanent across reboots:**
  ```bash
  sudo systemctl enable nvidia-persistenced
  ```

---

### Step 2: Prevent Ollama from Starving the Display of VRAM

Your RTX 4050 Laptop GPU has **6 GB VRAM**. GNOME Shell and your MSI display require **~1.0 to 1.5 GB VRAM** to render smoothly. If Ollama allocates 5.8 GB VRAM, the display driver will stall.

* **Limit Ollama parallel requests:**
  Prevent Ollama from spinning up multiple concurrent inference slots during batch queries:
  ```bash
  export OLLAMA_NUM_PARALLEL=1
  ```
* **Offload slightly fewer layers to GPU (if using large 7B/8B models):**
  When running `ollama run <model>`, make sure to leave at least 1.5 GB free. You can specify layer offloading in your API request or Modelfile (e.g. `num_gpu: 24` instead of `32`).

---

### Step 3: Temporarily Disable "Screen Blank / Display Sleep"

Because the freeze was triggered when the display woke up from screen blanking/sleep:

1. Open **Settings** $\rightarrow$ **Power**.
2. Set **Screen Blank** to **Never**.

---

### Summary Checklist for Today:

| Action | Command / Location | Benefit |
| :--- | :--- | :--- |
| **Enable Persistence** | `sudo nvidia-smi -pm 1` | Prevents GPU driver sleep lockups |
| **Prevent VRAM Overflow** | `export OLLAMA_NUM_PARALLEL=1` | Keeps VRAM available for MSI monitor |
| **Disable Display Blanking** | Ubuntu Settings $\rightarrow$ Power $\rightarrow$ Screen Blank: Never | Stops DPMS wake-up modeset calls |

Once your new HDMI cable arrives tomorrow (routing display output to the Intel iGPU), your desktop will be immune to NVIDIA GPU crashes!

---
That observation makes complete sense and further confirms what we found in the logs!

Here is why your MSI monitor was **always slow to wake up** during screen sleep/power saving:

### 🐢 Why NVIDIA External Displays Are Slow to Wake Up

1. **PCIe & GPU Runtime Power State (`D3cold`):**
   * When an external monitor is wired directly to the NVIDIA dGPU and goes to sleep, the Linux kernel puts the NVIDIA graphics chip into a deep low-power state (`D3cold`), turning off the DisplayPort physical link (PHY) and powering down clock generators.
2. **Heavy DPMS & AUX Handshake:**
   * Upon waking up, the `nvidia-modeset` driver has to do a full hardware re-initialization: wake up PCIe lanes from `D3cold`, re-establish DisplayPort AUX channel communications, re-read monitor EDID headers, and perform DRM atomic mode setting.
   * This whole process normally takes **3 to 6 seconds**, during which the screen stays black and the mouse cursor stutters.
3. **Driver Lock Contention (The Cause of Your Crash):**
   * If an AI workload (like Ollama) or background process was active on the GPU when the wake signal arrived, `nvidia-modeset` got stuck waiting for GPU memory locks before it could finish waking up the display—eventually leading to the freeze you experienced.

---

### ⚡ How Your Settings & New Cable Fix This

* **Right Now (`sudo nvidia-smi -pm 1`):**
  Enabling Persistence Mode prevents the NVIDIA GPU driver from tearing down its kernel context and dropping into deep `D3cold` sleep. This will **significantly speed up the monitor's wakeup time** and prevent the driver lockup.

* **Tomorrow (With the New HDMI / Intel Cable):**
  Intel's display driver (`i915`) handles display power management and DPMS transitions almost **instantly (< 200 ms)** without needing complex dGPU wake-ups. 

You've set up the ideal temporary workaround for today, and tomorrow's cable upgrade will give you both instant display wakeups and 100% crash protection!


---

When your HDMI cable arrives tomorrow, you can determine which GPU the HDMI port is connected to using a simple **one-line terminal check**.

---

### 🧪 How to Check Tomorrow (Step-by-Step)

1. Plug the new **HDMI cable** into your laptop and the MSI monitor.
2. Open your terminal and run this command:
   ```bash
   for status in /sys/class/drm/*/status; do echo "$status: $(cat $status)"; done
   ```

---

### 📊 How to Interpret the Output

Look at which line says **`connected`**:

#### **Case A: It shows `card2-HDMI-A-2: connected` (or `card2-HDMI-A-3`)**
* **Meaning:** The HDMI port is **physically wired to the Intel iGPU**! 🎉
* **Outcome:** The Intel GPU will handle the MSI display entirely. Your desktop and display are 100% safe from NVIDIA driver crashes during Ollama LLM queries.

#### **Case B: It shows `card1-HDMI-A-1: connected`**
* **Meaning:** The HDMI port is **physically wired to the NVIDIA dGPU**.

---

### ⚙️ What to Do If the HDMI Port Is Wired to NVIDIA (`card1`)

If your laptop's HDMI port turns out to be wired to the NVIDIA dGPU:

1. **Option 1: Switch to Intel Mode (Full Isolation)**
   You can force Linux to use Intel for all displays and reserve the NVIDIA GPU strictly as a headless CUDA compute device for Ollama:
   ```bash
   sudo prime-select intel
   ```
   *(Requires a quick reboot or log out/in).*

2. **Option 2: Stay in `on-demand` Mode with Persistence Enabled**
   Your current `prime-select query` shows your system is in `on-demand` mode. Keeping Persistence Mode enabled (`sudo nvidia-smi -pm 1`) will continue to keep the HDMI connection stable.
