diff --git a/operator/finetune_ops/core/autograd_engine.cpp b/operator/finetune_ops/core/autograd_engine.cpp index 0e01c76..d719bbe 100644 --- a/operator/finetune_ops/core/autograd_engine.cpp +++ b/operator/finetune_ops/core/autograd_engine.cpp @@ -178,6 +178,14 @@ void Engine::run_backward(const std::vector& outputs, return; } + // First-order backward must not retain a second graph of its own work. + struct RecordingGuard { + bool& enabled; + bool previous; + explicit RecordingGuard(bool& flag) : enabled(flag), previous(flag) { enabled = false; } + ~RecordingGuard() { enabled = previous; } + } recording_guard(enabled_); + // Topological order: process each node after all of its consumers so // accumulated gradients are complete. auto topo = topological_sort(roots); @@ -218,6 +226,16 @@ void Engine::run_backward(const std::vector& outputs, // `continue` above. if (!node->tensor->retains_grad()) { pending_grads_.erase(raw_ptr); + // All consumers have run. Keeping this node's saved tensors until + // the entire backward finishes needlessly retains the forward + // graph alongside its gradients. Leaf/retained gradients stay in + // the registry for the final writeback below. + node->tensor->grad_node_.reset(); + node->backward_fn.reset(); + node->next_edges.clear(); + tensor_to_node_.erase(raw_ptr); + tensor_registry_.erase(raw_ptr); + node->tensor.reset(); } } diff --git a/operator/finetune_ops/core/test_tokenizer_factory.cpp b/operator/finetune_ops/core/test_tokenizer_factory.cpp index 3655a92..1b01639 100644 --- a/operator/finetune_ops/core/test_tokenizer_factory.cpp +++ b/operator/finetune_ops/core/test_tokenizer_factory.cpp @@ -284,9 +284,23 @@ void test_factory_loads_minimal_real_assets() { } } +void test_streamed_added_tokens() { + const fs::path root = make_case_dir("streamed_added_tokens"); + write_minimal_qwen_assets(root); + write_file(root / "tokenizer.json", + R"({"decoy":"added_tokens","model":{"ignored":")" + std::string(2*1024*1024,'x') + + R"("},"added_tokens":[{"id":8,"content":"[done]","special":true},{"id":9,"content":"<|endoftext|>","special":true},{"id":10,"content":"<|im_end|>","special":true}]})"); + auto tokenizer = ops::TokenizerFactory::from_pretrained(root.string()); + auto ids = tokenizer->encode("[done]"); + require_eq(static_cast(ids.size()),1,"streamed special token length"); + require_eq(ids[0],8,"brackets inside an added token must not close the JSON array"); + require_eq(tokenizer->get_eos_token(),10,"streamed EOS token mismatch"); +} + } // namespace int main() { + test_streamed_added_tokens(); test_config_inference(); test_explicit_override_and_errors(); test_factory_loads_minimal_real_assets(); diff --git a/operator/finetune_ops/core/tokenizer_bpe.cpp b/operator/finetune_ops/core/tokenizer_bpe.cpp index 40aa2a8..de95451 100644 --- a/operator/finetune_ops/core/tokenizer_bpe.cpp +++ b/operator/finetune_ops/core/tokenizer_bpe.cpp @@ -306,20 +306,49 @@ namespace simple_json { throw std::runtime_error("Cannot open: " + filepath); } - std::stringstream buffer; - buffer << f.rdbuf(); - std::string content = buffer.str(); - + // tokenizer.json contains the entire BPE vocabulary. Read only this + // small root property instead of holding two copies of the full file. std::vector tokens; - - // Slice the added_tokens array only to avoid heavyweight regex on large files - size_t start = content.find("\"added_tokens\""); - if (start == std::string::npos) return tokens; - start = content.find('[', start); - if (start == std::string::npos) return tokens; - size_t close = content.find(']', start); - if (close == std::string::npos) return tokens; - std::string slice = content.substr(start, close - start); + std::string slice; + int depth = 0; + char c = 0; + while (f.get(c)) { + if (c == '{' || c == '[') { ++depth; continue; } + if (c == '}' || c == ']') { --depth; continue; } + if (c != '"') continue; + std::string name; + bool escaped = false; + while (f.get(c)) { + if (!escaped && c == '"') break; + if (depth == 1 && name.size() < 64) name += c; + if (!escaped && c == '\\') escaped = true; + else escaped = false; + } + if (depth != 1 || name != "added_tokens") continue; + f >> std::ws; + if (f.peek() != ':') continue; + f.get(); f >> std::ws; + if (!f.get(c) || c != '[') throw std::runtime_error("Invalid added_tokens array"); + int array_depth = 1; + bool in_string = false; + escaped = false; + while (array_depth && f.get(c)) { + if (slice.size() >= 1024 * 1024) throw std::runtime_error("added_tokens array exceeds 1 MiB"); + if (in_string) { + if (!escaped && c == '"') in_string = false; + if (!escaped && c == '\\') escaped = true; + else escaped = false; + } else { + if (c == '"') in_string = true; + else if (c == '[') ++array_depth; + else if (c == ']') --array_depth; + } + if (array_depth) slice += c; + } + if (array_depth) throw std::runtime_error("Truncated added_tokens array"); + break; + } + if (slice.empty()) return tokens; std::regex item_re( R"REGEX("id"\s*:\s*(\d+)[^}]*?"content"\s*:\s*"((?:[^"\\]|\\.)*)"[^}]*?"special"\s*:\s*(true|false))REGEX", diff --git a/operator/finetune_ops/graph/qwen_model.cpp b/operator/finetune_ops/graph/qwen_model.cpp index 8905698..d773d70 100644 --- a/operator/finetune_ops/graph/qwen_model.cpp +++ b/operator/finetune_ops/graph/qwen_model.cpp @@ -220,7 +220,10 @@ QwenConfig QwenConfig::from_pretrained(const std::string& path) { } // -------------- Construction -------------- -QwenModel::QwenModel(const QwenConfig& cfg) : config_(cfg) { +QwenModel::QwenModel(const QwenConfig& cfg) : QwenModel(cfg, true) {} + +QwenModel::QwenModel(const QwenConfig& cfg, bool allocate_weights) : config_(cfg) { + if (!allocate_weights) { layers_.resize(cfg.num_hidden_layers); return; } const bool defer_large_placeholders = qwen_should_defer_large_placeholders(cfg); if (!defer_large_placeholders) { embed_tokens_ = std::make_shared(std::vector{cfg.vocab_size, cfg.hidden_size}, kFloat32, kCPU); @@ -627,6 +630,30 @@ TensorPtr QwenModel::mlp(const TensorPtr& x, QwenBlock& blk) { return down; } +TensorPtr QwenModel::forward_attention_block(const TensorPtr& hidden, const TensorPtr& attention_mask, int layer) { + if (layer < 0 || layer >= config_.num_hidden_layers) throw std::invalid_argument("Invalid block index"); + TensorPtr pad_mask; + if (attention_mask) { + pad_mask = zeros({attention_mask->shape()[0], 1, 1, attention_mask->shape()[1]}, kFloat32, kCPU); + for (int64_t i = 0; i < attention_mask->numel(); ++i) + pad_mask->data()[i] = attention_mask->data()[i] > 0.5f ? 0.0f : -1e9f; + } + auto& block = layers_[layer]; + auto norm = rms_norm_affine(hidden, block.input_norm_weight, config_.rms_norm_eps); + return add(hidden, attention(norm, block, build_causal_mask(hidden->shape()[1]), pad_mask, hidden->shape()[1])); +} + +TensorPtr QwenModel::forward_mlp_block(const TensorPtr& hidden, int layer) { + if (layer < 0 || layer >= config_.num_hidden_layers) throw std::invalid_argument("Invalid block index"); + auto& block = layers_[layer]; + auto norm = rms_norm_affine(hidden, block.post_norm_weight, config_.rms_norm_eps); + return add(hidden, mlp(norm, block)); +} + +TensorPtr QwenModel::forward_block(const TensorPtr& hidden, const TensorPtr& attention_mask, int layer) { + return forward_mlp_block(forward_attention_block(hidden, attention_mask, layer), layer); +} + // -------------- Forward -------------- TensorPtr QwenModel::forward_hidden(const TensorPtr& input_ids, const TensorPtr& attention_mask) { auto x = embedding_lookup(embed_tokens_, input_ids); // [B,S,H] diff --git a/operator/finetune_ops/graph/qwen_model.h b/operator/finetune_ops/graph/qwen_model.h index d86ef97..0a20b3a 100644 --- a/operator/finetune_ops/graph/qwen_model.h +++ b/operator/finetune_ops/graph/qwen_model.h @@ -77,6 +77,10 @@ struct QwenKVCache { class QwenModel { public: explicit QwenModel(const QwenConfig& cfg); + QwenModel(const QwenConfig& cfg, bool allocate_weights); + TensorPtr forward_attention_block(const TensorPtr& hidden, const TensorPtr& attention_mask, int layer = 0); + TensorPtr forward_mlp_block(const TensorPtr& hidden, int layer = 0); + TensorPtr forward_block(const TensorPtr& hidden, const TensorPtr& attention_mask, int layer = 0); ~QwenModel() = default; TensorPtr forward_hidden(const TensorPtr& input_ids, const TensorPtr& attention_mask = nullptr);