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 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()); + } + 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 = "< & texts, std::vector & 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 & questions,