Archived
nemotron 3.5 implementation
This commit is contained in:
1 parent
33108e488b
commit
94c90b17ad
59 files changed
+6046
-76
No files matched your search
@@ -157,3 +157,14 @@ Community License 1.0 -- data/vectors/LICENSE.qwen-community-1.0.txt -- which ca
|
||||
every copy of it, including its condition that a Model-as-a-Service or AI-work-assistant business
|
||||
needs a separate license from Qwen to use it commercially. radiance's Apache-2.0 grant covers the
|
||||
code that loads and applies the file; it does not cover the file or its directions.
|
||||
|
||||
Nemotron 3.5 input fixtures
|
||||
--------------------------
|
||||
|
||||
tests/data/chat/nemotron35/template.jinja and tokenizer-subset.json come from NVIDIA's
|
||||
Nemotron-3.5-Embed-8B-BF16 checkpoint, revision
|
||||
781e779ee4ca9c2d2a4f38321993556baeab49a1:
|
||||
https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16/tree/781e779ee4ca9c2d2a4f38321993556baeab49a1
|
||||
The checkpoint's governing license is OpenMDW-1.1, retained in
|
||||
tests/data/chat/nemotron35/LICENSE. The tokenizer fixture is a subset preserving source token
|
||||
IDs and the BPE entries needed by the test corpus; it is not the complete serving tokenizer.
|
||||
@@ -64,6 +64,8 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
|
||||
| Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | `sdxl.yaml` |
|
||||
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` |
|
||||
| nomic-embed-text-v2-moe bf16: text embeddings, one card | `nomic-embed-v2-moe-bf16.rad` (959 MB) | [convert](#convert-a-checkpoint) | - |
|
||||
| Nemotron 3.5 Embed 1B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-1B-BF16) | — |
|
||||
| Nemotron 3.5 Embed 8B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16) | — |
|
||||
| Anima Aesthetic FP8: anime and illustration, text to image, one card (Base and Turbo convert the same way) | `anima-aesthetic-fp8.rad` (3.0 GiB) | [convert](#convert-a-checkpoint) | `anima.yaml` |
|
||||
| Qwen3-ASR 1.7B bf16: speech to text, `/v1/audio/transcriptions` and live over `/v1/realtime`, 30 languages, one card | the checkpoint as it ships (4.1 GiB) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) | — |
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(nemotron35_embed LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(nemotron35_embed architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/nemotron35_embed.cpp)
|
||||
@@ -0,0 +1,371 @@
|
||||
/* Nemotron-3.5-Embed: bidirectional BF16 text and a Pixtral encoder at TP1.
|
||||
*
|
||||
* The wrapper's language_model.* tensors are a Ministral3Model, without a logits head or Q/K
|
||||
* norms. Whole inputs attend bidirectionally and are mean-pooled after the final norm. The
|
||||
* endpoint normalises the vector after any dimensional truncation. Image rows replace only
|
||||
* their typed placeholders; separator tokens retain their vocabulary embeddings.
|
||||
*
|
||||
* Keep model-specific rotary interpretation here: the shared YaRN reader deliberately rejects
|
||||
* mscale, and changing its defaults would change unrelated models. This checkpoint's equal
|
||||
* mscale numerator/denominator give magnitude 1, independently of its position-dependent Q scale.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include "pixtral.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace nemotron35_embed {
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
rad_weight norm = 0, qkv = 0, out = 0, ff_norm = 0, gate_up = 0, down = 0;
|
||||
rad_op in_norm = 0, in_gain = 0, project = 0, rope = 0, qscale = 0, attn = 0, output = 0;
|
||||
rad_op add_attn = 0, pre_ff = 0, ff_gain = 0, gate = 0, act = 0, gate_mul = 0, ffn = 0,
|
||||
add_ff = 0;
|
||||
};
|
||||
struct Model {
|
||||
Geom g{};
|
||||
Names nm{""};
|
||||
rad_buf x = 0, h = 0, qkv = 0, attn = 0, o = 0, gu = 0, ff = 0, mean = 0, pooled = 0;
|
||||
rad_weight tok = 0, norm = 0;
|
||||
rad_op embed = 0, inject = 0, final_norm = 0, final_gain = 0, pool = 0, cast = 0;
|
||||
std::vector<Layer> layers;
|
||||
Pixtral vision;
|
||||
};
|
||||
static Model model;
|
||||
|
||||
/* JSON booleans reach plugins as 0/1, while out-of-tree callers may use their JSON spelling. */
|
||||
static bool false_value(const char* s) {
|
||||
return s && (!std::strcmp(s, "0") || !std::strcmp(s, "false"));
|
||||
}
|
||||
|
||||
static int read_rope(Geom& g, const RadModelMeta* meta) {
|
||||
constexpr const char* pre = "text_config.rope_parameters.";
|
||||
auto val = [&](const char* key, const char* fallback = nullptr) {
|
||||
return rad_meta_gets(meta, (std::string(pre) + key).c_str(), fallback);
|
||||
};
|
||||
const char* type = val("rope_type", val("type"));
|
||||
if (!type || std::strcmp(type, "yarn")) return RAD_E_UNSUPPORTED;
|
||||
const double factor = rad_meta_getf(meta, "text_config.rope_parameters.factor", 0);
|
||||
const double num = rad_meta_getf(meta, "text_config.rope_parameters.mscale", NAN);
|
||||
const double den = rad_meta_getf(meta, "text_config.rope_parameters.mscale_all_dim", NAN);
|
||||
if (!(factor >= 1) || !std::isfinite(factor) || !std::isfinite(num) || !std::isfinite(den) ||
|
||||
num < 0 || den < 0)
|
||||
return RAD_E_INVAL;
|
||||
auto magnitude = [&](double m) { return factor > 1 ? 1 + 0.1 * m * std::log(factor) : 1; };
|
||||
const double mag = num && den ? magnitude(num) / magnitude(den) : magnitude(1);
|
||||
if (!(mag > 0) || !std::isfinite(mag)) return RAD_E_INVAL;
|
||||
|
||||
/* Canonicalise only this plugin's temporary metadata view; never change the checkpoint or
|
||||
* shared reader. An explicit attention_factor, if present, is authoritative in Transformers. */
|
||||
std::vector<const char*> keys, vals;
|
||||
for (int i = 0; i < meta->n_kv; ++i) {
|
||||
const char* k = meta->kv_key[i];
|
||||
if (!std::strcmp(k, "text_config.rope_parameters.mscale") ||
|
||||
!std::strcmp(k, "text_config.rope_parameters.mscale_all_dim"))
|
||||
continue;
|
||||
keys.push_back(k);
|
||||
vals.push_back(meta->kv_val[i]);
|
||||
}
|
||||
char mag_text[48];
|
||||
std::snprintf(mag_text, sizeof mag_text, "%.17g", mag);
|
||||
const std::string derived = mag_text;
|
||||
if (!val("attention_factor")) {
|
||||
keys.push_back("text_config.rope_parameters.attention_factor");
|
||||
vals.push_back(derived.c_str());
|
||||
}
|
||||
RadModelMeta view = *meta;
|
||||
view.n_kv = (int)keys.size();
|
||||
view.kv_key = keys.data();
|
||||
view.kv_val = vals.data();
|
||||
return yarn_from(g, &view, "", g.head_dim);
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->max_seqs <= 0) return RAD_E_INVAL;
|
||||
if (ctx->rank != 0 || ctx->world_size > 1 || ctx->is_draft || ctx->max_spec > 0) {
|
||||
std::fprintf(stderr, "radiance: nemotron35_embed serves BF16 at TP1, without drafting\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->max_audio_frames > 0) {
|
||||
std::fprintf(stderr, "radiance: nemotron35_embed does not serve audio\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->max_ctx <= 0 || ctx->max_ctx > 32768) {
|
||||
std::fprintf(
|
||||
stderr,
|
||||
"radiance: nemotron35_embed: the embedding limit is 32768 tokens; set --max-model-len 32768 or lower\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (std::strcmp(rad_meta_gets(meta, "model_type", ""), "mistral3") ||
|
||||
std::strcmp(rad_meta_gets(meta, "text_config.model_type", ""), "ministral3") ||
|
||||
!false_value(rad_meta_gets(meta, "is_causal", nullptr)) ||
|
||||
!false_value(rad_meta_gets(meta, "text_config.is_causal", nullptr)) ||
|
||||
std::strcmp(rad_meta_gets(meta, "text_config.hidden_act", ""), "silu") ||
|
||||
(meta->quant && *meta->quant))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
const char* window = rad_meta_gets(meta, "text_config.sliding_window", nullptr);
|
||||
if (window && std::strcmp(window, "null") && std::strcmp(window, "0")) return RAD_E_UNSUPPORTED;
|
||||
const double beta =
|
||||
rad_meta_getf(meta, "text_config.rope_parameters.llama_4_scaling_beta", NAN);
|
||||
const int64_t original =
|
||||
rad_meta_geti(meta, "text_config.rope_parameters.original_max_position_embeddings", 0);
|
||||
if (!std::isfinite(beta) || beta < 0 || original <= 0) return RAD_E_INVAL;
|
||||
|
||||
model = Model{};
|
||||
Model& m = model;
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
if (g.n_head_kv <= 0 || g.n_head % g.n_head_kv || g.head_dim % 2) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(read_rope(g, meta));
|
||||
const int64_t T = g.max_tok, E = g.n_embd, Q = g.q_dim(), K = g.kv_dim(), F = g.n_ff;
|
||||
m.x = decl_b(b, nm.f("x"), RAD_BF16, {T, E});
|
||||
m.h = decl_b(b, nm.f("h"), RAD_BF16, {T, E});
|
||||
m.qkv = decl_b(b, nm.f("qkv"), RAD_BF16, {T, Q + 2 * K});
|
||||
m.attn = decl_b(b, nm.f("attn"), RAD_BF16, {T, Q});
|
||||
m.o = decl_b(b, nm.f("o"), RAD_BF16, {T, E});
|
||||
m.gu = decl_b(b, nm.f("gate_up"), RAD_BF16, {T, 2 * F});
|
||||
m.ff = decl_b(b, nm.f("ff"), RAD_BF16, {T, F});
|
||||
m.mean = decl_b(b, nm.f("mean"), RAD_BF16, {g.max_seqs, E});
|
||||
m.pooled = decl_b(b, nm.f("pooled"), RAD_F32, {g.max_seqs, E}, RAD_BUF_PERSIST);
|
||||
RAD_ARCH_TRY(rad_declare_pooled(b, m.pooled));
|
||||
auto weight = [&](const char* dest, const char* src, std::initializer_list<int64_t> shape,
|
||||
RadWeightGroup group) {
|
||||
if (map_copy(b, dest, src) < 0) return rad_weight(0);
|
||||
return decl_w(b, dest, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, group);
|
||||
};
|
||||
auto gemm = [&](int64_t N, int64_t kk, rad_weight w) {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", N), RAD_INT("K", kk),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto rms = [&] {
|
||||
// Ministral rounds the weightless norm before multiplying by the BF16 gain.
|
||||
return RAD_OP(b, "rmsnorm_p",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_F64("eps", g.eps),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto gain = [&](rad_weight w) {
|
||||
return RAD_OP(b, "mul_weight",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto add = [&] {
|
||||
return RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
RAD_ARCH_TRY(
|
||||
map_copy(b, nm.f("token_embd.weight"), nm.ckpt("language_model.embed_tokens.weight")));
|
||||
m.tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, E}, RAD_ACCESS_VOCAB,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
m.norm =
|
||||
weight(nm.f("output_norm.weight"), nm.ckpt("language_model.norm.weight"), {E}, grp_model());
|
||||
m.embed = rw(b,
|
||||
RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(m.tok)),
|
||||
{}, {m.x});
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int64_t i = 0; i < g.n_layer; ++i) {
|
||||
Layer& l = m.layers[(size_t)i];
|
||||
const auto group = grp_layer((int)i);
|
||||
const auto n = (long long)i;
|
||||
l.norm =
|
||||
weight(nm.f("blk.%lld.attn_norm.weight", n),
|
||||
nm.ckpt("language_model.layers.%lld.input_layernorm.weight", n), {E}, group);
|
||||
l.ff_norm = weight(nm.f("blk.%lld.ffn_norm.weight", n),
|
||||
nm.ckpt("language_model.layers.%lld.post_attention_layernorm.weight", n),
|
||||
{E}, group);
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.qkv.weight", n),
|
||||
{nm.ckpt("language_model.layers.%lld.self_attn.q_proj.weight", n),
|
||||
nm.ckpt("language_model.layers.%lld.self_attn.k_proj.weight", n),
|
||||
nm.ckpt("language_model.layers.%lld.self_attn.v_proj.weight", n)},
|
||||
0));
|
||||
l.qkv = decl_w(b, nm.f("blk.%lld.qkv.weight", n), RAD_BF16, {Q + 2 * K, E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, group);
|
||||
l.out =
|
||||
weight(nm.f("blk.%lld.attn_o.weight", n),
|
||||
nm.ckpt("language_model.layers.%lld.self_attn.o_proj.weight", n), {E, Q}, group);
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.gate_up.weight", n),
|
||||
{nm.ckpt("language_model.layers.%lld.mlp.gate_proj.weight", n),
|
||||
nm.ckpt("language_model.layers.%lld.mlp.up_proj.weight", n)},
|
||||
0));
|
||||
l.gate_up = decl_w(b, nm.f("blk.%lld.gate_up.weight", n), RAD_BF16, {2 * F, E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, group);
|
||||
l.down =
|
||||
weight(nm.f("blk.%lld.ffn_down.weight", n),
|
||||
nm.ckpt("language_model.layers.%lld.mlp.down_proj.weight", n), {E, F}, group);
|
||||
l.in_norm = rw(b, rms(), {m.x}, {m.h});
|
||||
l.in_gain = rw(b, gain(l.norm), {m.h}, {m.h});
|
||||
l.project = rw(b, gemm(Q + 2 * K, E, l.qkv), {m.h}, {m.qkv});
|
||||
l.rope = rw(
|
||||
b,
|
||||
decl_rotary(b, g, "ministral_rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.qkv}, {m.qkv});
|
||||
l.qscale = rw(
|
||||
b,
|
||||
RAD_OP(b, "position_scale",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", Q), RAD_INT("original", original),
|
||||
RAD_F64("beta", beta), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.qkv}, {m.qkv});
|
||||
l.attn = rw(b,
|
||||
RAD_OP(b, "embed_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 0),
|
||||
RAD_INT("max_seqlen", std::min(T, g.max_ctx)),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)g.head_dim))),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.qkv}, {m.attn});
|
||||
l.output = rw(b, gemm(E, Q, l.out), {m.attn}, {m.o});
|
||||
l.add_attn = rw(b, add(), {m.x, m.o}, {m.x});
|
||||
l.pre_ff = rw(b, rms(), {m.x}, {m.h});
|
||||
l.ff_gain = rw(b, gain(l.ff_norm), {m.h}, {m.h});
|
||||
l.gate = rw(b, gemm(2 * F, E, l.gate_up), {m.h}, {m.gu});
|
||||
l.act =
|
||||
rw(b,
|
||||
RAD_OP(b, "silu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", F), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.gu}, {m.gu});
|
||||
l.gate_mul =
|
||||
rw(b,
|
||||
RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", F), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.gu}, {m.ff});
|
||||
l.ffn = rw(b, gemm(E, F, l.down), {m.ff}, {m.o});
|
||||
l.add_ff = rw(b, add(), {m.x, m.o}, {m.x});
|
||||
}
|
||||
m.final_norm = rw(b, rms(), {m.x}, {m.h});
|
||||
m.final_gain = rw(b, gain(m.norm), {m.h}, {m.h});
|
||||
m.pool = rw(b,
|
||||
RAD_OP(b, "seg_mean",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.h}, {m.mean});
|
||||
m.cast = rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.mean}, {m.pooled});
|
||||
/* Recipes may quantise weights without changing the architecture descriptor. Do not read an
|
||||
* INT8 plane with a BF16-only graph, even when a container still advertises quant="". */
|
||||
const RadEncoding plain = rad_enc_plain(RAD_BF16);
|
||||
auto bf16_only = [&](const char* name) -> int {
|
||||
RadEncoding enc{};
|
||||
const int rc = rad_weight_encoding(b, name, &enc, nullptr, nullptr);
|
||||
if (rc == RAD_E_NOTFOUND) return RAD_OK; // conversion has not populated the encoding yet
|
||||
if (rc < 0) return rc;
|
||||
if (rad_enc_equal(&enc, &plain)) return RAD_OK;
|
||||
std::fprintf(
|
||||
stderr,
|
||||
"radiance: nemotron35_embed requires BF16 weight '%s'; quantised linears are not implemented yet\n",
|
||||
name);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
};
|
||||
RAD_ARCH_TRY(bf16_only(nm.f("token_embd.weight")));
|
||||
RAD_ARCH_TRY(bf16_only(nm.f("output_norm.weight")));
|
||||
for (int64_t i = 0; i < g.n_layer; ++i)
|
||||
for (const char* suffix : {"attn_norm", "ffn_norm", "qkv", "attn_o", "gate_up", "ffn_down"})
|
||||
RAD_ARCH_TRY(bf16_only(nm.f("blk.%lld.%s.weight", (long long)i, suffix)));
|
||||
RAD_ARCH_TRY(m.vision.declare(b, meta, ctx, nm, E, (int)g.n_layer));
|
||||
if (m.vision.on)
|
||||
m.inject =
|
||||
rw(b,
|
||||
RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.x}, {m.x});
|
||||
rad_note(
|
||||
b,
|
||||
"Nemotron-3.5-Embed: BF16 bidirectional embeddings, TP1; mean-pooled to %lld; Pixtral encoder %s",
|
||||
(long long)E, m.vision.on ? "on" : "off");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
if (!std::strcmp(rad_meta_gets(meta, "vision_config.model_type", ""), "pixtral")) {
|
||||
if (rad_meta_geti(meta, "spatial_merge_size", 0) != 2) return RAD_E_UNSUPPORTED;
|
||||
out->enc_merge = 4;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = model;
|
||||
const Geom& g = m.g;
|
||||
if (batch->enc) {
|
||||
m.vision.step(c, batch);
|
||||
return;
|
||||
}
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq, Q = g.q_dim(), K = g.kv_dim();
|
||||
if (batch->phase != RAD_PHASE_PREFILL || T <= 0 || T > g.max_tok || S <= 0 || S > g.max_seqs ||
|
||||
batch->max_q_len > g.max_ctx || !batch->token_ids || !batch->positions ||
|
||||
!batch->cu_seqlens) {
|
||||
rad_step_fail(
|
||||
c,
|
||||
"nemotron35_embed: expected whole text inputs within the declared token/context bounds");
|
||||
return;
|
||||
}
|
||||
if (batch->n_mm_rows < 0 || batch->n_mm_rows > T ||
|
||||
(batch->n_mm_rows && (!m.inject || !batch->mm_rows || !batch->mm_embd))) {
|
||||
rad_step_fail(
|
||||
c,
|
||||
"nemotron35_embed: image rows require a declared Pixtral encoder and valid row data");
|
||||
return;
|
||||
}
|
||||
const auto pos = praw(batch->positions, RAD_I32, T),
|
||||
cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
|
||||
RAD_ISSUE(c, m.embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.tok), brows(m.x, T));
|
||||
if (batch->n_mm_rows)
|
||||
RAD_ISSUE_N(c, m.inject, batch->n_mm_rows,
|
||||
praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, g.n_embd),
|
||||
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.x, T));
|
||||
for (const Layer& l : m.layers) {
|
||||
RAD_ISSUE(c, l.in_norm, brows(m.x, T), brows(m.h, T));
|
||||
RAD_ISSUE(c, l.in_gain, brows(m.h, T), RAD_W(l.norm), brows(m.h, T));
|
||||
RAD_ISSUE(c, l.project, brows(m.h, T), RAD_W(l.qkv), brows(m.qkv, T));
|
||||
RAD_ISSUE(c, l.rope, brows(m.qkv, T), pos);
|
||||
RAD_ISSUE(c, l.qscale, bcol(m.qkv, 0, Q, T), pos);
|
||||
RAD_ISSUE(c, l.attn, bcol(m.qkv, 0, Q, T), bcol(m.qkv, Q, K, T), bcol(m.qkv, Q + K, K, T),
|
||||
cu, brows(m.attn, T));
|
||||
RAD_ISSUE(c, l.output, brows(m.attn, T), RAD_W(l.out), brows(m.o, T));
|
||||
RAD_ISSUE(c, l.add_attn, brows(m.x, T), brows(m.o, T), brows(m.x, T));
|
||||
RAD_ISSUE(c, l.pre_ff, brows(m.x, T), brows(m.h, T));
|
||||
RAD_ISSUE(c, l.ff_gain, brows(m.h, T), RAD_W(l.ff_norm), brows(m.h, T));
|
||||
RAD_ISSUE(c, l.gate, brows(m.h, T), RAD_W(l.gate_up), brows(m.gu, T));
|
||||
RAD_ISSUE(c, l.act, bcol(m.gu, 0, g.n_ff, T), bcol(m.gu, 0, g.n_ff, T));
|
||||
RAD_ISSUE(c, l.gate_mul, bcol(m.gu, 0, g.n_ff, T), bcol(m.gu, g.n_ff, g.n_ff, T),
|
||||
brows(m.ff, T));
|
||||
RAD_ISSUE(c, l.ffn, brows(m.ff, T), RAD_W(l.down), brows(m.o, T));
|
||||
RAD_ISSUE(c, l.add_ff, brows(m.x, T), brows(m.o, T), brows(m.x, T));
|
||||
}
|
||||
RAD_ISSUE(c, m.final_norm, brows(m.x, T), brows(m.h, T));
|
||||
RAD_ISSUE(c, m.final_gain, brows(m.h, T), RAD_W(m.norm), brows(m.h, T));
|
||||
RAD_ISSUE(c, m.pool, brows(m.h, T), cu, brows(m.mean, S));
|
||||
RAD_ISSUE_N(c, m.cast, S, brows(m.mean, S), brows(m.pooled, S));
|
||||
}
|
||||
} // namespace nemotron35_embed
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PLUGIN(nemotron35_embed, "mistral3", "", "0.4.0",
|
||||
"Nemotron-3.5-Embed: experimental BF16 text/image embeddings, TP1")
|
||||
RAD_ARCH_PROBE(nemotron35_embed)
|
||||
#endif
|
||||
@@ -0,0 +1,302 @@
|
||||
/* Nemotron 3.5's Pixtral tower and Mistral3 projector, BF16 at TP1.
|
||||
* The processor supplies complete raster grids. Image/text prompt integration is a separate
|
||||
* acceptance gate: a working encoder pass alone does not make image embeddings serviceable. */
|
||||
#pragma once
|
||||
#include <arch/rad_arch.h>
|
||||
|
||||
namespace nemotron35_embed {
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Pixtral {
|
||||
struct Norm {
|
||||
rad_weight w = 0;
|
||||
rad_op rms = 0, gain = 0;
|
||||
};
|
||||
struct Layer {
|
||||
Norm n1, n2;
|
||||
rad_weight qkv = 0, out = 0, gu = 0, down = 0;
|
||||
rad_op project = 0, rope = 0, attn = 0, output = 0, add1 = 0;
|
||||
rad_op gate = 0, act = 0, gate_mul = 0, ffn = 0, add2 = 0;
|
||||
};
|
||||
bool on = false;
|
||||
int64_t P = 0, width = 0, heads = 0, hd = 0, ff = 0, depth = 0, patch_dim = 0;
|
||||
int64_t merge = 0, embd = 0, max_grid = 0;
|
||||
rad_buf x = 0, h = 0, qkv = 0, att = 0, o = 0, gu = 0, ffn = 0, packed = 0, merged = 0,
|
||||
proj = 0, out = 0;
|
||||
rad_weight patch = 0, merger = 0, linear1 = 0, linear2 = 0;
|
||||
rad_op stem = 0, pack = 0, merge_op = 0, project1 = 0, gelu = 0, project2 = 0;
|
||||
Norm pre, post;
|
||||
std::vector<Layer> layers;
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t output_width, int first_group) {
|
||||
on = false;
|
||||
if (ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
auto vi = [&](const char* k) {
|
||||
return rad_meta_geti(meta, (std::string("vision_config.") + k).c_str(), 0);
|
||||
};
|
||||
const char* bias = rad_meta_gets(meta, "multimodal_projector_bias", "");
|
||||
if (std::strcmp(rad_meta_gets(meta, "vision_config.model_type", ""), "pixtral") ||
|
||||
std::strcmp(rad_meta_gets(meta, "vision_config.hidden_act", ""), "silu") ||
|
||||
std::strcmp(rad_meta_gets(meta, "projector_hidden_act", ""), "gelu") ||
|
||||
(std::strcmp(bias, "0") && std::strcmp(bias, "false")) ||
|
||||
rad_meta_geti(meta, "vision_feature_layer", 0) != -1)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
const char* rope = rad_meta_gets(meta, "vision_config.rope_parameters.rope_type", "");
|
||||
/* This checkpoint saves `default`; PixtralVisionConfig interprets it as axial. */
|
||||
if (std::strcmp(rope, "default") && std::strcmp(rope, "axial")) return RAD_E_UNSUPPORTED;
|
||||
width = vi("hidden_size");
|
||||
heads = vi("num_attention_heads");
|
||||
ff = vi("intermediate_size");
|
||||
depth = vi("num_hidden_layers");
|
||||
const int64_t ps = vi("patch_size"), channels = vi("num_channels"),
|
||||
image_size = vi("image_size");
|
||||
merge = rad_meta_geti(meta, "spatial_merge_size", 0);
|
||||
embd = output_width;
|
||||
const double theta = rad_meta_getf(meta, "vision_config.rope_parameters.rope_theta", 0);
|
||||
const double eps = meta->rms_eps;
|
||||
if (width <= 0 || heads <= 0 || width % heads || (width / heads) % 4 || ff <= 0 ||
|
||||
depth <= 0 || ps <= 0 || channels != 3 || merge != 2 || embd <= 0 || image_size < ps ||
|
||||
!(theta > 0) || !std::isfinite(theta) || !(eps > 0) || !std::isfinite(eps))
|
||||
return RAD_E_INVAL;
|
||||
hd = width / heads;
|
||||
patch_dim = channels * ps * ps;
|
||||
max_grid = image_size / ps;
|
||||
if (vi("head_dim") && vi("head_dim") != hd) return RAD_E_INVAL;
|
||||
const int64_t mm = merge * merge, max_seg = ctx->max_enc_patches;
|
||||
P = max_seg;
|
||||
if (P % mm) return RAD_E_SHAPE;
|
||||
if (ctx->shape_probe) P = std::max(mm, std::min(P, ctx->max_tok) / mm * mm);
|
||||
if (P < mm) return RAD_E_INVAL;
|
||||
const int64_t R = P / mm;
|
||||
auto buf = [&](const char* name, int64_t rows, int64_t cols, uint32_t flags = 0) {
|
||||
return decl_b(b, nm.f("v.%s", name), RAD_BF16, {rows, cols}, flags);
|
||||
};
|
||||
x = buf("x", P, width);
|
||||
h = buf("h", P, width);
|
||||
qkv = buf("qkv", P, 3 * width);
|
||||
att = buf("attn", P, width);
|
||||
o = buf("o", P, width);
|
||||
gu = buf("gate_up", P, 2 * ff);
|
||||
ffn = buf("ff", P, ff);
|
||||
packed = buf("packed", R, mm * width);
|
||||
merged = buf("merged", R, width);
|
||||
proj = buf("proj", R, embd);
|
||||
out = buf("out", R, embd, RAD_BUF_PERSIST);
|
||||
auto weight = [&](const char* dest, const char* src, std::initializer_list<int64_t> shape,
|
||||
RadWeightGroup group) {
|
||||
if (map_copy(b, dest, src) < 0) return rad_weight(0);
|
||||
return decl_w(b, dest, RAD_BF16, shape, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, group);
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto norm = [&](Norm& n, const char* dest, const char* src, RadWeightGroup group, double e,
|
||||
rad_buf from, rad_buf to) {
|
||||
n.w = weight(dest, src, {width}, group);
|
||||
/* The reference narrows the weightless norm before multiplying by the BF16 gain. */
|
||||
n.rms = rw(b,
|
||||
RAD_OP(b, "rmsnorm_p",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_F64("eps", e), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{from}, {to});
|
||||
n.gain = rw(b,
|
||||
RAD_OP(b, "mul_weight",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(n.w)),
|
||||
{to}, {to});
|
||||
};
|
||||
auto add = [&] {
|
||||
return RAD_OP(
|
||||
b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
patch = weight(nm.f("v.patch.weight"), nm.ckpt("vision_tower.patch_conv.weight"),
|
||||
{width, patch_dim}, grp_model());
|
||||
stem = rw(b, gemm(P, width, patch_dim, patch), {}, {x});
|
||||
norm(pre, nm.f("v.pre.weight"), nm.ckpt("vision_tower.ln_pre.weight"), grp_model(), 1e-5, x,
|
||||
x);
|
||||
layers.resize((size_t)depth);
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
auto& l = layers[(size_t)i];
|
||||
const long long li = i;
|
||||
const auto group = grp_layer(first_group + (int)i);
|
||||
norm(l.n1, nm.f("v.blk.%lld.n1.weight", li),
|
||||
nm.ckpt("vision_tower.transformer.layers.%lld.attention_norm.weight", li), group,
|
||||
1e-5, x, h);
|
||||
norm(l.n2, nm.f("v.blk.%lld.n2.weight", li),
|
||||
nm.ckpt("vision_tower.transformer.layers.%lld.ffn_norm.weight", li), group, 1e-5,
|
||||
x, h);
|
||||
RAD_ARCH_TRY(map_concat(
|
||||
b, nm.f("v.blk.%lld.qkv.weight", li),
|
||||
{nm.ckpt("vision_tower.transformer.layers.%lld.attention.q_proj.weight", li),
|
||||
nm.ckpt("vision_tower.transformer.layers.%lld.attention.k_proj.weight", li),
|
||||
nm.ckpt("vision_tower.transformer.layers.%lld.attention.v_proj.weight", li)},
|
||||
0));
|
||||
l.qkv = decl_w(b, nm.f("v.blk.%lld.qkv.weight", li), RAD_BF16, {3 * width, width},
|
||||
RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, group);
|
||||
l.out =
|
||||
weight(nm.f("v.blk.%lld.out.weight", li),
|
||||
nm.ckpt("vision_tower.transformer.layers.%lld.attention.o_proj.weight", li),
|
||||
{width, width}, group);
|
||||
RAD_ARCH_TRY(map_concat(
|
||||
b, nm.f("v.blk.%lld.gate_up.weight", li),
|
||||
{nm.ckpt("vision_tower.transformer.layers.%lld.feed_forward.gate_proj.weight", li),
|
||||
nm.ckpt("vision_tower.transformer.layers.%lld.feed_forward.up_proj.weight", li)},
|
||||
0));
|
||||
l.gu = decl_w(b, nm.f("v.blk.%lld.gate_up.weight", li), RAD_BF16, {2 * ff, width},
|
||||
RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, group);
|
||||
l.down = weight(
|
||||
nm.f("v.blk.%lld.down.weight", li),
|
||||
nm.ckpt("vision_tower.transformer.layers.%lld.feed_forward.down_proj.weight", li),
|
||||
{width, ff}, group);
|
||||
l.project = rw(b, gemm(P, 3 * width, width, l.qkv), {h}, {qkv});
|
||||
l.rope = rw(b,
|
||||
RAD_OP(b, "pixtral_rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
|
||||
RAD_INT("n_head", heads), RAD_F64("theta", theta),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{qkv}, {qkv});
|
||||
l.attn = rw(
|
||||
b,
|
||||
RAD_OP(b, "embed_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd), RAD_INT("gqa", 1),
|
||||
RAD_INT("causal", 0), RAD_INT("max_seqlen", max_seg),
|
||||
RAD_F64("scale", 1 / std::sqrt((double)hd)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{qkv}, {att});
|
||||
l.output = rw(b, gemm(P, width, width, l.out), {att}, {o});
|
||||
l.add1 = rw(b, add(), {x, o}, {x});
|
||||
l.gate = rw(b, gemm(P, 2 * ff, width, l.gu), {h}, {gu});
|
||||
l.act = rw(
|
||||
b,
|
||||
RAD_OP(b, "silu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{gu}, {gu});
|
||||
l.gate_mul = rw(
|
||||
b,
|
||||
RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{gu}, {ffn});
|
||||
l.ffn = rw(b, gemm(P, width, ff, l.down), {ffn}, {o});
|
||||
l.add2 = rw(b, add(), {x, o}, {x});
|
||||
}
|
||||
norm(post, nm.f("v.post.weight"), nm.ckpt("multi_modal_projector.norm.weight"), grp_model(),
|
||||
eps, x, h);
|
||||
merger = weight(nm.f("v.merger.weight"),
|
||||
nm.ckpt("multi_modal_projector.patch_merger.merging_layer.weight"),
|
||||
{width, mm * width}, grp_model());
|
||||
linear1 = weight(nm.f("v.linear1.weight"), nm.ckpt("multi_modal_projector.linear_1.weight"),
|
||||
{embd, width}, grp_model());
|
||||
linear2 = weight(nm.f("v.linear2.weight"), nm.ckpt("multi_modal_projector.linear_2.weight"),
|
||||
{embd, embd}, grp_model());
|
||||
pack = rw(b,
|
||||
RAD_OP(b, "pixtral_merge",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("merge", merge), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{h}, {packed});
|
||||
merge_op = rw(b, gemm(R, width, mm * width, merger), {packed}, {merged});
|
||||
project1 = rw(b, gemm(R, embd, width, linear1), {merged}, {proj});
|
||||
gelu = rw(
|
||||
b,
|
||||
RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", embd), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{proj}, {proj});
|
||||
project2 = rw(b, gemm(R, embd, embd, linear2), {proj}, {out});
|
||||
const RadEncoding plain = rad_enc_plain(RAD_BF16);
|
||||
auto bf16_only = [&](const char* name) -> int {
|
||||
RadEncoding enc{};
|
||||
const int rc = rad_weight_encoding(b, name, &enc, nullptr, nullptr);
|
||||
if (rc == RAD_E_NOTFOUND) return RAD_OK;
|
||||
if (rc < 0) return rc;
|
||||
return rad_enc_equal(&enc, &plain) ? RAD_OK : RAD_E_UNSUPPORTED;
|
||||
};
|
||||
for (const char* name : {"patch", "pre", "post", "merger", "linear1", "linear2"})
|
||||
RAD_ARCH_TRY(bf16_only(nm.f("v.%s.weight", name)));
|
||||
for (int64_t i = 0; i < depth; ++i)
|
||||
for (const char* name : {"n1", "n2", "qkv", "out", "gate_up", "down"})
|
||||
RAD_ARCH_TRY(bf16_only(nm.f("v.blk.%lld.%s.weight", (long long)i, name)));
|
||||
if (!ctx->shape_probe) {
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE;
|
||||
e.patch_dim = patch_dim;
|
||||
e.merge = mm;
|
||||
e.max_patches = P;
|
||||
e.n_embd = embd;
|
||||
e.out = out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
}
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t n = batch->enc_n_patch, s = batch->enc_n_seg, mm = merge * merge;
|
||||
if (!on || batch->enc != RAD_MM_IMAGE || n <= 0 || n > P || n % mm || s <= 0 ||
|
||||
s > n / mm || batch->enc_max_seg <= 0 || batch->enc_max_seg > P || !batch->enc_pixels ||
|
||||
!batch->enc_coord || !batch->enc_cu || !batch->enc_seg_h || !batch->enc_seg_w) {
|
||||
rad_step_fail(c, "nemotron35_embed: invalid Pixtral encoder pass");
|
||||
return;
|
||||
}
|
||||
int64_t total = 0;
|
||||
for (int64_t i = 0; i < s; ++i) {
|
||||
const int64_t hh = batch->enc_seg_h[i], ww = batch->enc_seg_w[i];
|
||||
if (hh <= 0 || ww <= 0 || hh % merge || ww % merge || hh > max_grid || ww > max_grid ||
|
||||
hh * ww > batch->enc_max_seg || hh * ww > n - total) {
|
||||
rad_step_fail(c, "nemotron35_embed: Pixtral expects complete even raster grids");
|
||||
return;
|
||||
}
|
||||
total += hh * ww;
|
||||
}
|
||||
if (total != n) {
|
||||
rad_step_fail(c, "nemotron35_embed: Pixtral grid sizes disagree with patches");
|
||||
return;
|
||||
}
|
||||
const int64_t r = n / mm;
|
||||
const auto coord = praw2(batch->enc_coord, RAD_I32, 2, n),
|
||||
cu = praw(batch->enc_cu, RAD_I32, s + 1);
|
||||
auto norm = [&](const Norm& nrm, rad_buf from, rad_buf to) {
|
||||
RAD_ISSUE_N(c, nrm.rms, n, brows(from, n), brows(to, n));
|
||||
RAD_ISSUE_N(c, nrm.gain, n, brows(to, n), RAD_W(nrm.w), brows(to, n));
|
||||
};
|
||||
RAD_ISSUE_N(c, stem, n, praw2(batch->enc_pixels, RAD_BF16, n, patch_dim), RAD_W(patch),
|
||||
brows(x, n));
|
||||
norm(pre, x, x);
|
||||
for (const auto& l : layers) {
|
||||
norm(l.n1, x, h);
|
||||
RAD_ISSUE_N(c, l.project, n, brows(h, n), RAD_W(l.qkv), brows(qkv, n));
|
||||
RAD_ISSUE_N(c, l.rope, n, brows(qkv, n), coord);
|
||||
RAD_ISSUE_N(c, l.attn, n, bcol(qkv, 0, width, n), bcol(qkv, width, width, n),
|
||||
bcol(qkv, 2 * width, width, n), cu, brows(att, n));
|
||||
RAD_ISSUE_N(c, l.output, n, brows(att, n), RAD_W(l.out), brows(o, n));
|
||||
RAD_ISSUE_N(c, l.add1, n, brows(x, n), brows(o, n), brows(x, n));
|
||||
norm(l.n2, x, h);
|
||||
RAD_ISSUE_N(c, l.gate, n, brows(h, n), RAD_W(l.gu), brows(gu, n));
|
||||
RAD_ISSUE_N(c, l.act, n, bcol(gu, 0, ff, n), bcol(gu, 0, ff, n));
|
||||
RAD_ISSUE_N(c, l.gate_mul, n, bcol(gu, 0, ff, n), bcol(gu, ff, ff, n), brows(ffn, n));
|
||||
RAD_ISSUE_N(c, l.ffn, n, brows(ffn, n), RAD_W(l.down), brows(o, n));
|
||||
RAD_ISSUE_N(c, l.add2, n, brows(x, n), brows(o, n), brows(x, n));
|
||||
}
|
||||
norm(post, x, h);
|
||||
RAD_ISSUE_N(c, pack, n, brows(h, n), praw2(batch->enc_coord, RAD_I32, 4, n),
|
||||
brows(packed, r));
|
||||
RAD_ISSUE_N(c, merge_op, r, brows(packed, r), RAD_W(merger), brows(merged, r));
|
||||
RAD_ISSUE_N(c, project1, r, brows(merged, r), RAD_W(linear1), brows(proj, r));
|
||||
RAD_ISSUE_N(c, gelu, r, brows(proj, r), brows(proj, r));
|
||||
RAD_ISSUE_N(c, project2, r, brows(proj, r), RAD_W(linear2), brows(out, r));
|
||||
}
|
||||
};
|
||||
} // namespace nemotron35_embed
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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
@@ -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_;
|
||||
|
||||
@@ -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_);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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
@@ -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 */
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -21,6 +21,7 @@ plugin claims.
|
||||
| `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank |
|
||||
| `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector |
|
||||
| `arch/nomicbert` | `nomicbert` | *(empty)* | nomic-embed-text-v2-moe: a bidirectional post-norm encoder, 12 layers with 8 experts at top 2 on every second layer, mean-pooled to one vector an input |
|
||||
| `arch/nemotron35_embed` | `mistral3` | *(empty)* | Nemotron 3.5 Embed 1B and 8B: native BF16 bidirectional text/image encoders with a Pixtral tower, retrieval formatting and normalized mean pooling, TP1 ([geometry and contracts](#nemotron35_embed-embedding-models)) |
|
||||
| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense, and the E2B/E4B form at one rank, with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release or from bf16, served w4a8, or int8 codes on the same grid from bf16 (w8a8, the Q8 container). Optional draft model (`rad-convert --draft-model`): Google's assistant, with no cache of its own (`rad_drafter_shared_kv`), or z-lab's DFlash drafter, the block `arch/gemma4` serves (`arch/common/rad_gemma4_dflash.h`), or RedHatAI's DFlash2 speculator (`arch/common/rad_block_dflash2.h`) |
|
||||
| `arch/gemma3` | `gemma3` | *(empty)* | Gemma 3 dense text (TranslateGemma 27B) from the bf16 checkpoint: sliding-window and global attention at one head geometry, GemmaRMSNorm, GELU ffn; linears bf16, or int8, MXFP4 or asymmetric int4 over an activation scaled per (row, 128), as the recipe stores them. Optional DFlash2 drafter (`rad-convert --draft-model`) |
|
||||
| `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 |
|
||||
@@ -863,6 +864,79 @@ Traps:
|
||||
|
||||
---
|
||||
|
||||
# `nemotron35_embed`: embedding models
|
||||
|
||||
Native BF16 [Nemotron 3.5 Embed 1B](https://huggingface.co/nvidia/Nemotron-3.5-Embed-1B-BF16)
|
||||
and [8B](https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16) are bidirectional multimodal
|
||||
encoders, selected by `(mistral3, "")` with noncausal Mistral3/Ministral3 checks. They declare
|
||||
pooled output and no language-generation head. CPU (`libavx`, with `libref` as the oracle) and
|
||||
RDNA4 (`libr4d`) serve BF16 at TP1; quantized planes, TP>1, drafting and audio are rejected.
|
||||
[GUIDE §5.6](GUIDE.md#56-completions-embeddings-images-tokenising) covers serving and retrieval inputs.
|
||||
|
||||
| Checkpoint | Pinned revision | Text geometry | Default vector |
|
||||
|---|---|---|---:|
|
||||
| 1B BF16 | `e24ca1e346bcc53572bd7bdc02b3e8ebf66c197c` | 16 layers, hidden 2048, FFN 6144, 24 Q / 8 KV heads | 2048 |
|
||||
| 8B BF16 | `781e779ee4ca9c2d2a4f38321993556baeab49a1` | 34 layers, hidden 4096, FFN 14336, 32 Q / 8 KV heads | 4096 |
|
||||
|
||||
Both have 128-wide text heads. The 1B query width is 3072, independently of its hidden width.
|
||||
Each uses its own checkpoint weights and embedding space. The vision tower is Pixtral: 24 layers,
|
||||
hidden 1024, 16 heads of width 64, 14-pixel patches and a learned 2x2 patch merger/projector.
|
||||
|
||||
**Numerical contracts.** Native safetensors mapping fuses QKV and gate/up without changing
|
||||
precision. Attention is bidirectional over each complete input and isolated across inputs.
|
||||
Pooling is the valid-token mean; dimensional truncation precedes L2 normalization.
|
||||
|
||||
Ministral rounds the weightless norm before applying its BF16 gain. Its rotary rounds cos/sin
|
||||
and individual products to BF16, with model-local YaRN magnitude and position-dependent query
|
||||
scaling, including the position-16384 seam. Shared rotary defaults remain unchanged. Pixtral
|
||||
preserves axial height/width rotary, channel-major patch merging, exact GELU and BF16 seams.
|
||||
Only actual `[IMG]` rows receive image embeddings; separator embeddings remain ordinary tokens
|
||||
and participate in pooling. The model-specific operation laws are in [OPS.md](OPS.md).
|
||||
|
||||
**Context and images.** The maximum is 32768 total encoded tokens per input, including prefixes,
|
||||
image placeholders and separators. The backbone's 262144 positional slots do not establish a
|
||||
larger supported embedding context. Inputs are never silently truncated. Configured per-input,
|
||||
combined-token, sequence-slot and image-pass budgets remain separate limits.
|
||||
|
||||
The default longest edge is 1120, without initial enlargement. Reference PIL bicubic resizing
|
||||
aligns dimensions to 28, followed by CLIP normalization and raster 14x14 patches. The default
|
||||
maximum square has 6400 patches and must fit one encoder pass. The published 1540-pixel option
|
||||
and larger image settings are not validated by this port.
|
||||
|
||||
**Verification.** Stored tiny fixtures cover issued graphs, exact preprocessing/token identity,
|
||||
BF16 seams, ragged multimodal inputs, invalid shapes and both head geometries. The regular C++
|
||||
suite needs neither Python nor downloaded checkpoints. Opt-in R9700 entries are
|
||||
`nemotron35_device_test_card` and `r4d_bf16_capacity_test_card`; the latter uses over 8 GiB VRAM
|
||||
to cross actual activation-offset boundaries, with bounded host staging.
|
||||
|
||||
The offline native oracle uses CPU torch 2.14.1, matching torchvision 0.29.1, Transformers 5.20.0
|
||||
and Pillow 13.0.0, explicitly selecting PIL preprocessing and never running remote model code:
|
||||
|
||||
```sh
|
||||
HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 python tests/mknemotron35realreference.py \
|
||||
/models/Nemotron-3.5-Embed-1B-BF16 /tmp/nemotron-reference.json --extended
|
||||
RAD_NEMOTRON_REAL_FIXTURE=/tmp/nemotron-reference.json RAD_NEMOTRON_DEVICE=1 \
|
||||
RADIANCE_HOME="$PWD/build/radiance_home" RAD_TEST_CPU_BUDGET=0 OMP_WAIT_POLICY=passive \
|
||||
build/tests/engine_e2e_test nemotron35_real
|
||||
```
|
||||
|
||||
Use the corresponding native checkpoint for 8B; omit `RAD_NEMOTRON_DEVICE` for CPU execution.
|
||||
`RAD_NEMOTRON_DEVICE_INDEX=1` selects another physical card. Run large checks sequentially; 8B
|
||||
needs roughly 20 GB available host memory. Tiny gates are relative L2 <=.01 and cosine >=.9995.
|
||||
Native gates are cosine >=.9995, normalized L2 <=.032, norm error <=1e-5 and pairwise-score error
|
||||
<=.005, fixed before candidate evaluation. The full-model bound accounts for audited BF16
|
||||
backend sensitivity: eager-vs-SDPA alone reached 2.805% normalized L2 on the 8B samples.
|
||||
Individual/batched vectors must agree within L2 <=1e-5; native ranking margins >.01 must retain
|
||||
their ordering. These gates are not bitwise or broad retrieval-quality guarantees.
|
||||
|
||||
CPU/R9700 comparisons cover both variants; the extended 1B corpus reaches 1924 tokens with
|
||||
English/Spanish/Japanese retrieval groups. Separate synthetic capacity checks cover a complete
|
||||
32768-token input, four full 1B inputs in one 131072-token step and a default maximum image.
|
||||
They do not establish native accuracy at maximum context/resolution. Native INT8/Q8, GGUF and
|
||||
TP2 remain unimplemented.
|
||||
|
||||
---
|
||||
|
||||
# `nomicbert`: an embedding model
|
||||
|
||||
`arch/nomicbert` declares a pooled output (`rad_declare_pooled`) and no logits, so it is an
|
||||
|
||||
+30
-1
@@ -304,6 +304,7 @@ and runs.
|
||||
| `lfm2_bf16` | LiquidAI LFM2 and LFM2-VL in bf16, including d1 (§5.13) |
|
||||
| `embgemma2` | EmbeddingGemma 2, an embedding model (§5.6) |
|
||||
| `nomicbert` | nomic-embed-text-v2-moe, an embedding model (§5.6) |
|
||||
| `nemotron35_embed` | Nemotron 3.5 Embed 1B and 8B, BF16 text/image embeddings at TP1 (§5.6) |
|
||||
| `qwenimage21` | Qwen-Image 2.1 and 2.1-Turbo, an image model (§5.6) |
|
||||
| `krea2` | Krea 2 Raw and Turbo, an image model from text (§5.6) |
|
||||
| `anima` | Anima Base, Aesthetic and Turbo, an anime and illustration image model from text (§5.6) |
|
||||
@@ -2411,7 +2412,7 @@ token ids mixed, with its `add_special` and `parse_special` and their defaults);
|
||||
returns `tokens` as llama-server does, as `{id, piece}` objects with `with_pieces`. `/detokenize`
|
||||
returns the text as both `prompt` (vLLM) and `content` (llama-server).
|
||||
|
||||
**An embedding model** (EmbeddingGemma 2, nomic-embed-text-v2-moe) serves `/v1/embeddings` only;
|
||||
**An embedding model** (EmbeddingGemma 2, nomic-embed-text-v2-moe, Nemotron 3.5 Embed) serves `/v1/embeddings` only;
|
||||
completions and chat answer 501. One input is one vector and must fit one step
|
||||
(`--max-num-batched-tokens`); a longer one is refused with `context_length_exceeded`.
|
||||
|
||||
@@ -2421,6 +2422,34 @@ the directory must contain `tokenizer.json`. The engine adds neither the `search
|
||||
`search_document: ` prefix: the client sends it, or names the checkpoint's prompt with
|
||||
`prompt_name`. The checkpoint's shared `experts.bias` tensors are not applied.
|
||||
|
||||
Nemotron 3.5 Embed 1B and 8B load directly from their native BF16 safetensors snapshots, including
|
||||
the tokenizer, processor and retrieval-prompt files; no conversion is needed. Use the normal
|
||||
HIP/FFmpeg build for R9700 (`-DRAD_WITH_HIP=ON -DRAD_GPU_TARGETS=gfx1201 -DRAD_WITH_FFMPEG=ON`):
|
||||
|
||||
```sh
|
||||
RADIANCE_HOME="$PWD/build/radiance_home" build/bin/radiance \
|
||||
--model /models/Nemotron-3.5-Embed-1B-BF16 --kernels libr4d,libavx --tp 1 \
|
||||
--max-model-len 32768 --max-num-batched-tokens 32768 --max-num-seqs 4 \
|
||||
--mm-max-patches 6400
|
||||
```
|
||||
|
||||
Use the 8B checkpoint path for 8B, or a CPU build and `--kernels libavx` on x86-64. Named prompts
|
||||
are `query` (`query: `) and `document` (`passage: `). Typed text/image inputs and one user message
|
||||
with an optional leading system prefix follow the checkpoint's retrieval template: escaped user
|
||||
text, images before text, exact spacing and no implicit BOS/EOS. Images use data URLs. Raw token
|
||||
arrays are already formatted and receive no named prefix. Custom `--override-chat-template`
|
||||
files are rejected; use a named prompt or system prefix instead.
|
||||
|
||||
The 32768-token maximum counts prefixes, image placeholders and separators. `--max-model-len`
|
||||
may lower it. Four full inputs need `--max-num-batched-tokens 131072 --max-num-seqs 4` to share
|
||||
one step; requests arriving during an active forward wait for the next step. Configured budgets
|
||||
size the arenas, so raising a budget reserves more memory even for smaller requests. The BF16
|
||||
GEMMs use bounded row launches and rebased pointers for tall combined batches, preserving whole
|
||||
attention sequences and existing arithmetic; unsupported multi-launch chains are refused.
|
||||
`--mm-max-patches 6400` covers the default 1120-square image in one encoder pass. See
|
||||
[ARCHITECTURES.md](ARCHITECTURES.md#nemotron35_embed-embedding-models) for geometry, numerical
|
||||
contracts and validation limits.
|
||||
|
||||
```sh
|
||||
# text, a batch of texts, or token ids
|
||||
curl -s http://localhost:8000/v1/embeddings -H 'Content-Type: application/json' \
|
||||
|
||||
+41
@@ -218,6 +218,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
|
||||
| `clamp` | `M`(range) `n` `dtype` | `x`, `lo`w, `hi`w → `y` |
|
||||
| `conv2d` | `M`(range) `width` `cin` `cout` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `dtype` `t_last`/opt `act`/opt | `x`, `w`w, `cu_seqlens`, `valid`? → `y`; `b`w? |
|
||||
| `conv2d_unfold` | `M`(range) `width` `cin` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `t_last`/opt `dtype` | `x`, `cu_seqlens`, `valid`? → `y` |
|
||||
| `pixtral_merge` | `M`(range) `n` `merge` `dtype` | `x`, `coord` → `y` |
|
||||
| `conv1d_dw` | `M`(range) `n` `k` `cu_div`/opt `dtype` | `x`, `w`w, `cu_seqlens` → `y`; `b`w? |
|
||||
| `rel_sinusoid` | `M`(range) `n` `max_timescale`:f64/opt `dtype` | → `y` |
|
||||
| `gelu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gelu·up, tanh approx) |
|
||||
@@ -898,6 +899,10 @@ as the weight's GEMM stored them and claims no form. It changes no value.
|
||||
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` |
|
||||
| `rope_rows` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` (the same rotation; at 64+ rows and 4+ heads one angle a (token, pair), byte-identical) |
|
||||
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` |
|
||||
| `position_scale` | `M`(range) `n` `original` `beta`:f64 `dtype` | `x`:inout, `positions` |
|
||||
| `embed_attn` | `M`(range) `head_dim` `gqa` `causal` `max_seqlen`/opt `dtype` `scale`:f64/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
|
||||
| `ministral_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `qkv`:inout, `pos` |
|
||||
| `pixtral_rope` | `M`(range) `head_dim` `n_head` `theta`:f64 `dtype` | `qkv`:inout, `coord` |
|
||||
| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`?, `q_w`w?, `k_w`w? |
|
||||
| `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `v_norm`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w |
|
||||
| `qkv_norm_rope_kv_store` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `dtype` `v_norm`/opt `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w, `slot_mapping`, `kv_cache`:inout |
|
||||
@@ -1012,6 +1017,42 @@ prefix of the full-width table: at `head_dim 512, rotary_dim 128`, frequency `i
|
||||
ladders), and the head past `rotary_dim` is untouched either way. `rope_table` takes `head_dim` for
|
||||
the same reason: its angles must stay `rope`'s exactly.
|
||||
|
||||
**`position_scale`** multiplies query row `r` by
|
||||
`1 + beta * log(1 + floor(positions[r] / original))`, rounding the multiplier to the input's
|
||||
dtype before multiplying. It takes a pitched `[M, n]` query view and nonnegative i32 positions;
|
||||
columns outside that view (keys and values in a fused QKV buffer) are unchanged. `original` must
|
||||
be positive and `beta` finite and nonnegative. It currently has host rows for bf16 and f32 only.
|
||||
It implements Ministral 3's query scaling after RoPE; it is independent of YaRN's cos/sin
|
||||
magnitude and does not change existing `rope` behavior.
|
||||
|
||||
**`embed_attn`** serves complete noncausal segments of at most 32768 rows. QK dot products
|
||||
are rounded to the activation dtype, multiplied by `scale` (default `1/sqrt(head_dim)`) and
|
||||
rounded again. Softmax is float32; its probabilities are rounded to the activation dtype before
|
||||
the value product. This reproduces the eager BF16 materialization boundaries used by the
|
||||
Nemotron reference. `causal` must be zero. Existing `attn_dense` semantics are unchanged.
|
||||
|
||||
**`ministral_rope`** rotates the Q and K heads of fused QKV rows with NeoX pairing and the
|
||||
resolved YaRN frequency ladder. Cosine/sine are rounded to the activation dtype, as are each
|
||||
of the two products before addition/subtraction, matching Ministral's BF16 rotary expression.
|
||||
V heads are unchanged. Active rows come from the issued tensor views; `M` is the capacity band.
|
||||
This separate operation preserves every existing `rope` implementation and schema.
|
||||
|
||||
**`pixtral_rope`** rotates Q and K of `[M, 3 * n_head * head_dim]` fused QKV rows, leaving V
|
||||
unchanged. `coord` is `[2, M]` nonnegative i32 `(height, width)` patch coordinates. The head
|
||||
dimension must be divisible by four. NeoX pairs `(i, i + head_dim/2)` use the height ladder
|
||||
`theta^(-4j/head_dim)` for `i = j < head_dim/4`, then the width ladder
|
||||
`theta^(-(4j+2)/head_dim)` for `i = j + head_dim/4`. In BF16, cos/sin and each product are
|
||||
rounded before the addition, as in Transformers. Host rows support BF16 and f32. This is a
|
||||
separate contract from `rope`'s existing axial mode, whose two ladders are identical.
|
||||
|
||||
**`pixtral_merge`** packs `[M, n]` raster patch rows into `[M / merge^2, n * merge^2]` rows.
|
||||
`coord` is `[4, M]` i32 `(row, column, height, width)` patch coordinates; it must describe whole
|
||||
raster grids, each side divisible by `merge`. Images may have different widths. One output row
|
||||
is a merged spatial cell with columns `(channel, dy, dx)`, matching PyTorch `unfold`; values
|
||||
are copied exactly. The complete coordinates are validated before writing, so invalid grids
|
||||
leave the output unchanged. Host rows support BF16 and f32. Automatic random shape fixtures
|
||||
cannot supply this coupled coordinate grid; callers must provide a valid grid fixture.
|
||||
|
||||
**`qk_norm_rope`** RMS-norms each q and k head of a fused `[q | k | v]` row against its gain (plus
|
||||
`wadd`), rounds, and rotates in place. `positions` is read as `rope` reads it, integer or f32.
|
||||
|
||||
|
||||
+4
-3
@@ -397,9 +397,10 @@ says so with `RAD_ARCH_SERVES_IMPORTS(0)` (`qwen35_w8a8` does), and imports keep
|
||||
below it. The pass's block is `n_tok / n_seq`; a block the plugin has no ops for should fail the
|
||||
step (`rad_block_dflash2.h` does). Appended in ABI 27.
|
||||
- **Media preprocessing is the core's** (`core/mm`): resizing, patching, placeholder-token
|
||||
expansion and positions, in five processor families (Qwen-VL, Gemma 4, LFM2-VL, Unlimited-OCR,
|
||||
GLM-5.3) chosen by the container's `vision_config.model_type` (Unlimited-OCR's by its
|
||||
`model_type`). A vision model with another pipeline needs a core change.
|
||||
expansion and positions, in six processor families (Qwen-VL, Gemma 4, LFM2-VL, Unlimited-OCR,
|
||||
GLM-5.3 and Pixtral for Nemotron 3.5) chosen by the container's `vision_config.model_type`
|
||||
and owning-model checks (Unlimited-OCR's by its `model_type`). A vision model with another
|
||||
pipeline needs a core change.
|
||||
Audio goes through one of two feature extractors, Gemma 4's and Qwen3-ASR's (Whisper's), chosen
|
||||
by `audio_config.model_type`.
|
||||
- **A speech model says how it hears**, through the optional
|
||||
|
||||
@@ -47,6 +47,7 @@ set(AVX_KERNEL_SRC
|
||||
avx_lora.cpp
|
||||
avx_attn.cpp
|
||||
avx_kvstream.cpp
|
||||
avx_pixtral.cpp
|
||||
avx_sam_attn.cpp
|
||||
avx_qsa.cpp
|
||||
avx_moe.cpp
|
||||
|
||||
@@ -107,6 +107,19 @@ std::vector<Case> build_cases() {
|
||||
add("scale_rows", { HI("M", 6), HI("n", 640), HS("act", "none"), HS("dtype", dt) },
|
||||
EB(6, 640, w, 2));
|
||||
}
|
||||
for (const char* dt : {"f32", "bf16"})
|
||||
add("position_scale",
|
||||
{HI("M", 7), HI("n", 259), HI("original", 16384), HF("beta", 0.1), HS("dtype", dt)});
|
||||
for (const char* dt : {"f32", "bf16"})
|
||||
add("pixtral_rope",
|
||||
{HI("M", 7), HI("head_dim", 64), HI("n_head", 2), HF("theta", 10000), HS("dtype", dt)});
|
||||
for (const char* dt : {"f32", "bf16"})
|
||||
add("ministral_rope", {HI("M", 7), HI("head_dim", 128), HI("n_head", 4), HI("n_head_kv", 1),
|
||||
HF("theta", 1e6), HF("yarn_factor", 16), HF("yarn_low", 8),
|
||||
HF("yarn_high", 24), HF("yarn_magnitude", 1), HS("dtype", dt)});
|
||||
for (const char* dt : {"f32", "bf16"})
|
||||
add("embed_attn", {HI("M", 7), HI("head_dim", 64), HI("n_head", 4), HI("gqa", 2),
|
||||
HI("causal", 0), HI("n_seq", 2), HS("dtype", dt)});
|
||||
/* Every dtype pair: `cast` carries the narrowing conventions and is checked at 1e-6, i.e.
|
||||
* exactly. */
|
||||
for (const char* from : { "f32", "bf16", "f16", "fp8_e4m3", "fp8_e5m2", "i8" })
|
||||
|
||||
@@ -597,6 +597,33 @@ AVX_KERNEL(pool_cols) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ position_scale */
|
||||
/* Ministral 3's query multiplier is rounded before multiplication, as in libref. */
|
||||
AVX_KERNEL(position_scale) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *pos = &a->t[1];
|
||||
// M in the resolved geometry is a capacity band; issued views carry the active rows.
|
||||
const int64_t M = x->rank == 2 ? x->shape[0] : 0;
|
||||
const int64_t n = p_int(a, "n", 0), orig = p_int(a, "original", 0);
|
||||
const float beta = p_f32(a, "beta", -1);
|
||||
if (M <= 0 || M > p_int(a, "M", 0) || n <= 0 || orig <= 0 || !std::isfinite(beta) || beta < 0 ||
|
||||
x->rank != 2 || x->shape[0] < M || x->shape[1] != n || pos->rank != 1 || numel(pos) < M)
|
||||
return RAD_E_SHAPE;
|
||||
if (pos->dtype != RAD_I32 || (x->dtype != RAD_BF16 && x->dtype != RAD_F32)) return RAD_E_DTYPE;
|
||||
for (int64_t r = 0; r < M; ++r)
|
||||
if (ldi(pos, offlin(pos, r)) < 0) return RAD_E_INVAL;
|
||||
AVX_PARALLEL_FOR_IF(M * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < M; ++r) {
|
||||
const int64_t p = ldi(pos, offlin(pos, r));
|
||||
const float scale = narrow1(x->dtype, 1.0f + beta * std::log(1.0f + (float)(p / orig)));
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
const int64_t at = rowoff(x, r, n) + j * laststride(x);
|
||||
stt(x, at, ldt(x, at) * scale);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ scale_rows */
|
||||
/* y[m, i] = x[m, i] * act(s[m]), plus add[m, i] when the optional residual is passed.
|
||||
*
|
||||
|
||||
@@ -90,6 +90,8 @@ int avx_par_force(int threads);
|
||||
X(seg_mean) X(mul_weight) X(pool_rows) X(pool_cols) \
|
||||
X(relu) X(clamp) X(conv2d) X(conv1d_dw) \
|
||||
X(rel_sinusoid) X(seg_sinusoid) X(conv2d_unfold) \
|
||||
X(position_scale) \
|
||||
X(embed_attn) X(ministral_rope) X(pixtral_rope) X(pixtral_merge) \
|
||||
/* ---- quantisation and rotation */ \
|
||||
X(quant_act_i8) X(quant_act_i8g) X(had_quant_act_i8) X(quant_act_fp8) \
|
||||
X(had_quant_act_fp8) X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) \
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
/* Nemotron's text/vision rotary, patch merger and materialized BF16 attention.
|
||||
* Separate ops preserve existing rotary, attention and merger contracts. */
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
|
||||
#include "rad_yarn.h"
|
||||
|
||||
using namespace avx;
|
||||
|
||||
AVX_KERNEL(pixtral_rope) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *rc = &a->t[1];
|
||||
// The issue's row views can be smaller than the resolved M capacity band.
|
||||
const int64_t M = x->rank == 2 ? x->shape[0] : 0;
|
||||
const int64_t D = p_int(a, "head_dim", 0), H = p_int(a, "n_head", 0);
|
||||
const float theta = p_f32(a, "theta", 0);
|
||||
if (M <= 0 || M > p_int(a, "M", 0) || D <= 0 || D % 4 || H <= 0 || !(theta > 0) ||
|
||||
!std::isfinite(theta) || x->rank != 2 || x->shape[0] < M || x->shape[1] != 3 * H * D ||
|
||||
rc->rank != 2 || rc->shape[0] != 2 || rc->shape[1] != M)
|
||||
return RAD_E_SHAPE;
|
||||
if (rc->dtype != RAD_I32 || (x->dtype != RAD_BF16 && x->dtype != RAD_F32)) return RAD_E_DTYPE;
|
||||
for (int64_t r = 0; r < 2; ++r)
|
||||
for (int64_t p = 0; p < M; ++p)
|
||||
if (ldi(rc, r * rc->stride[0] + p * rc->stride[1]) < 0) return RAD_E_INVAL;
|
||||
AVX_PARALLEL_FOR_IF(M * H * D >= AVX_PAR_MIN)
|
||||
for (int64_t p = 0; p < M; ++p) {
|
||||
for (int64_t i = 0; i < D / 2; ++i) {
|
||||
const int64_t axis = i / (D / 4), j = i % (D / 4);
|
||||
const float pos = (float)ldi(rc, axis * rc->stride[0] + p * rc->stride[1]);
|
||||
const float inv = 1.0f / sc_pow(theta, (float)(4 * j + 2 * axis) / D);
|
||||
const float angle = pos * inv;
|
||||
const float c = narrow1(x->dtype, sc_cos(angle)), s = narrow1(x->dtype, sc_sin(angle));
|
||||
for (int64_t h = 0; h < 2 * H; ++h) {
|
||||
const int64_t u = rowoff(x, p, 3 * H * D) + (h * D + i) * laststride(x);
|
||||
const int64_t v = u + (D / 2) * laststride(x);
|
||||
const float a0 = ldt(x, u), b0 = ldt(x, v);
|
||||
/* Transformers narrows cos/sin and each product before adding BF16 tensors. */
|
||||
stt(x, u, narrow1(x->dtype, a0 * c) - narrow1(x->dtype, b0 * s));
|
||||
stt(x, v, narrow1(x->dtype, b0 * c) + narrow1(x->dtype, a0 * s));
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(pixtral_merge) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *rc = &a->t[1], *y = &a->t[2];
|
||||
const int64_t M = x->rank == 2 ? x->shape[0] : 0;
|
||||
const int64_t N = p_int(a, "n", 0), K = p_int(a, "merge", 0);
|
||||
if (M <= 0 || M > p_int(a, "M", 0) || N <= 0 || K <= 0 || K > M || M / K < K || M % (K * K) ||
|
||||
x->rank != 2 || x->shape[0] != M || x->shape[1] != N || rc->rank != 2 ||
|
||||
rc->shape[0] != 4 || rc->shape[1] != M || y->rank != 2 || y->shape[0] != M / (K * K) ||
|
||||
y->shape[1] != N * K * K)
|
||||
return RAD_E_SHAPE;
|
||||
if (rc->dtype != RAD_I32 || x->dtype != y->dtype ||
|
||||
(x->dtype != RAD_BF16 && x->dtype != RAD_F32))
|
||||
return RAD_E_DTYPE;
|
||||
const auto coord = [&](int axis, int64_t p) {
|
||||
return ldi(rc, axis * rc->stride[0] + p * rc->stride[1]);
|
||||
};
|
||||
/* Verify full raster grids before any write, including variable image widths. The grid at
|
||||
* each image's first patch defines its boundary; no image is merged with the next one. */
|
||||
for (int64_t p = 0; p < M;) {
|
||||
const int64_t h = coord(2, p), w = coord(3, p);
|
||||
if (h <= 0 || w <= 0 || h % K || w % K || h > (M - p) / w) return RAD_E_INVAL;
|
||||
for (int64_t j = 0; j < h * w; ++j)
|
||||
if (coord(0, p + j) != j / w || coord(1, p + j) != j % w || coord(2, p + j) != h ||
|
||||
coord(3, p + j) != w)
|
||||
return RAD_E_INVAL;
|
||||
p += h * w;
|
||||
}
|
||||
for (int64_t p = 0; p < M;) {
|
||||
const int64_t h = coord(2, p), w = coord(3, p);
|
||||
for (int64_t r = 0; r < h / K; ++r)
|
||||
for (int64_t c = 0; c < w / K; ++c) {
|
||||
const int64_t dst = p / (K * K) + r * (w / K) + c;
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t dy = 0; dy < K; ++dy)
|
||||
for (int64_t dx = 0; dx < K; ++dx) {
|
||||
const int64_t src = p + (r * K + dy) * w + c * K + dx;
|
||||
const int64_t col = (n * K + dy) * K + dx;
|
||||
stt(y, rowoff(y, dst, N * K * K) + col * laststride(y),
|
||||
ldt(x, rowoff(x, src, N) + n * laststride(x)));
|
||||
}
|
||||
}
|
||||
p += h * w;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(ministral_rope) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *pos = &a->t[1];
|
||||
const int64_t M = x->rank == 2 ? x->shape[0] : 0;
|
||||
const int64_t D = p_int(a, "head_dim", 0), H = p_int(a, "n_head", 0),
|
||||
K = p_int(a, "n_head_kv", 0);
|
||||
const float theta = p_f32(a, "theta", 0);
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (M <= 0 || M > p_int(a, "M", 0) || D <= 0 || D > 2048 || D % 2 || H <= 0 || H > 1024 ||
|
||||
K <= 0 || K > H || H % K || x->shape[1] != (H + 2 * K) * D || pos->rank != 1 ||
|
||||
numel(pos) != M || !(theta > 0) || !std::isfinite(theta) || !rad_yarn_valid(yarn))
|
||||
return RAD_E_SHAPE;
|
||||
if (pos->dtype != RAD_I32 || (x->dtype != RAD_BF16 && x->dtype != RAD_F32)) return RAD_E_DTYPE;
|
||||
for (int64_t p = 0; p < M; ++p)
|
||||
if (ldi(pos, offlin(pos, p)) < 0) return RAD_E_INVAL;
|
||||
float freq[1024];
|
||||
for (int64_t i = 0; i < D / 2; ++i)
|
||||
freq[i] = yarn.frequency(1.0f / sc_pow(theta, (float)(2 * i) / (float)D), (int)i);
|
||||
AVX_PARALLEL_FOR_IF(M * (H + K) * D >= AVX_PAR_MIN)
|
||||
for (int64_t p = 0; p < M; ++p) {
|
||||
const float position = (float)(ldi(pos, offlin(pos, p)));
|
||||
for (int64_t i = 0; i < D / 2; ++i) {
|
||||
const float angle = position * freq[i];
|
||||
const float c = narrow1(x->dtype, sc_cos(angle) * yarn.magnitude);
|
||||
const float s = narrow1(x->dtype, sc_sin(angle) * yarn.magnitude);
|
||||
for (int64_t h = 0; h < H + K; ++h) {
|
||||
const int64_t u = rowoff(x, p, (H + 2 * K) * D) + (h * D + i) * laststride(x);
|
||||
const int64_t v = u + (D / 2) * laststride(x);
|
||||
const float a0 = ldt(x, u), b0 = ldt(x, v);
|
||||
stt(x, u, narrow1(x->dtype, a0 * c) - narrow1(x->dtype, b0 * s));
|
||||
stt(x, v, narrow1(x->dtype, b0 * c) + narrow1(x->dtype, a0 * s));
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The eager BF16 attention expression materializes QK, scaled logits and probabilities.
|
||||
* Keep it separate from attn_dense's existing fused arithmetic. Only whole, noncausal segments
|
||||
* are served. Stack storage is bounded by the model's 32768-token limit. */
|
||||
AVX_KERNEL(embed_attn) {
|
||||
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3], *out = &a->t[4];
|
||||
const int64_t M = q->rank == 2 ? q->shape[0] : 0;
|
||||
const int64_t D = p_int(a, "head_dim", 0), G = p_int(a, "gqa", 1);
|
||||
if (M <= 0 || M > p_int(a, "M", 0) || D <= 0 || D > 2048 || G <= 0 || q->shape[1] <= 0 ||
|
||||
q->shape[1] % D || k->rank != 2 || v->rank != 2 || out->rank != 2 || cu->rank != 1 ||
|
||||
numel(cu) < 2 || k->shape[0] != M || v->shape[0] != M || out->shape[0] != M)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t H = q->shape[1] / D, S = numel(cu) - 1;
|
||||
if (H % G || k->shape[1] != H / G * D || v->shape[1] != H / G * D || out->shape[1] != H * D)
|
||||
return RAD_E_SHAPE;
|
||||
if (p_int(a, "causal", 0) != 0) return RAD_E_UNSUPPORTED;
|
||||
if ((q->dtype != RAD_BF16 && q->dtype != RAD_F32) || k->dtype != q->dtype ||
|
||||
v->dtype != q->dtype || out->dtype != q->dtype || cu->dtype != RAD_I32)
|
||||
return RAD_E_DTYPE;
|
||||
auto boundary = [&](int64_t s) { return ldi(cu, offlin(cu, s)); };
|
||||
if (boundary(0) != 0 || boundary(S) != M) return RAD_E_INVAL;
|
||||
for (int64_t s = 0; s < S; ++s)
|
||||
if (boundary(s) >= boundary(s + 1) || boundary(s + 1) - boundary(s) > 32768)
|
||||
return RAD_E_INVAL;
|
||||
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)D));
|
||||
if (!std::isfinite(scale) || !(scale > 0)) return RAD_E_INVAL;
|
||||
AVX_PARALLEL_FOR_IF(M * H * D >= AVX_PAR_MIN)
|
||||
for (int64_t sh = 0; sh < S * H; ++sh) {
|
||||
const int64_t s = sh / H, h = sh % H, kh = h / G;
|
||||
const int64_t begin = boundary(s), end = boundary(s + 1);
|
||||
float scores[32768], accum[2048];
|
||||
for (int64_t i = begin; i < end; ++i) {
|
||||
const int64_t qb = rowoff(q, i, H * D) + h * D * laststride(q);
|
||||
float maximum = -INFINITY;
|
||||
for (int64_t j = begin; j < end; ++j) {
|
||||
const int64_t kb = rowoff(k, j, H / G * D) + kh * D * laststride(k);
|
||||
float dot = 0;
|
||||
for (int64_t d = 0; d < D; ++d)
|
||||
dot += ldt(q, qb + d * laststride(q)) * ldt(k, kb + d * laststride(k));
|
||||
const float score = narrow1(q->dtype, narrow1(q->dtype, dot) * scale);
|
||||
scores[j - begin] = score;
|
||||
maximum = std::max(maximum, score);
|
||||
}
|
||||
float sum = 0;
|
||||
for (int64_t j = begin; j < end; ++j) {
|
||||
scores[j - begin] = std::exp(scores[j - begin] - maximum);
|
||||
sum += scores[j - begin];
|
||||
}
|
||||
std::fill_n(accum, D, 0.0f);
|
||||
for (int64_t j = begin; j < end; ++j) {
|
||||
const float probability = narrow1(q->dtype, scores[j - begin] / sum);
|
||||
const int64_t vb = rowoff(v, j, H / G * D) + kh * D * laststride(v);
|
||||
for (int64_t d = 0; d < D; ++d)
|
||||
accum[d] += probability * ldt(v, vb + d * laststride(v));
|
||||
}
|
||||
const int64_t ob = rowoff(out, i, H * D) + h * D * laststride(out);
|
||||
for (int64_t d = 0; d < D; ++d)
|
||||
stt(out, ob + d * laststride(out), accum[d]);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -358,6 +358,23 @@ static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_
|
||||
P_F64O("llama3_orig") };
|
||||
static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") };
|
||||
|
||||
static const RadParamSpec pPositionScale[] = { P_INT("M"), P_INT("n"), P_INT("original"),
|
||||
P_F64("beta"), P_STR("dtype") };
|
||||
static const RadOperandSpec oPositionScale[] = { INOUT("x"), OPD("positions") };
|
||||
|
||||
static const RadParamSpec pEmbedAttn[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
|
||||
P_INT("causal"), P_INTO("max_seqlen"), P_STR("dtype"), P_F64O("scale") };
|
||||
static const RadOperandSpec oEmbedAttn[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), OUT("out") };
|
||||
static const RadParamSpec pMinistralRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_INT("n_head_kv"), P_F64("theta"), P_STR("dtype"), P_F64O("yarn_factor"),
|
||||
P_F64O("yarn_low"), P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
|
||||
static const RadOperandSpec oMinistralRope[] = { INOUT("qkv"), OPD("pos") };
|
||||
static const RadParamSpec pPixtralRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_F64("theta"), P_STR("dtype") };
|
||||
static const RadOperandSpec oPixtralRope[] = { INOUT("qkv"), OPD("coord") };
|
||||
static const RadParamSpec pPixtralMerge[] = { P_INT("M"), P_INT("n"), P_INT("merge"), P_STR("dtype") };
|
||||
static const RadOperandSpec oPixtralMerge[] = { OPD("x"), OPD("coord"), OUT("y") };
|
||||
|
||||
static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("theta"),
|
||||
P_F64("scale"), P_STR("dtype"),
|
||||
P_F64O("yarn_factor"), P_F64O("yarn_low"),
|
||||
@@ -1118,6 +1135,16 @@ static const RadOpSchema kSchemas[] = {
|
||||
"block-key page and first-token position; slots past the count get page -1. nc is each "
|
||||
"sequence's complete-block count." },
|
||||
{ "rope", ARR(pRope), ARR(oRope), "rotary embedding in place." },
|
||||
{ "embed_attn", ARR(pEmbedAttn), ARR(oEmbedAttn),
|
||||
"Whole noncausal segments with QK, scaled scores and probabilities rounded to activation dtype." },
|
||||
{ "ministral_rope", ARR(pMinistralRope), ARR(oMinistralRope),
|
||||
"Ministral NeoX rotary with BF16 cos/sin and separately rounded products; V is unchanged." },
|
||||
{ "pixtral_rope", ARR(pPixtralRope), ARR(oPixtralRope),
|
||||
"Pixtral axial rotary with interleaved height/width frequencies and BF16 product rounding." },
|
||||
{ "pixtral_merge", ARR(pPixtralMerge), ARR(oPixtralMerge),
|
||||
"Pack full raster patch grids into channel-major spatial merge blocks, without mixing images." },
|
||||
{ "position_scale", ARR(pPositionScale), ARR(oPositionScale),
|
||||
"Ministral position-dependent query scaling, with the scale rounded before multiplication." },
|
||||
{ "qk_norm_rope", ARR(pQkNormRope), ARR(oQkNormRope), "per-head QK norm then rotary embedding." },
|
||||
{ "scale_rows", ARR(pScaleRows), ARR(oScaleRows),
|
||||
"one scalar per row, optionally through an activation, broadcast across the row." },
|
||||
@@ -1713,6 +1740,11 @@ SIMPLE("avx_kv_resolve", "kv_resolve", "attn",
|
||||
"streamed KV residency map: selected block ids become ring slots, misses copied in",
|
||||
"i32 maps, u8 block planes", L(kv_resolve)),
|
||||
SIMPLE("avx_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, L(rope)),
|
||||
SIMPLE("avx_embed_attn", "embed_attn", "attn", "BF16 materialized encoder attention", "bf16/f32, i32 cu", L(embed_attn)),
|
||||
SIMPLE("avx_ministral_rope", "ministral_rope", "attn", "Ministral BF16 rotary", "bf16/f32 inout, i32 positions", L(ministral_rope)),
|
||||
SIMPLE("avx_pixtral_rope", "pixtral_rope", "attn", "Pixtral interleaved axial rotary", "bf16/f32 inout, i32 coordinates", L(pixtral_rope)),
|
||||
SIMPLE("avx_pixtral_merge", "pixtral_merge", "vision", "channel-major patch merger packing", "bf16/f32, i32 coordinates", L(pixtral_merge)),
|
||||
SIMPLE("avx_position_scale", "position_scale", "attn", "Ministral position-dependent query scale", "bf16/f32 inout, i32 positions", L(position_scale)),
|
||||
SIMPLE("avx_rope_table", "rope_table", "attn", "cos/sin at each position's own row", DT_FLOAT,
|
||||
L(rope_table)),
|
||||
SIMPLE("avx_qsa_block_key", "qsa_block_key", "attn",
|
||||
|
||||
@@ -75,6 +75,7 @@ set(R4D_UNITS
|
||||
# Unlimited-OCR's SAM tower: windowed attention with decomposed relative position.
|
||||
"r4d_sam_attn_bf16|"
|
||||
"r4d_encoder_bf16|"
|
||||
"r4d_nemotron_bf16|"
|
||||
# The image generator: attention over a paged prefix plus the pass's own rows, the causal
|
||||
# head_dim-128 dense form and the 1152-wide decoder head; plus the sampler, adaptive norm,
|
||||
# implicit-GEMM convolution and pixel ops.
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/* r4d_bf16_gemm_rows.h -- host-side row chunks for the BF16 WMMA GEMMs.
|
||||
*
|
||||
* The operands' dimensions use the kernels' signed-int ABI. Each launch uses 32-bit element
|
||||
* offsets for A and W, but successive launches rebase A and Y with 64-bit pointers. Thus M*K
|
||||
* need not fit in 32 bits. W is reused whole and still must fit; a wider weight needs a different
|
||||
* addressing implementation. This is a matrix-shape constraint, not a deployment token budget.
|
||||
*/
|
||||
#ifndef R4D_BF16_GEMM_ROWS_H
|
||||
#define R4D_BF16_GEMM_ROWS_H
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <cstdint>
|
||||
|
||||
static inline int r4d_bf16_gemm_chunk_rows(int64_t M, int64_t N, int64_t K, int row_tile,
|
||||
int col_tile) {
|
||||
if (M < 1 || M > INT_MAX || N < 1 || N > INT_MAX || K < 16 || K > INT_MAX || K % 16 ||
|
||||
row_tile < 1 || col_tile < 1)
|
||||
return 0;
|
||||
constexpr int64_t offsets = UINT32_MAX;
|
||||
if (N > offsets / K) return 0;
|
||||
const int64_t gx = (N + col_tile - 1) / col_tile;
|
||||
/* Bound each launch's row grid, not the full matrix. The tiled kernel flattens block IDs
|
||||
* in unsigned arithmetic, so the product must fit too. No input is rejected for exceeding
|
||||
* this workgroup budget: it becomes another launch on the same stream. */
|
||||
const int64_t gy = std::min<int64_t>(65535, offsets / gx);
|
||||
int64_t rows = std::min(offsets / K, gy * row_tile);
|
||||
if (rows >= row_tile) rows -= rows % row_tile;
|
||||
return (int)std::min(M, rows);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// C[M,N] = A[M,K] @ W[N,K]^T, bf16 in and out, fp32 accumulate.
|
||||
//
|
||||
// General in M up to R4D_GEMM64_MAX_M: MT row tiles per block, grid.y covers the rest. The 64 is
|
||||
// General in M: MT row tiles per block, bounded grids with rebased row launches. The 64 is
|
||||
// the registry band, not a kernel limit; the M <= 16 row forwards here too.
|
||||
//
|
||||
// A scalar kernel (one wave per output column, M accumulators) costs one weight load and M
|
||||
@@ -18,13 +18,13 @@
|
||||
// results are never stored.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_bf16_gemm_rows.h"
|
||||
#include "r4d_gdn_wmma.h"
|
||||
#include "r4d_chain.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define R4D_GEMM64_MAX_M 65536
|
||||
#define WAVE32 32
|
||||
|
||||
// A fragment from a base pointer plus a compile-time k step. With fragGo's 32-bit element offset,
|
||||
@@ -155,30 +155,55 @@ void r4d_gemm_bf16_nt_m64(long a, long w, long c, int M, int K, int N, int WV, i
|
||||
/* `chain`: the chained form (r4d_rad_gemm_bf16_m64 passes the row's parameter; M <= 64 always). */
|
||||
static void gemm_bf16_m64_launch(long a, long w, long c, int M, int K, int N, int WV, int SK,
|
||||
int MB, long stream, bool chain) {
|
||||
if (M < 1 || M > R4D_GEMM64_MAX_M) throw std::runtime_error("r4d gemm_bf16_nt_m64: M out of range");
|
||||
if (K % (SK * 16)) throw std::runtime_error("r4d gemm_bf16_nt_m64: K must be divisible by SK*16");
|
||||
if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_bf16_nt_m64: threads/block > 1024");
|
||||
const int ntiles = (N + 15) / 16, mtiles = (M + 15) / 16;
|
||||
if (WV < 1 || SK < 1 || (int64_t)WV * SK > 1024 / WAVE32)
|
||||
throw std::runtime_error("r4d gemm_bf16_nt_m64: invalid threads/block");
|
||||
if (K % ((int64_t)SK * 16))
|
||||
throw std::runtime_error("r4d gemm_bf16_nt_m64: K must be divisible by SK*16");
|
||||
if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_bf16_nt_m64: MB must be 1..4");
|
||||
dim3 grid((ntiles + WV - 1) / WV, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32);
|
||||
const int chunk = r4d_bf16_gemm_chunk_rows(M, N, K, MB * 16, WV * 16);
|
||||
if (!chunk) throw std::runtime_error("r4d gemm_bf16_nt_m64: invalid dimensions or weight span");
|
||||
// A chained op must publish one completion, not one per rebased launch. Existing chained
|
||||
// decode shapes (M <= 64) fit one launch; do not silently change their synchronization law.
|
||||
if (chain && chunk < M)
|
||||
throw std::runtime_error("r4d gemm_bf16_nt_m64: chained rows need one launch");
|
||||
const int ntiles = (N + 15) / 16;
|
||||
dim3 block(WV * SK * WAVE32);
|
||||
size_t smem = (size_t)WV * SK * 256 * sizeof(float);
|
||||
auto Ap = (const unsigned short*)a; auto Wp = (const unsigned short*)w;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
auto Wp = (const unsigned short*)w;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH(MT) hipLaunchKernelGGL((chain ? r4dchain_gemm_bf16_nt_m64<MT> \
|
||||
: r4d_gemm_bf16_nt_m64_kernel<MT>), \
|
||||
grid, block, smem, st, Ap, Wp, Cp, M, K, N, WV, SK)
|
||||
switch (MB) {
|
||||
case 1: LAUNCH(1); break;
|
||||
case 2: LAUNCH(2); break;
|
||||
case 3: LAUNCH(3); break;
|
||||
case 4: LAUNCH(4); break;
|
||||
default: throw std::runtime_error("r4d gemm_bf16_nt_m64: MB unsupported");
|
||||
#define LAUNCH(MT) \
|
||||
hipLaunchKernelGGL((chain ? r4dchain_gemm_bf16_nt_m64<MT> : r4d_gemm_bf16_nt_m64_kernel<MT>), \
|
||||
grid, block, smem, st, Ap, Wp, Cp, mm, K, N, WV, SK)
|
||||
for (int64_t m0 = 0; m0 < M; m0 += chunk) {
|
||||
const int mm = (int)std::min<int64_t>(chunk, M - m0), mtiles = (mm + 15) / 16;
|
||||
dim3 grid((ntiles + WV - 1) / WV, (mtiles + MB - 1) / MB);
|
||||
auto Ap = (const unsigned short*)a + m0 * K;
|
||||
auto Cp = (__hip_bfloat16*)c + m0 * N;
|
||||
switch (MB) {
|
||||
case 1:
|
||||
LAUNCH(1);
|
||||
break;
|
||||
case 2:
|
||||
LAUNCH(2);
|
||||
break;
|
||||
case 3:
|
||||
LAUNCH(3);
|
||||
break;
|
||||
case 4:
|
||||
LAUNCH(4);
|
||||
break;
|
||||
default:
|
||||
throw std::runtime_error("r4d gemm_bf16_nt_m64: MB unsupported");
|
||||
}
|
||||
const hipError_t e = hipGetLastError();
|
||||
if (e != hipSuccess) throw std::runtime_error(hipGetErrorString(e));
|
||||
}
|
||||
#undef LAUNCH
|
||||
}
|
||||
|
||||
int r4d_gemm_bf16_nt_m64_max_m(void) { return R4D_GEMM64_MAX_M; }
|
||||
int r4d_gemm_bf16_nt_m64_max_m(void) {
|
||||
return INT_MAX;
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
@@ -187,14 +212,16 @@ extern "C" int r4d_rad_gemm_bf16_m64(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 0);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.M > r4d_gemm_bf16_nt_m64_max_m()) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!r4d_bf16_gemm_chunk_rows(g.M, g.N, g.K, 16, 16)) return R4D_NO(RAD_E_SHAPE);
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, g.M, 16, BR_FLAT, &c, (g.N + 15) / 16); /* "K divisible by SK*16" */
|
||||
if (rc != RAD_OK) return rc;
|
||||
const bool chain = r4d_geti_or(a, "chain", 0) != 0;
|
||||
if (chain && r4d_bf16_gemm_chunk_rows(g.M, g.N, g.K, c.mb * 16, c.wv * 16) < g.M)
|
||||
return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
R4D_TRY("gemm_bf16_nt_m64",
|
||||
gemm_bf16_m64_launch(r4d_addr(g.a), r4d_addr(g.b), r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb,
|
||||
(long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0));
|
||||
gemm_bf16_m64_launch(r4d_addr(g.a), r4d_addr(g.b), r4d_addr(g.y), (int)g.M, (int)g.K,
|
||||
(int)g.N, c.wv, c.sk, c.mb, (long)(uintptr_t)s, chain));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
// and their results are never stored.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_bf16_gemm_rows.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_gdn_wmma.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
@@ -173,7 +174,7 @@ __global__ __launch_bounds__(256) void r4d_gemm_bf16_nt_tiled_kernel(
|
||||
enum { kBtLargeGrid = 32 };
|
||||
|
||||
int r4d_gemm_bf16_nt_tiled_arm(int M, int N) {
|
||||
const long long g = (long long)((N + 127) / 128) * ((M + 127) / 128);
|
||||
const long long g = ((N + 127ll) / 128) * ((M + 127ll) / 128);
|
||||
return g >= kBtLargeGrid ? 1 : 2;
|
||||
}
|
||||
|
||||
@@ -181,23 +182,40 @@ int r4d_gemm_bf16_nt_tiled_arm(int M, int N) {
|
||||
int r4d_gemm_bf16_nt_tiled(long a, long w, long c, int M, int K, int N, int SK, int tile,
|
||||
long stream) {
|
||||
if (M < 1 || N < 1 || K < BT_BK || K % BT_BK) return -1;
|
||||
if (SK < 1 || K % (SK * 16)) return -1;
|
||||
if (SK < 1 || K % ((int64_t)SK * 16)) return -1;
|
||||
if (tile != 1 && tile != 2) return -1;
|
||||
// 32-bit element offsets: the last row of either operand has to be addressable.
|
||||
if ((long long)M * K >= (1ll << 32) || (long long)N * K >= (1ll << 32)) return -1;
|
||||
const int spk = K / SK / 16;
|
||||
const int bt = tile == 1 ? 128 : 64;
|
||||
dim3 grid((N + bt - 1) / bt, (M + bt - 1) / bt), block(256);
|
||||
auto Ap = (const unsigned short*)a; auto Wp = (const unsigned short*)w;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
const int chunk = r4d_bf16_gemm_chunk_rows(M, N, K, bt, bt);
|
||||
if (!chunk) return -1;
|
||||
dim3 block(256);
|
||||
auto Wp = (const unsigned short*)w;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH(TM, TN, S) hipLaunchKernelGGL((r4d_gemm_bf16_nt_tiled_kernel<TM, TN, S>), grid, \
|
||||
block, 0, st, Ap, Wp, Cp, M, K, N, spk)
|
||||
#define LAUNCH(TM, TN, S) \
|
||||
hipLaunchKernelGGL((r4d_gemm_bf16_nt_tiled_kernel<TM, TN, S>), grid, block, 0, st, Ap, Wp, Cp, \
|
||||
mm, K, N, spk)
|
||||
const bool split = SK > 1;
|
||||
if (tile == 1) { if (split) LAUNCH(4, 2, true); else LAUNCH(4, 2, false); }
|
||||
else { if (split) LAUNCH(2, 1, true); else LAUNCH(2, 1, false); }
|
||||
for (int64_t m0 = 0; m0 < M; m0 += chunk) {
|
||||
const int mm = (int)std::min<int64_t>(chunk, M - m0);
|
||||
dim3 grid((N + bt - 1) / bt, (mm + bt - 1) / bt);
|
||||
auto Ap = (const unsigned short*)a + m0 * K;
|
||||
auto Cp = (__hip_bfloat16*)c + m0 * N;
|
||||
if (tile == 1) {
|
||||
if (split)
|
||||
LAUNCH(4, 2, true);
|
||||
else
|
||||
LAUNCH(4, 2, false);
|
||||
} else {
|
||||
if (split)
|
||||
LAUNCH(2, 1, true);
|
||||
else
|
||||
LAUNCH(2, 1, false);
|
||||
}
|
||||
const hipError_t e = hipGetLastError();
|
||||
if (e != hipSuccess) return (int)e;
|
||||
}
|
||||
#undef LAUNCH
|
||||
return (int)hipGetLastError();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
@@ -205,6 +223,7 @@ extern "C" int r4d_rad_gemm_bf16_tiled(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 0);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (!r4d_bf16_gemm_chunk_rows(g.M, g.N, g.K, 64, 64)) return R4D_NO(RAD_E_SHAPE);
|
||||
// The skinny row's split rule with the same arguments keeps the two rows' outputs identical.
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, g.M, 16, BR_FLAT, &c, (g.N + 15) / 16);
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
// Model-local BF16 seams. Attention recomputes QK in three bounded passes: maximum, f32
|
||||
// denominator, then BF16 probabilities times V. Online rescaling would round unnormalised P
|
||||
// and change this op's eager contract. No quadratic score buffer, allocation or host barrier.
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_dt16.h"
|
||||
#include "rad_yarn.h"
|
||||
#include <climits>
|
||||
#include <algorithm>
|
||||
#include <new>
|
||||
|
||||
namespace {
|
||||
constexpr int NT = 256;
|
||||
struct RotaryFrequency {
|
||||
float f[64] = {};
|
||||
};
|
||||
__device__ float bf2f(uint16_t x) {
|
||||
return __builtin_bit_cast(float, (uint32_t)x << 16);
|
||||
}
|
||||
__device__ float narrow(float x) {
|
||||
return bf2f(f32_to_bf16(x));
|
||||
}
|
||||
|
||||
// Metadata is device resident. Validate on the same queue before any data writes. A malformed
|
||||
// index faults the pass (asynchronously), rather than returning a successful partial embedding.
|
||||
__global__ void validate(const int* x, int64_t stride, int64_t plane, int M, int mode, int extra,
|
||||
int limit, int* valid) {
|
||||
if (threadIdx.x || blockIdx.x) return;
|
||||
*valid = 0;
|
||||
bool ok = true;
|
||||
if (mode == 0 || mode == 1) {
|
||||
for (int r = 0; r < M; ++r) {
|
||||
ok = ok && x[(int64_t)r * stride] >= 0;
|
||||
if (mode == 1) ok = ok && x[plane + (int64_t)r * stride] >= 0;
|
||||
}
|
||||
} else if (mode == 2) {
|
||||
ok = x[0] == 0 && x[(int64_t)extra * stride] == M;
|
||||
for (int s = 0; s < extra; ++s) {
|
||||
const int64_t b = x[(int64_t)s * stride], e = x[(int64_t)(s + 1) * stride];
|
||||
ok = ok && b >= 0 && e > b && e <= M && e - b <= limit;
|
||||
}
|
||||
} else {
|
||||
for (int64_t p = 0; ok && p < M;) {
|
||||
const int64_t h = x[2 * plane + p * stride], w = x[3 * plane + p * stride];
|
||||
ok = h > 0 && w > 0 && h % extra == 0 && w % extra == 0 && h <= (M - p) / w;
|
||||
for (int64_t j = 0; ok && j < h * w; ++j)
|
||||
ok = x[(p + j) * stride] == j / w && x[plane + (p + j) * stride] == j % w &&
|
||||
x[2 * plane + (p + j) * stride] == h && x[3 * plane + (p + j) * stride] == w;
|
||||
if (ok) p += h * w;
|
||||
}
|
||||
}
|
||||
if (!ok) __builtin_trap();
|
||||
*valid = 1;
|
||||
}
|
||||
|
||||
__global__ void scale(uint16_t* x, int64_t ld, int64_t cs, const int* pos, int64_t ps, int M, int n,
|
||||
int original, float beta, const int* valid) {
|
||||
if (*valid != 1) return;
|
||||
for (int64_t r = blockIdx.y; r < M; r += gridDim.y) {
|
||||
const int64_t c = (int64_t)blockIdx.x * NT + threadIdx.x;
|
||||
if (c < n) {
|
||||
const float g = narrow(1.f + beta * logf(1.f + (float)(pos[r * ps] / original)));
|
||||
x[r * ld + c * cs] = f32_to_bf16(bf2f(x[r * ld + c * cs]) * g);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void rope(uint16_t* x, int64_t ld, int64_t cs, const int* pos, int64_t ps, int64_t plane,
|
||||
int M, int D, int H, int K, RotaryFrequency frequency, float magnitude,
|
||||
bool pixtral, const int* valid) {
|
||||
if (*valid != 1) return;
|
||||
const int i = threadIdx.x % (D / 2), h = threadIdx.x / (D / 2) + blockIdx.x * (NT / (D / 2));
|
||||
if (h >= H + K) return;
|
||||
for (int64_t r = blockIdx.y; r < M; r += gridDim.y) {
|
||||
const int axis = pixtral ? i / (D / 4) : 0;
|
||||
const float angle = (float)pos[axis * plane + r * ps] * frequency.f[i];
|
||||
const float c = narrow(cosf(angle) * magnitude), s = narrow(sinf(angle) * magnitude);
|
||||
const int64_t u = r * ld + (h * D + i) * cs, v = u + (D / 2) * cs;
|
||||
const float a = bf2f(x[u]), b = bf2f(x[v]);
|
||||
x[u] = f32_to_bf16(narrow(a * c) - narrow(b * s));
|
||||
x[v] = f32_to_bf16(narrow(b * c) + narrow(a * s));
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void merge(const uint16_t* x, int64_t ld, int64_t cs, const int* rc, int64_t rs,
|
||||
int64_t ps, uint16_t* y, int64_t yl, int64_t ys, int M, int N, int K,
|
||||
const int* valid) {
|
||||
if (*valid != 1) return;
|
||||
for (int64_t p = blockIdx.y; p < M; p += gridDim.y) {
|
||||
const int row = rc[p * ps], col = rc[rs + p * ps], w = rc[3 * rs + p * ps];
|
||||
if (row % K || col % K) continue;
|
||||
const int64_t base = p - (int64_t)row * w - col;
|
||||
const int64_t dst = base / (K * K) + (row / K) * (w / K) + col / K;
|
||||
for (int64_t n = (int64_t)blockIdx.x * NT + threadIdx.x; n < N; n += (int64_t)gridDim.x * NT)
|
||||
for (int dy = 0; dy < K; ++dy)
|
||||
for (int dx = 0; dx < K; ++dx)
|
||||
y[dst * yl + ((int64_t)n * K * K + dy * K + dx) * ys] =
|
||||
x[(p + (int64_t)dy * w + dx) * ld + (int64_t)n * cs];
|
||||
}
|
||||
}
|
||||
|
||||
template <int D>
|
||||
__global__ __launch_bounds__(32) void attention(const uint16_t* q, const uint16_t* k,
|
||||
const uint16_t* v, uint16_t* out, const int* cu,
|
||||
int64_t cus, int M, int H, int G, int64_t ql,
|
||||
int64_t kl, int64_t vl, int64_t ol, float scale,
|
||||
const int* valid) {
|
||||
if (*valid != 1) return;
|
||||
using BF = DT16<0>;
|
||||
const int lane = threadIdx.x, c = lane & 15, h = lane >> 4;
|
||||
const int begin = cu[(int64_t)blockIdx.z * cus], end = cu[(int64_t)(blockIdx.z + 1) * cus];
|
||||
const int qi = blockIdx.x * 16 + c, head = blockIdx.y, kh = head / G;
|
||||
if ((int)blockIdx.x * 16 >= end - begin) return;
|
||||
const int qr = begin + min(qi, end - begin - 1);
|
||||
typename BF::frag qf[D / 16];
|
||||
for (int t = 0; t < D / 16; ++t) {
|
||||
typename BF::frag f;
|
||||
for (int e = 0; e < 8; ++e)
|
||||
f[e] = __builtin_bit_cast(__bf16, q[(int64_t)qr * ql + head * D + t * 16 + h * 8 + e]);
|
||||
qf[t] = f;
|
||||
}
|
||||
__shared__ uint16_t sv[D][24];
|
||||
__shared__ float sp[16][16];
|
||||
v8f acc[D / 16];
|
||||
for (int t = 0; t < D / 16; ++t)
|
||||
acc[t] = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
float mx = -INFINITY, denom = 0;
|
||||
for (int pass = 0; pass < 3; ++pass) {
|
||||
for (int kb = begin; kb < end; kb += 16) {
|
||||
v8f s = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
if constexpr (D == 64) {
|
||||
// Pixtral's small heads: preserve the reference dot order, including very small
|
||||
// components beside the learned large coordinates. BF16 midpoint crossings
|
||||
// otherwise compound over the vision tower before the text encoder sees it.
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int kr = min(kb + h * 8 + e, end - 1);
|
||||
float dot = 0;
|
||||
for (int d = 0; d < D; ++d)
|
||||
dot +=
|
||||
bf2f(q[(int64_t)qr * ql + head * D + d]) * bf2f(k[(int64_t)kr * kl + kh * D + d]);
|
||||
s[e] = dot;
|
||||
}
|
||||
} else {
|
||||
for (int t = 0; t < D / 16; ++t) {
|
||||
typename BF::frag f;
|
||||
const int kr = min(kb + c, end - 1);
|
||||
for (int e = 0; e < 8; ++e)
|
||||
f[e] = __builtin_bit_cast(__bf16, k[(int64_t)kr * kl + kh * D + t * 16 + h * 8 + e]);
|
||||
s = BF::wmma(f, qf[t], s);
|
||||
}
|
||||
}
|
||||
float p[8];
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const float score = narrow(narrow(s[e]) * scale);
|
||||
p[e] = kb + h * 8 + e < end ? score : -INFINITY;
|
||||
if (pass == 0)
|
||||
mx = fmaxf(mx, p[e]);
|
||||
else
|
||||
p[e] = expf(p[e] - mx);
|
||||
if (pass == 1 && D != 64) denom += p[e];
|
||||
}
|
||||
if constexpr (D == 64) {
|
||||
if (pass == 1) {
|
||||
for (int e = 0; e < 8; ++e)
|
||||
denom += __shfl(p[e], c);
|
||||
for (int e = 0; e < 8; ++e)
|
||||
denom += __shfl(p[e], c + 16);
|
||||
}
|
||||
}
|
||||
if (pass != 2) continue;
|
||||
if constexpr (D == 64) {
|
||||
for (int e = 0; e < 8; ++e)
|
||||
sp[c][h * 8 + e] = narrow(p[e] / denom);
|
||||
__syncthreads();
|
||||
for (int j = 0; j < 16 && kb + j < end; ++j)
|
||||
for (int t = 0; t < D / 16; ++t)
|
||||
for (int e = 0; e < 8; ++e)
|
||||
acc[t][e] += sp[c][j] * bf2f(v[(int64_t)(kb + j) * vl + kh * D + t * 16 + h * 8 + e]);
|
||||
__syncthreads();
|
||||
continue;
|
||||
}
|
||||
for (int z = lane; z < D * 16; z += 32) {
|
||||
const int d = z / 16, key = z % 16;
|
||||
sv[d][key] = kb + key < end ? v[(int64_t)(kb + key) * vl + kh * D + d] : 0;
|
||||
}
|
||||
__syncthreads();
|
||||
typename BF::frag pf;
|
||||
for (int e = 0; e < 8; ++e)
|
||||
pf[e] = __builtin_bit_cast(__bf16, f32_to_bf16(p[e] / denom));
|
||||
for (int t = 0; t < D / 16; ++t) {
|
||||
typename BF::frag vf;
|
||||
for (int e = 0; e < 8; ++e)
|
||||
vf[e] = __builtin_bit_cast(__bf16, sv[t * 16 + c][h * 8 + e]);
|
||||
acc[t] = BF::wmma(vf, pf, acc[t]);
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
if (pass == 0) mx = fmaxf(mx, __shfl_xor(mx, 16));
|
||||
if (pass == 1 && D != 64) denom += __shfl_xor(denom, 16);
|
||||
}
|
||||
if (qi >= end - begin) return;
|
||||
for (int t = 0; t < D / 16; ++t)
|
||||
for (int e = 0; e < 8; ++e)
|
||||
out[(int64_t)(begin + qi) * ol + head * D + t * 16 + h * 8 + e] = f32_to_bf16(acc[t][e]);
|
||||
}
|
||||
|
||||
// Pixtral's RGB 14x14 patch projection has K=588, outside the existing K%16 GEMMs.
|
||||
// Keep the oracle's ordered f32 dot for this small stem: a WMMA reduction can cross a BF16
|
||||
// rounding midpoint. No existing GEMM row accepts this geometry, so no old row is replaced.
|
||||
__global__ __launch_bounds__(NT) void patch_projection(const uint16_t* a, const uint16_t* w,
|
||||
uint16_t* y, int M, int N, int64_t al,
|
||||
int64_t wl, int64_t yl) {
|
||||
const int n = blockIdx.x * NT + threadIdx.x;
|
||||
if (n >= N) return;
|
||||
for (int64_t r = blockIdx.y; r < M; r += gridDim.y) {
|
||||
float sum = 0;
|
||||
for (int d = 0; d < 588; ++d)
|
||||
sum += bf2f(a[r * al + d]) * bf2f(w[(int64_t)n * wl + d]);
|
||||
y[r * yl + n] = f32_to_bf16(sum);
|
||||
}
|
||||
}
|
||||
|
||||
bool matrix(const RadTensor& t, int64_t m, int64_t n) {
|
||||
constexpr int64_t max_elements = INT64_MAX / 2;
|
||||
if (!t.data || t.dtype != RAD_BF16 || t.rank != 2 || t.shape[0] != m || t.shape[1] != n ||
|
||||
m <= 0 || n <= 0 || t.stride[1] <= 0 || t.stride[0] <= 0 || n > max_elements / t.stride[1])
|
||||
return false;
|
||||
const int64_t columns = (n - 1) * t.stride[1];
|
||||
return t.stride[0] >= columns + 1 && (m - 1) <= (max_elements - columns) / t.stride[0];
|
||||
}
|
||||
bool indices(const RadTensor& t, int64_t n, int planes = 1) {
|
||||
constexpr int64_t max_elements = INT64_MAX / 4;
|
||||
if (!t.data || t.dtype != RAD_I32 || t.rank != (planes == 1 ? 1u : 2u) || n <= 0 ||
|
||||
t.stride[t.rank - 1] <= 0 || n > max_elements / t.stride[t.rank - 1])
|
||||
return false;
|
||||
if (planes == 1) return t.shape[0] == n;
|
||||
const int64_t columns = (n - 1) * t.stride[1];
|
||||
return t.shape[0] == planes && t.shape[1] == n && t.stride[0] >= columns + 1 &&
|
||||
t.stride[0] <= (max_elements - columns) / (planes - 1);
|
||||
}
|
||||
int prepare(const RadArgs* a, RadStream stream, const RadTensor& idx, int M, int mode,
|
||||
int extra = 0, int limit = 32768) {
|
||||
if (!a->scratch || a->scratch_bytes < 4) return RAD_E_SCRATCH;
|
||||
hipLaunchKernelGGL(validate, dim3(1), dim3(1), 0, (hipStream_t)stream, (const int*)idx.data,
|
||||
idx.stride[idx.rank - 1], idx.rank == 2 ? idx.stride[0] : 0, M, mode, extra,
|
||||
limit, (int*)a->scratch);
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
int finish() {
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
}
|
||||
|
||||
// Frequencies are shape constants. Resolve them once with the host oracle's powf, rather than
|
||||
// let a device pow approximation perturb long-position phases before BF16 narrowing.
|
||||
static int rotary_init(const RadParam* p, int np, void** out, bool pix) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
RadArgs a{};
|
||||
a.p = p;
|
||||
a.n_p = np;
|
||||
const int64_t D = r4d_geti_or(&a, "head_dim", 0);
|
||||
const float theta = r4d_getf(&a, "theta", 0);
|
||||
const RadYarn yarn = rad_yarn_args(&a);
|
||||
if ((D != 64 && D != 128) || !std::isfinite(theta) || theta <= 0 || !rad_yarn_valid(yarn))
|
||||
return RAD_E_SHAPE;
|
||||
auto* f = new (std::nothrow) RotaryFrequency;
|
||||
if (!f) return RAD_E_NOMEM;
|
||||
for (int i = 0; i < D / 2; ++i) {
|
||||
const int axis = pix ? i / (D / 4) : 0, j = pix ? i % (D / 4) : i;
|
||||
const float inv = 1.f / std::pow(theta, (float)(pix ? 4 * j + 2 * axis : 2 * i) / (float)D);
|
||||
f->f[i] = pix ? inv : yarn.frequency(inv, i);
|
||||
}
|
||||
*out = f;
|
||||
return RAD_OK;
|
||||
}
|
||||
extern "C" int r4d_ministral_init(const RadParam* p, int n, int, int, void** out) {
|
||||
return rotary_init(p, n, out, false);
|
||||
}
|
||||
extern "C" int r4d_pixtral_init(const RadParam* p, int n, int, int, void** out) {
|
||||
return rotary_init(p, n, out, true);
|
||||
}
|
||||
extern "C" void r4d_rotary_fini(void* p) {
|
||||
delete (RotaryFrequency*)p;
|
||||
}
|
||||
extern "C" int64_t r4d_nemotron_scratch(const RadArgs*) {
|
||||
return 4;
|
||||
}
|
||||
extern "C" int r4d_rad_position_scale(const RadArgs* a, RadStream stream) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const auto &x = a->t[0], &p = a->t[1];
|
||||
const int64_t M = x.rank == 2 ? x.shape[0] : 0, n = r4d_geti_or(a, "n", 0),
|
||||
orig = r4d_geti_or(a, "original", 0);
|
||||
const float beta = r4d_getf(a, "beta", -1);
|
||||
if (M <= 0 || M > INT_MAX || M > r4d_geti_or(a, "M", 0) || n <= 0 || n > INT_MAX || orig <= 0 ||
|
||||
orig > INT_MAX || !std::isfinite(beta) || beta < 0 || !matrix(x, M, n) || !indices(p, M))
|
||||
return RAD_E_SHAPE;
|
||||
int rc = prepare(a, stream, p, (int)M, 0);
|
||||
if (rc < 0) return rc;
|
||||
hipLaunchKernelGGL(scale, dim3((n + NT - 1) / NT, std::min<int64_t>(M, 65535)), dim3(NT), 0,
|
||||
(hipStream_t)stream, (uint16_t*)x.data, x.stride[0], x.stride[1],
|
||||
(const int*)p.data, p.stride[0], (int)M, (int)n, (int)orig, beta,
|
||||
(const int*)a->scratch);
|
||||
return finish();
|
||||
}
|
||||
static int rotary(const RadArgs* a, RadStream stream, bool pix) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const auto &x = a->t[0], &p = a->t[1];
|
||||
const int64_t M = x.rank == 2 ? x.shape[0] : 0, D = r4d_geti_or(a, "head_dim", 0),
|
||||
H = r4d_geti_or(a, "n_head", 0), K = pix ? H : r4d_geti_or(a, "n_head_kv", 0);
|
||||
const float theta = r4d_getf(a, "theta", 0);
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (M <= 0 || M > INT_MAX || M > r4d_geti_or(a, "M", 0) || (D != 64 && D != 128) || H <= 0 ||
|
||||
H > 1024 || K <= 0 || K > H || H % K || !std::isfinite(theta) || theta <= 0 ||
|
||||
!rad_yarn_valid(yarn) || !matrix(x, M, (H + 2 * K) * D) || !indices(p, M, pix ? 2 : 1))
|
||||
return RAD_E_SHAPE;
|
||||
if (!a->instance) return RAD_E_STATE;
|
||||
int rc = prepare(a, stream, p, (int)M, pix ? 1 : 0);
|
||||
if (rc < 0) return rc;
|
||||
hipLaunchKernelGGL(rope, dim3(((H + K) * (D / 2) + NT - 1) / NT, std::min<int64_t>(M, 65535)),
|
||||
dim3(NT), 0, (hipStream_t)stream, (uint16_t*)x.data, x.stride[0], x.stride[1],
|
||||
(const int*)p.data, p.stride[p.rank - 1], pix ? p.stride[0] : 0, (int)M,
|
||||
(int)D, (int)H, (int)K, *(const RotaryFrequency*)a->instance, yarn.magnitude,
|
||||
pix, (const int*)a->scratch);
|
||||
return finish();
|
||||
}
|
||||
extern "C" int r4d_rad_ministral_rope(const RadArgs* a, RadStream s) {
|
||||
return rotary(a, s, false);
|
||||
}
|
||||
extern "C" int r4d_rad_pixtral_rope(const RadArgs* a, RadStream s) {
|
||||
return rotary(a, s, true);
|
||||
}
|
||||
extern "C" int r4d_rad_pixtral_merge(const RadArgs* a, RadStream stream) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const auto &x = a->t[0], &p = a->t[1], &y = a->t[2];
|
||||
const int64_t M = x.rank == 2 ? x.shape[0] : 0, N = r4d_geti_or(a, "n", 0),
|
||||
K = r4d_geti_or(a, "merge", 0);
|
||||
if (M <= 0 || M > INT_MAX || M > r4d_geti_or(a, "M", 0) || N <= 0 || N > INT_MAX || K != 2 ||
|
||||
M % 4 || !matrix(x, M, N) || !indices(p, M, 4) || !matrix(y, M / 4, N * 4))
|
||||
return RAD_E_SHAPE;
|
||||
int rc = prepare(a, stream, p, (int)M, 3, 2);
|
||||
if (rc < 0) return rc;
|
||||
hipLaunchKernelGGL(merge, dim3((N + NT - 1) / NT, std::min<int64_t>(M, 65535)), dim3(NT), 0,
|
||||
(hipStream_t)stream, (const uint16_t*)x.data, x.stride[0], x.stride[1],
|
||||
(const int*)p.data, p.stride[0], p.stride[1], (uint16_t*)y.data, y.stride[0],
|
||||
y.stride[1], (int)M, (int)N, (int)K, (const int*)a->scratch);
|
||||
return finish();
|
||||
}
|
||||
extern "C" int r4d_rad_embed_attn(const RadArgs* a, RadStream stream) {
|
||||
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
|
||||
const auto &q = a->t[0], &k = a->t[1], &v = a->t[2], &cu = a->t[3], &o = a->t[4];
|
||||
const int64_t M = q.rank == 2 ? q.shape[0] : 0, D = r4d_geti_or(a, "head_dim", 0),
|
||||
G = r4d_geti_or(a, "gqa", 0), H = D > 0 ? q.shape[1] / D : 0,
|
||||
S = cu.rank == 1 ? cu.shape[0] - 1 : 0;
|
||||
if (M <= 0 || M > INT_MAX || M > r4d_geti_or(a, "M", 0) || (D != 64 && D != 128) || G <= 0 ||
|
||||
H <= 0 || H > 65535 || H % G || S <= 0 || S > 65535 || r4d_geti_or(a, "causal", 0) != 0 ||
|
||||
!matrix(q, M, H * D) || !matrix(k, M, H / G * D) || !matrix(v, M, H / G * D) ||
|
||||
!matrix(o, M, H * D) || !indices(cu, S + 1) || q.stride[1] != 1 || k.stride[1] != 1 ||
|
||||
v.stride[1] != 1 || o.stride[1] != 1)
|
||||
return RAD_E_SHAPE;
|
||||
const float sc = r4d_getf(a, "scale", 1.0 / std::sqrt((float)D));
|
||||
if (!std::isfinite(sc) || sc <= 0) return RAD_E_INVAL;
|
||||
const int64_t limit = std::min<int64_t>({M, 32768, r4d_geti_or(a, "max_seqlen", 32768)});
|
||||
if (limit <= 0) return RAD_E_SHAPE;
|
||||
int rc = prepare(a, stream, cu, (int)M, 2, (int)S, (int)limit);
|
||||
if (rc < 0) return rc;
|
||||
// Each segment is at most 32768; combined M may exceed that. The grid uses a bounded
|
||||
// per-segment extent without carving a request into independent attention states.
|
||||
dim3 grid((limit + 15) / 16, H, S);
|
||||
#define LAUNCH(DIM) \
|
||||
hipLaunchKernelGGL((attention<DIM>), grid, dim3(32), 0, (hipStream_t)stream, \
|
||||
(const uint16_t*)q.data, (const uint16_t*)k.data, (const uint16_t*)v.data, \
|
||||
(uint16_t*)o.data, (const int*)cu.data, cu.stride[0], (int)M, (int)H, (int)G, \
|
||||
q.stride[0], k.stride[0], v.stride[0], o.stride[0], sc, \
|
||||
(const int*)a->scratch)
|
||||
if (D == 64) {
|
||||
LAUNCH(64);
|
||||
} else {
|
||||
LAUNCH(128);
|
||||
}
|
||||
#undef LAUNCH
|
||||
return finish();
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_pixtral_patch(const RadArgs* a, RadStream stream) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const auto &x = a->t[0], &w = a->t[1], &y = a->t[2];
|
||||
const int64_t M = x.rank == 2 ? x.shape[0] : 0, N = r4d_geti_or(a, "N", 0);
|
||||
if (M <= 0 || M > INT_MAX || M > r4d_geti_or(a, "M", 0) || N <= 0 || N > INT_MAX ||
|
||||
r4d_geti_or(a, "K", 0) != 588 || !matrix(x, M, 588) || !matrix(w, N, 588) ||
|
||||
!matrix(y, M, N) || x.stride[1] != 1 || w.stride[1] != 1 || y.stride[1] != 1)
|
||||
return RAD_E_SHAPE;
|
||||
hipLaunchKernelGGL(patch_projection, dim3((N + NT - 1) / NT, std::min<int64_t>(M, 65535)),
|
||||
dim3(NT), 0, (hipStream_t)stream, (const uint16_t*)x.data,
|
||||
(const uint16_t*)w.data, (uint16_t*)y.data, (int)M, (int)N, x.stride[0],
|
||||
w.stride[0], y.stride[0]);
|
||||
return finish();
|
||||
}
|
||||
@@ -13,6 +13,19 @@
|
||||
#include "r4d_args.h"
|
||||
|
||||
|
||||
extern "C" {
|
||||
int r4d_rad_pixtral_patch(const RadArgs*, RadStream);
|
||||
int r4d_rad_position_scale(const RadArgs*, RadStream);
|
||||
int r4d_rad_ministral_rope(const RadArgs*, RadStream);
|
||||
int r4d_rad_pixtral_rope(const RadArgs*, RadStream);
|
||||
int r4d_rad_pixtral_merge(const RadArgs*, RadStream);
|
||||
int r4d_rad_embed_attn(const RadArgs*, RadStream);
|
||||
int64_t r4d_nemotron_scratch(const RadArgs*);
|
||||
int r4d_ministral_init(const RadParam*, int, int, int, void**);
|
||||
int r4d_pixtral_init(const RadParam*, int, int, int, void**);
|
||||
void r4d_rotary_fini(void*);
|
||||
}
|
||||
|
||||
/* ================================================================== the priority ladder
|
||||
*
|
||||
* The selector ranks candidate rows by an integer priority (spec §2.1); where two rows of one op
|
||||
|
||||
+74
-6
@@ -2915,7 +2915,37 @@ static const RadOperandSpec oQuantCols[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
|
||||
static const RadParamSpec pPositionScale[] = { P_INT("M"), P_INT("n"), P_INT("original"),
|
||||
P_F64("beta"), P_STR("dtype") };
|
||||
static const RadOperandSpec oPositionScale[] = { { "x", RAD_OPD_INOUT, 0 }, { "positions", RAD_OPD_IN, 0 } };
|
||||
|
||||
static const RadParamSpec pEmbedAttn[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
|
||||
P_INT("causal"), P_INTO("max_seqlen"), P_STR("dtype"), P_F64O("scale") };
|
||||
static const RadOperandSpec oEmbedAttn[] = { { "q", RAD_OPD_IN, 0 }, { "k", RAD_OPD_IN, 0 }, { "v", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "out", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pMinistralRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_INT("n_head_kv"), P_F64("theta"), P_STR("dtype"), P_F64O("yarn_factor"),
|
||||
P_F64O("yarn_low"), P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
|
||||
static const RadOperandSpec oMinistralRope[] = { { "qkv", RAD_OPD_INOUT, 0 }, { "pos", RAD_OPD_IN, 0 } };
|
||||
static const RadParamSpec pPixtralRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_F64("theta"), P_STR("dtype") };
|
||||
static const RadOperandSpec oPixtralRope[] = { { "qkv", RAD_OPD_INOUT, 0 }, { "coord", RAD_OPD_IN, 0 } };
|
||||
static const RadParamSpec pPixtralMerge[] = { P_INT("M"), P_INT("n"), P_INT("merge"), P_STR("dtype") };
|
||||
static const RadOperandSpec oPixtralMerge[] = { { "x", RAD_OPD_IN, 0 }, { "coord", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
|
||||
|
||||
static const RadOpSchema kSchemas[] = {
|
||||
{ "embed_attn", ROW(pEmbedAttn), ROW(oEmbedAttn),
|
||||
"Whole noncausal segments with QK, scaled scores and probabilities rounded to activation dtype." },
|
||||
{ "ministral_rope", ROW(pMinistralRope), ROW(oMinistralRope),
|
||||
"Ministral NeoX rotary with BF16 cos/sin and separately rounded products; V is unchanged." },
|
||||
{ "pixtral_rope", ROW(pPixtralRope), ROW(oPixtralRope),
|
||||
"Pixtral axial rotary with interleaved height/width frequencies and BF16 product rounding." },
|
||||
{ "pixtral_merge", ROW(pPixtralMerge), ROW(oPixtralMerge),
|
||||
"Pack full raster patch grids into channel-major spatial merge blocks, without mixing images." },
|
||||
{ "position_scale", ROW(pPositionScale), ROW(oPositionScale),
|
||||
"Scale query row p by 1 + beta * log(1 + floor(position[p] / original)), rounding the scale "
|
||||
"to x's dtype before multiplication. Positions are nonnegative i32." },
|
||||
|
||||
SCHEMA("rmsnorm", pRmsNorm, oRmsNorm,
|
||||
"y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in "
|
||||
"f32 after the load because forming it in bf16 first costs 0.3% per channel."),
|
||||
@@ -4760,16 +4790,16 @@ static const RadConstraint cLogitRerank[] = {
|
||||
static const RadConstraint cGemmNt[] = {
|
||||
C_LE("M", 16), C_DIV("K", 256), C_IN("dtype", "bf16"),
|
||||
};
|
||||
/* No 64-row cap: grid.y covers any row count, so the band is the grid's reach. A cap would force a
|
||||
* caller with a taller projection (the gated delta net's a|b) to slice it. */
|
||||
/* Matrix rows use the signed-int device ABI. Bounded row launches cover taller matrices without
|
||||
* requiring callers to slice their complete operations; arenas still follow configured budgets. */
|
||||
static const RadConstraint cGemmNt64[] = {
|
||||
C_LE("M", 65536), C_DIV("K", 16), C_IN("dtype", "bf16"),
|
||||
C_LE("M", 2147483647), C_DIV("K", 16), C_IN("dtype", "bf16"),
|
||||
};
|
||||
/* M > 64 is the prefill band, where the skinny row's per-wave fragment loads re-read the
|
||||
* activation once per N tile. N >= 128 because a 64- or 128-wide tile over a narrower N computes
|
||||
* mostly clamped rows; those shapes (the GDN a|b at 48, the shared-expert gate at 1) stay skinny. */
|
||||
static const RadConstraint cGemmNtTiled[] = {
|
||||
C_GE("M", 65), C_LE("M", 65536), C_GE("N", 128), C_DIV("K", 64), C_IN("dtype", "bf16"),
|
||||
C_GE("M", 65), C_LE("M", 2147483647), C_GE("N", 128), C_DIV("K", 64), C_IN("dtype", "bf16"),
|
||||
};
|
||||
/* The dense integer kernels take their group from a build constant and read no `group` argument.
|
||||
* A declaration at another group gets no kernel rather than a silent 128. */
|
||||
@@ -5588,7 +5618,43 @@ static const RadConstraint cVsa[] = {
|
||||
/* A thread quantises eight columns: one 16-byte load and one 8-byte store a row. */
|
||||
static const RadConstraint cQuantCols[] = { C_DIV("n", 8), C_IN("dtype", "bf16") };
|
||||
|
||||
static const RadConstraint cPixtralPatch[] = { C_IN("dtype","bf16"), C_EQ("K",588), C_GE("M",1), C_LE("M",2147483647), C_GE("N",1), C_LE("N",2147483647) };
|
||||
static const RadConstraint cNemotron[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 2147483647) };
|
||||
static const RadConstraint cNemotronMerge[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 2147483647), C_EQ("merge",2) };
|
||||
static const RadConstraint cNemotronRope64[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 2147483647), C_EQ("head_dim",64) };
|
||||
static const RadConstraint cNemotronRope128[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 2147483647), C_EQ("head_dim",128) };
|
||||
static const RadConstraint cNemotronAttn64[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 2147483647), C_EQ("head_dim",64), C_EQ("causal",0) };
|
||||
static const RadConstraint cNemotronAttn128[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 2147483647), C_EQ("head_dim",128), C_EQ("causal",0) };
|
||||
static const RadKernelInfo kKernels[] = {
|
||||
{ "gemm_bf16_pixtral_patch", "gemm_nt", "gemm", "RGB 14x14 patch projection with ordered f32 dots",
|
||||
"K=588, M<=INT_MAX, N<=INT_MAX, pitched bf16 rows", "bf16",
|
||||
RAD_DOMAIN_DEVICE, 10, ROW(cPixtralPatch), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_pixtral_patch },
|
||||
{ "position_scale_bf16", "position_scale", "attn", "Ministral rounded query scale", "pitched active rows, nonnegative i32 positions", "bf16",
|
||||
RAD_DOMAIN_DEVICE, 50, ROW(cNemotron), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_position_scale, r4d_nemotron_scratch },
|
||||
{ "pixtral_merge_bf16", "pixtral_merge", "vision", "Channel-major complete raster-grid merger", "merge 2, pitched active rows", "bf16",
|
||||
RAD_DOMAIN_DEVICE, 50, ROW(cNemotronMerge), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_pixtral_merge, r4d_nemotron_scratch },
|
||||
{ "ministral_rope_h64_bf16", "ministral_rope", "attn", "Ministral rotary with separately rounded products", "head_dim 64, pitched active rows", "bf16",
|
||||
RAD_DOMAIN_DEVICE, 50, ROW(cNemotronRope64), NOTUNE,
|
||||
r4d_ministral_init, r4d_rotary_fini, r4d_rad_ministral_rope, r4d_nemotron_scratch },
|
||||
{ "ministral_rope_h128_bf16", "ministral_rope", "attn", "Ministral rotary with separately rounded products", "head_dim 128, pitched active rows", "bf16",
|
||||
RAD_DOMAIN_DEVICE, 50, ROW(cNemotronRope128), NOTUNE,
|
||||
r4d_ministral_init, r4d_rotary_fini, r4d_rad_ministral_rope, r4d_nemotron_scratch },
|
||||
{ "pixtral_rope_h64_bf16", "pixtral_rope", "attn", "Pixtral axial rotary with BF16 product seams", "head_dim 64, pitched active rows", "bf16",
|
||||
RAD_DOMAIN_DEVICE, 50, ROW(cNemotronRope64), NOTUNE,
|
||||
r4d_pixtral_init, r4d_rotary_fini, r4d_rad_pixtral_rope, r4d_nemotron_scratch },
|
||||
{ "pixtral_rope_h128_bf16", "pixtral_rope", "attn", "Pixtral axial rotary with BF16 product seams", "head_dim 128, pitched active rows", "bf16",
|
||||
RAD_DOMAIN_DEVICE, 50, ROW(cNemotronRope128), NOTUNE,
|
||||
r4d_pixtral_init, r4d_rotary_fini, r4d_rad_pixtral_rope, r4d_nemotron_scratch },
|
||||
{ "embed_attn_h64_bf16", "embed_attn", "attn", "Three-pass BF16 eager whole-segment attention", "head_dim 64, pitched active rows", "bf16",
|
||||
RAD_DOMAIN_DEVICE, 50, ROW(cNemotronAttn64), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_embed_attn, r4d_nemotron_scratch },
|
||||
{ "embed_attn_h128_bf16", "embed_attn", "attn", "Three-pass BF16 eager whole-segment attention", "head_dim 128, pitched active rows", "bf16",
|
||||
RAD_DOMAIN_DEVICE, 50, ROW(cNemotronAttn128), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_embed_attn, r4d_nemotron_scratch },
|
||||
|
||||
/* ---------------------------------- the small model ops (r4d_model_bf16.hip) ----------------
|
||||
*
|
||||
* The ops between the larger kernels. They need device rows because the engine's buffers live in
|
||||
@@ -7796,7 +7862,7 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
|
||||
|
||||
{ "gemm_bf16_nt_m64", "gemm_nt", "gemm",
|
||||
"skinny GEMM C[M,N] = A[M,K] @ W[N,K]^T with 16x16x16 WMMA, split-K reduced in LDS",
|
||||
"any M -- MT row tiles a block and grid.y covers the rest; K divisible by SK*16; N, K runtime",
|
||||
"signed-int M, bounded row launches; K divisible by SK*16; N*K <= UINT32_MAX elements",
|
||||
"bf16 A / W / C, fp32 accumulate, deterministic reduction",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY,
|
||||
ROW(cGemmNt64), ROW(tGemmSkinny), r4d_tune_valid_gemm,
|
||||
@@ -7806,7 +7872,7 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
|
||||
{ "gemm_bf16_nt_tiled", "gemm_nt", "gemm",
|
||||
"the same GEMM at prefill row counts: eight waves a block over an LDS-staged 64-deep K tile, "
|
||||
"the next tile prefetched in registers while the current one is computed",
|
||||
"M > 64; N >= 128; K a multiple of 64; fragment rows past M or N clamped, never stored",
|
||||
"64 < M <= INT_MAX; N >= 128; K%64; bounded row launches; N*K <= UINT32_MAX elements",
|
||||
"bf16 A / W / C, fp32 accumulate. BYTE-IDENTICAL to gemm_bf16_nt_m64: the same WMMA sequence "
|
||||
"a tile and the same split count, the slices summed in the same order from 0.f",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_BF16_TILED,
|
||||
@@ -10213,6 +10279,8 @@ extern "C" int rad_kernel_concurrent(int i) {
|
||||
"hc_", "mtp_enter", "ar_", "gemm_w4a8_tiled", "gemm_w8a8_tiled", "lora_",
|
||||
/* The residency map's epoch, hand, heat counters and counters live across launches. */
|
||||
"kv_resolve",
|
||||
// Each model-local entry validates metadata before its dependent data launch.
|
||||
"position_scale_", "ministral_rope_", "pixtral_rope_", "pixtral_merge_", "embed_attn_",
|
||||
};
|
||||
for (const char* p : kStateful)
|
||||
if (std::strncmp(k->name, p, std::strlen(p)) == 0) return 0;
|
||||
|
||||
@@ -807,6 +807,34 @@ static int rope_ladder(const RadArgs* a, int64_t rot, int64_t head_dim, int64_t*
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* Ministral 3's query multiplier, applied after rotary and rounded to the activation dtype
|
||||
* before the product. Only the supplied query slice is changed; keys and values stay intact. */
|
||||
int ref_position_scale(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *pos = &a->t[1];
|
||||
// M in the resolved geometry is a capacity band; issued views carry the active rows.
|
||||
const int64_t M = x->rank == 2 ? x->shape[0] : 0;
|
||||
const int64_t n = p_int(a, "n", 0), orig = p_int(a, "original", 0);
|
||||
const float beta = p_f32(a, "beta", -1);
|
||||
if (M <= 0 || M > p_int(a, "M", 0) || n <= 0 || orig <= 0 || !std::isfinite(beta) || beta < 0 ||
|
||||
x->rank != 2 || x->shape[0] < M || x->shape[1] != n || pos->rank != 1 || numel(pos) < M)
|
||||
return RAD_E_SHAPE;
|
||||
if (pos->dtype != RAD_I32 || (x->dtype != RAD_BF16 && x->dtype != RAD_F32)) return RAD_E_DTYPE;
|
||||
/* Validate all positions before writing: an invalid batch must not leave a partial result. */
|
||||
for (int64_t r = 0; r < M; ++r)
|
||||
if (ld_int(pos->dtype, pos->data, offlin(pos, r)) < 0) return RAD_E_INVAL;
|
||||
REF_PAR_FOR(M * n)
|
||||
for (int64_t r = 0; r < M; ++r) {
|
||||
const int64_t p = ld_int(pos->dtype, pos->data, offlin(pos, r));
|
||||
const float scale = round_dt(x->dtype, 1.0f + beta * std::log(1.0f + (float)(p / orig)));
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
const int64_t at = rowoff(x, r, n) + j * laststride(x);
|
||||
stt(x, at, ldt(x, at) * scale);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_rope(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *qkv = &a->t[0], *pos = &a->t[1];
|
||||
|
||||
@@ -159,6 +159,11 @@ int ref_kv_store (const RadArgs*, RadStream);
|
||||
/* the store of a streamed group: the host mirror always, the ring slot when the block is resident */
|
||||
int ref_kv_store_streamed (const RadArgs*, RadStream);
|
||||
int ref_rope (const RadArgs*, RadStream);
|
||||
int ref_position_scale (const RadArgs*, RadStream);
|
||||
int ref_embed_attn (const RadArgs*, RadStream);
|
||||
int ref_ministral_rope (const RadArgs*, RadStream);
|
||||
int ref_pixtral_rope (const RadArgs*, RadStream);
|
||||
int ref_pixtral_merge (const RadArgs*, RadStream);
|
||||
int ref_rope_table (const RadArgs*, RadStream);
|
||||
int ref_qk_norm_rope (const RadArgs*, RadStream);
|
||||
/* image generation (ref_gen.cpp) */
|
||||
@@ -423,6 +428,11 @@ REF_SHAPE_FN(ref_sam_attn);
|
||||
REF_SHAPE_FN(ref_kv_store);
|
||||
REF_SHAPE_FN(ref_kv_store_streamed);
|
||||
REF_SHAPE_FN(ref_rope);
|
||||
REF_SHAPE_FN(ref_position_scale);
|
||||
REF_SHAPE_FN(ref_embed_attn);
|
||||
REF_SHAPE_FN(ref_ministral_rope);
|
||||
REF_SHAPE_FN(ref_pixtral_rope);
|
||||
REF_SHAPE_FN(ref_pixtral_merge);
|
||||
REF_SHAPE_FN(ref_rope_table);
|
||||
REF_SHAPE_FN(ref_qk_norm_rope);
|
||||
REF_SHAPE_FN(ref_ln_mod);
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
/* Nemotron's text/vision rotary, patch merger and materialized BF16 attention.
|
||||
* Separate ops preserve existing rotary, attention and merger contracts. */
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
|
||||
#include "rad_yarn.h"
|
||||
|
||||
using namespace ref;
|
||||
|
||||
int ref_pixtral_rope(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *rc = &a->t[1];
|
||||
// The issue's row views can be smaller than the resolved M capacity band.
|
||||
const int64_t M = x->rank == 2 ? x->shape[0] : 0;
|
||||
const int64_t D = p_int(a, "head_dim", 0), H = p_int(a, "n_head", 0);
|
||||
const float theta = p_f32(a, "theta", 0);
|
||||
if (M <= 0 || M > p_int(a, "M", 0) || D <= 0 || D % 4 || H <= 0 || !(theta > 0) ||
|
||||
!std::isfinite(theta) || x->rank != 2 || x->shape[0] < M || x->shape[1] != 3 * H * D ||
|
||||
rc->rank != 2 || rc->shape[0] != 2 || rc->shape[1] != M)
|
||||
return RAD_E_SHAPE;
|
||||
if (rc->dtype != RAD_I32 || (x->dtype != RAD_BF16 && x->dtype != RAD_F32)) return RAD_E_DTYPE;
|
||||
for (int64_t r = 0; r < 2; ++r)
|
||||
for (int64_t p = 0; p < M; ++p)
|
||||
if (ld_int(rc->dtype, rc->data, r * rc->stride[0] + p * rc->stride[1]) < 0)
|
||||
return RAD_E_INVAL;
|
||||
REF_PAR_FOR(M * H * D)
|
||||
for (int64_t p = 0; p < M; ++p) {
|
||||
for (int64_t i = 0; i < D / 2; ++i) {
|
||||
const int64_t axis = i / (D / 4), j = i % (D / 4);
|
||||
const float pos =
|
||||
(float)ld_int(rc->dtype, rc->data, axis * rc->stride[0] + p * rc->stride[1]);
|
||||
const float inv = 1.0f / ref_pow(theta, (float)(4 * j + 2 * axis) / D);
|
||||
const float angle = pos * inv;
|
||||
const float c = round_dt(x->dtype, ref_cos(angle)),
|
||||
s = round_dt(x->dtype, ref_sin(angle));
|
||||
for (int64_t h = 0; h < 2 * H; ++h) {
|
||||
const int64_t u = rowoff(x, p, 3 * H * D) + (h * D + i) * laststride(x);
|
||||
const int64_t v = u + (D / 2) * laststride(x);
|
||||
const float a0 = ldt(x, u), b0 = ldt(x, v);
|
||||
/* Transformers narrows cos/sin and each product before adding BF16 tensors. */
|
||||
stt(x, u, round_dt(x->dtype, a0 * c) - round_dt(x->dtype, b0 * s));
|
||||
stt(x, v, round_dt(x->dtype, b0 * c) + round_dt(x->dtype, a0 * s));
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_pixtral_merge(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *rc = &a->t[1], *y = &a->t[2];
|
||||
const int64_t M = x->rank == 2 ? x->shape[0] : 0;
|
||||
const int64_t N = p_int(a, "n", 0), K = p_int(a, "merge", 0);
|
||||
if (M <= 0 || M > p_int(a, "M", 0) || N <= 0 || K <= 0 || K > M || M / K < K || M % (K * K) ||
|
||||
x->rank != 2 || x->shape[0] != M || x->shape[1] != N || rc->rank != 2 ||
|
||||
rc->shape[0] != 4 || rc->shape[1] != M || y->rank != 2 || y->shape[0] != M / (K * K) ||
|
||||
y->shape[1] != N * K * K)
|
||||
return RAD_E_SHAPE;
|
||||
if (rc->dtype != RAD_I32 || x->dtype != y->dtype ||
|
||||
(x->dtype != RAD_BF16 && x->dtype != RAD_F32))
|
||||
return RAD_E_DTYPE;
|
||||
const auto coord = [&](int axis, int64_t p) {
|
||||
return ld_int(rc->dtype, rc->data, axis * rc->stride[0] + p * rc->stride[1]);
|
||||
};
|
||||
/* Verify full raster grids before any write, including variable image widths. The grid at
|
||||
* each image's first patch defines its boundary; no image is merged with the next one. */
|
||||
for (int64_t p = 0; p < M;) {
|
||||
const int64_t h = coord(2, p), w = coord(3, p);
|
||||
if (h <= 0 || w <= 0 || h % K || w % K || h > (M - p) / w) return RAD_E_INVAL;
|
||||
for (int64_t j = 0; j < h * w; ++j)
|
||||
if (coord(0, p + j) != j / w || coord(1, p + j) != j % w || coord(2, p + j) != h ||
|
||||
coord(3, p + j) != w)
|
||||
return RAD_E_INVAL;
|
||||
p += h * w;
|
||||
}
|
||||
for (int64_t p = 0; p < M;) {
|
||||
const int64_t h = coord(2, p), w = coord(3, p);
|
||||
for (int64_t r = 0; r < h / K; ++r)
|
||||
for (int64_t c = 0; c < w / K; ++c) {
|
||||
const int64_t dst = p / (K * K) + r * (w / K) + c;
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t dy = 0; dy < K; ++dy)
|
||||
for (int64_t dx = 0; dx < K; ++dx) {
|
||||
const int64_t src = p + (r * K + dy) * w + c * K + dx;
|
||||
const int64_t col = (n * K + dy) * K + dx;
|
||||
stt(y, rowoff(y, dst, N * K * K) + col * laststride(y),
|
||||
ldt(x, rowoff(x, src, N) + n * laststride(x)));
|
||||
}
|
||||
}
|
||||
p += h * w;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_ministral_rope(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *pos = &a->t[1];
|
||||
const int64_t M = x->rank == 2 ? x->shape[0] : 0;
|
||||
const int64_t D = p_int(a, "head_dim", 0), H = p_int(a, "n_head", 0),
|
||||
K = p_int(a, "n_head_kv", 0);
|
||||
const float theta = p_f32(a, "theta", 0);
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (M <= 0 || M > p_int(a, "M", 0) || D <= 0 || D > 2048 || D % 2 || H <= 0 || H > 1024 ||
|
||||
K <= 0 || K > H || H % K || x->shape[1] != (H + 2 * K) * D || pos->rank != 1 ||
|
||||
numel(pos) != M || !(theta > 0) || !std::isfinite(theta) || !rad_yarn_valid(yarn))
|
||||
return RAD_E_SHAPE;
|
||||
if (pos->dtype != RAD_I32 || (x->dtype != RAD_BF16 && x->dtype != RAD_F32)) return RAD_E_DTYPE;
|
||||
for (int64_t p = 0; p < M; ++p)
|
||||
if (ld_int(pos->dtype, pos->data, offlin(pos, p)) < 0) return RAD_E_INVAL;
|
||||
float freq[1024];
|
||||
for (int64_t i = 0; i < D / 2; ++i)
|
||||
freq[i] = yarn.frequency(1.0f / std::pow(theta, (float)(2 * i) / (float)D), (int)i);
|
||||
REF_PAR_FOR(M * (H + K) * D)
|
||||
for (int64_t p = 0; p < M; ++p) {
|
||||
const float position = (float)(ld_int(pos->dtype, pos->data, offlin(pos, p)));
|
||||
for (int64_t i = 0; i < D / 2; ++i) {
|
||||
const float angle = position * freq[i];
|
||||
const float c = round_dt(x->dtype, std::cos(angle) * yarn.magnitude);
|
||||
const float s = round_dt(x->dtype, std::sin(angle) * yarn.magnitude);
|
||||
for (int64_t h = 0; h < H + K; ++h) {
|
||||
const int64_t u = rowoff(x, p, (H + 2 * K) * D) + (h * D + i) * laststride(x);
|
||||
const int64_t v = u + (D / 2) * laststride(x);
|
||||
const float a0 = ldt(x, u), b0 = ldt(x, v);
|
||||
stt(x, u, round_dt(x->dtype, a0 * c) - round_dt(x->dtype, b0 * s));
|
||||
stt(x, v, round_dt(x->dtype, b0 * c) + round_dt(x->dtype, a0 * s));
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The eager BF16 attention expression materializes QK, scaled logits and probabilities.
|
||||
* Keep it separate from attn_dense's existing fused arithmetic. Only whole, noncausal segments
|
||||
* are served. Stack storage is bounded by the model's 32768-token limit. */
|
||||
int ref_embed_attn(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3], *out = &a->t[4];
|
||||
const int64_t M = q->rank == 2 ? q->shape[0] : 0;
|
||||
const int64_t D = p_int(a, "head_dim", 0), G = p_int(a, "gqa", 1);
|
||||
if (M <= 0 || M > p_int(a, "M", 0) || D <= 0 || D > 2048 || G <= 0 || q->shape[1] <= 0 ||
|
||||
q->shape[1] % D || k->rank != 2 || v->rank != 2 || out->rank != 2 || cu->rank != 1 ||
|
||||
numel(cu) < 2 || k->shape[0] != M || v->shape[0] != M || out->shape[0] != M)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t H = q->shape[1] / D, S = numel(cu) - 1;
|
||||
if (H % G || k->shape[1] != H / G * D || v->shape[1] != H / G * D || out->shape[1] != H * D)
|
||||
return RAD_E_SHAPE;
|
||||
if (p_int(a, "causal", 0) != 0) return RAD_E_UNSUPPORTED;
|
||||
if ((q->dtype != RAD_BF16 && q->dtype != RAD_F32) || k->dtype != q->dtype ||
|
||||
v->dtype != q->dtype || out->dtype != q->dtype || cu->dtype != RAD_I32)
|
||||
return RAD_E_DTYPE;
|
||||
auto boundary = [&](int64_t s) { return ld_int(cu->dtype, cu->data, offlin(cu, s)); };
|
||||
if (boundary(0) != 0 || boundary(S) != M) return RAD_E_INVAL;
|
||||
for (int64_t s = 0; s < S; ++s)
|
||||
if (boundary(s) >= boundary(s + 1) || boundary(s + 1) - boundary(s) > 32768)
|
||||
return RAD_E_INVAL;
|
||||
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)D));
|
||||
if (!std::isfinite(scale) || !(scale > 0)) return RAD_E_INVAL;
|
||||
REF_PAR_FOR(M * H * D)
|
||||
for (int64_t sh = 0; sh < S * H; ++sh) {
|
||||
const int64_t s = sh / H, h = sh % H, kh = h / G;
|
||||
const int64_t begin = boundary(s), end = boundary(s + 1);
|
||||
float scores[32768], accum[2048];
|
||||
for (int64_t i = begin; i < end; ++i) {
|
||||
const int64_t qb = rowoff(q, i, H * D) + h * D * laststride(q);
|
||||
float maximum = -INFINITY;
|
||||
for (int64_t j = begin; j < end; ++j) {
|
||||
const int64_t kb = rowoff(k, j, H / G * D) + kh * D * laststride(k);
|
||||
float dot = 0;
|
||||
for (int64_t d = 0; d < D; ++d)
|
||||
dot += ldt(q, qb + d * laststride(q)) * ldt(k, kb + d * laststride(k));
|
||||
const float score = round_dt(q->dtype, round_dt(q->dtype, dot) * scale);
|
||||
scores[j - begin] = score;
|
||||
maximum = std::max(maximum, score);
|
||||
}
|
||||
float sum = 0;
|
||||
for (int64_t j = begin; j < end; ++j) {
|
||||
scores[j - begin] = std::exp(scores[j - begin] - maximum);
|
||||
sum += scores[j - begin];
|
||||
}
|
||||
std::fill_n(accum, D, 0.0f);
|
||||
for (int64_t j = begin; j < end; ++j) {
|
||||
const float probability = round_dt(q->dtype, scores[j - begin] / sum);
|
||||
const int64_t vb = rowoff(v, j, H / G * D) + kh * D * laststride(v);
|
||||
for (int64_t d = 0; d < D; ++d)
|
||||
accum[d] += probability * ldt(v, vb + d * laststride(v));
|
||||
}
|
||||
const int64_t ob = rowoff(out, i, H * D) + h * D * laststride(out);
|
||||
for (int64_t d = 0; d < D; ++d)
|
||||
stt(out, ob + d * laststride(out), accum[d]);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -435,6 +435,23 @@ static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_he
|
||||
P_F64O("llama3_orig") };
|
||||
static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") };
|
||||
|
||||
static const RadParamSpec pPositionScale[] = { P_INT("M"), P_INT("n"), P_INT("original"),
|
||||
P_F64("beta"), P_STR("dtype") };
|
||||
static const RadOperandSpec oPositionScale[] = { INOUT("x"), OPD("positions") };
|
||||
|
||||
static const RadParamSpec pEmbedAttn[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
|
||||
P_INT("causal"), P_INTO("max_seqlen"), P_STR("dtype"), P_F64O("scale") };
|
||||
static const RadOperandSpec oEmbedAttn[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), OUT("out") };
|
||||
static const RadParamSpec pMinistralRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_INT("n_head_kv"), P_F64("theta"), P_STR("dtype"), P_F64O("yarn_factor"),
|
||||
P_F64O("yarn_low"), P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
|
||||
static const RadOperandSpec oMinistralRope[] = { INOUT("qkv"), OPD("pos") };
|
||||
static const RadParamSpec pPixtralRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_F64("theta"), P_STR("dtype") };
|
||||
static const RadOperandSpec oPixtralRope[] = { INOUT("qkv"), OPD("coord") };
|
||||
static const RadParamSpec pPixtralMerge[] = { P_INT("M"), P_INT("n"), P_INT("merge"), P_STR("dtype") };
|
||||
static const RadOperandSpec oPixtralMerge[] = { OPD("x"), OPD("coord"), OUT("y") };
|
||||
|
||||
/* The cos/sin plane a fused prologue reads instead of theta, at each position's own row of a
|
||||
* [max_ctx, rot] table. `rot`, `theta` and `scale` are spelled as on `rope`, which must compute the
|
||||
* same angles. */
|
||||
@@ -1457,6 +1474,17 @@ static const RadOpSchema kSchemas[] = {
|
||||
"cos/sin for the positions a step names, at each position's own row of a [max_ctx, rot] plane: "
|
||||
"rot values a row, cos for the first half and sin for the second. The angles are `rope`'s "
|
||||
"exactly. A row no position names is not written; a negative position writes nothing." },
|
||||
{ "embed_attn", ARR(pEmbedAttn), ARR(oEmbedAttn),
|
||||
"Whole noncausal segments with QK, scaled scores and probabilities rounded to activation dtype." },
|
||||
{ "ministral_rope", ARR(pMinistralRope), ARR(oMinistralRope),
|
||||
"Ministral NeoX rotary with BF16 cos/sin and separately rounded products; V is unchanged." },
|
||||
{ "pixtral_rope", ARR(pPixtralRope), ARR(oPixtralRope),
|
||||
"Pixtral axial rotary with interleaved height/width frequencies and BF16 product rounding." },
|
||||
{ "pixtral_merge", ARR(pPixtralMerge), ARR(oPixtralMerge),
|
||||
"Pack full raster patch grids into channel-major spatial merge blocks, without mixing images." },
|
||||
{ "position_scale", ARR(pPositionScale), ARR(oPositionScale),
|
||||
"Scale query row p by 1 + beta * log(1 + floor(position[p] / original)), rounding the scale "
|
||||
"to x's dtype before multiplication. Positions are nonnegative i32." },
|
||||
{ "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey),
|
||||
"QSA's compressed key, one vector per `ratio` rows of k: the block's mean accumulated in f32 and "
|
||||
"rounded to k's dtype, RMS-normed with gain (wadd + w), then NeoX-rotated over `rotary_dim` at "
|
||||
@@ -2380,6 +2408,11 @@ ROW("ref_kv_store_streamed", "kv_store_streamed", "attn",
|
||||
"scatter k and v into the host mirror always and into the resident ring slot", DT_ANY,
|
||||
nullptr, 0, nullptr, nullptr, ref_kv_store_streamed, nullptr),
|
||||
SIMPLE("ref_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, ref_rope),
|
||||
SIMPLE("ref_embed_attn", "embed_attn", "attn", "BF16 materialized encoder attention", "bf16/f32, i32 cu", ref_embed_attn),
|
||||
SIMPLE("ref_ministral_rope", "ministral_rope", "attn", "Ministral BF16 rotary", "bf16/f32 inout, i32 positions", ref_ministral_rope),
|
||||
SIMPLE("ref_pixtral_rope", "pixtral_rope", "attn", "Pixtral interleaved axial rotary", "bf16/f32 inout, i32 coordinates", ref_pixtral_rope),
|
||||
SIMPLE("ref_pixtral_merge", "pixtral_merge", "vision", "channel-major patch merger packing", "bf16/f32, i32 coordinates", ref_pixtral_merge),
|
||||
SIMPLE("ref_position_scale", "position_scale", "attn", "Ministral position-dependent query scale", "bf16/f32 inout, i32 positions", ref_position_scale),
|
||||
SIMPLE("ref_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary embedding",
|
||||
DT_FLOAT, ref_qk_norm_rope),
|
||||
|
||||
|
||||
@@ -534,6 +534,52 @@ int ref_act_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
|
||||
return binary_shape(p, n_p, operand, "act_mul", out);
|
||||
}
|
||||
|
||||
int ref_position_scale_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(act_dt(p, n_p), {M, n});
|
||||
o.t_idx({M}, 32768, -1, 0);
|
||||
return o.finish("position_scale", operand, out);
|
||||
}
|
||||
|
||||
int ref_embed_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "head_dim", 0);
|
||||
const int64_t G = gi(p, n_p, "gqa", 1), S = n_seq_of(p, n_p);
|
||||
Opd o;
|
||||
o.t(act_dt(p, n_p), {M, G * D});
|
||||
o.t(act_dt(p, n_p), {M, D});
|
||||
o.t(act_dt(p, n_p), {M, D});
|
||||
o.t_idx({S + 1}, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU);
|
||||
o.t(act_dt(p, n_p), {M, G * D});
|
||||
return o.finish("embed_attn", operand, out);
|
||||
}
|
||||
|
||||
int ref_ministral_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "head_dim", 0);
|
||||
const int64_t H = gi(p, n_p, "n_head", 0), K = gi(p, n_p, "n_head_kv", 0);
|
||||
Opd o;
|
||||
o.t(act_dt(p, n_p), {M, (H + 2 * K) * D});
|
||||
o.t_idx({M}, 32768, -1, 0);
|
||||
return o.finish("ministral_rope", operand, out);
|
||||
}
|
||||
|
||||
int ref_pixtral_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "head_dim", 0),
|
||||
H = gi(p, n_p, "n_head", 0);
|
||||
if (M <= 0 || D <= 0 || D % 4 || H <= 0) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(act_dt(p, n_p), {M, 3 * H * D});
|
||||
o.t_idx({2, M}, 80, -1, 0);
|
||||
return o.finish("pixtral_rope", operand, out);
|
||||
}
|
||||
|
||||
int ref_pixtral_merge_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
/* The coordinates describe complete raster grids. Random independent indices cannot make
|
||||
* a legal fixture: callers provide the grid and its patch data together. */
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
int ref_seg_mean_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
|
||||
+53
-6
@@ -15,7 +15,7 @@
|
||||
# builder. With the archive linked, a new ABI call missing from the fake would pull in
|
||||
# rad_builder.cpp.o and collide on every rad_decl_* symbol; without it the error is a single
|
||||
# undefined reference.
|
||||
set(RAD_TESTS_NO_CORE arch_test glm5next_test)
|
||||
set(RAD_TESTS_NO_CORE arch_test glm5next_test nemotron35_test)
|
||||
|
||||
# fixture_test tests tools/kfixture.cpp and tools/opshapes.cpp (the seeded draw, the reduction and
|
||||
# the on-disk recording) directly, kbench_test tools/kbench_core.cpp (rad-kbench's rules), and
|
||||
@@ -165,6 +165,28 @@ foreach(t ${RAD_TESTS})
|
||||
get_filename_component(n ${t} NAME_WE)
|
||||
if(n IN_LIST RAD_TESTS_NO_CORE)
|
||||
add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/core/util/rad_util.cpp)
|
||||
if(n STREQUAL "nemotron35_test")
|
||||
target_sources(${n} PRIVATE ${CMAKE_SOURCE_DIR}/core/mm/processor.cpp
|
||||
${CMAKE_SOURCE_DIR}/core/mm/item.cpp
|
||||
${CMAKE_SOURCE_DIR}/core/mm/media.cpp
|
||||
${CMAKE_SOURCE_DIR}/core/server/nemotron35.cpp
|
||||
${CMAKE_SOURCE_DIR}/core/server/oai.cpp)
|
||||
# Exercise the actual request parser without pulling the unrelated core runtime into the
|
||||
# recording-builder test. Unused completion/response helpers are discarded at link time.
|
||||
target_compile_options(${n} PRIVATE -ffunction-sections -fdata-sections)
|
||||
target_link_options(${n} PRIVATE -Wl,--gc-sections)
|
||||
file(GLOB NEMOTRON_TEST_TOKENIZER CONFIGURE_DEPENDS
|
||||
${CMAKE_SOURCE_DIR}/core/text/tokenizer*.cpp ${CMAKE_SOURCE_DIR}/core/text/unicode_norm*.cpp)
|
||||
target_sources(${n} PRIVATE ${NEMOTRON_TEST_TOKENIZER})
|
||||
target_link_libraries(${n} PRIVATE rad_vendor_llama)
|
||||
target_link_libraries(${n} PRIVATE ${CMAKE_DL_LIBS})
|
||||
target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/vendor)
|
||||
add_dependencies(${n} libref)
|
||||
if(TARGET libavx)
|
||||
add_dependencies(${n} libavx)
|
||||
target_compile_definitions(${n} PRIVATE RAD_NEMOTRON_TEST_AVX=1)
|
||||
endif()
|
||||
endif()
|
||||
elseif(n IN_LIST RAD_TESTS_HARNESS)
|
||||
add_executable(${n} ${t})
|
||||
add_dependencies(${n} harness_fixture)
|
||||
@@ -296,7 +318,7 @@ endif()
|
||||
# the host backend; convert_test runs rad-convert on the same checkpoints. Both start the built
|
||||
# binaries as children, so they depend on them and on every plugin the checkpoints select
|
||||
# (llama_fp8 for convert_test's --set of an fp8 quantization_config).
|
||||
set(RAD_E2E_DEPS radiance rad-convert libref libquant qwen35_bf16 lfm2_bf16 gemma4 gemma4_bf16
|
||||
set(RAD_E2E_DEPS radiance rad-convert libref libquant nemotron35_embed qwen35_bf16 lfm2_bf16 gemma4 gemma4_bf16
|
||||
llama_dense_fp8 llama_fp8 qwenimage21)
|
||||
if(TARGET libavx)
|
||||
list(APPEND RAD_E2E_DEPS libavx)
|
||||
@@ -622,16 +644,18 @@ endif()
|
||||
# vocabulary and registration, and serve rad-kbench's fixture through the installed tools
|
||||
# (tests/oot_plugins.sh). libr4d is included when the tree built it, with the same HIP compiler,
|
||||
# targets and RAD_HIP_VOPD_REPEATABLE. Labelled `oot`: it rebuilds every plugin and takes minutes.
|
||||
set(RAD_OOT_HIP "")
|
||||
set(RAD_OOT_COMPILER "")
|
||||
set(RAD_OOT_TARGETS "")
|
||||
if(RAD_HIP_FOUND AND TARGET libr4d)
|
||||
get_target_property(RAD_OOT_R4D_ARCH libr4d HIP_ARCHITECTURES)
|
||||
string(REPLACE ";" "\\;" RAD_OOT_R4D_ARCH "${RAD_OOT_R4D_ARCH}")
|
||||
set(RAD_OOT_HIP ${CMAKE_HIP_COMPILER} "${RAD_OOT_R4D_ARCH}" ${RAD_HIP_VOPD_REPEATABLE})
|
||||
set(RAD_OOT_COMPILER "${CMAKE_HIP_COMPILER}")
|
||||
set(RAD_OOT_TARGETS "${RAD_OOT_R4D_ARCH}")
|
||||
endif()
|
||||
add_test(NAME oot_plugins
|
||||
COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/oot_plugins.sh
|
||||
${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR}/oot ${RAD_OOT_HIP}
|
||||
${CMAKE_CXX_COMPILER})
|
||||
${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR}/oot "${RAD_OOT_COMPILER}" "${RAD_OOT_TARGETS}"
|
||||
"${RAD_HIP_VOPD_REPEATABLE}" "${CMAKE_CXX_COMPILER}")
|
||||
# RESOURCE_LOCK kbench_memory: its replay holds operands in host memory as the kbench entries do.
|
||||
set_tests_properties(oot_plugins PROPERTIES
|
||||
LABELS "oot"
|
||||
@@ -735,3 +759,26 @@ foreach(cost IN ITEMS kbench_ref:500 r4d_selftest:350 r4d_emu_attn_sweep:80 kben
|
||||
set_tests_properties(${t} PROPERTIES COST ${c})
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
# Model-local device kernels are checked on the actual engine queue against libref.
|
||||
if(TARGET nemotron35_device_test)
|
||||
set_target_properties(nemotron35_device_test PROPERTIES ENABLE_EXPORTS ON)
|
||||
add_dependencies(nemotron35_device_test libref)
|
||||
if(TARGET libr4d)
|
||||
add_dependencies(nemotron35_device_test libr4d)
|
||||
add_test(NAME nemotron35_device_test_card COMMAND nemotron35_device_test)
|
||||
set_tests_properties(nemotron35_device_test_card PROPERTIES LABELS "gpu" RUN_SERIAL TRUE
|
||||
ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT};RAD_TEST_CPU_BUDGET=0" TIMEOUT 180)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Large BF16 GEMMs require real device memory; ordinary host entries skip them.
|
||||
if(TARGET r4d_bf16_capacity_test)
|
||||
set_target_properties(r4d_bf16_capacity_test PROPERTIES ENABLE_EXPORTS ON)
|
||||
if(TARGET libr4d)
|
||||
add_dependencies(r4d_bf16_capacity_test libr4d)
|
||||
add_test(NAME r4d_bf16_capacity_test_card COMMAND r4d_bf16_capacity_test)
|
||||
set_tests_properties(r4d_bf16_capacity_test_card PROPERTIES LABELS "gpu" RUN_SERIAL TRUE
|
||||
ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT};RAD_TEST_CPU_BUDGET=0" TIMEOUT 300)
|
||||
endif()
|
||||
endif()
|
||||
@@ -0,0 +1,19 @@
|
||||
OpenMDW License Agreement, version 1.1 (OpenMDW-1.1)
|
||||
|
||||
By exercising rights granted to you under this agreement, you accept and agree to its terms.
|
||||
|
||||
As used in this agreement, “Model Materials” means the materials provided to you under this agreement, consisting of: (1) one or more machine learning models (including architecture and parameters); and (2) all related artifacts (including associated data, documentation and software) that are provided to you hereunder.
|
||||
|
||||
Subject to your compliance with this agreement, permission is hereby granted, free of charge, to deal in the Model Materials without restriction, including under all copyright, patent, database, and trade secret rights included or embodied therein.
|
||||
|
||||
If you distribute any portion of the Model Materials, you shall retain in your distribution (1) a copy of this agreement, and (2) all copyright notices and other notices of origin included in the Model Materials that are applicable to your distribution.
|
||||
|
||||
If you file, maintain, or voluntarily participate in a lawsuit against any person or entity asserting that the Model Materials directly or indirectly infringe any patent or copyright, then all rights and grants made to you hereunder are terminated, unless that lawsuit was in response to a corresponding lawsuit first brought against you.
|
||||
|
||||
This agreement does not impose any restrictions or obligations with respect to any use, modification, or sharing of any outputs generated by using the Model Materials.
|
||||
|
||||
THE MODEL MATERIALS ARE PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, NONINFRINGEMENT, ACCURACY, OR THE ABSENCE OF LATENT OR OTHER DEFECTS OR ERRORS, WHETHER OR NOT DISCOVERABLE, ALL TO THE GREATEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW.
|
||||
|
||||
YOU ARE SOLELY RESPONSIBLE FOR (1) CLEARING RIGHTS OF OTHER PERSONS THAT MAY APPLY TO THE MODEL MATERIALS OR ANY USE THEREOF, INCLUDING WITHOUT LIMITATION ANY PERSON’S COPYRIGHTS OR OTHER RIGHTS INCLUDED OR EMBODIED IN THE MODEL MATERIALS; (2) OBTAINING ANY NECESSARY CONSENTS, PERMISSIONS OR OTHER RIGHTS REQUIRED FOR ANY USE OF THE MODEL MATERIALS; OR (3) PERFORMING ANY DUE DILIGENCE OR UNDERTAKING ANY OTHER INVESTIGATIONS INTO THE MODEL MATERIALS OR ANYTHING INCORPORATED OR EMBODIED THEREIN.
|
||||
|
||||
IN NO EVENT SHALL THE PROVIDERS OF THE MODEL MATERIALS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MODEL MATERIALS, THE USE THEREOF OR OTHER DEALINGS THEREIN.
|
||||
@@ -0,0 +1,25 @@
|
||||
# Nemotron 3.5 input fixtures
|
||||
|
||||
Source: [nvidia/Nemotron-3.5-Embed-8B-BF16](https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16/tree/781e779ee4ca9c2d2a4f38321993556baeab49a1),
|
||||
revision `781e779ee4ca9c2d2a4f38321993556baeab49a1`.
|
||||
|
||||
The source checkpoint's model card identifies OpenMDW-1.1 as its governing license. A copy is
|
||||
retained in [LICENSE](LICENSE) for the copied template and model-derived tokenizer fixture;
|
||||
these upstream assets are separate from the engine's Apache-2.0 code. See the pinned
|
||||
[model card](https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16/blob/781e779ee4ca9c2d2a4f38321993556baeab49a1/README.md).
|
||||
|
||||
`template.jinja` copies that checkpoint's retrieval template. `tokenizer-subset.json` is a test
|
||||
fixture retaining the original token IDs, all byte tokens and added tokens, the normalizer,
|
||||
pre-tokenizer and decoder, and the BPE candidates needed by the checked-in input cases. Serving
|
||||
requires the complete checkpoint tokenizer. The subset is tested against the full Hugging Face
|
||||
tokenizer before generation and exercised by Radiance's real tokenizer in CTest.
|
||||
|
||||
Regenerate the subset and `tests/data/golden/nemotron35_input.json` offline:
|
||||
|
||||
```sh
|
||||
python3 tests/mknemotron35inputgolden.py --tokenizer /path/to/checkpoint/tokenizer.json
|
||||
```
|
||||
|
||||
The generator needs Jinja2, Hugging Face tokenizers, and the checked-in vision fixture. The
|
||||
golden records the source template, full tokenizer, and subset SHA-256 hashes. It runs no model
|
||||
weights and is never called by CMake or CTest.
|
||||
@@ -0,0 +1,67 @@
|
||||
{# nemo-mistral-retrieval-v1
|
||||
Derived from the Mistral Ministral-3 instruct chat template render_content
|
||||
macro and its image-before-text canonicalization. Retrieval adaptation:
|
||||
system content is the retrieval prefix; generation wrappers and BOS/EOS are
|
||||
deliberately omitted so message inference matches training token for token.
|
||||
#}
|
||||
{%- macro mark_user_text(text) -%}
|
||||
{{- text | replace("[", "[") | replace("<", "<") -}}
|
||||
{%- endmacro -%}
|
||||
{%- macro render_text_content(content, context_name) -%}
|
||||
{%- if content is string -%}
|
||||
{{- content -}}
|
||||
{%- elif content is sequence -%}
|
||||
{%- set ns = namespace(has_output=false) -%}
|
||||
{%- for block in content -%}
|
||||
{%- if block["type"] == "text" -%}
|
||||
{%- if ns.has_output %}{{ "\n\n" }}{% endif -%}
|
||||
{{- block["text"] -}}
|
||||
{%- set ns.has_output = true -%}
|
||||
{%- else -%}
|
||||
{{- raise_exception(context_name + " may contain only text blocks") -}}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- else -%}
|
||||
{{- raise_exception(context_name + " must be a string or a list of text blocks") -}}
|
||||
{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
{%- macro render_user_content(content) -%}
|
||||
{%- if content is string -%}
|
||||
{{- mark_user_text(content) -}}
|
||||
{%- elif content is sequence -%}
|
||||
{%- set ns = namespace(has_output=false) -%}
|
||||
{%- for block in content -%}
|
||||
{%- if block["type"] in ["image", "image_url"] -%}
|
||||
{%- if ns.has_output %}{{ " " }}{% endif -%}
|
||||
{{- "[IMG]" -}}
|
||||
{%- set ns.has_output = true -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- for block in content -%}
|
||||
{%- if block["type"] == "text" -%}
|
||||
{%- if ns.has_output %}{{ " " }}{% endif -%}
|
||||
{{- mark_user_text(block["text"]) -}}
|
||||
{%- set ns.has_output = true -%}
|
||||
{%- elif block["type"] not in ["image", "image_url"] -%}
|
||||
{{- raise_exception("User content supports only text and image blocks") -}}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- else -%}
|
||||
{{- raise_exception("User content must be a string or a list of text and image blocks") -}}
|
||||
{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
{%- if not ((messages | length == 1 and messages[0]["role"] == "user")
|
||||
or (messages | length == 2
|
||||
and messages[0]["role"] == "system"
|
||||
and messages[1]["role"] == "user")) -%}
|
||||
{{- raise_exception("Retrieval inputs require one user message with an optional leading system prefix") -}}
|
||||
{%- endif -%}
|
||||
{# Iterate messages so vLLM can trace message.content into the rendering macros. #}
|
||||
{%- for message in messages -%}
|
||||
{%- if message["role"] == "system" -%}
|
||||
{%- set prefix = render_text_content(message["content"], "System content") -%}
|
||||
{{- prefix.rstrip(" ") ~ " " -}}
|
||||
{%- else -%}
|
||||
{{- render_user_content(message["content"]) -}}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":"1.0","truncation":null,"padding":null,"added_tokens":[{"id":0,"content":"<unk>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":1,"content":"<s>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":2,"content":"</s>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":3,"content":"[INST]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":4,"content":"[/INST]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":5,"content":"[AVAILABLE_TOOLS]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":6,"content":"[/AVAILABLE_TOOLS]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":7,"content":"[TOOL_RESULTS]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":8,"content":"[/TOOL_RESULTS]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":9,"content":"[TOOL_CALLS]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":10,"content":"[IMG]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":11,"content":"<pad>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":12,"content":"[IMG_BREAK]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":13,"content":"[IMG_END]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":14,"content":"[PREFIX]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":15,"content":"[MIDDLE]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":16,"content":"[SUFFIX]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":17,"content":"[SYSTEM_PROMPT]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":18,"content":"[/SYSTEM_PROMPT]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":19,"content":"[TOOL_CONTENT]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":20,"content":"<SPECIAL_20>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":21,"content":"<SPECIAL_21>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":22,"content":"<SPECIAL_22>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":23,"content":"<SPECIAL_23>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":24,"content":"[AUDIO]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":25,"content":"[BEGIN_AUDIO]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":26,"content":"<SPECIAL_26>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":27,"content":"<SPECIAL_27>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":28,"content":"<SPECIAL_28>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":29,"content":"<SPECIAL_29>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":30,"content":"<SPECIAL_30>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":31,"content":"<SPECIAL_31>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":32,"content":"[ARGS]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":33,"content":"[CALL_ID]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":34,"content":"<SPECIAL_34>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":35,"content":"<SPECIAL_35>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":36,"content":"<SPECIAL_36>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":37,"content":"<SPECIAL_37>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":38,"content":"<SPECIAL_38>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":39,"content":"<SPECIAL_39>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":40,"content":"<SPECIAL_40>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":41,"content":"<SPECIAL_41>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":trueLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
{"provenance":{"transformers":"5.20.0","torch":"2.14.1+cpu","seed":413,"attention":"eager","dtype":"bfloat16","rotary_dtype":"float32"},"weights":{"language_model.embed_tokens.weight":{"shape":[32,16],"bf16":[47996,15398,48191,48310,15541,48481,15412,48365,15039,15526,15419,15342,15614,48219,15232,15632,15609,15502,15282,48140,15536,47964,15568,48002,15195,48206,15426,48357,15594,48141,48350,15370,47946,48391,15392,48175,48367,15397,48301,48273,15602,48089,47986,48213,48288,15531,47621,48391,15182,48337,48145,48359,47155,48085,15279,48145,15301,15460,48268,47942,15211,48110,15436,15652,48315,14968,48170,15332,48277,15233,15563,48335,15471,48314,15015,15128,48317,48255,48377,48028,15340,14862,48245,15495,48261,15502,48331,14653,48377,15269,15364,48250,15680,48287,15395,15457,48427,48347,15268,48134,48150,48129,48036,15273,48411,15373,15635,15631,15480,48111,48284,15420,48256,48259,14772,15277,15483,48462,15714,15368,47922,48175,15514,48171,15356,47712,48279,15649,48364,15444,15530,15694,15496,15538,15428,48263,48326,15544,15367,15517,48180,48212,48243,48348,15477,48045,48340,48378,48447,48178,15123,15275,15508,47892,15504,48301,48147,48329,15482,48207,15477,15593,15581,48291,48346,15517,15733,48374,15308,48405,15621,48389,48331,48261,15599,15329,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48048,15411,48103,48326,15437,15505,15174,15155,15375,15270,15499,48194,47890,48311,48358,47813,48129,15423,48454,15273,15521,48450,15322,48107,14547,15614,15434,15497,48107,15362,15409,48399,15538,47945,48434,48008,15401,15169,48112,47825,48209,14990,48146,15665,15540,15368,15154,15507,48161,15094,15624,15222,15156,48347,15544,15268,48242,48468,48255,48088,48067,15193,48138,15504,48388,15068,14734,15615,48182,15568,48358,15048,48221,48347,15494,48301,48386,48224,15425,48319,15596,15487,47956,15650,48118,48312,15382,15314,15403,14976,15418,15409,15579,15646,48244,48188,48217,47955,48250,15636,15593,15546,15644,48007,15299,15453,15494,15621,48159,48390,48308,48283,48280,15369,47841,15292,15693,48428,47887,48393,47803,15197,48171,15629,15429,48137,15374,48139,48147,15598,48319,48295,15375,15037,48294,48145,48100,15234,15644,47776,48269,15437,48274,48038,15294,47647,15155,48153,15676,48307,48255,48431,48157,15305,15301,15367,48082,48164,47996,15494,15658,48394,15161,47988,15515,47848,48235,15411,48427,48341,48250,48362,48398,48161,15160,15433,15437,48209,15517,15428,48155,48223,47878,15393,15597,48011,15403,48297,47963,47753,48104,15361,15111,48327,15491,15103,15344,47987,15369,48174,15660,48255,15514,48177,48239,48169,15530,48283,48249,48252,15301,48285,48299,48309,15199,15599,48167,48304,47748,48002,15240,15313,15381,48142,15381,48253,47916,15558,48396,47691,15088,15218,48357,15600,47924,15396,48302,48316,48065,48391,15134,15393,48431,15281,15503,48294,47293,48108,15546,48049,15511,48279,48315,15234,48329,48262,48263,48374,48418,48072,48332,47798,15370,15665,47616,15552,48401,48150,15461,15500,15257,15287,15366,48187,15001,15140,15564,15422,15580,15523,48307,15386,15578,48276,15486,48459,48412,48408,15201,15505,15526,15248,15496,48149,48344,48235,48338,15182,47992,48117,48163,14752,15556,15377,48204,48348,48169,14923,15485,15386,48185,48284,15522,48217,15280,15703,48074,48455,15605,48285]},"language_model.layers.0.self_attn.q_proj.weight":{"shape":[512,16],"bf16":[48251,48384,15286,15361,48125,48353,15564,15507,48045,15671,48309,14490,48197,48041,15159,15489,48161,47787,15541,48446,48328,48289,48241,48028,15141,15592,15374,15292,15295,48215,48059,15642,15149,15439,47852,15643,15554,48236,48170,48101,48310,15384,15503,15056,48136,48398,48287,47567,47949,15594,15567,48051,48369,48256,15060,48057,15366,15628,15602,15522,48282,48259,48376,48156,15541,48409,47686,15441,48234,15241,48404,48339,48345,15014,15346,15376,48135,15247,47815,15514,48187,48170,48251,15554,48142,48228,15343,48270,48205,47865,48095,47902,15096,15523,48301,15519,48178,48392,15522,15504,47896,15589,48423,47529,48104,15296,15604,47932,15368,15289,48347,48122,48087,48396,47566,48337,48419,15473,15545,47924,48236,47982,48201,48272,48234,15336,48347,15255,15559,48038,15515,47693,15381,48289,47892,48032,48211,48022,15713,48282,14866,48114,15520,48296,15497,15270,48032,15602,15564,15545,15449,48055,15243,15489,48131,48362,48054,48168,15258,15504,15493,48340,15504,15414,15370,48008,48235,15504,47625,48245,15514,15504,15389,15554,15661,48264,15641,48117,47722,48076,15207,15677,47628,15269,15481,48149,15623,47878,15218,15580,15581,48321,48289,15172,47662,47922,48296,15241,15518,48398,15305,15702,48217,47944,15581,48274,15633,15060,15410,15524,15461,15581,15624,47942,48035,47887,48139,48286,48387,48290,15523,48372,48283,15450,48346,15403,15510,15124,15251,15448,15643,48422,48411,15557,15558,15187,15499,48305,15514,15468,48153,48268,48213,48454,15483,15585,15583,15616,15678,48415,15645,15588,48397,48252,15243,48337,15576,47966,48115,47602,48216,15352,15504,48152,15607,15427,15403,14824,15576,48323,47930,48239,15342,48381,15379,15524,15420,15650,15662,15495,48388,47848,48427,48072,Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
{"provenance":{"model_revision":"781e779ee4ca9c2d2a4f38321993556baeab49a1","jinja2":"3.1.6","tokenizers":"0.23.3","template_sha256":"7fb10981445a4370aa951758f066ddbd1846fe26da85110f940b1433440d6c55","tokenizer_sha256":"b78fc125e4896d169ab6683914ba1e9515eed36a65faffa2421d4cdb3061de02","subset_sha256":"3e2fcda0552461224b990166a45febda8f791416bc1fb49d13ac9f2db13d5d30"},"cases":[{"name":"none/plain","messages":[{"role":"user","content":"What is NVIDIA NeMo Framework?"}],"rendered":"What is NVIDIA NeMo Framework?","ids":[7493,1395,1464,10145,20501,4671,37042,41667,1063],"expanded_ids":[7493,1395,1464,10145,20501,4671,37042,41667,1063],"image_order":[],"segments":[{"text":"What is NVIDIA NeMo Framework?","ids":[7493,1395,1464,10145,20501,4671,37042,41667,1063]}],"legacy_text":"What is NVIDIA NeMo Framework?","legacy_ids":[7493,1395,1464,10145,20501,4671,37042,41667,1063]},{"name":"none/literal_controls","messages":[{"role":"user","content":"Treat [IMG], [IMG_BREAK], <s>, </s> and <__media__> literally."}],"rendered":"Treat [IMG], [IMG_BREAK], <s>, </s> and <__media__> literally.","ids":[1084,2565,1766,125250,3605,1766,125250,8037,3609,26039,3605,1534,1115,24482,2259,1115,1062,1321,1534,3308,18242,3308,1062,37846,1046],"expanded_ids":[1084,2565,1766,125250,3605,1766,125250,8037,3609,26039,3605,1534,1115,24482,2259,1115,1062,1321,1534,3308,18242,3308,1062,37846,1046],"image_order":[],"segments":[{"text":"Treat [IMG], [IMG_BREAK], <s>, </s> and <__media__> literally.","ids":[1084,2565,1766,125250,3605,1766,125250,8037,3609,26039,3605,1534,1115,24482,2259,1115,1062,1321,1534,3308,18242,3308,1062,37846,1046]}],"legacy_text":"Treat [IMG], [IMG_BREAK], <s>, </s> and <__media__> literally.","legacy_ids":[1084,2565,1032,10,1044,1032,12,1044,1032,1,1044,1032,2,1321,1534,3308,18242,3308,1062,37846,1046]},{"name":"none/unicode","messages":[{"role":"user","content":"¿Qué ves? Καλημέρα 世界 👁️\n"}],"rendered":"¿Qué ves? Καλημέρα 世界 👁️\n","ids":[15870,33935,22044,1063,34057,11718,13175,5825,1032,29659,119685,1145,1129,1239,1184,1143,1010],"expanded_ids":[15870,33935,22044,1063,34057,11718,13175,5825,1032,29659,119685,1145,1129,1239,1184,1143,1010],"image_order":[],"segments":[{"text":"¿Qué ves? Καλημέρα 世界 👁️\n","ids":[15870,33935,22044,1063,34057,11718,13175,5825,1032,29659,119685,1145,1129,1239,1184,1143,1010]}],"legacy_text":"¿Qué ves? Καλημέρα 世界 👁️\n","legacy_ids":[15870,33935,22044,1063,34057,11718,13175,5825,1032,29659,119685,1145,1129,1239,1184,1143,1010]},{"name":"none/parts","messages":[{"role":"user","content":[{"type":"text","text":"first"},{"type":"text","text":""},{"type":"text","text":"last"}]}],"rendered":"first last","ids":[11517,1032,3804],"expanded_ids":[11517,1032,3804],"image_order":[],"segments":[{"text":"first last","ids":[11517,1032,3804]}]},{"name":"none/image_only","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,AA=="}}]}],"rendered":"[IMG]","ids":[10],"expanded_ids":[10,13],"image_order":[0],"segments":[{"text":"","ids":[]},{"text":"","ids":[]}]},{"name":"none/text_before_images","messages":[{"role":"user","content":[{"type":"text","text":"A [page]"},{"type":"image_url","image_url":{"url":"data:image/png;base64,AQ=="}},{"type":"text","text":"<details>"},{"type":"image_url","image_url":{"url":"data:image/png;base64,Ag=="}}]}],"rendered":"[IMG] [IMG] A [page] <details>","ids":[10,1032,10,1349,1766,9813,1093,1534,42561,1062],"expanded_ids":[10,10,13,1032,10,10,10,12,10,10,10,13,1349,1766,9813,1093,1534,42561,1062],"image_order":[1,2],"segments":[{"text":"","ids":[]},{"text":" ","ids":[1032]},{"text":" A [page] <details>","ids":[1349,1766,9813,1093,1534,42561,1062]}]},{"name":"none/empty_blocks","messages":[{"role":"user","content":[{"type":"text","text":""},{"type":"image_url","image_url":{"url":"data:image/png;base64,Aw=="}},{"type":"text","text":""}]}],"rendered":"[IMG] ","ids":[10,1256],"expanded_ids":[10,12,10,13,1256],"image_order":[3],"segments":[{"text":"","ids":[]},{"text":" ","ids":[1256]}]},{"name":"query/plain","messages":[{"role":"system","content":"query: "},{"role":"user","content":"What is NVIDIA NeMo Framework?"}],"rendered":"query: What is NVIDIA NeMo Framework?","ids":[5272,1058,5675,1395,1464,10145,20501,4671,37042,41667,1063],"expanded_ids":[5272,1058,5675,1395,1464,10145,20501,4671,37042,41667,1063],"image_order":[],"segments":[{"text":"query: What is NVIDIA NeMo Framework?","ids":[5272,1058,5675,1395,1464,10145,20501,4671,37042,41667,1063]}]},{"name":"query/literal_controls","messages":[{"role":"system","content":"query: "},{"role":"user","content":"Treat [IMG], [IMG_BREAK], <s>, </s> and <__media__> literally."}],"rendered":"query: Treat [IMG], [IMG_BREAK], <s>, </s> and <__media__> literally.","ids":[5272,1058,35280,1766,125250,3605,1766,125250,8037,3609,26039,3605,1534,1115,24482,2259,1115,1Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
{"provenance":{"transformers":"5.20.0","torch":"2.14.1+cpu","attention":"eager","dtype":"bfloat16","rotary_dtype":"float32","weights":["nemotron35.json","nemotron35_vision.json"]},"cases":[{"name":"image_only","inputs":[{"tokens":[10,10,13],"placements":[{"image":1,"tok":0}]}],"pooled":[[-0.78125,-0.099609375,0.55859375,0.306640625,0.51953125,0.58203125,0.2470703125,-2.140625,1.5,-0.435546875,0.1474609375,0.412109375,-2.25,-0.3671875,0.431640625,-1.2578125]],"hidden":[[[-0.76171875,-0.15234375,0.9921875,0.2197265625,0.34375,1.1015625,0.2431640625,-2.09375,1.546875,-0.66015625,-0.026123046875,0.3515625,-2.28125,-0.44140625,0.392578125,-0.96875],[-0.69921875,-0.2392578125,0.98046875,0.3828125,0.390625,0.953125,0.18359375,-2.234375,1.5546875,-0.72265625,0.07568359375,0.25,-2.234375,-0.392578125,0.330078125,-0.84375],[-0.875,0.0927734375,-0.294921875,0.318359375,0.8203125,-0.302734375,0.314453125,-2.109375,1.390625,0.07666015625,0.392578125,0.6328125,-2.21875,-0.26953125,0.578125,-1.96875]]]},{"name":"image_text","inputs":[{"tokens":[3,4,10,10,10,12,10,10,10,13,5,7,8,6],"placements":[{"image":2,"tok":2}]}],"pooled":[[-0.11181640625,0.26171875,0.5859375,0.5078125,1.7890625,1.0546875,0.35546875,-0.79296875,0.94140625,1.1484375,0.349609375,1.109375,-1.3984375,-0.5703125,-0.89453125,1.375]],"hidden":[[[0.17578125,-0.43359375,0.453125,-0.28515625,1.6796875,0.859375,0.34765625,-0.9296875,1.1796875,1.3515625,-0.333984375,0.9375,-1.2734375,-0.61328125,-0.392578125,2.59375],[-0.53125,0.314453125,0.39453125,0.59765625,1.0859375,1.125,0.75390625,-1.296875,1.3046875,0.48046875,0.2041015625,1.015625,-2.03125,-0.77734375,-1.4375,0.9921875],[0.0791015625,0.455078125,0.78515625,0.427734375,1.8671875,1.3984375,0.314453125,-0.71484375,1.15625,1.1796875,0.099609375,1.1875,-1.6953125,-0.486328125,-0.8359375,1.3125],[0.109375,0.46875,0.75,0.439453125,1.796875,1.375,0.314453125,-0.76953125,1.21875,1.1953125,0.24609375,1.1328125,-1.7421875,-0.5078125,-0.8359375,1.296875],[0.11474609375,0.337890625,0.79296875,0.58203125,2.03125,1.1953125,0.29296875,-0.7421875,1.1328125,1.109375,0.1103515625,1.2265625,-1.6484375,-0.375,-0.82421875,1.4453125],[-0.061767578125,0.578125,0.45703125,-0.1796875,1.953125,1.5234375,0.2734375,-0.61328125,1.1953125,1.0859375,0.66796875,0.69140625,-1.40625,-0.9375,-1.3828125,1.09375],[0.048583984375,0.318359375,0.77734375,0.53515625,2.015625,1.265625,0.302734375,-0.7578125,1.1171875,1.171875,0.1708984375,1.1875,-1.6875,-0.41796875,-0.76171875,1.421875],[0.1953125,0.279296875,0.703125,0.578125,1.96875,1.21875,0.27734375,-0.84375,1.140625,1.1640625,0.2275390625,1.171875,-1.6484375,-0.416015625,-0.87109375,1.4453125],[0.10546875,0.384765625,0.8046875,0.53515625,1.859375,1.2890625,0.2392578125,-0.8359375,1.21875,1.15625,0.177734375,1.1015625,-1.609375,-0.498046875,-0.94921875,1.4453125],[-0.1513671875,0.6015625,-0.61328125,0.5703125,2.15625,-0.296875,0.376953125,-0.84375,0.97265625,1.703125,0.53515625,1.3828125,-1.5625,-0.220703125,-0.44921875,0.01153564453125],[0.359375,0.39453125,0.3359375,1.1015625,1.4609375,1.9375,-0.427734375,-0.85546875,0.296875,1.3828125,0.54296875,0.79296875,0.033447265625,-1.1328125,-0.5703125,2.046875],[-0.330078125,-0.1416015625,0.6796875,0.55859375,1.984375,-0.369140625,1.40625,-0.4453125,0.87109375,0.7421875,0.69921875,0.69140625,-1.0703125,-0.41015625,-1.1328125,2.40625],[-0.59375,0.52734375,1.03125,1.421875,1.734375,1.375,0.400390625,-0.8984375,0.32421875,1.2421875,0.341796875,1.2109375,-1.3984375,-0.60546875,-0.90234375,0.21484375],[-1.078125,-0.41015625,0.8359375,0.220703125,1.375,0.84765625,0.08154296875,-0.546875,0.048828125,1.2109375,1.21875,1.8359375,-0.9375,-0.5859375,-1.1796875,1.5703125]]]},{"name":"two_images","inputs":[{"tokens":[3,10,10,13,5,10,12,10,13,5,7,9],"placements":[{"image":1,"tok":1},{"image":3,"tok":5}]}],"pooled":[[-0.59765625,1.3359375,0.423828125,0.53125,0.057861328125,-0.1748046875,0.84765625,-1.125,0.033203125,1.0390625,0.341796875,0.040771484375,-1.46875,-0.95703125,0.16015625,1.8984375]],"hidden":[[[-0.42578125,0.3359375,0.5390625,-0.375,0.1484375,-0.171875,0.8828125,-1.3046875,0.31640625,1.1875,-0.5625,0.0625,-1.4453125,-0.91015625,0.4921875,3.359375],[-0.7265625,1.65625,1.0625,0.6953125,0.1796875,0.2216796875,1.0234375,-1.1640625,0.1787109375,0.96875,-0.0380859375,0.306640625,-2.046875,-0.80078125,0.142578125,2.0625],[-0.62890625,1.515625,1.0546875,0.9765625,0.255859375,-0.023681640625,0.92578125,-1.3984375,0.1962890625,0.8671875,0.1123046875,0.1396484375,-1.9453125,-0.734375,0.056640625,2.25],[-0.80859375,1.53125,-0.80859375,0.66796875,0.76171875,-1.5234375,0.890625,-1.1484375,0.1142578125,1.5859375,0.52734375,0.64453125,-1.765625,-0.40625,0.390625,0.1455078125],[-0.33203125,1.4375,0.341796875,1.265625,-0.55859375,0.8203125,0.0250244140625,-1.1640625,-0.9453125,1.0859375,0.466796875,-0.33984375,0.1943359375,-1.484375,0.443359375,2.53125],[-0.78515625,1.625,1.0703125,0.69921875,0.08056640625,0.201171875,0.984375,-1.234375,0.072265625,0.91015625,0.166015Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
{"provenance":{"transformers":"5.20.0","torch":"2.14.1+cpu","torchvision":"0.29.1+cpu","pillow":"13.0.0","seed":8275,"processor":"PixtralImageProcessorPil","attention":"eager","dtype":"bfloat16","rotary_dtype":"float32"},"images":[{"f":0,"h":1,"w":1,"size":[28,28],"fnv":"d1a67e73b84cde45","expand":[10,13],"patches":[48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,16286,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,15990,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,48924,4Line truncated
|
||||
@@ -2341,4 +2341,525 @@ TEST(an_unconverted_qwen_image_pipeline_serves_the_containers_picture) {
|
||||
CHECK(direct.png == conv.png);
|
||||
}
|
||||
|
||||
namespace {
|
||||
json nemotron_fixture(const char* name) {
|
||||
return json::parse(tiny::read_text(std::string(RAD_GOLDEN_FIXTURES) + "/" + name));
|
||||
}
|
||||
|
||||
/* The same BF16 parameters as the component oracle, now read by the real checkpoint loader.
|
||||
* Extra vocabulary rows only make the byte tokenizer usable for HTTP input; the oracle cases
|
||||
* use the original 32 rows. No test executor or media adapter participates in these tests. */
|
||||
bool write_nemotron(const std::string& dir) {
|
||||
json weights = nemotron_fixture("nemotron35.json")["weights"];
|
||||
weights.update(nemotron_fixture("nemotron35_vision.json")["weights"]);
|
||||
std::vector<tiny::Tensor> ts;
|
||||
for (auto it = weights.begin(); it != weights.end(); ++it) {
|
||||
auto shape = it.value()["shape"].get<std::vector<int64_t>>();
|
||||
auto bits = it.value()["bf16"].get<std::vector<uint16_t>>();
|
||||
if (it.key() == "language_model.embed_tokens.weight") {
|
||||
shape[0] = 320;
|
||||
const auto original = bits;
|
||||
for (int row = 32; row < 320; ++row)
|
||||
bits.insert(bits.end(), original.begin() + row % 32 * 16,
|
||||
original.begin() + (row % 32 + 1) * 16);
|
||||
}
|
||||
tiny::Tensor t{it.key(), "BF16", shape, {}};
|
||||
t.bytes.resize(bits.size() * 2);
|
||||
std::memcpy(t.bytes.data(), bits.data(), t.bytes.size());
|
||||
ts.push_back(std::move(t));
|
||||
}
|
||||
json rope = {{"rope_type", "yarn"},
|
||||
{"rope_theta", 1e6},
|
||||
{"factor", 16.0},
|
||||
{"original_max_position_embeddings", 16384},
|
||||
{"beta_fast", 32.0},
|
||||
{"beta_slow", 1.0},
|
||||
{"mscale", 1.0},
|
||||
{"mscale_all_dim", 1.0},
|
||||
{"llama_4_scaling_beta", 0.1}};
|
||||
json tc = {{"model_type", "ministral3"},
|
||||
{"hidden_size", 16},
|
||||
{"intermediate_size", 32},
|
||||
{"num_hidden_layers", 2},
|
||||
{"num_attention_heads", 4},
|
||||
{"num_key_value_heads", 1},
|
||||
{"head_dim", 128},
|
||||
{"vocab_size", 320},
|
||||
{"max_position_embeddings", 262144},
|
||||
{"rms_norm_eps", 1e-5},
|
||||
{"hidden_act", "silu"},
|
||||
{"is_causal", false},
|
||||
{"use_cache", false},
|
||||
{"sliding_window", nullptr},
|
||||
{"rope_parameters", rope},
|
||||
{"bos_token_id", 1},
|
||||
{"eos_token_id", 2},
|
||||
{"pad_token_id", 11}};
|
||||
json vc = {{"model_type", "pixtral"},
|
||||
{"hidden_size", 64},
|
||||
{"intermediate_size", 96},
|
||||
{"num_hidden_layers", 2},
|
||||
{"num_attention_heads", 1},
|
||||
{"head_dim", 64},
|
||||
{"patch_size", 14},
|
||||
{"image_size", 1540},
|
||||
{"num_channels", 3},
|
||||
{"hidden_act", "silu"},
|
||||
{"rope_parameters", {{"rope_type", "default"}, {"rope_theta", 10000.0}}}};
|
||||
json config = {{"architectures", {"Mistral3Model"}},
|
||||
{"model_type", "mistral3"},
|
||||
{"is_causal", false},
|
||||
{"text_config", tc},
|
||||
{"vision_config", vc},
|
||||
{"image_token_index", 10},
|
||||
{"spatial_merge_size", 2},
|
||||
{"multimodal_projector_bias", false},
|
||||
{"projector_hidden_act", "gelu"},
|
||||
{"vision_feature_layer", -1}};
|
||||
json tok = json::parse(tiny::tokenizer_json());
|
||||
json vocab = json::object();
|
||||
for (int c = 0; c < 256; ++c)
|
||||
vocab[tiny::byte_symbol(c)] = 32 + c;
|
||||
vocab[tiny::byte_symbol(' ')] = 5;
|
||||
const int letter_ids[] = {3, 4, 7, 8, 9, 6};
|
||||
for (int i = 0; i < 6; ++i)
|
||||
vocab[std::string(1, 'A' + i)] = letter_ids[i];
|
||||
tok["added_tokens"] = json::array();
|
||||
for (const auto& [s, id] : std::vector<std::pair<std::string, int>>{{"<s>", 1},
|
||||
{"</s>", 2},
|
||||
{"<pad>", 11},
|
||||
{"[IMG]", 10},
|
||||
{"[IMG_BREAK]", 12},
|
||||
{"[IMG_END]", 13}}) {
|
||||
vocab[s] = id;
|
||||
tok["added_tokens"].push_back({{"id", id},
|
||||
{"content", s},
|
||||
{"special", true},
|
||||
{"single_word", false},
|
||||
{"lstrip", false},
|
||||
{"rstrip", false},
|
||||
{"normalized", false}});
|
||||
}
|
||||
tok["model"]["vocab"] = std::move(vocab);
|
||||
return tiny::write_text(dir + "/config.json", config.dump()) &&
|
||||
tiny::write_safetensors(dir + "/model.safetensors", ts) &&
|
||||
tiny::write_text(dir + "/tokenizer.json", tok.dump()) &&
|
||||
tiny::write_text(dir + "/config_sentence_transformers.json",
|
||||
R"({"prompts":{"query":"AB","document":"CE"}})");
|
||||
}
|
||||
|
||||
// Opt-in hardware checks reuse the same endpoint fixtures and gates. The default suite stays
|
||||
// on CPU; no unrelated test sees this switch.
|
||||
bool nemotron_device() {
|
||||
const char* e = std::getenv("RAD_NEMOTRON_DEVICE");
|
||||
return e && *e && *e != '0';
|
||||
}
|
||||
std::vector<const char*> nemotron_kernels() {
|
||||
return nemotron_device() ? std::vector<const char*>{"libr4d,libavx"}
|
||||
: std::vector<const char*>{"libref", "libavx"};
|
||||
}
|
||||
std::string nemotron_device_env() {
|
||||
const char* index = std::getenv("RAD_NEMOTRON_DEVICE_INDEX");
|
||||
return std::string("ROCR_VISIBLE_DEVICES=") + (index && *index ? index : "0");
|
||||
}
|
||||
std::vector<std::string> nemotron_env() {
|
||||
return nemotron_device() ? std::vector<std::string>{nemotron_device_env()}
|
||||
: std::vector<std::string>{};
|
||||
}
|
||||
|
||||
const std::vector<std::string> nemotron_args = {
|
||||
"--max-num-seqs", "4", "--max-num-batched-tokens", "64",
|
||||
"--max-model-len", "64", "--mm-max-patches", "64"};
|
||||
|
||||
std::vector<float> embedding_reply(int port, const json& body, int row = 0) {
|
||||
int status = 0;
|
||||
const auto reply = post(port, "/v1/embeddings", body, &status);
|
||||
if (status != 200) fprintf(stderr, " embedding HTTP %d: %s\n", status, reply.dump().c_str());
|
||||
CHECK_EQ(status, 200);
|
||||
if (status != 200 || !reply.contains("data") || row >= (int)reply["data"].size()) return {};
|
||||
return reply["data"][row]["embedding"].get<std::vector<float>>();
|
||||
}
|
||||
|
||||
void check_embedding(const std::vector<float>& got, std::vector<float> want, int dims = 16,
|
||||
double max_l2 = 0.01) {
|
||||
REQUIRE_EQ(got.size(), (size_t)dims);
|
||||
want.resize((size_t)dims);
|
||||
double n = 0, dot = 0, err = 0, gn = 0;
|
||||
for (float v : want)
|
||||
n += (double)v * v;
|
||||
for (int i = 0; i < dims; ++i) {
|
||||
want[(size_t)i] /= (float)std::sqrt(n);
|
||||
dot += (double)got[(size_t)i] * want[(size_t)i];
|
||||
const double d = got[(size_t)i] - want[(size_t)i];
|
||||
err += d * d;
|
||||
gn += (double)got[(size_t)i] * got[(size_t)i];
|
||||
}
|
||||
CHECK(std::abs(gn - 1) < 1e-5);
|
||||
if (dot / std::sqrt(gn) < 0.9995 || std::sqrt(err) > max_l2)
|
||||
fprintf(stderr, " embedding cosine %.9g, normalized L2 error %.9g\n",
|
||||
dot / std::sqrt(gn), std::sqrt(err));
|
||||
CHECK(dot / std::sqrt(gn) >= 0.9995);
|
||||
CHECK(std::sqrt(err) <= max_l2);
|
||||
}
|
||||
|
||||
json nemotron_image(const json& spec) {
|
||||
const int f = spec["f"], h = spec["h"], w = spec["w"];
|
||||
std::vector<uint8_t> rgb((size_t)h * w * 3);
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x)
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
uint64_t z = (uint64_t)f * 0x9E3779B97F4A7C15ull +
|
||||
(uint64_t)y * 0xBF58476D1CE4E5B9ull +
|
||||
(uint64_t)x * 0x94D049BB133111EBull +
|
||||
(uint64_t)c * 0x2545F4914F6CDD1Dull + 12345ull;
|
||||
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
|
||||
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
|
||||
rgb[((size_t)y * w + x) * 3 + c] = (uint8_t)((z ^ (z >> 31)) & 255);
|
||||
}
|
||||
std::vector<uint8_t> png;
|
||||
std::string why;
|
||||
if (rad::mm::encode_image(rgb.data(), w, h, 3, "png", 0, &png, &why) < 0) return nullptr;
|
||||
return {
|
||||
{"type", "image_url"},
|
||||
{"image_url",
|
||||
{{"url", "data:image/png;base64," + rad::server::base64_encode(png.data(), png.size())}}}};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST(nemotron35_endpoint_refuses_custom_template_overrides) {
|
||||
tiny::TempDir d("e2e_nemotron_template");
|
||||
REQUIRE(d.ok());
|
||||
REQUIRE(write_nemotron(d.path));
|
||||
const std::string path = d.path + "/override.jinja";
|
||||
REQUIRE(tiny::write_text(path, "{{ messages[0]['content'] }}"));
|
||||
for (const char* kernels : nemotron_kernels()) {
|
||||
#if !defined(__x86_64__)
|
||||
if (std::string(kernels) == "libavx") continue;
|
||||
#endif
|
||||
Server s;
|
||||
s.quiet = true;
|
||||
auto args = nemotron_args;
|
||||
args.insert(args.end(), {"--kernels", kernels, "--override-chat-template", path});
|
||||
CHECK(!s.start(d.path, args, nemotron_env()));
|
||||
CHECK(s.output().find("--override-chat-template is not supported for this model") !=
|
||||
std::string::npos);
|
||||
CHECK(s.stop() != 0);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(nemotron35_endpoint_loads_the_oracle_weights_and_pools_ragged_inputs) {
|
||||
tiny::TempDir d("e2e_nemotron");
|
||||
REQUIRE(d.ok());
|
||||
REQUIRE(write_nemotron(d.path));
|
||||
const auto fixture = nemotron_fixture("nemotron35.json");
|
||||
for (const char* kernels : nemotron_kernels()) {
|
||||
#if !defined(__x86_64__)
|
||||
if (std::string(kernels) == "libavx") continue;
|
||||
#endif
|
||||
Server s;
|
||||
auto args = nemotron_args;
|
||||
args.insert(args.end(), {"--kernels", kernels});
|
||||
if (!s.start(d.path, args, nemotron_env())) {
|
||||
fprintf(stderr, " complete Nemotron startup log:\n%s\n", s.output().c_str());
|
||||
REQUIRE(false);
|
||||
}
|
||||
for (const auto& c : fixture["cases"]) {
|
||||
if (c["name"] == "q_scale_boundary")
|
||||
continue; // HTTP starts each input at position zero
|
||||
const json req = {{"input", c["inputs"]}};
|
||||
for (int row = 0; row < (int)c["inputs"].size(); ++row)
|
||||
check_embedding(embedding_reply(s.port, req, row), c["pooled"][row]);
|
||||
}
|
||||
const auto raw = embedding_reply(s.port, {{"input", {3, 4, 5, 7}}});
|
||||
check_embedding(embedding_reply(s.port, {{"input", "C"}, {"prompt_name", "query"}}), raw);
|
||||
const json messages = {{{"role", "system"}, {"content", "AB "}},
|
||||
{{"role", "user"}, {"content", "C"}}};
|
||||
check_embedding(embedding_reply(s.port, {{"messages", messages}}), raw);
|
||||
check_embedding(embedding_reply(s.port, {{"input", {3, 4, 5, 7}}, {"dimensions", 8}}), raw,
|
||||
8);
|
||||
int status = 0;
|
||||
// Whole-input encoders need no generation slot after the last encoded token.
|
||||
const auto boundary =
|
||||
post(s.port, "/v1/embeddings", {{"input", std::vector<int>(64, 3)}}, &status);
|
||||
REQUIRE_EQ(status, 200);
|
||||
const auto values = boundary["data"][0]["embedding"].get<std::vector<float>>();
|
||||
CHECK_EQ(values.size(), (size_t)16);
|
||||
double norm = 0;
|
||||
for (float v : values) {
|
||||
CHECK(std::isfinite(v));
|
||||
norm += (double)v * v;
|
||||
}
|
||||
CHECK_NEAR(norm, 1.0, 1e-5);
|
||||
post(s.port, "/v1/embeddings", {{"input", std::vector<int>(65, 3)}}, &status);
|
||||
CHECK_EQ(status, 400);
|
||||
post(s.port, "/v1/chat/completions", {{"messages", {{{"role", "user"}, {"content", "A"}}}}},
|
||||
&status);
|
||||
CHECK_EQ(status, 501);
|
||||
REQUIRE_EQ(s.stop(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Small model dimensions isolate configured engine capacity from the available model-weight VRAM.
|
||||
TEST(nemotron35_configured_combined_capacity_exceeds_old_gemm_ceiling) {
|
||||
if (!nemotron_device()) SKIP("explicit RAD_NEMOTRON_DEVICE capacity validation only");
|
||||
tiny::TempDir d("e2e_nemotron_capacity");
|
||||
REQUIRE(d.ok());
|
||||
REQUIRE(write_nemotron(d.path));
|
||||
Server s;
|
||||
const std::vector<std::string> args = {"--kernels",
|
||||
"libr4d,libavx",
|
||||
"--max-num-seqs",
|
||||
"512",
|
||||
"--max-num-batched-tokens",
|
||||
"131073",
|
||||
"--max-model-len",
|
||||
"257",
|
||||
"--mm-max-patches",
|
||||
"64"};
|
||||
if (!s.start(d.path, args, nemotron_env())) {
|
||||
fprintf(stderr, " capacity startup log:\n%s\n", s.output().c_str());
|
||||
REQUIRE(false);
|
||||
}
|
||||
std::vector<int> a(256), b(257);
|
||||
for (size_t i = 0; i < a.size(); ++i)
|
||||
a[i] = 3 + i % 6;
|
||||
for (size_t i = 0; i < b.size(); ++i)
|
||||
b[i] = 8 - i % 6;
|
||||
const auto alone_a = embedding_reply(s.port, {{"input", a}});
|
||||
const auto alone_b = embedding_reply(s.port, {{"input", b}});
|
||||
json inputs = json::array();
|
||||
for (int i = 0; i < 511; ++i)
|
||||
inputs.push_back(a);
|
||||
inputs.push_back(b);
|
||||
auto stats = [&]() {
|
||||
Call c;
|
||||
std::string body;
|
||||
if (!c.send(s.port, "GET", "/stats", "") || c.read(&body) != 200) return json();
|
||||
return json::parse(body);
|
||||
};
|
||||
const auto before = stats();
|
||||
int status = 0;
|
||||
const auto reply = post(s.port, "/v1/embeddings", {{"input", inputs}}, &status);
|
||||
REQUIRE_EQ(status, 200);
|
||||
REQUIRE_EQ(reply["data"].size(), (size_t)512);
|
||||
const auto after = stats();
|
||||
CHECK_EQ(after["steps"].get<int64_t>() - before["steps"].get<int64_t>(), 1);
|
||||
CHECK_EQ(reply["usage"]["prompt_tokens"].get<int64_t>(), 131073);
|
||||
double worst = 0;
|
||||
for (int r = 0; r < 512; ++r) {
|
||||
const auto got = reply["data"][r]["embedding"].get<std::vector<float>>();
|
||||
const auto& expected = r == 511 ? alone_b : alone_a;
|
||||
REQUIRE_EQ(got.size(), expected.size());
|
||||
double err = 0;
|
||||
for (size_t j = 0; j < got.size(); ++j)
|
||||
err += std::pow((double)got[j] - expected[j], 2);
|
||||
worst = std::max(worst, std::sqrt(err));
|
||||
}
|
||||
fprintf(
|
||||
stderr,
|
||||
" 131073 combined tokens / 512 sequences / one completed step; worst individual L2 %.9g\n",
|
||||
worst);
|
||||
CHECK(worst <= 1e-5);
|
||||
post(s.port, "/v1/embeddings", {{"input", std::vector<int>(258, 3)}}, &status);
|
||||
CHECK_EQ(status, 400);
|
||||
if (const char* path = std::getenv("RAD_NEMOTRON_CAPACITY_SERVER_LOG"))
|
||||
tiny::write_text(path, s.output());
|
||||
REQUIRE_EQ(s.stop(), 0);
|
||||
}
|
||||
|
||||
TEST(nemotron35_endpoint_decodes_images_and_matches_the_multimodal_oracle) {
|
||||
if (!rad::mm::decoder_available()) SKIP("this build has no image codec");
|
||||
tiny::TempDir d("e2e_nemotron_mm");
|
||||
REQUIRE(d.ok());
|
||||
REQUIRE(write_nemotron(d.path));
|
||||
const auto vision = nemotron_fixture("nemotron35_vision.json");
|
||||
const auto mm = nemotron_fixture("nemotron35_multimodal.json");
|
||||
const json im1 = nemotron_image(vision["images"][1]);
|
||||
REQUIRE(im1.is_object());
|
||||
const json im2 = nemotron_image(vision["images"][2]);
|
||||
REQUIRE(im2.is_object());
|
||||
const json im3 = nemotron_image(vision["images"][3]);
|
||||
REQUIRE(im3.is_object());
|
||||
for (const char* kernels : nemotron_kernels()) {
|
||||
#if !defined(__x86_64__)
|
||||
if (std::string(kernels) == "libavx") continue;
|
||||
#endif
|
||||
Server s;
|
||||
auto args = nemotron_args;
|
||||
args.insert(args.end(), {"--kernels", kernels});
|
||||
if (!s.start(d.path, args, nemotron_env())) {
|
||||
fprintf(stderr, " complete Nemotron startup log:\n%s\n", s.output().c_str());
|
||||
REQUIRE(false);
|
||||
}
|
||||
const json only = {{"input", json::array({im1})}};
|
||||
// Text originally before its image must reach the reference's image-before-text order.
|
||||
const json combined = {{"input", json::array({{{"type", "text"}, {"text", "CDF"}}, im2})}};
|
||||
const json messages = {
|
||||
{{"role", "system"}, {"content", "AB"}},
|
||||
{{"role", "user"},
|
||||
{"content", json::array({{{"type", "text"}, {"text", "CE"}}, im1, im3})}}};
|
||||
for (const auto& c : mm["cases"]) {
|
||||
json req;
|
||||
if (c["name"] == "image_only")
|
||||
req = only;
|
||||
else if (c["name"] == "http_image_text")
|
||||
req = combined;
|
||||
else if (c["name"] == "http_two_images")
|
||||
req = {{"messages", messages}};
|
||||
else
|
||||
continue;
|
||||
check_embedding(embedding_reply(s.port, req), c["pooled"][0]);
|
||||
}
|
||||
const auto alone = embedding_reply(s.port, only);
|
||||
const json mixed = {{"input", json::array({"ABC", json::array({im1})})}};
|
||||
check_embedding(embedding_reply(s.port, mixed, 1), alone);
|
||||
REQUIRE_EQ(s.stop(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Opt-in for native 1B/8B checkpoints; weights remain external assets. The offline Python oracle writes this JSON;
|
||||
* neither the ordinary suite nor the engine downloads models or invokes Python. */
|
||||
TEST(nemotron35_real_weights_match_the_offline_transformers_reference) {
|
||||
const char* fixture = std::getenv("RAD_NEMOTRON_REAL_FIXTURE");
|
||||
if (!fixture || !*fixture)
|
||||
SKIP("set RAD_NEMOTRON_REAL_FIXTURE to the offline real-weight oracle JSON");
|
||||
#if !defined(__x86_64__)
|
||||
SKIP("this real-weight check uses libavx on x86-64");
|
||||
#endif
|
||||
const auto reference = json::parse(tiny::read_text(fixture));
|
||||
const int dims = reference.value("dimensions", (int)reference["cases"][0]["embedding"].size());
|
||||
REQUIRE(dims == 2048 || dims == 4096);
|
||||
const auto validation = reference.value("validation", json::object());
|
||||
REQUIRE(rad::mm::decoder_available());
|
||||
Server s;
|
||||
REQUIRE(
|
||||
s.start(reference["checkpoint"],
|
||||
{"--kernels", nemotron_device() ? "libr4d,libavx" : "libavx", "--max-num-seqs", "4",
|
||||
"--max-model-len", std::to_string(validation.value("context", 128)),
|
||||
"--max-num-batched-tokens", std::to_string(validation.value("batch_tokens", 256)),
|
||||
"--mm-max-patches", std::to_string(validation.value("patches", 64))},
|
||||
{"RADIANCE_HOST_VRAM_MIB=24576", "OMP_NUM_THREADS=8",
|
||||
nemotron_device() ? nemotron_device_env() : "ROCR_VISIBLE_DEVICES=99"}));
|
||||
json actual = json::array();
|
||||
for (const auto& c : reference["cases"]) {
|
||||
int status = 0;
|
||||
const auto reply = post(s.port, "/v1/embeddings", c["request"], &status);
|
||||
if (status != 200)
|
||||
fprintf(stderr, " %s HTTP %d: %s\n", c["name"].get<std::string>().c_str(), status,
|
||||
reply.dump().c_str());
|
||||
REQUIRE_EQ(status, 200);
|
||||
const auto got = reply["data"][0]["embedding"].get<std::vector<float>>();
|
||||
actual.push_back({{"name", c["name"]}, {"embedding", got}, {"usage", reply["usage"]}});
|
||||
const auto want = c["embedding"].get<std::vector<float>>();
|
||||
double dot = 0, err = 0, n = 0;
|
||||
REQUIRE_EQ(want.size(), (size_t)dims);
|
||||
REQUIRE_EQ(got.size(), want.size());
|
||||
for (size_t i = 0; i < got.size(); ++i) {
|
||||
dot += (double)got[i] * want[i];
|
||||
n += (double)got[i] * got[i];
|
||||
const double d = got[i] - want[i];
|
||||
err += d * d;
|
||||
}
|
||||
fprintf(stderr, " %s: %zu tokens, cosine %.9g, normalized L2 %.9g\n",
|
||||
c["name"].get<std::string>().c_str(), c["tokens"].size(), dot / std::sqrt(n),
|
||||
std::sqrt(err));
|
||||
CHECK_EQ(reply["usage"]["prompt_tokens"].get<size_t>(), c["tokens"].size());
|
||||
// Full-model gates differ from tiny fixtures: PyTorch eager vs SDPA alone reaches
|
||||
// 2.8% normalized L2 on these weights. 3.2% corresponds to the 0.9995 cosine gate.
|
||||
check_embedding(got, want, (int)want.size(), 0.032);
|
||||
}
|
||||
auto cosine = [](const std::vector<float>& x, const std::vector<float>& y) {
|
||||
double dot = 0, xn = 0, yn = 0;
|
||||
for (size_t i = 0; i < x.size(); ++i) {
|
||||
dot += (double)x[i] * y[i];
|
||||
xn += (double)x[i] * x[i];
|
||||
yn += (double)y[i] * y[i];
|
||||
}
|
||||
return dot / std::sqrt(xn * yn);
|
||||
};
|
||||
double score_error = 0;
|
||||
for (size_t i = 0; i < actual.size(); ++i)
|
||||
for (size_t j = 0; j < i; ++j) {
|
||||
const double got = cosine(actual[i]["embedding"], actual[j]["embedding"]);
|
||||
const double want =
|
||||
cosine(reference["cases"][i]["embedding"], reference["cases"][j]["embedding"]);
|
||||
score_error = std::max(score_error, std::abs(got - want));
|
||||
}
|
||||
fprintf(stderr, " maximum pairwise similarity score error %.9g\n", score_error);
|
||||
CHECK(score_error <= 0.005);
|
||||
for (const auto& group : reference.value("ranking_groups", json::array())) {
|
||||
const int q = group["query"], a = group["documents"][0], b = group["documents"][1];
|
||||
const double native =
|
||||
cosine(reference["cases"][q]["embedding"], reference["cases"][a]["embedding"]) -
|
||||
cosine(reference["cases"][q]["embedding"], reference["cases"][b]["embedding"]);
|
||||
const double candidate = cosine(actual[q]["embedding"], actual[a]["embedding"]) -
|
||||
cosine(actual[q]["embedding"], actual[b]["embedding"]);
|
||||
fprintf(stderr, " retrieval %s native margin %.9g candidate %.9g\n",
|
||||
group["language"].get<std::string>().c_str(), native, candidate);
|
||||
if (std::abs(native) > .01) CHECK(native * candidate > 0);
|
||||
}
|
||||
|
||||
// The real scheduler must preserve a ragged mixed text/image batch's row identities.
|
||||
const auto& cases = reference["cases"];
|
||||
const json mixed = {
|
||||
{"input", json::array({cases[1]["request"]["input"], cases[3]["request"]["input"]})}};
|
||||
check_embedding(embedding_reply(s.port, mixed, 0), cases[1]["embedding"], dims, 0.032);
|
||||
check_embedding(embedding_reply(s.port, mixed, 1), cases[3]["embedding"], dims, 0.032);
|
||||
if (nemotron_device()) {
|
||||
auto stats = [&]() {
|
||||
Call c;
|
||||
std::string body;
|
||||
if (!c.send(s.port, "GET", "/stats", "") || c.read(&body) != 200) return json();
|
||||
return json::parse(body);
|
||||
};
|
||||
const auto before = stats();
|
||||
int status = 0;
|
||||
const auto reply =
|
||||
post(s.port, "/v1/embeddings",
|
||||
{{"input", json::array({cases[0]["tokens"], cases[2]["tokens"]})}}, &status);
|
||||
REQUIRE_EQ(status, 200);
|
||||
check_embedding(reply["data"][0]["embedding"], cases[0]["embedding"], dims, 0.032);
|
||||
check_embedding(reply["data"][1]["embedding"], cases[2]["embedding"], dims, 0.032);
|
||||
const auto after = stats();
|
||||
REQUIRE(before.is_object() && after.is_object());
|
||||
fprintf(stderr, " whole-input batch: steps %lld -> %lld, prompt_tokens %zu\n",
|
||||
before["steps"].get<long long>(), after["steps"].get<long long>(),
|
||||
reply["usage"]["prompt_tokens"].get<size_t>());
|
||||
CHECK_EQ(after["steps"].get<long long>() - before["steps"].get<long long>(), 1);
|
||||
CHECK_EQ(reply["usage"]["prompt_tokens"].get<size_t>(),
|
||||
cases[0]["tokens"].size() + cases[2]["tokens"].size());
|
||||
// A disconnected client must not poison the next embedding, including pooled-row reuse.
|
||||
Call abandoned;
|
||||
REQUIRE(abandoned.send(s.port, "POST", "/v1/embeddings",
|
||||
json({{"input", std::vector<int>(120, 3)}}).dump()));
|
||||
::close(abandoned.fd);
|
||||
abandoned.fd = -1;
|
||||
check_embedding(embedding_reply(s.port, cases[0]["request"]), cases[0]["embedding"], dims,
|
||||
0.032);
|
||||
}
|
||||
// Repeated identical geometry reaches cold, recording, audit and playback paths. Changing
|
||||
// input contents at that geometry catches a tape retaining stale metadata or image rows.
|
||||
if (nemotron_device()) {
|
||||
for (int repeat = 0; repeat < 6; ++repeat)
|
||||
for (int i : {0, 1, 3, 4})
|
||||
check_embedding(embedding_reply(s.port, cases[i]["request"]), cases[i]["embedding"],
|
||||
dims, 0.032);
|
||||
}
|
||||
if (nemotron_device()) {
|
||||
Call c;
|
||||
std::string stats;
|
||||
REQUIRE(c.send(s.port, "GET", "/stats", ""));
|
||||
REQUIRE_EQ(c.read(&stats), 200);
|
||||
const auto state = json::parse(stats);
|
||||
fprintf(stderr, " device stats: %s\n", stats.c_str());
|
||||
if (const char* output = std::getenv("RAD_NEMOTRON_STATS_OUTPUT"))
|
||||
REQUIRE(tiny::write_text(output, state.dump(2) + "\n"));
|
||||
}
|
||||
if (const char* output = std::getenv("RAD_NEMOTRON_REAL_OUTPUT"))
|
||||
REQUIRE(tiny::write_text(output, actual.dump(2) + "\n"));
|
||||
REQUIRE_EQ(s.stop(), 0);
|
||||
if (const char* output = std::getenv("RAD_NEMOTRON_SERVER_LOG"))
|
||||
REQUIRE(tiny::write_text(output, s.output()));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Offline reference generator; never invoked by CMake or CTest.
|
||||
|
||||
Run with CPU PyTorch and transformers==5.20.0. No checkpoint download is needed. The fixture
|
||||
uses the official Ministral3Model with BF16 weights/activations and eager bidirectional attention.
|
||||
The recorded weights let C++ execute the architecture's actual issued graph against the oracle.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import transformers
|
||||
from transformers import Ministral3Config, Ministral3Model
|
||||
|
||||
torch.set_num_threads(1)
|
||||
torch.manual_seed(413)
|
||||
config = Ministral3Config(
|
||||
hidden_size=16,
|
||||
intermediate_size=32,
|
||||
num_hidden_layers=2,
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=1,
|
||||
head_dim=128,
|
||||
vocab_size=32,
|
||||
rms_norm_eps=1e-5,
|
||||
is_causal=False,
|
||||
use_cache=False,
|
||||
rope_parameters={
|
||||
"rope_type": "yarn",
|
||||
"rope_theta": 1e6,
|
||||
"factor": 16.0,
|
||||
"original_max_position_embeddings": 16384,
|
||||
"beta_fast": 32.0,
|
||||
"beta_slow": 1.0,
|
||||
"mscale": 1.0,
|
||||
"mscale_all_dim": 1.0,
|
||||
"llama_4_scaling_beta": 0.1,
|
||||
},
|
||||
)
|
||||
config._attn_implementation = "eager"
|
||||
model = Ministral3Model(config).eval()
|
||||
frequencies = model.rotary_emb.inv_freq.clone()
|
||||
model.to(torch.bfloat16)
|
||||
# from_pretrained(dtype=bfloat16) keeps these nonpersistent buffers in float32. A blanket .to()
|
||||
# would narrow them and generate a different reference, most visibly at long positions.
|
||||
model.rotary_emb.inv_freq = frequencies
|
||||
model.rotary_emb.original_inv_freq = frequencies.clone()
|
||||
# Non-unit gains catch misplaced/omitted norms. Keep them near one to resemble real weights.
|
||||
with torch.no_grad():
|
||||
for name, weight in model.named_parameters():
|
||||
if "norm" in name:
|
||||
weight.copy_(1 + 0.1 * torch.randn(weight.shape))
|
||||
|
||||
weights = {
|
||||
"language_model." + name: {
|
||||
"shape": list(w.shape),
|
||||
"bf16": w.detach().flatten().view(torch.uint16).tolist(),
|
||||
}
|
||||
for name, w in model.state_dict().items()
|
||||
}
|
||||
cases = []
|
||||
for name, inputs, offsets in [
|
||||
("short", [[3, 4, 7, 12, 6]], [0]),
|
||||
("ragged", [[3, 4, 7], [12, 6, 2, 8, 9]], [0, 0]),
|
||||
("q_scale_boundary", [[3, 4, 7, 12]], [16382]),
|
||||
]:
|
||||
expected = []
|
||||
for ids, offset in zip(inputs, offsets):
|
||||
with torch.no_grad():
|
||||
hidden = model(
|
||||
torch.tensor([ids]),
|
||||
attention_mask=torch.ones((1, len(ids)), dtype=torch.long),
|
||||
position_ids=torch.arange(offset, offset + len(ids))[None],
|
||||
use_cache=False,
|
||||
).last_hidden_state
|
||||
# Reproduce NVIDIA's documented BF16 masked sum/division before float normalization.
|
||||
pooled = (hidden.sum(1) / len(ids)).float()
|
||||
expected.append(pooled.flatten().tolist())
|
||||
cases.append({"name": name, "inputs": inputs, "offsets": offsets, "pooled": expected})
|
||||
|
||||
output = {
|
||||
"provenance": {
|
||||
"transformers": transformers.__version__,
|
||||
"torch": torch.__version__,
|
||||
"seed": 413,
|
||||
"attention": "eager",
|
||||
"dtype": "bfloat16",
|
||||
"rotary_dtype": "float32",
|
||||
},
|
||||
"weights": weights,
|
||||
"cases": cases,
|
||||
}
|
||||
path = Path(__file__).parent / "data" / "golden" / "nemotron35.json"
|
||||
path.write_text(json.dumps(output, separators=(",", ":")) + "\n")
|
||||
print(path, path.stat().st_size)
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Offline input oracle; never invoked by CMake/CTest.
|
||||
|
||||
Use --tokenizer with tokenizer.json from nvidia/Nemotron-3.5-Embed-8B-BF16 revision
|
||||
781e779ee4ca9c2d2a4f38321993556baeab49a1. Requires Jinja2 and Hugging Face tokenizers.
|
||||
The checked-in template is copied from that same checkpoint revision.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import jinja2
|
||||
import tokenizers
|
||||
from jinja2 import StrictUndefined
|
||||
from jinja2.sandbox import ImmutableSandboxedEnvironment
|
||||
|
||||
args = argparse.ArgumentParser()
|
||||
args.add_argument("--tokenizer", type=Path, required=True)
|
||||
opts = args.parse_args()
|
||||
root = Path(__file__).parent
|
||||
source = (root / "data/chat/nemotron35/template.jinja").read_text()
|
||||
env = ImmutableSandboxedEnvironment(undefined=StrictUndefined)
|
||||
|
||||
|
||||
def refuse(message):
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
env.globals["raise_exception"] = refuse
|
||||
template = env.from_string(source)
|
||||
tok = tokenizers.Tokenizer.from_file(str(opts.tokenizer))
|
||||
vision = json.loads((root / "data/golden/nemotron35_vision.json").read_text())
|
||||
cases = []
|
||||
expanded_checks = []
|
||||
user_inputs = [
|
||||
("plain", "What is NVIDIA NeMo Framework?"),
|
||||
("literal_controls", "Treat [IMG], [IMG_BREAK], <s>, </s> and <__media__> literally."),
|
||||
("unicode", "¿Qué ves? Καλημέρα 世界 👁️\n"),
|
||||
(
|
||||
"parts",
|
||||
[
|
||||
{"type": "text", "text": "first"},
|
||||
{"type": "text", "text": ""},
|
||||
{"type": "text", "text": "last"},
|
||||
],
|
||||
),
|
||||
("image_only", [{"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}]),
|
||||
(
|
||||
"text_before_images",
|
||||
[
|
||||
{"type": "text", "text": "A [page]"},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64,AQ=="}},
|
||||
{"type": "text", "text": "<details>"},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64,Ag=="}},
|
||||
],
|
||||
),
|
||||
(
|
||||
"empty_blocks",
|
||||
[
|
||||
{"type": "text", "text": ""},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64,Aw=="}},
|
||||
{"type": "text", "text": ""},
|
||||
],
|
||||
),
|
||||
]
|
||||
for prefix_name, prefix in [
|
||||
("none", None),
|
||||
("query", "query: "),
|
||||
("document", "passage: "),
|
||||
("system_blocks", [{"type": "text", "text": "x "}, {"type": "text", "text": "y\t "}]),
|
||||
]:
|
||||
for name, content in user_inputs:
|
||||
messages = [] if prefix is None else [{"role": "system", "content": prefix}]
|
||||
messages.append({"role": "user", "content": content})
|
||||
rendered = template.render(messages=messages)
|
||||
# Record text segments between genuine image placeholders. Escaped user literals contain
|
||||
# a ZWNJ, so they cannot be confused with these boundaries.
|
||||
segments = rendered.split("[IMG]")
|
||||
image_blocks = (
|
||||
[] if isinstance(content, str) else [b for b in content if b["type"] == "image_url"]
|
||||
)
|
||||
expanded = segments[0]
|
||||
order = []
|
||||
for i, block in enumerate(image_blocks):
|
||||
index = base64.b64decode(block["image_url"]["url"].split(",")[1])[0]
|
||||
order.append(index)
|
||||
expanded += (
|
||||
"".join(tok.id_to_token(t) for t in vision["images"][index]["expand"])
|
||||
+ segments[i + 1]
|
||||
)
|
||||
cases.append(
|
||||
{
|
||||
"name": prefix_name + "/" + name,
|
||||
"messages": messages,
|
||||
"rendered": rendered,
|
||||
"ids": tok.encode(rendered, add_special_tokens=False).ids,
|
||||
"expanded_ids": tok.encode(expanded, add_special_tokens=False).ids,
|
||||
"image_order": order,
|
||||
"segments": [
|
||||
{"text": s, "ids": tok.encode(s, add_special_tokens=False).ids}
|
||||
for s in segments
|
||||
],
|
||||
}
|
||||
)
|
||||
if prefix_name == "none" and isinstance(content, str):
|
||||
cases[-1]["legacy_text"] = content
|
||||
cases[-1]["legacy_ids"] = tok.encode(content, add_special_tokens=False).ids
|
||||
expanded_checks.append((expanded, cases[-1]["expanded_ids"]))
|
||||
|
||||
# A sparse fixture vocabulary, not a deployable tokenizer: retain every byte and added token,
|
||||
# and every BPE candidate that can occur in a fixture segment. Preserve original ids and merge
|
||||
# ordering. Both HF and the C++ tests run this subset; HF must reproduce the full tokenizer first.
|
||||
original = json.loads(opts.tokenizer.read_text())
|
||||
subset = copy.deepcopy(original)
|
||||
wanted = set(tokenizers.pre_tokenizers.ByteLevel.alphabet())
|
||||
wanted.update(t["content"] for t in original["added_tokens"])
|
||||
bytelevel = tokenizers.pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=False)
|
||||
for case in cases:
|
||||
samples = [seg["text"] for seg in case["segments"]]
|
||||
if "legacy_text" in case:
|
||||
samples.append(case["legacy_text"])
|
||||
for sample in samples:
|
||||
for text in (sample, tok.normalizer.normalize_str(sample)):
|
||||
encoded = "".join(p for p, offsets in bytelevel.pre_tokenize_str(text))
|
||||
wanted.update(
|
||||
encoded[i:j] for i in range(len(encoded)) for j in range(i + 1, len(encoded) + 1)
|
||||
)
|
||||
vocab = {t: i for t, i in original["model"]["vocab"].items() if t in wanted}
|
||||
merges = []
|
||||
for merge in original["model"]["merges"]:
|
||||
a, b = merge if isinstance(merge, list) else merge.split(" ")
|
||||
if a in vocab and b in vocab and a + b in vocab:
|
||||
merges.append(merge)
|
||||
subset["model"]["vocab"] = vocab
|
||||
subset["model"]["merges"] = merges
|
||||
subset_text = json.dumps(subset, ensure_ascii=False, separators=(",", ":"))
|
||||
small = tokenizers.Tokenizer.from_str(subset_text)
|
||||
for case in cases:
|
||||
assert small.encode(case["rendered"], add_special_tokens=False).ids == case["ids"]
|
||||
for seg in case["segments"]:
|
||||
assert small.encode(seg["text"], add_special_tokens=False).ids == seg["ids"]
|
||||
if "legacy_text" in case:
|
||||
assert small.encode(case["legacy_text"], add_special_tokens=False).ids == case["legacy_ids"]
|
||||
for expanded, ids in expanded_checks:
|
||||
assert small.encode(expanded, add_special_tokens=False).ids == ids
|
||||
(root / "data/chat/nemotron35/tokenizer-subset.json").write_text(subset_text + "\n")
|
||||
|
||||
result = {
|
||||
"provenance": {
|
||||
"model_revision": "781e779ee4ca9c2d2a4f38321993556baeab49a1",
|
||||
"jinja2": jinja2.__version__,
|
||||
"tokenizers": tokenizers.__version__,
|
||||
"template_sha256": hashlib.sha256(source.encode()).hexdigest(),
|
||||
"tokenizer_sha256": hashlib.sha256(opts.tokenizer.read_bytes()).hexdigest(),
|
||||
"subset_sha256": hashlib.sha256((subset_text + "\n").encode()).hexdigest(),
|
||||
},
|
||||
"cases": cases,
|
||||
}
|
||||
path = root / "data/golden/nemotron35_input.json"
|
||||
path.write_text(json.dumps(result, ensure_ascii=False, separators=(",", ":")) + "\n")
|
||||
print(path, path.stat().st_size)
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Offline full Mistral3Model oracle, reusing the checked-in tiny text and vision weights.
|
||||
Never run by CMake/CTest. Requires CPU torch and transformers==5.20.0.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import transformers
|
||||
from transformers import (
|
||||
Ministral3Config,
|
||||
Mistral3Config,
|
||||
Mistral3Model,
|
||||
PixtralVisionConfig,
|
||||
)
|
||||
|
||||
root = Path(__file__).parent / "data/golden"
|
||||
text = json.loads((root / "nemotron35.json").read_text())
|
||||
vision = json.loads((root / "nemotron35_vision.json").read_text())
|
||||
torch.set_num_threads(1)
|
||||
tc = Ministral3Config(
|
||||
hidden_size=16,
|
||||
intermediate_size=32,
|
||||
num_hidden_layers=2,
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=1,
|
||||
head_dim=128,
|
||||
vocab_size=32,
|
||||
rms_norm_eps=1e-5,
|
||||
is_causal=False,
|
||||
use_cache=False,
|
||||
rope_parameters={
|
||||
"rope_type": "yarn",
|
||||
"rope_theta": 1e6,
|
||||
"factor": 16.0,
|
||||
"original_max_position_embeddings": 16384,
|
||||
"beta_fast": 32.0,
|
||||
"beta_slow": 1.0,
|
||||
"mscale": 1.0,
|
||||
"mscale_all_dim": 1.0,
|
||||
"llama_4_scaling_beta": 0.1,
|
||||
},
|
||||
)
|
||||
vc = PixtralVisionConfig(
|
||||
hidden_size=64,
|
||||
intermediate_size=96,
|
||||
num_hidden_layers=2,
|
||||
num_attention_heads=1,
|
||||
patch_size=14,
|
||||
image_size=1540,
|
||||
hidden_act="silu",
|
||||
rope_parameters={"rope_type": "axial", "rope_theta": 10000.0},
|
||||
)
|
||||
config = Mistral3Config(
|
||||
text_config=tc,
|
||||
vision_config=vc,
|
||||
spatial_merge_size=2,
|
||||
image_token_index=10,
|
||||
multimodal_projector_bias=False,
|
||||
projector_hidden_act="gelu",
|
||||
vision_feature_layer=-1,
|
||||
is_causal=False,
|
||||
)
|
||||
model = Mistral3Model(config).eval()
|
||||
frequencies = {name: b.clone() for name, b in model.named_buffers()}
|
||||
model.to(torch.bfloat16)
|
||||
for name, b in frequencies.items():
|
||||
parent, attr = name.rsplit(".", 1)
|
||||
setattr(model.get_submodule(parent), attr, b)
|
||||
model.set_attn_implementation("eager")
|
||||
assert model.language_model.config._attn_implementation == "eager"
|
||||
assert model.vision_tower.config._attn_implementation == "eager"
|
||||
state = text["weights"] | vision["weights"]
|
||||
model.load_state_dict(
|
||||
{
|
||||
name: torch.tensor(w["bf16"], dtype=torch.uint16).view(torch.bfloat16).reshape(w["shape"])
|
||||
for name, w in state.items()
|
||||
},
|
||||
strict=True,
|
||||
)
|
||||
|
||||
|
||||
def sequence(parts):
|
||||
ids, placements = [], []
|
||||
for p in parts:
|
||||
if isinstance(p, list):
|
||||
ids.extend(p)
|
||||
else:
|
||||
placements.append({"image": p, "tok": len(ids)})
|
||||
ids.extend(vision["images"][p]["expand"])
|
||||
return {"tokens": ids, "placements": placements}
|
||||
|
||||
|
||||
def pixels(index):
|
||||
image = vision["images"][index]
|
||||
h, w = image["size"]
|
||||
patches = torch.tensor(image["patches"], dtype=torch.uint16).view(torch.bfloat16)
|
||||
return patches.reshape(h // 14, w // 14, 3, 14, 14).permute(2, 0, 3, 1, 4).reshape(3, h, w)
|
||||
|
||||
|
||||
image_only = sequence([1])
|
||||
combined = sequence([[3, 4], 2, [5, 7, 8, 6]])
|
||||
two_images = sequence([[3], 1, [5], 3, [5, 7, 9]])
|
||||
plain = sequence([[3, 4, 7, 8]])
|
||||
http_combined = sequence([2, [5, 7, 8, 6]])
|
||||
http_two = sequence([[3, 4, 5], 1, [5], 3, [5, 7, 9]])
|
||||
cases = []
|
||||
for name, inputs in [
|
||||
("image_only", [image_only]),
|
||||
("image_text", [combined]),
|
||||
("two_images", [two_images]),
|
||||
("ragged", [image_only, combined, two_images]),
|
||||
("text_and_image_batch", [plain, image_only]),
|
||||
("http_image_text", [http_combined]),
|
||||
("http_two_images", [http_two]),
|
||||
]:
|
||||
length = max(len(x["tokens"]) for x in inputs)
|
||||
ids = torch.full((len(inputs), length), 11, dtype=torch.long)
|
||||
mask = torch.zeros_like(ids)
|
||||
image_indices = []
|
||||
for s, x in enumerate(inputs):
|
||||
ids[s, : len(x["tokens"])] = torch.tensor(x["tokens"])
|
||||
mask[s, : len(x["tokens"])] = 1
|
||||
image_indices.extend(p["image"] for p in x["placements"])
|
||||
imgs = [pixels(i) for i in image_indices]
|
||||
sizes = torch.tensor([list(p.shape[1:]) for p in imgs])
|
||||
h, w = sizes.max(0).values.tolist()
|
||||
padded = torch.stack(
|
||||
[torch.nn.functional.pad(x, (0, w - x.shape[2], 0, h - x.shape[1])) for x in imgs]
|
||||
)
|
||||
with torch.no_grad():
|
||||
output = model(
|
||||
input_ids=ids,
|
||||
attention_mask=mask,
|
||||
pixel_values=padded,
|
||||
image_sizes=sizes,
|
||||
position_ids=torch.arange(length)[None].expand(len(inputs), -1),
|
||||
use_cache=False,
|
||||
)
|
||||
# NVIDIA's documented masked BF16 sum/divide; padding is not part of the valid-token mean.
|
||||
pooled = (
|
||||
(output.last_hidden_state * mask[..., None]).sum(1) / mask.sum(1)[:, None]
|
||||
).float()
|
||||
cases.append(
|
||||
{
|
||||
"name": name,
|
||||
"inputs": inputs,
|
||||
"pooled": pooled.tolist(),
|
||||
"hidden": [
|
||||
output.last_hidden_state[s, : len(x["tokens"])].float().tolist()
|
||||
for s, x in enumerate(inputs)
|
||||
],
|
||||
}
|
||||
)
|
||||
result = {
|
||||
"provenance": {
|
||||
"transformers": transformers.__version__,
|
||||
"torch": torch.__version__,
|
||||
"attention": "eager",
|
||||
"dtype": "bfloat16",
|
||||
"rotary_dtype": "float32",
|
||||
"weights": ["nemotron35.json", "nemotron35_vision.json"],
|
||||
},
|
||||
"cases": cases,
|
||||
}
|
||||
path = root / "nemotron35_multimodal.json"
|
||||
path.write_text(json.dumps(result, separators=(",", ":")) + "\n")
|
||||
print(path, path.stat().st_size)
|
||||
@@ -0,0 +1,292 @@
|
||||
"""Offline real-weight CPU oracle; never invoked by CMake or CTest.
|
||||
|
||||
Usage: python tests/mknemotron35realreference.py LOCAL_CHECKPOINT OUTPUT_JSON
|
||||
Requires torch2.14.1+cpu, torchvision0.29.1+cpu, transformers5.20.0 and Pillow13.0.0. The checkpoint is read locally, with no
|
||||
network access or remote code. Its full BF16 weights require about 20 GB of available RAM.
|
||||
The output includes HTTP requests and independent normalized embeddings for the optional
|
||||
engine_e2e_test real-weight case. Image processing explicitly uses the supported PIL backend.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import importlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import PIL
|
||||
import torch
|
||||
import torchvision
|
||||
import transformers
|
||||
from PIL import Image
|
||||
from transformers import AutoModel, AutoTokenizer, PixtralProcessor
|
||||
from transformers.models.pixtral.image_processing_pil_pixtral import (
|
||||
PixtralImageProcessorPil,
|
||||
)
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("checkpoint", type=Path)
|
||||
parser.add_argument("output", type=Path)
|
||||
parser.add_argument("--threads", type=int, default=8)
|
||||
parser.add_argument("--attention", choices=["eager", "sdpa"], default="eager")
|
||||
parser.add_argument(
|
||||
"--extended",
|
||||
action="store_true",
|
||||
help="include multilingual retrieval, longer text and a medium image",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--float-accumulation",
|
||||
action="store_true",
|
||||
help="diagnose BF16 BLAS differences with float32 products, narrowing each result",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
torch.set_num_threads(args.threads)
|
||||
checkpoint = args.checkpoint.resolve()
|
||||
metadata = (checkpoint / ".cache/huggingface/download").glob("model-*.safetensors.metadata")
|
||||
revisions = {p.read_text().splitlines()[0] for p in metadata}
|
||||
asset_manifest = checkpoint / "asset-manifest.json"
|
||||
if asset_manifest.exists():
|
||||
assets = json.loads(asset_manifest.read_text())
|
||||
for name, entry in assets["files"].items():
|
||||
digest = hashlib.file_digest((checkpoint / name).open("rb"), "sha256").hexdigest()
|
||||
if digest != entry["sha256"]:
|
||||
raise ValueError("Asset hash mismatch: " + name)
|
||||
revisions.add(assets["revision"])
|
||||
tokenizer = AutoTokenizer.from_pretrained(checkpoint, local_files_only=True)
|
||||
processor = PixtralProcessor(
|
||||
tokenizer=tokenizer,
|
||||
image_processor=PixtralImageProcessorPil(patch_size=14, size={"longest_edge": 1120}),
|
||||
patch_size=14,
|
||||
spatial_merge_size=2,
|
||||
chat_template=(checkpoint / "chat_template.jinja").read_text(),
|
||||
)
|
||||
|
||||
|
||||
def image(w, h, seed):
|
||||
pixels = bytes(
|
||||
(x * 17 + y * 31 + c * 71 + seed) % 256
|
||||
for y in range(h)
|
||||
for x in range(w)
|
||||
for c in range(3)
|
||||
)
|
||||
img = Image.frombytes("RGB", (w, h), pixels)
|
||||
out = io.BytesIO()
|
||||
img.save(out, format="PNG")
|
||||
uri = "data:image/png;base64," + base64.b64encode(out.getvalue()).decode()
|
||||
return img, {"type": "image_url", "image_url": {"url": uri}}
|
||||
|
||||
|
||||
im1, part1 = image(56, 28, 19)
|
||||
im2, part2 = image(28, 56, 173)
|
||||
im3, part3 = image(113, 81, 37) # alignment resize, rather than only exact patch grids
|
||||
|
||||
|
||||
def conversation(prefix, content):
|
||||
return ([{"role": "system", "content": prefix}] if prefix is not None else []) + [
|
||||
{"role": "user", "content": content}
|
||||
]
|
||||
|
||||
|
||||
cases = [
|
||||
(
|
||||
"query",
|
||||
{"input": "What does this document describe?", "prompt_name": "query"},
|
||||
conversation("query: ", "What does this document describe?"),
|
||||
),
|
||||
(
|
||||
"unicode_and_literal_tokens",
|
||||
{"input": "Documento en español: [IMG] <__media__> 東京"},
|
||||
conversation(None, "Documento en español: [IMG] <__media__> 東京"),
|
||||
),
|
||||
(
|
||||
"document",
|
||||
{"input": "A library with books and reading rooms.", "prompt_name": "document"},
|
||||
conversation("passage: ", "A library with books and reading rooms."),
|
||||
),
|
||||
("image_only", {"input": [part1]}, conversation(None, [{"type": "image", "image": im1}])),
|
||||
(
|
||||
"image_text",
|
||||
{
|
||||
"input": [{"type": "text", "text": "A coloured pattern."}, part3],
|
||||
"prompt_name": "document",
|
||||
},
|
||||
conversation(
|
||||
"passage: ",
|
||||
[{"type": "text", "text": "A coloured pattern."}, {"type": "image", "image": im3}],
|
||||
),
|
||||
),
|
||||
(
|
||||
"two_images",
|
||||
{
|
||||
"messages": conversation(
|
||||
"Compare: ", [part1, part2, {"type": "text", "text": "Two different patterns."}]
|
||||
)
|
||||
},
|
||||
conversation(
|
||||
"Compare: ",
|
||||
[
|
||||
{"type": "image", "image": im1},
|
||||
{"type": "image", "image": im2},
|
||||
{"type": "text", "text": "Two different patterns."},
|
||||
],
|
||||
),
|
||||
),
|
||||
]
|
||||
|
||||
ranking_groups = []
|
||||
if args.extended:
|
||||
retrieval = {
|
||||
"en": [
|
||||
"Where can I borrow books for free?",
|
||||
"A public library lends books to readers without charging a fee.",
|
||||
"The football team won its match with two goals.",
|
||||
],
|
||||
"es": [
|
||||
"¿Dónde puedo tomar libros prestados gratis?",
|
||||
"La biblioteca pública presta libros a los lectores sin cobrar.",
|
||||
"El equipo de fútbol ganó el partido con dos goles.",
|
||||
],
|
||||
"ja": [
|
||||
"無料で本を借りられる場所はどこですか?",
|
||||
"公共図書館では、読者は無料で本を借りることができます。",
|
||||
"サッカーチームは二得点で試合に勝ちました。",
|
||||
],
|
||||
}
|
||||
for language, texts in retrieval.items():
|
||||
indices = []
|
||||
for i, text in enumerate(texts):
|
||||
indices.append(len(cases))
|
||||
task = "query" if i == 0 else "document"
|
||||
prefix = "query: " if i == 0 else "passage: "
|
||||
cases.append(
|
||||
(
|
||||
f"retrieval_{language}_{i}",
|
||||
{"input": text, "prompt_name": task},
|
||||
conversation(prefix, text),
|
||||
)
|
||||
)
|
||||
ranking_groups.append({"language": language, "query": indices[0], "documents": indices[1:]})
|
||||
for repeats in [48, 192]:
|
||||
text = "The public library contains science books and historical maps. " * repeats
|
||||
cases.append(
|
||||
(
|
||||
f"longer_text_{repeats}",
|
||||
{"input": text, "prompt_name": "document"},
|
||||
conversation("passage: ", text),
|
||||
)
|
||||
)
|
||||
medium, medium_part = image(224, 112, 59)
|
||||
cases.append(
|
||||
(
|
||||
"medium_image_text",
|
||||
{
|
||||
"input": [medium_part, {"type": "text", "text": "A colourful document page."}],
|
||||
"prompt_name": "document",
|
||||
},
|
||||
conversation(
|
||||
"passage: ",
|
||||
[
|
||||
{"type": "image", "image": medium},
|
||||
{"type": "text", "text": "A colourful document page."},
|
||||
],
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
print("Loading local BF16 model", flush=True)
|
||||
model = AutoModel.from_pretrained(
|
||||
checkpoint,
|
||||
local_files_only=True,
|
||||
dtype=torch.bfloat16,
|
||||
trust_remote_code=False,
|
||||
attn_implementation=args.attention,
|
||||
).eval()
|
||||
if args.float_accumulation:
|
||||
linear, matmul, conv2d = torch.nn.functional.linear, torch.matmul, torch.nn.functional.conv2d
|
||||
|
||||
def float_linear(x, weight, bias=None):
|
||||
if x.dtype != torch.bfloat16:
|
||||
return linear(x, weight, bias)
|
||||
return linear(x.float(), weight.float(), None if bias is None else bias.float()).to(x.dtype)
|
||||
|
||||
def float_matmul(x, y, *rest, **kwargs):
|
||||
if x.dtype != torch.bfloat16:
|
||||
return matmul(x, y, *rest, **kwargs)
|
||||
return matmul(x.float(), y.float(), *rest, **kwargs).to(x.dtype)
|
||||
|
||||
def float_conv2d(x, weight, bias=None, *rest, **kwargs):
|
||||
if x.dtype != torch.bfloat16:
|
||||
return conv2d(x, weight, bias, *rest, **kwargs)
|
||||
return conv2d(
|
||||
x.float(), weight.float(), None if bias is None else bias.float(), *rest, **kwargs
|
||||
).to(x.dtype)
|
||||
|
||||
torch.nn.functional.linear = float_linear
|
||||
torch.matmul = float_matmul
|
||||
torch.nn.functional.conv2d = float_conv2d
|
||||
results = []
|
||||
for name, request, messages in cases:
|
||||
inputs = processor.apply_chat_template(
|
||||
messages, tokenize=True, return_dict=True, return_tensors="pt"
|
||||
)
|
||||
if "pixel_values" in inputs:
|
||||
inputs["pixel_values"] = inputs["pixel_values"].to(torch.bfloat16)
|
||||
with torch.inference_mode():
|
||||
hidden = model(**inputs, use_cache=False).last_hidden_state
|
||||
mask = inputs["attention_mask"].unsqueeze(-1)
|
||||
pooled = ((hidden * mask).sum(1) / mask.sum(1)).float()
|
||||
embedding = torch.nn.functional.normalize(pooled, dim=-1)[0].tolist()
|
||||
results.append(
|
||||
{
|
||||
"name": name,
|
||||
"request": request,
|
||||
"tokens": inputs["input_ids"][0].tolist(),
|
||||
"embedding": embedding,
|
||||
}
|
||||
)
|
||||
print(name, len(results[-1]["tokens"]), "tokens", flush=True)
|
||||
sources = {}
|
||||
for name in [
|
||||
"transformers.models.ministral3.modeling_ministral3",
|
||||
"transformers.models.mistral3.modeling_mistral3",
|
||||
"transformers.models.pixtral.modeling_pixtral",
|
||||
"transformers.models.pixtral.image_processing_pil_pixtral",
|
||||
]:
|
||||
path = Path(importlib.import_module(name).__file__)
|
||||
sources[name] = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
maximum = max(len(c["tokens"]) for c in results)
|
||||
context = max(128, 1 << (maximum - 1).bit_length())
|
||||
args.output.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"checkpoint": str(checkpoint),
|
||||
"dimensions": model.config.text_config.hidden_size,
|
||||
"validation": {
|
||||
"context": context,
|
||||
"batch_tokens": context * 2,
|
||||
"patches": 128 if args.extended else 64,
|
||||
},
|
||||
"ranking_groups": ranking_groups,
|
||||
"provenance": {
|
||||
"transformers": transformers.__version__,
|
||||
"torch": torch.__version__,
|
||||
"torchvision": torchvision.__version__,
|
||||
"pillow": PIL.__version__,
|
||||
"dtype": "bfloat16",
|
||||
"attention": args.attention,
|
||||
"processor": "PIL",
|
||||
"float_accumulation": args.float_accumulation,
|
||||
"model_revision": next(iter(revisions)) if len(revisions) == 1 else None,
|
||||
"sources": sources,
|
||||
"asset_manifest_sha256": hashlib.sha256(asset_manifest.read_bytes()).hexdigest()
|
||||
if asset_manifest.exists()
|
||||
else None,
|
||||
},
|
||||
"cases": results,
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
print(args.output, flush=True)
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Offline official Transformers/Pillow oracle for Nemotron 3.5's vision path.
|
||||
|
||||
Never called by CMake/CTest. Requires CPU torch/torchvision, transformers==5.20.0, NumPy and Pillow.
|
||||
Random tiny weights retain the production patch size, head width, activation and merger layout.
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import PIL
|
||||
import torch
|
||||
import torchvision
|
||||
import transformers
|
||||
from PIL import Image
|
||||
from transformers import (
|
||||
Ministral3Config,
|
||||
Mistral3Config,
|
||||
PixtralVisionConfig,
|
||||
PixtralVisionModel,
|
||||
)
|
||||
from transformers.models.mistral3.modeling_mistral3 import Mistral3MultiModalProjector
|
||||
from transformers.models.pixtral.image_processing_pil_pixtral import (
|
||||
PixtralImageProcessorPil,
|
||||
)
|
||||
from transformers.models.pixtral.processing_pixtral import PixtralProcessor
|
||||
|
||||
torch.set_num_threads(1)
|
||||
torch.manual_seed(8275)
|
||||
vc = PixtralVisionConfig(
|
||||
hidden_size=64,
|
||||
intermediate_size=96,
|
||||
num_hidden_layers=2,
|
||||
num_attention_heads=1,
|
||||
patch_size=14,
|
||||
image_size=1540,
|
||||
hidden_act="silu",
|
||||
rope_parameters={"rope_type": "axial", "rope_theta": 10000.0},
|
||||
)
|
||||
vc._attn_implementation = "eager"
|
||||
tc = Ministral3Config(
|
||||
hidden_size=16,
|
||||
intermediate_size=32,
|
||||
num_hidden_layers=2,
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=1,
|
||||
head_dim=128,
|
||||
vocab_size=32,
|
||||
rms_norm_eps=1e-5,
|
||||
is_causal=False,
|
||||
)
|
||||
config = Mistral3Config(
|
||||
vision_config=vc,
|
||||
text_config=tc,
|
||||
spatial_merge_size=2,
|
||||
multimodal_projector_bias=False,
|
||||
projector_hidden_act="gelu",
|
||||
vision_feature_layer=-1,
|
||||
)
|
||||
vision = PixtralVisionModel(vc).eval()
|
||||
frequencies = vision.patch_positional_embedding.inv_freq.clone()
|
||||
vision.to(torch.bfloat16)
|
||||
# Match from_pretrained(dtype=bfloat16): rotary frequency buffers stay float32.
|
||||
vision.patch_positional_embedding.inv_freq = frequencies
|
||||
vision.patch_positional_embedding.original_inv_freq = frequencies.clone()
|
||||
projector = Mistral3MultiModalProjector(config).to(torch.bfloat16).eval()
|
||||
with torch.no_grad():
|
||||
# The projector class is not a PreTrainedModel; initialise its linears explicitly.
|
||||
for name, weight in projector.named_parameters():
|
||||
weight.copy_(
|
||||
torch.randn(weight.shape) * 0.02
|
||||
if weight.ndim == 2
|
||||
else 1 + torch.randn(weight.shape) * 0.1
|
||||
)
|
||||
for name, weight in vision.named_parameters():
|
||||
if "norm" in name or "ln_pre" in name:
|
||||
weight.copy_(1 + 0.1 * torch.randn(weight.shape))
|
||||
|
||||
processor = PixtralImageProcessorPil(patch_size=28, size={"longest_edge": 1120})
|
||||
|
||||
|
||||
def frame(f, h, w):
|
||||
y, x, c = np.indices((h, w, 3), dtype=np.uint64)
|
||||
with np.errstate(over="ignore"):
|
||||
z = np.uint64(f) * np.uint64(0x9E3779B97F4A7C15) + y * np.uint64(0xBF58476D1CE4E5B9)
|
||||
z += (
|
||||
x * np.uint64(0x94D049BB133111EB) + c * np.uint64(0x2545F4914F6CDD1D) + np.uint64(12345)
|
||||
)
|
||||
z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
|
||||
z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
|
||||
return ((z ^ (z >> np.uint64(31))) & 255).astype(np.uint8)
|
||||
|
||||
|
||||
def patchify(x):
|
||||
# Only fixture serialisation: the oracle's convolution still consumes real [C,H,W] pixels.
|
||||
c, h, w = x.shape
|
||||
return x.reshape(c, h // 14, 14, w // 14, 14).permute(1, 3, 0, 2, 4).reshape(-1, 3 * 14 * 14)
|
||||
|
||||
|
||||
def bf16(x):
|
||||
return x.detach().contiguous().flatten().view(torch.uint16).tolist()
|
||||
|
||||
|
||||
def fnv(values):
|
||||
h = 0xCBF29CE484222325
|
||||
for v in values:
|
||||
for b in (v & 255, v >> 8):
|
||||
h = ((h ^ b) * 0x100000001B3) & ((1 << 64) - 1)
|
||||
return f"{h:016x}"
|
||||
|
||||
|
||||
images, pixels = [], []
|
||||
for f, h, w in [
|
||||
(0, 1, 1),
|
||||
(1, 28, 56),
|
||||
(2, 29, 57),
|
||||
(3, 56, 28),
|
||||
(4, 56, 56),
|
||||
(5, 1500, 1000),
|
||||
(6, 1, 10000),
|
||||
]:
|
||||
try:
|
||||
data = processor(images=[Image.fromarray(frame(f, h, w))], return_tensors="pt")
|
||||
except ValueError:
|
||||
if f != 6:
|
||||
raise
|
||||
# Flooring this extreme aspect ratio produces a zero side in the official processor.
|
||||
images.append({"f": f, "h": h, "w": w, "error": "zero resize side"})
|
||||
pixels.append(None)
|
||||
continue
|
||||
x = data["pixel_values"][0].to(torch.bfloat16)
|
||||
values = bf16(patchify(x))
|
||||
formatter = SimpleNamespace(
|
||||
patch_size=14,
|
||||
spatial_merge_size=2,
|
||||
image_token="[IMG]",
|
||||
image_break_token="[IMG_BREAK]",
|
||||
image_end_token="[IMG_END]",
|
||||
)
|
||||
expansion = PixtralProcessor.replace_image_token(formatter, data, 0)
|
||||
token_ids = {"[IMG]": 10, "[IMG_BREAK]": 12, "[IMG_END]": 13}
|
||||
images.append(
|
||||
{
|
||||
"f": f,
|
||||
"h": h,
|
||||
"w": w,
|
||||
"size": list(x.shape[1:]),
|
||||
"fnv": fnv(values),
|
||||
"expand": [token_ids[t] for t in re.findall(r"\[IMG(?:_BREAK|_END)?\]", expansion)],
|
||||
"patches": values if x.numel() < 20000 else [],
|
||||
}
|
||||
)
|
||||
pixels.append(x)
|
||||
|
||||
weights = {}
|
||||
for prefix, model in [("vision_tower", vision), ("multi_modal_projector", projector)]:
|
||||
for name, w in model.state_dict().items():
|
||||
weights[prefix + "." + name] = {"shape": list(w.shape), "bf16": bf16(w)}
|
||||
|
||||
captured = {}
|
||||
projector.norm.register_forward_hook(
|
||||
lambda m, a, y: captured.update(post_norm=y.detach().float().tolist())
|
||||
)
|
||||
projector.patch_merger.merging_layer.register_forward_pre_hook(
|
||||
lambda m, a: captured.update(packed=a[0].detach().float().tolist())
|
||||
)
|
||||
projector.patch_merger.register_forward_hook(
|
||||
lambda m, a, y: captured.update(merged=y.detach().float().tolist())
|
||||
)
|
||||
cases = []
|
||||
for name, indices in [("wide", [1]), ("tall", [3]), ("square", [4]), ("mixed", [2, 0])]:
|
||||
xs = [pixels[i] for i in indices]
|
||||
sizes = torch.tensor([list(x.shape[1:]) for x in xs])
|
||||
h, w = sizes.max(0).values.tolist()
|
||||
padded = torch.stack(
|
||||
[torch.nn.functional.pad(x, (0, w - x.shape[2], 0, h - x.shape[1])) for x in xs]
|
||||
)
|
||||
with torch.no_grad():
|
||||
hidden = vision(padded, image_sizes=sizes).last_hidden_state.squeeze(0)
|
||||
out = projector(hidden, sizes)
|
||||
cases.append(
|
||||
{
|
||||
"name": name,
|
||||
"images": indices,
|
||||
"hidden": hidden.float().tolist(),
|
||||
**captured,
|
||||
"out": out.float().tolist(),
|
||||
}
|
||||
)
|
||||
|
||||
# Isolate every frequency and dtype-rounding seam, including coordinates near the max grid.
|
||||
qkv = torch.linspace(-2, 2, 6 * 3 * 64).reshape(6, 3, 64).to(torch.bfloat16)
|
||||
coords = torch.tensor([[0, 0], [1, 2], [3, 1], [63, 79], [79, 63], [109, 109]])
|
||||
from transformers.models.pixtral.modeling_pixtral import apply_rotary_pos_emb
|
||||
|
||||
with torch.no_grad():
|
||||
cos, sin = vision.patch_positional_embedding(qkv, coords)
|
||||
q, k = apply_rotary_pos_emb(qkv[:, 0][None], qkv[:, 1][None], cos, sin, unsqueeze_dim=0)
|
||||
rotary = {
|
||||
"input": bf16(qkv),
|
||||
"coord": coords.T.flatten().tolist(),
|
||||
"output": bf16(torch.stack((q.squeeze(0), k.squeeze(0), qkv[:, 2]), dim=1)),
|
||||
}
|
||||
|
||||
result = {
|
||||
"provenance": {
|
||||
"transformers": transformers.__version__,
|
||||
"torch": torch.__version__,
|
||||
"torchvision": torchvision.__version__,
|
||||
"pillow": PIL.__version__,
|
||||
"seed": 8275,
|
||||
"processor": "PixtralImageProcessorPil",
|
||||
"attention": "eager",
|
||||
"dtype": "bfloat16",
|
||||
"rotary_dtype": "float32",
|
||||
},
|
||||
"images": images,
|
||||
"weights": weights,
|
||||
"cases": cases,
|
||||
"rotary": rotary,
|
||||
}
|
||||
path = Path(__file__).parent / "data" / "golden" / "nemotron35_vision.json"
|
||||
path.write_text(json.dumps(result, separators=(",", ":")) + "\n")
|
||||
print(path, path.stat().st_size)
|
||||
@@ -0,0 +1,332 @@
|
||||
// Independent operation checks on the engine's actual AQL queue, against libref. Ordinary host
|
||||
// CTest skips these; the explicit card entry is the hardware gate. No model weights required.
|
||||
#include "rad_test.h"
|
||||
#include "rad_abi.h"
|
||||
#include "rad_device.h"
|
||||
#include "rad_plugin.h"
|
||||
#include <dlfcn.h>
|
||||
#include <memory>
|
||||
#include <random>
|
||||
#define REQUIRE_OK(expr) REQUIRE_EQ((expr), RAD_OK)
|
||||
|
||||
namespace {
|
||||
struct Library {
|
||||
void* h;
|
||||
explicit Library(const char* name) {
|
||||
const char* home = std::getenv("RADIANCE_HOME");
|
||||
h = dlopen((std::string(home ? home : "") + "/kernels/" + name + ".so").c_str(),
|
||||
RTLD_NOW | RTLD_LOCAL);
|
||||
if (!h) throw std::runtime_error(dlerror());
|
||||
}
|
||||
~Library() { dlclose(h); }
|
||||
const RadKernelInfo* get(const char* op, int dim) {
|
||||
auto count = (int (*)())dlsym(h, "rad_kernel_count");
|
||||
auto at = (const RadKernelInfo* (*)(int))dlsym(h, "rad_kernel_at");
|
||||
for (int i = 0; i < count(); ++i) {
|
||||
auto k = at(i);
|
||||
if (std::strcmp(k->op, op)) continue;
|
||||
bool match = true;
|
||||
for (int j = 0; j < k->n_constraints; ++j) {
|
||||
auto& c = k->constraints[j];
|
||||
if (!std::strcmp(c.key, "head_dim") && c.op == RAD_C_EQ && c.ival != dim)
|
||||
match = false;
|
||||
if (!std::strcmp(op, "gemm_nt") &&
|
||||
std::strcmp(k->name, "gemm_bf16_pixtral_patch") &&
|
||||
k->domain == RAD_DOMAIN_DEVICE)
|
||||
match = false;
|
||||
}
|
||||
if (match) return k;
|
||||
}
|
||||
throw std::runtime_error(std::string("missing row ") + op);
|
||||
}
|
||||
};
|
||||
struct Buffer {
|
||||
std::vector<uint8_t> bytes;
|
||||
RadTensor t{};
|
||||
Buffer(uint32_t dt, int rows, int cols, int pitch = 0, int colstride = 1)
|
||||
: bytes(256 + (size_t)rows * (pitch ? pitch : cols * colstride) * (dt == RAD_I32 ? 4 : 2),
|
||||
0x5a) {
|
||||
t.data = bytes.data() + 128;
|
||||
t.dtype = dt;
|
||||
t.rank = cols ? 2 : 1;
|
||||
t.shape[0] = rows;
|
||||
t.stride[0] = pitch ? pitch : (cols ? cols * colstride : 1);
|
||||
if (cols) {
|
||||
t.shape[1] = cols;
|
||||
t.stride[1] = colstride;
|
||||
}
|
||||
}
|
||||
static std::unique_ptr<Buffer> ids(const std::vector<int>& ids, int planes = 1) {
|
||||
auto b = std::make_unique<Buffer>(RAD_I32, (int)ids.size(), 1);
|
||||
b->t.rank = planes == 1 ? 1 : 2;
|
||||
b->t.shape[0] = planes == 1 ? ids.size() : planes;
|
||||
b->t.shape[1] = ids.size() / planes;
|
||||
b->t.stride[0] = planes == 1 ? 1 : ids.size() / planes;
|
||||
b->t.stride[1] = 1;
|
||||
std::memcpy(b->t.data, ids.data(), ids.size() * 4);
|
||||
return b;
|
||||
}
|
||||
void fill(int seed) {
|
||||
std::mt19937 gen(seed);
|
||||
auto* p = (uint16_t*)t.data;
|
||||
for (int64_t r = 0; r < t.shape[0]; ++r)
|
||||
for (int64_t c = 0; c < t.shape[1]; ++c)
|
||||
p[r * t.stride[0] + c * t.stride[1]] =
|
||||
rad_f32_to_bf16(((int)(gen() % 2001) - 1000) / 1700.f);
|
||||
}
|
||||
};
|
||||
RadParam pi(const char* k, int64_t v) {
|
||||
RadParam p{};
|
||||
p.key = k;
|
||||
p.kind = RAD_P_INT;
|
||||
p.ival = v;
|
||||
return p;
|
||||
}
|
||||
RadParam pf(const char* k, double v) {
|
||||
RadParam p{};
|
||||
p.key = k;
|
||||
p.kind = RAD_P_F64;
|
||||
p.dval = v;
|
||||
return p;
|
||||
}
|
||||
RadParam ps(const char* k, const char* v) {
|
||||
RadParam p{};
|
||||
p.key = k;
|
||||
p.kind = RAD_P_STR;
|
||||
p.sval = v;
|
||||
return p;
|
||||
}
|
||||
bool device() {
|
||||
RadDeviceProps p{};
|
||||
return rad_dev_props(0, &p) == RAD_OK && !p.is_host_backend && rad_dev_set(0) == RAD_OK;
|
||||
}
|
||||
void compare(const char* op, std::vector<Buffer*> b, std::vector<RadParam> params, int output,
|
||||
int dim = 128, bool exact = true) {
|
||||
Library ref("libref"), gpu("libr4d");
|
||||
auto kr = ref.get(op, dim), kg = gpu.get(op, dim);
|
||||
RadStream stream = nullptr;
|
||||
REQUIRE_OK(rad_stream_create(&stream, 0));
|
||||
std::vector<RadTensor> ht, dt;
|
||||
std::vector<std::vector<uint8_t>> oracle;
|
||||
std::vector<void*> alloc;
|
||||
for (auto* x : b)
|
||||
oracle.push_back(x->bytes);
|
||||
for (size_t i = 0; i < b.size(); ++i) {
|
||||
auto h = b[i]->t;
|
||||
h.data = oracle[i].data() + 128;
|
||||
ht.push_back(h);
|
||||
void* p = rad_dev_alloc(b[i]->bytes.size(), RAD_MEM_DEVICE);
|
||||
REQUIRE(p);
|
||||
alloc.push_back(p);
|
||||
REQUIRE_OK(rad_memcpy_async(p, b[i]->bytes.data(), b[i]->bytes.size(), stream));
|
||||
auto d = b[i]->t;
|
||||
d.data = (uint8_t*)p + 128;
|
||||
dt.push_back(d);
|
||||
}
|
||||
void* scratch = rad_dev_alloc(256, RAD_MEM_DEVICE);
|
||||
REQUIRE(scratch);
|
||||
RadArgs a{};
|
||||
a.t = ht.data();
|
||||
a.n_t = ht.size();
|
||||
a.p = params.data();
|
||||
a.n_p = params.size();
|
||||
REQUIRE_OK(kr->launch(&a, nullptr));
|
||||
if (kg->init) REQUIRE_OK(kg->init(params.data(), params.size(), 0, 1, &a.instance));
|
||||
a.t = dt.data();
|
||||
a.scratch = scratch;
|
||||
a.scratch_bytes = 256;
|
||||
// Multiple launches on the same queue also check scratch reuse and ordering.
|
||||
REQUIRE_OK(kg->launch(&a, stream));
|
||||
REQUIRE_OK(rad_stream_sync(stream));
|
||||
for (size_t i = 0; i < b.size(); ++i) {
|
||||
std::vector<uint8_t> got(b[i]->bytes.size());
|
||||
REQUIRE_OK(rad_memcpy_async(got.data(), alloc[i], got.size(), stream));
|
||||
REQUIRE_OK(rad_stream_sync(stream));
|
||||
if ((int)i != output) {
|
||||
CHECK(got == b[i]->bytes);
|
||||
continue;
|
||||
}
|
||||
const auto& t = b[i]->t;
|
||||
double err = 0, norm = 0, maxerr = 0;
|
||||
size_t different = 0;
|
||||
auto expected = b[i]->bytes;
|
||||
auto* e = (uint16_t*)(oracle[i].data() + 128);
|
||||
auto* g = (uint16_t*)(got.data() + 128);
|
||||
for (int64_t r = 0; r < t.shape[0]; ++r)
|
||||
for (int64_t c = 0; c < t.shape[1]; ++c) {
|
||||
size_t j = r * t.stride[0] + c * t.stride[1];
|
||||
double x = rad_bf16_to_f32(e[j]), y = rad_bf16_to_f32(g[j]);
|
||||
REQUIRE(std::isfinite(y));
|
||||
err += (x - y) * (x - y);
|
||||
norm += x * x;
|
||||
maxerr = std::max(maxerr, std::abs(x - y));
|
||||
different += e[j] != g[j];
|
||||
std::memcpy(expected.data() + 128 + 2 * j, got.data() + 128 + 2 * j, 2);
|
||||
}
|
||||
CHECK(got == expected); // All padding and both 128-byte canaries are unchanged.
|
||||
const double rel = std::sqrt(err / std::max(norm, 1e-30));
|
||||
fprintf(stderr, " %s dim=%d relL2=%.9g maxAbs=%.9g bf16_differences=%zu\n", op, dim, rel,
|
||||
maxerr, different);
|
||||
if (exact)
|
||||
CHECK_EQ(different, (size_t)0);
|
||||
else {
|
||||
CHECK(rel <= 0.01);
|
||||
CHECK(maxerr <= 0.015);
|
||||
}
|
||||
}
|
||||
// Invalid dimensions fail synchronously before writing any operand.
|
||||
std::vector<uint8_t> before(b[output]->bytes.size()), after(before.size());
|
||||
REQUIRE_OK(rad_memcpy_async(before.data(), alloc[output], before.size(), stream));
|
||||
REQUIRE_OK(rad_stream_sync(stream));
|
||||
auto invalid = dt;
|
||||
invalid[0].shape[0] = 0;
|
||||
a.t = invalid.data();
|
||||
CHECK(kg->launch(&a, stream) < 0);
|
||||
invalid = dt;
|
||||
invalid[0].stride[1] = INT64_MAX;
|
||||
a.t = invalid.data();
|
||||
CHECK(kg->launch(&a, stream) < 0);
|
||||
if (kg->scratch) {
|
||||
a.t = dt.data();
|
||||
a.scratch_bytes = 0;
|
||||
CHECK_EQ(kg->launch(&a, stream), RAD_E_SCRATCH);
|
||||
}
|
||||
REQUIRE_OK(rad_memcpy_async(after.data(), alloc[output], after.size(), stream));
|
||||
REQUIRE_OK(rad_stream_sync(stream));
|
||||
CHECK(before == after);
|
||||
if (kg->fini) kg->fini(a.instance);
|
||||
for (void* p : alloc)
|
||||
rad_dev_free(p, RAD_MEM_DEVICE);
|
||||
rad_dev_free(scratch, RAD_MEM_DEVICE);
|
||||
rad_stream_destroy(stream);
|
||||
}
|
||||
}
|
||||
TEST(nemotron35_device_position_scale_boundary_and_row_grid_tail) {
|
||||
if (!device()) SKIP("explicit R9700 card run required");
|
||||
for (int M : {4, 65539}) {
|
||||
Buffer x(RAD_BF16, M, 5, 19, 2);
|
||||
x.fill(3);
|
||||
std::vector<int> p(M);
|
||||
for (int i = 0; i < M; ++i)
|
||||
p[i] = i % 4 == 0 ? 0 : i % 4 == 1 ? 16383 : i % 4 == 2 ? 16384 : 32767;
|
||||
auto pos = Buffer::ids(p);
|
||||
compare("position_scale", {&x, pos.get()},
|
||||
{pi("M", M + 128), pi("n", 5), pi("original", 16384), pf("beta", 0.1),
|
||||
ps("dtype", "bf16")},
|
||||
0);
|
||||
}
|
||||
}
|
||||
TEST(nemotron35_device_rotary_pitches_active_rows_and_reference_seams) {
|
||||
if (!device()) SKIP("explicit R9700 card run required");
|
||||
for (bool pix : {false, true})
|
||||
for (int D : {64, 128}) {
|
||||
const int M = 17, H = 4, K = pix ? 4 : 1;
|
||||
Buffer x(RAD_BF16, M, (H + 2 * K) * D, (H + 2 * K) * D * 2 + 13, 2);
|
||||
x.fill(44);
|
||||
std::vector<int> p(pix ? 2 * M : M);
|
||||
for (size_t i = 0; i < p.size(); ++i)
|
||||
p[i] = pix ? (int)(i * 7 % 110)
|
||||
: i % 4 == 0 ? 0
|
||||
: i % 4 == 1 ? 16383
|
||||
: i % 4 == 2 ? 16384
|
||||
: 32767;
|
||||
auto pos = Buffer::ids(p, pix ? 2 : 1);
|
||||
std::vector<RadParam> pars = {pi("M", 32),
|
||||
pi("head_dim", D),
|
||||
pi("n_head", H),
|
||||
pi("n_head_kv", K),
|
||||
pf("theta", pix ? 10000 : 1000000),
|
||||
ps("dtype", "bf16")};
|
||||
if (!pix) {
|
||||
pars.push_back(pf("yarn_factor", 16));
|
||||
pars.push_back(pf("yarn_low", 1));
|
||||
pars.push_back(pf("yarn_high", 27));
|
||||
pars.push_back(pf("yarn_magnitude", 1));
|
||||
}
|
||||
compare(pix ? "pixtral_rope" : "ministral_rope", {&x, pos.get()}, pars, 0, D, true);
|
||||
}
|
||||
}
|
||||
TEST(nemotron35_device_merger_ragged_rectangular_images) {
|
||||
if (!device()) SKIP("explicit R9700 card run required");
|
||||
const int M = 32, N = 37;
|
||||
Buffer x(RAD_BF16, M, N, 91, 2), y(RAD_BF16, M / 4, N * 4, 307, 2);
|
||||
x.fill(91);
|
||||
std::vector<int> p(4 * M);
|
||||
int off = 0;
|
||||
for (auto hw : {std::pair{2, 4}, std::pair{4, 6}}) {
|
||||
auto [h, w] = hw;
|
||||
for (int j = 0; j < h * w; ++j) {
|
||||
p[off + j] = j / w;
|
||||
p[M + off + j] = j % w;
|
||||
p[2 * M + off + j] = h;
|
||||
p[3 * M + off + j] = w;
|
||||
}
|
||||
off += h * w;
|
||||
}
|
||||
auto pos = Buffer::ids(p, 4);
|
||||
compare("pixtral_merge", {&x, pos.get(), &y},
|
||||
{pi("M", 64), pi("n", N), pi("merge", 2), ps("dtype", "bf16")}, 2);
|
||||
}
|
||||
TEST(nemotron35_device_attention_ragged_pitches_and_partial_tiles) {
|
||||
if (!device()) SKIP("explicit R9700 card run required");
|
||||
for (int D : {64, 128})
|
||||
for (int G : {1, 3, 4})
|
||||
for (int M : {1, 17, 73, 129}) {
|
||||
const int H = G * 2;
|
||||
Buffer q(RAD_BF16, M, H * D, H * D + 11), k(RAD_BF16, M, 2 * D, 2 * D + 7),
|
||||
v(RAD_BF16, M, 2 * D, 2 * D + 19), o(RAD_BF16, M, H * D, H * D + 5);
|
||||
q.fill(17);
|
||||
k.fill(35);
|
||||
v.fill(83);
|
||||
std::vector<int> cu =
|
||||
M > 17 ? std::vector<int>{0, 1, 17, M} : std::vector<int>{0, M};
|
||||
auto c = Buffer::ids(cu);
|
||||
compare("embed_attn", {&q, &k, &v, c.get(), &o},
|
||||
{pi("M", M + 256), pi("head_dim", D), pi("gqa", G), pi("causal", 0),
|
||||
pi("max_seqlen", M), ps("dtype", "bf16")},
|
||||
4, D, false);
|
||||
}
|
||||
}
|
||||
TEST(nemotron35_device_1b_exact_attention_head_geometry) {
|
||||
if (!device()) SKIP("explicit R9700 card run required");
|
||||
const int M = 49, D = 128, H = 24, G = 3;
|
||||
Buffer q(RAD_BF16, M, H * D, H * D + 13), k(RAD_BF16, M, 8 * D, 8 * D + 7),
|
||||
v(RAD_BF16, M, 8 * D, 8 * D + 11), o(RAD_BF16, M, H * D, H * D + 5);
|
||||
q.fill(19);
|
||||
k.fill(37);
|
||||
v.fill(85);
|
||||
auto cu = Buffer::ids({0, 1, 18, M});
|
||||
compare("embed_attn", {&q, &k, &v, cu.get(), &o},
|
||||
{pi("M", M), pi("head_dim", D), pi("gqa", G), pi("causal", 0), pi("max_seqlen", 31),
|
||||
ps("dtype", "bf16")},
|
||||
4, D, false);
|
||||
}
|
||||
TEST(nemotron35_device_combined_tokens_exceed_context_without_splitting_segments) {
|
||||
if (!device()) SKIP("explicit R9700 card run required");
|
||||
const int M = 32770, D = 64;
|
||||
Buffer q(RAD_BF16, M, D, D + 3), k(RAD_BF16, M, D, D + 5), v(RAD_BF16, M, D, D + 7),
|
||||
o(RAD_BF16, M, D, D + 11);
|
||||
q.fill(32);
|
||||
k.fill(53);
|
||||
v.fill(81);
|
||||
std::vector<int> cu(M + 1);
|
||||
for (int i = 0; i <= M; ++i)
|
||||
cu[i] = i;
|
||||
auto c = Buffer::ids(cu);
|
||||
compare("embed_attn", {&q, &k, &v, c.get(), &o},
|
||||
{pi("M", 65536), pi("head_dim", D), pi("gqa", 1), pi("causal", 0), pi("max_seqlen", 1),
|
||||
ps("dtype", "bf16")},
|
||||
4, D, true);
|
||||
}
|
||||
TEST(nemotron35_device_patch_projection_588_tail_and_pitched_rows) {
|
||||
if (!device()) SKIP("explicit R9700 card run required");
|
||||
for (int M : {1, 17, 65})
|
||||
for (int N : {37, 64, 1024}) {
|
||||
Buffer a(RAD_BF16, M, 588, 599), w(RAD_BF16, N, 588, 607), y(RAD_BF16, M, N, N + 5);
|
||||
a.fill(17);
|
||||
w.fill(91);
|
||||
compare("gemm_nt", {&a, &w, &y},
|
||||
{pi("M", 128), pi("N", N), pi("K", 588), ps("dtype", "bf16")}, 2, 128, true);
|
||||
}
|
||||
}
|
||||
RAD_TEST_MAIN()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,247 @@
|
||||
// Real AQL GEMM checks across registry, grid and 32-bit activation-offset boundaries.
|
||||
// Sparse dyadic inputs have an exact independent four-term oracle, including split-K.
|
||||
#include "rad_test.h"
|
||||
#include "rad_abi.h"
|
||||
#include "rad_device.h"
|
||||
#include "device/device.h"
|
||||
#include "plugin/registry.h"
|
||||
#include "rad_plugin.h"
|
||||
#include <dlfcn.h>
|
||||
#include <array>
|
||||
#include <climits>
|
||||
|
||||
namespace {
|
||||
bool device() {
|
||||
RadDeviceProps p{};
|
||||
return rad_dev_props(0, &p) == RAD_OK && !p.is_host_backend && rad_dev_set(0) == RAD_OK;
|
||||
}
|
||||
struct Library {
|
||||
void* h;
|
||||
Library() {
|
||||
const char* home = std::getenv("RADIANCE_HOME");
|
||||
h = dlopen((std::string(home ? home : "") + "/kernels/libr4d.so").c_str(),
|
||||
RTLD_NOW | RTLD_LOCAL);
|
||||
if (!h) throw std::runtime_error(dlerror());
|
||||
}
|
||||
~Library() { dlclose(h); }
|
||||
const RadKernelInfo* row(const char* name) {
|
||||
auto count = (int (*)())dlsym(h, "rad_kernel_count");
|
||||
auto at = (const RadKernelInfo* (*)(int))dlsym(h, "rad_kernel_at");
|
||||
for (int i = 0; i < count(); ++i)
|
||||
if (!std::strcmp(at(i)->name, name)) return at(i);
|
||||
throw std::runtime_error(name);
|
||||
}
|
||||
};
|
||||
RadTensor tensor(void* p, int64_t rows, int64_t cols) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = RAD_BF16;
|
||||
t.rank = 2;
|
||||
t.shape[0] = rows;
|
||||
t.shape[1] = cols;
|
||||
t.stride[0] = cols;
|
||||
t.stride[1] = 1;
|
||||
return t;
|
||||
}
|
||||
RadParam param(const char* k, int v) {
|
||||
RadParam p{};
|
||||
p.key = k;
|
||||
p.kind = RAD_P_INT;
|
||||
p.ival = v;
|
||||
return p;
|
||||
}
|
||||
float av(int64_t r, int j) {
|
||||
return (float)((r * (j + 1) + 3 * j) % 29 - 14) / 16;
|
||||
}
|
||||
float wv(int n, int j) {
|
||||
return (float)((n * (j + 2) + j) % 17 - 8) / 8;
|
||||
}
|
||||
void run(int M, int N, int K, const std::vector<std::array<int, 4>>& configs) {
|
||||
Library lib;
|
||||
RadStream s = nullptr;
|
||||
REQUIRE_EQ(rad_stream_create(&s, 0), RAD_OK);
|
||||
const size_t abytes = (size_t)M * K * 2, ybytes = (size_t)M * N * 2;
|
||||
void* ap = rad_dev_alloc(abytes + 256, RAD_MEM_DEVICE);
|
||||
void* wp = rad_dev_alloc((size_t)N * K * 2, RAD_MEM_DEVICE);
|
||||
void* yp = rad_dev_alloc(ybytes + 256, RAD_MEM_DEVICE);
|
||||
REQUIRE(ap && wp && yp);
|
||||
std::vector<uint8_t> guard(128, 0x5a);
|
||||
for (auto pair : {std::pair<void*, size_t>{ap, abytes}, {yp, ybytes}}) {
|
||||
REQUIRE_EQ(rad_memcpy_async(pair.first, guard.data(), 128, s), RAD_OK);
|
||||
REQUIRE_EQ(rad_memcpy_async((uint8_t*)pair.first + 128 + pair.second, guard.data(), 128, s),
|
||||
RAD_OK);
|
||||
}
|
||||
const int indices[] = {0, 1, 32, K - 1};
|
||||
constexpr int block = 64;
|
||||
std::vector<uint16_t> a((size_t)block * K, 0), w((size_t)N * K, 0);
|
||||
for (int n = 0; n < N; ++n)
|
||||
for (int j = 0; j < 4; ++j)
|
||||
w[(size_t)n * K + indices[j]] = rad_f32_to_bf16(wv(n, j));
|
||||
REQUIRE_EQ(rad_memcpy_async(wp, w.data(), w.size() * 2, s), RAD_OK);
|
||||
for (int64_t r = 0; r < M; r += block) {
|
||||
int rows = (int)std::min<int64_t>(block, M - r);
|
||||
for (int i = 0; i < rows; ++i)
|
||||
for (int j = 0; j < 4; ++j)
|
||||
a[(size_t)i * K + indices[j]] = rad_f32_to_bf16(av(r + i, j));
|
||||
REQUIRE_EQ(
|
||||
rad_memcpy_async((uint8_t*)ap + 128 + r * K * 2, a.data(), (size_t)rows * K * 2, s),
|
||||
RAD_OK);
|
||||
REQUIRE_EQ(rad_stream_sync(s),
|
||||
RAD_OK); // keep the pageable staging buffer alive until consumed
|
||||
}
|
||||
std::vector<uint16_t> got((size_t)M * N), expected(got.size());
|
||||
for (int64_t r = 0; r < M; ++r)
|
||||
for (int n = 0; n < N; ++n) {
|
||||
float sum = 0;
|
||||
for (int j = 0; j < 4; ++j)
|
||||
sum += av(r, j) * wv(n, j);
|
||||
expected[(size_t)r * N + n] = rad_f32_to_bf16(sum);
|
||||
}
|
||||
RadTensor t[] = {tensor((uint8_t*)ap + 128, M, K), tensor(wp, N, K),
|
||||
tensor((uint8_t*)yp + 128, M, N)};
|
||||
for (auto c : configs) {
|
||||
// c = tiled variant (0 for skinny), split count, row tiles, column waves.
|
||||
const auto* k = lib.row(c[0] ? "gemm_bf16_nt_tiled" : "gemm_bf16_nt_m64");
|
||||
RadParam p[] = {param("sk", c[1]), param("mb", c[2]), param("wv", c[3]),
|
||||
param("tile", c[0])};
|
||||
RadArgs args{};
|
||||
args.t = t;
|
||||
args.n_t = 3;
|
||||
args.p = p;
|
||||
args.n_p = 4;
|
||||
REQUIRE_EQ(k->launch(&args, s), RAD_OK);
|
||||
REQUIRE_EQ(rad_stream_sync(s), RAD_OK);
|
||||
REQUIRE_EQ(rad_memcpy_async(got.data(), t[2].data, ybytes, s), RAD_OK);
|
||||
REQUIRE_EQ(rad_stream_sync(s), RAD_OK);
|
||||
size_t bad = 0;
|
||||
while (bad < got.size() && got[bad] == expected[bad])
|
||||
++bad;
|
||||
fprintf(stderr, " %s M=%d N=%d K=%d tile=%d sk=%d mb=%d wv=%d first_mismatch=%zu/%zu\n",
|
||||
k->name, M, N, K, c[0], c[1], c[2], c[3], bad, got.size());
|
||||
CHECK_EQ(bad, got.size());
|
||||
for (auto pair : {std::pair<void*, size_t>{ap, abytes}, {yp, ybytes}}) {
|
||||
std::vector<uint8_t> before(128), after(128);
|
||||
REQUIRE_EQ(rad_memcpy_async(before.data(), pair.first, 128, s), RAD_OK);
|
||||
REQUIRE_EQ(
|
||||
rad_memcpy_async(after.data(), (uint8_t*)pair.first + 128 + pair.second, 128, s),
|
||||
RAD_OK);
|
||||
REQUIRE_EQ(rad_stream_sync(s), RAD_OK);
|
||||
CHECK(before == guard);
|
||||
CHECK(after == guard);
|
||||
}
|
||||
}
|
||||
rad_dev_free(ap, RAD_MEM_DEVICE);
|
||||
rad_dev_free(wp, RAD_MEM_DEVICE);
|
||||
rad_dev_free(yp, RAD_MEM_DEVICE);
|
||||
rad_stream_destroy(s);
|
||||
}
|
||||
}
|
||||
TEST(bf16_capacity_preserves_existing_kernel_selection) {
|
||||
if (!device()) SKIP("requires real device");
|
||||
rad::Registry r;
|
||||
REQUIRE_EQ(r.load_dir(home() + "/kernels", {"libr4d", "libref"}), RAD_OK);
|
||||
// Nomic/Qwen projection widths, a narrow output, and a vision-style K tail. Enlarging
|
||||
// the row range must preserve the old small/prefill ladder, including its seam values.
|
||||
struct Case { int m, n, k; const char* name; };
|
||||
const Case cases[] = {
|
||||
{1, 2304, 768, "gemm_bf16_nt_m16"},
|
||||
{16, 3584, 1024, "gemm_bf16_nt_m16"},
|
||||
{17, 3584, 1024, "gemm_bf16_nt_m64"},
|
||||
{64, 2304, 768, "gemm_bf16_nt_m64"},
|
||||
{65, 2304, 768, "gemm_bf16_nt_tiled"},
|
||||
{511, 768, 3072, "gemm_bf16_nt_tiled"},
|
||||
{65536, 1024, 3584, "gemm_bf16_nt_tiled"},
|
||||
{65, 17, 768, "gemm_bf16_nt_m64"},
|
||||
{65, 768, 1040, "gemm_bf16_nt_m64"},
|
||||
};
|
||||
for (const auto& c : cases) {
|
||||
rad::Geometry g;
|
||||
g.set_i("M", c.m);
|
||||
g.set_i("N", c.n);
|
||||
g.set_i("K", c.k);
|
||||
g.set_s("dtype", "bf16");
|
||||
const auto* row = r.select("gemm_nt", g, RAD_DOMAIN_DEVICE);
|
||||
REQUIRE(row);
|
||||
CHECK_EQ(std::string(row->info->name), c.name);
|
||||
}
|
||||
}
|
||||
TEST(bf16_capacity_old_boundary_and_ragged_tails) {
|
||||
if (!device()) SKIP("requires real device");
|
||||
for (int m : {65536, 65537, 131073})
|
||||
run(m, 129, 64, {{0, 1, 1, 1}, {0, 4, 3, 2}, {1, 1, 1, 1}, {2, 4, 1, 1}});
|
||||
}
|
||||
TEST(bf16_capacity_grid_row_rebase) {
|
||||
if (!device()) SKIP("requires real device");
|
||||
run(65535 * 16 + 1, 17, 64, {{0, 1, 1, 1}});
|
||||
}
|
||||
TEST(bf16_capacity_unsigned_activation_offset_rebase) {
|
||||
if (!device()) SKIP("requires real device");
|
||||
// >2^32 BF16 elements (~8 GiB). Host staging stays bounded at 8 MiB.
|
||||
run(65539, 129, 65536, {{0, 4, 1, 1}, {1, 4, 1, 1}, {2, 1, 1, 1}});
|
||||
}
|
||||
TEST(bf16_capacity_preserves_chained_decode_dependencies) {
|
||||
if (!device()) SKIP("requires real device");
|
||||
Library lib;
|
||||
const auto* k = lib.row("gemm_bf16_nt_m64");
|
||||
constexpr int m = 17, n = 64;
|
||||
std::vector<uint16_t> x(m * n), w(n * n, 0), got(m * n);
|
||||
for (int i = 0; i < m * n; ++i)
|
||||
x[i] = rad_f32_to_bf16((float)(i % 23 - 11) / 16);
|
||||
for (int i = 0; i < n; ++i)
|
||||
w[i * n + i] = rad_f32_to_bf16(2.f);
|
||||
void* xp = rad_dev_alloc(x.size() * 2, RAD_MEM_DEVICE);
|
||||
void* wp = rad_dev_alloc(w.size() * 2, RAD_MEM_DEVICE);
|
||||
void* yp = rad_dev_alloc(x.size() * 2, RAD_MEM_DEVICE);
|
||||
void* zp = rad_dev_alloc(x.size() * 2, RAD_MEM_DEVICE);
|
||||
REQUIRE(xp && wp && yp && zp);
|
||||
RadStream stream = nullptr;
|
||||
REQUIRE_EQ(rad_stream_create(&stream, 0), RAD_OK);
|
||||
REQUIRE_EQ(rad_memcpy_async(xp, x.data(), x.size() * 2, stream), RAD_OK);
|
||||
REQUIRE_EQ(rad_memcpy_async(wp, w.data(), w.size() * 2, stream), RAD_OK);
|
||||
RadParam p[] = {param("chain", 1), param("mb", 1), param("sk", 4), param("wv", 1)};
|
||||
RadTensor first[] = {tensor(xp, m, n), tensor(wp, n, n), tensor(yp, m, n)};
|
||||
RadTensor second[] = {tensor(yp, m, n), tensor(wp, n, n), tensor(zp, m, n)};
|
||||
RadArgs a{};
|
||||
a.n_t = 3;
|
||||
a.p = p;
|
||||
a.n_p = 4;
|
||||
rad_dev_chain_infer(1);
|
||||
REQUIRE_EQ(rad_dev_chain_enabled(), 1);
|
||||
for (int repeat = 0; repeat < 8; ++repeat) {
|
||||
a.t = first;
|
||||
REQUIRE_EQ(k->launch(&a, stream), RAD_OK);
|
||||
a.t = second;
|
||||
REQUIRE_EQ(k->launch(&a, stream), RAD_OK);
|
||||
}
|
||||
REQUIRE_EQ(rad_stream_sync(stream), RAD_OK);
|
||||
rad_dev_chain_infer(0);
|
||||
REQUIRE_EQ(rad_memcpy_async(got.data(), zp, got.size() * 2, stream), RAD_OK);
|
||||
REQUIRE_EQ(rad_stream_sync(stream), RAD_OK);
|
||||
for (size_t i = 0; i < got.size(); ++i)
|
||||
CHECK_EQ(got[i], rad_f32_to_bf16(4 * rad_bf16_to_f32(x[i])));
|
||||
for (void* v : {xp, wp, yp, zp})
|
||||
rad_dev_free(v, RAD_MEM_DEVICE);
|
||||
rad_stream_destroy(stream);
|
||||
}
|
||||
TEST(bf16_capacity_invalid_and_multilaunch_chain_fail_before_issue) {
|
||||
if (!device()) SKIP("requires real device");
|
||||
Library lib;
|
||||
RadTensor t[] = {tensor((void*)0x1000, 65539, 65536), tensor((void*)0x2000, 129, 65536),
|
||||
tensor((void*)0x3000, 65539, 129)};
|
||||
RadParam p[] = {param("chain", 1), param("mb", 1), param("sk", 1), param("wv", 1)};
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 3;
|
||||
a.p = p;
|
||||
a.n_p = 4;
|
||||
CHECK_EQ(lib.row("gemm_bf16_nt_m64")->launch(&a, nullptr), RAD_E_UNSUPPORTED);
|
||||
p[0].ival = 0;
|
||||
t[0].shape[0] = t[2].shape[0] = (int64_t)INT_MAX + 1;
|
||||
CHECK_EQ(lib.row("gemm_bf16_nt_m64")->launch(&a, nullptr), RAD_E_SHAPE);
|
||||
CHECK_EQ(lib.row("gemm_bf16_nt_tiled")->launch(&a, nullptr), RAD_E_SHAPE);
|
||||
t[0] = tensor((void*)0x1000, 65, 65536);
|
||||
t[2] = tensor((void*)0x3000, 65, 65536);
|
||||
CHECK_EQ(lib.row("gemm_bf16_nt_m64")->launch(&a, nullptr), RAD_E_SHAPE); // W span exceeds u32
|
||||
CHECK_EQ(lib.row("gemm_bf16_nt_tiled")->launch(&a, nullptr), RAD_E_SHAPE);
|
||||
}
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,53 @@
|
||||
/* Host-only coverage of the BF16 row launch plan, without allocating multi-gigabyte matrices. */
|
||||
#include "rad_test.h"
|
||||
#include "../libr4d/r4d_bf16_gemm_rows.h"
|
||||
|
||||
TEST(bf16_rows_deployment_budget_is_not_a_kernel_limit) {
|
||||
for (int64_t m :
|
||||
{65536ll, 65537ll, 131072ll, 131073ll, 240000ll, 500000ll, 524288ll, (long long)INT_MAX}) {
|
||||
CHECK(r4d_bf16_gemm_chunk_rows(m, 128, 4096, 128, 128) > 0);
|
||||
}
|
||||
CHECK_EQ(r4d_bf16_gemm_chunk_rows(131072, 128, 4096, 128, 128), 131072);
|
||||
CHECK_EQ(r4d_bf16_gemm_chunk_rows(500000, 128, 4096, 128, 128), 500000);
|
||||
}
|
||||
|
||||
TEST(bf16_rows_rebase_activation_spans_past_32_bits) {
|
||||
constexpr int64_t m = 500000, n = 128, k = 12288;
|
||||
CHECK(m * k > UINT32_MAX);
|
||||
for (int tile : {16, 64, 128}) {
|
||||
const int chunk = r4d_bf16_gemm_chunk_rows(m, n, k, tile, 128);
|
||||
CHECK(chunk > 0 && chunk < m);
|
||||
CHECK_EQ(chunk % tile, 0);
|
||||
CHECK((int64_t)chunk * k <= UINT32_MAX);
|
||||
CHECK((int64_t)(chunk + tile) * k > UINT32_MAX);
|
||||
CHECK_EQ((m + chunk - 1) / chunk, 2);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(bf16_rows_launch_grid_and_flattened_ids_are_bounded) {
|
||||
CHECK_EQ(r4d_bf16_gemm_chunk_rows(2000000, 1, 16, 16, 16), 65535 * 16);
|
||||
constexpr int64_t n = 67108800, k = 64;
|
||||
const int chunk = r4d_bf16_gemm_chunk_rows(INT_MAX, n, k, 64, 64);
|
||||
const int64_t gx = (n + 63) / 64, gy = (chunk + 63ll) / 64;
|
||||
CHECK(chunk > 0);
|
||||
CHECK(gx * gy <= UINT32_MAX);
|
||||
CHECK(gx * (gy + 1) > UINT32_MAX);
|
||||
}
|
||||
|
||||
TEST(bf16_rows_keep_real_dimension_and_weight_limits) {
|
||||
for (int64_t bad : {-1ll, 0ll, (long long)INT_MAX + 1}) {
|
||||
CHECK_EQ(r4d_bf16_gemm_chunk_rows(bad, 128, 64, 64, 64), 0);
|
||||
CHECK_EQ(r4d_bf16_gemm_chunk_rows(1000, bad, 64, 64, 64), 0);
|
||||
CHECK_EQ(r4d_bf16_gemm_chunk_rows(1000, 128, bad, 64, 64), 0);
|
||||
}
|
||||
CHECK_EQ(r4d_bf16_gemm_chunk_rows(1, 1, 17, 16, 16), 0);
|
||||
CHECK_EQ(r4d_bf16_gemm_chunk_rows(1, 1, 16, 0, 16), 0);
|
||||
CHECK_EQ(r4d_bf16_gemm_chunk_rows(1, 1, 16, 16, 0), 0);
|
||||
// W is not row-chunked: the largest legal number of weight rows is shape-dependent.
|
||||
CHECK(r4d_bf16_gemm_chunk_rows(1, UINT32_MAX / 64, 64, 64, 64) > 0);
|
||||
CHECK_EQ(r4d_bf16_gemm_chunk_rows(1, UINT32_MAX / 64 + 1, 64, 64, 64), 0);
|
||||
// Even when one tile exceeds the offset span, clamping serves a smaller row chunk.
|
||||
CHECK_EQ(r4d_bf16_gemm_chunk_rows(100, 1, INT_MAX - 15, 64, 16), 2);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+13
-1
@@ -1059,6 +1059,7 @@ TEST(op_vocabulary) {
|
||||
"sam_attn",
|
||||
/* A pipelined prefill's first-piece KV length, a device length less a device offset. */
|
||||
"sub_i32",
|
||||
"position_scale", "embed_attn", "ministral_rope", "pixtral_rope", "pixtral_merge",
|
||||
};
|
||||
for (const char* op : kOps) {
|
||||
if (!kern(op)) fprintf(stderr, " missing op '%s'\n", op);
|
||||
@@ -9604,6 +9605,15 @@ struct Geo {
|
||||
#define G(op, key, r, body) { op, key, r, [](A& a, int64_t R) { body; } }
|
||||
std::vector<Geo> geometries() {
|
||||
return {
|
||||
G("position_scale", "M", 3, a.i("M", R).i("n", 8).i("original", 16384)
|
||||
.d("beta", 0.1).s("dtype", "f32")),
|
||||
G("embed_attn", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head", 2).i("gqa", 2)
|
||||
.i("causal", 0).s("dtype", "f32")),
|
||||
G("ministral_rope", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head", 2)
|
||||
.i("n_head_kv", 1).d("theta", 1e6).s("dtype", "f32")),
|
||||
G("pixtral_rope", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head", 2)
|
||||
.d("theta", 10000.0).s("dtype", "f32")),
|
||||
G("pixtral_merge", "M", 4, a.i("M", R).i("n", 8).i("merge", 2).s("dtype", "f32")),
|
||||
G("rmsnorm", "M", 3, a.i("M", R).i("n", 8).d("eps", 1e-6).s("dtype", "f32")),
|
||||
G("rmsnorm_p", "M", 3, a.i("M", R).i("n", 8).d("eps", 1e-6).s("dtype", "f32")),
|
||||
G("rmsnorm_add", "M", 3, a.i("M", R).i("n", 8).d("eps", 1e-6).s("dtype", "f32")),
|
||||
@@ -9949,8 +9959,10 @@ std::vector<Geo> geometries() {
|
||||
* cannot be drawn; ref_shapes.cpp says why). The sweeps skip them; their hand cases above cover
|
||||
* them. */
|
||||
bool undrawable(const char* op) {
|
||||
// Complete raster grids need the hand-built cases in nemotron35_test, not random indices.
|
||||
return !std::strcmp(op, "givens_dense_quant") || !std::strcmp(op, "givens_rotate") ||
|
||||
!std::strcmp(op, "sample_merge_topk") || !std::strcmp(op, "gather_rows2");
|
||||
!std::strcmp(op, "sample_merge_topk") || !std::strcmp(op, "gather_rows2") ||
|
||||
!std::strcmp(op, "pixtral_merge");
|
||||
}
|
||||
|
||||
uint32_t lcg(uint32_t* s) { *s = *s * 1664525u + 1013904223u; return *s >> 8; }
|
||||
|
||||
@@ -6188,6 +6188,33 @@ TEST(an_embedding_input_longer_than_the_checkpoint_interval_is_admitted_whole) {
|
||||
CHECK(whole);
|
||||
}
|
||||
|
||||
/* The shared context check serves every embedding architecture. Exact-limit inputs need no
|
||||
* following generation slot, while generation keeps that slot and both refuse an overflow. */
|
||||
TEST(the_context_boundary_distinguishes_embeddings_from_generation) {
|
||||
for (bool embed : {false, true}) {
|
||||
for (int length : {169, 170, 171}) {
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/4096, /*states=*/64, /*max_tok=*/512, /*max_ctx=*/170,
|
||||
/*windowed=*/false, /*linear=*/false);
|
||||
REQUIRE_EQ(f.start(), RAD_OK);
|
||||
auto r = f.request(length, 1);
|
||||
r->embed = embed;
|
||||
const uint64_t id = f.add(std::move(r));
|
||||
REQUIRE(id != 0);
|
||||
const RadBatch* batch = f.sch.step();
|
||||
const bool fits = length < 170 || (embed && length == 170);
|
||||
if (fits) {
|
||||
REQUIRE(batch != nullptr);
|
||||
CHECK_EQ(batch->n_tok, length);
|
||||
CHECK_EQ((int)f.sch.find(id)->state, (int)ReqState::Running);
|
||||
} else {
|
||||
CHECK(batch == nullptr);
|
||||
CHECK_EQ((int)f.sch.find(id)->state, (int)ReqState::Failed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== speculation gates */
|
||||
/* A request that may not speculate (a constraining grammar that cannot snapshot) gets no draft
|
||||
* from either drafter: set_draft takes nothing and prompt lookup proposes nothing, though its
|
||||
|
||||
@@ -95,7 +95,7 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
|
||||
{ "gemma3", "" }, { "gemma4", "" },
|
||||
{ "gemma4", "compressed-tensors" }, { "glm5next", "" },
|
||||
{ "hyv3", "" }, { "hyv3", "fp8" }, { "hyv3", "gguf_ftype_15" },
|
||||
{ "lfm2", "" }, { "llama", "" },
|
||||
{ "lfm2", "" }, { "llama", "" }, { "mistral3", "" },
|
||||
{ "llama", "fp8_e4m3" }, { "nomicbert", "" }, { "qwen35", "" },
|
||||
{ "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" },
|
||||
{ "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" },
|
||||
|
||||
Reference in new issue
Block a user