PhotoBlaze-PIH / export_pih.py
JeremySD99's picture
Publish PhotoBlaze trained PIH ONNX models
8704dd8 verified
Raw History Blame Contribute Delete
5.99 kB
"""Export Adobe PIH's two networks without its browser-incompatible 5D LUT op.
Research only: outputs stay in ignored models/, not the production bundle.
Run with models/pih-env/Scripts/python experiments/match-to-scene/export_pih.py.
"""
from pathlib import Path
import argparse
import hashlib
import json
import optparse
import sys
import time
import numpy as np
import onnxruntime as ort
import torch
ROOT = Path(__file__).resolve().parents[2]
SOURCE = ROOT / "models" / "PIH"
OUTPUT = ROOT / "models" / "match-to-scene"
sys.path.insert(0, str(SOURCE))
from model import Model_Composite_PL, Model_Composite_PL_NoBG
class CompositeMaskInput(torch.nn.Module):
"""Keep the browser input layout while dropping the separate background."""
def __init__(self, network, *, gain=False):
super().__init__()
self.network = network
self.gain = gain
def forward(self, inputs):
composite = inputs[:, :3]
mask = inputs[:, 6:7]
if self.gain:
# The browser blends the intermediate against the background.
# This PIH variant blends it against the composite instead.
intermediate = inputs[:, 7:] + (composite - inputs[:, 3:6]) * (1 - mask)
return self.network(torch.cat((composite, mask, intermediate), dim=1))
return self.network(torch.cat((composite, mask), dim=1))
class Curves(torch.nn.Module):
def __init__(self, network):
super().__init__()
self.network = network
def forward(self, inputs):
return self.network(inputs)[0].reshape(1, 3, 32)
def apply_curves(curves, image):
# Exact align_corners=False / border behavior of the upstream separable LUT.
positions = (image * 32 - 0.5).clamp(0, 31)
lo = positions.floor().long()
hi = (lo + 1).clamp(max=31)
flat = curves.reshape(3, 32)
low = torch.gather(flat, 1, lo.reshape(3, -1)).reshape_as(image)
high = torch.gather(flat, 1, hi.reshape(3, -1)).reshape_as(image)
return low + (high - low) * (positions - lo)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--checkpoint", type=Path, default=SOURCE / "ckpt_g39.pth")
parser.add_argument("--output", type=Path, default=OUTPUT)
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
torch.manual_seed(7)
torch.serialization.add_safe_globals([optparse.Values])
checkpoint = args.checkpoint
state = torch.load(checkpoint, map_location="cpu", weights_only=True)
weights = state.get("state_dict", state)
no_background = weights["PL.conv1.weight"].shape[1] == 4
architecture = Model_Composite_PL_NoBG if no_background else Model_Composite_PL
model = architecture(dim=32, masking=True, brush=True, maskoffset=0.6,
swap=True, onlyupsample=True, aggupsample=True)
model.load_state_dict(weights, strict=True)
model.eval()
background = torch.rand(1, 3, 512, 512)
foreground = torch.rand(1, 3, 512, 512)
mask = torch.zeros(1, 1, 512, 512)
mask[:, :, 128:384, 128:384] = 1
mask[:, :, 128:384, 128] = 0.5
image = foreground * mask + background * (1-mask)
with torch.inference_mode():
start = time.perf_counter()
native_inputs = (image, mask) if no_background else (background, image, mask)
intermediate = model(*native_inputs)[0]
native_seconds = time.perf_counter() - start
inputs = torch.cat((image, background, mask), 1)
curve_model = Curves(model.PL)
gain_model = model.gainnet
if no_background:
curve_model = CompositeMaskInput(curve_model)
gain_model = CompositeMaskInput(gain_model, gain=True)
curve_model.eval()
gain_model.eval()
curves = curve_model(inputs)
outside = image if no_background else background
reconstructed = apply_curves(curves, image)*mask + outside*(1-mask)
lut_error = float((intermediate-reconstructed).abs().max())
assert lut_error < 1e-5, lut_error
browser_intermediate = apply_curves(curves, image)*mask + background*(1-mask)
gain_inputs = torch.cat((image, background, mask, browser_intermediate), 1)
if no_background:
native_gain = model.gainnet(torch.cat((image, mask, intermediate), 1))
torch.testing.assert_close(gain_model(gain_inputs), native_gain, atol=1e-5, rtol=1e-5)
reports = {}
for name, network, sample, output_name in [
("curves", curve_model, inputs, "curves"),
("gain", gain_model, gain_inputs, "gain"),
]:
path = args.output / f"{name}.onnx"
torch.onnx.export(network, sample, str(path), input_names=["inputs"],
output_names=[output_name], opset_version=17,
dynamo=False)
session = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
start = time.perf_counter()
actual = session.run(None, {"inputs": sample.numpy()})[0]
elapsed = time.perf_counter()-start
expected = network(sample).numpy()
error = float(np.max(np.abs(actual-expected)))
assert np.isfinite(actual).all()
assert error < 1e-4, (name, error)
reports[name] = {"bytes": path.stat().st_size, "seconds": elapsed,
"max_absolute_error": error,
"sha256": hashlib.sha256(path.read_bytes()).hexdigest()}
report = {"checkpoint_sha256": hashlib.sha256(checkpoint.read_bytes()).hexdigest(),
"native_seconds": native_seconds, "lut_max_absolute_error": lut_error,
"networks": reports, "validation": "synthetic inputs; native CPU only"}
(args.output / "validation.json").write_text(json.dumps(report, indent=2))
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()