MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / numerical_diff_pt2

Method numerical_diff_pt2

test/src/numerical_diff.cpp:19–70  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

17using namespace mgb;
18
19std::vector<HostTensorND> mgb::numerical_diff_pt2(
20 const std::vector<HostTensorND*>& input, std::function<float()> cost,
21 const std::vector<Maybe<float>>& eps) {
22 std::vector<HostTensorND> result;
23 if (!eps.empty())
24 mgb_assert(eps.size() == input.size());
25
26 for (size_t cur_inp_idx = 0; cur_inp_idx < input.size(); ++cur_inp_idx) {
27 result.emplace_back();
28 if (!input[cur_inp_idx])
29 continue;
30 auto&& cur_inp = input[cur_inp_idx];
31 auto&& dest = result.back();
32 dest.comp_node(cur_inp->comp_node())
33 .dtype(cur_inp->dtype())
34 .resize(cur_inp->shape());
35 auto dptr = dest.ptr<float>();
36
37 mgb_assert(cur_inp->layout().is_contiguous() || cur_inp->layout().is_empty());
38 auto cur_inp_ptr = cur_inp->ptr<float>();
39
40 mgb::RealTimer timer;
41 double prev_record = 0.0;
42 for (size_t i = 0, it = cur_inp->layout().total_nr_elems(); i < it; ++i) {
43 auto orig = cur_inp_ptr[i];
44 float delta;
45 if (eps.empty() || !eps[cur_inp_idx].valid()) {
46 delta = std::sqrt(std::numeric_limits<float>::epsilon()) *
47 std::max<float>(std::fabs(orig), 1);
48 } else {
49 delta = eps[cur_inp_idx].val();
50 }
51 cur_inp_ptr[i] = orig - delta;
52 auto c0 = cost();
53 cur_inp_ptr[i] = orig + delta;
54 auto c1 = cost();
55 cur_inp_ptr[i] = orig;
56
57 auto cur_time = timer.get_secs();
58 if (cur_time - prev_record > 10) {
59 prev_record = cur_time;
60 mgb_log_warn(
61 "numerical diff running for more than %.3f secs, "
62 "consider to reduce the tensor size",
63 cur_time);
64 }
65
66 dptr[i] = (c1 - c0) / (delta * 2);
67 }
68 }
69 return result;
70}
71
72namespace mgb {
73// explicit inst to avoid link error for Maybe::Maybe()

Callers

nothing calls this directly

Calls 15

emplace_backMethod · 0.80
backMethod · 0.80
resizeMethod · 0.80
sqrtFunction · 0.50
fabsFunction · 0.50
emptyMethod · 0.45
sizeMethod · 0.45
dtypeMethod · 0.45
comp_nodeMethod · 0.45
shapeMethod · 0.45
is_contiguousMethod · 0.45
layoutMethod · 0.45

Tested by

no test coverage detected