# VS Code Remote Debugging

Attach the VS Code debugger to your Valohai execution for interactive debugging with breakpoints, variable inspection, and step-through execution.

**What you'll accomplish:**

* Set breakpoints in VS Code on code running in Valohai
* Inspect and modify variables in real-time
* Step through execution line-by-line on cloud infrastructure

### Prerequisites <a href="#prerequisites" id="prerequisites"></a>

Before starting, ensure you have:

1. **SSH access configured** - Follow [SSH Overview](https://docs.valohai.com/installation-and-setup/advanced-topics/configure-ssh-access) to set up keys and firewall rules
2. **VS Code installed** with Python extension
3. **SSH private key** from the SSH setup

### Add debugpy to Your Code <a href="#add-debugpy-to-your-code" id="add-debugpy-to-your-code"></a>

`debugpy` implements the Debug Adapter Protocol for Python. Install it and add wait logic to your training script.

#### Python Code <a href="#python-code" id="python-code"></a>

```python
import debugpy
import numpy as np
import time

# Listen on port 5678 inside the container
debugpy.listen(5678)

# Halt execution until VS Code attaches
debugpy.wait_for_client()

# Your training code runs after debugger connects
for x in range(1, 20):
    print(f"Doing computation {x}")
    data = np.random.random((50, 50))
    sum = np.sum(data)
    time.sleep(2)
```

**Key points:**

* `debugpy.listen(5678)` - Container port for debug connection
* `debugpy.wait_for_client()` - Pauses until VS Code attaches

#### valohai.yaml <a href="#valohaiyaml" id="valohaiyaml"></a>

```yaml
- step:
    name: train
    image: python:3.9
    command:
      - pip install numpy debugpy
      - python train.py
```

> The execution will pause at `wait_for_client()` until you attach VS Code. This keeps it running without needing `sleep` commands.

### Start Execution with SSH <a href="#start-execution-with-ssh" id="start-execution-with-ssh"></a>

Launch your execution with SSH debugging enabled:

**Web UI:**

1. Enable **Run with SSH**
2. Paste public key or auto-generate
3. Start execution

**Command Line:**

```shell
vh exec run --adhoc --debug-key-file=/path/to/key.pub --debug-port 2222 train
```

**Wait for the IP address** in execution logs:

```
SSH connection available at: 52.214.159.193:2222
```

### Configure VS Code <a href="#configure-vs-code" id="configure-vs-code"></a>

#### 1. Create Debug Configuration <a href="#id-1-create-debug-configuration" id="id-1-create-debug-configuration"></a>

Create or edit `.vscode/launch.json` in your project:

```json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Remote Attach",
      "type": "python",
      "request": "attach",
      "connect": {
        "host": "localhost",
        "port": 5678
      },
      "pathMappings": [
        {
          "localRoot": "${workspaceFolder}",
          "remoteRoot": "/valohai/repository"
        }
      ]
    }
  ]
}
```

**Configuration details:**

* `host: localhost` - We'll tunnel through SSH
* `port: 5678` - Must match `debugpy.listen()` port
* `remoteRoot: /valohai/repository` - Where your code runs in the container

#### 2. Open SSH Tunnel <a href="#id-2-open-ssh-tunnel" id="id-2-open-ssh-tunnel"></a>

Create a tunnel from your local machine to the execution:

```shell
ssh -i /path/to/private-key <IP-FROM-LOGS> -p 2222 -L 5678:127.0.0.1:5678
```

**What this does:**

* Connects to Valohai execution via SSH
* Forwards local port 5678 → container port 5678
* Keeps connection open for debugging

> 💡 *Keep this terminal window open while debugging.*

#### 3. Attach Debugger <a href="#id-3-attach-debugger" id="id-3-attach-debugger"></a>

1. Open your `train.py` in VS Code
2. Set breakpoints by clicking left of line numbers
3. Open **Run and Debug** panel (Ctrl+Shift+D)
4. Select **Python: Remote Attach**
5. Click **Start Debugging** (F5)

<figure><img src="https://4109720758-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ff3mjTRQNkASbnMbJqzJ2%2Fuploads%2Fgit-blob-a01a8a0336ed2acbe66ef43cb2f8c2caed7f555d%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

Your code will resume from `debugpy.wait_for_client()` and hit your breakpoints.

***

### Debug Your Code <a href="#debug-your-code" id="debug-your-code"></a>

Once attached, you can:

* **Inspect variables** - Hover over variables or use Variables panel
* **Evaluate expressions** - Use Debug Console to run Python expressions
* **Step through code** - F10 (step over), F11 (step into), Shift+F11 (step out)
* **Modify variables** - Edit values in Variables panel during execution

<figure><img src="https://4109720758-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ff3mjTRQNkASbnMbJqzJ2%2Fuploads%2Fgit-blob-67bc5a2f1747e725537576193926f69ad3512a31%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

***

### Common Issues <a href="#common-issues" id="common-issues"></a>

**VS Code can't connect?**

* Verify SSH tunnel is running (check terminal)
* Ensure execution hasn't timed out
* Confirm `debugpy.listen(5678)` matches your tunnel port

**Path mapping errors?**

* Update `remoteRoot` in `launch.json` if your code is in a different container path
* VS Code may auto-detect - click "Auto-detect" if prompted

**Execution exits before attaching?**

* Ensure `debugpy.wait_for_client()` is called before your training code
* Check execution logs for errors during `pip install debugpy`

***

### Next Steps <a href="#next-steps" id="next-steps"></a>

* [PyCharm Remote Debugging](https://docs.valohai.com/development-and-debugging/pycharm-remote-debugging) - Alternative IDE debugging
* [SSH Overview](https://docs.valohai.com/installation-and-setup/advanced-topics/configure-ssh-access) - Learn about direct SSH access and tunneling
