File size: 18,059 Bytes
d20d01e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Set-BPE serialization: quantized cell trajectories <-> token streams.
//
// A port of the runtime's SpatialVocabulary / TemporalVocabulary (Python,
// ``tokenization/setbpe_{spatial,temporal}.py``).  Every merge is applied from
// a priority queue ordered exactly as the Python heaps order their tuples, so
// the token streams are identical, not merely equivalent.

#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

#include <algorithm>
#include <cstdint>
#include <functional>
#include <queue>
#include <stdexcept>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>

#include "parallel.hpp"

namespace py = pybind11;

namespace {

int lowest_bit(uint64_t mask) { return mask ? __builtin_ctzll(mask) : -1; }

uint64_t pair_key(int64_t left, int64_t right) {
  return (static_cast<uint64_t>(left) << 32) | static_cast<uint32_t>(right);
}

struct Rule {
  int64_t child;
  int64_t rank;
};

class SetBPE {
 public:
  SetBPE(std::vector<int64_t> bins, int64_t lookahead,
         const std::vector<std::pair<int64_t, int64_t>>& spatial_merges,
         const std::vector<std::tuple<int64_t, int64_t, int64_t>>& temporal_merges)
      : bins_(std::move(bins)), lookahead_(lookahead) {
    const int64_t dimension = static_cast<int64_t>(bins_.size());
    if (dimension < 1 || dimension > 63) throw std::invalid_argument("bins must have 1..63 slots");
    if (lookahead_ < 1) throw std::invalid_argument("lookahead must be positive");
    offsets_.assign(dimension + 1, 0);
    for (int64_t d = 0; d < dimension; ++d) {
      if (bins_[d] < 1) throw std::invalid_argument("every dimension needs at least one bin");
      offsets_[d + 1] = offsets_[d] + bins_[d];
    }
    atom_count_ = offsets_[dimension];
    spatial_size_ = atom_count_ + static_cast<int64_t>(spatial_merges.size());
    support_.assign(spatial_size_, 0);
    expansion_.assign(spatial_size_ * dimension, -1);
    for (int64_t d = 0; d < dimension; ++d) {
      for (int64_t v = 0; v < bins_[d]; ++v) {
        const int64_t token = offsets_[d] + v;
        support_[token] = uint64_t{1} << d;
        expansion_[token * dimension + d] = v;
      }
    }
    for (size_t rank = 0; rank < spatial_merges.size(); ++rank) {
      const auto [left, right] = spatial_merges[rank];
      const int64_t token = atom_count_ + static_cast<int64_t>(rank);
      if (left < 0 || right < 0 || left >= token || right >= token)
        throw std::invalid_argument("a merge rule must reference already-created tokens");
      if (support_[left] & support_[right])
        throw std::invalid_argument("a merge rule joins two overlapping supports");
      support_[token] = support_[left] | support_[right];
      for (int64_t d = 0; d < dimension; ++d) {
        expansion_[token * dimension + d] =
            std::max(expansion_[left * dimension + d], expansion_[right * dimension + d]);
      }
      spatial_rules_[pair_key(std::min(left, right), std::max(left, right))] =
          Rule{token, static_cast<int64_t>(rank)};
    }
    spatial_anchor_.resize(spatial_size_);
    for (int64_t token = 0; token < spatial_size_; ++token)
      spatial_anchor_[token] = lowest_bit(support_[token]);

    // Rooted temporal tokens: a pattern of (time offset, spatial token) pairs.
    vocab_size_ = spatial_size_ + static_cast<int64_t>(temporal_merges.size());
    patterns_.resize(vocab_size_);
    root_.resize(vocab_size_);
    for (int64_t token = 0; token < spatial_size_; ++token) {
      patterns_[token] = {{0, token}};
      root_[token] = token;
    }
    for (size_t rank = 0; rank < temporal_merges.size(); ++rank) {
      const auto [left, right, offset] = temporal_merges[rank];
      const int64_t child = spatial_size_ + static_cast<int64_t>(rank);
      if (left < 0 || right < 0 || left >= child || right >= child)
        throw std::invalid_argument("a temporal merge must reference already-created tokens");
      if (offset < 1 || offset >= lookahead_)
        throw std::invalid_argument("a temporal merge offset must be in [1, lookahead)");
      std::vector<std::pair<int64_t, int64_t>> pattern = patterns_[left];
      for (const auto& [time, token] : patterns_[right]) pattern.emplace_back(time + offset, token);
      std::sort(pattern.begin(), pattern.end());
      const int64_t span = 1 + pattern.back().first;
      if (span > lookahead_) throw std::invalid_argument("temporal merge exceeds the lookahead horizon");
      std::vector<uint64_t> masks(span, 0);
      int roots = 0;
      for (const auto& [time, token] : pattern) {
        if (masks[time] & support_[token])
          throw std::invalid_argument("temporal merge joins overlapping spatial supports");
        masks[time] |= support_[token];
        roots += time == 0;
      }
      if (roots != 1)
        throw std::invalid_argument("a rooted temporal token must have exactly one time-zero spatial token");
      patterns_[child] = std::move(pattern);
      root_[child] = root_[left];
      const auto key = std::make_tuple(left, right, offset);
      if (temporal_rules_.count(key)) throw std::invalid_argument("duplicate temporal merge rule");
      temporal_rules_[key] = Rule{child, static_cast<int64_t>(rank)};
    }
  }

  int64_t vocab_size() const { return vocab_size_; }

  // One dense [T, D] trajectory with -1 for semantically absent slots.
  std::vector<int64_t> encode(const int64_t* cells, int64_t steps) const {
    const int64_t dimension = static_cast<int64_t>(bins_.size());
    if (steps < 1) throw std::invalid_argument("every episode must have at least one step");
    uint64_t first_support = 0;
    for (int64_t t = 0; t < steps; ++t) {
      uint64_t support = 0;
      for (int64_t d = 0; d < dimension; ++d) {
        const int64_t value = cells[t * dimension + d];
        if (value < -1 || value >= bins_[d])
          throw std::invalid_argument("episodes must contain -1 or an in-range cell index");
        if (value >= 0) support |= uint64_t{1} << d;
      }
      if (!support) throw std::invalid_argument("every timestep needs at least one active coordinate");
      if (t == 0) first_support = support;
      else if (support != first_support)
        throw std::invalid_argument("active dimensions must remain constant within an episode");
    }

    // Instances, as in the Python encoder: token, anchor step, liveness.
    std::vector<int64_t> tokens, anchors;
    std::vector<char> active;
    std::vector<std::vector<std::pair<int64_t, int64_t>>> at(steps);  // (token, instance)
    for (int64_t t = 0; t < steps; ++t) {
      for (int64_t token : spatial_encode(cells + t * dimension)) {
        at[t].emplace_back(token, static_cast<int64_t>(tokens.size()));
        tokens.push_back(token);
        anchors.push_back(t);
        active.push_back(1);
      }
    }

    // (rank, anchor, root anchor dimension, left instance, right instance, child)
    using Offer = std::tuple<int64_t, int64_t, int64_t, int64_t, int64_t, int64_t>;
    std::priority_queue<Offer, std::vector<Offer>, std::greater<Offer>> frontier;
    auto offer = [&](int64_t left_instance, int64_t right_instance) {
      const auto found = temporal_rules_.find(std::make_tuple(
          tokens[left_instance], tokens[right_instance],
          anchors[right_instance] - anchors[left_instance]));
      if (found == temporal_rules_.end()) return;
      const Rule& rule = found->second;
      frontier.emplace(rule.rank, anchors[left_instance],
                       spatial_anchor_[root_[rule.child]], left_instance, right_instance,
                       rule.child);
    };
    for (int64_t anchor = 0; anchor < steps; ++anchor) {
      for (int64_t offset = 1; offset < std::min<int64_t>(lookahead_, steps - anchor); ++offset) {
        for (const auto& [left_token, left_instance] : at[anchor]) {
          for (const auto& [right_token, right_instance] : at[anchor + offset]) {
            offer(left_instance, right_instance);
          }
        }
      }
    }
    auto erase = [&](int64_t step, int64_t token) {
      auto& items = at[step];
      for (auto it = items.begin(); it != items.end(); ++it) {
        if (it->first == token) { items.erase(it); return; }
      }
    };
    while (!frontier.empty()) {
      const auto [rank, anchor, root_anchor, left_instance, right_instance, child] = frontier.top();
      frontier.pop();
      (void)rank; (void)root_anchor;
      if (!active[left_instance] || !active[right_instance]) continue;
      if (anchors[left_instance] != anchor) continue;
      const auto resolved = temporal_rules_.find(std::make_tuple(
          tokens[left_instance], tokens[right_instance], anchors[right_instance] - anchor));
      if (resolved == temporal_rules_.end() || resolved->second.child != child) continue;
      active[left_instance] = 0;
      active[right_instance] = 0;
      erase(anchor, tokens[left_instance]);
      erase(anchors[right_instance], tokens[right_instance]);
      const int64_t new_instance = static_cast<int64_t>(tokens.size());
      tokens.push_back(child);
      anchors.push_back(anchor);
      active.push_back(1);
      at[anchor].emplace_back(child, new_instance);
      for (int64_t offset = 1; offset < lookahead_; ++offset) {
        const int64_t future = anchor + offset;
        if (future < steps) {
          for (const auto& [token, other] : at[future]) offer(new_instance, other);
        }
        const int64_t past = anchor - offset;
        if (past >= 0) {
          for (const auto& [token, other] : at[past]) offer(other, new_instance);
        }
      }
    }

    std::vector<std::tuple<int64_t, int64_t, int64_t>> ordered;
    for (int64_t anchor = 0; anchor < steps; ++anchor) {
      for (const auto& [token, instance] : at[anchor]) {
        if (active[instance]) ordered.emplace_back(anchor, spatial_anchor_[root_[token]], token);
      }
    }
    std::sort(ordered.begin(), ordered.end());
    std::vector<int64_t> stream;
    stream.reserve(ordered.size());
    for (const auto& item : ordered) stream.push_back(std::get<2>(item));
    return stream;
  }

  // Tokens -> dense [T, D] cells (-1 outside ``full``), validating like the runtime.
  std::vector<int64_t> decode(const int64_t* stream, int64_t length, uint64_t full) const {
    const int64_t dimension = static_cast<int64_t>(bins_.size());
    std::vector<uint64_t> coverage{0};
    std::vector<std::vector<int64_t>> spatial_tokens(1);
    size_t front = 0;
    for (int64_t index = 0; index < length; ++index) {
      const int64_t token = stream[index];
      if (token < 0 || token >= vocab_size_)
        throw std::invalid_argument("temporal token " + std::to_string(token) + " is outside the vocabulary");
      while (front < coverage.size() && coverage[front] == full) ++front;
      if (front == coverage.size()) {
        coverage.push_back(0);
        spatial_tokens.emplace_back();
      }
      const uint64_t uncovered = full & ~coverage[front];
      if (spatial_anchor_[root_[token]] != lowest_bit(uncovered))
        throw std::invalid_argument("temporal stream violates root order at the earliest incomplete step");
      for (const auto& [offset, spatial_token] : patterns_[token]) {
        const size_t step = front + static_cast<size_t>(offset);
        while (step >= coverage.size()) {
          coverage.push_back(0);
          spatial_tokens.emplace_back();
        }
        if (coverage[step] & support_[spatial_token])
          throw std::invalid_argument("temporal stream contains overlapping spatial support");
        coverage[step] |= support_[spatial_token];
        spatial_tokens[step].push_back(spatial_token);
      }
    }
    for (uint64_t mask : coverage) {
      if (mask != full) throw std::invalid_argument("temporal stream ended with an incomplete control step");
    }
    std::vector<int64_t> cells(coverage.size() * dimension, -1);
    for (size_t step = 0; step < coverage.size(); ++step) {
      for (int64_t token : spatial_tokens[step]) {
        for (int64_t d = 0; d < dimension; ++d) {
          const int64_t value = expansion_[token * dimension + d];
          if (value >= 0) cells[step * dimension + d] = value;
        }
      }
    }
    return cells;
  }

 private:
  // Spatial Set-BPE of one dense row: merges in rank order, then anchor order.
  std::vector<int64_t> spatial_encode(const int64_t* row) const {
    const int64_t dimension = static_cast<int64_t>(bins_.size());
    std::vector<int64_t> present;
    for (int64_t d = 0; d < dimension; ++d) {
      if (row[d] >= 0) present.push_back(offsets_[d] + row[d]);
    }
    std::sort(present.begin(), present.end());
    using Candidate = std::tuple<int64_t, int64_t, int64_t, int64_t>;  // rank, child, left, right
    std::priority_queue<Candidate, std::vector<Candidate>, std::greater<Candidate>> heap;
    for (size_t i = 0; i < present.size(); ++i) {
      for (size_t j = i + 1; j < present.size(); ++j) {
        const auto found = spatial_rules_.find(pair_key(present[i], present[j]));
        if (found != spatial_rules_.end())
          heap.emplace(found->second.rank, found->second.child, present[i], present[j]);
      }
    }
    std::vector<int64_t> tokens = present;  // a small set; linear lookups are fastest
    auto contains = [&](int64_t token) {
      return std::find(tokens.begin(), tokens.end(), token) != tokens.end();
    };
    while (!heap.empty()) {
      const auto [rank, child, left, right] = heap.top();
      heap.pop();
      (void)rank;
      if (!contains(left) || !contains(right)) continue;
      tokens.erase(std::find(tokens.begin(), tokens.end(), left));
      tokens.erase(std::find(tokens.begin(), tokens.end(), right));
      for (int64_t other : tokens) {
        const int64_t low = std::min(child, other), high = std::max(child, other);
        const auto found = spatial_rules_.find(pair_key(low, high));
        if (found != spatial_rules_.end())
          heap.emplace(found->second.rank, found->second.child, low, high);
      }
      tokens.push_back(child);
    }
    std::sort(tokens.begin(), tokens.end(), [&](int64_t a, int64_t b) {
      return std::make_pair(spatial_anchor_[a], a) < std::make_pair(spatial_anchor_[b], b);
    });
    return tokens;
  }

  struct TupleHash {
    size_t operator()(const std::tuple<int64_t, int64_t, int64_t>& key) const {
      const auto [a, b, c] = key;
      return std::hash<uint64_t>()((static_cast<uint64_t>(a) * 1000003u) ^
                                   (static_cast<uint64_t>(b) << 20) ^ static_cast<uint64_t>(c));
    }
  };

  std::vector<int64_t> bins_;
  int64_t lookahead_;
  std::vector<int64_t> offsets_;
  int64_t atom_count_ = 0, spatial_size_ = 0, vocab_size_ = 0;
  std::vector<uint64_t> support_;
  std::vector<int64_t> expansion_;
  std::vector<int> spatial_anchor_;
  std::unordered_map<uint64_t, Rule> spatial_rules_;
  std::vector<std::vector<std::pair<int64_t, int64_t>>> patterns_;
  std::vector<int64_t> root_;
  std::unordered_map<std::tuple<int64_t, int64_t, int64_t>, Rule, TupleHash> temporal_rules_;
};

// Encode B dense [T, D] trajectories in parallel; returns one stream per row.
py::list encode_batch(const SetBPE& codec,
                      const py::array_t<int64_t, py::array::c_style | py::array::forcecast>& cells,
                      int threads) {
  if (cells.ndim() != 3) throw std::invalid_argument("cells must have shape [B, T, D]");
  const int64_t batch = cells.shape(0), steps = cells.shape(1), width = cells.shape(2);
  const int64_t* data = cells.data();
  std::vector<std::vector<int64_t>> streams(batch);
  {
    py::gil_scoped_release release;
    ac2::parallel_for(batch, threads, [&](int64_t index) {
      streams[index] = codec.encode(data + index * steps * width, steps);
    });
  }
  py::list output(batch);
  for (int64_t index = 0; index < batch; ++index) output[index] = py::cast(streams[index]);
  return output;
}

// Decode B equal-horizon streams to dense [B, T, D] cells (-1 outside ``full``).
py::array_t<int64_t> decode_batch(const SetBPE& codec, const std::vector<std::vector<int64_t>>& streams,
                                  int64_t width, uint64_t full, int threads) {
  const int64_t batch = static_cast<int64_t>(streams.size());
  if (batch < 1) throw std::invalid_argument("streams must not be empty");
  std::vector<std::vector<int64_t>> cells(batch);
  {
    py::gil_scoped_release release;
    ac2::parallel_for(batch, threads, [&](int64_t index) {
      if (streams[index].empty()) throw std::invalid_argument("token stream must not be empty");
      cells[index] = codec.decode(streams[index].data(), static_cast<int64_t>(streams[index].size()), full);
    });
  }
  const int64_t steps = static_cast<int64_t>(cells[0].size()) / width;
  for (const auto& row : cells) {
    if (static_cast<int64_t>(row.size()) != steps * width)
      throw std::invalid_argument("all token streams in a batch must decode to the same length");
  }
  py::array_t<int64_t> output({batch, steps, width});
  int64_t* out = output.mutable_data();
  for (int64_t index = 0; index < batch; ++index)
    std::copy(cells[index].begin(), cells[index].end(), out + index * steps * width);
  return output;
}

}  // namespace

void register_setbpe(py::module_& module) {
  py::class_<SetBPE>(module, "SetBPE")
      .def(py::init<std::vector<int64_t>, int64_t, const std::vector<std::pair<int64_t, int64_t>>&,
                    const std::vector<std::tuple<int64_t, int64_t, int64_t>>&>(),
           py::arg("bins"), py::arg("lookahead"), py::arg("spatial_merges"),
           py::arg("temporal_merges"))
      .def_property_readonly("vocab_size", &SetBPE::vocab_size)
      .def("encode_batch", &encode_batch, py::arg("cells"), py::arg("threads") = 0,
           "Dense [B, T, D] cells (-1 = absent) -> one token stream per row.")
      .def("decode_batch", &decode_batch, py::arg("streams"), py::arg("width"),
           py::arg("full_support"), py::arg("threads") = 0,
           "Equal-horizon streams -> dense [B, T, D] cells, -1 outside full_support.");
}