Categories
Uncategorized

How to set up a CUDA GPU for computing only?

Most of logic board today comes with an integrated graphic card. Once a CUDA device is plugged in, X11 will recognize there is a new VGA device and configure it for X11 with memory allocations.

Blow is an example nvidia-smi output showing Xorg (X11) and gnome environment are using a large chunk of the GPU memory.

+—————————————————————————–+
| NVIDIA-SMI 470.182.03   Driver Version: 470.182.03   CUDA Version: 11.4     |
|——————————-+———————-+———————-+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  NVIDIA GeForce …  Off  | 00000000:01:00.0  On |                  N/A |
|  0%   48C    P8    19W / 180W |   1201MiB /  8110MiB |     13%      Default |
|                               |                      |                  N/A |
+——————————-+———————-+———————-++—————————————————————————–+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      1738      G   /usr/lib/xorg/Xorg                246MiB |
|    0   N/A  N/A      2033      G   /usr/bin/gnome-shell                7MiB |
|    0   N/A  N/A      2812      G   /usr/lib/xorg/Xorg                514MiB |
|    0   N/A  N/A      2942      G   /usr/bin/gnome-shell              169MiB |
|    0   N/A  N/A    321543      G   …NiYQ%3D%3D&browser=chrome       36MiB |
|    0   N/A  N/A    321587      G   …/debug.log –shared-files        5MiB |
|    0   N/A  N/A    458830      G   …390373760644109118,131072      115MiB |
|    0   N/A  N/A    458872      G   …veSuggestionsOnlyOnDemand       78MiB |
+—————————————————————————–+

If you want to use the CUDA device for computing, better free up the GPU memory. Here is a way to do it.

First, find the address of the device you want to use. You can change “Display” to “VGA” to list all the devices can be used to control the monitor.

$ lspci |grep Display
00:02.0 Display controller: Intel Corporation UHD Graphics 630 (Desktop)

Then edit or create /etc/X11/xorg.conf. Note: “sudo” privilege is required here.

Section "Device"
    Identifier      "intel"
    Driver          "intel"
    BusId           "PCI:0:2:0"
EndSection

Section "Screen"
    Identifier      "intel"
    Device          "intel"
EndSection

Restart the X11 environment or reboot, and you will see that GPU memory is now freed up and can all be used for CUDA computing.

~$ nvidia-smi
Mon May 1 11:03:18 2023
+—————————————————————————–+
| NVIDIA-SMI 470.182.03 Driver Version: 470.182.03 CUDA Version: 11.4 |
|——————————-+———————-+———————-+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|===============================+======================+======================|
| 0 NVIDIA GeForce … Off | 00000000:01:00.0 Off | N/A |
| 0% 55C P8 10W / 180W | 2MiB / 8119MiB | 0% Default |
| | | N/A |
+——————————-+———————-+———————-+

+—————————————————————————–+
| Processes: |
| GPU GI CI PID Type Process name GPU Memory |
| ID ID Usage |
|=============================================================================|
| No running processes found |
+—————————————————————————–+

Categories
Uncategorized

Using Python Scripts to Control WiFi Router

Controlling network access of a specific device to a router using web interface is a pain. Thanks to Mathieu Velten, who developed pynetgear, a Python package that supports scripting Netgear router, by reverse engineering the Netgear Genie App.

I wrote the following code utilizing the pynetgear package to turn on (Allow) and off (Block) network access for a specific device to my router.

#!/usr/bin/env python
import sys
import time
import click
from pynetgear import Netgear


class NetgearManager:
    """
    Netgear Router Manager
    """
    def __init__(self, pwd):
        self.session = Netgear(password=pwd)

    def search_connected_device_by_name(self, name):
        found = []
        for device in self.session.get_attached_devices():
            if device.name == name:
                found.append(device)
        if len(found) >= 0:
            return found
        return None

    def get_device_status_by_name(self, name):
        devices = self.search_connected_device_by_name(name)
        if len(devices) > 1:
            print(f'More than one device has the name {name}', file=sys.stderr)
            for d in devices:
                print(d.ip, d.type, d.mac, d.allow_block_device)
        return False

    def set_device_status_by_name(self, name, status_code, delay):
        assert status_code in ['Allow', 'Block']
        devices = self.search_connected_device_by_name(name)
        if len(devices)==1:
            mac_address = devices[0].mac
            return self.set_device_status_by_mac(self, mac_address, status_code, delay)
        elif len(devices)>1:
            print(f'More than one device has the name {name}', file=sys.stderr)
            for d in devices:
                print(d.ip, d.type, d.mac, d.allow_or_block, file=sys.stderr)
        return False

    def set_device_status_by_mac(self, mac, status_code, delay):
        if delay > 0:
            time.sleep(delay)
        return self.session.allow_block_device(mac, device_status=status_code)

@click.group()
def cli():
    pass

@click.command()
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=False, help='Netgear outer admmin password')
@click.option('--name', help='Device name')
@click.option('--mac', default=None, help='Device MAC address')
@click.option('--status', help='Status: Allow or Block')
@click.option('--delay', default=0, help='Time delay in minutes')
def switch(password, name, mac, status, delay):
    manager = NetgearManager(password)
    delay *= 60                 # minutes to seconds
    if mac:
        result = manager.set_device_status_by_mac(mac, status, delay)
    else:
        result = manager.set_device_status_by_name(name, status, delay)
    if not result:
        msg = f'Cannot switch device {name} status to {status}'
        print(msg, file=sys.stderr)

@click.command()
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=False, help='Netgear outer admmin password')
def show(password):
    manager = NetgearManager(password)
    devices = []
    for idx, dev in enumerate(manager.session.get_attached_devices()):
        print(str(idx), dev.name, dev.ip, dev.type, dev.mac, dev.allow_or_block)

cli.add_command(switch)
cli.add_command(show)

if __name__ == '__main__':
    cli()


Categories
Uncategorized

PyTorch Geometric and CUDA

PyTorch Geometric (PyG) is an add-on library for developing graph neural networks using Python. It supports CUDA but you’ll have to make sure to install it correctly. Below is one error message I got after installing PyG:

from torch_geometric.data import Data
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
...

OSError: /anaconda3/lib/python3.7/site-packages/torch_sparse/_version_cuda.so: undefined symbol: _ZN5torch3jit17parseSchemaOrNameERKSs

It is clear this error is related to CUDA version. So, I checked it:

print(torch.version.cuda, torch.version)
10.2, 1.9.0

Running $ nvidia-smi, gave a CUDA version 11.2. So my system was somehow messed up with mixed versions of CUDA. To fix the mess and get PyG working, I did the following:

$ pip uninstall torch
$ pip install torch===1.9.1+cu111 -f https://download.pytorch.org/whl/torch_stable.html
$ pip install torch-scatter -f https://data.pyg.org/whl/torch-1.9.1+cu111.html
$ pip install torch-sparse -f https://data.pyg.org/whl/torch-1.9.1+cu111.html
$ pip install torch-geometric
$ apt-get install nvidia-modprobe

Note that there is no existing wheel built with CUDA 11.2 (cu112) so I used the closest version (cu111). Now PyG works! The “nvidia-modprobe” kernel extension fixes “RuntimeError: CUDA unknown error – this may be due to an incorrectly set up environment, e.g. changing env variable CUDA_VISIBLE_DEVICES after program start. Setting the available devices to be zero,” which I got after having two Python sessions running and both trying to using CUDA.

Update from some other testing regarding these errors:

RuntimeError: Detected that PyTorch and torch_cluster were compiled with different CUDA versions. PyTorch has CUDA version 11.1 and torch_cluster has CUDA version 10.2. Please reinstall the torch_cluster that matches your PyTorch install.

RuntimeError: Detected that PyTorch and torch_spline_conv were compiled with different CUDA versions. PyTorch has CUDA version 11.1 and torch_spline_conv has CUDA version 10.2. Please reinstall the torch_spline_conv that matches your PyTorch install.

The following commands fixed it:

$ pip install --upgrade pip
$ CUDA=cu111
$ TORCH=1.9.1
$ pip install torch-cluster==1.5.9 -f https://data.pyg.org/whl/torch-${TORCH}+${CUDA}.html
$ pip install torch-spline-conv -f https://data.pyg.org/whl/torch-${TORCH}+${CUDA}.html

Categories
Uncategorized

Git with Python

There are times when you want to do the source code management programmatically, and here comes GitPython. GitPython wraps the git commands so that you can execute most git functions from within Python (and without using shutils or subprocess). The example code snippet below shows how to do a “git clone” and if the destination is already there, it will try a “git checkout” first from the “master” branch if it exists then the “main” branch if the master branch does not exist.

try:
    git.Repo.clone_from(remote_repo, local_repo)
except GitCommandError as error:
    if error.status == 128:
        repo = git.Repo(local_repo)
        branch = 'master'
        try:
            repo.git.checkout(branch)
        except GitCommandError:
            branch = 'main'  
            repo.git.checkout(branch)
                
    else:
        msg = ' '.join(error.command)
        msg += error.stderr
        sys.exit(f'Error in running git: {msg}.')
Categories
Uncategorized

Signing Git Commit using GPG

I have been enjoying using Magit in Emacs to do all the git related stuff and run into an error when tagging a release. The error message is

git … tag --annotate --sign -m my_msg
error: gpg failed to sign the data
error: unable to sign the tag

This turned out to be caused by the fact that I have not set up gpg signing and signature. Below is how the problem is fixed and from now on all my git commits are going to be signed.

$ gpg --gen-key

There were a few dialogues between these commands, e.g. asking for names, e-mail, secret key, and it is recommended that you type random keys after these questions so that when gpg generate randoms there is more entropy. In the end, you will see some text with a line like this:

gpg: key 404NOTMYREALKEYID marked as ultimately trusted

This string “404NOTMYREALKEYID” is the key id. The same key id also shows up in the output of the following command:

$ gpg --list-secret-keys --keyid-format LONG
.....
---------------------------
sec   rsa3072/404NOTMYREALKEYID ......

Finally, just registering this key id with git. And the problem is solved. So the problem is not in Magit, but my configuration, since Magit uses the “–sign” option when it calls Git, which is actually a good practice.

$ git config --global commit.gpgsign true
$ git config --global user.signingkey 404NOTMYREALKEYID

Categories
Uncategorized

Some Improvements of the Python Language

Recently I have been reading a lot of Python code and noticed several improvements of the language that are really useful and wished that I had knew earlier since some of the changes were added to the Python language specification back from Python 3.5.

One improvement is the Type Hints (PEP 484, implemented in Python 3.5). It allows developers to add a type after a function parameter and a return type, which allows the code reader or another developer to understand what types are intended for the parameters. There is no checking of the actual parameter types being passed. The following example from the PEP 484 page explains its usage.

def greeting(name: str) -> str:
    return 'Hello ' + name

Another nice improvement is the new string formatting method introduced in Python 3.6 under “Formatted string literals.” It allows one to add Python variable values (or even calls) to a string object. Previously one has to use the “.format()” method to format a string. The example below explains how convenient it is now with the method.

def greeting(name: str) -> str:
    return f'Hello {name}'