Skip to content

[TF] Refactor gradients computation with expandingShape #24249

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 24, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions stdlib/public/TensorFlow/Gradients.swift
Original file line number Diff line number Diff line change
Expand Up @@ -577,10 +577,9 @@ extension Tensor where Scalar : TensorFlowFloatingPoint {
squeezingAxes axes: Tensor<Int32>
) -> (Tensor, (Tensor) -> Tensor) {
let value = sum(squeezingAxes: axes)
return (value, { [shape = shapeTensor] in
var res = $0
for i in axes.array.scalars { res = res.expandingShape(at: Int(i)) }
return res.broadcast(toShape: shape)
return (value, { [shape = shapeTensor] v in
let unsqueezed = v.expandingShape(at: axes.scalars.map { Int($0) })
return unsqueezed.broadcast(toShape: shape)
})
}

Expand All @@ -599,10 +598,9 @@ extension Tensor where Scalar : TensorFlowFloatingPoint {
) -> (Tensor, (Tensor) -> Tensor) {
let value = mean(squeezingAxes: axes)
let count = Raw.gather(params: shapeTensor, indices: axes).product()
return (value, { [shape = shapeTensor] in
var res = $0
for i in axes.array.scalars { res = res.expandingShape(at: Int(i)) }
return res.broadcast(toShape: shape) / Tensor(count)
return (value, { [shape = shapeTensor] v in
let unsqueezed = v.expandingShape(at: axes.scalars.map { Int($0) })
return unsqueezed.broadcast(toShape: shape) / Tensor(count)
})
}
}
Expand Down