Skip to content

Instantly share code, notes, and snippets.

@erayack
Forked from ivanfioravanti/mlx_memory.sh
Last active December 27, 2025 23:44
Show Gist options
  • Select an option

  • Save erayack/fb277a8e061e2bdf6a1ebc470f499b4c to your computer and use it in GitHub Desktop.

Select an option

Save erayack/fb277a8e061e2bdf6a1ebc470f499b4c to your computer and use it in GitHub Desktop.
Script to set MLX memory limits
#!/usr/bin/env bash
set -euo pipefail
DEFAULT_WIRED_LIMIT_PERCENT=85
DEFAULT_WIRED_LWM_PERCENT=75
usage() {
cat <<'EOF'
Usage: set_wired_limits.sh [MAX_PERCENT] [LWM_PERCENT] [--apply]
- MAX_PERCENT: upper bound percent (0-100), default 85
- LWM_PERCENT: lower bound percent (0-100), default 75
- --apply: actually write values via sysctl (otherwise dry-run)
EOF
}
APPLY=0
ARGS=()
for arg in "$@"; do
case "$arg" in
--apply) APPLY=1 ;;
-h|--help) usage; exit 0 ;;
*) ARGS+=("$arg") ;;
esac
done
WIRED_LIMIT_PERCENT=${ARGS[0]:-$DEFAULT_WIRED_LIMIT_PERCENT}
WIRED_LWM_PERCENT=${ARGS[1]:-$DEFAULT_WIRED_LWM_PERCENT}
if ! [[ "$WIRED_LIMIT_PERCENT" =~ ^[0-9]+$ && "$WIRED_LWM_PERCENT" =~ ^[0-9]+$ ]]; then
echo "Error: Percentages must be integers." >&2
exit 1
fi
if (( WIRED_LIMIT_PERCENT < 0 || WIRED_LIMIT_PERCENT > 100 || WIRED_LWM_PERCENT < 0 || WIRED_LWM_PERCENT > 100 )); then
echo "Error: Percentages must be between 0 and 100." >&2
exit 1
fi
TOTAL_MEM_MB=$(( $(sysctl -n hw.memsize) / 1024 / 1024 ))
WIRED_LIMIT_MB=$(( TOTAL_MEM_MB * WIRED_LIMIT_PERCENT / 100 ))
WIRED_LWM_MB=$(( TOTAL_MEM_MB * WIRED_LWM_PERCENT / 100 ))
echo "Total memory: ${TOTAL_MEM_MB} MB"
echo "Maximum limit: ${WIRED_LIMIT_MB} MB (${WIRED_LIMIT_PERCENT}%) -> sysctl key: iogpu.wired_limit_mb"
echo "Lower bound: ${WIRED_LWM_MB} MB (${WIRED_LWM_PERCENT}%) -> sysctl key: iogpu.wired_lwm_mb"
if (( APPLY )); then
echo "Applying settings (sudo required)…"
sudo sysctl -w iogpu.wired_limit_mb="$WIRED_LIMIT_MB"
sudo sysctl -w iogpu.wired_lwm_mb="$WIRED_LWM_MB"
echo "Done."
else
echo "Dry-run only. Re-run with --apply to write values."
fi
@erayack
Copy link
Author

erayack commented Dec 27, 2025

Adds  set -euo pipefail  for safer shell execution.

  • Validates integer input and range before doing any work.
  • Dry-run by default reduces accidental writes;  --apply  is explicit.
  • Help/usage text for quick reference.

Testing guidance:

  • Dry-run with defaults:  ./set_wired_limits.sh 
  • Dry-run custom:  ./set_wired_limits.sh 80 70 
  • Apply after review:  ./set_wired_limits.sh 80 70 --apply 
  • Error cases:  ./set_wired_limits.sh 110  should exit with validation error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment