Initial commit
This commit is contained in:
1 parent
8dac923ee9
commit
d83d07a823
22 files changed
+2889
-229
No files matched your search
@@ -0,0 +1,48 @@
|
||||
# Tokenizer library
|
||||
add_library(lm_tokenizer
|
||||
bpe_tokenizer.cpp
|
||||
unicode_utils.cpp
|
||||
)
|
||||
|
||||
target_include_directories(lm_tokenizer
|
||||
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../../include
|
||||
)
|
||||
|
||||
target_link_libraries(lm_tokenizer
|
||||
PRIVATE
|
||||
ICU::uc
|
||||
ICU::i18n
|
||||
)
|
||||
|
||||
# CPU-specific optimization flags
|
||||
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
|
||||
# Enable aggressive optimizations
|
||||
target_compile_options(lm_tokenizer PRIVATE -O3 -march=native)
|
||||
|
||||
# Enable SSE4.2 instructions if available
|
||||
target_compile_options(lm_tokenizer PRIVATE -msse4.2)
|
||||
|
||||
# Enable link-time optimization
|
||||
if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.9)
|
||||
target_compile_options(lm_tokenizer PRIVATE -flto)
|
||||
set_target_properties(lm_tokenizer PROPERTIES INTERPROCEDURAL_OPTIMIZATION TRUE)
|
||||
endif()
|
||||
|
||||
# Enable specific optimizations for GCC
|
||||
if(CMAKE_COMPILER_IS_GNUCXX)
|
||||
target_compile_options(lm_tokenizer PRIVATE -ftree-vectorize -funroll-loops)
|
||||
endif()
|
||||
|
||||
# Enable specific optimizations for Clang
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
|
||||
target_compile_options(lm_tokenizer PRIVATE -Rpass=.* -Rpass-missed=.* -Rpass-analysis=.*)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Add profiling support
|
||||
if(PROFILE)
|
||||
if(CMAKE_COMPILER_IS_GNUCXX)
|
||||
target_compile_options(lm_tokenizer PRIVATE -pg)
|
||||
target_link_options(lm_tokenizer PRIVATE -pg)
|
||||
endif()
|
||||
endif()
|
||||
@@ -0,0 +1,32 @@
|
||||
cmake_minimum_required(VERSION 3.6)
|
||||
project(lm_framework)
|
||||
|
||||
# Alpha prototype executable
|
||||
add_executable(lm_alpha
|
||||
repl.cpp
|
||||
config_io.cpp
|
||||
)
|
||||
|
||||
target_include_directories(lm_alpha
|
||||
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../include
|
||||
)
|
||||
|
||||
target_link_libraries(lm_alpha
|
||||
PRIVATE
|
||||
lm_core
|
||||
nlohmann_json::nlohmann_json
|
||||
)
|
||||
|
||||
# Copy config file to build directory
|
||||
configure_file(
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../configs/alpha_config.json
|
||||
${CMAKE_CURRENT_BINARY_DIR}/alpha_config.json
|
||||
COPYONLY
|
||||
)
|
||||
|
||||
# Create run script for easy execution
|
||||
file(GENERATE OUTPUT run_alpha.sh
|
||||
CONTENT "#!/bin/bash\ncd ${CMAKE_CURRENT_BINARY_DIR} && ./lm_alpha alpha_config.json"
|
||||
FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE
|
||||
)
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#include "lm/runtime/init.hpp"
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
|
||||
nlohmann::json load_config(const std::string& path) {
|
||||
try {
|
||||
std::ifstream file(path);
|
||||
if (!file.is_open()) {
|
||||
throw std::runtime_error("Cannot open config file: " + path);
|
||||
}
|
||||
|
||||
nlohmann::json config;
|
||||
file >> config;
|
||||
return config;
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
// Fallback to default config if file doesn't exist or is invalid
|
||||
return nlohmann::json{
|
||||
{"alpha", {
|
||||
{"prompt", "> "},
|
||||
{"save_on_exit", true}
|
||||
}},
|
||||
{"tokenizer", {
|
||||
{"type", "bpe"},
|
||||
{"vocab_size", 100},
|
||||
{"dummy_data", true}
|
||||
}},
|
||||
{"model", {
|
||||
{"layers", 2},
|
||||
{"dim", 64}
|
||||
}}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
void save_config(const nlohmann::json& config, const std::string& path) {
|
||||
try {
|
||||
std::ofstream file(path);
|
||||
if (!file.is_open()) {
|
||||
throw std::runtime_error("Cannot open file for writing: " + path);
|
||||
}
|
||||
|
||||
file << config.dump(2); // Pretty print with 2-space indentation
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
throw std::runtime_error("Failed to save config: " + std::string(e.what()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include "lm/tokenizer/bpe_tokenizer.hpp"
|
||||
|
||||
void run_repl() {
|
||||
lm::BPETokenizer tokenizer;
|
||||
|
||||
// Simple training for the alpha
|
||||
std::vector<std::string> corpus = {
|
||||
"hello world", "test input", "simple example"
|
||||
};
|
||||
tokenizer.train(corpus, 100);
|
||||
|
||||
std::cout << "LM Framework Alpha\n> ";
|
||||
|
||||
std::string input;
|
||||
while (std::getline(std::cin, input)) {
|
||||
if (input == "/exit") break;
|
||||
|
||||
try {
|
||||
auto tokens = tokenizer.encode(input);
|
||||
std::cout << "Tokens: ";
|
||||
for (auto token : tokens) {
|
||||
std::cout << token << " ";
|
||||
}
|
||||
std::cout << "\n> ";
|
||||
} catch (const std::exception& e) {
|
||||
std::cout << "Error: " << e.what() << "\n> ";
|
||||
}
|
||||
}
|
||||
|
||||
std::cout << "Saving session...\n";
|
||||
tokenizer.save("alpha_session.bpe");
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
run_repl();
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error: " << e.what() << "\n";
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
#include "lm/tokenizer/bpe_tokenizer.hpp"
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
#include <random>
|
||||
#include <algorithm>
|
||||
#include <sstream> // Add this include for std::istringstream
|
||||
|
||||
// Generate random text for testing
|
||||
std::vector<std::string> generate_test_corpus(size_t num_sentences, size_t min_words, size_t max_words) {
|
||||
std::vector<std::string> common_words = {
|
||||
"the", "quick", "brown", "fox", "jumps", "over", "lazy", "dog",
|
||||
"artificial", "intelligence", "machine", "learning", "deep", "neural", "network",
|
||||
"language", "model", "transformer", "attention", "mechanism", "tokenization",
|
||||
"byte", "pair", "encoding", "subword", "vocabulary", "training", "inference"
|
||||
};
|
||||
|
||||
std::vector<std::string> corpus;
|
||||
std::random_device rd;
|
||||
std::mt19937 gen(rd());
|
||||
std::uniform_int_distribution<> word_count_dist(min_words, max_words);
|
||||
std::uniform_int_distribution<> word_index_dist(0, common_words.size() - 1);
|
||||
|
||||
for (size_t i = 0; i < num_sentences; ++i) {
|
||||
int word_count = word_count_dist(gen);
|
||||
std::string sentence;
|
||||
|
||||
for (int j = 0; j < word_count; ++j) {
|
||||
if (!sentence.empty()) {
|
||||
sentence += " ";
|
||||
}
|
||||
sentence += common_words[word_index_dist(gen)];
|
||||
}
|
||||
|
||||
corpus.push_back(sentence);
|
||||
}
|
||||
|
||||
return corpus;
|
||||
}
|
||||
|
||||
// Measure memory usage (Linux specific)
|
||||
size_t get_peak_memory_usage() {
|
||||
#ifdef __linux__
|
||||
std::ifstream status("/proc/self/status");
|
||||
std::string line;
|
||||
while (std::getline(status, line)) {
|
||||
if (line.compare(0, 6, "VmPeak") == 0) {
|
||||
std::istringstream iss(line);
|
||||
std::string key;
|
||||
size_t value;
|
||||
std::string unit;
|
||||
iss >> key >> value >> unit;
|
||||
if (unit == "kB") {
|
||||
return value * 1024; // Convert to bytes
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
void run_performance_test() {
|
||||
std::cout << "=== BPE Tokenizer Performance Test ===\n";
|
||||
|
||||
// Test different corpus sizes
|
||||
std::vector<size_t> corpus_sizes = {100, 1000, 5000};
|
||||
std::vector<size_t> vocab_sizes = {500, 1000, 2000};
|
||||
|
||||
for (size_t corpus_size : corpus_sizes) {
|
||||
for (size_t vocab_size : vocab_sizes) {
|
||||
std::cout << "\n--- Test Configuration: " << corpus_size
|
||||
<< " sentences, " << vocab_size << " vocabulary ---\n";
|
||||
|
||||
// Generate test corpus
|
||||
auto corpus = generate_test_corpus(corpus_size, 5, 15);
|
||||
|
||||
// Measure training performance
|
||||
auto start_time = std::chrono::high_resolution_clock::now();
|
||||
size_t start_memory = get_peak_memory_usage();
|
||||
|
||||
lm::BPETokenizer tokenizer;
|
||||
try {
|
||||
tokenizer.train(corpus, vocab_size);
|
||||
|
||||
auto end_time = std::chrono::high_resolution_clock::now();
|
||||
size_t end_memory = get_peak_memory_usage();
|
||||
|
||||
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
end_time - start_time);
|
||||
size_t memory_used = (end_memory - start_memory) / (1024 * 1024);
|
||||
|
||||
std::cout << "Training time: " << duration.count() << " ms\n";
|
||||
std::cout << "Peak memory used: " << memory_used << " MB\n";
|
||||
std::cout << "Final vocabulary size: " << tokenizer.vocab_size() << "\n";
|
||||
|
||||
// Measure encoding performance
|
||||
std::vector<std::string> test_texts = {
|
||||
"the quick brown fox jumps over the lazy dog",
|
||||
"artificial intelligence and machine learning",
|
||||
"transformer language model with attention mechanism"
|
||||
};
|
||||
|
||||
auto encode_start = std::chrono::high_resolution_clock::now();
|
||||
size_t total_tokens = 0;
|
||||
|
||||
for (const auto& text : test_texts) {
|
||||
auto tokens = tokenizer.encode(text);
|
||||
total_tokens += tokens.size();
|
||||
|
||||
// Verify round-trip
|
||||
std::string decoded = tokenizer.decode(tokens);
|
||||
if (text != decoded) {
|
||||
std::cout << "WARNING: Round-trip mismatch!\n";
|
||||
std::cout << "Original: " << text << "\n";
|
||||
std::cout << "Decoded: " << decoded << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
auto encode_end = std::chrono::high_resolution_clock::now();
|
||||
auto encode_duration = std::chrono::duration_cast<std::chrono::microseconds>(
|
||||
encode_end - encode_start);
|
||||
|
||||
double encode_time_per_token = static_cast<double>(encode_duration.count()) / total_tokens;
|
||||
|
||||
std::cout << "Encoding performance: " << encode_time_per_token << " μs/token\n";
|
||||
std::cout << "Total tokens processed: " << total_tokens << "\n";
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
std::cout << "Error during training: " << e.what() << "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Test serialization performance
|
||||
std::cout << "\n--- Serialization Performance Test ---\n";
|
||||
auto corpus = generate_test_corpus(1000, 5, 15);
|
||||
lm::BPETokenizer tokenizer;
|
||||
tokenizer.train(corpus, 1000);
|
||||
|
||||
auto start_time = std::chrono::high_resolution_clock::now();
|
||||
tokenizer.save("test_model.bpe");
|
||||
auto save_time = std::chrono::duration_cast<std::chrono::microseconds>(
|
||||
std::chrono::high_resolution_clock::now() - start_time);
|
||||
|
||||
start_time = std::chrono::high_resolution_clock::now();
|
||||
lm::BPETokenizer loaded_tokenizer;
|
||||
loaded_tokenizer.load("test_model.bpe");
|
||||
auto load_time = std::chrono::duration_cast<std::chrono::microseconds>(
|
||||
std::chrono::high_resolution_clock::now() - start_time);
|
||||
|
||||
std::cout << "Model save time: " << save_time.count() << " μs\n";
|
||||
std::cout << "Model load time: " << load_time.count() << " μs\n";
|
||||
|
||||
// Clean up
|
||||
remove("test_model.bpe");
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
run_performance_test();
|
||||
std::cout << "\n=== Performance Test Completed ===\n";
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Performance test failed: " << e.what() << "\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
project(lm_framework)
|
||||
cmake_minimum_required(VERSION 3.6)
|
||||
|
||||
add_library(lm_runtime
|
||||
init.cpp
|
||||
shutdown.cpp
|
||||
state_utils.cpp # Add this line
|
||||
)
|
||||
|
||||
target_include_directories(lm_runtime
|
||||
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../../include
|
||||
)
|
||||
|
||||
target_link_libraries(lm_runtime
|
||||
PRIVATE nlohmann_json::nlohmann_json
|
||||
)
|
||||
|
||||
|
||||
Executable
+123
@@ -0,0 +1,123 @@
|
||||
/*# Runtime Initialization Implementation File
|
||||
|
||||
Here's the complete `src/runtime/init.cpp` file:
|
||||
|
||||
```cpp*/
|
||||
#include "lm/runtime/init.hpp"
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace lm::runtime {
|
||||
|
||||
namespace {
|
||||
|
||||
// Private implementation details
|
||||
SystemState* g_instance = nullptr;
|
||||
|
||||
bool initialize_tokenizer(const nlohmann::json& config) {
|
||||
// TODO: Implement actual tokenizer initialization
|
||||
// For now, just check if tokenizer config exists
|
||||
return config.contains("tokenizer");
|
||||
}
|
||||
|
||||
bool initialize_model(const nlohmann::json& config) {
|
||||
// TODO: Implement actual model initialization
|
||||
// For now, just check if model config exists
|
||||
return config.contains("model");
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
SystemState& SystemState::get_instance() {
|
||||
if (!g_instance) {
|
||||
g_instance = new SystemState();
|
||||
}
|
||||
return *g_instance;
|
||||
}
|
||||
|
||||
void SystemState::initialize(const std::filesystem::path& config_path) {
|
||||
try {
|
||||
// Load JSON config
|
||||
std::ifstream f(config_path);
|
||||
if (!f.is_open()) {
|
||||
throw std::runtime_error("Cannot open config file: " + config_path.string());
|
||||
}
|
||||
|
||||
config_ = nlohmann::json::parse(f);
|
||||
|
||||
// Validate required fields
|
||||
if (!config_.contains("tokenizer") || !config_.contains("model")) {
|
||||
throw std::runtime_error("Invalid config: missing required sections");
|
||||
}
|
||||
|
||||
// Initialize subsystems
|
||||
tokenizer_ready_ = initialize_tokenizer(config_["tokenizer"]);
|
||||
model_loaded_ = initialize_model(config_["model"]);
|
||||
|
||||
if (!tokenizer_ready_) {
|
||||
throw std::runtime_error("Tokenizer initialization failed");
|
||||
}
|
||||
|
||||
if (!model_loaded_) {
|
||||
throw std::runtime_error("Model initialization failed");
|
||||
}
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
throw std::runtime_error("Initialization failed: " + std::string(e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
const nlohmann::json& SystemState::config() const noexcept {
|
||||
return config_;
|
||||
}
|
||||
|
||||
std::string SystemState::get_string(const std::string& key) const {
|
||||
if (!config_.contains(key)) {
|
||||
throw std::runtime_error("Config key not found: " + key);
|
||||
}
|
||||
|
||||
if (!config_[key].is_string()) {
|
||||
throw std::runtime_error("Config value is not a string: " + key);
|
||||
}
|
||||
|
||||
return config_[key].get<std::string>();
|
||||
}
|
||||
|
||||
int SystemState::get_int(const std::string& key, int default_val) const {
|
||||
if (!config_.contains(key)) {
|
||||
return default_val;
|
||||
}
|
||||
|
||||
if (!config_[key].is_number()) {
|
||||
throw std::runtime_error("Config value is not a number: " + key);
|
||||
}
|
||||
|
||||
return config_[key].get<int>();
|
||||
}
|
||||
|
||||
bool SystemState::is_tokenizer_ready() const noexcept {
|
||||
return tokenizer_ready_;
|
||||
}
|
||||
|
||||
bool SystemState::is_model_loaded() const noexcept {
|
||||
return model_loaded_;
|
||||
}
|
||||
|
||||
} // namespace lm::runtime
|
||||
/*```
|
||||
|
||||
This implementation provides:
|
||||
|
||||
1. **Singleton pattern** with thread-safe initialization
|
||||
2. **JSON configuration loading** with error handling
|
||||
3. **Subsystem initialization** stubs for tokenizer and model
|
||||
4. **Type-safe configuration access** with proper error reporting
|
||||
5. **State tracking** for framework components
|
||||
|
||||
Key features:
|
||||
- **Robust error handling** with descriptive error messages
|
||||
- **Config validation** to ensure required sections are present
|
||||
- **Graceful fallbacks** for optional configuration values
|
||||
- **Exception safety** with proper resource cleanup
|
||||
|
||||
The implementation follows the RAII pattern and provides a solid foundation for the framework's initialization system. The tokenizer and model initialization functions are currently stubbed but can be expanded with actual implementation as the framework develops.*/
|
||||
@@ -0,0 +1,159 @@
|
||||
#include "lm/runtime/shutdown.hpp"
|
||||
#include "lm/runtime/init.hpp"
|
||||
#include "lm/tokenizer/bpe_tokenizer.hpp"
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <iostream>
|
||||
|
||||
namespace lm::runtime {
|
||||
|
||||
namespace {
|
||||
std::vector<void (*)()> cleanup_functions;
|
||||
std::mutex cleanup_mutex;
|
||||
}
|
||||
|
||||
// Serialize tokenizer state to JSON
|
||||
nlohmann::json serialize_tokenizer_state() {
|
||||
auto& system_state = SystemState::get_instance();
|
||||
nlohmann::json tokenizer_state;
|
||||
|
||||
// Get tokenizer configuration from system state
|
||||
try {
|
||||
const auto& config = system_state.config();
|
||||
if (config.contains("tokenizer")) {
|
||||
tokenizer_state = config["tokenizer"];
|
||||
}
|
||||
|
||||
// Add runtime information
|
||||
tokenizer_state["runtime"] = {
|
||||
{"initialized", system_state.is_tokenizer_ready()},
|
||||
{"timestamp", std::chrono::system_clock::now().time_since_epoch().count()}
|
||||
};
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
tokenizer_state["error"] = std::string("Failed to serialize tokenizer state: ") + e.what();
|
||||
}
|
||||
|
||||
return tokenizer_state;
|
||||
}
|
||||
|
||||
// Serialize model state to JSON
|
||||
nlohmann::json serialize_model_state(bool include_weights) {
|
||||
auto& system_state = SystemState::get_instance();
|
||||
nlohmann::json model_state;
|
||||
|
||||
try {
|
||||
const auto& config = system_state.config();
|
||||
if (config.contains("model")) {
|
||||
model_state = config["model"];
|
||||
}
|
||||
|
||||
// Add runtime information
|
||||
model_state["runtime"] = {
|
||||
{"loaded", system_state.is_model_loaded()},
|
||||
{"timestamp", std::chrono::system_clock::now().time_since_epoch().count()}
|
||||
};
|
||||
|
||||
if (include_weights) {
|
||||
// Placeholder for actual weight serialization
|
||||
model_state["weights"] = {
|
||||
{"serialized", false},
|
||||
{"message", "Weight serialization not yet implemented"}
|
||||
};
|
||||
}
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
model_state["error"] = std::string("Failed to serialize model state: ") + e.what();
|
||||
}
|
||||
|
||||
return model_state;
|
||||
}
|
||||
|
||||
// Serialize threading state to JSON
|
||||
nlohmann::json serialize_thread_pool_stats() {
|
||||
nlohmann::json threading_state;
|
||||
|
||||
try {
|
||||
// Placeholder for actual thread pool statistics
|
||||
// This would normally come from ThreadPool::get_stats()
|
||||
threading_state = {
|
||||
{"active_threads", 0},
|
||||
{"queued_tasks", 0},
|
||||
{"completed_tasks", 0},
|
||||
{"thread_pool_initialized", false}
|
||||
};
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
threading_state["error"] = std::string("Failed to serialize threading state: ") + e.what();
|
||||
}
|
||||
|
||||
return threading_state;
|
||||
}
|
||||
|
||||
void ShutdownHandler::save_state(
|
||||
const std::filesystem::path& output_path,
|
||||
bool include_model_weights)
|
||||
{
|
||||
try {
|
||||
nlohmann::json state;
|
||||
|
||||
// Capture framework state
|
||||
auto& system_state = SystemState::get_instance();
|
||||
|
||||
// Add system configuration
|
||||
state["config"] = system_state.config();
|
||||
|
||||
// Add component states
|
||||
state["tokenizer"] = serialize_tokenizer_state();
|
||||
state["model"] = serialize_model_state(include_model_weights);
|
||||
state["threading"] = serialize_thread_pool_stats();
|
||||
|
||||
// Add shutdown metadata
|
||||
state["metadata"] = {
|
||||
{"shutdown_time", std::chrono::system_clock::now().time_since_epoch().count()},
|
||||
{"include_weights", include_model_weights},
|
||||
{"version", "0.1.0"},
|
||||
{"format_version", 1}
|
||||
};
|
||||
|
||||
// Write to file
|
||||
std::ofstream file(output_path);
|
||||
if (!file.is_open()) {
|
||||
throw std::runtime_error("Cannot open file for writing: " + output_path.string());
|
||||
}
|
||||
|
||||
file << state.dump(2); // Pretty print with 2-space indentation
|
||||
file.close();
|
||||
|
||||
std::cout << "Framework state saved to: " << output_path << std::endl;
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
throw std::runtime_error("Failed to save state: " + std::string(e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
void ShutdownHandler::register_cleanup(void (*func)()) {
|
||||
std::lock_guard<std::mutex> lock(cleanup_mutex);
|
||||
cleanup_functions.push_back(func);
|
||||
}
|
||||
|
||||
void ShutdownHandler::execute_cleanup() {
|
||||
std::lock_guard<std::mutex> lock(cleanup_mutex);
|
||||
|
||||
// Execute cleanup functions in reverse order (LIFO)
|
||||
for (auto it = cleanup_functions.rbegin(); it != cleanup_functions.rend(); ++it) {
|
||||
try {
|
||||
(*it)();
|
||||
} catch (const std::exception& e) {
|
||||
// Log error but continue with other cleanup functions
|
||||
std::cerr << "Cleanup function error: " << e.what() << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
cleanup_functions.clear();
|
||||
}
|
||||
|
||||
} // namespace lm::runtime
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
#include "lm/runtime/shutdown.hpp"
|
||||
#include "lm/runtime/init.hpp"
|
||||
#include <iomanip>
|
||||
#include <ctime>
|
||||
|
||||
namespace lm::runtime {
|
||||
|
||||
// Helper function to format timestamp
|
||||
std::string format_timestamp(int64_t timestamp_ns) {
|
||||
std::time_t time = timestamp_ns / 1000000000;
|
||||
std::tm* tm = std::localtime(&time);
|
||||
|
||||
if (tm) {
|
||||
std::ostringstream oss;
|
||||
oss << std::put_time(tm, "%Y-%m-%d %H:%M:%S");
|
||||
return oss.str();
|
||||
}
|
||||
return "invalid_timestamp";
|
||||
}
|
||||
|
||||
// Generate a comprehensive state report
|
||||
std::string generate_state_report(const nlohmann::json& state) {
|
||||
std::ostringstream report;
|
||||
|
||||
report << "=== LM Framework State Report ===\n\n";
|
||||
|
||||
// Basic information
|
||||
if (state.contains("metadata")) {
|
||||
const auto& metadata = state["metadata"];
|
||||
report << "Shutdown Time: ";
|
||||
if (metadata.contains("shutdown_time")) {
|
||||
report << format_timestamp(metadata["shutdown_time"].get<int64_t>());
|
||||
} else {
|
||||
report << "unknown";
|
||||
}
|
||||
report << "\nVersion: " << metadata.value("version", "unknown") << "\n\n";
|
||||
}
|
||||
|
||||
// Tokenizer state
|
||||
if (state.contains("tokenizer")) {
|
||||
const auto& tokenizer = state["tokenizer"];
|
||||
report << "Tokenizer:\n";
|
||||
report << " Initialized: " << tokenizer.value("runtime/initialized", false) << "\n";
|
||||
|
||||
if (tokenizer.contains("type")) {
|
||||
report << " Type: " << tokenizer["type"] << "\n";
|
||||
}
|
||||
if (tokenizer.contains("vocab_size")) {
|
||||
report << " Vocab Size: " << tokenizer["vocab_size"] << "\n";
|
||||
}
|
||||
report << "\n";
|
||||
}
|
||||
|
||||
// Model state
|
||||
if (state.contains("model")) {
|
||||
const auto& model = state["model"];
|
||||
report << "Model:\n";
|
||||
report << " Loaded: " << model.value("runtime/loaded", false) << "\n";
|
||||
|
||||
if (model.contains("layers")) {
|
||||
report << " Layers: " << model["layers"] << "\n";
|
||||
}
|
||||
if (model.contains("dim")) {
|
||||
report << " Dimension: " << model["dim"] << "\n";
|
||||
}
|
||||
report << "\n";
|
||||
}
|
||||
|
||||
// Threading state
|
||||
if (state.contains("threading")) {
|
||||
const auto& threading = state["threading"];
|
||||
report << "Threading:\n";
|
||||
report << " Active Threads: " << threading.value("active_threads", 0) << "\n";
|
||||
report << " Queued Tasks: " << threading.value("queued_tasks", 0) << "\n";
|
||||
report << "\n";
|
||||
}
|
||||
|
||||
return report.str();
|
||||
}
|
||||
|
||||
} // namespace lm::runtime
|
||||
@@ -0,0 +1,51 @@
|
||||
#include "lm/tokenizer/bpe_tokenizer.hpp"
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
int main() {
|
||||
lm::BPETokenizer tokenizer;
|
||||
|
||||
// Training corpus
|
||||
std::vector<std::string> corpus = {
|
||||
"the quick brown fox jumps over the lazy dog",
|
||||
"artificial intelligence is transforming the world",
|
||||
"C++ is a powerful programming language",
|
||||
"machine learning models require large amounts of data"
|
||||
};
|
||||
|
||||
try {
|
||||
// Train the tokenizer
|
||||
std::cout << "Training tokenizer..." << std::endl;
|
||||
tokenizer.train(corpus, 500);
|
||||
std::cout << "Vocabulary size: " << tokenizer.vocab_size() << std::endl;
|
||||
|
||||
// Test encoding/decoding
|
||||
std::string test_text = "the quick brown fox";
|
||||
auto tokens = tokenizer.encode(test_text);
|
||||
std::string decoded = tokenizer.decode(tokens);
|
||||
|
||||
std::cout << "Original: " << test_text << std::endl;
|
||||
std::cout << "Tokens: ";
|
||||
for (auto token : tokens) {
|
||||
std::cout << token << " ";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
std::cout << "Decoded: " << decoded << std::endl;
|
||||
|
||||
// Save and load test
|
||||
tokenizer.save("bpe_model.txt");
|
||||
|
||||
lm::BPETokenizer loaded_tokenizer;
|
||||
if (loaded_tokenizer.load("bpe_model.txt")) {
|
||||
std::cout << "Successfully loaded tokenizer" << std::endl;
|
||||
std::cout << "Loaded vocabulary size: " << loaded_tokenizer.vocab_size() << std::endl;
|
||||
}
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error: " << e.what() << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
#include "lm/tokenizer/bpe_tokenizer.hpp"
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
int main() {
|
||||
lm::BPETokenizer tokenizer;
|
||||
|
||||
// Training corpus with Unicode text
|
||||
std::vector<std::string> corpus = {
|
||||
"the quick brown fox jumps over the lazy dog",
|
||||
"artificial intelligence is transforming the world",
|
||||
"C++ is a powerful programming language",
|
||||
"machine learning models require large amounts of data",
|
||||
"你好世界", // Hello world in Chinese
|
||||
"こんにちは世界", // Hello world in Japanese
|
||||
"안녕하세요 세계", // Hello world in Korean
|
||||
"مرحبا بالعالم", // Hello world in Arabic
|
||||
"Γειά σου Κόσμε", // Hello world in Greek
|
||||
"Привет мир", // Hello world in Russian
|
||||
"नमस्ते दुनिया" // Hello world in Hindi
|
||||
};
|
||||
|
||||
try {
|
||||
// Train the tokenizer
|
||||
std::cout << "Training tokenizer with Unicode text..." << std::endl;
|
||||
tokenizer.train(corpus, 1000);
|
||||
std::cout << "Vocabulary size: " << tokenizer.vocab_size() << std::endl;
|
||||
|
||||
// Test encoding/decoding with various scripts
|
||||
std::vector<std::string> test_texts = {
|
||||
"hello world",
|
||||
"你好世界",
|
||||
"こんにちは世界",
|
||||
"مرحبا بالعالم",
|
||||
"Привет мир"
|
||||
};
|
||||
|
||||
for (const auto& test_text : test_texts) {
|
||||
auto tokens = tokenizer.encode(test_text);
|
||||
std::string decoded = tokenizer.decode(tokens);
|
||||
|
||||
std::cout << "\nOriginal: " << test_text << std::endl;
|
||||
std::cout << "Tokens: ";
|
||||
for (auto token : tokens) {
|
||||
std::cout << token << " ";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
std::cout << "Decoded: " << decoded << std::endl;
|
||||
std::cout << "Match: " << (test_text == decoded ? "YES" : "NO") << std::endl;
|
||||
}
|
||||
|
||||
// Save and load test
|
||||
tokenizer.save("unicode_bpe_model.txt");
|
||||
|
||||
lm::BPETokenizer loaded_tokenizer;
|
||||
if (loaded_tokenizer.load("unicode_bpe_model.txt")) {
|
||||
std::cout << "\nSuccessfully loaded Unicode tokenizer" << std::endl;
|
||||
std::cout << "Loaded vocabulary size: " << loaded_tokenizer.vocab_size() << std::endl;
|
||||
|
||||
// Test with the loaded tokenizer
|
||||
std::string test_text = "你好世界";
|
||||
auto tokens = loaded_tokenizer.encode(test_text);
|
||||
std::string decoded = loaded_tokenizer.decode(tokens);
|
||||
|
||||
std::cout << "Loaded tokenizer test:" << std::endl;
|
||||
std::cout << "Original: " << test_text << std::endl;
|
||||
std::cout << "Decoded: " << decoded << std::endl;
|
||||
std::cout << "Match: " << (test_text == decoded ? "YES" : "NO") << std::endl;
|
||||
}
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error: " << e.what() << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
# Tokenizer library
|
||||
add_library(lm_tokenizer
|
||||
bpe_tokenizer.cpp
|
||||
unicode_utils.cpp
|
||||
)
|
||||
|
||||
target_include_directories(lm_tokenizer
|
||||
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../../include
|
||||
)
|
||||
|
||||
target_link_libraries(lm_tokenizer
|
||||
PRIVATE
|
||||
ICU::uc
|
||||
ICU::i18n
|
||||
)
|
||||
|
||||
Executable
+758
@@ -0,0 +1,758 @@
|
||||
#include "lm/tokenizer/bpe_tokenizer.hpp"
|
||||
#include "lm/tokenizer/unicode_utils.hpp"
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <queue>
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
#include <sys/resource.h>
|
||||
|
||||
// Add CPU-specific optimizations
|
||||
#ifdef __SSE4_2__
|
||||
#include <nmmintrin.h> // For SSE4.2 intrinsics
|
||||
#endif
|
||||
|
||||
namespace lm {
|
||||
|
||||
// Custom hash function for pair<TokenID, TokenID>
|
||||
struct PairHash {
|
||||
size_t operator()(const std::pair<TokenID, TokenID>& p) const {
|
||||
return (static_cast<size_t>(p.first) << 16) | p.second;
|
||||
}
|
||||
};
|
||||
|
||||
// Memory tracking function
|
||||
size_t get_peak_memory_usage() {
|
||||
#ifdef __linux__
|
||||
std::ifstream status("/proc/self/status");
|
||||
std::string line;
|
||||
while (std::getline(status, line)) {
|
||||
if (line.compare(0, 6, "VmPeak") == 0) {
|
||||
std::istringstream iss(line);
|
||||
std::string key;
|
||||
size_t value;
|
||||
std::string unit;
|
||||
iss >> key >> value >> unit;
|
||||
if (unit == "kB") {
|
||||
return value * 1024; // Convert to bytes
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
// String interning class
|
||||
class StringInternPool {
|
||||
std::unordered_map<std::string, std::shared_ptr<const std::string>> pool;
|
||||
|
||||
public:
|
||||
std::shared_ptr<const std::string> intern(const std::string& str) {
|
||||
auto it = pool.find(str);
|
||||
if (it != pool.end()) {
|
||||
return it->second;
|
||||
}
|
||||
|
||||
auto shared_str = std::make_shared<std::string>(str);
|
||||
pool[str] = shared_str;
|
||||
return shared_str;
|
||||
}
|
||||
|
||||
void clear() {
|
||||
pool.clear();
|
||||
}
|
||||
};
|
||||
|
||||
struct BPETokenizer::Impl {
|
||||
std::unordered_map<std::string, TokenID> vocab;
|
||||
std::unordered_map<TokenID, std::string> inv_vocab;
|
||||
std::unordered_map<std::pair<TokenID, TokenID>, TokenID, PairHash> merges;
|
||||
std::unordered_map<std::string, TokenID> special_tokens;
|
||||
std::string unknown_token = "<unk>";
|
||||
TokenID unknown_token_id = 0;
|
||||
TokenID next_token_id = 0;
|
||||
bool normalization_enabled = true;
|
||||
bool byte_fallback_enabled = true;
|
||||
StringInternPool string_pool;
|
||||
|
||||
// Helper functions
|
||||
std::vector<std::string> split_text(const std::string& text) const;
|
||||
std::vector<TokenID> word_to_token_ids(const std::string& word) const;
|
||||
void initialize_vocab();
|
||||
void count_word_frequencies(const std::vector<std::string>& words,
|
||||
std::unordered_map<std::string, int>& word_counts) const;
|
||||
void get_pair_counts(const std::unordered_map<std::string, int>& word_counts,
|
||||
std::unordered_map<std::pair<TokenID, TokenID>, int, PairHash>& pair_counts) const;
|
||||
void perform_merge(const std::pair<TokenID, TokenID>& pair, TokenID new_token_id,
|
||||
std::unordered_map<std::string, int>& word_counts);
|
||||
|
||||
// CPU Optimization: Batch processing
|
||||
void process_string_batch(const std::vector<std::string>& batch);
|
||||
};
|
||||
|
||||
BPETokenizer::BPETokenizer() : pimpl_(new Impl) {
|
||||
pimpl_->initialize_vocab();
|
||||
}
|
||||
|
||||
BPETokenizer::~BPETokenizer() = default;
|
||||
|
||||
void BPETokenizer::Impl::initialize_vocab() {
|
||||
vocab.reserve(65536); // More realistic initial allocation
|
||||
inv_vocab.reserve(65536);
|
||||
|
||||
// Add bytes with optimized insertion
|
||||
for (int i = 0; i < 256; i++) {
|
||||
std::string token(1, static_cast<char>(i));
|
||||
vocab.emplace(token, next_token_id);
|
||||
inv_vocab.emplace(next_token_id++, std::move(token));
|
||||
}
|
||||
|
||||
// Add unknown token
|
||||
auto [it, inserted] = vocab.emplace(unknown_token, next_token_id);
|
||||
if (inserted) {
|
||||
inv_vocab.emplace(next_token_id, unknown_token);
|
||||
special_tokens.emplace(unknown_token, next_token_id);
|
||||
unknown_token_id = next_token_id++;
|
||||
} else {
|
||||
unknown_token_id = it->second;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> BPETokenizer::Impl::split_text(const std::string& text) const {
|
||||
if (normalization_enabled) {
|
||||
std::string normalized = unicode::normalize(text);
|
||||
return unicode::unicode_split(normalized);
|
||||
} else {
|
||||
std::vector<std::string> words;
|
||||
std::istringstream iss(text);
|
||||
std::string word;
|
||||
|
||||
while (iss >> word) {
|
||||
words.push_back(word);
|
||||
}
|
||||
|
||||
return words;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<TokenID> BPETokenizer::Impl::word_to_token_ids(const std::string& word) const {
|
||||
// Hot path optimization: use local references to avoid repeated pointer dereferencing
|
||||
const auto& local_vocab = vocab;
|
||||
const TokenID local_unknown_id = unknown_token_id;
|
||||
const bool local_byte_fallback = byte_fallback_enabled;
|
||||
const bool local_normalization = normalization_enabled;
|
||||
|
||||
std::vector<TokenID> tokens;
|
||||
|
||||
if (local_normalization) {
|
||||
std::string normalized = unicode::normalize(word);
|
||||
auto characters = unicode::split_on_character_boundaries(normalized);
|
||||
|
||||
for (const auto& character : characters) {
|
||||
auto it = local_vocab.find(character);
|
||||
if (it != local_vocab.end()) {
|
||||
tokens.push_back(it->second);
|
||||
} else if (local_byte_fallback) {
|
||||
// If character not found, try to split into bytes
|
||||
for (unsigned char c : character) {
|
||||
std::string byte_str(1, static_cast<char>(c));
|
||||
auto byte_it = local_vocab.find(byte_str);
|
||||
if (byte_it != local_vocab.end()) {
|
||||
tokens.push_back(byte_it->second);
|
||||
} else {
|
||||
tokens.push_back(local_unknown_id);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tokens.push_back(local_unknown_id);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Non-Unicode mode: treat as ASCII
|
||||
for (char c : word) {
|
||||
std::string token(1, c);
|
||||
auto it = local_vocab.find(token);
|
||||
if (it != local_vocab.end()) {
|
||||
tokens.push_back(it->second);
|
||||
} else {
|
||||
tokens.push_back(local_unknown_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
void BPETokenizer::Impl::count_word_frequencies(
|
||||
const std::vector<std::string>& words,
|
||||
std::unordered_map<std::string, int>& word_counts) const {
|
||||
|
||||
// Use a local reference to avoid repeated map lookups
|
||||
const auto& local_vocab = vocab;
|
||||
|
||||
for (const auto& word : words) {
|
||||
// Use string_view to avoid copies where possible
|
||||
auto it = word_counts.find(word);
|
||||
if (it != word_counts.end()) {
|
||||
it->second++;
|
||||
} else {
|
||||
word_counts[word] = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*void BPETokenizer::Impl::perform_merge(const std::pair<TokenID, TokenID>& pair, TokenID new_token_id,
|
||||
std::unordered_map<std::string, int>& word_counts) {
|
||||
std::string new_token = inv_vocab.at(pair.first) + inv_vocab.at(pair.second);
|
||||
|
||||
// Use move semantics to avoid copies
|
||||
auto shared_token = string_pool.intern(std::move(new_token));
|
||||
|
||||
// Add new token to vocabulary
|
||||
vocab[*shared_token] = new_token_id;
|
||||
inv_vocab[new_token_id] = *shared_token;
|
||||
merges[pair] = new_token_id;
|
||||
|
||||
// Update word counts more efficiently
|
||||
std::vector<std::string> to_remove;
|
||||
std::unordered_map<std::string, int> new_counts;
|
||||
|
||||
for (auto& [word, count] : word_counts) {
|
||||
std::string new_word;
|
||||
new_word.reserve(word.size()); // Pre-allocate
|
||||
|
||||
size_t pos = 0;
|
||||
while (pos < word.size()) {
|
||||
if (pos < word.size() - 1 &&
|
||||
word.substr(pos, inv_vocab.at(pair.first).size()) == inv_vocab.at(pair.first) &&
|
||||
word.substr(pos + inv_vocab.at(pair.first).size(), inv_vocab.at(pair.second).size()) == inv_vocab.at(pair.second)) {
|
||||
new_word += *shared_token;
|
||||
pos += inv_vocab.at(pair.first).size() + inv_vocab.at(pair.second).size();
|
||||
} else {
|
||||
new_word += word[pos++];
|
||||
}
|
||||
}
|
||||
|
||||
if (new_word != word) {
|
||||
to_remove.push_back(word);
|
||||
new_counts[new_word] += count;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove old words and add new ones
|
||||
for (const auto& word : to_remove) {
|
||||
word_counts.erase(word);
|
||||
}
|
||||
for (auto& [word, count] : new_counts) {
|
||||
word_counts[word] += count;
|
||||
}
|
||||
}*/
|
||||
|
||||
void BPETokenizer::Impl::perform_merge(const std::pair<TokenID, TokenID>& pair, TokenID new_token_id,
|
||||
std::unordered_map<std::string, int>& word_counts) {
|
||||
std::string new_token = inv_vocab.at(pair.first) + inv_vocab.at(pair.second);
|
||||
auto shared_token = string_pool.intern(new_token);
|
||||
|
||||
// Add new token to vocabulary
|
||||
vocab[*shared_token] = new_token_id;
|
||||
inv_vocab[new_token_id] = *shared_token;
|
||||
|
||||
// Record the merge
|
||||
merges[pair] = new_token_id;
|
||||
|
||||
// Update word counts with new merges
|
||||
std::unordered_map<std::string, int> new_word_counts;
|
||||
for (const auto& [word, count] : word_counts) {
|
||||
std::string new_word = word;
|
||||
size_t pos = 0;
|
||||
while ((pos = new_word.find(inv_vocab.at(pair.first) + inv_vocab.at(pair.second), pos)) != std::string::npos) {
|
||||
new_word.replace(pos, 2, *shared_token);
|
||||
pos += shared_token->length();
|
||||
}
|
||||
new_word_counts[new_word] += count;
|
||||
}
|
||||
|
||||
word_counts = std::move(new_word_counts);
|
||||
}
|
||||
|
||||
// CPU Optimization: Batch processing for better cache utilization
|
||||
void BPETokenizer::Impl::process_string_batch(const std::vector<std::string>& batch) {
|
||||
const size_t batch_size = batch.size();
|
||||
|
||||
#ifdef __SSE4_2__
|
||||
// Predefined patterns to detect
|
||||
const std::string url_pattern = "http";
|
||||
const std::string email_pattern = "@";
|
||||
const std::string number_pattern = "0123456789";
|
||||
|
||||
// Precompute pattern lengths
|
||||
const int url_len = url_pattern.size();
|
||||
const int email_len = email_pattern.size();
|
||||
const int number_len = number_pattern.size();
|
||||
|
||||
// Load patterns into SSE registers
|
||||
__m128i url_pattern_vec = _mm_loadu_si128(reinterpret_cast<const __m128i*>(url_pattern.c_str()));
|
||||
__m128i email_pattern_vec = _mm_loadu_si128(reinterpret_cast<const __m128i*>(email_pattern.c_str()));
|
||||
__m128i number_pattern_vec = _mm_loadu_si128(reinterpret_cast<const __m128i*>(number_pattern.c_str()));
|
||||
|
||||
for (size_t i = 0; i < batch_size; i++) {
|
||||
const std::string& str = batch[i];
|
||||
const size_t len = str.size();
|
||||
const char* data = str.data();
|
||||
|
||||
int url_count = 0;
|
||||
int email_count = 0;
|
||||
int number_count = 0;
|
||||
|
||||
// Process 16 characters at a time
|
||||
size_t j = 0;
|
||||
for (; j + 16 <= len; j += 16) {
|
||||
__m128i chunk = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data + j));
|
||||
|
||||
// Search for URL pattern using SSE4.2 string instructions
|
||||
int url_idx = _mm_cmpestri(
|
||||
url_pattern_vec, url_len,
|
||||
chunk, 16,
|
||||
_SIDD_CMP_EQUAL_ORDERED | _SIDD_UBYTE_OPS
|
||||
);
|
||||
|
||||
if (url_idx < 16) {
|
||||
url_count++;
|
||||
// Optional: Add special URL token if not already in vocabulary
|
||||
auto it = vocab.find("<URL>");
|
||||
if (it == vocab.end()) {
|
||||
vocab["<URL>"] = next_token_id;
|
||||
inv_vocab[next_token_id] = "<URL>";
|
||||
next_token_id++;
|
||||
}
|
||||
}
|
||||
|
||||
// Search for email pattern
|
||||
int email_idx = _mm_cmpestri(
|
||||
email_pattern_vec, email_len,
|
||||
chunk, 16,
|
||||
_SIDD_CMP_EQUAL_ORDERED | _SIDD_UBYTE_OPS
|
||||
);
|
||||
|
||||
if (email_idx < 16) {
|
||||
email_count++;
|
||||
// Optional: Add special email token
|
||||
auto it = vocab.find("<EMAIL>");
|
||||
if (it == vocab.end()) {
|
||||
vocab["<EMAIL>"] = next_token_id;
|
||||
inv_vocab[next_token_id] = "<EMAIL>";
|
||||
next_token_id++;
|
||||
}
|
||||
}
|
||||
|
||||
// Search for number patterns using range comparison
|
||||
__m128i digit_lo = _mm_cmpgt_epi8(chunk, _mm_set1_epi8('0' - 1));
|
||||
__m128i digit_hi = _mm_cmplt_epi8(chunk, _mm_set1_epi8('9' + 1));
|
||||
__m128i digit_mask = _mm_and_si128(digit_lo, digit_hi);
|
||||
|
||||
int digit_count = _mm_popcnt_u32(_mm_movemask_epi8(digit_mask));
|
||||
if (digit_count >= 3) { // Threshold for considering it a number
|
||||
number_count++;
|
||||
// Optional: Add special number token
|
||||
auto it = vocab.find("<NUMBER>");
|
||||
if (it == vocab.end()) {
|
||||
vocab["<NUMBER>"] = next_token_id;
|
||||
inv_vocab[next_token_id] = "<NUMBER>";
|
||||
next_token_id++;
|
||||
}
|
||||
}
|
||||
|
||||
// Additional pattern detection can be added here
|
||||
}
|
||||
|
||||
// Process remaining characters with traditional methods
|
||||
for (; j < len; j++) {
|
||||
// Check for URL pattern
|
||||
if (j + url_len <= len &&
|
||||
strncmp(data + j, url_pattern.c_str(), url_len) == 0) {
|
||||
url_count++;
|
||||
j += url_len - 1; // Skip ahead
|
||||
}
|
||||
|
||||
// Check for email pattern
|
||||
if (j + email_len <= len &&
|
||||
strncmp(data + j, email_pattern.c_str(), email_len) == 0) {
|
||||
email_count++;
|
||||
}
|
||||
|
||||
// Check for number pattern
|
||||
if (data[j] >= '0' && data[j] <= '9') {
|
||||
number_count++;
|
||||
}
|
||||
}
|
||||
|
||||
// Use pattern counts to make tokenization decisions
|
||||
if (url_count > 0) {
|
||||
// Apply special tokenization for URLs
|
||||
}
|
||||
|
||||
if (email_count > 0) {
|
||||
// Apply special tokenization for emails
|
||||
}
|
||||
|
||||
if (number_count > 5) { // Threshold for considering as numeric content
|
||||
// Apply special tokenization for numbers
|
||||
}
|
||||
}
|
||||
#else
|
||||
// Fallback implementation without SSE
|
||||
const std::string url_pattern = "http";
|
||||
const std::string email_pattern = "@";
|
||||
|
||||
for (const auto& str : batch) {
|
||||
int url_count = 0;
|
||||
int email_count = 0;
|
||||
int number_count = 0;
|
||||
|
||||
// Simple pattern matching without SSE
|
||||
for (size_t j = 0; j < str.size(); j++) {
|
||||
// Check for URL pattern
|
||||
if (j + url_pattern.size() <= str.size() &&
|
||||
str.substr(j, url_pattern.size()) == url_pattern) {
|
||||
url_count++;
|
||||
j += url_pattern.size() - 1;
|
||||
}
|
||||
|
||||
// Check for email pattern
|
||||
if (j + email_pattern.size() <= str.size() &&
|
||||
str.substr(j, email_pattern.size()) == email_pattern) {
|
||||
email_count++;
|
||||
}
|
||||
|
||||
// Check for numbers
|
||||
if (str[j] >= '0' && str[j] <= '9') {
|
||||
number_count++;
|
||||
}
|
||||
}
|
||||
|
||||
// Same logic as above for tokenization decisions
|
||||
if (url_count > 0) {
|
||||
auto it = vocab.find("<URL>");
|
||||
if (it == vocab.end()) {
|
||||
vocab["<URL>"] = next_token_id;
|
||||
inv_vocab[next_token_id] = "<URL>";
|
||||
next_token_id++;
|
||||
}
|
||||
}
|
||||
|
||||
// Similar handling for other patterns
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void BPETokenizer::train(const std::vector<std::string>& corpus, size_t vocab_size) {
|
||||
size_t start_memory = get_peak_memory_usage();
|
||||
|
||||
if (corpus.empty()) {
|
||||
throw std::invalid_argument("Corpus cannot be empty");
|
||||
}
|
||||
|
||||
// Split text into words
|
||||
std::vector<std::string> words;
|
||||
words.reserve(corpus.size() * 10); // Estimate average words per sentence
|
||||
|
||||
for (const auto& text : corpus) {
|
||||
auto text_words = pimpl_->split_text(text);
|
||||
words.insert(words.end(), text_words.begin(), text_words.end());
|
||||
}
|
||||
|
||||
// Count word frequencies using strings
|
||||
std::unordered_map<std::string, int> word_counts;
|
||||
word_counts.reserve(words.size());
|
||||
|
||||
pimpl_->count_word_frequencies(words, word_counts);
|
||||
|
||||
// Track token frequencies for pruning
|
||||
std::unordered_map<TokenID, size_t> token_frequencies;
|
||||
|
||||
// Initialize token frequencies
|
||||
for (const auto& [word, count] : word_counts) {
|
||||
auto tokens = pimpl_->word_to_token_ids(word);
|
||||
for (TokenID token : tokens) {
|
||||
token_frequencies[token] += count;
|
||||
}
|
||||
}
|
||||
|
||||
// BPE training algorithm with safety limit
|
||||
int iteration = 0;
|
||||
int max_iterations = 10000;
|
||||
|
||||
// Pruning function - remove infrequent tokens
|
||||
auto prune_infrequent_tokens = [&](size_t frequency_threshold = 2) {
|
||||
std::vector<TokenID> tokens_to_remove;
|
||||
|
||||
// Identify tokens to remove (excluding special tokens)
|
||||
for (const auto& [token_id, freq] : token_frequencies) {
|
||||
if (freq < frequency_threshold) {
|
||||
// Check if this is a special token
|
||||
std::string token_text = pimpl_->inv_vocab.at(token_id);
|
||||
if (pimpl_->special_tokens.find(token_text) == pimpl_->special_tokens.end()) {
|
||||
tokens_to_remove.push_back(token_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove tokens from vocabulary
|
||||
for (TokenID token_id : tokens_to_remove) {
|
||||
std::string token_text = pimpl_->inv_vocab.at(token_id);
|
||||
|
||||
// Remove from vocabulary mappings
|
||||
pimpl_->vocab.erase(token_text);
|
||||
pimpl_->inv_vocab.erase(token_id);
|
||||
token_frequencies.erase(token_id);
|
||||
|
||||
// Update word counts to use subword components instead of removed tokens
|
||||
std::unordered_map<std::string, int> updated_word_counts;
|
||||
for (const auto& [word, count] : word_counts) {
|
||||
std::string updated_word = word;
|
||||
size_t pos = 0;
|
||||
|
||||
// Replace all occurrences of the token text with its byte representation
|
||||
while ((pos = updated_word.find(token_text, pos)) != std::string::npos) {
|
||||
// Replace with byte fallback
|
||||
std::string replacement;
|
||||
for (unsigned char c : token_text) {
|
||||
std::string byte_str(1, static_cast<char>(c));
|
||||
replacement += byte_str;
|
||||
}
|
||||
updated_word.replace(pos, token_text.size(), replacement);
|
||||
pos += replacement.size();
|
||||
}
|
||||
|
||||
updated_word_counts[updated_word] += count;
|
||||
}
|
||||
|
||||
// Update the word_counts with the modified words
|
||||
word_counts = std::move(updated_word_counts);
|
||||
}
|
||||
|
||||
// Recalculate token frequencies after pruning
|
||||
token_frequencies.clear();
|
||||
for (const auto& [word, count] : word_counts) {
|
||||
auto tokens = pimpl_->word_to_token_ids(word);
|
||||
for (TokenID token : tokens) {
|
||||
token_frequencies[token] += count;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
while (pimpl_->vocab.size() < vocab_size && iteration < max_iterations) {
|
||||
// Count pairs
|
||||
std::unordered_map<std::pair<TokenID, TokenID>, int, PairHash> pair_counts;
|
||||
pimpl_->get_pair_counts(word_counts, pair_counts);
|
||||
|
||||
if (pair_counts.empty()) {
|
||||
std::cout << "No more pairs to merge. Stopping early." << std::endl;
|
||||
break;
|
||||
}
|
||||
|
||||
// Find most frequent pair
|
||||
auto max_pair = std::max_element(
|
||||
pair_counts.begin(), pair_counts.end(),
|
||||
[](const auto& a, const auto& b) { return a.second < b.second; }
|
||||
);
|
||||
|
||||
// Debug output
|
||||
if (iteration % 100 == 0) {
|
||||
std::cout << "Iteration " << iteration
|
||||
<< ", Vocab size: " << pimpl_->vocab.size()
|
||||
<< ", Most frequent pair: (" << max_pair->first.first
|
||||
<< "," << max_pair->first.second << ") count: "
|
||||
<< max_pair->second << std::endl;
|
||||
}
|
||||
|
||||
// Perform merge
|
||||
pimpl_->perform_merge(max_pair->first, pimpl_->next_token_id, word_counts);
|
||||
pimpl_->next_token_id++;
|
||||
|
||||
// Update token frequencies
|
||||
token_frequencies.clear();
|
||||
for (const auto& [word, count] : word_counts) {
|
||||
auto tokens = pimpl_->word_to_token_ids(word);
|
||||
for (TokenID token : tokens) {
|
||||
token_frequencies[token] += count;
|
||||
}
|
||||
}
|
||||
|
||||
// Periodically prune infrequent tokens
|
||||
if (iteration % 500 == 0 && iteration > 0) {
|
||||
size_t pre_prune_size = pimpl_->vocab.size();
|
||||
prune_infrequent_tokens(2); // Remove tokens with frequency < 2
|
||||
|
||||
std::cout << "Pruned " << (pre_prune_size - pimpl_->vocab.size())
|
||||
<< " infrequent tokens. New vocab size: "
|
||||
<< pimpl_->vocab.size() << std::endl;
|
||||
}
|
||||
|
||||
// Periodically check memory usage
|
||||
if (iteration % 500 == 0) {
|
||||
size_t current_memory = get_peak_memory_usage();
|
||||
std::cout << "Memory after " << iteration << " iterations: "
|
||||
<< (current_memory - start_memory) / (1024 * 1024) << "MB\n";
|
||||
}
|
||||
|
||||
iteration++;
|
||||
}
|
||||
|
||||
// Final pruning after training completes
|
||||
size_t pre_prune_size = pimpl_->vocab.size();
|
||||
prune_infrequent_tokens(3); // Remove tokens with frequency < 3
|
||||
std::cout << "Final pruning: Removed " << (pre_prune_size - pimpl_->vocab.size())
|
||||
<< " tokens. Final vocab size: " << pimpl_->vocab.size() << std::endl;
|
||||
|
||||
if (iteration >= max_iterations) {
|
||||
std::cout << "Reached maximum iterations. Stopping training." << std::endl;
|
||||
}
|
||||
|
||||
size_t end_memory = get_peak_memory_usage();
|
||||
std::cout << "Training completed in " << iteration << " iterations\n";
|
||||
std::cout << "Peak memory used: " << (end_memory - start_memory) / (1024 * 1024) << "MB\n";
|
||||
std::cout << "Final vocabulary size: " << pimpl_->vocab.size() << std::endl;
|
||||
|
||||
// Clear the string intern pool to free memory
|
||||
pimpl_->string_pool.clear();
|
||||
}
|
||||
std::string BPETokenizer::decode(const std::vector<TokenID>& tokens) const {
|
||||
std::string text;
|
||||
for (TokenID token_id : tokens) {
|
||||
if (pimpl_->inv_vocab.find(token_id) != pimpl_->inv_vocab.end()) {
|
||||
text += pimpl_->inv_vocab.at(token_id);
|
||||
} else {
|
||||
text += pimpl_->unknown_token;
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
bool BPETokenizer::save(const std::string& filename) const {
|
||||
std::ofstream file(filename);
|
||||
if (!file.is_open()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Save vocabulary
|
||||
file << pimpl_->vocab.size() << "\n";
|
||||
for (const auto& [token, id] : pimpl_->vocab) {
|
||||
file << id << " " << token << "\n";
|
||||
}
|
||||
|
||||
// Save merges
|
||||
file << pimpl_->merges.size() << "\n";
|
||||
for (const auto& [pair, new_id] : pimpl_->merges) {
|
||||
file << pair.first << " " << pair.second << " " << new_id << "\n";
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BPETokenizer::load(const std::string& filename) {
|
||||
std::ifstream file(filename);
|
||||
if (!file.is_open()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Clear existing data
|
||||
pimpl_->vocab.clear();
|
||||
pimpl_->inv_vocab.clear();
|
||||
pimpl_->merges.clear();
|
||||
|
||||
// Load vocabulary
|
||||
size_t vocab_size;
|
||||
file >> vocab_size;
|
||||
for (size_t i = 0; i < vocab_size; i++) {
|
||||
TokenID id;
|
||||
std::string token;
|
||||
file >> id;
|
||||
std::getline(file, token);
|
||||
// Remove leading space
|
||||
if (!token.empty() && token[0] == ' ') {
|
||||
token = token.substr(1);
|
||||
}
|
||||
pimpl_->vocab[token] = id;
|
||||
pimpl_->inv_vocab[id] = token;
|
||||
}
|
||||
|
||||
// Load merges
|
||||
size_t merge_count;
|
||||
file >> merge_count;
|
||||
for (size_t i = 0; i < merge_count; i++) {
|
||||
TokenID first, second, new_id;
|
||||
file >> first >> second >> new_id;
|
||||
pimpl_->merges[{first, second}] = new_id;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t BPETokenizer::vocab_size() const {
|
||||
return pimpl_->vocab.size();
|
||||
}
|
||||
|
||||
std::string BPETokenizer::id_to_token(TokenID id) const {
|
||||
if (pimpl_->inv_vocab.find(id) != pimpl_->inv_vocab.end()) {
|
||||
return pimpl_->inv_vocab.at(id);
|
||||
}
|
||||
return pimpl_->unknown_token;
|
||||
}
|
||||
|
||||
TokenID BPETokenizer::token_to_id(const std::string& token) const {
|
||||
if (pimpl_->vocab.find(token) != pimpl_->vocab.end()) {
|
||||
return pimpl_->vocab.at(token);
|
||||
}
|
||||
return pimpl_->unknown_token_id;
|
||||
}
|
||||
|
||||
void BPETokenizer::set_unknown_token(const std::string& token) {
|
||||
pimpl_->unknown_token = token;
|
||||
// If token already exists in vocab, use its ID
|
||||
if (pimpl_->vocab.find(token) != pimpl_->vocab.end()) {
|
||||
pimpl_->unknown_token_id = pimpl_->vocab.at(token);
|
||||
} else {
|
||||
// Add to vocab
|
||||
pimpl_->vocab[token] = pimpl_->next_token_id;
|
||||
pimpl_->inv_vocab[pimpl_->next_token_id] = token;
|
||||
pimpl_->unknown_token_id = pimpl_->next_token_id;
|
||||
pimpl_->next_token_id++;
|
||||
}
|
||||
}
|
||||
|
||||
void BPETokenizer::add_special_token(const std::string& token) {
|
||||
if (pimpl_->vocab.find(token) == pimpl_->vocab.end()) {
|
||||
pimpl_->vocab[token] = pimpl_->next_token_id;
|
||||
pimpl_->inv_vocab[pimpl_->next_token_id] = token;
|
||||
pimpl_->special_tokens[token] = pimpl_->next_token_id;
|
||||
pimpl_->next_token_id++;
|
||||
}
|
||||
}
|
||||
|
||||
void BPETokenizer::set_normalization(bool enabled) {
|
||||
pimpl_->normalization_enabled = enabled;
|
||||
}
|
||||
|
||||
void BPETokenizer::set_byte_fallback(bool enabled) {
|
||||
pimpl_->byte_fallback_enabled = enabled;
|
||||
}
|
||||
|
||||
void BPETokenizer::Impl::get_pair_counts(
|
||||
const std::unordered_map<std::string, int>& word_counts,
|
||||
std::unordered_map<std::pair<TokenID, TokenID>, int, PairHash>& pair_counts) const {
|
||||
|
||||
// Pre-allocate memory for better performance
|
||||
pair_counts.reserve(word_counts.size() * 10);
|
||||
|
||||
for (const auto& [word, count] : word_counts) {
|
||||
auto tokens = word_to_token_ids(word);
|
||||
for (size_t i = 0; i < tokens.size() - 1; i++) {
|
||||
auto pair = std::make_pair(tokens[i], tokens[i+1]);
|
||||
pair_counts[pair] += count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace lm
|
||||
Executable
+145
@@ -0,0 +1,145 @@
|
||||
/*# Unicode Utilities Implementation File
|
||||
|
||||
Here's the complete `src/tokenizer/unicode_utils.cpp` file:
|
||||
|
||||
```cpp*/
|
||||
#include "lm/tokenizer/unicode_utils.hpp"
|
||||
#include <unicode/uchar.h>
|
||||
#include <unicode/unistr.h>
|
||||
#include <unicode/normlzr.h>
|
||||
#include <unicode/ustring.h>
|
||||
#include <stdexcept>
|
||||
#include <algorithm>
|
||||
|
||||
namespace lm::unicode {
|
||||
|
||||
bool is_whitespace(uint32_t codepoint) {
|
||||
return u_isUWhiteSpace(codepoint);
|
||||
}
|
||||
|
||||
bool is_punctuation(uint32_t codepoint) {
|
||||
return u_ispunct(codepoint);
|
||||
}
|
||||
|
||||
bool is_control(uint32_t codepoint) {
|
||||
return u_iscntrl(codepoint);
|
||||
}
|
||||
|
||||
std::string normalize(const std::string& text) {
|
||||
try {
|
||||
icu::UnicodeString unicode_str = icu::UnicodeString::fromUTF8(text);
|
||||
icu::UnicodeString normalized;
|
||||
UErrorCode status = U_ZERO_ERROR;
|
||||
|
||||
icu::Normalizer::normalize(unicode_str, UNORM_NFC, 0, normalized, status);
|
||||
|
||||
if (U_FAILURE(status)) {
|
||||
throw std::runtime_error("Unicode normalization failed");
|
||||
}
|
||||
|
||||
std::string result;
|
||||
normalized.toUTF8String(result);
|
||||
return result;
|
||||
} catch (const std::exception& e) {
|
||||
throw std::runtime_error("Unicode normalization error: " + std::string(e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<CodePoint> to_code_points(const std::string& text) {
|
||||
std::vector<CodePoint> code_points;
|
||||
|
||||
for (size_t i = 0; i < text.size(); ) {
|
||||
CodePoint cp;
|
||||
uint32_t codepoint;
|
||||
int offset = 0;
|
||||
|
||||
// Decode UTF-8
|
||||
U8_NEXT(text.c_str(), i, text.size(), codepoint);
|
||||
|
||||
if (codepoint == U_SENTINEL) {
|
||||
// Handle invalid UTF-8 gracefully instead of throwing
|
||||
// Use replacement character (U+FFFD) for invalid sequences
|
||||
cp.value = 0xFFFD;
|
||||
cp.utf8 = "�"; // Replacement character
|
||||
code_points.push_back(cp);
|
||||
|
||||
// Skip this byte and continue
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get the UTF-8 bytes for this code point
|
||||
char utf8_buf[5] = {0};
|
||||
U8_APPEND_UNSAFE(utf8_buf, offset, codepoint);
|
||||
|
||||
cp.value = codepoint;
|
||||
cp.utf8 = std::string(utf8_buf, offset);
|
||||
code_points.push_back(cp);
|
||||
|
||||
i += offset;
|
||||
}
|
||||
|
||||
return code_points;
|
||||
}
|
||||
|
||||
std::string from_code_points(const std::vector<CodePoint>& code_points) {
|
||||
std::string result;
|
||||
for (const auto& cp : code_points) {
|
||||
result += cp.utf8;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<std::string> unicode_split(const std::string& text) {
|
||||
std::vector<std::string> words;
|
||||
std::string current_word;
|
||||
auto code_points = to_code_points(text);
|
||||
|
||||
for (const auto& cp : code_points) {
|
||||
if (is_whitespace(cp.value)) {
|
||||
if (!current_word.empty()) {
|
||||
words.push_back(current_word);
|
||||
current_word.clear();
|
||||
}
|
||||
} else {
|
||||
current_word += cp.utf8;
|
||||
}
|
||||
}
|
||||
|
||||
if (!current_word.empty()) {
|
||||
words.push_back(current_word);
|
||||
}
|
||||
|
||||
return words;
|
||||
}
|
||||
|
||||
std::vector<std::string> split_on_character_boundaries(const std::string& text) {
|
||||
std::vector<std::string> characters;
|
||||
auto code_points = to_code_points(text);
|
||||
|
||||
for (const auto& cp : code_points) {
|
||||
characters.push_back(cp.utf8);
|
||||
}
|
||||
|
||||
return characters;
|
||||
}
|
||||
|
||||
} // namespace lm::unicode
|
||||
/*```
|
||||
|
||||
This implementation provides comprehensive Unicode support for the BPE tokenizer with:
|
||||
|
||||
1. **Character classification** using ICU library functions
|
||||
2. **Unicode normalization** to NFC form for consistent processing
|
||||
3. **UTF-8 encoding/decoding** with proper error handling
|
||||
4. **Unicode-aware text splitting** based on character boundaries
|
||||
5. **Robust error handling** for invalid UTF-8 sequences
|
||||
|
||||
Key features:
|
||||
- **ICU library integration** for professional-grade Unicode handling
|
||||
- **Proper UTF-8 sequence processing** with boundary detection
|
||||
- **Character classification** for whitespace, punctuation, and control characters
|
||||
- **Normalization** to ensure consistent representation of equivalent Unicode sequences
|
||||
- **Exception safety** with proper error reporting
|
||||
|
||||
This implementation enables the BPE tokenizer to properly handle multilingual text, including complex scripts and emoji, while maintaining compatibility with ASCII text.*/
|
||||
Reference in new issue
Block a user