Split tile-graph off shared prep spine
This commit is contained in:
parent
cd09307367
commit
b3a2d72cc1
14 changed files with 389 additions and 301 deletions
|
|
@ -3,7 +3,7 @@ from __future__ import annotations
|
|||
import numpy as np
|
||||
|
||||
from .metrics import luminance
|
||||
from .types import SourceAnalysis
|
||||
from .types import ContinuousSourceAnalysis, TileGraphSourceAnalysis
|
||||
|
||||
|
||||
def _require_torch():
|
||||
|
|
@ -104,23 +104,12 @@ def _kmeans_torch(torch, data_t, k: int, seed: int, iterations: int = 12):
|
|||
return centers_t, labels_t
|
||||
|
||||
|
||||
def _colorize_clusters(cluster_map: np.ndarray, centers: np.ndarray) -> np.ndarray:
|
||||
if centers.size == 0:
|
||||
return np.zeros((*cluster_map.shape, 4), dtype=np.float32)
|
||||
palette = np.clip(centers[:, :3], 0.0, 1.0)
|
||||
preview = palette[np.clip(cluster_map, 0, len(palette) - 1)]
|
||||
alpha = np.ones((*cluster_map.shape, 1), dtype=np.float32)
|
||||
return np.concatenate([preview, alpha], axis=-1)
|
||||
|
||||
|
||||
def analyze_source(
|
||||
def analyze_continuous_source(
|
||||
rgba: np.ndarray,
|
||||
seed: int,
|
||||
cluster_count: int = 6,
|
||||
device: str | None = None,
|
||||
*,
|
||||
include_clusters: bool = True,
|
||||
) -> SourceAnalysis:
|
||||
) -> ContinuousSourceAnalysis:
|
||||
if device is not None:
|
||||
torch = _require_torch()
|
||||
resolved_device = _resolve_device(torch, device)
|
||||
|
|
@ -128,45 +117,46 @@ def analyze_source(
|
|||
edge_map_t = _compute_edge_map_torch(torch, rgba_t)
|
||||
alpha_t = rgba_t[..., 3]
|
||||
cluster_map_t = torch.full(alpha_t.shape, -1, device=resolved_device, dtype=torch.long)
|
||||
centers_t = torch.zeros((0, 4), device=resolved_device, dtype=torch.float32)
|
||||
preview_t = torch.zeros((*alpha_t.shape, 4), device=resolved_device, dtype=torch.float32)
|
||||
if include_clusters:
|
||||
opaque_t = alpha_t > 0.05
|
||||
if bool(torch.any(opaque_t).item()):
|
||||
samples_t = rgba_t[opaque_t]
|
||||
k = min(cluster_count, max(2, int(np.sqrt(int(samples_t.shape[0]) // 64 + 1))))
|
||||
centers_t, labels_t = _kmeans_torch(torch, samples_t, k=k, seed=seed)
|
||||
cluster_map_t[opaque_t] = labels_t
|
||||
preview_palette_t = centers_t[:, :3].clamp(0.0, 1.0) if centers_t.numel() else torch.zeros((1, 3), device=resolved_device, dtype=torch.float32)
|
||||
preview_indices_t = torch.clamp(cluster_map_t, 0, max(0, preview_palette_t.shape[0] - 1))
|
||||
preview_t = preview_palette_t[preview_indices_t]
|
||||
preview_t = torch.cat([preview_t, alpha_t[..., None]], dim=-1)
|
||||
return SourceAnalysis(
|
||||
opaque_t = alpha_t > 0.05
|
||||
if bool(torch.any(opaque_t).item()):
|
||||
samples_t = rgba_t[opaque_t]
|
||||
k = min(cluster_count, max(2, int(np.sqrt(int(samples_t.shape[0]) // 64 + 1))))
|
||||
_centers_t, labels_t = _kmeans_torch(torch, samples_t, k=k, seed=seed)
|
||||
cluster_map_t[opaque_t] = labels_t
|
||||
return ContinuousSourceAnalysis(
|
||||
edge_map=edge_map_t.detach().cpu().numpy().astype(np.float32),
|
||||
cluster_map=cluster_map_t.detach().cpu().numpy().astype(np.int32),
|
||||
cluster_centers=centers_t.detach().cpu().numpy().astype(np.float32),
|
||||
alpha_map=alpha_t.detach().cpu().numpy().astype(np.float32),
|
||||
cluster_preview=preview_t.detach().cpu().numpy().astype(np.float32),
|
||||
)
|
||||
|
||||
edge_map = _compute_edge_map(rgba)
|
||||
alpha = rgba[..., 3]
|
||||
cluster_map = np.full(alpha.shape, -1, dtype=np.int32)
|
||||
centers = np.zeros((0, 4), dtype=np.float32)
|
||||
preview = np.zeros((*alpha.shape, 4), dtype=np.float32)
|
||||
if include_clusters:
|
||||
opaque = alpha > 0.05
|
||||
if np.any(opaque):
|
||||
samples = rgba[opaque]
|
||||
k = min(cluster_count, max(2, int(np.sqrt(samples.shape[0] // 64 + 1))))
|
||||
centers, labels = _kmeans(samples, k=k, seed=seed)
|
||||
cluster_map[opaque] = labels
|
||||
preview = _colorize_clusters(np.maximum(cluster_map, 0), centers if centers.size else np.zeros((1, 4), dtype=np.float32))
|
||||
preview[..., 3] = alpha
|
||||
return SourceAnalysis(
|
||||
opaque = alpha > 0.05
|
||||
if np.any(opaque):
|
||||
samples = rgba[opaque]
|
||||
k = min(cluster_count, max(2, int(np.sqrt(samples.shape[0] // 64 + 1))))
|
||||
_centers, labels = _kmeans(samples, k=k, seed=seed)
|
||||
cluster_map[opaque] = labels
|
||||
return ContinuousSourceAnalysis(
|
||||
edge_map=edge_map,
|
||||
cluster_map=cluster_map,
|
||||
cluster_centers=centers,
|
||||
alpha_map=alpha.astype(np.float32),
|
||||
cluster_preview=preview,
|
||||
)
|
||||
|
||||
|
||||
def analyze_tile_graph_source(
|
||||
rgba: np.ndarray,
|
||||
*,
|
||||
device: str | None = None,
|
||||
) -> TileGraphSourceAnalysis:
|
||||
if device is not None:
|
||||
torch = _require_torch()
|
||||
resolved_device = _resolve_device(torch, device)
|
||||
rgba_t = torch.from_numpy(rgba).to(device=resolved_device, dtype=torch.float32)
|
||||
edge_map_t = _compute_edge_map_torch(torch, rgba_t)
|
||||
return TileGraphSourceAnalysis(
|
||||
edge_map=edge_map_t.detach().cpu().numpy().astype(np.float32),
|
||||
)
|
||||
|
||||
return TileGraphSourceAnalysis(
|
||||
edge_map=_compute_edge_map(rgba),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ from .io import premultiply, unpremultiply
|
|||
from .metrics import source_lattice_consistency_breakdown
|
||||
from .params import SolverHyperParams
|
||||
from .source_reference import build_source_lattice_reference
|
||||
from .types import InferenceResult, SolverArtifacts, SourceAnalysis
|
||||
from .types import ContinuousSourceAnalysis, InferenceResult, SolverArtifacts
|
||||
|
||||
|
||||
def _require_torch():
|
||||
|
|
@ -1358,7 +1358,7 @@ def _discrete_refine_output(
|
|||
def optimize_uv_field(
|
||||
rgba: np.ndarray,
|
||||
inference: InferenceResult,
|
||||
analysis: SourceAnalysis,
|
||||
analysis: ContinuousSourceAnalysis,
|
||||
steps: int,
|
||||
seed: int,
|
||||
device: str,
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ from typing import Any
|
|||
|
||||
import numpy as np
|
||||
|
||||
from .analysis import analyze_source
|
||||
from .analysis import analyze_continuous_source, analyze_tile_graph_source
|
||||
from .continuous import optimize_uv_field
|
||||
from .diagnostics import (
|
||||
summarize_run,
|
||||
|
|
@ -29,7 +29,7 @@ from .params import SolverHyperParams
|
|||
from .palette import load_palette, quantize_rgba, save_palette_report
|
||||
from .preprocess import strip_edge_background
|
||||
from .tile_graph import optimize_tile_graph
|
||||
from .types import InferenceResult, RunResult
|
||||
from .types import ContinuousSourceAnalysis, InferenceResult, RunResult, TileGraphSourceAnalysis
|
||||
|
||||
|
||||
def run_pipeline(
|
||||
|
|
@ -79,11 +79,11 @@ def run_pipeline(
|
|||
device=device,
|
||||
)
|
||||
inference_mode = "fixed"
|
||||
analysis = analyze_source(
|
||||
analysis = _prepare_analysis(
|
||||
source,
|
||||
seed=seed,
|
||||
device=device if reconstruction_mode == "tile-graph" else None,
|
||||
include_clusters=reconstruction_mode != "tile-graph",
|
||||
device=device,
|
||||
reconstruction_mode=reconstruction_mode,
|
||||
)
|
||||
inference = _select_phase_candidate(
|
||||
source,
|
||||
|
|
@ -139,8 +139,6 @@ def run_pipeline(
|
|||
)
|
||||
write_alpha_preview(diagnostics_path / "alpha-preview.png", source, output_rgba)
|
||||
write_heatmap(diagnostics_path / "noise-heatmap.png", cleanup.isolated_heatmap)
|
||||
if analysis.cluster_centers.size:
|
||||
save_rgba(diagnostics_path / "cluster-preview.png", analysis.cluster_preview)
|
||||
run_json = summarize_run(result)
|
||||
run_json["inference"] = inference_to_json(inference)
|
||||
run_json["settings"] = {
|
||||
|
|
@ -167,6 +165,18 @@ def run_pipeline(
|
|||
return result
|
||||
|
||||
|
||||
def _prepare_analysis(
|
||||
source: np.ndarray,
|
||||
*,
|
||||
seed: int,
|
||||
device: str,
|
||||
reconstruction_mode: str,
|
||||
) -> ContinuousSourceAnalysis | TileGraphSourceAnalysis:
|
||||
if reconstruction_mode == "tile-graph":
|
||||
return analyze_tile_graph_source(source, device=device)
|
||||
return analyze_continuous_source(source, seed=seed)
|
||||
|
||||
|
||||
def _select_phase_candidate(
|
||||
source: np.ndarray,
|
||||
inference: InferenceResult,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ from __future__ import annotations
|
|||
import numpy as np
|
||||
|
||||
from .io import premultiply, unpremultiply
|
||||
from .types import SourceLatticeReference
|
||||
from .types import SourceLatticeReference, TileGraphSourceReference
|
||||
|
||||
|
||||
def _require_torch():
|
||||
|
|
@ -95,16 +95,6 @@ def _lattice_indices_torch(
|
|||
return y_idx[:, None] * target_width + x_idx[None, :]
|
||||
|
||||
|
||||
def _reference_deltas(reference: np.ndarray) -> tuple[np.ndarray | None, np.ndarray | None, np.ndarray | None, np.ndarray | None]:
|
||||
height = reference.shape[0]
|
||||
width = reference.shape[1]
|
||||
delta_x = reference[:, 1:, :] - reference[:, :-1, :] if width > 1 else None
|
||||
delta_y = reference[1:, :, :] - reference[:-1, :, :] if height > 1 else None
|
||||
delta_diag = reference[1:, 1:, :] - reference[:-1, :-1, :] if height > 1 and width > 1 else None
|
||||
delta_anti = reference[1:, :-1, :] - reference[:-1, 1:, :] if height > 1 and width > 1 else None
|
||||
return delta_x, delta_y, delta_diag, delta_anti
|
||||
|
||||
|
||||
def _unpremultiply_torch(torch, premul_t):
|
||||
alpha = premul_t[..., 3:4].clamp_min(1e-6)
|
||||
rgb = torch.where(alpha > 1e-6, premul_t[..., :3] / alpha, torch.zeros_like(premul_t[..., :3]))
|
||||
|
|
@ -147,6 +137,65 @@ def build_source_lattice_reference(
|
|||
edge_grad_y_hint: np.ndarray | None = None,
|
||||
device: str | None = None,
|
||||
) -> SourceLatticeReference:
|
||||
payload = _build_reference_payload(
|
||||
source_rgba,
|
||||
target_width=target_width,
|
||||
target_height=target_height,
|
||||
phase_x=phase_x,
|
||||
phase_y=phase_y,
|
||||
alpha_threshold=alpha_threshold,
|
||||
edge_hint=edge_hint,
|
||||
edge_grad_x_hint=edge_grad_x_hint,
|
||||
edge_grad_y_hint=edge_grad_y_hint,
|
||||
device=device,
|
||||
)
|
||||
return SourceLatticeReference(**payload)
|
||||
|
||||
|
||||
def build_tile_graph_source_reference(
|
||||
source_rgba: np.ndarray,
|
||||
*,
|
||||
target_width: int,
|
||||
target_height: int,
|
||||
phase_x: float,
|
||||
phase_y: float,
|
||||
alpha_threshold: float = 0.05,
|
||||
edge_hint: np.ndarray | None = None,
|
||||
device: str | None = None,
|
||||
) -> TileGraphSourceReference:
|
||||
payload = _build_reference_payload(
|
||||
source_rgba,
|
||||
target_width=target_width,
|
||||
target_height=target_height,
|
||||
phase_x=phase_x,
|
||||
phase_y=phase_y,
|
||||
alpha_threshold=alpha_threshold,
|
||||
edge_hint=edge_hint,
|
||||
device=device,
|
||||
)
|
||||
return TileGraphSourceReference(
|
||||
sharp_rgba=payload["sharp_rgba"],
|
||||
sharp_x=payload["sharp_x"],
|
||||
sharp_y=payload["sharp_y"],
|
||||
edge_peak_x=payload["edge_peak_x"],
|
||||
edge_peak_y=payload["edge_peak_y"],
|
||||
edge_strength=payload["edge_strength"],
|
||||
)
|
||||
|
||||
|
||||
def _build_reference_payload(
|
||||
source_rgba: np.ndarray,
|
||||
*,
|
||||
target_width: int,
|
||||
target_height: int,
|
||||
phase_x: float,
|
||||
phase_y: float,
|
||||
alpha_threshold: float = 0.05,
|
||||
edge_hint: np.ndarray | None = None,
|
||||
edge_grad_x_hint: np.ndarray | None = None,
|
||||
edge_grad_y_hint: np.ndarray | None = None,
|
||||
device: str | None = None,
|
||||
) -> dict[str, np.ndarray | float]:
|
||||
if device is not None:
|
||||
torch = _require_torch()
|
||||
resolved_device = _resolve_device(torch, device)
|
||||
|
|
@ -261,29 +310,21 @@ def build_source_lattice_reference(
|
|||
expected_pixels_per_cell = float(source_rgba.shape[0] * source_rgba.shape[1]) / float(cell_count)
|
||||
cell_support_t = (counts_t / max(expected_pixels_per_cell, 1.0)).reshape(target_height, target_width)
|
||||
|
||||
sharp_premul_np = sharp_premul_t.detach().cpu().numpy().astype(np.float32)
|
||||
delta_x, delta_y, delta_diag, delta_anti = _reference_deltas(sharp_premul_np)
|
||||
return SourceLatticeReference(
|
||||
mean_rgba=mean_rgba_t.detach().cpu().numpy().astype(np.float32),
|
||||
sharp_rgba=sharp_rgba_t.detach().cpu().numpy().astype(np.float32),
|
||||
dispersion=dispersion,
|
||||
lattice_indices=indices_t.detach().cpu().numpy().astype(np.int32),
|
||||
cell_dispersion=cell_dispersion_t.detach().cpu().numpy().astype(np.float32),
|
||||
cell_counts=counts_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.float32),
|
||||
cell_support=cell_support_t.detach().cpu().numpy().astype(np.float32),
|
||||
cell_alpha_max=cell_alpha_max_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.float32),
|
||||
sharp_x=sharp_x_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.int32),
|
||||
sharp_y=sharp_y_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.int32),
|
||||
edge_peak_x=edge_peak_x_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.int32),
|
||||
edge_peak_y=edge_peak_y_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.int32),
|
||||
edge_strength=edge_strength_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.float32),
|
||||
edge_grad_x=edge_grad_x_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.float32),
|
||||
edge_grad_y=edge_grad_y_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.float32),
|
||||
delta_x=delta_x.astype(np.float32) if delta_x is not None else None,
|
||||
delta_y=delta_y.astype(np.float32) if delta_y is not None else None,
|
||||
delta_diag=delta_diag.astype(np.float32) if delta_diag is not None else None,
|
||||
delta_anti=delta_anti.astype(np.float32) if delta_anti is not None else None,
|
||||
)
|
||||
return {
|
||||
"mean_rgba": mean_rgba_t.detach().cpu().numpy().astype(np.float32),
|
||||
"sharp_rgba": sharp_rgba_t.detach().cpu().numpy().astype(np.float32),
|
||||
"dispersion": dispersion,
|
||||
"cell_dispersion": cell_dispersion_t.detach().cpu().numpy().astype(np.float32),
|
||||
"cell_support": cell_support_t.detach().cpu().numpy().astype(np.float32),
|
||||
"cell_alpha_max": cell_alpha_max_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.float32),
|
||||
"sharp_x": sharp_x_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.int32),
|
||||
"sharp_y": sharp_y_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.int32),
|
||||
"edge_peak_x": edge_peak_x_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.int32),
|
||||
"edge_peak_y": edge_peak_y_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.int32),
|
||||
"edge_strength": edge_strength_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.float32),
|
||||
"edge_grad_x": edge_grad_x_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.float32),
|
||||
"edge_grad_y": edge_grad_y_flat_t.reshape(target_height, target_width).detach().cpu().numpy().astype(np.float32),
|
||||
}
|
||||
|
||||
height = source_rgba.shape[0]
|
||||
width = source_rgba.shape[1]
|
||||
|
|
@ -394,25 +435,18 @@ def build_source_lattice_reference(
|
|||
expected_pixels_per_cell = float(source_rgba.shape[0] * source_rgba.shape[1]) / float(cell_count)
|
||||
cell_support = (counts / max(expected_pixels_per_cell, 1.0)).reshape(target_height, target_width)
|
||||
|
||||
delta_x, delta_y, delta_diag, delta_anti = _reference_deltas(sharp_premul)
|
||||
return SourceLatticeReference(
|
||||
mean_rgba=mean_rgba.astype(np.float32),
|
||||
sharp_rgba=sharp_rgba.astype(np.float32),
|
||||
dispersion=dispersion,
|
||||
lattice_indices=indices.astype(np.int32),
|
||||
cell_dispersion=cell_dispersion.astype(np.float32),
|
||||
cell_counts=counts.reshape(target_height, target_width).astype(np.float32),
|
||||
cell_support=cell_support.astype(np.float32),
|
||||
cell_alpha_max=cell_alpha_max.reshape(target_height, target_width).astype(np.float32),
|
||||
sharp_x=sharp_x_flat.reshape(target_height, target_width).astype(np.int32),
|
||||
sharp_y=sharp_y_flat.reshape(target_height, target_width).astype(np.int32),
|
||||
edge_peak_x=edge_peak_x_flat.reshape(target_height, target_width).astype(np.int32),
|
||||
edge_peak_y=edge_peak_y_flat.reshape(target_height, target_width).astype(np.int32),
|
||||
edge_strength=edge_strength_flat.reshape(target_height, target_width).astype(np.float32),
|
||||
edge_grad_x=edge_grad_x_flat.reshape(target_height, target_width).astype(np.float32),
|
||||
edge_grad_y=edge_grad_y_flat.reshape(target_height, target_width).astype(np.float32),
|
||||
delta_x=delta_x.astype(np.float32) if delta_x is not None else None,
|
||||
delta_y=delta_y.astype(np.float32) if delta_y is not None else None,
|
||||
delta_diag=delta_diag.astype(np.float32) if delta_diag is not None else None,
|
||||
delta_anti=delta_anti.astype(np.float32) if delta_anti is not None else None,
|
||||
)
|
||||
return {
|
||||
"mean_rgba": mean_rgba.astype(np.float32),
|
||||
"sharp_rgba": sharp_rgba.astype(np.float32),
|
||||
"dispersion": dispersion,
|
||||
"cell_dispersion": cell_dispersion.astype(np.float32),
|
||||
"cell_support": cell_support.astype(np.float32),
|
||||
"cell_alpha_max": cell_alpha_max.reshape(target_height, target_width).astype(np.float32),
|
||||
"sharp_x": sharp_x_flat.reshape(target_height, target_width).astype(np.int32),
|
||||
"sharp_y": sharp_y_flat.reshape(target_height, target_width).astype(np.int32),
|
||||
"edge_peak_x": edge_peak_x_flat.reshape(target_height, target_width).astype(np.int32),
|
||||
"edge_peak_y": edge_peak_y_flat.reshape(target_height, target_width).astype(np.int32),
|
||||
"edge_strength": edge_strength_flat.reshape(target_height, target_width).astype(np.float32),
|
||||
"edge_grad_x": edge_grad_x_flat.reshape(target_height, target_width).astype(np.float32),
|
||||
"edge_grad_y": edge_grad_y_flat.reshape(target_height, target_width).astype(np.float32),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,8 +9,8 @@ import numpy as np
|
|||
|
||||
from .metrics import source_lattice_consistency_breakdown
|
||||
from .params import SolverHyperParams
|
||||
from .source_reference import build_source_lattice_reference
|
||||
from .types import InferenceResult, SolverArtifacts, SourceAnalysis
|
||||
from .source_reference import build_tile_graph_source_reference
|
||||
from .types import InferenceResult, SolverArtifacts, TileGraphSourceAnalysis
|
||||
|
||||
_RIGHT = 0
|
||||
_DOWN = 1
|
||||
|
|
@ -54,7 +54,6 @@ def _resolve_device(torch, requested: str) -> str:
|
|||
@dataclass(slots=True)
|
||||
class TileGraphModel:
|
||||
candidate_rgba: np.ndarray
|
||||
candidate_coords: np.ndarray
|
||||
candidate_area_ratio: np.ndarray
|
||||
candidate_coverage: np.ndarray
|
||||
candidate_deltas: np.ndarray
|
||||
|
|
@ -63,7 +62,12 @@ class TileGraphModel:
|
|||
reference_sharp_rgba: np.ndarray
|
||||
reference_edge_rgba: np.ndarray
|
||||
edge_strength: np.ndarray
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class TileGraphBuildStats:
|
||||
component_count: int
|
||||
candidate_count: int
|
||||
edge_density: float
|
||||
average_choices: float
|
||||
model_device: str
|
||||
|
|
@ -72,10 +76,12 @@ class TileGraphModel:
|
|||
|
||||
_TILE_GRAPH_MODEL_CACHE_MAX_ENTRIES = 8
|
||||
_TILE_GRAPH_MODEL_CACHE: OrderedDict[tuple[object, ...], TileGraphModel] = OrderedDict()
|
||||
_TILE_GRAPH_BUILD_STATS_CACHE: OrderedDict[tuple[object, ...], TileGraphBuildStats] = OrderedDict()
|
||||
|
||||
|
||||
def clear_tile_graph_model_cache() -> None:
|
||||
_TILE_GRAPH_MODEL_CACHE.clear()
|
||||
_TILE_GRAPH_BUILD_STATS_CACHE.clear()
|
||||
|
||||
|
||||
def _hash_array(array: np.ndarray) -> str:
|
||||
|
|
@ -118,19 +124,28 @@ def _tile_graph_model_cache_key(
|
|||
)
|
||||
|
||||
|
||||
def _get_cached_tile_graph_model(cache_key: tuple[object, ...]) -> TileGraphModel | None:
|
||||
def _get_cached_tile_graph_model(cache_key: tuple[object, ...]) -> tuple[TileGraphModel, TileGraphBuildStats] | None:
|
||||
cached = _TILE_GRAPH_MODEL_CACHE.get(cache_key)
|
||||
if cached is None:
|
||||
cached_stats = _TILE_GRAPH_BUILD_STATS_CACHE.get(cache_key)
|
||||
if cached is None or cached_stats is None:
|
||||
return None
|
||||
_TILE_GRAPH_MODEL_CACHE.move_to_end(cache_key)
|
||||
return cached
|
||||
_TILE_GRAPH_BUILD_STATS_CACHE.move_to_end(cache_key)
|
||||
return cached, cached_stats
|
||||
|
||||
|
||||
def _store_cached_tile_graph_model(cache_key: tuple[object, ...], model: TileGraphModel) -> None:
|
||||
def _store_cached_tile_graph_model(
|
||||
cache_key: tuple[object, ...],
|
||||
model: TileGraphModel,
|
||||
stats: TileGraphBuildStats,
|
||||
) -> None:
|
||||
_TILE_GRAPH_MODEL_CACHE[cache_key] = model
|
||||
_TILE_GRAPH_MODEL_CACHE.move_to_end(cache_key)
|
||||
_TILE_GRAPH_BUILD_STATS_CACHE[cache_key] = stats
|
||||
_TILE_GRAPH_BUILD_STATS_CACHE.move_to_end(cache_key)
|
||||
while len(_TILE_GRAPH_MODEL_CACHE) > _TILE_GRAPH_MODEL_CACHE_MAX_ENTRIES:
|
||||
_TILE_GRAPH_MODEL_CACHE.popitem(last=False)
|
||||
old_key, _old_model = _TILE_GRAPH_MODEL_CACHE.popitem(last=False)
|
||||
_TILE_GRAPH_BUILD_STATS_CACHE.pop(old_key, None)
|
||||
|
||||
|
||||
def _make_regular_uv(height: int, width: int, target_height: int, target_width: int, phase_x: float, phase_y: float) -> np.ndarray:
|
||||
|
|
@ -147,10 +162,6 @@ def _make_regular_uv(height: int, width: int, target_height: int, target_width:
|
|||
return uv.astype(np.float32)
|
||||
|
||||
|
||||
def _rgba_luminance(rgba: np.ndarray) -> np.ndarray:
|
||||
return rgba[..., 0] * 0.2126 + rgba[..., 1] * 0.7152 + rgba[..., 2] * 0.0722
|
||||
|
||||
|
||||
def _component_axis_stats(member_x: np.ndarray, member_y: np.ndarray) -> tuple[float, float, float, float, float]:
|
||||
if member_x.size <= 1:
|
||||
return 1.0, 0.0, 0.0, 0.0, 0.0
|
||||
|
|
@ -871,10 +882,10 @@ def build_tile_graph_model(
|
|||
source_rgba: np.ndarray,
|
||||
*,
|
||||
inference: InferenceResult,
|
||||
analysis: SourceAnalysis,
|
||||
analysis: TileGraphSourceAnalysis,
|
||||
solver_params: SolverHyperParams | None = None,
|
||||
device: str = "cpu",
|
||||
) -> TileGraphModel:
|
||||
) -> tuple[TileGraphModel, TileGraphBuildStats]:
|
||||
torch = _require_torch()
|
||||
resolved_device = _resolve_device(torch, device)
|
||||
solver_params = solver_params or SolverHyperParams()
|
||||
|
|
@ -886,8 +897,9 @@ def build_tile_graph_model(
|
|||
)
|
||||
cached_model = _get_cached_tile_graph_model(cache_key)
|
||||
if cached_model is not None:
|
||||
return replace(cached_model, cache_hit=True)
|
||||
source_reference = build_source_lattice_reference(
|
||||
model, stats = cached_model
|
||||
return model, replace(stats, cache_hit=True)
|
||||
source_reference = build_tile_graph_source_reference(
|
||||
source_rgba,
|
||||
target_width=inference.target_width,
|
||||
target_height=inference.target_height,
|
||||
|
|
@ -974,7 +986,6 @@ def build_tile_graph_model(
|
|||
)
|
||||
|
||||
candidate_linear: list[int] = []
|
||||
candidate_coords: list[tuple[int, int]] = []
|
||||
candidate_area_ratio: list[float] = []
|
||||
candidate_coverage: list[float] = []
|
||||
candidate_source_x: list[float] = []
|
||||
|
|
@ -995,7 +1006,6 @@ def build_tile_graph_model(
|
|||
return
|
||||
seen_pixels.add(pixel_index)
|
||||
candidate_linear.append(pixel_index)
|
||||
candidate_coords.append((coord_y, coord_x))
|
||||
candidate_area_ratio.append(float(max(area_ratio, 1e-3)))
|
||||
candidate_coverage.append(float(np.clip(coverage, 0.0, 1.0)))
|
||||
candidate_source_x.append(float(source_x))
|
||||
|
|
@ -1052,7 +1062,6 @@ def build_tile_graph_model(
|
|||
candidate_deltas_t[:, direction] = source_t[sample_y_t, sample_x_t] - center_rgba_t
|
||||
|
||||
candidate_rgba_np = center_rgba_t.detach().cpu().numpy().astype(np.float32)
|
||||
candidate_coords_np = np.asarray(candidate_coords, dtype=np.int32)
|
||||
candidate_area_ratio_np = np.asarray(candidate_area_ratio, dtype=np.float32)
|
||||
candidate_coverage_np = np.asarray(candidate_coverage, dtype=np.float32)
|
||||
candidate_deltas_np = candidate_deltas_t.detach().cpu().numpy().astype(np.float32)
|
||||
|
|
@ -1068,7 +1077,6 @@ def build_tile_graph_model(
|
|||
)
|
||||
base_model = TileGraphModel(
|
||||
candidate_rgba=candidate_rgba_np,
|
||||
candidate_coords=candidate_coords_np,
|
||||
candidate_area_ratio=candidate_area_ratio_np,
|
||||
candidate_coverage=candidate_coverage_np,
|
||||
candidate_deltas=candidate_deltas_np,
|
||||
|
|
@ -1077,14 +1085,17 @@ def build_tile_graph_model(
|
|||
reference_sharp_rgba=source_reference.sharp_rgba.astype(np.float32),
|
||||
reference_edge_rgba=edge_rgba_np.reshape(inference.target_height, inference.target_width, -1).astype(np.float32),
|
||||
edge_strength=source_reference.edge_strength.astype(np.float32),
|
||||
)
|
||||
base_stats = TileGraphBuildStats(
|
||||
component_count=component_total,
|
||||
candidate_count=int(candidate_rgba_np.shape[0]),
|
||||
edge_density=edge_density,
|
||||
average_choices=average_choices,
|
||||
model_device=resolved_device,
|
||||
cache_hit=False,
|
||||
)
|
||||
_store_cached_tile_graph_model(cache_key, base_model)
|
||||
return replace(base_model, cache_hit=False)
|
||||
_store_cached_tile_graph_model(cache_key, base_model, base_stats)
|
||||
return base_model, base_stats
|
||||
|
||||
|
||||
def _cell_candidate_span(model: TileGraphModel, y: int, x: int) -> tuple[int, int]:
|
||||
|
|
@ -1273,48 +1284,10 @@ def _assignment_rgba(model: TileGraphModel, selected: np.ndarray) -> np.ndarray:
|
|||
return model.candidate_rgba[selected]
|
||||
|
||||
|
||||
def _pair_penalty(model: TileGraphModel, left_idx: int, right_idx: int, direction: int, solver_params: SolverHyperParams) -> float:
|
||||
observed_delta = model.candidate_rgba[right_idx] - model.candidate_rgba[left_idx]
|
||||
expected = model.candidate_deltas[left_idx, direction]
|
||||
reverse = model.candidate_deltas[right_idx, _OPPOSITE[direction]]
|
||||
delta_penalty = np.mean(np.abs(observed_delta - expected))
|
||||
reverse_penalty = np.mean(np.abs(-observed_delta - reverse))
|
||||
return float((delta_penalty + reverse_penalty) * 0.5 * solver_params.tile_graph_delta_weight)
|
||||
|
||||
|
||||
def _assignment_score(selected: np.ndarray, model: TileGraphModel, unary_cost: np.ndarray, solver_params: SolverHyperParams) -> float:
|
||||
height, width = selected.shape
|
||||
gathered = np.zeros((height, width), dtype=np.float32)
|
||||
for y in range(height):
|
||||
for x in range(width):
|
||||
start, end = _cell_candidate_span(model, y, x)
|
||||
indices = model.cell_candidate_indices[start:end]
|
||||
match = np.flatnonzero(indices == selected[y, x])
|
||||
if match.size == 0:
|
||||
continue
|
||||
gathered[y, x] = unary_cost[start + int(match[0])]
|
||||
score = float(np.mean(gathered))
|
||||
if width > 1:
|
||||
penalties = []
|
||||
for y in range(height):
|
||||
for x in range(width - 1):
|
||||
penalties.append(_pair_penalty(model, int(selected[y, x]), int(selected[y, x + 1]), _RIGHT, solver_params))
|
||||
if penalties:
|
||||
score += float(np.mean(np.asarray(penalties, dtype=np.float32)))
|
||||
if height > 1:
|
||||
penalties = []
|
||||
for y in range(height - 1):
|
||||
for x in range(width):
|
||||
penalties.append(_pair_penalty(model, int(selected[y, x]), int(selected[y + 1, x]), _DOWN, solver_params))
|
||||
if penalties:
|
||||
score += float(np.mean(np.asarray(penalties, dtype=np.float32)))
|
||||
return score
|
||||
|
||||
|
||||
def optimize_tile_graph(
|
||||
rgba: np.ndarray,
|
||||
inference: InferenceResult,
|
||||
analysis: SourceAnalysis,
|
||||
analysis: TileGraphSourceAnalysis,
|
||||
steps: int,
|
||||
seed: int,
|
||||
device: str,
|
||||
|
|
@ -1327,7 +1300,7 @@ def optimize_tile_graph(
|
|||
torch.manual_seed(seed)
|
||||
if resolved_device == "cuda":
|
||||
torch.cuda.manual_seed_all(seed)
|
||||
model = build_tile_graph_model(
|
||||
model, build_stats = build_tile_graph_model(
|
||||
rgba,
|
||||
inference=inference,
|
||||
analysis=analysis,
|
||||
|
|
@ -1443,14 +1416,14 @@ def optimize_tile_graph(
|
|||
kept_initial_assignment = True
|
||||
diagnostics = {
|
||||
"mode": "tile-graph",
|
||||
"tile_graph_model_device": model.model_device,
|
||||
"tile_graph_model_device": build_stats.model_device,
|
||||
"tile_graph_solver_device": resolved_device,
|
||||
"tile_graph_model_cache_hit": model.cache_hit,
|
||||
"tile_graph_model_cache_hit": build_stats.cache_hit,
|
||||
"tile_graph_proposal_mode": "atomic-components",
|
||||
"tile_graph_component_count": model.component_count,
|
||||
"tile_graph_candidate_count": int(model.candidate_rgba.shape[0]),
|
||||
"tile_graph_edge_density": model.edge_density,
|
||||
"tile_graph_average_choices": model.average_choices,
|
||||
"tile_graph_component_count": build_stats.component_count,
|
||||
"tile_graph_candidate_count": build_stats.candidate_count,
|
||||
"tile_graph_edge_density": build_stats.edge_density,
|
||||
"tile_graph_average_choices": build_stats.average_choices,
|
||||
"tile_graph_initial_score": float(loss_history[0]),
|
||||
"tile_graph_final_score": float(loss_history[-1]),
|
||||
"tile_graph_initial_source_fidelity": float(initial_source_fidelity),
|
||||
|
|
|
|||
|
|
@ -28,12 +28,17 @@ class InferenceResult:
|
|||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class SourceAnalysis:
|
||||
class ContinuousSourceAnalysis:
|
||||
edge_map: np.ndarray
|
||||
cluster_map: np.ndarray
|
||||
cluster_centers: np.ndarray
|
||||
alpha_map: np.ndarray
|
||||
cluster_preview: np.ndarray
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class TileGraphSourceAnalysis:
|
||||
edge_map: np.ndarray
|
||||
|
||||
|
||||
SourceAnalysis = ContinuousSourceAnalysis | TileGraphSourceAnalysis
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
|
|
@ -41,9 +46,7 @@ class SourceLatticeReference:
|
|||
mean_rgba: np.ndarray
|
||||
sharp_rgba: np.ndarray
|
||||
dispersion: float
|
||||
lattice_indices: np.ndarray
|
||||
cell_dispersion: np.ndarray
|
||||
cell_counts: np.ndarray
|
||||
cell_support: np.ndarray
|
||||
cell_alpha_max: np.ndarray
|
||||
sharp_x: np.ndarray
|
||||
|
|
@ -53,10 +56,16 @@ class SourceLatticeReference:
|
|||
edge_strength: np.ndarray
|
||||
edge_grad_x: np.ndarray
|
||||
edge_grad_y: np.ndarray
|
||||
delta_x: np.ndarray | None
|
||||
delta_y: np.ndarray | None
|
||||
delta_diag: np.ndarray | None
|
||||
delta_anti: np.ndarray | None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class TileGraphSourceReference:
|
||||
sharp_rgba: np.ndarray
|
||||
sharp_x: np.ndarray
|
||||
sharp_y: np.ndarray
|
||||
edge_peak_x: np.ndarray
|
||||
edge_peak_y: np.ndarray
|
||||
edge_strength: np.ndarray
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
|
|
@ -87,7 +96,7 @@ class RunResult:
|
|||
source_rgba: np.ndarray
|
||||
output_rgba: np.ndarray
|
||||
inference: InferenceResult
|
||||
analysis: SourceAnalysis
|
||||
analysis: ContinuousSourceAnalysis | TileGraphSourceAnalysis
|
||||
solver: SolverArtifacts
|
||||
cleanup: CleanupArtifacts
|
||||
palette_result: PaletteResult | None
|
||||
|
|
|
|||
Loading…
Reference in a new issue