Исходный код СУБД 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#include "qembed_layer_norm.h"
 
#include <cmath>
 
#include "contrib_ops/cpu/bert/embed_layer_norm_helper.h"
#include "core/framework/op_kernel.h"
#include "core/providers/common.h"
#include "core/quantization/quantization.h"
 
namespace onnxruntime {
namespace contrib {
 
namespace {
 
template <typename T, typename QuantizedType>
Status ComputeInternal(OpKernelContext* context, float epsilon) {
  const Tensor* input_ids = context->Input<Tensor>(0);
  const Tensor* segment_ids = context->Input<Tensor>(1);  // optional. nullptr if it's distill-bert
  const Tensor* word_embedding = context->Input<Tensor>(2);
  const Tensor* position_embedding = context->Input<Tensor>(3);
  const Tensor* segment_embedding = context->Input<Tensor>(4);  // optional. nullptr if it's distill-bert
  const Tensor* gamma = context->Input<Tensor>(5);
  const Tensor* beta = context->Input<Tensor>(6);
  const Tensor* mask = context->Input<Tensor>(7);  // optional. nullptr if not provided
  const Tensor* word_embedding_scale = context->Input<Tensor>(8);
  const Tensor* position_embedding_scale = context->Input<Tensor>(9);
  const Tensor* segment_embedding_scale = context->Input<Tensor>(10);
  const Tensor* gamma_scale = context->Input<Tensor>(11);
  const Tensor* beta_scale = context->Input<Tensor>(12);
  const Tensor* word_embedding_zero_point = context->Input<Tensor>(13);
  const Tensor* position_embedding_zero_point = context->Input<Tensor>(14);
  const Tensor* segment_embedding_zero_point = context->Input<Tensor>(15);
  const Tensor* gamma_zero_point = context->Input<Tensor>(16);
  const Tensor* beta_zero_point = context->Input<Tensor>(17);
 
  const auto& input_dims = input_ids->Shape().GetDims();
  int batch_size = static_cast<int>(input_dims[0]);
  int sequence_length = static_cast<int>(input_dims[1]);
  int64_t hidden_size = word_embedding->Shape()[1];
 
  // Request outputs:
  TensorShape output_shape({batch_size, sequence_length, hidden_size});
  Tensor* output = context->Output(0, output_shape);
 
  TensorShape mask_index_shape({batch_size});
  Tensor* mask_index = context->Output(1, mask_index_shape);
  bool has_segment_embedding = segment_ids != nullptr;
 
  const int32_t* input_ids_data = input_ids->Data<int32_t>();
  const int32_t* segment_ids_data =
      has_segment_embedding ? segment_ids->Data<int32_t>() : nullptr;
 
  int word_embedding_length = static_cast<int>(word_embedding->Shape()[0]);
  int position_embedding_length = static_cast<int>(position_embedding->Shape()[0]);
  int segment_embedding_length =
      has_segment_embedding ? static_cast<int>(segment_embedding->Shape()[0]) : 0;
 
  // Grab quantization values:
  quantization::Params<QuantizedType> word_embedding_params =
      quantization::GetTensorQuantizationParams<QuantizedType>(word_embedding_scale,
                                                               word_embedding_zero_point);
  quantization::Params<QuantizedType> position_embedding_params =
      quantization::GetTensorQuantizationParams<QuantizedType>(position_embedding_scale,
                                                               position_embedding_zero_point);
  quantization::Params<QuantizedType> segment_embedding_params;
  if (has_segment_embedding) {
    segment_embedding_params =
        quantization::GetTensorQuantizationParams<QuantizedType>(segment_embedding_scale,
                                                                 segment_embedding_zero_point);
  }
  quantization::Params<QuantizedType> gamma_params =
      quantization::GetTensorQuantizationParams<QuantizedType>(gamma_scale, gamma_zero_point);
  quantization::Params<QuantizedType> beta_params =
      quantization::GetTensorQuantizationParams<QuantizedType>(beta_scale, beta_zero_point);
 
  // Grab pointers to buffers each Tensor represents:
  const QuantizedType* word_embedding_data = word_embedding->Data<QuantizedType>();
  const QuantizedType* position_embedding_data = position_embedding->Data<QuantizedType>();
  const QuantizedType* segment_embedding_data =
      has_segment_embedding ? segment_embedding->Data<QuantizedType>() : nullptr;
  const QuantizedType* gamma_data = gamma->Data<QuantizedType>();
  const QuantizedType* beta_data = beta->Data<QuantizedType>();
 
  T* output_data = output->MutableData<T>();
 
  // Perform the Op:
  {
    std::atomic_bool failed{false};
 
    // TODO: Profile and tune this batch parallel execution based on input size.
    // More info: https://github.com/microsoft/onnxruntime/pull/8124/files#r656629895
    int n = batch_size * sequence_length;
    concurrency::ThreadPool::TryBatchParallelFor(
        context->GetOperatorThreadPool(), n, [=, &failed](ptrdiff_t index) {
          int word_col_index = input_ids_data[index];
          if (word_col_index < 0 || word_col_index >= word_embedding_length) {
            failed.store(true, std::memory_order_release);
            return;
          }
          int position_col_index = index % sequence_length;
          if (position_col_index >= position_embedding_length) {
            failed.store(true, std::memory_order_release);
            return;
          }
          int segment_col_index = 0;
          if (nullptr != segment_ids_data) {
            segment_col_index = segment_ids_data[index];
            if (segment_col_index < 0 || segment_col_index >= segment_embedding_length) {
              failed.store(true, std::memory_order_release);
              return;
            }
          }
 
          // Grab inputs for the embeddings for the current batch index:
          const QuantizedType* input_word_embedding =
              word_embedding_data + word_col_index * hidden_size;
          const QuantizedType* input_position_embedding =
              position_embedding_data + position_col_index * hidden_size;
          const QuantizedType* input_segment_embedding = nullptr;
          if (segment_embedding_data != nullptr) {
            input_segment_embedding =
                segment_embedding_data + segment_col_index * hidden_size;
          }
 
          T* output = output_data + (index * hidden_size);
 
          T sum = static_cast<T>(0);
          for (int i = 0; i < hidden_size; ++i) {
            // TODO(kreeger): Use a table query to improve performance:
            T subtotal = quantization::Dequantize<QuantizedType>(input_word_embedding[i],
                                                                 word_embedding_params) +
                         quantization::Dequantize<QuantizedType>(input_position_embedding[i],
                                                                 position_embedding_params);
            if (segment_embedding_data != nullptr) {
              subtotal += quantization::Dequantize<QuantizedType>(input_segment_embedding[i],
                                                                  segment_embedding_params);
            }
            output[i] = subtotal;
            sum += subtotal;
          }
 
          T mean = sum / hidden_size;
          sum = 0;
 
          for (int i = 0; i < hidden_size; i++) {
            T a = output[i] - mean;
            output[i] = a;
            sum += a * a;
          }
 
          T e = sqrt(sum / hidden_size + epsilon);
          for (int i = 0; i < hidden_size; i++) {
            // TODO(kreeger): Consider keeping these as int8 or use PrePack()!
            T cur_gamma = quantization::Dequantize<QuantizedType>(gamma_data[i], gamma_params);
            T cur_beta = quantization::Dequantize<QuantizedType>(beta_data[i], beta_params);
            output[i] = output[i] / e * cur_gamma + cur_beta;
          }
        },
        0);
 
    if (failed.load(std::memory_order_acquire)) {
      return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "input index out of range");
    }
  }
 
  // Calculate mask
  if (nullptr != mask && nullptr != mask_index) {
    const int32_t* mask_data = mask->Data<int32_t>();
    int32_t* mask_index_data = mask_index->MutableData<int32_t>();
    for (int b = 0; b < batch_size; b++) {
      int32_t cur_sum = 0;
      const int32_t* cur_mask_data = mask_data + (static_cast<int64_t>(b) * sequence_length);
      for (int s = 0; s < sequence_length; ++s) {
        if (cur_mask_data[s] == 1) {
          cur_sum += cur_mask_data[s];
        }
      }
      mask_index_data[b] = cur_sum;
    }
  } else if (mask_index != nullptr) {
    memset(mask_index->MutableData<int32_t>(), 0, batch_size * sizeof(int32_t));
  }
  return Status::OK();
}
 
Status CheckQuantizedInputs(OpKernelContext* context, bool* is_signed_inputs) {
  const Tensor* segment_ids_tensor = context->Input<Tensor>(1);
  const Tensor* segment_embedding_tensor = context->Input<Tensor>(4);
  const Tensor* word_embedding_scale_tensor = context->Input<Tensor>(8);
  const Tensor* position_embedding_scale_tensor = context->Input<Tensor>(9);
  const Tensor* segment_embedding_scale_tensor = context->Input<Tensor>(10);
  const Tensor* gamma_scale_tensor = context->Input<Tensor>(11);
  const Tensor* beta_scale_tensor = context->Input<Tensor>(12);
  const Tensor* word_embedding_zero_point_tensor = context->Input<Tensor>(13);
  const Tensor* position_embedding_zero_point_tensor = context->Input<Tensor>(14);
  const Tensor* segment_embedding_zero_point_tensor = context->Input<Tensor>(15);
  const Tensor* gamma_zero_point_tensor = context->Input<Tensor>(16);
  const Tensor* beta_zero_point_tensor = context->Input<Tensor>(17);
 
  const bool has_segment_embedding = segment_ids_tensor != nullptr;
  ORT_RETURN_IF(has_segment_embedding != (segment_embedding_tensor != nullptr) ||
                    has_segment_embedding != (segment_embedding_scale_tensor != nullptr) ||
                    has_segment_embedding != (segment_embedding_zero_point_tensor != nullptr),
                "segment_ids, segment_embedding, segment_embedding_scale, and segment_embedding_zero_point "
                "must either all be provided or all be omitted");
 
  bool word_embedding_is_signed_inputs = word_embedding_zero_point_tensor->IsDataType<int8_t>();
 
  if (!IsScalarOr1ElementVector(word_embedding_scale_tensor)) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                           "Word embedding scale must be a scalar or 1D tensor of size 1");
  }
 
  if (!IsScalarOr1ElementVector(position_embedding_scale_tensor) &&
      position_embedding_scale_tensor->IsDataType<int8_t>() == word_embedding_is_signed_inputs) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                           "Position embedding scale must be a scalar or 1D tensor of size 1");
  }
 
  if (has_segment_embedding && !IsScalarOr1ElementVector(segment_embedding_scale_tensor) &&
      segment_embedding_scale_tensor->IsDataType<int8_t>() == word_embedding_is_signed_inputs) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                           "Segment embedding scale must be a scalar or 1D tensor of size 1");
  }
 
  if (!IsScalarOr1ElementVector(gamma_scale_tensor) &&
      gamma_scale_tensor->IsDataType<int8_t>() == word_embedding_is_signed_inputs) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                           "Gamma scale must be a scalar or 1D tensor of size 1");
  }
 
  if (!IsScalarOr1ElementVector(beta_scale_tensor) &&
      beta_scale_tensor->IsDataType<int8_t>() == word_embedding_is_signed_inputs) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                           "Beta scale must be a scalar or 1D tensor of size 1");
  }
 
  if (!IsScalarOr1ElementVector(word_embedding_zero_point_tensor) &&
      word_embedding_zero_point_tensor->IsDataType<int8_t>() == word_embedding_is_signed_inputs) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                           "Word embedding zero point must be a scalar or 1D tensor of size 1");
  }
 
  if (!IsScalarOr1ElementVector(position_embedding_zero_point_tensor) &&
      position_embedding_zero_point_tensor->IsDataType<int8_t>() == word_embedding_is_signed_inputs) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                           "Position embedding zero point must be a scalar or 1D tensor of size 1");
  }
 
  if (has_segment_embedding && !IsScalarOr1ElementVector(segment_embedding_zero_point_tensor) &&
      segment_embedding_zero_point_tensor->IsDataType<int8_t>() == word_embedding_is_signed_inputs) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                           "Segment embedding zero point must be a scalar or 1D tensor of size 1");
  }
 
  if (!IsScalarOr1ElementVector(gamma_zero_point_tensor) &&
      gamma_zero_point_tensor->IsDataType<int8_t>() == word_embedding_is_signed_inputs) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                           "Gamma zero point must be a scalar or 1D tensor of size 1");
  }
 
  if (!IsScalarOr1ElementVector(beta_zero_point_tensor) &&
      beta_zero_point_tensor->IsDataType<int8_t>() == word_embedding_is_signed_inputs) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                           "Beta zero point must be a scalar or 1D tensor of size 1");
  }
 
  *is_signed_inputs = word_embedding_is_signed_inputs;
  return Status::OK();
}
 
}  // namespace
 
// This op is internal-only, so register outside of onnx:
#define REGISTER_KERNEL_TYPED(T)                                  \
  ONNX_OPERATOR_TYPED_KERNEL_EX(                                  \
      QEmbedLayerNormalization,                                   \
      kMSDomain,                                                  \
      1,                                                          \
      T,                                                          \
      kCpuExecutionProvider,                                      \
      KernelDefBuilder()                                          \
          .TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \
      QEmbedLayerNorm<T>);
 
REGISTER_KERNEL_TYPED(float)
 
template <typename T>
QEmbedLayerNorm<T>::QEmbedLayerNorm(const OpKernelInfo& op_kernel_info)
    : EmbedLayerNormBase(op_kernel_info) {
}
 
template <typename T>
Status QEmbedLayerNorm<T>::Compute(OpKernelContext* context) const {
  ORT_RETURN_IF_ERROR(embed_layer_norm::CheckInputs(context, true));
 
  bool is_signed_inputs = false;
  ORT_RETURN_IF_ERROR(CheckQuantizedInputs(context, &is_signed_inputs));
 
  if (is_signed_inputs) {
    return ComputeInternal<T, int8_t>(context, epsilon());
  } else {
    return ComputeInternal<T, uint8_t>(context, epsilon());
  }
}
 
}  // namespace contrib
}  // namespace onnxruntime