aboutsummaryrefslogtreecommitdiff
path: root/icing/scoring/score-and-rank_benchmark.cc
blob: cc1d99540c82aec335a26ddfa2ab38aa15c5cf2f (plain)
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
// Copyright (C) 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <algorithm>
#include <cstdint>
#include <limits>
#include <memory>
#include <random>
#include <string>
#include <utility>
#include <vector>

#include "testing/base/public/benchmark.h"
#include "icing/document-builder.h"
#include "icing/file/filesystem.h"
#include "icing/index/hit/doc-hit-info.h"
#include "icing/index/iterator/doc-hit-info-iterator-test-util.h"
#include "icing/index/iterator/doc-hit-info-iterator.h"
#include "icing/proto/document.pb.h"
#include "icing/proto/schema.pb.h"
#include "icing/proto/scoring.pb.h"
#include "icing/schema/schema-store.h"
#include "icing/scoring/ranker.h"
#include "icing/scoring/scored-document-hit.h"
#include "icing/scoring/scoring-processor.h"
#include "icing/store/document-id.h"
#include "icing/store/document-store.h"
#include "icing/testing/common-matchers.h"
#include "icing/testing/tmp-directory.h"
#include "icing/util/clock.h"

// This is an overall benchmark for ScoringProcessor, Scorer, and Ranker. It
// shows how performance varies when we score different numbers of document
// hits.
//
// Run on a Linux workstation:
//    $ blaze build -c opt --dynamic_mode=off --copt=-gmlt
//    //icing/scoring:score-and-rank_benchmark
//
//    $ blaze-bin/icing/scoring/score-and-rank_benchmark
//    --benchmarks=all --benchmark_memory_usage
//
// Run on an Android device:
//    $ blaze build --copt="-DGOOGLE_COMMANDLINEFLAGS_FULL_API=1"
//    --config=android_arm64 -c opt --dynamic_mode=off --copt=-gmlt
//    //icing/scoring:score-and-rank_benchmark
//
//    $ adb push blaze-bin/icing/scoring/score-and-rank_benchmark
//    /data/local/tmp/
//
//    $ adb shell /data/local/tmp/score-and-rank_benchmark --benchmarks=all

namespace icing {
namespace lib {

namespace {

SchemaProto CreateSchemaWithEmailType() {
  SchemaProto schema;
  auto type_config = schema.add_types();
  type_config->set_schema_type("Email");
  auto subject = type_config->add_properties();
  subject->set_property_name("subject");
  subject->set_data_type(PropertyConfigProto::DataType::STRING);
  subject->set_cardinality(PropertyConfigProto::Cardinality::OPTIONAL);
  return schema;
}

DocumentProto CreateEmailDocument(int id, int document_score,
                                  uint64_t creation_timestamp_ms) {
  return DocumentBuilder()
      .SetKey("icing", "uri" + std::to_string(id))
      .SetSchema("Email")
      .AddStringProperty("subject", "subject" + std::to_string(id))
      .SetScore(document_score)
      .SetCreationTimestampMs(creation_timestamp_ms)
      .Build();
}

void BM_ScoreAndRankDocumentHitsByDocumentScore(benchmark::State& state) {
  const std::string base_dir = GetTestTempDir() + "/score_and_rank_benchmark";
  const std::string document_store_dir = base_dir + "/document_store";
  const std::string schema_store_dir = base_dir + "/schema_store";

  // Creates file directories
  Filesystem filesystem;
  filesystem.DeleteDirectoryRecursively(base_dir.c_str());
  filesystem.CreateDirectoryRecursively(document_store_dir.c_str());
  filesystem.CreateDirectoryRecursively(schema_store_dir.c_str());

  Clock clock;
  ICING_ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<SchemaStore> schema_store,
      SchemaStore::Create(&filesystem, base_dir, &clock));

  ICING_ASSERT_OK_AND_ASSIGN(
      DocumentStore::CreateResult create_result,
      DocumentStore::Create(&filesystem, document_store_dir, &clock,
                            schema_store.get()));
  std::unique_ptr<DocumentStore> document_store =
      std::move(create_result.document_store);

  ICING_ASSERT_OK(schema_store->SetSchema(CreateSchemaWithEmailType()));

  ScoringSpecProto scoring_spec;
  scoring_spec.set_rank_by(ScoringSpecProto::RankingStrategy::DOCUMENT_SCORE);
  ICING_ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ScoringProcessor> scoring_processor,
      ScoringProcessor::Create(scoring_spec, document_store.get(),
                               schema_store.get()));

  int num_to_score = state.range(0);
  int num_of_documents = state.range(1);

  std::mt19937 random_generator;
  std::uniform_int_distribution<int> distribution(
      1, std::numeric_limits<int>::max());

  // Puts documents into document store
  std::vector<DocHitInfo> doc_hit_infos;
  for (int i = 0; i < num_of_documents; i++) {
    ICING_ASSERT_OK_AND_ASSIGN(
        DocumentId document_id,
        document_store->Put(CreateEmailDocument(
            /*id=*/i, /*document_score=*/distribution(random_generator),
            /*creation_timestamp_ms=*/1)));
    doc_hit_infos.emplace_back(document_id);
  }

  ScoredDocumentHitComparator scored_document_hit_comparator(
      /*is_descending=*/true);

  for (auto _ : state) {
    // Creates a dummy DocHitInfoIterator with results, we need to pause the
    // timer here so that the cost of copying test data is not included.
    state.PauseTiming();
    std::unique_ptr<DocHitInfoIterator> doc_hit_info_iterator =
        std::make_unique<DocHitInfoIteratorDummy>(doc_hit_infos);
    state.ResumeTiming();

    std::vector<ScoredDocumentHit> scored_document_hits =
        scoring_processor->Score(std::move(doc_hit_info_iterator),
                                 num_to_score);

    BuildHeapInPlace(&scored_document_hits, scored_document_hit_comparator);
    // Ranks and gets the first page, 20 is a common page size
    std::vector<ScoredDocumentHit> results =
        PopTopResultsFromHeap(&scored_document_hits, /*num_results=*/20,
                              scored_document_hit_comparator);
  }

  // Clean up
  document_store.reset();
  schema_store.reset();
  filesystem.DeleteDirectoryRecursively(base_dir.c_str());
}
BENCHMARK(BM_ScoreAndRankDocumentHitsByDocumentScore)
    // num_to_score, num_of_documents in document store
    ->ArgPair(1000, 30000)
    ->ArgPair(3000, 30000)
    ->ArgPair(5000, 30000)
    ->ArgPair(7000, 30000)
    ->ArgPair(9000, 30000)
    ->ArgPair(11000, 30000)
    ->ArgPair(13000, 30000)
    ->ArgPair(15000, 30000)
    ->ArgPair(17000, 30000)
    ->ArgPair(19000, 30000)
    ->ArgPair(21000, 30000)
    ->ArgPair(23000, 30000)
    ->ArgPair(25000, 30000)
    ->ArgPair(27000, 30000)
    ->ArgPair(29000, 30000)
    // Starting from this line, we're trying to see if num_of_documents affects
    // performance
    ->ArgPair(10000, 10000)
    ->ArgPair(10000, 12000)
    ->ArgPair(10000, 14000)
    ->ArgPair(10000, 16000)
    ->ArgPair(10000, 18000)
    ->ArgPair(10000, 20000);

void BM_ScoreAndRankDocumentHitsByCreationTime(benchmark::State& state) {
  const std::string base_dir = GetTestTempDir() + "/score_and_rank_benchmark";
  const std::string document_store_dir = base_dir + "/document_store";
  const std::string schema_store_dir = base_dir + "/schema_store";

  // Creates file directories
  Filesystem filesystem;
  filesystem.DeleteDirectoryRecursively(base_dir.c_str());
  filesystem.CreateDirectoryRecursively(document_store_dir.c_str());
  filesystem.CreateDirectoryRecursively(schema_store_dir.c_str());

  Clock clock;
  ICING_ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<SchemaStore> schema_store,
      SchemaStore::Create(&filesystem, base_dir, &clock));

  ICING_ASSERT_OK_AND_ASSIGN(
      DocumentStore::CreateResult create_result,
      DocumentStore::Create(&filesystem, document_store_dir, &clock,
                            schema_store.get()));
  std::unique_ptr<DocumentStore> document_store =
      std::move(create_result.document_store);

  ICING_ASSERT_OK(schema_store->SetSchema(CreateSchemaWithEmailType()));

  ScoringSpecProto scoring_spec;
  scoring_spec.set_rank_by(
      ScoringSpecProto::RankingStrategy::CREATION_TIMESTAMP);
  ICING_ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ScoringProcessor> scoring_processor,
      ScoringProcessor::Create(scoring_spec, document_store.get(),
                               schema_store.get()));

  int num_to_score = state.range(0);
  int num_of_documents = state.range(1);

  std::mt19937_64 random_generator;
  std::uniform_int_distribution<int64_t> distribution(
      1, std::numeric_limits<int64_t>::max());

  // Puts documents into document store
  std::vector<DocHitInfo> doc_hit_infos;
  for (int i = 0; i < num_of_documents; i++) {
    ICING_ASSERT_OK_AND_ASSIGN(
        DocumentId document_id,
        document_store->Put(CreateEmailDocument(
            /*id=*/i, /*document_score=*/1,
            /*creation_timestamp_ms=*/distribution(random_generator))));
    doc_hit_infos.emplace_back(document_id);
  }

  ScoredDocumentHitComparator scored_document_hit_comparator(
      /*is_descending=*/true);

  for (auto _ : state) {
    // Creates a dummy DocHitInfoIterator with results, we need to pause the
    // timer here so that the cost of copying test data is not included.
    state.PauseTiming();
    std::unique_ptr<DocHitInfoIterator> doc_hit_info_iterator =
        std::make_unique<DocHitInfoIteratorDummy>(doc_hit_infos);
    state.ResumeTiming();

    std::vector<ScoredDocumentHit> scored_document_hits =
        scoring_processor->Score(std::move(doc_hit_info_iterator),
                                 num_to_score);

    BuildHeapInPlace(&scored_document_hits, scored_document_hit_comparator);
    // Ranks and gets the first page, 20 is a common page size
    std::vector<ScoredDocumentHit> results =
        PopTopResultsFromHeap(&scored_document_hits, /*num_results=*/20,
                              scored_document_hit_comparator);
  }

  // Clean up
  document_store.reset();
  schema_store.reset();
  filesystem.DeleteDirectoryRecursively(base_dir.c_str());
}
BENCHMARK(BM_ScoreAndRankDocumentHitsByCreationTime)
    // num_to_score, num_of_documents in document store
    ->ArgPair(1000, 30000)
    ->ArgPair(3000, 30000)
    ->ArgPair(5000, 30000)
    ->ArgPair(7000, 30000)
    ->ArgPair(9000, 30000)
    ->ArgPair(11000, 30000)
    ->ArgPair(13000, 30000)
    ->ArgPair(15000, 30000)
    ->ArgPair(17000, 30000)
    ->ArgPair(19000, 30000)
    ->ArgPair(21000, 30000)
    ->ArgPair(23000, 30000)
    ->ArgPair(25000, 30000)
    ->ArgPair(27000, 30000)
    ->ArgPair(29000, 30000)
    // Starting from this line, we're trying to see if num_of_documents affects
    // performance
    ->ArgPair(10000, 10000)
    ->ArgPair(10000, 12000)
    ->ArgPair(10000, 14000)
    ->ArgPair(10000, 16000)
    ->ArgPair(10000, 18000)
    ->ArgPair(10000, 20000);

void BM_ScoreAndRankDocumentHitsNoScoring(benchmark::State& state) {
  const std::string base_dir = GetTestTempDir() + "/score_and_rank_benchmark";
  const std::string document_store_dir = base_dir + "/document_store";
  const std::string schema_store_dir = base_dir + "/schema_store";

  // Creates file directories
  Filesystem filesystem;
  filesystem.DeleteDirectoryRecursively(base_dir.c_str());
  filesystem.CreateDirectoryRecursively(document_store_dir.c_str());
  filesystem.CreateDirectoryRecursively(schema_store_dir.c_str());

  Clock clock;
  ICING_ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<SchemaStore> schema_store,
      SchemaStore::Create(&filesystem, base_dir, &clock));

  ICING_ASSERT_OK_AND_ASSIGN(
      DocumentStore::CreateResult create_result,
      DocumentStore::Create(&filesystem, document_store_dir, &clock,
                            schema_store.get()));
  std::unique_ptr<DocumentStore> document_store =
      std::move(create_result.document_store);

  ICING_ASSERT_OK(schema_store->SetSchema(CreateSchemaWithEmailType()));

  ScoringSpecProto scoring_spec;
  scoring_spec.set_rank_by(ScoringSpecProto::RankingStrategy::NONE);
  ICING_ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ScoringProcessor> scoring_processor,
      ScoringProcessor::Create(scoring_spec, document_store.get(),
                               schema_store.get()));

  int num_to_score = state.range(0);
  int num_of_documents = state.range(1);

  // Puts documents into document store
  std::vector<DocHitInfo> doc_hit_infos;
  for (int i = 0; i < num_of_documents; i++) {
    ICING_ASSERT_OK_AND_ASSIGN(
        DocumentId document_id,
        document_store->Put(CreateEmailDocument(/*id=*/i, /*document_score=*/1,
                                                /*creation_timestamp_ms=*/1)));
    doc_hit_infos.emplace_back(document_id);
  }

  ScoredDocumentHitComparator scored_document_hit_comparator(
      /*is_descending=*/true);

  for (auto _ : state) {
    // Creates a dummy DocHitInfoIterator with results, we need to pause the
    // timer here so that the cost of copying test data is not included.
    state.PauseTiming();
    std::unique_ptr<DocHitInfoIterator> doc_hit_info_iterator =
        std::make_unique<DocHitInfoIteratorDummy>(doc_hit_infos);
    state.ResumeTiming();

    std::vector<ScoredDocumentHit> scored_document_hits =
        scoring_processor->Score(std::move(doc_hit_info_iterator),
                                 num_to_score);

    BuildHeapInPlace(&scored_document_hits, scored_document_hit_comparator);
    // Ranks and gets the first page, 20 is a common page size
    std::vector<ScoredDocumentHit> results =
        PopTopResultsFromHeap(&scored_document_hits, /*num_results=*/20,
                              scored_document_hit_comparator);
  }

  // Clean up
  document_store.reset();
  schema_store.reset();
  filesystem.DeleteDirectoryRecursively(base_dir.c_str());
}
BENCHMARK(BM_ScoreAndRankDocumentHitsNoScoring)
    // num_to_score, num_of_documents in document store
    ->ArgPair(1000, 30000)
    ->ArgPair(3000, 30000)
    ->ArgPair(5000, 30000)
    ->ArgPair(7000, 30000)
    ->ArgPair(9000, 30000)
    ->ArgPair(11000, 30000)
    ->ArgPair(13000, 30000)
    ->ArgPair(15000, 30000)
    ->ArgPair(17000, 30000)
    ->ArgPair(19000, 30000)
    ->ArgPair(21000, 30000)
    ->ArgPair(23000, 30000)
    ->ArgPair(25000, 30000)
    ->ArgPair(27000, 30000)
    ->ArgPair(29000, 30000)
    // Starting from this line, we're trying to see if num_of_documents affects
    // performance
    ->ArgPair(10000, 10000)
    ->ArgPair(10000, 12000)
    ->ArgPair(10000, 14000)
    ->ArgPair(10000, 16000)
    ->ArgPair(10000, 18000)
    ->ArgPair(10000, 20000);

void BM_ScoreAndRankDocumentHitsByRelevanceScoring(benchmark::State& state) {
  const std::string base_dir = GetTestTempDir() + "/score_and_rank_benchmark";
  const std::string document_store_dir = base_dir + "/document_store";
  const std::string schema_store_dir = base_dir + "/schema_store";

  // Creates file directories
  Filesystem filesystem;
  filesystem.DeleteDirectoryRecursively(base_dir.c_str());
  filesystem.CreateDirectoryRecursively(document_store_dir.c_str());
  filesystem.CreateDirectoryRecursively(schema_store_dir.c_str());

  Clock clock;
  ICING_ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<SchemaStore> schema_store,
      SchemaStore::Create(&filesystem, base_dir, &clock));

  ICING_ASSERT_OK_AND_ASSIGN(
      DocumentStore::CreateResult create_result,
      DocumentStore::Create(&filesystem, document_store_dir, &clock,
                            schema_store.get()));
  std::unique_ptr<DocumentStore> document_store =
      std::move(create_result.document_store);

  ICING_ASSERT_OK(schema_store->SetSchema(CreateSchemaWithEmailType()));

  ScoringSpecProto scoring_spec;
  scoring_spec.set_rank_by(ScoringSpecProto::RankingStrategy::RELEVANCE_SCORE);
  ICING_ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ScoringProcessor> scoring_processor,
      ScoringProcessor::Create(scoring_spec, document_store.get(),
                               schema_store.get()));

  int num_to_score = state.range(0);
  int num_of_documents = state.range(1);

  std::mt19937 random_generator;
  std::uniform_int_distribution<int> distribution(
      1, std::numeric_limits<int>::max());

  SectionId section_id = 0;
  SectionIdMask section_id_mask = 1U << section_id;

  // Puts documents into document store
  std::vector<DocHitInfo> doc_hit_infos;
  for (int i = 0; i < num_of_documents; i++) {
    ICING_ASSERT_OK_AND_ASSIGN(
        DocumentId document_id,
        document_store->Put(CreateEmailDocument(
                                /*id=*/i, /*document_score=*/1,
                                /*creation_timestamp_ms=*/1),
                            /*num_tokens=*/10));
    DocHitInfo doc_hit = DocHitInfo(document_id, section_id_mask);
    // Set five matches for term "foo" for each document hit.
    doc_hit.UpdateSection(section_id, /*hit_term_frequency=*/5);
    doc_hit_infos.push_back(doc_hit);
  }

  ScoredDocumentHitComparator scored_document_hit_comparator(
      /*is_descending=*/true);

  for (auto _ : state) {
    // Creates a dummy DocHitInfoIterator with results, we need to pause the
    // timer here so that the cost of copying test data is not included.
    state.PauseTiming();
    std::unique_ptr<DocHitInfoIterator> doc_hit_info_iterator =
        std::make_unique<DocHitInfoIteratorDummy>(doc_hit_infos, "foo");
    // Create a query term iterator that assigns the document hits to term
    // "foo".
    std::unordered_map<std::string, std::unique_ptr<DocHitInfoIterator>>
        query_term_iterators;
    query_term_iterators["foo"] =
        std::make_unique<DocHitInfoIteratorDummy>(doc_hit_infos, "foo");
    state.ResumeTiming();

    std::vector<ScoredDocumentHit> scored_document_hits =
        scoring_processor->Score(std::move(doc_hit_info_iterator), num_to_score,
                                 &query_term_iterators);

    BuildHeapInPlace(&scored_document_hits, scored_document_hit_comparator);
    // Ranks and gets the first page, 20 is a common page size
    std::vector<ScoredDocumentHit> results =
        PopTopResultsFromHeap(&scored_document_hits, /*num_results=*/20,
                              scored_document_hit_comparator);
  }

  // Clean up
  document_store.reset();
  schema_store.reset();
  filesystem.DeleteDirectoryRecursively(base_dir.c_str());
}
BENCHMARK(BM_ScoreAndRankDocumentHitsByRelevanceScoring)
    // num_to_score, num_of_documents in document store
    ->ArgPair(1000, 30000)
    ->ArgPair(3000, 30000)
    ->ArgPair(5000, 30000)
    ->ArgPair(7000, 30000)
    ->ArgPair(9000, 30000)
    ->ArgPair(11000, 30000)
    ->ArgPair(13000, 30000)
    ->ArgPair(15000, 30000)
    ->ArgPair(17000, 30000)
    ->ArgPair(19000, 30000)
    ->ArgPair(21000, 30000)
    ->ArgPair(23000, 30000)
    ->ArgPair(25000, 30000)
    ->ArgPair(27000, 30000)
    ->ArgPair(29000, 30000)
    // Starting from this line, we're trying to see if num_of_documents affects
    // performance
    ->ArgPair(10000, 10000)
    ->ArgPair(10000, 12000)
    ->ArgPair(10000, 14000)
    ->ArgPair(10000, 16000)
    ->ArgPair(10000, 18000)
    ->ArgPair(10000, 20000);

}  // namespace

}  // namespace lib
}  // namespace icing