sapbot

AMD Fan control

May 18th, 2026
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env node
  2.  
  3. const { exec } = require('child_process');
  4. const util = require('util');
  5. const execPromise = util.promisify(exec);
  6.  
  7. /**
  8.  * Parse GPU usage percentage from `rocm-smi -u` output.
  9.  * Expected format: "GPU[0] : GPU use (%): 0" or similar.
  10.  * Returns number or null if not found.
  11.  */
  12. function parseGpuUsage(output) {
  13.   const match = output.match(/GPU use\s*\(\%\):\s*(\d+)/i);
  14.   if (match && match[1]) {
  15.     return parseInt(match[1], 10);
  16.   }
  17.   return null;
  18. }
  19.  
  20. /**
  21.  * Set GPU fan speed to a given percentage (0-100).
  22.  * Uses `rocm-smi --setfan <percent>%`.
  23.  */
  24. async function setFanSpeed(percent) {
  25.   if (percent < 0 || percent > 100) {
  26.     console.error(`Invalid fan speed: ${percent} (must be 0-100)`);
  27.     return;
  28.   }
  29.   const cmd = `rocm-smi --setfan ${percent}%`;
  30.   try {
  31.     const { stdout, stderr } = await execPromise(cmd);
  32.     if (stderr && !stderr.includes('WARNING')) {
  33.       console.warn('Fan set stderr:', stderr.trim());
  34.     }
  35.     console.log(`Fan set to ${percent}% — ${stdout.match(/Successfully set fan speed/i) ? 'success' : 'check output'}`);
  36.   } catch (error) {
  37.     console.error(`Failed to set fan speed to ${percent}%:`, error.message);
  38.   }
  39. }
  40.  
  41. /**
  42.  * Fetch current GPU usage and apply as fan speed.
  43.  */
  44. async function updateFanByUsage() {
  45.   try {
  46.     const { stdout, stderr } = await execPromise('rocm-smi -u');
  47.     if (stderr && !stderr.includes('WARNING')) {
  48.       console.warn('GPU usage stderr:', stderr.trim());
  49.     }
  50.  
  51.     const usagePercent = parseGpuUsage(stdout);
  52.     if (usagePercent === null) {
  53.       console.error('Could not parse GPU usage from rocm-smi output.');
  54.       return;
  55.     }
  56.  
  57.     console.log(`Current GPU usage: ${usagePercent}%`);
  58.     await setFanSpeed(usagePercent);
  59.   } catch (error) {
  60.     console.error('Error executing rocm-smi -u:', error.message);
  61.   }
  62. }
  63.  
  64. // Run immediately, then every second
  65. updateFanByUsage();
  66. setInterval(updateFanByUsage, 1000);
Advertisement
Add Comment
Please, Sign In to add comment