nemotron 3.5 implementation

This commit is contained in:
Gaspa79 authored and StillDeadcode committed 2026-10-30 10:22:53 +01:00
1 parent 33108e488b
commit 94c90b17ad
59 files changed
+6046 -76

No files matched your search

+4
View File
@@ -19,6 +19,8 @@
#include <string_view>
#include <vector>
struct RadModelMeta;
namespace rad {
namespace gen { struct Request; struct AudioRequest; class AudioTicket; struct VideoRequest; class VideoTicket; }
namespace mm { struct Frame; struct Item; }
@@ -539,6 +541,8 @@ public:
virtual std::string default_prompt() const { return std::string(); }
/* The chat template a `messages` input renders through, or null. */
virtual IChatTemplate* message_template() const { return nullptr; }
/* Read-only checkpoint metadata for the server's input formatter; null when unknown. */
virtual const RadModelMeta* metadata() const { return nullptr; }
};
/* Multimodal preprocessing (spec §11). The server pulls the bytes out of a content part; the
+117
View File
@@ -0,0 +1,117 @@
#include "server/nemotron35.h"
#include "rad_plugin.h"
#include <cstring>
namespace rad::server {
bool nemotron35_retrieval_meta(const RadModelMeta* meta) {
if (!meta) return false;
const auto is = [&](const char* key, const char* value) {
return !std::strcmp(rad_meta_gets(meta, key, ""), value);
};
const auto noncausal = [&](const char* key) { return is(key, "0") || is(key, "false"); };
return is("model_type", "mistral3") && is("text_config.model_type", "ministral3") &&
is("vision_config.model_type", "pixtral") && noncausal("is_causal") &&
noncausal("text_config.is_causal");
}
int nemotron35_format(const json& messages, std::vector<Nemotron35Piece>* pieces,
std::string* why) {
if (!pieces) return RAD_E_INVAL;
pieces->clear();
auto no = [&](const char* message) {
if (why) *why = message;
pieces->clear();
return RAD_E_INVAL;
};
if (!messages.is_array() || (messages.size() != 1 && messages.size() != 2))
return no(
"retrieval inputs require one user message with an optional leading system prefix");
for (size_t i = 0; i < messages.size(); ++i) {
const auto& msg = messages[i];
const char* role = i + 1 == messages.size() ? "user" : "system";
if (!msg.is_object() || !msg.contains("role") || msg["role"] != role ||
!msg.contains("content"))
return no(
"retrieval inputs require one user message with an optional leading system prefix");
}
auto text = [&](const std::string& s) {
if (!pieces->empty() && !pieces->back().image)
pieces->back().text += s;
else {
Nemotron35Piece p;
p.text = s;
pieces->push_back(std::move(p));
}
};
if (messages.size() == 2) {
const auto& content = messages[0]["content"];
std::string prefix;
if (content.is_string())
prefix = content.get<std::string>();
else if (content.is_array()) {
bool first = true;
for (const auto& block : content) {
if (!block.is_object() || block.value("type", json()) != "text" ||
!block.contains("text") || !block["text"].is_string())
return no("system content may contain only text blocks");
if (!first) prefix += "\n\n";
prefix += block["text"].get<std::string>();
first = false;
}
} else
return no("system content must be a string or a list of text blocks");
while (!prefix.empty() && prefix.back() == ' ')
prefix.pop_back();
text(prefix + " ");
}
const auto escape = [](const std::string& s) {
std::string out;
for (char c : s) {
out += c;
if (c == '[' || c == '<') out += "\xe2\x80\x8c";
}
return out;
};
const auto& user = messages.back()["content"];
if (user.is_string())
text(escape(user.get<std::string>()));
else if (user.is_array()) {
/* Stable image-before-text canonicalization. The image part itself moves with its
* bytes, so image identity cannot be lost when the original list starts with text. */
for (const auto& block : user) {
if (!block.is_object() || !block.contains("type") || !block["type"].is_string())
return no("user content must contain typed text and image blocks");
const auto type = block["type"].get<std::string>();
if (type != "text" && type != "image_url" && type != "image" && type != "input_image")
return no("user content supports only text and image blocks");
if (type == "text" && (!block.contains("text") || !block["text"].is_string()))
return no("user text blocks require string text");
}
bool emitted = false;
for (const auto& block : user)
if (block["type"] != "text") {
if (emitted) text(" ");
Nemotron35Piece p;
p.image = true;
p.content = block;
pieces->push_back(std::move(p));
emitted = true;
}
for (const auto& block : user)
if (block["type"] == "text") {
if (emitted) text(" ");
text(escape(block["text"].get<std::string>()));
emitted = true;
}
} else
return no("user content must be a string or a list of text and image blocks");
bool has_image = false;
for (const auto& p : *pieces)
has_image |= p.image;
if (has_image)
for (const auto& p : *pieces)
if (!p.image && p.text.find("[IMG]") != std::string::npos)
return no("a retrieval system prefix cannot add image placeholders");
return RAD_OK;
}
} // namespace rad::server
+18
View File
@@ -0,0 +1,18 @@
/* Nemotron 3.5's retrieval template, with images kept typed until token assembly.
* Other embedding models continue through their existing template/raw-input paths. */
#pragma once
#include "server/iface.h"
#include <nlohmann/json.hpp>
struct RadModelMeta;
namespace rad::server {
struct Nemotron35Piece {
bool image = false;
std::string text;
json content; // the original image part, including its data URL
};
bool nemotron35_retrieval_meta(const RadModelMeta* meta);
int nemotron35_format(const json& messages, std::vector<Nemotron35Piece>* pieces, std::string* why);
} // namespace rad::server
+118 -14
View File
@@ -3,6 +3,7 @@
#include "json_partial.h"
#include "rad_internal.h"
#include "mm/processor.h"
#include "server/nemotron35.h"
#include <nlohmann/json.hpp>
@@ -2386,6 +2387,80 @@ static int embedding_input(const std::string& text,
return RAD_OK;
}
/* Keep model-owned image blocks typed: sending an internal sentinel through this template
* turns it into escaped user text. Adjacent text is joined before tokenization, preserving BPE
* boundaries, and no implicit BOS/EOS is added to the retrieval template's output. */
static int nemotron35_embedding_input(const json& messages, const OaiDeps& d, const OaiLimits& lim,
int32_t image_tokens, const char* field, OaiRequest* out,
ApiError* err) {
std::vector<Nemotron35Piece> pieces;
std::string why;
if (nemotron35_format(messages, &pieces, &why) < 0) {
*err = err_bad(field, why);
return RAD_E_INVAL;
}
size_t n_images = 0;
for (const auto& piece : pieces)
n_images += piece.image ? 1 : 0;
PromptInput p;
auto media = std::make_shared<mm::PromptMedia>();
for (const auto& piece : pieces) {
if (!piece.image) {
p.text += piece.text;
const auto ids = d.tok->encode(piece.text, false, /*parse_special=*/true);
p.tokens.insert(p.tokens.end(), ids.begin(), ids.end());
continue;
}
MediaKind kind;
std::vector<uint8_t> bytes;
std::string type = piece.content["type"].get<std::string>();
if (type == "image")
type = "image_url"; // template spelling; transport still requires a data URL
const char* part_field =
!std::strcmp(field, "messages") ? "messages[].content[]" : "input[]";
const int rc = read_media_part(piece.content, type, part_field, d, lim, &kind, &bytes, err);
if (rc < 0) return rc;
if (rc == 0 || kind != MediaKind::Image) {
*err = err_bad(part_field,
"Nemotron retrieval inputs support only text and image data URLs");
return RAD_E_INVAL;
}
MediaOpts opts;
opts.image_tokens = image_tokens;
opts.several_pictures = n_images > 1;
std::shared_ptr<mm::Item> item;
const int status = d.mm->prepare(kind, bytes, opts, &item, &why);
if (status < 0 || !item) {
*err = err_bad(part_field, "the image could not be used: " +
(why.empty() ? std::string(rad_strerror(status)) : why));
return status < 0 ? status : RAD_E_INVAL;
}
p.text += "[IMG]";
mm::Placed pl;
pl.item = std::move(item);
pl.tok = (int32_t)p.tokens.size();
p.tokens.insert(p.tokens.end(), pl.item->expand.begin(), pl.item->expand.end());
media->items.push_back(std::move(pl));
}
if (!media->items.empty()) {
media->layout();
p.media = std::move(media);
}
out->prompts.push_back(std::move(p));
return RAD_OK;
}
int check_embedding_template(const IEmbedder* embed, bool overridden, std::string* why) {
if (overridden && embed && nemotron35_retrieval_meta(embed->metadata())) {
if (why)
*why = "Nemotron 3.5 uses its reference retrieval formatter; "
"--override-chat-template is not supported for this model. "
"Use a system prefix or prompt_name.";
return RAD_E_UNSUPPORTED;
}
return RAD_OK;
}
int parse_embeddings_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
OaiRequest* out, ApiError* err) {
json b;
@@ -2450,6 +2525,41 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
}
}
const bool nemotron35 =
d.embed && nemotron35_retrieval_meta(d.embed->metadata());
auto finish_inputs = [&]() -> int {
int64_t cap = lim.max_ctx;
if (nemotron35) {
cap = cap > 0 ? std::min<int64_t>(cap, 32768) : 32768;
if (d.embed->max_input() > 0) cap = std::min(cap, d.embed->max_input());
}
for (size_t i = 0; i < out->prompts.size(); ++i) {
const int64_t n = (int64_t)out->prompts[i].tokens.size();
if (n == 0) {
*err = err_bad("input", "tokenised to nothing");
return RAD_E_INVAL;
}
if (cap > 0 && n > cap) {
*err = err_bad("input",
"input " + std::to_string(i) + " is " + std::to_string(n) +
(nemotron35 ? " tokens, more than the embedding input limit of "
: " tokens, more than the model context of ") +
std::to_string(cap));
err->code = "context_length_exceeded";
err->n_prompt_tokens = n;
err->n_ctx = cap;
return RAD_E_INVAL;
}
}
return RAD_OK;
};
auto retrieval = [&](const json& content) -> int {
json messages = json::array();
if (!prefix.empty()) messages.push_back({{"role", "system"}, {"content", prefix}});
messages.push_back({{"role", "user"}, {"content", content}});
return nemotron35_embedding_input(messages, d, lim, out->image_tokens, "input", out, err);
};
/* vLLM's chat embedding (`messages`): one input rendered by the model's chat template
* (EmbeddingGemma 2's concatenates the system text, then each message's text and media
* placeholders), with the tokenizer's special tokens around the whole. */
@@ -2463,6 +2573,11 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
"and takes no prompt");
return RAD_E_INVAL;
}
if (nemotron35) {
RAD_TRY(nemotron35_embedding_input(b.at("messages"), d, lim, out->image_tokens,
"messages", out, err));
return finish_inputs();
}
IChatTemplate* tpl = d.embed ? d.embed->message_template() : nullptr;
if (!tpl) {
*err = err_bad("messages", "this model has no chat template to render messages with");
@@ -2500,6 +2615,7 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
};
/* Control tokens are parsed as for a /v1/completions prompt: no template wraps the input. */
auto push_text = [&](const std::string& s) {
if (nemotron35) return retrieval(s);
std::vector<std::pair<MediaKind, std::vector<uint8_t>>> none;
return embedding_input(prefix + s, none, d, out->image_tokens, out, err);
};
@@ -2509,6 +2625,7 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
* tokenizer's special tokens go around the whole, matching what HuggingFace's processor feeds
* the model (EmbeddingGemma 2's template concatenates text and placeholders). */
auto push_parts = [&](const json& parts, ApiError* e) -> int {
if (nemotron35) return retrieval(parts);
std::vector<std::pair<MediaKind, std::vector<uint8_t>>> media;
std::string rendered = prefix;
for (const auto& part : parts) {
@@ -2581,20 +2698,7 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
return RAD_E_INVAL;
}
for (size_t i = 0; i < out->prompts.size(); ++i) {
const int64_t n = (int64_t)out->prompts[i].tokens.size();
if (n == 0) { *err = err_bad("input", "tokenised to nothing"); return RAD_E_INVAL; }
if (lim.max_ctx > 0 && n > lim.max_ctx) {
*err = err_bad("input", "input " + std::to_string(i) + " is " + std::to_string(n) +
" tokens, more than the model context of " +
std::to_string(lim.max_ctx));
err->code = "context_length_exceeded";
err->n_prompt_tokens = n;
err->n_ctx = lim.max_ctx;
return RAD_E_INVAL;
}
}
return RAD_OK;
return finish_inputs();
}
/* ================================================================== responses */
+2
View File
@@ -303,6 +303,8 @@ int decode_media_url(const std::string& url, const std::string& field,
int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
std::vector<std::pair<MediaKind, std::vector<uint8_t>>>& media,
const MediaOpts& opts, PromptInput* out, ApiError* err);
/* Startup policy for a model-owned embedding formatter: never silently ignore an override. */
int check_embedding_template(const IEmbedder* embed, bool overridden, std::string* why);
/* Embeddings: fills `out->prompts` with one entry per input. */
int parse_embeddings_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
OaiRequest* out, ApiError* err);