Исходный код СУБД 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#include "contrib_ops/cpu/sparse/sparse_attention.h"
#include "contrib_ops/cpu/sparse/sparse_attention_helper.h"
#include "contrib_ops/cpu/bert/rotary_helper.h"
#include "contrib_ops/cpu/bert/attention_utils.h"
#include "contrib_ops/cpu/bert/rotary_embedding.h"
#include "contrib_ops/cpu/bert/rotary_embedding_helper.h"
 
#include "core/framework/tensorprotoutils.h"
#include "core/graph/onnx_protobuf.h"
#include "core/common/safeint.h"
#include "core/platform/threadpool.h"
 
#include <unsupported/Eigen/SpecialFunctions>
#include <vector>
 
using onnxruntime::concurrency::ThreadPool;
 
namespace onnxruntime {
namespace contrib {
 
#define REGISTER_KERNEL_TYPED(T)                                        \
  ONNX_OPERATOR_TYPED_KERNEL_EX(                                        \
      SparseAttention,                                                  \
      kMSDomain,                                                        \
      1,                                                                \
      T,                                                                \
      kCpuExecutionProvider,                                            \
      KernelDefBuilder()                                                \
          .TypeConstraint("T", DataTypeImpl::GetTensorType<T>())        \
          .TypeConstraint("M", DataTypeImpl::GetTensorType<int32_t>()), \
      SparseAttention<T>);
 
REGISTER_KERNEL_TYPED(float)
REGISTER_KERNEL_TYPED(MLFloat16)
 
namespace {
 
// Validate CSR row-pointer monotonicity and column-index range.
// Must be called after CheckInputs has populated the parameters struct.
Status ValidateCSRIndices(const SparseAttentionParameters& parameters,
                          const Tensor& block_row_indices,
                          const Tensor& block_col_indices) {
  const int num_layout = parameters.num_sparse_layout;
  const int max_blocks = parameters.stride_row_indices - 1;
  const int col_count = parameters.stride_col_indices;
 
  const int32_t* row_data = block_row_indices.Data<int32_t>();
  const int32_t* col_data = block_col_indices.Data<int32_t>();
  for (int l = 0; l < num_layout; ++l) {
    const int32_t* r = row_data + l * (max_blocks + 1);
    if (r[0] != 0) {
      return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                             "block_row_indices[", l, "][0] must be 0, got ", r[0]);
    }
    for (int i = 0; i < max_blocks; ++i) {
      if (r[i] < 0 || r[i] > r[i + 1] || r[i + 1] > col_count) {
        return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                               "block_row_indices values are not monotonically non-decreasing or exceed "
                               "block_col_indices columns at layout ",
                               l, " row ", i,
                               ": r[", i, "]=", r[i], ", r[", i + 1, "]=", r[i + 1],
                               ", col_count=", col_count);
      }
    }
    const int32_t* c = col_data + l * col_count;
    const int nnz = r[max_blocks];
    for (int k = 0; k < nnz; ++k) {
      if (c[k] < 0 || c[k] >= max_blocks) {
        return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                               "block_col_indices[", l, "][", k, "]=", c[k],
                               " is out of valid range [0, ", max_blocks, ")");
      }
    }
  }
 
  return Status::OK();
}
 
// Validate total_key_lengths element values.
Status ValidateKeyLengths(const SparseAttentionParameters& parameters,
                          const Tensor& total_key_lengths) {
  const int batch_size = parameters.batch_size;
  const int sequence_length = parameters.sequence_length;
  const int total_sequence_length = parameters.total_sequence_length;
 
  const auto* key_len_data = total_key_lengths.Data<int32_t>();
  const bool is_prompt = (sequence_length == total_sequence_length);
  const int min_key_length = is_prompt ? 1 : sequence_length;
  for (int i = 0; i < batch_size; ++i) {
    const int key_length = key_len_data[i];
    if (key_length < min_key_length || key_length > total_sequence_length) {
      return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                             "key_total_sequence_lengths value ", key_length,
                             " at batch index ", i,
                             " is out of range [", min_key_length, ", ", total_sequence_length, "].");
    }
  }
 
  return Status::OK();
}
 
}  // namespace
 
template <typename T>
SparseAttention<T>::SparseAttention(const OpKernelInfo& info) : OpKernel(info), SparseAttentionBase(info) {
}
 
template <typename T>
Status SparseAttention<T>::Compute(OpKernelContext* context) const {
  const Tensor* query = context->Input<Tensor>(0);
  const Tensor* key = context->Input<Tensor>(1);
  const Tensor* value = context->Input<Tensor>(2);
  const Tensor* past_key = context->Input<Tensor>(3);
  const Tensor* past_value = context->Input<Tensor>(4);
  const Tensor* block_row_indices = context->Input<Tensor>(5);
  const Tensor* block_col_indices = context->Input<Tensor>(6);
  const Tensor* total_seq_len = context->Input<Tensor>(7);
  const Tensor* total_key_lengths = context->Input<Tensor>(8);
  const Tensor* cos_cache = context->Input<Tensor>(9);
  const Tensor* sin_cache = context->Input<Tensor>(10);
 
  SparseAttentionParameters parameters = {};
 
  // Parameters from node attribute shall be set before calling CheckInputs
  parameters.sparse_block_size = sparse_block_size_;
  parameters.num_heads = num_heads_;
  parameters.kv_num_heads = kv_num_heads_;
  parameters.scale = scale_;
  parameters.do_rotary = do_rotary_;
  parameters.rotary_interleaved = rotary_interleaved_;
  ORT_RETURN_IF_ERROR(sparse_attention_helper::CheckInputs(&parameters,
                                                           query,
                                                           key,
                                                           value,
                                                           past_key,
                                                           past_value,
                                                           cos_cache,
                                                           sin_cache,
                                                           block_row_indices,
                                                           block_col_indices,
                                                           total_key_lengths,
                                                           total_seq_len));
  ORT_RETURN_IF_ERROR(ValidateCSRIndices(parameters,
                                         *block_row_indices,
                                         *block_col_indices));
  ORT_RETURN_IF_ERROR(ValidateKeyLengths(parameters,
                                         *total_key_lengths));
 
  const int batch_size = parameters.batch_size;
  const int sequence_length = parameters.sequence_length;
  int q_hidden_size = parameters.hidden_size;
 
  std::vector<int64_t> output_shape(3);
  output_shape[0] = static_cast<int64_t>(batch_size);
  output_shape[1] = static_cast<int64_t>(sequence_length);
  output_shape[2] = static_cast<int64_t>(q_hidden_size);
  Tensor* output = context->Output(0, output_shape);
 
  constexpr bool past_present_share_buffer = true;  // Only supports share buffer for past and present for now.
  parameters.past_present_share_buffer = past_present_share_buffer;
 
  int head_size = parameters.head_size;
  const int cache_length = past_present_share_buffer
                               ? parameters.max_cache_sequence_length
                               : parameters.total_sequence_length;
  std::vector<int64_t> present_k_shape({static_cast<int64_t>(batch_size),
                                        static_cast<int64_t>(kv_num_heads_),
                                        static_cast<int64_t>(cache_length),
                                        static_cast<int64_t>(head_size)});
  std::vector<int64_t> present_v_shape({static_cast<int64_t>(batch_size),
                                        static_cast<int64_t>(kv_num_heads_),
                                        static_cast<int64_t>(cache_length),
                                        static_cast<int64_t>(head_size)});
  Tensor* present_key = context->Output(1, present_k_shape);
  Tensor* present_value = context->Output(2, present_v_shape);
 
  // Check past and present share buffer.
  if (past_present_share_buffer) {
    ORT_ENFORCE(past_key->DataRaw() == present_key->DataRaw() && past_value->DataRaw() == present_value->DataRaw());
  }
 
  AllocatorPtr allocator;
  ORT_RETURN_IF_ERROR(context->GetTempSpaceAllocator(&allocator));
 
  auto element_type = DataTypeImpl::GetType<T>();
  OrtValue Q;
  OrtValue K;
  OrtValue V;
 
  const bool packed_qkv = parameters.is_packed_qkv;
  if (packed_qkv) {
    ORT_RETURN_IF_ERROR(MaybeTransposeToBNSH<T>(
        allocator, batch_size, num_heads_ + 2 * kv_num_heads_, sequence_length, head_size, query, Q));
  } else {
    ORT_RETURN_IF_ERROR(MaybeTransposeToBNSH<T>(
        allocator, batch_size, num_heads_, sequence_length, head_size, query, Q));
    ORT_RETURN_IF_ERROR(MaybeTransposeToBNSH<T>(
        allocator, batch_size, kv_num_heads_, sequence_length, head_size, key, K));
    ORT_RETURN_IF_ERROR(MaybeTransposeToBNSH<T>(
        allocator, batch_size, kv_num_heads_, sequence_length, head_size, value, V));
  }
 
  OrtValue RotaryQKV;
  OrtValue RotaryQ;
  OrtValue RotaryK;
  T* q_rotary = Q.GetMutable<Tensor>()->MutableData<T>();
  T* k_rotary = packed_qkv ? nullptr : K.GetMutable<Tensor>()->MutableData<T>();
  if (do_rotary_) {
    ORT_ENFORCE(cos_cache != nullptr && sin_cache != nullptr, "cos_cache and sin_cache must be provided when do_rotary is true");
    rotary_embedding_helper::RotaryParameters rotary_params = {};
    rotary_params.batch_size = batch_size;
    rotary_params.sequence_length = sequence_length;
    rotary_params.hidden_size = q_hidden_size;
    rotary_params.head_size = head_size;
    rotary_params.rotary_embedding_dim = parameters.rotary_dim;
    rotary_params.num_heads = num_heads_;
    rotary_params.max_sequence_length = parameters.max_rotary_sequence_length;
    rotary_params.seq_stride = head_size;
    rotary_params.head_stride = sequence_length * rotary_params.seq_stride;
    rotary_params.batch_stride = (packed_qkv ? (num_heads_ + 2 * kv_num_heads_) : num_heads_) *
                                 rotary_params.head_stride;
    rotary_params.position_ids_format = sequence_length == 1 ? 1 : 0;
    rotary_params.transposed = true;
    auto* tp = context->GetOperatorThreadPool();
 
    const bool is_prompt = parameters.total_sequence_length == parameters.sequence_length;
    std::vector<int64_t> pos_ids(is_prompt ? 1 : batch_size * sequence_length);
    if (is_prompt) {
      pos_ids[0] = static_cast<int64_t>(0);
    } else if (sequence_length == 1) {
      for (int b = 0; b < batch_size; b++) {
        pos_ids[b] = static_cast<int64_t>(total_key_lengths->Data<int32_t>()[b]) - 1;
      }
    } else {
      // This supports a rare case that sequence_length > 1 when it is not prompt.
      for (int b = 0; b < batch_size; b++) {
        for (int s = 0; s < sequence_length; s++) {
          pos_ids[b * sequence_length + s] = static_cast<int64_t>(total_key_lengths->Data<int32_t>()[b]) -
                                             (sequence_length - s);
        }
      }
    }
 
    const T* q_input;
    const T* k_input;
    if (packed_qkv) {
      TensorShape qkv_shape({batch_size, num_heads_ + 2 * kv_num_heads_, sequence_length, head_size});
      Tensor::InitOrtValue(element_type, qkv_shape, allocator, RotaryQKV);
      q_input = Q.Get<Tensor>().Data<T>();
      k_input = q_input + num_heads_ * sequence_length * head_size;
      q_rotary = RotaryQKV.GetMutable<Tensor>()->MutableData<T>();
      k_rotary = q_rotary + num_heads_ * sequence_length * head_size;
    } else {
      TensorShape q_shape({batch_size, num_heads_, sequence_length, head_size});
      Tensor::InitOrtValue(element_type, q_shape, allocator, RotaryQ);
      TensorShape k_shape({batch_size, kv_num_heads_, sequence_length, head_size});
      Tensor::InitOrtValue(element_type, k_shape, allocator, RotaryK);
      q_input = Q.Get<Tensor>().Data<T>();
      k_input = K.Get<Tensor>().Data<T>();
      q_rotary = RotaryQ.GetMutable<Tensor>()->MutableData<T>();
      k_rotary = RotaryK.GetMutable<Tensor>()->MutableData<T>();
    }
 
    ORT_RETURN_IF_ERROR(RunRotaryEmbedding<T>(tp, rotary_params, q_input,
                                              pos_ids.data(), cos_cache->Data<T>(),
                                              sin_cache->Data<T>(), q_rotary, rotary_interleaved_));
 
    rotary_params.num_heads = kv_num_heads_;
    rotary_params.hidden_size = parameters.kv_hidden_size;
    if (!packed_qkv) {
      rotary_params.batch_stride = kv_num_heads_ * rotary_params.head_stride;
    }
    ORT_RETURN_IF_ERROR(RunRotaryEmbedding<T>(tp, rotary_params, k_input,
                                              pos_ids.data(), cos_cache->Data<T>(),
                                              sin_cache->Data<T>(), k_rotary, rotary_interleaved_));
    if (packed_qkv) {
      const T* v_input = k_input + kv_num_heads_ * sequence_length * head_size;
      T* v_rotary = k_rotary + kv_num_heads_ * sequence_length * head_size;
      ORT_RETURN_IF_ERROR(rotary_helper::PackVIntoRotaryQKV<T>(tp,
                                                               parameters.batch_size,
                                                               parameters.sequence_length,
                                                               parameters.num_heads,
                                                               parameters.kv_num_heads,
                                                               parameters.head_size,
                                                               v_input,
                                                               v_rotary));
    }
  }
 
  ORT_RETURN_IF_ERROR(context->GetTempSpaceAllocator(&allocator));
  // Compute the attention score and apply the score to V
  return ApplyAttention(q_rotary, packed_qkv ? nullptr : k_rotary, packed_qkv ? nullptr : V.Get<Tensor>().Data<T>(),
                        past_key, past_value, output, present_key, present_value,
                        total_key_lengths, block_row_indices, block_col_indices, parameters, allocator, context);
}
}  // namespace contrib
}  // namespace onnxruntime