hs-rerank-1 — LiteRT

These LiteRT files run hindsight-ai/hs-rerank-1, a multilingual reranker, on Android phones. On a Snapdragon Galaxy S26, a query and document pair of up to 128 tokens takes 3.3 ms on the NPU, 3.6 ms on the GPU at FP16 and 7.1 ms on the CPU — speed still being tuned (updates follow). On that phone and a Pixel 11 Pro, the _fp16_int8emb files on the CPU and on a GPU at FP32 kept the relevance probabilities within 0.016 of the publisher's float32 model on all 8,002 test pairs; the _embeds_fp16 files, run on the Galaxy S26 only, stayed within 0.008 on 1,002 of them.

Run it

Each file reads a fixed number of tokens, its window: L128 takes a query and document pair of up to 128 tokens, counting the 3 special tokens the tokenizer adds. Pick the smallest window that holds your pair. Use the _fp16_int8emb files on the CPU and on a GPU at FP32, and the _embeds_fp16 files on a GPU at FP16 and on the NPU.

To try both on a computer, put hs_rerank_1_L128_fp16_int8emb.tflite, hs_rerank_1_L128_embeds_fp16.tflite, tok_embeddings_fp16.bin and tokenizer.json from this repository in one folder, save the code below there as usage.py, and run:

pip install ai-edge-litert==2.3.0 tokenizers==0.23.3 numpy==2.5.4
python usage.py
import numpy as np
from ai_edge_litert.compiled_model import CompiledModel, CpuOptions, HardwareAccelerator, Options
from tokenizers import Tokenizer

TOKENIZER_FILE = "tokenizer.json"
IDS_MODEL = "hs_rerank_1_L128_fp16_int8emb.tflite"
EMBEDS_MODEL = "hs_rerank_1_L128_embeds_fp16.tflite"
TABLE_FILE = "tok_embeddings_fp16.bin"

tokenizer = Tokenizer.from_file(TOKENIZER_FILE)
tokenizer.no_truncation()
options = Options(hardware_accelerators=HardwareAccelerator.CPU, cpu_options=CpuOptions(num_threads=4))


class Reranker:
    def __init__(self, filename, table=None):
        self.filename, self.table = filename, table
        self.input_name = "input_ids" if table is None else "inputs_embeds"
        self.model = CompiledModel.from_file(filename, options=options)
        self.signature, = self.model.get_signature_list()
        details = self.model.get_input_tensor_details(self.signature)
        self.window = int(details["attention_mask"]["shape"][1])
        self.inputs = {name: self.model.create_input_buffer_by_name(self.signature, name)
                       for name in (self.input_name, "attention_mask")}
        self.outputs = {"score": self.model.create_output_buffer_by_name(self.signature, "score")}

    def encode_inputs(self, query, document):
        ids = tokenizer.encode(query, document, add_special_tokens=True).ids
        if len(ids) > self.window:
            advice = "Shorten the pair."
            if self.window < 1024:
                next_file = self.filename.replace(f"_L{self.window}_", f"_L{2 * self.window}_")
                advice = f"Use {next_file}."
            raise ValueError(f"{len(ids)} tokens exceed the {self.window}-token window. {advice}")
        tokens = np.zeros((1, self.window), dtype=np.int32)  # pad token ID 0
        mask = np.zeros((1, self.window), dtype=np.float32)
        tokens[0, :len(ids)] = ids
        mask[0, :len(ids)] = 1.0
        return tokens, mask

    def score(self, query, document):
        ids, mask = self.encode_inputs(query, document)
        values = ids if self.table is None else self.table[ids].astype(np.float32)
        self.inputs[self.input_name].write(values)
        self.inputs["attention_mask"].write(mask)
        self.model.run_by_name(self.signature, self.inputs, self.outputs)
        logit = float(self.outputs["score"].read(1, np.float32)[0])
        return float(1 / (1 + np.exp(-logit)))  # The publisher's default predict() activation.


ids_model = Reranker(IDS_MODEL)
table = np.memmap(TABLE_FILE, mode="r", dtype="<f2", shape=(256_000, 384))
embeds_model = Reranker(EMBEDS_MODEL, table)


def score_ids(query, document):
    return ids_model.score(query, document)


def score_embeds(query, document):
    return embeds_model.score(query, document)


if __name__ == "__main__":
    query = "¿Qué app de presupuesto estoy creando?"
    documents = [
        "El usuario quiere tooltips en su app de presupuesto.",
        "El usuario corre los domingos por la mañana.",
    ]
    for name, score in (("ids", score_ids), ("embeds", score_embeds)):
        scores = [score(query, doc) for doc in documents]
        for i, (doc, value) in enumerate(zip(documents, scores)):
            print(f"{name} document {i}: {value:.6f}  {doc}")
        ranking = sorted(range(len(documents)), key=scores.__getitem__, reverse=True)
        print(f"{name} ranking: {ranking}")

It prints:

ids document 0: 0.964681  El usuario quiere tooltips en su app de presupuesto.
ids document 1: 0.000296  El usuario corre los domingos por la mañana.
ids ranking: [0, 1]
embeds document 0: 0.964737  El usuario quiere tooltips en su app de presupuesto.
embeds document 1: 0.000289  El usuario corre los domingos por la mañana.
embeds ranking: [0, 1]

On this example from the publisher's card, the publisher's float32 model returns 0.964708 and 0.000289 from predict(). With both file names changed to the L1024 files, the code prints the same output. Tested with ai-edge-litert 2.3.0, tokenizers 0.23.3 and numpy 2.5.4 on Python 3.13, on an arm64 Mac.

When it does not work

  • A pair longer than the window stops the code with a message. Below L1024 it names the file with twice the window: ValueError: 191 tokens exceed the 128-token window. Use hs_rerank_1_L256_fp16_int8emb.tflite. At L1024 it says Shorten the pair.
  • These files stop at 1,024 tokens per pair, while the publisher's model reads up to 8,192. Shorten longer pairs.
  • Run the _fp16_int8emb files on a GPU at FP32. At FP16 their probabilities moved by up to 0.0235 on a Snapdragon Galaxy S26 and 0.0225 on a Pixel 11 Pro, and at FP16 with FP32 accumulation by 0.0226 on the Pixel 11 Pro, past the 0.02 limit, all on JSQuAD pairs.
  • For FP16 GPU speed, use the _embeds_fp16 files. Of the two phones, only the Snapdragon Galaxy S26 ran them, on 1,002 of the pairs and none from JSQuAD. On those pairs, they moved the probabilities by up to 0.0080 on its GPU at FP16, where the _fp16_int8emb files moved them by 0.0084.
  • On the NPU every score we recorded was a float16 value, and close scores can tie. At L1024, a pair and the same pair without its last five tokens score 4.6474 and 4.6607 in the publisher's model, and both score 4.6523 on the NPU. This is the one check the L1024 NPU file failed.
  • The first load of a file on the NPU compiles the graph on the phone: 1.0–5.7 s per file in our runs, each started with an empty compile cache, not part of the times below. The Snapdragon Galaxy S26's NPU is the only NPU measured.
  • On the Mac we tested, LiteRT wrote INFO and WARNING messages to stderr, such as NPU accelerator could not be loaded, and the code still ran on the CPU.

Files

file window, tokens input for size
hs_rerank_1_L128_fp16_int8emb.tflite 128 input_ids CPU, GPU at FP32 132.7 MB
hs_rerank_1_L256_fp16_int8emb.tflite 256 input_ids CPU, GPU at FP32 133.4 MB
hs_rerank_1_L512_fp16_int8emb.tflite 512 input_ids CPU, GPU at FP32 135.8 MB
hs_rerank_1_L1024_fp16_int8emb.tflite 1024 input_ids CPU, GPU at FP32 145.5 MB
hs_rerank_1_L128_embeds_fp16.tflite 128 inputs_embeds GPU at FP16, NPU 31.3 MB
hs_rerank_1_L256_embeds_fp16.tflite 256 inputs_embeds GPU at FP16, NPU 32.0 MB
hs_rerank_1_L512_embeds_fp16.tflite 512 inputs_embeds GPU at FP16, NPU 34.5 MB
hs_rerank_1_L1024_embeds_fp16.tflite 1024 inputs_embeds GPU at FP16, NPU 44.2 MB
tok_embeddings_fp16.bin — token rows _embeds_fp16 files 196.6 MB
tokenizer.json — — all files 34.4 MB

Both forms store the fully connected weights in float16. _fp16_int8emb files take token ids, and their token table is int8 with one scale per row. _embeds_fp16 files take the token rows instead: look each id up in tok_embeddings_fp16.bin, the publisher's token table in float16, 256,000 rows of 384 values, little-endian and row-major, with the padding id 0 at row 0. tokenizer.json is the publisher's file, byte for byte, and SHA256SUMS lists the sha256 of the ten files above.

Each file takes attention_mask as float32 [1, L], with 1 for tokens and 0 for padding, and either input_ids as int32 [1, L] or inputs_embeds as float32 [1, L, 384]. It returns score, a float32 [1, 1] raw logit. The code turns it into a probability with a sigmoid, as the publisher's predict() does.

Accuracy

The checks compare the phones' scores with the publisher's float32 model, run with sentence-transformers 6.3.0 on a Mac CPU. They use 8,002 query and document pairs:

  • NanoSciFact: 50 queries, each with the top 20 of 2,919 documents found by the publisher's embedding model hindsight-ai/hs-embed-1, and again with its relevant documents plus random ones, 20 in all.
  • JSQuAD: 200 Japanese questions, each with the top 20 of 1,145 paragraphs found by hs-embed-1, and 100 questions with their own paragraph plus 19 random ones.
  • The Spanish example on the publisher's card.

The limits were set before these files were made: no probability on the NanoSciFact and JSQuAD pairs moves by more than 0.02, nDCG@10 on the two sets found by hs-embed-1 drops by at most 0.01, and the first Spanish document ranks first. Pairs longer than 1,024 tokens were first cut to 1,024 tokens, longest first, for the publisher's model too; each pair then ran in the smallest window that holds it.

phone · backend file largest probability change nDCG@10, NanoSciFact / JSQuAD top 20
the publisher's float32 model — — 0.7928 / 0.9435
Snapdragon Galaxy S26 · CPU _fp16_int8emb 0.0156 0.7928 / 0.9435
Snapdragon Galaxy S26 · GPU, FP32 _fp16_int8emb 0.0156 0.7928 / 0.9435
Snapdragon Galaxy S26 · GPU, FP16 with FP32 accumulation _fp16_int8emb 0.0153 0.7928 / 0.9435
Snapdragon Galaxy S26 · GPU, FP16 _fp16_int8emb 0.0235, over 0.02 0.7928 / 0.9416
Pixel 11 Pro · CPU _fp16_int8emb 0.0156 0.7928 / 0.9435
Pixel 11 Pro · GPU, FP32 _fp16_int8emb 0.0156 0.7928 / 0.9435
Pixel 11 Pro · GPU, FP16 with FP32 accumulation _fp16_int8emb 0.0226, over 0.02 0.7928 / 0.9435
Pixel 11 Pro · GPU, FP16 _fp16_int8emb 0.0225, over 0.02 0.7928 / 0.9398
Snapdragon Galaxy S26 · GPU, FP32 _embeds_fp16 0.0004 0.7928 / —
Snapdragon Galaxy S26 · GPU, FP16 with FP32 accumulation _embeds_fp16 0.0026 0.7928 / —
Snapdragon Galaxy S26 · GPU, FP16 _embeds_fp16 0.0080 0.7928 / —
Snapdragon Galaxy S26 · NPU _embeds_fp16 0.0033 0.7928 / —

The _embeds_fp16 rows ran the Spanish example and the 1,000 NanoSciFact pairs found by hs-embed-1.

Speed on a Snapdragon Galaxy S26

backend file L128 L256 L512 L1024 peak memory
NPU _embeds_fp16 3.33 ms 5.92 ms 8.69 ms 29.22 ms 660 MiB
GPU, FP16 _embeds_fp16 3.61 ms 5.34 ms 10.53 ms 30.36 ms 451 MiB
GPU, FP16 with FP32 accumulation _embeds_fp16 4.28 ms 7.05 ms 13.77 ms 38.14 ms 412 MiB
GPU, FP32 _embeds_fp16 5.41 ms 9.09 ms 21.45 ms 60.00 ms 417 MiB
GPU, FP32 _fp16_int8emb 5.63 ms 9.41 ms 21.47 ms 60.05 ms 769 MiB
CPU, 4 threads _fp16_int8emb 7.09 ms 12.92 ms 32.65 ms 104.17 ms 393 MiB

The phone is a Galaxy S26 (Snapdragon, SM8850) on Android API level 36. A time is one call: write the inputs, run, and read the output. Each time is the median of 20 calls after 5 warm-up calls, and each series started on a rested phone: thermal status 0, no cap on the CPU clocks and no thermal limit on the GPU clock. The CPU and GPU calls used a pair that fills the window, and the NPU calls used one fixed test pair.

For _embeds_fp16 the token rows were looked up before the calls, so the times include writing inputs_embeds but not the lookup. A file computes its whole window, so a short pair costs about as much as a full one. On the CPU at L1024, a 32-token pair took 98.1 ms and a 1,024-token pair 104.2 ms. On the GPU the median run call alone took 0.07–0.98 ms, so time GPU calls with the output read included.

Peak memory is the highest resident memory, VmHWM, of the process that ran the accuracy checks, over the four windows. It was read every 2 s, so the NPU figure, from runs of 2–11 s, may be below the real peak.

The phone results in Accuracy and Speed come from LiteRT 2.2.0. The CPU and GPU ran in CompiledModel in an Android app, with the GPU through OpenCL and every node of the graph on the GPU. The GPU's FP32, FP16 with FP32 accumulation and FP16 are its CompiledModel.GpuOptions.Precision values FP32, FP16_WITH_FP32_ACCUM and FP16. The NPU ran through LiteRT's C API with the Qualcomm compiler plugin, which put every op of the graph on the NPU; its timings used htp_performance_mode = 2. The Pixel 11 Pro, on Android API level 37 with a PowerVR C-Series GPU, was checked for accuracy only.

How the files were made

  • The source is hindsight-ai/hs-rerank-1 at its fp32 revision, stored in float32. Cast to float16, its 54 tensors equal the FP16 weights on the publisher's main branch at 6bc7caf.
  • The model is an 8-layer ModernBERT encoder of width 384 with a 256,000-token vocabulary.
  • litert-torch 0.10.0 exported two graphs per window, one taking token ids and one taking token rows, from PyTorch 2.14.1, Transformers 5.22.1 and sentence-transformers 6.3.0. AI Edge Quantizer 0.10.1 converted the weights to float16 and int8.
  • Five LayerNorms, those of the last two layers and the final norm, run on their input halved, a shift chosen from the largest values over the 8,002 pairs, to keep float16 arithmetic in range. In the float32 PyTorch graph this changes no output: the largest difference over those pairs is 0.0.

License

MIT, the license of the publisher's model.

Downloads last month
44
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Model tree for litert-community/hs-rerank-1

Quantized
(1)
this model