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
+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