Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions .github/workflows/validate_wrapper.yml
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,7 @@ jobs:
run: >-
cmake --build build/wrapper-contract --target
llamadart_owner_api_test llamadart_owner_reentrancy_test
llamadart_model_fd_test llamadart_threadpool_test
llamadart_file_sha256_test llamadart_model_fd_test llamadart_threadpool_test
llamadart_grammar_top_k_test
llamadart_f16_dot_accumulation_test
llamadart_speculative_api_test
Expand Down Expand Up @@ -657,7 +657,7 @@ jobs:
cmake --build --preset windows-x64-full --target
llamadart_barrier_test
llamadart_owner_api_test llamadart_owner_reentrancy_test
llamadart_model_fd_test
llamadart_file_sha256_test llamadart_model_fd_test
llamadart_build_identity_test llamadart_upstream_abi_test
llamadart_cancel_flag_test
llamadart_exit_teardown_test
Expand All @@ -676,7 +676,7 @@ jobs:
$wrapperDir = (Resolve-Path build/wx64).Path
$upstreamDir = (Resolve-Path build/wx64/bin).Path
$env:PATH = "$wrapperDir;$upstreamDir;$env:PATH"
ctest --test-dir build/wx64 -R "owner_api|owner_reentrant|model_fd|barrier|build_identity|upstream_abi|cancel_flag|vocabulary|reasoning-budget|vulkan_device_info|device_memory|fit_api|tts_api|tts_types|asr_stream|tts_stream|image_token_limit" --timeout 120 --output-on-failure
ctest --test-dir build/wx64 -R "owner_api|owner_reentrant|file_sha256|model_fd|barrier|build_identity|upstream_abi|cancel_flag|vocabulary|reasoning-budget|vulkan_device_info|device_memory|fit_api|tts_api|tts_types|asr_stream|tts_stream|image_token_limit" --timeout 120 --output-on-failure
- name: Validate wrapper exports
shell: pwsh
run: |
Expand Down Expand Up @@ -734,7 +734,7 @@ jobs:
- name: Build the exit teardown test
run: >-
cmake --build ${{ matrix.build_dir }} --target
llamadart_owner_api_test llamadart_owner_reentrancy_test llamadart_model_fd_test llamadart_threadpool_test llamadart_exit_teardown_test llamadart_image_token_limit_test llamadart_fit_api_test llamadart_device_memory_test
llamadart_owner_api_test llamadart_owner_reentrancy_test llamadart_file_sha256_test llamadart_model_fd_test llamadart_threadpool_test llamadart_exit_teardown_test llamadart_image_token_limit_test llamadart_fit_api_test llamadart_device_memory_test
llamadart_grammar_top_k_test
llamadart_build_identity_test llamadart_cancel_flag_test
llamadart_f16_dot_accumulation_test
Expand All @@ -750,7 +750,7 @@ jobs:
# the Metal library, which takes most of a minute.
- name: Run the exit teardown scenarios
run: >-
ctest --test-dir ${{ matrix.build_dir }} -R "owner_|model_fd|threadpool|exit_teardown|grammar_top_k|image_token_limit|fit_api|device_memory|build_identity|cancel_flag|f16_dot_accumulation|f16_residual_kernels|upstream_abi|mtmd_compat|asr_stream"
ctest --test-dir ${{ matrix.build_dir }} -R "owner_|file_sha256|model_fd|threadpool|exit_teardown|grammar_top_k|image_token_limit|fit_api|device_memory|build_identity|cancel_flag|f16_dot_accumulation|f16_residual_kernels|upstream_abi|mtmd_compat|asr_stream"
--timeout 300 --output-on-failure
# Apple CPUs have FHM, so the shipped build takes the FMLAL branch of
# patch 0005. ARMv8.2-A with FP16 compiles its conversion branch, as on
Expand Down
12 changes: 11 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,7 @@ endif()
add_library(llamadart_lib SHARED
"src/llama_dart_wrapper.cpp"
"src/llama_dart_build_identity.cpp"
"src/llama_dart_file_sha256.cpp"
"src/llama_dart_image_token_limit.cpp"
"src/llama_dart_device_memory.cpp"
"src/llama_dart_vulkan_device_info.cpp")
Expand All @@ -338,6 +339,7 @@ if (NOT EXISTS "${LLAMADART_VULKAN_HEADERS_INCLUDE}/vulkan/vulkan_core.h")
message(FATAL_ERROR "Missing submodule: third_party/Vulkan-Headers. Run: git submodule update --init --recursive")
endif()
target_include_directories(llamadart_lib SYSTEM PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/third_party/llama.cpp/vendor/hash"
"${LLAMADART_VULKAN_HEADERS_INCLUDE}")
target_link_libraries(llamadart_lib PRIVATE ${CMAKE_DL_LIBS})
if (MSVC)
Expand Down Expand Up @@ -651,6 +653,14 @@ if (LLAMADART_BUILD_TESTS)
add_test(NAME llamadart_cancel_flag_flag
COMMAND llamadart_cancel_flag_test flag)

add_executable(llamadart_file_sha256_test tests/file_sha256_test.cpp)
target_compile_features(llamadart_file_sha256_test PRIVATE cxx_std_17)
target_compile_definitions(llamadart_file_sha256_test PRIVATE LLAMADART_TESTING=1)
target_include_directories(llamadart_file_sha256_test PRIVATE src)
target_link_libraries(llamadart_file_sha256_test PRIVATE llamadart_lib Threads::Threads)
add_test(NAME llamadart_file_sha256_contract COMMAND llamadart_file_sha256_test)
set_tests_properties(llamadart_file_sha256_contract PROPERTIES TIMEOUT 30)

add_executable(llamadart_model_fd_test tests/model_fd_test.cpp)
target_compile_features(llamadart_model_fd_test PRIVATE cxx_std_17)
target_link_libraries(llamadart_model_fd_test PRIVATE llamadart_lib)
Expand Down Expand Up @@ -993,7 +1003,7 @@ if (LLAMADART_BUILD_TESTS)
llamadart_build_identity_test llamadart_upstream_abi_test llamadart_cancel_flag_test
llamadart_tts_eval_test llamadart_tts_seed_test llamadart_tts_batch_test llamadart_tts_sampler_test
llamadart_exit_teardown_test llamadart_model_fd_test llamadart_threadpool_test
llamadart_grammar_top_k_test
llamadart_grammar_top_k_test llamadart_file_sha256_test
llamadart_mtmd_compat_test
llamadart_vulkan_device_info_test llamadart_barrier_test llamadart_image_token_limit_test
llamadart_fit_api_test llamadart_device_memory_test)
Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,23 @@ Generic MTP initialization requires empty target memory and checks rollback
support before accepting the session. See [the MTP rollback contract and local
component checks](docs/speculative_mtp_rollback.md).

## File SHA-256

Bindings can look up `llama_dart_file_sha256_api_version` and require version
1 to hash a downloaded model before initializing a backend. On older bundles
the symbol may be absent. Call `llama_dart_file_sha256` on a worker thread
with a stable regular file, a 32-byte output and an optional cancel byte.
Compare the raw digest with the expected checksum only on status zero. The
[public header](src/llama_dart_wrapper.h) defines the status codes. A directory
returns open failure (2) on Windows and read error (3) on POSIX.

The wrapper reads 256 KiB at a time and checks for I/O errors and size changes
through EOF. Android and Linux arm64 select SHA-2 instructions when the CPU
advertises them. Apple arm64 uses the same instructions. Other targets use
llama.cpp's vendored public-domain SHA-256 implementation. To measure a
1 GiB file with a Release test build, run
`llamadart_file_sha256_test --benchmark`.

## Exit Teardown

ggml-metal aborts in its static destructor
Expand Down
184 changes: 184 additions & 0 deletions src/llama_dart_file_sha256.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
#include "llama_dart_wrapper.h"
#include "llama_dart_cancel_eval_internal.h"
#include "llama_dart_file_sha256_test_hooks.h"

#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <sys/stat.h>

#if defined(_WIN32)
#include <io.h>
#else
#include <fcntl.h>
#include <unistd.h>
#endif

#if defined(__aarch64__) && defined(__AARCH64EL__) && (defined(__linux__) || defined(__APPLE__))
#include <arm_neon.h>
#if defined(__linux__)
#include <asm/hwcap.h>
#include <sys/auxv.h>
#endif
#define LLAMADART_ARM_SHA2 1
#endif

namespace {
// Keep the upstream public-domain implementation private to the wrapper.
// Its constants, state and padding are shared by both compression paths.
#include "sha256/sha256.c"

constexpr size_t chunk_size = 256 * 1024;

#if defined(LLAMADART_ARM_SHA2)
bool has_arm_sha2() {
#if defined(__linux__)
return (getauxval(AT_HWCAP) & HWCAP_SHA2) != 0;
#else
return true; // SHA-256 instructions are baseline on Apple arm64.
#endif
}

__attribute__((target("+crypto"), noinline)) void hash_blocks(sha256_t &ctx, const uint8_t *bytes,
size_t size) {
uint32x4_t abcd = vld1q_u32(ctx.state);
uint32x4_t efgh = vld1q_u32(ctx.state + 4);
for (size_t offset = 0; offset < size; offset += 64) {
const auto initial_abcd = abcd;
const auto initial_efgh = efgh;
uint32x4_t words[4];
for (unsigned i = 0; i < 4; ++i) {
words[i] = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(bytes + offset + 16 * i)));
}
// Constant indices keep the four message vectors in registers.
#if defined(__clang__)
#pragma clang loop unroll(full)
#else
#pragma GCC unroll 16
#endif
for (unsigned group = 0; group < 16; ++group) {
const unsigned i = group % 4;
const auto rounds = vaddq_u32(words[i], vld1q_u32(K + 4 * group));
if (group < 12) {
words[i] = vsha256su1q_u32(vsha256su0q_u32(words[i], words[(i + 1) % 4]),
words[(i + 2) % 4], words[(i + 3) % 4]);
}
const auto old_abcd = abcd;
abcd = vsha256hq_u32(abcd, efgh, rounds);
efgh = vsha256h2q_u32(efgh, old_abcd, rounds);
}
abcd = vaddq_u32(abcd, initial_abcd);
efgh = vaddq_u32(efgh, initial_efgh);
}
vst1q_u32(ctx.state, abcd);
vst1q_u32(ctx.state + 4, efgh);
ctx.count += size;
}
#endif

llama_dart_file_sha256_status hash_stream(FILE *file, uint64_t remaining, uint8_t digest[32],
const int8_t *cancel_flag) {
std::unique_ptr<uint8_t, decltype(&std::free)> buffer(
static_cast<uint8_t *>(std::malloc(chunk_size)), std::free);
if (!buffer)
return LLAMA_DART_FILE_SHA256_OUT_OF_MEMORY;

sha256_t ctx;
sha256_init(&ctx);
#if defined(LLAMADART_ARM_SHA2)
const bool accelerated = has_arm_sha2();
#endif
while (remaining > 0) {
if (llama_dart_cancel_flag_set(cancel_flag))
return LLAMA_DART_FILE_SHA256_CANCELLED;
const size_t wanted = static_cast<size_t>(std::min<uint64_t>(remaining, chunk_size));
const size_t n = std::fread(buffer.get(), 1, wanted, file);
if (std::ferror(file))
return LLAMA_DART_FILE_SHA256_READ_ERROR;
if (n != wanted)
return LLAMA_DART_FILE_SHA256_SHORT_READ;
size_t blocks = 0;
#if defined(LLAMADART_ARM_SHA2)
if (accelerated) {
blocks = n - n % 64;
hash_blocks(ctx, buffer.get(), blocks);
}
#endif
sha256_update(&ctx, buffer.get() + blocks, n - blocks);
remaining -= n;
}
if (std::fgetc(file) != EOF)
return LLAMA_DART_FILE_SHA256_FILE_GREW;
if (std::ferror(file))
return LLAMA_DART_FILE_SHA256_READ_ERROR;
if (llama_dart_cancel_flag_set(cancel_flag))
return LLAMA_DART_FILE_SHA256_CANCELLED;
sha256_final(&ctx, digest);
return LLAMA_DART_FILE_SHA256_OK;
}

FILE *open_file(const char *path) {
#ifdef _WIN32
return ggml_fopen(path, "rb");
#else
// Inspect the opened object without blocking on a FIFO with no writer.
const int fd = open(path, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
if (fd < 0)
return nullptr;
FILE *file = fdopen(fd, "rb");
if (!file)
close(fd);
return file;
#endif
}

int64_t file_size(FILE *file) {
#ifdef _WIN32
struct _stat64 info;
if (_fstat64(_fileno(file), &info) != 0 || (info.st_mode & _S_IFMT) != _S_IFREG)
return -1;
#else
struct stat info;
if (fstat(fileno(file), &info) != 0 || !S_ISREG(info.st_mode))
return -1;
#endif
return info.st_size;
}

llama_dart_file_sha256_status hash_and_close(FILE *file, int64_t size, uint8_t out_digest[32],
const int8_t *cancel_flag) {
uint8_t digest[32];
auto status = size < 0 ? LLAMA_DART_FILE_SHA256_READ_ERROR
: hash_stream(file, static_cast<uint64_t>(size), digest, cancel_flag);
if (std::fclose(file) != 0 && status == LLAMA_DART_FILE_SHA256_OK) {
return LLAMA_DART_FILE_SHA256_READ_ERROR;
}
if (status == LLAMA_DART_FILE_SHA256_OK)
std::memcpy(out_digest, digest, sizeof(digest));
return status;
}
} // namespace

uint32_t llama_dart_file_sha256_api_version(void) { return 1; }

llama_dart_file_sha256_status llama_dart_file_sha256(const char *path, uint8_t out_digest[32],
const int8_t *cancel_flag) {
if (!path || !*path || !out_digest)
return LLAMA_DART_FILE_SHA256_INVALID_ARGUMENT;
if (llama_dart_cancel_flag_set(cancel_flag))
return LLAMA_DART_FILE_SHA256_CANCELLED;
FILE *file = open_file(path);
if (!file)
return LLAMA_DART_FILE_SHA256_OPEN_FAILED;
return hash_and_close(file, file_size(file), out_digest, cancel_flag);
}

#if defined(LLAMADART_TESTING) && !defined(_WIN32)
llama_dart_file_sha256_status llama_dart_test_sha256_and_close(FILE *file, int64_t size,
uint8_t digest[32],
const int8_t *cancel_flag) {
return hash_and_close(file, size, digest, cancel_flag);
}
#endif
10 changes: 10 additions & 0 deletions src/llama_dart_file_sha256_test_hooks.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#pragma once

#if defined(LLAMADART_TESTING) && !defined(_WIN32)
#include "llama_dart_wrapper.h"
#include <stdio.h>

extern "C" LLAMADART_API enum llama_dart_file_sha256_status
llama_dart_test_sha256_and_close(FILE *file, int64_t size, uint8_t digest[32],
const int8_t *cancel_flag);
#endif
26 changes: 25 additions & 1 deletion src/llama_dart_wrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ LLAMADART_API void llama_dart_set_log_level(int level);
// llama_dart_clear_last_error first to learn whether a free threw.
//
// The functions without a barrier are llama_dart_build_identity,
// llama_dart_last_error, llama_dart_clear_last_error,
// the llama_dart_file_sha256 functions, llama_dart_last_error, llama_dart_clear_last_error,
// llama_dart_set_log_level, the
// llama_dart_exit_ functions other than llama_dart_exit_track and
// llama_dart_exit_free, the draft context getter and
Expand Down Expand Up @@ -536,6 +536,30 @@ LLAMADART_API struct llama_model * llama_dart_model_load_from_file(
const char * path_model,
struct llama_model_params params);

// Optional full-file SHA-256 API. Resolve this probe and require version 1.
LLAMADART_API uint32_t llama_dart_file_sha256_api_version(void);

enum llama_dart_file_sha256_status {
LLAMA_DART_FILE_SHA256_OK = 0,
LLAMA_DART_FILE_SHA256_INVALID_ARGUMENT = 1,
LLAMA_DART_FILE_SHA256_OPEN_FAILED = 2,
LLAMA_DART_FILE_SHA256_READ_ERROR = 3,
LLAMA_DART_FILE_SHA256_SHORT_READ = 4,
LLAMA_DART_FILE_SHA256_CANCELLED = 5,
LLAMA_DART_FILE_SHA256_FILE_GREW = 6,
LLAMA_DART_FILE_SHA256_OUT_OF_MEMORY = 7,
};

// Hash a stable regular file at a NUL-terminated UTF-8 path, on any thread,
// without initializing a model or backend. Only OK writes the 32 digest bytes.
// OPEN_FAILED includes a directory rejected by the Windows file open.
// READ_ERROR includes a failed size query or an opened non-regular file. SHORT_READ
// and FILE_GREW compare the bytes read with the opened file's initial size.
// cancel_flag may be NULL. Otherwise keep it live until return and set it
// atomically to a nonzero byte to cancel between reads.
LLAMADART_API enum llama_dart_file_sha256_status llama_dart_file_sha256(
const char * path, uint8_t out_digest[32], const int8_t * cancel_flag);

// Model load from a caller-owned file descriptor, API v1. See
// docs/model_load_from_fd.md. Returns 0 where the platform has no descriptor
// loader (Windows) and 1 elsewhere; check it before use.
Expand Down
Loading
Loading