Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Hf token fix (#3393)

Meggison Oritsemisandba027e1da66
diff --git a/.github/actions/tests/action.yml b/.github/actions/tests/action.yml
index 9d86ea18b..505e8933d 100644
--- a/.github/actions/tests/action.yml
+++ b/.github/actions/tests/action.yml
@@ -29,6 +29,10 @@ inputs:
ref:
description: "Git reference to checkout"
default: ${{ github.sha }}
+ huggingface-token:
+ description: "HuggingFace Hub API token for model downloads"
+ required: false
+ default: ""
runs:
@@ -43,5 +47,7 @@ runs:
- name: Run CPU tests ${{ inputs.pytorch-dtype }}
shell: bash -l {0}
+ env:
+ HF_TOKEN: ${{ inputs.huggingface-token }}
run: |
pytest -v ./tests/ --device=${{ inputs.pytorch-device }} --dtype=${{ inputs.pytorch-dtype }} ${{ inputs.pytest-extra }}
diff --git a/.github/download-models-weights.py b/.github/download-models-weights.py
index 6b3a9d699..145fa9eeb 100644
--- a/.github/download-models-weights.py
+++ b/.github/download-models-weights.py
@@ -23,7 +23,7 @@ import torch
models = {
"sold2_wireframe": ("torchhub", "http://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth"),
- "stabilityai/stable-diffusion-2-1": ("diffusers", "StableDiffusionPipeline"),
+ "runwayml/stable-diffusion-v1-5": ("diffusers", "StableDiffusionPipeline"),
}
diff --git a/.github/workflows/self-tests.yml b/.github/workflows/self-tests.yml
index bec306a4d..0bc6989cc 100644
--- a/.github/workflows/self-tests.yml
+++ b/.github/workflows/self-tests.yml
@@ -37,6 +37,8 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
- uses: ./.github/actions/tests/
+ with:
+ huggingface-token: ${{ secrets.HUGGING_FACE_HUB_TOKEN }}
workflow-tests:
uses: ./.github/workflows/tests.yml
diff --git a/kornia/augmentation/_2d/intensity/dissolving.py b/kornia/augmentation/_2d/intensity/dissolving.py
index 4448fbafd..74f751c51 100644
--- a/kornia/augmentation/_2d/intensity/dissolving.py
+++ b/kornia/augmentation/_2d/intensity/dissolving.py
@@ -36,7 +36,7 @@ class RandomDissolving(IntensityAugmentationBase2D):
* - SD 1.4
- SD 1.5
- - SD 2.1
+ - SD xl
* - figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-1.4.png
- figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-1.5.png
- figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-2.1.png
@@ -59,7 +59,7 @@ class RandomDissolving(IntensityAugmentationBase2D):
def __init__(
self,
step_range: Tuple[float, float] = (100, 500),
- version: str = "2.1",
+ version: str = "1.5",
p: float = 0.5,
keepdim: bool = False,
**kwargs: Any,
diff --git a/kornia/filters/dissolving.py b/kornia/filters/dissolving.py
index 5ccf31f7f..91d95bf8e 100644
--- a/kornia/filters/dissolving.py
+++ b/kornia/filters/dissolving.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import os
from typing import Any
import torch
@@ -24,14 +25,17 @@ from kornia.core.external import diffusers
class _DissolvingWraper_HF:
- def __init__(self, model: Module, num_ddim_steps: int = 50) -> None:
+ def __init__(self, model: Module, num_ddim_steps: int = 50, is_sdxl: bool = False) -> None:
self.model = model
self.num_ddim_steps = num_ddim_steps
+ self.is_sdxl = is_sdxl
self.tokenizer = self.model.tokenizer
self.model.scheduler.set_timesteps(self.num_ddim_steps)
self.total_steps = len(self.model.scheduler.timesteps) # Total number of sampling steps.
self.prompt: str
self.context: Tensor
+ self.pooled_embeddings: Tensor | None = None
+ self.add_time_ids: Tensor | None = None
def predict_start_from_noise(self, noise_pred: Tensor, timestep: int, latent: Tensor) -> Tensor:
return (
@@ -41,19 +45,94 @@ class _DissolvingWraper_HF:
@torch.no_grad()
def init_prompt(self, prompt: str) -> None:
- uncond_input = self.model.tokenizer(
- [""], padding="max_length", max_length=self.model.tokenizer.model_max_length, return_tensors="pt"
- )
- uncond_embeddings = self.model.text_encoder(uncond_input.input_ids.to(self.model.device))[0]
- text_input = self.model.tokenizer(
- [prompt],
- padding="max_length",
- max_length=self.model.tokenizer.model_max_length,
- truncation=True,
- return_tensors="pt",
- )
- text_embeddings = self.model.text_encoder(text_input.input_ids.to(self.model.device))[0]
- self.context = torch.cat([uncond_embeddings, text_embeddings])
+ if self.is_sdxl:
+ # Handle models with dual text encoders
+ tokenizers = (
+ [self.model.tokenizer, self.model.tokenizer_2]
+ if hasattr(self.model, "tokenizer_2")
+ else [self.model.tokenizer]
+ )
+ text_encoders = (
+ [self.model.text_encoder, self.model.text_encoder_2]
+ if hasattr(self.model, "text_encoder_2")
+ else [self.model.text_encoder]
+ )
+
+ prompt_embeds_list = []
+ pooled_prompt_embeds = None
+
+ for i, (tokenizer, text_encoder) in enumerate(zip(tokenizers, text_encoders)):
+ text_inputs = tokenizer(
+ [prompt],
+ padding="max_length",
+ max_length=tokenizer.model_max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+ text_input_ids = text_inputs.input_ids.to(self.model.device)
+
+ outputs = text_encoder(text_input_ids, output_hidden_states=True)
+ # Extract pooled embeddings from the last text encoder
+ if i == len(tokenizers) - 1:
+ # Get pooled output from text encoder
+ pooled_prompt_embeds = (
+ outputs.pooler_output if hasattr(outputs, "pooler_output") else outputs.text_embeds
+ )
+ # Get the penultimate hidden state
+ prompt_embeds = outputs.hidden_states[-2]
+ prompt_embeds_list.append(prompt_embeds)
+
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
+
+ # Get negative (unconditional) embeddings
+ negative_prompt_embeds_list = []
+ negative_pooled_prompt_embeds = None
+
+ for i, (tokenizer, text_encoder) in enumerate(zip(tokenizers, text_encoders)):
+ uncond_inputs = tokenizer(
+ [""],
+ padding="max_length",
+ max_length=tokenizer.model_max_length,
+ return_tensors="pt",
+ )
+ uncond_input_ids = uncond_inputs.input_ids.to(self.model.device)
+
+ outputs = text_encoder(uncond_input_ids, output_hidden_states=True)
+ # Extract pooled embeddings from the last text encoder
+ if i == len(tokenizers) - 1:
+ negative_pooled_prompt_embeds = (
+ outputs.pooler_output if hasattr(outputs, "pooler_output") else outputs.text_embeds
+ )
+ negative_prompt_embeds = outputs.hidden_states[-2]
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
+
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
+
+ self.context = torch.cat([negative_prompt_embeds, prompt_embeds])
+ # Type narrowing: these are guaranteed to be set in the loops above when is_sdxl=True
+ if pooled_prompt_embeds is not None and negative_pooled_prompt_embeds is not None:
+ self.pooled_embeddings = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds])
+
+ # Create time_ids for models that require additional conditioning
+ # Format: (original_size, crops_coords_top_left, target_size)
+ add_time_ids = torch.tensor([[1024, 1024, 0, 0, 1024, 1024]], device=self.model.device)
+ self.add_time_ids = torch.cat([add_time_ids, add_time_ids])
+ else:
+ # SD 1.x
+ uncond_input = self.model.tokenizer(
+ [""], padding="max_length", max_length=self.model.tokenizer.model_max_length, return_tensors="pt"
+ )
+ uncond_embeddings = self.model.text_encoder(uncond_input.input_ids.to(self.model.device))[0]
+ text_input = self.model.tokenizer(
+ [prompt],
+ padding="max_length",
+ max_length=self.model.tokenizer.model_max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+ text_embeddings = self.model.text_encoder(text_input.input_ids.to(self.model.device))[0]
+ self.context = torch.cat([uncond_embeddings, text_embeddings])
+
self.prompt = prompt
# Encode the image to latent using the VAE.
@@ -87,7 +166,29 @@ class _DissolvingWraper_HF:
t = self.num_ddim_steps - self.model.scheduler.timesteps[i]
latent = self.model.scheduler.scale_model_input(latent, t)
cond_embeddings = cond_embeddings.repeat(latent.size(0), 1, 1)
- noise_pred = self.model.unet(latent, t, cond_embeddings).sample
+
+ if self.is_sdxl:
+ # Pass additional conditioning to models that require it
+ # Type narrowing: these are guaranteed to be set when is_sdxl=True
+ if self.pooled_embeddings is not None and self.add_time_ids is not None:
+ _, pooled_embeds = self.pooled_embeddings.chunk(2)
+ _, add_time_ids = self.add_time_ids.chunk(2)
+
+ # Expand embeddings to match batch size if needed
+ batch_size = latent.size(0)
+ if pooled_embeds.size(0) != batch_size:
+ pooled_embeds = pooled_embeds.expand(batch_size, -1)
+ if add_time_ids.size(0) != batch_size:
+ add_time_ids = add_time_ids.expand(batch_size, -1)
+
+ added_cond_kwargs = {
+ "text_embeds": pooled_embeds,
+ "time_ids": add_time_ids,
+ }
+ noise_pred = self.model.unet(latent, t, cond_embeddings, added_cond_kwargs=added_cond_kwargs).sample
+ else:
+ noise_pred = self.model.unet(latent, t, cond_embeddings).sample
+
pred_x0 = self.predict_start_from_noise(noise_pred, t, latent)
return pred_x0
@@ -105,7 +206,7 @@ class StableDiffusionDissolving(ImageModule):
Based on :cite:`shi2024dissolving`, the dissolving transformation is essentially applying one-step
reverse diffusion. Our implementation currently supports HuggingFace implementations of SD 1.4, 1.5
- and 2.1. SD 1.X tends to remove more details than SD2.1.
+ and SD XL (replacing the discontinued SD 2.1). SD 1.X tends to remove more details than SD-XL.
.. list-table:: Title
:widths: 32 32 32
@@ -113,20 +214,19 @@ class StableDiffusionDissolving(ImageModule):
* - SD 1.4
- SD 1.5
- - SD 2.1
+ - SD XL
* - figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-1.4.png
- figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-1.5.png
- figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-2.1.png
Args:
- version: the version of the stable diffusion model.
+ version: the version of the stable diffusion model. Options: "1.4", "1.5", "xl".
**kwargs: additional arguments for `.from_pretrained`.
"""
- def __init__(self, version: str = "2.1", **kwargs: Any):
+ def __init__(self, version: str = "1.5", **kwargs: Any):
super().__init__()
- StableDiffusionPipeline = diffusers.StableDiffusionPipeline
DDIMScheduler = diffusers.DDIMScheduler
# Load the scheduler and model pipeline from diffusers library
@@ -142,22 +242,34 @@ class StableDiffusionDissolving(ImageModule):
# Filter out arguments that are not supported by all component models
kwargs.pop("offload_state_dict", None)
+ # Get HF token from environment if not explicitly provided
+ if "token" not in kwargs:
+ hf_token = os.environ.get("HF_TOKEN")
+ if hf_token:
+ kwargs["token"] = hf_token
+
+ is_sdxl = False
+
if version == "1.4":
+ StableDiffusionPipeline = diffusers.StableDiffusionPipeline
self._sdm_model = StableDiffusionPipeline.from_pretrained( # type:ignore
"CompVis/stable-diffusion-v1-4", scheduler=scheduler, **kwargs
)
elif version == "1.5":
+ StableDiffusionPipeline = diffusers.StableDiffusionPipeline
self._sdm_model = StableDiffusionPipeline.from_pretrained( # type:ignore
"runwayml/stable-diffusion-v1-5", scheduler=scheduler, **kwargs
)
- elif version == "2.1":
- self._sdm_model = StableDiffusionPipeline.from_pretrained( # type:ignore
- "stabilityai/stable-diffusion-2-1", scheduler=scheduler, **kwargs
+ elif version == "xl":
+ StableDiffusionXLPipeline = diffusers.StableDiffusionXLPipeline
+ self._sdm_model = StableDiffusionXLPipeline.from_pretrained( # type:ignore
+ "stabilityai/stable-diffusion-xl-base-1.0", scheduler=scheduler, **kwargs
)
+ is_sdxl = True
else:
raise NotImplementedError
- self.model = _DissolvingWraper_HF(self._sdm_model, num_ddim_steps=1000)
+ self.model = _DissolvingWraper_HF(self._sdm_model, num_ddim_steps=1000, is_sdxl=is_sdxl)
def forward(self, input: Tensor, step_number: int) -> Tensor:
return self.model.dissolve(input, step_number)
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index d95e29bce..5a4c5a950 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -5248,12 +5248,12 @@ class TestRandomDissolving(BaseTester):
def test_batch_proc(self, device, dtype):
images = torch.rand(4, 3, 16, 16)
- aug = RandomDissolving(p=1.0, version="2.1", cache_dir="weights/")
+ aug = RandomDissolving(p=1.0, version="1.5", cache_dir="weights/")
images_aug = aug(images)
assert images_aug.shape == images.shape
def test_single_proc(self, device, dtype):
images = torch.rand(3, 16, 16)
- aug = RandomDissolving(p=1.0, keepdim=True, version="2.1", cache_dir="weights/")
+ aug = RandomDissolving(p=1.0, keepdim=True, version="1.5", cache_dir="weights/")
images_aug = aug(images)
assert images_aug.shape == images.shape
diff --git a/tests/filters/test_dissolving.py b/tests/filters/test_dissolving.py
index b9afe55e5..03cc470c5 100644
--- a/tests/filters/test_dissolving.py
+++ b/tests/filters/test_dissolving.py
@@ -33,7 +33,7 @@ WEIGHTS_CACHE_DIR = "weights/"
class TestStableDiffusionDissolving:
@pytest.fixture(scope="class")
def sdm_2_1(self):
- return StableDiffusionDissolving(version="2.1", cache_dir=WEIGHTS_CACHE_DIR)
+ return StableDiffusionDissolving(version="1.5", cache_dir=WEIGHTS_CACHE_DIR)
@pytest.fixture(scope="class")
def dummy_image(self):