File size: 26,593 Bytes
790d9ba | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 | """Synthetic checks for the diffusion refinement pass.
No model downloads, no GPU, no server -- pure numpy/PIL, runs in about a
second. Covers everything in services/refine except the SDXL call itself.
py -3.12 scripts/test_refine.py
The invariant worth caring about most is the last section: a refinement pass
must not change a single pixel outside its own mask. Everything else is
quality; that one is correctness, and it is asserted at runtime too.
"""
from __future__ import annotations
import base64
import pathlib
import sys
import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
import numpy as np
from PIL import Image
from services.refine.assets import (
read_refine_assets,
refine_assets_path,
surface_masks_from_bundle,
write_refine_assets,
)
from services.refine.diffusion import get_processing_size
from services.refine.grouping import group_surfaces_by_material
from services.refine.guide import apply_diffusion_as_realism_guide, recover_detail
from services.refine.masks import (
composite_surface_only,
make_binary_mask,
mask_coverage,
mask_to_bool,
outside_mask_difference,
prepare_safe_diffusion_mask,
)
from services.refine.photometric import (
add_camera_noise,
apply_shadow_map,
enhance_material_microdetail,
extract_shadow_map,
prepare_depth,
transfer_original_lighting,
)
from services.refine.profiles import (
LIGHTING_TRANSFER_STRENGTH,
MATERIALS,
MAX_LIGHT_RATIO,
MIN_LIGHT_RATIO,
MIN_SHADOW_RATIO,
SHADOW_TRANSFER_STRENGTH,
SURFACE_KINDS,
build_prompts,
detail_recovery_for,
normalize_material_type,
normalize_surface_kind,
)
H, W = 240, 320
FLOOR = (slice(150, 240), slice(0, 320))
WALL_LEFT = (slice(20, 150), slice(0, 150))
WALL_RIGHT = (slice(20, 150), slice(170, 320))
failures: list[str] = []
def check(label: str, condition: bool, detail: str = "") -> None:
if condition:
print(f" PASS {label}")
else:
failures.append(label)
print(f" FAIL {label}" + (f" ({detail})" if detail else ""))
def mask_of(*regions) -> np.ndarray:
mask = np.zeros((H, W), dtype=np.uint8)
for region in regions:
mask[region] = 1
return mask
def room_photo() -> Image.Image:
"""A toy room: bright wall, darker floor, a light gradient across it."""
rgb = np.zeros((H, W, 3), dtype=np.uint8)
rgb[:, :] = (90, 90, 95)
rgb[WALL_LEFT] = (185, 182, 175)
rgb[WALL_RIGHT] = (185, 182, 175)
rgb[FLOOR] = (120, 105, 88)
gradient = np.linspace(0.72, 1.18, W, dtype=np.float32)[None, :, None]
return Image.fromarray(np.clip(rgb * gradient, 0, 255).astype(np.uint8), mode="RGB")
def tiled_composite(original: Image.Image, mask: np.ndarray) -> Image.Image:
"""The original with a flat, evenly lit "tile" pasted into the mask."""
array = np.array(original, dtype=np.uint8, copy=True)
inside = mask > 0
array[inside] = (196, 190, 178)
return Image.fromarray(array, mode="RGB")
def main() -> int:
original = room_photo()
floor_mask = mask_of(FLOOR)
composite = tiled_composite(original, floor_mask)
print("\nProfiles")
check("every material defines both surface kinds",
all(kind in MATERIALS[m] for m in MATERIALS for kind in SURFACE_KINDS),
str([(m, k) for m in MATERIALS for k in SURFACE_KINDS if k not in MATERIALS[m]]))
check("numeric tuning is shared, not duplicated per kind",
all("diffusion_strength" in MATERIALS[m] and "diffusion_strength" not in MATERIALS[m]["wall"]
for m in MATERIALS))
# Guidance and controlnet are still the reference script's. Only strength
# and steps moved, and only for the two outliers: at 0.46 and 0.36 they let
# SDXL invent veining and grain instead of photographing the tile that was
# actually applied, and they cost 3-6x every other material. Reference
# values kept here so the change stays visible and reversible.
check("wood keeps the reference guidance and controlnet",
MATERIALS["wood"]["guidance"] == 3.0
and MATERIALS["wood"]["controlnet"] == 0.15)
check("wood strength is reduced from the reference 0.36",
MATERIALS["wood"]["diffusion_strength"] == 0.18
and MATERIALS["wood"]["steps"] == 22)
check("marble keeps the reference controlnet",
MATERIALS["marble"]["controlnet"] == 0.25)
check("marble strength is reduced from the reference 0.46",
MATERIALS["marble"]["diffusion_strength"] == 0.20
and MATERIALS["marble"]["steps"] == 22)
check("the conservative materials are untouched",
all(MATERIALS[m]["diffusion_strength"] == v for m, v in
(("porcelain", 0.09), ("ceramic", 0.09), ("stone", 0.10),
("laminate", 0.09), ("vinyl", 0.09), ("carpet", 0.12),
("concrete", 0.10), ("generic", 0.09))),
"only the two outliers were meant to move")
check("unknown material falls back to generic",
normalize_material_type("brushed-titanium") == "generic")
check("missing material falls back to generic", normalize_material_type(None) == "generic")
check("material lookup is case and space insensitive",
normalize_material_type(" MarBle ") == "marble")
check("unknown surface kind falls back to floor",
normalize_surface_kind("ceiling") == "floor")
floor_prompt, floor_negative, wood = build_prompts("wood", "floor")
wall_prompt, wall_negative, wood_again = build_prompts("wood", "wall")
check("floor and wall share one profile object", wood is wood_again)
check("floor prompt talks about flooring", "flooring" in floor_prompt.lower())
check("wall prompt does not talk about flooring",
"flooring" not in wall_prompt.lower() and "floor contact" not in wall_prompt.lower())
# Was: asserts the wall prompt says "panelling". That is itself a claim
# about what the wall is made of, which is the thing the generic prompt
# deliberately refuses to make. Panel seams are covered generically by
# "preserve exact pattern and tile layout" plus "keep every existing seam,
# joint and boundary exactly where it is".
check("wall prompt talks about walls",
"wall" in wall_prompt.lower() and "ceiling" in wall_prompt.lower())
check("wall negative guards the ceiling join",
"wall bleeding into ceiling" in wall_negative.lower())
check("floor negative guards the wall join",
"floor bleeding into wall" in floor_negative.lower())
check("material description is threaded into the prompt",
"warm grey veining" in build_prompts("marble", "wall", "warm grey veining")[0])
check("wood gets the strongest pattern recovery",
detail_recovery_for("wood")["pattern"] > detail_recovery_for("porcelain")["pattern"])
print("\nMasks")
binary = make_binary_mask(np.full((H, W), 200, dtype=np.uint8))
check("threshold produces only 0 and 255",
set(np.unique(np.asarray(binary))).issubset({0, 255}))
soft = np.zeros((H, W), dtype=np.uint8)
soft[FLOOR] = 127
check("just-below-threshold is excluded", not mask_to_bool(soft).any())
soft[FLOOR] = 128
check("exactly-at-threshold is included", mask_to_bool(soft)[FLOOR].all())
# Regression. The reference script only ever saw masks decoded from a JPEG,
# so it assumed 0/255. Internal masks are 0/1 uint8, and thresholding those
# at 128 emptied them -- which turned every later stage into a silent no-op
# rather than an error, so the output looked merely unimproved.
check("a 0/1 uint8 mask is not thresholded away", mask_to_bool(mask_of(FLOOR))[200, 160])
check("a boolean mask is accepted", mask_to_bool(mask_of(FLOOR).astype(bool))[200, 160])
check("a 0/255 mask still works", mask_to_bool(mask_of(FLOOR) * 255)[200, 160])
check("a float 0..1 mask is accepted",
mask_to_bool(mask_of(FLOOR).astype(np.float32))[200, 160])
check("a 0/1 mask composites for real",
(np.asarray(composite_surface_only(
original, Image.fromarray(np.full((H, W, 3), 255, np.uint8), "RGB"),
mask_of(FLOOR)))[FLOOR] == 255).all())
safe = prepare_safe_diffusion_mask(floor_mask, edge_guard=8)
safe_np = np.asarray(safe) >= 128
check("edge guard shrinks the mask", safe_np.sum() < floor_mask.sum())
check("edge guard keeps the interior", safe_np[200, 160])
check("edge guard clears the boundary row", not safe_np[150, 160])
check("coverage is reported as a sane fraction",
0.4 < mask_coverage(safe, floor_mask) < 1.0,
f"{mask_coverage(safe, floor_mask):.3f}")
check("a mask thinner than the guard survives as empty rather than crashing",
np.asarray(prepare_safe_diffusion_mask(mask_of((slice(10, 14), slice(10, 300))), 8)).sum() == 0)
print("\nPhotometric stages")
lit = transfer_original_lighting(original, composite, floor_mask, sigma=35, strength=0.5)
original_np = np.asarray(original).astype(int)
composite_np = np.asarray(composite).astype(int)
lit_np = np.asarray(lit).astype(int)
outside = ~mask_to_bool(floor_mask)
check("lighting transfer leaves outside pixels untouched",
np.array_equal(lit_np[outside], composite_np[outside]))
left_before = abs(composite_np[200, 20].mean() - original_np[200, 20].mean())
left_after = abs(lit_np[200, 20].mean() - original_np[200, 20].mean())
check("lighting transfer moves the tile toward the room's brightness",
left_after < left_before, f"{left_before:.1f} -> {left_after:.1f}")
shadow_map = extract_shadow_map(original, floor_mask, blur_sigma=22, strength=0.58)
check("shadow map never brightens", shadow_map.max() <= 1.0 + 1e-6)
check("shadow map is clamped from below", shadow_map.min() >= 0.58 - 1e-6)
check("shadow map is neutral outside the mask", np.allclose(shadow_map[outside], 1.0))
shadowed = np.asarray(apply_shadow_map(composite, floor_mask, shadow_map)).astype(int)
check("shadow application leaves outside pixels untouched",
np.array_equal(shadowed[outside], composite_np[outside]))
detailed = np.asarray(
enhance_material_microdetail(composite, floor_mask, 0.12, 0.015)).astype(int)
check("microdetail leaves outside pixels untouched",
np.array_equal(detailed[outside], composite_np[outside]))
noisy = np.asarray(add_camera_noise(composite, floor_mask, 0.2, seed=42)).astype(int)
check("camera noise leaves outside pixels untouched",
np.array_equal(noisy[outside], composite_np[outside]))
check("camera noise is reproducible for a fixed seed",
np.array_equal(noisy, np.asarray(
add_camera_noise(composite, floor_mask, 0.2, seed=42)).astype(int)))
ramp = np.tile(np.linspace(20, 220, W, dtype=np.uint8), (H, 1))
depth_rgb = np.asarray(prepare_depth(Image.fromarray(ramp, mode="L")))
check("depth is normalised to the full 8-bit range",
depth_rgb.min() == 0 and depth_rgb.max() == 255)
check("depth is expanded to three channels", depth_rgb.shape == (H, W, 3))
flat = np.asarray(prepare_depth(Image.fromarray(np.full((H, W), 77, np.uint8), mode="L")))
check("a constant depth map does not divide by zero", np.isfinite(flat).all())
print("\nBlending")
generated = Image.fromarray(
np.clip(np.asarray(composite).astype(np.float32) * 1.06, 0, 255).astype(np.uint8), "RGB")
recovered = recover_detail(generated, composite, "wood")
check("detail recovery returns the same size", recovered.size == composite.size)
check("detail recovery stays in gamut",
np.asarray(recovered).min() >= 0 and np.asarray(recovered).max() <= 255)
guided = apply_diffusion_as_realism_guide(composite, generated, floor_mask)
check("realism guide leaves outside pixels untouched",
np.array_equal(np.asarray(guided).astype(int)[outside], composite_np[outside]))
check("realism guide changes less than raw diffusion",
np.abs(np.asarray(guided).astype(int) - composite_np).mean()
< np.abs(np.asarray(generated).astype(int) - composite_np).mean())
print("\nStrict compositing")
wild = Image.fromarray(np.full((H, W, 3), 255, np.uint8), "RGB")
strict = composite_surface_only(original, wild, floor_mask)
check("compositing takes refined pixels inside the mask",
(np.asarray(strict)[FLOOR] == 255).all())
check("compositing takes base pixels outside the mask",
outside_mask_difference(strict, original, floor_mask) == 0)
smaller = wild.resize((W // 2, H // 2), Image.Resampling.LANCZOS)
check("a differently sized refinement is resized rather than rejected",
composite_surface_only(original, smaller, floor_mask).size == original.size)
check("an empty mask is a no-op",
outside_mask_difference(
composite_surface_only(original, wild, np.zeros((H, W), np.uint8)),
original, np.zeros((H, W), np.uint8)) == 0)
print("\nMaterial grouping")
groups = group_surfaces_by_material(
[
{"segmentIds": [0], "materialType": "wood", "surfaceKind": "floor"},
{"segmentIds": [1, 2], "materialType": "marble", "surfaceKind": "wall"},
],
{0: mask_of(FLOOR), 1: mask_of(WALL_LEFT), 2: mask_of(WALL_RIGHT)},
)
check("one group per material", len(groups) == 2, f"got {len(groups)}")
check("walls sharing a material are unioned",
int(groups[1]["mask"].sum()) == int(mask_of(WALL_LEFT, WALL_RIGHT).sum()))
check("groups are disjoint",
not (groups[0]["mask"].astype(bool) & groups[1]["mask"].astype(bool)).any())
check("surface kind rides along with the group", groups[1]["surfaceKind"] == "wall")
same = group_surfaces_by_material(
[
{"segmentIds": [0], "materialType": "marble", "surfaceKind": "floor"},
{"segmentIds": [1], "materialType": "marble", "surfaceKind": "wall"},
],
{0: mask_of(FLOOR), 1: mask_of(WALL_LEFT)},
)
check("one material on two planes stays two groups, not one",
len(same) == 2, f"got {len(same)} — floor and wall prompts must not merge")
merged = group_surfaces_by_material(
[
{"segmentIds": [1], "materialType": "marble", "surfaceKind": "wall"},
{"segmentIds": [2], "materialType": "marble", "surfaceKind": "wall"},
],
{1: mask_of(WALL_LEFT), 2: mask_of(WALL_RIGHT)},
)
check("same material and same kind collapses to one pass", len(merged) == 1)
check("unknown segment ids are skipped rather than crashing",
group_surfaces_by_material(
[{"segmentIds": [0, 99], "materialType": "wood", "surfaceKind": "floor"}],
{0: mask_of(FLOOR)})[0]["mask"].sum() == mask_of(FLOOR).sum())
check("a group with no resolvable mask is dropped",
group_surfaces_by_material(
[{"segmentIds": [99], "materialType": "wood", "surfaceKind": "floor"}],
{0: mask_of(FLOOR)}) == [])
check("an empty request yields no groups", group_surfaces_by_material([], {}) == [])
print("\nRefinement asset side-car")
job_id = "test-refine-" + uuid.uuid4().hex[:8]
depth_in = np.linspace(0.8, 6.4, H * W, dtype=np.float32).reshape(H, W)
depth_in[0, 0] = np.nan # MoGe leaves holes where geometry is unresolved
try:
written = write_refine_assets(
job_id, depth_in,
{0: mask_of(FLOOR), 1: mask_of(WALL_LEFT), 2: mask_of(WALL_RIGHT)}, W, H)
check("side-car is written", written is not None and written.exists())
loaded = read_refine_assets(job_id)
check("side-car round-trips every segment", sorted(loaded["masks"]) == [0, 1, 2])
check("masks survive bit-packing exactly",
np.array_equal(loaded["masks"][1], mask_of(WALL_LEFT)))
check("shape is preserved", loaded["masks"][0].shape == (H, W))
check("depth survives as a monotonic uint16",
loaded["depth"].dtype == np.uint16
and loaded["depth"][H - 1, W - 1] > loaded["depth"][H // 2, 0])
check("non-finite depth does not poison the normalisation",
np.isfinite(loaded["depth"]).all())
raw_bytes = H * W * 4 + 3 * H * W # float32 depth + three uint8 masks
check("side-car is much smaller than the raw arrays",
written.stat().st_size < raw_bytes // 3,
f"{written.stat().st_size} vs {raw_bytes} raw")
finally:
refine_assets_path(job_id).unlink(missing_ok=True)
check("a missing side-car reads as None",
read_refine_assets("test-refine-does-not-exist") is None)
check("no masks means no side-car", write_refine_assets(job_id, None, {}, W, H) is None)
bundle = {
"width": W, "height": H,
"segments": [
{"id": 0, "mask": base64.b64encode(
np.flatnonzero(mask_of(FLOOR).ravel()).astype(np.uint32).tobytes()).decode()},
{"id": 3, "mask": None},
],
}
rebuilt = surface_masks_from_bundle(bundle)
check("bundle indices rebuild into masks", np.array_equal(rebuilt[0], mask_of(FLOOR)))
check("a segment with no mask is skipped", 3 not in rebuilt)
print("\nProcessing size")
check("a large image is scaled under the cap", get_processing_size(1920, 1080, 896)[0] == 896)
check("sizes are multiples of eight",
all(value % 8 == 0 for value in get_processing_size(1920, 1080, 896)))
# Rounding to the VAE's multiple of 8 can nudge a dimension up by a few px
# (300 -> 304). Harmless: the result is composited back at full resolution.
check("a small image is not scaled down", get_processing_size(400, 300, 896) == (400, 304))
check("rounding never moves a dimension by more than 8px",
all(abs(a - b) < 8 for a, b in zip(get_processing_size(400, 300, 896), (400, 300))))
check("aspect ratio is held to within a pixel of the eight-grid",
abs(get_processing_size(1600, 900, 896)[1] / get_processing_size(1600, 900, 896)[0]
- 900 / 1600) < 0.01)
print("\nGPU swap symmetry")
# Regression. unload_diffusion_pipeline existed but nothing called it, so
# the swap only ran one way: refinement freed the CV models for SDXL, then
# the next conversion reloaded them on top of SDXL's ~9.5 GB and the
# process was OOM-killed. That surfaced as a dead backend, not an error,
# which made it look like a tunnel problem for hours.
loader_source = (pathlib.Path(__file__).resolve().parents[1] / "models" / "loader.py").read_text(encoding="utf-8")
conversion_source = (pathlib.Path(__file__).resolve().parents[1] / "services" / "jobs" / "conversion.py").read_text(encoding="utf-8")
runner_source = (pathlib.Path(__file__).resolve().parents[1] / "services" / "refine" / "runner.py").read_text(encoding="utf-8")
check("loader defines both unload directions",
"def unload_cv_models" in loader_source
and "def unload_diffusion_pipeline" in loader_source)
check("refinement frees the CV models before loading SDXL",
"unload_cv_models()" in runner_source)
check("conversion frees SDXL before the CV models reload",
"unload_diffusion_pipeline()" in conversion_source,
"without this the two model sets co-reside and the process is OOM-killed")
print("\nMulti-pass invariant")
# Two passes over disjoint masks, each writing garbage inside its own area:
# the untouched middle strip and everything else must survive exactly.
working = original
for group in groups:
working = composite_surface_only(
working, Image.fromarray(np.full((H, W, 3), 7, np.uint8), "RGB"), group["mask"])
combined = np.zeros((H, W), np.uint8)
for group in groups:
combined |= group["mask"]
check("after two passes nothing outside the union changed",
outside_mask_difference(working, original, combined) == 0)
check("the gap between the two walls is untouched",
np.array_equal(np.asarray(working)[100, 155:168], np.asarray(original)[100, 155:168]))
# ---------------------------------------------------------------
# Photometric range.
#
# These pin the bug that made refinement look unlit: the transfer rails
# were a correction band for a composite that already carried the room's
# light. Ours is a flat tile paste (enable_shading_transfer is off), so the
# rails have to span real shadow depth, not +/-13%.
# ---------------------------------------------------------------
# ---------------------------------------------------------------
# Generic prompt.
#
# materialType is a keyword guess against the tile's name and it misfires
# on most of the catalogue, so the prompt must not assert what the surface
# is made of. The negatives must not name decorative layouts either: a good
# part of the catalogue *is* checkerboards, and a negative cannot separate
# "do not invent one" from "remove the one that is there".
# ---------------------------------------------------------------
print("\nGeneric prompt")
floor_prompts = {build_prompts(m, "floor")[0] for m in MATERIALS}
floor_negatives = {build_prompts(m, "floor")[1] for m in MATERIALS}
check("one floor prompt is shared by every material",
len(floor_prompts) == 1, f"{len(floor_prompts)} distinct prompts")
check("one floor negative is shared by every material",
len(floor_negatives) == 1, f"{len(floor_negatives)} distinct negatives")
check("floor and wall prompts still differ",
build_prompts("marble", "floor")[0] != build_prompts("marble", "wall")[0],
"plane orientation is known, unlike material, and does change the wording")
banned_material = ("marble", "wood", "porcelain", "ceramic", "vinyl",
"laminate", "carpet", "concrete", "granite", "terrazzo")
banned_layout = ("checkerboard", "herringbone", "parquet", "basket weave",
"mosaic", "brick pattern", "plank")
for kind in SURFACE_KINDS:
text, negative, _ = build_prompts("marble", kind)
hits = [w for w in banned_material if w in text.lower() or w in negative.lower()]
check(f"{kind} prompt names no material",
not hits, f"found {hits}; the material is a guess and may be wrong")
layout_hits = [w for w in banned_layout if w in negative.lower()]
check(f"{kind} negative fights no decorative layout",
not layout_hits,
f"found {layout_hits}; this pushes SDXL off the tile that was applied")
check("numeric tuning stays per material",
MATERIALS["marble"]["diffusion_strength"] != MATERIALS["porcelain"]["diffusion_strength"],
"strength is the real lever and should still vary")
check("a supplied material description still reaches the prompt",
"Calacatta gold" in build_prompts("marble", "floor", "Calacatta gold")[0],
"real description text is trustworthy in a way the keyword guess is not")
print("\nPhotometric range")
darkest = 1.0 + (MIN_LIGHT_RATIO - 1.0) * LIGHTING_TRANSFER_STRENGTH
brightest = 1.0 + (MAX_LIGHT_RATIO - 1.0) * LIGHTING_TRANSFER_STRENGTH
# The bathroom reference needs a p1 ratio of 0.46 and a median of 0.75.
check("lighting transfer can reach a real cast shadow (<= 0.50)",
darkest <= 0.50,
f"effective floor is {darkest:.3f}; shadows get flattened above ~0.6")
check("lighting transfer stays conservative when brightening (<= 1.30)",
brightest <= 1.30,
f"effective ceiling is {brightest:.3f}; brightening a dark tile blows out")
check("brightening rail is tighter than the darkening rail",
(1.0 - darkest) > (brightest - 1.0),
"darkening is the safe direction and should have the wider rail")
shadow_floor = 1.0 - (1.0 - MIN_SHADOW_RATIO) * SHADOW_TRANSFER_STRENGTH
check("shadow transfer can reach at least 30% local darkening",
shadow_floor <= 0.70, f"effective floor is {shadow_floor:.3f}")
# ---------------------------------------------------------------
# Diffusion cost. strength gates the real step count, so it is both the
# speed knob and the how-much-may-SDXL-redesign-the-tile knob.
# ---------------------------------------------------------------
print("\nDiffusion cost")
worst = max(MATERIALS.items(), key=lambda kv: kv[1]["diffusion_strength"] * kv[1]["steps"])
worst_steps = worst[1]["diffusion_strength"] * worst[1]["steps"]
check("no material costs more than 6 real denoise steps",
worst_steps <= 6.0,
f"{worst[0]} costs {worst_steps:.1f}; marble at 0.46x28=12.9 was both "
f"the slowest pass and the one that redesigned the tile")
check("no material is allowed to redraw more than a quarter of the surface",
all(m["diffusion_strength"] <= 0.25 for m in MATERIALS.values()),
"above ~0.25 SDXL stops photographing the applied tile and invents its own")
# ---------------------------------------------------------------
# Model residency. Dropping SDXL means the next refinement re-parses ~7 GB
# off disk, which is the multi-minute "Loading refinement model" wait.
# ---------------------------------------------------------------
print("\nModel residency")
loader_source = (pathlib.Path(__file__).resolve().parents[1] / "models" / "loader.py").read_text(encoding="utf-8")
check("unload parks SDXL in CPU RAM instead of always dropping it",
"diffusion_parked" in loader_source and 'pipe.to("cpu")' in loader_source,
"without parking every refinement pays a full disk reload")
check("a parked pipeline is moved back to the GPU before reuse",
"state.diffusion_pipe.to(state.device)" in loader_source,
"a parked pipeline left on the CPU would run inference at CPU speed")
check("parking is skipped when RAM headroom is unknown or short",
"_available_ram_gb" in loader_source and "REFINE_PARK_MIN_FREE_RAM_GB" in loader_source,
"parking without a RAM check can OOM the host")
print()
if failures:
print(f"{len(failures)} FAILED: {', '.join(failures)}")
return 1
print("All checks passed.")
return 0
if __name__ == "__main__":
sys.exit(main())
|