Spaces:
Runtime error
Runtime error
Update
Browse files- .pre-commit-config.yaml +59 -36
- .style.yapf +0 -5
- .vscode/settings.json +30 -0
- app.py +38 -53
- model.py +42 -66
.pre-commit-config.yaml
CHANGED
|
@@ -1,37 +1,60 @@
|
|
| 1 |
-
exclude: ^stylegan3
|
| 2 |
repos:
|
| 3 |
-
- repo: https://github.com/pre-commit/pre-commit-hooks
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
- repo: https://github.com/pre-commit/mirrors-mypy
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
repos:
|
| 2 |
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
| 3 |
+
rev: v4.6.0
|
| 4 |
+
hooks:
|
| 5 |
+
- id: check-executables-have-shebangs
|
| 6 |
+
- id: check-json
|
| 7 |
+
- id: check-merge-conflict
|
| 8 |
+
- id: check-shebang-scripts-are-executable
|
| 9 |
+
- id: check-toml
|
| 10 |
+
- id: check-yaml
|
| 11 |
+
- id: end-of-file-fixer
|
| 12 |
+
- id: mixed-line-ending
|
| 13 |
+
args: ["--fix=lf"]
|
| 14 |
+
- id: requirements-txt-fixer
|
| 15 |
+
- id: trailing-whitespace
|
| 16 |
+
- repo: https://github.com/myint/docformatter
|
| 17 |
+
rev: v1.7.5
|
| 18 |
+
hooks:
|
| 19 |
+
- id: docformatter
|
| 20 |
+
args: ["--in-place"]
|
| 21 |
+
- repo: https://github.com/pycqa/isort
|
| 22 |
+
rev: 5.13.2
|
| 23 |
+
hooks:
|
| 24 |
+
- id: isort
|
| 25 |
+
args: ["--profile", "black"]
|
| 26 |
+
- repo: https://github.com/pre-commit/mirrors-mypy
|
| 27 |
+
rev: v1.10.0
|
| 28 |
+
hooks:
|
| 29 |
+
- id: mypy
|
| 30 |
+
args: ["--ignore-missing-imports"]
|
| 31 |
+
additional_dependencies:
|
| 32 |
+
[
|
| 33 |
+
"types-python-slugify",
|
| 34 |
+
"types-requests",
|
| 35 |
+
"types-PyYAML",
|
| 36 |
+
"types-pytz",
|
| 37 |
+
]
|
| 38 |
+
- repo: https://github.com/psf/black
|
| 39 |
+
rev: 24.4.2
|
| 40 |
+
hooks:
|
| 41 |
+
- id: black
|
| 42 |
+
language_version: python3.10
|
| 43 |
+
args: ["--line-length", "119"]
|
| 44 |
+
- repo: https://github.com/kynan/nbstripout
|
| 45 |
+
rev: 0.7.1
|
| 46 |
+
hooks:
|
| 47 |
+
- id: nbstripout
|
| 48 |
+
args:
|
| 49 |
+
[
|
| 50 |
+
"--extra-keys",
|
| 51 |
+
"metadata.interpreter metadata.kernelspec cell.metadata.pycharm",
|
| 52 |
+
]
|
| 53 |
+
- repo: https://github.com/nbQA-dev/nbQA
|
| 54 |
+
rev: 1.8.5
|
| 55 |
+
hooks:
|
| 56 |
+
- id: nbqa-black
|
| 57 |
+
- id: nbqa-pyupgrade
|
| 58 |
+
args: ["--py37-plus"]
|
| 59 |
+
- id: nbqa-isort
|
| 60 |
+
args: ["--float-to-top"]
|
.style.yapf
DELETED
|
@@ -1,5 +0,0 @@
|
|
| 1 |
-
[style]
|
| 2 |
-
based_on_style = pep8
|
| 3 |
-
blank_line_before_nested_class_or_def = false
|
| 4 |
-
spaces_before_comment = 2
|
| 5 |
-
split_before_logical_operator = true
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.vscode/settings.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"editor.formatOnSave": true,
|
| 3 |
+
"files.insertFinalNewline": false,
|
| 4 |
+
"[python]": {
|
| 5 |
+
"editor.defaultFormatter": "ms-python.black-formatter",
|
| 6 |
+
"editor.formatOnType": true,
|
| 7 |
+
"editor.codeActionsOnSave": {
|
| 8 |
+
"source.organizeImports": "explicit"
|
| 9 |
+
}
|
| 10 |
+
},
|
| 11 |
+
"[jupyter]": {
|
| 12 |
+
"files.insertFinalNewline": false
|
| 13 |
+
},
|
| 14 |
+
"black-formatter.args": [
|
| 15 |
+
"--line-length=119"
|
| 16 |
+
],
|
| 17 |
+
"isort.args": ["--profile", "black"],
|
| 18 |
+
"flake8.args": [
|
| 19 |
+
"--max-line-length=119"
|
| 20 |
+
],
|
| 21 |
+
"ruff.lint.args": [
|
| 22 |
+
"--line-length=119"
|
| 23 |
+
],
|
| 24 |
+
"notebook.output.scrolling": true,
|
| 25 |
+
"notebook.formatOnCellExecution": true,
|
| 26 |
+
"notebook.formatOnSave.enabled": true,
|
| 27 |
+
"notebook.codeActionsOnSave": {
|
| 28 |
+
"source.organizeImports": "explicit"
|
| 29 |
+
}
|
| 30 |
+
}
|
app.py
CHANGED
|
@@ -9,101 +9,86 @@ import numpy as np
|
|
| 9 |
|
| 10 |
from model import Model
|
| 11 |
|
| 12 |
-
DESCRIPTION =
|
| 13 |
|
| 14 |
|
| 15 |
def get_sample_image_url(name: str) -> str:
|
| 16 |
-
sample_image_dir =
|
| 17 |
-
return f
|
| 18 |
|
| 19 |
|
| 20 |
def get_sample_image_markdown(name: str) -> str:
|
| 21 |
url = get_sample_image_url(name)
|
| 22 |
-
size = name.split(
|
| 23 |
-
truncation_type =
|
| 24 |
-
return f
|
| 25 |
- size: {size}x{size}
|
| 26 |
- seed: 0-99
|
| 27 |
- truncation: 0.7
|
| 28 |
- truncation type: {truncation_type}
|
| 29 |
-

|
| 30 |
|
| 31 |
|
| 32 |
def get_cluster_center_image_url(model_name: str) -> str:
|
| 33 |
-
cluster_center_image_dir =
|
| 34 |
-
|
|
|
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
def get_cluster_center_image_markdown(model_name: str) -> str:
|
| 38 |
url = get_cluster_center_image_url(model_name)
|
| 39 |
-
return f
|
| 40 |
|
| 41 |
|
| 42 |
model = Model()
|
| 43 |
|
| 44 |
-
with gr.Blocks(css=
|
| 45 |
gr.Markdown(DESCRIPTION)
|
| 46 |
|
| 47 |
with gr.Tabs():
|
| 48 |
-
with gr.TabItem(
|
| 49 |
with gr.Row():
|
| 50 |
with gr.Column():
|
| 51 |
with gr.Group():
|
| 52 |
-
model_name = gr.Dropdown(label=
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
seed = gr.Slider(label='Seed',
|
| 56 |
-
minimum=0,
|
| 57 |
-
maximum=np.iinfo(np.uint32).max,
|
| 58 |
-
step=1,
|
| 59 |
-
value=0)
|
| 60 |
-
psi = gr.Slider(label='Truncation psi',
|
| 61 |
-
minimum=0,
|
| 62 |
-
maximum=2,
|
| 63 |
-
step=0.05,
|
| 64 |
-
value=0.7)
|
| 65 |
truncation_type = gr.Dropdown(
|
| 66 |
-
label=
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
run_button = gr.Button('Run')
|
| 70 |
with gr.Column():
|
| 71 |
-
result = gr.Image(label=
|
| 72 |
|
| 73 |
-
with gr.TabItem(
|
| 74 |
with gr.Row():
|
| 75 |
-
paths = sorted(pathlib.Path(
|
| 76 |
names = [path.stem for path in paths]
|
| 77 |
-
model_name2 = gr.Dropdown(label=
|
| 78 |
-
choices=names,
|
| 79 |
-
value='dogs_1024_multimodal_lpips')
|
| 80 |
with gr.Row():
|
| 81 |
text = get_sample_image_markdown(model_name2.value)
|
| 82 |
sample_images = gr.Markdown(text)
|
| 83 |
|
| 84 |
-
with gr.TabItem(
|
| 85 |
with gr.Row():
|
| 86 |
-
model_name3 = gr.Dropdown(label=
|
| 87 |
-
choices=model.MODEL_NAMES,
|
| 88 |
-
value=model.MODEL_NAMES[0])
|
| 89 |
with gr.Row():
|
| 90 |
text = get_cluster_center_image_markdown(model_name3.value)
|
| 91 |
cluster_center_images = gr.Markdown(value=text)
|
| 92 |
|
| 93 |
model_name.change(fn=model.set_model, inputs=model_name)
|
| 94 |
-
run_button.click(
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
model_name3.change(fn=get_cluster_center_image_markdown,
|
| 106 |
-
inputs=model_name3,
|
| 107 |
-
outputs=cluster_center_images)
|
| 108 |
|
| 109 |
demo.queue(max_size=10).launch()
|
|
|
|
| 9 |
|
| 10 |
from model import Model
|
| 11 |
|
| 12 |
+
DESCRIPTION = "# [Self-Distilled StyleGAN](https://github.com/self-distilled-stylegan/self-distilled-internet-photos)"
|
| 13 |
|
| 14 |
|
| 15 |
def get_sample_image_url(name: str) -> str:
|
| 16 |
+
sample_image_dir = "https://huggingface.co/spaces/hysts/Self-Distilled-StyleGAN/resolve/main/samples"
|
| 17 |
+
return f"{sample_image_dir}/{name}.jpg"
|
| 18 |
|
| 19 |
|
| 20 |
def get_sample_image_markdown(name: str) -> str:
|
| 21 |
url = get_sample_image_url(name)
|
| 22 |
+
size = name.split("_")[1]
|
| 23 |
+
truncation_type = "_".join(name.split("_")[2:])
|
| 24 |
+
return f"""
|
| 25 |
- size: {size}x{size}
|
| 26 |
- seed: 0-99
|
| 27 |
- truncation: 0.7
|
| 28 |
- truncation type: {truncation_type}
|
| 29 |
+
"""
|
| 30 |
|
| 31 |
|
| 32 |
def get_cluster_center_image_url(model_name: str) -> str:
|
| 33 |
+
cluster_center_image_dir = (
|
| 34 |
+
"https://huggingface.co/spaces/hysts/Self-Distilled-StyleGAN/resolve/main/cluster_center_images"
|
| 35 |
+
)
|
| 36 |
+
return f"{cluster_center_image_dir}/{model_name}.jpg"
|
| 37 |
|
| 38 |
|
| 39 |
def get_cluster_center_image_markdown(model_name: str) -> str:
|
| 40 |
url = get_cluster_center_image_url(model_name)
|
| 41 |
+
return f""
|
| 42 |
|
| 43 |
|
| 44 |
model = Model()
|
| 45 |
|
| 46 |
+
with gr.Blocks(css="style.css") as demo:
|
| 47 |
gr.Markdown(DESCRIPTION)
|
| 48 |
|
| 49 |
with gr.Tabs():
|
| 50 |
+
with gr.TabItem("App"):
|
| 51 |
with gr.Row():
|
| 52 |
with gr.Column():
|
| 53 |
with gr.Group():
|
| 54 |
+
model_name = gr.Dropdown(label="Model", choices=model.MODEL_NAMES, value=model.MODEL_NAMES[0])
|
| 55 |
+
seed = gr.Slider(label="Seed", minimum=0, maximum=np.iinfo(np.uint32).max, step=1, value=0)
|
| 56 |
+
psi = gr.Slider(label="Truncation psi", minimum=0, maximum=2, step=0.05, value=0.7)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
truncation_type = gr.Dropdown(
|
| 58 |
+
label="Truncation Type", choices=model.TRUNCATION_TYPES, value=model.TRUNCATION_TYPES[0]
|
| 59 |
+
)
|
| 60 |
+
run_button = gr.Button("Run")
|
|
|
|
| 61 |
with gr.Column():
|
| 62 |
+
result = gr.Image(label="Result", elem_id="result")
|
| 63 |
|
| 64 |
+
with gr.TabItem("Sample Images"):
|
| 65 |
with gr.Row():
|
| 66 |
+
paths = sorted(pathlib.Path("samples").glob("*"))
|
| 67 |
names = [path.stem for path in paths]
|
| 68 |
+
model_name2 = gr.Dropdown(label="Type", choices=names, value="dogs_1024_multimodal_lpips")
|
|
|
|
|
|
|
| 69 |
with gr.Row():
|
| 70 |
text = get_sample_image_markdown(model_name2.value)
|
| 71 |
sample_images = gr.Markdown(text)
|
| 72 |
|
| 73 |
+
with gr.TabItem("Cluster Center Images"):
|
| 74 |
with gr.Row():
|
| 75 |
+
model_name3 = gr.Dropdown(label="Model", choices=model.MODEL_NAMES, value=model.MODEL_NAMES[0])
|
|
|
|
|
|
|
| 76 |
with gr.Row():
|
| 77 |
text = get_cluster_center_image_markdown(model_name3.value)
|
| 78 |
cluster_center_images = gr.Markdown(value=text)
|
| 79 |
|
| 80 |
model_name.change(fn=model.set_model, inputs=model_name)
|
| 81 |
+
run_button.click(
|
| 82 |
+
fn=model.set_model_and_generate_image,
|
| 83 |
+
inputs=[
|
| 84 |
+
model_name,
|
| 85 |
+
seed,
|
| 86 |
+
psi,
|
| 87 |
+
truncation_type,
|
| 88 |
+
],
|
| 89 |
+
outputs=result,
|
| 90 |
+
)
|
| 91 |
+
model_name2.change(fn=get_sample_image_markdown, inputs=model_name2, outputs=sample_images)
|
| 92 |
+
model_name3.change(fn=get_cluster_center_image_markdown, inputs=model_name3, outputs=cluster_center_images)
|
|
|
|
|
|
|
| 93 |
|
| 94 |
demo.queue(max_size=10).launch()
|
model.py
CHANGED
|
@@ -11,7 +11,7 @@ import torch.nn as nn
|
|
| 11 |
from huggingface_hub import hf_hub_download
|
| 12 |
|
| 13 |
current_dir = pathlib.Path(__file__).parent
|
| 14 |
-
submodule_dir = current_dir /
|
| 15 |
sys.path.insert(0, submodule_dir.as_posix())
|
| 16 |
|
| 17 |
|
|
@@ -29,11 +29,10 @@ class LPIPS(lpips.LPIPS):
|
|
| 29 |
return [lpips.normalize_tensor(x) for x in data]
|
| 30 |
|
| 31 |
@torch.inference_mode()
|
| 32 |
-
def compute_distance(self, features0: list[torch.Tensor],
|
| 33 |
-
features1: list[torch.Tensor]) -> float:
|
| 34 |
res = 0
|
| 35 |
for lin, x0, x1 in zip(self.lins, features0, features1):
|
| 36 |
-
d = (x0 - x1)**2
|
| 37 |
y = lin(d)
|
| 38 |
y = lpips.lpips.spatial_average(y)
|
| 39 |
res += y.item()
|
|
@@ -43,23 +42,22 @@ class LPIPS(lpips.LPIPS):
|
|
| 43 |
class Model:
|
| 44 |
|
| 45 |
MODEL_NAMES = [
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
]
|
| 54 |
TRUNCATION_TYPES = [
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
]
|
| 59 |
|
| 60 |
def __init__(self):
|
| 61 |
-
self.device = torch.device(
|
| 62 |
-
'cuda:0' if torch.cuda.is_available() else 'cpu')
|
| 63 |
self._download_all_models()
|
| 64 |
self._download_all_cluster_centers()
|
| 65 |
self._download_all_cluster_center_images()
|
|
@@ -67,32 +65,27 @@ class Model:
|
|
| 67 |
self.model_name = self.MODEL_NAMES[0]
|
| 68 |
self.model = self._load_model(self.model_name)
|
| 69 |
self.cluster_centers = self._load_cluster_centers(self.model_name)
|
| 70 |
-
self.cluster_center_images = self._load_cluster_center_images(
|
| 71 |
-
self.model_name)
|
| 72 |
|
| 73 |
self.lpips = LPIPS()
|
| 74 |
-
self.cluster_center_lpips_feature_dict = self._compute_cluster_center_lpips_features(
|
| 75 |
-
)
|
| 76 |
|
| 77 |
def _load_model(self, model_name: str) -> nn.Module:
|
| 78 |
-
path = hf_hub_download(
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
model = pickle.load(f)['G_ema']
|
| 82 |
model.eval()
|
| 83 |
model.to(self.device)
|
| 84 |
return model
|
| 85 |
|
| 86 |
def _load_cluster_centers(self, model_name: str) -> torch.Tensor:
|
| 87 |
-
path = hf_hub_download(
|
| 88 |
-
f'cluster_centers/{model_name}.npy')
|
| 89 |
centers = np.load(path)
|
| 90 |
centers = torch.from_numpy(centers).float().to(self.device)
|
| 91 |
return centers
|
| 92 |
|
| 93 |
def _load_cluster_center_images(self, model_name: str) -> np.ndarray:
|
| 94 |
-
path = hf_hub_download(
|
| 95 |
-
f'cluster_center_images/{model_name}.npy')
|
| 96 |
return np.load(path)
|
| 97 |
|
| 98 |
def set_model(self, model_name: str) -> None:
|
|
@@ -101,8 +94,7 @@ class Model:
|
|
| 101 |
self.model_name = model_name
|
| 102 |
self.model = self._load_model(model_name)
|
| 103 |
self.cluster_centers = self._load_cluster_centers(model_name)
|
| 104 |
-
self.cluster_center_images = self._load_cluster_center_images(
|
| 105 |
-
model_name)
|
| 106 |
|
| 107 |
def _download_all_models(self):
|
| 108 |
for name in self.MODEL_NAMES:
|
|
@@ -118,9 +110,7 @@ class Model:
|
|
| 118 |
|
| 119 |
def generate_z(self, seed: int) -> torch.Tensor:
|
| 120 |
seed = int(np.clip(seed, 0, np.iinfo(np.uint32).max))
|
| 121 |
-
return torch.from_numpy(
|
| 122 |
-
np.random.RandomState(seed).randn(1, self.model.z_dim)).float().to(
|
| 123 |
-
self.device)
|
| 124 |
|
| 125 |
def compute_w(self, z: torch.Tensor) -> torch.Tensor:
|
| 126 |
label = torch.zeros((1, self.model.c_dim), device=self.device)
|
|
@@ -128,8 +118,7 @@ class Model:
|
|
| 128 |
return w
|
| 129 |
|
| 130 |
@staticmethod
|
| 131 |
-
def truncate_w(w_center: torch.Tensor, w: torch.Tensor,
|
| 132 |
-
psi: float) -> torch.Tensor:
|
| 133 |
if psi == 1:
|
| 134 |
return w
|
| 135 |
return w_center.lerp(w, psi)
|
|
@@ -139,67 +128,54 @@ class Model:
|
|
| 139 |
return self.model.synthesis(w)
|
| 140 |
|
| 141 |
def postprocess(self, tensor: torch.Tensor) -> np.ndarray:
|
| 142 |
-
tensor = (tensor.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(
|
| 143 |
-
torch.uint8)
|
| 144 |
return tensor.cpu().numpy()
|
| 145 |
|
| 146 |
def compute_lpips_features(self, image: np.ndarray) -> list[torch.Tensor]:
|
| 147 |
data = self.lpips.preprocess(image)
|
| 148 |
return self.lpips.compute_features(data)
|
| 149 |
|
| 150 |
-
def _compute_cluster_center_lpips_features(
|
| 151 |
-
self) -> dict[str, list[list[torch.Tensor]]]:
|
| 152 |
res = dict()
|
| 153 |
for name in self.MODEL_NAMES:
|
| 154 |
images = self._load_cluster_center_images(name)
|
| 155 |
-
res[name] = [
|
| 156 |
-
self.compute_lpips_features(image) for image in images
|
| 157 |
-
]
|
| 158 |
return res
|
| 159 |
|
| 160 |
-
def compute_distance_to_cluster_centers(
|
| 161 |
-
|
| 162 |
-
if distance_type == 'l2':
|
| 163 |
return self._compute_l2_distance_to_cluster_centers(ws)
|
| 164 |
-
elif distance_type ==
|
| 165 |
return self._compute_lpips_distance_to_cluster_centers(ws)
|
| 166 |
else:
|
| 167 |
raise ValueError
|
| 168 |
|
| 169 |
-
def _compute_l2_distance_to_cluster_centers(
|
| 170 |
-
|
| 171 |
-
dist2 = ((self.cluster_centers - ws[0, 0])**2).sum(dim=1)
|
| 172 |
return dist2.cpu().numpy()
|
| 173 |
|
| 174 |
-
def _compute_lpips_distance_to_cluster_centers(
|
| 175 |
-
self, ws: torch.Tensor) -> np.ndarray:
|
| 176 |
x = self.synthesize(ws)
|
| 177 |
x = self.postprocess(x)[0]
|
| 178 |
feat0 = self.compute_lpips_features(x)
|
| 179 |
-
cluster_center_features = self.cluster_center_lpips_feature_dict[
|
| 180 |
-
|
| 181 |
-
distances = [
|
| 182 |
-
self.lpips.compute_distance(feat0, feat1)
|
| 183 |
-
for feat1 in cluster_center_features
|
| 184 |
-
]
|
| 185 |
return np.asarray(distances)
|
| 186 |
|
| 187 |
-
def find_nearest_cluster_center(self, ws: torch.Tensor,
|
| 188 |
-
distance_type: str) -> int:
|
| 189 |
distances = self.compute_distance_to_cluster_centers(ws, distance_type)
|
| 190 |
return int(np.argmin(distances))
|
| 191 |
|
| 192 |
-
def generate_image(self, seed: int, truncation_psi: float,
|
| 193 |
-
truncation_type: str) -> np.ndarray:
|
| 194 |
z = self.generate_z(seed)
|
| 195 |
ws = self.compute_w(z)
|
| 196 |
if truncation_type == self.TRUNCATION_TYPES[2]:
|
| 197 |
w0 = self.model.mapping.w_avg
|
| 198 |
else:
|
| 199 |
if truncation_type == self.TRUNCATION_TYPES[0]:
|
| 200 |
-
distance_type =
|
| 201 |
elif truncation_type == self.TRUNCATION_TYPES[1]:
|
| 202 |
-
distance_type =
|
| 203 |
else:
|
| 204 |
raise ValueError
|
| 205 |
cluster_index = self.find_nearest_cluster_center(ws, distance_type)
|
|
@@ -209,8 +185,8 @@ class Model:
|
|
| 209 |
out = self.postprocess(out)
|
| 210 |
return out[0]
|
| 211 |
|
| 212 |
-
def set_model_and_generate_image(
|
| 213 |
-
|
| 214 |
-
|
| 215 |
self.set_model(model_name)
|
| 216 |
return self.generate_image(seed, truncation_psi, truncation_type)
|
|
|
|
| 11 |
from huggingface_hub import hf_hub_download
|
| 12 |
|
| 13 |
current_dir = pathlib.Path(__file__).parent
|
| 14 |
+
submodule_dir = current_dir / "stylegan3"
|
| 15 |
sys.path.insert(0, submodule_dir.as_posix())
|
| 16 |
|
| 17 |
|
|
|
|
| 29 |
return [lpips.normalize_tensor(x) for x in data]
|
| 30 |
|
| 31 |
@torch.inference_mode()
|
| 32 |
+
def compute_distance(self, features0: list[torch.Tensor], features1: list[torch.Tensor]) -> float:
|
|
|
|
| 33 |
res = 0
|
| 34 |
for lin, x0, x1 in zip(self.lins, features0, features1):
|
| 35 |
+
d = (x0 - x1) ** 2
|
| 36 |
y = lin(d)
|
| 37 |
y = lpips.lpips.spatial_average(y)
|
| 38 |
res += y.item()
|
|
|
|
| 42 |
class Model:
|
| 43 |
|
| 44 |
MODEL_NAMES = [
|
| 45 |
+
"dogs_1024",
|
| 46 |
+
"elephants_512",
|
| 47 |
+
"horses_256",
|
| 48 |
+
"bicycles_256",
|
| 49 |
+
"lions_512",
|
| 50 |
+
"giraffes_512",
|
| 51 |
+
"parrots_512",
|
| 52 |
]
|
| 53 |
TRUNCATION_TYPES = [
|
| 54 |
+
"Multimodal (LPIPS)",
|
| 55 |
+
"Multimodal (L2)",
|
| 56 |
+
"Global",
|
| 57 |
]
|
| 58 |
|
| 59 |
def __init__(self):
|
| 60 |
+
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
|
|
|
| 61 |
self._download_all_models()
|
| 62 |
self._download_all_cluster_centers()
|
| 63 |
self._download_all_cluster_center_images()
|
|
|
|
| 65 |
self.model_name = self.MODEL_NAMES[0]
|
| 66 |
self.model = self._load_model(self.model_name)
|
| 67 |
self.cluster_centers = self._load_cluster_centers(self.model_name)
|
| 68 |
+
self.cluster_center_images = self._load_cluster_center_images(self.model_name)
|
|
|
|
| 69 |
|
| 70 |
self.lpips = LPIPS()
|
| 71 |
+
self.cluster_center_lpips_feature_dict = self._compute_cluster_center_lpips_features()
|
|
|
|
| 72 |
|
| 73 |
def _load_model(self, model_name: str) -> nn.Module:
|
| 74 |
+
path = hf_hub_download("public-data/Self-Distilled-StyleGAN", f"models/{model_name}_pytorch.pkl")
|
| 75 |
+
with open(path, "rb") as f:
|
| 76 |
+
model = pickle.load(f)["G_ema"]
|
|
|
|
| 77 |
model.eval()
|
| 78 |
model.to(self.device)
|
| 79 |
return model
|
| 80 |
|
| 81 |
def _load_cluster_centers(self, model_name: str) -> torch.Tensor:
|
| 82 |
+
path = hf_hub_download("public-data/Self-Distilled-StyleGAN", f"cluster_centers/{model_name}.npy")
|
|
|
|
| 83 |
centers = np.load(path)
|
| 84 |
centers = torch.from_numpy(centers).float().to(self.device)
|
| 85 |
return centers
|
| 86 |
|
| 87 |
def _load_cluster_center_images(self, model_name: str) -> np.ndarray:
|
| 88 |
+
path = hf_hub_download("public-data/Self-Distilled-StyleGAN", f"cluster_center_images/{model_name}.npy")
|
|
|
|
| 89 |
return np.load(path)
|
| 90 |
|
| 91 |
def set_model(self, model_name: str) -> None:
|
|
|
|
| 94 |
self.model_name = model_name
|
| 95 |
self.model = self._load_model(model_name)
|
| 96 |
self.cluster_centers = self._load_cluster_centers(model_name)
|
| 97 |
+
self.cluster_center_images = self._load_cluster_center_images(model_name)
|
|
|
|
| 98 |
|
| 99 |
def _download_all_models(self):
|
| 100 |
for name in self.MODEL_NAMES:
|
|
|
|
| 110 |
|
| 111 |
def generate_z(self, seed: int) -> torch.Tensor:
|
| 112 |
seed = int(np.clip(seed, 0, np.iinfo(np.uint32).max))
|
| 113 |
+
return torch.from_numpy(np.random.RandomState(seed).randn(1, self.model.z_dim)).float().to(self.device)
|
|
|
|
|
|
|
| 114 |
|
| 115 |
def compute_w(self, z: torch.Tensor) -> torch.Tensor:
|
| 116 |
label = torch.zeros((1, self.model.c_dim), device=self.device)
|
|
|
|
| 118 |
return w
|
| 119 |
|
| 120 |
@staticmethod
|
| 121 |
+
def truncate_w(w_center: torch.Tensor, w: torch.Tensor, psi: float) -> torch.Tensor:
|
|
|
|
| 122 |
if psi == 1:
|
| 123 |
return w
|
| 124 |
return w_center.lerp(w, psi)
|
|
|
|
| 128 |
return self.model.synthesis(w)
|
| 129 |
|
| 130 |
def postprocess(self, tensor: torch.Tensor) -> np.ndarray:
|
| 131 |
+
tensor = (tensor.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8)
|
|
|
|
| 132 |
return tensor.cpu().numpy()
|
| 133 |
|
| 134 |
def compute_lpips_features(self, image: np.ndarray) -> list[torch.Tensor]:
|
| 135 |
data = self.lpips.preprocess(image)
|
| 136 |
return self.lpips.compute_features(data)
|
| 137 |
|
| 138 |
+
def _compute_cluster_center_lpips_features(self) -> dict[str, list[list[torch.Tensor]]]:
|
|
|
|
| 139 |
res = dict()
|
| 140 |
for name in self.MODEL_NAMES:
|
| 141 |
images = self._load_cluster_center_images(name)
|
| 142 |
+
res[name] = [self.compute_lpips_features(image) for image in images]
|
|
|
|
|
|
|
| 143 |
return res
|
| 144 |
|
| 145 |
+
def compute_distance_to_cluster_centers(self, ws: torch.Tensor, distance_type: str) -> list[torch.Tensor]:
|
| 146 |
+
if distance_type == "l2":
|
|
|
|
| 147 |
return self._compute_l2_distance_to_cluster_centers(ws)
|
| 148 |
+
elif distance_type == "lpips":
|
| 149 |
return self._compute_lpips_distance_to_cluster_centers(ws)
|
| 150 |
else:
|
| 151 |
raise ValueError
|
| 152 |
|
| 153 |
+
def _compute_l2_distance_to_cluster_centers(self, ws: torch.Tensor) -> np.ndarray:
|
| 154 |
+
dist2 = ((self.cluster_centers - ws[0, 0]) ** 2).sum(dim=1)
|
|
|
|
| 155 |
return dist2.cpu().numpy()
|
| 156 |
|
| 157 |
+
def _compute_lpips_distance_to_cluster_centers(self, ws: torch.Tensor) -> np.ndarray:
|
|
|
|
| 158 |
x = self.synthesize(ws)
|
| 159 |
x = self.postprocess(x)[0]
|
| 160 |
feat0 = self.compute_lpips_features(x)
|
| 161 |
+
cluster_center_features = self.cluster_center_lpips_feature_dict[self.model_name]
|
| 162 |
+
distances = [self.lpips.compute_distance(feat0, feat1) for feat1 in cluster_center_features]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
return np.asarray(distances)
|
| 164 |
|
| 165 |
+
def find_nearest_cluster_center(self, ws: torch.Tensor, distance_type: str) -> int:
|
|
|
|
| 166 |
distances = self.compute_distance_to_cluster_centers(ws, distance_type)
|
| 167 |
return int(np.argmin(distances))
|
| 168 |
|
| 169 |
+
def generate_image(self, seed: int, truncation_psi: float, truncation_type: str) -> np.ndarray:
|
|
|
|
| 170 |
z = self.generate_z(seed)
|
| 171 |
ws = self.compute_w(z)
|
| 172 |
if truncation_type == self.TRUNCATION_TYPES[2]:
|
| 173 |
w0 = self.model.mapping.w_avg
|
| 174 |
else:
|
| 175 |
if truncation_type == self.TRUNCATION_TYPES[0]:
|
| 176 |
+
distance_type = "lpips"
|
| 177 |
elif truncation_type == self.TRUNCATION_TYPES[1]:
|
| 178 |
+
distance_type = "l2"
|
| 179 |
else:
|
| 180 |
raise ValueError
|
| 181 |
cluster_index = self.find_nearest_cluster_center(ws, distance_type)
|
|
|
|
| 185 |
out = self.postprocess(out)
|
| 186 |
return out[0]
|
| 187 |
|
| 188 |
+
def set_model_and_generate_image(
|
| 189 |
+
self, model_name: str, seed: int, truncation_psi: float, truncation_type: str
|
| 190 |
+
) -> np.ndarray:
|
| 191 |
self.set_model(model_name)
|
| 192 |
return self.generate_image(seed, truncation_psi, truncation_type)
|