Reuse tile-graph phase probes

This commit is contained in:
Meta Vens 2026-04-23 01:02:39 +01:00
commit 94af8d8560
4 changed files with 153 additions and 32 deletions

View file

@ -45,8 +45,10 @@ Current tile-graph status:
- tile-graph now falls back to its initial assignment when the propagation loop would make source-lattice fidelity worse, which is currently important for preserving sharp internal contour cells
- it still beats naive resize on the repo's synthetic thin-feature regression and now does so without letting the final propagation step blur past the initial placement
- source-region connected-components now have a device-side Torch path, so the expensive labeling step no longer depends on Python flood fill
- on the real cleaned badge, the current tile-graph model build now takes about `9.48s` on CPU versus `6.37s` on CUDA while producing the same `2499` source regions and `23223` candidates
- the remaining large-fixture bottleneck is the per-component one-cell window cutting pass, which still hops back to CPU after labeling
- on the real cleaned badge, the current end-to-end `tile-graph` pipeline now lands at about `270.8s` on this machine after reusing the chosen phase-rerank probe instead of rebuilding the same selected candidate a second time; the older stroke-aware badge run was about `443.1s`
- profiling the selected badge candidate shows the main remaining bottleneck is model construction, not the solver loop: `build_tile_graph_model(...)` takes about `142.3s`, and about `131.2s` of that is `_extract_source_region_tiles(...)`
- the low-confidence badge rerank is also expensive because it still probes eight lattice candidates before the final pick; on the same fixture that phase takes about `223.9s`, of which about `208.1s` is reconstruction work
- the remaining large-fixture bottleneck is the per-component one-cell window cutting pass inside source-region extraction, which is still Python/NumPy-heavy after the GPU CCL stage
- elongated source regions now get a stroke-aware slicing pass that follows their principal axis instead of only marching with cardinal queue steps, and the repo now has a shallow-stroke regression that checks for fan-out on that kind of component
- that stroke-aware slicer is a real synthetic improvement but not a real-badge win yet: the latest badge probe under `artifacts/badge-tile-graph-stroke-v2-cuda/` still keeps the initial assignment and slightly regresses source-fidelity (`0.1832` vs `0.1800`)
- the new low-risk hybrid mode keeps tile-graph's source-owned candidates but scores them against a continuous-optimizer geometry prepass; on the cleaned badge it improves tile-graph from `0.1832` to `0.1785` under `artifacts/badge-hybrid-v2-cuda/`

View file

@ -20,7 +20,7 @@ Implemented:
Verified:
- local editable install in a dedicated venv
- full test suite currently passing (`59 passed`)
- full test suite currently passing (`60 passed`)
- compare-mode smoke run against a real emblem image
- the cleaned real badge fixture in `tests/fixtures/real/ai-badge-cleaned.png` still beats naive resize on source-lattice consistency on the continuous path
- the latest full-emblem tile-graph atomic probe under `artifacts/full-emblem-tile-graph-atomic-v3-cuda/` lands at `0.0224` source-fidelity, beating the older full-emblem tile-graph CUDA baseline at `0.0283`
@ -57,29 +57,29 @@ The most provisional areas are:
### Active pass
This pass adds the first low-risk hybrid path between the continuous solver and tile-graph instead of treating them as completely separate experiments.
This pass focused on iteration speed for `tile-graph`, because the current badge loop had become too slow to support quick debugging.
What landed:
- `pipeline.py` now supports `reconstruction_mode="hybrid"` and runs a zero-step continuous prepass before tile-graph
- `tile_graph.py` now accepts an optional geometry reference image plus guidance map and adds a geometry-match term to the tile-graph unary cost
- `cli.py` now exposes `--reconstruction-mode hybrid`
- `tests/test_pipeline.py` now covers both the direct hybrid handoff seam and an actual end-to-end hybrid smoke run
- `pipeline.py` now reuses the chosen low-confidence phase-rerank reconstruction for `tile-graph` and `hybrid` instead of rebuilding the same selected candidate again after selection
- `tests/test_pipeline.py` now has a regression that locks in that reuse behavior for low-confidence `tile-graph` runs
Current implementation note:
- source-region labeling is still device-backed, but the one-cell window cutting pass remains CPU-side and still dominates large-fixture runtime
- the hybrid is intentionally conservative for this first pass: it only biases tile-graph's unary cost with the continuous prepass layout and does not yet replace the pairwise objective or the source-region builder
- on the cleaned badge, the current `tile-graph` end-to-end run now lands at about `270.8s` on this machine after reuse, down from about `443.1s` for the earlier stroke-aware badge run
- profiling the selected badge candidate shows that the solver loop is not the problem: the final `tile-graph` reconstruction used about `142.3s`, and about `131.2s` of that sat inside `_extract_source_region_tiles(...)`
- the low-confidence badge rerank is the other major cost center: `_select_phase_candidate(...)` took about `223.9s` on the same fixture, with about `208.1s` of that spent inside reconstruction probes
- `infer_lattice(...)` still takes about `44.1s` on that fixture, so iteration work that does not change the lattice itself should eventually be able to reuse or pin inference too
- the hybrid remains intentionally conservative: it only biases tile-graph's unary cost with the continuous prepass layout and does not yet replace the pairwise objective or the source-region builder
- on the cleaned badge, that conservative hybrid still helps: the latest run under `artifacts/badge-hybrid-v2-cuda/` lands at `0.1785`, improving on the current tile-graph badge baseline at `0.1832`
- the hybrid is still far behind the stronger continuous badge result (`0.0832`), so the seam looks promising but it is not yet enough to solve the real contour problem by itself
- the runtime overhead is modest relative to the current stroke-aware tile-graph pass: about `460.7s` for the hybrid badge probe versus about `443.1s` for the current non-hybrid tile-graph badge probe on this machine
- the latest full-emblem atomic probe under `artifacts/full-emblem-tile-graph-atomic-v3-cuda/` lands at `0.0224` source-fidelity with `34278` candidates and about `2.16` average choices per cell
- that beats the earlier full-CUDA tile-graph baseline (`0.0283`) and materially improves on the first atomic-only attempt (`0.1571`), which chose atomic regions too eagerly and then let the solver blur them out again
Next after that:
- split tile-graph iteration into a cached model-build phase and a near-free solve phase so weight tuning does not keep paying the `~131s` source-region cutting bill
- add an explicit fast-iteration path that reuses or pins lattice inference when the experiment is only changing tile-graph internals
- port or reformulate `_extract_source_region_tiles(...)` so it no longer spends most of the badge runtime in Python/NumPy window cutting
- reduce rerank probe cost by using cached candidate builds where possible or by using a cheaper rerank proxy before full tile-graph reconstruction
- decide whether the next hybrid pass should add geometry-aware pairwise terms before changing the source-region builder again
- keep pushing the initial candidate builder toward true source-side stroke ownership instead of only better stroke slicing within the same builder
- port the per-component window cutting pass back toward a fully device-friendly formulation instead of only accelerating the labeling step
- decide whether the next stroke pass should use a real contour/skeleton trace instead of only a principal-axis approximation
- rerank low-confidence top lattice candidates with short real solver probes instead of relying only on the cheapest preview
- evaluate whether the tile-graph propagation loop should become more contour-aware or simply stay more conservative now that the initial assignment is stronger
- rerun tuning after the tile-graph objective and candidate sets stabilize
- decide whether the tile-graph path should stay an alternate solver or become a candidate generator for the continuous refine stage
@ -108,6 +108,7 @@ Current status:
- on the cleaned badge, the new CCL-backed tile-graph run under `artifacts/badge-tile-graph-ccl-cuda/` still lands at a weak `0.1800`, so the current CCL work should be treated as an infrastructure/performance step rather than a visual-quality fix
- the new stroke-aware badge run under `artifacts/badge-tile-graph-stroke-v2-cuda/` still does not solve the guard-contour problem and slightly regresses to `0.1832`, so the next stroke pass should be judged on whether it changes the source-side path model more fundamentally
- the first hybrid badge run under `artifacts/badge-hybrid-v2-cuda/` improves that tile-graph baseline to `0.1785`, which is modest but real progress in the combined direction
- on the cleaned badge, iteration is still dominated by preprocessing work rather than the tile-graph parity solver: about `44.1s` in inference, `223.9s` in low-confidence rerank probes, and `142.3s` in the final selected-candidate build before this pass started reusing the chosen phase probe
Important note:
- the checkerboard is baked into the source image, not transparency

View file

@ -32,6 +32,10 @@ from .tile_graph import optimize_tile_graph
from .types import InferenceResult, RunResult
def _reuse_phase_probe_reconstruction(reconstruction_mode: str) -> bool:
return reconstruction_mode in {"tile-graph", "hybrid"}
def run_pipeline(
input_path: str | Path,
output_path: str | Path,
@ -54,7 +58,7 @@ def run_pipeline(
source = strip_edge_background(source)
inference = infer_lattice(source, target_size=target_size, device=device)
analysis = analyze_source(source, seed=seed, device=device if reconstruction_mode in {"tile-graph", "hybrid"} else None)
inference = _select_phase_candidate(
inference, cached_reconstruction = _select_phase_candidate_with_reconstruction(
source,
inference,
analysis=analysis,
@ -63,16 +67,21 @@ def run_pipeline(
solver_params=solver_params,
reconstruction_mode=reconstruction_mode,
)
solver, reconstruction_diagnostics = _run_reconstruction(
source,
inference=inference,
analysis=analysis,
steps=steps,
seed=seed,
device=device,
solver_params=solver_params,
reconstruction_mode=reconstruction_mode,
)
if cached_reconstruction is not None:
solver, reconstruction_diagnostics = cached_reconstruction
reconstruction_diagnostics = dict(reconstruction_diagnostics)
reconstruction_diagnostics["reused_phase_probe_reconstruction"] = True
else:
solver, reconstruction_diagnostics = _run_reconstruction(
source,
inference=inference,
analysis=analysis,
steps=steps,
seed=seed,
device=device,
solver_params=solver_params,
reconstruction_mode=reconstruction_mode,
)
cleanup = cleanup_pixels(solver.target_rgba, source_guidance=solver.guidance_strength)
palette = load_palette(palette_path) if palette_path else None
palette_result = quantize_rgba(cleanup.cleaned_rgba, mode=palette_mode, palette=palette)
@ -138,9 +147,31 @@ def _select_phase_candidate(
solver_params: SolverHyperParams | None = None,
reconstruction_mode: str = "continuous",
) -> InferenceResult:
selected, _ = _select_phase_candidate_with_reconstruction(
source,
inference,
analysis=analysis,
seed=seed,
device=device,
solver_params=solver_params,
reconstruction_mode=reconstruction_mode,
)
return selected
def _select_phase_candidate_with_reconstruction(
source: np.ndarray,
inference: InferenceResult,
*,
analysis,
seed: int,
device: str,
solver_params: SolverHyperParams | None = None,
reconstruction_mode: str = "continuous",
):
solver_params = solver_params or SolverHyperParams()
if len(inference.top_candidates) <= 1 or inference.confidence >= solver_params.phase_rerank_confidence_threshold:
return inference
return inference, None
top_score = float(inference.top_candidates[0].score)
candidate_records: list[dict[str, float | InferenceResult]] = []
@ -153,7 +184,7 @@ def _select_phase_candidate(
confidence=inference.confidence,
top_candidates=inference.top_candidates,
)
candidate_artifacts, _ = _run_reconstruction(
candidate_artifacts, candidate_diagnostics = _run_reconstruction(
source,
inference=candidate_inference,
analysis=analysis,
@ -181,11 +212,12 @@ def _select_phase_candidate(
"edge_concentration": foreground_edge_concentration(candidate_artifacts.target_rgba),
"inference_penalty": top_score - float(candidate.score),
"size_delta_ratio": _size_delta_ratio(inference, candidate_inference),
"cached_reconstruction": (candidate_artifacts, candidate_diagnostics),
}
)
if not candidate_records:
return inference
return inference, None
support_penalty = _normalize_penalty(record["support_score"] for record in candidate_records)
edge_position_penalty = _normalize_penalty(record["edge_position_error"] for record in candidate_records)
@ -203,6 +235,8 @@ def _select_phase_candidate(
baseline_rank: float | None = None
best_rank = float("inf")
best_candidate = inference
best_cached_reconstruction = None
baseline_cached_reconstruction = None
annotated_candidates = []
for index, record in enumerate(candidate_records):
candidate_inference = record["inference"]
@ -238,9 +272,11 @@ def _select_phase_candidate(
)
if baseline_rank is None:
baseline_rank = rank
baseline_cached_reconstruction = record.get("cached_reconstruction")
if rank < best_rank:
best_rank = rank
best_candidate = record["inference"]
best_cached_reconstruction = record.get("cached_reconstruction")
annotated_candidates.sort(key=lambda candidate: float(candidate.breakdown.get("phase_rerank_score", float("inf"))))
for rank, candidate in enumerate(annotated_candidates, start=1):
candidate.breakdown["phase_rerank_rank"] = float(rank)
@ -255,7 +291,7 @@ def _select_phase_candidate(
)
if baseline_rank is None or best_rank > baseline_rank - solver_params.phase_rerank_margin:
if annotated_candidates:
return InferenceResult(
selected = InferenceResult(
target_width=inference.target_width,
target_height=inference.target_height,
phase_x=inference.phase_x,
@ -263,8 +299,11 @@ def _select_phase_candidate(
confidence=inference.confidence,
top_candidates=annotated_candidates,
)
return inference
return best_candidate
cached = baseline_cached_reconstruction if _reuse_phase_probe_reconstruction(reconstruction_mode) else None
return selected, cached
return inference, None
cached = best_cached_reconstruction if _reuse_phase_probe_reconstruction(reconstruction_mode) else None
return best_candidate, cached
def _normalize_penalty(values, *, higher_is_better: bool = False) -> list[float]:

View file

@ -322,6 +322,85 @@ def test_pipeline_hybrid_mode_writes_reconstruction_diagnostics(tmp_path: Path)
assert result.diagnostics["reconstruction"]["mode"] == "hybrid"
def test_pipeline_reuses_phase_probe_reconstruction_for_tile_graph(tmp_path: Path, monkeypatch) -> None:
source = np.zeros((6, 6, 4), dtype=np.float32)
source[..., 3] = 1.0
input_path = tmp_path / "input.png"
output_path = tmp_path / "output.png"
from repixelizer.io import save_rgba
save_rgba(input_path, source)
candidate_a = InferenceCandidate(target_width=3, target_height=3, phase_x=0.0, phase_y=0.0, score=0.91, breakdown={})
candidate_b = InferenceCandidate(target_width=4, target_height=4, phase_x=0.2, phase_y=-0.2, score=0.90, breakdown={})
inference = InferenceResult(
target_width=3,
target_height=3,
phase_x=0.0,
phase_y=0.0,
confidence=0.0,
top_candidates=[candidate_a, candidate_b],
)
class DummyAnalysis:
cluster_preview = np.zeros((6, 6, 4), dtype=np.float32)
call_count = {"tile_graph": 0}
def fake_optimize_tile_graph(
source_rgba,
inference,
analysis,
steps,
seed,
device,
solver_params=None,
geometry_reference_rgba=None,
geometry_guidance_strength=None,
):
del source_rgba, analysis, steps, seed, device, solver_params, geometry_reference_rgba, geometry_guidance_strength
call_count["tile_graph"] += 1
rgba = np.zeros((inference.target_height, inference.target_width, 4), dtype=np.float32)
rgba[..., 3] = 1.0
rgba[..., 0] = 0.2 if inference.target_width == 3 else 0.8
return (
SolverArtifacts(
target_rgba=rgba,
uv_field=np.zeros((inference.target_height, inference.target_width, 2), dtype=np.float32),
guidance_strength=np.zeros((inference.target_height, inference.target_width), dtype=np.float32),
initial_rgba=rgba.copy(),
loss_history=[],
),
{"mode": "tile-graph", "tile_graph_candidate_count": 1},
)
def fake_support(source_rgba, output_rgba, *, target_width, target_height, phase_x, phase_y):
del source_rgba, output_rgba, target_height, phase_x, phase_y
return {"score": 0.05 if target_width == 3 else 0.15}
monkeypatch.setattr("repixelizer.pipeline.infer_lattice", lambda *args, **kwargs: inference)
monkeypatch.setattr("repixelizer.pipeline.analyze_source", lambda *args, **kwargs: DummyAnalysis())
monkeypatch.setattr("repixelizer.pipeline.optimize_tile_graph", fake_optimize_tile_graph)
monkeypatch.setattr("repixelizer.pipeline.source_lattice_consistency_breakdown", fake_support)
monkeypatch.setattr("repixelizer.pipeline.foreground_edge_position_error", lambda *args, **kwargs: 0.1)
monkeypatch.setattr("repixelizer.pipeline.foreground_stroke_wobble_error", lambda *args, **kwargs: 0.5)
monkeypatch.setattr("repixelizer.pipeline.foreground_edge_concentration", lambda *args, **kwargs: 0.2)
result = run_pipeline(
input_path,
output_path,
reconstruction_mode="tile-graph",
steps=200,
device="cpu",
)
assert output_path.exists()
assert call_count["tile_graph"] == 2
assert result.diagnostics["reconstruction"]["reused_phase_probe_reconstruction"] is True
assert result.output_rgba.shape[:2] == (3, 3)
def test_phase_rerank_can_accept_low_confidence_size_jump_with_strong_support(monkeypatch) -> None:
source = np.zeros((16, 16, 4), dtype=np.float32)
candidate_a = InferenceCandidate(target_width=16, target_height=16, phase_x=0.0, phase_y=0.0, score=0.91, breakdown={})