ml-stable-diffusion icon indicating copy to clipboard operation
ml-stable-diffusion copied to clipboard

Add a way to cancel .generateImages()

Open martinlexow opened this issue 2 years ago • 6 comments

Generating images can take quite a while and users may want to cancel the progress. Adding a way to abort .generateImages() would be a great benefit.

martinlexow avatar Dec 27 '22 16:12 martinlexow

I've been having this issue as well. I've tried many things from canceling the DispatchQueue where generateImages() was called, calling unloadResources() in the pipeline, etc but none of them works.

godly-devotion avatar Dec 27 '22 19:12 godly-devotion

Should generateImages() be made async? If so we can Task.checkCancellation() on each iteration.

JustinMeans avatar Dec 27 '22 20:12 JustinMeans

@JustinMeans That would be helpful. Not sure if this is the best method but this is how I am currently calling it.

godly-devotion avatar Dec 27 '22 21:12 godly-devotion

How about using progress handler, just return false to cancel the image generation?

nonisolated func progressHandler(progress: StableDiffusionPipeline.Progress) -> Bool {...}

ynagatomo avatar Dec 27 '22 22:12 ynagatomo

@ynagatomo Just tested, that works too 👍 An official solution would be nice though as it does trigger the error handler. Also having the continueGeneration bool is slightly ugly haha.

let images = try pipeline.generateImages(
    prompt: prompt,
    negativePrompt: negativePrompt,
    imageCount: batchSize,
    stepCount: stepCount,
    seed: seed,
    guidanceScale: guidanceScale,
    disableSafety: true,
    scheduler: scheduler
) { progress in
    return handleProgress(progress)
}

private func handleProgress(_ progress: StableDiffusionPipeline.Progress) -> Bool {
    self.progress = progress
    return continueGeneration
}

godly-devotion avatar Dec 27 '22 22:12 godly-devotion

I agree that .generateImages() should be async. Also, then the progress closure wouldn't need to return a boolean either as it could just respect Task cancellation internally.

sindresorhus avatar Dec 28 '22 11:12 sindresorhus