Skip to content
Open
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
7 changes: 6 additions & 1 deletion edge0-infer/src/app/text/bpe.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,12 @@ std::vector<int32_t>
Bpe::encode_fragments(const std::vector<Fragment> &fragments,
bool standalone) const {
std::string text;
const bool has_protocol = std::any_of(fragments.begin(), fragments.end(),
[](const Fragment& f) { return f.protocol && !f.text.empty(); });
std::vector<bool> allowed;
for (const auto &f : fragments) {
text += f.text;
allowed.insert(allowed.end(), f.text.size(), f.protocol);
if (has_protocol) allowed.insert(allowed.end(), f.text.size(), f.protocol);
}
if (!valid_utf8(text))
throw TextError(Error::invalid_argument, "input is not valid UTF-8");
Expand All @@ -170,6 +172,9 @@ Bpe::encode_fragments(const std::vector<Fragment> &fragments,
};
std::vector<Span> spans = {{0, text.size(), -1}};
for (auto id : specials_) {
// Plain user input cannot contain control tokens. User-defined tokens
// still match in standalone encoding, as required by that API.
if (!has_protocol && !(standalone && data_.types[id] == 4)) continue;
const auto &s = data_.tokens[id];
std::vector<Span> next;
for (auto span : spans) {
Expand Down
15 changes: 15 additions & 0 deletions edge0-infer/tests/unit/app/text_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,21 @@ void bpe_test() {
}
require(rejected,"unknown pre-tokenizer reports actual and supported names");
}
{
auto many=d;
for (int i=0;i<512;++i) {
many.tokens.push_back("<control_"+std::to_string(i)+">");many.types.push_back(3);
}
Bpe controls(many);
const std::string body="<control_7> custom <control_511>";
require(controls.encode_input({{body,false},{"",true}})==Bpe(d).encode_input({{body,false}}),
"untrusted control spellings remain ordinary across an empty protocol fragment");
const auto standalone=controls.encode(body,false);
require(std::find(standalone.begin(),standalone.end(),262)!=standalone.end(),
"standalone user-defined tokens remain recognized without protocol input");
require(controls.encode("<control_7>",true)==std::vector<int32_t>({270}),
"explicit protocol parsing remains enabled");
}
Bpe b(d);
require(b.encode("abc", false) == std::vector<int32_t>({97, 257}),
"rank priority");
Expand Down