StableDiffusion on nodejs with GPU acceleration using Cuda or DirectML
npm install stable-diffusion-nodejstypescript
import { PNG } from 'pngjs'
import { StableDiffusionPipeline } from 'stable-diffusion-nodejs'
const pipe = await StableDiffusionPipeline.fromPretrained(
'directml', // can be 'cuda' on linux or 'cpu' on mac os
'aislamov/stable-diffusion-2-1-base-onnx', // relative path or huggingface repo with onnx model
)
const image = await pipe.run("A photo of a cat", undefined, 1, 9, 30)
const p = new PNG({ width: 512, height: 512, inputColorType: 2 })
p.data = Buffer.from((await image[0].data()))
p.pack().pipe(fs.createWriteStream('output.png')).on('finish', () => {
console.log('Image saved as output.png');
})
`
$3
`typescript
import * as tf from "@tensorflow/tfjs-node"
import { StableDiffusionPipeline } from 'stable-diffusion-nodejs'
const pipe = await StableDiffusionPipeline.fromPretrained(
'directml', // can be 'cuda' on linux or 'cpu' on mac os
'aislamov/stable-diffusion-2-1-base-onnx', // relative path or huggingface repo with onnx model
)
const image = await pipe.run("A photo of a cat", undefined, 1, 9, 30)
const png = await tf.node.encodePng(image[0])
fs.writeFileSync("output.png", png);
`
$3
`typescript
import * as tf from "@tensorflow/tfjs-node"
import { StableDiffusionPipeline } from 'stable-diffusion-nodejs'
const pipe = await StableDiffusionPipeline.fromPretrained(
'directml', // can be 'cuda' on linux or 'cpu' on mac os
'CompVis/stable-diffusion-v1-4',
'onnx', // hf hub revision
1, // SD version, cannot detect automatically yet
)
const image = await pipe.run("A photo of a cat", undefined, 1, 9, 30)
const png = await tf.node.encodePng(image[0])
fs.writeFileSync("output.png", png);
`
Command-line usage
To test inference run this command. It will download SD2.1 onnx version from huggingface hub
$3
npm run txt2img -- --prompt "an astronaut riding a horse" --provider directml
$3
npm run txt2img -- --prompt "an astronaut riding a horse" --provider cuda
You can also use --provider cpu` on a mac or if you don't have a supported videocard