File size: 13,931 Bytes
7ef8e61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c82c36
 
 
 
 
 
 
 
 
 
 
 
7ef8e61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
diff --git a/common/common.cpp b/common/common.cpp
index 9a71a33..7803c15 100644
--- a/common/common.cpp
+++ b/common/common.cpp
@@ -1172,6 +1172,7 @@
     { COMMON_DECISION_TYPE_PPLX_DECIDER,   "pplx-decider"  },
     { COMMON_DECISION_TYPE_LFM2_D1,        "lfm2-d1"       },
     { COMMON_DECISION_TYPE_LFM2_D1_OMNI,   "lfm2-d1-omni"  },
+    { COMMON_DECISION_TYPE_CRIVO,         "crivo"         },
 };
 
 static common_decision_type common_decision_type_from_string(const std::string & str) {
@@ -1289,7 +1290,7 @@
     // TODO: maybe improve this in the future
     const auto decision_type = common_get_decision_type(model);
     if (decision_type == COMMON_DECISION_TYPE_LAYA || decision_type == COMMON_DECISION_TYPE_KEV || decision_type == COMMON_DECISION_TYPE_CLEF ||
-        decision_type == COMMON_DECISION_TYPE_LFM2_D1_OMNI) {
+        decision_type == COMMON_DECISION_TYPE_LFM2_D1_OMNI || decision_type == COMMON_DECISION_TYPE_CRIVO) {
         params.embedding    = true;
         params.pooling_type = LLAMA_POOLING_TYPE_NONE;
 
diff --git a/common/common.h b/common/common.h
index d89f803..4b6b9af 100644
--- a/common/common.h
+++ b/common/common.h
@@ -965,6 +965,7 @@
     COMMON_DECISION_TYPE_PPLX_DECIDER, // same as openjev, label codes of 1 or 2 letters
     COMMON_DECISION_TYPE_LFM2_D1, // same as openjev, the labels depend on the question type
     COMMON_DECISION_TYPE_LFM2_D1_OMNI, // same as laya, other prompt layout
+    COMMON_DECISION_TYPE_CRIVO,       // same as laya without head blocks, one marker token per option
     COMMON_DECISION_TYPE_UNKNOWN, // a decision model of a type that is not supported
 };
 
diff --git a/conversion/__init__.py b/conversion/__init__.py
index 2a62dba..a5aa647 100644
--- a/conversion/__init__.py
+++ b/conversion/__init__.py
@@ -203,6 +203,7 @@
     "ModernBertForMaskedLM": "bert",
     "ModernBertForSequenceClassification": "bert",
     "ModernBertModel": "bert",
+    "ModernBertOptDecisionModel": "bert",
     "NanbeigeForCausalLM": "nanbeige",
     "NemotronForCausalLM": "nemotron",
     "NemotronHForCausalLM": "nemotron",
diff --git a/conversion/bert.py b/conversion/bert.py
index f247154..d27a486 100644
--- a/conversion/bert.py
+++ b/conversion/bert.py
@@ -745,3 +745,71 @@
             name = f"head.layers.{bid}.{suffix}"
 
         yield from super().modify_tensors(data_torch, name, bid)
+
+
+def _is_crivo_checkpoint(dir_model: Path) -> bool:
+    config_path = dir_model / "config.json"
+    if not config_path.is_file():
+        return False
+    with open(config_path, encoding="utf-8") as f:
+        config = json.load(f)
+    return config.get("model_type") == "modernbert" and "opt_token" in config.get("decision", {})
+
+
+@ModelBase.register_hparams_loader(_is_crivo_checkpoint)
+def _load_crivo_hparams(dir_model: Path) -> dict[str, Any]:
+    logger.info("gguf: detected ModernBert decision checkpoint (crivo)")
+    with open(dir_model / "config.json", encoding="utf-8") as f:
+        hparams = json.load(f)
+    hparams["architectures"] = ["ModernBertOptDecisionModel"]
+    return hparams
+
+
+@ModelBase.register("ModernBertOptDecisionModel")
+@ModelBase.example("tardellirs/crivo-150m")
+class ModernBertOptDecisionModel(ModernBertModel):
+    model_arch = gguf.MODEL_ARCH.MODERN_BERT
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        # crivo has no classifier, drop the dummy LABEL_0
+        self.cls_out_labels = None
+
+    def set_vocab(self):
+        super().set_vocab()
+        self.gguf_writer.add_add_sep_token(False)
+        self.gguf_writer.add_token_type_count(3)  # choice, score, noul
+        self.gguf_writer.add_chat_template([{"name": "systemone", "template": self._systemone_template()}])
+
+    def _systemone_template(self) -> str:
+        with open(self.dir_model / "tokenizer_config.json", encoding="utf-8") as f:
+            tokenizer_config = json.load(f)
+        tok_cls, tok_sep = (tokenizer_config[k] for k in ("cls_token", "sep_token"))
+        # the special tokens are adjacent to the text, no spaces, so the whole prompt
+        # tokenizes the same way as the pieces did during training
+        return (
+            tok_cls + "{{ instructions }}" + tok_sep + "{{ state }}" + tok_sep
+            + "{% for o in options %}[OPT]{{ o.text }}{% endfor %}"
+        )
+
+    def set_gguf_parameters(self):
+        super().set_gguf_parameters()
+        self.gguf_writer.add_decision_type(gguf.DecisionType.CRIVO)
+        self.gguf_writer.add_decision_block_count(0)
+
+    @classmethod
+    def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
+        name, gen = item
+
+        if name.startswith("encoder."):
+            name = name[8:]
+
+        return super().filter_tensors((name, gen))
+
+    def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
+        if name == "type_embedding.weight":
+            # the rows are [noul, choice, score], the server reads [choice, score, noul]
+            name = "token_types.weight"
+            data_torch = data_torch[[1, 2, 0], :]
+
+        yield from super().modify_tensors(data_torch, name, bid)
diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py
index 9ed43c7..d009eea 100644
--- a/gguf-py/gguf/constants.py
+++ b/gguf-py/gguf/constants.py
@@ -6089,6 +6089,7 @@
     PPLX_DECIDER = "pplx-decider"  # same as openjev, label codes of 1 or 2 letters
     LFM2_D1 = "lfm2-d1"  # same as openjev, the labels depend on the question type
     LFM2_D1_OMNI = "lfm2-d1-omni"  # same head as laya on a bidirectional LFM2 trunk, other prompt layout
+    CRIVO   = "crivo"    # same head as laya without head blocks, one marker token per option
 
 
 class VisionProjectorType:
diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp
index 5f77d43..d5a4ac4 100644
--- a/tools/server/server-common.cpp
+++ b/tools/server/server-common.cpp
@@ -158,6 +158,7 @@ std::vector<std::string> server_model_output_modalities(common_decision_type dec
         case COMMON_DECISION_TYPE_PPLX_DECIDER:
         case COMMON_DECISION_TYPE_LFM2_D1:
         case COMMON_DECISION_TYPE_LFM2_D1_OMNI:
+        case COMMON_DECISION_TYPE_CRIVO:
             return {"decisions"};
         default:
             // fallback when there is no decision type or the metadata is bad
diff --git a/src/models/modern-bert.cpp b/src/models/modern-bert.cpp
index 84c85f8..15474c0 100644
--- a/src/models/modern-bert.cpp
+++ b/src/models/modern-bert.cpp
@@ -34,14 +34,17 @@
         hparams.act_cls = GGML_UNARY_OP_GELU_ERF;
     }
 
-    ml.get_key(LLM_KV_DECISION_BLOCK_COUNT, hparams.n_layer_decision, false);
-    if (hparams.n_layer_decision > 0) {
-        if (hparams.n_layer_decision >= hparams.n_layer()) {
-            throw std::runtime_error("invalid number of decision blocks");
-        }
-        // the head blocks always use full attention
-        for (uint32_t il = hparams.n_layer() - hparams.n_layer_decision; il < hparams.n_layer(); il++) {
-            hparams.is_swa_impl[il] = false;
+    // a decision model can have zero head blocks, the scorer runs on the encoder output
+    const bool is_decision = ml.get_key(LLM_KV_DECISION_BLOCK_COUNT, hparams.n_layer_decision, false);
+    if (is_decision) {
+        if (hparams.n_layer_decision > 0) {
+            if (hparams.n_layer_decision >= hparams.n_layer()) {
+                throw std::runtime_error("invalid number of decision blocks");
+            }
+            // the head blocks always use full attention
+            for (uint32_t il = hparams.n_layer() - hparams.n_layer_decision; il < hparams.n_layer(); il++) {
+                hparams.is_swa_impl[il] = false;
+            }
         }
         // the output is one score per question type
         hparams.n_embd_out_impl = N_DECISION_TYPES;
@@ -92,7 +95,7 @@
     cls       = create_tensor(tn(LLM_TENSOR_CLS,      "weight"), {n_embd, n_embd},            TENSOR_NOT_REQUIRED);
     cls_norm  = create_tensor(tn(LLM_TENSOR_CLS_NORM, "weight"), {n_embd},                    TENSOR_NOT_REQUIRED);
 
-    if (hparams.n_layer_decision == 0) {
+    if (hparams.n_embd_out_impl == 0) {
         return;
     }
 
@@ -236,7 +239,7 @@
             LLM_NORM, -1);
     cb(cur, "final_norm_out", -1);
 
-    if (n_layer_dec > 0) {
+    if (hparams.n_embd_out_impl > 0) {
         cur = build_decision_head(model, cur, inp_attn, inp_out_ids);
     }
 
diff --git a/tools/server/server-decision.cpp b/tools/server/server-decision.cpp
index 11ad66a..aec75ef 100644
--- a/tools/server/server-decision.cpp
+++ b/tools/server/server-decision.cpp
@@ -132,6 +132,15 @@
             throw std::runtime_error("decision model has no mask token");
         }
         n_options_max = 255;
+    } else if (model_type == COMMON_DECISION_TYPE_CRIVO) {
+        // the options are marked with a dedicated token
+        const auto toks = common_tokenize(vocab, "[OPT]", false, true);
+        if (toks.size() != 1) {
+            throw std::runtime_error("decision model has no [OPT] token");
+        }
+        token_marker = toks[0];
+        text_marker  = common_token_to_piece(vocab, token_marker, true);
+        n_options_max = 255;
     } else {
         throw std::runtime_error("unsupported decision model type: " + type_name);
     }
@@ -420,6 +429,31 @@
     return val;
 }
 
+// crivo renders a value like its training code: strings are stripped, other JSON is compact with sorted keys
+static std::string decision_crivo_render(const json & val) {
+    if (val.is_null()) {
+        return "";
+    }
+    if (val.is_string()) {
+        return string_strip(val.get<std::string>());
+    }
+    return decision_sort_keys(val).dump_safe(-1);
+}
+
+// crivo option text: choice is "key: desc" (or just the key), noul is "false: desc"/"true: desc" (or No./Yes.), score is "i: desc"
+static std::string decision_crivo_option_text(server_decision_question_type qtype, const server_decision_option & opt) {
+    const std::string d = decision_crivo_render(opt.description);
+    switch (qtype) {
+        case SERVER_DECISION_QUESTION_CHOICE:
+            return (d.empty() || d == opt.key) ? opt.key : opt.key + ": " + d;
+        case SERVER_DECISION_QUESTION_NOUL:
+            return d.empty() ? (opt.key == "true" ? "Yes." : "No.") : opt.key + ": " + d;
+        case SERVER_DECISION_QUESTION_SCORE:
+            return opt.key + ": " + d;
+    }
+    return opt.key;
+}
+
 // given to the lfm2-d1-omni template: text between the pieces of the prompt, and at the start of the pieces that are cut to a token budget
 static const std::string D1OMNI_MARKER        = "<<d1omni:";
 static const std::string D1OMNI_SEP           = "<<d1omni:sep>>";
@@ -567,6 +601,9 @@
                 option["description"] = decision_kev_text(opt.description);
             }
         }
+        if (type == COMMON_DECISION_TYPE_CRIVO) {
+            option["text"] = decision_crivo_option_text(question.type, opt);
+        }
         if (!label_texts.empty()) {
             option["label"] = label_texts[i];
         }
@@ -618,6 +655,12 @@
         inp["instructions"] = decision_kev_text(question.instructions);
     }
 
+    // the crivo template takes the pieces pre-rendered, like the training code
+    if (type == COMMON_DECISION_TYPE_CRIVO) {
+        inp["state"]        = decision_crivo_render(state);
+        inp["instructions"] = decision_crivo_render(question.instructions);
+    }
+
     // the input must not contain the marker of the options
     if (!text_marker.empty()) {
         inp = decision_replace_text(inp, text_marker, " ");
@@ -689,6 +732,9 @@
     if (type == COMMON_DECISION_TYPE_LAYA) {
         fill_task_laya(tokens, question, task);
     }
+    if (type == COMMON_DECISION_TYPE_CRIVO) {
+        fill_task_crivo(tokens, question, task);
+    }
     if (type == COMMON_DECISION_TYPE_KEV) {
         // an option is read at its end token, the question at the last token
         for (size_t i = 0; i < tokens.size(); i++) {
@@ -761,6 +807,22 @@
     task.decision.column = question.type;
 }
 
+// the prompt is: [cls] instructions [sep] state [sep] ([opt] option)*
+// crivo reads the inputs whole, the score of each option is read at its marker
+void server_decision_context::fill_task_crivo(llama_tokens & tokens, const server_decision_question & question, server_task & task) const {
+    const size_t n_options = question.options.size();
+    for (size_t i = 0; i < tokens.size(); i++) {
+        if (tokens[i] == token_marker) {
+            task.decision.markers.push_back(i);
+        }
+    }
+    if (task.decision.markers.size() != n_options) {
+        throw std::runtime_error("unexpected layout of the decision prompt");
+    }
+    // the output has one score per question type
+    task.decision.column = question.type;
+}
+
 // each piece is cut to its budget as the model was trained (d1-omni prompt.py: encode), the state gets the room that is left
 // the media come first, the text after them has a budget of its own
 void server_decision_context::fill_task_d1omni(
diff --git a/tools/server/server-decision.h b/tools/server/server-decision.h
index 5c7e44f..3e49275 100644
--- a/tools/server/server-decision.h
+++ b/tools/server/server-decision.h
@@ -137,6 +137,7 @@
     // LFM2_D1: label text and tokens of each option
     void d1_labels(const server_decision_question & question, std::vector<std::string> & texts, std::vector<llama_tokens> & groups) const;
     void fill_task_laya(llama_tokens & tokens, const server_decision_question & question, server_task & task) const;
+    void fill_task_crivo(llama_tokens & tokens, const server_decision_question & question, server_task & task) const;
     void fill_task_d1omni(
             const json & state,
             const std::vector<server_decision_question> & questions,