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

+8
View File
@@ -2529,11 +2529,19 @@ int Engine::run_server() {
return v ? std::string(v) : std::string();
}
server::IChatTemplate* message_template() const override { return tpl; }
const RadModelMeta* metadata() const override { return meta; }
} embed_info;
embed_info.d = pooled_dim_;
embed_info.n = cfg_.max_tok;
embed_info.meta = &meta_;
if (embedding_) d.embed = &embed_info;
std::string embed_why;
const int embed_rc = server::check_embedding_template(
d.embed, !cfg_.override_chat_template.empty(), &embed_why);
if (embed_rc < 0) {
RAD_ERR("%s", embed_why.c_str());
return embed_rc;
}
/* The template loader warns on its own about a missing or broken template; this only decides
* whether the chat endpoint exists. The reply format is the architecture plugin's when it
+26
View File
@@ -61,6 +61,32 @@ void PromptMedia::layout() {
for (size_t pi = 0; pi < items.size(); ++pi) {
const Placed& p = items[pi];
const Item& it = *p.item;
if (!it.row_tokens.empty()) {
/* Explicit image placeholders form flat runs separated by ordinary vocabulary
* tokens. The scheduler already maps each run through row0; separators get no row. */
for (size_t first = 0; first < it.row_tokens.size();) {
size_t end = first + 1;
while (end < it.row_tokens.size() &&
it.row_tokens[end] == it.row_tokens[end - 1] + 1)
++end;
const int64_t run_tok = (int64_t)p.tok + it.row_tokens[first];
pos += run_tok - tok;
RopeLayout::Run r;
r.tok = (int32_t)run_tok;
r.n = (int32_t)(end - first);
r.w = r.n;
r.base = (int32_t)pos;
r.flat = true;
r.item = (int32_t)pi;
r.row0 = (int32_t)first;
pos += r.n;
tok = run_tok + r.n;
r.shift = (int32_t)(pos - tok);
rope.runs.push_back(r);
first = end;
}
continue;
}
const int32_t m = it.rows_h > 0 ? it.grid_h / it.rows_h : 1;
for (int32_t s = 0; s < it.n_seg; ++s) {
const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s];
+129 -2
View File
@@ -50,6 +50,48 @@ static bool meta_bool(const RadModelMeta& m, const char* key, bool dflt) {
}
int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
/* Only the requested noncausal Mistral3/Ministral3 wrapper selects this new path. */
if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "mistral3") &&
!std::strcmp(rad_meta_gets(&m, "text_config.model_type", ""), "ministral3") &&
!std::strcmp(rad_meta_gets(&m, "vision_config.model_type", ""), "pixtral") &&
!meta_bool(m, "is_causal", true) && !meta_bool(m, "text_config.is_causal", true)) {
family = Family::Pixtral;
patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0);
merge = (int32_t)rad_meta_geti(&m, "spatial_merge_size", 0);
temporal = 1;
if (patch != 14 || merge != 2) {
if (why) *why = "Nemotron 3.5's Pixtral processor requires patch 14 and merge 2";
return RAD_E_UNSUPPORTED;
}
pixtral_longest_edge =
(int32_t)rad_meta_geti(&m, "processor.image_processor.size.longest_edge", 1120);
tok_image = (int32_t)rad_meta_geti(&m, "image_token_index", -1);
image_token = rad_meta_gets(&m, "processor.image_token", "[IMG]");
image_break_token = rad_meta_gets(&m, "processor.image_break_token", "[IMG_BREAK]");
image_end_token = rad_meta_gets(&m, "processor.image_end_token", "[IMG_END]");
const char* root = "processor.image_processor.";
for (const char* flag : {"do_resize", "do_convert_rgb", "do_rescale", "do_normalize"}) {
if (!meta_bool(m, (std::string(root) + flag).c_str(), true)) {
if (why)
*why = "Pixtral requires resize, RGB conversion, rescaling and normalization";
return RAD_E_UNSUPPORTED;
}
}
if (rad_meta_geti(&m, "processor.image_processor.resample", 3) != 3 ||
rad_meta_getf(&m, "processor.image_processor.rescale_factor", 1.0 / 255) != 1.0 / 255) {
if (why) *why = "Pixtral supports bicubic RGB rescaling by 1/255";
return RAD_E_UNSUPPORTED;
}
const float clip_mean[] = {.48145466f, .4578275f, .40821073f};
const float clip_std[] = {.26862954f, .26130258f, .27577711f};
std::copy(clip_mean, clip_mean + 3, mean);
std::copy(clip_std, clip_std + 3, stdv);
read_triple(m, "processor.image_processor.image_mean", mean);
read_triple(m, "processor.image_processor.image_std", stdv);
image_min_pixels = video_min_pixels = (int64_t)factor() * factor();
image_max_pixels = video_max_pixels = (int64_t)pixtral_longest_edge * pixtral_longest_edge;
return check(why);
}
/* Unlimited-OCR: one processor class, two modes, both stated in preprocessor_config.json and
* processor_config.json (`processor.*`). Every key has the reference's default, so a container
* converted before the tower landed still states a processor. */
@@ -304,6 +346,17 @@ int VisionConfig::check(std::string* why) const {
if (max_frames < min_frames)
return no("max_frames " + std::to_string(max_frames) + " is below min_frames " +
std::to_string(min_frames));
if (family == Family::Pixtral &&
(patch != 14 || merge != 2 || temporal != 1 || tok_image < 0 ||
pixtral_longest_edge < factor() || pixtral_longest_edge % factor() ||
pixtral_longest_edge > 1540 || image_token.empty() || image_break_token.empty() ||
image_end_token.empty()))
return no(
"Pixtral requires patch geometry, merge 2, image token ids and a whole merged-patch longest edge");
if (family == Family::Pixtral)
for (int i = 0; i < 3; ++i)
if (!std::isfinite(mean[i]) || !std::isfinite(stdv[i]))
return no("Pixtral requires finite image means and deviations");
if (family == Family::Lfm2) {
if (min_tiles < 1 || max_tiles < min_tiles || tile <= 0 || tile % factor())
return no("the tiling (min_tiles " + std::to_string(min_tiles) + ", max_tiles " +
@@ -1066,6 +1119,17 @@ int Processor::init(const VisionConfig& cfg,
if (cfg.patch <= 0 || cfg.temporal <= 0 || cfg.merge <= 0 || cfg.max_patches <= 0)
return RAD_E_INVAL;
cfg_ = cfg;
if (cfg.family == Family::Pixtral) {
if (!token_id) return RAD_E_INVAL;
cfg_.tok_image = token_id(cfg.image_token);
cfg_.tok_break = token_id(cfg.image_break_token);
cfg_.tok_end = token_id(cfg.image_end_token);
if (cfg_.tok_image < 0 || cfg_.tok_image != cfg.tok_image || cfg_.tok_break < 0 ||
cfg_.tok_end < 0)
return RAD_E_NOTFOUND;
encode_text_ = std::move(encode_text);
return cfg_.check(nullptr);
}
if (cfg.family == Family::Lfm2) {
/* The config names the markers rather than numbering them. Resolve all of them here so a
* vocabulary missing one is refused at startup, not on the first large picture. */
@@ -1587,6 +1651,67 @@ int Processor::image_glm5next(const Frame& f, std::shared_ptr<Item>* out, std::s
return RAD_OK;
}
/* The official PIL processor: cap the longest edge without enlarging, floor the aspect-ratio
* resize, then ceil both sides to patch * merge. Patch rows are raster order, (channel, y, x).
* The merger needs that order; merge-block ordering here would silently rotate the wrong grid. */
int Processor::image_pixtral(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
if (!out || f.h <= 0 || f.w <= 0 || (int64_t)f.h * f.w > c.max_source_pixels ||
f.rgb.size() != (uint64_t)f.h * f.w * 3) {
if (why) *why = "invalid Pixtral RGB frame or source pixel limit exceeded";
return RAD_E_INVAL;
}
const double ratio =
std::max((double)f.h / c.pixtral_longest_edge, (double)f.w / c.pixtral_longest_edge);
int64_t h = f.h, w = f.w;
if (ratio > 1) {
h = (int64_t)std::floor(h / ratio);
w = (int64_t)std::floor(w / ratio);
}
const int64_t factor = c.factor();
h = ((h + factor - 1) / factor) * factor;
w = ((w + factor - 1) / factor) * factor;
if (h <= 0 || w <= 0 || (h / c.patch) * (w / c.patch) > c.max_patches) {
if (why) *why = "Pixtral image is empty after resize or exceeds one encoder pass";
return RAD_E_INVAL;
}
Frame resized;
resize_bicubic(f, (int32_t)w, (int32_t)h, &resized);
auto it = std::make_shared<Item>();
it->grid_t = 1;
it->grid_h = (int32_t)(h / c.patch);
it->grid_w = (int32_t)(w / c.patch);
it->rope_1d = true;
it->patch_raster = true;
finish_item(c, it.get());
uint16_t lut[3][256];
for (int ch = 0; ch < 3; ++ch)
for (int v = 0; v < 256; ++v) {
const float scaled = (float)((double)v * (1.0 / 255));
lut[ch][v] = rad_f32_to_bf16((scaled - c.mean[ch]) / c.stdv[ch]);
}
it->pixels.resize((size_t)it->n_patch * it->patch_dim);
auto* dst = it->pixels.data();
for (int py = 0; py < it->grid_h; ++py)
for (int px = 0; px < it->grid_w; ++px)
for (int ch = 0; ch < 3; ++ch)
for (int y = 0; y < c.patch; ++y)
for (int x = 0; x < c.patch; ++x)
*dst++ = lut[ch][resized.rgb[
((size_t)(py * c.patch + y) * w + px * c.patch + x) * 3 + ch]];
it->seg_at.push_back(0);
for (int y = 0; y < it->rows_h; ++y) {
for (int x = 0; x < it->rows_w; ++x) {
it->row_tokens.push_back((int32_t)it->expand.size());
it->expand.push_back(c.tok_image);
}
it->expand.push_back(y + 1 == it->rows_h ? c.tok_end : c.tok_break);
}
content_key(*it, &it->key_hi, &it->key_lo);
*out = std::move(it);
return RAD_OK;
}
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why,
const ImageMode& mode) const {
const VisionConfig& c = cfg_;
@@ -1595,6 +1720,7 @@ int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::strin
return RAD_E_UNSUPPORTED;
}
if (c.family == Family::Gemma4) return image_gemma4(f, c.image_soft_tokens, out, why);
if (c.family == Family::Pixtral) return image_pixtral(f, out, why);
if (c.family == Family::Lfm2) return image_lfm2(f, out, why);
if (c.family == Family::Glm5Next) return image_glm5next(f, out, why);
if (c.family == Family::UnlimitedOcr) return image_unlimitedocr(f, mode, out, why);
@@ -1690,7 +1816,7 @@ int Processor::video_gemma4(const Video& v, std::shared_ptr<Item>* out, std::str
int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
if (c.family == Family::Gemma4) return video_gemma4(v, out, why);
if (c.family == Family::Glm5Next) {
if (c.family == Family::Glm5Next || c.family == Family::Pixtral) {
if (why) *why = "this model's processor takes pictures, not video";
return RAD_E_UNSUPPORTED;
}
@@ -1941,7 +2067,8 @@ std::vector<int64_t> sample_cb(const VideoInfo& info, const void* user) {
int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
std::string* why) const {
if (cfg_.family == Family::Lfm2 || cfg_.family == Family::Glm5Next) {
if (cfg_.family == Family::Lfm2 || cfg_.family == Family::Glm5Next ||
cfg_.family == Family::Pixtral) {
if (why) *why = "this model's processor takes pictures, not video";
return RAD_E_UNSUPPORTED;
}
+15 -2
View File
@@ -75,8 +75,12 @@ enum class Kind { Image, Video, Audio };
* fixed-point bicubic only when its size changes; the rest of the canvas, right and
* bottom, is zero bytes. Patches as QwenVL's. Images only, spelled <begin_of_image>
* placeholders <end_of_image>, the tokens at their positions (the language model has no
* rotary). */
enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr, Glm5Next };
* rotary).
* Pixtral Nemotron 3.5's noncausal Mistral3 wrapper: longest-edge resize, then ceil each side
* to patch * merge; PIL bicubic and CLIP normalization. Raster (channel, y, x) patches;
* image placeholders per merged grid row, each followed by IMG_BREAK (last: IMG_END).
* Every token has ordinary 1-D positions, and separators retain their token embedding. */
enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr, Glm5Next, Pixtral };
struct VisionConfig {
Family family = Family::QwenVL;
@@ -113,6 +117,10 @@ struct VisionConfig {
/* The vocabulary's spelling of the picture marker (`processor.image_token`); every
* placeholder of a picture is that one id. */
std::string image_token = "<image>";
/* Pixtral: resize within this longest edge, then round each side up to patch * merge.
* Its image rows are separated by real vocabulary tokens, without an opening marker. */
int32_t pixtral_longest_edge = 0, tok_break = -1;
std::string image_break_token = "[IMG_BREAK]", image_end_token = "[IMG_END]";
/* Deployment bounds, not the checkpoint's. `max_patches` is the encoder's pass size: an image
* is one segment and a segment is never split, so the image band's ceiling is lowered to fit
@@ -272,6 +280,10 @@ struct Item {
* them like any other id. */
std::vector<int32_t> expand;
std::vector<int32_t> seg_at;
/* Optional explicit placeholder positions within expand, one per encoder output row.
* Pixtral uses this because each grid row ends with a separator token that keeps its own
* language embedding. Empty preserves the existing contiguous per-segment representation. */
std::vector<int32_t> row_tokens;
/* Content key over the patches and the grid, taken before the encoder runs, so a prefix-cache
* hit over this item skips the encoder as well as the prefill. The patches already reflect
@@ -411,6 +423,7 @@ private:
int image_unlimitedocr(const Frame& f, const ImageMode& mode, std::shared_ptr<Item>* out,
std::string* why) const;
int image_glm5next(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
int image_pixtral(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
/* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */
int32_t tok_thumbnail_ = -1;
std::vector<int32_t> tok_tiles_;
+5 -5
View File
@@ -1884,11 +1884,11 @@ const RadBatch* Scheduler::step() {
if (cfg_.prefill_span > 1 && span_now_ && !plan_.e.empty()) break;
int32_t slot = waiting_[at];
SchedReq& s = *reqs_[(size_t)slot];
/* A sequence the context cannot hold never runs: its prompt alone reaches the last
* addressable position, so prefilling it would write positions the block and rotary
* tables lack. The server refuses such prompts; this is the scheduler's own bound.
* close_request removes it from waiting_, so `at` now names the next request. */
if (ctx_limit_ > 0 && s.seq_len() >= ctx_limit_) {
/* Generation reserves one position after the prompt. An embedding consumes just
* the prompt, so its exact context boundary fits without a generation slot.
* close_request removes a refused input from waiting_, so `at` names the next one. */
if (ctx_limit_ > 0 &&
(s.seq_len() > ctx_limit_ || (!s.req->embed && s.seq_len() == ctx_limit_))) {
RAD_WARN("request %llu failed: %lld tokens leave no room in a %lld-token context",
(unsigned long long)s.req->id, (long long)s.seq_len(),
(long long)ctx_limit_);
+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);