|
| 1 | +// Copyright 2020 The TensorFlow Authors. All Rights Reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import TensorFlow |
| 16 | + |
| 17 | +struct CellRule: Layer { |
| 18 | + @noDerivative var perceptionFilter: Tensor<Float> |
| 19 | + @noDerivative let fireRate: Float |
| 20 | + |
| 21 | + var conv1: Conv2D<Float> |
| 22 | + var conv2: Conv2D<Float> |
| 23 | + |
| 24 | + init(stateChannels: Int, fireRate: Float, useBias: Bool) { |
| 25 | + self.fireRate = fireRate |
| 26 | + |
| 27 | + let horizontalSobelKernel = |
| 28 | + Tensor<Float>( |
| 29 | + shape: [3, 3, 1, 1], scalars: [-1.0, 0.0, 1.0, -2.0, 0.0, 2.0, -1.0, 0.0, 1.0]) / 8.0 |
| 30 | + let horizontalSobelFilter = horizontalSobelKernel.broadcasted(to: [3, 3, stateChannels, 1]) |
| 31 | + let verticalSobelKernel = |
| 32 | + Tensor<Float>( |
| 33 | + shape: [3, 3, 1, 1], scalars: [-1.0, -2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 2.0, 1.0]) / 8.0 |
| 34 | + let verticalSobelFilter = verticalSobelKernel.broadcasted(to: [3, 3, stateChannels, 1]) |
| 35 | + let identityKernel = Tensor<Float>( |
| 36 | + shape: [3, 3, 1, 1], scalars: [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]) |
| 37 | + let identityFilter = identityKernel.broadcasted(to: [3, 3, stateChannels, 1]) |
| 38 | + perceptionFilter = Tensor( |
| 39 | + concatenating: [horizontalSobelFilter, verticalSobelFilter, identityFilter], alongAxis: 3) |
| 40 | + |
| 41 | + conv1 = Conv2D<Float>(filterShape: (1, 1, stateChannels * 3, 128)) |
| 42 | + conv2 = Conv2D<Float>( |
| 43 | + filterShape: (1, 1, 128, stateChannels), useBias: useBias, filterInitializer: zeros()) |
| 44 | + } |
| 45 | + |
| 46 | + @differentiable |
| 47 | + func livingMask(_ input: Tensor<Float>) -> Tensor<Float> { |
| 48 | + let alphaChannel = input.slice( |
| 49 | + lowerBounds: [0, 0, 0, 3], sizes: [input.shape[0], input.shape[1], input.shape[2], 1]) |
| 50 | + let localMaximum = |
| 51 | + maxPool2D(alphaChannel, filterSize: (1, 3, 3, 1), strides: (1, 1, 1, 1), padding: .same) |
| 52 | + return withoutDerivative(at: input) { _ in localMaximum.mask { $0 .> 0.1 } } |
| 53 | + } |
| 54 | + |
| 55 | + @differentiable |
| 56 | + func perceive(_ input: Tensor<Float>) -> Tensor<Float> { |
| 57 | + return depthwiseConv2D( |
| 58 | + input, filter: perceptionFilter, strides: (1, 1, 1, 1), padding: .same) |
| 59 | + } |
| 60 | + |
| 61 | + @differentiable |
| 62 | + func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> { |
| 63 | + let perception = perceive(input) |
| 64 | + let dx = conv2(relu(conv1(perception))) |
| 65 | + |
| 66 | + let updateDistribution = Tensor<Float>( |
| 67 | + randomUniform: [input.shape[0], input.shape[1], input.shape[2], 1], on: input.device) |
| 68 | + let updateMask = withoutDerivative(at: input) { _ in |
| 69 | + updateDistribution.mask { $0 .< fireRate } |
| 70 | + } |
| 71 | + |
| 72 | + let updatedState = input + (dx * updateMask) |
| 73 | + let combinedLivingMask = livingMask(input) * livingMask(updatedState) |
| 74 | + return updatedState * combinedLivingMask |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +func normalizeGradient(_ gradient: CellRule.TangentVector) -> CellRule.TangentVector { |
| 79 | + var outputGradient = gradient |
| 80 | + for kp in gradient.recursivelyAllWritableKeyPaths(to: Tensor<Float>.self) { |
| 81 | + let norm = sqrt(gradient[keyPath: kp].squared().sum()) |
| 82 | + outputGradient[keyPath: kp] = gradient[keyPath: kp] / (norm + 1e-8) |
| 83 | + } |
| 84 | + return outputGradient |
| 85 | +} |
| 86 | + |
| 87 | +extension Tensor where Scalar: Numeric { |
| 88 | + @differentiable(where Scalar: TensorFlowFloatingPoint) |
| 89 | + var colorComponents: Tensor { |
| 90 | + precondition(self.rank == 3 || self.rank == 4) |
| 91 | + if self.rank == 3 { |
| 92 | + return self.slice( |
| 93 | + lowerBounds: [0, 0, 0], sizes: [self.shape[0], self.shape[1], 4]) |
| 94 | + } else { |
| 95 | + return self.slice( |
| 96 | + lowerBounds: [0, 0, 0, 0], sizes: [self.shape[0], self.shape[1], self.shape[2], 4]) |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + func mask(condition: (Tensor) -> Tensor<Bool>) -> Tensor { |
| 101 | + let satisfied = condition(self) |
| 102 | + return Tensor(zerosLike: self) |
| 103 | + .replacing(with: Tensor(onesLike: self), where: satisfied) |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +// Note: the following is an identity function that serves to cut the backward trace into |
| 108 | +// smaller identical traces, to improve X10 performance. |
| 109 | +@inlinable |
| 110 | +@differentiable |
| 111 | +func clipBackwardsTrace(_ input: Tensor<Float>) -> Tensor<Float> { |
| 112 | + return input |
| 113 | +} |
| 114 | + |
| 115 | +@inlinable |
| 116 | +@derivative(of: clipBackwardsTrace) |
| 117 | +func _vjpClipBackwardsTrace( |
| 118 | + _ input: Tensor<Float> |
| 119 | +) -> (value: Tensor<Float>, pullback: (Tensor<Float>) -> Tensor<Float>) { |
| 120 | + return ( |
| 121 | + input, |
| 122 | + { |
| 123 | + LazyTensorBarrier() |
| 124 | + return $0 |
| 125 | + } |
| 126 | + ) |
| 127 | +} |
0 commit comments