| 616 | } |
| 617 | |
| 618 | static std::pair<int, int> test_gradient_accumulation( |
| 619 | enum ggml_opt_optimizer_type optim, |
| 620 | ggml_backend_sched_t backend_sched, ggml_backend_t backend, const int32_t nbatch_physical, const enum ggml_opt_loss_type loss_type) { |
| 621 | int ntest = 0; |
| 622 | int npass = 0; |
| 623 | |
| 624 | struct helper_ctx_data cd = helper_get_ctx_data( |
| 625 | optim, |
| 626 | backend_sched, backend, /*init_opt_ctx =*/ true, /*optimizer_defaults =*/ false, /*nbatch_logical =*/ 6, nbatch_physical, loss_type); |
| 627 | |
| 628 | std::vector<float> grad_history(ndata); |
| 629 | for (int64_t idata = 0; idata < ndata; ++idata) { |
| 630 | grad_history[idata] = NAN; |
| 631 | } |
| 632 | |
| 633 | bool const adamw = optim == GGML_OPT_OPTIMIZER_TYPE_ADAMW; |
| 634 | if (adamw) |
| 635 | for (int epoch = 1; epoch <= 4; ++epoch) { |
| 636 | if (nbatch_physical == 1) { |
| 637 | for (int idata = 0; idata < ndata; ++idata) { |
| 638 | const float idataf = idata; |
| 639 | ggml_opt_alloc(cd.opt_ctx, /*backward =*/ true); |
| 640 | ggml_backend_tensor_set(cd.inputs, &idataf, 0, 1*sizeof(float)); |
| 641 | ggml_opt_eval(cd.opt_ctx, cd.result); |
| 642 | ggml_backend_tensor_get(ggml_opt_grad_acc(cd.opt_ctx, cd.weights), grad_history.data() + idata, 0, 1*sizeof(float)); |
| 643 | } |
| 644 | } else if (nbatch_physical == 2) { |
| 645 | for (int idata = 0; idata < ndata; idata += 2) { |
| 646 | const float idataf[2] = {float(idata + 0), float(idata + 1)}; |
| 647 | ggml_opt_alloc(cd.opt_ctx, /*backward =*/ true); |
| 648 | ggml_backend_tensor_set(cd.inputs, idataf, 0, 2*sizeof(float)); |
| 649 | ggml_opt_eval(cd.opt_ctx, cd.result); |
| 650 | |
| 651 | grad_history[idata + 0] = 0.0f; |
| 652 | ggml_backend_tensor_get(ggml_opt_grad_acc(cd.opt_ctx, cd.weights), grad_history.data() + idata + 1, 0, 1*sizeof(float)); |
| 653 | } |
| 654 | } else { |
| 655 | GGML_ASSERT(false); |
| 656 | } |
| 657 | |
| 658 | { |
| 659 | GGML_ASSERT(ndata == 6); |
| 660 | constexpr double atol = 1e-6; |
| 661 | bool subtest_ok = true; |
| 662 | if (loss_type == GGML_OPT_LOSS_TYPE_SUM) { |
| 663 | if (nbatch_physical == 1) { |
| 664 | subtest_ok = subtest_ok && almost_equal(grad_history[0], 1.0, atol); |
| 665 | subtest_ok = subtest_ok && almost_equal(grad_history[2], 3.0, atol); |
| 666 | subtest_ok = subtest_ok && almost_equal(grad_history[4], 5.0, atol); |
| 667 | } else { |
| 668 | subtest_ok = subtest_ok && almost_equal(grad_history[0], 0.0, atol); |
| 669 | subtest_ok = subtest_ok && almost_equal(grad_history[2], 0.0, atol); |
| 670 | subtest_ok = subtest_ok && almost_equal(grad_history[4], 0.0, atol); |
| 671 | } |
| 672 | subtest_ok = subtest_ok && almost_equal(grad_history[1], 2.0, atol); |
| 673 | subtest_ok = subtest_ok && almost_equal(grad_history[3], 4.0, atol); |
| 674 | subtest_ok = subtest_ok && almost_equal(grad_history[5], 6.0, atol); |
| 675 | } else if (loss_type == GGML_OPT_LOSS_TYPE_MEAN) { |
no test coverage detected