Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#include "core/common/common.h"
#include "core/common/inlined_containers.h"
#include "core/common/narrow.h"
#include "core/common/safeint.h"
#include "core/common/utf8_util.h"
#include "core/framework/op_kernel.h"
#include "core/framework/tensor.h"
#include "re2/re2.h"
 
// Use PMR (polymorphic memory resource) when the standard library supports it.
// This reduces per-token allocation overhead by using a monotonic buffer.
#ifdef __has_include
#if __has_include(<memory_resource>)
#include <memory_resource>
#if defined(__cpp_lib_memory_resource) && __cpp_lib_memory_resource >= 201603L
#define ORT_PMR_ALLOCATOR_SUPPORTED
#endif
#endif
#endif
#if !defined(ORT_PMR_ALLOCATOR_SUPPORTED) && defined(_MSC_VER)
// MSVC supports PMR but may not define the feature-test macro in older modes
#include <memory_resource>
#define ORT_PMR_ALLOCATOR_SUPPORTED
#endif
 
#include <optional>
#include <type_traits>
#include <vector>
 
#ifdef ORT_PMR_ALLOCATOR_SUPPORTED
using SlicesVector = std::pmr::vector<re2::StringPiece>;
#else
using SlicesVector = std::vector<re2::StringPiece>;
#endif
 
namespace onnxruntime {
namespace contrib {
 
class Tokenizer final : public OpKernel {
 public:
  explicit Tokenizer(const OpKernelInfo& info);
  Tokenizer(const Tokenizer&) = delete;
  Tokenizer& operator=(const Tokenizer&) = delete;
  ~Tokenizer() = default;
 
  Status Compute(OpKernelContext* context) const override;
 
 private:
  Status EstimateNumberOfTokens(gsl::span<const std::string> input_span,
                                size_t& max_tokens_per_row,
                                size_t& total_tokens_estimate,
                                InlinedVector<size_t>& utf8_lengths) const;
 
  Status CharTokenize(OpKernelContext* context, size_t N, size_t C,
                      gsl::span<const int64_t> input_dims) const;
 
  Status SeparatorExpressionTokenizer(OpKernelContext* context, size_t N, size_t C,
                                      gsl::span<const int64_t> input_dims) const;
 
  Status TokenExpression(OpKernelContext* ctx,
                         size_t N, size_t C,
                         gsl::span<const int64_t> input_dims) const;
 
  Status OutputData(gsl::span<const SlicesVector> rows,
                    size_t max_tokens, size_t max_output_index, std::string* output_data) const;
 
  bool mark_{false};
  std::string pad_value_;
  size_t mincharnum_{0};
  bool char_tokenezation_{false};
  InlinedVector<std::unique_ptr<re2::RE2>> separators_;
  std::unique_ptr<re2::RE2> regex_;
};
 
using namespace utf8_util;
 
ONNX_CPU_OPERATOR_TYPED_MS_KERNEL(
    Tokenizer,
    1,
    string,
    KernelDefBuilder()
        .TypeConstraint("T", DataTypeImpl::GetTensorType<std::string>()),
    contrib::Tokenizer);
 
namespace tokenizer_details {
constexpr char kStartMarker = 0x2;
constexpr char kEndMarker = 0x3;
}  // namespace tokenizer_details
 
using namespace tokenizer_details;
 
Tokenizer::Tokenizer(const OpKernelInfo& info) : OpKernel(info) {
  int64_t mark = 0;
  auto status = info.GetAttr("mark", &mark);
  ORT_ENFORCE(status.IsOK(), "attribute mark is not set");
  mark_ = mark != 0;
 
  status = info.GetAttr("pad_value", &pad_value_);
  ORT_ENFORCE(status.IsOK(), "attribute pad_value is not set");
 
  int64_t mincharnum = 0;
  status = info.GetAttr("mincharnum", &mincharnum);
  ORT_ENFORCE(status.IsOK(), "attribute mincharnum is not set");
  ORT_ENFORCE(mincharnum > 0, "attribute mincharnum must have a positive value");
  mincharnum_ = narrow<size_t>(mincharnum);
 
  // Optional attributes either or
  std::vector<std::string> separators;
  std::string tokenexp;
  status = info.GetAttrs("separators", separators);
  if (!status.IsOK()) {
    status = info.GetAttr("tokenexp", &tokenexp);
    ORT_ENFORCE(status.IsOK(), "Either one of the separators OR tokenexp attributes required but none is set");
    ORT_ENFORCE(!tokenexp.empty(), "Expecting a non-empty tokenexp");
    char_tokenezation_ = (tokenexp == ".");
  } else {
    ORT_ENFORCE(!separators.empty(), "separators must not be empty");
    if (separators.size() == 1 && separators[0].empty()) {
      char_tokenezation_ = true;
    }
  }
 
  ORT_ENFORCE(!char_tokenezation_ || mincharnum_ < 2,
              "mincharnum is too big for char level tokenezation");
 
  // Check if we have separators or tokenexp
  if (!char_tokenezation_) {
    if (!separators.empty()) {
      re2::RE2::Options options;
      options.set_longest_match(true);
      // UTF-8 mode also validates that separator patterns are valid UTF-8
      options.set_encoding(re2::RE2::Options::EncodingUTF8);
      for (const auto& sep : separators) {
        std::unique_ptr<re2::RE2> regex = std::make_unique<re2::RE2>(sep, options);
        if (!regex->ok()) {
          ORT_THROW("Can not digest separators: ", sep, " ", regex->error());
        }
        separators_.push_back(std::move(regex));
      }
    } else {
      // Use tokenexp
      assert(!tokenexp.empty());
      re2::RE2::Options options;
      options.set_longest_match(true);
      // UTF-8 mode also validates that the tokenexp pattern is valid UTF-8
      options.set_encoding(re2::RE2::Options::EncodingUTF8);
      std::unique_ptr<re2::RE2> regex = std::make_unique<re2::RE2>(tokenexp, options);
      if (!regex->ok()) {
        ORT_THROW("Can not digest tokenexp: ", regex->error());
      }
      regex_.swap(regex);
    }
  }
}
 
Status Tokenizer::EstimateNumberOfTokens(gsl::span<const std::string> input_span,
                                         size_t& max_tokens_per_row, size_t& total_tokens_estimate,
                                         InlinedVector<size_t>& utf8_lengths) const {
  total_tokens_estimate = 0;
  max_tokens_per_row = 0;
  utf8_lengths.clear();
  utf8_lengths.reserve(input_span.size());
  for (const auto& s : input_span) {
    size_t utf8_chars = 0;  // length in utf8 chars
    if (!utf8_validate(reinterpret_cast<const unsigned char*>(s.data()), s.size(),
                       utf8_chars)) {
      return Status(common::ONNXRUNTIME, common::INVALID_ARGUMENT,
                    "Input string contains invalid utf8 chars at input index: " +
                        std::to_string(utf8_lengths.size()));
    }
    utf8_lengths.push_back(utf8_chars);
    auto tokens = std::max<size_t>(1, utf8_chars / mincharnum_);
    total_tokens_estimate = SafeInt<size_t>(total_tokens_estimate) + tokens;
    max_tokens_per_row = std::max(max_tokens_per_row, tokens);
  }
 
  return Status::OK();
}
 
Status Tokenizer::CharTokenize(OpKernelContext* ctx, size_t N, size_t C,
                               gsl::span<const int64_t> input_dims) const {
  // With char tokenzation we get as many tokens as the number of
  // utf8 characters in the string. So for every string we calculate its character(utf8) length
  // add padding and add start/end test separators if necessary
  size_t max_tokens = 0;
  auto X = ctx->Input<Tensor>(0);
  auto const input_data = X->Data<std::string>();
  auto curr_input = input_data;
  const size_t num_elements = SafeInt<size_t>(N) * C;
  auto const last = input_data + num_elements;
  while (curr_input != last) {
    const auto& s = *curr_input;
    size_t tokens = 0;  // length in utf8 chars
    if (!utf8_validate(reinterpret_cast<const unsigned char*>(s.data()), s.size(),
                       tokens)) {
      // Do not include the input text in the error message as it could
      // be deemed as a compliance violation by teams using this operator
      return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                             "Input string contains invalid utf8 chars at element: ",
                             std::distance(input_data, curr_input));
    }
    max_tokens = std::max(max_tokens, tokens);
    ++curr_input;
  }
 
  TensorShapeVector output_dims(input_dims.begin(), input_dims.end());
  // Check if we have no output due to apparently empty strings input.
  if (max_tokens == 0) {
    output_dims.push_back(0);
    TensorShape output_shape(output_dims);
    ctx->Output(0, output_shape);
    return Status::OK();
  }
 
  if (mark_) {
    max_tokens += 2;  // Start/end markers as separate tokens
  }
 
  output_dims.push_back(max_tokens);
  TensorShape output_shape(output_dims);
  auto output_tensor = ctx->Output(0, output_shape);
  auto const output_data = output_tensor->MutableData<std::string>();
  size_t output_index = 0;
  curr_input = input_data;
  while (curr_input != last) {
    const auto& s = *curr_input;
    if (mark_) {
      output_data[output_index].assign(&kStartMarker, 1);
      ++output_index;
    }
    size_t tokens = 0;
    const size_t str_len = s.size();
    for (size_t token_idx = 0; token_idx < str_len;) {
      size_t tlen = 0;
      if (!utf8_bytes(static_cast<unsigned char>(s[token_idx]), tlen) || tlen == 0) {
        // Should not happen since we validated UTF-8 above, but guarantee progress
        tlen = 1;
      }
      ORT_RETURN_IF_NOT(token_idx + tlen <= str_len, "UTF-8 character overruns string boundary");
      output_data[output_index] = s.substr(token_idx, tlen);
      ++output_index;
      token_idx += tlen;
      ++tokens;
    }
    if (mark_) {
      output_data[output_index].assign(&kEndMarker, 1);
      ++output_index;
    }
    // Padding strings
    ORT_RETURN_IF_NOT(tokens + (static_cast<size_t>(mark_) * 2) <= max_tokens,
                      "CharTokenize: token count exceeds max tokens");
    const size_t pads = max_tokens - (static_cast<size_t>(mark_) * 2) - tokens;
    for (size_t p = 0; p < pads; ++p) {
      output_data[output_index] = pad_value_;
      ++output_index;
    }
    ++curr_input;
  }
  return Status::OK();
}
 
namespace {
 
// We use std::vector in this case, because InlinedVector::clear() is incompatible
// with std::vector. It also deallocates memory, which is not what we want.
 
// When ORT_PMR_ALLOCATOR_SUPPORTED is defined, we use std::pmr::monotonic_buffer_resource
// to pre-allocate memory for token StringPieces and reduce per-token allocation overhead.
 
#ifdef ORT_PMR_ALLOCATOR_SUPPORTED
/// <summary>
/// This class provides a thin abstraction over the std::pmr::monotonic_buffer_resource
/// If the allocated buffer is not enough, additional allocations are done using
/// new/delete.
/// </summary>
class MonotonicAllocatorWithDefault : public std::pmr::monotonic_buffer_resource {
 public:
  MonotonicAllocatorWithDefault(void* ptr, size_t size_in_bytes)
      : monotonic_buffer_resource(ptr, size_in_bytes, std::pmr::get_default_resource()) {}
  MonotonicAllocatorWithDefault(void* ptr, size_t size_in_bytes, std::pmr::memory_resource* upstream)
      : monotonic_buffer_resource(ptr, size_in_bytes, upstream) {}
};
 
class MemoryAllocator {
 public:
  explicit MemoryAllocator(size_t num_of_slices) {
    size_t allocated_size = 0;
    void* ptr = AlignedAllocate(num_of_slices, allocated_size);
    resource_.emplace(ptr, allocated_size);
  }
 
  SlicesVector CreateVectorWithAllocator() {
    return SlicesVector(&resource_.value());
  }
 
  SlicesVector& EmplaceBack(std::vector<SlicesVector>& rows) {
    return rows.emplace_back(&resource_.value());
  }
 
 private:
  /// <summary>
  /// Pre-allocate memory for the tokens to reduce a number of individual
  /// allocations and thus memory contention.
  /// Used in conjunction with PMR memory allocatior
  /// </summary>
  /// <param name="num">number of objects of T</param>
  /// <param name="buf">buffer holder</param>
  /// <param name="allocated_size">aligned allocated size</param>
  /// <returns>pointer to the buffer</returns>
  void* AlignedAllocate(size_t num, size_t& allocated_size) {
    constexpr size_t alignment = alignof(re2::StringPiece);
    const size_t size_bytes = SafeInt<size_t>(num) * sizeof(re2::StringPiece) + alignment;
    buf_holder_ = std::make_unique<uint8_t[]>(size_bytes);
    void* ptr = buf_holder_.get();
    allocated_size = size_bytes;
    return std::align(alignment, size_bytes, ptr, allocated_size);
  }
 
  std::unique_ptr<uint8_t[]> buf_holder_;
  std::optional<MonotonicAllocatorWithDefault> resource_;
};
 
#else
 
class MemoryAllocator {
 public:
  explicit MemoryAllocator(size_t /* num_of_slices */) {
  }
 
  SlicesVector CreateVectorWithAllocator() const {
    return SlicesVector{};
  }
 
  SlicesVector& EmplaceBack(std::vector<SlicesVector>& rows) const {
    return rows.emplace_back();
  }
};
 
#endif
}  // namespace
 
Status Tokenizer::OutputData(gsl::span<const SlicesVector> rows,
                             size_t max_tokens, size_t max_output_index, std::string* output_data) const {
  size_t output_index = 0;
  for (const auto& row : rows) {
    const size_t markers = static_cast<size_t>(mark_) * 2;
    ORT_RETURN_IF_NOT(row.size() + markers <= max_tokens, "Tokenizer row size exceeds max tokens");
    ORT_RETURN_IF_NOT(output_index + max_tokens <= max_output_index,
                      "Tokenizer output would exceed buffer capacity");
    size_t c_idx = output_index;
    if (mark_) {
      output_data[output_index++].assign(&kStartMarker, 1);
    }
    // Output tokens for this row
    for (const auto& token : row) {
      output_data[output_index++].assign(token.data(), token.length());
    }
    if (mark_) {
      output_data[output_index++].assign(&kEndMarker, 1);
    }
    const size_t pads = max_tokens - markers - row.size();
    for (size_t p = 0; p < pads; ++p) {
      output_data[output_index++] = pad_value_;
    }
    ORT_RETURN_IF(output_index > max_output_index, "Tokenizer output index out of bounds");
    ORT_RETURN_IF((output_index - c_idx) > max_tokens, "Tokenizer output exceeded max tokens per row");
  }
  return Status::OK();
}
 
Status Tokenizer::SeparatorExpressionTokenizer(OpKernelContext* ctx,
                                               size_t N, size_t C,
                                               gsl::span<const int64_t> input_dims) const {
  using namespace re2;
 
  auto X = ctx->Input<Tensor>(0);
  const auto input_span = X->DataAsSpan<std::string>();
 
  // Let's estimate maximum number of tokens
  // It is hard to estimate the number of separate characters that would not appear in the
  // output.
  size_t total_tokens_estimate = 0;
  size_t max_tokens_per_row = 0;
  InlinedVector<size_t> utf8_lengths;
  ORT_RETURN_IF_ERROR(EstimateNumberOfTokens(input_span, max_tokens_per_row, total_tokens_estimate, utf8_lengths));
  // Add a scratch token vector allocation
  total_tokens_estimate += max_tokens_per_row;
 
  // Pre-allocate memory for all tokens (StringPieces)
  MemoryAllocator allocator(total_tokens_estimate);
 
  // Make sure the vectors below are destroyed before the allocator
  const size_t vector_num = SafeInt<size_t>(N) * C;
 
  std::vector<SlicesVector> rows;
  rows.reserve(vector_num);
 
  // Re-use the same vector for each tokenization round
  SlicesVector tokens = allocator.CreateVectorWithAllocator();
  tokens.reserve(max_tokens_per_row);
 
  // We do not constraint the search to match
  // on the beginning or end of the string
  constexpr RE2::Anchor anchor = RE2::UNANCHORED;
 
  // Scan all strings and attempt to find separators in them
  // collect all the output tokens here
  size_t max_tokens = 0;
  size_t str_idx = 0;
  for (const auto& s : input_span) {
    size_t utf8_chars = utf8_lengths[str_idx++];
 
    const auto expected_tokens = std::max<size_t>(1, utf8_chars / mincharnum_);
    auto& row = allocator.EmplaceBack(rows);
    row.reserve(expected_tokens);
    row.emplace_back(s);
 
    for (const auto& sep : separators_) {
      for (const auto& text : row) {
        const auto end_pos = text.length();
        size_t start_pos = 0;
        StringPiece submatch;
 
        bool match = false;
        do {
          if (start_pos > end_pos) {
            break;
          }
          match = sep->Match(text, start_pos, end_pos, anchor, &submatch, 1);
          if (match) {
            // Record  pos/len
            ORT_RETURN_IF(submatch.data() == nullptr, "RE2 match returned null submatch");
            size_t match_pos = submatch.data() - text.data();
            ORT_RETURN_IF_NOT(match_pos >= start_pos, "RE2 match position before start");
            auto token_len = match_pos - start_pos;
            utf8_chars = 0;
            bool valid = utf8_len(reinterpret_cast<const unsigned char*>(text.data() + start_pos),
                                  token_len, utf8_chars);
            if (!valid) {
              return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                                     "Match contains invalid utf8 chars at byte offset: ", match_pos);
            }
            if (utf8_chars >= mincharnum_) {
              tokens.emplace_back(text.data() + start_pos, token_len);
            }
            // Update starting position
            // Guard against empty string match
            auto match_len = submatch.length();
            if (match_len > 0) {
              start_pos = match_pos + match_len;
            } else {
              size_t bytes = 1;  // Always advance at least 1 byte to guarantee progress
              // Advance by one UTF-8 character when within bounds
              if (match_pos < end_pos) {
                size_t char_bytes = 0;
                if (utf8_bytes(static_cast<unsigned char>(text[match_pos]), char_bytes) && char_bytes > 0) {
                  bytes = char_bytes;
                }
              }
              start_pos = match_pos + bytes;
            }
          } else {
            // record trailing token
            auto trailing_len = end_pos - start_pos;
            utf8_chars = 0;
            utf8_len(reinterpret_cast<const unsigned char*>(text.data() + start_pos),
                     trailing_len, utf8_chars);
            if (utf8_chars >= mincharnum_) {
              tokens.emplace_back(text.data() + start_pos, trailing_len);
            }
          }
        } while (match);
      }  // row
 
      // We want to preserve the buffer for the next separator
      // copying slices is cheaper than allocating new memory
      if (!tokens.empty()) {
        row = tokens;
        tokens.clear();
        continue;
      }
 
      // Nothing more to match for any remaining separators
      row.clear();
      tokens.clear();
      break;
    }  // separators_
    max_tokens = std::max(max_tokens, row.size());
  }
 
  TensorShapeVector output_dims(input_dims.begin(), input_dims.end());
  // Check if we have no output due to either empty input
  // or everything is a separator
  if (max_tokens == 0) {
    output_dims.push_back(0);
    TensorShape output_shape(output_dims);
    ctx->Output(0, output_shape);
    return Status::OK();
  }
 
  if (mark_) {
    max_tokens += 2;  // Start/end markers as separate tokens
  }
 
  output_dims.push_back(max_tokens);
  TensorShape output_shape(output_dims);
 
  auto output_tensor = ctx->Output(0, output_shape);
  auto const output_data = output_tensor->MutableData<std::string>();
 
  ORT_RETURN_IF_ERROR(OutputData(rows, max_tokens, narrow<size_t>(output_shape.Size()), output_data));
 
  return Status::OK();
}
 
Status Tokenizer::TokenExpression(OpKernelContext* ctx,
                                  size_t N, size_t C,
                                  gsl::span<const int64_t> input_dims) const {
  using namespace re2;
 
  size_t max_tokens = 0;
  auto X = ctx->Input<Tensor>(0);
  const auto input_span = X->DataAsSpan<std::string>();
 
  // Let's estimate maximum number of tokens
  size_t total_tokens_estimate = 0;
  size_t max_tokens_per_row = 0;
  InlinedVector<size_t> utf8_lengths;
  ORT_RETURN_IF_ERROR(EstimateNumberOfTokens(input_span, max_tokens_per_row, total_tokens_estimate, utf8_lengths));
 
  // Pre-allocate memory for all tokens (StringPieces)
  MemoryAllocator allocator(total_tokens_estimate);
 
  // Make sure the vectors below are destroyed before the allocator
  const size_t vector_num = SafeInt<size_t>(N) * C;
 
  // We use std::vector in this case, because InlinedVector::clear() is incompatible
  // with std::vector. It also deallocates memory, which is not what we want.
  std::vector<SlicesVector> rows;
  rows.reserve(vector_num);
 
  // We do not constraint the search to match
  // on the beginning or end of the string
  constexpr RE2::Anchor anchor = RE2::UNANCHORED;
 
  size_t str_idx = 0;
  for (const auto& s : input_span) {
    size_t utf8_chars = utf8_lengths[str_idx++];
 
    auto& row = allocator.EmplaceBack(rows);
 
    if (utf8_chars >= mincharnum_) {
      auto estimated_tokens = std::max<size_t>(1, utf8_chars / mincharnum_);
      row.reserve(estimated_tokens);
 
      StringPiece text(s);
      const auto end_pos = s.length();
      size_t start_pos = 0;
      StringPiece submatch;
 
      bool match = true;
      do {
        if (start_pos > end_pos) {
          break;
        }
        match = regex_->Match(text, start_pos, end_pos, anchor, &submatch, 1);
        if (match) {
          // Record  pos/len
          ORT_RETURN_IF(submatch.data() == nullptr, "RE2 match returned null submatch");
          size_t match_pos = submatch.data() - s.data();
          ORT_RETURN_IF_NOT(match_pos >= start_pos, "RE2 match position before start");
          // Guard against empty match and make
          // sure we make progress either way
          auto token_len = submatch.length();
          utf8_chars = 0;
          if (!utf8_len(reinterpret_cast<const unsigned char*>(submatch.data()), token_len, utf8_chars)) {
            return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                                   "Match contains invalid utf8 chars at byte offset: ", match_pos);
          }
          if (utf8_chars >= mincharnum_) {
            row.push_back(submatch);
            start_pos = match_pos + token_len;
          } else {
            // Advance by one UTF-8 character, or at least 1 byte to guarantee progress
            size_t bytes = 1;
            if (match_pos < end_pos) {
              size_t char_bytes = 0;
              if (utf8_bytes(static_cast<unsigned char>(text[match_pos]), char_bytes) && char_bytes > 0) {
                bytes = char_bytes;
              }
            }
            start_pos = match_pos + bytes;
          }
        }
      } while (match);
    }
    max_tokens = std::max(max_tokens, row.size());
  }
 
  // Check for empty output
  TensorShapeVector output_dims(input_dims.begin(), input_dims.end());
  // Check if we have no output due to either empty input
  // everything is a separator
  if (max_tokens == 0) {
    output_dims.push_back(0);
    TensorShape output_shape(output_dims);
    ctx->Output(0, output_shape);
    return Status::OK();
  }
 
  if (mark_) {
    max_tokens += 2;  // Start/end markers as separate tokens
  }
 
  output_dims.push_back(max_tokens);
  TensorShape output_shape(output_dims);
 
  auto output_tensor = ctx->Output(0, output_shape);
  auto const output_data = output_tensor->MutableData<std::string>();
 
  ORT_RETURN_IF_ERROR(OutputData(rows, max_tokens, narrow<size_t>(output_shape.Size()), output_data));
 
  return Status::OK();
}
 
Status Tokenizer::Compute(OpKernelContext* ctx) const {
  // Get input buffer ptr
  auto X = ctx->Input<Tensor>(0);
  if (X == nullptr) return Status(common::ONNXRUNTIME, common::FAIL, "input count mismatch");
  if (!X->IsDataTypeString()) {
    return Status(common::ONNXRUNTIME, common::INVALID_ARGUMENT,
                  "tensor(string) expected as input");
  }
 
  auto& input_shape = X->Shape();
  auto input_dims = input_shape.GetDims();
  size_t N = 0;
  size_t C = 0;
  if (input_dims.size() == 1) {
    N = 1;
    C = narrow<size_t>(input_dims[0]);
  } else if (input_dims.size() == 2) {
    N = narrow<size_t>(input_dims[0]);
    C = narrow<size_t>(input_dims[1]);
  } else {
    return Status(common::ONNXRUNTIME, common::INVALID_ARGUMENT,
                  "Input dimensions are either [C] or [N][C] allowed");
  }
 
  // Empty input
  Status s;
  if (input_shape.Size() == 0) {
    std::vector<int64_t> output_dims;
    if (input_dims.size() == 2) {
      output_dims.push_back(input_dims[0]);
    }
    output_dims.push_back(0);
 
    TensorShape output_shape(output_dims);
    ctx->Output(0, output_shape);
    return s;
  }
 
  if (char_tokenezation_) {
    s = CharTokenize(ctx, N, C, input_dims);
  } else {
    if (!separators_.empty()) {
      s = SeparatorExpressionTokenizer(ctx, N, C, input_dims);
    } else {
      assert(regex_ != nullptr);
      s = TokenExpression(ctx, N, C, input_dims);
    }
  }
  return s;
}
}  // namespace contrib
}  // namespace onnxruntime