Sundaydream commited on
Commit
fe2abe8
·
verified ·
1 Parent(s): 57bd583

Qwen3-Reranker-0.6B Core ML int8, compiled

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
Qwen3Reranker.mlmodelc/analytics/coremldata.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28c83e3735a90ab9d4f38cf31a31c5eb9b078ec9700443aba000fb8988a9ddf9
3
+ size 243
Qwen3Reranker.mlmodelc/coremldata.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27758036bde2510df206f4343146f90509785307dc8a607665e7fa96a0cabf2b
3
+ size 939
Qwen3Reranker.mlmodelc/model.mil ADDED
The diff for this file is too large to render. See raw diff
 
Qwen3Reranker.mlmodelc/weights/weight.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55a35f46fdda6129daf0f346a35fb1f3a1e49e4c8405c6ab65f2c9f3b13e9776
3
+ size 598934464
README.md ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: Qwen/Qwen3-Reranker-0.6B
4
+ base_model_relation: quantized
5
+ library_name: coreml
6
+ pipeline_tag: text-ranking
7
+ language:
8
+ - multilingual
9
+ - en
10
+ - zh
11
+ tags:
12
+ - coreml
13
+ - apple-neural-engine
14
+ - ane
15
+ - int8
16
+ - on-device
17
+ - reranker
18
+ - qwen3
19
+ ---
20
+
21
+ # Qwen3-Reranker-0.6B — Core ML int8 (Apple Neural Engine, compiled)
22
+
23
+ [English](#english) · [中文](#中文)
24
+
25
+ <a id="english"></a>
26
+
27
+ ## English
28
+
29
+ [Qwen/Qwen3-Reranker-0.6B](https://huggingface.co/Qwen/Qwen3-Reranker-0.6B) converted to Core ML:
30
+
31
+ - **Neural Engine.** The model runs on the Apple Neural Engine (2,566 of 2,573 ops; the other 7 are the token-embedding lookup, on the CPU).
32
+ - **int8 weights.** Activations stay fp16.
33
+ - **Precompiled.** It ships as a compiled `.mlmodelc`.
34
+ - **Fixed lengths.** Nine functions have fixed lengths from 128 to 768 tokens and share one set of weights.
35
+
36
+ It scores a (query, document) pair the way the model card does: the logits of "no" and "yes" at the last position,
37
+ and the relevance score is `sigmoid(yes − no)`.
38
+
39
+ ### Files
40
+
41
+ | File | What | Size |
42
+ |---|---|---|
43
+ | `Qwen3Reranker.mlmodelc` | int8 weights, functions `L128`, `L160`, `L192`, `L224`, `L256`, `L320`, `L384`, `L512`, `L768` | 606 MB |
44
+ | `tokenizer.json` | The original Qwen3 tokenizer, unchanged | 11 MB |
45
+ | `config.json` | Prompt strings, token ids, functions, input and output layout | |
46
+ | `SHA256SUMS` | Checksums of every file | |
47
+
48
+ Sizes are in MB = 10⁶ bytes.
49
+
50
+ ### Inputs and output
51
+
52
+ Every function `L{N}` takes:
53
+
54
+ | Name | Type | Shape | Content |
55
+ |---|---|---|---|
56
+ | `input_ids` | int32 | [1, N] | Token ids, **left-padded** with 151643 (`<\|endoftext\|>`) |
57
+ | `mask` | fp16 | [1, N] | 0 for padding, 1 for tokens |
58
+
59
+ It returns `logits`, fp32 [1, 2], in the order **[no, yes]**. Relevance = `1 / (1 + exp(no − yes))`, which is the
60
+ same as the model card's softmax over the "no" and "yes" logits.
61
+
62
+ ### Use
63
+
64
+ 1. Build three strings (`\n` is a newline). The prefix and suffix are fixed and are also in `config.json`:
65
+
66
+ ```text
67
+ prefix: <|im_start|>system\nJudge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be "yes" or "no".<|im_end|>\n<|im_start|>user\n
68
+ body: <Instruct>: {instruction}\n<Query>: {query}\n<Document>: {document}
69
+ suffix: <|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n
70
+ ```
71
+
72
+ In the body, replace `{instruction}`, `{query}` and `{document}` with your instruction, query and document.
73
+ The default instruction is `Given a web search query, retrieve relevant passages that answer the query`.
74
+ 2. Tokenize each string with `tokenizer.json`, without adding special tokens. The prefix is 39 tokens and the suffix
75
+ is 9.
76
+ 3. Cut the body's tokens so that prefix + body + suffix ≤ 768. Join the three lists; the result has n tokens.
77
+ 4. Pick the smallest N ≥ n from {128, 160, 192, 224, 256, 320, 384, 512, 768}, left-pad to N, and call function
78
+ `L{N}`.
79
+
80
+ ```python
81
+ import numpy as np, coremltools as ct
82
+ from tokenizers import Tokenizer
83
+
84
+ tok = Tokenizer.from_file("tokenizer.json")
85
+ enc = lambda s: tok.encode(s, add_special_tokens=False).ids
86
+ PREFIX = ("<|im_start|>system\nJudge whether the Document meets the requirements based on the Query and the Instruct "
87
+ "provided. Note that the answer can only be \"yes\" or \"no\".<|im_end|>\n<|im_start|>user\n")
88
+ SUFFIX = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
89
+ INSTRUCT = "Given a web search query, retrieve relevant passages that answer the query"
90
+ SIZES = [128, 160, 192, 224, 256, 320, 384, 512, 768]
91
+ models = {}
92
+
93
+ def score(query, doc):
94
+ pre, suf = enc(PREFIX), enc(SUFFIX)
95
+ body = enc(f"<Instruct>: {INSTRUCT}\n<Query>: {query}\n<Document>: {doc}")[:768 - len(pre) - len(suf)]
96
+ ids = pre + body + suf; n = len(ids); N = next(s for s in SIZES if s >= n)
97
+ if N not in models:
98
+ models[N] = ct.models.CompiledMLModel("Qwen3Reranker.mlmodelc",
99
+ compute_units=ct.ComputeUnit.CPU_AND_NE, function_name=f"L{N}")
100
+ feed = {"input_ids": np.array([[151643] * (N - n) + ids], np.int32),
101
+ "mask": np.array([[0] * (N - n) + [1] * n], np.float16)}
102
+ no, yes = models[N].predict(feed)["logits"].reshape(-1)
103
+ return float(1 / (1 + np.exp(no - yes)))
104
+
105
+ print(score("周末去哪里爬山", "香山公园秋季红叶最好看,周末游客较多,建议早上出发。"))
106
+ ```
107
+
108
+ ```swift
109
+ import CoreML
110
+
111
+ let config = MLModelConfiguration()
112
+ config.computeUnits = .cpuAndNeuralEngine
113
+ config.functionName = "L256" // smallest bucket that fits
114
+ let model = try MLModel(contentsOf: rerankerURL, configuration: config) // Qwen3Reranker.mlmodelc
115
+
116
+ let ids = try MLMultiArray(shape: [1, 256], dataType: .int32) // left-padded with 151643
117
+ let mask = try MLMultiArray(shape: [1, 256], dataType: .float16) // 0 = padding, 1 = token
118
+ // … fill ids and mask …
119
+ let out = try model.prediction(from: MLDictionaryFeatureProvider(dictionary: ["input_ids": ids, "mask": mask]))
120
+ let logits = out.featureValue(for: "logits")!.multiArrayValue!
121
+ let relevance = 1 / (1 + exp(logits[0].doubleValue - logits[1].doubleValue)) // [no, yes]
122
+ ```
123
+
124
+ Load each function once and keep it. Loading a function is slow; scoring is fast.
125
+
126
+ ### How it was converted
127
+
128
+ We wrote the Qwen3 forward pass by hand in PyTorch so it can be traced with fixed shapes:
129
+
130
+ - **Fixed length per function.** Inputs are left-padded and use a causal mask plus a padding mask. The RoPE tables are
131
+ precomputed.
132
+ - **RMSNorm safe for fp16.** On our test pairs, Qwen3's hidden states reach values above 8,000, and squaring them inside RMSNorm
133
+ overflows fp16. Each RMSNorm first divides the row by its largest absolute value, which leaves the result
134
+ mathematically unchanged. (With plain RMSNorm, our conversion of Qwen3-Embedding-0.6B, which has the same backbone,
135
+ reached only cosine 0.90 to the original on the Neural Engine.)
136
+ - **MLP scaled for fp16.** The MLP's gate × up product is scaled by 1/64 before `down_proj`, and the result is scaled
137
+ back by 64.
138
+ - **Two-row LM head.** Only the two LM-head rows that are needed ("no" 2152, "yes" 9693) are kept, so each call
139
+ returns 2 logits instead of 151,669.
140
+
141
+ Then, for each length:
142
+
143
+ 1. trace with `torch.jit.trace`;
144
+ 2. convert with coremltools 9 to an ML Program (fp16 compute, macOS 15 target);
145
+ 3. quantize to int8 with `linear_quantize_weights` (linear symmetric, per output channel, weights with more than
146
+ 2048 elements);
147
+ 4. merge the nine functions with `ct.utils.save_multifunction`, which stores the weights once;
148
+ 5. compile with `ct.utils.compile_model`.
149
+
150
+ ### Validation
151
+
152
+ Tests ran on one MacBook Pro (M3 Max, macOS 26.7) with the Neural Engine. For each query we took
153
+ [EmbeddingGemma 2](https://huggingface.co/google/embeddinggemma-2)'s top 30 results and reranked them with this model,
154
+ using the default instruction above. The reference is the original model in PyTorch (fp16, GPU), called as in its
155
+ model card.
156
+
157
+ | Test set | EmbeddingGemma 2 alone | + PyTorch reranker | **+ this model (int8, ANE)** | Rank correlation with PyTorch |
158
+ |---|---|---|---|---|
159
+ | Simulated personal knowledge base, 113 queries | 93.5 | 97.5 | **96.9** | 0.992 |
160
+ | MLQA, Chinese question → English passage, 100 queries | 60.8 | 69.0 | **68.9** | 0.993 |
161
+ | MLQA, English question → Chinese passage, 100 queries | 63.3 | 78.9 | **78.6** | 0.995 |
162
+
163
+ All scores are nDCG@10. The simulated knowledge base has 2,829 chunks of notes, Wikipedia pages, open-source
164
+ documentation and code, mixed Chinese and English, with queries written by an LLM. Rank correlation is the mean
165
+ Spearman correlation over each query's 30 candidates.
166
+
167
+ **Other checks.** An fp16 build of the same conversion matched PyTorch on three more sets:
168
+
169
+ | Test set | PyTorch reranker | fp16 build (ANE) |
170
+ |---|---|---|
171
+ | T2Retrieval (Chinese) | 94.2 | 94.3 |
172
+ | DuRetrieval (Chinese) | 93.7 | 93.8 |
173
+ | SciFact (English) | 73.0 | 71.1 |
174
+
175
+ **The instruction matters.** On SciFact, reranking with the default web-search instruction lowered nDCG@10 from 82.2
176
+ to 73.0, because SciFact's queries are scientific claims, not questions. Write an instruction that matches your task.
177
+
178
+ **Speed** (M3 Max, Neural Engine, one pair per call, median):
179
+
180
+ | Function | L128 | L160 | L192 | L224 | L256 | L320 | L384 | L512 | L768 |
181
+ |---|---|---|---|---|---|---|---|---|---|
182
+ | ms per pair | 14.5 | 20.2 | 22.7 | 25.8 | 31.1 | 44.9 | 54.0 | 83.5 | 145 |
183
+
184
+ Reranking the top 10 takes about 0.3–0.4 s per query on these test sets; the top 30 takes 0.8–1.2 s. int8 is barely
185
+ faster than fp16 (at most 6%), but it is half the size. In a test with fp16 weights, scoring 4 pairs as one batch was
186
+ slower per pair than scoring them one at a time.
187
+
188
+ ### Limitations
189
+
190
+ - **Tested on one machine only:** M3 Max with macOS 26.7. The model needs macOS 15 / iOS 18 or later, because it is a
191
+ multifunction model.
192
+ - **First load is slow.** The first load on a device compiles each function for the Neural Engine. On the M3 Max this
193
+ took 13–30 s per function, 2–3 minutes for all nine. Core ML caches the result. Apps should warm the functions up in
194
+ the background.
195
+ - **768-token limit.** Pairs longer than 768 tokens must be truncated. The original model accepts much longer inputs.
196
+ - **Small test sets.** The test sets are small and some queries are LLM-written.
197
+
198
+ ### License and attribution
199
+
200
+ - **License.** Apache 2.0, the same as [Qwen3-Reranker-0.6B](https://huggingface.co/Qwen/Qwen3-Reranker-0.6B).
201
+ - **Qwen.** The model is by the Qwen team, Alibaba Cloud.
202
+ - **This repo.** We did the Core ML conversion, the int8 quantization and the tests. This repo is not affiliated with
203
+ the Qwen team.
204
+
205
+ ---
206
+
207
+ <a id="中文"></a>
208
+
209
+ ## 中文
210
+
211
+ 本仓库是 [Qwen/Qwen3-Reranker-0.6B](https://huggingface.co/Qwen/Qwen3-Reranker-0.6B) 的 Core ML 版本:
212
+
213
+ - **神经网络引擎**:模型在 Apple 神经网络引擎(ANE)上运行(2,573 个算子中有 2,566 个在 ANE 上,剩下 7 个是查词表那一步,在 CPU 上)。
214
+ - **int8 权重**:计算仍用 fp16。
215
+ - **预先编译**:以编译好的 `.mlmodelc` 发布。
216
+ - **固定长度**:有 9 个长度固定的函数,从 128 到 768 个 token,共用一份权重。
217
+
218
+ 打分方式和官方模型卡相同:取最后一个位置上“no”和“yes”两个词的 logit,相关度 = `sigmoid(yes − no)`。
219
+
220
+ ### 文件
221
+
222
+ | 文件 | 内容 | 大小 |
223
+ |---|---|---|
224
+ | `Qwen3Reranker.mlmodelc` | int8 权重;函数 `L128`、`L160`、`L192`、`L224`、`L256`、`L320`、`L384`、`L512`、`L768` | 606 MB |
225
+ | `tokenizer.json` | Qwen3 原版分词器,未改动 | 11 MB |
226
+ | `config.json` | 提示词、特殊 token、函数列表、输入输出格式 | |
227
+ | `SHA256SUMS` | 所有文件的校验和 | |
228
+
229
+ 本页的 MB 指 10⁶ 字节。
230
+
231
+ ### 输入和输出
232
+
233
+ 每个函数 `L{N}` 的输入:
234
+
235
+ | 名称 | 类型 | 形状 | 内容 |
236
+ |---|---|---|---|
237
+ | `input_ids` | int32 | [1, N] | token id,**在左侧补齐**,补齐值为 151643(`<\|endoftext\|>`) |
238
+ | `mask` | fp16 | [1, N] | 补齐的位置为 0,有 token 的位置为 1 |
239
+
240
+ 输出是 `logits`,fp32 [1, 2],顺序是 **[no, yes]**。相关度 = `1 / (1 + exp(no − yes))`,
241
+ 和模型卡里对 no、yes 两个 logit 做 softmax 的结果相同。
242
+
243
+ ### 用法
244
+
245
+ 1. **拼三段文本**(`\n` 表示换行)。前缀和后缀是固定的,`config.json` 里也有:
246
+
247
+ ```text
248
+ prefix: <|im_start|>system\nJudge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be "yes" or "no".<|im_end|>\n<|im_start|>user\n
249
+ body: <Instruct>: {instruction}\n<Query>: {query}\n<Document>: {document}
250
+ suffix: <|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n
251
+ ```
252
+
253
+ 把 body 里的 `{instruction}`、`{query}`、`{document}` 分别换成指令、查询和文档。
254
+ 默认指令是 `Given a web search query, retrieve relevant passages that answer the query`。
255
+ 2. **分词。** 三段分别用 `tokenizer.json` 分词,不加特殊 token。前缀 39 个 token,后缀 9 个。
256
+ 3. **截断。** 截短中间一段,使前缀 + 中间 + 后缀 ≤ 768 个 token,再把三段拼起来,共 n 个 token。
257
+ 4. **运行。** 在 {128, 160, 192, 224, 256, 320, 384, 512, 768} 中选出不小于 n 的最小值 N,在左侧补齐到 N,
258
+ 然后调用函数 `L{N}`。
259
+
260
+ ```python
261
+ import numpy as np, coremltools as ct
262
+ from tokenizers import Tokenizer
263
+
264
+ tok = Tokenizer.from_file("tokenizer.json")
265
+ enc = lambda s: tok.encode(s, add_special_tokens=False).ids
266
+ PREFIX = ("<|im_start|>system\nJudge whether the Document meets the requirements based on the Query and the Instruct "
267
+ "provided. Note that the answer can only be \"yes\" or \"no\".<|im_end|>\n<|im_start|>user\n")
268
+ SUFFIX = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
269
+ INSTRUCT = "Given a web search query, retrieve relevant passages that answer the query"
270
+ SIZES = [128, 160, 192, 224, 256, 320, 384, 512, 768]
271
+ models = {}
272
+
273
+ def score(query, doc):
274
+ pre, suf = enc(PREFIX), enc(SUFFIX)
275
+ body = enc(f"<Instruct>: {INSTRUCT}\n<Query>: {query}\n<Document>: {doc}")[:768 - len(pre) - len(suf)]
276
+ ids = pre + body + suf; n = len(ids); N = next(s for s in SIZES if s >= n)
277
+ if N not in models:
278
+ models[N] = ct.models.CompiledMLModel("Qwen3Reranker.mlmodelc",
279
+ compute_units=ct.ComputeUnit.CPU_AND_NE, function_name=f"L{N}")
280
+ feed = {"input_ids": np.array([[151643] * (N - n) + ids], np.int32),
281
+ "mask": np.array([[0] * (N - n) + [1] * n], np.float16)}
282
+ no, yes = models[N].predict(feed)["logits"].reshape(-1)
283
+ return float(1 / (1 + np.exp(no - yes)))
284
+
285
+ print(score("周末去哪里爬山", "香山公园秋季红叶最好看,周末游客较多,建议早上出发。"))
286
+ ```
287
+
288
+ ```swift
289
+ import CoreML
290
+
291
+ let config = MLModelConfiguration()
292
+ config.computeUnits = .cpuAndNeuralEngine
293
+ config.functionName = "L256" // 能放下这一对的最小长度档
294
+ let model = try MLModel(contentsOf: rerankerURL, configuration: config) // Qwen3Reranker.mlmodelc
295
+
296
+ let ids = try MLMultiArray(shape: [1, 256], dataType: .int32) // 在左侧用 151643 补齐
297
+ let mask = try MLMultiArray(shape: [1, 256], dataType: .float16) // 0 = 补齐,1 = token
298
+ // …… 填入 ids 和 mask ……
299
+ let out = try model.prediction(from: MLDictionaryFeatureProvider(dictionary: ["input_ids": ids, "mask": mask]))
300
+ let logits = out.featureValue(for: "logits")!.multiArrayValue!
301
+ let relevance = 1 / (1 + exp(logits[0].doubleValue - logits[1].doubleValue)) // 顺序是 [no, yes]
302
+ ```
303
+
304
+ 每个函数加载一次后保留复用:加载慢,打分快。
305
+
306
+ ### 转换方法
307
+
308
+ 我们用 PyTorch 手写了 Qwen3 的前向计算,使它能以固定形状被追踪:
309
+
310
+ - **每个函数长度固定**:输入在左侧补齐,使用因果遮罩和补齐遮罩;RoPE 表预先算好。
311
+ - **防 fp16 溢出的 RMSNorm**:在我们的测试样本上,Qwen3 的隐藏状态有超过 8,000 的离群值,在 RMSNorm 里平方后会超出 fp16 的范围。
312
+ 每个 RMSNorm 先把这一行除以它的最大绝对值,数学上结果不变。(我们转换同一骨干的 Qwen3-Embedding-0.6B 时,
313
+ 用普通 RMSNorm 在神经网络引擎上和原版的余弦相似度只有 0.90。)
314
+ - **防溢出的 MLP**:MLP 中 gate × up 的乘积先乘以 1/64,经过 `down_proj` 之后再乘回 64。
315
+ - **只保留两行输出层**:只保留需要的两行(“no” 2152、“yes” 9693),每次调用只输出 2 个 logit,而不是 151,669 个。
316
+
317
+ 然后对每个长度:
318
+
319
+ 1. 用 `torch.jit.trace` 追踪;
320
+ 2. 用 coremltools 9 转成 ML Program(fp16 计算,最低 macOS 15);
321
+ 3. 用 `linear_quantize_weights` 压成 int8(线性对称,按输出通道;只压缩元素数超过 2048 的权重);
322
+ 4. 用 `ct.utils.save_multifunction` 把 9 个函数合并成一个模型,权重只存一份;
323
+ 5. 用 `ct.utils.compile_model` 编译。
324
+
325
+ ### 验证
326
+
327
+ 在一台 MacBook Pro(M3 Max,macOS 26.7)上测试,模型跑在神经网络引擎上。对每条查询,先取
328
+ [EmbeddingGemma 2](https://huggingface.co/google/embeddinggemma-2) 检索出的前 30 条结果,再用本模型重排,指令用上面的默认指令。
329
+ 参照是 PyTorch 原版模型(fp16,GPU),调用方式和模型卡相同。
330
+
331
+ | 测试集 | 只用 EmbeddingGemma 2 | + PyTorch 原版重排 | **+ 本模型(int8,ANE)** | 和 PyTorch 排序的相关系数 |
332
+ |---|---|---|---|---|
333
+ | 模拟个人知识库,113 条查询 | 93.5 | 97.5 | **96.9** | 0.992 |
334
+ | MLQA,中文问题找英文段落,100 条查询 | 60.8 | 69.0 | **68.9** | 0.993 |
335
+ | MLQA,英文问题找中文段落,100 条查询 | 63.3 | 78.9 | **78.6** | 0.995 |
336
+
337
+ - **指标**:都是 nDCG@10。
338
+ - **模拟个人知识库**:2,829 个文本块,内容包括笔记、维基百科页面、开源文档和代码,中英混合;查询由大模型编写。
339
+ - **相关系数**:对每条查询的 30 个候选计算 Spearman 相关系数,再取平均。
340
+
341
+ **其他检查**:同一转换方法的 fp16 版本在另外三个测试集上也和 PyTorch 一致:
342
+
343
+ | 测试集 | PyTorch 原版重排 | fp16 版本(ANE) |
344
+ |---|---|---|
345
+ | T2Retrieval(中文) | 94.2 | 94.3 |
346
+ | DuRetrieval(中文) | 93.7 | 93.8 |
347
+ | SciFact(英文) | 73.0 | 71.1 |
348
+
349
+ **指令很重要**:在 SciFact 上,用默认的网页搜索指令重排后,nDCG@10 从 82.2 降到了 73.0。
350
+ 原因是 SciFact 的查询是科学论断,不是问题。请按自己的任务写指令。
351
+
352
+ **速度**(M3 Max,神经网络引擎,每次调用打一对分,取中位数):
353
+
354
+ | 函数 | L128 | L160 | L192 | L224 | L256 | L320 | L384 | L512 | L768 |
355
+ |---|---|---|---|---|---|---|---|---|---|
356
+ | 每对耗时(ms) | 14.5 | 20.2 | 22.7 | 25.8 | 31.1 | 44.9 | 54.0 | 83.5 | 145 |
357
+
358
+ - **每条查询的耗时**:在这些测试集上,重排前 10 条约 0.3–0.4 秒,前 30 条约 0.8–1.2 秒。
359
+ - **int8 和 fp16 对比**:int8 只比 fp16 快一点(最多 6%),但体积减半。
360
+ - **批量打分**:在 fp16 版本上测过,把 4 对放在一个批次里打分,平均每对反而比逐对打分更慢。
361
+
362
+ ### 局限
363
+
364
+ - **只在一台机器上测过**:M3 Max,macOS 26.7。模型是多函数模型,需要 macOS 15 / iOS 18 或更高版本。
365
+ - **第一次加载很慢**:在每台设备上第一次加载时,系统要把每个函数编译给神经网络引擎。M3 Max 上每个函数需要 13–30 秒,
366
+ 9 个函数共 2–3 分钟。Core ML 会缓存编译结果。建议 App 在后台预热各个函数。
367
+ - **最长 768 个 token**:超过 768 个 token 的输入必须截断,而原版模型支持长得多的输入。
368
+ - **测试集很小**:部分查询由大模型编写。
369
+
370
+ ### 许可证和来源
371
+
372
+ - **许可证**:Apache 2.0,和 [Qwen3-Reranker-0.6B](https://huggingface.co/Qwen/Qwen3-Reranker-0.6B) 相同。
373
+ - **Qwen**:模型由阿里云通义千问团队发布。
374
+ - **本仓库**:我们做了 Core ML 转换、int8 量化和测试。本仓库与通义千问团队没有关联。
SHA256SUMS ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 LICENSE
2
+ 28c83e3735a90ab9d4f38cf31a31c5eb9b078ec9700443aba000fb8988a9ddf9 Qwen3Reranker.mlmodelc/analytics/coremldata.bin
3
+ 27758036bde2510df206f4343146f90509785307dc8a607665e7fa96a0cabf2b Qwen3Reranker.mlmodelc/coremldata.bin
4
+ 8df1324548aa3585be89f00627f887571f3ac40b6b816ab8f9439842e32ad9b8 Qwen3Reranker.mlmodelc/model.mil
5
+ 55a35f46fdda6129daf0f346a35fb1f3a1e49e4c8405c6ab65f2c9f3b13e9776 Qwen3Reranker.mlmodelc/weights/weight.bin
6
+ 184530324f224da2898a7ee094e6b2e68a137d263e4fc936582865536eb828f6 config.json
7
+ aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4 tokenizer.json
config.json ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_model": "Qwen/Qwen3-Reranker-0.6B",
3
+ "format": "coreml-compiled",
4
+ "model": "Qwen3Reranker.mlmodelc",
5
+ "compute_units": "cpuAndNeuralEngine",
6
+ "precision": {
7
+ "weights": "int8 (linear symmetric, per output channel)",
8
+ "activations": "fp16"
9
+ },
10
+ "minimum_os": {
11
+ "macOS": "15.0",
12
+ "iOS": "18.0"
13
+ },
14
+ "tokenizer": "tokenizer.json",
15
+ "add_special_tokens": false,
16
+ "functions": {
17
+ "L128": {
18
+ "tokens": 128
19
+ },
20
+ "L160": {
21
+ "tokens": 160
22
+ },
23
+ "L192": {
24
+ "tokens": 192
25
+ },
26
+ "L224": {
27
+ "tokens": 224
28
+ },
29
+ "L256": {
30
+ "tokens": 256
31
+ },
32
+ "L320": {
33
+ "tokens": 320
34
+ },
35
+ "L384": {
36
+ "tokens": 384
37
+ },
38
+ "L512": {
39
+ "tokens": 512
40
+ },
41
+ "L768": {
42
+ "tokens": 768
43
+ }
44
+ },
45
+ "inputs": {
46
+ "input_ids": {
47
+ "dtype": "int32",
48
+ "shape": [
49
+ 1,
50
+ "L"
51
+ ],
52
+ "padding": "left",
53
+ "pad_token_id": 151643
54
+ },
55
+ "mask": {
56
+ "dtype": "float16",
57
+ "shape": [
58
+ 1,
59
+ "L"
60
+ ],
61
+ "values": "0 for padding, 1 for tokens"
62
+ }
63
+ },
64
+ "output": {
65
+ "logits": {
66
+ "dtype": "float32",
67
+ "shape": [
68
+ 1,
69
+ 2
70
+ ],
71
+ "order": [
72
+ "no",
73
+ "yes"
74
+ ],
75
+ "score": "sigmoid(yes - no) = probability that the document is relevant"
76
+ }
77
+ },
78
+ "token_ids": {
79
+ "yes": 9693,
80
+ "no": 2152,
81
+ "pad": 151643
82
+ },
83
+ "prompt": {
84
+ "prefix": "<|im_start|>system\nJudge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be \"yes\" or \"no\".<|im_end|>\n<|im_start|>user\n",
85
+ "body": "<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {document}",
86
+ "suffix": "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
87
+ "default_instruction": "Given a web search query, retrieve relevant passages that answer the query",
88
+ "prefix_tokens": 39,
89
+ "suffix_tokens": 9,
90
+ "truncate": "truncate the body tokens so prefix + body + suffix <= 768"
91
+ }
92
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4
3
+ size 11422654