splade-ja-310m-onnx-int8
English | 日本語
A variant of mahiyama/splade-ja-310m converted to ONNX and dynamically quantized to INT8 for CPU inference. It is intended as a query encoder for online search and is optimized first and foremost for low latency per request.
Highlights
| Metric | Original PyTorch (CPU) | This model (ONNX INT8 / CPU) | Improvement |
|---|---|---|---|
| P50 latency | 191.3 ms | 44.2 ms | 4.33× faster |
| P95 latency | 250.7 ms | 68.5 ms | 3.66× faster |
| P99 latency | 297.4 ms | 85.4 ms | 3.48× faster |
| mean latency | 193.5 ms | 46.6 ms | 4.15× faster |
| Model size | 1576 MB | 395 MB | 4× compression |
Moving from CPU PyTorch (FP32) to CPU ONNX INT8 speeds up P50 by 4.33 times and compresses the model size to one-fourth. GPU PyTorch (RTX 3080) has a P50 of 31.4 ms, so this model (44.2 ms) achieves latency of the same order as a GPU while running on CPU.
Usage Examples
# pip install "optimum[onnxruntime]" "transformers>=4.48,<5" "onnxruntime<1.20" torch
import torch
import onnxruntime as ort
from optimum.onnxruntime import ORTModelForMaskedLM
from transformers import AutoTokenizer
MODEL_ID = "mahiyama/splade-ja-310m-onnx-int8"
# --- 1. Load model & tokenizer (once at startup) -----------------------------
opts = ort.SessionOptions()
opts.intra_op_num_threads = 4 # Number of physical cores, or test 1-4 to choose the fastest
opts.inter_op_num_threads = 1
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
model = ORTModelForMaskedLM.from_pretrained(
MODEL_ID,
file_name="model_quantized.onnx",
provider="CPUExecutionProvider",
session_options=opts,
)
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
# --- 2. Encode a single query into a sparse vector ---------------------------
@torch.no_grad()
def encode_query(text: str, top_k: int = 128, max_length: int = 512):
"""Returns the SPLADE sparse vector (indices, values).
top_k: Quantization noise increases non-zero dimensions, so keeping only
the top-K dimensions in production speeds up downstream sparse retrieval.
"""
inputs = tokenizer(
text, return_tensors="pt", truncation=True, max_length=max_length,
)
logits = model(**inputs).logits # (1, L, V=102400)
# SPLADE pooling: max_i log(1 + ReLU(logits))
activated = torch.log1p(torch.relu(logits)) # (1, L, V)
activated *= inputs["attention_mask"].unsqueeze(-1) # mask padding
pooled = activated.max(dim=1).values.squeeze(0) # (V,)
# Top-K pruning (recommended)
values, idx = pooled.topk(top_k)
mask = values > 0
return idx[mask].numpy(), values[mask].numpy()
# --- 3. Try it out -----------------------------------------------------------
# Query: "What is the capital of Japan?"
indices, values = encode_query("日本の首都はどこですか?")
print(f"non-zero dims : {len(indices)}")
print(f"top tokens : "
f"{[tokenizer.decode([i]) for i in indices[(-values).argsort()[:10]]]}")
Calling onnxruntime Directly (Minimal Example Without optimum)
import numpy as np
import onnxruntime as ort
from huggingface_hub import snapshot_download
from transformers import AutoTokenizer
MODEL_ID = "mahiyama/splade-ja-310m-onnx-int8"
local_dir = snapshot_download(MODEL_ID)
opts = ort.SessionOptions()
opts.intra_op_num_threads = 4
opts.inter_op_num_threads = 1
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
session = ort.InferenceSession(
f"{local_dir}/model_quantized.onnx",
sess_options=opts,
providers=["CPUExecutionProvider"],
)
tokenizer = AutoTokenizer.from_pretrained(local_dir)
input_names = {i.name for i in session.get_inputs()}
def encode_query(text, top_k=128, max_length=512):
inputs = tokenizer(
text, return_tensors="np", truncation=True, max_length=max_length,
)
feed = {k: v for k, v in inputs.items() if k in input_names}
logits = session.run(None, feed)[0] # (1, L, V)
activated = np.log1p(np.maximum(logits, 0.0))
activated *= inputs["attention_mask"][:, :, None]
pooled = activated.max(axis=1).squeeze(0) # (V,)
idx = np.argpartition(-pooled, top_k)[:top_k]
mask = pooled[idx] > 0
return idx[mask], pooled[idx][mask]
Quantization Details
| Setting | Value |
|---|---|
| Method | ONNX Runtime dynamic INT8 quantization (post-training) |
| Profile | avx512_vnni (assumes Ice Lake / Sapphire Rapids or later CPUs) |
| per_channel | False (per-tensor) |
| Calibration | Not required (dynamic quantization) |
| Quantization targets | MatMul / Add (LayerNorm excluded) |
| Quantization time | About 17 seconds (measured with this model) |
With ModernBERT (vocab = 102400), per_channel=True was extremely slow (did not finish after more than 15 minutes), so this model uses per_channel=False. In terms of accuracy, both have only a minor impact on recall@10, so this causes no problems in practice.
Recommendations by CPU Generation
This model is built with the avx512_vnni profile. If it does not run well on older generation CPUs, change the provider options in onnxruntime or re-quantize it yourself.
| CPU Generation | Profile |
|---|---|
| Ice Lake / Sapphire Rapids or later | avx512_vnni (this model) |
| Skylake / Cascade Lake | avx512 |
| Haswell / Broadwell | avx2 |
| Apple Silicon / Graviton | arm64 |
Tokenizer Notes
The original mahiyama/splade-ja-310m was uploaded with transformers 5.x, where tokenizer_class in tokenizer_config.json is set to TokenizersBackend (a 5.x-only class). In this repository, because optimum 2.1 does not support transformers 5.x, a transformers 4.x-compatible version with tokenizer_class rewritten to PreTrainedTokenizerFast is bundled. The behavior is exactly the same.
Benchmark Details
Latency Measurements (Measured with This Model)
| Configuration | P50 (ms) | P95 (ms) | P99 (ms) | mean (ms) | min (ms) | max (ms) |
|---|---|---|---|---|---|---|
| GPU PyTorch FP32 (RTX 3080) | 31.4 | 39.3 | 42.3 | 33.0 | 27.7 | 44.1 |
| CPU PyTorch FP32 | 191.3 | 250.7 | 297.4 | 193.5 | 117.1 | 299.4 |
| CPU ONNX INT8 (this model) | 44.2 | 68.5 | 85.4 | 46.6 | 26.9 | 108.9 |
Measurement Conditions
- Batch size: 1 (assuming online queries)
- max_length: 512
- threads: 4
- 100 trials + 10 warmup
- Evaluation dataset: randomly sampled from JaCWIR-mini (1,000 queries)
- Environment: Windows 11, 24 vCore CPU (AMD Ryzen 9 3900XT 12-Core Processor) + RTX 3080, Python 3.12, onnxruntime 1.19, optimum 2.1, transformers 4.57
Limitations
- Quantization noise increases non-zero dimensions (query_active_dims). Top-K pruning (around k=128) is strongly recommended before passing the vectors to retrieval.
- This model is tuned specifically for CPU and offers no speed advantage on GPU. For GPU use cases, use the original PyTorch model (mahiyama/splade-ja-310m).
- Because quantization is intended to reduce CPU inference costs, a configuration that processes the corpus side—which is computed only once offline—with the original model (GPU FP32) yields the highest quality.
License
MIT
- Downloads last month
- 40
Model tree for mahiyama/splade-ja-310m-onnx-int8
Base model
sbintuitions/modernbert-ja-310m