Publish reviewed NaviSense Spatial Caption research release
Browse filesExact reviewed card and artifacts; source checksums and local validation retained.
Files changed (21)
- .gitattributes+1
- LICENSEAdded+88
- README.mdAdded+94
- assets/caption-pareto.pngAdded
- config.jsonAdded+46
- coreml/CaptionSpatialPoolHeadFloat32.mlpackage/Data/com.apple.CoreML/model.mlmodelAdded+3
- coreml/CaptionSpatialPoolHeadFloat32.mlpackage/Data/com.apple.CoreML/weights/weight.binAdded+3
- coreml/CaptionSpatialPoolHeadFloat32.mlpackage/Manifest.jsonAdded+18
- coreml/MobileCLIPS0SpatialImageFloat16.mlpackage/Data/com.apple.CoreML/model.mlmodelAdded+3
- coreml/MobileCLIPS0SpatialImageFloat16.mlpackage/Data/com.apple.CoreML/weights/weight.binAdded+3
- coreml/MobileCLIPS0SpatialImageFloat16.mlpackage/Manifest.jsonAdded+18
- coreml/README.mdAdded+1
- head.safetensorsAdded+3
- metadata/benchmark.jsonAdded+73
- metadata/training.jsonAdded+49
- metadata/verification.jsonAdded+24
- model.safetensorsAdded+3
- parity-fixtures.npzAdded+3
- requirements.txtAdded+8
- spatial_caption_router.pyAdded+162
- verify.pyAdded+17
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textassets/caption-pareto.png filter=lfs diff=lfs merge=lfs -text
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788Disclaimer: IMPORTANT: This Apple Machine Learning Research Model isspecifically developed and released by Apple Inc. ("Apple") for the sole purposeof scientific research of artificial intelligence and machine-learningtechnology. “Apple Machine Learning Research Model” means the model, includingbut not limited to algorithms, formulas, trained model weights, parameters,configurations, checkpoints, and any related materials (includingdocumentation).
This Apple Machine Learning Research Model is provided to You byApple in consideration of your agreement to the following terms, and your use,modification, creation of Model Derivatives, and or redistribution of the AppleMachine Learning Research Model constitutes acceptance of this Agreement. If Youdo not agree with these terms, please do not use, modify, create ModelDerivatives of, or distribute this Apple Machine Learning Research Model orModel Derivatives.
* License Scope: In consideration of your agreement to abide by the following terms, and subject to these terms, Apple hereby grants you a personal, non-exclusive, worldwide, non-transferable, royalty-free, revocable, and limited license, to use, copy, modify, distribute, and create Model Derivatives (defined below) of the Apple Machine Learning Research Model exclusively for Research Purposes. You agree that any Model Derivatives You may create or that may be created for You will be limited to Research Purposes as well. “Research Purposes” means non-commercial scientific research and academic development activities, such as experimentation, analysis, testing conducted by You with the sole intent to advance scientific knowledge and research. “Research Purposes” does not include any commercial exploitation, product development or use in any commercial product or service.
* Distribution of Apple Machine Learning Research Model and Model Derivatives: If you choose to redistribute Apple Machine Learning Research Model or its Model Derivatives, you must provide a copy of this Agreement to such third party, and ensure that the following attribution notice be provided: “Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement.” Additionally, all Model Derivatives must clearly be identified as such, including disclosure of modifications and changes made to the Apple Machine Learning Research Model. The name, trademarks, service marks or logos of Apple may not be used to endorse or promote Model Derivatives or the relationship between You and Apple. “Model Derivatives” means any models or any other artifacts created by modifications, improvements, adaptations, alterations to the architecture, algorithm or training processes of the Apple Machine Learning Research Model, or by any retraining, fine-tuning of the Apple Machine Learning Research Model.
* No Other License: Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent, trademark, and similar intellectual property rights worldwide that may be infringed by the Apple Machine Learning Research Model, the Model Derivatives or by other works in which the Apple Machine Learning Research Model may be incorporated.
* Compliance with Laws: Your use of Apple Machine Learning Research Model must be in compliance with all applicable laws and regulations.
* Term and Termination: The term of this Agreement will begin upon your acceptance of this Agreement or use of the Apple Machine Learning Research Model and will continue until terminated in accordance with the following terms. Apple may terminate this Agreement at any time if You are in breach of any term or condition of this Agreement. Upon termination of this Agreement, You must cease to use all Apple Machine Learning Research Models and Model Derivatives and permanently delete any copy thereof. Sections 3, 6 and 7 will survive termination.
* Disclaimer and Limitation of Liability: This Apple Machine Learning Research Model and any outputs generated by the Apple Machine Learning Research Model are provided on an “AS IS” basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE MACHINE LEARNING RESEARCH MODEL OR OUTPUTS GENERATED BY THE APPLE MACHINE LEARNING RESEARCH MODEL. You are solely responsible for determining the appropriateness of using or redistributing the Apple Machine Learning Research Model and any outputs of the Apple Machine Learning Research Model and assume any risks associated with Your use of the Apple Machine Learning Research Model and any output and results. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE MACHINE LEARNING RESEARCH MODEL AND ANY OUTPUTS OF THE APPLE MACHINE LEARNING RESEARCH MODEL, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* Governing Law: This Agreement will be governed by and construed under the laws of the State of California without regard to its choice of law principles. The Convention on Contracts for the International Sale of Goods shall not apply to the Agreement except that the arbitration clause and any arbitration hereunder shall be governed by the Federal Arbitration Act, Chapters 1 and 2.
Copyright (C) 2025 Apple Inc. All Rights Reserved.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394---license: apple-amlrlibrary_name: pytorchbase_model: apple/MobileCLIP-S0datasets:- ajay-narayanan/NaviSense-Spatial-Caption-Routerlanguage:- entags:- model-routing- spatial-captioning- accessibility- mobileclip- custom-code---
# NaviSense Spatial Caption Router · MobileCLIP-S0
Predicts the expected location-caption quality of **LFM2.5-VL-450M** and **GPT-4o-mini** from an image and requested object label, before either captioner runs. The router selects a backend; caption generation is performed separately.
This release is the selected **original small spatial router**, not the later larger blend or ranking-loss experiments.
## Architecture and training
- Frozen MobileCLIP-S0 image/text encoders; one 256×256 image pass supplies a global vector and 64 local vectors, each 512-dimensional.- Whole-image EXIF-upright RGB letterboxing, bilinear resize, padding value 127 and division by 255. It uses scene context rather than the detector router's center crop.- Fixed object-conditioned pooling at temperature 5. Global/text/local interactions and nine spatial summaries form **2,569 features**.- One **2569 → 64 → 2** head with ReLU and training dropout 0.2: **164,610 learned parameters**, plus four output-correction constants.- Two sigmoid outputs after positive affine correction, ordered **`[lfm_iphone, gpt4o_mini]`**. These are numeric expected **judge scores/5**, not success probabilities.
The head fits 8,000 training pairs with MSE, AdamW, learning rate 0.001, weight decay 0.05, batch size 256 and 35 epochs, seed 20261126. Of 2,000 validation pairs, 1,011 fit output correction and 989 support model selection. Test and reserve pairs receive no gradient fitting. The encoder checkpoint and code revisions are pinned in `config.json`.
## Routing policy
Choose the backend maximizing:
```textpredicted_score_over_5 − 0.125 × estimated_latency_seconds```
Each backend starts at its 8k-training mean latency. Estimates combine its last **eight selected calls** with **eight training-mean prior observations**. Update only the chosen backend after its call. No current unchosen latency, generated caption, reference or judge record is a routing input.
## Usage
Download the repository and install its `requirements.txt`. The bundle contains the frozen encoder weights, trained head, correction, configuration and standalone inference code; it does not contain either captioner.
```pythonimport sysfrom huggingface_hub import snapshot_downloadfrom PIL import Image
folder = snapshot_download( "ajay-narayanan/NaviSense-Spatial-Caption-Router-MobileCLIP-S0", token=True)sys.path.insert(0, folder)from spatial_caption_router import SpatialCaptionRouter
router = SpatialCaptionRouter.from_pretrained(folder)scores = router([Image.open("scene.jpg")], ["mug"])[0].tolist()policy = router.new_policy() # retain this instance across requestsbackend = policy.choose(scores)print(router.config["backends"][backend])# After calling that captioner: policy.observe(backend, measured_latency_ms)```
Authenticate when accessing a private repository. `encode_images` and `encode_queries` expose reusable features; object-text embeddings can be cached.
## Existing 5k-test benchmark
At **λ = 0.125**, using stored backend timings:
| Policy | Mean score/5 (%) | Mean backend ms | GPT calls | Utility ||---|---:|---:|---:|---:|| Always LFM | 73.404 | 464.8 | 0% | 0.675941 || Always GPT-4o-mini | 79.384 | 1261.4 | 100% | 0.636163 || Uniform random, 50/50 | 76.394 | 863.0 | 49.98% | 0.656066 || Training-average prior | 73.404 | 464.8 | 0% | 0.675941 || Object-label prior | 74.972 | 606.7 | 18.08% | 0.673883 || Cosine threshold | 79.992 | 992.0 | 65.80% | 0.675916 || **NaviSense router** | 77.392 | 702.6 | 30.26% | **0.686100** |
Random results average 1,000 independent fair-coin trials. The privileged hindsight upper bound is **0.818180 utility**; it uses both true rewards and current costs and cannot be deployed. Quality is model-judge reward, not binary or human accuracy. Full metrics and provenance are in `metadata/benchmark.json`.

## Verification, deployment and limits
The complete FP32 safetensors file is approximately **216 MB**; the separate head is approximately **0.659 MB**. Frozen encoders account for most storage. CoreML image and pooling/head exports are included separately; full Swift/text-encoder integration and actual iPhone latency remain unverified.
Reloaded weights reproduce all 5,000 cached-feature routing decisions and the benchmark above. Tensor-score error against stored predictions is at most 1.79e-7. Four image inputs give identical results before and after saving; freshly encoded CPU features differ numerically from the historical CUDA cache. Benchmark reproduction on cached features does not establish identical pixel-to-score behavior on every device.
**Backend timings exclude router inference.** Historical development/test inspection, reference errors and judge mistakes limit the evidence. No real-world blind-user retrieval success or end-to-end phone performance is established.
The bundled MobileCLIP weights and derivative are subject to the **Apple Machine Learning Research Model License**, included in `LICENSE`. This is a research release under those upstream terms; see the license before use.12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "format_version": 1, "architectures": [ "SpatialCaptionRouter" ], "encoder": "apple/MobileCLIP-S0", "encoder_revision": "71aa3e13dda93115871afbd017336535ba29886c", "encoder_code_revision": "48faa0fea4b08d74188b3841771aca6ff2c92852", "image_resolution": 256, "local_grid": 8, "local_tokens": 64, "local_dimension": 512, "input_dim": 2569, "hidden": 64, "dropout": 0.2, "pooling_temperature": 5.0, "backends": [ "lfm_iphone", "gpt4o_mini" ], "output_semantics": "Expected numeric judge score/5, not success probabilities; explicit abstention task reward0.", "preprocessing": "EXIF-upright RGB, bilinear ImageOps.contain into256, centeredRGB127 letterbox, /255. Local vectors normalized thenFP16rounded and pooled inFP32.", "training_mean_latency_ms": [ 465.6586315989538, 1262.0192540647695 ], "policy": { "lambda_per_second": 0.125, "window": 8, "prior_weight": 8 }, "training": { "pairs": 8000, "validation_correction_pairs": 1011, "validation_selection_pairs": 989, "loss": "MSE on both normalized scores", "epochs": 35, "batch_size": 256, "learning_rate": 0.001, "weight_decay": 0.05, "seed": 20261126 }, "source_checkpoint_sha256": "cde1859f8bd4ad9697c908140978a811b06a8857d82a8e5ad3957a17b752b1d2", "source_dataset": "ajay-narayanan/NaviSense-Spatial-Caption-Router", "source_dataset_cases_sha256": "15594a4cd443b6381b9879bcec0e4831594120bf9c3d8497219cedb3b2f04279"}123version https://git-lfs.github.com/spec/v1oid sha256:de630cfc3d270dd1e8e2ff118a0f34951ffd05d367818a8e4943f8cea2df2f6asize 12517123version https://git-lfs.github.com/spec/v1oid sha256:3f01cc5ea82947f1e0b12050f4da805ed20145b6baf20498f5b9c57951fa6f4asize 659328123456789101112131415161718{ "fileFormatVersion": "1.0.0", "itemInfoEntries": { "2294df97-eb79-4a52-8168-497cae34a9ee": { "author": "com.apple.CoreML", "description": "CoreML Model Weights", "name": "weights", "path": "com.apple.CoreML/weights" }, "577db564-113b-49a2-beea-db192b1f9efe": { "author": "com.apple.CoreML", "description": "CoreML Model Specification", "name": "model.mlmodel", "path": "com.apple.CoreML/model.mlmodel" } }, "rootModelIdentifier": "577db564-113b-49a2-beea-db192b1f9efe"}123version https://git-lfs.github.com/spec/v1oid sha256:51fe6e540d84b8d8f8b8c575a1493c61435b6c40ce60e5db56f3da27f472e39fsize 156544123version https://git-lfs.github.com/spec/v1oid sha256:7c8b920c73cefe701bf4890e53f5596a1e8aa525ad5f5d2c4d2e87d892eb3d12size 22717696123456789101112131415161718{ "fileFormatVersion": "1.0.0", "itemInfoEntries": { "35bf3e99-833a-46a5-b045-0583d7140f05": { "author": "com.apple.CoreML", "description": "CoreML Model Weights", "name": "weights", "path": "com.apple.CoreML/weights" }, "b31b2d55-3834-4d0f-bcf7-d76b73bea85b": { "author": "com.apple.CoreML", "description": "CoreML Model Specification", "name": "model.mlmodel", "path": "com.apple.CoreML/model.mlmodel" } }, "rootModelIdentifier": "b31b2d55-3834-4d0f-bcf7-d76b73bea85b"}1CoreML image and pooling/head exports from the selected v14 router. Image input is256RGB, EXIF-upright and gray127letterboxed; normalized global512 plus64x512local outputs. The pool/head expects cached normalized object-text vectors, image vectors, local tokens and geometry. Text-encoder integration, full Swift pipeline and actual Mac/iPhone parity/latency remain unmeasured. Conversion success is not device performance. Use the PyTorch safetensors bundle for the complete desktop reference.123version https://git-lfs.github.com/spec/v1oid sha256:2a30aeb5016f1d5cc9b8ae6cf977715abde190520a40e765d6f70d6a1d7b98edsize 65888012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273{ "lambda_per_second": 0.125, "test_pairs": 5000, "policies": { "always_edge": { "quality": 0.73404, "mean_ms": 464.7923608333586, "p95_ms": 575.3213624979253, "cloud_fraction": 0.0, "utility": 0.6759409548958303 }, "always_cloud": { "quality": 0.79384, "mean_ms": 1261.4127211832906, "p95_ms": 1927.568125363905, "cloud_fraction": 1.0, "utility": 0.6361634098520887 }, "training_average": { "quality": 0.73404, "mean_ms": 464.7923608333586, "p95_ms": 575.3213624979253, "cloud_fraction": 0.0, "utility": 0.6759409548958303 }, "object_label_prior": { "quality": 0.74972, "mean_ms": 606.6924611523085, "p95_ms": 1377.3547545075419, "cloud_fraction": 0.1808, "utility": 0.6738834423559615 }, "cosine_threshold": { "quality": 0.7999200000000001, "mean_ms": 992.0345519982388, "p95_ms": 1789.0957582276314, "cloud_fraction": 0.658, "utility": 0.6759156810002201 }, "our_router": { "quality": 0.77392, "mean_ms": 702.5614567456302, "p95_ms": 1548.3700323733503, "cloud_fraction": 0.3026, "utility": 0.6860998179067962 }, "hindsight_oracle": { "quality": 0.90856, "mean_ms": 723.0378933632885, "p95_ms": 1554.4034496298993, "cloud_fraction": 0.3244, "utility": 0.8181802633295889 }, "random_50_50": { "quality": 0.7639419199999999, "mean_ms": 863.0113169652795, "p95_ms": 1708.5658545925398, "cloud_fraction": 0.4997776, "utility": 0.65606550537934, "trials": 1000, "utility_std": 0.0029921729430381137, "utility_seed_range_95": [ 0.6502443064539533, 0.6620374361270868 ], "probability_each_backend": 0.5, "exact_expected_utility": 0.6560521823739593 } }, "source_test_predictions_sha256": "fe366d5436847af172c227f87a31fdfa4b24b0e515b0252c9faeeb503e2854a5", "score_mse": 0.10501796778121127, "note": "Historical cached-feature replay; unmeasured phone router overhead excluded."}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849{ "selected": { "name": "spatial_soft-s20261126-positive_affine", "mode": "spatial_soft", "seed": 20261126, "correction": "positive_affine", "validation": { "n": 989, "mean_score_over_5": 0.746814964610718, "mean_task_reward_0_to_5": 3.73407482305359, "mean_judge_score_when_caption_scored": 3.7416413373860182, "scored_caption_count": 987, "abstention_count": 2, "abstention_rate": 0.0020222446916076846, "mean_ms": 511.97487035215664, "median_ms": 442.4900833328138, "p95_ms": 936.5343234967436, "cloud_fraction": 0.05864509605662285, "lfm_fraction": 0.9413549039433772, "utility": 0.6259161592250383, "assumed_router_ms": 0.0, "grade_at_least_4_rate": 0.6390293225480284 }, "validation_mse": 0.09973196970270033, "parameters": 164610 }, "head_parameters": 164610, "source_checkpoint_sha256": "cde1859f8bd4ad9697c908140978a811b06a8857d82a8e5ad3957a17b752b1d2", "settings": { "pairs": 8000, "validation_correction_pairs": 1011, "validation_selection_pairs": 989, "loss": "MSE on both normalized scores", "epochs": 35, "batch_size": 256, "learning_rate": 0.001, "weight_decay": 0.05, "seed": 20261126 }, "encoder_checkpoint_sha256": "809b408eff74f8058843e86a1f92967097d42ba782450e85b8f4867b7f0ca0b7", "scale": [ 0.4154433310031891, 0.5135794281959534 ], "bias": [ 0.6347211599349976, 0.6765820980072021 ]}123456789101112131415161718192021222324{ "status": "passed", "source_checkpoint_hash_verified": true, "source_encoder_hash_verified": true, "complete_safetensors_weight_bytes": 215930140, "head_safetensors_bytes": 658880, "head_parameters": 164610, "encoder_parameters": 53792065, "fixture64_max_abs_error": 1.1920928955078125e-07, "all5000_cached_prediction_max_abs_error": 1.7881393432617188e-07, "all5000_actions_and_public_policy_match": true, "fixture_reload_predictions_exact": true, "pixel_sample_reload_predictions_exact": true, "pixel_sample_count": 4, "pixel_cpu_vs_historical_cuda_cache_max_abs_error": 0.0004127621650695801, "current_test_quality": 0.77392, "current_mean_backend_ms": 702.5614567456302, "current_utility": 0.6860998179067962, "gpt_calls": 1513, "physical_iphone_runtime_measured": false, "export_script_sha256": "7d1989b16215a94f5a191846b633fb550769882da2750d0b792515760bc15120", "inference_code_sha256": "d7ad58dd394c26629073b9d5c2a50bb2b177368daa5f43033f7c177600832868", "model_safetensors_sha256": "e83920b214e7b95cf07e46d265a4579fdc254e12eadca8c7534b25431cea5b09"}123version https://git-lfs.github.com/spec/v1oid sha256:e83920b214e7b95cf07e46d265a4579fdc254e12eadca8c7534b25431cea5b09size 215930140123version https://git-lfs.github.com/spec/v1oid sha256:45539dc5ce1b6e1c253418b88389a87456c87589aa7df6fd218b56dff929e9d0size 521598112345678torch==2.8.0torchvision==0.23.0numpy==2.2.6Pillow==11.2.1timm==1.0.30safetensors>=0.4huggingface_hub>=0.36mobileclip @ git+https://github.com/apple-aiml-research/ml-mobileclip.git@48faa0fea4b08d74188b3841771aca6ff2c92852123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162"""Standalone inference for the frozen NaviSense Spatial Caption Router.
Requires the pinned official MobileCLIP package, PyTorch, Pillow, NumPy,Hugging Face Hub and safetensors. No captioner is loaded or called here."""from collections import dequeimport jsonimport mathfrom pathlib import Path
import numpy as npfrom PIL import Image,ImageOpsimport torchfrom torch import nn
BACKENDS=('lfm_iphone','gpt4o_mini')
def normalized(x): return x/torch.sqrt((x*x).sum(-1,keepdim=True)).clamp_min(1e-8)
def geometry(width,height): rw,rh=256,256 if width>height:rh=round(height/width*256) elif height>width:rw=round(width/height*256) if min(rw,rh)<1:raise ValueError('Image aspect ratio cannot fit the256pixel canvas') left,top=(256-rw)//2,(256-rh)//2 edges=np.linspace(0,256,9);centers=(edges[:-1]+edges[1:])/2 xx,yy=np.meshgrid(centers,centers) x=np.clip(2*(xx-left)/rw-1,-1,1);y=np.clip(2*(yy-top)/rh-1,-1,1) overlap_x=np.maximum(0,np.minimum(edges[1:],left+rw)-np.maximum(edges[:-1],left)) overlap_y=np.maximum(0,np.minimum(edges[1:],top+rh)-np.maximum(edges[:-1],top)) coverage=(overlap_y[:,None]*overlap_x[None,:])/32**2 coords=np.stack([x,y,x*x,y*y],-1).reshape(64,4).astype(np.float32) return coords,coverage.reshape(64).astype(np.float32)
class CaptionRoutingPolicy: def __init__(self,training_mean_ms,penalty=.125,window=8,prior_weight=8): if len(training_mean_ms)!=2 or any(not math.isfinite(v) or v<=0 for v in training_mean_ms): raise ValueError('Supply two positive training timing priors') self.prior=tuple(float(v) for v in training_mean_ms) self.penalty=float(penalty);self.weight=float(prior_weight) self.history=[deque(maxlen=window),deque(maxlen=window)];self.pending=None
@property def estimated_latency_ms(self): return tuple((sum(h)+self.weight*p)/(len(h)+self.weight) for h,p in zip(self.history,self.prior))
def choose(self,scores): if self.pending is not None:raise RuntimeError('Observe the previous selected call first') values=tuple(float(v) for v in scores) if len(values)!=2 or any(not math.isfinite(v) or not 0<=v<=1 for v in values): raise ValueError('Expected two numeric normalized scores') costs=self.estimated_latency_ms self.pending=min(range(2),key=lambda i:(-values[i]+self.penalty*costs[i]/1000,costs[i],i)) return self.pending
def observe(self,backend,latency_ms): if self.pending is None or backend!=self.pending:raise ValueError('Observe only the chosen backend') if latency_ms is not None: value=float(latency_ms) if not math.isfinite(value) or value<0:raise ValueError('Latency must be finite and nonnegative') self.history[backend].append(value) self.pending=None
class SpatialCaptionRouter(nn.Module): def __init__(self,config): super().__init__() import mobileclip if config.get('format_version')!=1 or config.get('input_dim')!=2569 or config.get('hidden')!=64: raise ValueError('Unsupported caption-router configuration') if config.get('backends')!=list(BACKENDS):raise ValueError('Unexpected backend order') self.encoder,_,_=mobileclip.create_model_and_transforms('mobileclip_s0',pretrained=None, reparameterize=True,device='cpu') self.tokenizer=mobileclip.get_tokenizer('mobileclip_s0') self.head=nn.Sequential(nn.Linear(2569,64),nn.ReLU(),nn.Dropout(.2),nn.Linear(64,2)) self.register_buffer('scale',torch.ones(2));self.register_buffer('bias',torch.zeros(2)) self.config=config;self._text_cache={}
def feature_vector(self,global_image,object_embedding,local_tokens,coords,coverage): cosine=(local_tokens*object_embedding[:,None,:]).sum(-1) logits=5*cosine+coverage.clamp_min(1e-8).log() logits=torch.where(coverage>0,logits,torch.full_like(logits,-1e4)) weights=logits.softmax(-1) attended=normalized((local_tokens*weights[:,:,None]).sum(1)) moments=(coords*weights[:,:,None]).sum(1) entropy=-(weights*weights.clamp_min(1e-8).log()).sum(1,keepdim=True)/math.log(64) top=torch.topk(torch.where(coverage>0,cosine,torch.full_like(cosine,-1)),2,dim=1).values ascending_top=torch.cat([top[:,1:2],top[:,0:1]],1) summary=torch.cat([moments,entropy,ascending_top,top[:,0:1]-top[:,1:2], (global_image*object_embedding).sum(1,keepdim=True)],1)*.1 return torch.cat([global_image,object_embedding,normalized(global_image*object_embedding), attended,normalized(attended*object_embedding),summary],1)
@torch.inference_mode() def score_from_features(self,global_image,object_embedding,local_tokens,coords,coverage): features=self.feature_vector(global_image,object_embedding,local_tokens,coords,coverage) return (self.head(features)*self.scale+self.bias).sigmoid()
@torch.inference_mode() def encode_images(self,images): device=self.scale.device;arrays=[];coordinates=[];coverages=[] for image in images: image=ImageOps.exif_transpose(image).convert('RGB') c,cov=geometry(*image.size) contained=ImageOps.contain(image,(256,256),method=Image.Resampling.BILINEAR) canvas=Image.new('RGB',(256,256),(127,127,127)) canvas.paste(contained,((256-contained.width)//2,(256-contained.height)//2)) arrays.append(np.asarray(canvas,dtype=np.uint8).transpose(2,0,1).copy()) coordinates.append(c);coverages.append(cov) pixels=torch.from_numpy(np.stack(arrays)).to(device=device,dtype=torch.float32)/255 model=self.encoder.image_encoder.model spatial=model.conv_exp(model.forward_tokens(model.forward_embeddings(pixels))) global_image=normalized(model.head(spatial)) local=normalized(spatial.flatten(2).transpose(1,2) @ model.head.proj) # Training caches store normalized local vectors in FP16, then pool in FP32. local=local.to(torch.float16).float() return (global_image,local,torch.from_numpy(np.stack(coordinates)).to(device), torch.from_numpy(np.stack(coverages)).to(device))
@torch.inference_mode() def encode_queries(self,queries): device=self.scale.device;missing=[] for query in queries: if not isinstance(query,str) or not query:raise ValueError('Object labels must be nonempty strings') key=(str(device),query) if key not in self._text_cache and query not in missing:missing.append(query) if missing: for query in missing: if len(self.tokenizer.tokenizer.encode(query))+2>self.tokenizer.context_length: raise ValueError('Object label exceeds the tokenizer budget; no silent truncation') tokens=self.tokenizer(missing).to(device) vectors=self.encoder.encode_text(tokens,normalize=True) for query,vector in zip(missing,vectors):self._text_cache[(str(device),query)]=vector return torch.stack([self._text_cache[(str(device),query)] for query in queries])
@torch.inference_mode() def forward(self,images,queries): if not images or len(images)!=len(queries):raise ValueError('Supply one object label per image') g,local,coords,coverage=self.encode_images(images) return self.score_from_features(g,self.encode_queries(queries),local,coords,coverage)
def new_policy(self): p=self.config['policy'] return CaptionRoutingPolicy(self.config['training_mean_latency_ms'],p['lambda_per_second'], p['window'],p['prior_weight'])
@classmethod def from_pretrained(cls,source,*,revision=None,token=None,device='cpu',local_files_only=False): from huggingface_hub import snapshot_download from safetensors.torch import load_model directory=Path(source) if not directory.is_dir(): directory=Path(snapshot_download(str(source),revision=revision,token=token, local_files_only=local_files_only,allow_patterns=['config.json','model.safetensors'])) config=json.loads((directory/'config.json').read_text()) router=cls(config) load_model(router,directory/'model.safetensors',strict=True) return router.eval().requires_grad_(False).to(device)1234567891011121314151617"""Run local tensor-fixture checks after downloading this model repository."""import jsonfrom pathlib import Pathimport numpy as npimport torchfrom spatial_caption_router import SpatialCaptionRouter
root=Path(__file__).resolve().parenttorch.set_num_threads(2)router=SpatialCaptionRouter.from_pretrained(root)with np.load(root/'parity-fixtures.npz',allow_pickle=False) as f: values=[torch.from_numpy(f[k]) for k in ('global_image','object_embedding','local_tokens','coords','coverage')] prediction=router.score_from_features(*values).numpy() error=float(np.max(np.abs(prediction-f['expected_score_over_5'])))assert error<3e-7print(json.dumps({'status':'passed','fixtures':len(prediction),'score_max_abs_error':error, 'phone_runtime_tested':False},indent=2)).gitattributes+1
LICENSEAdded+88
README.mdAdded+94
assets/caption-pareto.pngAdded

Large File Pointer Details
- SHA256: 9657a284ce8ee018c509b70f53ea0d61bdb584e26212c7256f5cdf9b3c5049b0
- Pointer size: 131 Bytes
- Size of remote file: 173 kB
config.jsonAdded+46
coreml/CaptionSpatialPoolHeadFloat32.mlpackage/Data/com.apple.CoreML/model.mlmodelAdded+3
coreml/CaptionSpatialPoolHeadFloat32.mlpackage/Data/com.apple.CoreML/weights/weight.binAdded+3
coreml/CaptionSpatialPoolHeadFloat32.mlpackage/Manifest.jsonAdded+18
coreml/MobileCLIPS0SpatialImageFloat16.mlpackage/Data/com.apple.CoreML/model.mlmodelAdded+3
coreml/MobileCLIPS0SpatialImageFloat16.mlpackage/Data/com.apple.CoreML/weights/weight.binAdded+3
coreml/MobileCLIPS0SpatialImageFloat16.mlpackage/Manifest.jsonAdded+18
coreml/README.mdAdded+1
head.safetensorsAdded+3
metadata/benchmark.jsonAdded+73
metadata/training.jsonAdded+49
metadata/verification.jsonAdded+24
model.safetensorsAdded+3
parity-fixtures.npzAdded+3
requirements.txtAdded+8
spatial_caption_router.pyAdded+162
verify.pyAdded+17