Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
130 changes: 130 additions & 0 deletions cpp/grammar_matcher.cc
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include <xgrammar/matcher.h>

#include <algorithm>
#include <chrono>
#include <cstdint>
#include <optional>
#include <thread>
Expand All @@ -36,6 +37,100 @@ int32_t GetBitmaskSize(int vocab_size) { return DynamicBitset::GetBufferSize(voc

DLDataType GetBitmaskDLType() { return DLDataType{kDLInt, 32, 1}; }

namespace details {

using Clock = std::chrono::steady_clock;
using TimePoint = Clock::time_point;

bool TraverseDraftTreeRecursive(
int32_t current_position,
int32_t parent_position,
const int64_t* retrieve_next_token,
const int64_t* retrieve_next_sibling,
const int64_t* draft_tokens,
GrammarMatcher& matcher,
DLTensor* token_bitmask,
double time_threshold,
const TimePoint& start_time
) {
int32_t* bitmask_data = reinterpret_cast<int32_t*>(token_bitmask->data);
int32_t bitmask_size = static_cast<int32_t>(token_bitmask->shape[1]);
Comment on lines +60 to +61

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The implementation ignores the byte_offset of the token_bitmask DLTensor. According to the DLPack specification, the actual data pointer should be calculated as (char*)data + byte_offset. Additionally, the code assumes the tensor is contiguous by using shape[1] as the row stride. If the input tensor is a slice or has padding, this will lead to incorrect memory access. It is recommended to use strides[0] (if not null) to navigate between rows.


bool accepted;
if (current_position == 0) {
// The first token generated by the target model is always accepted.
accepted = true;
} else {
int32_t current_token_id = draft_tokens[current_position];
int32_t* parent_bitmask = bitmask_data + parent_position * bitmask_size;
// 32 boolean bitmask values are packed into 32-bit integers.
accepted = (parent_bitmask[current_token_id / 32] & (1 << (current_token_id % 32))) != 0;

Copilot AI May 1, 2026

Copy link

Choose a reason for hiding this comment

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

TraverseDraftTreeRecursive computes parent_bitmask = bitmask_data + parent_position * bitmask_size for every non-root node without validating that parent_position is non-negative. If the input tree is malformed (e.g., retrieve_next_sibling[0] != -1 or any traversal path reaches a node with parent_position == -1), this will index before the buffer and cause memory corruption. Please enforce the invariant (no root siblings / valid parent_position for non-root nodes) with a check, or restructure the logic to avoid using an invalid parent_position.

Copilot uses AI. Check for mistakes.

// Check timeout for non-root nodes so the root token mask is still computed.
if (time_threshold > 0) {
auto elapsed = std::chrono::duration<double>(Clock::now() - start_time).count();
if (elapsed > time_threshold) {
return false;
}
}
}

if (accepted) {
if (current_position != 0) {
matcher.AcceptToken(draft_tokens[current_position]);
}

if (!matcher.IsTerminated()) {
matcher.FillNextTokenBitmask(token_bitmask, current_position);

if (retrieve_next_token[current_position] != -1) {
bool success = TraverseDraftTreeRecursive(
retrieve_next_token[current_position],
current_position,
retrieve_next_token,
retrieve_next_sibling,
draft_tokens,
matcher,
token_bitmask,
time_threshold,
start_time
);
if (!success) {
if (current_position != 0) {
matcher.Rollback(1);
}
return false;
}
}
}

if (current_position != 0) {
matcher.Rollback(1);
}
}
Comment on lines +63 to +130

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

There are several issues in the recursive traversal logic:

  1. OOB Access: current_token_id is used to index parent_bitmask without checking if it's within the valid range [0, vocab_size). This can lead to crashes or undefined behavior if the draft model produces an invalid token ID.
  2. Incorrect Rollback: If matcher.AcceptToken fails (returns false), the code still calls matcher.Rollback(1) at the end of the block. This will incorrectly pop a state that was pushed by a previous successful token acceptance, corrupting the matcher's state for other branches of the tree.
  3. Uninitialized Bitmasks: If a node is not accepted (either by the parent bitmask or the grammar), its corresponding row in token_bitmask is never filled. Since token_bitmask is typically initialized to all ones (unmasked) in Python, these rejected nodes will incorrectly appear as having no constraints.
  4. Termination Handling: If the matcher is terminated, FillNextTokenBitmask cannot be called. The bitmask for such nodes should be zeroed out to indicate no further tokens are allowed.
  bool accepted;
  if (current_position == 0) {
    // The first token generated by the target model is always accepted.
    accepted = true;
  } else {
    int32_t current_token_id = static_cast<int32_t>(draft_tokens[current_position]);
    // Check if the token is within the valid range for the bitmask.
    if (current_token_id < 0 || current_token_id / 32 >= bitmask_size) {
      accepted = false;
    } else {
      int32_t* parent_bitmask = bitmask_data + parent_position * bitmask_size;
      // 32 boolean bitmask values are packed into 32-bit integers.
      accepted = (parent_bitmask[current_token_id / 32] & (1 << (current_token_id % 32))) != 0;
    }

    // Check timeout for non-root nodes so the root token mask is still computed.
    if (accepted && time_threshold > 0) {
      auto elapsed = std::chrono::duration<double>(Clock::now() - start_time).count();
      if (elapsed > time_threshold) {
        return false;
      }
    }
  }

  if (accepted) {
    bool token_accepted = true;
    if (current_position != 0) {
      token_accepted = matcher.AcceptToken(draft_tokens[current_position]);
    }

    if (token_accepted) {
      if (!matcher.IsTerminated()) {
        matcher.FillNextTokenBitmask(token_bitmask, current_position);

        if (retrieve_next_token[current_position] != -1) {
          bool success = TraverseDraftTreeRecursive(
              retrieve_next_token[current_position],
              current_position,
              retrieve_next_token,
              retrieve_next_sibling,
              draft_tokens,
              matcher,
              token_bitmask,
              time_threshold,
              start_time
          );
          if (!success) {
            if (current_position != 0) {
              matcher.Rollback(1);
            }
            return false;
          }
        }
      } else {
        // If terminated, no more tokens are allowed from this node.
        std::fill_n(bitmask_data + current_position * bitmask_size, bitmask_size, 0);
      }

      if (current_position != 0) {
        matcher.Rollback(1);
      }
    } else {
      // Token rejected by grammar: zero out the bitmask for this node.
      std::fill_n(bitmask_data + current_position * bitmask_size, bitmask_size, 0);
    }
  } else {
    // Node not accepted: zero out the bitmask for this node.
    std::fill_n(bitmask_data + current_position * bitmask_size, bitmask_size, 0);
  }


if (retrieve_next_sibling[current_position] != -1) {
bool success = TraverseDraftTreeRecursive(
retrieve_next_sibling[current_position],
parent_position,
retrieve_next_token,
retrieve_next_sibling,
draft_tokens,
matcher,
token_bitmask,
time_threshold,
start_time
);
if (!success) {
return false;
}
Comment on lines +60 to +146

Copilot AI May 1, 2026

Copy link

Choose a reason for hiding this comment

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

TraverseDraftTreeRecursive uses recursion for both child and sibling traversal. Since this is now part of the public GrammarMatcher API, very deep/degenerate draft trees (e.g., long linear chains with timeout disabled) can cause stack overflow. Consider rewriting this traversal iteratively with an explicit stack (or enforcing a maximum depth) to make the API robust for untrusted/large inputs.

Suggested change
int32_t* bitmask_data = reinterpret_cast<int32_t*>(token_bitmask->data);
int32_t bitmask_size = static_cast<int32_t>(token_bitmask->shape[1]);
bool accepted;
if (current_position == 0) {
// The first token generated by the target model is always accepted.
accepted = true;
} else {
XGRAMMAR_CHECK(parent_position >= 0)
<< "Non-root draft tree nodes must have a valid parent position";
int64_t current_token_id = draft_tokens[current_position];
if (current_token_id < 0 || current_token_id >= static_cast<int64_t>(bitmask_size) * 32) {
accepted = false;
} else {
int32_t* parent_bitmask = bitmask_data + parent_position * bitmask_size;
// 32 boolean bitmask values are packed into 32-bit integers.
uint32_t token_mask = uint32_t{1} << static_cast<uint32_t>(current_token_id % 32);
accepted = (static_cast<uint32_t>(parent_bitmask[current_token_id / 32]) & token_mask) != 0;
}
// Check timeout for non-root nodes so the root token mask is still computed.
if (accepted && time_threshold > 0) {
auto elapsed = std::chrono::duration<double>(Clock::now() - start_time).count();
if (elapsed > time_threshold) {
return false;
}
}
}
if (accepted) {
bool token_accepted = true;
if (current_position != 0) {
token_accepted = matcher.AcceptToken(static_cast<int32_t>(draft_tokens[current_position]));
}
if (token_accepted) {
if (!matcher.IsTerminated()) {
matcher.FillNextTokenBitmask(token_bitmask, current_position);
if (retrieve_next_token[current_position] != -1) {
bool success = TraverseDraftTreeRecursive(
retrieve_next_token[current_position],
current_position,
retrieve_next_token,
retrieve_next_sibling,
draft_tokens,
matcher,
token_bitmask,
time_threshold,
start_time
);
if (!success) {
if (current_position != 0) {
matcher.Rollback(1);
}
return false;
}
}
} else {
ClearTokenBitmaskRow(bitmask_data, bitmask_size, current_position);
}
if (current_position != 0) {
matcher.Rollback(1);
}
} else {
ClearTokenBitmaskRow(bitmask_data, bitmask_size, current_position);
}
} else {
ClearTokenBitmaskRow(bitmask_data, bitmask_size, current_position);
}
if (retrieve_next_sibling[current_position] != -1) {
bool success = TraverseDraftTreeRecursive(
retrieve_next_sibling[current_position],
parent_position,
retrieve_next_token,
retrieve_next_sibling,
draft_tokens,
matcher,
token_bitmask,
time_threshold,
start_time
);
if (!success) {
return false;
}
struct TraversalFrame {
int32_t current_position;
int32_t parent_position;
bool entered;
bool rollback_on_exit;
};
int32_t* bitmask_data = reinterpret_cast<int32_t*>(token_bitmask->data);
int32_t bitmask_size = static_cast<int32_t>(token_bitmask->shape[1]);
std::vector<TraversalFrame> stack;
stack.push_back({current_position, parent_position, false, false});
while (!stack.empty()) {
TraversalFrame& frame = stack.back();
if (!frame.entered) {
frame.entered = true;
bool accepted;
if (frame.current_position == 0) {
// The first token generated by the target model is always accepted.
accepted = true;
} else {
XGRAMMAR_CHECK(frame.parent_position >= 0)
<< "Non-root draft tree nodes must have a valid parent position";
int64_t current_token_id = draft_tokens[frame.current_position];
if (current_token_id < 0 || current_token_id >= static_cast<int64_t>(bitmask_size) * 32) {
accepted = false;
} else {
int32_t* parent_bitmask = bitmask_data + frame.parent_position * bitmask_size;
// 32 boolean bitmask values are packed into 32-bit integers.
uint32_t token_mask = uint32_t{1} << static_cast<uint32_t>(current_token_id % 32);
accepted =
(static_cast<uint32_t>(parent_bitmask[current_token_id / 32]) & token_mask) != 0;
}
// Check timeout for non-root nodes so the root token mask is still computed.
if (accepted && time_threshold > 0) {
auto elapsed = std::chrono::duration<double>(Clock::now() - start_time).count();
if (elapsed > time_threshold) {
return false;
}
}
}
if (!accepted) {
ClearTokenBitmaskRow(bitmask_data, bitmask_size, frame.current_position);
int64_t sibling_position = retrieve_next_sibling[frame.current_position];
stack.pop_back();
if (sibling_position != -1) {
stack.push_back(
{static_cast<int32_t>(sibling_position), frame.parent_position, false, false}
);
}
continue;
}
bool token_accepted = true;
if (frame.current_position != 0) {
token_accepted = matcher.AcceptToken(static_cast<int32_t>(draft_tokens[frame.current_position]));
}
if (!token_accepted) {
ClearTokenBitmaskRow(bitmask_data, bitmask_size, frame.current_position);
int64_t sibling_position = retrieve_next_sibling[frame.current_position];
stack.pop_back();
if (sibling_position != -1) {
stack.push_back(
{static_cast<int32_t>(sibling_position), frame.parent_position, false, false}
);
}
continue;
}
frame.rollback_on_exit = (frame.current_position != 0);
if (matcher.IsTerminated()) {
ClearTokenBitmaskRow(bitmask_data, bitmask_size, frame.current_position);
} else {
matcher.FillNextTokenBitmask(token_bitmask, frame.current_position);
}
int64_t child_position = retrieve_next_token[frame.current_position];
if (child_position != -1 && !matcher.IsTerminated()) {
stack.push_back(
{static_cast<int32_t>(child_position), frame.current_position, false, false}
);
}
continue;
}
int64_t sibling_position = retrieve_next_sibling[frame.current_position];
int32_t sibling_parent_position = frame.parent_position;
bool rollback_on_exit = frame.rollback_on_exit;
stack.pop_back();
if (rollback_on_exit) {
matcher.Rollback(1);
}
if (sibling_position != -1) {
stack.push_back(
{static_cast<int32_t>(sibling_position), sibling_parent_position, false, false}
);
}

Copilot uses AI. Check for mistakes.
}
Comment on lines +132 to +147

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The sibling traversal is implemented recursively. While this is tail-recursive, it is safer and more idiomatic to use an iterative loop for siblings to avoid potential stack overflow issues on very wide trees, especially since this is now part of the core public API. A while loop similar to the one in ClearDraftTreeSiblingChain would be more robust.


return true;
}

} // namespace details

int32_t* CheckAndGetBitmaskPtr(const DLTensor& token_bitmask, int vocab_size, int index) {
XGRAMMAR_CHECK(token_bitmask.dtype.code == kDLInt && token_bitmask.dtype.bits == 32)
<< "The provied bitmask's dtype is not valid: should be int32";
Expand Down Expand Up @@ -1103,6 +1198,41 @@ bool GrammarMatcher::FillNextTokenBitmask(
return pimpl_->FillNextTokenBitmask(next_token_bitmask, index, debug_print);
}

bool GrammarMatcher::TraverseDraftTree(
const DLTensor* retrieve_next_token,
const DLTensor* retrieve_next_sibling,
const DLTensor* draft_tokens,
DLTensor* token_bitmask,
double time_threshold
) {
XGRAMMAR_CHECK(retrieve_next_token->dtype.code == kDLInt && retrieve_next_token->dtype.bits == 64)
<< "The retrieve_next_token tensor must be int64";
XGRAMMAR_CHECK(
retrieve_next_sibling->dtype.code == kDLInt && retrieve_next_sibling->dtype.bits == 64
) << "The retrieve_next_sibling tensor must be int64";
XGRAMMAR_CHECK(draft_tokens->dtype.code == kDLInt && draft_tokens->dtype.bits == 64)
<< "The draft_tokens tensor must be int64";
XGRAMMAR_CHECK(token_bitmask->dtype.code == kDLInt && token_bitmask->dtype.bits == 32)
<< "The token_bitmask tensor must be int32";

XGRAMMAR_CHECK(retrieve_next_token->shape[0] == retrieve_next_sibling->shape[0])
<< "The retrieve_next_token and retrieve_next_sibling tensors must have the same length";
XGRAMMAR_CHECK(retrieve_next_token->shape[0] == draft_tokens->shape[0])
<< "The retrieve_next_token and draft_tokens tensors must have the same length";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The input tensors should be validated for device (must be CPU) and dimensions (ndim) before accessing their data pointers. Additionally, token_bitmask should be checked to ensure its batch size matches the number of nodes in the tree.

  XGRAMMAR_CHECK(retrieve_next_token->ndim == 1 && retrieve_next_token->dtype.code == kDLInt && retrieve_next_token->dtype.bits == 64)
      << "The retrieve_next_token tensor must be a 1D int64 tensor";
  XGRAMMAR_CHECK(retrieve_next_sibling->ndim == 1 && retrieve_next_sibling->dtype.code == kDLInt && retrieve_next_sibling->dtype.bits == 64)
      << "The retrieve_next_sibling tensor must be a 1D int64 tensor";
  XGRAMMAR_CHECK(draft_tokens->ndim == 1 && draft_tokens->dtype.code == kDLInt && draft_tokens->dtype.bits == 64)
      << "The draft_tokens tensor must be a 1D int64 tensor";
  XGRAMMAR_CHECK(token_bitmask->ndim == 2 && token_bitmask->dtype.code == kDLInt && token_bitmask->dtype.bits == 32)
      << "The token_bitmask tensor must be a 2D int32 tensor";

  auto check_cpu = [](const DLTensor* tensor, const char* name) {
    XGRAMMAR_CHECK(tensor->device.device_type == kDLCPU ||
                   tensor->device.device_type == kDLCUDAHost ||
                   tensor->device.device_type == kDLROCMHost)
        << "The " << name << " tensor must be on CPU";
  };
  check_cpu(retrieve_next_token, "retrieve_next_token");
  check_cpu(retrieve_next_sibling, "retrieve_next_sibling");
  check_cpu(draft_tokens, "draft_tokens");
  check_cpu(token_bitmask, "token_bitmask");

  XGRAMMAR_CHECK(retrieve_next_token->shape[0] == retrieve_next_sibling->shape[0])
      << "The retrieve_next_token and retrieve_next_sibling tensors must have the same length";
  XGRAMMAR_CHECK(retrieve_next_token->shape[0] == draft_tokens->shape[0])
      << "The retrieve_next_token and draft_tokens tensors must have the same length";
  XGRAMMAR_CHECK(retrieve_next_token->shape[0] == token_bitmask->shape[0])
      << "The token_bitmask batch size must match the number of nodes in the tree";

Copilot AI May 1, 2026

Copy link

Choose a reason for hiding this comment

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

GrammarMatcher::TraverseDraftTree validates dtypes and matching lengths, but does not validate that the tensors are CPU-accessible and have the expected ranks/shapes (e.g., token_bitmask is assumed 2D and accessed via shape[1] in the recursion). Passing a 1D bitmask or any GPU-only tensor can lead to out-of-bounds reads or dereferencing device memory in host code. Please add explicit checks for ndim (retrieve_* and draft_tokens are 1D; token_bitmask is 2D), token_bitmask.shape[0] == num_nodes, and that all inputs are on CPU/host-accessible devices before starting the traversal.

Copilot uses AI. Check for mistakes.

return details::TraverseDraftTreeRecursive(
0,
-1,
reinterpret_cast<const int64_t*>(retrieve_next_token->data),
reinterpret_cast<const int64_t*>(retrieve_next_sibling->data),
reinterpret_cast<const int64_t*>(draft_tokens->data),
*this,
token_bitmask,
time_threshold,
details::Clock::now()
);
}

std::string GrammarMatcher::FindJumpForwardString() { return pimpl_->FindJumpForwardString(); }

void GrammarMatcher::Rollback(int num_tokens) { pimpl_->Rollback(num_tokens); }
Comment on lines +1276 to 1284

Copilot AI May 1, 2026

Copy link

Choose a reason for hiding this comment

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

TraverseDraftTree dereferences raw DLTensor->data pointers later in the function, but currently only checks retrieve_next_sibling->data for null. Please add explicit non-null (and non-empty where relevant) checks for retrieve_next_token->data, draft_tokens->data, and token_bitmask->data as well, to avoid potential null dereference crashes when called through DLPack/FFI.

Copilot uses AI. Check for mistakes.
Expand Down
132 changes: 1 addition & 131 deletions cpp/testing.cc
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

#include <xgrammar/xgrammar.h>

#include <chrono>
#include <algorithm>
#include <cstdint>
#include <sstream>
#include <string>
Expand Down Expand Up @@ -58,134 +58,4 @@ std::string _PrintGrammarFSMs(const Grammar& grammar) {
return result;
}

namespace details {

using Clock = std::chrono::steady_clock;
using TimePoint = Clock::time_point;

bool DFS(
int32_t curr,
int32_t parent_pos,
const int64_t* retrieve_next_token,
const int64_t* retrieve_next_sibling,
const int64_t* draft_tokens,
GrammarMatcher& matcher,
DLTensor* bitmask,
double time_threshold,
const TimePoint& start_time
) {
int32_t* bitmask_data = reinterpret_cast<int32_t*>(bitmask->data);
int32_t bitmask_size = static_cast<int32_t>(bitmask->shape[1]);

bool accepted;
if (curr == 0) {
// The first token generated by the target model, always accepted
accepted = true;
} else {
int32_t curr_token_id = draft_tokens[curr];
int32_t* parent_bitmask = bitmask_data + parent_pos * bitmask_size;
// 32 boolean bitmask values are packed into 32-bit integers
accepted = (parent_bitmask[curr_token_id / 32] & (1 << (curr_token_id % 32))) != 0;

// Check timeout for non-root nodes (so that it can at least compute vocab mask
// for the root node, matching the non-speculative-decoding overhead)
if (time_threshold > 0) {
auto elapsed = std::chrono::duration<double>(Clock::now() - start_time).count();
if (elapsed > time_threshold) {
return false;
}
}
}

if (accepted) {
if (curr != 0) {
matcher.AcceptToken(draft_tokens[curr]);
}

if (!matcher.IsTerminated()) {
matcher.FillNextTokenBitmask(bitmask, curr);

if (retrieve_next_token[curr] != -1) {
bool success =
DFS(retrieve_next_token[curr],
curr,
retrieve_next_token,
retrieve_next_sibling,
draft_tokens,
matcher,
bitmask,
time_threshold,
start_time);
if (!success) {
if (curr != 0) {
matcher.Rollback(1);
}
return false;
}
}
}

if (curr != 0) {
matcher.Rollback(1);
}
}

if (retrieve_next_sibling[curr] != -1) {
bool success =
DFS(retrieve_next_sibling[curr],
parent_pos,
retrieve_next_token,
retrieve_next_sibling,
draft_tokens,
matcher,
bitmask,
time_threshold,
start_time);
if (!success) {
return false;
}
}

return true;
}

} // namespace details

bool TraverseDraftTree(
const DLTensor* retrieve_next_token,
const DLTensor* retrieve_next_sibling,
const DLTensor* draft_tokens,
GrammarMatcher& matcher,
DLTensor* bitmask,
double time_threshold
) {
// Check dtype
XGRAMMAR_CHECK(retrieve_next_token->dtype.code == kDLInt && retrieve_next_token->dtype.bits == 64)
<< "The retrieve_next_token tensor must be int64";
XGRAMMAR_CHECK(
retrieve_next_sibling->dtype.code == kDLInt && retrieve_next_sibling->dtype.bits == 64
) << "The retrieve_next_sibling tensor must be int64";
XGRAMMAR_CHECK(draft_tokens->dtype.code == kDLInt && draft_tokens->dtype.bits == 64)
<< "The draft_tokens tensor must be int64";
XGRAMMAR_CHECK(bitmask->dtype.code == kDLInt && bitmask->dtype.bits == 32)
<< "The bitmask tensor must be int32";

XGRAMMAR_CHECK(retrieve_next_token->shape[0] == retrieve_next_sibling->shape[0])
<< "The retrieve_next_token and retrieve_next_sibling tensors must have the same length";
XGRAMMAR_CHECK(retrieve_next_token->shape[0] == draft_tokens->shape[0])
<< "The retrieve_next_token and draft_tokens tensors must have the same length";

return details::DFS(
0,
-1,
reinterpret_cast<const int64_t*>(retrieve_next_token->data),
reinterpret_cast<const int64_t*>(retrieve_next_sibling->data),
reinterpret_cast<const int64_t*>(draft_tokens->data),
matcher,
bitmask,
time_threshold,
details::Clock::now()
);
}

} // namespace xgrammar
27 changes: 0 additions & 27 deletions cpp/testing.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,33 +25,6 @@ Grammar _EBNFToGrammarNoNormalization(

std::string _PrintGrammarFSMs(const Grammar& grammar);

/*!
* \brief Traverse the tree constructed by the draft model to generate the logits mask.
*
* This function performs a DFS traversal of the speculative decoding tree and fills
* the token bitmask for each position based on grammar constraints.
*
* \param retrieve_next_token DLTensor where retrieve_next_token[i] gives the index of
* the child node of node i, or -1 if no child exists.
* \param retrieve_next_sibling DLTensor where retrieve_next_sibling[i] gives the index of
* the sibling node of node i, or -1 if no sibling exists.
* \param draft_tokens DLTensor of draft token ids at each position in the tree.
* \param matcher The grammar matcher to use for validation.
* \param bitmask DLTensor to store the bitmask (2D: num_nodes x bitmask_size).
* \param time_threshold Maximum allowed time in seconds for the DFS traversal.
* If the traversal exceeds this threshold, it returns false.
* A value <= 0 disables the timeout (default: -1.0).
* \return true if the traversal completed successfully, false if it timed out.
*/
bool TraverseDraftTree(
const DLTensor* retrieve_next_token,
const DLTensor* retrieve_next_sibling,
const DLTensor* draft_tokens,
GrammarMatcher& matcher,
DLTensor* bitmask,
double time_threshold = -1.0
);

} // namespace xgrammar

#endif // XGRAMMAR_TESTING_H_
24 changes: 22 additions & 2 deletions cpp/tvm_ffi/tvm_ffi.cc
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,27 @@ TVM_FFI_STATIC_INIT_BLOCK() {
return o->value.FillNextTokenBitmask(dlt, static_cast<int>(index), debug_print);
}
)
.def(
"traverse_draft_tree",
[](GrammarMatcherObj* o,
ffi::AnyView retrieve_next_token,
ffi::AnyView retrieve_next_sibling,
ffi::AnyView draft_tokens,
ffi::AnyView token_bitmask,
double time_threshold) {
DLTensor* retrieve_next_token_ptr = retrieve_next_token.cast<DLTensor*>();
DLTensor* retrieve_next_sibling_ptr = retrieve_next_sibling.cast<DLTensor*>();
DLTensor* draft_tokens_ptr = draft_tokens.cast<DLTensor*>();
DLTensor* token_bitmask_ptr = token_bitmask.cast<DLTensor*>();
return o->value.TraverseDraftTree(
retrieve_next_token_ptr,
retrieve_next_sibling_ptr,
draft_tokens_ptr,
token_bitmask_ptr,
time_threshold
);
}
)
.def(
"find_jump_forward_string",
[](GrammarMatcherObj* o) { return ffi::String(o->value.FindJumpForwardString()); }
Expand Down Expand Up @@ -919,11 +940,10 @@ TVM_FFI_STATIC_INIT_BLOCK() {
time_threshold_opt == nullptr ? -1.0 : time_threshold_opt.cast<double>();
GrammarMatcher& matcher =
const_cast<GrammarMatcher&>(matcher_ref.as<GrammarMatcherObj>()->value);
return TraverseDraftTree(
return matcher.TraverseDraftTree(
retrieve_next_token_ptr,
retrieve_next_sibling_ptr,
draft_tokens_ptr,
matcher,
bitmask_ptr,
time_threshold
);
Expand Down
Loading
Loading