hpc-toolkitpk-unix

hpc-toolkit

Linux tuning scripts and configs for HPC GPU nodes — NUMA, huge pages, CPU governors, InfiniBand, RoCE, and production sysctl/limits templates.

git clone https://github.com/pk-unix/hpc-toolkit.git
cd hpc-toolkit

What it looks like

~/hpc-toolkit
$ ./hpc/numa-check.sh NUMA topology: gpu-node-07 Node 0: CPUs 0-31 Mem 512GB GPUs 0,1,2,3 IB mlx5_0,mlx5_1 Node 1: CPUs 32-63 Mem 512GB GPUs 4,5,6,7 IB mlx5_2,mlx5_3 ✓ GPU-to-NUMA affinity correct for all 8 GPUs ✓ IB adapters bound to matching NUMA node $ ./networking/ib-check.sh Port State Rate Errors (link/sym/rcv) mlx5_0 Active 400Gb/s 0 / 0 / 0 mlx5_1 Active 400Gb/s 0 / 0 / 0 mlx5_2 Active 400Gb/s 0 / 0 / 0 mlx5_3 Active 200Gb/s 0 / 14 / 0 ⚠ running at half speed $ sudo ./hpc/hugepages-setup.sh --count 4096 --persistent Configuring 4096 × 2MB huge pages (8GB) across NUMA nodes... Node 0: 2048 pages allocated Node 1: 2048 pages allocated ✓ Persisted to /etc/sysctl.d/90-hugepages.conf

This is an illustrative example of real command output — run the scripts on an actual HPC node to see your own results.

Source

networking/ib-check.sh

#!/bin/bash
# InfiniBand link health check — port state, speed, error counters.
# Flags links that are down, degraded, or accumulating errors.
#
# Usage:
#   ./ib-check.sh             # all IB ports
#   ./ib-check.sh --errors    # show error counters only
#   ./ib-check.sh --watch     # refresh every 5s

set -euo pipefail

RED='\033[0;31m'; YEL='\033[0;33m'; GRN='\033[0;32m'; CYN='\033[0;36m'; RST='\033[0m'

ERRORS_ONLY=${1:-}
WATCH=0
[[ "${1:-}" == "--watch" ]] && WATCH=1

check_all() {
    echo "=== InfiniBand Status: $(hostname) @ $(date '+%H:%M:%S') ==="
    echo ""

    if ! command -v ibstat &>/dev/null; then
        echo "ibstat not found — trying sysfs fallback"
        for dev in /sys/class/infiniband/*/; do
            devname=$(basename "$dev")
            for port in "$dev/ports"/*/; do
                portnum=$(basename "$port")
                state=$(cat "$port/state"      2>/dev/null | awk '{print $2}')
                speed=$(cat "$port/rate"       2>/dev/null || echo "?")
                phys=$(cat  "$port/phys_state" 2>/dev/null | awk '{print $2}')
                printf "  %-12s port %s  state=%-10s  phys=%-10s  %s Gb/s\n" \
                    "$devname" "$portnum" "$state" "$phys" "$speed"
            done
        done
        return
    fi

    ibstat 2>/dev/null | awk '
        /^CA / { ca=$2 }
        /Port / { port=$2 }
        /State:/ { state=$2 }
        /Physical state:/ { phys=$3 }
        /Rate:/ { rate=$2 }
        /Link layer:/ {
            color = ""
            if (state != "Active") color = "\033[0;31m"
            printf "  %-15s port %s  state=%-10s  phys=%-15s  %s Gb/s  %s\n",
                ca, port, color state "\033[0m", phys, rate, $0
        }
    '
    echo ""

    # Error counters via perfquery
    if command -v perfquery &>/dev/null; then
        echo -e "${CYN}Error counters (non-zero only):${RST}"
        found=0
        ibstat 2>/dev/null | awk '/^CA /{ca=$2} /Port /{port=$2} /^$/{print ca,port}' | \
        while read -r ca port; do
            [[ -z "$ca" || -z "$port" ]] && continue
            out=$(perfquery -x "$ca" "$port" 2>/dev/null || true)
            errors=$(echo "$out" | grep -vE "^(#|PortSelect|CounterSelect|SymbolErrors|LinkDownedCounter|PortRcvErrors|PortXmitDiscards|PortXmitConstraintErrors|PortRcvConstraintErrors|LocalLinkIntegrityErrors|ExcessiveBufferOverrunErrors|VL15Dropped|PortXmitData|PortRcvData|PortXmitPkts|PortRcvPkts|PortXmitWait|QP1Dropped).*\. 0$" | grep -vE "^$" || true)
            if [[ -n "$errors" ]]; then
                echo -e "  ${YEL}$ca port $port:${RST}"; echo "$errors" | sed 's/^/    /'
                found=1
            fi
        done
        [[ $found -eq 0 ]] && echo -e "  ${GRN}✓  No errors${RST}"
    fi
}

if [[ $WATCH -eq 1 ]]; then
    while true; do clear; check_all; sleep 5; done
else
    check_all
fi

networking/net-tune.sh

#!/bin/bash
# Apply network tuning for high-throughput HPC workloads.
# Increases socket buffers, TCP settings, and RoCE/RDMA parameters.
#
# Usage:
#   ./net-tune.sh --apply      # apply all tunings
#   ./net-tune.sh --status     # show current values
#   ./net-tune.sh --roce       # also apply RoCE-specific settings

set -euo pipefail

RED='\033[0;31m'; GRN='\033[0;32m'; YEL='\033[0;33m'; RST='\033[0m'
[[ $EUID -ne 0 ]] && { echo -e "${RED}Run as root.${RST}"; exit 1; }

MODE="${1:---status}"

declare -A TUNINGS=(
    # Socket buffers (256 MB)
    ["net.core.rmem_max"]="268435456"
    ["net.core.wmem_max"]="268435456"
    ["net.core.rmem_default"]="67108864"
    ["net.core.wmem_default"]="67108864"
    ["net.ipv4.tcp_rmem"]="4096 87380 268435456"
    ["net.ipv4.tcp_wmem"]="4096 65536 268435456"
    # Backlog / queues
    ["net.core.netdev_max_backlog"]="250000"
    ["net.core.somaxconn"]="65535"
    ["net.ipv4.tcp_max_syn_backlog"]="65535"
    # TCP performance
    ["net.ipv4.tcp_congestion_control"]="bbr"
    ["net.ipv4.tcp_mtu_probing"]="1"
    ["net.ipv4.tcp_timestamps"]="0"
    ["net.ipv4.tcp_sack"]="1"
    # Memory
    ["vm.swappiness"]="10"
    ["vm.dirty_ratio"]="10"
    ["vm.dirty_background_ratio"]="5"
)

show_status() {
    echo "=== Network Tuning Status ==="
    for key in "${!TUNINGS[@]}"; do
        current=$(sysctl -n "$key" 2>/dev/null || echo "N/A")
        target="${TUNINGS[$key]}"
        if [[ "$current" == "$target" ]]; then
            echo -e "  ${GRN}✓${RST} $key = $current"
        else
            echo -e "  ${YEL}≠${RST} $key = $current  (target: $target)"
        fi
    done | sort
}

apply_tunings() {
    echo -e "${YEL}Applying network tunings…${RST}"
    for key in "${!TUNINGS[@]}"; do
        sysctl -w "$key=${TUNINGS[$key]}" > /dev/null 2>&1 && \
            echo -e "  ${GRN}✓${RST} $key" || \
            echo -e "  ${RED}✗${RST} $key (skipped)"
    done

    if [[ "${2:-}" == "--roce" ]]; then
        echo ""
        echo -e "${YEL}Applying RoCE settings…${RST}"
        # Enable ECN for RoCE lossless fabric
        for iface in $(ls /sys/class/net/ | grep -E "^(eth|ens|ib|rdma)"); do
            tc qdisc add dev "$iface" root fq 2>/dev/null || true
        done
        sysctl -w net.ipv4.tcp_ecn=1 > /dev/null
        echo -e "  ${GRN}✓${RST} ECN enabled"
    fi

    echo ""
    echo -e "${GRN}Done. To persist across reboots:${RST}"
    echo "  sysctl -p /etc/sysctl.d/90-hpc-net.conf"
    echo ""
    echo "  Or run: $0 --persist"
}

persist() {
    conf="/etc/sysctl.d/90-hpc-net.conf"
    {
        echo "# HPC network tunings — generated by net-tune.sh"
        for key in "${!TUNINGS[@]}"; do
            echo "$key = ${TUNINGS[$key]}"
        done
    } | sort > "$conf"
    echo -e "${GRN}✓  Written to $conf${RST}"
}

case "$MODE" in
    --apply)   apply_tunings "$@" ;;
    --persist) persist ;;
    *)         show_status ;;
esac

hpc/cpu-perf-mode.sh

#!/bin/bash
# Set CPU frequency governor to 'performance' on all cores.
# Also disables CPU C-states and enables turbo boost for low-latency HPC.
#
# Usage:
#   ./cpu-perf-mode.sh              # set performance mode
#   ./cpu-perf-mode.sh --status     # show current governors
#   ./cpu-perf-mode.sh --powersave  # restore powersave (after job)

set -euo pipefail

RED='\033[0;31m'; GRN='\033[0;32m'; YEL='\033[0;33m'; RST='\033[0m'

[[ $EUID -ne 0 ]] && { echo -e "${RED}Run as root.${RST}"; exit 1; }

MODE="${1:-performance}"

show_status() {
    echo "=== CPU Governor Status ==="
    echo ""
    echo "Current governors (unique):"
    sort -u /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor 2>/dev/null \
        | uniq -c || echo "  (cpufreq not available)"
    echo ""
    echo "Turbo boost:"
    if [[ -f /sys/devices/system/cpu/intel_pstate/no_turbo ]]; then
        val=$(cat /sys/devices/system/cpu/intel_pstate/no_turbo)
        [[ $val -eq 0 ]] && echo "  Enabled" || echo "  Disabled"
    elif [[ -f /sys/devices/system/cpu/cpufreq/boost ]]; then
        val=$(cat /sys/devices/system/cpu/cpufreq/boost)
        [[ $val -eq 1 ]] && echo "  Enabled" || echo "  Disabled"
    else
        echo "  Unknown"
    fi
    echo ""
    echo "C-state limits (cpu0):"
    for state in /sys/devices/system/cpu/cpu0/cpuidle/state*/; do
        name=$(cat "$state/name"     2>/dev/null || echo "?")
        dis=$(cat  "$state/disable"  2>/dev/null || echo "?")
        lat=$(cat  "$state/latency"  2>/dev/null || echo "?")
        printf "  %-6s  disabled=%-1s  latency=%s us\n" "$name" "$dis" "$lat"
    done
}

if [[ "$MODE" == "--status" ]]; then
    show_status; exit 0
fi

GOV="performance"
[[ "$MODE" == "--powersave" ]] && GOV="powersave"

echo -e "${YEL}Setting governor → $GOV on all CPUs…${RST}"
for cpu in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do
    echo "$GOV" > "$cpu" 2>/dev/null || true
done

# Disable C-states beyond C1 for performance mode (re-enable for powersave)
if [[ "$GOV" == "performance" ]]; then
    for state in /sys/devices/system/cpu/cpu*/cpuidle/state[2-9]/disable; do
        echo 1 > "$state" 2>/dev/null || true
    done
    # Enable turbo
    [[ -f /sys/devices/system/cpu/intel_pstate/no_turbo ]] && echo 0 > /sys/devices/system/cpu/intel_pstate/no_turbo
    [[ -f /sys/devices/system/cpu/cpufreq/boost ]]         && echo 1 > /sys/devices/system/cpu/cpufreq/boost
    echo -e "${GRN}✓  Performance mode: C-states C2+ disabled, turbo on.${RST}"
else
    for state in /sys/devices/system/cpu/cpu*/cpuidle/state[2-9]/disable; do
        echo 0 > "$state" 2>/dev/null || true
    done
    echo -e "${GRN}✓  Powersave mode: C-states restored.${RST}"
fi

echo ""
show_status

hpc/hugepages-setup.sh

#!/bin/bash
# Configure huge pages for HPC workloads.
# Supports 2MB (default) and 1GB (persistent) huge pages.
#
# Usage:
#   ./hugepages-setup.sh --count 4096          # set 4096 x 2MB pages
#   ./hugepages-setup.sh --1gb --count 16      # set 16 x 1GB pages
#   ./hugepages-setup.sh --status              # show current state
#   ./hugepages-setup.sh --persistent          # also add to /etc/sysctl.d/

set -euo pipefail

RED='\033[0;31m'; GRN='\033[0;32m'; YEL='\033[0;33m'; RST='\033[0m'

usage() {
    echo "Usage: $0 [--count N] [--1gb] [--status] [--persistent]"
    exit 1
}

STATUS=0; COUNT=0; USE_1GB=0; PERSISTENT=0
while [[ $# -gt 0 ]]; do
    case $1 in
        --status)     STATUS=1 ;;
        --count)      COUNT=$2; shift ;;
        --1gb)        USE_1GB=1 ;;
        --persistent) PERSISTENT=1 ;;
        *)            usage ;;
    esac
    shift
done

show_status() {
    echo "=== Huge Pages Status: $(hostname) ==="
    echo ""
    echo "2MB huge pages:"
    grep -E "HugePages_|Hugepagesize:" /proc/meminfo | grep -v "1048576"
    echo ""
    echo "1GB huge pages:"
    grep "1048576" /proc/meminfo || echo "  (none configured)"
    echo ""
    echo "Huge page mounts:"
    mount | grep hugetlbfs || echo "  (none)"
    echo ""
    echo "NUMA breakdown:"
    for node in /sys/devices/system/node/node*/hugepages/hugepages-*/; do
        [[ -d "$node" ]] || continue
        total=$(cat "$node/nr_hugepages" 2>/dev/null || echo 0)
        free=$(cat  "$node/free_hugepages" 2>/dev/null || echo 0)
        [[ $total -gt 0 ]] && echo "  $node  total=$total  free=$free"
    done
}

if [[ $STATUS -eq 1 ]]; then
    show_status
    exit 0
fi

[[ $COUNT -eq 0 ]] && usage
[[ $EUID -ne 0 ]]  && { echo -e "${RED}Run as root.${RST}"; exit 1; }

if [[ $USE_1GB -eq 1 ]]; then
    SIZE="hugepages-1048576kB"
    SYSCTL_KEY="vm.nr_hugepages_mempolicy"
    PAGE_SIZE="1GB"
else
    SIZE="hugepages-2048kB"
    SYSCTL_KEY="vm.nr_hugepages"
    PAGE_SIZE="2MB"
fi

echo -e "${YEL}Setting $COUNT x $PAGE_SIZE huge pages…${RST}"
echo "$COUNT" > /proc/sys/vm/nr_hugepages

actual=$(grep "^HugePages_Total:" /proc/meminfo | awk '{print $2}')
if [[ "$actual" -lt "$COUNT" ]]; then
    echo -e "${YEL}Warning: only $actual of $COUNT pages allocated (memory fragmentation?).${RST}"
    echo "Try: echo 3 > /proc/sys/vm/drop_caches && re-run"
else
    echo -e "${GRN}✓  $actual x $PAGE_SIZE huge pages allocated.${RST}"
fi

if [[ $PERSISTENT -eq 1 ]]; then
    conf="/etc/sysctl.d/90-hugepages.conf"
    echo "$SYSCTL_KEY = $COUNT" > "$conf"
    echo -e "${GRN}✓  Written to $conf (persistent across reboots).${RST}"
fi

show_status

hpc/numa-check.sh

#!/bin/bash
# NUMA topology summary — CPUs, memory, and GPU affinity per node.
# Useful before pinning MPI ranks or GPU workloads to NUMA domains.
#
# Usage:  ./numa-check.sh

set -euo pipefail

CYN='\033[0;36m'; GRN='\033[0;32m'; YEL='\033[0;33m'; RST='\033[0m'

echo "=== NUMA Topology: $(hostname) ==="
echo ""

# ── NUMA nodes + CPUs + memory ─────────────────────────────────────────────
echo -e "${CYN}NUMA nodes:${RST}"
numactl --hardware 2>/dev/null || lscpu | grep -E "NUMA|Socket|Core"
echo ""

# ── CPU → NUMA mapping ─────────────────────────────────────────────────────
echo -e "${CYN}CPU cores per NUMA node:${RST}"
for node in /sys/devices/system/node/node*/; do
    n=$(basename "$node")
    cpus=$(cat "$node/cpulist" 2>/dev/null || echo "?")
    mem_kb=$(cat "$node/meminfo" 2>/dev/null | grep "MemTotal" | awk '{print $4}')
    mem_gb=$(( ${mem_kb:-0} / 1024 / 1024 ))
    echo "  $n: CPUs $cpus  —  ${mem_gb} GB"
done
echo ""

# ── GPU → NUMA affinity ────────────────────────────────────────────────────
if command -v nvidia-smi &>/dev/null; then
    echo -e "${CYN}GPU NUMA affinity:${RST}"
    nvidia-smi --query-gpu=index,name,pci.bus_id --format=csv,noheader | \
    while IFS=',' read -r idx name pci; do
        pci=$(echo "$pci" | xargs | tr '[:upper:]' '[:lower:]')
        # Find NUMA node via sysfs PCI path
        numa_node=$(cat "/sys/bus/pci/devices/$pci/numa_node" 2>/dev/null || echo "?")
        printf "  GPU %-2s  %-35s  NUMA node %s\n" \
            "$(echo $idx|xargs)" "$(echo $name|xargs)" "$numa_node"
    done
    echo ""
fi

# ── InfiniBand → NUMA affinity ─────────────────────────────────────────────
if ls /sys/class/infiniband/ &>/dev/null 2>&1; then
    echo -e "${CYN}InfiniBand → NUMA affinity:${RST}"
    for ib in /sys/class/infiniband/*/; do
        dev=$(basename "$ib")
        # Get underlying PCI device
        pci=$(readlink -f "$ib/device" 2>/dev/null | xargs basename || echo "")
        numa_node=$(cat "/sys/bus/pci/devices/$pci/numa_node" 2>/dev/null || echo "?")
        echo "  $dev  →  NUMA node $numa_node"
    done
    echo ""
fi

# ── Recommendation ─────────────────────────────────────────────────────────
echo -e "${YEL}Tip: bind workloads with:  numactl --cpunodebind=<N> --membind=<N> <cmd>${RST}"
echo -e "${YEL}Or set in MPI:             mpirun --map-by ppr:1:numa:pe=<cpus_per_rank>${RST}"

Full README

# hpc-toolkit

Linux tuning scripts and configs for HPC GPU nodes — NUMA, huge pages, CPU governors, InfiniBand, RoCE, and production sysctl/limits templates.

---

## Contents

### `hpc/` — Node tuning
| Script | What it does |
|---|---|
| `numa-check.sh` | NUMA topology: CPUs, memory, GPU affinity, IB affinity per node |
| `hugepages-setup.sh` | Configure 2MB or 1GB huge pages with NUMA breakdown + persistence |
| `cpu-perf-mode.sh` | Set performance governor, disable C-states C2+, enable turbo boost |

### `networking/` — InfiniBand & network
| Script | What it does |
|---|---|
| `ib-check.sh` | IB port state, speed, and error counters (ibstat + perfquery) |
| `net-tune.sh` | Apply/persist high-throughput sysctl network settings (BBR, large buffers, RoCE) |

### `configs/` — Drop-in config templates
| File | Where to put it |
|---|---|
| `sysctl-hpc.conf` | `/etc/sysctl.d/90-hpc.conf` |
| `limits-hpc.conf` | `/etc/security/limits.d/90-hpc.conf` |

---

## Quick usage

```bash
git clone https://github.com/pk-unix/hpc-toolkit.git
cd hpc-toolkit
chmod +x hpc/*.sh networking/*.sh

# Check NUMA topology and GPU/IB affinity
./hpc/numa-check.sh

# Set performance mode (requires root)
sudo ./hpc/cpu-perf-mode.sh

# Configure huge pages (root, persistent)
sudo ./hpc/hugepages-setup.sh --count 4096 --persistent

# Check InfiniBand link health
./networking/ib-check.sh
./networking/ib-check.sh --watch   # refresh every 5s

# Apply network tunings (root)
sudo ./networking/net-tune.sh --apply

# Apply drop-in configs
sudo cp configs/sysctl-hpc.conf /etc/sysctl.d/90-hpc.conf && sudo sysctl --system
sudo cp configs/limits-hpc.conf /etc/security/limits.d/90-hpc.conf
```

## Requirements

- Bash 4+, root for tuning scripts
- `numactl` for NUMA checks
- `ibstat`, `perfquery` for InfiniBand checks (from `infiniband-diags` package)
- `nvidia-smi` for GPU affinity in `numa-check.sh` (optional)

## Related

- **[gpu-toolkit](https://github.com/pk-unix/gpu-toolkit)** — GPU diagnostics and Xid monitoring
- **[slurm-node-watcher](https://github.com/pk-unix/slurm-node-watcher)** — SLURM node auto-drain on faults