| 293 | } |
| 294 | |
| 295 | ValueRefList GradTransformation::apply_transformation( |
| 296 | const Operator& op, Span<ValueRef> inputs) { |
| 297 | auto fallback = [&] { |
| 298 | SmallVector<ValueRef> unwrapped_inputs(inputs.size()); |
| 299 | { |
| 300 | // overhead |
| 301 | for (size_t i = 0; i < inputs.size(); ++i) { |
| 302 | if (auto&& grad_value = as_grad_value(inputs[i])) { |
| 303 | unwrapped_inputs[i] = grad_value->m_value; |
| 304 | } else { |
| 305 | unwrapped_inputs[i] = inputs[i]; |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | return imperative::apply(op, unwrapped_inputs); |
| 310 | }; |
| 311 | if (op.is<GetAttr>()) { |
| 312 | // overhead |
| 313 | if (auto&& grad_value = as_grad_value(inputs.item())) { |
| 314 | return imperative::apply(op, grad_value->m_value); |
| 315 | } else { |
| 316 | return imperative::apply(op, inputs); |
| 317 | } |
| 318 | } |
| 319 | if (m_suppressed) { |
| 320 | return fallback(); |
| 321 | } |
| 322 | if (auto* op_val = op.as<ApplyOp>()) { |
| 323 | size_t nr_require_grad = 0; |
| 324 | SmallVector<bool> require_grads(inputs.size()); |
| 325 | for (size_t i = 0; i < inputs.size(); ++i) { |
| 326 | if (is_grad_value(inputs[i])) { |
| 327 | nr_require_grad++; |
| 328 | require_grads[i] = true; |
| 329 | } else { |
| 330 | require_grads[i] = false; |
| 331 | } |
| 332 | } |
| 333 | if (nr_require_grad == 0) { |
| 334 | return imperative::apply(op, inputs); |
| 335 | } |
| 336 | SmallVector<ValueRef> captured_inputs(inputs.size()); |
| 337 | SmallVector<bool> inputs_require_grad(inputs.size()); |
| 338 | // capture value so that trace could assume input as same |
| 339 | auto capture_value = [](const ValueRef& value) { |
| 340 | // TODO: fastpath copy shouldn't be an OpDef |
| 341 | static auto fastpath_copy = FastpathCopy::make(); |
| 342 | return imperative::apply(ApplyOp(*fastpath_copy), value)[0]; |
| 343 | }; |
| 344 | for (size_t i = 0; i < inputs.size(); ++i) { |
| 345 | auto& input = inputs[i]; |
| 346 | if (auto&& grad_value = as_grad_value(input)) { |
| 347 | captured_inputs[i] = capture_value(grad_value->m_value); |
| 348 | inputs_require_grad[i] = true; |
| 349 | } else { |
| 350 | captured_inputs[i] = capture_value(input); |
| 351 | inputs_require_grad[i] = false; |
| 352 | } |
nothing calls this directly
no test coverage detected