test-barrier.cpp 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include "ggml.h"
  2. #include "ggml-cpu.h"
  3. #include <chrono>
  4. #include <iostream>
  5. #include <cstdio>
  6. #include <cstdlib>
  7. #include <cassert>
  8. #include <vector>
  9. #include <thread>
  10. #define MAX_NARGS 2
  11. int main(int argc, char *argv[]) {
  12. int n_threads = std::max(1, std::min(4, (int) std::thread::hardware_concurrency()));
  13. int n_rounds = 100;
  14. if (argc > 1) {
  15. n_threads = std::atoi(argv[1]);
  16. }
  17. if (argc > 2) {
  18. n_rounds = std::atoi(argv[2]);
  19. }
  20. struct ggml_init_params params = {
  21. /* .mem_size = */ 1024*1024*1024,
  22. /* .mem_buffer = */ NULL,
  23. /* .no_alloc = */ false,
  24. };
  25. struct ggml_context * ctx = ggml_init(params);
  26. // Create graph
  27. struct ggml_cgraph * gf = ggml_new_graph(ctx);
  28. // Lots of small, parallel ops where barriers in between will dominate
  29. struct ggml_tensor * out = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 64);
  30. for (int i = 0; i < 1000; i++) {
  31. struct ggml_tensor * a = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, 64, 128);
  32. out = ggml_mul_mat(ctx, a, out);
  33. struct ggml_tensor * d = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, 128, 64);
  34. out = ggml_mul_mat(ctx, d, out);
  35. }
  36. ggml_build_forward_expand(gf, out);
  37. int n_nodes = ggml_graph_n_nodes(gf);
  38. // Create threadpool
  39. struct ggml_threadpool_params tpp = ggml_threadpool_params_default(n_threads);
  40. struct ggml_threadpool* threadpool = ggml_threadpool_new(&tpp);
  41. if (!threadpool) {
  42. fprintf(stderr, "threadpool create failed : n_threads %d\n", n_threads);
  43. exit(1);
  44. }
  45. // Create compute plan
  46. struct ggml_cplan cplan = ggml_graph_plan(gf, n_threads, threadpool);
  47. std::vector<uint8_t> work_data(cplan.work_size);
  48. cplan.work_data = work_data.data();
  49. std::cerr << "graph-compute with"
  50. << "\n n_threads: " << n_threads
  51. << "\n n_nodes: " << n_nodes
  52. << "\n n_rounds: " << n_rounds
  53. << "\n";
  54. // ggml_graph_print(gf);
  55. // Warmup
  56. ggml_graph_compute(gf, &cplan);
  57. auto t0 = std::chrono::high_resolution_clock::now();
  58. for (int i=0; i < n_rounds; i++) {
  59. ggml_graph_compute(gf, &cplan);
  60. }
  61. auto t1 = std::chrono::high_resolution_clock::now();
  62. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(t1-t0).count();
  63. auto nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(t1-t0).count();
  64. std::cerr << "graph-compute took " << usec << " usec "
  65. << "\n " << (float) usec / n_rounds << " usec per-iter"
  66. << "\n " << (float) nsec / (n_rounds * n_nodes) << " nsec per-node"
  67. << "\n";
  68. ggml_threadpool_free(threadpool);
  69. ggml_free(ctx);
  70. return 0;
  71. }