Repository navigation
How to match PatchCore ONNX inference score with ckpt inference score? #3644
|
Hi Anomalib team, First of all, thank you to the Anomalib team for providing such a powerful tool for industrial use. Environment
Results Comparison (same image, same model)Pre-processor (from model.pre_processor)ONNX Output NodesTraining Codedatamodule = Folder(
name="Epoch/Product1",
root="./datasets/Epoch/Product1",
normal_dir="train/good",
normal_test_dir="test/good",
abnormal_dir="test/defect",
test_split_mode="from_dir",
val_split_mode="same_as_test",
train_batch_size=8,
eval_batch_size=8,
)
model = Patchcore(
backbone="wide_resnet101_2",
num_neighbors=2,
coreset_sampling_ratio=0.3,
)
engine = Engine(max_epochs=1)
engine.fit(datamodule=datamodule, model=model)
engine.export(
model=model,
export_type=ExportType.ONNX,
ckpt_path="path/to/model.ckpt",
export_root="path/to/output/",
)ckpt Inference Code (pred_score=0.6543, correct)model = Patchcore(backbone="wide_resnet101_2")
engine = Engine()
dataset = PredictDataset(path="test_image.png")
predictions = engine.predict(
model=model,
dataset=dataset,
ckpt_path="path/to/model.ckpt",
)
print(predictions[0].pred_score) # tensor([0.6543])ONNX Inference Code (pred_score=1.0, incorrect)import cv2
import numpy as np
import onnxruntime as ort
from PIL import Image
# Pre-processing
img_bgr = cv2.imread("test_image.png")
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
pil_img = Image.fromarray(img_rgb)
pil_img = pil_img.resize((256, 256), Image.Resampling.BILINEAR)
img_float = np.array(pil_img).astype(np.float32) / 255.0
mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
img_float = (img_float - mean) / std
img_transposed = np.transpose(img_float, (2, 0, 1))
input_tensor = np.expand_dims(img_transposed, axis=0) # [1, 3, 256, 256]
sess = ort.InferenceSession("model.onnx")
outputs = sess.run(None, {sess.get_inputs()[0].name: input_tensor})
print("pred_score:", outputs[0]) # [1.0] ← incorrect
print("pred_label:", outputs[1]) # [True]What I have investigated
Questions
|
Replies: 5 comments
|
Hi @ricklina90, I also have the same issue when exporting to ONNX. Have you found a solution? |
|
I managed to get sameish outputs when comparing the output of the trained model and the ONNX export in the debugger. dataset = PredictDataset(path=TEST_IMAGE_PATH)
predictions = engine.predict(
model=model,
dataset=dataset,
)and the resulting ONNX export using the following code def validate_onnx_export(onnx_path: Path, sample_image_path: Path, input_size: tuple[int, int] = (256, 256)):
"""Run ONNXRuntime inference on one sample image to validate exported model."""
print(f"Validating ONNX model with ONNXRuntime: {onnx_path}")
session = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
input_meta = session.get_inputs()[0]
# Build input tensor from an RGB image as NCHW (1, 3, H, W).
image = Image.open(sample_image_path).convert("RGB").resize(input_size)
image_np = np.asarray(image)
image_chw = np.transpose(image_np, (2, 0, 1))[None, ...]
if input_meta.type == "tensor(float)":
input_tensor = image_chw.astype(np.float32) / 255.0
elif input_meta.type == "tensor(uint8)":
input_tensor = image_chw.astype(np.uint8)
else:
raise ValueError(f"Unsupported ONNX input type: {input_meta.type}")
outputs = session.run(None, {input_meta.name: input_tensor})
print("ONNXRuntime inference successful.")
print(f" Input name: {input_meta.name}")
print(f" Input type: {input_meta.type}")
print(f" Input shape: {input_tensor.shape}")
print(f" Number of outputs: {len(outputs)}")
for idx, out in enumerate(outputs):
out_arr = np.asarray(out)
print(
f" Output[{idx}] shape={out_arr.shape}, dtype={out_arr.dtype}, "
f"min={out_arr.min():.6f}, max={out_arr.max():.6f}"
)
return outputsI compared |
|
@ricklina90 thanks for the detailed reproducer and @kirillmeisser thanks for investigating. @ricklina90 the root cause is double normalization. The exported ONNX graph traces The Meanwhile, on the checkpoint path ( Your inference script normalizes the tensor with the ImageNet stats before feeding it to ONNX Runtime. The baked-in The reason your The exported ONNX model expects a raw img = Image.open(img_path).convert("RGB")
x = np.array(img, dtype=np.float32) / 255.0 # keep [0, 1]
x = np.transpose(x, (2, 0, 1))[None, ...] # NCHW
# do NOT subtract ImageNet mean / divide by std — the ONNX graph already does this
sess = ort.InferenceSession(str(onnx_path))
out = sess.run(None, {sess.get_inputs()[0].name: x}) |
|
Thank you all for the help and investigation! Following the suggestion to remove the ImageNet mean/std normalization, Results Comparison (same image, same model)
The pred_score is closer than before (previously always 1.0), Test files for reproduction: Download Folder structure after extraction: Note: Please update the paths in Environment:
I apologize if my testing is insufficient or if I am missing something. |
|
Hi @ashwinvaidya17, Thank you for your previous explanation about double normalization. I have followed your suggestion as described here: However, after removing the ImageNet mean/std normalization from my inference script, the pred_score still does not match the ckpt result:
I have uploaded test files (model.ckpt, model.onnx, test image, and inference script) to OneDrive for reproduction: Could you please advise what the correct inference pipeline should be? |
I managed to get sameish outputs when comparing the output of the trained model and the ONNX export in the debugger.
and the resulting ONNX export using the following code