-
Notifications
You must be signed in to change notification settings - Fork 12
Add cytosyn model for image generation #188
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
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
d187f2f
Add cytosyn model
Mr-Milk c3ff728
Add a function for image generation
Mr-Milk bf97e02
Update dependencies
Mr-Milk b406752
Fix a bug that leds to the failure of list_models
Mr-Milk a36e119
Rename it to match the language style in the tools module
Mr-Milk 983d937
Update the docstring
Mr-Milk 2ee110e
Add tests for image generation models
Mr-Milk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| from .cytosyn import CytoSyn | ||
|
|
||
| __all__ = ["CytoSyn"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| from importlib import import_module | ||
| from importlib.util import find_spec | ||
|
|
||
| import torch | ||
|
|
||
| from .._model_registry import register | ||
| from .._utils import hf_access | ||
| from ..base import ImageGenerationModel, ModelTask | ||
|
|
||
|
|
||
| @register( | ||
| key="cytosyn", | ||
| task=ModelTask.image_generation, | ||
| is_gated=True, | ||
| license="CC BY-NC-ND 4.0", | ||
| description="A REPA-E Histopathology Image Generation Model", | ||
| commercial=False, | ||
| github_url="https://github.com/prov-gigatime/GigaTIME", | ||
| paper_url="https://www.owkin.com/blogs-case-studies/" | ||
| "cytosyn-a-state-of-the-art-diffusion-model-for-histopathology-image-generation", | ||
| param_size="766M", | ||
| ) | ||
| class CytoSyn(ImageGenerationModel): | ||
| def __init__(self, model_path=None, token=None): | ||
| diffusers = find_spec("diffusers") | ||
| if diffusers is None: | ||
| raise ModuleNotFoundError( | ||
| "Please install diffusers to use CytoSyn: `pip install diffusers`" | ||
| ) | ||
|
|
||
| DiffusionPipeline = import_module("diffusers.pipelines").DiffusionPipeline | ||
| with hf_access("Owkin-Bioptimus/CytoSyn"): | ||
| self.model = DiffusionPipeline.from_pretrained( | ||
| "Owkin-Bioptimus/CytoSyn", | ||
| custom_pipeline="Owkin-Bioptimus/CytoSyn", | ||
| trust_remote_code=True, | ||
| torch_dtype=torch.float32, | ||
| ) | ||
|
|
||
| def generate(self, *args, **kwargs): | ||
| opts = dict( | ||
| num_images_per_prompt=1, | ||
| num_inference_steps=250, | ||
| guidance_scale=1.0, # No guidance for unconditional | ||
| ) | ||
| opts.update(kwargs) | ||
| return self.model(**opts)["images"] | ||
|
|
||
| def generate_conditionally(self, h0_mini_embeds, **kwargs): | ||
| opts = dict( | ||
| h0_mini_embeds=h0_mini_embeds, | ||
| num_images_per_prompt=1, | ||
| num_inference_steps=250, | ||
| guidance_scale=2.5, | ||
| guidance_low=0.0, | ||
| guidance_high=0.75, | ||
| ) | ||
| opts.update(kwargs) | ||
| return self.model(**opts)["images"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| from contextlib import nullcontext | ||
| from typing import List | ||
|
|
||
| import torch | ||
| from PIL import Image | ||
| from wsidata import WSIData | ||
|
|
||
| from lazyslide import _api | ||
| from lazyslide.models import MODEL_REGISTRY | ||
| from lazyslide.models.base import ImageGenerationModel | ||
|
|
||
|
|
||
| def image_generation( | ||
| wsi: WSIData = None, | ||
| model: str | ImageGenerationModel = "cytosyn", | ||
| prompt_tiles: slice = None, | ||
| tile_key: str = "tiles", | ||
| device: str = None, | ||
| amp: bool = None, | ||
| autocast_dtype: torch.dtype = None, | ||
| num_images_per_tiles: int = 2, | ||
| seed: int = 0, | ||
| **kwargs, | ||
| ) -> List[Image.Image]: | ||
| """ | ||
| Generation of tile images unconditionally or conditionally. | ||
|
|
||
| Currently only supports cytosyn model, conditionally generation relied on H0-mini features. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| wsi : :class:`WSIData <wsidata.WSIData>` | ||
| The WSIData object to work on. | ||
| model : str, default: "cytosyn" | ||
| The image generation model. | ||
| prompt_tiles : slice, default: None | ||
| The tiles to generate images for, please use index to select tiles. | ||
| If None, unconditional generation is performed. | ||
| tile_key : str, default: "tiles" | ||
| Which tile table to use. | ||
| device : str, optional | ||
| The device to use for inference. If not provided, the device will be automatically selected. | ||
| amp : bool, default: False | ||
| Whether to use automatic mixed precision. | ||
| autocast_dtype : torch.dtype, default: torch.float16 | ||
| The dtype for automatic mixed precision. | ||
| num_images_per_tiles : int, default: 2 | ||
| The number of images to generate for each tile if conditional generation is used. | ||
| Otherwise, it's the total number of images to generate if unconditional generation is used. | ||
| seed : int, default: 0 | ||
| The random seed to ensure reproducible image generation (May not work for all models). | ||
| kwargs : dict, optional | ||
| Please refer to the documentation of the specific model for additional parameters. | ||
|
|
||
| Returns | ||
| ------- | ||
| :class:`PIL.Image.Image` | ||
| The function returns a list of generated images in PIL format. | ||
|
|
||
| Examples | ||
| -------- | ||
|
|
||
| >>> import lazyslide as zs | ||
| >>> # Unconditional generation | ||
| >>> imgs = zs.tl.image_generation() | ||
| >>> # Conditional generation | ||
| >>> wsi = zs.datasets.sample() | ||
| >>> zs.tl.feature_extraction(wsi, "h0-mini") | ||
| >>> imgs = zs.tl.image_generation(wsi, prompt_tiles=slice(0, 2)) # Generate images for the first two tiles | ||
|
|
||
| """ | ||
| device = _api.default_value("device", device) | ||
| amp = _api.default_value("amp", amp) | ||
| autocast_dtype = _api.default_value("autocast_dtype", autocast_dtype) | ||
|
|
||
| if isinstance(model, ImageGenerationModel): | ||
| raise NotImplementedError("Currently only supports cytosyn model.") | ||
|
|
||
| generation_model: ImageGenerationModel = MODEL_REGISTRY[model]() | ||
| try: | ||
| generation_model.to(device) | ||
| except: # noqa: E722 | ||
SamirMoustafa marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| pass | ||
| if isinstance(device, torch.device): | ||
| device = device.type | ||
| amp_ctx = torch.autocast(device, autocast_dtype) if amp else nullcontext() | ||
| with amp_ctx, torch.inference_mode(): | ||
| opts = dict( | ||
| num_images_per_prompt=num_images_per_tiles, | ||
| seed=seed, | ||
| ) | ||
| opts.update(kwargs) | ||
| # Unconditional generation | ||
| if prompt_tiles is None: | ||
| return generation_model.generate(**opts) | ||
| # Conditional generation | ||
| else: | ||
| # Check if H0-mini features exist | ||
| try: | ||
| feature_key = wsi._check_feature_key("h0-mini", tile_key) | ||
| except KeyError: | ||
| raise KeyError( | ||
| "H0-mini features are needed for image generation with cytosyn model." | ||
| ) | ||
| cls_tokens = wsi[feature_key][prompt_tiles].X[:, :768] | ||
| cls_tokens = torch.tensor(cls_tokens, dtype=torch.float32) | ||
| return generation_model.generate_conditionally(cls_tokens, **opts) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import pytest | ||
| import torch | ||
| from huggingface_hub.errors import GatedRepoError | ||
|
|
||
| from lazyslide.models import MODEL_REGISTRY, list_models | ||
| from lazyslide.models.base import ImageGenerationModel | ||
|
|
||
| # List of image generation models to test | ||
| IMAGE_GENERATION_MODELS = list_models(task="image_generation") | ||
|
|
||
|
|
||
| @pytest.mark.large_runner | ||
| @pytest.mark.parametrize("model_name", IMAGE_GENERATION_MODELS) | ||
| def test_image_generation_model(model_name): | ||
| # Initialize the model | ||
| try: | ||
| model = MODEL_REGISTRY[model_name]() | ||
| except GatedRepoError: | ||
| pytest.skip(f"{model_name} is not available.") | ||
| return | ||
|
|
||
| # Test 1: Model initialization | ||
| assert isinstance(model, ImageGenerationModel) | ||
|
|
||
| # Test 6: Model prediction | ||
| with torch.inference_mode(): | ||
| _ = model.generate() | ||
SamirMoustafa marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| # Explicitly delete the model to free memory | ||
| del model | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.