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
18 changes: 18 additions & 0 deletions operator/finetune_ops/core/autograd_engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,14 @@ void Engine::run_backward(const std::vector<TensorPtr>& 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);
Expand Down Expand Up @@ -218,6 +226,16 @@ void Engine::run_backward(const std::vector<TensorPtr>& 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();
}
}

Expand Down
14 changes: 14 additions & 0 deletions operator/finetune_ops/core/test_tokenizer_factory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<int>(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();
Expand Down
55 changes: 42 additions & 13 deletions operator/finetune_ops/core/tokenizer_bpe.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<AddedTokenInfo> 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");
Comment on lines +335 to +336

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not reject valid large added-token arrays

Any valid tokenizer.json whose root added_tokens array exceeds 1 MiB now throws during tokenizer construction, whereas the previous parser had no such size restriction. Tokenizers with many added vocabulary entries or long added-token contents therefore become unloadable; preserve bounded memory by parsing entries incrementally instead of imposing an undocumented fixed limit.

Useful? React with 👍 / 👎.

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",
Expand Down
29 changes: 28 additions & 1 deletion operator/finetune_ops/graph/qwen_model.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Comment on lines +225 to +226

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve strict shape checks in allocation-free mode

When allocate_weights is false, every weight slot remains null, so qwen_assign_checked skips its strict_shape_check && slot comparison even though strict checking defaults to enabled. A malformed streamed checkpoint can therefore install an incorrectly sized normalization weight and make rms_norm_affine read past its buffer, or accept projection shapes that fail only during the later forward pass. Validate assigned tensors against dimensions derived from QwenConfig rather than relying on allocated placeholders.

Useful? React with 👍 / 👎.

const bool defer_large_placeholders = qwen_should_defer_large_placeholders(cfg);
if (!defer_large_placeholders) {
embed_tokens_ = std::make_shared<Tensor>(std::vector<int64_t>{cfg.vocab_size, cfg.hidden_size}, kFloat32, kCPU);
Expand Down Expand Up @@ -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<float>()[i] = attention_mask->data<float>()[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]
Expand Down
4 changes: 4 additions & 0 deletions operator/finetune_ops/graph/qwen_model.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading