Download validate.py from raphtlw/siglip2-so400m-patch16-384-coreml: direct link, hf CLI and curl.
- Browser
- Download file 2.71 kB
-
https://huggingface.co/raphtlw/siglip2-so400m-patch16-384-coreml/resolve/main/validate.py
- Command line
-
hf download hf://raphtlw/siglip2-so400m-patch16-384-coreml/validate.py
-
curl -L -o validate.py https://huggingface.co/raphtlw/siglip2-so400m-patch16-384-coreml/resolve/main/validate.py
2.71 kB
| import json | |
| import sys | |
| from pathlib import Path | |
| import coremltools as ct | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| from transformers import AutoModel, AutoProcessor | |
| from convert import IMAGE_SIDE, MODEL, REVISION, TEXT_LENGTH | |
| models = Path(sys.argv[1]) | |
| photos = sorted(Path(sys.argv[2]).glob("*.jpg")) | |
| queries = [ | |
| "laksa", "noodle soup", "a cat", "bridge over the sea at sunset", "hawker centre food stalls", | |
| "hotel with a boat on the roof", "叻沙", "猫", "kucing", "jambatan", "a car", | |
| ] | |
| processor = AutoProcessor.from_pretrained(MODEL, revision=REVISION) | |
| model = AutoModel.from_pretrained(MODEL, revision=REVISION, dtype=torch.float32, attn_implementation="eager").eval() | |
| image_model = ct.models.MLModel(str(models / "siglip2_image.mlpackage"), compute_units=ct.ComputeUnit.CPU_AND_NE) | |
| text_model = ct.models.MLModel(str(models / "siglip2_text.mlpackage"), compute_units=ct.ComputeUnit.CPU_AND_NE) | |
| def normalized(vector): | |
| vector = np.asarray(vector, dtype=np.float32).reshape(-1) | |
| return vector / np.linalg.norm(vector) | |
| def features(output): | |
| return output if isinstance(output, torch.Tensor) else output.pooler_output | |
| images = {} | |
| for path in photos: | |
| picture = Image.open(path).convert("RGB") | |
| with torch.no_grad(): | |
| reference = normalized(features(model.get_image_features(**processor(images=picture, return_tensors="pt")))) | |
| resized = picture.resize((IMAGE_SIDE, IMAGE_SIDE), Image.BILINEAR) | |
| converted = normalized(image_model.predict({"image": resized})["embedding"]) | |
| print(f"image {path.stem}: Core ML against PyTorch {float(reference @ converted):.4f}") | |
| images[path.stem] = converted | |
| texts = {} | |
| tokens = {} | |
| for query in queries: | |
| text = query.lower() | |
| encoded = processor(text=[text], padding="max_length", max_length=TEXT_LENGTH, return_tensors="pt") | |
| with torch.no_grad(): | |
| reference = normalized(features(model.get_text_features(input_ids=encoded["input_ids"]))) | |
| ids = encoded["input_ids"].numpy().astype(np.int32) | |
| converted = normalized(text_model.predict({"text": ids})["embedding"]) | |
| print(f"text {query}: Core ML against PyTorch {float(reference @ converted):.4f}") | |
| texts[query] = converted | |
| tokens[text] = [int(value) for value in ids[0] if value != 0] | |
| names = list(images) | |
| print("query".ljust(34) + " ".join(name[:10].ljust(10) for name in names)) | |
| for query in queries: | |
| row = " ".join(f"{float(texts[query] @ images[name]):.3f}".ljust(10) for name in names) | |
| print(query.ljust(34) + row) | |
| (models / "token-checks.json").write_text(json.dumps(tokens, ensure_ascii=False, indent=1)) | |
| print("pad id", processor.tokenizer.pad_token_id, "eos id", processor.tokenizer.eos_token_id) | |