Skip to content

Image2image - python #115

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jan 31, 2023
Merged

Image2image - python #115

merged 6 commits into from
Jan 31, 2023

Conversation

littleowl
Copy link
Contributor

@littleowl littleowl commented Jan 28, 2023

Adds image2image functionality.

This is only the python portion needed to generate the VAE Encoder.

Swift
Original PR

In Python, a new CoreML model can be generated to encode the latent space for image2image. The model bakes in some of the operations typically performed in the pipeline so that a separate model would not need to be created for those operations, nor would the CPU be needed to perform the tensor multiplications. Some of the simpler math involving the scheduler's time steps are performed on the cpu and passed into the encoder. The encoder works around torch.randn missing operation by passing in nose tensors to apply to the image latent space.

Initial feedback from the initial PR #73 was to separate the python portion of the PR. Additionally, it was asked if we could implement the methodology to override the randn PyTorch function as instructions can be found how to do so in coremltools documentation. Initially, I had no qualms digging into this task to see how we could simplify the interface. However, when investigating the issue, I had discovered that I had already tried these steps initially when I initially had encountered the missing randn function. I had actually implemented the suggestion from @atiorh to encounter other errors:

The initial error:

  File "/opt/homebrew/Caskroom/miniforge/base/envs/coreml_stable_diffusion/lib/python3.8/site-packages/coremltools/converters/mil/frontend/torch/converter.py", line 270, in convert
    convert_nodes(self.context, self.graph)
  File "/opt/homebrew/Caskroom/miniforge/base/envs/coreml_stable_diffusion/lib/python3.8/site-packages/coremltools/converters/mil/frontend/torch/ops.py", line 100, in convert_nodes
    raise RuntimeError(
RuntimeError: PyTorch convert function for op 'randn' not implemented.

Error with randn override:

  File "/opt/homebrew/Caskroom/miniforge/base/envs/coreml_stable_diffusion/lib/python3.8/site-packages/coremltools/converters/mil/frontend/torch/torch_op_registry.py", line 42, in func_wrapper
    raise ValueError("Torch op {} already registered.".format(f_name))
ValueError: Torch op randn already registered.

Furthermore, I cannot say that I actually agree that it is a good idea to generate the random numbers in python anyways. The noise for the latent space generation for regular prompt based generation is generated in Swift on the CPU. It could be that some techniques might need to use the same seed. For instance, there is experimentation with interoperable translation between two latent spaces. For reasons such as this, I would weigh on the side of generating the noise from swift.

That said, in the commit history of this branch, you can see where I tried to do this a second time. Where I tried importing the original DiagonalGaussianDistribution function and overriding the randn function.

However, this solution copies the parts of the DiagonalGaussianDistribution class needed to a CoreMLDiagonalGaussianDistribution. Furthermore it optimizes the other operations that happen just after the VAEEncoder in the Diffusion library. Otherwise we would need yet another model, or math library to perform these routines.

Do not erase the below when submitting your pull request:
#########

  • I agree to the terms outlined in CONTRIBUTING.md

This was referenced Jan 28, 2023
Copy link
Contributor

@atiorh atiorh left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the amazing effort @littleowl, we are almost there!

  • I ran this commit on a fresh install and it requires a one-liner fix from the main branch to work with the latest diffusers release so please rebase one last time to get that in.
  • The generated model has ~56dB PSNR which is pretty good
  • I requested minor changes such as removing device placement code to improve readability, moving from camelCase to underscore in I/O names for consistency and some typos.
  • Regarding the generation of noise in-network versus out-of-network. The solution to ValueError: Torch op randn already registered is to prepend the op registration by:
from coremltools.converters.mil.frontend.torch.torch_op_registry import _TORCH_OPS_REGISTRY
if 'randn' in _TORCH_OPS_REGISTRY:
  del _TORCH_OPS_REGISTRY['randn']

but it isn't too important as it turns out that making the random seed an actual network input would have required some more work. I am convinced that generating the noise tensor in Swift sounds like the right way to go at the moment since @msiracusa wrote an RNG to match NumPy RNG behavior.

@littleowl
Copy link
Contributor Author

@atiorh thank you for your review and insights. I believe I have resolved all of your comments and I've tested once more with the swift code with the name changes. Let me know if there is anything else!

@littleowl littleowl requested a review from atiorh January 31, 2023 05:59
@atiorh
Copy link
Contributor

atiorh commented Jan 31, 2023

Thanks for the amazing work @littleowl !

@atiorh atiorh merged commit 086cc5e into apple:main Jan 31, 2023
takeyat pushed a commit to takeyat/ml-stable-diffusion that referenced this pull request Feb 7, 2023
* commit 'e4ca3ff86b4a63c4ffe85a16b0afadb0f6c98fe4':
  Add link to HF app to the Example Swift App section. (apple#121)
  Image2image - python (apple#115)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants