From 5cb05330cb2133c8c3571d69e331903a3a10a0f9 Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 11:24:13 -0400 Subject: [PATCH 01/14] Copied the apple/swift TensorFlow tests. --- .../DeepLearningTests/InitializerTests.swift | 83 +++ Tests/DeepLearningTests/LayerTests.swift | 2 +- .../OperatorTests/BasicTests.swift | 488 ++++++++++++++++++ .../OperatorTests/ComparisonTests.swift | 35 ++ .../{ => OperatorTests}/DatasetTests.swift | 4 +- .../OperatorTests/MathTests.swift | 214 ++++++++ Tests/DeepLearningTests/TensorTests.swift | 2 +- Tests/DeepLearningTests/XCTestManifests.swift | 3 + 8 files changed, 827 insertions(+), 4 deletions(-) create mode 100644 Tests/DeepLearningTests/InitializerTests.swift create mode 100644 Tests/DeepLearningTests/OperatorTests/BasicTests.swift create mode 100644 Tests/DeepLearningTests/OperatorTests/ComparisonTests.swift rename Tests/DeepLearningTests/{ => OperatorTests}/DatasetTests.swift (99%) create mode 100644 Tests/DeepLearningTests/OperatorTests/MathTests.swift diff --git a/Tests/DeepLearningTests/InitializerTests.swift b/Tests/DeepLearningTests/InitializerTests.swift new file mode 100644 index 000000000..ced975f98 --- /dev/null +++ b/Tests/DeepLearningTests/InitializerTests.swift @@ -0,0 +1,83 @@ +// Copyright 2019 The TensorFlow Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import XCTest +@testable import DeepLearning + +final class InitializerTests: XCTestCase { + func testInitializers() { + let scalar = Tensor(1) + let matrix: Tensor = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] + let broadcastScalar = Tensor(broadcasting: 10, rank: 3) + let some4d = Tensor(shape: [2, 1, 2, 1], scalars: [2, 3, 4, 5]) + XCTAssertEqual(ShapedArray(shape: [2, 1, 2, 1], scalars: [2, 3, 4, 5]), some4d.array) + XCTAssertEqual(ShapedArray(shape: [], scalars: [1]), scalar.array) + XCTAssertEqual(ShapedArray(shape: [2, 3], scalars: [1, 2, 3, 4, 5, 6]), matrix.array) + XCTAssertEqual(ShapedArray(shape: [1, 1, 1], scalars: [10]), broadcastScalar.array) + } + + func testFactoryInitializers() { + let x = Tensor(ones: [1, 10]) + XCTAssertEqual(ShapedArray(repeating: 1, shape: [1, 10]), x.array) + } + + func testNumericInitializers() { + let x = Tensor(oneHotAtIndices: [0, 2, -1, 1], depth: 3) + XCTAssertEqual(ShapedArray( + shape: [4, 3], + scalars: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]), x.array) + } + + func testScalarToTensorConversion() { + let tensor = Tensor(broadcasting: 42, rank: 4) + XCTAssertEqual([1, 1, 1, 1], tensor.shape) + XCTAssertEqual([42], tensor.scalars) + } + + func testArrayConversion() { + let array3D = ShapedArray(repeating: 1.0, shape: [2, 3, 4]) + let tensor3D = Tensor(array3D) + XCTAssertEqual(array3D, tensor3D.array) + } + + func testDataTypeCast() { + let x = Tensor(ones: [5, 5]) + let ints = Tensor(x) + let floats = Tensor(x) + let u32s = Tensor(floats) + XCTAssertEqual(ShapedArray(repeating: 1, shape: [5, 5]), ints.array) + XCTAssertEqual(ShapedArray(repeating: 1, shape: [5, 5]), floats.array) + XCTAssertEqual(ShapedArray(repeating: 1, shape: [5, 5]), u32s.array) + } + + func testBoolToNumericCast() { + let bools = Tensor(shape: [2, 2], scalars: [true, false, true, false]) + let ints = Tensor(bools) + let floats = Tensor(bools) + let i8s = Tensor(bools) + XCTAssertEqual(ShapedArray(shape: [2, 2], scalars: [1, 0, 1, 0]), ints.array) + XCTAssertEqual(ShapedArray(shape: [2, 2], scalars: [1, 0, 1, 0]), floats.array) + XCTAssertEqual(ShapedArray(shape: [2, 2], scalars: [1, 0, 1, 0]), i8s.array) + } + + static var allTests = [ + ("testInitializers", testInitializers), + ("testFactoryInitializers", testFactoryInitializers), + ("testNumericInitializers", testNumericInitializers), + ("testScalarToTensorConversion", testScalarToTensorConversion), + ("testArrayConversion", testArrayConversion), + ("testDataTypeCast", testDataTypeCast), + ("testBoolToNumericCast", testBoolToNumericCast) + ] +} diff --git a/Tests/DeepLearningTests/LayerTests.swift b/Tests/DeepLearningTests/LayerTests.swift index ca57ec304..77ab1cdb7 100644 --- a/Tests/DeepLearningTests/LayerTests.swift +++ b/Tests/DeepLearningTests/LayerTests.swift @@ -199,7 +199,7 @@ final class LayerTests: XCTestCase { [[ 0.066890605, 0.049586136, 0.024610005, 0.09341654]], [[ 0.065792546, 0.009325638, 0.06439907, 0.114802904]], [[ 0.055909205, 0.00035158166, 0.054020774, 0.09812111]]]) - let (𝛁rnn, 𝛁inputs) = pullback(.init(inputs.map { SimpleRNNCell.State($0) })) + let (𝛁rnn, _) = pullback(.init(inputs.map { SimpleRNNCell.State($0) })) XCTAssertEqual(𝛁rnn.cell.weight, [[ 0.0, 0.0, 0.0, 0.0], [-0.0051169936, 0.0014167001, 0.0074189613, 0.017496519], diff --git a/Tests/DeepLearningTests/OperatorTests/BasicTests.swift b/Tests/DeepLearningTests/OperatorTests/BasicTests.swift new file mode 100644 index 000000000..9b17c9ac4 --- /dev/null +++ b/Tests/DeepLearningTests/OperatorTests/BasicTests.swift @@ -0,0 +1,488 @@ +// Copyright 2019 The TensorFlow Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import XCTest +@testable import DeepLearning + +infix operator ++: AdditionPrecedence +infix operator .= + +infix operator ..: StridedRangeFormationPrecedence +precedencegroup StridedRangeFormationPrecedence { + associativity: left + higherThan: CastingPrecedence + lowerThan: RangeFormationPrecedence +} + +final class BasicOperatorTests: XCTestCase { + func testElementIndexing() { + // NOTE: cannot test multiple `Tensor.shape` or `Tensor.scalars` directly + // until send and receive are implemented (without writing a bunch of mini + // tests). Instead, `Tensor.array` is called to make a ShapedArray host copy + // and the ShapedArray is tested. + let tensor3D = Tensor( + shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1))) + let element2D = tensor3D[2] + let element1D = tensor3D[1][3] + let element0D = tensor3D[2][0][3] + + let array2D = element2D.array + let array1D = element1D.array + let array0D = element0D.array + + /// Test shapes + XCTAssertEqual([4, 5], array2D.shape) + XCTAssertEqual([5], array1D.shape) + XCTAssertEqual([], array0D.shape) + + /// Test scalars + XCTAssertEqual(Array(stride(from: 40.0, to: 60, by: 1)), array2D.scalars) + XCTAssertEqual(Array(stride(from: 35.0, to: 40, by: 1)), array1D.scalars) + XCTAssertEqual([43], array0D.scalars) + } + + func testElementIndexingAssignment() { + // NOTE: cannot test multiple `Tensor.shape` or `Tensor.scalars` directly + // until send and receive are implemented (without writing a bunch of mini + // tests). Instead, `Tensor.array` is called to make a ShapedArray host copy + // and the ShapedArray is tested. + var tensor3D = Tensor( + shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1))) + tensor3D[2] = Tensor( + shape: [4, 5], scalars: Array(stride(from: 20.0, to: 40, by: 1))) + let element2D = tensor3D[2] + let element1D = tensor3D[1][3] + let element0D = tensor3D[2][0][3] + + let array2D = element2D.array + let array1D = element1D.array + let array0D = element0D.array + + /// Test shapes + XCTAssertEqual([4, 5], array2D.shape) + XCTAssertEqual([5], array1D.shape) + XCTAssertEqual([], array0D.shape) + + /// Test scalars + XCTAssertEqual(Array(stride(from: 20.0, to: 40, by: 1)), array2D.scalars) + XCTAssertEqual(Array(stride(from: 35.0, to: 40, by: 1)), array1D.scalars) + XCTAssertEqual([23], array0D.scalars) + } + + func testNestedElementIndexing() { + // NOTE: This test could use a clearer name, along with other "indexing" + // tests. Note to update corresponding test names in other files + // (shaped_array.test) as well. + let tensor3D = Tensor( + shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1))) + let element1D = tensor3D[1, 3] + let element0D = tensor3D[2, 0, 3] + + let array1D = element1D.array + let array0D = element0D.array + + /// Test shapes + XCTAssertEqual([5], array1D.shape) + XCTAssertEqual([], array0D.shape) + + /// Test scalars + XCTAssertEqual(Array(stride(from: 35.0, to: 40, by: 1)), array1D.scalars) + XCTAssertEqual([43], array0D.scalars) + } + + func testSliceIndexing() { + // NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send + // and receive are implemented (without writing a bunch of mini tests). + // Instead, `Tensor.array` is called to make a ShapedArray host copy and the + // ShapedArray is tested instead. + let tensor3D = Tensor( + shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1))) + let slice3D = tensor3D[2...] + let slice2D = tensor3D[1][0..<2] + let slice1D = tensor3D[0][0][3..<5] + + let array3D = slice3D.array + let array2D = slice2D.array + let array1D = slice1D.array + + /// Test shapes + XCTAssertEqual([1, 4, 5], array3D.shape) + XCTAssertEqual([2, 5], array2D.shape) + XCTAssertEqual([2], array1D.shape) + + /// Test scalars + XCTAssertEqual(Array(stride(from: 40.0, to: 60, by: 1)), array3D.scalars) + XCTAssertEqual(Array(stride(from: 20.0, to: 30, by: 1)), array2D.scalars) + XCTAssertEqual(Array(stride(from: 3.0, to: 5, by: 1)), array1D.scalars) + } + + func testSliceIndexingAssignment() { + // NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send + // and receive are implemented (without writing a bunch of mini tests). + // Instead, `Tensor.array` is called to make a ShapedArray host copy and the + // ShapedArray is tested instead. + var tensor3D = Tensor( + shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1))) + tensor3D[2, 0..<5, 0..<6] = Tensor( + shape: [4, 5], scalars: Array(stride(from: 20.0, to: 40, by: 1))) + let slice3D = tensor3D[2...] + let slice2D = tensor3D[1][0..<2] + let slice1D = tensor3D[0][0][3..<5] + + let array3D = slice3D.array + let array2D = slice2D.array + let array1D = slice1D.array + + /// Test shapes + XCTAssertEqual([1, 4, 5], array3D.shape) + XCTAssertEqual([2, 5], array2D.shape) + XCTAssertEqual([2], array1D.shape) + + /// Test scalars + XCTAssertEqual(Array(stride(from: 20.0, to: 40, by: 1)), array3D.scalars) + XCTAssertEqual(Array(stride(from: 20.0, to: 30, by: 1)), array2D.scalars) + XCTAssertEqual(Array(stride(from: 3.0, to: 5, by: 1)), array1D.scalars) + } + + func testEllipsisIndexing() { + // NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send + // and receive are implemented (without writing a bunch of mini tests). + // Instead, `Tensor.array` is called to make a ShapedArray host copy and the + // ShapedArray is tested instead. + var tensor3D = Tensor( + shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1))) + tensor3D[2, TensorRange.ellipsis] = Tensor( + shape: [4, 5], scalars: Array(stride(from: 20.0, to: 40, by: 1))) + let slice3D = tensor3D[2..., TensorRange.ellipsis] + let slice2D = tensor3D[1][0..<2] + let slice1D = tensor3D[0][0][3..<5] + + let array3D = slice3D.array + let array2D = slice2D.array + let array1D = slice1D.array + + /// Test shapes + XCTAssertEqual([1, 4, 5], array3D.shape) + XCTAssertEqual([2, 5], array2D.shape) + XCTAssertEqual([2], array1D.shape) + + /// Test scalars + XCTAssertEqual(Array(stride(from: 20.0, to: 40, by: 1)), array3D.scalars) + XCTAssertEqual(Array(stride(from: 20.0, to: 30, by: 1)), array2D.scalars) + XCTAssertEqual(Array(stride(from: 3.0, to: 5, by: 1)), array1D.scalars) + } + + func testNewAxisIndexing() { + // NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send + // and receive are implemented (without writing a bunch of mini tests). + // Instead, `Tensor.array` is called to make a ShapedArray host copy and the + // ShapedArray is tested instead. + let tensor3D = Tensor( + shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1))) + let newAxis = TensorRange.newAxis + let ellipsis = TensorRange.ellipsis + let slice3D = tensor3D[2..., newAxis, ellipsis] + let slice2D = tensor3D[1, newAxis][0..<1, 0..<2] + let slice1D = tensor3D[0][newAxis, 0][0..<1, 3..<5, newAxis] + + let array3D = slice3D.array + let array2D = slice2D.array + let array1D = slice1D.array + + /// Test shapes + XCTAssertEqual([1, 1, 4, 5], array3D.shape) + XCTAssertEqual([1, 2, 5], array2D.shape) + XCTAssertEqual([1, 2, 1], array1D.shape) + + /// Test scalars + XCTAssertEqual(Array(stride(from: 40.0, to: 60, by: 1)), array3D.scalars) + XCTAssertEqual(Array(stride(from: 20.0, to: 30, by: 1)), array2D.scalars) + XCTAssertEqual(Array(stride(from: 3.0, to: 5, by: 1)), array1D.scalars) + } + + func testSqueezeAxisIndexing() { + // NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send + // and receive are implemented (without writing a bunch of mini tests). + // Instead, `Tensor.array` is called to make a ShapedArray host copy and the + // ShapedArray is tested instead. + let tensor3D = Tensor( + shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1))) + let newAxis = TensorRange.newAxis + let ellipsis = TensorRange.ellipsis + let squeezeAxis = TensorRange.squeezeAxis + let slice3D = tensor3D[2..., newAxis, ellipsis][squeezeAxis, squeezeAxis] + let slice2D = tensor3D[1, newAxis][squeezeAxis, 0..<2] + let slice1D = tensor3D[0..<1, 0, 3..<5, newAxis][ + squeezeAxis, ellipsis, squeezeAxis] + + let array3D = slice3D.array + let array2D = slice2D.array + let array1D = slice1D.array + + /// Test shapes + XCTAssertEqual([4, 5], array3D.shape) + XCTAssertEqual([2, 5], array2D.shape) + XCTAssertEqual([2], array1D.shape) + + /// Test scalars + XCTAssertEqual(Array(stride(from: 40.0, to: 60, by: 1)), array3D.scalars) + XCTAssertEqual(Array(stride(from: 20.0, to: 30, by: 1)), array2D.scalars) + XCTAssertEqual(Array(stride(from: 3.0, to: 5, by: 1)), array1D.scalars) + } + + func testStridedSliceIndexing() { + // NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send + // and receive are implemented (without writing a bunch of mini tests). + // Instead, `Tensor.array` is called to make a ShapedArray host copy and the + // ShapedArray is tested instead. + let tensor3D = Tensor( + shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1))) + let slice3D = tensor3D[2...] + let slice2D = tensor3D[1][0..<3..2] + let slice1D = tensor3D[0][0][1..<5..2] + + let array3D = slice3D.array + let array2D = slice2D.array + let array1D = slice1D.array + + /// Test shapes + XCTAssertEqual([1, 4, 5], array3D.shape) + XCTAssertEqual([2, 5], array2D.shape) + XCTAssertEqual([2], array1D.shape) + + /// Test scalars + XCTAssertEqual(Array(stride(from: 40.0, to: 60, by: 1)), array3D.scalars) + XCTAssertEqual( + Array(stride(from: 20.0, to: 25, by: 1)) + + Array(stride(from: 30.0, to: 35, by: 1)), array2D.scalars) + XCTAssertEqual(Array(stride(from: 1.0, to: 5, by: 2)), array1D.scalars) + } + + func testStridedSliceIndexingAssignment() { + // NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send + // and receive are implemented (without writing a bunch of mini tests). + // Instead, `Tensor.array` is called to make a ShapedArray host copy and the + // ShapedArray is tested instead. + var tensor3D = Tensor( + shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1))) + tensor3D[2, 0..<5..2, 0..<6] = Tensor( + shape: [2, 5], scalars: Array(stride(from: 20.0, to: 40, by: 2))) + let slice3D = tensor3D[2...] + let slice2D = tensor3D[1][0..<2] + let slice1D = tensor3D[0][0][3..<5] + + let array3D = slice3D.array + let array2D = slice2D.array + let array1D = slice1D.array + + /// Test shapes + XCTAssertEqual([1, 4, 5], array3D.shape) + XCTAssertEqual([2, 5], array2D.shape) + XCTAssertEqual([2], array1D.shape) + + /// Test scalars + XCTAssertEqual( + Array(stride(from: 20.0, to: 30, by: 2)) + + Array(stride(from: 45.0, to: 50, by: 1)) + + Array(stride(from: 30.0, to: 40, by: 2)) + + Array(stride(from: 55.0, to: 60, by: 1)), array3D.scalars) + XCTAssertEqual(Array(stride(from: 20.0, to: 30, by: 1)), array2D.scalars) + XCTAssertEqual(Array(stride(from: 3.0, to: 5, by: 1)), array1D.scalars) + } + + func testWholeTensorSlicing() { + let t: Tensor = [[[1, 1, 1], [2, 2, 2]], + [[3, 3, 3], [4, 4, 4]], + [[5, 5, 5], [6, 6, 6]]] + let slice2 = t.slice(lowerBounds: [1, 0, 0], upperBounds: [2, 1, 3]) + XCTAssertEqual(ShapedArray(shape: [1, 1, 3], scalars: [3, 3, 3]), slice2.array) + } + + func testAdvancedIndexing() { + // NOTE: cannot test multiple `Tensor.shape` or `Tensor.scalars` directly + // until send and receive are implemented (without writing a bunch of mini + // tests). Instead, `Tensor.array` is called to make a ShapedArray host copy + // and the ShapedArray is tested. + let tensor3D = Tensor( + shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1))) + let element2D = tensor3D[1..<3, 0, 3...] + let array2D = element2D.array + + // Test shape + XCTAssertEqual([2, 2], array2D.shape) + + // Test scalars + XCTAssertEqual(Array([23.0, 24.0, 43.0, 44.0]), array2D.scalars) + } + + func testConcatenation() { + // 2 x 3 + let t1 = Tensor([[0, 1, 2], [3, 4, 5]]) + // 2 x 3 + let t2 = Tensor([[6, 7, 8], [9, 10, 11]]) + let concatenated = t1 ++ t2 + let concatenated0 = t1.concatenated(with: t2) + let concatenated1 = t1.concatenated(with: t2, alongAxis: 1) + XCTAssertEqual(ShapedArray(shape: [4, 3], scalars: Array(0..<12)), concatenated.array) + XCTAssertEqual(ShapedArray(shape: [4, 3], scalars: Array(0..<12)), concatenated0.array) + XCTAssertEqual( + ShapedArray(shape: [2, 6], scalars: [0, 1, 2, 6, 7, 8, 3, 4, 5, 9, 10, 11]), + concatenated1.array) + } + + func testVJPConcatenation() { + let a1 = Tensor([1,2,3,4]) + let b1 = Tensor([5,6,7,8,9,10]) + + let a2 = Tensor([1,1,1,1]) + let b2 = Tensor([1,1,1,1,1,1]) + + let grads = gradient(at: a2, b2) { a, b in + return ((a1 * a) ++ (b1 * b)).sum() + } + + XCTAssertEqual(a1, grads.0) + XCTAssertEqual(b1, grads.1) + } + + func testVJPConcatenationNegativeAxis() { + let a1 = Tensor([1,2,3,4]) + let b1 = Tensor([5,6,7,8,9,10]) + + let a2 = Tensor([1,1,1,1]) + let b2 = Tensor([1,1,1,1,1,1]) + + let grads = gradient(at: a2, b2) { a, b in + return (a1 * a).concatenated(with: b1 * b, alongAxis: -1).sum() + } + + XCTAssertEqual(a1, grads.0) + XCTAssertEqual(b1, grads.1) + } + + func testTranspose() { + // 3 x 2 -> 2 x 3 + let xT = Tensor([[1, 2], [3, 4], [5, 6]]).transposed() + let xTArray = xT.array + XCTAssertEqual(2, xTArray.rank) + XCTAssertEqual([2, 3], xTArray.shape) + XCTAssertEqual([1, 3, 5, 2, 4, 6], xTArray.scalars) + } + + func testReshape() { + // 2 x 3 -> 1 x 3 x 1 x 2 x 1 + let matrix = Tensor([[0, 1, 2], [3, 4, 5]]) + let reshaped = matrix.reshaped(to: [1, 3, 1, 2, 1]) + + XCTAssertEqual([1, 3, 1, 2, 1], reshaped.shape) + XCTAssertEqual(Array(0..<6), reshaped.scalars) + } + + func testFlatten() { + // 2 x 3 -> 6 + let matrix = Tensor([[0, 1, 2], [3, 4, 5]]) + let flattened = matrix.flattened() + + XCTAssertEqual([6], flattened.shape) + XCTAssertEqual(Array(0..<6), flattened.scalars) + } + + func testFlatten0D() { + let scalar = Tensor(5) + let flattened = scalar.flattened() + XCTAssertEqual([1], flattened.shape) + XCTAssertEqual([5], flattened.scalars) + } + + func testReshapeToScalar() { + // 1 x 1 -> scalar + let z = Tensor([[10]]).reshaped(to: []) + XCTAssertEqual([], z.shape) + } + + func testReshapeTensor() { + // 2 x 3 -> 1 x 3 x 1 x 2 x 1 + let x = Tensor(repeating: 0.0, shape: [2, 3]) + let y = Tensor(repeating: 0.0, shape: [1, 3, 1, 2, 1]) + let result = x.reshaped(like: y) + XCTAssertEqual([1, 3, 1, 2, 1], result.shape) + } + + func testUnbroadcasted1() { + let x = Tensor(repeating: 1, shape: [2, 3, 4, 5]) + let y = Tensor(repeating: 1, shape: [4, 5]) + let z = x.unbroadcasted(like: y) + XCTAssertEqual(ShapedArray(repeating: 6, shape: [4, 5]), z.array) + } + + func testUnbroadcasted2() { + let x = Tensor(repeating: 1, shape: [2, 3, 4, 5]) + let y = Tensor(repeating: 1, shape: [3, 1, 5]) + let z = x.unbroadcasted(like: y) + XCTAssertEqual(ShapedArray(repeating: 8, shape: [3, 1, 5]), z.array) + } + + func testSliceUpdate() { + var t1 = Tensor([[1, 2, 3], [4, 5, 6]]) + t1[0] = Tensor(zeros: [3]) + XCTAssertEqual(ShapedArray(shape:[2, 3], scalars: [0, 0, 0, 4, 5, 6]), t1.array) + var t2 = t1 + t2[0][2] = Tensor(3) + XCTAssertEqual(ShapedArray(shape:[2, 3], scalars: [0, 0, 3, 4, 5, 6]), t2.array) + var t3 = Tensor([[true, true, true], [false, false, false]]) + t3[0][1] = Tensor(false) + XCTAssertEqual(ShapedArray( + shape:[2, 3], scalars: [true, false, true, false, false, false]), t3.array) + var t4 = Tensor([[true, true, true], [false, false, false]]) + t4[0] = Tensor(repeating: false, shape: [3]) + XCTAssertEqual(ShapedArray(repeating: false, shape: [2, 3]), t4.array) + } + + func testBroadcastTensor() { + // 1 -> 2 x 3 x 4 + let one = Tensor(1) + var target = Tensor(repeating: 0.0, shape: [2, 3, 4]) + let broadcasted = one.broadcasted(like: target) + XCTAssertEqual(Tensor(repeating: 1, shape: [2, 3, 4]), broadcasted) + target .= Tensor(repeating: 1, shape: [1, 3, 1]) + XCTAssertEqual(Tensor(repeating: 1, shape: [2, 3, 4]), target) + } + + static var allTests = [ + ("testElementIndexing", testElementIndexing), + ("testElementIndexingAssignment", testElementIndexingAssignment), + ("testNestedElementIndexing", testNestedElementIndexing), + ("testSliceIndexing", testSliceIndexing), + ("testSliceIndexingAssignment", testSliceIndexingAssignment), + ("testEllipsisIndexing", testEllipsisIndexing), + ("testNewAxisIndexing", testNewAxisIndexing), + ("testSqueezeAxisIndexing", testSqueezeAxisIndexing), + ("testStridedSliceIndexing", testStridedSliceIndexing), + ("testStridedSliceIndexingAssignment", testStridedSliceIndexingAssignment), + ("testWholeTensorSlicing", testWholeTensorSlicing), + ("testAdvancedIndexing", testAdvancedIndexing), + ("testConcatenation", testConcatenation), + ("testVJPConcatenation", testVJPConcatenation), + ("testTranspose", testTranspose), + ("testReshape", testReshape), + ("testFlatten", testFlatten), + ("testFlatten0D", testFlatten0D), + ("testReshapeToScalar", testReshapeToScalar), + ("testReshapeTensor", testReshapeTensor), + ("testUnbroadcasted1", testUnbroadcasted1), + ("testUnbroadcasted2", testUnbroadcasted2), + ("testSliceUpdate", testSliceUpdate), + ("testBroadcastTensor", testBroadcastTensor) + ] +} diff --git a/Tests/DeepLearningTests/OperatorTests/ComparisonTests.swift b/Tests/DeepLearningTests/OperatorTests/ComparisonTests.swift new file mode 100644 index 000000000..e20a9cdc9 --- /dev/null +++ b/Tests/DeepLearningTests/OperatorTests/ComparisonTests.swift @@ -0,0 +1,35 @@ +// Copyright 2019 The TensorFlow Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import XCTest +@testable import DeepLearning + +final class ComparisonOperatorTests: XCTestCase { + func testElementwiseComparison() { + let x = Tensor([0, 1, 2]) + let y = Tensor([2, 1, 3]) + XCTAssertEqual((x .< y).scalars, [true, false, true]) + } + + func testLexicographicalComparison() { + let x = Tensor([0, 1, 2, 3, 4]) + let y = Tensor([2, 3, 4, 5, 6]) + XCTAssertTrue(x < y) + } + + static var allTests = [ + ("testElementwiseComparison", testElementwiseComparison), + ("testLexicographicalComparison", testLexicographicalComparison) + ] +} diff --git a/Tests/DeepLearningTests/DatasetTests.swift b/Tests/DeepLearningTests/OperatorTests/DatasetTests.swift similarity index 99% rename from Tests/DeepLearningTests/DatasetTests.swift rename to Tests/DeepLearningTests/OperatorTests/DatasetTests.swift index 1c58fb5c6..54f413e50 100644 --- a/Tests/DeepLearningTests/DatasetTests.swift +++ b/Tests/DeepLearningTests/OperatorTests/DatasetTests.swift @@ -13,9 +13,9 @@ // limitations under the License. import XCTest -import DeepLearning +@testable import DeepLearning -struct SimpleOutput : TensorGroup { +struct SimpleOutput: TensorGroup { let a: TensorHandle let b: TensorHandle } diff --git a/Tests/DeepLearningTests/OperatorTests/MathTests.swift b/Tests/DeepLearningTests/OperatorTests/MathTests.swift new file mode 100644 index 000000000..0db5406ed --- /dev/null +++ b/Tests/DeepLearningTests/OperatorTests/MathTests.swift @@ -0,0 +1,214 @@ +// Copyright 2019 The TensorFlow Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import XCTest +@testable import DeepLearning + +final class MathOperatorTests: XCTestCase { + func testReduction() { + // 2 x 5 + let x = Tensor([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]) + XCTAssertEqual(Tensor(30), x.sum()) + XCTAssertEqual( + Tensor(shape: [5], scalars: [2, 4, 6, 8, 10]), + x.sum(squeezingAxes: 0)) + XCTAssertEqual( + Tensor(shape: [1, 5], scalars: [2, 4, 6, 8, 10]), + x.sum(alongAxes: 0)) + + XCTAssertEqual(Tensor(14400), x.product()) + XCTAssertEqual( + Tensor(shape: [5], scalars: [1, 4, 9, 16, 25]), + x.product(squeezingAxes: 0)) + XCTAssertEqual( + Tensor(shape: [1, 5], scalars: [1, 4, 9, 16, 25]), + x.product(alongAxes: 0)) + + XCTAssertEqual(Tensor(3), x.mean()) + XCTAssertEqual( + Tensor(shape: [5], scalars: [1, 2, 3, 4, 5]), + x.mean(squeezingAxes: 0)) + XCTAssertEqual( + Tensor(shape: [5], scalars: [1, 2, 3, 4, 5]), + x.mean(alongAxes: 0)) + XCTAssertEqual( + Tensor(shape: [2], scalars: [3, 3]), + x.mean(squeezingAxes: 1)) + XCTAssertEqual( + Tensor(shape: [1, 2], scalars: [3, 3]), + x.mean(alongAxes: 1)) + + XCTAssertEqual(Tensor(2), x.variance()) + XCTAssertEqual( + Tensor(shape: [5], scalars: [0, 0, 0, 0, 0]), + x.variance(squeezingAxes: 0)) + XCTAssertEqual( + Tensor(shape: [5], scalars: [0, 0, 0, 0, 0]), + x.variance(alongAxes: 0)) + XCTAssertEqual( + Tensor(shape: [2], scalars: [2, 2]), + x.variance(squeezingAxes: 1)) + XCTAssertEqual( + Tensor(shape: [1, 2], scalars: [2, 2]), + x.variance(alongAxes: 1)) + } + + func testArgmax() { + // 2 x 3 + let x = Tensor([[0, 1, 2], [3, 4, 5]]) + let argmax0 = x.argmax(squeezingAxis: 0) + let argmax1 = x.argmax(squeezingAxis: 1) + let scalarsArgmax = x.argmax() + XCTAssertEqual(ShapedArray(shape: [3], scalars: [1, 1, 1]), argmax0.array) + XCTAssertEqual(ShapedArray(shape: [2], scalars: [2, 2]), argmax1.array) + XCTAssertEqual(ShapedArray(shape: [], scalars: [5]), scalarsArgmax.array) + } + + func testCeilAndFloor() { + let x = Tensor([-1.3, -0.4, 0.5, 1.6]) + let xFloor = floor(x) + let xCeil = ceil(x) + XCTAssertEqual(ShapedArray(shape: [4], scalars: [-2, -1, 0, 1]), xFloor.array) + XCTAssertEqual(ShapedArray(shape: [4], scalars: [-1, 0, 1, 2]), xCeil.array) + } + + func testSimpleMath() { + let x = Tensor([1.2, 1.2]) + let y = tanh(x) + let array = y.array + XCTAssertEqual([2], array.shape) + XCTAssertEqual(0.833655, Double(array.scalars[0])) + XCTAssertEqual(0.833655, Double(array.scalars[1])) + } + + func testStandardDeviation() { + XCTAssertEqual(Tensor(0), Tensor([1]).standardDeviation()) + XCTAssertEqual(Tensor(0.5), Tensor([0, 1]).standardDeviation(alongAxes: 0)) + XCTAssertEqual(Tensor(0.5), Tensor([0, 1]).standardDeviation()) + XCTAssertEqual( + 2.87228132, + Tensor(rangeFrom: 0, to: 10, stride: 1).standardDeviation().scalarized(), + accuracy: 0.001) + let matrix = Tensor(rangeFrom: 0, to: 10, stride: 1).reshaped(to: [2, 5]) + XCTAssertEqual(2.87228132, matrix.standardDeviation().scalarized(), accuracy: 0.001) + let values = matrix.standardDeviation(alongAxes: 1).array.scalars + XCTAssertEqual(1.4142, Double(values[0]), accuracy: 0.0001) + XCTAssertEqual(1.4142, Double(values[1]), accuracy: 0.0001) + } + + func test3Adds() { + let a = Tensor([1]) + let b = Tensor([2]) + let c = Tensor([3]) + + let o = a + b + c + XCTAssertEqual([6], o.scalars) + } + + func testMultiOpMath() { + let x = Tensor([1.2, 1.2]) + let y = Tensor([2.4, 2.4]) + let t1 = x + y + let t2 = t1 * t1 + let t3 = sqrt(t2) + + let array1 = t1.array + let array2 = t2.array + let array3 = t3.array + XCTAssertEqual([2], array1.shape) + XCTAssertEqual([2], array2.shape) + XCTAssertEqual([2], array3.shape) + XCTAssertEqual(3.6, Double(array1.scalars[0]), accuracy: 0.0001) + XCTAssertEqual(3.6, Double(array1.scalars[1]), accuracy: 0.0001) + XCTAssertEqual(12.96, Double(array2.scalars[0]), accuracy: 0.0001) + XCTAssertEqual(12.96, Double(array2.scalars[1]), accuracy: 0.0001) + XCTAssertEqual(3.6, Double(array3.scalars[0]), accuracy: 0.0001) + XCTAssertEqual(3.6, Double(array3.scalars[1]), accuracy: 0.0001) + } + + func testXWPlusB() { + // Shape: 1 x 4 + let x = Tensor([[1.0, 2.0, 2.0, 1.0]]) + // Shape: 4 x 2 + let w = Tensor([[1.0, 0.0], [3.0, 0.0], [2.0, 3.0], [1.0, 0.0]]) + // Shape: 2 + let b = Tensor([0.5, 0.5]) + // Shape: 1 x 2 (broadcasted) + let result = matmul(x, w) + b + XCTAssertEqual([1, 2], result.shape) + XCTAssertEqual([12.5, 6.5], result.scalars) + } + + func testXORInference() { + func xor(_ x: Float, _ y: Float) -> Float { + let x = Tensor([x, y]).reshaped(to: [1, 2]) + + // FIXME: If params are declared outside of `xor`, it would crash. + // 2 x 4 + let w1 = Tensor( + [[-1.83586664, -0.20809225, 0.47667537, 1.90780607], + [-1.83523219, -0.51167348, 0.15490439, 1.91018065]]) + // 1 x 4 + let b1 = Tensor([[2.54353216, 0.25132703, -0.16503136, -0.85754058]]) + // 4 x 1 + let w2 = Tensor([[3.04350065], [0.35590511], [-0.3252157], [3.49349223]]) + // 1 x 1 + let b2 = Tensor([[-0.74635993]]) + + let o1 = tanh(matmul(x, w1) + b1) + let y = tanh(matmul(o1, w2) + b2) + return y.array.scalars[0] // TODO: use better scalar getter + } + + XCTAssertEqual(0.0, xor(0.0, 0.0), accuracy: 0.1) + XCTAssertEqual(1.0, xor(0.0, 1.0), accuracy: 0.1) + XCTAssertEqual(1.0, xor(1.0, 0.0), accuracy: 0.1) + XCTAssertEqual(0.0, xor(1.0, 1.0), accuracy: 0.1) + } + + func testMLPClassifierStruct() { + struct MLPClassifier { + // 2 x 4 + var w1 = Tensor([[1.0, 0.8, 0.4, 0.4], + [0.4, 0.3, 0.2, 0.1]]) + // 4 x 1 + var w2 = Tensor([[0.4], [0.4], [0.3], [0.9]]) + var b1 = Tensor(zeros: [1, 4]) + var b2 = Tensor(zeros: [1, 1]) + + func prediction(for x: Tensor) -> Tensor { + let o1 = tanh(matmul(x, w1) + b1) + return tanh(matmul(o1, w2) + b2) + } + } + + let input = Tensor([[1, 0.5]]) + let classifier = MLPClassifier() + let prediction = classifier.prediction(for: input) + XCTAssertEqual(0.816997, Double(prediction.scalars[0]), accuracy: 0.0001) + } + + static var allTests = [ + ("testReduction", testReduction), + ("testArgmax", testArgmax), + ("testCeilAndFloor", testCeilAndFloor), + ("testSimpleMath", testSimpleMath), + ("testStandardDeviation", testStandardDeviation), + ("test3Adds", test3Adds), + ("testMultiOpMath", testMultiOpMath), + ("testXWPlusB", testXWPlusB), + ("testXORInference", testXORInference), + ("testMLPClassifierStruct", testMLPClassifierStruct) + ] +} diff --git a/Tests/DeepLearningTests/TensorTests.swift b/Tests/DeepLearningTests/TensorTests.swift index 015254875..03218f995 100644 --- a/Tests/DeepLearningTests/TensorTests.swift +++ b/Tests/DeepLearningTests/TensorTests.swift @@ -13,7 +13,7 @@ // limitations under the License. import XCTest -import TensorFlow +@testable import DeepLearning final class TensorTests: XCTestCase { func testSimpleCond() { diff --git a/Tests/DeepLearningTests/XCTestManifests.swift b/Tests/DeepLearningTests/XCTestManifests.swift index 9f30a652e..d068f03df 100644 --- a/Tests/DeepLearningTests/XCTestManifests.swift +++ b/Tests/DeepLearningTests/XCTestManifests.swift @@ -23,7 +23,10 @@ public func allTests() -> [XCTestCaseEntry] { testCase(SequentialTests.allTests), testCase(LayerTests.allTests), testCase(TensorTests.allTests), + testCase(BasicOperatorTests.allTests), + testCase(ComparisonOperatorTests.allTests), testCase(DatasetTests.allTests), + testCase(MathOperatorTests.allTests), ] } #endif From 09adac37f926a9566a0e92e59cd491e01ea744bf Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 11:26:51 -0400 Subject: [PATCH 02/14] Added a script that clones the TF bindings. --- .gitignore | 4 ++++ clone_tensorflow_bindings.sh | 3 +++ 2 files changed, 7 insertions(+) create mode 100644 clone_tensorflow_bindings.sh diff --git a/.gitignore b/.gitignore index c719a53ee..f68ac894b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,7 @@ xcuserdata DerivedData/ *.xcodeproj *~ +Sources/TensorFlow/Bindings + +### MacOS ### +.DS_Store diff --git a/clone_tensorflow_bindings.sh b/clone_tensorflow_bindings.sh new file mode 100644 index 000000000..2037a386f --- /dev/null +++ b/clone_tensorflow_bindings.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +git clone git@github.com:tensorflow/swift-bindings.git Sources/DeepLearning/Bindings From 987be169377775c0dec066615f5575a822ecdabe Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 15:58:39 -0400 Subject: [PATCH 03/14] Added the bindings sources. --- .gitignore | 1 - .../Bindings/EagerExecution.swift | 557 + .../Bindings/EagerExecution.swift.gyb | 318 + Sources/DeepLearning/Bindings/README.md | 27 + .../Bindings/RawOpsGenerated.swift | 37640 ++++++++++++++++ .../Bindings/TFTensorOperation.swift | 137 + .../Bindings/generate_wrappers.py | 717 + clone_tensorflow_bindings.sh | 3 - 8 files changed, 39396 insertions(+), 4 deletions(-) create mode 100644 Sources/DeepLearning/Bindings/EagerExecution.swift create mode 100644 Sources/DeepLearning/Bindings/EagerExecution.swift.gyb create mode 100644 Sources/DeepLearning/Bindings/README.md create mode 100644 Sources/DeepLearning/Bindings/RawOpsGenerated.swift create mode 100644 Sources/DeepLearning/Bindings/TFTensorOperation.swift create mode 100644 Sources/DeepLearning/Bindings/generate_wrappers.py delete mode 100644 clone_tensorflow_bindings.sh diff --git a/.gitignore b/.gitignore index f68ac894b..567f66548 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,6 @@ xcuserdata DerivedData/ *.xcodeproj *~ -Sources/TensorFlow/Bindings ### MacOS ### .DS_Store diff --git a/Sources/DeepLearning/Bindings/EagerExecution.swift b/Sources/DeepLearning/Bindings/EagerExecution.swift new file mode 100644 index 000000000..ba1bf75ce --- /dev/null +++ b/Sources/DeepLearning/Bindings/EagerExecution.swift @@ -0,0 +1,557 @@ +// !!! THIS CODE IS AUTOMATICALLY GENERATED, DO NOT EDIT BY HAND !!! +// +// Copyright 2018-19 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CTensorFlow + +/// **WARNING:** After constructing a `TFE_Op`, any one of its `execute` methods must be called +/// *exactly once*. If not called, then a memory leak is introduced due to the underlying TensorFlow +/// eager op object not being freed. If called more than once, then a SEGFAULT may occur due to +/// trying to execute a TensorFlow eager op that has already been freed. +@usableFromInline +internal struct TFE_Op : TFTensorOperation { + @usableFromInline internal let status: CTFStatus + @usableFromInline internal let op: CTFEOp + @usableFromInline internal let outputCount: Int + + @usableFromInline + internal init(_ name: String, _ outputCount: Int) { + self.status = TF_NewStatus() + self.op = TFE_NewOp(_ExecutionContext.global.eagerContext, name, status) + self.outputCount = outputCount + } + + @inlinable @inline(__always) + internal func addInput(_ input: _AnyTensorHandle) { + TFE_OpAddInput(op, input._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: Tensor) { + TFE_OpAddInput(op, input.handle._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: StringTensor) { + TFE_OpAddInput(op, input.handle._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: ResourceHandle) { + TFE_OpAddInput(op, input._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: VariantHandle) { + TFE_OpAddInput(op, input._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInputList(_ input: T) { + let count = input._tensorHandleCount + var buffer = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) + defer { buffer.deallocate() } + let pointer = UnsafeMutablePointer(buffer.baseAddress) + input._unpackTensorHandles(into: buffer.baseAddress) + TFE_OpAddInputList(op, pointer, count, status) + // TODO: checkOk(status) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Bool) { + TFE_OpSetAttrBool(op, name, value ? 1 : 0) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Int) { + TFE_OpSetAttrInt(op, name, Int64(value)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Int32) { + TFE_OpSetAttrInt(op, name, Int64(value)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Int64) { + TFE_OpSetAttrInt(op, name, value) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Float) { + TFE_OpSetAttrFloat(op, name, value) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Double) { + TFE_OpSetAttrFloat(op, name, Float(value)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: String) { + value.utf8CString.withUnsafeBufferPointer { buffer in + // utf8CString is null-terminated; TFE_OpSetAttrString wants + // non-null-terminated. + TFE_OpSetAttrString(op, name, buffer.baseAddress, buffer.count - 1) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: TensorDataType) { + TFE_OpSetAttrType(op, name, value._cDataType) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: TensorShape) { + let dimensions: [Int64] = value.dimensions.map(Int64.init) + dimensions.withUnsafeBufferPointer { buffer in + TFE_OpSetAttrShape(op, name, buffer.baseAddress, Int32(buffer.count), status) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: TensorShape?) { + guard let shape = value else { + TFE_OpSetAttrShape(op, name, nil, -1, status) + return + } + updateAttribute(name, shape) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Bool]) { + value.map({ $0 ? UInt8(1) : UInt8(0) }).withUnsafeBufferPointer { buffer in + TFE_OpSetAttrBoolList(op, name, buffer.baseAddress, Int32(buffer.count)) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Int]) { + updateAttribute(name, value.map(Int64.init)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Int32]) { + updateAttribute(name, value.map(Int64.init)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Int64]) { + value.withUnsafeBufferPointer { buffer in + TFE_OpSetAttrIntList(op, name, buffer.baseAddress, Int32(buffer.count)) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Float]) { + value.withUnsafeBufferPointer { buffer in + TFE_OpSetAttrFloatList(op, name, buffer.baseAddress, Int32(buffer.count)) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Double]) { + updateAttribute(name, value.map(Float.init)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [String]) { + // Collect all the strings' utf8 bytes into a single array so that we can + // address all the strings with a single + // `flattenedStringBytes.withUnsafeBufferPointer`. + var flattenedStringBytes: [CChar] = [] + var lengths: [Int] = [] + for string in value { + // Don't include the null-terminator because TFE_OpSetAttrStringList uses + // lengths instead of null-terminators. + let stringBytes = string.utf8CString.dropLast() + flattenedStringBytes.append(contentsOf: stringBytes) + lengths.append(stringBytes.count) + } + + // Calculate the addresses of all the strings within our single buffer, and + // then call TFE_OpSetAttrStringList. + flattenedStringBytes.withUnsafeBufferPointer { flattenedStringBytesBuffer in + var stringAddrs: [UnsafeRawPointer?] = [] + var currentStringAddr = + flattenedStringBytesBuffer.baseAddress.map(UnsafeRawPointer.init) + for length in lengths { + stringAddrs.append(currentStringAddr) + currentStringAddr = currentStringAddr?.advanced(by: length) + } + + stringAddrs.withUnsafeBufferPointer { stringAddrsBuffer in + lengths.withUnsafeBufferPointer { lengthsBuffer in + TFE_OpSetAttrStringList(op, name, stringAddrsBuffer.baseAddress, + lengthsBuffer.baseAddress, Int32(value.count)) + } + } + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [TensorDataType]) { + value.withUnsafeBufferPointer { buffer in + buffer.withMemoryRebound(to: TF_DataType.self) { reboundBuffer in + TFE_OpSetAttrTypeList(op, name, reboundBuffer.baseAddress, Int32(reboundBuffer.count)) + } + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [TensorShape]) { + let flattenedDims = value.flatMap { $0.dimensions.map(Int64.init) } + let ranks = value.map { Int32($0.rank) } + flattenedDims.withUnsafeBufferPointer { flattenedDimsBuffer in + var dimsPtr: UnsafePointer? = flattenedDimsBuffer.baseAddress + var dims: [UnsafePointer?] = [] + for rank in ranks { + dims.append(dimsPtr) + if rank >= 0 { + dimsPtr = dimsPtr.map { $0.advanced(by: Int(rank)) } + } + } + dims.withUnsafeMutableBufferPointer { dimsBuffer in + ranks.withUnsafeBufferPointer { ranksBuffer in + TFE_OpSetAttrShapeList( + op, name, dimsBuffer.baseAddress, ranksBuffer.baseAddress, + Int32(ranksBuffer.count), status) + } + } + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [TensorShape?]) { + let flattenedDims = value.flatMap { (tensorShapeOpt) -> [Int64] in + if let tensorShape = tensorShapeOpt { + return tensorShape.dimensions.map(Int64.init) + } + return [] + } + let ranks = value.map { shape in (shape?.rank).map(Int32.init) ?? -1 } + flattenedDims.withUnsafeBufferPointer { flattenedDimsBuffer in + var dimsPtr: UnsafePointer? = flattenedDimsBuffer.baseAddress + var dims: [UnsafePointer?] = [] + for rank in ranks { + dims.append(dimsPtr) + if rank >= 0 { + dimsPtr = dimsPtr.map { $0.advanced(by: Int(rank)) } + } + } + dims.withUnsafeMutableBufferPointer { dimsBuffer in + ranks.withUnsafeBufferPointer { ranksBuffer in + TFE_OpSetAttrShapeList( + op, name, dimsBuffer.baseAddress, ranksBuffer.baseAddress, + Int32(ranksBuffer.count), status) + } + } + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: (In) -> Out) { + _tffunc(value).utf8CString.withUnsafeBufferPointer { buffer in + // utf8CString is null-terminated; TFE_OpSetAttrFunctionName wants + // non-null-terminated. + TFE_OpSetAttrFunctionName(op, name, buffer.baseAddress, buffer.count - 1) + } + } + + /// **WARNING:** After constructing a `TFE_Op`, any one of its `execute` methods must be called + /// *exactly once*. If not called, then a memory leak is introduced due to the underlying + /// TensorFlow eager op object not being freed. If called more than once, then a SEGFAULT may + /// occur due to trying to execute a TensorFlow eager op that has already been freed. + + @inlinable @inline(__always) + internal func evaluateUnsafe() -> UnsafeMutablePointer { + var count: Int32 = Int32(self.outputCount) + let buffer: UnsafeMutablePointer = + UnsafeMutablePointer.allocate(capacity: Int(count)) + _TFCOpSetDeviceFromScope(op, status) + checkOk(status) + _TFCEagerExecute(op, UnsafeMutablePointer(buffer), &count, status) + checkOk(status) + TFE_DeleteOp(op) + TF_DeleteStatus(status) + return buffer + } + + @inlinable @inline(__always) + internal func execute() { + let _ = evaluateUnsafe() + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int + ) -> (T0) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int + ) -> (T0, T1) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int + ) -> (T0, T1, T2) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int + ) -> (T0, T1, T2, T3) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int + ) -> (T0, T1, T2, T3, T4) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let offset4 = offset3 + Int32(count3) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), + T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int + ) -> (T0, T1, T2, T3, T4, T5) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let offset4 = offset3 + Int32(count3) + let offset5 = offset4 + Int32(count4) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), + T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), + T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int + ) -> (T0, T1, T2, T3, T4, T5, T6) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let offset4 = offset3 + Int32(count3) + let offset5 = offset4 + Int32(count4) + let offset6 = offset5 + Int32(count5) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), + T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), + T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5), + T6.init(_owning: buffer.advanced(by: Int(offset6)), count: count6)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int, + _ count7: Int + ) -> (T0, T1, T2, T3, T4, T5, T6, T7) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let offset4 = offset3 + Int32(count3) + let offset5 = offset4 + Int32(count4) + let offset6 = offset5 + Int32(count5) + let offset7 = offset6 + Int32(count6) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), + T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), + T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5), + T6.init(_owning: buffer.advanced(by: Int(offset6)), count: count6), + T7.init(_owning: buffer.advanced(by: Int(offset7)), count: count7)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int, + _ count7: Int, + _ count8: Int + ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let offset4 = offset3 + Int32(count3) + let offset5 = offset4 + Int32(count4) + let offset6 = offset5 + Int32(count5) + let offset7 = offset6 + Int32(count6) + let offset8 = offset7 + Int32(count7) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), + T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), + T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5), + T6.init(_owning: buffer.advanced(by: Int(offset6)), count: count6), + T7.init(_owning: buffer.advanced(by: Int(offset7)), count: count7), + T8.init(_owning: buffer.advanced(by: Int(offset8)), count: count8)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int, + _ count7: Int, + _ count8: Int, + _ count9: Int + ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let offset4 = offset3 + Int32(count3) + let offset5 = offset4 + Int32(count4) + let offset6 = offset5 + Int32(count5) + let offset7 = offset6 + Int32(count6) + let offset8 = offset7 + Int32(count7) + let offset9 = offset8 + Int32(count8) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), + T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), + T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5), + T6.init(_owning: buffer.advanced(by: Int(offset6)), count: count6), + T7.init(_owning: buffer.advanced(by: Int(offset7)), count: count7), + T8.init(_owning: buffer.advanced(by: Int(offset8)), count: count8), + T9.init(_owning: buffer.advanced(by: Int(offset9)), count: count9)) + buffer.deallocate() + return result + } + +} diff --git a/Sources/DeepLearning/Bindings/EagerExecution.swift.gyb b/Sources/DeepLearning/Bindings/EagerExecution.swift.gyb new file mode 100644 index 000000000..14e8f1d0f --- /dev/null +++ b/Sources/DeepLearning/Bindings/EagerExecution.swift.gyb @@ -0,0 +1,318 @@ +// !!! THIS CODE IS AUTOMATICALLY GENERATED, DO NOT EDIT BY HAND !!! +// +// Copyright 2018-19 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CTensorFlow + +/// **WARNING:** After constructing a `TFE_Op`, any one of its `execute` methods must be called +/// *exactly once*. If not called, then a memory leak is introduced due to the underlying TensorFlow +/// eager op object not being freed. If called more than once, then a SEGFAULT may occur due to +/// trying to execute a TensorFlow eager op that has already been freed. +@usableFromInline +internal struct TFE_Op : TFTensorOperation { + @usableFromInline internal let status: CTFStatus + @usableFromInline internal let op: CTFEOp + @usableFromInline internal let outputCount: Int + + @usableFromInline + internal init(_ name: String, _ outputCount: Int) { + self.status = TF_NewStatus() + self.op = TFE_NewOp(_ExecutionContext.global.eagerContext, name, status) + self.outputCount = outputCount + } + + @inlinable @inline(__always) + internal func addInput(_ input: _AnyTensorHandle) { + TFE_OpAddInput(op, input._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: Tensor) { + TFE_OpAddInput(op, input.handle._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: StringTensor) { + TFE_OpAddInput(op, input.handle._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: ResourceHandle) { + TFE_OpAddInput(op, input._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: VariantHandle) { + TFE_OpAddInput(op, input._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInputList(_ input: T) { + let count = input._tensorHandleCount + var buffer = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) + defer { buffer.deallocate() } + let pointer = UnsafeMutablePointer(buffer.baseAddress) + input._unpackTensorHandles(into: buffer.baseAddress) + TFE_OpAddInputList(op, pointer, count, status) + // TODO: checkOk(status) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Bool) { + TFE_OpSetAttrBool(op, name, value ? 1 : 0) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Int) { + TFE_OpSetAttrInt(op, name, Int64(value)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Int32) { + TFE_OpSetAttrInt(op, name, Int64(value)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Int64) { + TFE_OpSetAttrInt(op, name, value) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Float) { + TFE_OpSetAttrFloat(op, name, value) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Double) { + TFE_OpSetAttrFloat(op, name, Float(value)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: String) { + value.utf8CString.withUnsafeBufferPointer { buffer in + // utf8CString is null-terminated; TFE_OpSetAttrString wants + // non-null-terminated. + TFE_OpSetAttrString(op, name, buffer.baseAddress, buffer.count - 1) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: TensorDataType) { + TFE_OpSetAttrType(op, name, value._cDataType) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: TensorShape) { + let dimensions: [Int64] = value.dimensions.map(Int64.init) + dimensions.withUnsafeBufferPointer { buffer in + TFE_OpSetAttrShape(op, name, buffer.baseAddress, Int32(buffer.count), status) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: TensorShape?) { + guard let shape = value else { + TFE_OpSetAttrShape(op, name, nil, -1, status) + return + } + updateAttribute(name, shape) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Bool]) { + value.map({ $0 ? UInt8(1) : UInt8(0) }).withUnsafeBufferPointer { buffer in + TFE_OpSetAttrBoolList(op, name, buffer.baseAddress, Int32(buffer.count)) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Int]) { + updateAttribute(name, value.map(Int64.init)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Int32]) { + updateAttribute(name, value.map(Int64.init)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Int64]) { + value.withUnsafeBufferPointer { buffer in + TFE_OpSetAttrIntList(op, name, buffer.baseAddress, Int32(buffer.count)) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Float]) { + value.withUnsafeBufferPointer { buffer in + TFE_OpSetAttrFloatList(op, name, buffer.baseAddress, Int32(buffer.count)) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Double]) { + updateAttribute(name, value.map(Float.init)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [String]) { + // Collect all the strings' utf8 bytes into a single array so that we can + // address all the strings with a single + // `flattenedStringBytes.withUnsafeBufferPointer`. + var flattenedStringBytes: [CChar] = [] + var lengths: [Int] = [] + for string in value { + // Don't include the null-terminator because TFE_OpSetAttrStringList uses + // lengths instead of null-terminators. + let stringBytes = string.utf8CString.dropLast() + flattenedStringBytes.append(contentsOf: stringBytes) + lengths.append(stringBytes.count) + } + + // Calculate the addresses of all the strings within our single buffer, and + // then call TFE_OpSetAttrStringList. + flattenedStringBytes.withUnsafeBufferPointer { flattenedStringBytesBuffer in + var stringAddrs: [UnsafeRawPointer?] = [] + var currentStringAddr = + flattenedStringBytesBuffer.baseAddress.map(UnsafeRawPointer.init) + for length in lengths { + stringAddrs.append(currentStringAddr) + currentStringAddr = currentStringAddr?.advanced(by: length) + } + + stringAddrs.withUnsafeBufferPointer { stringAddrsBuffer in + lengths.withUnsafeBufferPointer { lengthsBuffer in + TFE_OpSetAttrStringList(op, name, stringAddrsBuffer.baseAddress, + lengthsBuffer.baseAddress, Int32(value.count)) + } + } + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [TensorDataType]) { + value.withUnsafeBufferPointer { buffer in + buffer.withMemoryRebound(to: TF_DataType.self) { reboundBuffer in + TFE_OpSetAttrTypeList(op, name, reboundBuffer.baseAddress, Int32(reboundBuffer.count)) + } + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [TensorShape]) { + let flattenedDims = value.flatMap { $0.dimensions.map(Int64.init) } + let ranks = value.map { Int32($0.rank) } + flattenedDims.withUnsafeBufferPointer { flattenedDimsBuffer in + var dimsPtr: UnsafePointer? = flattenedDimsBuffer.baseAddress + var dims: [UnsafePointer?] = [] + for rank in ranks { + dims.append(dimsPtr) + if rank >= 0 { + dimsPtr = dimsPtr.map { $0.advanced(by: Int(rank)) } + } + } + dims.withUnsafeMutableBufferPointer { dimsBuffer in + ranks.withUnsafeBufferPointer { ranksBuffer in + TFE_OpSetAttrShapeList( + op, name, dimsBuffer.baseAddress, ranksBuffer.baseAddress, + Int32(ranksBuffer.count), status) + } + } + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [TensorShape?]) { + let flattenedDims = value.flatMap { (tensorShapeOpt) -> [Int64] in + if let tensorShape = tensorShapeOpt { + return tensorShape.dimensions.map(Int64.init) + } + return [] + } + let ranks = value.map { shape in (shape?.rank).map(Int32.init) ?? -1 } + flattenedDims.withUnsafeBufferPointer { flattenedDimsBuffer in + var dimsPtr: UnsafePointer? = flattenedDimsBuffer.baseAddress + var dims: [UnsafePointer?] = [] + for rank in ranks { + dims.append(dimsPtr) + if rank >= 0 { + dimsPtr = dimsPtr.map { $0.advanced(by: Int(rank)) } + } + } + dims.withUnsafeMutableBufferPointer { dimsBuffer in + ranks.withUnsafeBufferPointer { ranksBuffer in + TFE_OpSetAttrShapeList( + op, name, dimsBuffer.baseAddress, ranksBuffer.baseAddress, + Int32(ranksBuffer.count), status) + } + } + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: (In) -> Out) { + _tffunc(value).utf8CString.withUnsafeBufferPointer { buffer in + // utf8CString is null-terminated; TFE_OpSetAttrFunctionName wants + // non-null-terminated. + TFE_OpSetAttrFunctionName(op, name, buffer.baseAddress, buffer.count - 1) + } + } + + /// **WARNING:** After constructing a `TFE_Op`, any one of its `execute` methods must be called + /// *exactly once*. If not called, then a memory leak is introduced due to the underlying + /// TensorFlow eager op object not being freed. If called more than once, then a SEGFAULT may + /// occur due to trying to execute a TensorFlow eager op that has already been freed. + + @inlinable @inline(__always) + internal func evaluateUnsafe() -> UnsafeMutablePointer { + var count: Int32 = Int32(self.outputCount) + let buffer: UnsafeMutablePointer = + UnsafeMutablePointer.allocate(capacity: Int(count)) + _TFCOpSetDeviceFromScope(op, status) + checkOk(status) + _TFCEagerExecute(op, UnsafeMutablePointer(buffer), &count, status) + checkOk(status) + TFE_DeleteOp(op) + TF_DeleteStatus(status) + return buffer + } + + @inlinable @inline(__always) + internal func execute() { + let _ = evaluateUnsafe() + } + +%for n in range(1, 10 + 1): + @inlinable @inline(__always) + internal func execute<${", ".join(["T" + str(i) + " : TensorArrayProtocol" for i in range(n)])}>( + ${",\n ".join(["_ count" + str(i) + ": Int" for i in range(n)])} + ) -> (${", ".join(["T" + str(i) for i in range(n)])}) { + let buffer = evaluateUnsafe() +%for i in range(n): + let offset${i} = ${"Int32(0)" if i == 0 else "offset" + str(i - 1) + " + Int32(count" + str(i - 1) + ")"} +%end + let result = ( + ${",\n ".join(["T" + str(i) + ".init(_owning: buffer.advanced(by: Int(offset" + str(i) + ")), count: count" + str(i) + ")" for i in range(n)])}) + buffer.deallocate() + return result + } + +%end +} diff --git a/Sources/DeepLearning/Bindings/README.md b/Sources/DeepLearning/Bindings/README.md new file mode 100644 index 000000000..2da786ee6 --- /dev/null +++ b/Sources/DeepLearning/Bindings/README.md @@ -0,0 +1,27 @@ +# Swift for TensorFlow Ops Bindings + +This repository contains TensorFlow ops bindings for +[Swift for TensorFlow](https://github.com/tensorflow/swift). + +These bindings are automatically generated from TensorFlow ops +specified either using ops registered to the TensorFlow runtime +or via a protobuf file similar to +[ops.pbtxt](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/ops/ops.pbtxt) +in the main TensorFlow repo. + +## How to regenerate the bindings + +To regenerate the swift ops bindings, run the following command. Note +that this will use the TensorFlow (1.9 or above) python package. + +``` shell +python generate_wrappers.py --output_path=RawOpsGenerated.swift +``` + +Documentation gets automatically generated when adding a path to the +`api_def` proto directory. This directory should contain per operator +`api_def` protos with names like `api_def_OpName.pbtxt`. + +```shell +python generate_wrappers.py --output_path=RawOpsGenerated.swift --api_def_path=/path/to/tensorflow/core/api_def/base_api +``` diff --git a/Sources/DeepLearning/Bindings/RawOpsGenerated.swift b/Sources/DeepLearning/Bindings/RawOpsGenerated.swift new file mode 100644 index 000000000..51aa03bd2 --- /dev/null +++ b/Sources/DeepLearning/Bindings/RawOpsGenerated.swift @@ -0,0 +1,37640 @@ +// !!! THIS CODE IS AUTOMATICALLY GENERATED, DO NOT EDIT BY HAND !!! +// +// Copyright 2018-19 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CTensorFlow + +@inlinable @inline(__always) +func makeOp(_ name: String, _ nOutputs: Int) -> TFTensorOperation { + _ExecutionContext.makeOp(name, nOutputs) +} + +public enum Raw { + +static let generatedTensorFlowVersion = "1.14.1-dev20190516" +static let generatedTensorFlowGitVersion = "v1.12.1-2080-g4e3a33a1d2" + +// @_frozen // SR-9739 +public enum A { + case apples + case oranges + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .apples: return "apples" + case .oranges: return "oranges" + } + } + } +} + +// @_frozen // SR-9739 +public enum DataFormat { + case nchw + case nhwc + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .nchw: return "NCHW" + case .nhwc: return "NHWC" + } + } + } +} + +// @_frozen // SR-9739 +public enum DataFormat1 { + case ncdhw + case ndhwc + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .ncdhw: return "NCDHW" + case .ndhwc: return "NDHWC" + } + } + } +} + +// @_frozen // SR-9739 +public enum DataFormat4 { + case nchw + case nchwVectC + case nhwc + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .nchw: return "NCHW" + case .nchwVectC: return "NCHW_VECT_C" + case .nhwc: return "NHWC" + } + } + } +} + +// @_frozen // SR-9739 +public enum DensityUnit { + case cm + case in_ + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .cm: return "cm" + case .in_: return "in" + } + } + } +} + +// @_frozen // SR-9739 +public enum Direction { + case bidirectional + case unidirectional + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .bidirectional: return "bidirectional" + case .unidirectional: return "unidirectional" + } + } + } +} + +// @_frozen // SR-9739 +public enum Errors { + case ignore + case replace + case strict + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .ignore: return "ignore" + case .replace: return "replace" + case .strict: return "strict" + } + } + } +} + +// @_frozen // SR-9739 +public enum FinalOp { + case div + case id + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .div: return "Div" + case .id: return "Id" + } + } + } +} + +// @_frozen // SR-9739 +public enum Format { + case empty + case grayscale + case rgb + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .empty: return "" + case .grayscale: return "grayscale" + case .rgb: return "rgb" + } + } + } +} + +// @_frozen // SR-9739 +public enum InputMode { + case autoSelect + case linearInput + case skipInput + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .autoSelect: return "auto_select" + case .linearInput: return "linear_input" + case .skipInput: return "skip_input" + } + } + } +} + +// @_frozen // SR-9739 +public enum LossType { + case hingeLoss + case logisticLoss + case poissonLoss + case smoothHingeLoss + case squaredLoss + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .hingeLoss: return "hinge_loss" + case .logisticLoss: return "logistic_loss" + case .poissonLoss: return "poisson_loss" + case .smoothHingeLoss: return "smooth_hinge_loss" + case .squaredLoss: return "squared_loss" + } + } + } +} + +// @_frozen // SR-9739 +public enum MergeOp { + case add + case max + case min + case mul + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .add: return "Add" + case .max: return "Max" + case .min: return "Min" + case .mul: return "Mul" + } + } + } +} + +// @_frozen // SR-9739 +public enum Method { + case bilinear + case nearest + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .bilinear: return "bilinear" + case .nearest: return "nearest" + } + } + } +} + +// @_frozen // SR-9739 +public enum Method3 { + case bilinear + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .bilinear: return "bilinear" + } + } + } +} + +// @_frozen // SR-9739 +public enum Mode { + case minCombined + case minFirst + case scaled + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .minCombined: return "MIN_COMBINED" + case .minFirst: return "MIN_FIRST" + case .scaled: return "SCALED" + } + } + } +} + +// @_frozen // SR-9739 +public enum Mode5 { + case reflect + case symmetric + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .reflect: return "REFLECT" + case .symmetric: return "SYMMETRIC" + } + } + } +} + +// @_frozen // SR-9739 +public enum OutputEncoding { + case utf16Be + case utf32Be + case utf8 + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .utf16Be: return "UTF-16-BE" + case .utf32Be: return "UTF-32-BE" + case .utf8: return "UTF-8" + } + } + } +} + +// @_frozen // SR-9739 +public enum Padding { + case same + case valid + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .same: return "SAME" + case .valid: return "VALID" + } + } + } +} + +// @_frozen // SR-9739 +public enum Padding2 { + case explicit + case same + case valid + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .explicit: return "EXPLICIT" + case .same: return "SAME" + case .valid: return "VALID" + } + } + } +} + +// @_frozen // SR-9739 +public enum Reduction { + case max + case min + case prod + case sum + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .max: return "max" + case .min: return "min" + case .prod: return "prod" + case .sum: return "sum" + } + } + } +} + +// @_frozen // SR-9739 +public enum RnnMode { + case gru + case lstm + case rnnRelu + case rnnTanh + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .gru: return "gru" + case .lstm: return "lstm" + case .rnnRelu: return "rnn_relu" + case .rnnTanh: return "rnn_tanh" + } + } + } +} + +// @_frozen // SR-9739 +public enum RoundMode { + case halfToEven + case halfUp + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .halfToEven: return "HALF_TO_EVEN" + case .halfUp: return "HALF_UP" + } + } + } +} + +// @_frozen // SR-9739 +public enum RoundMode6 { + case halfAwayFromZero + case halfToEven + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .halfAwayFromZero: return "HALF_AWAY_FROM_ZERO" + case .halfToEven: return "HALF_TO_EVEN" + } + } + } +} + +// @_frozen // SR-9739 +public enum SplitType { + case inequality + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .inequality: return "inequality" + } + } + } +} + +// @_frozen // SR-9739 +public enum Unit { + case byte + case utf8Char + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .byte: return "BYTE" + case .utf8Char: return "UTF8_CHAR" + } + } + } +} + + +@inlinable @inline(__always) +public static func a( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("A", nOutputs) + + return op.execute(Int(1)) +} + +/// Raise a exception to abort the process when called. +/// +/// If exit_without_error is true, the process will exit normally, +/// otherwise it will exit with a SIGABORT signal. +/// +/// Returns nothing but an exception. +/// +/// - Attr error_msg: A string which is the message associated with the exception. +@inlinable @inline(__always) +public static func abort( + errorMsg: String, + exitWithoutError: Bool = false +) { + let nOutputs = 0 + let op = makeOp("Abort", nOutputs) + op.updateAttribute("error_msg", errorMsg) + op.updateAttribute("exit_without_error", exitWithoutError) + op.execute() +} + +/// Computes the absolute value of a tensor. +/// +/// Given a tensor `x`, this operation returns a tensor containing the absolute +/// value of each element in `x`. For example, if x is an input element and y is +/// an output element, this operation computes \\(y = |x|\\). +@inlinable @inline(__always) +public static func abs( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Abs", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Returns the element-wise sum of a list of tensors. +/// +/// `tf.accumulate_n_v2` performs the same operation as `tf.add_n`, but does not +/// wait for all of its inputs to be ready before beginning to sum. This can +/// save memory if inputs are ready at different times, since minimum temporary +/// storage is proportional to the output size rather than the inputs size. +/// +/// Unlike the original `accumulate_n`, `accumulate_n_v2` is differentiable. +/// +/// Returns a `Tensor` of same shape and type as the elements of `inputs`. +/// +/// - Parameter inputs: A list of `Tensor` objects, each with same shape and type. +/// +/// - Attr shape: Shape of elements of `inputs`. +@inlinable @inline(__always) +public static func accumulateNV2( + inputs: [Tensor], + shape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AccumulateNV2", nOutputs) + op.updateAttribute("N", inputs.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.addInputList(inputs) + return op.execute(Int(1)) +} + +/// Computes acos of x element-wise. +@inlinable @inline(__always) +public static func acos( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Acos", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes inverse hyperbolic cosine of x element-wise. +@inlinable @inline(__always) +public static func acosh( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Acosh", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Returns x + y element-wise. +/// +/// *NOTE*: `Add` supports broadcasting. `AddN` does not. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func add( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Add", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns x + y element-wise. +/// +/// *NOTE*: `Add` supports broadcasting. `AddN` does not. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func add( + _ x: StringTensor, + _ y: StringTensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("Add", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Add an `N`-minibatch `SparseTensor` to a `SparseTensorsMap`, return `N` handles. +/// +/// A `SparseTensor` of rank `R` is represented by three tensors: `sparse_indices`, +/// `sparse_values`, and `sparse_shape`, where +/// +/// ```sparse_indices.shape[1] == sparse_shape.shape[0] == R``` +/// +/// An `N`-minibatch of `SparseTensor` objects is represented as a `SparseTensor` +/// having a first `sparse_indices` column taking values between `[0, N)`, where +/// the minibatch size `N == sparse_shape[0]`. +/// +/// The input `SparseTensor` must have rank `R` greater than 1, and the first +/// dimension is treated as the minibatch dimension. Elements of the `SparseTensor` +/// must be sorted in increasing order of this first dimension. The stored +/// `SparseTensor` objects pointed to by each row of the output `sparse_handles` +/// will have rank `R-1`. +/// +/// The `SparseTensor` values can then be read out as part of a minibatch by passing +/// the given keys as vector elements to `TakeManySparseFromTensorsMap`. To ensure +/// the correct `SparseTensorsMap` is accessed, ensure that the same +/// `container` and `shared_name` are passed to that Op. If no `shared_name` +/// is provided here, instead use the *name* of the Operation created by calling +/// `AddManySparseToTensorsMap` as the `shared_name` passed to +/// `TakeManySparseFromTensorsMap`. Ensure the Operations are colocated. +/// +/// - Parameters: +/// - sparse_indices: 2-D. The `indices` of the minibatch `SparseTensor`. +/// `sparse_indices[:, 0]` must be ordered values in `[0, N)`. +/// - sparse_values: 1-D. The `values` of the minibatch `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the minibatch `SparseTensor`. +/// The minibatch size `N == sparse_shape[0]`. +/// +/// - Attrs: +/// - container: The container name for the `SparseTensorsMap` created by this op. +/// - shared_name: The shared name for the `SparseTensorsMap` created by this op. +/// If blank, the new Operation's unique name is used. +/// +/// - Output sparse_handles: 1-D. The handles of the `SparseTensor` now stored in the +/// `SparseTensorsMap`. Shape: `[N]`. +@inlinable @inline(__always) +public static func addManySparseToTensorsMap( + sparseIndices: Tensor, + sparseValues: Tensor, + sparseShape: Tensor, + container: String, + sharedName: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AddManySparseToTensorsMap", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(sparseIndices) + op.addInput(sparseValues) + op.addInput(sparseShape) + return op.execute(Int(1)) +} + +/// Add all input tensors element wise. +/// +/// - Parameter inputs: Must all be the same size and shape. +@inlinable @inline(__always) +public static func addN( + inputs: [Tensor] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AddN", nOutputs) + op.updateAttribute("N", inputs.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInputList(inputs) + return op.execute(Int(1)) +} + +/// Add a `SparseTensor` to a `SparseTensorsMap` return its handle. +/// +/// A `SparseTensor` is represented by three tensors: `sparse_indices`, +/// `sparse_values`, and `sparse_shape`. +/// +/// This operator takes the given `SparseTensor` and adds it to a container +/// object (a `SparseTensorsMap`). A unique key within this container is generated +/// in the form of an `int64`, and this is the value that is returned. +/// +/// The `SparseTensor` can then be read out as part of a minibatch by passing +/// the key as a vector element to `TakeManySparseFromTensorsMap`. To ensure +/// the correct `SparseTensorsMap` is accessed, ensure that the same +/// `container` and `shared_name` are passed to that Op. If no `shared_name` +/// is provided here, instead use the *name* of the Operation created by calling +/// `AddSparseToTensorsMap` as the `shared_name` passed to +/// `TakeManySparseFromTensorsMap`. Ensure the Operations are colocated. +/// +/// - Parameters: +/// - sparse_indices: 2-D. The `indices` of the `SparseTensor`. +/// - sparse_values: 1-D. The `values` of the `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the `SparseTensor`. +/// +/// - Attrs: +/// - container: The container name for the `SparseTensorsMap` created by this op. +/// - shared_name: The shared name for the `SparseTensorsMap` created by this op. +/// If blank, the new Operation's unique name is used. +/// +/// - Output sparse_handle: 0-D. The handle of the `SparseTensor` now stored in the +/// `SparseTensorsMap`. +@inlinable @inline(__always) +public static func addSparseToTensorsMap( + sparseIndices: Tensor, + sparseValues: Tensor, + sparseShape: Tensor, + container: String, + sharedName: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AddSparseToTensorsMap", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(sparseIndices) + op.addInput(sparseValues) + op.addInput(sparseShape) + return op.execute(Int(1)) +} + +/// Returns x + y element-wise. +/// +/// *NOTE*: `Add` supports broadcasting. `AddN` does not. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func addV2( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AddV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Deprecated. Disallowed in GraphDef version >= 2. +@inlinable @inline(__always) +public static func adjustContrast( + images: Tensor, + contrastFactor: Tensor, + minValue: Tensor, + maxValue: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AdjustContrast", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + op.addInput(contrastFactor) + op.addInput(minValue) + op.addInput(maxValue) + return op.execute(Int(1)) +} + +/// Adjust the contrast of one or more images. +/// +/// `images` is a tensor of at least 3 dimensions. The last 3 dimensions are +/// interpreted as `[height, width, channels]`. The other dimensions only +/// represent a collection of images, such as `[batch, height, width, channels].` +/// +/// Contrast is adjusted independently for each channel of each image. +/// +/// For each channel, the Op first computes the mean of the image pixels in the +/// channel and then adjusts each component of each pixel to +/// `(x - mean) * contrast_factor + mean`. +/// +/// - Parameters: +/// - images: Images to adjust. At least 3-D. +/// - contrast_factor: A float multiplier for adjusting contrast. +/// +/// - Output output: The contrast-adjusted image or images. +@inlinable @inline(__always) +public static func adjustContrastv2( + images: Tensor, + contrastFactor: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AdjustContrastv2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + op.addInput(contrastFactor) + return op.execute(Int(1)) +} + +/// Adjust the hue of one or more images. +/// +/// `images` is a tensor of at least 3 dimensions. The last dimension is +/// interpretted as channels, and must be three. +/// +/// The input image is considered in the RGB colorspace. Conceptually, the RGB +/// colors are first mapped into HSV. A delta is then applied all the hue values, +/// and then remapped back to RGB colorspace. +/// +/// - Parameters: +/// - images: Images to adjust. At least 3-D. +/// - delta: A float delta to add to the hue. +/// +/// - Output output: The hue-adjusted image or images. +@inlinable @inline(__always) +public static func adjustHue( + images: Tensor, + delta: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AdjustHue", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + op.addInput(delta) + return op.execute(Int(1)) +} + +/// Adjust the saturation of one or more images. +/// +/// `images` is a tensor of at least 3 dimensions. The last dimension is +/// interpretted as channels, and must be three. +/// +/// The input image is considered in the RGB colorspace. Conceptually, the RGB +/// colors are first mapped into HSV. A scale is then applied all the saturation +/// values, and then remapped back to RGB colorspace. +/// +/// - Parameters: +/// - images: Images to adjust. At least 3-D. +/// - scale: A float scale to add to the saturation. +/// +/// - Output output: The hue-adjusted image or images. +@inlinable @inline(__always) +public static func adjustSaturation( + images: Tensor, + scale: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AdjustSaturation", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + op.addInput(scale) + return op.execute(Int(1)) +} + +/// Computes the "logical and" of elements across dimensions of a tensor. +/// +/// Reduces `input` along the dimensions given in `axis`. Unless +/// `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in +/// `axis`. If `keep_dims` is true, the reduced dimensions are +/// retained with length 1. +/// +/// - Parameters: +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. +/// +/// - Attr keep_dims: If true, retain reduced dimensions with length 1. +/// +/// - Output output: The reduced tensor. +@inlinable @inline(__always) +public static func all( + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("All", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) +} + +/// Generates labels for candidate sampling with a learned unigram distribution. +/// +/// See explanations of candidate sampling and the data formats at +/// go/candidate-sampling. +/// +/// For each batch, this op picks a single set of sampled candidate labels. +/// +/// The advantages of sampling candidates per-batch are simplicity and the +/// possibility of efficient dense matrix multiplication. The disadvantage is that +/// the sampled candidates must be chosen independently of the context and of the +/// true labels. +/// +/// - Parameter true_classes: A batch_size * num_true matrix, in which each row contains the +/// IDs of the num_true target_classes in the corresponding original label. +/// +/// - Attrs: +/// - num_true: Number of true labels per context. +/// - num_sampled: Number of candidates to produce. +/// - unique: If unique is true, we sample with rejection, so that all sampled +/// candidates in a batch are unique. This requires some approximation to +/// estimate the post-rejection sampling probabilities. +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. +/// +/// - Outputs: +/// - sampled_candidates: A vector of length num_sampled, in which each element is +/// the ID of a sampled candidate. +/// - true_expected_count: A batch_size * num_true matrix, representing +/// the number of times each candidate is expected to occur in a batch +/// of sampled candidates. If unique=true, then this is a probability. +/// - sampled_expected_count: A vector of length num_sampled, for each sampled +/// candidate representing the number of times the candidate is expected +/// to occur in a batch of sampled candidates. If unique=true, then this is a +/// probability. +@inlinable @inline(__always) +public static func allCandidateSampler( + trueClasses: Tensor, + numTrue: Int64, + numSampled: Int64, + unique: Bool, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> (sampledCandidates: Tensor, trueExpectedCount: Tensor, sampledExpectedCount: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("AllCandidateSampler", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("num_sampled", numSampled) + op.updateAttribute("unique", unique) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// An Op to exchange data across TPU replicas. +/// +/// On each replica, the input is split into `split_count` blocks along +/// `split_dimension` and send to the other replicas given group_assignment. After +/// receiving `split_count` - 1 blocks from other replicas, we concatenate the +/// blocks along `concat_dimension` as the output. +/// +/// For example, suppose there are 2 TPU replicas: +/// replica 0 receives input: `[[A, B]]` +/// replica 1 receives input: `[[C, D]]` +/// +/// group_assignment=`[[0, 1]]` +/// concat_dimension=0 +/// split_dimension=1 +/// split_count=2 +/// +/// replica 0's output: `[[A], [C]]` +/// replica 1's output: `[[B], [D]]` +/// +/// - Parameters: +/// - input: The local input to the sum. +/// - group_assignment: An int32 tensor with shape +/// [num_groups, num_replicas_per_group]. `group_assignment[i]` represents the +/// replica ids in the ith subgroup. +/// +/// - Attrs: +/// - T: The type of elements to be exchanged. +/// - concat_dimension: The dimension number to concatenate. +/// - split_dimension: The dimension number to split. +/// - split_count: The number of splits, this number must equal to the sub-group +/// size(group_assignment.get_shape()[1]) +/// +/// - Output output: The exchanged result. +@inlinable @inline(__always) +public static func allToAll( + _ input: Tensor, + groupAssignment: Tensor, + concatDimension: Int64, + splitDimension: Int64, + splitCount: Int64 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AllToAll", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("concat_dimension", concatDimension) + op.updateAttribute("split_dimension", splitDimension) + op.updateAttribute("split_count", splitCount) + op.addInput(input) + op.addInput(groupAssignment) + return op.execute(Int(1)) +} + +/// Returns the argument of a complex number. +/// +/// Given a tensor `input` of complex numbers, this operation returns a tensor of +/// type `float` that is the argument of each element in `input`. All elements in +/// `input` must be complex numbers of the form \\(a + bj\\), where *a* +/// is the real part and *b* is the imaginary part. +/// +/// The argument returned by this operation is of the form \\(atan2(b, a)\\). +/// +/// For example: +/// +/// ``` +/// # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] +/// tf.angle(input) ==> [2.0132, 1.056] +/// ``` +/// +/// @compatibility(numpy) +/// Equivalent to np.angle. +/// @end_compatibility +@inlinable @inline(__always) +public static func angle< + T: TensorFlowScalar, + Tout: FloatingPoint & TensorFlowScalar +>( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Angle", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// A container for an iterator resource. +/// +/// - Output handle: A handle to the iterator that can be passed to a "MakeIterator" or +/// "IteratorGetNext" op. In contrast to Iterator, AnonymousIterator prevents +/// resource sharing by name, and does not keep a reference to the resource +/// container. +@inlinable @inline(__always) +public static func anonymousIterator( + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("AnonymousIterator", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + return op.execute(Int(1)) +} + +/// A container for an iterator resource. +/// +/// - Outputs: +/// - handle: A handle to the iterator that can be passed to a "MakeIterator" or +/// "IteratorGetNext" op. In contrast to Iterator, AnonymousIterator prevents +/// resource sharing by name, and does not keep a reference to the resource +/// container. +/// - deleter: A variant deleter that should be passed into the op that deletes the iterator. +@inlinable @inline(__always) +public static func anonymousIteratorV2( + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> (handle: ResourceHandle, deleter: VariantHandle) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("AnonymousIteratorV2", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + return op.execute(Int(1), Int(1)) +} + +/// Computes the "logical or" of elements across dimensions of a tensor. +/// +/// Reduces `input` along the dimensions given in `axis`. Unless +/// `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in +/// `axis`. If `keep_dims` is true, the reduced dimensions are +/// retained with length 1. +/// +/// - Parameters: +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. +/// +/// - Attr keep_dims: If true, retain reduced dimensions with length 1. +/// +/// - Output output: The reduced tensor. +@inlinable @inline(__always) +public static func any( + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Any", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) +} + +/// Returns the truth value of abs(x-y) < tolerance element-wise. +@inlinable @inline(__always) +public static func approximateEqual( + _ x: Tensor, + _ y: Tensor, + tolerance: Double = 1e-05 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ApproximateEqual", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("tolerance", tolerance) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns the index with the largest value across dimensions of a tensor. +/// +/// Note that in case of ties the identity of the return value is not guaranteed. +/// +/// Usage: +/// ```python +/// import tensorflow as tf +/// a = [1, 10, 26.9, 2.8, 166.32, 62.3] +/// b = tf.math.argmax(input = a) +/// c = tf.keras.backend.eval(b) +/// # c = 4 +/// # here a[4] = 166.32 which is the largest element of a across axis 0 +/// ``` +/// +/// - Parameter dimension: int32 or int64, must be in the range `[-rank(input), rank(input))`. +/// Describes which dimension of the input Tensor to reduce across. For vectors, +/// use dimension = 0. +@inlinable @inline(__always) +public static func argMax< + T: Numeric & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar, + OutputType: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + dimension: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ArgMax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("output_type", OutputType.tensorFlowDataType) + op.addInput(input) + op.addInput(dimension) + return op.execute(Int(1)) +} + +/// Returns the index with the smallest value across dimensions of a tensor. +/// +/// Note that in case of ties the identity of the return value is not guaranteed. +/// +/// Usage: +/// ```python +/// import tensorflow as tf +/// a = [1, 10, 26.9, 2.8, 166.32, 62.3] +/// b = tf.math.argmin(input = a) +/// c = tf.keras.backend.eval(b) +/// # c = 0 +/// # here a[0] = 1 which is the smallest element of a across axis 0 +/// ``` +/// +/// - Parameter dimension: int32 or int64, must be in the range `[-rank(input), rank(input))`. +/// Describes which dimension of the input Tensor to reduce across. For vectors, +/// use dimension = 0. +@inlinable @inline(__always) +public static func argMin< + T: Numeric & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar, + OutputType: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + dimension: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ArgMin", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("output_type", OutputType.tensorFlowDataType) + op.addInput(input) + op.addInput(dimension) + return op.execute(Int(1)) +} + +/// Converts each entry in the given tensor to strings. Supports many numeric +/// +/// types and boolean. +/// +/// - Attrs: +/// - precision: The post-decimal precision to use for floating point numbers. +/// Only used if precision > -1. +/// - scientific: Use scientific notation for floating point numbers. +/// - shortest: Use shortest representation (either scientific or standard) for +/// floating point numbers. +/// - width: Pad pre-decimal numbers to this width. +/// Applies to both floating point and integer numbers. +/// Only used if width > -1. +/// - fill: The value to pad if width > -1. If empty, pads with spaces. +/// Another typical value is '0'. String cannot be longer than 1 character. +@inlinable @inline(__always) +public static func asString( + _ input: Tensor, + precision: Int64 = -1, + scientific: Bool = false, + shortest: Bool = false, + width: Int64 = -1, + fill: String +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("AsString", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("precision", precision) + op.updateAttribute("scientific", scientific) + op.updateAttribute("shortest", shortest) + op.updateAttribute("width", width) + op.updateAttribute("fill", fill) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Computes the trignometric inverse sine of x element-wise. +/// +/// The `tf.math.asin` operation returns the inverse of `tf.math.sin`, such that +/// if `y = tf.math.sin(x)` then, `x = tf.math.asin(y)`. +/// +/// **Note**: The output of `tf.math.asin` will lie within the invertible range +/// of sine, i.e [-pi/2, pi/2]. +/// +/// For example: +/// +/// ```python +/// # Note: [1.047, 0.785] ~= [(pi/3), (pi/4)] +/// x = tf.constant([1.047, 0.785]) +/// y = tf.math.sin(x) # [0.8659266, 0.7068252] +/// +/// tf.math.asin(y) # [1.047, 0.785] = x +/// ``` +/// +@inlinable @inline(__always) +public static func asin( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Asin", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes inverse hyperbolic sine of x element-wise. +@inlinable @inline(__always) +public static func asinh( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Asinh", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Asserts that the given condition is true. +/// +/// If `condition` evaluates to false, print the list of tensors in `data`. +/// `summarize` determines how many entries of the tensors to print. +/// +/// - Parameters: +/// - condition: The condition to evaluate. +/// - data: The tensors to print out when condition is false. +/// +/// - Attr summarize: Print this many entries of each tensor. +@inlinable @inline(__always) +public static func assert( + condition: Tensor, + data: T, + summarize: Int64 = 3 +) { + let nOutputs = 0 + let op = makeOp("Assert", nOutputs) + op.updateAttribute("T", data._typeList) + op.updateAttribute("summarize", summarize) + op.addInput(condition) + op.addInputList(data) + op.execute() +} + +/// Adds a value to the current value of a variable. +/// +/// Any ReadVariableOp with a control dependency on this op is guaranteed to +/// see the incremented value or a subsequent newer one. +/// +/// - Parameters: +/// - resource: handle to the resource in which to store the variable. +/// - value: the value by which the variable will be incremented. +/// +/// - Attr dtype: the dtype of the value. +@inlinable @inline(__always) +public static func assignAddVariableOp( + resource: ResourceHandle, + value: Tensor +) { + let nOutputs = 0 + let op = makeOp("AssignAddVariableOp", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(value) + op.execute() +} + +/// Subtracts a value from the current value of a variable. +/// +/// Any ReadVariableOp with a control dependency on this op is guaranteed to +/// see the decremented value or a subsequent newer one. +/// +/// - Parameters: +/// - resource: handle to the resource in which to store the variable. +/// - value: the value by which the variable will be incremented. +/// +/// - Attr dtype: the dtype of the value. +@inlinable @inline(__always) +public static func assignSubVariableOp( + resource: ResourceHandle, + value: Tensor +) { + let nOutputs = 0 + let op = makeOp("AssignSubVariableOp", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(value) + op.execute() +} + +/// Assigns a new value to a variable. +/// +/// Any ReadVariableOp with a control dependency on this op is guaranteed to return +/// this value or a subsequent newer value of the variable. +/// +/// - Parameters: +/// - resource: handle to the resource in which to store the variable. +/// - value: the value to set the new tensor to use. +/// +/// - Attr dtype: the dtype of the value. +@inlinable @inline(__always) +public static func assignVariableOp( + resource: ResourceHandle, + value: Tensor +) { + let nOutputs = 0 + let op = makeOp("AssignVariableOp", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(value) + op.execute() +} + +/// Computes the trignometric inverse tangent of x element-wise. +/// +/// The `tf.math.atan` operation returns the inverse of `tf.math.tan`, such that +/// if `y = tf.math.tan(x)` then, `x = tf.math.atan(y)`. +/// +/// **Note**: The output of `tf.math.atan` will lie within the invertible range +/// of tan, i.e (-pi/2, pi/2). +/// +/// For example: +/// +/// ```python +/// # Note: [1.047, 0.785] ~= [(pi/3), (pi/4)] +/// x = tf.constant([1.047, 0.785]) +/// y = tf.math.tan(x) # [1.731261, 0.99920404] +/// +/// tf.math.atan(y) # [1.047, 0.785] = x +/// ``` +/// +@inlinable @inline(__always) +public static func atan( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Atan", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes arctangent of `y/x` element-wise, respecting signs of the arguments. +/// +/// This is the angle \( \theta \in [-\pi, \pi] \) such that +/// \[ x = r \cos(\theta) \] +/// and +/// \[ y = r \sin(\theta) \] +/// where \(r = \sqrt(x^2 + y^2) \). +@inlinable @inline(__always) +public static func atan2( + _ y: Tensor, + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Atan2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes inverse hyperbolic tangent of x element-wise. +@inlinable @inline(__always) +public static func atanh( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Atanh", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func attr( + _ a: Int64 +) { + let nOutputs = 0 + let op = makeOp("Attr", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrBool( + _ a: Bool +) { + let nOutputs = 0 + let op = makeOp("AttrBool", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrBoolList( + _ a: [Bool] +) { + let nOutputs = 0 + let op = makeOp("AttrBoolList", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrDefault( + _ a: String = "banana" +) { + let nOutputs = 0 + let op = makeOp("AttrDefault", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrEmptyListDefault( + _ a: [Double] +) { + let nOutputs = 0 + let op = makeOp("AttrEmptyListDefault", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrEnum( + _ a: A +) { + let nOutputs = 0 + let op = makeOp("AttrEnum", nOutputs) + op.updateAttribute("a", a.cName) + op.execute() +} + +@inlinable @inline(__always) +public static func attrEnumList( + _ a: [String] +) { + let nOutputs = 0 + let op = makeOp("AttrEnumList", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrFloat( + _ a: Double +) { + let nOutputs = 0 + let op = makeOp("AttrFloat", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrListDefault( + _ a: [Int32] = [5, 15] +) { + let nOutputs = 0 + let op = makeOp("AttrListDefault", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrListMin( + _ a: [Int32] +) { + let nOutputs = 0 + let op = makeOp("AttrListMin", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrListTypeDefault( + _ a: [Tensor], + _ b: [Tensor] +) { + let nOutputs = 0 + let op = makeOp("AttrListTypeDefault", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.addInputList(b) + op.execute() +} + +@inlinable @inline(__always) +public static func attrMin( + _ a: Int64 +) { + let nOutputs = 0 + let op = makeOp("AttrMin", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrPartialShape( + _ a: TensorShape? +) { + let nOutputs = 0 + let op = makeOp("AttrPartialShape", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrPartialShapeList( + _ a: [TensorShape?] +) { + let nOutputs = 0 + let op = makeOp("AttrPartialShapeList", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrShape( + _ a: TensorShape? +) { + let nOutputs = 0 + let op = makeOp("AttrShape", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrShapeList( + _ a: [TensorShape?] +) { + let nOutputs = 0 + let op = makeOp("AttrShapeList", nOutputs) + op.updateAttribute("a", a) + op.execute() +} + +@inlinable @inline(__always) +public static func attrTypeDefault( + _ a: Tensor +) { + let nOutputs = 0 + let op = makeOp("AttrTypeDefault", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.execute() +} + +/// Produces a visualization of audio data over time. +/// +/// Spectrograms are a standard way of representing audio information as a series of +/// slices of frequency information, one slice for each window of time. By joining +/// these together into a sequence, they form a distinctive fingerprint of the sound +/// over time. +/// +/// This op expects to receive audio data as an input, stored as floats in the range +/// -1 to 1, together with a window width in samples, and a stride specifying how +/// far to move the window between slices. From this it generates a three +/// dimensional output. The lowest dimension has an amplitude value for each +/// frequency during that time slice. The next dimension is time, with successive +/// frequency slices. The final dimension is for the channels in the input, so a +/// stereo audio input would have two here for example. +/// +/// This means the layout when converted and saved as an image is rotated 90 degrees +/// clockwise from a typical spectrogram. Time is descending down the Y axis, and +/// the frequency decreases from left to right. +/// +/// Each value in the result represents the square root of the sum of the real and +/// imaginary parts of an FFT on the current window of samples. In this way, the +/// lowest dimension represents the power of each frequency in the current window, +/// and adjacent windows are concatenated in the next dimension. +/// +/// To get a more intuitive and visual look at what this operation does, you can run +/// tensorflow/examples/wav_to_spectrogram to read in an audio file and save out the +/// resulting spectrogram as a PNG image. +/// +/// - Parameter input: Float representation of audio data. +/// +/// - Attrs: +/// - window_size: How wide the input window is in samples. For the highest efficiency +/// this should be a power of two, but other values are accepted. +/// - stride: How widely apart the center of adjacent sample windows should be. +/// - magnitude_squared: Whether to return the squared magnitude or just the +/// magnitude. Using squared magnitude can avoid extra calculations. +/// +/// - Output spectrogram: 3D representation of the audio frequencies as an image. +@inlinable @inline(__always) +public static func audioSpectrogram( + _ input: Tensor, + windowSize: Int64, + stride: Int64, + magnitudeSquared: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AudioSpectrogram", nOutputs) + op.updateAttribute("window_size", windowSize) + op.updateAttribute("stride", stride) + op.updateAttribute("magnitude_squared", magnitudeSquared) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Outputs a `Summary` protocol buffer with audio. +/// +/// The summary has up to `max_outputs` summary values containing audio. The +/// audio is built from `tensor` which must be 3-D with shape `[batch_size, +/// frames, channels]` or 2-D with shape `[batch_size, frames]`. The values are +/// assumed to be in the range of `[-1.0, 1.0]` with a sample rate of `sample_rate`. +/// +/// The `tag` argument is a scalar `Tensor` of type `string`. It is used to +/// build the `tag` of the summary values: +/// +/// * If `max_outputs` is 1, the summary value tag is '*tag*/audio'. +/// * If `max_outputs` is greater than 1, the summary value tags are +/// generated sequentially as '*tag*/audio/0', '*tag*/audio/1', etc. +/// +/// - Parameters: +/// - tag: Scalar. Used to build the `tag` attribute of the summary values. +/// - tensor: 2-D of shape `[batch_size, frames]`. +/// +/// - Attrs: +/// - sample_rate: The sample rate of the signal in hertz. +/// - max_outputs: Max number of batch elements to generate audio for. +/// +/// - Output summary: Scalar. Serialized `Summary` protocol buffer. +@inlinable @inline(__always) +public static func audioSummary( + tag: StringTensor, + _ tensor: Tensor, + sampleRate: Double, + maxOutputs: Int64 = 3 +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("AudioSummary", nOutputs) + op.updateAttribute("sample_rate", sampleRate) + op.updateAttribute("max_outputs", maxOutputs) + op.addInput(tag) + op.addInput(tensor) + return op.execute(Int(1)) +} + +/// Outputs a `Summary` protocol buffer with audio. +/// +/// The summary has up to `max_outputs` summary values containing audio. The +/// audio is built from `tensor` which must be 3-D with shape `[batch_size, +/// frames, channels]` or 2-D with shape `[batch_size, frames]`. The values are +/// assumed to be in the range of `[-1.0, 1.0]` with a sample rate of `sample_rate`. +/// +/// The `tag` argument is a scalar `Tensor` of type `string`. It is used to +/// build the `tag` of the summary values: +/// +/// * If `max_outputs` is 1, the summary value tag is '*tag*/audio'. +/// * If `max_outputs` is greater than 1, the summary value tags are +/// generated sequentially as '*tag*/audio/0', '*tag*/audio/1', etc. +/// +/// - Parameters: +/// - tag: Scalar. Used to build the `tag` attribute of the summary values. +/// - tensor: 2-D of shape `[batch_size, frames]`. +/// - sample_rate: The sample rate of the signal in hertz. +/// +/// - Attr max_outputs: Max number of batch elements to generate audio for. +/// +/// - Output summary: Scalar. Serialized `Summary` protocol buffer. +@inlinable @inline(__always) +public static func audioSummaryV2( + tag: StringTensor, + _ tensor: Tensor, + sampleRate: Tensor, + maxOutputs: Int64 = 3 +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("AudioSummaryV2", nOutputs) + op.updateAttribute("max_outputs", maxOutputs) + op.addInput(tag) + op.addInput(tensor) + op.addInput(sampleRate) + return op.execute(Int(1)) +} + +/// Performs average pooling on the input. +/// +/// Each entry in `output` is the mean of the corresponding size `ksize` +/// window in `value`. +/// +/// - Parameter value: 4-D with shape `[batch, height, width, channels]`. +/// +/// - Attrs: +/// - ksize: The size of the sliding window for each dimension of `value`. +/// - strides: The stride of the sliding window for each dimension of `value`. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// +/// - Output output: The average pooled output tensor. +@inlinable @inline(__always) +public static func avgPool( + value: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AvgPool", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + return op.execute(Int(1)) +} + +/// Performs 3D average pooling on the input. +/// +/// - Parameter input: Shape `[batch, depth, rows, cols, channels]` tensor to pool over. +/// +/// - Attrs: +/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of +/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. +/// +/// - Output output: The average pooled output tensor. +@inlinable @inline(__always) +public static func avgPool3D( + _ input: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AvgPool3D", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Computes gradients of average pooling function. +/// +/// - Parameters: +/// - orig_input_shape: The original input dimensions. +/// - grad: Output backprop of shape `[batch, depth, rows, cols, channels]`. +/// +/// - Attrs: +/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of +/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. +/// +/// - Output output: The backprop for input. +@inlinable @inline(__always) +public static func avgPool3DGrad( + origInputShape: Tensor, + grad: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AvgPool3DGrad", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInputShape) + op.addInput(grad) + return op.execute(Int(1)) +} + +/// Computes gradients of the average pooling function. +/// +/// - Parameters: +/// - orig_input_shape: 1-D. Shape of the original input to `avg_pool`. +/// - grad: 4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. +/// the output of `avg_pool`. +/// +/// - Attrs: +/// - ksize: The size of the sliding window for each dimension of the input. +/// - strides: The stride of the sliding window for each dimension of the input. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// +/// - Output output: 4-D. Gradients w.r.t. the input of `avg_pool`. +@inlinable @inline(__always) +public static func avgPoolGrad( + origInputShape: Tensor, + grad: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("AvgPoolGrad", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInputShape) + op.addInput(grad) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func b( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("B", nOutputs) + + return op.execute(Int(1)) +} + +/// Batches all input tensors nondeterministically. +/// +/// When many instances of this Op are being run concurrently with the same +/// container/shared_name in the same device, some will output zero-shaped Tensors +/// and others will output Tensors of size up to max_batch_size. +/// +/// All Tensors in in_tensors are batched together (so, for example, labels and +/// features should be batched with a single instance of this operation. +/// +/// Each invocation of batch emits an `id` scalar which will be used to identify +/// this particular invocation when doing unbatch or its gradient. +/// +/// Each op which emits a non-empty batch will also emit a non-empty batch_index +/// Tensor, which, is a [K, 3] matrix where each row contains the invocation's id, +/// start, and length of elements of each set of Tensors present in batched_tensors. +/// +/// Batched tensors are concatenated along the first dimension, and all tensors in +/// in_tensors must have the first dimension of the same size. +/// +/// in_tensors: The tensors to be batched. +/// num_batch_threads: Number of scheduling threads for processing batches of work. +/// Determines the number of batches processed in parallel. +/// max_batch_size: Batch sizes will never be bigger than this. +/// batch_timeout_micros: Maximum number of microseconds to wait before outputting +/// an incomplete batch. +/// allowed_batch_sizes: Optional list of allowed batch sizes. If left empty, does +/// nothing. Otherwise, supplies a list of batch sizes, causing the op to pad +/// batches up to one of those sizes. The entries must increase monotonically, and +/// the final entry must equal max_batch_size. +/// grad_timeout_micros: The timeout to use for the gradient. See Unbatch. +/// batched_tensors: Either empty tensors or a batch of concatenated Tensors. +/// batch_index: If out_tensors is non-empty, has information to invert it. +/// container: Controls the scope of sharing of this batch. +/// id: always contains a scalar with a unique ID for this invocation of Batch. +/// shared_name: Concurrently running instances of batch in the same device with the +/// same container and shared_name will batch their elements together. If left +/// empty, the op name will be used as the shared name. +/// T: the types of tensors to be batched. +@inlinable @inline(__always) +public static func batch( + inTensors: T, + numBatchThreads: Int64, + maxBatchSize: Int64, + maxEnqueuedBatches: Int64 = 10, + batchTimeoutMicros: Int64, + allowedBatchSizes: [Int32], + gradTimeoutMicros: Int64, + container: String, + sharedName: String, + batchingQueue: String +) -> (batchedTensors: T, batchIndex: Tensor, id: Tensor) { + let nOutputs = Int(inTensors._typeList.count) + Int(1) + Int(1) + let op = makeOp("Batch", nOutputs) + op.updateAttribute("num_batch_threads", numBatchThreads) + op.updateAttribute("max_batch_size", maxBatchSize) + op.updateAttribute("max_enqueued_batches", maxEnqueuedBatches) + op.updateAttribute("batch_timeout_micros", batchTimeoutMicros) + op.updateAttribute("allowed_batch_sizes", allowedBatchSizes) + op.updateAttribute("grad_timeout_micros", gradTimeoutMicros) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("batching_queue", batchingQueue) + op.updateAttribute("T", inTensors._typeList) + op.addInputList(inTensors) + return op.execute(Int(inTensors._typeList.count), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func batchCholesky( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchCholesky", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func batchCholeskyGrad( + l: Tensor, + grad: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchCholeskyGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(l) + op.addInput(grad) + return op.execute(Int(1)) +} + +/// Creates a dataset that batches `batch_size` elements from `input_dataset`. +/// +/// - Parameter batch_size: A scalar representing the number of elements to accumulate in a +/// batch. +@inlinable @inline(__always) +public static func batchDataset( + inputDataset: VariantHandle, + batchSize: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("BatchDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(batchSize) + return op.execute(Int(1)) +} + +/// Creates a dataset that batches `batch_size` elements from `input_dataset`. +/// +/// - Parameters: +/// - batch_size: A scalar representing the number of elements to accumulate in a batch. +/// - drop_remainder: A scalar representing whether the last batch should be dropped in case its size +/// is smaller than desired. +@inlinable @inline(__always) +public static func batchDatasetV2( + inputDataset: VariantHandle, + batchSize: Tensor, + dropRemainder: Tensor, + parallelCopy: Bool = false, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("BatchDatasetV2", nOutputs) + op.updateAttribute("parallel_copy", parallelCopy) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(batchSize) + op.addInput(dropRemainder) + return op.execute(Int(1)) +} + +/// Batches all the inputs tensors to the computation done by the function. +/// +/// So, for example, in the following code +/// +/// ```python +/// +/// # This input will be captured. +/// y = tf.placeholder_with_default(1.0, shape=[]) +/// +/// @tf.Defun(tf.float32) +/// def computation(a): +/// return tf.matmul(a, a) + y +/// +/// b = gen_batch_ops.batch_function( +/// f=computation +/// in_tensors=[a], +/// captured_tensors=computation.captured_inputs, +/// Tout=[o.type for o in computation.definition.signature.output_arg], +/// num_batch_threads=1, +/// max_batch_size=10, +/// batch_timeout_micros=100000, # 100ms +/// allowed_batch_sizes=[3, 10], +/// batching_queue="") +/// +/// If more than one session.run call is simultaneously trying to compute `b` +/// the values of `a` will be gathered, non-deterministically concatenated +/// along the first axis, and only one thread will run the computation. +/// +/// Assumes that all arguments of the function are Tensors which will be batched +/// along their first dimension. +/// +/// Arguments that are captured, are not batched. The session.run call which does +/// the concatenation, will use the values of the captured tensors available to it. +/// Therefore, typical uses of captured tensors should involve values which remain +/// unchanged across session.run calls. Inference is a good example of this. +/// +/// SparseTensor is not supported. The return value of the decorated function +/// must be a Tensor or a list/tuple of Tensors. +/// +/// - Parameters: +/// - in_tensors: The tensors to be batched. +/// - captured_tensors: The tensors which are captured in the function, and don't need +/// to be batched. +/// +/// - Attrs: +/// - num_batch_threads: Number of scheduling threads for processing batches of work. +/// Determines the number of batches processed in parallel. +/// - max_batch_size: Batch sizes will never be bigger than this. +/// - batch_timeout_micros: Maximum number of microseconds to wait before outputting +/// an incomplete batch. +/// - max_enqueued_batches: Maximum number of batches enqueued. Default: 10. +/// - allowed_batch_sizes: Optional list of allowed batch sizes. If left empty, does +/// nothing. Otherwise, supplies a list of batch sizes, causing the op to pad +/// batches up to one of those sizes. The entries must increase monotonically, and +/// the final entry must equal max_batch_size. +/// - container: Controls the scope of sharing of this batch. +/// - shared_name: Concurrently running instances of batch in the same device with the +/// same container and shared_name will batch their elements together. If left +/// empty, the op name will be used as the shared name. +/// - Tin: the types of tensors to be batched. +/// - Tcaptured: the types of the captured tensors. +/// - Tout: the types of the output tensors. +/// +/// - Output out_tensors: The output tensors. +@inlinable @inline(__always) +public static func batchFunction< + FIn: TensorGroup, + FOut: TensorGroup, + Tin: TensorArrayProtocol, + Tcaptured: TensorArrayProtocol, + Tout: TensorGroup +>( + inTensors: Tin, + capturedTensors: Tcaptured, + f: (FIn) -> FOut, + numBatchThreads: Int64, + maxBatchSize: Int64, + batchTimeoutMicros: Int64, + maxEnqueuedBatches: Int64 = 10, + allowedBatchSizes: [Int32], + container: String, + sharedName: String, + batchingQueue: String +) -> Tout { + let nOutputs = Int(Tout._typeList.count) + let op = makeOp("BatchFunction", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("num_batch_threads", numBatchThreads) + op.updateAttribute("max_batch_size", maxBatchSize) + op.updateAttribute("batch_timeout_micros", batchTimeoutMicros) + op.updateAttribute("max_enqueued_batches", maxEnqueuedBatches) + op.updateAttribute("allowed_batch_sizes", allowedBatchSizes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("batching_queue", batchingQueue) + op.updateAttribute("Tin", inTensors._typeList) + op.updateAttribute("Tcaptured", capturedTensors._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.addInputList(inTensors) + op.addInputList(capturedTensors) + return op.execute(Int(Tout._typeList.count)) +} + +/// Multiplies slices of two tensors in batches. +/// +/// Multiplies all slices of `Tensor` `x` and `y` (each slice can be +/// viewed as an element of a batch), and arranges the individual results +/// in a single output tensor of the same batch size. Each of the +/// individual slices can optionally be adjointed (to adjoint a matrix +/// means to transpose and conjugate it) before multiplication by setting +/// the `adj_x` or `adj_y` flag to `True`, which are by default `False`. +/// +/// The input tensors `x` and `y` are 2-D or higher with shape `[..., r_x, c_x]` +/// and `[..., r_y, c_y]`. +/// +/// The output tensor is 2-D or higher with shape `[..., r_o, c_o]`, where: +/// +/// r_o = c_x if adj_x else r_x +/// c_o = r_y if adj_y else c_y +/// +/// It is computed as: +/// +/// output[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :]) +/// +/// - Parameters: +/// - x: 2-D or higher with shape `[..., r_x, c_x]`. +/// - y: 2-D or higher with shape `[..., r_y, c_y]`. +/// +/// - Attrs: +/// - adj_x: If `True`, adjoint the slices of `x`. Defaults to `False`. +/// - adj_y: If `True`, adjoint the slices of `y`. Defaults to `False`. +/// +/// - Output output: 3-D or higher with shape `[..., r_o, c_o]` +@inlinable @inline(__always) +public static func batchMatMul( + _ x: Tensor, + _ y: Tensor, + adjX: Bool = false, + adjY: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchMatMul", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("adj_x", adjX) + op.updateAttribute("adj_y", adjY) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Multiplies slices of two tensors in batches. +/// +/// Multiplies all slices of `Tensor` `x` and `y` (each slice can be +/// viewed as an element of a batch), and arranges the individual results +/// in a single output tensor of the same batch size. Each of the +/// individual slices can optionally be adjointed (to adjoint a matrix +/// means to transpose and conjugate it) before multiplication by setting +/// the `adj_x` or `adj_y` flag to `True`, which are by default `False`. +/// +/// The input tensors `x` and `y` are 2-D or higher with shape `[..., r_x, c_x]` +/// and `[..., r_y, c_y]`. +/// +/// The output tensor is 2-D or higher with shape `[..., r_o, c_o]`, where: +/// +/// r_o = c_x if adj_x else r_x +/// c_o = r_y if adj_y else c_y +/// +/// It is computed as: +/// +/// output[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :]) +/// +/// *NOTE*: `BatchMatMulV2` supports broadcasting in the batch dimensions. More +/// about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html). +/// +/// +/// - Parameters: +/// - x: 2-D or higher with shape `[..., r_x, c_x]`. +/// - y: 2-D or higher with shape `[..., r_y, c_y]`. +/// +/// - Attrs: +/// - adj_x: If `True`, adjoint the slices of `x`. Defaults to `False`. +/// - adj_y: If `True`, adjoint the slices of `y`. Defaults to `False`. +/// +/// - Output output: 3-D or higher with shape `[..., r_o, c_o]` +@inlinable @inline(__always) +public static func batchMatMulV2( + _ x: Tensor, + _ y: Tensor, + adjX: Bool = false, + adjY: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchMatMulV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("adj_x", adjX) + op.updateAttribute("adj_y", adjY) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func batchMatrixBandPart( + _ input: Tensor, + numLower: Tensor, + numUpper: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchMatrixBandPart", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(numLower) + op.addInput(numUpper) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func batchMatrixDeterminant( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchMatrixDeterminant", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func batchMatrixDiag( + diagonal: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchMatrixDiag", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(diagonal) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func batchMatrixDiagPart( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchMatrixDiagPart", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func batchMatrixInverse( + _ input: Tensor, + adjoint: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchMatrixInverse", nOutputs) + op.updateAttribute("adjoint", adjoint) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func batchMatrixSetDiag( + _ input: Tensor, + diagonal: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchMatrixSetDiag", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(diagonal) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func batchMatrixSolve( + matrix: Tensor, + rhs: Tensor, + adjoint: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchMatrixSolve", nOutputs) + op.updateAttribute("adjoint", adjoint) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(matrix) + op.addInput(rhs) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func batchMatrixSolveLs( + matrix: Tensor, + rhs: Tensor, + l2Regularizer: Tensor, + fast: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchMatrixSolveLs", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("fast", fast) + op.addInput(matrix) + op.addInput(rhs) + op.addInput(l2Regularizer) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func batchMatrixTriangularSolve( + matrix: Tensor, + rhs: Tensor, + lower: Bool = true, + adjoint: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchMatrixTriangularSolve", nOutputs) + op.updateAttribute("lower", lower) + op.updateAttribute("adjoint", adjoint) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(matrix) + op.addInput(rhs) + return op.execute(Int(1)) +} + +/// Batch normalization. +/// +/// This op is deprecated. Prefer `tf.nn.batch_normalization`. +/// +/// - Parameters: +/// - t: A 4D input Tensor. +/// - m: A 1D mean Tensor with size matching the last dimension of t. +/// This is the first output from tf.nn.moments, +/// or a saved moving average thereof. +/// - v: A 1D variance Tensor with size matching the last dimension of t. +/// This is the second output from tf.nn.moments, +/// or a saved moving average thereof. +/// - beta: A 1D beta Tensor with size matching the last dimension of t. +/// An offset to be added to the normalized tensor. +/// - gamma: A 1D gamma Tensor with size matching the last dimension of t. +/// If "scale_after_normalization" is true, this tensor will be multiplied +/// with the normalized tensor. +/// +/// - Attrs: +/// - variance_epsilon: A small float number to avoid dividing by 0. +/// - scale_after_normalization: A bool indicating whether the resulted tensor +/// needs to be multiplied with gamma. +@inlinable @inline(__always) +public static func batchNormWithGlobalNormalization( + t: Tensor, + m: Tensor, + v: Tensor, + beta: Tensor, + gamma: Tensor, + varianceEpsilon: Double, + scaleAfterNormalization: Bool +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchNormWithGlobalNormalization", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("variance_epsilon", varianceEpsilon) + op.updateAttribute("scale_after_normalization", scaleAfterNormalization) + op.addInput(t) + op.addInput(m) + op.addInput(v) + op.addInput(beta) + op.addInput(gamma) + return op.execute(Int(1)) +} + +/// Gradients for batch normalization. +/// +/// This op is deprecated. See `tf.nn.batch_normalization`. +/// +/// - Parameters: +/// - t: A 4D input Tensor. +/// - m: A 1D mean Tensor with size matching the last dimension of t. +/// This is the first output from tf.nn.moments, +/// or a saved moving average thereof. +/// - v: A 1D variance Tensor with size matching the last dimension of t. +/// This is the second output from tf.nn.moments, +/// or a saved moving average thereof. +/// - gamma: A 1D gamma Tensor with size matching the last dimension of t. +/// If "scale_after_normalization" is true, this Tensor will be multiplied +/// with the normalized Tensor. +/// - backprop: 4D backprop Tensor. +/// +/// - Attrs: +/// - variance_epsilon: A small float number to avoid dividing by 0. +/// - scale_after_normalization: A bool indicating whether the resulted tensor +/// needs to be multiplied with gamma. +/// +/// - Outputs: +/// - dx: 4D backprop tensor for input. +/// - dm: 1D backprop tensor for mean. +/// - dv: 1D backprop tensor for variance. +/// - db: 1D backprop tensor for beta. +/// - dg: 1D backprop tensor for gamma. +@inlinable @inline(__always) +public static func batchNormWithGlobalNormalizationGrad( + t: Tensor, + m: Tensor, + v: Tensor, + gamma: Tensor, + backprop: Tensor, + varianceEpsilon: Double, + scaleAfterNormalization: Bool +) -> (dx: Tensor, dm: Tensor, dv: Tensor, db: Tensor, dg: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("BatchNormWithGlobalNormalizationGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("variance_epsilon", varianceEpsilon) + op.updateAttribute("scale_after_normalization", scaleAfterNormalization) + op.addInput(t) + op.addInput(m) + op.addInput(v) + op.addInput(gamma) + op.addInput(backprop) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func batchSelfAdjointEig( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchSelfAdjointEig", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func batchSelfAdjointEigV2( + _ input: Tensor, + computeV: Bool = true +) -> (e: Tensor, v: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("BatchSelfAdjointEigV2", nOutputs) + op.updateAttribute("compute_v", computeV) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func batchSvd( + _ input: Tensor, + computeUv: Bool = true, + fullMatrices: Bool = false +) -> (s: Tensor, u: Tensor, v: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("BatchSvd", nOutputs) + op.updateAttribute("compute_uv", computeUv) + op.updateAttribute("full_matrices", fullMatrices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// BatchToSpace for 4-D tensors of type T. +/// +/// This is a legacy version of the more general BatchToSpaceND. +/// +/// Rearranges (permutes) data from batch into blocks of spatial data, followed by +/// cropping. This is the reverse transformation of SpaceToBatch. More specifically, +/// this op outputs a copy of the input tensor where values from the `batch` +/// dimension are moved in spatial blocks to the `height` and `width` dimensions, +/// followed by cropping along the `height` and `width` dimensions. +/// +/// - Parameters: +/// - input: 4-D tensor with shape +/// `[batch*block_size*block_size, height_pad/block_size, width_pad/block_size, +/// depth]`. Note that the batch size of the input tensor must be divisible by +/// `block_size * block_size`. +/// - crops: 2-D tensor of non-negative integers with shape `[2, 2]`. It specifies +/// how many elements to crop from the intermediate result across the spatial +/// dimensions as follows: +/// +/// crops = [[crop_top, crop_bottom], [crop_left, crop_right]] +/// +/// - Output output: 4-D with shape `[batch, height, width, depth]`, where: +/// +/// height = height_pad - crop_top - crop_bottom +/// width = width_pad - crop_left - crop_right +/// +/// The attr `block_size` must be greater than one. It indicates the block size. +/// +/// Some examples: +/// +/// (1) For the following input of shape `[4, 1, 1, 1]` and block_size of 2: +/// +/// ``` +/// [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] +/// ``` +/// +/// The output tensor has shape `[1, 2, 2, 1]` and value: +/// +/// ``` +/// x = [[[[1], [2]], [[3], [4]]]] +/// ``` +/// +/// (2) For the following input of shape `[4, 1, 1, 3]` and block_size of 2: +/// +/// ``` +/// [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] +/// ``` +/// +/// The output tensor has shape `[1, 2, 2, 3]` and value: +/// +/// ``` +/// x = [[[[1, 2, 3], [4, 5, 6]], +/// [[7, 8, 9], [10, 11, 12]]]] +/// ``` +/// +/// (3) For the following input of shape `[4, 2, 2, 1]` and block_size of 2: +/// +/// ``` +/// x = [[[[1], [3]], [[9], [11]]], +/// [[[2], [4]], [[10], [12]]], +/// [[[5], [7]], [[13], [15]]], +/// [[[6], [8]], [[14], [16]]]] +/// ``` +/// +/// The output tensor has shape `[1, 4, 4, 1]` and value: +/// +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]], +/// [[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` +/// +/// (4) For the following input of shape `[8, 1, 2, 1]` and block_size of 2: +/// +/// ``` +/// x = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]], +/// [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]] +/// ``` +/// +/// The output tensor has shape `[2, 2, 4, 1]` and value: +/// +/// ``` +/// x = [[[[1], [3]], [[5], [7]]], +/// [[[2], [4]], [[10], [12]]], +/// [[[5], [7]], [[13], [15]]], +/// [[[6], [8]], [[14], [16]]]] +/// ``` +@inlinable @inline(__always) +public static func batchToSpace< + T: TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + crops: Tensor, + blockSize: Int64 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchToSpace", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("block_size", blockSize) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(crops) + return op.execute(Int(1)) +} + +/// BatchToSpace for N-D tensors of type T. +/// +/// This operation reshapes the "batch" dimension 0 into `M + 1` dimensions of shape +/// `block_shape + [batch]`, interleaves these blocks back into the grid defined by +/// the spatial dimensions `[1, ..., M]`, to obtain a result with the same rank as +/// the input. The spatial dimensions of this intermediate result are then +/// optionally cropped according to `crops` to produce the output. This is the +/// reverse of SpaceToBatch. See below for a precise description. +/// +/// - Parameters: +/// - input: N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`, +/// where spatial_shape has M dimensions. +/// - block_shape: 1-D with shape `[M]`, all values must be >= 1. +/// - crops: 2-D with shape `[M, 2]`, all values must be >= 0. +/// `crops[i] = [crop_start, crop_end]` specifies the amount to crop from input +/// dimension `i + 1`, which corresponds to spatial dimension `i`. It is +/// required that +/// `crop_start[i] + crop_end[i] <= block_shape[i] * input_shape[i + 1]`. +/// +/// This operation is equivalent to the following steps: +/// +/// 1. Reshape `input` to `reshaped` of shape: +/// [block_shape[0], ..., block_shape[M-1], +/// batch / prod(block_shape), +/// input_shape[1], ..., input_shape[N-1]] +/// +/// 2. Permute dimensions of `reshaped` to produce `permuted` of shape +/// [batch / prod(block_shape), +/// +/// input_shape[1], block_shape[0], +/// ..., +/// input_shape[M], block_shape[M-1], +/// +/// input_shape[M+1], ..., input_shape[N-1]] +/// +/// 3. Reshape `permuted` to produce `reshaped_permuted` of shape +/// [batch / prod(block_shape), +/// +/// input_shape[1] * block_shape[0], +/// ..., +/// input_shape[M] * block_shape[M-1], +/// +/// input_shape[M+1], +/// ..., +/// input_shape[N-1]] +/// +/// 4. Crop the start and end of dimensions `[1, ..., M]` of +/// `reshaped_permuted` according to `crops` to produce the output of shape: +/// [batch / prod(block_shape), +/// +/// input_shape[1] * block_shape[0] - crops[0,0] - crops[0,1], +/// ..., +/// input_shape[M] * block_shape[M-1] - crops[M-1,0] - crops[M-1,1], +/// +/// input_shape[M+1], ..., input_shape[N-1]] +/// +/// Some examples: +/// +/// (1) For the following input of shape `[4, 1, 1, 1]`, `block_shape = [2, 2]`, and +/// `crops = [[0, 0], [0, 0]]`: +/// +/// ``` +/// [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] +/// ``` +/// +/// The output tensor has shape `[1, 2, 2, 1]` and value: +/// +/// ``` +/// x = [[[[1], [2]], [[3], [4]]]] +/// ``` +/// +/// (2) For the following input of shape `[4, 1, 1, 3]`, `block_shape = [2, 2]`, and +/// `crops = [[0, 0], [0, 0]]`: +/// +/// ``` +/// [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] +/// ``` +/// +/// The output tensor has shape `[1, 2, 2, 3]` and value: +/// +/// ``` +/// x = [[[[1, 2, 3], [4, 5, 6]], +/// [[7, 8, 9], [10, 11, 12]]]] +/// ``` +/// +/// (3) For the following input of shape `[4, 2, 2, 1]`, `block_shape = [2, 2]`, and +/// `crops = [[0, 0], [0, 0]]`: +/// +/// ``` +/// x = [[[[1], [3]], [[9], [11]]], +/// [[[2], [4]], [[10], [12]]], +/// [[[5], [7]], [[13], [15]]], +/// [[[6], [8]], [[14], [16]]]] +/// ``` +/// +/// The output tensor has shape `[1, 4, 4, 1]` and value: +/// +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]], +/// [[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` +/// +/// (4) For the following input of shape `[8, 1, 3, 1]`, `block_shape = [2, 2]`, and +/// `crops = [[0, 0], [2, 0]]`: +/// +/// ``` +/// x = [[[[0], [1], [3]]], [[[0], [9], [11]]], +/// [[[0], [2], [4]]], [[[0], [10], [12]]], +/// [[[0], [5], [7]]], [[[0], [13], [15]]], +/// [[[0], [6], [8]]], [[[0], [14], [16]]]] +/// ``` +/// +/// The output tensor has shape `[2, 2, 4, 1]` and value: +/// +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]]], +/// [[[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` +@inlinable @inline(__always) +public static func batchToSpaceND< + T: TensorFlowScalar, + TblockShape: BinaryInteger & TensorFlowScalar, + Tcrops: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + blockShape: Tensor, + crops: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchToSpaceND", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tblock_shape", TblockShape.tensorFlowDataType) + op.updateAttribute("Tcrops", Tcrops.tensorFlowDataType) + op.addInput(input) + op.addInput(blockShape) + op.addInput(crops) + return op.execute(Int(1)) +} + +/// Computes the Bessel i0e function of `x` element-wise. +/// +/// Exponentially scaled modified Bessel function of order 0 defined as +/// `bessel_i0e(x) = exp(-abs(x)) bessel_i0(x)`. +/// +/// This function is faster and numerically stabler than `bessel_i0(x)`. +@inlinable @inline(__always) +public static func besselI0e( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BesselI0e", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the Bessel i1e function of `x` element-wise. +/// +/// Exponentially scaled modified Bessel function of order 0 defined as +/// `bessel_i1e(x) = exp(-abs(x)) bessel_i1(x)`. +/// +/// This function is faster and numerically stabler than `bessel_i1(x)`. +@inlinable @inline(__always) +public static func besselI1e( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BesselI1e", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Compute the regularized incomplete beta integral \\(I_x(a, b)\\). +/// +/// The regularized incomplete beta integral is defined as: +/// +/// +/// \\(I_x(a, b) = \frac{B(x; a, b)}{B(a, b)}\\) +/// +/// where +/// +/// +/// \\(B(x; a, b) = \int_0^x t^{a-1} (1 - t)^{b-1} dt\\) +/// +/// +/// is the incomplete beta function and \\(B(a, b)\\) is the *complete* +/// beta function. +@inlinable @inline(__always) +public static func betainc( + _ a: Tensor, + _ b: Tensor, + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Betainc", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(b) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Adds `bias` to `value`. +/// +/// This is a special case of `tf.add` where `bias` is restricted to be 1-D. +/// Broadcasting is supported, so `value` may have any number of dimensions. +/// +/// - Parameters: +/// - value: Any number of dimensions. +/// - bias: 1-D with size the last dimension of `value`. +/// +/// - Attr data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the bias tensor will be added to the last dimension +/// of the value tensor. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// The tensor will be added to "in_channels", the third-to-the-last +/// dimension. +/// +/// - Output output: Broadcasted sum of `value` and `bias`. +@inlinable @inline(__always) +public static func biasAdd( + value: Tensor, + bias: Tensor, + dataFormat: DataFormat = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BiasAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("data_format", dataFormat.cName) + op.addInput(value) + op.addInput(bias) + return op.execute(Int(1)) +} + +/// The backward operation for "BiasAdd" on the "bias" tensor. +/// +/// It accumulates all the values from out_backprop into the feature dimension. +/// For NHWC data format, the feature dimension is the last. For NCHW data format, +/// the feature dimension is the third-to-last. +/// +/// - Parameter out_backprop: Any number of dimensions. +/// +/// - Attr data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the bias tensor will be added to the last dimension +/// of the value tensor. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// The tensor will be added to "in_channels", the third-to-the-last +/// dimension. +/// +/// - Output output: 1-D with size the feature dimension of `out_backprop`. +@inlinable @inline(__always) +public static func biasAddGrad( + outBackprop: Tensor, + dataFormat: DataFormat = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BiasAddGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("data_format", dataFormat.cName) + op.addInput(outBackprop) + return op.execute(Int(1)) +} + +/// Adds `bias` to `value`. +/// +/// This is a deprecated version of BiasAdd and will be soon removed. +/// +/// This is a special case of `tf.add` where `bias` is restricted to be 1-D. +/// Broadcasting is supported, so `value` may have any number of dimensions. +/// +/// - Parameters: +/// - value: Any number of dimensions. +/// - bias: 1-D with size the last dimension of `value`. +/// +/// - Output output: Broadcasted sum of `value` and `bias`. +@inlinable @inline(__always) +public static func biasAddV1( + value: Tensor, + bias: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BiasAddV1", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + op.addInput(bias) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func binary( + _ a: Tensor, + _ b: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Binary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(b) + return op.execute(Int(1)) +} + +/// Counts the number of occurrences of each value in an integer array. +/// +/// Outputs a vector with length `size` and the same dtype as `weights`. If +/// `weights` are empty, then index `i` stores the number of times the value `i` is +/// counted in `arr`. If `weights` are non-empty, then index `i` stores the sum of +/// the value in `weights` at each index where the corresponding value in `arr` is +/// `i`. +/// +/// Values in `arr` outside of the range [0, size) are ignored. +/// +/// - Parameters: +/// - arr: int32 `Tensor`. +/// - size: non-negative int32 scalar `Tensor`. +/// - weights: is an int32, int64, float32, or float64 `Tensor` with the same +/// shape as `arr`, or a length-0 `Tensor`, in which case it acts as all weights +/// equal to 1. +/// +/// - Output bins: 1D `Tensor` with length equal to `size`. The counts or summed weights for +/// each value in the range [0, size). +@inlinable @inline(__always) +public static func bincount( + arr: Tensor, + size: Tensor, + weights: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Bincount", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(arr) + op.addInput(size) + op.addInput(weights) + return op.execute(Int(1)) +} + +/// Bitcasts a tensor from one type to another without copying data. +/// +/// Given a tensor `input`, this operation returns a tensor that has the same buffer +/// data as `input` with datatype `type`. +/// +/// If the input datatype `T` is larger than the output datatype `type` then the +/// shape changes from [...] to [..., sizeof(`T`)/sizeof(`type`)]. +/// +/// If `T` is smaller than `type`, the operator requires that the rightmost +/// dimension be equal to sizeof(`type`)/sizeof(`T`). The shape then goes from +/// [..., sizeof(`type`)/sizeof(`T`)] to [...]. +/// +/// tf.bitcast() and tf.cast() work differently when real dtype is casted as a complex dtype +/// (e.g. tf.complex64 or tf.complex128) as tf.cast() make imaginary part 0 while tf.bitcast() +/// gives module error. +/// For example, +/// +/// Example 1: +/// ```python +/// >>> a = [1., 2., 3.] +/// >>> equality_bitcast = tf.bitcast(a,tf.complex128) +/// tensorflow.python.framework.errors_impl.InvalidArgumentError: Cannot bitcast from float to complex128: shape [3] [Op:Bitcast] +/// >>> equality_cast = tf.cast(a,tf.complex128) +/// >>> print(equality_cast) +/// tf.Tensor([1.+0.j 2.+0.j 3.+0.j], shape=(3,), dtype=complex128) +/// ``` +/// Example 2: +/// ```python +/// >>> tf.bitcast(tf.constant(0xffffffff, dtype=tf.uint32), tf.uint8) +/// +/// ``` +/// Example 3: +/// ```python +/// >>> x = [1., 2., 3.] +/// >>> y = [0., 2., 3.] +/// >>> equality= tf.equal(x,y) +/// >>> equality_cast = tf.cast(equality,tf.float32) +/// >>> equality_bitcast = tf.bitcast(equality_cast,tf.uint8) +/// >>> print(equality) +/// tf.Tensor([False True True], shape=(3,), dtype=bool) +/// >>> print(equality_cast) +/// tf.Tensor([0. 1. 1.], shape=(3,), dtype=float32) +/// >>> print(equality_bitcast) +/// tf.Tensor( +/// [[ 0 0 0 0] +/// [ 0 0 128 63] +/// [ 0 0 128 63]], shape=(3, 4), dtype=uint8) +/// ``` +/// +/// *NOTE*: Bitcast is implemented as a low-level cast, so machines with different +/// endian orderings will give different results. +@inlinable @inline(__always) +public static func bitcast< + T: Numeric & TensorFlowScalar, + Type: Numeric & TensorFlowScalar +>( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Bitcast", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("type", Type.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Elementwise computes the bitwise AND of `x` and `y`. +/// +/// The result will have those bits set, that are set in both `x` and `y`. The +/// computation is performed on the underlying representations of `x` and `y`. +@inlinable @inline(__always) +public static func bitwiseAnd( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BitwiseAnd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Elementwise computes the bitwise OR of `x` and `y`. +/// +/// The result will have those bits set, that are set in `x`, `y` or both. The +/// computation is performed on the underlying representations of `x` and `y`. +@inlinable @inline(__always) +public static func bitwiseOr( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BitwiseOr", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Elementwise computes the bitwise XOR of `x` and `y`. +/// +/// The result will have those bits set, that are different in `x` and `y`. The +/// computation is performed on the underlying representations of `x` and `y`. +@inlinable @inline(__always) +public static func bitwiseXor( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BitwiseXor", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Computes the LSTM cell forward propagation for all the time steps. +/// +/// This is equivalent to applying LSTMBlockCell in a loop, like so: +/// +/// ```python +/// for x1 in unpack(x): +/// i1, cs1, f1, o1, ci1, co1, h1 = LSTMBlock( +/// x1, cs_prev, h_prev, w, wci, wcf, wco, b) +/// cs_prev = cs1 +/// h_prev = h1 +/// i.append(i1) +/// cs.append(cs1) +/// f.append(f1) +/// o.append(o1) +/// ci.append(ci1) +/// co.append(co1) +/// h.append(h1) +/// return pack(i), pack(cs), pack(f), pack(o), pack(ci), pack(ch), pack(h) +/// ``` +/// +/// - Parameters: +/// - seq_len_max: Maximum time length actually used by this input. Outputs are padded +/// with zeros beyond this length. +/// - x: The sequence input to the LSTM, shape (timelen, batch_size, num_inputs). +/// - cs_prev: Value of the initial cell state. +/// - h_prev: Initial output of cell (to be used for peephole). +/// - w: The weight matrix. +/// - wci: The weight matrix for input gate peephole connection. +/// - wcf: The weight matrix for forget gate peephole connection. +/// - wco: The weight matrix for output gate peephole connection. +/// - b: The bias vector. +/// +/// - Attrs: +/// - forget_bias: The forget gate bias. +/// - cell_clip: Value to clip the 'cs' value to. +/// - use_peephole: Whether to use peephole weights. +/// +/// - Outputs: +/// - i: The input gate over the whole time sequence. +/// - cs: The cell state before the tanh over the whole time sequence. +/// - f: The forget gate over the whole time sequence. +/// - o: The output gate over the whole time sequence. +/// - ci: The cell input over the whole time sequence. +/// - co: The cell after the tanh over the whole time sequence. +/// - h: The output h vector over the whole time sequence. +@inlinable @inline(__always) +public static func blockLSTM( + seqLenMax: Tensor, + _ x: Tensor, + csPrev: Tensor, + hPrev: Tensor, + w: Tensor, + wci: Tensor, + wcf: Tensor, + wco: Tensor, + _ b: Tensor, + forgetBias: Double = 1, + cellClip: Double = 3, + usePeephole: Bool = false +) -> (i: Tensor, cs: Tensor, f: Tensor, o: Tensor, ci: Tensor, co: Tensor, h: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("BlockLSTM", nOutputs) + op.updateAttribute("forget_bias", forgetBias) + op.updateAttribute("cell_clip", cellClip) + op.updateAttribute("use_peephole", usePeephole) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(seqLenMax) + op.addInput(x) + op.addInput(csPrev) + op.addInput(hPrev) + op.addInput(w) + op.addInput(wci) + op.addInput(wcf) + op.addInput(wco) + op.addInput(b) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// Computes the LSTM cell backward propagation for the entire time sequence. +/// +/// This implementation is to be used in conjunction of LSTMBlock. +/// +/// - Parameters: +/// - seq_len_max: Maximum time length actually used by this input. Outputs are padded +/// with zeros beyond this length. +/// - x: The sequence input to the LSTM, shape (timelen, batch_size, num_inputs). +/// - cs_prev: Value of the initial cell state. +/// - h_prev: Initial output of cell (to be used for peephole). +/// - w: The weight matrix. +/// - wci: The weight matrix for input gate peephole connection. +/// - wcf: The weight matrix for forget gate peephole connection. +/// - wco: The weight matrix for output gate peephole connection. +/// - b: The bias vector. +/// - i: The input gate over the whole time sequence. +/// - cs: The cell state before the tanh over the whole time sequence. +/// - f: The forget gate over the whole time sequence. +/// - o: The output gate over the whole time sequence. +/// - ci: The cell input over the whole time sequence. +/// - co: The cell after the tanh over the whole time sequence. +/// - h: The output h vector over the whole time sequence. +/// - cs_grad: The current gradient of cs. +/// - h_grad: The gradient of h vector. +/// +/// - Attr use_peephole: Whether to use peephole weights. +/// +/// - Outputs: +/// - x_grad: The gradient of x to be back-propped. +/// - cs_prev_grad: The gradient of cs_prev to be back-propped. +/// - h_prev_grad: The gradient of h_prev to be back-propped. +/// - w_grad: The gradient for w to be back-propped. +/// - wci_grad: The gradient for wci to be back-propped. +/// - wcf_grad: The gradient for wcf to be back-propped. +/// - wco_grad: The gradient for wco to be back-propped. +/// - b_grad: The gradient for w to be back-propped. +@inlinable @inline(__always) +public static func blockLSTMGrad( + seqLenMax: Tensor, + _ x: Tensor, + csPrev: Tensor, + hPrev: Tensor, + w: Tensor, + wci: Tensor, + wcf: Tensor, + wco: Tensor, + _ b: Tensor, + i: Tensor, + cs: Tensor, + f: Tensor, + o: Tensor, + ci: Tensor, + co: Tensor, + h: Tensor, + csGrad: Tensor, + hGrad: Tensor, + usePeephole: Bool +) -> (xGrad: Tensor, csPrevGrad: Tensor, hPrevGrad: Tensor, wGrad: Tensor, wciGrad: Tensor, wcfGrad: Tensor, wcoGrad: Tensor, bGrad: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("BlockLSTMGrad", nOutputs) + op.updateAttribute("use_peephole", usePeephole) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(seqLenMax) + op.addInput(x) + op.addInput(csPrev) + op.addInput(hPrev) + op.addInput(w) + op.addInput(wci) + op.addInput(wcf) + op.addInput(wco) + op.addInput(b) + op.addInput(i) + op.addInput(cs) + op.addInput(f) + op.addInput(o) + op.addInput(ci) + op.addInput(co) + op.addInput(h) + op.addInput(csGrad) + op.addInput(hGrad) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// Aggregates the summary of accumulated stats for the batch. +/// +/// The summary stats contains gradients and hessians accumulated for each node, feature dimension id and bucket. +/// +/// - Parameters: +/// - node_ids: int32; Rank 1 Tensor containing node ids for each example, shape [batch_size]. +/// - gradients: float32; Rank 2 Tensor (shape=[batch_size, logits_dimension]) with gradients for each example. +/// - hessians: float32; Rank 2 Tensor (shape=[batch_size, hessian_dimension]) with hessians for each example. +/// - feature: int32; Rank 2 feature Tensors (shape=[batch_size, feature_dimension]). +/// +/// - Attrs: +/// - max_splits: int; the maximum number of splits possible in the whole tree. +/// - num_buckets: int; equals to the maximum possible value of bucketized feature. +/// +/// - Output stats_summary: output Rank 4 Tensor (shape=[splits, feature_dimension, buckets, logits_dimension + hessian_dimension]) +/// containing accumulated stats for each node, feature dimension and bucket. +@inlinable @inline(__always) +public static func boostedTreesAggregateStats( + nodeIds: Tensor, + gradients: Tensor, + hessians: Tensor, + feature: Tensor, + maxSplits: Int64, + numBuckets: Int64 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BoostedTreesAggregateStats", nOutputs) + op.updateAttribute("max_splits", maxSplits) + op.updateAttribute("num_buckets", numBuckets) + op.addInput(nodeIds) + op.addInput(gradients) + op.addInput(hessians) + op.addInput(feature) + return op.execute(Int(1)) +} + +/// Bucketize each feature based on bucket boundaries. +/// +/// An op that returns a list of float tensors, where each tensor represents the +/// bucketized values for a single feature. +/// +/// - Parameters: +/// - float_values: float; List of Rank 1 Tensor each containing float values for a single feature. +/// - bucket_boundaries: float; List of Rank 1 Tensors each containing the bucket boundaries for a single +/// feature. +/// +/// - Attr num_features: inferred int; number of features. +/// +/// - Output buckets: int; List of Rank 1 Tensors each containing the bucketized values for a single feature. +@inlinable @inline(__always) +public static func boostedTreesBucketize( + floatValues: [Tensor], + bucketBoundaries: [Tensor] +) -> [Tensor] { + let nOutputs = Int(floatValues.count) + let op = makeOp("BoostedTreesBucketize", nOutputs) + op.updateAttribute("num_features", floatValues.count) + op.addInputList(floatValues) + op.addInputList(bucketBoundaries) + return op.execute(Int(floatValues.count)) +} + +/// Calculates gains for each feature and returns the best possible split information for the feature. +/// +/// The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature. +/// +/// It is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split. +/// +/// In this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features). +/// +/// The output shapes are compatible in a way that the first dimension of all tensors are the same and equal to the number of possible split nodes for each feature. +/// +/// - Parameters: +/// - node_id_range: A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive). +/// - stats_summary: A Rank 4 tensor (#shape=[max_splits, feature_dims, bucket, stats_dims]) for accumulated stats summary (gradient/hessian) per node, per dimension, per buckets for each feature. +/// The first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used. +/// - l1: l1 regularization factor on leaf weights, per instance based. +/// - l2: l2 regularization factor on leaf weights, per instance based. +/// - tree_complexity: adjustment to the gain, per leaf based. +/// - min_node_weight: mininum avg of hessians in a node before required for the node to be considered for splitting. +/// +/// - Attrs: +/// - logits_dimension: The dimension of logit, i.e., number of classes. +/// - split_type: A string indicating if this Op should perform inequality split or equality split. +/// +/// - Outputs: +/// - node_ids: A Rank 1 tensors indicating possible split node ids for each feature. The length of the list is num_features, but each tensor has different size as each feature provides different possible nodes. See above for details like shapes and sizes. +/// - gains: A Rank 1 tensors indicating the best gains for each feature to split for certain nodes. See above for details like shapes and sizes. +/// - feature_dimensions: A Rank 1 tensors indicating the best feature dimension for each feature to split for certain nodes if the feature is multi-dimension. See above for details like shapes and sizes. +/// - thresholds: A Rank 1 tensors indicating the bucket id to compare with (as a threshold) for split in each node. See above for details like shapes and sizes. +/// - left_node_contribs: A Rank 2 tensors indicating the contribution of the left nodes when branching from parent nodes (given by the tensor element in the output node_ids_list) to the left direction by the given threshold for each feature. This value will be used to make the left node value by adding to the parent node value. Second dimension size is 1 for 1-dimensional logits, but would be larger for multi-class problems. See above for details like shapes and sizes. +/// - right_node_contribs: A Rank 2 tensors, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node. +/// - split_with_default_directions: A Rank 1 tensors indicating the which direction to go if data is missing. See above for details like shapes and sizes. +@inlinable @inline(__always) +public static func boostedTreesCalculateBestFeatureSplit( + nodeIdRange: Tensor, + statsSummary: Tensor, + l1: Tensor, + l2: Tensor, + treeComplexity: Tensor, + minNodeWeight: Tensor, + logitsDimension: Int64, + splitType: SplitType = .inequality +) -> (nodeIds: Tensor, gains: Tensor, featureDimensions: Tensor, thresholds: Tensor, leftNodeContribs: Tensor, rightNodeContribs: Tensor, splitWithDefaultDirections: StringTensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("BoostedTreesCalculateBestFeatureSplit", nOutputs) + op.updateAttribute("logits_dimension", logitsDimension) + op.updateAttribute("split_type", splitType.cName) + op.addInput(nodeIdRange) + op.addInput(statsSummary) + op.addInput(l1) + op.addInput(l2) + op.addInput(treeComplexity) + op.addInput(minNodeWeight) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// Calculates gains for each feature and returns the best possible split information for the feature. +/// +/// The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature. +/// +/// It is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split. +/// +/// In this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features). +/// +/// The length of output lists are all of the same length, `num_features`. +/// The output shapes are compatible in a way that the first dimension of all tensors of all lists are the same and equal to the number of possible split nodes for each feature. +/// +/// - Parameters: +/// - node_id_range: A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive). +/// - stats_summary_list: A list of Rank 3 tensor (#shape=[max_splits, bucket, 2]) for accumulated stats summary (gradient/hessian) per node per buckets for each feature. The first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used. +/// - l1: l1 regularization factor on leaf weights, per instance based. +/// - l2: l2 regularization factor on leaf weights, per instance based. +/// - tree_complexity: adjustment to the gain, per leaf based. +/// - min_node_weight: mininum avg of hessians in a node before required for the node to be considered for splitting. +/// +/// - Attrs: +/// - max_splits: the number of nodes that can be split in the whole tree. Used as a dimension of output tensors. +/// - num_features: inferred from the size of `stats_summary_list`; the number of total features. +/// +/// - Outputs: +/// - node_ids_list: An output list of Rank 1 tensors indicating possible split node ids for each feature. The length of the list is num_features, but each tensor has different size as each feature provides different possible nodes. See above for details like shapes and sizes. +/// - gains_list: An output list of Rank 1 tensors indicating the best gains for each feature to split for certain nodes. See above for details like shapes and sizes. +/// - thresholds_list: An output list of Rank 1 tensors indicating the bucket id to compare with (as a threshold) for split in each node. See above for details like shapes and sizes. +/// - left_node_contribs_list: A list of Rank 2 tensors indicating the contribution of the left nodes when branching from parent nodes (given by the tensor element in the output node_ids_list) to the left direction by the given threshold for each feature. This value will be used to make the left node value by adding to the parent node value. Second dimension size is 1 for 1-dimensional logits, but would be larger for multi-class problems. See above for details like shapes and sizes. +/// - right_node_contribs_list: A list of Rank 2 tensors, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node. +@inlinable @inline(__always) +public static func boostedTreesCalculateBestGainsPerFeature( + nodeIdRange: Tensor, + statsSummaryList: [Tensor], + l1: Tensor, + l2: Tensor, + treeComplexity: Tensor, + minNodeWeight: Tensor, + maxSplits: Int64 +) -> (nodeIdsList: [Tensor], gainsList: [Tensor], thresholdsList: [Tensor], leftNodeContribsList: [Tensor], rightNodeContribsList: [Tensor]) { + let nOutputs = Int(statsSummaryList.count) + Int(statsSummaryList.count) + Int(statsSummaryList.count) + Int(statsSummaryList.count) + Int(statsSummaryList.count) + let op = makeOp("BoostedTreesCalculateBestGainsPerFeature", nOutputs) + op.updateAttribute("max_splits", maxSplits) + op.updateAttribute("num_features", statsSummaryList.count) + op.addInput(nodeIdRange) + op.addInputList(statsSummaryList) + op.addInput(l1) + op.addInput(l2) + op.addInput(treeComplexity) + op.addInput(minNodeWeight) + return op.execute(Int(statsSummaryList.count), Int(statsSummaryList.count), Int(statsSummaryList.count), Int(statsSummaryList.count), Int(statsSummaryList.count)) +} + +/// Calculates the prior from the training data (the bias) and fills in the first node with the logits' prior. Returns a boolean indicating whether to continue centering. +/// +/// - Parameters: +/// - tree_ensemble_handle: Handle to the tree ensemble. +/// - mean_gradients: A tensor with shape=[logits_dimension] with mean of gradients for a first node. +/// - mean_hessians: A tensor with shape=[logits_dimension] mean of hessians for a first node. +/// - l1: l1 regularization factor on leaf weights, per instance based. +/// - l2: l2 regularization factor on leaf weights, per instance based. +/// +/// - Output continue_centering: Bool, whether to continue bias centering. +@inlinable @inline(__always) +public static func boostedTreesCenterBias( + treeEnsembleHandle: ResourceHandle, + meanGradients: Tensor, + meanHessians: Tensor, + l1: Tensor, + l2: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BoostedTreesCenterBias", nOutputs) + op.addInput(treeEnsembleHandle) + op.addInput(meanGradients) + op.addInput(meanHessians) + op.addInput(l1) + op.addInput(l2) + return op.execute(Int(1)) +} + +/// Creates a tree ensemble model and returns a handle to it. +/// +/// - Parameters: +/// - tree_ensemble_handle: Handle to the tree ensemble resource to be created. +/// - stamp_token: Token to use as the initial value of the resource stamp. +/// - tree_ensemble_serialized: Serialized proto of the tree ensemble. +@inlinable @inline(__always) +public static func boostedTreesCreateEnsemble( + treeEnsembleHandle: ResourceHandle, + stampToken: Tensor, + treeEnsembleSerialized: StringTensor +) { + let nOutputs = 0 + let op = makeOp("BoostedTreesCreateEnsemble", nOutputs) + op.addInput(treeEnsembleHandle) + op.addInput(stampToken) + op.addInput(treeEnsembleSerialized) + op.execute() +} + +/// Create the Resource for Quantile Streams. +/// +/// - Parameters: +/// - quantile_stream_resource_handle: resource; Handle to quantile stream resource. +/// - epsilon: float; The required approximation error of the stream resource. +/// - num_streams: int; The number of streams managed by the resource that shares the same epsilon. +/// +/// - Attr max_elements: int; The maximum number of data points that can be fed to the stream. +@inlinable @inline(__always) +public static func boostedTreesCreateQuantileStreamResource( + quantileStreamResourceHandle: ResourceHandle, + epsilon: Tensor, + numStreams: Tensor, + maxElements: Int64 = 1099511627776 +) { + let nOutputs = 0 + let op = makeOp("BoostedTreesCreateQuantileStreamResource", nOutputs) + op.updateAttribute("max_elements", maxElements) + op.addInput(quantileStreamResourceHandle) + op.addInput(epsilon) + op.addInput(numStreams) + op.execute() +} + +/// Deserializes a serialized tree ensemble config and replaces current tree +/// +/// ensemble. +/// +/// - Parameters: +/// - tree_ensemble_handle: Handle to the tree ensemble. +/// - stamp_token: Token to use as the new value of the resource stamp. +/// - tree_ensemble_serialized: Serialized proto of the ensemble. +@inlinable @inline(__always) +public static func boostedTreesDeserializeEnsemble( + treeEnsembleHandle: ResourceHandle, + stampToken: Tensor, + treeEnsembleSerialized: StringTensor +) { + let nOutputs = 0 + let op = makeOp("BoostedTreesDeserializeEnsemble", nOutputs) + op.addInput(treeEnsembleHandle) + op.addInput(stampToken) + op.addInput(treeEnsembleSerialized) + op.execute() +} + +/// Creates a handle to a BoostedTreesEnsembleResource +@inlinable @inline(__always) +public static func boostedTreesEnsembleResourceHandleOp( + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("BoostedTreesEnsembleResourceHandleOp", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Debugging/model interpretability outputs for each example. +/// +/// It traverses all the trees and computes debug metrics for individual examples, +/// such as getting split feature ids and logits after each split along the decision +/// path used to compute directional feature contributions. +/// +/// - Parameter bucketized_features: A list of rank 1 Tensors containing bucket id for each +/// feature. +/// +/// - Attrs: +/// - num_bucketized_features: Inferred. +/// - logits_dimension: scalar, dimension of the logits, to be used for constructing the protos in +/// examples_debug_outputs_serialized. +/// +/// - Output examples_debug_outputs_serialized: Output rank 1 Tensor containing a proto serialized as a string for each example. +@inlinable @inline(__always) +public static func boostedTreesExampleDebugOutputs( + treeEnsembleHandle: ResourceHandle, + bucketizedFeatures: [Tensor], + logitsDimension: Int64 +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("BoostedTreesExampleDebugOutputs", nOutputs) + op.updateAttribute("num_bucketized_features", bucketizedFeatures.count) + op.updateAttribute("logits_dimension", logitsDimension) + op.addInput(treeEnsembleHandle) + op.addInputList(bucketizedFeatures) + return op.execute(Int(1)) +} + +/// Retrieves the tree ensemble resource stamp token, number of trees and growing statistics. +/// +/// - Parameter tree_ensemble_handle: Handle to the tree ensemble. +/// +/// - Outputs: +/// - stamp_token: Stamp token of the tree ensemble resource. +/// - num_trees: The number of trees in the tree ensemble resource. +/// - num_finalized_trees: The number of trees that were finished successfully. +/// - num_attempted_layers: The number of layers we attempted to build (but not necessarily succeeded). +/// - last_layer_nodes_range: Rank size 2 tensor that contains start and end ids of the nodes in the latest +/// layer. +@inlinable @inline(__always) +public static func boostedTreesGetEnsembleStates( + treeEnsembleHandle: ResourceHandle +) -> (stampToken: Tensor, numTrees: Tensor, numFinalizedTrees: Tensor, numAttemptedLayers: Tensor, lastLayerNodesRange: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("BoostedTreesGetEnsembleStates", nOutputs) + op.addInput(treeEnsembleHandle) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// Makes the summary of quantiles for the batch. +/// +/// An op that takes a list of tensors (one tensor per feature) and outputs the +/// quantile summaries for each tensor. +/// +/// - Parameters: +/// - float_values: float; List of Rank 1 Tensors each containing values for a single feature. +/// - example_weights: float; Rank 1 Tensor with weights per instance. +/// - epsilon: float; The required maximum approximation error. +/// +/// - Attr num_features: int; Inferred from the size of float_values. +/// The number of float features. +/// +/// - Output summaries: float; List of Rank 2 Tensors each containing the quantile summary +/// (value, weight, min_rank, max_rank) of a single feature. +@inlinable @inline(__always) +public static func boostedTreesMakeQuantileSummaries( + floatValues: [Tensor], + exampleWeights: Tensor, + epsilon: Tensor +) -> [Tensor] { + let nOutputs = Int(floatValues.count) + let op = makeOp("BoostedTreesMakeQuantileSummaries", nOutputs) + op.updateAttribute("num_features", floatValues.count) + op.addInputList(floatValues) + op.addInput(exampleWeights) + op.addInput(epsilon) + return op.execute(Int(floatValues.count)) +} + +/// Makes the summary of accumulated stats for the batch. +/// +/// The summary stats contains gradients and hessians accumulated into the corresponding node and bucket for each example. +/// +/// - Parameters: +/// - node_ids: int32 Rank 1 Tensor containing node ids, which each example falls into for the requested layer. +/// - gradients: float32; Rank 2 Tensor (shape=[#examples, 1]) for gradients. +/// - hessians: float32; Rank 2 Tensor (shape=[#examples, 1]) for hessians. +/// - bucketized_features_list: int32 list of Rank 1 Tensors, each containing the bucketized feature (for each feature column). +/// +/// - Attrs: +/// - max_splits: int; the maximum number of splits possible in the whole tree. +/// - num_buckets: int; equals to the maximum possible value of bucketized feature. +/// - num_features: int; inferred from the size of bucketized_features_list; the number of features. +/// +/// - Output stats_summary: output Rank 4 Tensor (shape=[#features, #splits, #buckets, 2]) containing accumulated stats put into the corresponding node and bucket. The first index of 4th dimension refers to gradients, and the second to hessians. +@inlinable @inline(__always) +public static func boostedTreesMakeStatsSummary( + nodeIds: Tensor, + gradients: Tensor, + hessians: Tensor, + bucketizedFeaturesList: [Tensor], + maxSplits: Int64, + numBuckets: Int64 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BoostedTreesMakeStatsSummary", nOutputs) + op.updateAttribute("max_splits", maxSplits) + op.updateAttribute("num_buckets", numBuckets) + op.updateAttribute("num_features", bucketizedFeaturesList.count) + op.addInput(nodeIds) + op.addInput(gradients) + op.addInput(hessians) + op.addInputList(bucketizedFeaturesList) + return op.execute(Int(1)) +} + +/// Runs multiple additive regression ensemble predictors on input instances and +/// +/// computes the logits. It is designed to be used during prediction. +/// It traverses all the trees and calculates the final score for each instance. +/// +/// - Parameter bucketized_features: A list of rank 1 Tensors containing bucket id for each +/// feature. +/// +/// - Attrs: +/// - num_bucketized_features: Inferred. +/// - logits_dimension: scalar, dimension of the logits, to be used for partial logits +/// shape. +/// +/// - Output logits: Output rank 2 Tensor containing logits for each example. +@inlinable @inline(__always) +public static func boostedTreesPredict( + treeEnsembleHandle: ResourceHandle, + bucketizedFeatures: [Tensor], + logitsDimension: Int64 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BoostedTreesPredict", nOutputs) + op.updateAttribute("num_bucketized_features", bucketizedFeatures.count) + op.updateAttribute("logits_dimension", logitsDimension) + op.addInput(treeEnsembleHandle) + op.addInputList(bucketizedFeatures) + return op.execute(Int(1)) +} + +/// Add the quantile summaries to each quantile stream resource. +/// +/// An op that adds a list of quantile summaries to a quantile stream resource. Each +/// summary Tensor is rank 2, containing summaries (value, weight, min_rank, max_rank) +/// for a single feature. +/// +/// - Parameters: +/// - quantile_stream_resource_handle: resource handle referring to a QuantileStreamResource. +/// - summaries: string; List of Rank 2 Tensor each containing the summaries for a single feature. +@inlinable @inline(__always) +public static func boostedTreesQuantileStreamResourceAddSummaries( + quantileStreamResourceHandle: ResourceHandle, + summaries: [Tensor] +) { + let nOutputs = 0 + let op = makeOp("BoostedTreesQuantileStreamResourceAddSummaries", nOutputs) + op.updateAttribute("num_features", summaries.count) + op.addInput(quantileStreamResourceHandle) + op.addInputList(summaries) + op.execute() +} + +/// Deserialize bucket boundaries and ready flag into current QuantileAccumulator. +/// +/// An op that deserializes bucket boundaries and are boundaries ready flag into current QuantileAccumulator. +/// +/// - Parameters: +/// - quantile_stream_resource_handle: resource handle referring to a QuantileStreamResource. +/// - bucket_boundaries: float; List of Rank 1 Tensors each containing the bucket boundaries for a feature. +/// +/// - Attr num_streams: inferred int; number of features to get bucket boundaries for. +@inlinable @inline(__always) +public static func boostedTreesQuantileStreamResourceDeserialize( + quantileStreamResourceHandle: ResourceHandle, + bucketBoundaries: [Tensor] +) { + let nOutputs = 0 + let op = makeOp("BoostedTreesQuantileStreamResourceDeserialize", nOutputs) + op.updateAttribute("num_streams", bucketBoundaries.count) + op.addInput(quantileStreamResourceHandle) + op.addInputList(bucketBoundaries) + op.execute() +} + +/// Flush the summaries for a quantile stream resource. +/// +/// An op that flushes the summaries for a quantile stream resource. +/// +/// - Parameters: +/// - quantile_stream_resource_handle: resource handle referring to a QuantileStreamResource. +/// - num_buckets: int; approximate number of buckets unless using generate_quantiles. +/// +/// - Attr generate_quantiles: bool; If True, the output will be the num_quantiles for each stream where the ith +/// entry is the ith quantile of the input with an approximation error of epsilon. +/// Duplicate values may be present. +/// If False, the output will be the points in the histogram that we got which roughly +/// translates to 1/epsilon boundaries and without any duplicates. +/// Default to False. +@inlinable @inline(__always) +public static func boostedTreesQuantileStreamResourceFlush( + quantileStreamResourceHandle: ResourceHandle, + numBuckets: Tensor, + generateQuantiles: Bool = false +) { + let nOutputs = 0 + let op = makeOp("BoostedTreesQuantileStreamResourceFlush", nOutputs) + op.updateAttribute("generate_quantiles", generateQuantiles) + op.addInput(quantileStreamResourceHandle) + op.addInput(numBuckets) + op.execute() +} + +/// Generate the bucket boundaries for each feature based on accumulated summaries. +/// +/// An op that returns a list of float tensors for a quantile stream resource. Each +/// tensor is Rank 1 containing bucket boundaries for a single feature. +/// +/// - Parameter quantile_stream_resource_handle: resource handle referring to a QuantileStreamResource. +/// +/// - Attr num_features: inferred int; number of features to get bucket boundaries for. +/// +/// - Output bucket_boundaries: float; List of Rank 1 Tensors each containing the bucket boundaries for a feature. +@inlinable @inline(__always) +public static func boostedTreesQuantileStreamResourceGetBucketBoundaries( + quantileStreamResourceHandle: ResourceHandle, + numFeatures: Int64 +) -> [Tensor] { + let nOutputs = Int(numFeatures) + let op = makeOp("BoostedTreesQuantileStreamResourceGetBucketBoundaries", nOutputs) + op.updateAttribute("num_features", numFeatures) + op.addInput(quantileStreamResourceHandle) + return op.execute(Int(numFeatures)) +} + +/// Creates a handle to a BoostedTreesQuantileStreamResource. +@inlinable @inline(__always) +public static func boostedTreesQuantileStreamResourceHandleOp( + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("BoostedTreesQuantileStreamResourceHandleOp", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Serializes the tree ensemble to a proto. +/// +/// - Parameter tree_ensemble_handle: Handle to the tree ensemble. +/// +/// - Outputs: +/// - stamp_token: Stamp token of the tree ensemble resource. +/// - tree_ensemble_serialized: Serialized proto of the ensemble. +@inlinable @inline(__always) +public static func boostedTreesSerializeEnsemble( + treeEnsembleHandle: ResourceHandle +) -> (stampToken: Tensor, treeEnsembleSerialized: StringTensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("BoostedTreesSerializeEnsemble", nOutputs) + op.addInput(treeEnsembleHandle) + return op.execute(Int(1), Int(1)) +} + +/// Runs multiple additive regression ensemble predictors on input instances and +/// +/// computes the update to cached logits. It is designed to be used during training. +/// It traverses the trees starting from cached tree id and cached node id and +/// calculates the updates to be pushed to the cache. +/// +/// - Parameters: +/// - cached_tree_ids: Rank 1 Tensor containing cached tree ids which is the starting +/// tree of prediction. +/// - cached_node_ids: Rank 1 Tensor containing cached node id which is the starting +/// node of prediction. +/// - bucketized_features: A list of rank 1 Tensors containing bucket id for each +/// feature. +/// +/// - Attrs: +/// - num_bucketized_features: Inferred. +/// - logits_dimension: scalar, dimension of the logits, to be used for partial logits +/// shape. +/// +/// - Outputs: +/// - partial_logits: Rank 2 Tensor containing logits update (with respect to cached +/// values stored) for each example. +/// - tree_ids: Rank 1 Tensor containing new tree ids for each example. +/// - node_ids: Rank 1 Tensor containing new node ids in the new tree_ids. +@inlinable @inline(__always) +public static func boostedTreesTrainingPredict( + treeEnsembleHandle: ResourceHandle, + cachedTreeIds: Tensor, + cachedNodeIds: Tensor, + bucketizedFeatures: [Tensor], + logitsDimension: Int64 +) -> (partialLogits: Tensor, treeIds: Tensor, nodeIds: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("BoostedTreesTrainingPredict", nOutputs) + op.updateAttribute("num_bucketized_features", bucketizedFeatures.count) + op.updateAttribute("logits_dimension", logitsDimension) + op.addInput(treeEnsembleHandle) + op.addInput(cachedTreeIds) + op.addInput(cachedNodeIds) + op.addInputList(bucketizedFeatures) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Updates the tree ensemble by either adding a layer to the last tree being grown +/// +/// or by starting a new tree. +/// +/// - Parameters: +/// - tree_ensemble_handle: Handle to the ensemble variable. +/// - feature_ids: Rank 1 tensor with ids for each feature. This is the real id of +/// the feature that will be used in the split. +/// - node_ids: List of rank 1 tensors representing the nodes for which this feature +/// has a split. +/// - gains: List of rank 1 tensors representing the gains for each of the feature's +/// split. +/// - thresholds: List of rank 1 tensors representing the thesholds for each of the +/// feature's split. +/// - left_node_contribs: List of rank 2 tensors with left leaf contribs for each of +/// the feature's splits. Will be added to the previous node values to constitute +/// the values of the left nodes. +/// - right_node_contribs: List of rank 2 tensors with right leaf contribs for each +/// of the feature's splits. Will be added to the previous node values to constitute +/// the values of the right nodes. +/// - max_depth: Max depth of the tree to build. +/// - learning_rate: shrinkage const for each new tree. +/// +/// - Attrs: +/// - pruning_mode: 0-No pruning, 1-Pre-pruning, 2-Post-pruning. +/// - num_features: Number of features that have best splits returned. INFERRED. +@inlinable @inline(__always) +public static func boostedTreesUpdateEnsemble( + treeEnsembleHandle: ResourceHandle, + featureIds: Tensor, + nodeIds: [Tensor], + gains: [Tensor], + thresholds: [Tensor], + leftNodeContribs: [Tensor], + rightNodeContribs: [Tensor], + maxDepth: Tensor, + learningRate: Tensor, + pruningMode: Int64 +) { + let nOutputs = 0 + let op = makeOp("BoostedTreesUpdateEnsemble", nOutputs) + op.updateAttribute("pruning_mode", pruningMode) + op.updateAttribute("num_features", nodeIds.count) + op.addInput(treeEnsembleHandle) + op.addInput(featureIds) + op.addInputList(nodeIds) + op.addInputList(gains) + op.addInputList(thresholds) + op.addInputList(leftNodeContribs) + op.addInputList(rightNodeContribs) + op.addInput(maxDepth) + op.addInput(learningRate) + op.execute() +} + +/// Return the shape of s0 op s1 with broadcast. +/// +/// Given `s0` and `s1`, tensors that represent shapes, compute `r0`, the +/// broadcasted shape. `s0`, `s1` and `r0` are all integer vectors. +@inlinable @inline(__always) +public static func broadcastArgs( + s0: Tensor, + s1: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BroadcastArgs", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(s0) + op.addInput(s1) + return op.execute(Int(1)) +} + +/// Return the reduction indices for computing gradients of s0 op s1 with broadcast. +/// +/// This is typically used by gradient computations for a broadcasting operation. +@inlinable @inline(__always) +public static func broadcastGradientArgs( + s0: Tensor, + s1: Tensor +) -> (r0: Tensor, r1: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("BroadcastGradientArgs", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(s0) + op.addInput(s1) + return op.execute(Int(1), Int(1)) +} + +/// Broadcast an array for a compatible shape. +/// +/// Broadcasting is the process of making arrays to have compatible shapes +/// for arithmetic operations. Two shapes are compatible if for each +/// dimension pair they are either equal or one of them is one. When trying +/// to broadcast a Tensor to a shape, it starts with the trailing dimensions, +/// and works its way forward. +/// +/// For example, +/// ``` +/// >>> x = tf.constant([1, 2, 3]) +/// >>> y = tf.broadcast_to(x, [3, 3]) +/// >>> sess.run(y) +/// array([[1, 2, 3], +/// [1, 2, 3], +/// [1, 2, 3]], dtype=int32) +/// ``` +/// In the above example, the input Tensor with the shape of `[1, 3]` +/// is broadcasted to output Tensor with shape of `[3, 3]`. +/// +/// - Parameters: +/// - input: A Tensor to broadcast. +/// - shape: An 1-D `int` Tensor. The shape of the desired output. +/// +/// - Output output: A Tensor. +@inlinable @inline(__always) +public static func broadcastTo< + T: TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + shape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BroadcastTo", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(shape) + return op.execute(Int(1)) +} + +/// Bucketizes 'input' based on 'boundaries'. +/// +/// For example, if the inputs are +/// boundaries = [0, 10, 100] +/// input = [[-5, 10000] +/// [150, 10] +/// [5, 100]] +/// +/// then the output will be +/// output = [[0, 3] +/// [3, 2] +/// [1, 3]] +/// +/// - Parameter input: Any shape of Tensor contains with int or float type. +/// +/// - Attr boundaries: A sorted list of floats gives the boundary of the buckets. +/// +/// - Output output: Same shape with 'input', each value of input replaced with bucket index. +/// +/// @compatibility(numpy) +/// Equivalent to np.digitize. +/// @end_compatibility +@inlinable @inline(__always) +public static func bucketize( + _ input: Tensor, + boundaries: [Double] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Bucketize", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("boundaries", boundaries) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Performs beam search decoding on the logits given in input. +/// +/// A note about the attribute merge_repeated: For the beam search decoder, +/// this means that if consecutive entries in a beam are the same, only +/// the first of these is emitted. That is, when the top path is "A B B B B", +/// "A B" is returned if merge_repeated = True but "A B B B B" is +/// returned if merge_repeated = False. +/// +/// - Parameters: +/// - inputs: 3-D, shape: `(max_time x batch_size x num_classes)`, the logits. +/// - sequence_length: A vector containing sequence lengths, size `(batch)`. +/// +/// - Attrs: +/// - beam_width: A scalar >= 0 (beam search beam width). +/// - top_paths: A scalar >= 0, <= beam_width (controls output size). +/// - merge_repeated: If true, merge repeated classes in output. +/// +/// - Outputs: +/// - decoded_indices: A list (length: top_paths) of indices matrices. Matrix j, +/// size `(total_decoded_outputs[j] x 2)`, has indices of a +/// `SparseTensor`. The rows store: [batch, time]. +/// - decoded_values: A list (length: top_paths) of values vectors. Vector j, +/// size `(length total_decoded_outputs[j])`, has the values of a +/// `SparseTensor`. The vector stores the decoded classes for beam j. +/// - decoded_shape: A list (length: top_paths) of shape vector. Vector j, +/// size `(2)`, stores the shape of the decoded `SparseTensor[j]`. +/// Its values are: `[batch_size, max_decoded_length[j]]`. +/// - log_probability: A matrix, shaped: `(batch_size x top_paths)`. The +/// sequence log-probabilities. +@inlinable @inline(__always) +public static func cTCBeamSearchDecoder( + inputs: Tensor, + sequenceLength: Tensor, + beamWidth: Int64, + topPaths: Int64, + mergeRepeated: Bool = true +) -> (decodedIndices: [Tensor], decodedValues: [Tensor], decodedShape: [Tensor], logProbability: Tensor) { + let nOutputs = Int(topPaths) + Int(topPaths) + Int(topPaths) + Int(1) + let op = makeOp("CTCBeamSearchDecoder", nOutputs) + op.updateAttribute("beam_width", beamWidth) + op.updateAttribute("top_paths", topPaths) + op.updateAttribute("merge_repeated", mergeRepeated) + op.addInput(inputs) + op.addInput(sequenceLength) + return op.execute(Int(topPaths), Int(topPaths), Int(topPaths), Int(1)) +} + +/// Performs greedy decoding on the logits given in inputs. +/// +/// A note about the attribute merge_repeated: if enabled, when +/// consecutive logits' maximum indices are the same, only the first of +/// these is emitted. Labeling the blank '*', the sequence "A B B * B B" +/// becomes "A B B" if merge_repeated = True and "A B B B B" if +/// merge_repeated = False. +/// +/// Regardless of the value of merge_repeated, if the maximum index of a given +/// time and batch corresponds to the blank, index `(num_classes - 1)`, no new +/// element is emitted. +/// +/// - Parameters: +/// - inputs: 3-D, shape: `(max_time x batch_size x num_classes)`, the logits. +/// - sequence_length: A vector containing sequence lengths, size `(batch_size)`. +/// +/// - Attr merge_repeated: If True, merge repeated classes in output. +/// +/// - Outputs: +/// - decoded_indices: Indices matrix, size `(total_decoded_outputs x 2)`, +/// of a `SparseTensor`. The rows store: [batch, time]. +/// - decoded_values: Values vector, size: `(total_decoded_outputs)`, +/// of a `SparseTensor`. The vector stores the decoded classes. +/// - decoded_shape: Shape vector, size `(2)`, of the decoded SparseTensor. +/// Values are: `[batch_size, max_decoded_length]`. +/// - log_probability: Matrix, size `(batch_size x 1)`, containing sequence +/// log-probabilities. +@inlinable @inline(__always) +public static func cTCGreedyDecoder( + inputs: Tensor, + sequenceLength: Tensor, + mergeRepeated: Bool = false +) -> (decodedIndices: Tensor, decodedValues: Tensor, decodedShape: Tensor, logProbability: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("CTCGreedyDecoder", nOutputs) + op.updateAttribute("merge_repeated", mergeRepeated) + op.addInput(inputs) + op.addInput(sequenceLength) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Calculates the CTC Loss (log probability) for each batch entry. Also calculates +/// +/// the gradient. This class performs the softmax operation for you, so inputs +/// should be e.g. linear projections of outputs by an LSTM. +/// +/// - Parameters: +/// - inputs: 3-D, shape: `(max_time x batch_size x num_classes)`, the logits. +/// - labels_indices: The indices of a `SparseTensor`. +/// `labels_indices(i, :) == [b, t]` means `labels_values(i)` stores the id for +/// `(batch b, time t)`. +/// - labels_values: The values (labels) associated with the given batch and time. +/// - sequence_length: A vector containing sequence lengths (batch). +/// +/// - Attrs: +/// - preprocess_collapse_repeated: Scalar, if true then repeated labels are +/// collapsed prior to the CTC calculation. +/// - ctc_merge_repeated: Scalar. If set to false, *during* CTC calculation +/// repeated non-blank labels will not be merged and are interpreted as +/// individual labels. This is a simplified version of CTC. +/// - ignore_longer_outputs_than_inputs: Scalar. If set to true, during CTC +/// calculation, items that have longer output sequences than input sequences +/// are skipped: they don't contribute to the loss term and have zero-gradient. +/// +/// - Outputs: +/// - loss: A vector (batch) containing log-probabilities. +/// - gradient: The gradient of `loss`. 3-D, shape: +/// `(max_time x batch_size x num_classes)`. +@inlinable @inline(__always) +public static func cTCLoss( + inputs: Tensor, + labelsIndices: Tensor, + labelsValues: Tensor, + sequenceLength: Tensor, + preprocessCollapseRepeated: Bool = false, + ctcMergeRepeated: Bool = true, + ignoreLongerOutputsThanInputs: Bool = false +) -> (loss: Tensor, gradient: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("CTCLoss", nOutputs) + op.updateAttribute("preprocess_collapse_repeated", preprocessCollapseRepeated) + op.updateAttribute("ctc_merge_repeated", ctcMergeRepeated) + op.updateAttribute("ignore_longer_outputs_than_inputs", ignoreLongerOutputsThanInputs) + op.addInput(inputs) + op.addInput(labelsIndices) + op.addInput(labelsValues) + op.addInput(sequenceLength) + return op.execute(Int(1), Int(1)) +} + +/// Creates a dataset that caches elements from `input_dataset`. +/// +/// A CacheDataset will iterate over the input_dataset, and store tensors. If the +/// cache already exists, the cache will be used. If the cache is inappropriate +/// (e.g. cannot be opened, contains tensors of the wrong shape / size), an error +/// will the returned when used. +/// +/// - Parameter filename: A path on the filesystem where we should cache the dataset. Note: this +/// will be a directory. +@inlinable @inline(__always) +public static func cacheDataset( + inputDataset: VariantHandle, + filename: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("CacheDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(filename) + return op.execute(Int(1)) +} + +/// Cast x of type SrcT to y of DstT. +@inlinable @inline(__always) +public static func cast< + Srct: TensorFlowScalar, + Dstt: TensorFlowScalar +>( + _ x: Tensor, + truncate: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Cast", nOutputs) + op.updateAttribute("SrcT", Srct.tensorFlowDataType) + op.updateAttribute("DstT", Dstt.tensorFlowDataType) + op.updateAttribute("Truncate", truncate) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Returns element-wise smallest integer not less than x. +@inlinable @inline(__always) +public static func ceil( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Ceil", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Checks a tensor for NaN and Inf values. +/// +/// When run, reports an `InvalidArgument` error if `tensor` has any values +/// that are not a number (NaN) or infinity (Inf). Otherwise, passes `tensor` as-is. +/// +/// - Attr message: Prefix of the error message. +@inlinable @inline(__always) +public static func checkNumerics( + _ tensor: Tensor, + message: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CheckNumerics", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("message", message) + op.addInput(tensor) + return op.execute(Int(1)) +} + +/// Computes the Cholesky decomposition of one or more square matrices. +/// +/// The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions +/// form square matrices. +/// +/// The input has to be symmetric and positive definite. Only the lower-triangular +/// part of the input will be used for this operation. The upper-triangular part +/// will not be read. +/// +/// The output is a tensor of the same shape as the input +/// containing the Cholesky decompositions for all input submatrices `[..., :, :]`. +/// +/// **Note**: The gradient computation on GPU is faster for large matrices but +/// not for large batch dimensions when the submatrices are small. In this +/// case it might be faster to use the CPU. +/// +/// - Parameter input: Shape is `[..., M, M]`. +/// +/// - Output output: Shape is `[..., M, M]`. +@inlinable @inline(__always) +public static func cholesky( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Cholesky", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Computes the reverse mode backpropagated gradient of the Cholesky algorithm. +/// +/// For an explanation see "Differentiation of the Cholesky algorithm" by +/// Iain Murray http://arxiv.org/abs/1602.07527. +/// +/// - Parameters: +/// - l: Output of batch Cholesky algorithm l = cholesky(A). Shape is `[..., M, M]`. +/// Algorithm depends only on lower triangular part of the innermost matrices of +/// this tensor. +/// - grad: df/dl where f is some scalar function. Shape is `[..., M, M]`. +/// Algorithm depends only on lower triangular part of the innermost matrices of +/// this tensor. +/// +/// - Output output: Symmetrized version of df/dA . Shape is `[..., M, M]` +@inlinable @inline(__always) +public static func choleskyGrad( + l: Tensor, + grad: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CholeskyGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(l) + op.addInput(grad) + return op.execute(Int(1)) +} + +/// Clips tensor values to a specified min and max. +/// +/// Given a tensor `t`, this operation returns a tensor of the same type and +/// shape as `t` with its values clipped to `clip_value_min` and `clip_value_max`. +/// Any values less than `clip_value_min` are set to `clip_value_min`. Any values +/// greater than `clip_value_max` are set to `clip_value_max`. +/// +/// - Parameters: +/// - t: A `Tensor`. +/// - clip_value_min: A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape +/// as `t`. The minimum value to clip by. +/// - clip_value_max: A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape +/// as `t`. The maximum value to clip by. +/// +/// - Output output: A clipped `Tensor` with the same shape as input 't'. +@inlinable @inline(__always) +public static func clipByValue( + t: Tensor, + clipValueMin: Tensor, + clipValueMax: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ClipByValue", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(t) + op.addInput(clipValueMin) + op.addInput(clipValueMax) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func closeSummaryWriter( + writer: ResourceHandle +) { + let nOutputs = 0 + let op = makeOp("CloseSummaryWriter", nOutputs) + op.addInput(writer) + op.execute() +} + +/// Receives a tensor value broadcast from another device. +@inlinable @inline(__always) +public static func collectiveBcastRecv( + groupSize: Int64, + groupKey: Int64, + instanceKey: Int64, + shape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CollectiveBcastRecv", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("group_size", groupSize) + op.updateAttribute("group_key", groupKey) + op.updateAttribute("instance_key", instanceKey) + op.updateAttribute("shape", shape) + return op.execute(Int(1)) +} + +/// Broadcasts a tensor value to one or more other devices. +@inlinable @inline(__always) +public static func collectiveBcastSend( + _ input: Tensor, + groupSize: Int64, + groupKey: Int64, + instanceKey: Int64, + shape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CollectiveBcastSend", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("group_size", groupSize) + op.updateAttribute("group_key", groupKey) + op.updateAttribute("instance_key", instanceKey) + op.updateAttribute("shape", shape) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Mutually accumulates multiple tensors of identical type and shape. +@inlinable @inline(__always) +public static func collectiveGather( + _ input: Tensor, + groupSize: Int64, + groupKey: Int64, + instanceKey: Int64, + shape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CollectiveGather", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("group_size", groupSize) + op.updateAttribute("group_key", groupKey) + op.updateAttribute("instance_key", instanceKey) + op.updateAttribute("shape", shape) + op.addInput(input) + return op.execute(Int(1)) +} + +/// An Op to permute tensors across replicated TPU instances. +/// +/// Each instance supplies its own input. +/// +/// For example, suppose there are 4 TPU instances: `[A, B, C, D]`. Passing +/// source_target_pairs=`[[0,1],[1,2],[2,3],[3,0]]` gets the outputs: +/// `[D, A, B, C]`. +/// +/// - Parameters: +/// - input: The local input to be permuted. Currently only supports float and +/// bfloat16. +/// - source_target_pairs: A tensor with shape [num_pairs, 2]. +/// +/// - Attr T: The type of elements to be exchanged. +/// +/// - Output output: The permuted input. +@inlinable @inline(__always) +public static func collectivePermute( + _ input: Tensor, + sourceTargetPairs: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CollectivePermute", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(sourceTargetPairs) + return op.execute(Int(1)) +} + +/// Mutually reduces multiple tensors of identical type and shape. +@inlinable @inline(__always) +public static func collectiveReduce( + _ input: Tensor, + groupSize: Int64, + groupKey: Int64, + instanceKey: Int64, + mergeOp: MergeOp, + finalOp: FinalOp, + subdivOffsets: [Int32], + waitFor: [Int32] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CollectiveReduce", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("group_size", groupSize) + op.updateAttribute("group_key", groupKey) + op.updateAttribute("instance_key", instanceKey) + op.updateAttribute("merge_op", mergeOp.cName) + op.updateAttribute("final_op", finalOp.cName) + op.updateAttribute("subdiv_offsets", subdivOffsets) + op.updateAttribute("wait_for", waitFor) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Greedily selects a subset of bounding boxes in descending order of score, +/// +/// This operation performs non_max_suppression on the inputs per batch, across +/// all classes. +/// Prunes away boxes that have high intersection-over-union (IOU) overlap +/// with previously selected boxes. Bounding boxes are supplied as +/// [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any +/// diagonal pair of box corners and the coordinates can be provided as normalized +/// (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm +/// is agnostic to where the origin is in the coordinate system. Also note that +/// this algorithm is invariant to orthogonal transformations and translations +/// of the coordinate system; thus translating or reflections of the coordinate +/// system result in the same boxes being selected by the algorithm. +/// The output of this operation is the final boxes, scores and classes tensor +/// returned after performing non_max_suppression. +/// +/// - Parameters: +/// - boxes: A 4-D float tensor of shape `[batch_size, num_boxes, q, 4]`. If `q` is 1 then +/// same boxes are used for all classes otherwise, if `q` is equal to number of +/// classes, class-specific boxes are used. +/// - scores: A 3-D float tensor of shape `[batch_size, num_boxes, num_classes]` +/// representing a single score corresponding to each box (each row of boxes). +/// - max_output_size_per_class: A scalar integer tensor representing the maximum number of +/// boxes to be selected by non max suppression per class +/// - max_total_size: A scalar representing maximum number of boxes retained over all classes. +/// - iou_threshold: A 0-D float tensor representing the threshold for deciding whether +/// boxes overlap too much with respect to IOU. +/// - score_threshold: A 0-D float tensor representing the threshold for deciding when to remove +/// boxes based on score. +/// +/// - Attrs: +/// - pad_per_class: If false, the output nmsed boxes, scores and classes +/// are padded/clipped to `max_total_size`. If true, the +/// output nmsed boxes, scores and classes are padded to be of length +/// `max_size_per_class`*`num_classes`, unless it exceeds `max_total_size` in +/// which case it is clipped to `max_total_size`. Defaults to false. +/// - clip_boxes: If true, assume the box coordinates are between [0, 1] and clip the output boxes +/// if they fall beyond [0, 1]. If false, do not do clipping and output the box +/// coordinates as it is. +/// +/// - Outputs: +/// - nmsed_boxes: A [batch_size, max_detections, 4] float32 tensor +/// containing the non-max suppressed boxes. +/// - nmsed_scores: A [batch_size, max_detections] float32 tensor +/// containing the scores for the boxes. +/// - nmsed_classes: A [batch_size, max_detections] float32 tensor +/// containing the classes for the boxes. +/// - valid_detections: A [batch_size] int32 tensor indicating the number of +/// valid detections per batch item. Only the top num_detections[i] entries in +/// nms_boxes[i], nms_scores[i] and nms_class[i] are valid. The rest of the +/// entries are zero paddings. +@inlinable @inline(__always) +public static func combinedNonMaxSuppression( + boxes: Tensor, + scores: Tensor, + maxOutputSizePerClass: Tensor, + maxTotalSize: Tensor, + iouThreshold: Tensor, + scoreThreshold: Tensor, + padPerClass: Bool = false, + clipBoxes: Bool = true +) -> (nmsedBoxes: Tensor, nmsedScores: Tensor, nmsedClasses: Tensor, validDetections: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("CombinedNonMaxSuppression", nOutputs) + op.updateAttribute("pad_per_class", padPerClass) + op.updateAttribute("clip_boxes", clipBoxes) + op.addInput(boxes) + op.addInput(scores) + op.addInput(maxOutputSizePerClass) + op.addInput(maxTotalSize) + op.addInput(iouThreshold) + op.addInput(scoreThreshold) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Compare values of `input` to `threshold` and pack resulting bits into a `uint8`. +/// +/// Each comparison returns a boolean `true` (if `input_value > threshold`) +/// or and `false` otherwise. +/// +/// This operation is useful for Locality-Sensitive-Hashing (LSH) and other +/// algorithms that use hashing approximations of cosine and `L2` distances; +/// codes can be generated from an input via: +/// +/// ```python +/// codebook_size = 50 +/// codebook_bits = codebook_size * 32 +/// codebook = tf.get_variable('codebook', [x.shape[-1].value, codebook_bits], +/// dtype=x.dtype, +/// initializer=tf.orthogonal_initializer()) +/// codes = compare_and_threshold(tf.matmul(x, codebook), threshold=0.) +/// codes = tf.bitcast(codes, tf.int32) # go from uint8 to int32 +/// # now codes has shape x.shape[:-1] + [codebook_size] +/// ``` +/// +/// **NOTE**: Currently, the innermost dimension of the tensor must be divisible +/// by 8. +/// +/// Given an `input` shaped `[s0, s1, ..., s_n]`, the output is +/// a `uint8` tensor shaped `[s0, s1, ..., s_n / 8]`. +/// +/// - Parameters: +/// - input: Values to compare against `threshold` and bitpack. +/// - threshold: Threshold to compare against. +/// +/// - Attr T: The type of the input and threshold. +/// +/// - Output output: The bitpacked comparisons. +@inlinable @inline(__always) +public static func compareAndBitpack( + _ input: Tensor, + threshold: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CompareAndBitpack", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(threshold) + return op.execute(Int(1)) +} + +/// Converts two real numbers to a complex number. +/// +/// Given a tensor `real` representing the real part of a complex number, and a +/// tensor `imag` representing the imaginary part of a complex number, this +/// operation returns complex numbers elementwise of the form \\(a + bj\\), where +/// *a* represents the `real` part and *b* represents the `imag` part. +/// +/// The input tensors `real` and `imag` must have the same shape. +/// +/// For example: +/// +/// ``` +/// # tensor 'real' is [2.25, 3.25] +/// # tensor `imag` is [4.75, 5.75] +/// tf.complex(real, imag) ==> [[2.25 + 4.75j], [3.25 + 5.75j]] +/// ``` +@inlinable @inline(__always) +public static func complex< + T: FloatingPoint & TensorFlowScalar, + Tout: TensorFlowScalar +>( + real: Tensor, + imag: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Complex", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(real) + op.addInput(imag) + return op.execute(Int(1)) +} + +/// Computes the complex absolute value of a tensor. +/// +/// Given a tensor `x` of complex numbers, this operation returns a tensor of type +/// `float` or `double` that is the absolute value of each element in `x`. All +/// elements in `x` must be complex numbers of the form \\(a + bj\\). The absolute +/// value is computed as \\( \sqrt{a^2 + b^2}\\). +@inlinable @inline(__always) +public static func complexAbs< + T: TensorFlowScalar, + Tout: FloatingPoint & TensorFlowScalar +>( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ComplexAbs", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func complexStruct( + nA: Int64, + nB: Int64 +) -> (a: [Tensor], b: [Tensor], c: TC) { + let nOutputs = Int(nA) + Int(nB) + Int(TC._typeList.count) + let op = makeOp("ComplexStruct", nOutputs) + op.updateAttribute("n_a", nA) + op.updateAttribute("n_b", nB) + op.updateAttribute("t_c", TC._typeList) + return op.execute(Int(nA), Int(nB), Int(TC._typeList.count)) +} + +/// Computes the ids of the positions in sampled_candidates that match true_labels. +/// +/// When doing log-odds NCE, the result of this op should be passed through a +/// SparseToDense op, then added to the logits of the sampled candidates. This has +/// the effect of 'removing' the sampled labels that match the true labels by +/// making the classifier sure that they are sampled labels. +/// +/// - Parameters: +/// - true_classes: The true_classes output of UnpackSparseLabels. +/// - sampled_candidates: The sampled_candidates output of CandidateSampler. +/// +/// - Attrs: +/// - num_true: Number of true labels per context. +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. +/// +/// - Outputs: +/// - indices: A vector of indices corresponding to rows of true_candidates. +/// - ids: A vector of IDs of positions in sampled_candidates that match a true_label +/// for the row with the corresponding index in indices. +/// - weights: A vector of the same length as indices and ids, in which each element +/// is -FLOAT_MAX. +@inlinable @inline(__always) +public static func computeAccidentalHits( + trueClasses: Tensor, + sampledCandidates: Tensor, + numTrue: Int64, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> (indices: Tensor, ids: Tensor, weights: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("ComputeAccidentalHits", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + op.addInput(sampledCandidates) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Concatenates tensors along one dimension. +/// +/// - Parameters: +/// - concat_dim: 0-D. The dimension along which to concatenate. Must be in the +/// range [0, rank(values)). +/// - values: The `N` Tensors to concatenate. Their ranks and types must match, +/// and their sizes must match in all dimensions except `concat_dim`. +/// +/// - Output output: A `Tensor` with the concatenation of values stacked along the +/// `concat_dim` dimension. This tensor's shape matches that of `values` except +/// in `concat_dim` where it has the sum of the sizes. +@inlinable @inline(__always) +public static func concat( + concatDim: Tensor, + _ values: [Tensor] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Concat", nOutputs) + op.updateAttribute("N", values.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(concatDim) + op.addInputList(values) + return op.execute(Int(1)) +} + +/// Computes offsets of concat inputs within its output. +/// +/// For example: +/// +/// ``` +/// # 'x' is [2, 2, 7] +/// # 'y' is [2, 3, 7] +/// # 'z' is [2, 5, 7] +/// concat_offset(2, [x, y, z]) => [0, 0, 0], [0, 2, 0], [0, 5, 0] +/// ``` +/// +/// This is typically used by gradient computations for a concat operation. +/// +/// - Parameters: +/// - concat_dim: The dimension along which to concatenate. +/// - shape: The `N` int32 vectors representing shape of tensors being concatenated. +/// +/// - Output offset: The `N` int32 vectors representing the starting offset +/// of input tensors within the concatenated output. +@inlinable @inline(__always) +public static func concatOffset( + concatDim: Tensor, + shape: [Tensor] +) -> [Tensor] { + let nOutputs = Int(shape.count) + let op = makeOp("ConcatOffset", nOutputs) + op.updateAttribute("N", shape.count) + op.addInput(concatDim) + op.addInputList(shape) + return op.execute(Int(shape.count)) +} + +/// Concatenates tensors along one dimension. +/// +/// - Parameters: +/// - values: List of `N` Tensors to concatenate. Their ranks and types must match, +/// and their sizes must match in all dimensions except `concat_dim`. +/// - axis: 0-D. The dimension along which to concatenate. Must be in the +/// range [-rank(values), rank(values)). +/// +/// - Output output: A `Tensor` with the concatenation of values stacked along the +/// `concat_dim` dimension. This tensor's shape matches that of `values` except +/// in `concat_dim` where it has the sum of the sizes. +@inlinable @inline(__always) +public static func concatV2< + T: TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + _ values: [Tensor], + axis: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ConcatV2", nOutputs) + op.updateAttribute("N", values.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInputList(values) + op.addInput(axis) + return op.execute(Int(1)) +} + +/// Creates a dataset that concatenates `input_dataset` with `another_dataset`. +@inlinable @inline(__always) +public static func concatenateDataset( + inputDataset: VariantHandle, + anotherDataset: VariantHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ConcatenateDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(anotherDataset) + return op.execute(Int(1)) +} + +/// Sets up the centralized structures for a distributed TPU system. +/// +/// - Attrs: +/// - embedding_config: Reserved. Do not use. +/// - tpu_embedding_config: Serialized tensorflow.tpu.TPUEmbeddingConfiguration that +/// describes the embedding lookups of the program. +/// - is_global_init: Reserved. Do not use. +/// +/// - Output topology: A serialized tensorflow.tpu.TopologyProto that describes the TPU +/// topology. +@inlinable @inline(__always) +public static func configureDistributedTPU( + embeddingConfig: String, + tpuEmbeddingConfig: String, + isGlobalInit: Bool = false +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("ConfigureDistributedTPU", nOutputs) + op.updateAttribute("embedding_config", embeddingConfig) + op.updateAttribute("tpu_embedding_config", tpuEmbeddingConfig) + op.updateAttribute("is_global_init", isGlobalInit) + return op.execute(Int(1)) +} + +/// Returns the complex conjugate of a complex number. +/// +/// Given a tensor `input` of complex numbers, this operation returns a tensor of +/// complex numbers that are the complex conjugate of each element in `input`. The +/// complex numbers in `input` must be of the form \\(a + bj\\), where *a* is the +/// real part and *b* is the imaginary part. +/// +/// The complex conjugate returned by this operation is of the form \\(a - bj\\). +/// +/// For example: +/// +/// ``` +/// # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] +/// tf.conj(input) ==> [-2.25 - 4.75j, 3.25 - 5.75j] +/// ``` +@inlinable @inline(__always) +public static func conj( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conj", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Shuffle dimensions of x according to a permutation and conjugate the result. +/// +/// The output `y` has the same rank as `x`. The shapes of `x` and `y` satisfy: +/// `y.shape[i] == x.shape[perm[i]] for i in [0, 1, ..., rank(x) - 1]` +/// `y[i,j,k,...,s,t,u] == conj(x[perm[i], perm[j], perm[k],...,perm[s], perm[t], perm[u]])` +@inlinable @inline(__always) +public static func conjugateTranspose< + T: TensorFlowScalar, + Tperm: BinaryInteger & TensorFlowScalar +>( + _ x: Tensor, + perm: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ConjugateTranspose", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tperm", Tperm.tensorFlowDataType) + op.addInput(x) + op.addInput(perm) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func constructionFails( +) { + let nOutputs = 0 + let op = makeOp("ConstructionFails", nOutputs) + + op.execute() +} + +/// This op consumes a lock created by `MutexLock`. +/// +/// This op exists to consume a tensor created by `MutexLock` (other than +/// direct control dependencies). It should be the only that consumes the tensor, +/// and will raise an error if it is not. Its only purpose is to keep the +/// mutex lock tensor alive until it is consumed by this op. +/// +/// **NOTE**: This operation must run on the same device as its input. This may +/// be enforced via the `colocate_with` mechanism. +/// +/// - Parameter mutex_lock: A tensor returned by `MutexLock`. +@inlinable @inline(__always) +public static func consumeMutexLock( + mutexLock: VariantHandle +) { + let nOutputs = 0 + let op = makeOp("ConsumeMutexLock", nOutputs) + op.addInput(mutexLock) + op.execute() +} + +/// Does nothing. Serves as a control trigger for scheduling. +/// +/// Only useful as a placeholder for control edges. +@inlinable @inline(__always) +public static func controlTrigger( +) { + let nOutputs = 0 + let op = makeOp("ControlTrigger", nOutputs) + + op.execute() +} + +/// Computes a 2-D convolution given 4-D `input` and `filter` tensors. +/// +/// Given an input tensor of shape `[batch, in_height, in_width, in_channels]` +/// and a filter / kernel tensor of shape +/// `[filter_height, filter_width, in_channels, out_channels]`, this op +/// performs the following: +/// +/// 1. Flattens the filter to a 2-D matrix with shape +/// `[filter_height * filter_width * in_channels, output_channels]`. +/// 2. Extracts image patches from the input tensor to form a *virtual* +/// tensor of shape `[batch, out_height, out_width, +/// filter_height * filter_width * in_channels]`. +/// 3. For each patch, right-multiplies the filter matrix and the image patch +/// vector. +/// +/// In detail, with the default NHWC format, +/// +/// output[b, i, j, k] = +/// sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] * +/// filter[di, dj, q, k] +/// +/// Must have `strides[0] = strides[3] = 1`. For the most common case of the same +/// horizontal and vertices strides, `strides = [1, stride, stride, 1]`. +/// +/// - Parameters: +/// - input: A 4-D tensor. The dimension order is interpreted according to the value +/// of `data_format`, see below for details. +/// - filter: A 4-D tensor of shape +/// `[filter_height, filter_width, in_channels, out_channels]` +/// +/// - Attrs: +/// - strides: 1-D tensor of length 4. The stride of the sliding window for each +/// dimension of `input`. The dimension order is determined by the value of +/// `data_format`, see below for details. +/// - padding: The type of padding algorithm to use. +/// - explicit_paddings: If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith +/// dimension, the amount of padding inserted before and after the dimension is +/// `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If +/// `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, height, width, channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, channels, height, width]. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each +/// filter element on that dimension. The dimension order is determined by the +/// value of `data_format`, see above for details. Dilations in the batch and +/// depth dimensions must be 1. +/// +/// - Output output: A 4-D tensor. The dimension order is determined by the value of +/// `data_format`, see below for details. +@inlinable @inline(__always) +public static func conv2D( + _ input: Tensor, + filter: Tensor, + strides: [Int32], + useCudnnOnGpu: Bool = true, + padding: Padding2, + explicitPaddings: [Int32], + dataFormat: DataFormat = .nhwc, + dilations: [Int32] = [1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conv2D", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("use_cudnn_on_gpu", useCudnnOnGpu) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("explicit_paddings", explicitPaddings) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + return op.execute(Int(1)) +} + +/// Computes the gradients of convolution with respect to the filter. +/// +/// - Parameters: +/// - input: 4-D with shape `[batch, in_height, in_width, in_channels]`. +/// - filter_sizes: An integer vector representing the tensor shape of `filter`, +/// where `filter` is a 4-D +/// `[filter_height, filter_width, in_channels, out_channels]` tensor. +/// - out_backprop: 4-D with shape `[batch, out_height, out_width, out_channels]`. +/// Gradients w.r.t. the output of the convolution. +/// +/// - Attrs: +/// - strides: The stride of the sliding window for each dimension of the input +/// of the convolution. Must be in the same order as the dimension specified with +/// format. +/// - padding: The type of padding algorithm to use. +/// - explicit_paddings: If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith +/// dimension, the amount of padding inserted before and after the dimension is +/// `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If +/// `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter +/// element on that dimension. The dimension order is determined by the value of +/// `data_format`, see above for details. Dilations in the batch and depth +/// dimensions must be 1. +/// +/// - Output output: 4-D with shape +/// `[filter_height, filter_width, in_channels, out_channels]`. Gradient w.r.t. +/// the `filter` input of the convolution. +@inlinable @inline(__always) +public static func conv2DBackpropFilter( + _ input: Tensor, + filterSizes: Tensor, + outBackprop: Tensor, + strides: [Int32], + useCudnnOnGpu: Bool = true, + padding: Padding2, + explicitPaddings: [Int32], + dataFormat: DataFormat = .nhwc, + dilations: [Int32] = [1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conv2DBackpropFilter", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("use_cudnn_on_gpu", useCudnnOnGpu) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("explicit_paddings", explicitPaddings) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filterSizes) + op.addInput(outBackprop) + return op.execute(Int(1)) +} + +/// Computes the gradients of convolution with respect to the input. +/// +/// - Parameters: +/// - input_sizes: An integer vector representing the shape of `input`, +/// where `input` is a 4-D `[batch, height, width, channels]` tensor. +/// - filter: 4-D with shape +/// `[filter_height, filter_width, in_channels, out_channels]`. +/// - out_backprop: 4-D with shape `[batch, out_height, out_width, out_channels]`. +/// Gradients w.r.t. the output of the convolution. +/// +/// - Attrs: +/// - strides: The stride of the sliding window for each dimension of the input +/// of the convolution. Must be in the same order as the dimension specified with +/// format. +/// - padding: The type of padding algorithm to use. +/// - explicit_paddings: If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith +/// dimension, the amount of padding inserted before and after the dimension is +/// `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If +/// `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter +/// element on that dimension. The dimension order is determined by the value of +/// `data_format`, see above for details. Dilations in the batch and depth +/// dimensions must be 1. +/// +/// - Output output: 4-D with shape `[batch, in_height, in_width, in_channels]`. Gradient +/// w.r.t. the input of the convolution. +@inlinable @inline(__always) +public static func conv2DBackpropInput( + inputSizes: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + useCudnnOnGpu: Bool = true, + padding: Padding2, + explicitPaddings: [Int32], + dataFormat: DataFormat = .nhwc, + dilations: [Int32] = [1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conv2DBackpropInput", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("use_cudnn_on_gpu", useCudnnOnGpu) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("explicit_paddings", explicitPaddings) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(inputSizes) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) +} + +/// Computes a 3-D convolution given 5-D `input` and `filter` tensors. +/// +/// In signal processing, cross-correlation is a measure of similarity of +/// two waveforms as a function of a time-lag applied to one of them. This +/// is also known as a sliding dot product or sliding inner-product. +/// +/// Our Conv3D implements a form of cross-correlation. +/// +/// - Parameters: +/// - input: Shape `[batch, in_depth, in_height, in_width, in_channels]`. +/// - filter: Shape `[filter_depth, filter_height, filter_width, in_channels, +/// out_channels]`. `in_channels` must match between `input` and `filter`. +/// +/// - Attrs: +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. +/// - dilations: 1-D tensor of length 5. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each +/// filter element on that dimension. The dimension order is determined by the +/// value of `data_format`, see above for details. Dilations in the batch and +/// depth dimensions must be 1. +@inlinable @inline(__always) +public static func conv3D( + _ input: Tensor, + filter: Tensor, + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc, + dilations: [Int32] = [1, 1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conv3D", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + return op.execute(Int(1)) +} + +/// Computes the gradients of 3-D convolution with respect to the filter. +/// +/// - Parameters: +/// - input: Shape `[batch, depth, rows, cols, in_channels]`. +/// - filter: Shape `[depth, rows, cols, in_channels, out_channels]`. +/// `in_channels` must match between `input` and `filter`. +/// - out_backprop: Backprop signal of shape `[batch, out_depth, out_rows, out_cols, +/// out_channels]`. +/// +/// - Attrs: +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +@inlinable @inline(__always) +public static func conv3DBackpropFilter( + _ input: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conv3DBackpropFilter", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) +} + +/// Computes the gradients of 3-D convolution with respect to the filter. +/// +/// - Parameters: +/// - input: Shape `[batch, depth, rows, cols, in_channels]`. +/// - filter_sizes: An integer vector representing the tensor shape of `filter`, +/// where `filter` is a 5-D +/// `[filter_depth, filter_height, filter_width, in_channels, out_channels]` +/// tensor. +/// - out_backprop: Backprop signal of shape `[batch, out_depth, out_rows, out_cols, +/// out_channels]`. +/// +/// - Attrs: +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. +/// - dilations: 1-D tensor of length 5. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each +/// filter element on that dimension. The dimension order is determined by the +/// value of `data_format`, see above for details. Dilations in the batch and +/// depth dimensions must be 1. +@inlinable @inline(__always) +public static func conv3DBackpropFilterV2( + _ input: Tensor, + filterSizes: Tensor, + outBackprop: Tensor, + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc, + dilations: [Int32] = [1, 1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conv3DBackpropFilterV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filterSizes) + op.addInput(outBackprop) + return op.execute(Int(1)) +} + +/// Computes the gradients of 3-D convolution with respect to the input. +/// +/// - Parameters: +/// - input: Shape `[batch, depth, rows, cols, in_channels]`. +/// - filter: Shape `[depth, rows, cols, in_channels, out_channels]`. +/// `in_channels` must match between `input` and `filter`. +/// - out_backprop: Backprop signal of shape `[batch, out_depth, out_rows, out_cols, +/// out_channels]`. +/// +/// - Attrs: +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +@inlinable @inline(__always) +public static func conv3DBackpropInput( + _ input: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conv3DBackpropInput", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) +} + +/// Computes the gradients of 3-D convolution with respect to the input. +/// +/// - Parameters: +/// - input_sizes: An integer vector representing the tensor shape of `input`, +/// where `input` is a 5-D +/// `[batch, depth, rows, cols, in_channels]` tensor. +/// - filter: Shape `[depth, rows, cols, in_channels, out_channels]`. +/// `in_channels` must match between `input` and `filter`. +/// - out_backprop: Backprop signal of shape `[batch, out_depth, out_rows, out_cols, +/// out_channels]`. +/// +/// - Attrs: +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. +/// - dilations: 1-D tensor of length 5. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each +/// filter element on that dimension. The dimension order is determined by the +/// value of `data_format`, see above for details. Dilations in the batch and +/// depth dimensions must be 1. +@inlinable @inline(__always) +public static func conv3DBackpropInputV2< + T: FloatingPoint & TensorFlowScalar, + Tshape: BinaryInteger & TensorFlowScalar +>( + inputSizes: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc, + dilations: [Int32] = [1, 1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conv3DBackpropInputV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("Tshape", Tshape.tensorFlowDataType) + op.addInput(inputSizes) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) +} + +/// Copy Op. +/// +/// Performs CPU-to-CPU or GPU-to-GPU deep-copying of tensor, depending on the +/// device on which the tensor is allocated. +/// N.B.: If the all downstream attached debug ops are disabled given the current +/// gRPC gating status, the output will simply forward the input tensor without +/// deep-copying. See the documentation of Debug* ops for more details. +/// +/// Unlike the CopyHost Op, this op does not have HostMemory constraint on its +/// input or output. +/// +/// - Parameter input: Input tensor. +/// +/// - Attrs: +/// - tensor_name: The name of the input tensor. +/// - debug_ops_spec: A list of debug op spec (op, url, gated_grpc) for attached debug +/// ops. Each element of the list has the format +/// ;;, wherein gated_grpc is boolean represented +/// as 0/1. E.g., "DebugIdentity;grpc://foo:3333;1", +/// "DebugIdentity;file:///tmp/tfdbg_1;0". +/// +/// - Output output: Output tensor, deep-copied from input. +@inlinable @inline(__always) +public static func copy( + _ input: Tensor, + tensorName: String, + debugOpsSpec: [String] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Copy", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("tensor_name", tensorName) + op.updateAttribute("debug_ops_spec", debugOpsSpec) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Copy Host Op. +/// +/// Performs CPU-to-CPU deep-copying of tensor. +/// N.B.: If the all downstream attached debug ops are disabled given the current +/// gRPC gating status, the output will simply forward the input tensor without +/// deep-copying. See the documentation of Debug* ops for more details. +/// +/// Unlike the Copy Op, this op has HostMemory constraint on its input or output. +/// +/// - Parameter input: Input tensor. +/// +/// - Attrs: +/// - tensor_name: The name of the input tensor. +/// - debug_ops_spec: A list of debug op spec (op, url, gated_grpc) for attached debug +/// ops. Each element of the list has the format +/// ;;, wherein gated_grpc is boolean represented +/// as 0/1. E.g., "DebugIdentity;grpc://foo:3333;1", +/// "DebugIdentity;file:///tmp/tfdbg_1;0". +/// +/// - Output output: Output tensor, deep-copied from input. +@inlinable @inline(__always) +public static func copyHost( + _ input: Tensor, + tensorName: String, + debugOpsSpec: [String] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CopyHost", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("tensor_name", tensorName) + op.updateAttribute("debug_ops_spec", debugOpsSpec) + op.addInput(input) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func copyOp( + _ a: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CopyOp", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + return op.execute(Int(1)) +} + +/// Computes cos of x element-wise. +@inlinable @inline(__always) +public static func cos( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Cos", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes hyperbolic cosine of x element-wise. +@inlinable @inline(__always) +public static func cosh( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Cosh", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func createSummaryDbWriter( + writer: ResourceHandle, + dbUri: StringTensor, + experimentName: StringTensor, + runName: StringTensor, + userName: StringTensor +) { + let nOutputs = 0 + let op = makeOp("CreateSummaryDbWriter", nOutputs) + op.addInput(writer) + op.addInput(dbUri) + op.addInput(experimentName) + op.addInput(runName) + op.addInput(userName) + op.execute() +} + +@inlinable @inline(__always) +public static func createSummaryFileWriter( + writer: ResourceHandle, + logdir: StringTensor, + maxQueue: Tensor, + flushMillis: Tensor, + filenameSuffix: StringTensor +) { + let nOutputs = 0 + let op = makeOp("CreateSummaryFileWriter", nOutputs) + op.addInput(writer) + op.addInput(logdir) + op.addInput(maxQueue) + op.addInput(flushMillis) + op.addInput(filenameSuffix) + op.execute() +} + +/// Extracts crops from the input image tensor and resizes them. +/// +/// Extracts crops from the input image tensor and resizes them using bilinear +/// sampling or nearest neighbor sampling (possibly with aspect ratio change) to a +/// common output size specified by `crop_size`. This is more general than the +/// `crop_to_bounding_box` op which extracts a fixed size slice from the input image +/// and does not allow resizing or aspect ratio change. +/// +/// Returns a tensor with `crops` from the input `image` at positions defined at the +/// bounding box locations in `boxes`. The cropped boxes are all resized (with +/// bilinear or nearest neighbor interpolation) to a fixed +/// `size = [crop_height, crop_width]`. The result is a 4-D tensor +/// `[num_boxes, crop_height, crop_width, depth]`. The resizing is corner aligned. +/// In particular, if `boxes = [[0, 0, 1, 1]]`, the method will give identical +/// results to using `tf.image.resize_bilinear()` or +/// `tf.image.resize_nearest_neighbor()`(depends on the `method` argument) with +/// `align_corners=True`. +/// +/// - Parameters: +/// - image: A 4-D tensor of shape `[batch, image_height, image_width, depth]`. +/// Both `image_height` and `image_width` need to be positive. +/// - boxes: A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor +/// specifies the coordinates of a box in the `box_ind[i]` image and is specified +/// in normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of +/// `y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the +/// `[0, 1]` interval of normalized image height is mapped to +/// `[0, image_height - 1]` in image height coordinates. We do allow `y1` > `y2`, in +/// which case the sampled crop is an up-down flipped version of the original +/// image. The width dimension is treated similarly. Normalized coordinates +/// outside the `[0, 1]` range are allowed, in which case we use +/// `extrapolation_value` to extrapolate the input image values. +/// - box_ind: A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`. +/// The value of `box_ind[i]` specifies the image that the `i`-th box refers to. +/// - crop_size: A 1-D tensor of 2 elements, `size = [crop_height, crop_width]`. All +/// cropped image patches are resized to this size. The aspect ratio of the image +/// content is not preserved. Both `crop_height` and `crop_width` need to be +/// positive. +/// +/// - Attrs: +/// - method: A string specifying the sampling method for resizing. It can be either +/// `"bilinear"` or `"nearest"` and default to `"bilinear"`. Currently two sampling +/// methods are supported: Bilinear and Nearest Neighbor. +/// - extrapolation_value: Value used for extrapolation, when applicable. +/// +/// - Output crops: A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`. +@inlinable @inline(__always) +public static func cropAndResize( + image: Tensor, + boxes: Tensor, + boxInd: Tensor, + cropSize: Tensor, + method: Method = .bilinear, + extrapolationValue: Double = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CropAndResize", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("method", method.cName) + op.updateAttribute("extrapolation_value", extrapolationValue) + op.addInput(image) + op.addInput(boxes) + op.addInput(boxInd) + op.addInput(cropSize) + return op.execute(Int(1)) +} + +/// Computes the gradient of the crop_and_resize op wrt the input boxes tensor. +/// +/// - Parameters: +/// - grads: A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`. +/// - image: A 4-D tensor of shape `[batch, image_height, image_width, depth]`. +/// Both `image_height` and `image_width` need to be positive. +/// - boxes: A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor +/// specifies the coordinates of a box in the `box_ind[i]` image and is specified +/// in normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of +/// `y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the +/// `[0, 1]` interval of normalized image height is mapped to +/// `[0, image_height - 1] in image height coordinates. We do allow y1 > y2, in +/// which case the sampled crop is an up-down flipped version of the original +/// image. The width dimension is treated similarly. Normalized coordinates +/// outside the `[0, 1]` range are allowed, in which case we use +/// `extrapolation_value` to extrapolate the input image values. +/// - box_ind: A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`. +/// The value of `box_ind[i]` specifies the image that the `i`-th box refers to. +/// +/// - Attr method: A string specifying the interpolation method. Only 'bilinear' is +/// supported for now. +/// +/// - Output output: A 2-D tensor of shape `[num_boxes, 4]`. +@inlinable @inline(__always) +public static func cropAndResizeGradBoxes( + grads: Tensor, + image: Tensor, + boxes: Tensor, + boxInd: Tensor, + method: Method3 = .bilinear +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CropAndResizeGradBoxes", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("method", method.cName) + op.addInput(grads) + op.addInput(image) + op.addInput(boxes) + op.addInput(boxInd) + return op.execute(Int(1)) +} + +/// Computes the gradient of the crop_and_resize op wrt the input image tensor. +/// +/// - Parameters: +/// - grads: A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`. +/// - boxes: A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor +/// specifies the coordinates of a box in the `box_ind[i]` image and is specified +/// in normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of +/// `y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the +/// `[0, 1]` interval of normalized image height is mapped to +/// `[0, image_height - 1] in image height coordinates. We do allow y1 > y2, in +/// which case the sampled crop is an up-down flipped version of the original +/// image. The width dimension is treated similarly. Normalized coordinates +/// outside the `[0, 1]` range are allowed, in which case we use +/// `extrapolation_value` to extrapolate the input image values. +/// - box_ind: A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`. +/// The value of `box_ind[i]` specifies the image that the `i`-th box refers to. +/// - image_size: A 1-D tensor with value `[batch, image_height, image_width, depth]` +/// containing the original image size. Both `image_height` and `image_width` need +/// to be positive. +/// +/// - Attr method: A string specifying the interpolation method. Only 'bilinear' is +/// supported for now. +/// +/// - Output output: A 4-D tensor of shape `[batch, image_height, image_width, depth]`. +@inlinable @inline(__always) +public static func cropAndResizeGradImage( + grads: Tensor, + boxes: Tensor, + boxInd: Tensor, + imageSize: Tensor, + method: Method = .bilinear +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CropAndResizeGradImage", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("method", method.cName) + op.addInput(grads) + op.addInput(boxes) + op.addInput(boxInd) + op.addInput(imageSize) + return op.execute(Int(1)) +} + +/// Compute the pairwise cross product. +/// +/// `a` and `b` must be the same shape; they can either be simple 3-element vectors, +/// or any shape where the innermost dimension is 3. In the latter case, each pair +/// of corresponding 3-element vectors is cross-multiplied independently. +/// +/// - Parameters: +/// - a: A tensor containing 3-element vectors. +/// - b: Another tensor, of same type and shape as `a`. +/// +/// - Output product: Pairwise cross product of the vectors in `a` and `b`. +@inlinable @inline(__always) +public static func cross( + _ a: Tensor, + _ b: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Cross", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(b) + return op.execute(Int(1)) +} + +/// An Op to sum inputs across replicated TPU instances. +/// +/// Each instance supplies its own input. +/// +/// For example, suppose there are 8 TPU instances: `[A, B, C, D, E, F, G, H]`. +/// Passing group_assignment=`[[0,2,4,6],[1,3,5,7]]` sets `A, C, E, G` as group 0, +/// and `B, D, F, H` as group 1. Thus we get the outputs: +/// `[A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H]`. +/// +/// - Parameters: +/// - input: The local input to the sum. +/// - group_assignment: An int32 tensor with shape +/// [num_groups, num_replicas_per_group]. `group_assignment[i]` represents the +/// replica ids in the ith subgroup. +/// +/// - Attr T: The type of elements to be summed. +/// +/// - Output output: The sum of all the distributed inputs. +@inlinable @inline(__always) +public static func crossReplicaSum( + _ input: Tensor, + groupAssignment: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CrossReplicaSum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(groupAssignment) + return op.execute(Int(1)) +} + +/// A RNN backed by cuDNN. +/// +/// Computes the RNN from the input and initial states, with respect to the params +/// buffer. +/// +/// rnn_mode: Indicates the type of the RNN model. +/// input_mode: Indicate whether there is a linear projection between the input and +/// the actual computation before the first layer. 'skip_input' is only allowed +/// when input_size == num_units; 'auto_select' implies 'skip_input' when +/// input_size == num_units; otherwise, it implies 'linear_input'. +/// direction: Indicates whether a bidirectional model will be used. Should be +/// "unidirectional" or "bidirectional". +/// dropout: Dropout probability. When set to 0., dropout is disabled. +/// seed: The 1st part of a seed to initialize dropout. +/// seed2: The 2nd part of a seed to initialize dropout. +/// input: A 3-D tensor with the shape of [seq_length, batch_size, input_size]. +/// input_h: A 3-D tensor with the shape of [num_layer * dir, batch_size, +/// num_units]. +/// input_c: For LSTM, a 3-D tensor with the shape of +/// [num_layer * dir, batch, num_units]. For other models, it is ignored. +/// params: A 1-D tensor that contains the weights and biases in an opaque layout. +/// The size must be created through CudnnRNNParamsSize, and initialized +/// separately. Note that they might not be compatible across different +/// generations. So it is a good idea to save and restore +/// output: A 3-D tensor with the shape of [seq_length, batch_size, +/// dir * num_units]. +/// output_h: The same shape has input_h. +/// output_c: The same shape as input_c for LSTM. An empty tensor for other models. +/// is_training: Indicates whether this operation is used for inferenece or +/// training. +/// reserve_space: An opaque tensor that can be used in backprop calculation. It +/// is only produced if is_training is false. +@inlinable @inline(__always) +public static func cudnnRNN( + _ input: Tensor, + inputH: Tensor, + inputC: Tensor, + params: Tensor, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0, + isTraining: Bool = true +) -> (output: Tensor, outputH: Tensor, outputC: Tensor, reserveSpace: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("CudnnRNN", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("is_training", isTraining) + op.addInput(input) + op.addInput(inputH) + op.addInput(inputC) + op.addInput(params) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Backprop step of CudnnRNN. +/// +/// Compute the backprop of both data and weights in a RNN. +/// +/// rnn_mode: Indicates the type of the RNN model. +/// input_mode: Indicate whether there is a linear projection between the input and +/// the actual computation before the first layer. 'skip_input' is only allowed +/// when input_size == num_units; 'auto_select' implies 'skip_input' when +/// input_size == num_units; otherwise, it implies 'linear_input'. +/// direction: Indicates whether a bidirectional model will be used. Should be +/// "unidirectional" or "bidirectional". +/// dropout: Dropout probability. When set to 0., dropout is disabled. +/// seed: The 1st part of a seed to initialize dropout. +/// seed2: The 2nd part of a seed to initialize dropout. +/// input: A 3-D tensor with the shape of [seq_length, batch_size, input_size]. +/// input_h: A 3-D tensor with the shape of [num_layer * dir, batch_size, +/// num_units]. +/// input_c: For LSTM, a 3-D tensor with the shape of +/// [num_layer * dir, batch, num_units]. For other models, it is ignored. +/// params: A 1-D tensor that contains the weights and biases in an opaque layout. +/// The size must be created through CudnnRNNParamsSize, and initialized +/// separately. Note that they might not be compatible across different +/// generations. So it is a good idea to save and restore +/// output: A 3-D tensor with the shape of [seq_length, batch_size, +/// dir * num_units]. +/// output_h: The same shape has input_h. +/// output_c: The same shape as input_c for LSTM. An empty tensor for other models. +/// output_backprop: A 3-D tensor with the same shape as output in the forward pass. +/// output_h_backprop: A 3-D tensor with the same shape as output_h in the forward +/// pass. +/// output_c_backprop: A 3-D tensor with the same shape as output_c in the forward +/// pass. +/// reserve_space: The same reserve_space produced in for forward operation. +/// input_backprop: The backprop to input in the forward pass. Has the same shape +/// as input. +/// input_h_backprop: The backprop to input_h in the forward pass. Has the same +/// shape as input_h. +/// input_c_backprop: The backprop to input_c in the forward pass. Has the same +/// shape as input_c. +/// params_backprop: The backprop to the params buffer in the forward pass. Has the +/// same shape as params. +@inlinable @inline(__always) +public static func cudnnRNNBackprop( + _ input: Tensor, + inputH: Tensor, + inputC: Tensor, + params: Tensor, + output: Tensor, + outputH: Tensor, + outputC: Tensor, + outputBackprop: Tensor, + outputHBackprop: Tensor, + outputCBackprop: Tensor, + reserveSpace: Tensor, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> (inputBackprop: Tensor, inputHBackprop: Tensor, inputCBackprop: Tensor, paramsBackprop: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("CudnnRNNBackprop", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(input) + op.addInput(inputH) + op.addInput(inputC) + op.addInput(params) + op.addInput(output) + op.addInput(outputH) + op.addInput(outputC) + op.addInput(outputBackprop) + op.addInput(outputHBackprop) + op.addInput(outputCBackprop) + op.addInput(reserveSpace) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Backprop step of CudnnRNN. +/// +/// Compute the backprop of both data and weights in a RNN. Takes an extra +/// "host_reserved" inupt than CudnnRNNBackprop, which is used to determine RNN +/// cudnnRNNAlgo_t and cudnnMathType_t. +/// +/// rnn_mode: Indicates the type of the RNN model. +/// input_mode: Indicates whether there is a linear projection between the input and +/// the actual computation before the first layer. 'skip_input' is only allowed +/// when input_size == num_units; 'auto_select' implies 'skip_input' when +/// input_size == num_units; otherwise, it implies 'linear_input'. +/// direction: Indicates whether a bidirectional model will be used. Should be +/// "unidirectional" or "bidirectional". +/// dropout: Dropout probability. When set to 0., dropout is disabled. +/// seed: The 1st part of a seed to initialize dropout. +/// seed2: The 2nd part of a seed to initialize dropout. +/// input: A 3-D tensor with the shape of [seq_length, batch_size, input_size]. +/// input_h: A 3-D tensor with the shape of [num_layer * dir, batch_size, +/// num_units]. +/// input_c: For LSTM, a 3-D tensor with the shape of +/// [num_layer * dir, batch, num_units]. For other models, it is ignored. +/// params: A 1-D tensor that contains the weights and biases in an opaque layout. +/// The size must be created through CudnnRNNParamsSize, and initialized +/// separately. Note that they might not be compatible across different +/// generations. So it is a good idea to save and restore +/// output: A 3-D tensor with the shape of [seq_length, batch_size, +/// dir * num_units]. +/// output_h: The same shape has input_h. +/// output_c: The same shape as input_c for LSTM. An empty tensor for other models. +/// output_backprop: A 3-D tensor with the same shape as output in the forward pass. +/// output_h_backprop: A 3-D tensor with the same shape as output_h in the forward +/// pass. +/// output_c_backprop: A 3-D tensor with the same shape as output_c in the forward +/// pass. +/// reserve_space: The same reserve_space produced in the forward operation. +/// host_reserved: The same host_reserved produced in the forward operation. +/// input_backprop: The backprop to input in the forward pass. Has the same shape +/// as input. +/// input_h_backprop: The backprop to input_h in the forward pass. Has the same +/// shape as input_h. +/// input_c_backprop: The backprop to input_c in the forward pass. Has the same +/// shape as input_c. +/// params_backprop: The backprop to the params buffer in the forward pass. Has the +/// same shape as params. +@inlinable @inline(__always) +public static func cudnnRNNBackpropV2( + _ input: Tensor, + inputH: Tensor, + inputC: Tensor, + params: Tensor, + output: Tensor, + outputH: Tensor, + outputC: Tensor, + outputBackprop: Tensor, + outputHBackprop: Tensor, + outputCBackprop: Tensor, + reserveSpace: Tensor, + hostReserved: Tensor, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> (inputBackprop: Tensor, inputHBackprop: Tensor, inputCBackprop: Tensor, paramsBackprop: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("CudnnRNNBackpropV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(input) + op.addInput(inputH) + op.addInput(inputC) + op.addInput(params) + op.addInput(output) + op.addInput(outputH) + op.addInput(outputC) + op.addInput(outputBackprop) + op.addInput(outputHBackprop) + op.addInput(outputCBackprop) + op.addInput(reserveSpace) + op.addInput(hostReserved) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Backprop step of CudnnRNNV3. +/// +/// Compute the backprop of both data and weights in a RNN. Takes an extra +/// "sequence_lengths" input than CudnnRNNBackprop. +/// +/// rnn_mode: Indicates the type of the RNN model. +/// input_mode: Indicates whether there is a linear projection between the input and +/// the actual computation before the first layer. 'skip_input' is only allowed +/// when input_size == num_units; 'auto_select' implies 'skip_input' when +/// input_size == num_units; otherwise, it implies 'linear_input'. +/// direction: Indicates whether a bidirectional model will be used. Should be +/// "unidirectional" or "bidirectional". +/// dropout: Dropout probability. When set to 0., dropout is disabled. +/// seed: The 1st part of a seed to initialize dropout. +/// seed2: The 2nd part of a seed to initialize dropout. +/// input: If time_major is true, this is a 3-D tensor with the shape of +/// [seq_length, batch_size, input_size]. If time_major is false, the shape is +/// [batch_size, seq_length, input_size]. +/// input_h: If time_major is true, this is a 3-D tensor with the shape of +/// [num_layer * dir, batch_size, num_units]. If time_major is false, the shape +/// is [batch_size, num_layer * dir, num_units]. +/// input_c: For LSTM, a 3-D tensor with the shape of +/// [num_layer * dir, batch, num_units]. For other models, it is ignored. +/// params: A 1-D tensor that contains the weights and biases in an opaque layout. +/// The size must be created through CudnnRNNParamsSize, and initialized +/// separately. Note that they might not be compatible across different +/// generations. So it is a good idea to save and restore +/// sequence_lengths: a vector of lengths of each input sequence. +/// output: If time_major is true, this is a 3-D tensor with the shape of +/// [seq_length, batch_size, dir * num_units]. If time_major is false, the +/// shape is [batch_size, seq_length, dir * num_units]. +/// output_h: The same shape has input_h. +/// output_c: The same shape as input_c for LSTM. An empty tensor for other models. +/// output_backprop: A 3-D tensor with the same shape as output in the forward pass. +/// output_h_backprop: A 3-D tensor with the same shape as output_h in the forward +/// pass. +/// output_c_backprop: A 3-D tensor with the same shape as output_c in the forward +/// pass. +/// time_major: Indicates whether the input/output format is time major or batch +/// major. +/// reserve_space: The same reserve_space produced in the forward operation. +/// input_backprop: The backprop to input in the forward pass. Has the same shape +/// as input. +/// input_h_backprop: The backprop to input_h in the forward pass. Has the same +/// shape as input_h. +/// input_c_backprop: The backprop to input_c in the forward pass. Has the same +/// shape as input_c. +/// params_backprop: The backprop to the params buffer in the forward pass. Has the +/// same shape as params. +@inlinable @inline(__always) +public static func cudnnRNNBackpropV3( + _ input: Tensor, + inputH: Tensor, + inputC: Tensor, + params: Tensor, + sequenceLengths: Tensor, + output: Tensor, + outputH: Tensor, + outputC: Tensor, + outputBackprop: Tensor, + outputHBackprop: Tensor, + outputCBackprop: Tensor, + reserveSpace: Tensor, + hostReserved: Tensor, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0, + timeMajor: Bool = true +) -> (inputBackprop: Tensor, inputHBackprop: Tensor, inputCBackprop: Tensor, paramsBackprop: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("CudnnRNNBackpropV3", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("time_major", timeMajor) + op.addInput(input) + op.addInput(inputH) + op.addInput(inputC) + op.addInput(params) + op.addInput(sequenceLengths) + op.addInput(output) + op.addInput(outputH) + op.addInput(outputC) + op.addInput(outputBackprop) + op.addInput(outputHBackprop) + op.addInput(outputCBackprop) + op.addInput(reserveSpace) + op.addInput(hostReserved) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Converts CudnnRNN params from canonical form to usable form. +/// +/// Writes a set of weights into the opaque params buffer so they can be used in +/// upcoming training or inferences. +/// +/// Note that the params buffer may not be compatible across different GPUs. So any +/// save and restoration should be converted to and from the canonical weights and +/// biases. +/// +/// num_layers: Specifies the number of layers in the RNN model. +/// num_units: Specifies the size of the hidden state. +/// input_size: Specifies the size of the input state. +/// weights: the canonical form of weights that can be used for saving +/// and restoration. They are more likely to be compatible across different +/// generations. +/// biases: the canonical form of biases that can be used for saving +/// and restoration. They are more likely to be compatible across different +/// generations. +/// num_params: number of parameter sets for all layers. +/// Each layer may contain multiple parameter sets, with each set consisting of +/// a weight matrix and a bias vector. +/// rnn_mode: Indicates the type of the RNN model. +/// input_mode: Indicate whether there is a linear projection between the input and +/// The actual computation before the first layer. 'skip_input' is only allowed +/// when input_size == num_units; 'auto_select' implies 'skip_input' when +/// input_size == num_units; otherwise, it implies 'linear_input'. +/// direction: Indicates whether a bidirectional model will be used. +/// dir = (direction == bidirectional) ? 2 : 1 +/// dropout: dropout probability. When set to 0., dropout is disabled. +/// seed: the 1st part of a seed to initialize dropout. +/// seed2: the 2nd part of a seed to initialize dropout. +@inlinable @inline(__always) +public static func cudnnRNNCanonicalToParams( + numLayers: Tensor, + numUnits: Tensor, + inputSize: Tensor, + weights: [Tensor], + biases: [Tensor], + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CudnnRNNCanonicalToParams", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("num_params", weights.count) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(numLayers) + op.addInput(numUnits) + op.addInput(inputSize) + op.addInputList(weights) + op.addInputList(biases) + return op.execute(Int(1)) +} + +/// Computes size of weights that can be used by a Cudnn RNN model. +/// +/// Return the params size that can be used by the Cudnn RNN model. Subsequent +/// weight allocation and initialization should use this size. +/// +/// num_layers: Specifies the number of layers in the RNN model. +/// num_units: Specifies the size of the hidden state. +/// input_size: Specifies the size of the input state. +/// rnn_mode: Indicates the type of the RNN model. +/// input_mode: Indicate whether there is a linear projection between the input and +/// The actual computation before the first layer. 'skip_input' is only allowed +/// when input_size == num_units; 'auto_select' implies 'skip_input' when +/// input_size == num_units; otherwise, it implies 'linear_input'. +/// direction: Indicates whether a bidirectional model will be used. +/// dir = (direction == bidirectional) ? 2 : 1 +/// dropout: dropout probability. When set to 0., dropout is disabled. +/// seed: the 1st part of a seed to initialize dropout. +/// seed2: the 2nd part of a seed to initialize dropout. +/// params_size: The size of the params buffer that should be allocated and +/// initialized for this RNN model. Note that this params buffer may not be +/// compatible across GPUs. Please use CudnnRNNParamsWeights and +/// CudnnRNNParamsBiases to save and restore them in a way that is compatible +/// across different runs. +@inlinable @inline(__always) +public static func cudnnRNNParamsSize( + numLayers: Tensor, + numUnits: Tensor, + inputSize: Tensor, + t: TensorDataType, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CudnnRNNParamsSize", nOutputs) + op.updateAttribute("T", t) + op.updateAttribute("S", S.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(numLayers) + op.addInput(numUnits) + op.addInput(inputSize) + return op.execute(Int(1)) +} + +/// Retrieves CudnnRNN params in canonical form. +/// +/// Retrieves a set of weights from the opaque params buffer that can be saved and +/// restored in a way compatible with future runs. +/// +/// Note that the params buffer may not be compatible across different GPUs. So any +/// save and restoration should be converted to and from the canonical weights and +/// biases. +/// +/// num_layers: Specifies the number of layers in the RNN model. +/// num_units: Specifies the size of the hidden state. +/// input_size: Specifies the size of the input state. +/// num_params: number of parameter sets for all layers. +/// Each layer may contain multiple parameter sets, with each set consisting of +/// a weight matrix and a bias vector. +/// weights: the canonical form of weights that can be used for saving +/// and restoration. They are more likely to be compatible across different +/// generations. +/// biases: the canonical form of biases that can be used for saving +/// and restoration. They are more likely to be compatible across different +/// generations. +/// rnn_mode: Indicates the type of the RNN model. +/// input_mode: Indicate whether there is a linear projection between the input and +/// The actual computation before the first layer. 'skip_input' is only allowed +/// when input_size == num_units; 'auto_select' implies 'skip_input' when +/// input_size == num_units; otherwise, it implies 'linear_input'. +/// direction: Indicates whether a bidirectional model will be used. +/// dir = (direction == bidirectional) ? 2 : 1 +/// dropout: dropout probability. When set to 0., dropout is disabled. +/// seed: the 1st part of a seed to initialize dropout. +/// seed2: the 2nd part of a seed to initialize dropout. +@inlinable @inline(__always) +public static func cudnnRNNParamsToCanonical( + numLayers: Tensor, + numUnits: Tensor, + inputSize: Tensor, + params: Tensor, + numParams: Int64, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> (weights: [Tensor], biases: [Tensor]) { + let nOutputs = Int(numParams) + Int(numParams) + let op = makeOp("CudnnRNNParamsToCanonical", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("num_params", numParams) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(numLayers) + op.addInput(numUnits) + op.addInput(inputSize) + op.addInput(params) + return op.execute(Int(numParams), Int(numParams)) +} + +/// A RNN backed by cuDNN. +/// +/// Computes the RNN from the input and initial states, with respect to the params +/// buffer. Produces one extra output "host_reserved" than CudnnRNN. +/// +/// rnn_mode: Indicates the type of the RNN model. +/// input_mode: Indicates whether there is a linear projection between the input and +/// the actual computation before the first layer. 'skip_input' is only allowed +/// when input_size == num_units; 'auto_select' implies 'skip_input' when +/// input_size == num_units; otherwise, it implies 'linear_input'. +/// direction: Indicates whether a bidirectional model will be used. Should be +/// "unidirectional" or "bidirectional". +/// dropout: Dropout probability. When set to 0., dropout is disabled. +/// seed: The 1st part of a seed to initialize dropout. +/// seed2: The 2nd part of a seed to initialize dropout. +/// input: A 3-D tensor with the shape of [seq_length, batch_size, input_size]. +/// input_h: A 3-D tensor with the shape of [num_layer * dir, batch_size, +/// num_units]. +/// input_c: For LSTM, a 3-D tensor with the shape of +/// [num_layer * dir, batch, num_units]. For other models, it is ignored. +/// params: A 1-D tensor that contains the weights and biases in an opaque layout. +/// The size must be created through CudnnRNNParamsSize, and initialized +/// separately. Note that they might not be compatible across different +/// generations. So it is a good idea to save and restore +/// output: A 3-D tensor with the shape of [seq_length, batch_size, +/// dir * num_units]. +/// output_h: The same shape has input_h. +/// output_c: The same shape as input_c for LSTM. An empty tensor for other models. +/// is_training: Indicates whether this operation is used for inferenece or +/// training. +/// reserve_space: An opaque tensor that can be used in backprop calculation. It +/// is only produced if is_training is true. +/// host_reserved: An opaque tensor that can be used in backprop calculation. It is +/// only produced if is_training is true. It is output on host memory rather than +/// device memory. +@inlinable @inline(__always) +public static func cudnnRNNV2( + _ input: Tensor, + inputH: Tensor, + inputC: Tensor, + params: Tensor, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0, + isTraining: Bool = true +) -> (output: Tensor, outputH: Tensor, outputC: Tensor, reserveSpace: Tensor, hostReserved: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("CudnnRNNV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("is_training", isTraining) + op.addInput(input) + op.addInput(inputH) + op.addInput(inputC) + op.addInput(params) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// A RNN backed by cuDNN. +/// +/// Computes the RNN from the input and initial states, with respect to the params +/// buffer. Accepts one extra input "sequence_lengths" than CudnnRNN. +/// +/// rnn_mode: Indicates the type of the RNN model. +/// input_mode: Indicates whether there is a linear projection between the input and +/// the actual computation before the first layer. 'skip_input' is only allowed +/// when input_size == num_units; 'auto_select' implies 'skip_input' when +/// input_size == num_units; otherwise, it implies 'linear_input'. +/// direction: Indicates whether a bidirectional model will be used. Should be +/// "unidirectional" or "bidirectional". +/// dropout: Dropout probability. When set to 0., dropout is disabled. +/// seed: The 1st part of a seed to initialize dropout. +/// seed2: The 2nd part of a seed to initialize dropout. +/// input: If time_major is true, this is a 3-D tensor with the shape of +/// [seq_length, batch_size, input_size]. If time_major is false, the shape is +/// [batch_size, seq_length, input_size]. +/// input_h: If time_major is true, this is a 3-D tensor with the shape of +/// [num_layer * dir, batch_size, num_units]. If time_major is false, the shape +/// is [batch_size, num_layer * dir, num_units]. +/// input_c: For LSTM, a 3-D tensor with the shape of +/// [num_layer * dir, batch, num_units]. For other models, it is ignored. +/// params: A 1-D tensor that contains the weights and biases in an opaque layout. +/// The size must be created through CudnnRNNParamsSize, and initialized +/// separately. Note that they might not be compatible across different +/// generations. So it is a good idea to save and restore +/// sequence_lengths: a vector of lengths of each input sequence. +/// output: If time_major is true, this is a 3-D tensor with the shape of +/// [seq_length, batch_size, dir * num_units]. If time_major is false, the +/// shape is [batch_size, seq_length, dir * num_units]. +/// output_h: The same shape has input_h. +/// output_c: The same shape as input_c for LSTM. An empty tensor for other models. +/// is_training: Indicates whether this operation is used for inferenece or +/// training. +/// time_major: Indicates whether the input/output format is time major or batch +/// major. +/// reserve_space: An opaque tensor that can be used in backprop calculation. It +/// is only produced if is_training is true. +@inlinable @inline(__always) +public static func cudnnRNNV3( + _ input: Tensor, + inputH: Tensor, + inputC: Tensor, + params: Tensor, + sequenceLengths: Tensor, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0, + isTraining: Bool = true, + timeMajor: Bool = true +) -> (output: Tensor, outputH: Tensor, outputC: Tensor, reserveSpace: Tensor, hostReserved: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("CudnnRNNV3", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("is_training", isTraining) + op.updateAttribute("time_major", timeMajor) + op.addInput(input) + op.addInput(inputH) + op.addInput(inputC) + op.addInput(params) + op.addInput(sequenceLengths) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// Compute the cumulative product of the tensor `x` along `axis`. +/// +/// By default, this op performs an inclusive cumprod, which means that the first +/// element of the input is identical to the first element of the output: +/// +/// ```python +/// tf.cumprod([a, b, c]) # => [a, a * b, a * b * c] +/// ``` +/// +/// By setting the `exclusive` kwarg to `True`, an exclusive cumprod is +/// performed instead: +/// +/// ```python +/// tf.cumprod([a, b, c], exclusive=True) # => [1, a, a * b] +/// ``` +/// +/// By setting the `reverse` kwarg to `True`, the cumprod is performed in the +/// opposite direction: +/// +/// ```python +/// tf.cumprod([a, b, c], reverse=True) # => [a * b * c, b * c, c] +/// ``` +/// +/// This is more efficient than using separate `tf.reverse` ops. +/// +/// The `reverse` and `exclusive` kwargs can also be combined: +/// +/// ```python +/// tf.cumprod([a, b, c], exclusive=True, reverse=True) # => [b * c, c, 1] +/// ``` +/// +/// - Parameters: +/// - x: A `Tensor`. Must be one of the following types: `float32`, `float64`, +/// `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, +/// `complex128`, `qint8`, `quint8`, `qint32`, `half`. +/// - axis: A `Tensor` of type `int32` (default: 0). Must be in the range +/// `[-rank(x), rank(x))`. +/// +/// - Attrs: +/// - exclusive: If `True`, perform exclusive cumprod. +/// - reverse: A `bool` (default: False). +@inlinable @inline(__always) +public static func cumprod< + T: Numeric & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + _ x: Tensor, + axis: Tensor, + exclusive: Bool = false, + reverse: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Cumprod", nOutputs) + op.updateAttribute("exclusive", exclusive) + op.updateAttribute("reverse", reverse) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(x) + op.addInput(axis) + return op.execute(Int(1)) +} + +/// Compute the cumulative sum of the tensor `x` along `axis`. +/// +/// By default, this op performs an inclusive cumsum, which means that the first +/// element of the input is identical to the first element of the output: +/// +/// ```python +/// tf.cumsum([a, b, c]) # => [a, a + b, a + b + c] +/// ``` +/// +/// By setting the `exclusive` kwarg to `True`, an exclusive cumsum is +/// performed instead: +/// +/// ```python +/// tf.cumsum([a, b, c], exclusive=True) # => [0, a, a + b] +/// ``` +/// +/// By setting the `reverse` kwarg to `True`, the cumsum is performed in the +/// opposite direction: +/// +/// ```python +/// tf.cumsum([a, b, c], reverse=True) # => [a + b + c, b + c, c] +/// ``` +/// +/// This is more efficient than using separate `tf.reverse` ops. +/// +/// The `reverse` and `exclusive` kwargs can also be combined: +/// +/// ```python +/// tf.cumsum([a, b, c], exclusive=True, reverse=True) # => [b + c, c, 0] +/// ``` +/// +/// - Parameters: +/// - x: A `Tensor`. Must be one of the following types: `float32`, `float64`, +/// `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, +/// `complex128`, `qint8`, `quint8`, `qint32`, `half`. +/// - axis: A `Tensor` of type `int32` (default: 0). Must be in the range +/// `[-rank(x), rank(x))`. +/// +/// - Attrs: +/// - exclusive: If `True`, perform exclusive cumsum. +/// - reverse: A `bool` (default: False). +@inlinable @inline(__always) +public static func cumsum< + T: Numeric & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + _ x: Tensor, + axis: Tensor, + exclusive: Bool = false, + reverse: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Cumsum", nOutputs) + op.updateAttribute("exclusive", exclusive) + op.updateAttribute("reverse", reverse) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(x) + op.addInput(axis) + return op.execute(Int(1)) +} + +/// Returns the dimension index in the destination data format given the one in +/// +/// the source data format. +/// +/// - Parameter x: A Tensor with each element as a dimension index in source data format. +/// Must be in the range [-4, 4). +/// +/// - Attrs: +/// - src_format: source data format. +/// - dst_format: destination data format. +/// +/// - Output y: A Tensor with each element as a dimension index in destination data format. +@inlinable @inline(__always) +public static func dataFormatDimMap( + _ x: Tensor, + srcFormat: String = "NHWC", + dstFormat: String = "NCHW" +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DataFormatDimMap", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("src_format", srcFormat) + op.updateAttribute("dst_format", dstFormat) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Returns the permuted vector/tensor in the destination data format given the +/// +/// one in the source data format. +/// +/// - Parameter x: Vector of size 4 or Tensor of shape (4, 2) in source data format. +/// +/// - Attrs: +/// - src_format: source data format. +/// - dst_format: destination data format. +/// +/// - Output y: Vector of size 4 or Tensor of shape (4, 2) in destination data format. +@inlinable @inline(__always) +public static func dataFormatVecPermute( + _ x: Tensor, + srcFormat: String = "NHWC", + dstFormat: String = "NCHW" +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DataFormatVecPermute", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("src_format", srcFormat) + op.updateAttribute("dst_format", dstFormat) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Returns a serialized GraphDef representing `input_dataset`. +/// +/// Returns a graph representation for `input_dataset`. +/// +/// - Parameter input_dataset: A variant tensor representing the dataset to return the graph representation for. +/// +/// - Output graph: The graph representation of the dataset (as serialized GraphDef). +@inlinable @inline(__always) +public static func datasetToGraph( + inputDataset: VariantHandle +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("DatasetToGraph", nOutputs) + op.addInput(inputDataset) + return op.execute(Int(1)) +} + +/// Outputs the single element from the given dataset. +/// +/// - Parameter dataset: A handle to a dataset that contains a single element. +/// +/// - Output components: The components of the single element of `input`. +@inlinable @inline(__always) +public static func datasetToSingleElement( + dataset: VariantHandle, + outputShapes: [TensorShape?] +) -> OutputTypes { + let nOutputs = Int(OutputTypes._typeList.count) + let op = makeOp("DatasetToSingleElement", nOutputs) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(dataset) + return op.execute(Int(OutputTypes._typeList.count)) +} + +/// Identity op for gradient debugging. +/// +/// This op is hidden from public in Python. It is used by TensorFlow Debugger to +/// register gradient tensors for gradient debugging. +/// This op operates on non-reference-type tensors. +@inlinable @inline(__always) +public static func debugGradientIdentity( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DebugGradientIdentity", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Debug Identity Op. +/// +/// Provides an identity mapping of the non-Ref type input tensor for debugging. +/// +/// - Parameter input: Input tensor, non-Reference type. +/// +/// - Attrs: +/// - tensor_name: Name of the input tensor. +/// - debug_urls: List of URLs to debug targets, e.g., +/// file:///foo/tfdbg_dump, grpc:://localhost:11011 +/// - gated_grpc: Whether this op will be gated. If any of the debug_urls of this +/// debug node is of the grpc:// scheme, when the value of this attribute is set +/// to True, the data will not actually be sent via the grpc stream unless this +/// debug op has been enabled at the debug_url. If all of the debug_urls of this +/// debug node are of the grpc:// scheme and the debug op is enabled at none of +/// them, the output will be an empty Tensor. +/// +/// - Output output: Output tensor that equals the input tensor. +@inlinable @inline(__always) +public static func debugIdentity( + _ input: Tensor, + deviceName: String, + tensorName: String, + debugUrls: [String], + gatedGrpc: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DebugIdentity", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("device_name", deviceName) + op.updateAttribute("tensor_name", tensorName) + op.updateAttribute("debug_urls", debugUrls) + op.updateAttribute("gated_grpc", gatedGrpc) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Debug NaN Value Counter Op +/// +/// Counts number of NaNs in the input tensor, for debugging. +/// +/// - Parameter input: Input tensor, non-Reference type. +/// +/// - Attrs: +/// - tensor_name: Name of the input tensor. +/// - debug_urls: List of URLs to debug targets, e.g., +/// file:///foo/tfdbg_dump, grpc:://localhost:11011. +/// - gated_grpc: Whether this op will be gated. If any of the debug_urls of this +/// debug node is of the grpc:// scheme, when the value of this attribute is set +/// to True, the data will not actually be sent via the grpc stream unless this +/// debug op has been enabled at the debug_url. If all of the debug_urls of this +/// debug node are of the grpc:// scheme and the debug op is enabled at none of +/// them, the output will be an empty Tensor. +/// +/// - Output output: An integer output tensor that is the number of NaNs in the input. +@inlinable @inline(__always) +public static func debugNanCount( + _ input: Tensor, + deviceName: String, + tensorName: String, + debugUrls: [String], + gatedGrpc: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DebugNanCount", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("device_name", deviceName) + op.updateAttribute("tensor_name", tensorName) + op.updateAttribute("debug_urls", debugUrls) + op.updateAttribute("gated_grpc", gatedGrpc) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Debug Numeric Summary Op. +/// +/// Provide a basic summary of numeric value types, range and distribution. +/// +/// - Parameter input: Input tensor, non-Reference type, float or double. +/// +/// - Attrs: +/// - tensor_name: Name of the input tensor. +/// - debug_urls: List of URLs to debug targets, e.g., +/// file:///foo/tfdbg_dump, grpc:://localhost:11011 +/// - lower_bound: (float) The lower bound <= which values will be included in the +/// generalized -inf count. Default: -inf. +/// - upper_bound: (float) The upper bound >= which values will be included in the +/// generalized +inf count. Default: +inf. +/// - mute_if_healthy: (bool) Do not send data to the debug URLs unless at least one +/// of elements [2], [3] and [7] (i.e., the nan count and the generalized -inf and +/// inf counts) is non-zero. +/// - gated_grpc: Whether this op will be gated. If any of the debug_urls of this +/// debug node is of the grpc:// scheme, when the value of this attribute is set +/// to True, the data will not actually be sent via the grpc stream unless this +/// debug op has been enabled at the debug_url. If all of the debug_urls of this +/// debug node are of the grpc:// scheme and the debug op is enabled at none of +/// them, the output will be an empty Tensor. +/// +/// - Output output: A double tensor of shape [14 + nDimensions], where nDimensions is the +/// the number of dimensions of the tensor's shape. The elements of output are: +/// [0]: is initialized (1.0) or not (0.0). +/// [1]: total number of elements +/// [2]: NaN element count +/// [3]: generalized -inf count: elements <= lower_bound. lower_bound is -inf by +/// default. +/// [4]: negative element count (excluding -inf), if lower_bound is the default +/// -inf. Otherwise, this is the count of elements > lower_bound and < 0. +/// [5]: zero element count +/// [6]: positive element count (excluding +inf), if upper_bound is the default +/// -inf. Otherwise, this is the count of elements < upper_bound and > 0. +/// [7]: generalized +inf count, elements >= upper_bound. upper_bound is +inf by +/// default. +/// Output elements [1:8] are all zero, if the tensor is uninitialized. +/// [8]: minimum of all non-inf and non-NaN elements. +/// If uninitialized or no such element exists: +inf. +/// [9]: maximum of all non-inf and non-NaN elements. +/// If uninitialized or no such element exists: -inf. +/// [10]: mean of all non-inf and non-NaN elements. +/// If uninitialized or no such element exists: NaN. +/// [11]: variance of all non-inf and non-NaN elements. +/// If uninitialized or no such element exists: NaN. +/// [12]: Data type of the tensor encoded as an enum integer. See the DataType +/// proto for more details. +/// [13]: Number of dimensions of the tensor (ndims). +/// [14+]: Sizes of the dimensions. +@inlinable @inline(__always) +public static func debugNumericSummary( + _ input: Tensor, + deviceName: String, + tensorName: String, + debugUrls: [String], + lowerBound: Double = -Double.infinity, + upperBound: Double = Double.infinity, + muteIfHealthy: Bool = false, + gatedGrpc: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DebugNumericSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("device_name", deviceName) + op.updateAttribute("tensor_name", tensorName) + op.updateAttribute("debug_urls", debugUrls) + op.updateAttribute("lower_bound", lowerBound) + op.updateAttribute("upper_bound", upperBound) + op.updateAttribute("mute_if_healthy", muteIfHealthy) + op.updateAttribute("gated_grpc", gatedGrpc) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Decode and Crop a JPEG-encoded image to a uint8 tensor. +/// +/// The attr `channels` indicates the desired number of color channels for the +/// decoded image. +/// +/// Accepted values are: +/// +/// * 0: Use the number of channels in the JPEG-encoded image. +/// * 1: output a grayscale image. +/// * 3: output an RGB image. +/// +/// If needed, the JPEG-encoded image is transformed to match the requested number +/// of color channels. +/// +/// The attr `ratio` allows downscaling the image by an integer factor during +/// decoding. Allowed values are: 1, 2, 4, and 8. This is much faster than +/// downscaling the image later. +/// +/// +/// It is equivalent to a combination of decode and crop, but much faster by only +/// decoding partial jpeg image. +/// +/// - Parameters: +/// - contents: 0-D. The JPEG-encoded image. +/// - crop_window: 1-D. The crop window: [crop_y, crop_x, crop_height, crop_width]. +/// +/// - Attrs: +/// - channels: Number of color channels for the decoded image. +/// - ratio: Downscaling ratio. +/// - fancy_upscaling: If true use a slower but nicer upscaling of the +/// chroma planes (yuv420/422 only). +/// - try_recover_truncated: If true try to recover an image from truncated input. +/// - acceptable_fraction: The minimum required fraction of lines before a truncated +/// input is accepted. +/// - dct_method: string specifying a hint about the algorithm used for +/// decompression. Defaults to "" which maps to a system-specific +/// default. Currently valid values are ["INTEGER_FAST", +/// "INTEGER_ACCURATE"]. The hint may be ignored (e.g., the internal +/// jpeg library changes to a version that does not have that specific +/// option.) +/// +/// - Output image: 3-D with shape `[height, width, channels]`.. +@inlinable @inline(__always) +public static func decodeAndCropJpeg( + contents: StringTensor, + cropWindow: Tensor, + channels: Int64 = 0, + ratio: Int64 = 1, + fancyUpscaling: Bool = true, + tryRecoverTruncated: Bool = false, + acceptableFraction: Double = 1, + dctMethod: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DecodeAndCropJpeg", nOutputs) + op.updateAttribute("channels", channels) + op.updateAttribute("ratio", ratio) + op.updateAttribute("fancy_upscaling", fancyUpscaling) + op.updateAttribute("try_recover_truncated", tryRecoverTruncated) + op.updateAttribute("acceptable_fraction", acceptableFraction) + op.updateAttribute("dct_method", dctMethod) + op.addInput(contents) + op.addInput(cropWindow) + return op.execute(Int(1)) +} + +/// Decode web-safe base64-encoded strings. +/// +/// Input may or may not have padding at the end. See EncodeBase64 for padding. +/// Web-safe means that input must use - and _ instead of + and /. +/// +/// - Parameter input: Base64 strings to decode. +/// +/// - Output output: Decoded strings. +@inlinable @inline(__always) +public static func decodeBase64( + _ input: StringTensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("DecodeBase64", nOutputs) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Decode the first frame of a BMP-encoded image to a uint8 tensor. +/// +/// The attr `channels` indicates the desired number of color channels for the +/// decoded image. +/// +/// Accepted values are: +/// +/// * 0: Use the number of channels in the BMP-encoded image. +/// * 3: output an RGB image. +/// * 4: output an RGBA image. +/// +/// - Parameter contents: 0-D. The BMP-encoded image. +/// +/// - Output image: 3-D with shape `[height, width, channels]`. RGB order +@inlinable @inline(__always) +public static func decodeBmp( + contents: StringTensor, + channels: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DecodeBmp", nOutputs) + op.updateAttribute("channels", channels) + op.addInput(contents) + return op.execute(Int(1)) +} + +/// Convert CSV records to tensors. Each column maps to one tensor. +/// +/// RFC 4180 format is expected for the CSV records. +/// (https://tools.ietf.org/html/rfc4180) +/// Note that we allow leading and trailing spaces with int or float field. +/// +/// - Parameters: +/// - records: Each string is a record/row in the csv and all records should have +/// the same format. +/// - record_defaults: One tensor per column of the input record, with either a +/// scalar default value for that column or an empty vector if the column is +/// required. +/// +/// - Attrs: +/// - field_delim: char delimiter to separate fields in a record. +/// - use_quote_delim: If false, treats double quotation marks as regular +/// characters inside of the string fields (ignoring RFC 4180, Section 2, +/// Bullet 5). +/// - na_value: Additional string to recognize as NA/NaN. +/// +/// - Output output: Each tensor will have the same shape as records. +@inlinable @inline(__always) +public static func decodeCSV( + records: StringTensor, + recordDefaults: OutType, + fieldDelim: String = ",", + useQuoteDelim: Bool = true, + naValue: String, + selectCols: [Int32] +) -> OutType { + let nOutputs = Int(recordDefaults._typeList.count) + let op = makeOp("DecodeCSV", nOutputs) + op.updateAttribute("OUT_TYPE", recordDefaults._typeList) + op.updateAttribute("field_delim", fieldDelim) + op.updateAttribute("use_quote_delim", useQuoteDelim) + op.updateAttribute("na_value", naValue) + op.updateAttribute("select_cols", selectCols) + op.addInput(records) + op.addInputList(recordDefaults) + return op.execute(Int(recordDefaults._typeList.count)) +} + +/// Decompress strings. +/// +/// This op decompresses each element of the `bytes` input `Tensor`, which +/// is assumed to be compressed using the given `compression_type`. +/// +/// The `output` is a string `Tensor` of the same shape as `bytes`, +/// each element containing the decompressed data from the corresponding +/// element in `bytes`. +/// +/// - Parameter bytes: A Tensor of string which is compressed. +/// +/// - Attr compression_type: A scalar containing either (i) the empty string (no +/// compression), (ii) "ZLIB", or (iii) "GZIP". +/// +/// - Output output: A Tensor with the same shape as input `bytes`, uncompressed +/// from bytes. +@inlinable @inline(__always) +public static func decodeCompressed( + bytes: StringTensor, + compressionType: String +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("DecodeCompressed", nOutputs) + op.updateAttribute("compression_type", compressionType) + op.addInput(bytes) + return op.execute(Int(1)) +} + +/// Decode the frame(s) of a GIF-encoded image to a uint8 tensor. +/// +/// GIF images with frame or transparency compression are not supported. +/// On Linux and MacOS systems, convert animated GIFs from compressed to +/// uncompressed by running: +/// +/// convert $src.gif -coalesce $dst.gif +/// +/// This op also supports decoding JPEGs and PNGs, though it is cleaner to use +/// `tf.image.decode_image`. +/// +/// - Parameter contents: 0-D. The GIF-encoded image. +/// +/// - Output image: 4-D with shape `[num_frames, height, width, 3]`. RGB channel order. +@inlinable @inline(__always) +public static func decodeGif( + contents: StringTensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DecodeGif", nOutputs) + op.addInput(contents) + return op.execute(Int(1)) +} + +/// Convert JSON-encoded Example records to binary protocol buffer strings. +/// +/// This op translates a tensor containing Example records, encoded using +/// the [standard JSON +/// mapping](https://developers.google.com/protocol-buffers/docs/proto3#json), +/// into a tensor containing the same records encoded as binary protocol +/// buffers. The resulting tensor can then be fed to any of the other +/// Example-parsing ops. +/// +/// - Parameter json_examples: Each string is a JSON object serialized according to the JSON +/// mapping of the Example proto. +/// +/// - Output binary_examples: Each string is a binary Example protocol buffer corresponding +/// to the respective element of `json_examples`. +@inlinable @inline(__always) +public static func decodeJSONExample( + jsonExamples: StringTensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("DecodeJSONExample", nOutputs) + op.addInput(jsonExamples) + return op.execute(Int(1)) +} + +/// Decode a JPEG-encoded image to a uint8 tensor. +/// +/// The attr `channels` indicates the desired number of color channels for the +/// decoded image. +/// +/// Accepted values are: +/// +/// * 0: Use the number of channels in the JPEG-encoded image. +/// * 1: output a grayscale image. +/// * 3: output an RGB image. +/// +/// If needed, the JPEG-encoded image is transformed to match the requested number +/// of color channels. +/// +/// The attr `ratio` allows downscaling the image by an integer factor during +/// decoding. Allowed values are: 1, 2, 4, and 8. This is much faster than +/// downscaling the image later. +/// +/// +/// This op also supports decoding PNGs and non-animated GIFs since the interface is +/// the same, though it is cleaner to use `tf.image.decode_image`. +/// +/// - Parameter contents: 0-D. The JPEG-encoded image. +/// +/// - Attrs: +/// - channels: Number of color channels for the decoded image. +/// - ratio: Downscaling ratio. +/// - fancy_upscaling: If true use a slower but nicer upscaling of the +/// chroma planes (yuv420/422 only). +/// - try_recover_truncated: If true try to recover an image from truncated input. +/// - acceptable_fraction: The minimum required fraction of lines before a truncated +/// input is accepted. +/// - dct_method: string specifying a hint about the algorithm used for +/// decompression. Defaults to "" which maps to a system-specific +/// default. Currently valid values are ["INTEGER_FAST", +/// "INTEGER_ACCURATE"]. The hint may be ignored (e.g., the internal +/// jpeg library changes to a version that does not have that specific +/// option.) +/// +/// - Output image: 3-D with shape `[height, width, channels]`.. +@inlinable @inline(__always) +public static func decodeJpeg( + contents: StringTensor, + channels: Int64 = 0, + ratio: Int64 = 1, + fancyUpscaling: Bool = true, + tryRecoverTruncated: Bool = false, + acceptableFraction: Double = 1, + dctMethod: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DecodeJpeg", nOutputs) + op.updateAttribute("channels", channels) + op.updateAttribute("ratio", ratio) + op.updateAttribute("fancy_upscaling", fancyUpscaling) + op.updateAttribute("try_recover_truncated", tryRecoverTruncated) + op.updateAttribute("acceptable_fraction", acceptableFraction) + op.updateAttribute("dct_method", dctMethod) + op.addInput(contents) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func decodePaddedRaw( + inputBytes: StringTensor, + fixedLength: Tensor, + littleEndian: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DecodePaddedRaw", nOutputs) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("little_endian", littleEndian) + op.addInput(inputBytes) + op.addInput(fixedLength) + return op.execute(Int(1)) +} + +/// Decode a PNG-encoded image to a uint8 or uint16 tensor. +/// +/// The attr `channels` indicates the desired number of color channels for the +/// decoded image. +/// +/// Accepted values are: +/// +/// * 0: Use the number of channels in the PNG-encoded image. +/// * 1: output a grayscale image. +/// * 3: output an RGB image. +/// * 4: output an RGBA image. +/// +/// If needed, the PNG-encoded image is transformed to match the requested number +/// of color channels. +/// +/// This op also supports decoding JPEGs and non-animated GIFs since the interface +/// is the same, though it is cleaner to use `tf.image.decode_image`. +/// +/// - Parameter contents: 0-D. The PNG-encoded image. +/// +/// - Attr channels: Number of color channels for the decoded image. +/// +/// - Output image: 3-D with shape `[height, width, channels]`. +@inlinable @inline(__always) +public static func decodePng( + contents: StringTensor, + channels: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DecodePng", nOutputs) + op.updateAttribute("channels", channels) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(contents) + return op.execute(Int(1)) +} + +/// The op extracts fields from a serialized protocol buffers message into tensors. +/// +/// The `decode_proto` op extracts fields from a serialized protocol buffers +/// message into tensors. The fields in `field_names` are decoded and converted +/// to the corresponding `output_types` if possible. +/// +/// A `message_type` name must be provided to give context for the field +/// names. The actual message descriptor can be looked up either in the +/// linked-in descriptor pool or a filename provided by the caller using +/// the `descriptor_source` attribute. +/// +/// Each output tensor is a dense tensor. This means that it is padded to +/// hold the largest number of repeated elements seen in the input +/// minibatch. (The shape is also padded by one to prevent zero-sized +/// dimensions). The actual repeat counts for each example in the +/// minibatch can be found in the `sizes` output. In many cases the output +/// of `decode_proto` is fed immediately into tf.squeeze if missing values +/// are not a concern. When using tf.squeeze, always pass the squeeze +/// dimension explicitly to avoid surprises. +/// +/// For the most part, the mapping between Proto field types and +/// TensorFlow dtypes is straightforward. However, there are a few +/// special cases: +/// +/// - A proto field that contains a submessage or group can only be converted +/// to `DT_STRING` (the serialized submessage). This is to reduce the +/// complexity of the API. The resulting string can be used as input +/// to another instance of the decode_proto op. +/// +/// - TensorFlow lacks support for unsigned integers. The ops represent uint64 +/// types as a `DT_INT64` with the same twos-complement bit pattern +/// (the obvious way). Unsigned int32 values can be represented exactly by +/// specifying type `DT_INT64`, or using twos-complement if the caller +/// specifies `DT_INT32` in the `output_types` attribute. +/// +/// The `descriptor_source` attribute selects a source of protocol +/// descriptors to consult when looking up `message_type`. This may be a +/// filename containing a serialized `FileDescriptorSet` message, +/// or the special value `local://`, in which case only descriptors linked +/// into the code will be searched; the filename can be on any filesystem +/// accessible to TensorFlow. +/// +/// You can build a `descriptor_source` file using the `--descriptor_set_out` +/// and `--include_imports` options to the protocol compiler `protoc`. +/// +/// The `local://` database only covers descriptors linked into the +/// code via C++ libraries, not Python imports. You can link in a proto descriptor +/// by creating a cc_library target with alwayslink=1. +/// +/// Both binary and text proto serializations are supported, and can be +/// chosen using the `format` attribute. +/// +/// - Parameter bytes: Tensor of serialized protos with shape `batch_shape`. +/// +/// - Attrs: +/// - message_type: Name of the proto message type to decode. +/// - field_names: List of strings containing proto field names. An extension field can be decoded +/// by using its full name, e.g. EXT_PACKAGE.EXT_FIELD_NAME. +/// - output_types: List of TF types to use for the respective field in field_names. +/// - descriptor_source: Either the special value `local://` or a path to a file containing +/// a serialized `FileDescriptorSet`. +/// - message_format: Either `binary` or `text`. +/// - sanitize: Whether to sanitize the result or not. +/// +/// - Outputs: +/// - sizes: Tensor of int32 with shape `[batch_shape, len(field_names)]`. +/// Each entry is the number of values found for the corresponding field. +/// Optional fields may have 0 or 1 values. +/// - values: List of tensors containing values for the corresponding field. +/// `values[i]` has datatype `output_types[i]` +/// and shape `[batch_shape, max(sizes[...,i])]`. +@inlinable @inline(__always) +public static func decodeProtoV2( + bytes: StringTensor, + messageType: String, + fieldNames: [String], + descriptorSource: String = "local://", + messageFormat: String = "binary", + sanitize: Bool = false +) -> (sizes: Tensor, values: OutputTypes) { + let nOutputs = Int(1) + Int(OutputTypes._typeList.count) + let op = makeOp("DecodeProtoV2", nOutputs) + op.updateAttribute("message_type", messageType) + op.updateAttribute("field_names", fieldNames) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("descriptor_source", descriptorSource) + op.updateAttribute("message_format", messageFormat) + op.updateAttribute("sanitize", sanitize) + op.addInput(bytes) + return op.execute(Int(1), Int(OutputTypes._typeList.count)) +} + +/// Reinterpret the bytes of a string as a vector of numbers. +/// +/// - Parameter bytes: All the elements must have the same length. +/// +/// - Attr little_endian: Whether the input `bytes` are in little-endian order. +/// Ignored for `out_type` values that are stored in a single byte like +/// `uint8`. +/// +/// - Output output: A Tensor with one more dimension than the input `bytes`. The +/// added dimension will have size equal to the length of the elements +/// of `bytes` divided by the number of bytes to represent `out_type`. +@inlinable @inline(__always) +public static func decodeRaw( + bytes: StringTensor, + littleEndian: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DecodeRaw", nOutputs) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("little_endian", littleEndian) + op.addInput(bytes) + return op.execute(Int(1)) +} + +/// Decode a 16-bit PCM WAV file to a float tensor. +/// +/// The -32768 to 32767 signed 16-bit values will be scaled to -1.0 to 1.0 in float. +/// +/// When desired_channels is set, if the input contains fewer channels than this +/// then the last channel will be duplicated to give the requested number, else if +/// the input has more channels than requested then the additional channels will be +/// ignored. +/// +/// If desired_samples is set, then the audio will be cropped or padded with zeroes +/// to the requested length. +/// +/// The first output contains a Tensor with the content of the audio samples. The +/// lowest dimension will be the number of channels, and the second will be the +/// number of samples. For example, a ten-sample-long stereo WAV file should give an +/// output shape of [10, 2]. +/// +/// - Parameter contents: The WAV-encoded audio, usually from a file. +/// +/// - Attrs: +/// - desired_channels: Number of sample channels wanted. +/// - desired_samples: Length of audio requested. +/// +/// - Outputs: +/// - audio: 2-D with shape `[length, channels]`. +/// - sample_rate: Scalar holding the sample rate found in the WAV header. +@inlinable @inline(__always) +public static func decodeWav( + contents: StringTensor, + desiredChannels: Int64 = -1, + desiredSamples: Int64 = -1 +) -> (audio: Tensor, sampleRate: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("DecodeWav", nOutputs) + op.updateAttribute("desired_channels", desiredChannels) + op.updateAttribute("desired_samples", desiredSamples) + op.addInput(contents) + return op.execute(Int(1), Int(1)) +} + +/// Makes a copy of `x`. +/// +/// - Parameter x: The source tensor of type `T`. +/// +/// - Output y: y: A `Tensor` of type `T`. A copy of `x`. Guaranteed that `y` +/// is not an alias of `x`. +@inlinable @inline(__always) +public static func deepCopy( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DeepCopy", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// A container for an iterator resource. +/// +/// - Parameters: +/// - handle: A handle to the iterator to delete. +/// - deleter: A variant deleter. +@inlinable @inline(__always) +public static func deleteIterator( + handle: ResourceHandle, + deleter: VariantHandle +) { + let nOutputs = 0 + let op = makeOp("DeleteIterator", nOutputs) + op.addInput(handle) + op.addInput(deleter) + op.execute() +} + +/// Delete the tensor specified by its handle in the session. +/// +/// - Parameter handle: The handle for a tensor stored in the session state. +@inlinable @inline(__always) +public static func deleteSessionTensor( + handle: StringTensor +) { + let nOutputs = 0 + let op = makeOp("DeleteSessionTensor", nOutputs) + op.addInput(handle) + op.execute() +} + +/// Applies set operation along last dimension of 2 `Tensor` inputs. +/// +/// See SetOperationOp::SetOperationFromContext for values of `set_operation`. +/// +/// Output `result` is a `SparseTensor` represented by `result_indices`, +/// `result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this +/// has rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth` +/// dimension contains the result of `set_operation` applied to the corresponding +/// `[0...n-1]` dimension of `set`. +/// +/// - Parameters: +/// - set1: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`. +/// Dimension `n` contains values in a set, duplicates are allowed but ignored. +/// - set2: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set1`. +/// Dimension `n` contains values in a set, duplicates are allowed but ignored. +/// +/// - Outputs: +/// - result_indices: 2D indices of a `SparseTensor`. +/// - result_values: 1D values of a `SparseTensor`. +/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is +/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` +/// is the max result set size across all `0...n-1` dimensions. +@inlinable @inline(__always) +public static func denseToDenseSetOperation( + set1: Tensor, + set2: Tensor, + setOperation: String, + validateIndices: Bool = true +) -> (resultIndices: Tensor, resultValues: Tensor, resultShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("DenseToDenseSetOperation", nOutputs) + op.updateAttribute("set_operation", setOperation) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(set1) + op.addInput(set2) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Applies set operation along last dimension of 2 `Tensor` inputs. +/// +/// See SetOperationOp::SetOperationFromContext for values of `set_operation`. +/// +/// Output `result` is a `SparseTensor` represented by `result_indices`, +/// `result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this +/// has rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth` +/// dimension contains the result of `set_operation` applied to the corresponding +/// `[0...n-1]` dimension of `set`. +/// +/// - Parameters: +/// - set1: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`. +/// Dimension `n` contains values in a set, duplicates are allowed but ignored. +/// - set2: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set1`. +/// Dimension `n` contains values in a set, duplicates are allowed but ignored. +/// +/// - Outputs: +/// - result_indices: 2D indices of a `SparseTensor`. +/// - result_values: 1D values of a `SparseTensor`. +/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is +/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` +/// is the max result set size across all `0...n-1` dimensions. +@inlinable @inline(__always) +public static func denseToDenseSetOperation( + set1: StringTensor, + set2: StringTensor, + setOperation: String, + validateIndices: Bool = true +) -> (resultIndices: Tensor, resultValues: StringTensor, resultShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("DenseToDenseSetOperation", nOutputs) + op.updateAttribute("set_operation", setOperation) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(set1) + op.addInput(set2) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Applies set operation along last dimension of `Tensor` and `SparseTensor`. +/// +/// See SetOperationOp::SetOperationFromContext for values of `set_operation`. +/// +/// Input `set2` is a `SparseTensor` represented by `set2_indices`, `set2_values`, +/// and `set2_shape`. For `set2` ranked `n`, 1st `n-1` dimensions must be the same +/// as `set1`. Dimension `n` contains values in a set, duplicates are allowed but +/// ignored. +/// +/// If `validate_indices` is `True`, this op validates the order and range of `set2` +/// indices. +/// +/// Output `result` is a `SparseTensor` represented by `result_indices`, +/// `result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this +/// has rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth` +/// dimension contains the result of `set_operation` applied to the corresponding +/// `[0...n-1]` dimension of `set`. +/// +/// - Parameters: +/// - set1: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`. +/// Dimension `n` contains values in a set, duplicates are allowed but ignored. +/// - set2_indices: 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major +/// order. +/// - set2_values: 1D `Tensor`, values of a `SparseTensor`. Must be in row-major +/// order. +/// - set2_shape: 1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must +/// be the same as the 1st `n-1` dimensions of `set1`, `result_shape[n]` is the +/// max set size across `n-1` dimensions. +/// +/// - Outputs: +/// - result_indices: 2D indices of a `SparseTensor`. +/// - result_values: 1D values of a `SparseTensor`. +/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is +/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` +/// is the max result set size across all `0...n-1` dimensions. +@inlinable @inline(__always) +public static func denseToSparseSetOperation( + set1: Tensor, + set2Indices: Tensor, + set2Values: Tensor, + set2Shape: Tensor, + setOperation: String, + validateIndices: Bool = true +) -> (resultIndices: Tensor, resultValues: Tensor, resultShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("DenseToSparseSetOperation", nOutputs) + op.updateAttribute("set_operation", setOperation) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(set1) + op.addInput(set2Indices) + op.addInput(set2Values) + op.addInput(set2Shape) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Applies set operation along last dimension of `Tensor` and `SparseTensor`. +/// +/// See SetOperationOp::SetOperationFromContext for values of `set_operation`. +/// +/// Input `set2` is a `SparseTensor` represented by `set2_indices`, `set2_values`, +/// and `set2_shape`. For `set2` ranked `n`, 1st `n-1` dimensions must be the same +/// as `set1`. Dimension `n` contains values in a set, duplicates are allowed but +/// ignored. +/// +/// If `validate_indices` is `True`, this op validates the order and range of `set2` +/// indices. +/// +/// Output `result` is a `SparseTensor` represented by `result_indices`, +/// `result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this +/// has rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth` +/// dimension contains the result of `set_operation` applied to the corresponding +/// `[0...n-1]` dimension of `set`. +/// +/// - Parameters: +/// - set1: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`. +/// Dimension `n` contains values in a set, duplicates are allowed but ignored. +/// - set2_indices: 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major +/// order. +/// - set2_values: 1D `Tensor`, values of a `SparseTensor`. Must be in row-major +/// order. +/// - set2_shape: 1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must +/// be the same as the 1st `n-1` dimensions of `set1`, `result_shape[n]` is the +/// max set size across `n-1` dimensions. +/// +/// - Outputs: +/// - result_indices: 2D indices of a `SparseTensor`. +/// - result_values: 1D values of a `SparseTensor`. +/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is +/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` +/// is the max result set size across all `0...n-1` dimensions. +@inlinable @inline(__always) +public static func denseToSparseSetOperation( + set1: StringTensor, + set2Indices: Tensor, + set2Values: StringTensor, + set2Shape: Tensor, + setOperation: String, + validateIndices: Bool = true +) -> (resultIndices: Tensor, resultValues: StringTensor, resultShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("DenseToSparseSetOperation", nOutputs) + op.updateAttribute("set_operation", setOperation) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(set1) + op.addInput(set2Indices) + op.addInput(set2Values) + op.addInput(set2Shape) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// DepthToSpace for tensors of type T. +/// +/// Rearranges data from depth into blocks of spatial data. +/// This is the reverse transformation of SpaceToDepth. More specifically, +/// this op outputs a copy of the input tensor where values from the `depth` +/// dimension are moved in spatial blocks to the `height` and `width` dimensions. +/// The attr `block_size` indicates the input block size and how the data is moved. +/// +/// * Chunks of data of size `block_size * block_size` from depth are rearranged +/// into non-overlapping blocks of size `block_size x block_size` +/// * The width the output tensor is `input_depth * block_size`, whereas the +/// height is `input_height * block_size`. +/// * The Y, X coordinates within each block of the output image are determined +/// by the high order component of the input channel index. +/// * The depth of the input tensor must be divisible by +/// `block_size * block_size`. +/// +/// The `data_format` attr specifies the layout of the input and output tensors +/// with the following options: +/// "NHWC": `[ batch, height, width, channels ]` +/// "NCHW": `[ batch, channels, height, width ]` +/// "NCHW_VECT_C": +/// `qint8 [ batch, channels / 4, height, width, 4 ]` +/// +/// It is useful to consider the operation as transforming a 6-D Tensor. +/// e.g. for data_format = NHWC, +/// Each element in the input tensor can be specified via 6 coordinates, +/// ordered by decreasing memory layout significance as: +/// n,iY,iX,bY,bX,oC (where n=batch index, iX, iY means X or Y coordinates +/// within the input image, bX, bY means coordinates +/// within the output block, oC means output channels). +/// The output would be the input transposed to the following layout: +/// n,iY,bY,iX,bX,oC +/// +/// This operation is useful for resizing the activations between convolutions +/// (but keeping all data), e.g. instead of pooling. It is also useful for training +/// purely convolutional models. +/// +/// For example, given an input of shape `[1, 1, 1, 4]`, data_format = "NHWC" and +/// block_size = 2: +/// +/// ``` +/// x = [[[[1, 2, 3, 4]]]] +/// +/// ``` +/// +/// This operation will output a tensor of shape `[1, 2, 2, 1]`: +/// +/// ``` +/// [[[[1], [2]], +/// [[3], [4]]]] +/// ``` +/// +/// Here, the input has a batch of 1 and each batch element has shape `[1, 1, 4]`, +/// the corresponding output will have 2x2 elements and will have a depth of +/// 1 channel (1 = `4 / (block_size * block_size)`). +/// The output element shape is `[2, 2, 1]`. +/// +/// For an input tensor with larger depth, here of shape `[1, 1, 1, 12]`, e.g. +/// +/// ``` +/// x = [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]] +/// ``` +/// +/// This operation, for block size of 2, will return the following tensor of shape +/// `[1, 2, 2, 3]` +/// +/// ``` +/// [[[[1, 2, 3], [4, 5, 6]], +/// [[7, 8, 9], [10, 11, 12]]]] +/// +/// ``` +/// +/// Similarly, for the following input of shape `[1 2 2 4]`, and a block size of 2: +/// +/// ``` +/// x = [[[[1, 2, 3, 4], +/// [5, 6, 7, 8]], +/// [[9, 10, 11, 12], +/// [13, 14, 15, 16]]]] +/// ``` +/// +/// the operator will return the following tensor of shape `[1 4 4 1]`: +/// +/// ``` +/// x = [[[ [1], [2], [5], [6]], +/// [ [3], [4], [7], [8]], +/// [ [9], [10], [13], [14]], +/// [ [11], [12], [15], [16]]]] +/// +/// ``` +/// +/// - Attr block_size: The size of the spatial block, same as in Space2Depth. +@inlinable @inline(__always) +public static func depthToSpace( + _ input: Tensor, + blockSize: Int64, + dataFormat: DataFormat4 = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DepthToSpace", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("block_size", blockSize) + op.updateAttribute("data_format", dataFormat.cName) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Computes a 2-D depthwise convolution given 4-D `input` and `filter` tensors. +/// +/// Given an input tensor of shape `[batch, in_height, in_width, in_channels]` +/// and a filter / kernel tensor of shape +/// `[filter_height, filter_width, in_channels, channel_multiplier]`, containing +/// `in_channels` convolutional filters of depth 1, `depthwise_conv2d` applies +/// a different filter to each input channel (expanding from 1 channel to +/// `channel_multiplier` channels for each), then concatenates the results +/// together. Thus, the output has `in_channels * channel_multiplier` channels. +/// +/// ``` +/// for k in 0..in_channels-1 +/// for q in 0..channel_multiplier-1 +/// output[b, i, j, k * channel_multiplier + q] = +/// sum_{di, dj} input[b, strides[1] * i + di, strides[2] * j + dj, k] * +/// filter[di, dj, k, q] +/// ``` +/// +/// Must have `strides[0] = strides[3] = 1`. For the most common case of the same +/// horizontal and vertices strides, `strides = [1, stride, stride, 1]`. +/// +/// - Attrs: +/// - strides: 1-D of length 4. The stride of the sliding window for each dimension +/// of `input`. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, height, width, channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, channels, height, width]. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter +/// element on that dimension. The dimension order is determined by the value of +/// `data_format`, see above for details. Dilations in the batch and depth +/// dimensions must be 1. +@inlinable @inline(__always) +public static func depthwiseConv2dNative( + _ input: Tensor, + filter: Tensor, + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc, + dilations: [Int32] = [1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DepthwiseConv2dNative", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + return op.execute(Int(1)) +} + +/// Computes the gradients of depthwise convolution with respect to the filter. +/// +/// - Parameters: +/// - input: 4-D with shape based on `data_format`. For example, if +/// `data_format` is 'NHWC' then `input` is a 4-D `[batch, in_height, +/// in_width, in_channels]` tensor. +/// - filter_sizes: An integer vector representing the tensor shape of `filter`, +/// where `filter` is a 4-D +/// `[filter_height, filter_width, in_channels, depthwise_multiplier]` tensor. +/// - out_backprop: 4-D with shape based on `data_format`. +/// For example, if `data_format` is 'NHWC' then +/// out_backprop shape is `[batch, out_height, out_width, out_channels]`. +/// Gradients w.r.t. the output of the convolution. +/// +/// - Attrs: +/// - strides: The stride of the sliding window for each dimension of the input +/// of the convolution. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, height, width, channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, channels, height, width]. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter +/// element on that dimension. The dimension order is determined by the value of +/// `data_format`, see above for details. Dilations in the batch and depth +/// dimensions must be 1. +/// +/// - Output output: 4-D with shape +/// `[filter_height, filter_width, in_channels, out_channels]`. Gradient w.r.t. +/// the `filter` input of the convolution. +@inlinable @inline(__always) +public static func depthwiseConv2dNativeBackpropFilter( + _ input: Tensor, + filterSizes: Tensor, + outBackprop: Tensor, + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc, + dilations: [Int32] = [1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DepthwiseConv2dNativeBackpropFilter", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filterSizes) + op.addInput(outBackprop) + return op.execute(Int(1)) +} + +/// Computes the gradients of depthwise convolution with respect to the input. +/// +/// - Parameters: +/// - input_sizes: An integer vector representing the shape of `input`, based +/// on `data_format`. For example, if `data_format` is 'NHWC' then +/// `input` is a 4-D `[batch, height, width, channels]` tensor. +/// - filter: 4-D with shape +/// `[filter_height, filter_width, in_channels, depthwise_multiplier]`. +/// - out_backprop: 4-D with shape based on `data_format`. +/// For example, if `data_format` is 'NHWC' then +/// out_backprop shape is `[batch, out_height, out_width, out_channels]`. +/// Gradients w.r.t. the output of the convolution. +/// +/// - Attrs: +/// - strides: The stride of the sliding window for each dimension of the input +/// of the convolution. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, height, width, channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, channels, height, width]. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter +/// element on that dimension. The dimension order is determined by the value of +/// `data_format`, see above for details. Dilations in the batch and depth +/// dimensions must be 1. +/// +/// - Output output: 4-D with shape according to `data_format`. For example, if +/// `data_format` is 'NHWC', output shape is `[batch, in_height, +/// in_width, in_channels]`. Gradient w.r.t. the input of the +/// convolution. +@inlinable @inline(__always) +public static func depthwiseConv2dNativeBackpropInput( + inputSizes: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc, + dilations: [Int32] = [1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DepthwiseConv2dNativeBackpropInput", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(inputSizes) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) +} + +/// Dequantize the 'input' tensor into a float Tensor. +/// +/// [min_range, max_range] are scalar floats that specify the range for +/// the 'input' data. The 'mode' attribute controls exactly which calculations are +/// used to convert the float values to their quantized equivalents. +/// +/// In 'MIN_COMBINED' mode, each value of the tensor will undergo the following: +/// +/// ``` +/// if T == qint8: in[i] += (range(T) + 1)/ 2.0 +/// out[i] = min_range + (in[i]* (max_range - min_range) / range(T)) +/// ``` +/// here `range(T) = numeric_limits::max() - numeric_limits::min()` +/// +/// *MIN_COMBINED Mode Example* +/// +/// If the input comes from a QuantizedRelu6, the output type is +/// quint8 (range of 0-255) but the possible range of QuantizedRelu6 is +/// 0-6. The min_range and max_range values are therefore 0.0 and 6.0. +/// Dequantize on quint8 will take each value, cast to float, and multiply +/// by 6 / 255. +/// Note that if quantizedtype is qint8, the operation will additionally add +/// each value by 128 prior to casting. +/// +/// If the mode is 'MIN_FIRST', then this approach is used: +/// +/// ```c++ +/// num_discrete_values = 1 << (# of bits in T) +/// range_adjust = num_discrete_values / (num_discrete_values - 1) +/// range = (range_max - range_min) * range_adjust +/// range_scale = range / num_discrete_values +/// const double offset_input = static_cast(input) - lowest_quantized; +/// result = range_min + ((input - numeric_limits::min()) * range_scale) +/// ``` +/// +/// *SCALED mode Example* +/// +/// `SCALED` mode matches the quantization approach used in +/// `QuantizeAndDequantize{V2|V3}`. +/// +/// If the mode is `SCALED`, we do not use the full range of the output type, +/// choosing to elide the lowest possible value for symmetry (e.g., output range is +/// -127 to 127, not -128 to 127 for signed 8 bit quantization), so that 0.0 maps to +/// 0. +/// +/// We first find the range of values in our tensor. The +/// range we use is always centered on 0, so we find m such that +/// ```c++ +/// m = max(abs(input_min), abs(input_max)) +/// ``` +/// +/// Our input tensor range is then `[-m, m]`. +/// +/// Next, we choose our fixed-point quantization buckets, `[min_fixed, max_fixed]`. +/// If T is signed, this is +/// ``` +/// num_bits = sizeof(T) * 8 +/// [min_fixed, max_fixed] = +/// [-(1 << (num_bits - 1) - 1), (1 << (num_bits - 1)) - 1] +/// ``` +/// +/// Otherwise, if T is unsigned, the fixed-point range is +/// ``` +/// [min_fixed, max_fixed] = [0, (1 << num_bits) - 1] +/// ``` +/// +/// From this we compute our scaling factor, s: +/// ```c++ +/// s = (2 * m) / (max_fixed - min_fixed) +/// ``` +/// +/// Now we can dequantize the elements of our tensor: +/// ```c++ +/// result = input * s +/// ``` +/// +/// - Parameters: +/// - min_range: The minimum scalar value possibly produced for the input. +/// - max_range: The maximum scalar value possibly produced for the input. +@inlinable @inline(__always) +public static func dequantize( + _ input: Tensor, + minRange: Tensor, + maxRange: Tensor, + mode: Mode = .minCombined +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Dequantize", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("mode", mode.cName) + op.addInput(input) + op.addInput(minRange) + op.addInput(maxRange) + return op.execute(Int(1)) +} + +/// Converts the given variant tensor to an iterator and stores it in the given resource. +/// +/// - Parameters: +/// - resource_handle: A handle to an iterator resource. +/// - serialized: A variant tensor storing the state of the iterator contained in the +/// resource. +@inlinable @inline(__always) +public static func deserializeIterator( + resourceHandle: ResourceHandle, + serialized: VariantHandle +) { + let nOutputs = 0 + let op = makeOp("DeserializeIterator", nOutputs) + op.addInput(resourceHandle) + op.addInput(serialized) + op.execute() +} + +/// Deserialize and concatenate `SparseTensors` from a serialized minibatch. +/// +/// The input `serialized_sparse` must be a string matrix of shape `[N x 3]` where +/// `N` is the minibatch size and the rows correspond to packed outputs of +/// `SerializeSparse`. The ranks of the original `SparseTensor` objects +/// must all match. When the final `SparseTensor` is created, it has rank one +/// higher than the ranks of the incoming `SparseTensor` objects +/// (they have been concatenated along a new row dimension). +/// +/// The output `SparseTensor` object's shape values for all dimensions but the +/// first are the max across the input `SparseTensor` objects' shape values +/// for the corresponding dimensions. Its first shape value is `N`, the minibatch +/// size. +/// +/// The input `SparseTensor` objects' indices are assumed ordered in +/// standard lexicographic order. If this is not the case, after this +/// step run `SparseReorder` to restore index ordering. +/// +/// For example, if the serialized input is a `[2 x 3]` matrix representing two +/// original `SparseTensor` objects: +/// +/// index = [ 0] +/// [10] +/// [20] +/// values = [1, 2, 3] +/// shape = [50] +/// +/// and +/// +/// index = [ 2] +/// [10] +/// values = [4, 5] +/// shape = [30] +/// +/// then the final deserialized `SparseTensor` will be: +/// +/// index = [0 0] +/// [0 10] +/// [0 20] +/// [1 2] +/// [1 10] +/// values = [1, 2, 3, 4, 5] +/// shape = [2 50] +/// +/// - Parameter serialized_sparse: 2-D, The `N` serialized `SparseTensor` objects. +/// Must have 3 columns. +/// +/// - Attr dtype: The `dtype` of the serialized `SparseTensor` objects. +@inlinable @inline(__always) +public static func deserializeManySparse( + serializedSparse: StringTensor +) -> (sparseIndices: Tensor, sparseValues: Tensor, sparseShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("DeserializeManySparse", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(serializedSparse) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Deserialize `SparseTensor` objects. +/// +/// The input `serialized_sparse` must have the shape `[?, ?, ..., ?, 3]` where +/// the last dimension stores serialized `SparseTensor` objects and the other N +/// dimensions (N >= 0) correspond to a batch. The ranks of the original +/// `SparseTensor` objects must all match. When the final `SparseTensor` is +/// created, its rank is the rank of the incoming `SparseTensor` objects plus N; +/// the sparse tensors have been concatenated along new dimensions, one for each +/// batch. +/// +/// The output `SparseTensor` object's shape values for the original dimensions +/// are the max across the input `SparseTensor` objects' shape values for the +/// corresponding dimensions. The new dimensions match the size of the batch. +/// +/// The input `SparseTensor` objects' indices are assumed ordered in +/// standard lexicographic order. If this is not the case, after this +/// step run `SparseReorder` to restore index ordering. +/// +/// For example, if the serialized input is a `[2 x 3]` matrix representing two +/// original `SparseTensor` objects: +/// +/// index = [ 0] +/// [10] +/// [20] +/// values = [1, 2, 3] +/// shape = [50] +/// +/// and +/// +/// index = [ 2] +/// [10] +/// values = [4, 5] +/// shape = [30] +/// +/// then the final deserialized `SparseTensor` will be: +/// +/// index = [0 0] +/// [0 10] +/// [0 20] +/// [1 2] +/// [1 10] +/// values = [1, 2, 3, 4, 5] +/// shape = [2 50] +/// +/// - Parameter serialized_sparse: The serialized `SparseTensor` objects. The last dimension +/// must have 3 columns. +/// +/// - Attr dtype: The `dtype` of the serialized `SparseTensor` objects. +@inlinable @inline(__always) +public static func deserializeSparse< + Dtype: TensorFlowScalar, + Tserialized: TensorFlowScalar +>( + serializedSparse: Tensor +) -> (sparseIndices: Tensor, sparseValues: Tensor, sparseShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("DeserializeSparse", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tserialized", Tserialized.tensorFlowDataType) + op.addInput(serializedSparse) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Deserialize `SparseTensor` objects. +/// +/// The input `serialized_sparse` must have the shape `[?, ?, ..., ?, 3]` where +/// the last dimension stores serialized `SparseTensor` objects and the other N +/// dimensions (N >= 0) correspond to a batch. The ranks of the original +/// `SparseTensor` objects must all match. When the final `SparseTensor` is +/// created, its rank is the rank of the incoming `SparseTensor` objects plus N; +/// the sparse tensors have been concatenated along new dimensions, one for each +/// batch. +/// +/// The output `SparseTensor` object's shape values for the original dimensions +/// are the max across the input `SparseTensor` objects' shape values for the +/// corresponding dimensions. The new dimensions match the size of the batch. +/// +/// The input `SparseTensor` objects' indices are assumed ordered in +/// standard lexicographic order. If this is not the case, after this +/// step run `SparseReorder` to restore index ordering. +/// +/// For example, if the serialized input is a `[2 x 3]` matrix representing two +/// original `SparseTensor` objects: +/// +/// index = [ 0] +/// [10] +/// [20] +/// values = [1, 2, 3] +/// shape = [50] +/// +/// and +/// +/// index = [ 2] +/// [10] +/// values = [4, 5] +/// shape = [30] +/// +/// then the final deserialized `SparseTensor` will be: +/// +/// index = [0 0] +/// [0 10] +/// [0 20] +/// [1 2] +/// [1 10] +/// values = [1, 2, 3, 4, 5] +/// shape = [2 50] +/// +/// - Parameter serialized_sparse: The serialized `SparseTensor` objects. The last dimension +/// must have 3 columns. +/// +/// - Attr dtype: The `dtype` of the serialized `SparseTensor` objects. +@inlinable @inline(__always) +public static func deserializeSparse( + serializedSparse: StringTensor +) -> (sparseIndices: Tensor, sparseValues: Tensor, sparseShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("DeserializeSparse", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tserialized", TensorDataType(TF_STRING)) + op.addInput(serializedSparse) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Deletes the resource specified by the handle. +/// +/// All subsequent operations using the resource will result in a NotFound +/// error status. +/// +/// - Parameter resource: handle to the resource to delete. +/// +/// - Attr ignore_lookup_error: whether to ignore the error when the resource +/// doesn't exist. +@inlinable @inline(__always) +public static func destroyResourceOp( + resource: ResourceHandle, + ignoreLookupError: Bool = true +) { + let nOutputs = 0 + let op = makeOp("DestroyResourceOp", nOutputs) + op.updateAttribute("ignore_lookup_error", ignoreLookupError) + op.addInput(resource) + op.execute() +} + +@inlinable @inline(__always) +public static func devicePlacementOp( +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("DevicePlacementOp", nOutputs) + + return op.execute(Int(1)) +} + +/// Returns a diagonal tensor with a given diagonal values. +/// +/// Given a `diagonal`, this operation returns a tensor with the `diagonal` and +/// everything else padded with zeros. The diagonal is computed as follows: +/// +/// Assume `diagonal` has dimensions [D1,..., Dk], then the output is a tensor of +/// rank 2k with dimensions [D1,..., Dk, D1,..., Dk] where: +/// +/// `output[i1,..., ik, i1,..., ik] = diagonal[i1, ..., ik]` and 0 everywhere else. +/// +/// For example: +/// +/// ``` +/// # 'diagonal' is [1, 2, 3, 4] +/// tf.diag(diagonal) ==> [[1, 0, 0, 0] +/// [0, 2, 0, 0] +/// [0, 0, 3, 0] +/// [0, 0, 0, 4]] +/// ``` +/// +/// - Parameter diagonal: Rank k tensor where k is at most 1. +@inlinable @inline(__always) +public static func diag( + diagonal: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Diag", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(diagonal) + return op.execute(Int(1)) +} + +/// Returns the diagonal part of the tensor. +/// +/// This operation returns a tensor with the `diagonal` part +/// of the `input`. The `diagonal` part is computed as follows: +/// +/// Assume `input` has dimensions `[D1,..., Dk, D1,..., Dk]`, then the output is a +/// tensor of rank `k` with dimensions `[D1,..., Dk]` where: +/// +/// `diagonal[i1,..., ik] = input[i1, ..., ik, i1,..., ik]`. +/// +/// For example: +/// +/// ``` +/// # 'input' is [[1, 0, 0, 0] +/// [0, 2, 0, 0] +/// [0, 0, 3, 0] +/// [0, 0, 0, 4]] +/// +/// tf.diag_part(input) ==> [1, 2, 3, 4] +/// ``` +/// +/// - Parameter input: Rank k tensor where k is even and not zero. +/// +/// - Output diagonal: The extracted diagonal. +@inlinable @inline(__always) +public static func diagPart( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DiagPart", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Computes Psi, the derivative of Lgamma (the log of the absolute value of +/// +/// `Gamma(x)`), element-wise. +@inlinable @inline(__always) +public static func digamma( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Digamma", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the grayscale dilation of 4-D `input` and 3-D `filter` tensors. +/// +/// The `input` tensor has shape `[batch, in_height, in_width, depth]` and the +/// `filter` tensor has shape `[filter_height, filter_width, depth]`, i.e., each +/// input channel is processed independently of the others with its own structuring +/// function. The `output` tensor has shape +/// `[batch, out_height, out_width, depth]`. The spatial dimensions of the output +/// tensor depend on the `padding` algorithm. We currently only support the default +/// "NHWC" `data_format`. +/// +/// In detail, the grayscale morphological 2-D dilation is the max-sum correlation +/// (for consistency with `conv2d`, we use unmirrored filters): +/// +/// output[b, y, x, c] = +/// max_{dy, dx} input[b, +/// strides[1] * y + rates[1] * dy, +/// strides[2] * x + rates[2] * dx, +/// c] + +/// filter[dy, dx, c] +/// +/// Max-pooling is a special case when the filter has size equal to the pooling +/// kernel size and contains all zeros. +/// +/// Note on duality: The dilation of `input` by the `filter` is equal to the +/// negation of the erosion of `-input` by the reflected `filter`. +/// +/// - Parameters: +/// - input: 4-D with shape `[batch, in_height, in_width, depth]`. +/// - filter: 3-D with shape `[filter_height, filter_width, depth]`. +/// +/// - Attrs: +/// - strides: The stride of the sliding window for each dimension of the input +/// tensor. Must be: `[1, stride_height, stride_width, 1]`. +/// - rates: The input stride for atrous morphological dilation. Must be: +/// `[1, rate_height, rate_width, 1]`. +/// - padding: The type of padding algorithm to use. +/// +/// - Output output: 4-D with shape `[batch, out_height, out_width, depth]`. +@inlinable @inline(__always) +public static func dilation2D( + _ input: Tensor, + filter: Tensor, + strides: [Int32], + rates: [Int32], + padding: Padding +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Dilation2D", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("rates", rates) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(filter) + return op.execute(Int(1)) +} + +/// Computes the gradient of morphological 2-D dilation with respect to the filter. +/// +/// - Parameters: +/// - input: 4-D with shape `[batch, in_height, in_width, depth]`. +/// - filter: 3-D with shape `[filter_height, filter_width, depth]`. +/// - out_backprop: 4-D with shape `[batch, out_height, out_width, depth]`. +/// +/// - Attrs: +/// - strides: 1-D of length 4. The stride of the sliding window for each dimension of +/// the input tensor. Must be: `[1, stride_height, stride_width, 1]`. +/// - rates: 1-D of length 4. The input stride for atrous morphological dilation. +/// Must be: `[1, rate_height, rate_width, 1]`. +/// - padding: The type of padding algorithm to use. +/// +/// - Output filter_backprop: 3-D with shape `[filter_height, filter_width, depth]`. +@inlinable @inline(__always) +public static func dilation2DBackpropFilter( + _ input: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + rates: [Int32], + padding: Padding +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Dilation2DBackpropFilter", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("rates", rates) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) +} + +/// Computes the gradient of morphological 2-D dilation with respect to the input. +/// +/// - Parameters: +/// - input: 4-D with shape `[batch, in_height, in_width, depth]`. +/// - filter: 3-D with shape `[filter_height, filter_width, depth]`. +/// - out_backprop: 4-D with shape `[batch, out_height, out_width, depth]`. +/// +/// - Attrs: +/// - strides: 1-D of length 4. The stride of the sliding window for each dimension of +/// the input tensor. Must be: `[1, stride_height, stride_width, 1]`. +/// - rates: 1-D of length 4. The input stride for atrous morphological dilation. +/// Must be: `[1, rate_height, rate_width, 1]`. +/// - padding: The type of padding algorithm to use. +/// +/// - Output in_backprop: 4-D with shape `[batch, in_height, in_width, depth]`. +@inlinable @inline(__always) +public static func dilation2DBackpropInput( + _ input: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + rates: [Int32], + padding: Padding +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Dilation2DBackpropInput", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("rates", rates) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) +} + +/// Returns x / y element-wise. +/// +/// *NOTE*: `Div` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func div( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Div", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns 0 if the denominator is zero. +/// +/// +/// *NOTE*: `DivNoNan` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func divNoNan( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DivNoNan", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Draw bounding boxes on a batch of images. +/// +/// Outputs a copy of `images` but draws on top of the pixels zero or more bounding +/// boxes specified by the locations in `boxes`. The coordinates of the each +/// bounding box in `boxes` are encoded as `[y_min, x_min, y_max, x_max]`. The +/// bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and +/// height of the underlying image. +/// +/// For example, if an image is 100 x 200 pixels (height x width) and the bounding +/// box is `[0.1, 0.2, 0.5, 0.9]`, the upper-left and bottom-right coordinates of +/// the bounding box will be `(40, 10)` to `(180, 50)` (in (x,y) coordinates). +/// +/// Parts of the bounding box may fall outside the image. +/// +/// - Parameters: +/// - images: 4-D with shape `[batch, height, width, depth]`. A batch of images. +/// - boxes: 3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding +/// boxes. +/// +/// - Output output: 4-D with the same shape as `images`. The batch of input images with +/// bounding boxes drawn on the images. +@inlinable @inline(__always) +public static func drawBoundingBoxes( + images: Tensor, + boxes: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DrawBoundingBoxes", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + op.addInput(boxes) + return op.execute(Int(1)) +} + +/// Draw bounding boxes on a batch of images. +/// +/// Outputs a copy of `images` but draws on top of the pixels zero or more bounding +/// boxes specified by the locations in `boxes`. The coordinates of the each +/// bounding box in `boxes` are encoded as `[y_min, x_min, y_max, x_max]`. The +/// bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and +/// height of the underlying image. +/// +/// For example, if an image is 100 x 200 pixels (height x width) and the bounding +/// box is `[0.1, 0.2, 0.5, 0.9]`, the upper-left and bottom-right coordinates of +/// the bounding box will be `(40, 10)` to `(100, 50)` (in (x,y) coordinates). +/// +/// Parts of the bounding box may fall outside the image. +/// +/// - Parameters: +/// - images: 4-D with shape `[batch, height, width, depth]`. A batch of images. +/// - boxes: 3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding +/// boxes. +/// - colors: 2-D. A list of RGBA colors to cycle through for the boxes. +/// +/// - Output output: 4-D with the same shape as `images`. The batch of input images with +/// bounding boxes drawn on the images. +@inlinable @inline(__always) +public static func drawBoundingBoxesV2( + images: Tensor, + boxes: Tensor, + colors: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DrawBoundingBoxesV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + op.addInput(boxes) + op.addInput(colors) + return op.execute(Int(1)) +} + +/// Partitions `data` into `num_partitions` tensors using indices from `partitions`. +/// +/// For each index tuple `js` of size `partitions.ndim`, the slice `data[js, ...]` +/// becomes part of `outputs[partitions[js]]`. The slices with `partitions[js] = i` +/// are placed in `outputs[i]` in lexicographic order of `js`, and the first +/// dimension of `outputs[i]` is the number of entries in `partitions` equal to `i`. +/// In detail, +/// +/// ```python +/// outputs[i].shape = [sum(partitions == i)] + data.shape[partitions.ndim:] +/// +/// outputs[i] = pack([data[js, ...] for js if partitions[js] == i]) +/// ``` +/// +/// `data.shape` must start with `partitions.shape`. +/// +/// For example: +/// +/// ```python +/// # Scalar partitions. +/// partitions = 1 +/// num_partitions = 2 +/// data = [10, 20] +/// outputs[0] = [] # Empty with shape [0, 2] +/// outputs[1] = [[10, 20]] +/// +/// # Vector partitions. +/// partitions = [0, 0, 1, 1, 0] +/// num_partitions = 2 +/// data = [10, 20, 30, 40, 50] +/// outputs[0] = [10, 20, 50] +/// outputs[1] = [30, 40] +/// ``` +/// +/// See `dynamic_stitch` for an example on how to merge partitions back. +/// +///
+/// +///
+/// +/// - Parameter partitions: Any shape. Indices in the range `[0, num_partitions)`. +/// +/// - Attr num_partitions: The number of partitions to output. +@inlinable @inline(__always) +public static func dynamicPartition( + data: Tensor, + partitions: Tensor, + numPartitions: Int64 +) -> [Tensor] { + let nOutputs = Int(numPartitions) + let op = makeOp("DynamicPartition", nOutputs) + op.updateAttribute("num_partitions", numPartitions) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(data) + op.addInput(partitions) + return op.execute(Int(numPartitions)) +} + +/// Interleave the values from the `data` tensors into a single tensor. +/// +/// Builds a merged tensor such that +/// +/// ```python +/// merged[indices[m][i, ..., j], ...] = data[m][i, ..., j, ...] +/// ``` +/// +/// For example, if each `indices[m]` is scalar or vector, we have +/// +/// ```python +/// # Scalar indices: +/// merged[indices[m], ...] = data[m][...] +/// +/// # Vector indices: +/// merged[indices[m][i], ...] = data[m][i, ...] +/// ``` +/// +/// Each `data[i].shape` must start with the corresponding `indices[i].shape`, +/// and the rest of `data[i].shape` must be constant w.r.t. `i`. That is, we +/// must have `data[i].shape = indices[i].shape + constant`. In terms of this +/// `constant`, the output shape is +/// +/// merged.shape = [max(indices)] + constant +/// +/// Values are merged in order, so if an index appears in both `indices[m][i]` and +/// `indices[n][j]` for `(m,i) < (n,j)` the slice `data[n][j]` will appear in the +/// merged result. If you do not need this guarantee, ParallelDynamicStitch might +/// perform better on some devices. +/// +/// For example: +/// +/// ```python +/// indices[0] = 6 +/// indices[1] = [4, 1] +/// indices[2] = [[5, 2], [0, 3]] +/// data[0] = [61, 62] +/// data[1] = [[41, 42], [11, 12]] +/// data[2] = [[[51, 52], [21, 22]], [[1, 2], [31, 32]]] +/// merged = [[1, 2], [11, 12], [21, 22], [31, 32], [41, 42], +/// [51, 52], [61, 62]] +/// ``` +/// +/// This method can be used to merge partitions created by `dynamic_partition` +/// as illustrated on the following example: +/// +/// ```python +/// # Apply function (increments x_i) on elements for which a certain condition +/// # apply (x_i != -1 in this example). +/// x=tf.constant([0.1, -1., 5.2, 4.3, -1., 7.4]) +/// condition_mask=tf.not_equal(x,tf.constant(-1.)) +/// partitioned_data = tf.dynamic_partition( +/// x, tf.cast(condition_mask, tf.int32) , 2) +/// partitioned_data[1] = partitioned_data[1] + 1.0 +/// condition_indices = tf.dynamic_partition( +/// tf.range(tf.shape(x)[0]), tf.cast(condition_mask, tf.int32) , 2) +/// x = tf.dynamic_stitch(condition_indices, partitioned_data) +/// # Here x=[1.1, -1., 6.2, 5.3, -1, 8.4], the -1. values remain +/// # unchanged. +/// ``` +/// +///
+/// +///
+@inlinable @inline(__always) +public static func dynamicStitch( + indices: [Tensor], + data: [Tensor] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DynamicStitch", nOutputs) + op.updateAttribute("N", indices.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInputList(indices) + op.addInputList(data) + return op.execute(Int(1)) +} + +/// Eagerly executes a python function to compute func(input)->output. The +/// +/// semantics of the input, output, and attributes are the same as those for +/// PyFunc. +@inlinable @inline(__always) +public static func eagerPyFunc< + Tin: TensorArrayProtocol, + Tout: TensorGroup +>( + _ input: Tin, + token: String +) -> Tout { + let nOutputs = Int(Tout._typeList.count) + let op = makeOp("EagerPyFunc", nOutputs) + op.updateAttribute("token", token) + op.updateAttribute("Tin", input._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.addInputList(input) + return op.execute(Int(Tout._typeList.count)) +} + +/// Computes the (possibly normalized) Levenshtein Edit Distance. +/// +/// The inputs are variable-length sequences provided by SparseTensors +/// (hypothesis_indices, hypothesis_values, hypothesis_shape) +/// and +/// (truth_indices, truth_values, truth_shape). +/// +/// The inputs are: +/// +/// - Parameters: +/// - hypothesis_indices: The indices of the hypothesis list SparseTensor. +/// This is an N x R int64 matrix. +/// - hypothesis_values: The values of the hypothesis list SparseTensor. +/// This is an N-length vector. +/// - hypothesis_shape: The shape of the hypothesis list SparseTensor. +/// This is an R-length vector. +/// - truth_indices: The indices of the truth list SparseTensor. +/// This is an M x R int64 matrix. +/// - truth_values: The values of the truth list SparseTensor. +/// This is an M-length vector. +/// - truth_shape: truth indices, vector. +/// +/// - Attr normalize: boolean (if true, edit distances are normalized by length of truth). +/// +/// The output is: +/// +/// - Output output: A dense float tensor with rank R - 1. +/// +/// For the example input: +/// +/// // hypothesis represents a 2x1 matrix with variable-length values: +/// // (0,0) = ["a"] +/// // (1,0) = ["b"] +/// hypothesis_indices = [[0, 0, 0], +/// [1, 0, 0]] +/// hypothesis_values = ["a", "b"] +/// hypothesis_shape = [2, 1, 1] +/// +/// // truth represents a 2x2 matrix with variable-length values: +/// // (0,0) = [] +/// // (0,1) = ["a"] +/// // (1,0) = ["b", "c"] +/// // (1,1) = ["a"] +/// truth_indices = [[0, 1, 0], +/// [1, 0, 0], +/// [1, 0, 1], +/// [1, 1, 0]] +/// truth_values = ["a", "b", "c", "a"] +/// truth_shape = [2, 2, 2] +/// normalize = true +/// +/// The output will be: +/// +/// // output is a 2x2 matrix with edit distances normalized by truth lengths. +/// output = [[inf, 1.0], // (0,0): no truth, (0,1): no hypothesis +/// [0.5, 1.0]] // (1,0): addition, (1,1): no hypothesis +@inlinable @inline(__always) +public static func editDistance( + hypothesisIndices: Tensor, + hypothesisValues: Tensor, + hypothesisShape: Tensor, + truthIndices: Tensor, + truthValues: Tensor, + truthShape: Tensor, + normalize: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("EditDistance", nOutputs) + op.updateAttribute("normalize", normalize) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(hypothesisIndices) + op.addInput(hypothesisValues) + op.addInput(hypothesisShape) + op.addInput(truthIndices) + op.addInput(truthValues) + op.addInput(truthShape) + return op.execute(Int(1)) +} + +/// Computes exponential linear: `exp(features) - 1` if < 0, `features` otherwise. +/// +/// See [Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs) +/// ](http://arxiv.org/abs/1511.07289) +@inlinable @inline(__always) +public static func elu( + features: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Elu", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) +} + +/// Computes gradients for the exponential linear (Elu) operation. +/// +/// - Parameters: +/// - gradients: The backpropagated gradients to the corresponding Elu operation. +/// - outputs: The outputs of the corresponding Elu operation. +/// +/// - Output backprops: The gradients: `gradients * (outputs + 1)` if outputs < 0, +/// `gradients` otherwise. +@inlinable @inline(__always) +public static func eluGrad( + gradients: Tensor, + outputs: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("EluGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(outputs) + return op.execute(Int(1)) +} + +/// Creates a tensor with the given shape. +/// +/// This operation creates a tensor of `shape` and `dtype`. +/// +/// - Parameter shape: 1-D. Represents the shape of the output tensor. +/// +/// - Attr init: If True, initialize the returned tensor with the default value of dtype. Otherwise, the implementation is free not to initializethe tensor's content. +/// +/// - Output output: A `Tensor` of type `T`. +@inlinable @inline(__always) +public static func empty( + shape: Tensor, + init_: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Empty", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("init", init_) + op.addInput(shape) + return op.execute(Int(1)) +} + +/// Creates and returns an empty tensor list. +/// +/// All list elements must be tensors of dtype element_dtype and shape compatible +/// with element_shape. +/// +/// handle: an empty tensor list. +/// element_dtype: the type of elements in the list. +/// element_shape: a shape compatible with that of elements in the list. +@inlinable @inline(__always) +public static func emptyTensorList( + elementShape: Tensor, + maxNumElements: Tensor, + elementDtype: TensorDataType +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("EmptyTensorList", nOutputs) + op.updateAttribute("element_dtype", elementDtype) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(elementShape) + op.addInput(maxNumElements) + return op.execute(Int(1)) +} + +/// Encode strings into web-safe base64 format. +/// +/// Refer to the following article for more information on base64 format: +/// en.wikipedia.org/wiki/Base64. Base64 strings may have padding with '=' at the +/// end so that the encoded has length multiple of 4. See Padding section of the +/// link above. +/// +/// Web-safe means that the encoder uses - and _ instead of + and /. +/// +/// - Parameter input: Strings to be encoded. +/// +/// - Attr pad: Bool whether padding is applied at the ends. +/// +/// - Output output: Input strings encoded in base64. +@inlinable @inline(__always) +public static func encodeBase64( + _ input: StringTensor, + pad: Bool = false +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("EncodeBase64", nOutputs) + op.updateAttribute("pad", pad) + op.addInput(input) + return op.execute(Int(1)) +} + +/// JPEG-encode an image. +/// +/// `image` is a 3-D uint8 Tensor of shape `[height, width, channels]`. +/// +/// The attr `format` can be used to override the color format of the encoded +/// output. Values can be: +/// +/// * `''`: Use a default format based on the number of channels in the image. +/// * `grayscale`: Output a grayscale JPEG image. The `channels` dimension +/// of `image` must be 1. +/// * `rgb`: Output an RGB JPEG image. The `channels` dimension +/// of `image` must be 3. +/// +/// If `format` is not specified or is the empty string, a default format is picked +/// in function of the number of channels in `image`: +/// +/// * 1: Output a grayscale image. +/// * 3: Output an RGB image. +/// +/// - Parameter image: 3-D with shape `[height, width, channels]`. +/// +/// - Attrs: +/// - format: Per pixel image format. +/// - quality: Quality of the compression from 0 to 100 (higher is better and slower). +/// - progressive: If True, create a JPEG that loads progressively (coarse to fine). +/// - optimize_size: If True, spend CPU/RAM to reduce size with no quality change. +/// - chroma_downsampling: See http://en.wikipedia.org/wiki/Chroma_subsampling. +/// - density_unit: Unit used to specify `x_density` and `y_density`: +/// pixels per inch (`'in'`) or centimeter (`'cm'`). +/// - x_density: Horizontal pixels per density unit. +/// - y_density: Vertical pixels per density unit. +/// - xmp_metadata: If not empty, embed this XMP metadata in the image header. +/// +/// - Output contents: 0-D. JPEG-encoded image. +@inlinable @inline(__always) +public static func encodeJpeg( + image: Tensor, + format: Format, + quality: Int64 = 95, + progressive: Bool = false, + optimizeSize: Bool = false, + chromaDownsampling: Bool = true, + densityUnit: DensityUnit = .in_, + xDensity: Int64 = 300, + yDensity: Int64 = 300, + xmpMetadata: String +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("EncodeJpeg", nOutputs) + op.updateAttribute("format", format.cName) + op.updateAttribute("quality", quality) + op.updateAttribute("progressive", progressive) + op.updateAttribute("optimize_size", optimizeSize) + op.updateAttribute("chroma_downsampling", chromaDownsampling) + op.updateAttribute("density_unit", densityUnit.cName) + op.updateAttribute("x_density", xDensity) + op.updateAttribute("y_density", yDensity) + op.updateAttribute("xmp_metadata", xmpMetadata) + op.addInput(image) + return op.execute(Int(1)) +} + +/// JPEG encode input image with provided compression quality. +/// +/// `image` is a 3-D uint8 Tensor of shape `[height, width, channels]`. +/// `quality` is an int32 jpeg compression quality value between 0 and 100. +/// +/// +/// - Parameters: +/// - images: Images to adjust. At least 3-D. +/// - quality: An int quality to encode to. +/// +/// - Output contents: 0-D. JPEG-encoded image. +@inlinable @inline(__always) +public static func encodeJpegVariableQuality( + images: Tensor, + quality: Tensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("EncodeJpegVariableQuality", nOutputs) + op.addInput(images) + op.addInput(quality) + return op.execute(Int(1)) +} + +/// PNG-encode an image. +/// +/// `image` is a 3-D uint8 or uint16 Tensor of shape `[height, width, channels]` +/// where `channels` is: +/// +/// * 1: for grayscale. +/// * 2: for grayscale + alpha. +/// * 3: for RGB. +/// * 4: for RGBA. +/// +/// The ZLIB compression level, `compression`, can be -1 for the PNG-encoder +/// default or a value from 0 to 9. 9 is the highest compression level, generating +/// the smallest output, but is slower. +/// +/// - Parameter image: 3-D with shape `[height, width, channels]`. +/// +/// - Attr compression: Compression level. +/// +/// - Output contents: 0-D. PNG-encoded image. +@inlinable @inline(__always) +public static func encodePng( + image: Tensor, + compression: Int64 = -1 +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("EncodePng", nOutputs) + op.updateAttribute("compression", compression) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(image) + return op.execute(Int(1)) +} + +/// The op serializes protobuf messages provided in the input tensors. +/// +/// The types of the tensors in `values` must match the schema for the +/// fields specified in `field_names`. All the tensors in `values` must +/// have a common shape prefix, *batch_shape*. +/// +/// The `sizes` tensor specifies repeat counts for each field. The repeat +/// count (last dimension) of a each tensor in `values` must be greater +/// than or equal to corresponding repeat count in `sizes`. +/// +/// A `message_type` name must be provided to give context for the field +/// names. The actual message descriptor can be looked up either in the +/// linked-in descriptor pool or a filename provided by the caller using +/// the `descriptor_source` attribute. +/// +/// The `descriptor_source` attribute selects a source of protocol +/// descriptors to consult when looking up `message_type`. This may be a +/// filename containing a serialized `FileDescriptorSet` message, +/// or the special value `local://`, in which case only descriptors linked +/// into the code will be searched; the filename can be on any filesystem +/// accessible to TensorFlow. +/// +/// You can build a `descriptor_source` file using the `--descriptor_set_out` +/// and `--include_imports` options to the protocol compiler `protoc`. +/// +/// The `local://` database only covers descriptors linked into the +/// code via C++ libraries, not Python imports. You can link in a proto descriptor +/// by creating a cc_library target with alwayslink=1. +/// +/// There are a few special cases in the value mapping: +/// +/// Submessage and group fields must be pre-serialized as TensorFlow strings. +/// +/// TensorFlow lacks support for unsigned int64s, so they must be +/// represented as `tf.int64` with the same twos-complement bit pattern +/// (the obvious way). +/// +/// Unsigned int32 values can be represented exactly with `tf.int64`, or +/// with sign wrapping if the input is of type `tf.int32`. +/// +/// - Parameters: +/// - sizes: Tensor of int32 with shape `[batch_shape, len(field_names)]`. +/// - values: List of tensors containing values for the corresponding field. +/// +/// - Attrs: +/// - field_names: List of strings containing proto field names. +/// - message_type: Name of the proto message type to decode. +/// - Tinput_types: The input types. +/// +/// - Output bytes: Tensor of serialized protos with shape `batch_shape`. +@inlinable @inline(__always) +public static func encodeProto( + sizes: Tensor, + _ values: TinputTypes, + fieldNames: [String], + messageType: String, + descriptorSource: String = "local://" +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("EncodeProto", nOutputs) + op.updateAttribute("field_names", fieldNames) + op.updateAttribute("message_type", messageType) + op.updateAttribute("descriptor_source", descriptorSource) + op.updateAttribute("Tinput_types", values._typeList) + op.addInput(sizes) + op.addInputList(values) + return op.execute(Int(1)) +} + +/// Encode audio data using the WAV file format. +/// +/// This operation will generate a string suitable to be saved out to create a .wav +/// audio file. It will be encoded in the 16-bit PCM format. It takes in float +/// values in the range -1.0f to 1.0f, and any outside that value will be clamped to +/// that range. +/// +/// `audio` is a 2-D float Tensor of shape `[length, channels]`. +/// `sample_rate` is a scalar Tensor holding the rate to use (e.g. 44100). +/// +/// - Parameters: +/// - audio: 2-D with shape `[length, channels]`. +/// - sample_rate: Scalar containing the sample frequency. +/// +/// - Output contents: 0-D. WAV-encoded file contents. +@inlinable @inline(__always) +public static func encodeWav( + audio: Tensor, + sampleRate: Tensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("EncodeWav", nOutputs) + op.addInput(audio) + op.addInput(sampleRate) + return op.execute(Int(1)) +} + +/// An op that enqueues a list of input batch tensors to TPUEmbedding. +/// +/// - Parameters: +/// - batch: A list of 1D tensors, one for each embedding table, containing the +/// indices into the tables. +/// - mode_override: A string input that overrides the mode specified in the +/// TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', +/// 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set +/// in TPUEmbeddingConfiguration is used, otherwise mode_override is used. +/// +/// - Attr device_ordinal: The TPU device to use. Should be >= 0 and less than the number +/// of TPU cores in the task on which the node is placed. +@inlinable @inline(__always) +public static func enqueueTPUEmbeddingIntegerBatch( + batch: [Tensor], + modeOverride: StringTensor, + deviceOrdinal: Int64 = -1 +) { + let nOutputs = 0 + let op = makeOp("EnqueueTPUEmbeddingIntegerBatch", nOutputs) + op.updateAttribute("N", batch.count) + op.updateAttribute("device_ordinal", deviceOrdinal) + op.addInputList(batch) + op.addInput(modeOverride) + op.execute() +} + +/// An op that enqueues TPUEmbedding input indices from a SparseTensor. +/// +/// This Op eases the porting of code that uses embedding_lookup_sparse(), +/// although some Python preprocessing of the SparseTensor arguments to +/// embedding_lookup_sparse() is required to produce the arguments to this Op, +/// since only a single EnqueueTPUEmbeddingSparseBatch Op is allowed per training +/// step. +/// +/// The tensors at corresponding positions in the three input lists +/// must have the same shape, i.e. rank 1 with dim_size() equal to the total +/// number of lookups into the table described by the corresponding table_id. +/// +/// - Parameters: +/// - sample_indices: A list of rank 1 Tensors specifying the training example and +/// feature to which the corresponding embedding_indices and aggregation_weights +/// values belong. sample_indices[i] must equal b * nf + f, where nf is the +/// number of features from the corresponding table, f is in [0, nf), and +/// b is in [0, batch size). +/// - embedding_indices: A list of rank 1 Tensors, indices into the embedding tables. +/// - aggregation_weights: A list of rank 1 Tensors containing per sample -- i.e. per +/// (training example, feature) -- aggregation weights. +/// - mode_override: A string input that overrides the mode specified in the +/// TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', +/// 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set +/// in TPUEmbeddingConfiguration is used, otherwise mode_override is used. +/// +/// - Attrs: +/// - device_ordinal: The TPU device to use. Should be >= 0 and less than the number +/// of TPU cores in the task on which the node is placed. +/// - combiners: A list of string scalars, one for each embedding table that specify +/// how to normalize the embedding activations after weighted summation. +/// Supported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have +/// the sum of the weights be 0 for 'mean' or the sum of the squared weights be +/// 0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for +/// all tables. +@inlinable @inline(__always) +public static func enqueueTPUEmbeddingSparseBatch< + T1: BinaryInteger & TensorFlowScalar, + T2: BinaryInteger & TensorFlowScalar, + T3: FloatingPoint & TensorFlowScalar +>( + sampleIndices: [Tensor], + embeddingIndices: [Tensor], + aggregationWeights: [Tensor], + modeOverride: StringTensor, + deviceOrdinal: Int64 = -1, + combiners: [String] +) { + let nOutputs = 0 + let op = makeOp("EnqueueTPUEmbeddingSparseBatch", nOutputs) + op.updateAttribute("T1", T1.tensorFlowDataType) + op.updateAttribute("T2", T2.tensorFlowDataType) + op.updateAttribute("T3", T3.tensorFlowDataType) + op.updateAttribute("N", sampleIndices.count) + op.updateAttribute("device_ordinal", deviceOrdinal) + op.updateAttribute("combiners", combiners) + op.addInputList(sampleIndices) + op.addInputList(embeddingIndices) + op.addInputList(aggregationWeights) + op.addInput(modeOverride) + op.execute() +} + +/// Eases the porting of code that uses tf.nn.embedding_lookup_sparse(). +/// +/// sample_indices[i], embedding_indices[i] and aggregation_weights[i] correspond +/// to the ith feature. table_ids[i] indicates which embedding table to look up ith +/// feature. +/// +/// The tensors at corresponding positions in the three input lists (sample_indices, +/// embedding_indices and aggregation_weights) must have the same shape, i.e. rank 1 +/// with dim_size() equal to the total number of lookups into the table described by +/// the corresponding feature. +/// +/// - Parameters: +/// - sample_indices: A list of rank 1 Tensors specifying the training example to +/// which the corresponding embedding_indices and aggregation_weights values +/// belong. It corresponds to sp_ids.indices[:,0] in embedding_lookup_sparse(). +/// - embedding_indices: A list of rank 1 Tensors, indices into the embedding tables. +/// It corresponds to sp_ids.values in embedding_lookup_sparse(). +/// - aggregation_weights: A list of rank 1 Tensors containing per training example +/// aggregation weights. It corresponds to sp_weights.values in +/// embedding_lookup_sparse(). +/// - mode_override: A string input that overrides the mode specified in the +/// TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', +/// 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set +/// in TPUEmbeddingConfiguration is used, otherwise mode_override is used. +/// +/// - Attrs: +/// - device_ordinal: The TPU device to use. Should be >= 0 and less than the number +/// of TPU cores in the task on which the node is placed. +/// - combiners: A list of string scalars, one for each embedding table that specify +/// how to normalize the embedding activations after weighted summation. +/// Supported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have +/// the sum of the weights be 0 for 'mean' or the sum of the squared weights be +/// 0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for +/// all tables. +/// - table_ids: A list of integers specifying the identifier of the embedding table +/// (offset of TableDescriptor in the TPUEmbeddingConfiguration) to lookup the +/// corresponding input. The ith input is looked up using table_ids[i]. The size +/// of the table_ids list must be equal to that of sample_indices, +/// embedding_indices and aggregation_weights. +@inlinable @inline(__always) +public static func enqueueTPUEmbeddingSparseTensorBatch< + T1: BinaryInteger & TensorFlowScalar, + T2: BinaryInteger & TensorFlowScalar, + T3: FloatingPoint & TensorFlowScalar +>( + sampleIndices: [Tensor], + embeddingIndices: [Tensor], + aggregationWeights: [Tensor], + modeOverride: StringTensor, + deviceOrdinal: Int64 = -1, + combiners: [String], + tableIds: [Int32], + maxSequenceLengths: [Int32] +) { + let nOutputs = 0 + let op = makeOp("EnqueueTPUEmbeddingSparseTensorBatch", nOutputs) + op.updateAttribute("T1", T1.tensorFlowDataType) + op.updateAttribute("T2", T2.tensorFlowDataType) + op.updateAttribute("T3", T3.tensorFlowDataType) + op.updateAttribute("N", sampleIndices.count) + op.updateAttribute("device_ordinal", deviceOrdinal) + op.updateAttribute("combiners", combiners) + op.updateAttribute("table_ids", tableIds) + op.updateAttribute("max_sequence_lengths", maxSequenceLengths) + op.addInputList(sampleIndices) + op.addInputList(embeddingIndices) + op.addInputList(aggregationWeights) + op.addInput(modeOverride) + op.execute() +} + +/// Ensures that the tensor's shape matches the expected shape. +/// +/// Raises an error if the input tensor's shape does not match the specified shape. +/// Returns the input tensor otherwise. +/// +/// - Parameter input: A tensor, whose shape is to be validated. +/// +/// - Attr shape: The expected (possibly partially specified) shape of the input tensor. +/// +/// - Output output: A tensor with the same shape and contents as the input tensor or value. +@inlinable @inline(__always) +public static func ensureShape( + _ input: Tensor, + shape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("EnsureShape", nOutputs) + op.updateAttribute("shape", shape) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Creates or finds a child frame, and makes `data` available to the child frame. +/// +/// This op is used together with `Exit` to create loops in the graph. +/// The unique `frame_name` is used by the `Executor` to identify frames. If +/// `is_constant` is true, `output` is a constant in the child frame; otherwise +/// it may be changed in the child frame. At most `parallel_iterations` iterations +/// are run in parallel in the child frame. +/// +/// - Parameter data: The tensor to be made available to the child frame. +/// +/// - Attrs: +/// - frame_name: The name of the child frame. +/// - is_constant: If true, the output is constant within the child frame. +/// - parallel_iterations: The number of iterations allowed to run in parallel. +/// +/// - Output output: The same tensor as `data`. +@inlinable @inline(__always) +public static func enter( + data: Tensor, + frameName: String, + isConstant: Bool = false, + parallelIterations: Int64 = 10 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Enter", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("frame_name", frameName) + op.updateAttribute("is_constant", isConstant) + op.updateAttribute("parallel_iterations", parallelIterations) + op.addInput(data) + return op.execute(Int(1)) +} + +/// Returns the truth value of (x == y) element-wise. +/// +/// *NOTE*: `Equal` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func equal( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Equal", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns the truth value of (x == y) element-wise. +/// +/// *NOTE*: `Equal` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func equal( + _ x: StringTensor, + _ y: StringTensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Equal", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Computes the Gauss error function of `x` element-wise. +@inlinable @inline(__always) +public static func erf( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Erf", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the complementary error function of `x` element-wise. +@inlinable @inline(__always) +public static func erfc( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Erfc", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the euclidean norm of elements across dimensions of a tensor. +/// +/// Reduces `input` along the dimensions given in `axis`. Unless +/// `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in +/// `axis`. If `keep_dims` is true, the reduced dimensions are +/// retained with length 1. +/// +/// - Parameters: +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. +/// +/// - Attr keep_dims: If true, retain reduced dimensions with length 1. +/// +/// - Output output: The reduced tensor. +@inlinable @inline(__always) +public static func euclideanNorm< + T: Numeric & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("EuclideanNorm", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) +} + +/// Exits the current frame to its parent frame. +/// +/// Exit makes its input `data` available to the parent frame. +/// +/// - Parameter data: The tensor to be made available to the parent frame. +/// +/// - Output output: The same tensor as `data`. +@inlinable @inline(__always) +public static func exit( + data: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Exit", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(data) + return op.execute(Int(1)) +} + +/// Computes exponential of x element-wise. \\(y = e^x\\). +@inlinable @inline(__always) +public static func exp( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Exp", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Inserts a dimension of 1 into a tensor's shape. +/// +/// Given a tensor `input`, this operation inserts a dimension of 1 at the +/// dimension index `axis` of `input`'s shape. The dimension index `axis` starts at +/// zero; if you specify a negative number for `axis` it is counted backward from +/// the end. +/// +/// This operation is useful if you want to add a batch dimension to a single +/// element. For example, if you have a single image of shape `[height, width, +/// channels]`, you can make it a batch of 1 image with `expand_dims(image, 0)`, +/// which will make the shape `[1, height, width, channels]`. +/// +/// Other examples: +/// +/// ``` +/// # 't' is a tensor of shape [2] +/// shape(expand_dims(t, 0)) ==> [1, 2] +/// shape(expand_dims(t, 1)) ==> [2, 1] +/// shape(expand_dims(t, -1)) ==> [2, 1] +/// +/// # 't2' is a tensor of shape [2, 3, 5] +/// shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5] +/// shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5] +/// shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1] +/// ``` +/// +/// This operation requires that: +/// +/// `-1-input.dims() <= dim <= input.dims()` +/// +/// This operation is related to `squeeze()`, which removes dimensions of +/// size 1. +/// +/// - Parameter dim: 0-D (scalar). Specifies the dimension index at which to +/// expand the shape of `input`. Must be in the range +/// `[-rank(input) - 1, rank(input)]`. +/// +/// - Output output: Contains the same data as `input`, but its shape has an additional +/// dimension of size 1 added. +@inlinable @inline(__always) +public static func expandDims< + T: TensorFlowScalar, + Tdim: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + dim: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ExpandDims", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tdim", Tdim.tensorFlowDataType) + op.addInput(input) + op.addInput(dim) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func experimentalAssertNextDataset( + inputDataset: VariantHandle, + transformations: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalAssertNextDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(transformations) + return op.execute(Int(1)) +} + +/// Creates a dataset that shards the input dataset. +/// +/// Creates a dataset that shards the input dataset by num_workers, returning a +/// sharded dataset for the index-th worker. This attempts to automatically shard +/// a dataset by examining the Dataset graph and inserting a shard op before the +/// inputs to a reader Dataset (e.g. CSVDataset, TFRecordDataset). +/// +/// This dataset will throw a NotFound error if we cannot shard the dataset +/// automatically. +/// +/// - Parameters: +/// - input_dataset: A variant tensor representing the input dataset. +/// - num_workers: A scalar representing the number of workers to distribute this dataset across. +/// - index: A scalar representing the index of the current worker out of num_workers. +@inlinable @inline(__always) +public static func experimentalAutoShardDataset( + inputDataset: VariantHandle, + numWorkers: Tensor, + index: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalAutoShardDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(numWorkers) + op.addInput(index) + return op.execute(Int(1)) +} + +/// Records the bytes size of each element of `input_dataset` in a StatsAggregator. +@inlinable @inline(__always) +public static func experimentalBytesProducedStatsDataset( + inputDataset: VariantHandle, + tag: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalBytesProducedStatsDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(tag) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func experimentalCSVDataset( + filenames: StringTensor, + compressionType: StringTensor, + bufferSize: Tensor, + header: Tensor, + fieldDelim: StringTensor, + useQuoteDelim: Tensor, + naValue: StringTensor, + selectCols: Tensor, + recordDefaults: OutputTypes, + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalCSVDataset", nOutputs) + op.updateAttribute("output_types", recordDefaults._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(filenames) + op.addInput(compressionType) + op.addInput(bufferSize) + op.addInput(header) + op.addInput(fieldDelim) + op.addInput(useQuoteDelim) + op.addInput(naValue) + op.addInput(selectCols) + op.addInputList(recordDefaults) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func experimentalChooseFastestDataset( + inputDatasets: [VariantHandle], + numExperiments: Int64, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalChooseFastestDataset", nOutputs) + op.updateAttribute("N", inputDatasets.count) + op.updateAttribute("num_experiments", numExperiments) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInputList(inputDatasets) + return op.execute(Int(1)) +} + +/// Returns the cardinality of `input_dataset`. +/// +/// Returns the cardinality of `input_dataset`. +/// +/// - Parameter input_dataset: A variant tensor representing the dataset to return cardinality for. +/// +/// - Output cardinality: The cardinality of `input_dataset`. Named constants are used to represent +/// infinite and unknown cardinality. +@inlinable @inline(__always) +public static func experimentalDatasetCardinality( + inputDataset: VariantHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ExperimentalDatasetCardinality", nOutputs) + op.addInput(inputDataset) + return op.execute(Int(1)) +} + +/// Writes the given dataset to the given file using the TFRecord format. +/// +/// - Parameters: +/// - input_dataset: A variant tensor representing the dataset to write. +/// - filename: A scalar string tensor representing the filename to use. +/// - compression_type: A scalar string tensor containing either (i) the empty string (no +/// compression), (ii) "ZLIB", or (iii) "GZIP". +@inlinable @inline(__always) +public static func experimentalDatasetToTFRecord( + inputDataset: VariantHandle, + filename: StringTensor, + compressionType: StringTensor +) { + let nOutputs = 0 + let op = makeOp("ExperimentalDatasetToTFRecord", nOutputs) + op.addInput(inputDataset) + op.addInput(filename) + op.addInput(compressionType) + op.execute() +} + +/// Creates a dataset that batches input elements into a SparseTensor. +/// +/// - Parameters: +/// - input_dataset: A handle to an input dataset. Must have a single component. +/// - batch_size: A scalar representing the number of elements to accumulate in a +/// batch. +/// - row_shape: A vector representing the dense shape of each row in the produced +/// SparseTensor. The shape may be partially specified, using `-1` to indicate +/// that a particular dimension should use the maximum size of all batch elements. +@inlinable @inline(__always) +public static func experimentalDenseToSparseBatchDataset( + inputDataset: VariantHandle, + batchSize: Tensor, + rowShape: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalDenseToSparseBatchDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(batchSize) + op.addInput(rowShape) + return op.execute(Int(1)) +} + +/// A substitute for `InterleaveDataset` on a fixed list of `N` datasets. +/// +/// - Parameters: +/// - selector_input_dataset: A dataset of scalar `DT_INT64` elements that determines which of the +/// `N` data inputs should produce the next output element. +/// - data_input_datasets: `N` datasets with the same type that will be interleaved according to +/// the values of `selector_input_dataset`. +@inlinable @inline(__always) +public static func experimentalDirectedInterleaveDataset( + selectorInputDataset: VariantHandle, + dataInputDatasets: [VariantHandle], + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalDirectedInterleaveDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("N", dataInputDatasets.count) + op.addInput(selectorInputDataset) + op.addInputList(dataInputDatasets) + return op.execute(Int(1)) +} + +/// Creates a dataset that computes a group-by on `input_dataset`. +/// +/// Creates a dataset that computes a group-by on `input_dataset`. +/// +/// - Parameters: +/// - input_dataset: A variant tensor representing the input dataset. +/// - key_func_other_arguments: A list of tensors, typically values that were captured when +/// building a closure for `key_func`. +/// - init_func_other_arguments: A list of tensors, typically values that were captured when +/// building a closure for `init_func`. +/// - reduce_func_other_arguments: A list of tensors, typically values that were captured when +/// building a closure for `reduce_func`. +/// - finalize_func_other_arguments: A list of tensors, typically values that were captured when +/// building a closure for `finalize_func`. +/// +/// - Attrs: +/// - key_func: A function mapping an element of `input_dataset`, concatenated +/// with `key_func_other_arguments` to a scalar value of type DT_INT64. +/// - init_func: A function mapping a key of type DT_INT64, concatenated with +/// `init_func_other_arguments` to the initial reducer state. +/// - reduce_func: A function mapping the current reducer state and an element of `input_dataset`, +/// concatenated with `reduce_func_other_arguments` to a new reducer state. +/// - finalize_func: A function mapping the final reducer state to an output element. +@inlinable @inline(__always) +public static func experimentalGroupByReducerDataset< + KeyfuncIn: TensorGroup, + KeyfuncOut: TensorGroup, + InitfuncIn: TensorGroup, + InitfuncOut: TensorGroup, + ReducefuncIn: TensorGroup, + ReducefuncOut: TensorGroup, + FinalizefuncIn: TensorGroup, + FinalizefuncOut: TensorGroup, + TkeyFuncOtherArguments: TensorArrayProtocol, + TinitFuncOtherArguments: TensorArrayProtocol, + TreduceFuncOtherArguments: TensorArrayProtocol, + TfinalizeFuncOtherArguments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + keyFuncOtherArguments: TkeyFuncOtherArguments, + initFuncOtherArguments: TinitFuncOtherArguments, + reduceFuncOtherArguments: TreduceFuncOtherArguments, + finalizeFuncOtherArguments: TfinalizeFuncOtherArguments, + keyFunc: (KeyfuncIn) -> KeyfuncOut, + initFunc: (InitfuncIn) -> InitfuncOut, + reduceFunc: (ReducefuncIn) -> ReducefuncOut, + finalizeFunc: (FinalizefuncIn) -> FinalizefuncOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalGroupByReducerDataset", nOutputs) + op.updateAttribute("key_func", keyFunc) + op.updateAttribute("init_func", initFunc) + op.updateAttribute("reduce_func", reduceFunc) + op.updateAttribute("finalize_func", finalizeFunc) + op.updateAttribute("Tkey_func_other_arguments", keyFuncOtherArguments._typeList) + op.updateAttribute("Tinit_func_other_arguments", initFuncOtherArguments._typeList) + op.updateAttribute("Treduce_func_other_arguments", reduceFuncOtherArguments._typeList) + op.updateAttribute("Tfinalize_func_other_arguments", finalizeFuncOtherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(keyFuncOtherArguments) + op.addInputList(initFuncOtherArguments) + op.addInputList(reduceFuncOtherArguments) + op.addInputList(finalizeFuncOtherArguments) + return op.execute(Int(1)) +} + +/// Creates a dataset that computes a windowed group-by on `input_dataset`. +/// +/// // TODO(mrry): Support non-int64 keys. +/// +/// - Attr key_func: A function mapping an element of `input_dataset`, concatenated +/// with `key_func_other_arguments` to a scalar value of type DT_INT64. +@inlinable @inline(__always) +public static func experimentalGroupByWindowDataset< + KeyfuncIn: TensorGroup, + KeyfuncOut: TensorGroup, + ReducefuncIn: TensorGroup, + ReducefuncOut: TensorGroup, + WindowsizefuncIn: TensorGroup, + WindowsizefuncOut: TensorGroup, + TkeyFuncOtherArguments: TensorArrayProtocol, + TreduceFuncOtherArguments: TensorArrayProtocol, + TwindowSizeFuncOtherArguments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + keyFuncOtherArguments: TkeyFuncOtherArguments, + reduceFuncOtherArguments: TreduceFuncOtherArguments, + windowSizeFuncOtherArguments: TwindowSizeFuncOtherArguments, + keyFunc: (KeyfuncIn) -> KeyfuncOut, + reduceFunc: (ReducefuncIn) -> ReducefuncOut, + windowSizeFunc: (WindowsizefuncIn) -> WindowsizefuncOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalGroupByWindowDataset", nOutputs) + op.updateAttribute("key_func", keyFunc) + op.updateAttribute("reduce_func", reduceFunc) + op.updateAttribute("window_size_func", windowSizeFunc) + op.updateAttribute("Tkey_func_other_arguments", keyFuncOtherArguments._typeList) + op.updateAttribute("Treduce_func_other_arguments", reduceFuncOtherArguments._typeList) + op.updateAttribute("Twindow_size_func_other_arguments", windowSizeFuncOtherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(keyFuncOtherArguments) + op.addInputList(reduceFuncOtherArguments) + op.addInputList(windowSizeFuncOtherArguments) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func experimentalIdentityIndexedDataset( + size: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalIdentityIndexedDataset", nOutputs) + op.addInput(size) + return op.execute(Int(1)) +} + +/// Creates a dataset that contains the elements of `input_dataset` ignoring errors. +@inlinable @inline(__always) +public static func experimentalIgnoreErrorsDataset( + inputDataset: VariantHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalIgnoreErrorsDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func experimentalIndexedDatasetGet( + materialized: ResourceHandle, + index: Tensor, + outputShapes: [TensorShape?] +) -> OutputTypes { + let nOutputs = Int(OutputTypes._typeList.count) + let op = makeOp("ExperimentalIndexedDatasetGet", nOutputs) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(materialized) + op.addInput(index) + return op.execute(Int(OutputTypes._typeList.count)) +} + +@inlinable @inline(__always) +public static func experimentalIndexedDatasetMaterialize( + dataset: VariantHandle, + materialized: ResourceHandle +) { + let nOutputs = 0 + let op = makeOp("ExperimentalIndexedDatasetMaterialize", nOutputs) + op.addInput(dataset) + op.addInput(materialized) + op.execute() +} + +/// Returns the name of the device on which `resource` has been placed. +@inlinable @inline(__always) +public static func experimentalIteratorGetDevice( + resource: ResourceHandle +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("ExperimentalIteratorGetDevice", nOutputs) + op.addInput(resource) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func experimentalLMDBDataset( + filenames: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalLMDBDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(filenames) + return op.execute(Int(1)) +} + +/// Records the latency of producing `input_dataset` elements in a StatsAggregator. +@inlinable @inline(__always) +public static func experimentalLatencyStatsDataset( + inputDataset: VariantHandle, + tag: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalLatencyStatsDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(tag) + return op.execute(Int(1)) +} + +/// Creates a dataset that fuses mapping with batching. +/// +/// Creates a dataset that applies `f` to the outputs of `input_dataset` and then +/// batches `batch_size` of them. +/// +/// Unlike a "MapDataset", which applies `f` sequentially, this dataset invokes up +/// to `batch_size * num_parallel_batches` copies of `f` in parallel. +/// +/// - Parameters: +/// - input_dataset: A variant tensor representing the input dataset. +/// - other_arguments: A list of tensors, typically values that were captured when building a closure +/// for `f`. +/// - batch_size: A scalar representing the number of elements to accumulate in a +/// batch. It determines the number of concurrent invocations of `f` that process +/// elements from `input_dataset` in parallel. +/// - num_parallel_calls: A scalar representing the maximum number of parallel invocations of the `map_fn` +/// function. Applying the `map_fn` on consecutive input elements in parallel has +/// the potential to improve input pipeline throughput. +/// - drop_remainder: A scalar representing whether the last batch should be dropped in case its size +/// is smaller than desired. +/// +/// - Attr f: A function to apply to the outputs of `input_dataset`. +@inlinable @inline(__always) +public static func experimentalMapAndBatchDataset< + FIn: TensorGroup, + FOut: TensorGroup, + Targuments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + otherArguments: Targuments, + batchSize: Tensor, + numParallelCalls: Tensor, + dropRemainder: Tensor, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + preserveCardinality: Bool = false +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalMapAndBatchDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("preserve_cardinality", preserveCardinality) + op.addInput(inputDataset) + op.addInputList(otherArguments) + op.addInput(batchSize) + op.addInput(numParallelCalls) + op.addInput(dropRemainder) + return op.execute(Int(1)) +} + +/// Creates a dataset that applies `f` to the outputs of `input_dataset`. +@inlinable @inline(__always) +public static func experimentalMapDataset< + FIn: TensorGroup, + FOut: TensorGroup, + Targuments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + otherArguments: Targuments, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + useInterOpParallelism: Bool = true, + preserveCardinality: Bool = false +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalMapDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("use_inter_op_parallelism", useInterOpParallelism) + op.updateAttribute("preserve_cardinality", preserveCardinality) + op.addInput(inputDataset) + op.addInputList(otherArguments) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func experimentalMatchingFilesDataset( + patterns: StringTensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalMatchingFilesDataset", nOutputs) + op.addInput(patterns) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func experimentalMaterializedIndexDatasetHandle( + container: String, + sharedName: String, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalMaterializedIndexDatasetHandle", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + return op.execute(Int(1)) +} + +/// Creates a dataset that overrides the maximum intra-op parallelism. +/// +/// - Parameter max_intra_op_parallelism: Identifies the maximum intra-op parallelism to use. +@inlinable @inline(__always) +public static func experimentalMaxIntraOpParallelismDataset( + inputDataset: VariantHandle, + maxIntraOpParallelism: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalMaxIntraOpParallelismDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(maxIntraOpParallelism) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func experimentalNonSerializableDataset( + inputDataset: VariantHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalNonSerializableDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + return op.execute(Int(1)) +} + +/// Creates a dataset that fuses mapping with batching. +/// +/// Creates a dataset that applies `f` to the outputs of `input_dataset` and then +/// batches `batch_size` of them. +/// +/// Unlike a "MapDataset", which applies `f` sequentially, this dataset invokes up +/// to `batch_size * num_parallel_batches` copies of `f` in parallel. +/// +/// Unlike "MapAndBatchDatasetV2", this dataset uses a NUMA-aware thread scheduling +/// policy. Because it uses the single-threaded executor, it only supports the +/// function-based control flow ops. +/// +/// - Parameters: +/// - input_dataset: A variant tensor representing the input dataset. +/// - other_arguments: A list of tensors, typically values that were captured when building a closure +/// for `f`. +/// - batch_size: A scalar representing the number of elements to accumulate in a +/// batch. It determines the number of concurrent invocations of `f` that process +/// elements from `input_dataset` in parallel. +/// - num_parallel_calls: A scalar representing the maximum number of parallel invocations of the `map_fn` +/// function. Applying the `map_fn` on consecutive input elements in parallel has +/// the potential to improve input pipeline throughput. +/// - drop_remainder: A scalar representing whether the last batch should be dropped in case its size +/// is smaller than desired. +/// +/// - Attr f: A function to apply to the outputs of `input_dataset`. +@inlinable @inline(__always) +public static func experimentalNumaMapAndBatchDataset< + FIn: TensorGroup, + FOut: TensorGroup, + Targuments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + otherArguments: Targuments, + batchSize: Tensor, + numParallelCalls: Tensor, + dropRemainder: Tensor, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + preserveCardinality: Bool = false +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalNumaMapAndBatchDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("preserve_cardinality", preserveCardinality) + op.addInput(inputDataset) + op.addInputList(otherArguments) + op.addInput(batchSize) + op.addInput(numParallelCalls) + op.addInput(dropRemainder) + return op.execute(Int(1)) +} + +/// Creates a dataset that applies `f` to the outputs of `input_dataset`. +/// +/// The resulting dataset is similar to the `InterleaveDataset`, with the exception +/// that if retrieving the next value from a dataset would cause the requester to +/// block, it will skip that input dataset. This dataset is especially useful +/// when loading data from a variable-latency datastores (e.g. HDFS, GCS), as it +/// allows the training step to proceed so long as some data is available. +/// +/// !! WARNING !! This dataset is not deterministic! +/// +/// - Attr f: A function mapping elements of `input_dataset`, concatenated with +/// `other_arguments`, to a Dataset variant that contains elements matching +/// `output_types` and `output_shapes`. +@inlinable @inline(__always) +public static func experimentalParallelInterleaveDataset< + FIn: TensorGroup, + FOut: TensorGroup, + Targuments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + otherArguments: Targuments, + cycleLength: Tensor, + blockLength: Tensor, + sloppy: Tensor, + bufferOutputElements: Tensor, + prefetchInputElements: Tensor, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalParallelInterleaveDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(otherArguments) + op.addInput(cycleLength) + op.addInput(blockLength) + op.addInput(sloppy) + op.addInput(bufferOutputElements) + op.addInput(prefetchInputElements) + return op.execute(Int(1)) +} + +/// Transforms `input_dataset` containing `Example` protos as vectors of DT_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features. +/// +/// - Parameter dense_defaults: A dict mapping string keys to `Tensor`s. +/// The keys of the dict must match the dense_keys of the feature. +/// +/// - Attrs: +/// - sparse_keys: A list of string keys in the examples features. +/// The results for these keys will be returned as `SparseTensor` objects. +/// - dense_keys: A list of Ndense string Tensors (scalars). +/// The keys expected in the Examples features associated with dense values. +/// - sparse_types: A list of `DTypes` of the same length as `sparse_keys`. +/// Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`), +/// and `tf.string` (`BytesList`) are supported. +/// - Tdense: A list of DTypes of the same length as `dense_keys`. +/// Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`), +/// and `tf.string` (`BytesList`) are supported. +/// +/// - dense_shapes: List of tuples with the same length as `dense_keys`. +/// The shape of the data for each dense feature referenced by `dense_keys`. +/// Required for any input tensors identified by `dense_keys`. Must be +/// either fully defined, or may contain an unknown first dimension. +/// An unknown first dimension means the feature is treated as having +/// a variable number of blocks, and the output shape along this dimension +/// is considered unknown at graph build time. Padding is applied for +/// minibatch elements smaller than the maximum number of blocks for the +/// given feature along this dimension. +/// - output_types: The type list for the return values. +/// - output_shapes: The list of shapes being produced. +@inlinable @inline(__always) +public static func experimentalParseExampleDataset( + inputDataset: VariantHandle, + numParallelCalls: Tensor, + denseDefaults: Tdense, + sparseKeys: [String], + denseKeys: [String], + sparseTypes: [TensorDataType], + denseShapes: [TensorShape?], + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + sloppy: Bool = false +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalParseExampleDataset", nOutputs) + op.updateAttribute("sparse_keys", sparseKeys) + op.updateAttribute("dense_keys", denseKeys) + op.updateAttribute("sparse_types", sparseTypes) + op.updateAttribute("Tdense", denseDefaults._typeList) + op.updateAttribute("dense_shapes", denseShapes) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("sloppy", sloppy) + op.addInput(inputDataset) + op.addInput(numParallelCalls) + op.addInputList(denseDefaults) + return op.execute(Int(1)) +} + +/// Creates a dataset that uses a custom thread pool to compute `input_dataset`. +/// +/// - Parameter num_threads: Identifies the number of threads to use for the private threadpool. +@inlinable @inline(__always) +public static func experimentalPrivateThreadPoolDataset( + inputDataset: VariantHandle, + numThreads: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalPrivateThreadPoolDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(numThreads) + return op.execute(Int(1)) +} + +/// Creates a Dataset that returns pseudorandom numbers. +/// +/// - Parameters: +/// - seed: A scalar seed for the random number generator. If either seed or +/// seed2 is set to be non-zero, the random number generator is seeded +/// by the given seed. Otherwise, a random seed is used. +/// - seed2: A second scalar seed to avoid seed collision. +@inlinable @inline(__always) +public static func experimentalRandomDataset( + seed: Tensor, + seed2: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalRandomDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(seed) + op.addInput(seed2) + return op.execute(Int(1)) +} + +/// Creates a dataset that changes the batch size. +/// +/// Creates a dataset that changes the batch size of the dataset to current batch +/// size // num_workers. +/// +/// - Parameters: +/// - input_dataset: A variant tensor representing the input dataset. +/// - num_workers: A scalar representing the number of workers to distribute this batch across. As +/// a result of this transformation the current batch size would end up being +/// divided by this parameter. +@inlinable @inline(__always) +public static func experimentalRebatchDataset( + inputDataset: VariantHandle, + numWorkers: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalRebatchDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(numWorkers) + return op.execute(Int(1)) +} + +/// Creates a dataset successively reduces `f` over the elements of `input_dataset`. +@inlinable @inline(__always) +public static func experimentalScanDataset< + FIn: TensorGroup, + FOut: TensorGroup, + Tstate: TensorArrayProtocol, + Targuments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + initialState: Tstate, + otherArguments: Targuments, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + preserveCardinality: Bool = false +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalScanDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Tstate", initialState._typeList) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("preserve_cardinality", preserveCardinality) + op.addInput(inputDataset) + op.addInputList(initialState) + op.addInputList(otherArguments) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func experimentalSetStatsAggregatorDataset( + inputDataset: VariantHandle, + statsAggregator: ResourceHandle, + tag: StringTensor, + counterPrefix: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalSetStatsAggregatorDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(statsAggregator) + op.addInput(tag) + op.addInput(counterPrefix) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func experimentalSleepDataset( + inputDataset: VariantHandle, + sleepMicroseconds: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalSleepDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(sleepMicroseconds) + return op.execute(Int(1)) +} + +/// Creates a dataset that passes a sliding window over `input_dataset`. +/// +/// - Parameters: +/// - window_size: A scalar representing the number of elements in the +/// sliding window. +/// - window_shift: A scalar representing the steps moving the sliding window +/// forward in one iteration. It must be positive. +/// - window_stride: A scalar representing the stride of the input elements of the sliding window. +/// It must be positive. +@inlinable @inline(__always) +public static func experimentalSlidingWindowDataset( + inputDataset: VariantHandle, + windowSize: Tensor, + windowShift: Tensor, + windowStride: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalSlidingWindowDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(windowSize) + op.addInput(windowShift) + op.addInput(windowStride) + return op.execute(Int(1)) +} + +/// Creates a dataset that executes a SQL query and emits rows of the result set. +/// +/// - Parameters: +/// - driver_name: The database type. Currently, the only supported type is 'sqlite'. +/// - data_source_name: A connection string to connect to the database. +/// - query: A SQL query to execute. +@inlinable @inline(__always) +public static func experimentalSqlDataset( + driverName: StringTensor, + dataSourceName: StringTensor, + query: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalSqlDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(driverName) + op.addInput(dataSourceName) + op.addInput(query) + return op.execute(Int(1)) +} + +/// Creates a statistics manager resource. +@inlinable @inline(__always) +public static func experimentalStatsAggregatorHandle( + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalStatsAggregatorHandle", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Produces a summary of any statistics recorded by the given statistics manager. +@inlinable @inline(__always) +public static func experimentalStatsAggregatorSummary( + iterator: ResourceHandle +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("ExperimentalStatsAggregatorSummary", nOutputs) + op.addInput(iterator) + return op.execute(Int(1)) +} + +/// Creates a dataset that stops iteration when predicate` is false. +/// +/// The `predicate` function must return a scalar boolean and accept the +/// following arguments: +/// +/// * One tensor for each component of an element of `input_dataset`. +/// * One tensor for each value in `other_arguments`. +/// +/// - Parameter other_arguments: A list of tensors, typically values that were captured when +/// building a closure for `predicate`. +/// +/// - Attr predicate: A function returning a scalar boolean. +@inlinable @inline(__always) +public static func experimentalTakeWhileDataset< + PredicateIn: TensorGroup, + PredicateOut: TensorGroup, + Targuments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + otherArguments: Targuments, + predicate: (PredicateIn) -> PredicateOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalTakeWhileDataset", nOutputs) + op.updateAttribute("predicate", predicate) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(otherArguments) + return op.execute(Int(1)) +} + +/// Creates a dataset that uses a custom thread pool to compute `input_dataset`. +/// +/// - Parameter thread_pool: A resource produced by the ThreadPoolHandle op. +@inlinable @inline(__always) +public static func experimentalThreadPoolDataset( + inputDataset: VariantHandle, + threadPool: ResourceHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalThreadPoolDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(threadPool) + return op.execute(Int(1)) +} + +/// Creates a dataset that uses a custom thread pool to compute `input_dataset`. +/// +/// - Attrs: +/// - num_threads: The number of threads in the thread pool. +/// - max_intra_op_parallelism: The maximum degree of parallelism to use within operations that execute on this +/// threadpool. +/// - display_name: A human-readable name for the threads that may be visible in some +/// visualizations. +/// threadpool. +/// +/// - Output handle: A resource that can be consumed by one or more ExperimentalThreadPoolDataset +/// ops. +@inlinable @inline(__always) +public static func experimentalThreadPoolHandle( + numThreads: Int64, + maxIntraOpParallelism: Int64 = 1, + displayName: String, + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalThreadPoolHandle", nOutputs) + op.updateAttribute("num_threads", numThreads) + op.updateAttribute("max_intra_op_parallelism", maxIntraOpParallelism) + op.updateAttribute("display_name", displayName) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// A dataset that splits the elements of its input into multiple elements. +@inlinable @inline(__always) +public static func experimentalUnbatchDataset( + inputDataset: VariantHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalUnbatchDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + return op.execute(Int(1)) +} + +/// Creates a dataset that contains the unique elements of `input_dataset`. +@inlinable @inline(__always) +public static func experimentalUniqueDataset( + inputDataset: VariantHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ExperimentalUniqueDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + return op.execute(Int(1)) +} + +/// Computes exponential of x - 1 element-wise. +/// +/// I.e., \\(y = (\exp x) - 1\\). +@inlinable @inline(__always) +public static func expm1( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Expm1", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Extracts a glimpse from the input tensor. +/// +/// Returns a set of windows called glimpses extracted at location +/// `offsets` from the input tensor. If the windows only partially +/// overlaps the inputs, the non overlapping areas will be filled with +/// random noise. +/// +/// The result is a 4-D tensor of shape `[batch_size, glimpse_height, +/// glimpse_width, channels]`. The channels and batch dimensions are the +/// same as that of the input tensor. The height and width of the output +/// windows are specified in the `size` parameter. +/// +/// The argument `normalized` and `centered` controls how the windows are built: +/// +/// * If the coordinates are normalized but not centered, 0.0 and 1.0 +/// correspond to the minimum and maximum of each height and width +/// dimension. +/// * If the coordinates are both normalized and centered, they range from +/// -1.0 to 1.0. The coordinates (-1.0, -1.0) correspond to the upper +/// left corner, the lower right corner is located at (1.0, 1.0) and the +/// center is at (0, 0). +/// * If the coordinates are not normalized they are interpreted as +/// numbers of pixels. +/// +/// - Parameters: +/// - input: A 4-D float tensor of shape `[batch_size, height, width, channels]`. +/// - size: A 1-D tensor of 2 elements containing the size of the glimpses +/// to extract. The glimpse height must be specified first, following +/// by the glimpse width. +/// - offsets: A 2-D integer tensor of shape `[batch_size, 2]` containing +/// the y, x locations of the center of each window. +/// +/// - Attrs: +/// - centered: indicates if the offset coordinates are centered relative to +/// the image, in which case the (0, 0) offset is relative to the center +/// of the input images. If false, the (0,0) offset corresponds to the +/// upper left corner of the input images. +/// - normalized: indicates if the offset coordinates are normalized. +/// - uniform_noise: indicates if the noise should be generated using a +/// uniform distribution or a Gaussian distribution. +/// - noise: indicates if the noise should `uniform`, `gaussian`, or +/// `zero`. The default is `uniform` which means the the noise type +/// will be decided by `uniform_noise`. +/// +/// - Output glimpse: A tensor representing the glimpses `[batch_size, +/// glimpse_height, glimpse_width, channels]`. +@inlinable @inline(__always) +public static func extractGlimpse( + _ input: Tensor, + size: Tensor, + offsets: Tensor, + centered: Bool = true, + normalized: Bool = true, + uniformNoise: Bool = true, + noise: String = "uniform" +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ExtractGlimpse", nOutputs) + op.updateAttribute("centered", centered) + op.updateAttribute("normalized", normalized) + op.updateAttribute("uniform_noise", uniformNoise) + op.updateAttribute("noise", noise) + op.addInput(input) + op.addInput(size) + op.addInput(offsets) + return op.execute(Int(1)) +} + +/// Extract `patches` from `images` and put them in the "depth" output dimension. +/// +/// - Parameter images: 4-D Tensor with shape `[batch, in_rows, in_cols, depth]`. +/// +/// - Attrs: +/// - ksizes: The size of the sliding window for each dimension of `images`. +/// - strides: 1-D of length 4. How far the centers of two consecutive patches are in +/// the images. Must be: `[1, stride_rows, stride_cols, 1]`. +/// - rates: 1-D of length 4. Must be: `[1, rate_rows, rate_cols, 1]`. This is the +/// input stride, specifying how far two consecutive patch samples are in the +/// input. Equivalent to extracting patches with +/// `patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1)`, followed by +/// subsampling them spatially by a factor of `rates`. This is equivalent to +/// `rate` in dilated (a.k.a. Atrous) convolutions. +/// - padding: The type of padding algorithm to use. +/// +/// We specify the size-related attributes as: +/// +/// ```python +/// ksizes = [1, ksize_rows, ksize_cols, 1] +/// strides = [1, strides_rows, strides_cols, 1] +/// rates = [1, rates_rows, rates_cols, 1] +/// ``` +/// +/// - Output patches: 4-D Tensor with shape `[batch, out_rows, out_cols, ksize_rows * +/// ksize_cols * depth]` containing image patches with size +/// `ksize_rows x ksize_cols x depth` vectorized in the "depth" dimension. Note +/// `out_rows` and `out_cols` are the dimensions of the output patches. +@inlinable @inline(__always) +public static func extractImagePatches( + images: Tensor, + ksizes: [Int32], + strides: [Int32], + rates: [Int32], + padding: Padding +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ExtractImagePatches", nOutputs) + op.updateAttribute("ksizes", ksizes) + op.updateAttribute("strides", strides) + op.updateAttribute("rates", rates) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("padding", padding.cName) + op.addInput(images) + return op.execute(Int(1)) +} + +/// Extract the shape information of a JPEG-encoded image. +/// +/// This op only parses the image header, so it is much faster than DecodeJpeg. +/// +/// - Parameter contents: 0-D. The JPEG-encoded image. +/// +/// - Attr output_type: (Optional) The output type of the operation (int32 or int64). +/// Defaults to int32. +/// +/// - Output image_shape: 1-D. The image shape with format [height, width, channels]. +@inlinable @inline(__always) +public static func extractJpegShape( + contents: StringTensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ExtractJpegShape", nOutputs) + op.updateAttribute("output_type", OutputType.tensorFlowDataType) + op.addInput(contents) + return op.execute(Int(1)) +} + +/// Extract `patches` from `input` and put them in the "depth" output dimension. 3D extension of `extract_image_patches`. +/// +/// - Parameter input: 5-D Tensor with shape `[batch, in_planes, in_rows, in_cols, depth]`. +/// +/// - Attrs: +/// - ksizes: The size of the sliding window for each dimension of `input`. +/// - strides: 1-D of length 5. How far the centers of two consecutive patches are in +/// `input`. Must be: `[1, stride_planes, stride_rows, stride_cols, 1]`. +/// - padding: The type of padding algorithm to use. +/// +/// We specify the size-related attributes as: +/// +/// ```python +/// ksizes = [1, ksize_planes, ksize_rows, ksize_cols, 1] +/// strides = [1, stride_planes, strides_rows, strides_cols, 1] +/// ``` +/// +/// - Output patches: 5-D Tensor with shape `[batch, out_planes, out_rows, out_cols, +/// ksize_planes * ksize_rows * ksize_cols * depth]` containing patches +/// with size `ksize_planes x ksize_rows x ksize_cols x depth` vectorized +/// in the "depth" dimension. Note `out_planes`, `out_rows` and `out_cols` +/// are the dimensions of the output patches. +@inlinable @inline(__always) +public static func extractVolumePatches( + _ input: Tensor, + ksizes: [Int32], + strides: [Int32], + padding: Padding +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ExtractVolumePatches", nOutputs) + op.updateAttribute("ksizes", ksizes) + op.updateAttribute("strides", strides) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Fast Fourier transform. +/// +/// Computes the 1-dimensional discrete Fourier transform over the inner-most +/// dimension of `input`. +/// +/// - Parameter input: A complex tensor. +/// +/// - Output output: A complex tensor of the same shape as `input`. The inner-most +/// dimension of `input` is replaced with its 1D Fourier transform. +/// +/// @compatibility(numpy) +/// Equivalent to np.fft.fft +/// @end_compatibility +@inlinable @inline(__always) +public static func fFT( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FFT", nOutputs) + op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// 2D fast Fourier transform. +/// +/// Computes the 2-dimensional discrete Fourier transform over the inner-most +/// 2 dimensions of `input`. +/// +/// - Parameter input: A complex tensor. +/// +/// - Output output: A complex tensor of the same shape as `input`. The inner-most 2 +/// dimensions of `input` are replaced with their 2D Fourier transform. +/// +/// @compatibility(numpy) +/// Equivalent to np.fft.fft2 +/// @end_compatibility +@inlinable @inline(__always) +public static func fFT2D( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FFT2D", nOutputs) + op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// 3D fast Fourier transform. +/// +/// Computes the 3-dimensional discrete Fourier transform over the inner-most 3 +/// dimensions of `input`. +/// +/// - Parameter input: A complex64 tensor. +/// +/// - Output output: A complex64 tensor of the same shape as `input`. The inner-most 3 +/// dimensions of `input` are replaced with their 3D Fourier transform. +/// +/// @compatibility(numpy) +/// Equivalent to np.fft.fftn with 3 dimensions. +/// @end_compatibility +@inlinable @inline(__always) +public static func fFT3D( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FFT3D", nOutputs) + op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// A queue that produces elements in first-in first-out order. +/// +/// - Attrs: +/// - component_types: The type of each component in a value. +/// - shapes: The shape of each component in a value. The length of this attr must +/// be either 0 or the same as the length of component_types. If the length of +/// this attr is 0, the shapes of queue elements are not constrained, and +/// only one element may be dequeued at a time. +/// - capacity: The upper bound on the number of elements in this queue. +/// Negative numbers mean no limit. +/// - container: If non-empty, this queue is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this queue will be shared under the given name +/// across multiple sessions. +/// +/// - Output handle: The handle to the queue. +@inlinable @inline(__always) +public static func fIFOQueueV2( + componentTypes: [TensorDataType], + shapes: [TensorShape?], + capacity: Int64 = -1, + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("FIFOQueueV2", nOutputs) + op.updateAttribute("component_types", componentTypes) + op.updateAttribute("shapes", shapes) + op.updateAttribute("capacity", capacity) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Output a fact about factorials. +@inlinable @inline(__always) +public static func fact( +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("Fact", nOutputs) + + return op.execute(Int(1)) +} + +/// This op is used as a placeholder in If branch functions. It doesn't provide a +/// valid output when run, so must either be removed (e.g. replaced with a +/// function input) or guaranteed not to be used (e.g. if mirroring an +/// intermediate output needed for the gradient computation of the other branch). +/// +/// - Attrs: +/// - dtype: The type of the output. +/// - shape: The purported shape of the output. This is only used for shape inference; +/// the output will not necessarily have this shape. Can be a partial shape. +/// +/// - Output output: \"Fake\" output value. This should not be consumed by another op. +@inlinable @inline(__always) +public static func fakeParam( + shape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FakeParam", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + return op.execute(Int(1)) +} + +/// Fake-quantize the 'inputs' tensor, type float to 'outputs' tensor of same type. +/// +/// Attributes `[min; max]` define the clamping range for the `inputs` data. +/// `inputs` values are quantized into the quantization range (`[0; 2^num_bits - 1]` +/// when `narrow_range` is false and `[1; 2^num_bits - 1]` when it is true) and +/// then de-quantized and output as floats in `[min; max]` interval. +/// `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive. +/// +/// Before quantization, `min` and `max` values are adjusted with the following +/// logic. +/// It is suggested to have `min <= 0 <= max`. If `0` is not in the range of values, +/// the behavior can be unexpected: +/// If `0 < min < max`: `min_adj = 0` and `max_adj = max - min`. +/// If `min < max < 0`: `min_adj = min - max` and `max_adj = 0`. +/// If `min <= 0 <= max`: `scale = (max - min) / (2^num_bits - 1) `, +/// `min_adj = scale * round(min / scale)` and `max_adj = max + min_adj - min`. +/// +/// Quantization is called fake since the output is still in floating point. +@inlinable @inline(__always) +public static func fakeQuantWithMinMaxArgs( + inputs: Tensor, + min: Double = -6, + max: Double = 6, + numBits: Int64 = 8, + narrowRange: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FakeQuantWithMinMaxArgs", nOutputs) + op.updateAttribute("min", min) + op.updateAttribute("max", max) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("narrow_range", narrowRange) + op.addInput(inputs) + return op.execute(Int(1)) +} + +/// Compute gradients for a FakeQuantWithMinMaxArgs operation. +/// +/// - Parameters: +/// - gradients: Backpropagated gradients above the FakeQuantWithMinMaxArgs operation. +/// - inputs: Values passed as inputs to the FakeQuantWithMinMaxArgs operation. +/// +/// - Output backprops: Backpropagated gradients below the FakeQuantWithMinMaxArgs operation: +/// `gradients * (inputs >= min && inputs <= max)`. +@inlinable @inline(__always) +public static func fakeQuantWithMinMaxArgsGradient( + gradients: Tensor, + inputs: Tensor, + min: Double = -6, + max: Double = 6, + numBits: Int64 = 8, + narrowRange: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FakeQuantWithMinMaxArgsGradient", nOutputs) + op.updateAttribute("min", min) + op.updateAttribute("max", max) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("narrow_range", narrowRange) + op.addInput(gradients) + op.addInput(inputs) + return op.execute(Int(1)) +} + +/// Fake-quantize the 'inputs' tensor of type float via global float scalars `min` +/// +/// and `max` to 'outputs' tensor of same shape as `inputs`. +/// +/// `[min; max]` define the clamping range for the `inputs` data. +/// `inputs` values are quantized into the quantization range (`[0; 2^num_bits - 1]` +/// when `narrow_range` is false and `[1; 2^num_bits - 1]` when it is true) and +/// then de-quantized and output as floats in `[min; max]` interval. +/// `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive. +/// +/// Before quantization, `min` and `max` values are adjusted with the following +/// logic. +/// It is suggested to have `min <= 0 <= max`. If `0` is not in the range of values, +/// the behavior can be unexpected: +/// If `0 < min < max`: `min_adj = 0` and `max_adj = max - min`. +/// If `min < max < 0`: `min_adj = min - max` and `max_adj = 0`. +/// If `min <= 0 <= max`: `scale = (max - min) / (2^num_bits - 1) `, +/// `min_adj = scale * round(min / scale)` and `max_adj = max + min_adj - min`. +/// +/// This operation has a gradient and thus allows for training `min` and `max` +/// values. +@inlinable @inline(__always) +public static func fakeQuantWithMinMaxVars( + inputs: Tensor, + min: Tensor, + max: Tensor, + numBits: Int64 = 8, + narrowRange: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FakeQuantWithMinMaxVars", nOutputs) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("narrow_range", narrowRange) + op.addInput(inputs) + op.addInput(min) + op.addInput(max) + return op.execute(Int(1)) +} + +/// Compute gradients for a FakeQuantWithMinMaxVars operation. +/// +/// - Parameters: +/// - gradients: Backpropagated gradients above the FakeQuantWithMinMaxVars operation. +/// - inputs: Values passed as inputs to the FakeQuantWithMinMaxVars operation. +/// min, max: Quantization interval, scalar floats. +/// +/// - Attrs: +/// - num_bits: The bitwidth of the quantization; between 2 and 8, inclusive. +/// - narrow_range: Whether to quantize into 2^num_bits - 1 distinct values. +/// +/// - Outputs: +/// - backprops_wrt_input: Backpropagated gradients w.r.t. inputs: +/// `gradients * (inputs >= min && inputs <= max)`. +/// - backprop_wrt_min: Backpropagated gradients w.r.t. min parameter: +/// `sum(gradients * (inputs < min))`. +/// - backprop_wrt_max: Backpropagated gradients w.r.t. max parameter: +/// `sum(gradients * (inputs > max))`. +@inlinable @inline(__always) +public static func fakeQuantWithMinMaxVarsGradient( + gradients: Tensor, + inputs: Tensor, + min: Tensor, + max: Tensor, + numBits: Int64 = 8, + narrowRange: Bool = false +) -> (backpropsWrtInput: Tensor, backpropWrtMin: Tensor, backpropWrtMax: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("FakeQuantWithMinMaxVarsGradient", nOutputs) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("narrow_range", narrowRange) + op.addInput(gradients) + op.addInput(inputs) + op.addInput(min) + op.addInput(max) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Fake-quantize the 'inputs' tensor of type float and one of the shapes: `[d]`, +/// +/// `[b, d]` `[b, h, w, d]` via per-channel floats `min` and `max` of shape `[d]` +/// to 'outputs' tensor of same shape as `inputs`. +/// +/// `[min; max]` define the clamping range for the `inputs` data. +/// `inputs` values are quantized into the quantization range (`[0; 2^num_bits - 1]` +/// when `narrow_range` is false and `[1; 2^num_bits - 1]` when it is true) and +/// then de-quantized and output as floats in `[min; max]` interval. +/// `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive. +/// +/// Before quantization, `min` and `max` values are adjusted with the following +/// logic. +/// It is suggested to have `min <= 0 <= max`. If `0` is not in the range of values, +/// the behavior can be unexpected: +/// If `0 < min < max`: `min_adj = 0` and `max_adj = max - min`. +/// If `min < max < 0`: `min_adj = min - max` and `max_adj = 0`. +/// If `min <= 0 <= max`: `scale = (max - min) / (2^num_bits - 1) `, +/// `min_adj = scale * round(min / scale)` and `max_adj = max + min_adj - min`. +/// +/// This operation has a gradient and thus allows for training `min` and `max` +/// values. +@inlinable @inline(__always) +public static func fakeQuantWithMinMaxVarsPerChannel( + inputs: Tensor, + min: Tensor, + max: Tensor, + numBits: Int64 = 8, + narrowRange: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FakeQuantWithMinMaxVarsPerChannel", nOutputs) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("narrow_range", narrowRange) + op.addInput(inputs) + op.addInput(min) + op.addInput(max) + return op.execute(Int(1)) +} + +/// Compute gradients for a FakeQuantWithMinMaxVarsPerChannel operation. +/// +/// - Parameters: +/// - gradients: Backpropagated gradients above the FakeQuantWithMinMaxVars operation, +/// shape one of: `[d]`, `[b, d]`, `[b, h, w, d]`. +/// - inputs: Values passed as inputs to the FakeQuantWithMinMaxVars operation, shape +/// same as `gradients`. +/// min, max: Quantization interval, floats of shape `[d]`. +/// +/// - Attrs: +/// - num_bits: The bitwidth of the quantization; between 2 and 16, inclusive. +/// - narrow_range: Whether to quantize into 2^num_bits - 1 distinct values. +/// +/// - Outputs: +/// - backprops_wrt_input: Backpropagated gradients w.r.t. inputs, shape same as +/// `inputs`: +/// `gradients * (inputs >= min && inputs <= max)`. +/// - backprop_wrt_min: Backpropagated gradients w.r.t. min parameter, shape `[d]`: +/// `sum_per_d(gradients * (inputs < min))`. +/// - backprop_wrt_max: Backpropagated gradients w.r.t. max parameter, shape `[d]`: +/// `sum_per_d(gradients * (inputs > max))`. +@inlinable @inline(__always) +public static func fakeQuantWithMinMaxVarsPerChannelGradient( + gradients: Tensor, + inputs: Tensor, + min: Tensor, + max: Tensor, + numBits: Int64 = 8, + narrowRange: Bool = false +) -> (backpropsWrtInput: Tensor, backpropWrtMin: Tensor, backpropWrtMax: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("FakeQuantWithMinMaxVarsPerChannelGradient", nOutputs) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("narrow_range", narrowRange) + op.addInput(gradients) + op.addInput(inputs) + op.addInput(min) + op.addInput(max) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Creates a tensor filled with a scalar value. +/// +/// This operation creates a tensor of shape `dims` and fills it with `value`. +/// +/// For example: +/// +/// ``` +/// # Output tensor has shape [2, 3]. +/// fill([2, 3], 9) ==> [[9, 9, 9] +/// [9, 9, 9]] +/// ``` +/// +/// `tf.fill` differs from `tf.constant` in a few ways: +/// +/// * `tf.fill` only supports scalar contents, whereas `tf.constant` supports +/// Tensor values. +/// * `tf.fill` creates an Op in the computation graph that constructs the actual +/// Tensor value at runtime. This is in contrast to `tf.constant` which embeds +/// the entire Tensor into the graph with a `Const` node. +/// * Because `tf.fill` evaluates at graph runtime, it supports dynamic shapes +/// based on other runtime Tensors, unlike `tf.constant`. +/// +/// - Parameters: +/// - dims: 1-D. Represents the shape of the output tensor. +/// - value: 0-D (scalar). Value to fill the returned tensor. +/// +/// @compatibility(numpy) +/// Equivalent to np.full +/// @end_compatibility +@inlinable @inline(__always) +public static func fill< + T: TensorFlowScalar, + IndexType: BinaryInteger & TensorFlowScalar +>( + dims: Tensor, + value: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Fill", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("index_type", IndexType.tensorFlowDataType) + op.addInput(dims) + op.addInput(value) + return op.execute(Int(1)) +} + +/// Creates a dataset containing elements of first component of `input_dataset` having true in the last component. +@inlinable @inline(__always) +public static func filterByLastComponentDataset( + inputDataset: VariantHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("FilterByLastComponentDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + return op.execute(Int(1)) +} + +/// Creates a dataset containing elements of `input_dataset` matching `predicate`. +/// +/// The `predicate` function must return a scalar boolean and accept the +/// following arguments: +/// +/// * One tensor for each component of an element of `input_dataset`. +/// * One tensor for each value in `other_arguments`. +/// +/// - Parameter other_arguments: A list of tensors, typically values that were captured when +/// building a closure for `predicate`. +/// +/// - Attr predicate: A function returning a scalar boolean. +@inlinable @inline(__always) +public static func filterDataset< + PredicateIn: TensorGroup, + PredicateOut: TensorGroup, + Targuments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + otherArguments: Targuments, + predicate: (PredicateIn) -> PredicateOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("FilterDataset", nOutputs) + op.updateAttribute("predicate", predicate) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(otherArguments) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func fingerprint( + data: Tensor, + method: StringTensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Fingerprint", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(data) + op.addInput(method) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func fiveFloatOutputs( +) -> (a: Tensor, b: Tensor, c: Tensor, d: Tensor, e: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("FiveFloatOutputs", nOutputs) + + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// Creates a dataset that emits the records from one or more binary files. +/// +/// - Parameters: +/// - filenames: A scalar or a vector containing the name(s) of the file(s) to be +/// read. +/// - header_bytes: A scalar representing the number of bytes to skip at the +/// beginning of a file. +/// - record_bytes: A scalar representing the number of bytes in each record. +/// - footer_bytes: A scalar representing the number of bytes to skip at the end +/// of a file. +/// - buffer_size: A scalar representing the number of bytes to buffer. Must be > 0. +@inlinable @inline(__always) +public static func fixedLengthRecordDataset( + filenames: StringTensor, + headerBytes: Tensor, + recordBytes: Tensor, + footerBytes: Tensor, + bufferSize: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("FixedLengthRecordDataset", nOutputs) + op.addInput(filenames) + op.addInput(headerBytes) + op.addInput(recordBytes) + op.addInput(footerBytes) + op.addInput(bufferSize) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func fixedLengthRecordDatasetV2( + filenames: StringTensor, + headerBytes: Tensor, + recordBytes: Tensor, + footerBytes: Tensor, + bufferSize: Tensor, + compressionType: StringTensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("FixedLengthRecordDatasetV2", nOutputs) + op.addInput(filenames) + op.addInput(headerBytes) + op.addInput(recordBytes) + op.addInput(footerBytes) + op.addInput(bufferSize) + op.addInput(compressionType) + return op.execute(Int(1)) +} + +/// A Reader that outputs fixed-length records from a file. +/// +/// - Attrs: +/// - header_bytes: Number of bytes in the header, defaults to 0. +/// - record_bytes: Number of bytes in the record. +/// - footer_bytes: Number of bytes in the footer, defaults to 0. +/// - hop_bytes: Number of bytes to hop before each read. Default of 0 means using +/// record_bytes. +/// - container: If non-empty, this reader is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this reader is named in the given bucket +/// with this shared_name. Otherwise, the node name is used instead. +/// - encoding: The type of encoding for the file. Currently ZLIB and GZIP +/// are supported. Defaults to none. +/// +/// - Output reader_handle: The handle to reference the Reader. +@inlinable @inline(__always) +public static func fixedLengthRecordReaderV2( + headerBytes: Int64 = 0, + recordBytes: Int64, + footerBytes: Int64 = 0, + hopBytes: Int64 = 0, + container: String, + sharedName: String, + encoding: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("FixedLengthRecordReaderV2", nOutputs) + op.updateAttribute("header_bytes", headerBytes) + op.updateAttribute("record_bytes", recordBytes) + op.updateAttribute("footer_bytes", footerBytes) + op.updateAttribute("hop_bytes", hopBytes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("encoding", encoding) + return op.execute(Int(1)) +} + +/// Generates labels for candidate sampling with a learned unigram distribution. +/// +/// A unigram sampler could use a fixed unigram distribution read from a +/// file or passed in as an in-memory array instead of building up the distribution +/// from data on the fly. There is also an option to skew the distribution by +/// applying a distortion power to the weights. +/// +/// The vocabulary file should be in CSV-like format, with the last field +/// being the weight associated with the word. +/// +/// For each batch, this op picks a single set of sampled candidate labels. +/// +/// The advantages of sampling candidates per-batch are simplicity and the +/// possibility of efficient dense matrix multiplication. The disadvantage is that +/// the sampled candidates must be chosen independently of the context and of the +/// true labels. +/// +/// - Parameter true_classes: A batch_size * num_true matrix, in which each row contains the +/// IDs of the num_true target_classes in the corresponding original label. +/// +/// - Attrs: +/// - num_true: Number of true labels per context. +/// - num_sampled: Number of candidates to randomly sample. +/// - unique: If unique is true, we sample with rejection, so that all sampled +/// candidates in a batch are unique. This requires some approximation to +/// estimate the post-rejection sampling probabilities. +/// - range_max: The sampler will sample integers from the interval [0, range_max). +/// - vocab_file: Each valid line in this file (which should have a CSV-like format) +/// corresponds to a valid word ID. IDs are in sequential order, starting from +/// num_reserved_ids. The last entry in each line is expected to be a value +/// corresponding to the count or relative probability. Exactly one of vocab_file +/// and unigrams needs to be passed to this op. +/// - distortion: The distortion is used to skew the unigram probability distribution. +/// Each weight is first raised to the distortion's power before adding to the +/// internal unigram distribution. As a result, distortion = 1.0 gives regular +/// unigram sampling (as defined by the vocab file), and distortion = 0.0 gives +/// a uniform distribution. +/// - num_reserved_ids: Optionally some reserved IDs can be added in the range [0, +/// ..., num_reserved_ids) by the users. One use case is that a special unknown +/// word token is used as ID 0. These IDs will have a sampling probability of 0. +/// - num_shards: A sampler can be used to sample from a subset of the original range +/// in order to speed up the whole computation through parallelism. This parameter +/// (together with 'shard') indicates the number of partitions that are being +/// used in the overall computation. +/// - shard: A sampler can be used to sample from a subset of the original range +/// in order to speed up the whole computation through parallelism. This parameter +/// (together with 'num_shards') indicates the particular partition number of a +/// sampler op, when partitioning is being used. +/// - unigrams: A list of unigram counts or probabilities, one per ID in sequential +/// order. Exactly one of vocab_file and unigrams should be passed to this op. +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. +/// +/// - Outputs: +/// - sampled_candidates: A vector of length num_sampled, in which each element is +/// the ID of a sampled candidate. +/// - true_expected_count: A batch_size * num_true matrix, representing +/// the number of times each candidate is expected to occur in a batch +/// of sampled candidates. If unique=true, then this is a probability. +/// - sampled_expected_count: A vector of length num_sampled, for each sampled +/// candidate representing the number of times the candidate is expected +/// to occur in a batch of sampled candidates. If unique=true, then this is a +/// probability. +@inlinable @inline(__always) +public static func fixedUnigramCandidateSampler( + trueClasses: Tensor, + numTrue: Int64, + numSampled: Int64, + unique: Bool, + rangeMax: Int64, + vocabFile: String, + distortion: Double = 1, + numReservedIds: Int64 = 0, + numShards: Int64 = 1, + shard: Int64 = 0, + unigrams: [Double], + seed: Int64 = 0, + seed2: Int64 = 0 +) -> (sampledCandidates: Tensor, trueExpectedCount: Tensor, sampledExpectedCount: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("FixedUnigramCandidateSampler", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("num_sampled", numSampled) + op.updateAttribute("unique", unique) + op.updateAttribute("range_max", rangeMax) + op.updateAttribute("vocab_file", vocabFile) + op.updateAttribute("distortion", distortion) + op.updateAttribute("num_reserved_ids", numReservedIds) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard", shard) + op.updateAttribute("unigrams", unigrams) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Creates a dataset that applies `f` to the outputs of `input_dataset`. +/// +/// Unlike MapDataset, the `f` in FlatMapDataset is expected to return a +/// Dataset variant, and FlatMapDataset will flatten successive results +/// into a single Dataset. +/// +/// - Attr f: A function mapping elements of `input_dataset`, concatenated with +/// `other_arguments`, to a Dataset variant that contains elements matching +/// `output_types` and `output_shapes`. +@inlinable @inline(__always) +public static func flatMapDataset< + FIn: TensorGroup, + FOut: TensorGroup, + Targuments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + otherArguments: Targuments, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("FlatMapDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(otherArguments) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func floatInput( + _ a: Tensor +) { + let nOutputs = 0 + let op = makeOp("FloatInput", nOutputs) + op.addInput(a) + op.execute() +} + +@inlinable @inline(__always) +public static func floatOutput( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FloatOutput", nOutputs) + + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func floatOutputStringOutput( +) -> (a: Tensor, b: StringTensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("FloatOutputStringOutput", nOutputs) + + return op.execute(Int(1), Int(1)) +} + +/// Returns element-wise largest integer not greater than x. +@inlinable @inline(__always) +public static func floor( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Floor", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Returns x // y element-wise. +/// +/// *NOTE*: `FloorDiv` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func floorDiv( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FloorDiv", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns element-wise remainder of division. When `x < 0` xor `y < 0` is +/// +/// true, this follows Python semantics in that the result here is consistent +/// with a flooring divide. E.g. `floor(x / y) * y + mod(x, y) = x`. +/// +/// *NOTE*: `FloorMod` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func floorMod( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FloorMod", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func flushSummaryWriter( + writer: ResourceHandle +) { + let nOutputs = 0 + let op = makeOp("FlushSummaryWriter", nOutputs) + op.addInput(writer) + op.execute() +} + +@inlinable @inline(__always) +public static func foo1( + _ a: Tensor, + _ b: Tensor, + c: Tensor +) -> (d: Tensor, e: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("Foo1", nOutputs) + op.addInput(a) + op.addInput(b) + op.addInput(c) + return op.execute(Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func foo2( + _ a: Tensor, + _ b: StringTensor, + c: StringTensor +) -> (d: Tensor, e: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("Foo2", nOutputs) + op.addInput(a) + op.addInput(b) + op.addInput(c) + return op.execute(Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func foo3( + _ a: Tensor, + _ b: StringTensor, + c: Tensor +) -> (d: Tensor, e: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("Foo3", nOutputs) + op.addInput(a) + op.addInput(b) + op.addInput(c) + return op.execute(Int(1), Int(1)) +} + +/// ```python +/// output = input; +/// for i in range(start, limit, delta) +/// output = body(i, output); +/// ``` +/// +/// - Parameters: +/// - start: The lower bound. An int32 +/// - limit: The upper bound. An int32 +/// - delta: The increment. An int32 +/// - input: A list of input tensors whose types are T. +/// +/// - Attrs: +/// - T: A list of dtypes. +/// - body: A function that takes a list of tensors (int32, T) and returns another +/// list of tensors (T). +/// +/// - Output output: A list of output tensors whose types are T. +@inlinable @inline(__always) +public static func for_< + T: TensorArrayProtocol, + BodyIn: TensorGroup, + BodyOut: TensorGroup +>( + start: Tensor, + limit: Tensor, + delta: Tensor, + _ input: T, + body: (BodyIn) -> BodyOut +) -> T { + let nOutputs = Int(input._typeList.count) + let op = makeOp("For", nOutputs) + op.updateAttribute("T", input._typeList) + op.updateAttribute("body", body) + op.addInput(start) + op.addInput(limit) + op.addInput(delta) + op.addInputList(input) + return op.execute(Int(input._typeList.count)) +} + +/// Performs fractional average pooling on the input. +/// +/// Fractional average pooling is similar to Fractional max pooling in the pooling +/// region generation step. The only difference is that after pooling regions are +/// generated, a mean operation is performed instead of a max operation in each +/// pooling region. +/// +/// - Parameter value: 4-D with shape `[batch, height, width, channels]`. +/// +/// - Attrs: +/// - pooling_ratio: Pooling ratio for each dimension of `value`, currently only +/// supports row and col dimension and should be >= 1.0. For example, a valid +/// pooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements +/// must be 1.0 because we don't allow pooling on batch and channels +/// dimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions +/// respectively. +/// - pseudo_random: When set to True, generates the pooling sequence in a +/// pseudorandom fashion, otherwise, in a random fashion. Check paper [Benjamin +/// Graham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) for +/// difference between pseudorandom and random. +/// - overlapping: When set to True, it means when pooling, the values at the boundary +/// of adjacent pooling cells are used by both cells. For example: +/// +/// `index 0 1 2 3 4` +/// +/// `value 20 5 16 3 7` +/// +/// If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. +/// The result would be [41/3, 26/3] for fractional avg pooling. +/// - deterministic: When set to True, a fixed pooling region will be used when +/// iterating over a FractionalAvgPool node in the computation graph. Mainly used +/// in unit test to make FractionalAvgPool deterministic. +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. +/// +/// - Outputs: +/// - output: output tensor after fractional avg pooling. +/// - row_pooling_sequence: row pooling sequence, needed to calculate gradient. +/// - col_pooling_sequence: column pooling sequence, needed to calculate gradient. +@inlinable @inline(__always) +public static func fractionalAvgPool( + value: Tensor, + poolingRatio: [Double], + pseudoRandom: Bool = false, + overlapping: Bool = false, + deterministic: Bool = false, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> (output: Tensor, rowPoolingSequence: Tensor, colPoolingSequence: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("FractionalAvgPool", nOutputs) + op.updateAttribute("pooling_ratio", poolingRatio) + op.updateAttribute("pseudo_random", pseudoRandom) + op.updateAttribute("overlapping", overlapping) + op.updateAttribute("deterministic", deterministic) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Computes gradient of the FractionalAvgPool function. +/// +/// Unlike FractionalMaxPoolGrad, we don't need to find arg_max for +/// FractionalAvgPoolGrad, we just need to evenly back-propagate each element of +/// out_backprop to those indices that form the same pooling cell. Therefore, we +/// just need to know the shape of original input tensor, instead of the whole +/// tensor. +/// +/// - Parameters: +/// - orig_input_tensor_shape: Original input tensor shape for `fractional_avg_pool` +/// - out_backprop: 4-D with shape `[batch, height, width, channels]`. Gradients +/// w.r.t. the output of `fractional_avg_pool`. +/// - row_pooling_sequence: row pooling sequence, form pooling region with +/// col_pooling_sequence. +/// - col_pooling_sequence: column pooling sequence, form pooling region with +/// row_pooling sequence. +/// +/// - Attr overlapping: When set to True, it means when pooling, the values at the boundary +/// of adjacent pooling cells are used by both cells. For example: +/// +/// `index 0 1 2 3 4` +/// +/// `value 20 5 16 3 7` +/// +/// If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. +/// The result would be [41/3, 26/3] for fractional avg pooling. +/// +/// - Output output: 4-D. Gradients w.r.t. the input of `fractional_avg_pool`. +@inlinable @inline(__always) +public static func fractionalAvgPoolGrad( + origInputTensorShape: Tensor, + outBackprop: Tensor, + rowPoolingSequence: Tensor, + colPoolingSequence: Tensor, + overlapping: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FractionalAvgPoolGrad", nOutputs) + op.updateAttribute("overlapping", overlapping) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInputTensorShape) + op.addInput(outBackprop) + op.addInput(rowPoolingSequence) + op.addInput(colPoolingSequence) + return op.execute(Int(1)) +} + +/// Performs fractional max pooling on the input. +/// +/// Fractional max pooling is slightly different than regular max pooling. In +/// regular max pooling, you downsize an input set by taking the maximum value of +/// smaller N x N subsections of the set (often 2x2), and try to reduce the set by +/// a factor of N, where N is an integer. Fractional max pooling, as you might +/// expect from the word "fractional", means that the overall reduction ratio N +/// does not have to be an integer. +/// +/// The sizes of the pooling regions are generated randomly but are fairly uniform. +/// For example, let's look at the height dimension, and the constraints on the +/// list of rows that will be pool boundaries. +/// +/// First we define the following: +/// +/// 1. input_row_length : the number of rows from the input set +/// 2. output_row_length : which will be smaller than the input +/// 3. alpha = input_row_length / output_row_length : our reduction ratio +/// 4. K = floor(alpha) +/// 5. row_pooling_sequence : this is the result list of pool boundary rows +/// +/// Then, row_pooling_sequence should satisfy: +/// +/// 1. a[0] = 0 : the first value of the sequence is 0 +/// 2. a[end] = input_row_length : the last value of the sequence is the size +/// 3. K <= (a[i+1] - a[i]) <= K+1 : all intervals are K or K+1 size +/// 4. length(row_pooling_sequence) = output_row_length+1 +/// +/// For more details on fractional max pooling, see this paper: +/// [Benjamin Graham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) +/// +/// - Parameter value: 4-D with shape `[batch, height, width, channels]`. +/// +/// - Attrs: +/// - pooling_ratio: Pooling ratio for each dimension of `value`, currently only +/// supports row and col dimension and should be >= 1.0. For example, a valid +/// pooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements +/// must be 1.0 because we don't allow pooling on batch and channels +/// dimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions +/// respectively. +/// - pseudo_random: When set to True, generates the pooling sequence in a +/// pseudorandom fashion, otherwise, in a random fashion. Check paper [Benjamin +/// Graham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) for +/// difference between pseudorandom and random. +/// - overlapping: When set to True, it means when pooling, the values at the boundary +/// of adjacent pooling cells are used by both cells. For example: +/// +/// `index 0 1 2 3 4` +/// +/// `value 20 5 16 3 7` +/// +/// If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. +/// The result would be [20, 16] for fractional max pooling. +/// - deterministic: When set to True, a fixed pooling region will be used when +/// iterating over a FractionalMaxPool node in the computation graph. Mainly used +/// in unit test to make FractionalMaxPool deterministic. +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. +/// +/// - Outputs: +/// - output: output tensor after fractional max pooling. +/// - row_pooling_sequence: row pooling sequence, needed to calculate gradient. +/// - col_pooling_sequence: column pooling sequence, needed to calculate gradient. +@inlinable @inline(__always) +public static func fractionalMaxPool( + value: Tensor, + poolingRatio: [Double], + pseudoRandom: Bool = false, + overlapping: Bool = false, + deterministic: Bool = false, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> (output: Tensor, rowPoolingSequence: Tensor, colPoolingSequence: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("FractionalMaxPool", nOutputs) + op.updateAttribute("pooling_ratio", poolingRatio) + op.updateAttribute("pseudo_random", pseudoRandom) + op.updateAttribute("overlapping", overlapping) + op.updateAttribute("deterministic", deterministic) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Computes gradient of the FractionalMaxPool function. +/// +/// - Parameters: +/// - orig_input: Original input for `fractional_max_pool` +/// - orig_output: Original output for `fractional_max_pool` +/// - out_backprop: 4-D with shape `[batch, height, width, channels]`. Gradients +/// w.r.t. the output of `fractional_max_pool`. +/// - row_pooling_sequence: row pooling sequence, form pooling region with +/// col_pooling_sequence. +/// - col_pooling_sequence: column pooling sequence, form pooling region with +/// row_pooling sequence. +/// +/// - Attr overlapping: When set to True, it means when pooling, the values at the boundary +/// of adjacent pooling cells are used by both cells. For example: +/// +/// `index 0 1 2 3 4` +/// +/// `value 20 5 16 3 7` +/// +/// If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. +/// The result would be [20, 16] for fractional max pooling. +/// +/// - Output output: 4-D. Gradients w.r.t. the input of `fractional_max_pool`. +@inlinable @inline(__always) +public static func fractionalMaxPoolGrad( + origInput: Tensor, + origOutput: Tensor, + outBackprop: Tensor, + rowPoolingSequence: Tensor, + colPoolingSequence: Tensor, + overlapping: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FractionalMaxPoolGrad", nOutputs) + op.updateAttribute("overlapping", overlapping) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(outBackprop) + op.addInput(rowPoolingSequence) + op.addInput(colPoolingSequence) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func funcAttr( + f: (FIn) -> FOut +) { + let nOutputs = 0 + let op = makeOp("FuncAttr", nOutputs) + op.updateAttribute("f", f) + op.execute() +} + +/// Batch normalization. +/// +/// Note that the size of 4D Tensors are defined by either "NHWC" or "NCHW". +/// The size of 1D Tensors matches the dimension C of the 4D Tensors. +/// +/// - Parameters: +/// - x: A 4D Tensor for input data. +/// - scale: A 1D Tensor for scaling factor, to scale the normalized x. +/// - offset: A 1D Tensor for offset, to shift to the normalized x. +/// - mean: A 1D Tensor for population mean. Used for inference only; +/// must be empty for training. +/// - variance: A 1D Tensor for population variance. Used for inference only; +/// must be empty for training. +/// +/// - Attrs: +/// - T: The data type for the elements of input and output Tensors. +/// - epsilon: A small float number added to the variance of x. +/// - data_format: The data format for x and y. Either "NHWC" (default) or "NCHW". +/// - is_training: A bool value to indicate the operation is for training (default) +/// or inference. +/// +/// - Outputs: +/// - y: A 4D Tensor for output data. +/// - batch_mean: A 1D Tensor for the computed batch mean, to be used by TensorFlow +/// to compute the running mean. +/// - batch_variance: A 1D Tensor for the computed batch variance, to be used by +/// TensorFlow to compute the running variance. +/// - reserve_space_1: A 1D Tensor for the computed batch mean, to be reused +/// in the gradient computation. +/// - reserve_space_2: A 1D Tensor for the computed batch variance (inverted variance +/// in the cuDNN case), to be reused in the gradient computation. +@inlinable @inline(__always) +public static func fusedBatchNorm( + _ x: Tensor, + scale: Tensor, + offset: Tensor, + mean: Tensor, + variance: Tensor, + epsilon: Double = 0.0001, + dataFormat: DataFormat = .nhwc, + isTraining: Bool = true +) -> (y: Tensor, batchMean: Tensor, batchVariance: Tensor, reserveSpace1: Tensor, reserveSpace2: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("FusedBatchNorm", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("epsilon", epsilon) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("is_training", isTraining) + op.addInput(x) + op.addInput(scale) + op.addInput(offset) + op.addInput(mean) + op.addInput(variance) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// Gradient for batch normalization. +/// +/// Note that the size of 4D Tensors are defined by either "NHWC" or "NCHW". +/// The size of 1D Tensors matches the dimension C of the 4D Tensors. +/// +/// - Parameters: +/// - y_backprop: A 4D Tensor for the gradient with respect to y. +/// - x: A 4D Tensor for input data. +/// - scale: A 1D Tensor for scaling factor, to scale the normalized x. +/// - reserve_space_1: When is_training is True, a 1D Tensor for the computed batch +/// mean to be reused in gradient computation. When is_training is +/// False, a 1D Tensor for the population mean to be reused in both +/// 1st and 2nd order gradient computation. +/// - reserve_space_2: When is_training is True, a 1D Tensor for the computed batch +/// variance (inverted variance in the cuDNN case) to be reused in +/// gradient computation. When is_training is False, a 1D Tensor +/// for the population variance to be reused in both 1st and 2nd +/// order gradient computation. +/// +/// - Attrs: +/// - T: The data type for the elements of input and output Tensors. +/// - epsilon: A small float number added to the variance of x. +/// - data_format: The data format for y_backprop, x, x_backprop. +/// Either "NHWC" (default) or "NCHW". +/// - is_training: A bool value to indicate the operation is for training (default) +/// or inference. +/// +/// - Outputs: +/// - x_backprop: A 4D Tensor for the gradient with respect to x. +/// - scale_backprop: A 1D Tensor for the gradient with respect to scale. +/// - offset_backprop: A 1D Tensor for the gradient with respect to offset. +/// - reserve_space_3: Unused placeholder to match the mean input in FusedBatchNorm. +/// - reserve_space_4: Unused placeholder to match the variance input +/// in FusedBatchNorm. +@inlinable @inline(__always) +public static func fusedBatchNormGrad( + yBackprop: Tensor, + _ x: Tensor, + scale: Tensor, + reserveSpace1: Tensor, + reserveSpace2: Tensor, + epsilon: Double = 0.0001, + dataFormat: DataFormat = .nhwc, + isTraining: Bool = true +) -> (xBackprop: Tensor, scaleBackprop: Tensor, offsetBackprop: Tensor, reserveSpace3: Tensor, reserveSpace4: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("FusedBatchNormGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("epsilon", epsilon) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("is_training", isTraining) + op.addInput(yBackprop) + op.addInput(x) + op.addInput(scale) + op.addInput(reserveSpace1) + op.addInput(reserveSpace2) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// Gradient for batch normalization. +/// +/// Note that the size of 4D Tensors are defined by either "NHWC" or "NCHW". +/// The size of 1D Tensors matches the dimension C of the 4D Tensors. +/// +/// - Parameters: +/// - y_backprop: A 4D Tensor for the gradient with respect to y. +/// - x: A 4D Tensor for input data. +/// - scale: A 1D Tensor for scaling factor, to scale the normalized x. +/// - reserve_space_1: When is_training is True, a 1D Tensor for the computed batch +/// mean to be reused in gradient computation. When is_training is +/// False, a 1D Tensor for the population mean to be reused in both +/// 1st and 2nd order gradient computation. +/// - reserve_space_2: When is_training is True, a 1D Tensor for the computed batch +/// variance (inverted variance in the cuDNN case) to be reused in +/// gradient computation. When is_training is False, a 1D Tensor +/// for the population variance to be reused in both 1st and 2nd +/// order gradient computation. +/// +/// - Attrs: +/// - T: The data type for the elements of input and output Tensors. +/// - U: The data type for the scale, offset, mean, and variance. +/// - epsilon: A small float number added to the variance of x. +/// - data_format: The data format for y_backprop, x, x_backprop. +/// Either "NHWC" (default) or "NCHW". +/// - is_training: A bool value to indicate the operation is for training (default) +/// or inference. +/// +/// - Outputs: +/// - x_backprop: A 4D Tensor for the gradient with respect to x. +/// - scale_backprop: A 1D Tensor for the gradient with respect to scale. +/// - offset_backprop: A 1D Tensor for the gradient with respect to offset. +/// - reserve_space_3: Unused placeholder to match the mean input in FusedBatchNorm. +/// - reserve_space_4: Unused placeholder to match the variance input +/// in FusedBatchNorm. +@inlinable @inline(__always) +public static func fusedBatchNormGradV2< + T: FloatingPoint & TensorFlowScalar, + U: FloatingPoint & TensorFlowScalar +>( + yBackprop: Tensor, + _ x: Tensor, + scale: Tensor, + reserveSpace1: Tensor, + reserveSpace2: Tensor, + epsilon: Double = 0.0001, + dataFormat: DataFormat = .nhwc, + isTraining: Bool = true +) -> (xBackprop: Tensor, scaleBackprop: Tensor, offsetBackprop: Tensor, reserveSpace3: Tensor, reserveSpace4: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("FusedBatchNormGradV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("U", U.tensorFlowDataType) + op.updateAttribute("epsilon", epsilon) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("is_training", isTraining) + op.addInput(yBackprop) + op.addInput(x) + op.addInput(scale) + op.addInput(reserveSpace1) + op.addInput(reserveSpace2) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// Batch normalization. +/// +/// Note that the size of 4D Tensors are defined by either "NHWC" or "NCHW". +/// The size of 1D Tensors matches the dimension C of the 4D Tensors. +/// +/// - Parameters: +/// - x: A 4D Tensor for input data. +/// - scale: A 1D Tensor for scaling factor, to scale the normalized x. +/// - offset: A 1D Tensor for offset, to shift to the normalized x. +/// - mean: A 1D Tensor for population mean. Used for inference only; +/// must be empty for training. +/// - variance: A 1D Tensor for population variance. Used for inference only; +/// must be empty for training. +/// +/// - Attrs: +/// - T: The data type for the elements of input and output Tensors. +/// - U: The data type for the scale, offset, mean, and variance. +/// - epsilon: A small float number added to the variance of x. +/// - data_format: The data format for x and y. Either "NHWC" (default) or "NCHW". +/// - is_training: A bool value to indicate the operation is for training (default) +/// or inference. +/// +/// - Outputs: +/// - y: A 4D Tensor for output data. +/// - batch_mean: A 1D Tensor for the computed batch mean, to be used by TensorFlow +/// to compute the running mean. +/// - batch_variance: A 1D Tensor for the computed batch variance, to be used by +/// TensorFlow to compute the running variance. +/// - reserve_space_1: A 1D Tensor for the computed batch mean, to be reused +/// in the gradient computation. +/// - reserve_space_2: A 1D Tensor for the computed batch variance (inverted variance +/// in the cuDNN case), to be reused in the gradient computation. +@inlinable @inline(__always) +public static func fusedBatchNormV2< + T: FloatingPoint & TensorFlowScalar, + U: FloatingPoint & TensorFlowScalar +>( + _ x: Tensor, + scale: Tensor, + offset: Tensor, + mean: Tensor, + variance: Tensor, + epsilon: Double = 0.0001, + dataFormat: DataFormat = .nhwc, + isTraining: Bool = true +) -> (y: Tensor, batchMean: Tensor, batchVariance: Tensor, reserveSpace1: Tensor, reserveSpace2: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("FusedBatchNormV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("U", U.tensorFlowDataType) + op.updateAttribute("epsilon", epsilon) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("is_training", isTraining) + op.addInput(x) + op.addInput(scale) + op.addInput(offset) + op.addInput(mean) + op.addInput(variance) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// Performs a padding as a preprocess during a convolution. +/// +/// Similar to FusedResizeAndPadConv2d, this op allows for an optimized +/// implementation where the spatial padding transformation stage is fused with the +/// im2col lookup, but in this case without the bilinear filtering required for +/// resizing. Fusing the padding prevents the need to write out the intermediate +/// results as whole tensors, reducing memory pressure, and we can get some latency +/// gains by merging the transformation calculations. +/// The data_format attribute for Conv2D isn't supported by this op, and 'NHWC' +/// order is used instead. +/// Internally this op uses a single per-graph scratch buffer, which means that it +/// will block if multiple versions are being run in parallel. This is because this +/// operator is primarily an optimization to minimize memory usage. +/// +/// - Parameters: +/// - input: 4-D with shape `[batch, in_height, in_width, in_channels]`. +/// - paddings: A two-column matrix specifying the padding sizes. The number of +/// rows must be the same as the rank of `input`. +/// - filter: 4-D with shape +/// `[filter_height, filter_width, in_channels, out_channels]`. +/// +/// - Attrs: +/// - strides: 1-D of length 4. The stride of the sliding window for each dimension +/// of `input`. Must be in the same order as the dimension specified with format. +/// - padding: The type of padding algorithm to use. +@inlinable @inline(__always) +public static func fusedPadConv2D( + _ input: Tensor, + paddings: Tensor, + filter: Tensor, + mode: Mode5, + strides: [Int32], + padding: Padding +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FusedPadConv2D", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("mode", mode.cName) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(paddings) + op.addInput(filter) + return op.execute(Int(1)) +} + +/// Performs a resize and padding as a preprocess during a convolution. +/// +/// It's often possible to do spatial transformations more efficiently as part of +/// the packing stage of a convolution, so this op allows for an optimized +/// implementation where these stages are fused together. This prevents the need to +/// write out the intermediate results as whole tensors, reducing memory pressure, +/// and we can get some latency gains by merging the transformation calculations. +/// The data_format attribute for Conv2D isn't supported by this op, and defaults to +/// 'NHWC' order. +/// Internally this op uses a single per-graph scratch buffer, which means that it +/// will block if multiple versions are being run in parallel. This is because this +/// operator is primarily an optimization to minimize memory usage. +/// +/// - Parameters: +/// - input: 4-D with shape `[batch, in_height, in_width, in_channels]`. +/// - size: A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The +/// new size for the images. +/// - paddings: A two-column matrix specifying the padding sizes. The number of +/// rows must be the same as the rank of `input`. +/// - filter: 4-D with shape +/// `[filter_height, filter_width, in_channels, out_channels]`. +/// +/// - Attrs: +/// - resize_align_corners: If true, the centers of the 4 corner pixels of the input and output tensors are +/// aligned, preserving the values at the corner pixels. Defaults to false. +/// - strides: 1-D of length 4. The stride of the sliding window for each dimension +/// of `input`. Must be in the same order as the dimension specified with format. +/// - padding: The type of padding algorithm to use. +@inlinable @inline(__always) +public static func fusedResizeAndPadConv2D( + _ input: Tensor, + size: Tensor, + paddings: Tensor, + filter: Tensor, + resizeAlignCorners: Bool = false, + mode: Mode5, + strides: [Int32], + padding: Padding +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FusedResizeAndPadConv2D", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("resize_align_corners", resizeAlignCorners) + op.updateAttribute("mode", mode.cName) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(size) + op.addInput(paddings) + op.addInput(filter) + return op.execute(Int(1)) +} + +/// Computes the GRU cell forward propagation for 1 time step. +/// +/// Args +/// x: Input to the GRU cell. +/// h_prev: State input from the previous GRU cell. +/// w_ru: Weight matrix for the reset and update gate. +/// w_c: Weight matrix for the cell connection gate. +/// b_ru: Bias vector for the reset and update gate. +/// b_c: Bias vector for the cell connection gate. +/// +/// Returns +/// r: Output of the reset gate. +/// u: Output of the update gate. +/// c: Output of the cell connection gate. +/// h: Current state of the GRU cell. +/// +/// Note on notation of the variables: +/// +/// Concatenation of a and b is represented by a_b +/// Element-wise dot product of a and b is represented by ab +/// Element-wise dot product is represented by \circ +/// Matrix multiplication is represented by * +/// +/// Biases are initialized with : +/// `b_ru` - constant_initializer(1.0) +/// `b_c` - constant_initializer(0.0) +/// +/// This kernel op implements the following mathematical equations: +/// +/// ``` +/// x_h_prev = [x, h_prev] +/// +/// [r_bar u_bar] = x_h_prev * w_ru + b_ru +/// +/// r = sigmoid(r_bar) +/// u = sigmoid(u_bar) +/// +/// h_prevr = h_prev \circ r +/// +/// x_h_prevr = [x h_prevr] +/// +/// c_bar = x_h_prevr * w_c + b_c +/// c = tanh(c_bar) +/// +/// h = (1-u) \circ c + u \circ h_prev +/// ``` +@inlinable @inline(__always) +public static func gRUBlockCell( + _ x: Tensor, + hPrev: Tensor, + wRu: Tensor, + wC: Tensor, + bRu: Tensor, + bC: Tensor +) -> (r: Tensor, u: Tensor, c: Tensor, h: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("GRUBlockCell", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(hPrev) + op.addInput(wRu) + op.addInput(wC) + op.addInput(bRu) + op.addInput(bC) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Computes the GRU cell back-propagation for 1 time step. +/// +/// Args +/// x: Input to the GRU cell. +/// h_prev: State input from the previous GRU cell. +/// w_ru: Weight matrix for the reset and update gate. +/// w_c: Weight matrix for the cell connection gate. +/// b_ru: Bias vector for the reset and update gate. +/// b_c: Bias vector for the cell connection gate. +/// r: Output of the reset gate. +/// u: Output of the update gate. +/// c: Output of the cell connection gate. +/// d_h: Gradients of the h_new wrt to objective function. +/// +/// Returns +/// d_x: Gradients of the x wrt to objective function. +/// d_h_prev: Gradients of the h wrt to objective function. +/// d_c_bar Gradients of the c_bar wrt to objective function. +/// d_r_bar_u_bar Gradients of the r_bar & u_bar wrt to objective function. +/// +/// This kernel op implements the following mathematical equations: +/// +/// Note on notation of the variables: +/// +/// Concatenation of a and b is represented by a_b +/// Element-wise dot product of a and b is represented by ab +/// Element-wise dot product is represented by \circ +/// Matrix multiplication is represented by * +/// +/// Additional notes for clarity: +/// +/// `w_ru` can be segmented into 4 different matrices. +/// ``` +/// w_ru = [w_r_x w_u_x +/// w_r_h_prev w_u_h_prev] +/// ``` +/// Similarly, `w_c` can be segmented into 2 different matrices. +/// ``` +/// w_c = [w_c_x w_c_h_prevr] +/// ``` +/// Same goes for biases. +/// ``` +/// b_ru = [b_ru_x b_ru_h] +/// b_c = [b_c_x b_c_h] +/// ``` +/// Another note on notation: +/// ``` +/// d_x = d_x_component_1 + d_x_component_2 +/// +/// where d_x_component_1 = d_r_bar * w_r_x^T + d_u_bar * w_r_x^T +/// and d_x_component_2 = d_c_bar * w_c_x^T +/// +/// d_h_prev = d_h_prev_component_1 + d_h_prevr \circ r + d_h \circ u +/// where d_h_prev_componenet_1 = d_r_bar * w_r_h_prev^T + d_u_bar * w_r_h_prev^T +/// ``` +/// +/// Mathematics behind the Gradients below: +/// ``` +/// d_c_bar = d_h \circ (1-u) \circ (1-c \circ c) +/// d_u_bar = d_h \circ (h-c) \circ u \circ (1-u) +/// +/// d_r_bar_u_bar = [d_r_bar d_u_bar] +/// +/// [d_x_component_1 d_h_prev_component_1] = d_r_bar_u_bar * w_ru^T +/// +/// [d_x_component_2 d_h_prevr] = d_c_bar * w_c^T +/// +/// d_x = d_x_component_1 + d_x_component_2 +/// +/// d_h_prev = d_h_prev_component_1 + d_h_prevr \circ r + u +/// ``` +/// Below calculation is performed in the python wrapper for the Gradients +/// (not in the gradient kernel.) +/// ``` +/// d_w_ru = x_h_prevr^T * d_c_bar +/// +/// d_w_c = x_h_prev^T * d_r_bar_u_bar +/// +/// d_b_ru = sum of d_r_bar_u_bar along axis = 0 +/// +/// d_b_c = sum of d_c_bar along axis = 0 +/// ``` +@inlinable @inline(__always) +public static func gRUBlockCellGrad( + _ x: Tensor, + hPrev: Tensor, + wRu: Tensor, + wC: Tensor, + bRu: Tensor, + bC: Tensor, + r: Tensor, + u: Tensor, + c: Tensor, + dH: Tensor +) -> (dX: Tensor, dHPrev: Tensor, dCBar: Tensor, dRBarUBar: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("GRUBlockCellGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(hPrev) + op.addInput(wRu) + op.addInput(wC) + op.addInput(bRu) + op.addInput(bC) + op.addInput(r) + op.addInput(u) + op.addInput(c) + op.addInput(dH) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Gather slices from `params` according to `indices`. +/// +/// `indices` must be an integer tensor of any dimension (usually 0-D or 1-D). +/// Produces an output tensor with shape `indices.shape + params.shape[1:]` where: +/// +/// ```python +/// # Scalar indices +/// output[:, ..., :] = params[indices, :, ... :] +/// +/// # Vector indices +/// output[i, :, ..., :] = params[indices[i], :, ... :] +/// +/// # Higher rank indices +/// output[i, ..., j, :, ... :] = params[indices[i, ..., j], :, ..., :] +/// ``` +/// +/// If `indices` is a permutation and `len(indices) == params.shape[0]` then +/// this operation will permute `params` accordingly. +/// +/// `validate_indices`: DEPRECATED. If this operation is assigned to CPU, values in +/// `indices` are always validated to be within range. If assigned to GPU, +/// out-of-bound indices result in safe but unspecified behavior, which may include +/// raising an error. +/// +///
+/// +///
+@inlinable @inline(__always) +public static func gather< + Tparams: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + params: Tensor, + indices: Tensor, + validateIndices: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Gather", nOutputs) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("Tparams", Tparams.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(params) + op.addInput(indices) + return op.execute(Int(1)) +} + +/// Gather slices from `params` into a Tensor with shape specified by `indices`. +/// +/// `indices` is an K-dimensional integer tensor, best thought of as a +/// (K-1)-dimensional tensor of indices into `params`, where each element defines a +/// slice of `params`: +/// +/// output[\\(i_0, ..., i_{K-2}\\)] = params[indices[\\(i_0, ..., i_{K-2}\\)]] +/// +/// Whereas in `tf.gather` `indices` defines slices into the first +/// dimension of `params`, in `tf.gather_nd`, `indices` defines slices into the +/// first `N` dimensions of `params`, where `N = indices.shape[-1]`. +/// +/// The last dimension of `indices` can be at most the rank of +/// `params`: +/// +/// indices.shape[-1] <= params.rank +/// +/// The last dimension of `indices` corresponds to elements +/// (if `indices.shape[-1] == params.rank`) or slices +/// (if `indices.shape[-1] < params.rank`) along dimension `indices.shape[-1]` +/// of `params`. The output tensor has shape +/// +/// indices.shape[:-1] + params.shape[indices.shape[-1]:] +/// +/// Note that on CPU, if an out of bound index is found, an error is returned. +/// On GPU, if an out of bound index is found, a 0 is stored in the +/// corresponding output value. +/// +/// Some examples below. +/// +/// Simple indexing into a matrix: +/// +/// ```python +/// indices = [[0, 0], [1, 1]] +/// params = [['a', 'b'], ['c', 'd']] +/// output = ['a', 'd'] +/// ``` +/// +/// Slice indexing into a matrix: +/// +/// ```python +/// indices = [[1], [0]] +/// params = [['a', 'b'], ['c', 'd']] +/// output = [['c', 'd'], ['a', 'b']] +/// ``` +/// +/// Indexing into a 3-tensor: +/// +/// ```python +/// indices = [[1]] +/// params = [[['a0', 'b0'], ['c0', 'd0']], +/// [['a1', 'b1'], ['c1', 'd1']]] +/// output = [[['a1', 'b1'], ['c1', 'd1']]] +/// +/// +/// indices = [[0, 1], [1, 0]] +/// params = [[['a0', 'b0'], ['c0', 'd0']], +/// [['a1', 'b1'], ['c1', 'd1']]] +/// output = [['c0', 'd0'], ['a1', 'b1']] +/// +/// +/// indices = [[0, 0, 1], [1, 0, 1]] +/// params = [[['a0', 'b0'], ['c0', 'd0']], +/// [['a1', 'b1'], ['c1', 'd1']]] +/// output = ['b0', 'b1'] +/// ``` +/// +/// Batched indexing into a matrix: +/// +/// ```python +/// indices = [[[0, 0]], [[0, 1]]] +/// params = [['a', 'b'], ['c', 'd']] +/// output = [['a'], ['b']] +/// ``` +/// +/// Batched slice indexing into a matrix: +/// +/// ```python +/// indices = [[[1]], [[0]]] +/// params = [['a', 'b'], ['c', 'd']] +/// output = [[['c', 'd']], [['a', 'b']]] +/// ``` +/// +/// Batched indexing into a 3-tensor: +/// +/// ```python +/// indices = [[[1]], [[0]]] +/// params = [[['a0', 'b0'], ['c0', 'd0']], +/// [['a1', 'b1'], ['c1', 'd1']]] +/// output = [[[['a1', 'b1'], ['c1', 'd1']]], +/// [[['a0', 'b0'], ['c0', 'd0']]]] +/// +/// indices = [[[0, 1], [1, 0]], [[0, 0], [1, 1]]] +/// params = [[['a0', 'b0'], ['c0', 'd0']], +/// [['a1', 'b1'], ['c1', 'd1']]] +/// output = [[['c0', 'd0'], ['a1', 'b1']], +/// [['a0', 'b0'], ['c1', 'd1']]] +/// +/// +/// indices = [[[0, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 1, 0]]] +/// params = [[['a0', 'b0'], ['c0', 'd0']], +/// [['a1', 'b1'], ['c1', 'd1']]] +/// output = [['b0', 'b1'], ['d0', 'c1']] +/// ``` +/// +/// See also `tf.gather` and `tf.batch_gather`. +/// +/// - Parameters: +/// - params: The tensor from which to gather values. +/// - indices: Index tensor. +/// +/// - Output output: Values from `params` gathered from indices given by `indices`, with +/// shape `indices.shape[:-1] + params.shape[indices.shape[-1]:]`. +@inlinable @inline(__always) +public static func gatherNd< + Tparams: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + params: Tensor, + indices: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("GatherNd", nOutputs) + op.updateAttribute("Tparams", Tparams.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(params) + op.addInput(indices) + return op.execute(Int(1)) +} + +/// Gather slices from `params` axis `axis` according to `indices`. +/// +/// `indices` must be an integer tensor of any dimension (usually 0-D or 1-D). +/// Produces an output tensor with shape `params.shape[:axis] + indices.shape + +/// params.shape[axis + 1:]` where: +/// +/// ```python +/// # Scalar indices (output is rank(params) - 1). +/// output[a_0, ..., a_n, b_0, ..., b_n] = +/// params[a_0, ..., a_n, indices, b_0, ..., b_n] +/// +/// # Vector indices (output is rank(params)). +/// output[a_0, ..., a_n, i, b_0, ..., b_n] = +/// params[a_0, ..., a_n, indices[i], b_0, ..., b_n] +/// +/// # Higher rank indices (output is rank(params) + rank(indices) - 1). +/// output[a_0, ..., a_n, i, ..., j, b_0, ... b_n] = +/// params[a_0, ..., a_n, indices[i, ..., j], b_0, ..., b_n] +/// ``` +/// +///
+/// +///
+/// +/// Note that on CPU, if an out of bound index is found, an error is returned. +/// On GPU, if an out of bound index is found, a 0 is stored in the +/// corresponding output value. +/// +/// See also `tf.batch_gather` and `tf.gather_nd`. +/// +/// - Parameters: +/// - params: The tensor from which to gather values. Must be at least rank +/// `axis + 1`. +/// - indices: Index tensor. Must be in range `[0, params.shape[axis])`. +/// - axis: The axis in `params` to gather `indices` from. Defaults to the first +/// dimension. Supports negative indexes. +/// +/// - Output output: Values from `params` gathered from indices given by `indices`, with +/// shape `params.shape[:axis] + indices.shape + params.shape[axis + 1:]`. +@inlinable @inline(__always) +public static func gatherV2< + Tparams: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar, + Taxis: BinaryInteger & TensorFlowScalar +>( + params: Tensor, + indices: Tensor, + axis: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("GatherV2", nOutputs) + op.updateAttribute("Tparams", Tparams.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("Taxis", Taxis.tensorFlowDataType) + op.addInput(params) + op.addInput(indices) + op.addInput(axis) + return op.execute(Int(1)) +} + +/// Re-configures the GCS block cache with the new configuration values. +/// +/// If the values are the same as already configured values, this op is a no-op. If +/// they are different, the current contents of the block cache is dropped, and a +/// new block cache is created fresh. +@inlinable @inline(__always) +public static func gcsConfigureBlockCache( + maxCacheSize: Tensor, + blockSize: Tensor, + maxStaleness: Tensor +) { + let nOutputs = 0 + let op = makeOp("GcsConfigureBlockCache", nOutputs) + op.addInput(maxCacheSize) + op.addInput(blockSize) + op.addInput(maxStaleness) + op.execute() +} + +/// Configures the credentials used by the GCS client of the local TF runtime. +/// +/// The json input can be of the format: +/// +/// 1. Refresh Token: +/// { +/// "client_id": "", +/// "client_secret": "", +/// "refresh_token: "", +/// "type": "authorized_user", +/// } +/// +/// 2. Service Account: +/// { +/// "type": "service_account", +/// "project_id": "", +/// "private_key_id": "", +/// "private_key": "------BEGIN PRIVATE KEY-----\n\n-----END PRIVATE KEY------\n", +/// "client_email": "@.iam.gserviceaccount.com", +/// "client_id": "", +/// # Some additional fields elided +/// } +/// +/// Note the credentials established through this method are shared across all +/// sessions run on this runtime. +/// +/// Note be sure to feed the inputs to this op to ensure the credentials are not +/// stored in a constant op within the graph that might accidentally be checkpointed +/// or in other ways be persisted or exfiltrated. +@inlinable @inline(__always) +public static func gcsConfigureCredentials( + json: StringTensor +) { + let nOutputs = 0 + let op = makeOp("GcsConfigureCredentials", nOutputs) + op.addInput(json) + op.execute() +} + +/// Generates serialized partition messages suitable for batch reads. +/// +/// This op should not be used directly by clients. Instead, the +/// bigquery_reader_ops.py file defines a clean interface to the reader. +/// +/// - Attrs: +/// - project_id: GCP project ID. +/// - dataset_id: BigQuery Dataset ID. +/// - table_id: Table to read. +/// - columns: List of columns to read. Leave empty to read all columns. +/// - timestamp_millis: Table snapshot timestamp in millis since epoch. Relative +/// (negative or zero) snapshot times are not allowed. For more details, see +/// 'Table Decorators' in BigQuery docs. +/// - num_partitions: Number of partitions to split the table into. +/// - test_end_point: Do not use. For testing purposes only. +/// +/// - Output partitions: Serialized table partitions. +@inlinable @inline(__always) +public static func generateBigQueryReaderPartitions( + projectId: String, + datasetId: String, + tableId: String, + columns: [String], + timestampMillis: Int64, + numPartitions: Int64, + testEndPoint: String +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("GenerateBigQueryReaderPartitions", nOutputs) + op.updateAttribute("project_id", projectId) + op.updateAttribute("dataset_id", datasetId) + op.updateAttribute("table_id", tableId) + op.updateAttribute("columns", columns) + op.updateAttribute("timestamp_millis", timestampMillis) + op.updateAttribute("num_partitions", numPartitions) + op.updateAttribute("test_end_point", testEndPoint) + return op.execute(Int(1)) +} + +/// Given a path to new and old vocabulary files, returns a remapping Tensor of +/// +/// length `num_new_vocab`, where `remapping[i]` contains the row number in the old +/// vocabulary that corresponds to row `i` in the new vocabulary (starting at line +/// `new_vocab_offset` and up to `num_new_vocab` entities), or `-1` if entry `i` +/// in the new vocabulary is not in the old vocabulary. The old vocabulary is +/// constrained to the first `old_vocab_size` entries if `old_vocab_size` is not the +/// default value of -1. +/// +/// `num_vocab_offset` enables +/// use in the partitioned variable case, and should generally be set through +/// examining partitioning info. The format of the files should be a text file, +/// with each line containing a single entity within the vocabulary. +/// +/// For example, with `new_vocab_file` a text file containing each of the following +/// elements on a single line: `[f0, f1, f2, f3]`, old_vocab_file = [f1, f0, f3], +/// `num_new_vocab = 3, new_vocab_offset = 1`, the returned remapping would be +/// `[0, -1, 2]`. +/// +/// The op also returns a count of how many entries in the new vocabulary +/// were present in the old vocabulary, which is used to calculate the number of +/// values to initialize in a weight matrix remapping +/// +/// This functionality can be used to remap both row vocabularies (typically, +/// features) and column vocabularies (typically, classes) from TensorFlow +/// checkpoints. Note that the partitioning logic relies on contiguous vocabularies +/// corresponding to div-partitioned variables. Moreover, the underlying remapping +/// uses an IndexTable (as opposed to an inexact CuckooTable), so client code should +/// use the corresponding index_table_from_file() as the FeatureColumn framework +/// does (as opposed to tf.feature_to_id(), which uses a CuckooTable). +/// +/// - Parameters: +/// - new_vocab_file: Path to the new vocab file. +/// - old_vocab_file: Path to the old vocab file. +/// +/// - Attrs: +/// - new_vocab_offset: How many entries into the new vocab file to start reading. +/// - num_new_vocab: Number of entries in the new vocab file to remap. +/// - old_vocab_size: Number of entries in the old vocab file to consider. If -1, +/// use the entire old vocabulary. +/// +/// - Outputs: +/// - remapping: A Tensor of length num_new_vocab where the element at index i +/// is equal to the old ID that maps to the new ID i. This element is -1 for any +/// new ID that is not found in the old vocabulary. +/// - num_present: Number of new vocab entries found in old vocab. +@inlinable @inline(__always) +public static func generateVocabRemapping( + newVocabFile: StringTensor, + oldVocabFile: StringTensor, + newVocabOffset: Int64, + numNewVocab: Int64, + oldVocabSize: Int64 = -1 +) -> (remapping: Tensor, numPresent: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("GenerateVocabRemapping", nOutputs) + op.updateAttribute("new_vocab_offset", newVocabOffset) + op.updateAttribute("num_new_vocab", numNewVocab) + op.updateAttribute("old_vocab_size", oldVocabSize) + op.addInput(newVocabFile) + op.addInput(oldVocabFile) + return op.execute(Int(1), Int(1)) +} + +/// Creates a dataset that invokes a function to generate elements. +@inlinable @inline(__always) +public static func generatorDataset< + InitfuncIn: TensorGroup, + InitfuncOut: TensorGroup, + NextfuncIn: TensorGroup, + NextfuncOut: TensorGroup, + FinalizefuncIn: TensorGroup, + FinalizefuncOut: TensorGroup, + TinitFuncArgs: TensorArrayProtocol, + TnextFuncArgs: TensorArrayProtocol, + TfinalizeFuncArgs: TensorArrayProtocol +>( + initFuncOtherArgs: TinitFuncArgs, + nextFuncOtherArgs: TnextFuncArgs, + finalizeFuncOtherArgs: TfinalizeFuncArgs, + initFunc: (InitfuncIn) -> InitfuncOut, + nextFunc: (NextfuncIn) -> NextfuncOut, + finalizeFunc: (FinalizefuncIn) -> FinalizefuncOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("GeneratorDataset", nOutputs) + op.updateAttribute("init_func", initFunc) + op.updateAttribute("next_func", nextFunc) + op.updateAttribute("finalize_func", finalizeFunc) + op.updateAttribute("Tinit_func_args", initFuncOtherArgs._typeList) + op.updateAttribute("Tnext_func_args", nextFuncOtherArgs._typeList) + op.updateAttribute("Tfinalize_func_args", finalizeFuncOtherArgs._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInputList(initFuncOtherArgs) + op.addInputList(nextFuncOtherArgs) + op.addInputList(finalizeFuncOtherArgs) + return op.execute(Int(1)) +} + +/// Store the input tensor in the state of the current session. +/// +/// - Parameter value: The tensor to be stored. +/// +/// - Output handle: The handle for the tensor stored in the session state, represented +/// as a string. +@inlinable @inline(__always) +public static func getSessionHandle( + value: Tensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("GetSessionHandle", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + return op.execute(Int(1)) +} + +/// Store the input tensor in the state of the current session. +/// +/// - Parameter value: The tensor to be stored. +/// +/// - Output handle: The handle for the tensor stored in the session state, represented +/// as a ResourceHandle object. +@inlinable @inline(__always) +public static func getSessionHandleV2( + value: Tensor +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("GetSessionHandleV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + return op.execute(Int(1)) +} + +/// Get the value of the tensor specified by its handle. +/// +/// - Parameter handle: The handle for a tensor stored in the session state. +/// +/// - Attr dtype: The type of the output value. +/// +/// - Output value: The tensor for the given handle. +@inlinable @inline(__always) +public static func getSessionTensor( + handle: StringTensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("GetSessionTensor", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(handle) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func graphDefVersion( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("GraphDefVersion", nOutputs) + + return op.execute(Int(1)) +} + +/// Returns the truth value of (x > y) element-wise. +/// +/// *NOTE*: `Greater` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func greater( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Greater", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns the truth value of (x >= y) element-wise. +/// +/// *NOTE*: `GreaterEqual` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func greaterEqual( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("GreaterEqual", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Gives a guarantee to the TF runtime that the input tensor is a constant. +/// +/// The runtime is then free to make optimizations based on this. +/// +/// Only accepts value typed tensors as inputs and rejects resource variable handles +/// as input. +/// +/// Returns the input tensor without modification. +@inlinable @inline(__always) +public static func guaranteeConst( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("GuaranteeConst", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Convert one or more images from HSV to RGB. +/// +/// Outputs a tensor of the same shape as the `images` tensor, containing the RGB +/// value of the pixels. The output is only well defined if the value in `images` +/// are in `[0,1]`. +/// +/// See `rgb_to_hsv` for a description of the HSV encoding. +/// +/// - Parameter images: 1-D or higher rank. HSV data to convert. Last dimension must be size 3. +/// +/// - Output output: `images` converted to RGB. +@inlinable @inline(__always) +public static func hSVToRGB( + images: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("HSVToRGB", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + return op.execute(Int(1)) +} + +/// Creates a non-initialized hash table. +/// +/// This op creates a hash table, specifying the type of its keys and values. +/// Before using the table you will have to initialize it. After initialization the +/// table will be immutable. +/// +/// - Attrs: +/// - container: If non-empty, this table is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this table is shared under the given name across +/// multiple sessions. +/// - use_node_name_sharing: If true and shared_name is empty, the table is shared +/// using the node name. +/// - key_dtype: Type of the table keys. +/// - value_dtype: Type of the table values. +/// +/// - Output table_handle: Handle to a table. +@inlinable @inline(__always) +public static func hashTableV2( + container: String, + sharedName: String, + useNodeNameSharing: Bool = false, + keyDtype: TensorDataType, + valueDtype: TensorDataType +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("HashTableV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("use_node_name_sharing", useNodeNameSharing) + op.updateAttribute("key_dtype", keyDtype) + op.updateAttribute("value_dtype", valueDtype) + return op.execute(Int(1)) +} + +/// Return histogram of values. +/// +/// Given the tensor `values`, this operation returns a rank 1 histogram counting +/// the number of entries in `values` that fall into every bin. The bins are +/// equal width and determined by the arguments `value_range` and `nbins`. +/// +/// ```python +/// # Bins will be: (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf) +/// nbins = 5 +/// value_range = [0.0, 5.0] +/// new_values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15] +/// +/// with tf.get_default_session() as sess: +/// hist = tf.histogram_fixed_width(new_values, value_range, nbins=5) +/// variables.global_variables_initializer().run() +/// sess.run(hist) => [2, 1, 1, 0, 2] +/// ``` +/// +/// - Parameters: +/// - values: Numeric `Tensor`. +/// - value_range: Shape [2] `Tensor` of same `dtype` as `values`. +/// values <= value_range[0] will be mapped to hist[0], +/// values >= value_range[1] will be mapped to hist[-1]. +/// - nbins: Scalar `int32 Tensor`. Number of histogram bins. +/// +/// - Output out: A 1-D `Tensor` holding histogram of values. +@inlinable @inline(__always) +public static func histogramFixedWidth< + T: Numeric & TensorFlowScalar, + Dtype: BinaryInteger & TensorFlowScalar +>( + _ values: Tensor, + valueRange: Tensor, + nbins: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("HistogramFixedWidth", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(values) + op.addInput(valueRange) + op.addInput(nbins) + return op.execute(Int(1)) +} + +/// Outputs a `Summary` protocol buffer with a histogram. +/// +/// The generated +/// [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) +/// has one summary value containing a histogram for `values`. +/// +/// This op reports an `InvalidArgument` error if any value is not finite. +/// +/// - Parameters: +/// - tag: Scalar. Tag to use for the `Summary.Value`. +/// - values: Any shape. Values to use to build the histogram. +/// +/// - Output summary: Scalar. Serialized `Summary` protocol buffer. +@inlinable @inline(__always) +public static func histogramSummary( + tag: StringTensor, + _ values: Tensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("HistogramSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(tag) + op.addInput(values) + return op.execute(Int(1)) +} + +/// Inverse fast Fourier transform. +/// +/// Computes the inverse 1-dimensional discrete Fourier transform over the +/// inner-most dimension of `input`. +/// +/// - Parameter input: A complex tensor. +/// +/// - Output output: A complex tensor of the same shape as `input`. The inner-most +/// dimension of `input` is replaced with its inverse 1D Fourier transform. +/// +/// @compatibility(numpy) +/// Equivalent to np.fft.ifft +/// @end_compatibility +@inlinable @inline(__always) +public static func iFFT( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("IFFT", nOutputs) + op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Inverse 2D fast Fourier transform. +/// +/// Computes the inverse 2-dimensional discrete Fourier transform over the +/// inner-most 2 dimensions of `input`. +/// +/// - Parameter input: A complex tensor. +/// +/// - Output output: A complex tensor of the same shape as `input`. The inner-most 2 +/// dimensions of `input` are replaced with their inverse 2D Fourier transform. +/// +/// @compatibility(numpy) +/// Equivalent to np.fft.ifft2 +/// @end_compatibility +@inlinable @inline(__always) +public static func iFFT2D( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("IFFT2D", nOutputs) + op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Inverse 3D fast Fourier transform. +/// +/// Computes the inverse 3-dimensional discrete Fourier transform over the +/// inner-most 3 dimensions of `input`. +/// +/// - Parameter input: A complex64 tensor. +/// +/// - Output output: A complex64 tensor of the same shape as `input`. The inner-most 3 +/// dimensions of `input` are replaced with their inverse 3D Fourier transform. +/// +/// @compatibility(numpy) +/// Equivalent to np.fft.ifftn with 3 dimensions. +/// @end_compatibility +@inlinable @inline(__always) +public static func iFFT3D( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("IFFT3D", nOutputs) + op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Return a tensor with the same shape and contents as the input tensor or value. +@inlinable @inline(__always) +public static func identity( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Identity", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Returns a list of tensors with the same shapes and contents as the input +/// +/// tensors. +/// +/// This op can be used to override the gradient for complicated functions. For +/// example, suppose y = f(x) and we wish to apply a custom function g for backprop +/// such that dx = g(dy). In Python, +/// +/// ```python +/// with tf.get_default_graph().gradient_override_map( +/// {'IdentityN': 'OverrideGradientWithG'}): +/// y, _ = identity_n([f(x), x]) +/// +/// @tf.RegisterGradient('OverrideGradientWithG') +/// def ApplyG(op, dy, _): +/// return [None, g(dy)] # Do not backprop to f(x). +/// ``` +@inlinable @inline(__always) +public static func identityN( + _ input: T +) -> T { + let nOutputs = Int(input._typeList.count) + let op = makeOp("IdentityN", nOutputs) + op.updateAttribute("T", input._typeList) + op.addInputList(input) + return op.execute(Int(input._typeList.count)) +} + +/// A Reader that outputs the queued work as both the key and value. +/// +/// To use, enqueue strings in a Queue. ReaderRead will take the front +/// work string and output (work, work). +/// +/// - Attrs: +/// - container: If non-empty, this reader is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this reader is named in the given bucket +/// with this shared_name. Otherwise, the node name is used instead. +/// +/// - Output reader_handle: The handle to reference the Reader. +@inlinable @inline(__always) +public static func identityReaderV2( + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("IdentityReaderV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// output = cond ? then_branch(input) : else_branch(input) +/// +/// - Parameters: +/// - cond: A Tensor. If the tensor is a scalar of non-boolean type, the +/// scalar is converted to a boolean according to the +/// following rule: if the scalar is a numerical value, non-zero means +/// `True` and zero means False; if the scalar is a string, non-empty +/// means `True` and empty means `False`. If the tensor is not a scalar, +/// being empty means False and being non-empty means True. +/// - input: A list of input tensors. +/// +/// - Attrs: +/// - Tin: A list of input types. +/// - Tout: A list of output types. +/// - then_branch: A function that takes 'inputs' and returns a list of tensors, whose +/// types are the same as what else_branch returns. +/// - else_branch: A function that takes 'inputs' and returns a list of tensors, whose +/// types are the same as what then_branch returns. +/// +/// - Output output: A list of return values. +@inlinable @inline(__always) +public static func if_< + Tcond: TensorFlowScalar, + Tin: TensorArrayProtocol, + Tout: TensorGroup, + ThenbranchIn: TensorGroup, + ThenbranchOut: TensorGroup, + ElsebranchIn: TensorGroup, + ElsebranchOut: TensorGroup +>( + cond: Tensor, + _ input: Tin, + thenBranch: (ThenbranchIn) -> ThenbranchOut, + elseBranch: (ElsebranchIn) -> ElsebranchOut, + outputShapes: [TensorShape?] +) -> Tout { + let nOutputs = Int(Tout._typeList.count) + let op = makeOp("If", nOutputs) + op.updateAttribute("Tcond", Tcond.tensorFlowDataType) + op.updateAttribute("Tin", input._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("then_branch", thenBranch) + op.updateAttribute("else_branch", elseBranch) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(cond) + op.addInputList(input) + return op.execute(Int(Tout._typeList.count)) +} + +/// Compute the lower regularized incomplete Gamma function `P(a, x)`. +/// +/// The lower regularized incomplete Gamma function is defined as: +/// +/// +/// \\(P(a, x) = gamma(a, x) / Gamma(a) = 1 - Q(a, x)\\) +/// +/// where +/// +/// \\(gamma(a, x) = \\int_{0}^{x} t^{a-1} exp(-t) dt\\) +/// +/// is the lower incomplete Gamma function. +/// +/// Note, above `Q(a, x)` (`Igammac`) is the upper regularized complete +/// Gamma function. +@inlinable @inline(__always) +public static func igamma( + _ a: Tensor, + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Igamma", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the gradient of `igamma(a, x)` wrt `a`. +@inlinable @inline(__always) +public static func igammaGradA( + _ a: Tensor, + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("IgammaGradA", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Compute the upper regularized incomplete Gamma function `Q(a, x)`. +/// +/// The upper regularized incomplete Gamma function is defined as: +/// +/// \\(Q(a, x) = Gamma(a, x) / Gamma(a) = 1 - P(a, x)\\) +/// +/// where +/// +/// \\(Gamma(a, x) = int_{x}^{\infty} t^{a-1} exp(-t) dt\\) +/// +/// is the upper incomplete Gama function. +/// +/// Note, above `P(a, x)` (`Igamma`) is the lower regularized complete +/// Gamma function. +@inlinable @inline(__always) +public static func igammac( + _ a: Tensor, + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Igammac", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Returns the imaginary part of a complex number. +/// +/// Given a tensor `input` of complex numbers, this operation returns a tensor of +/// type `float` that is the imaginary part of each element in `input`. All +/// elements in `input` must be complex numbers of the form \\(a + bj\\), where *a* +/// is the real part and *b* is the imaginary part returned by this operation. +/// +/// For example: +/// +/// ``` +/// # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] +/// tf.imag(input) ==> [4.75, 5.75] +/// ``` +@inlinable @inline(__always) +public static func imag< + T: TensorFlowScalar, + Tout: FloatingPoint & TensorFlowScalar +>( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Imag", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Returns immutable tensor from memory region. +/// +/// The current implementation memmaps the tensor from a file. +/// +/// - Attrs: +/// - dtype: Type of the returned tensor. +/// - shape: Shape of the returned tensor. +/// - memory_region_name: Name of readonly memory region used by the tensor, see +/// NewReadOnlyMemoryRegionFromFile in tensorflow::Env. +@inlinable @inline(__always) +public static func immutableConst( + shape: TensorShape?, + memoryRegionName: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ImmutableConst", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.updateAttribute("memory_region_name", memoryRegionName) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func importEvent( + writer: ResourceHandle, + event: StringTensor +) { + let nOutputs = 0 + let op = makeOp("ImportEvent", nOutputs) + op.addInput(writer) + op.addInput(event) + op.execute() +} + +@inlinable @inline(__always) +public static func inPolymorphicTwice( + _ a: [Tensor], + _ b: [Tensor] +) { + let nOutputs = 0 + let op = makeOp("InPolymorphicTwice", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", a.count) + op.updateAttribute("M", b.count) + op.addInputList(a) + op.addInputList(b) + op.execute() +} + +/// Says whether the targets are in the top `K` predictions. +/// +/// This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the +/// prediction for the target class is among the top `k` predictions among +/// all predictions for example `i`. Note that the behavior of `InTopK` differs +/// from the `TopK` op in its handling of ties; if multiple classes have the +/// same prediction value and straddle the top-`k` boundary, all of those +/// classes are considered to be in the top `k`. +/// +/// More formally, let +/// +/// \\(predictions_i\\) be the predictions for all classes for example `i`, +/// \\(targets_i\\) be the target class for example `i`, +/// \\(out_i\\) be the output for example `i`, +/// +/// $$out_i = predictions_{i, targets_i} \in TopKIncludingTies(predictions_i)$$ +/// +/// - Parameters: +/// - predictions: A `batch_size` x `classes` tensor. +/// - targets: A `batch_size` vector of class ids. +/// +/// - Attr k: Number of top elements to look at for computing precision. +/// +/// - Output precision: Computed Precision at `k` as a `bool Tensor`. +@inlinable @inline(__always) +public static func inTopK( + predictions: Tensor, + targets: Tensor, + k: Int64 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("InTopK", nOutputs) + op.updateAttribute("k", k) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(predictions) + op.addInput(targets) + return op.execute(Int(1)) +} + +/// Says whether the targets are in the top `K` predictions. +/// +/// This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the +/// prediction for the target class is among the top `k` predictions among +/// all predictions for example `i`. Note that the behavior of `InTopK` differs +/// from the `TopK` op in its handling of ties; if multiple classes have the +/// same prediction value and straddle the top-`k` boundary, all of those +/// classes are considered to be in the top `k`. +/// +/// More formally, let +/// +/// \\(predictions_i\\) be the predictions for all classes for example `i`, +/// \\(targets_i\\) be the target class for example `i`, +/// \\(out_i\\) be the output for example `i`, +/// +/// $$out_i = predictions_{i, targets_i} \in TopKIncludingTies(predictions_i)$$ +/// +/// - Parameters: +/// - predictions: A `batch_size` x `classes` tensor. +/// - targets: A `batch_size` vector of class ids. +/// - k: Number of top elements to look at for computing precision. +/// +/// - Output precision: Computed precision at `k` as a `bool Tensor`. +@inlinable @inline(__always) +public static func inTopKV2( + predictions: Tensor, + targets: Tensor, + k: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("InTopKV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(predictions) + op.addInput(targets) + op.addInput(k) + return op.execute(Int(1)) +} + +/// A placeholder op for a value that will be fed into the computation. +/// +/// - Attrs: +/// - dtype: The type of elements in the tensor. +/// - shape: The shape of the tensor. +/// +/// - Output output: A tensor that will be provided using the infeed mechanism. +@inlinable @inline(__always) +public static func infeedDequeue( + shape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("InfeedDequeue", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + return op.execute(Int(1)) +} + +/// Fetches multiple values from infeed as an XLA tuple. +/// +/// - Attrs: +/// - dtypes: The element types of each element in `outputs`. +/// - shapes: The shapes of each tensor in `outputs`. +/// +/// - Output outputs: A list of tensors that will be provided using the infeed mechanism. +@inlinable @inline(__always) +public static func infeedDequeueTuple( + shapes: [TensorShape?] +) -> Dtypes { + let nOutputs = Int(Dtypes._typeList.count) + let op = makeOp("InfeedDequeueTuple", nOutputs) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("shapes", shapes) + return op.execute(Int(Dtypes._typeList.count)) +} + +/// An op which feeds a single Tensor value into the computation. +/// +/// - Parameter input: A tensor that will be provided using the infeed mechanism. +/// +/// - Attrs: +/// - dtype: The type of elements in the tensor. +/// - shape: The shape of the tensor. +/// - layout: A vector holding the requested layout in minor-to-major sequence. +/// If a layout attribute is passed, but its values are all -1, the layout will +/// be computed by the infeed operation. +/// - device_ordinal: The TPU device to use. This should be -1 when the Op +/// is running on a TPU device, and >= 0 when the Op is running on the CPU +/// device. +@inlinable @inline(__always) +public static func infeedEnqueue( + _ input: Tensor, + shape: TensorShape?, + layout: [Int32], + deviceOrdinal: Int64 = -1 +) { + let nOutputs = 0 + let op = makeOp("InfeedEnqueue", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.updateAttribute("layout", layout) + op.updateAttribute("device_ordinal", deviceOrdinal) + op.addInput(input) + op.execute() +} + +/// An op which enqueues prelinearized buffer into TPU infeed. +/// +/// - Parameter input: A variant tensor representing linearized output. +/// +/// - Attr device_ordinal: The TPU device to use. This should be -1 when the Op is running on a TPU device +/// and = 0 when the Op is running on the CPU device. +@inlinable @inline(__always) +public static func infeedEnqueuePrelinearizedBuffer( + _ input: VariantHandle, + deviceOrdinal: Int64 = -1 +) { + let nOutputs = 0 + let op = makeOp("InfeedEnqueuePrelinearizedBuffer", nOutputs) + op.updateAttribute("device_ordinal", deviceOrdinal) + op.addInput(input) + op.execute() +} + +/// Feeds multiple Tensor values into the computation as an XLA tuple. +/// +/// - Parameter inputs: A list of tensors that will be provided using the infeed mechanism. +/// +/// - Attrs: +/// - dtypes: The element types of each element in `inputs`. +/// - shapes: The shapes of each tensor in `inputs`. +/// - layouts: A vector holding the requested layout in minor-to-major sequence for +/// all the tuple shapes, in the order the shapes appear in the "shapes" input. +/// The layout elements for a sub-shape can be set to -1, in which case the +/// corresponding layout will be computed by the infeed operation. +/// - device_ordinal: The TPU device to use. This should be -1 when the Op +/// is running on a TPU device, and >= 0 when the Op is running on the CPU +/// device. +@inlinable @inline(__always) +public static func infeedEnqueueTuple( + inputs: Dtypes, + shapes: [TensorShape?], + layouts: [Int32], + deviceOrdinal: Int64 = -1 +) { + let nOutputs = 0 + let op = makeOp("InfeedEnqueueTuple", nOutputs) + op.updateAttribute("dtypes", inputs._typeList) + op.updateAttribute("shapes", shapes) + op.updateAttribute("layouts", layouts) + op.updateAttribute("device_ordinal", deviceOrdinal) + op.addInputList(inputs) + op.execute() +} + +/// Initializes a table from a text file. +/// +/// It inserts one key-value pair into the table for each line of the file. +/// The key and value is extracted from the whole line content, elements from the +/// split line based on `delimiter` or the line number (starting from zero). +/// Where to extract the key and value from a line is specified by `key_index` and +/// `value_index`. +/// +/// - A value of -1 means use the line number(starting from zero), expects `int64`. +/// - A value of -2 means use the whole line content, expects `string`. +/// - A value >= 0 means use the index (starting at zero) of the split line based +/// on `delimiter`. +/// +/// - Parameters: +/// - table_handle: Handle to a table which will be initialized. +/// - filename: Filename of a vocabulary text file. +/// +/// - Attrs: +/// - key_index: Column index in a line to get the table `key` values from. +/// - value_index: Column index that represents information of a line to get the table +/// `value` values from. +/// - vocab_size: Number of elements of the file, use -1 if unknown. +/// - delimiter: Delimiter to separate fields in a line. +@inlinable @inline(__always) +public static func initializeTableFromTextFileV2( + tableHandle: ResourceHandle, + filename: StringTensor, + keyIndex: Int64, + valueIndex: Int64, + vocabSize: Int64 = -1, + delimiter: String = "\t" +) { + let nOutputs = 0 + let op = makeOp("InitializeTableFromTextFileV2", nOutputs) + op.updateAttribute("key_index", keyIndex) + op.updateAttribute("value_index", valueIndex) + op.updateAttribute("vocab_size", vocabSize) + op.updateAttribute("delimiter", delimiter) + op.addInput(tableHandle) + op.addInput(filename) + op.execute() +} + +/// Table initializer that takes two tensors for keys and values respectively. +/// +/// - Parameters: +/// - table_handle: Handle to a table which will be initialized. +/// - keys: Keys of type Tkey. +/// - values: Values of type Tval. +@inlinable @inline(__always) +public static func initializeTableV2< + Tkey: TensorFlowScalar, + Tval: TensorFlowScalar +>( + tableHandle: ResourceHandle, + keys: Tensor, + _ values: Tensor +) { + let nOutputs = 0 + let op = makeOp("InitializeTableV2", nOutputs) + op.updateAttribute("Tkey", Tkey.tensorFlowDataType) + op.updateAttribute("Tval", Tval.tensorFlowDataType) + op.addInput(tableHandle) + op.addInput(keys) + op.addInput(values) + op.execute() +} + +/// Adds v into specified rows of x. +/// +/// Computes y = x; y[i, :] += v; return y. +/// +/// - Parameters: +/// - x: A `Tensor` of type T. +/// - i: A vector. Indices into the left-most dimension of `x`. +/// - v: A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. +/// +/// - Output y: A `Tensor` of type T. An alias of `x`. The content of `y` is undefined if there are duplicates in `i`. +@inlinable @inline(__always) +public static func inplaceAdd( + _ x: Tensor, + i: Tensor, + v: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("InplaceAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(i) + op.addInput(v) + return op.execute(Int(1)) +} + +/// Subtracts `v` into specified rows of `x`. +/// +/// Computes y = x; y[i, :] -= v; return y. +/// +/// - Parameters: +/// - x: A `Tensor` of type T. +/// - i: A vector. Indices into the left-most dimension of `x`. +/// - v: A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. +/// +/// - Output y: A `Tensor` of type T. An alias of `x`. The content of `y` is undefined if there are duplicates in `i`. +@inlinable @inline(__always) +public static func inplaceSub( + _ x: Tensor, + i: Tensor, + v: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("InplaceSub", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(i) + op.addInput(v) + return op.execute(Int(1)) +} + +/// Updates specified rows with values in `v`. +/// +/// Computes `x[i, :] = v; return x`. +/// +/// - Parameters: +/// - x: A tensor of type `T`. +/// - i: A vector. Indices into the left-most dimension of `x`. +/// - v: A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. +/// +/// - Output y: A `Tensor` of type T. An alias of `x`. The content of `y` is undefined if there are duplicates in `i`. +@inlinable @inline(__always) +public static func inplaceUpdate( + _ x: Tensor, + i: Tensor, + v: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("InplaceUpdate", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(i) + op.addInput(v) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func int64Output( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Int64Output", nOutputs) + + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func intAttr( + foo: Int64 = 1 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("IntAttr", nOutputs) + op.updateAttribute("foo", foo) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func intInput( + _ a: Tensor +) { + let nOutputs = 0 + let op = makeOp("IntInput", nOutputs) + op.addInput(a) + op.execute() +} + +@inlinable @inline(__always) +public static func intInputFloatInput( + _ a: Tensor, + _ b: Tensor +) { + let nOutputs = 0 + let op = makeOp("IntInputFloatInput", nOutputs) + op.addInput(a) + op.addInput(b) + op.execute() +} + +@inlinable @inline(__always) +public static func intInputIntOutput( + _ a: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("IntInputIntOutput", nOutputs) + op.addInput(a) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func intOutput( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("IntOutput", nOutputs) + + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func intOutputFloatOutput( +) -> (a: Tensor, b: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("IntOutputFloatOutput", nOutputs) + + return op.execute(Int(1), Int(1)) +} + +/// Creates a dataset that applies `f` to the outputs of `input_dataset`. +/// +/// Unlike MapDataset, the `f` in InterleaveDataset is expected to return +/// a Dataset variant, and InterleaveDataset will flatten successive +/// results into a single Dataset. Unlike FlatMapDataset, +/// InterleaveDataset will interleave sequences of up to `block_length` +/// consecutive elements from `cycle_length` input elements. +/// +/// - Attr f: A function mapping elements of `input_dataset`, concatenated with +/// `other_arguments`, to a Dataset variant that contains elements matching +/// `output_types` and `output_shapes`. +@inlinable @inline(__always) +public static func interleaveDataset< + FIn: TensorGroup, + FOut: TensorGroup, + Targuments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + otherArguments: Targuments, + cycleLength: Tensor, + blockLength: Tensor, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("InterleaveDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(otherArguments) + op.addInput(cycleLength) + op.addInput(blockLength) + return op.execute(Int(1)) +} + +/// Computes the reciprocal of x element-wise. +/// +/// I.e., \\(y = 1 / x\\). +@inlinable @inline(__always) +public static func inv( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Inv", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the gradient for the inverse of `x` wrt its input. +/// +/// Specifically, `grad = -dy * y*y`, where `y = 1/x`, and `dy` +/// is the corresponding input gradient. +@inlinable @inline(__always) +public static func invGrad( + _ y: Tensor, + dy: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("InvGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(dy) + return op.execute(Int(1)) +} + +/// Flips all bits elementwise. +/// +/// The result will have exactly those bits set, that are not set in `x`. The +/// computation is performed on the underlying representation of x. +@inlinable @inline(__always) +public static func invert( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Invert", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the inverse permutation of a tensor. +/// +/// This operation computes the inverse of an index permutation. It takes a 1-D +/// integer tensor `x`, which represents the indices of a zero-based array, and +/// swaps each value with its index position. In other words, for an output tensor +/// `y` and an input tensor `x`, this operation computes the following: +/// +/// `y[x[i]] = i for i in [0, 1, ..., len(x) - 1]` +/// +/// The values must include 0. There can be no duplicate values or negative values. +/// +/// For example: +/// +/// ``` +/// # tensor `x` is [3, 4, 0, 2, 1] +/// invert_permutation(x) ==> [2, 4, 3, 0, 1] +/// ``` +/// +/// - Parameter x: 1-D. +/// +/// - Output y: 1-D. +@inlinable @inline(__always) +public static func invertPermutation( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("InvertPermutation", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Checks whether a tree ensemble has been initialized. +/// +/// - Parameter tree_ensemble_handle: Handle to the tree ensemble resouce. +/// +/// - Output is_initialized: output boolean on whether it is initialized or not. +@inlinable @inline(__always) +public static func isBoostedTreesEnsembleInitialized( + treeEnsembleHandle: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("IsBoostedTreesEnsembleInitialized", nOutputs) + op.addInput(treeEnsembleHandle) + return op.execute(Int(1)) +} + +/// Checks whether a quantile stream has been initialized. +/// +/// An Op that checks if quantile stream resource is initialized. +/// +/// - Parameter quantile_stream_resource_handle: resource; The reference to quantile stream resource handle. +/// +/// - Output is_initialized: bool; True if the resource is initialized, False otherwise. +@inlinable @inline(__always) +public static func isBoostedTreesQuantileStreamResourceInitialized( + quantileStreamResourceHandle: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("IsBoostedTreesQuantileStreamResourceInitialized", nOutputs) + op.addInput(quantileStreamResourceHandle) + return op.execute(Int(1)) +} + +/// Returns which elements of x are finite. +/// +/// @compatibility(numpy) +/// Equivalent to np.isfinite +/// @end_compatibility +@inlinable @inline(__always) +public static func isFinite( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("IsFinite", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Returns which elements of x are Inf. +/// +/// @compatibility(numpy) +/// Equivalent to np.isinf +/// @end_compatibility +@inlinable @inline(__always) +public static func isInf( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("IsInf", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Returns which elements of x are NaN. +/// +/// @compatibility(numpy) +/// Equivalent to np.isnan +/// @end_compatibility +@inlinable @inline(__always) +public static func isNan( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("IsNan", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// A container for an iterator resource. +/// +/// - Output handle: A handle to the iterator that can be passed to a "MakeIterator" +/// or "IteratorGetNext" op. +@inlinable @inline(__always) +public static func iterator( + sharedName: String, + container: String, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("Iterator", nOutputs) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("container", container) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + return op.execute(Int(1)) +} + +/// Converts the given string representing a handle to an iterator to a resource. +/// +/// - Parameter string_handle: A string representation of the given handle. +/// +/// - Attrs: +/// - output_types: If specified, defines the type of each tuple component in an +/// element produced by the resulting iterator. +/// - output_shapes: If specified, defines the shape of each tuple component in an +/// element produced by the resulting iterator. +/// +/// - Output resource_handle: A handle to an iterator resource. +@inlinable @inline(__always) +public static func iteratorFromStringHandle( + stringHandle: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("IteratorFromStringHandle", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(stringHandle) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func iteratorFromStringHandleV2( + stringHandle: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("IteratorFromStringHandleV2", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(stringHandle) + return op.execute(Int(1)) +} + +/// Gets the next output from the given iterator . +@inlinable @inline(__always) +public static func iteratorGetNext( + iterator: ResourceHandle, + outputShapes: [TensorShape?] +) -> OutputTypes { + let nOutputs = Int(OutputTypes._typeList.count) + let op = makeOp("IteratorGetNext", nOutputs) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(iterator) + return op.execute(Int(OutputTypes._typeList.count)) +} + +/// Gets the next output from the given iterator as an Optional variant. +@inlinable @inline(__always) +public static func iteratorGetNextAsOptional( + iterator: ResourceHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("IteratorGetNextAsOptional", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(iterator) + return op.execute(Int(1)) +} + +/// Gets the next output from the given iterator. +/// +/// This operation is a synchronous version IteratorGetNext. It should only be used +/// in situations where the iterator does not block the calling thread, or where +/// the calling thread is not a member of the thread pool used to execute parallel +/// operations (e.g. in eager mode). +@inlinable @inline(__always) +public static func iteratorGetNextSync( + iterator: ResourceHandle, + outputShapes: [TensorShape?] +) -> OutputTypes { + let nOutputs = Int(OutputTypes._typeList.count) + let op = makeOp("IteratorGetNextSync", nOutputs) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(iterator) + return op.execute(Int(OutputTypes._typeList.count)) +} + +/// Converts the given `resource_handle` representing an iterator to a string. +/// +/// - Parameter resource_handle: A handle to an iterator resource. +/// +/// - Output string_handle: A string representation of the given handle. +@inlinable @inline(__always) +public static func iteratorToStringHandle( + resourceHandle: ResourceHandle +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("IteratorToStringHandle", nOutputs) + op.addInput(resourceHandle) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func iteratorV2( + sharedName: String, + container: String, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("IteratorV2", nOutputs) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("container", container) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + return op.execute(Int(1)) +} + +/// Returns the index of a data point that should be added to the seed set. +/// +/// Entries in distances are assumed to be squared distances of candidate points to +/// the already sampled centers in the seed set. The op constructs one Markov chain +/// of the k-MC^2 algorithm and returns the index of one candidate point to be added +/// as an additional cluster center. +/// +/// - Parameters: +/// - distances: Vector with squared distances to the closest previously sampled cluster center +/// for each candidate point. +/// - seed: Scalar. Seed for initializing the random number generator. +/// +/// - Output index: Scalar with the index of the sampled point. +@inlinable @inline(__always) +public static func kMC2ChainInitialization( + distances: Tensor, + seed: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("KMC2ChainInitialization", nOutputs) + op.addInput(distances) + op.addInput(seed) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func kernelLabel( +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("KernelLabel", nOutputs) + + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func kernelLabelRequired( + _ input: Tensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("KernelLabelRequired", nOutputs) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Selects num_to_sample rows of input using the KMeans++ criterion. +/// +/// Rows of points are assumed to be input points. One row is selected at random. +/// Subsequent rows are sampled with probability proportional to the squared L2 +/// distance from the nearest row selected thus far till num_to_sample rows have +/// been sampled. +/// +/// - Parameters: +/// - points: Matrix of shape (n, d). Rows are assumed to be input points. +/// - num_to_sample: Scalar. The number of rows to sample. This value must not be larger than n. +/// - seed: Scalar. Seed for initializing the random number generator. +/// - num_retries_per_sample: Scalar. For each row that is sampled, this parameter +/// specifies the number of additional points to draw from the current +/// distribution before selecting the best. If a negative value is specified, a +/// heuristic is used to sample O(log(num_to_sample)) additional points. +/// +/// - Output samples: Matrix of shape (num_to_sample, d). The sampled rows. +@inlinable @inline(__always) +public static func kmeansPlusPlusInitialization( + points: Tensor, + numToSample: Tensor, + seed: Tensor, + numRetriesPerSample: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("KmeansPlusPlusInitialization", nOutputs) + op.addInput(points) + op.addInput(numToSample) + op.addInput(seed) + op.addInput(numRetriesPerSample) + return op.execute(Int(1)) +} + +/// L2 Loss. +/// +/// Computes half the L2 norm of a tensor without the `sqrt`: +/// +/// output = sum(t ** 2) / 2 +/// +/// - Parameter t: Typically 2-D, but may have any dimensions. +/// +/// - Output output: 0-D. +@inlinable @inline(__always) +public static func l2Loss( + t: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("L2Loss", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(t) + return op.execute(Int(1)) +} + +/// Local Response Normalization. +/// +/// The 4-D `input` tensor is treated as a 3-D array of 1-D vectors (along the last +/// dimension), and each vector is normalized independently. Within a given vector, +/// each component is divided by the weighted, squared sum of inputs within +/// `depth_radius`. In detail, +/// +/// sqr_sum[a, b, c, d] = +/// sum(input[a, b, c, d - depth_radius : d + depth_radius + 1] ** 2) +/// output = input / (bias + alpha * sqr_sum) ** beta +/// +/// For details, see [Krizhevsky et al., ImageNet classification with deep +/// convolutional neural networks (NIPS 2012)](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks). +/// +/// - Parameter input: 4-D. +/// +/// - Attrs: +/// - depth_radius: 0-D. Half-width of the 1-D normalization window. +/// - bias: An offset (usually positive to avoid dividing by 0). +/// - alpha: A scale factor, usually positive. +/// - beta: An exponent. +@inlinable @inline(__always) +public static func lRN( + _ input: Tensor, + depthRadius: Int64 = 5, + bias: Double = 1, + alpha: Double = 1, + beta: Double = 0.5 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LRN", nOutputs) + op.updateAttribute("depth_radius", depthRadius) + op.updateAttribute("bias", bias) + op.updateAttribute("alpha", alpha) + op.updateAttribute("beta", beta) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Gradients for Local Response Normalization. +/// +/// - Parameters: +/// - input_grads: 4-D with shape `[batch, height, width, channels]`. +/// - input_image: 4-D with shape `[batch, height, width, channels]`. +/// - output_image: 4-D with shape `[batch, height, width, channels]`. +/// +/// - Attrs: +/// - depth_radius: A depth radius. +/// - bias: An offset (usually > 0 to avoid dividing by 0). +/// - alpha: A scale factor, usually positive. +/// - beta: An exponent. +/// +/// - Output output: The gradients for LRN. +@inlinable @inline(__always) +public static func lRNGrad( + inputGrads: Tensor, + inputImage: Tensor, + outputImage: Tensor, + depthRadius: Int64 = 5, + bias: Double = 1, + alpha: Double = 1, + beta: Double = 0.5 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LRNGrad", nOutputs) + op.updateAttribute("depth_radius", depthRadius) + op.updateAttribute("bias", bias) + op.updateAttribute("alpha", alpha) + op.updateAttribute("beta", beta) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(inputGrads) + op.addInput(inputImage) + op.addInput(outputImage) + return op.execute(Int(1)) +} + +/// Computes the LSTM cell forward propagation for 1 time step. +/// +/// This implementation uses 1 weight matrix and 1 bias vector, and there's an +/// optional peephole connection. +/// +/// This kernel op implements the following mathematical equations: +/// +/// ```python +/// xh = [x, h_prev] +/// [i, f, ci, o] = xh * w + b +/// f = f + forget_bias +/// +/// if not use_peephole: +/// wci = wcf = wco = 0 +/// +/// i = sigmoid(cs_prev * wci + i) +/// f = sigmoid(cs_prev * wcf + f) +/// ci = tanh(ci) +/// +/// cs = ci .* i + cs_prev .* f +/// cs = clip(cs, cell_clip) +/// +/// o = sigmoid(cs * wco + o) +/// co = tanh(cs) +/// h = co .* o +/// ``` +/// +/// - Parameters: +/// - x: The input to the LSTM cell, shape (batch_size, num_inputs). +/// - cs_prev: Value of the cell state at previous time step. +/// - h_prev: Output of the previous cell at previous time step. +/// - w: The weight matrix. +/// - wci: The weight matrix for input gate peephole connection. +/// - wcf: The weight matrix for forget gate peephole connection. +/// - wco: The weight matrix for output gate peephole connection. +/// - b: The bias vector. +/// +/// - Attrs: +/// - forget_bias: The forget gate bias. +/// - cell_clip: Value to clip the 'cs' value to. +/// - use_peephole: Whether to use peephole weights. +/// +/// - Outputs: +/// - i: The input gate. +/// - cs: The cell state before the tanh. +/// - f: The forget gate. +/// - o: The output gate. +/// - ci: The cell input. +/// - co: The cell after the tanh. +/// - h: The output h vector. +@inlinable @inline(__always) +public static func lSTMBlockCell( + _ x: Tensor, + csPrev: Tensor, + hPrev: Tensor, + w: Tensor, + wci: Tensor, + wcf: Tensor, + wco: Tensor, + _ b: Tensor, + forgetBias: Double = 1, + cellClip: Double = 3, + usePeephole: Bool = false +) -> (i: Tensor, cs: Tensor, f: Tensor, o: Tensor, ci: Tensor, co: Tensor, h: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("LSTMBlockCell", nOutputs) + op.updateAttribute("forget_bias", forgetBias) + op.updateAttribute("cell_clip", cellClip) + op.updateAttribute("use_peephole", usePeephole) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(csPrev) + op.addInput(hPrev) + op.addInput(w) + op.addInput(wci) + op.addInput(wcf) + op.addInput(wco) + op.addInput(b) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// Computes the LSTM cell backward propagation for 1 timestep. +/// +/// This implementation is to be used in conjunction of LSTMBlockCell. +/// +/// - Parameters: +/// - x: The input to the LSTM cell, shape (batch_size, num_inputs). +/// - cs_prev: The previous cell state. +/// - h_prev: The previous h state. +/// - w: The weight matrix. +/// - wci: The weight matrix for input gate peephole connection. +/// - wcf: The weight matrix for forget gate peephole connection. +/// - wco: The weight matrix for output gate peephole connection. +/// - b: The bias vector. +/// - i: The input gate. +/// - cs: The cell state before the tanh. +/// - f: The forget gate. +/// - o: The output gate. +/// - ci: The cell input. +/// - co: The cell after the tanh. +/// - cs_grad: The current gradient of cs. +/// - h_grad: The gradient of h vector. +/// +/// - Attr use_peephole: Whether the cell uses peephole connections. +/// +/// - Outputs: +/// - cs_prev_grad: The gradient of cs to be back-propped. +/// - dicfo: The derivative wrt to [i, cs, f, o]. +/// - wci_grad: The gradient for wci to be back-propped. +/// - wcf_grad: The gradient for wcf to be back-propped. +/// - wco_grad: The gradient for wco to be back-propped. +@inlinable @inline(__always) +public static func lSTMBlockCellGrad( + _ x: Tensor, + csPrev: Tensor, + hPrev: Tensor, + w: Tensor, + wci: Tensor, + wcf: Tensor, + wco: Tensor, + _ b: Tensor, + i: Tensor, + cs: Tensor, + f: Tensor, + o: Tensor, + ci: Tensor, + co: Tensor, + csGrad: Tensor, + hGrad: Tensor, + usePeephole: Bool +) -> (csPrevGrad: Tensor, dicfo: Tensor, wciGrad: Tensor, wcfGrad: Tensor, wcoGrad: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("LSTMBlockCellGrad", nOutputs) + op.updateAttribute("use_peephole", usePeephole) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(csPrev) + op.addInput(hPrev) + op.addInput(w) + op.addInput(wci) + op.addInput(wcf) + op.addInput(wco) + op.addInput(b) + op.addInput(i) + op.addInput(cs) + op.addInput(f) + op.addInput(o) + op.addInput(ci) + op.addInput(co) + op.addInput(csGrad) + op.addInput(hGrad) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// Computes rectified linear: `max(features, features * alpha)`. +@inlinable @inline(__always) +public static func leakyRelu( + features: Tensor, + alpha: Double = 0.2 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LeakyRelu", nOutputs) + op.updateAttribute("alpha", alpha) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) +} + +/// Computes rectified linear gradients for a LeakyRelu operation. +/// +/// - Parameters: +/// - gradients: The backpropagated gradients to the corresponding LeakyRelu operation. +/// - features: The features passed as input to the corresponding LeakyRelu operation, +/// OR the outputs of that operation (both work equivalently). +/// +/// - Output backprops: `gradients * (features > 0) + alpha * gradients * (featurs <= 0)`. +@inlinable @inline(__always) +public static func leakyReluGrad( + gradients: Tensor, + features: Tensor, + alpha: Double = 0.2 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LeakyReluGrad", nOutputs) + op.updateAttribute("alpha", alpha) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(features) + return op.execute(Int(1)) +} + +/// Generates labels for candidate sampling with a learned unigram distribution. +/// +/// See explanations of candidate sampling and the data formats at +/// go/candidate-sampling. +/// +/// For each batch, this op picks a single set of sampled candidate labels. +/// +/// The advantages of sampling candidates per-batch are simplicity and the +/// possibility of efficient dense matrix multiplication. The disadvantage is that +/// the sampled candidates must be chosen independently of the context and of the +/// true labels. +/// +/// - Parameter true_classes: A batch_size * num_true matrix, in which each row contains the +/// IDs of the num_true target_classes in the corresponding original label. +/// +/// - Attrs: +/// - num_true: Number of true labels per context. +/// - num_sampled: Number of candidates to randomly sample. +/// - unique: If unique is true, we sample with rejection, so that all sampled +/// candidates in a batch are unique. This requires some approximation to +/// estimate the post-rejection sampling probabilities. +/// - range_max: The sampler will sample integers from the interval [0, range_max). +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. +/// +/// - Outputs: +/// - sampled_candidates: A vector of length num_sampled, in which each element is +/// the ID of a sampled candidate. +/// - true_expected_count: A batch_size * num_true matrix, representing +/// the number of times each candidate is expected to occur in a batch +/// of sampled candidates. If unique=true, then this is a probability. +/// - sampled_expected_count: A vector of length num_sampled, for each sampled +/// candidate representing the number of times the candidate is expected +/// to occur in a batch of sampled candidates. If unique=true, then this is a +/// probability. +@inlinable @inline(__always) +public static func learnedUnigramCandidateSampler( + trueClasses: Tensor, + numTrue: Int64, + numSampled: Int64, + unique: Bool, + rangeMax: Int64, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> (sampledCandidates: Tensor, trueExpectedCount: Tensor, sampledExpectedCount: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("LearnedUnigramCandidateSampler", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("num_sampled", numSampled) + op.updateAttribute("unique", unique) + op.updateAttribute("range_max", rangeMax) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Elementwise computes the bitwise left-shift of `x` and `y`. +/// +/// If `y` is negative, or greater than or equal to the width of `x` in bits the +/// result is implementation defined. +@inlinable @inline(__always) +public static func leftShift( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LeftShift", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns the truth value of (x < y) element-wise. +/// +/// *NOTE*: `Less` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func less( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Less", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns the truth value of (x <= y) element-wise. +/// +/// *NOTE*: `LessEqual` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func lessEqual( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LessEqual", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Computes the log of the absolute value of `Gamma(x)` element-wise. +@inlinable @inline(__always) +public static func lgamma( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Lgamma", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Generates values in an interval. +/// +/// A sequence of `num` evenly-spaced values are generated beginning at `start`. +/// If `num > 1`, the values in the sequence increase by `stop - start / num - 1`, +/// so that the last one is exactly `stop`. +/// +/// For example: +/// +/// ``` +/// tf.linspace(10.0, 12.0, 3, name="linspace") => [ 10.0 11.0 12.0] +/// ``` +/// +/// - Parameters: +/// - start: 0-D tensor. First entry in the range. +/// - stop: 0-D tensor. Last entry in the range. +/// - num: 0-D tensor. Number of values to generate. +/// +/// - Output output: 1-D. The generated values. +@inlinable @inline(__always) +public static func linSpace< + T: FloatingPoint & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + start: Tensor, + stop: Tensor, + num: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LinSpace", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(start) + op.addInput(stop) + op.addInput(num) + return op.execute(Int(1)) +} + +/// Computes the difference between two lists of numbers or strings. +/// +/// Given a list `x` and a list `y`, this operation returns a list `out` that +/// represents all values that are in `x` but not in `y`. The returned list `out` +/// is sorted in the same order that the numbers appear in `x` (duplicates are +/// preserved). This operation also returns a list `idx` that represents the +/// position of each `out` element in `x`. In other words: +/// +/// `out[i] = x[idx[i]] for i in [0, 1, ..., len(out) - 1]` +/// +/// For example, given this input: +/// +/// ``` +/// x = [1, 2, 3, 4, 5, 6] +/// y = [1, 3, 5] +/// ``` +/// +/// This operation would return: +/// +/// ``` +/// out ==> [2, 4, 6] +/// idx ==> [1, 3, 5] +/// ``` +/// +/// - Parameters: +/// - x: 1-D. Values to keep. +/// - y: 1-D. Values to remove. +/// +/// - Outputs: +/// - out: 1-D. Values present in `x` but not in `y`. +/// - idx: 1-D. Positions of `x` values preserved in `out`. +@inlinable @inline(__always) +public static func listDiff< + T: TensorFlowScalar, + OutIdx: BinaryInteger & TensorFlowScalar +>( + _ x: Tensor, + _ y: Tensor +) -> (out: Tensor, idx: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("ListDiff", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func listInput( + _ a: [Tensor] +) { + let nOutputs = 0 + let op = makeOp("ListInput", nOutputs) + op.updateAttribute("N", a.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInputList(a) + op.execute() +} + +@inlinable @inline(__always) +public static func listOutput( +) -> T { + let nOutputs = Int(T._typeList.count) + let op = makeOp("ListOutput", nOutputs) + op.updateAttribute("T", T._typeList) + return op.execute(Int(T._typeList.count)) +} + +/// Loads a 2-D (matrix) `Tensor` with name `old_tensor_name` from the checkpoint +/// +/// at `ckpt_path` and potentially reorders its rows and columns using the +/// specified remappings. +/// +/// Most users should use one of the wrapper initializers (such as +/// `tf.contrib.framework.load_and_remap_matrix_initializer`) instead of this +/// function directly. +/// +/// The remappings are 1-D tensors with the following properties: +/// +/// * `row_remapping` must have exactly `num_rows` entries. Row `i` of the output +/// matrix will be initialized from the row corresponding to index +/// `row_remapping[i]` in the old `Tensor` from the checkpoint. +/// * `col_remapping` must have either 0 entries (indicating that no column +/// reordering is needed) or `num_cols` entries. If specified, column `j` of the +/// output matrix will be initialized from the column corresponding to index +/// `col_remapping[j]` in the old `Tensor` from the checkpoint. +/// * A value of -1 in either of the remappings signifies a "missing" entry. In that +/// case, values from the `initializing_values` tensor will be used to fill that +/// missing row or column. If `row_remapping` has `r` missing entries and +/// `col_remapping` has `c` missing entries, then the following condition must be +/// true: +/// +/// `(r * num_cols) + (c * num_rows) - (r * c) == len(initializing_values)` +/// +/// The remapping tensors can be generated using the GenerateVocabRemapping op. +/// +/// As an example, with row_remapping = [1, 0, -1], col_remapping = [0, 2, -1], +/// initializing_values = [0.5, -0.5, 0.25, -0.25, 42], and w(i, j) representing +/// the value from row i, column j of the old tensor in the checkpoint, the output +/// matrix will look like the following: +/// +/// [[w(1, 0), w(1, 2), 0.5], +/// [w(0, 0), w(0, 2), -0.5], +/// [0.25, -0.25, 42]] +/// +/// - Parameters: +/// - ckpt_path: Path to the TensorFlow checkpoint (version 2, `TensorBundle`) from +/// which the old matrix `Tensor` will be loaded. +/// - old_tensor_name: Name of the 2-D `Tensor` to load from checkpoint. +/// - row_remapping: An int `Tensor` of row remappings (generally created by +/// `generate_vocab_remapping`). Even if no row remapping is needed, this must +/// still be an index-valued Tensor (e.g. [0, 1, 2, ...]), or a shifted +/// index-valued `Tensor` (e.g. [8, 9, 10, ...], for partitioned `Variables`). +/// - col_remapping: An int `Tensor` of column remappings (generally created by +/// `generate_vocab_remapping`). May be a size-0 `Tensor` if only row remapping +/// is to be done (e.g. column ordering is the same). +/// - initializing_values: A float `Tensor` containing values to fill in for cells +/// in the output matrix that are not loaded from the checkpoint. Length must be +/// exactly the same as the number of missing / new cells. +/// +/// - Attrs: +/// - num_rows: Number of rows (length of the 1st dimension) in the output matrix. +/// - num_cols: Number of columns (length of the 2nd dimension) in the output matrix. +/// - max_rows_in_memory: The maximum number of rows to load from the checkpoint at +/// once. If less than or equal to 0, the entire matrix will be loaded into +/// memory. Setting this arg trades increased disk reads for lower memory usage. +/// +/// - Output output_matrix: Output matrix containing existing values loaded from the +/// checkpoint, and with any missing values filled in from initializing_values. +@inlinable @inline(__always) +public static func loadAndRemapMatrix( + ckptPath: StringTensor, + oldTensorName: StringTensor, + rowRemapping: Tensor, + colRemapping: Tensor, + initializingValues: Tensor, + numRows: Int64, + numCols: Int64, + maxRowsInMemory: Int64 = -1 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LoadAndRemapMatrix", nOutputs) + op.updateAttribute("num_rows", numRows) + op.updateAttribute("num_cols", numCols) + op.updateAttribute("max_rows_in_memory", maxRowsInMemory) + op.addInput(ckptPath) + op.addInput(oldTensorName) + op.addInput(rowRemapping) + op.addInput(colRemapping) + op.addInput(initializingValues) + return op.execute(Int(1)) +} + +/// Load ADAM embedding parameters. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the ADAM optimization algorithm. +/// - momenta: Value of momenta used in the ADAM optimization algorithm. +/// - velocities: Value of velocities used in the ADAM optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingADAMParameters( + parameters: Tensor, + momenta: Tensor, + velocities: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingADAMParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(momenta) + op.addInput(velocities) + op.execute() +} + +/// Load ADAM embedding parameters with debug support. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the ADAM optimization algorithm. +/// - momenta: Value of momenta used in the ADAM optimization algorithm. +/// - velocities: Value of velocities used in the ADAM optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the ADAM optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingADAMParametersGradAccumDebug( + parameters: Tensor, + momenta: Tensor, + velocities: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingADAMParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(momenta) + op.addInput(velocities) + op.addInput(gradientAccumulators) + op.execute() +} + +/// Load Adadelta embedding parameters. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the Adadelta optimization algorithm. +/// - accumulators: Value of accumulators used in the Adadelta optimization algorithm. +/// - updates: Value of updates used in the Adadelta optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingAdadeltaParameters( + parameters: Tensor, + accumulators: Tensor, + updates: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingAdadeltaParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(updates) + op.execute() +} + +/// Load Adadelta parameters with debug support. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the Adadelta optimization algorithm. +/// - accumulators: Value of accumulators used in the Adadelta optimization algorithm. +/// - updates: Value of updates used in the Adadelta optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the Adadelta optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingAdadeltaParametersGradAccumDebug( + parameters: Tensor, + accumulators: Tensor, + updates: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingAdadeltaParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(updates) + op.addInput(gradientAccumulators) + op.execute() +} + +/// Load Adagrad embedding parameters. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the Adagrad optimization algorithm. +/// - accumulators: Value of accumulators used in the Adagrad optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingAdagradParameters( + parameters: Tensor, + accumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingAdagradParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.execute() +} + +/// Load Adagrad embedding parameters with debug support. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the Adagrad optimization algorithm. +/// - accumulators: Value of accumulators used in the Adagrad optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the Adagrad optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingAdagradParametersGradAccumDebug( + parameters: Tensor, + accumulators: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingAdagradParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(gradientAccumulators) + op.execute() +} + +/// Load centered RMSProp embedding parameters. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the centered RMSProp optimization algorithm. +/// - ms: Value of ms used in the centered RMSProp optimization algorithm. +/// - mom: Value of mom used in the centered RMSProp optimization algorithm. +/// - mg: Value of mg used in the centered RMSProp optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingCenteredRMSPropParameters( + parameters: Tensor, + ms: Tensor, + mom: Tensor, + mg: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingCenteredRMSPropParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(ms) + op.addInput(mom) + op.addInput(mg) + op.execute() +} + +/// Load FTRL embedding parameters. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the FTRL optimization algorithm. +/// - accumulators: Value of accumulators used in the FTRL optimization algorithm. +/// - linears: Value of linears used in the FTRL optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingFTRLParameters( + parameters: Tensor, + accumulators: Tensor, + linears: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingFTRLParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(linears) + op.execute() +} + +/// Load FTRL embedding parameters with debug support. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the FTRL optimization algorithm. +/// - accumulators: Value of accumulators used in the FTRL optimization algorithm. +/// - linears: Value of linears used in the FTRL optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the FTRL optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingFTRLParametersGradAccumDebug( + parameters: Tensor, + accumulators: Tensor, + linears: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingFTRLParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(linears) + op.addInput(gradientAccumulators) + op.execute() +} + +/// Load MDL Adagrad Light embedding parameters. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the MDL Adagrad Light optimization algorithm. +/// - accumulators: Value of accumulators used in the MDL Adagrad Light optimization algorithm. +/// - weights: Value of weights used in the MDL Adagrad Light optimization algorithm. +/// - benefits: Value of benefits used in the MDL Adagrad Light optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingMDLAdagradLightParameters( + parameters: Tensor, + accumulators: Tensor, + weights: Tensor, + benefits: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingMDLAdagradLightParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(weights) + op.addInput(benefits) + op.execute() +} + +/// Load Momentum embedding parameters. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the Momentum optimization algorithm. +/// - momenta: Value of momenta used in the Momentum optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingMomentumParameters( + parameters: Tensor, + momenta: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingMomentumParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(momenta) + op.execute() +} + +/// Load Momentum embedding parameters with debug support. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the Momentum optimization algorithm. +/// - momenta: Value of momenta used in the Momentum optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the Momentum optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingMomentumParametersGradAccumDebug( + parameters: Tensor, + momenta: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingMomentumParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(momenta) + op.addInput(gradientAccumulators) + op.execute() +} + +/// Load proximal Adagrad embedding parameters. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the proximal Adagrad optimization algorithm. +/// - accumulators: Value of accumulators used in the proximal Adagrad optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingProximalAdagradParameters( + parameters: Tensor, + accumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingProximalAdagradParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.execute() +} + +/// Load proximal Adagrad embedding parameters with debug support. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the proximal Adagrad optimization algorithm. +/// - accumulators: Value of accumulators used in the proximal Adagrad optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the proximal Adagrad optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingProximalAdagradParametersGradAccumDebug( + parameters: Tensor, + accumulators: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingProximalAdagradParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(gradientAccumulators) + op.execute() +} + +/// Load RMSProp embedding parameters. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the RMSProp optimization algorithm. +/// - ms: Value of ms used in the RMSProp optimization algorithm. +/// - mom: Value of mom used in the RMSProp optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingRMSPropParameters( + parameters: Tensor, + ms: Tensor, + mom: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingRMSPropParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(ms) + op.addInput(mom) + op.execute() +} + +/// Load RMSProp embedding parameters with debug support. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameters: +/// - parameters: Value of parameters used in the RMSProp optimization algorithm. +/// - ms: Value of ms used in the RMSProp optimization algorithm. +/// - mom: Value of mom used in the RMSProp optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the RMSProp optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingRMSPropParametersGradAccumDebug( + parameters: Tensor, + ms: Tensor, + mom: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingRMSPropParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(ms) + op.addInput(mom) + op.addInput(gradientAccumulators) + op.execute() +} + +/// Load SGD embedding parameters. +/// +/// An op that loads optimization parameters into HBM for embedding. Must be +/// preceded by a ConfigureTPUEmbeddingHost op that sets up the correct +/// embedding table configuration. For example, this op is used to install +/// parameters that are loaded from a checkpoint before a training loop is +/// executed. +/// +/// - Parameter parameters: Value of parameters used in the stochastic gradient descent optimization algorithm. +@inlinable @inline(__always) +public static func loadTPUEmbeddingStochasticGradientDescentParameters( + parameters: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) { + let nOutputs = 0 + let op = makeOp("LoadTPUEmbeddingStochasticGradientDescentParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.execute() +} + +/// Computes natural logarithm of x element-wise. +/// +/// I.e., \\(y = \log_e x\\). +@inlinable @inline(__always) +public static func log( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Log", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes natural logarithm of (1 + x) element-wise. +/// +/// I.e., \\(y = \log_e (1 + x)\\). +@inlinable @inline(__always) +public static func log1p( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Log1p", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the sign and the log of the absolute value of the determinant of +/// +/// one or more square matrices. +/// +/// The input is a tensor of shape `[N, M, M]` whose inner-most 2 dimensions +/// form square matrices. The outputs are two tensors containing the signs and +/// absolute values of the log determinants for all N input submatrices +/// `[..., :, :]` such that the determinant = sign*exp(log_abs_determinant). +/// The log_abs_determinant is computed as det(P)*sum(log(diag(LU))) where LU +/// is the LU decomposition of the input and P is the corresponding +/// permutation matrix. +/// +/// - Parameter input: Shape is `[N, M, M]`. +/// +/// - Outputs: +/// - sign: The signs of the log determinants of the inputs. Shape is `[N]`. +/// - log_abs_determinant: The logs of the absolute values of the determinants +/// of the N input matrices. Shape is `[N]`. +@inlinable @inline(__always) +public static func logMatrixDeterminant( + _ input: Tensor +) -> (sign: Tensor, logAbsDeterminant: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("LogMatrixDeterminant", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) +} + +/// Computes log softmax activations. +/// +/// For each batch `i` and class `j` we have +/// +/// logsoftmax[i, j] = logits[i, j] - log(sum(exp(logits[i]))) +/// +/// - Parameter logits: 2-D with shape `[batch_size, num_classes]`. +/// +/// - Output logsoftmax: Same shape as `logits`. +@inlinable @inline(__always) +public static func logSoftmax( + logits: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LogSoftmax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(logits) + return op.execute(Int(1)) +} + +/// Generates labels for candidate sampling with a log-uniform distribution. +/// +/// See explanations of candidate sampling and the data formats at +/// go/candidate-sampling. +/// +/// For each batch, this op picks a single set of sampled candidate labels. +/// +/// The advantages of sampling candidates per-batch are simplicity and the +/// possibility of efficient dense matrix multiplication. The disadvantage is that +/// the sampled candidates must be chosen independently of the context and of the +/// true labels. +/// +/// - Parameter true_classes: A batch_size * num_true matrix, in which each row contains the +/// IDs of the num_true target_classes in the corresponding original label. +/// +/// - Attrs: +/// - num_true: Number of true labels per context. +/// - num_sampled: Number of candidates to randomly sample. +/// - unique: If unique is true, we sample with rejection, so that all sampled +/// candidates in a batch are unique. This requires some approximation to +/// estimate the post-rejection sampling probabilities. +/// - range_max: The sampler will sample integers from the interval [0, range_max). +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. +/// +/// - Outputs: +/// - sampled_candidates: A vector of length num_sampled, in which each element is +/// the ID of a sampled candidate. +/// - true_expected_count: A batch_size * num_true matrix, representing +/// the number of times each candidate is expected to occur in a batch +/// of sampled candidates. If unique=true, then this is a probability. +/// - sampled_expected_count: A vector of length num_sampled, for each sampled +/// candidate representing the number of times the candidate is expected +/// to occur in a batch of sampled candidates. If unique=true, then this is a +/// probability. +@inlinable @inline(__always) +public static func logUniformCandidateSampler( + trueClasses: Tensor, + numTrue: Int64, + numSampled: Int64, + unique: Bool, + rangeMax: Int64, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> (sampledCandidates: Tensor, trueExpectedCount: Tensor, sampledExpectedCount: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("LogUniformCandidateSampler", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("num_sampled", numSampled) + op.updateAttribute("unique", unique) + op.updateAttribute("range_max", rangeMax) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Returns the truth value of x AND y element-wise. +/// +/// *NOTE*: `LogicalAnd` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func logicalAnd( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LogicalAnd", nOutputs) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns the truth value of NOT x element-wise. +@inlinable @inline(__always) +public static func logicalNot( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LogicalNot", nOutputs) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Returns the truth value of x OR y element-wise. +/// +/// *NOTE*: `LogicalOr` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func logicalOr( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LogicalOr", nOutputs) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Outputs all keys and values in the table. +/// +/// - Parameter table_handle: Handle to the table. +/// +/// - Outputs: +/// - keys: Vector of all keys present in the table. +/// - values: Tensor of all values in the table. Indexed in parallel with `keys`. +@inlinable @inline(__always) +public static func lookupTableExportV2< + Tkeys: TensorFlowScalar, + Tvalues: TensorFlowScalar +>( + tableHandle: ResourceHandle +) -> (keys: Tensor, values: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("LookupTableExportV2", nOutputs) + op.updateAttribute("Tkeys", Tkeys.tensorFlowDataType) + op.updateAttribute("Tvalues", Tvalues.tensorFlowDataType) + op.addInput(tableHandle) + return op.execute(Int(1), Int(1)) +} + +/// Looks up keys in a table, outputs the corresponding values. +/// +/// The tensor `keys` must of the same type as the keys of the table. +/// The output `values` is of the type of the table values. +/// +/// The scalar `default_value` is the value output for keys not present in the +/// table. It must also be of the same type as the table values. +/// +/// - Parameters: +/// - table_handle: Handle to the table. +/// - keys: Any shape. Keys to look up. +/// +/// - Output values: Same shape as `keys`. Values found in the table, or `default_values` +/// for missing keys. +@inlinable @inline(__always) +public static func lookupTableFindV2< + Tin: TensorFlowScalar, + Tout: TensorFlowScalar +>( + tableHandle: ResourceHandle, + keys: Tensor, + defaultValue: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LookupTableFindV2", nOutputs) + op.updateAttribute("Tin", Tin.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(tableHandle) + op.addInput(keys) + op.addInput(defaultValue) + return op.execute(Int(1)) +} + +/// Replaces the contents of the table with the specified keys and values. +/// +/// The tensor `keys` must be of the same type as the keys of the table. +/// The tensor `values` must be of the type of the table values. +/// +/// - Parameters: +/// - table_handle: Handle to the table. +/// - keys: Any shape. Keys to look up. +/// - values: Values to associate with keys. +@inlinable @inline(__always) +public static func lookupTableImportV2< + Tin: TensorFlowScalar, + Tout: TensorFlowScalar +>( + tableHandle: ResourceHandle, + keys: Tensor, + _ values: Tensor +) { + let nOutputs = 0 + let op = makeOp("LookupTableImportV2", nOutputs) + op.updateAttribute("Tin", Tin.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(tableHandle) + op.addInput(keys) + op.addInput(values) + op.execute() +} + +/// Updates the table to associates keys with values. +/// +/// The tensor `keys` must be of the same type as the keys of the table. +/// The tensor `values` must be of the type of the table values. +/// +/// - Parameters: +/// - table_handle: Handle to the table. +/// - keys: Any shape. Keys to look up. +/// - values: Values to associate with keys. +@inlinable @inline(__always) +public static func lookupTableInsertV2< + Tin: TensorFlowScalar, + Tout: TensorFlowScalar +>( + tableHandle: ResourceHandle, + keys: Tensor, + _ values: Tensor +) { + let nOutputs = 0 + let op = makeOp("LookupTableInsertV2", nOutputs) + op.updateAttribute("Tin", Tin.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(tableHandle) + op.addInput(keys) + op.addInput(values) + op.execute() +} + +/// Removes keys and its associated values from a table. +/// +/// The tensor `keys` must of the same type as the keys of the table. Keys not +/// already in the table are silently ignored. +/// +/// - Parameters: +/// - table_handle: Handle to the table. +/// - keys: Any shape. Keys of the elements to remove. +@inlinable @inline(__always) +public static func lookupTableRemoveV2( + tableHandle: ResourceHandle, + keys: Tensor +) { + let nOutputs = 0 + let op = makeOp("LookupTableRemoveV2", nOutputs) + op.updateAttribute("Tin", Tin.tensorFlowDataType) + op.addInput(tableHandle) + op.addInput(keys) + op.execute() +} + +/// Computes the number of elements in the given table. +/// +/// - Parameter table_handle: Handle to the table. +/// +/// - Output size: Scalar that contains number of elements in the table. +@inlinable @inline(__always) +public static func lookupTableSizeV2( + tableHandle: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LookupTableSizeV2", nOutputs) + op.addInput(tableHandle) + return op.execute(Int(1)) +} + +/// Forwards the input to the output. +/// +/// This operator represents the loop termination condition used by the +/// "pivot" switches of a loop. +/// +/// - Parameter input: A boolean scalar, representing the branch predicate of the Switch op. +/// +/// - Output output: The same tensor as `input`. +@inlinable @inline(__always) +public static func loopCond( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LoopCond", nOutputs) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Applies lower_bound(sorted_search_values, values) along each row. +/// +/// Each set of rows with the same index in (sorted_inputs, values) is treated +/// independently. The resulting row is the equivalent of calling +/// `np.searchsorted(sorted_inputs, values, side='left')`. +/// +/// The result is not a global index to the entire +/// `Tensor`, but rather just the index in the last dimension. +/// +/// A 2-D example: +/// sorted_sequence = [[0, 3, 9, 9, 10], +/// [1, 2, 3, 4, 5]] +/// values = [[2, 4, 9], +/// [0, 2, 6]] +/// +/// result = LowerBound(sorted_sequence, values) +/// +/// result == [[1, 2, 2], +/// [0, 1, 5]] +/// +/// - Parameters: +/// - sorted_inputs: 2-D Tensor where each row is ordered. +/// - values: 2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains +/// the values that will be searched for in `sorted_search_values`. +/// +/// - Output output: A `Tensor` with the same shape as `values`. It contains the first scalar index +/// into the last dimension where values can be inserted without changing the +/// ordered property. +@inlinable @inline(__always) +public static func lowerBound< + T: TensorFlowScalar, + OutType: BinaryInteger & TensorFlowScalar +>( + sortedInputs: Tensor, + _ values: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LowerBound", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(sortedInputs) + op.addInput(values) + return op.execute(Int(1)) +} + +/// Computes the LU decomposition of one or more square matrices. +/// +/// The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions +/// form square matrices. +/// +/// The input has to be invertible. +/// +/// The output consists of two tensors LU and P containing the LU decomposition +/// of all input submatrices `[..., :, :]`. LU encodes the lower triangular and +/// upper triangular factors. +/// +/// For each input submatrix of shape `[M, M]`, L is a lower triangular matrix of +/// shape `[M, M]` with unit diagonal whose entries correspond to the strictly lower +/// triangular part of LU. U is a upper triangular matrix of shape `[M, M]` whose +/// entries correspond to the upper triangular part, including the diagonal, of LU. +/// +/// P represents a permutation matrix encoded as a list of indices each between `0` +/// and `M-1`, inclusive. If P_mat denotes the permutation matrix corresponding to +/// P, then the L, U and P satisfies P_mat * input = L * U. +/// +/// - Parameter input: A tensor of shape `[..., M, M]` whose inner-most 2 dimensions form matrices of +/// size `[M, M]`. +/// +/// - Outputs: +/// - lu: A tensor of shape `[..., M, M]` whose strictly lower triangular part denotes the +/// lower triangular factor `L` with unit diagonal, and whose upper triangular part +/// denotes the upper triangular factor `U`. +/// - p: Permutation of the rows encoded as a list of indices in `0..M-1`. Shape is +/// `[..., M]`. +/// @compatibility(scipy) +/// Similar to `scipy.linalg.lu`, except the triangular factors `L` and `U` are +/// packed into a single tensor, the permutation is applied to `input` instead of +/// the right hand side and the permutation `P` is returned as a list of indices +/// instead of a permutation matrix. +/// @end_compatibility +@inlinable @inline(__always) +public static func lu< + T: FloatingPoint & TensorFlowScalar, + OutputIdxType: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor +) -> (lu: Tensor, p: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("Lu", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("output_idx_type", OutputIdxType.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) +} + +/// Makes a new iterator from the given `dataset` and stores it in `iterator`. +/// +/// This operation may be executed multiple times. Each execution will reset the +/// iterator in `iterator` to the first element of `dataset`. +@inlinable @inline(__always) +public static func makeIterator( + dataset: VariantHandle, + iterator: ResourceHandle +) { + let nOutputs = 0 + let op = makeOp("MakeIterator", nOutputs) + op.addInput(dataset) + op.addInput(iterator) + op.execute() +} + +/// Op removes all elements in the underlying container. +@inlinable @inline(__always) +public static func mapClear( + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String +) { + let nOutputs = 0 + let op = makeOp("MapClear", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.execute() +} + +/// Creates a dataset that applies `f` to the outputs of `input_dataset`. +@inlinable @inline(__always) +public static func mapDataset< + FIn: TensorGroup, + FOut: TensorGroup, + Targuments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + otherArguments: Targuments, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + useInterOpParallelism: Bool = true, + preserveCardinality: Bool = false +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("MapDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("use_inter_op_parallelism", useInterOpParallelism) + op.updateAttribute("preserve_cardinality", preserveCardinality) + op.addInput(inputDataset) + op.addInputList(otherArguments) + return op.execute(Int(1)) +} + +/// Maps a function on the list of tensors unpacked from arguments on dimension 0. +/// The function given by `f` is assumed to be stateless, and is executed +/// concurrently on all the slices; up to batch_size (i.e. the size of the 0th +/// dimension of each argument) functions will be scheduled at once. +/// +/// The `max_intra_op_parallelism` attr, which defaults to 1, can be used to +/// limit the intra op parallelism. To limit inter-op parallelism, a user can +/// set a private threadpool on the dataset using `tf.data.Options`'s +/// `ThreadingOptions`. +/// +/// Note that this op is not exposed to users directly, but is invoked in tf.data +/// rewrites. +/// +/// - Parameters: +/// - arguments: A list of tensors whose types are `Targuments`, corresponding to the inputs +/// the function should be mapped over. +/// - captured_inputs: A list of tensors whose types are `Tcaptured`, corresponding to the captured +/// inputs of the defun. +/// +/// - Attrs: +/// - Targuments: A list of types. +/// - Tcaptured: A list of types. +/// - output_types: A list of types. +/// - output_shapes: A list of shapes. +/// +/// - Output output: A list of output tensors whose types are `output_types` and whose dimensions +/// 0 are the same as the dimensions 0 of the tensors in `arguments`, and whose +/// remaining dimensions correspond to those in `output_shapes`. +@inlinable @inline(__always) +public static func mapDefun< + Targuments: TensorArrayProtocol, + Tcaptured: TensorArrayProtocol, + OutputTypes: TensorGroup, + FIn: TensorGroup, + FOut: TensorGroup +>( + arguments: Targuments, + capturedInputs: Tcaptured, + outputShapes: [TensorShape?], + f: (FIn) -> FOut, + maxIntraOpParallelism: Int64 = 1 +) -> OutputTypes { + let nOutputs = Int(OutputTypes._typeList.count) + let op = makeOp("MapDefun", nOutputs) + op.updateAttribute("Targuments", arguments._typeList) + op.updateAttribute("Tcaptured", capturedInputs._typeList) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("f", f) + op.updateAttribute("max_intra_op_parallelism", maxIntraOpParallelism) + op.addInputList(arguments) + op.addInputList(capturedInputs) + return op.execute(Int(OutputTypes._typeList.count)) +} + +/// Op returns the number of incomplete elements in the underlying container. +@inlinable @inline(__always) +public static func mapIncompleteSize( + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MapIncompleteSize", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Op peeks at the values at the specified key. If the +/// +/// underlying container does not contain this key +/// this op will block until it does. +@inlinable @inline(__always) +public static func mapPeek( + key: Tensor, + indices: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String +) -> Dtypes { + let nOutputs = Int(Dtypes._typeList.count) + let op = makeOp("MapPeek", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(key) + op.addInput(indices) + return op.execute(Int(Dtypes._typeList.count)) +} + +/// Op returns the number of elements in the underlying container. +@inlinable @inline(__always) +public static func mapSize( + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MapSize", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Stage (key, values) in the underlying container which behaves like a hashtable. +/// +/// - Parameters: +/// - key: int64 +/// - values: a list of tensors +/// dtypes A list of data types that inserted values should adhere to. +/// +/// - Attrs: +/// - capacity: Maximum number of elements in the Staging Area. If > 0, inserts +/// on the container will block when the capacity is reached. +/// - container: If non-empty, this queue is placed in the given container. Otherwise, +/// a default container is used. +/// - shared_name: It is necessary to match this name to the matching Unstage Op. +@inlinable @inline(__always) +public static func mapStage( + key: Tensor, + indices: Tensor, + _ values: FakeDtypes, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String +) { + let nOutputs = 0 + let op = makeOp("MapStage", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("fake_dtypes", values._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(key) + op.addInput(indices) + op.addInputList(values) + op.execute() +} + +/// Op removes and returns the values associated with the key +/// +/// from the underlying container. If the underlying container +/// does not contain this key, the op will block until it does. +@inlinable @inline(__always) +public static func mapUnstage( + key: Tensor, + indices: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String +) -> Dtypes { + let nOutputs = Int(Dtypes._typeList.count) + let op = makeOp("MapUnstage", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(key) + op.addInput(indices) + return op.execute(Int(Dtypes._typeList.count)) +} + +/// Op removes and returns a random (key, value) +/// +/// from the underlying container. If the underlying container +/// does not contain elements, the op will block until it does. +@inlinable @inline(__always) +public static func mapUnstageNoKey( + indices: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String +) -> (key: Tensor, values: Dtypes) { + let nOutputs = Int(1) + Int(Dtypes._typeList.count) + let op = makeOp("MapUnstageNoKey", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(indices) + return op.execute(Int(1), Int(Dtypes._typeList.count)) +} + +/// Multiply the matrix "a" by the matrix "b". +/// +/// The inputs must be two-dimensional matrices and the inner dimension of +/// "a" (after being transposed if transpose_a is true) must match the +/// outer dimension of "b" (after being transposed if transposed_b is +/// true). +/// +/// *Note*: The default kernel implementation for MatMul on GPUs uses +/// cublas. +/// +/// - Attrs: +/// - transpose_a: If true, "a" is transposed before multiplication. +/// - transpose_b: If true, "b" is transposed before multiplication. +@inlinable @inline(__always) +public static func matMul( + _ a: Tensor, + _ b: Tensor, + transposeA: Bool = false, + transposeB: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MatMul", nOutputs) + op.updateAttribute("transpose_a", transposeA) + op.updateAttribute("transpose_b", transposeB) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(b) + return op.execute(Int(1)) +} + +/// Returns the set of files matching one or more glob patterns. +/// +/// Note that this routine only supports wildcard characters in the +/// basename portion of the pattern, not in the directory portion. +/// Note also that the order of filenames returned can be non-deterministic. +/// +/// - Parameter pattern: Shell wildcard pattern(s). Scalar or vector of type string. +/// +/// - Output filenames: A vector of matching filenames. +@inlinable @inline(__always) +public static func matchingFiles( + pattern: StringTensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("MatchingFiles", nOutputs) + op.addInput(pattern) + return op.execute(Int(1)) +} + +/// Copy a tensor setting everything outside a central band in each innermost matrix +/// +/// to zero. +/// +/// The `band` part is computed as follows: +/// Assume `input` has `k` dimensions `[I, J, K, ..., M, N]`, then the output is a +/// tensor with the same shape where +/// +/// `band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]`. +/// +/// The indicator function +/// +/// `in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower)) && +/// (num_upper < 0 || (n-m) <= num_upper)`. +/// +/// For example: +/// +/// ``` +/// # if 'input' is [[ 0, 1, 2, 3] +/// [-1, 0, 1, 2] +/// [-2, -1, 0, 1] +/// [-3, -2, -1, 0]], +/// +/// tf.matrix_band_part(input, 1, -1) ==> [[ 0, 1, 2, 3] +/// [-1, 0, 1, 2] +/// [ 0, -1, 0, 1] +/// [ 0, 0, -1, 0]], +/// +/// tf.matrix_band_part(input, 2, 1) ==> [[ 0, 1, 0, 0] +/// [-1, 0, 1, 0] +/// [-2, -1, 0, 1] +/// [ 0, -2, -1, 0]] +/// ``` +/// +/// Useful special cases: +/// +/// ``` +/// tf.matrix_band_part(input, 0, -1) ==> Upper triangular part. +/// tf.matrix_band_part(input, -1, 0) ==> Lower triangular part. +/// tf.matrix_band_part(input, 0, 0) ==> Diagonal. +/// ``` +/// +/// - Parameters: +/// - input: Rank `k` tensor. +/// - num_lower: 0-D tensor. Number of subdiagonals to keep. If negative, keep entire +/// lower triangle. +/// - num_upper: 0-D tensor. Number of superdiagonals to keep. If negative, keep +/// entire upper triangle. +/// +/// - Output band: Rank `k` tensor of the same shape as input. The extracted banded tensor. +@inlinable @inline(__always) +public static func matrixBandPart< + T: TensorFlowScalar, + Tindex: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + numLower: Tensor, + numUpper: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MatrixBandPart", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindex", Tindex.tensorFlowDataType) + op.addInput(input) + op.addInput(numLower) + op.addInput(numUpper) + return op.execute(Int(1)) +} + +/// Computes the determinant of one or more square matrices. +/// +/// The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions +/// form square matrices. The output is a tensor containing the determinants +/// for all input submatrices `[..., :, :]`. +/// +/// - Parameter input: Shape is `[..., M, M]`. +/// +/// - Output output: Shape is `[...]`. +@inlinable @inline(__always) +public static func matrixDeterminant( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MatrixDeterminant", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Returns a batched diagonal tensor with a given batched diagonal values. +/// +/// Given a `diagonal`, this operation returns a tensor with the `diagonal` and +/// everything else padded with zeros. The diagonal is computed as follows: +/// +/// Assume `diagonal` has `k` dimensions `[I, J, K, ..., N]`, then the output is a +/// tensor of rank `k+1` with dimensions [I, J, K, ..., N, N]` where: +/// +/// `output[i, j, k, ..., m, n] = 1{m=n} * diagonal[i, j, k, ..., n]`. +/// +/// For example: +/// +/// ``` +/// # 'diagonal' is [[1, 2, 3, 4], [5, 6, 7, 8]] +/// +/// and diagonal.shape = (2, 4) +/// +/// tf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0] +/// [0, 2, 0, 0] +/// [0, 0, 3, 0] +/// [0, 0, 0, 4]], +/// [[5, 0, 0, 0] +/// [0, 6, 0, 0] +/// [0, 0, 7, 0] +/// [0, 0, 0, 8]]] +/// +/// which has shape (2, 4, 4) +/// ``` +/// +/// - Parameter diagonal: Rank `k`, where `k >= 1`. +/// +/// - Output output: Rank `k+1`, with `output.shape = diagonal.shape + [diagonal.shape[-1]]`. +@inlinable @inline(__always) +public static func matrixDiag( + diagonal: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MatrixDiag", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(diagonal) + return op.execute(Int(1)) +} + +/// Returns the batched diagonal part of a batched tensor. +/// +/// This operation returns a tensor with the `diagonal` part +/// of the batched `input`. The `diagonal` part is computed as follows: +/// +/// Assume `input` has `k` dimensions `[I, J, K, ..., M, N]`, then the output is a +/// tensor of rank `k - 1` with dimensions `[I, J, K, ..., min(M, N)]` where: +/// +/// `diagonal[i, j, k, ..., n] = input[i, j, k, ..., n, n]`. +/// +/// The input must be at least a matrix. +/// +/// For example: +/// +/// ``` +/// # 'input' is [[[1, 0, 0, 0] +/// [0, 2, 0, 0] +/// [0, 0, 3, 0] +/// [0, 0, 0, 4]], +/// [[5, 0, 0, 0] +/// [0, 6, 0, 0] +/// [0, 0, 7, 0] +/// [0, 0, 0, 8]]] +/// +/// and input.shape = (2, 4, 4) +/// +/// tf.matrix_diag_part(input) ==> [[1, 2, 3, 4], [5, 6, 7, 8]] +/// +/// which has shape (2, 4) +/// ``` +/// +/// - Parameter input: Rank `k` tensor where `k >= 2`. +/// +/// - Output diagonal: The extracted diagonal(s) having shape +/// `diagonal.shape = input.shape[:-2] + [min(input.shape[-2:])]`. +@inlinable @inline(__always) +public static func matrixDiagPart( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MatrixDiagPart", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Deprecated, use python implementation tf.linalg.matrix_exponential. +@inlinable @inline(__always) +public static func matrixExponential( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MatrixExponential", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Computes the inverse of one or more square invertible matrices or their +/// +/// adjoints (conjugate transposes). +/// +/// The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions +/// form square matrices. The output is a tensor of the same shape as the input +/// containing the inverse for all input submatrices `[..., :, :]`. +/// +/// The op uses LU decomposition with partial pivoting to compute the inverses. +/// +/// If a matrix is not invertible there is no guarantee what the op does. It +/// may detect the condition and raise an exception or it may simply return a +/// garbage result. +/// +/// - Parameter input: Shape is `[..., M, M]`. +/// +/// - Output output: Shape is `[..., M, M]`. +/// +/// @compatibility(numpy) +/// Equivalent to np.linalg.inv +/// @end_compatibility +@inlinable @inline(__always) +public static func matrixInverse( + _ input: Tensor, + adjoint: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MatrixInverse", nOutputs) + op.updateAttribute("adjoint", adjoint) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Computes the matrix logarithm of one or more square matrices: +/// +/// +/// \\(log(exp(A)) = A\\) +/// +/// This op is only defined for complex matrices. If A is positive-definite and +/// real, then casting to a complex matrix, taking the logarithm and casting back +/// to a real matrix will give the correct result. +/// +/// This function computes the matrix logarithm using the Schur-Parlett algorithm. +/// Details of the algorithm can be found in Section 11.6.2 of: +/// Nicholas J. Higham, Functions of Matrices: Theory and Computation, SIAM 2008. +/// ISBN 978-0-898716-46-7. +/// +/// The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions +/// form square matrices. The output is a tensor of the same shape as the input +/// containing the exponential for all input submatrices `[..., :, :]`. +/// +/// - Parameter input: Shape is `[..., M, M]`. +/// +/// - Output output: Shape is `[..., M, M]`. +/// +/// @compatibility(scipy) +/// Equivalent to scipy.linalg.logm +/// @end_compatibility +@inlinable @inline(__always) +public static func matrixLogarithm( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MatrixLogarithm", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Returns a batched matrix tensor with new batched diagonal values. +/// +/// Given `input` and `diagonal`, this operation returns a tensor with the +/// same shape and values as `input`, except for the main diagonal of the +/// innermost matrices. These will be overwritten by the values in `diagonal`. +/// +/// The output is computed as follows: +/// +/// Assume `input` has `k+1` dimensions `[I, J, K, ..., M, N]` and `diagonal` has +/// `k` dimensions `[I, J, K, ..., min(M, N)]`. Then the output is a +/// tensor of rank `k+1` with dimensions `[I, J, K, ..., M, N]` where: +/// +/// * `output[i, j, k, ..., m, n] = diagonal[i, j, k, ..., n]` for `m == n`. +/// * `output[i, j, k, ..., m, n] = input[i, j, k, ..., m, n]` for `m != n`. +/// +/// - Parameters: +/// - input: Rank `k+1`, where `k >= 1`. +/// - diagonal: Rank `k`, where `k >= 1`. +/// +/// - Output output: Rank `k+1`, with `output.shape = input.shape`. +@inlinable @inline(__always) +public static func matrixSetDiag( + _ input: Tensor, + diagonal: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MatrixSetDiag", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(diagonal) + return op.execute(Int(1)) +} + +/// Solves systems of linear equations. +/// +/// `Matrix` is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions +/// form square matrices. `Rhs` is a tensor of shape `[..., M, K]`. The `output` is +/// a tensor shape `[..., M, K]`. If `adjoint` is `False` then each output matrix +/// satisfies `matrix[..., :, :] * output[..., :, :] = rhs[..., :, :]`. +/// If `adjoint` is `True` then each output matrix satisfies +/// `adjoint(matrix[..., :, :]) * output[..., :, :] = rhs[..., :, :]`. +/// +/// - Parameters: +/// - matrix: Shape is `[..., M, M]`. +/// - rhs: Shape is `[..., M, K]`. +/// +/// - Attr adjoint: Boolean indicating whether to solve with `matrix` or its (block-wise) +/// adjoint. +/// +/// - Output output: Shape is `[..., M, K]`. +@inlinable @inline(__always) +public static func matrixSolve( + matrix: Tensor, + rhs: Tensor, + adjoint: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MatrixSolve", nOutputs) + op.updateAttribute("adjoint", adjoint) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(matrix) + op.addInput(rhs) + return op.execute(Int(1)) +} + +/// Solves one or more linear least-squares problems. +/// +/// `matrix` is a tensor of shape `[..., M, N]` whose inner-most 2 dimensions +/// form real or complex matrices of size `[M, N]`. `Rhs` is a tensor of the same +/// type as `matrix` and shape `[..., M, K]`. +/// The output is a tensor shape `[..., N, K]` where each output matrix solves +/// each of the equations +/// `matrix[..., :, :]` * `output[..., :, :]` = `rhs[..., :, :]` +/// in the least squares sense. +/// +/// We use the following notation for (complex) matrix and right-hand sides +/// in the batch: +/// +/// `matrix`=\\(A \in \mathbb{C}^{m \times n}\\), +/// `rhs`=\\(B \in \mathbb{C}^{m \times k}\\), +/// `output`=\\(X \in \mathbb{C}^{n \times k}\\), +/// `l2_regularizer`=\\(\lambda \in \mathbb{R}\\). +/// +/// If `fast` is `True`, then the solution is computed by solving the normal +/// equations using Cholesky decomposition. Specifically, if \\(m \ge n\\) then +/// \\(X = (A^H A + \lambda I)^{-1} A^H B\\), which solves the least-squares +/// problem \\(X = \mathrm{argmin}_{Z \in \Re^{n \times k} } ||A Z - B||_F^2 + \lambda ||Z||_F^2\\). +/// If \\(m \lt n\\) then `output` is computed as +/// \\(X = A^H (A A^H + \lambda I)^{-1} B\\), which (for \\(\lambda = 0\\)) is the +/// minimum-norm solution to the under-determined linear system, i.e. +/// \\(X = \mathrm{argmin}_{Z \in \mathbb{C}^{n \times k} } ||Z||_F^2 \\), +/// subject to \\(A Z = B\\). Notice that the fast path is only numerically stable +/// when \\(A\\) is numerically full rank and has a condition number +/// \\(\mathrm{cond}(A) \lt \frac{1}{\sqrt{\epsilon_{mach} } }\\) or \\(\lambda\\) is +/// sufficiently large. +/// +/// If `fast` is `False` an algorithm based on the numerically robust complete +/// orthogonal decomposition is used. This computes the minimum-norm +/// least-squares solution, even when \\(A\\) is rank deficient. This path is +/// typically 6-7 times slower than the fast path. If `fast` is `False` then +/// `l2_regularizer` is ignored. +/// +/// - Parameters: +/// - matrix: Shape is `[..., M, N]`. +/// - rhs: Shape is `[..., M, K]`. +/// - l2_regularizer: Scalar tensor. +/// +/// @compatibility(numpy) +/// Equivalent to np.linalg.lstsq +/// @end_compatibility +/// +/// - Output output: Shape is `[..., N, K]`. +@inlinable @inline(__always) +public static func matrixSolveLs( + matrix: Tensor, + rhs: Tensor, + l2Regularizer: Tensor, + fast: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MatrixSolveLs", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("fast", fast) + op.addInput(matrix) + op.addInput(rhs) + op.addInput(l2Regularizer) + return op.execute(Int(1)) +} + +/// Computes the matrix square root of one or more square matrices: +/// +/// matmul(sqrtm(A), sqrtm(A)) = A +/// +/// The input matrix should be invertible. If the input matrix is real, it should +/// have no eigenvalues which are real and negative (pairs of complex conjugate +/// eigenvalues are allowed). +/// +/// The matrix square root is computed by first reducing the matrix to +/// quasi-triangular form with the real Schur decomposition. The square root +/// of the quasi-triangular matrix is then computed directly. Details of +/// the algorithm can be found in: Nicholas J. Higham, "Computing real +/// square roots of a real matrix", Linear Algebra Appl., 1987. +/// +/// The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions +/// form square matrices. The output is a tensor of the same shape as the input +/// containing the matrix square root for all input submatrices `[..., :, :]`. +/// +/// - Parameter input: Shape is `[..., M, M]`. +/// +/// - Output output: Shape is `[..., M, M]`. +/// +/// @compatibility(scipy) +/// Equivalent to scipy.linalg.sqrtm +/// @end_compatibility +@inlinable @inline(__always) +public static func matrixSquareRoot( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MatrixSquareRoot", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Solves systems of linear equations with upper or lower triangular matrices by +/// +/// backsubstitution. +/// +/// `matrix` is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions form +/// square matrices. If `lower` is `True` then the strictly upper triangular part +/// of each inner-most matrix is assumed to be zero and not accessed. +/// If `lower` is False then the strictly lower triangular part of each inner-most +/// matrix is assumed to be zero and not accessed. +/// `rhs` is a tensor of shape `[..., M, K]`. +/// +/// The output is a tensor of shape `[..., M, K]`. If `adjoint` is +/// `True` then the innermost matrices in `output` satisfy matrix equations +/// `matrix[..., :, :] * output[..., :, :] = rhs[..., :, :]`. +/// If `adjoint` is `False` then the strictly then the innermost matrices in +/// `output` satisfy matrix equations +/// `adjoint(matrix[..., i, k]) * output[..., k, j] = rhs[..., i, j]`. +/// +/// - Parameters: +/// - matrix: Shape is `[..., M, M]`. +/// - rhs: Shape is `[..., M, K]`. +/// +/// - Attrs: +/// - lower: Boolean indicating whether the innermost matrices in `matrix` are +/// lower or upper triangular. +/// - adjoint: Boolean indicating whether to solve with `matrix` or its (block-wise) +/// adjoint. +/// +/// @compatibility(numpy) +/// Equivalent to scipy.linalg.solve_triangular +/// @end_compatibility +/// +/// - Output output: Shape is `[..., M, K]`. +@inlinable @inline(__always) +public static func matrixTriangularSolve( + matrix: Tensor, + rhs: Tensor, + lower: Bool = true, + adjoint: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MatrixTriangularSolve", nOutputs) + op.updateAttribute("lower", lower) + op.updateAttribute("adjoint", adjoint) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(matrix) + op.addInput(rhs) + return op.execute(Int(1)) +} + +/// Computes the maximum of elements across dimensions of a tensor. +/// +/// Reduces `input` along the dimensions given in `axis`. Unless +/// `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in +/// `axis`. If `keep_dims` is true, the reduced dimensions are +/// retained with length 1. +/// +/// - Parameters: +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. +/// +/// - Attr keep_dims: If true, retain reduced dimensions with length 1. +/// +/// - Output output: The reduced tensor. +@inlinable @inline(__always) +public static func max< + T: Numeric & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Max", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) +} + +/// Performs max pooling on the input. +/// +/// - Parameter input: 4-D input to pool over. +/// +/// - Attrs: +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// +/// - Output output: The max pooled output tensor. +@inlinable @inline(__always) +public static func maxPool( + _ input: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat4 = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPool", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Performs 3D max pooling on the input. +/// +/// - Parameter input: Shape `[batch, depth, rows, cols, channels]` tensor to pool over. +/// +/// - Attrs: +/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of +/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. +/// +/// - Output output: The max pooled output tensor. +@inlinable @inline(__always) +public static func maxPool3D( + _ input: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPool3D", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Computes gradients of max pooling function. +/// +/// - Parameters: +/// - orig_input: The original input tensor. +/// - orig_output: The original output tensor. +/// - grad: Output backprop of shape `[batch, depth, rows, cols, channels]`. +/// +/// - Attrs: +/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of +/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. +@inlinable @inline(__always) +public static func maxPool3DGrad< + T: FloatingPoint & TensorFlowScalar, + Tinput: FloatingPoint & TensorFlowScalar +>( + origInput: Tensor, + origOutput: Tensor, + grad: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPool3DGrad", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("TInput", Tinput.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(grad) + return op.execute(Int(1)) +} + +/// Computes second-order gradients of the maxpooling function. +/// +/// - Parameters: +/// - orig_input: The original input tensor. +/// - orig_output: The original output tensor. +/// - grad: Output backprop of shape `[batch, depth, rows, cols, channels]`. +/// +/// - Attrs: +/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of +/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. +/// +/// - Output output: Gradients of gradients w.r.t. the input to `max_pool`. +@inlinable @inline(__always) +public static func maxPool3DGradGrad( + origInput: Tensor, + origOutput: Tensor, + grad: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPool3DGradGrad", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(grad) + return op.execute(Int(1)) +} + +/// Computes gradients of the maxpooling function. +/// +/// - Parameters: +/// - orig_input: The original input tensor. +/// - orig_output: The original output tensor. +/// - grad: 4-D. Gradients w.r.t. the output of `max_pool`. +/// +/// - Attrs: +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// +/// - Output output: Gradients w.r.t. the input to `max_pool`. +@inlinable @inline(__always) +public static func maxPoolGrad( + origInput: Tensor, + origOutput: Tensor, + grad: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPoolGrad", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(grad) + return op.execute(Int(1)) +} + +/// Computes second-order gradients of the maxpooling function. +/// +/// - Parameters: +/// - orig_input: The original input tensor. +/// - orig_output: The original output tensor. +/// - grad: 4-D. Gradients of gradients w.r.t. the input of `max_pool`. +/// +/// - Attrs: +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// +/// - Output output: Gradients of gradients w.r.t. the input to `max_pool`. +@inlinable @inline(__always) +public static func maxPoolGradGrad( + origInput: Tensor, + origOutput: Tensor, + grad: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPoolGradGrad", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(grad) + return op.execute(Int(1)) +} + +/// Computes second-order gradients of the maxpooling function. +/// +/// - Parameters: +/// - orig_input: The original input tensor. +/// - orig_output: The original output tensor. +/// - grad: 4-D. Gradients of gradients w.r.t. the input of `max_pool`. +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// +/// - Attrs: +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// +/// - Output output: Gradients of gradients w.r.t. the input to `max_pool`. +@inlinable @inline(__always) +public static func maxPoolGradGradV2( + origInput: Tensor, + origOutput: Tensor, + grad: Tensor, + ksize: Tensor, + strides: Tensor, + padding: Padding, + dataFormat: DataFormat = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPoolGradGradV2", nOutputs) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(grad) + op.addInput(ksize) + op.addInput(strides) + return op.execute(Int(1)) +} + +/// Computes second-order gradients of the maxpooling function. +/// +/// - Parameters: +/// - input: The original input. +/// - grad: 4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. the +/// input of `max_pool`. +/// - argmax: The indices of the maximum values chosen for each output of `max_pool`. +/// +/// - Attrs: +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// - padding: The type of padding algorithm to use. +/// - include_batch_in_index: Whether to include batch dimension in flattened index of `argmax`. +/// +/// - Output output: Gradients of gradients w.r.t. the input of `max_pool`. +@inlinable @inline(__always) +public static func maxPoolGradGradWithArgmax< + Targmax: BinaryInteger & TensorFlowScalar, + T: Numeric & TensorFlowScalar +>( + _ input: Tensor, + grad: Tensor, + argmax: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + includeBatchInIndex: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPoolGradGradWithArgmax", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("include_batch_in_index", includeBatchInIndex) + op.updateAttribute("Targmax", Targmax.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(grad) + op.addInput(argmax) + return op.execute(Int(1)) +} + +/// Computes gradients of the maxpooling function. +/// +/// - Parameters: +/// - orig_input: The original input tensor. +/// - orig_output: The original output tensor. +/// - grad: 4-D. Gradients w.r.t. the output of `max_pool`. +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// +/// - Attrs: +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// +/// - Output output: Gradients w.r.t. the input to `max_pool`. +@inlinable @inline(__always) +public static func maxPoolGradV2( + origInput: Tensor, + origOutput: Tensor, + grad: Tensor, + ksize: Tensor, + strides: Tensor, + padding: Padding, + dataFormat: DataFormat = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPoolGradV2", nOutputs) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(grad) + op.addInput(ksize) + op.addInput(strides) + return op.execute(Int(1)) +} + +/// Computes gradients of the maxpooling function. +/// +/// - Parameters: +/// - input: The original input. +/// - grad: 4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. the +/// output of `max_pool`. +/// - argmax: The indices of the maximum values chosen for each output of `max_pool`. +/// +/// - Attrs: +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// - padding: The type of padding algorithm to use. +/// - include_batch_in_index: Whether to include batch dimension in flattened index of `argmax`. +/// +/// - Output output: Gradients w.r.t. the input of `max_pool`. +@inlinable @inline(__always) +public static func maxPoolGradWithArgmax< + Targmax: BinaryInteger & TensorFlowScalar, + T: Numeric & TensorFlowScalar +>( + _ input: Tensor, + grad: Tensor, + argmax: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + includeBatchInIndex: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPoolGradWithArgmax", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("include_batch_in_index", includeBatchInIndex) + op.updateAttribute("Targmax", Targmax.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(grad) + op.addInput(argmax) + return op.execute(Int(1)) +} + +/// Performs max pooling on the input. +/// +/// - Parameters: +/// - input: 4-D input to pool over. +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// +/// - Attrs: +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// +/// - Output output: The max pooled output tensor. +@inlinable @inline(__always) +public static func maxPoolV2( + _ input: Tensor, + ksize: Tensor, + strides: Tensor, + padding: Padding, + dataFormat: DataFormat4 = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPoolV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.addInput(input) + op.addInput(ksize) + op.addInput(strides) + return op.execute(Int(1)) +} + +/// Performs max pooling on the input and outputs both max values and indices. +/// +/// The indices in `argmax` are flattened, so that a maximum value at position +/// `[b, y, x, c]` becomes flattened index: +/// `(y * width + x) * channels + c` if `include_batch_in_index` is False; +/// `((b * height + y) * width + x) * channels + c` if `include_batch_in_index` is True. +/// +/// The indices returned are always in `[0, height) x [0, width)` before flattening, +/// even if padding is involved and the mathematically correct answer is outside +/// (either negative or too large). This is a bug, but fixing it is difficult to do +/// in a safe backwards compatible way, especially due to flattening. +/// +/// - Parameter input: 4-D with shape `[batch, height, width, channels]`. Input to pool over. +/// +/// - Attrs: +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// - padding: The type of padding algorithm to use. +/// - include_batch_in_index: Whether to include batch dimension in flattened index of `argmax`. +/// +/// - Outputs: +/// - output: The max pooled output tensor. +/// - argmax: 4-D. The flattened indices of the max values chosen for each output. +@inlinable @inline(__always) +public static func maxPoolWithArgmax< + Targmax: BinaryInteger & TensorFlowScalar, + T: Numeric & TensorFlowScalar +>( + _ input: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + includeBatchInIndex: Bool = false +) -> (output: Tensor, argmax: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("MaxPoolWithArgmax", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("Targmax", Targmax.tensorFlowDataType) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("include_batch_in_index", includeBatchInIndex) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) +} + +/// Returns the max of x and y (i.e. x > y ? x : y) element-wise. +/// +/// *NOTE*: `Maximum` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func maximum( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Maximum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Computes the mean of elements across dimensions of a tensor. +/// +/// Reduces `input` along the dimensions given in `axis`. Unless +/// `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in +/// `axis`. If `keep_dims` is true, the reduced dimensions are +/// retained with length 1. +/// +/// - Parameters: +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. +/// +/// - Attr keep_dims: If true, retain reduced dimensions with length 1. +/// +/// - Output output: The reduced tensor. +@inlinable @inline(__always) +public static func mean< + T: Numeric & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Mean", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) +} + +/// Forwards the value of an available tensor from `inputs` to `output`. +/// +/// `Merge` waits for at least one of the tensors in `inputs` to become available. +/// It is usually combined with `Switch` to implement branching. +/// +/// `Merge` forwards the first tensor to become available to `output`, and sets +/// `value_index` to its index in `inputs`. +/// +/// - Parameter inputs: The input tensors, exactly one of which will become available. +/// +/// - Outputs: +/// - output: Will be set to the available input tensor. +/// - value_index: The index of the chosen input tensor in `inputs`. +@inlinable @inline(__always) +public static func merge( + inputs: [Tensor] +) -> (output: Tensor, valueIndex: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("Merge", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", inputs.count) + op.addInputList(inputs) + return op.execute(Int(1), Int(1)) +} + +/// Merges summaries. +/// +/// This op creates a +/// [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) +/// protocol buffer that contains the union of all the values in the input +/// summaries. +/// +/// When the Op is run, it reports an `InvalidArgument` error if multiple values +/// in the summaries to merge use the same tag. +/// +/// - Parameter inputs: Can be of any shape. Each must contain serialized `Summary` protocol +/// buffers. +/// +/// - Output summary: Scalar. Serialized `Summary` protocol buffer. +@inlinable @inline(__always) +public static func mergeSummary( + inputs: [StringTensor] +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("MergeSummary", nOutputs) + op.updateAttribute("N", inputs.count) + op.addInputList(inputs) + return op.execute(Int(1)) +} + +/// V2 format specific: merges the metadata files of sharded checkpoints. The +/// +/// result is one logical checkpoint, with one physical metadata file and renamed +/// data files. +/// +/// Intended for "grouping" multiple checkpoints in a sharded checkpoint setup. +/// +/// If delete_old_dirs is true, attempts to delete recursively the dirname of each +/// path in the input checkpoint_prefixes. This is useful when those paths are non +/// user-facing temporary locations. +/// +/// - Parameters: +/// - checkpoint_prefixes: prefixes of V2 checkpoints to merge. +/// - destination_prefix: scalar. The desired final prefix. Allowed to be the same +/// as one of the checkpoint_prefixes. +/// +/// - Attr delete_old_dirs: see above. +@inlinable @inline(__always) +public static func mergeV2Checkpoints( + checkpointPrefixes: StringTensor, + destinationPrefix: StringTensor, + deleteOldDirs: Bool = true +) { + let nOutputs = 0 + let op = makeOp("MergeV2Checkpoints", nOutputs) + op.updateAttribute("delete_old_dirs", deleteOldDirs) + op.addInput(checkpointPrefixes) + op.addInput(destinationPrefix) + op.execute() +} + +/// Transforms a spectrogram into a form that's useful for speech recognition. +/// +/// Mel Frequency Cepstral Coefficients are a way of representing audio data that's +/// been effective as an input feature for machine learning. They are created by +/// taking the spectrum of a spectrogram (a 'cepstrum'), and discarding some of the +/// higher frequencies that are less significant to the human ear. They have a long +/// history in the speech recognition world, and https://en.wikipedia.org/wiki/Mel-frequency_cepstrum +/// is a good resource to learn more. +/// +/// - Parameters: +/// - spectrogram: Typically produced by the Spectrogram op, with magnitude_squared +/// set to true. +/// - sample_rate: How many samples per second the source audio used. +/// +/// - Attrs: +/// - upper_frequency_limit: The highest frequency to use when calculating the +/// ceptstrum. +/// - lower_frequency_limit: The lowest frequency to use when calculating the +/// ceptstrum. +/// - filterbank_channel_count: Resolution of the Mel bank used internally. +/// - dct_coefficient_count: How many output channels to produce per time slice. +@inlinable @inline(__always) +public static func mfcc( + spectrogram: Tensor, + sampleRate: Tensor, + upperFrequencyLimit: Double = 4000, + lowerFrequencyLimit: Double = 20, + filterbankChannelCount: Int64 = 40, + dctCoefficientCount: Int64 = 13 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Mfcc", nOutputs) + op.updateAttribute("upper_frequency_limit", upperFrequencyLimit) + op.updateAttribute("lower_frequency_limit", lowerFrequencyLimit) + op.updateAttribute("filterbank_channel_count", filterbankChannelCount) + op.updateAttribute("dct_coefficient_count", dctCoefficientCount) + op.addInput(spectrogram) + op.addInput(sampleRate) + return op.execute(Int(1)) +} + +/// Computes the minimum of elements across dimensions of a tensor. +/// +/// Reduces `input` along the dimensions given in `axis`. Unless +/// `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in +/// `axis`. If `keep_dims` is true, the reduced dimensions are +/// retained with length 1. +/// +/// - Parameters: +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. +/// +/// - Attr keep_dims: If true, retain reduced dimensions with length 1. +/// +/// - Output output: The reduced tensor. +@inlinable @inline(__always) +public static func min< + T: Numeric & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Min", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) +} + +/// Returns the min of x and y (i.e. x < y ? x : y) element-wise. +/// +/// *NOTE*: `Minimum` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func minimum( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Minimum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Pads a tensor with mirrored values. +/// +/// This operation pads a `input` with mirrored values according to the `paddings` +/// you specify. `paddings` is an integer tensor with shape `[n, 2]`, where n is +/// the rank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates +/// how many values to add before the contents of `input` in that dimension, and +/// `paddings[D, 1]` indicates how many values to add after the contents of `input` +/// in that dimension. Both `paddings[D, 0]` and `paddings[D, 1]` must be no greater +/// than `input.dim_size(D)` (or `input.dim_size(D) - 1`) if `copy_border` is true +/// (if false, respectively). +/// +/// The padded size of each dimension D of the output is: +/// +/// `paddings(D, 0) + input.dim_size(D) + paddings(D, 1)` +/// +/// For example: +/// +/// ``` +/// # 't' is [[1, 2, 3], [4, 5, 6]]. +/// # 'paddings' is [[1, 1]], [2, 2]]. +/// # 'mode' is SYMMETRIC. +/// # rank of 't' is 2. +/// pad(t, paddings) ==> [[2, 1, 1, 2, 3, 3, 2] +/// [2, 1, 1, 2, 3, 3, 2] +/// [5, 4, 4, 5, 6, 6, 5] +/// [5, 4, 4, 5, 6, 6, 5]] +/// ``` +/// +/// - Parameters: +/// - input: The input tensor to be padded. +/// - paddings: A two-column matrix specifying the padding sizes. The number of +/// rows must be the same as the rank of `input`. +/// +/// - Attr mode: Either `REFLECT` or `SYMMETRIC`. In reflect mode the padded regions +/// do not include the borders, while in symmetric mode the padded regions +/// do include the borders. For example, if `input` is `[1, 2, 3]` and `paddings` +/// is `[0, 2]`, then the output is `[1, 2, 3, 2, 1]` in reflect mode, and +/// it is `[1, 2, 3, 3, 2]` in symmetric mode. +/// +/// - Output output: The padded tensor. +@inlinable @inline(__always) +public static func mirrorPad< + T: TensorFlowScalar, + Tpaddings: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + paddings: Tensor, + mode: Mode5 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MirrorPad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) + op.updateAttribute("mode", mode.cName) + op.addInput(input) + op.addInput(paddings) + return op.execute(Int(1)) +} + +/// Gradient op for `MirrorPad` op. This op folds a mirror-padded tensor. +/// +/// This operation folds the padded areas of `input` by `MirrorPad` according to the +/// `paddings` you specify. `paddings` must be the same as `paddings` argument +/// given to the corresponding `MirrorPad` op. +/// +/// The folded size of each dimension D of the output is: +/// +/// `input.dim_size(D) - paddings(D, 0) - paddings(D, 1)` +/// +/// For example: +/// +/// ``` +/// # 't' is [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. +/// # 'paddings' is [[0, 1]], [0, 1]]. +/// # 'mode' is SYMMETRIC. +/// # rank of 't' is 2. +/// pad(t, paddings) ==> [[ 1, 5] +/// [11, 28]] +/// ``` +/// +/// - Parameters: +/// - input: The input tensor to be folded. +/// - paddings: A two-column matrix specifying the padding sizes. The number of +/// rows must be the same as the rank of `input`. +/// +/// - Attr mode: The mode used in the `MirrorPad` op. +/// +/// - Output output: The folded tensor. +@inlinable @inline(__always) +public static func mirrorPadGrad< + T: TensorFlowScalar, + Tpaddings: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + paddings: Tensor, + mode: Mode5 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MirrorPadGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) + op.updateAttribute("mode", mode.cName) + op.addInput(input) + op.addInput(paddings) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func mixedStruct( + nA: Int64 +) -> (a: [Tensor], b: Tensor) { + let nOutputs = Int(nA) + Int(1) + let op = makeOp("MixedStruct", nOutputs) + op.updateAttribute("n_a", nA) + return op.execute(Int(nA), Int(1)) +} + +/// Returns element-wise remainder of division. This emulates C semantics in that +/// +/// the result here is consistent with a truncating divide. E.g. +/// `tf.truncatediv(x, y) * y + truncate_mod(x, y) = x`. +/// +/// *NOTE*: `Mod` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func mod( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Mod", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Identity transformation that models performance. +/// +/// Identity transformation that models performance. +/// +/// - Parameter input_dataset: A variant tensor representing the input dataset. +@inlinable @inline(__always) +public static func modelDataset( + inputDataset: VariantHandle, + cpuBudget: Int64 = 0, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ModelDataset", nOutputs) + op.updateAttribute("cpu_budget", cpuBudget) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + return op.execute(Int(1)) +} + +/// Returns x * y element-wise. +/// +/// *NOTE*: `Multiply` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func mul( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Mul", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns x * y element-wise. Returns zero if y is zero, even if x if infinite or NaN. +/// +/// *NOTE*: `Mul` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func mulNoNan( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MulNoNan", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Creates a MultiDeviceIterator resource. +/// +/// - Attrs: +/// - devices: A list of devices the iterator works across. +/// - shared_name: If non-empty, this resource will be shared under the given name +/// across multiple sessions. +/// - container: If non-empty, this resource is placed in the given container. +/// Otherwise, a default container is used. +/// - output_types: The type list for the return values. +/// - output_shapes: The list of shapes being produced. +/// +/// - Output handle: Handle to the resource created. +@inlinable @inline(__always) +public static func multiDeviceIterator( + devices: [String], + sharedName: String, + container: String, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("MultiDeviceIterator", nOutputs) + op.updateAttribute("devices", devices) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("container", container) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + return op.execute(Int(1)) +} + +/// Generates a MultiDeviceIterator resource from its provided string handle. +/// +/// - Parameter string_handle: String representing the resource. +/// +/// - Attrs: +/// - output_types: The type list for the return values. +/// - output_shapes: The list of shapes being produced. +/// +/// - Output multi_device_iterator: A MultiDeviceIterator resource. +@inlinable @inline(__always) +public static func multiDeviceIteratorFromStringHandle( + stringHandle: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("MultiDeviceIteratorFromStringHandle", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(stringHandle) + return op.execute(Int(1)) +} + +/// Gets next element for the provided shard number. +/// +/// - Parameters: +/// - multi_device_iterator: A MultiDeviceIterator resource. +/// - shard_num: Integer representing which shard to fetch data for. +/// - incarnation_id: Which incarnation of the MultiDeviceIterator is running. +/// +/// - Attrs: +/// - output_types: The type list for the return values. +/// - output_shapes: The list of shapes being produced. +/// +/// - Output components: Result of the get_next on the dataset. +@inlinable @inline(__always) +public static func multiDeviceIteratorGetNextFromShard( + multiDeviceIterator: ResourceHandle, + shardNum: Tensor, + incarnationId: Tensor, + outputShapes: [TensorShape?] +) -> OutputTypes { + let nOutputs = Int(OutputTypes._typeList.count) + let op = makeOp("MultiDeviceIteratorGetNextFromShard", nOutputs) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(multiDeviceIterator) + op.addInput(shardNum) + op.addInput(incarnationId) + return op.execute(Int(OutputTypes._typeList.count)) +} + +/// Initializes the multi device iterator with the given dataset. +/// +/// - Parameters: +/// - dataset: Dataset to be iterated upon. +/// - multi_device_iterator: A MultiDeviceIteratorResource. +/// - max_buffer_size: The maximum size of the host side per device buffer to keep. +/// +/// - Output incarnation_id: An int64 indicating which incarnation of the MultiDeviceIterator +/// is running. +@inlinable @inline(__always) +public static func multiDeviceIteratorInit( + dataset: VariantHandle, + multiDeviceIterator: ResourceHandle, + maxBufferSize: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MultiDeviceIteratorInit", nOutputs) + op.addInput(dataset) + op.addInput(multiDeviceIterator) + op.addInput(maxBufferSize) + return op.execute(Int(1)) +} + +/// Produces a string handle for the given MultiDeviceIterator. +/// +/// - Parameter multi_device_iterator: A MultiDeviceIterator resource. +/// +/// - Output string_handle: A string representing the resource. +@inlinable @inline(__always) +public static func multiDeviceIteratorToStringHandle( + multiDeviceIterator: ResourceHandle +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("MultiDeviceIteratorToStringHandle", nOutputs) + op.addInput(multiDeviceIterator) + return op.execute(Int(1)) +} + +/// Draws samples from a multinomial distribution. +/// +/// - Parameters: +/// - logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]` +/// represents the unnormalized log probabilities for all classes. +/// - num_samples: 0-D. Number of independent samples to draw for each row slice. +/// +/// - Attrs: +/// - seed: If either seed or seed2 is set to be non-zero, the internal random number +/// generator is seeded by the given seed. Otherwise, a random seed is used. +/// - seed2: A second seed to avoid seed collision. +/// +/// - Output output: 2-D Tensor with shape `[batch_size, num_samples]`. Each slice `[i, :]` +/// contains the drawn class labels with range `[0, num_classes)`. +@inlinable @inline(__always) +public static func multinomial< + T: Numeric & TensorFlowScalar, + OutputDtype: BinaryInteger & TensorFlowScalar +>( + logits: Tensor, + numSamples: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Multinomial", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("output_dtype", OutputDtype.tensorFlowDataType) + op.addInput(logits) + op.addInput(numSamples) + return op.execute(Int(1)) +} + +/// Creates an empty hash table that uses tensors as the backing store. +/// +/// It uses "open addressing" with quadratic reprobing to resolve +/// collisions. +/// +/// This op creates a mutable hash table, specifying the type of its keys and +/// values. Each value must be a scalar. Data can be inserted into the table using +/// the insert operations. It does not support the initialization operation. +/// +/// - Parameter empty_key: The key used to represent empty key buckets internally. Must not +/// be used in insert or lookup operations. +/// +/// - Attrs: +/// - container: If non-empty, this table is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this table is shared under the given name across +/// multiple sessions. +/// - key_dtype: Type of the table keys. +/// - value_dtype: Type of the table values. +/// - value_shape: The shape of each value. +/// - initial_num_buckets: The initial number of hash table buckets. Must be a power +/// to 2. +/// - max_load_factor: The maximum ratio between number of entries and number of +/// buckets before growing the table. Must be between 0 and 1. +/// +/// - Output table_handle: Handle to a table. +@inlinable @inline(__always) +public static func mutableDenseHashTableV2( + emptyKey: Tensor, + deletedKey: Tensor, + container: String, + sharedName: String, + useNodeNameSharing: Bool = false, + valueDtype: TensorDataType, + valueShape: TensorShape?, + initialNumBuckets: Int64 = 131072, + maxLoadFactor: Double = 0.8 +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("MutableDenseHashTableV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("use_node_name_sharing", useNodeNameSharing) + op.updateAttribute("key_dtype", KeyDtype.tensorFlowDataType) + op.updateAttribute("value_dtype", valueDtype) + op.updateAttribute("value_shape", valueShape) + op.updateAttribute("initial_num_buckets", initialNumBuckets) + op.updateAttribute("max_load_factor", maxLoadFactor) + op.addInput(emptyKey) + op.addInput(deletedKey) + return op.execute(Int(1)) +} + +/// Creates an empty hash table. +/// +/// This op creates a mutable hash table, specifying the type of its keys and +/// values. Each value must be a vector. Data can be inserted into the table using +/// the insert operations. It does not support the initialization operation. +/// +/// - Attrs: +/// - container: If non-empty, this table is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this table is shared under the given name across +/// multiple sessions. +/// - key_dtype: Type of the table keys. +/// - value_dtype: Type of the table values. +/// +/// - Output table_handle: Handle to a table. +@inlinable @inline(__always) +public static func mutableHashTableOfTensorsV2( + container: String, + sharedName: String, + useNodeNameSharing: Bool = false, + keyDtype: TensorDataType, + valueDtype: TensorDataType, + valueShape: TensorShape? +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("MutableHashTableOfTensorsV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("use_node_name_sharing", useNodeNameSharing) + op.updateAttribute("key_dtype", keyDtype) + op.updateAttribute("value_dtype", valueDtype) + op.updateAttribute("value_shape", valueShape) + return op.execute(Int(1)) +} + +/// Creates an empty hash table. +/// +/// This op creates a mutable hash table, specifying the type of its keys and +/// values. Each value must be a scalar. Data can be inserted into the table using +/// the insert operations. It does not support the initialization operation. +/// +/// - Attrs: +/// - container: If non-empty, this table is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this table is shared under the given name across +/// multiple sessions. +/// - use_node_name_sharing: If true and shared_name is empty, the table is shared +/// using the node name. +/// - key_dtype: Type of the table keys. +/// - value_dtype: Type of the table values. +/// +/// - Output table_handle: Handle to a table. +@inlinable @inline(__always) +public static func mutableHashTableV2( + container: String, + sharedName: String, + useNodeNameSharing: Bool = false, + keyDtype: TensorDataType, + valueDtype: TensorDataType +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("MutableHashTableV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("use_node_name_sharing", useNodeNameSharing) + op.updateAttribute("key_dtype", keyDtype) + op.updateAttribute("value_dtype", valueDtype) + return op.execute(Int(1)) +} + +/// Locks a mutex resource. The output is the lock. So long as the lock tensor +/// +/// is alive, any other request to use `MutexLock` with this mutex will wait. +/// +/// This is particularly useful for creating a critical section when used in +/// conjunction with `MutexLockIdentity`: +/// +/// ```python +/// +/// mutex = mutex_v2( +/// shared_name=handle_name, container=container, name=name) +/// +/// def execute_in_critical_section(fn, *args, **kwargs): +/// lock = gen_resource_variable_ops.mutex_lock(mutex) +/// +/// with ops.control_dependencies([lock]): +/// r = fn(*args, **kwargs) +/// +/// with ops.control_dependencies(nest.flatten(r)): +/// with ops.colocate_with(mutex): +/// ensure_lock_exists = mutex_lock_identity(lock) +/// +/// # Make sure that if any element of r is accessed, all of +/// # them are executed together. +/// r = nest.map_structure(tf.identity, r) +/// +/// with ops.control_dependencies([ensure_lock_exists]): +/// return nest.map_structure(tf.identity, r) +/// ``` +/// +/// While `fn` is running in the critical section, no other functions which wish to +/// use this critical section may run. +/// +/// Often the use case is that two executions of the same graph, in parallel, +/// wish to run `fn`; and we wish to ensure that only one of them executes +/// at a time. This is especially important if `fn` modifies one or more +/// variables at a time. +/// +/// It is also useful if two separate functions must share a resource, but we +/// wish to ensure the usage is exclusive. +/// +/// - Parameter mutex: The mutex resource to lock. +/// +/// - Output mutex_lock: A tensor that keeps a shared pointer to a lock on the mutex; +/// when the Tensor is destroyed, the use count on the shared pointer is decreased +/// by 1. When it reaches 0, the lock is released. +@inlinable @inline(__always) +public static func mutexLock( + mutex: ResourceHandle +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("MutexLock", nOutputs) + op.addInput(mutex) + return op.execute(Int(1)) +} + +/// Creates a Mutex resource that can be locked by `MutexLock`. +/// +/// - Attrs: +/// - container: If non-empty, this variable is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this variable is named in the given bucket +/// with this shared_name. Otherwise, the node name is used instead. +/// +/// - Output resource: The mutex resource. +@inlinable @inline(__always) +public static func mutexV2( + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("MutexV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func nInPolymorphicTwice( + _ a: [Tensor], + _ b: [Tensor] +) { + let nOutputs = 0 + let op = makeOp("NInPolymorphicTwice", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.addInputList(b) + op.execute() +} + +@inlinable @inline(__always) +public static func nInTwice( + _ a: [Tensor], + _ b: [StringTensor] +) { + let nOutputs = 0 + let op = makeOp("NInTwice", nOutputs) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.addInputList(b) + op.execute() +} + +@inlinable @inline(__always) +public static func nInTwoTypeVariables< + S: TensorFlowScalar, + T: TensorFlowScalar +>( + _ a: [Tensor], + _ b: [Tensor] +) { + let nOutputs = 0 + let op = makeOp("NInTwoTypeVariables", nOutputs) + op.updateAttribute("S", S.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.addInputList(b) + op.execute() +} + +@inlinable @inline(__always) +public static func nIntsIn( + _ a: [Tensor] +) { + let nOutputs = 0 + let op = makeOp("NIntsIn", nOutputs) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.execute() +} + +@inlinable @inline(__always) +public static func nIntsOut( + n: Int64 +) -> [Tensor] { + let nOutputs = Int(n) + let op = makeOp("NIntsOut", nOutputs) + op.updateAttribute("N", n) + return op.execute(Int(n)) +} + +@inlinable @inline(__always) +public static func nIntsOutDefault( + n: Int64 = 3 +) -> [Tensor] { + let nOutputs = Int(n) + let op = makeOp("NIntsOutDefault", nOutputs) + op.updateAttribute("N", n) + return op.execute(Int(n)) +} + +@inlinable @inline(__always) +public static func nPolymorphicIn( + _ a: [Tensor] +) { + let nOutputs = 0 + let op = makeOp("NPolymorphicIn", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.execute() +} + +@inlinable @inline(__always) +public static func nPolymorphicOut( + n: Int64 +) -> [Tensor] { + let nOutputs = Int(n) + let op = makeOp("NPolymorphicOut", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", n) + return op.execute(Int(n)) +} + +@inlinable @inline(__always) +public static func nPolymorphicOutDefault( + n: Int64 = 2 +) -> [Tensor] { + let nOutputs = Int(n) + let op = makeOp("NPolymorphicOutDefault", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", n) + return op.execute(Int(n)) +} + +@inlinable @inline(__always) +public static func nPolymorphicRestrictIn( + _ a: [Tensor] +) { + let nOutputs = 0 + let op = makeOp("NPolymorphicRestrictIn", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.execute() +} + +@inlinable @inline(__always) +public static func nPolymorphicRestrictIn( + _ a: [StringTensor] +) { + let nOutputs = 0 + let op = makeOp("NPolymorphicRestrictIn", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.execute() +} + +@inlinable @inline(__always) +public static func nPolymorphicRestrictOut( + n: Int64 +) -> [Tensor] { + let nOutputs = Int(n) + let op = makeOp("NPolymorphicRestrictOut", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", n) + return op.execute(Int(n)) +} + +@inlinable @inline(__always) +public static func nPolymorphicRestrictOut( + n: Int64 +) -> [StringTensor] { + let nOutputs = Int(n) + let op = makeOp("NPolymorphicRestrictOut", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.updateAttribute("N", n) + return op.execute(Int(n)) +} + +/// Outputs a tensor containing the reduction across all input tensors. +/// +/// Outputs a tensor containing the reduction across all input tensors passed to ops +/// within the same `shared_name. +/// +/// The graph should be constructed so if one op runs with shared_name value `c`, +/// then `num_devices` ops will run with shared_name value `c`. Failure to do so +/// will cause the graph execution to fail to complete. +/// +/// input: the input to the reduction +/// data: the value of the reduction across all `num_devices` devices. +/// reduction: the reduction operation to perform. +/// num_devices: The number of devices participating in this reduction. +/// shared_name: Identifier that shared between ops of the same reduction. +@inlinable @inline(__always) +public static func ncclAllReduce( + _ input: Tensor, + reduction: Reduction, + numDevices: Int64, + sharedName: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("NcclAllReduce", nOutputs) + op.updateAttribute("reduction", reduction.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("num_devices", numDevices) + op.updateAttribute("shared_name", sharedName) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Sends `input` to all devices that are connected to the output. +/// +/// Sends `input` to all devices that are connected to the output. +/// +/// The graph should be constructed so that all ops connected to the output have a +/// valid device assignment, and the op itself is assigned one of these devices. +/// +/// input: The input to the broadcast. +/// output: The same as input. +/// shape: The shape of the input tensor. +/// +@inlinable @inline(__always) +public static func ncclBroadcast( + _ input: Tensor, + shape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("NcclBroadcast", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Reduces `input` from `num_devices` using `reduction` to a single device. +/// +/// Reduces `input` from `num_devices` using `reduction` to a single device. +/// +/// The graph should be constructed so that all inputs have a valid device +/// assignment, and the op itself is assigned one of these devices. +/// +/// input: The input to the reduction. +/// data: the value of the reduction across all `num_devices` devices. +/// reduction: the reduction operation to perform. +@inlinable @inline(__always) +public static func ncclReduce( + _ input: [Tensor], + reduction: Reduction +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("NcclReduce", nOutputs) + op.updateAttribute("reduction", reduction.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("num_devices", input.count) + op.addInputList(input) + return op.execute(Int(1)) +} + +/// Selects the k nearest centers for each point. +/// +/// Rows of points are assumed to be input points. Rows of centers are assumed to be +/// the list of candidate centers. For each point, the k centers that have least L2 +/// distance to it are computed. +/// +/// - Parameters: +/// - points: Matrix of shape (n, d). Rows are assumed to be input points. +/// - centers: Matrix of shape (m, d). Rows are assumed to be centers. +/// - k: Number of nearest centers to return for each point. If k is larger than m, then +/// only m centers are returned. +/// +/// - Outputs: +/// - nearest_center_indices: Matrix of shape (n, min(m, k)). Each row contains the indices of the centers +/// closest to the corresponding point, ordered by increasing distance. +/// - nearest_center_distances: Matrix of shape (n, min(m, k)). Each row contains the squared L2 distance to the +/// corresponding center in nearest_center_indices. +@inlinable @inline(__always) +public static func nearestNeighbors( + points: Tensor, + centers: Tensor, + k: Tensor +) -> (nearestCenterIndices: Tensor, nearestCenterDistances: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("NearestNeighbors", nOutputs) + op.addInput(points) + op.addInput(centers) + op.addInput(k) + return op.execute(Int(1), Int(1)) +} + +/// Computes numerical negative value element-wise. +/// +/// I.e., \\(y = -x\\). +@inlinable @inline(__always) +public static func neg( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Neg", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Returns the next representable value of `x1` in the direction of `x2`, element-wise. +/// +/// This operation returns the same result as the C++ std::nextafter function. +/// +/// It can also return a subnormal number. +/// +/// @compatibility(cpp) +/// Equivalent to C++ std::nextafter function. +/// @end_compatibility +@inlinable @inline(__always) +public static func nextAfter( + x1: Tensor, + x2: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("NextAfter", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x1) + op.addInput(x2) + return op.execute(Int(1)) +} + +/// Makes its input available to the next iteration. +/// +/// - Parameter data: The tensor to be made available to the next iteration. +/// +/// - Output output: The same tensor as `data`. +@inlinable @inline(__always) +public static func nextIteration( + data: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("NextIteration", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(data) + return op.execute(Int(1)) +} + +/// Does nothing. Only useful as a placeholder for control edges. +@inlinable @inline(__always) +public static func noOp( +) { + let nOutputs = 0 + let op = makeOp("NoOp", nOutputs) + + op.execute() +} + +/// Non-deterministically generates some integers. +/// +/// This op may use some OS-provided source of non-determinism (e.g. an RNG), so each execution will give different results. +/// +/// - Parameter shape: The shape of the output tensor. +/// +/// - Attr dtype: The type of the output. +/// +/// - Output output: Non-deterministic integer values with specified shape. +@inlinable @inline(__always) +public static func nonDeterministicInts< + Dtype: TensorFlowScalar, + ShapeDtype: TensorFlowScalar +>( + shape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("NonDeterministicInts", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(shape) + return op.execute(Int(1)) +} + +/// Greedily selects a subset of bounding boxes in descending order of score, +/// +/// pruning away boxes that have high intersection-over-union (IOU) overlap +/// with previously selected boxes. Bounding boxes are supplied as +/// [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any +/// diagonal pair of box corners and the coordinates can be provided as normalized +/// (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm +/// is agnostic to where the origin is in the coordinate system. Note that this +/// algorithm is invariant to orthogonal transformations and translations +/// of the coordinate system; thus translating or reflections of the coordinate +/// system result in the same boxes being selected by the algorithm. +/// The output of this operation is a set of integers indexing into the input +/// collection of bounding boxes representing the selected boxes. The bounding +/// box coordinates corresponding to the selected indices can then be obtained +/// using the `tf.gather operation`. For example: +/// selected_indices = tf.image.non_max_suppression( +/// boxes, scores, max_output_size, iou_threshold) +/// selected_boxes = tf.gather(boxes, selected_indices) +/// +/// - Parameters: +/// - boxes: A 2-D float tensor of shape `[num_boxes, 4]`. +/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single +/// score corresponding to each box (each row of boxes). +/// - max_output_size: A scalar integer tensor representing the maximum number of +/// boxes to be selected by non max suppression. +/// +/// - Attr iou_threshold: A float representing the threshold for deciding whether boxes +/// overlap too much with respect to IOU. +/// +/// - Output selected_indices: A 1-D integer tensor of shape `[M]` representing the selected +/// indices from the boxes tensor, where `M <= max_output_size`. +@inlinable @inline(__always) +public static func nonMaxSuppression( + boxes: Tensor, + scores: Tensor, + maxOutputSize: Tensor, + iouThreshold: Double = 0.5 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("NonMaxSuppression", nOutputs) + op.updateAttribute("iou_threshold", iouThreshold) + op.addInput(boxes) + op.addInput(scores) + op.addInput(maxOutputSize) + return op.execute(Int(1)) +} + +/// Greedily selects a subset of bounding boxes in descending order of score, +/// +/// pruning away boxes that have high intersection-over-union (IOU) overlap +/// with previously selected boxes. Bounding boxes are supplied as +/// [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any +/// diagonal pair of box corners and the coordinates can be provided as normalized +/// (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm +/// is agnostic to where the origin is in the coordinate system. Note that this +/// algorithm is invariant to orthogonal transformations and translations +/// of the coordinate system; thus translating or reflections of the coordinate +/// system result in the same boxes being selected by the algorithm. +/// +/// The output of this operation is a set of integers indexing into the input +/// collection of bounding boxes representing the selected boxes. The bounding +/// box coordinates corresponding to the selected indices can then be obtained +/// using the `tf.gather operation`. For example: +/// +/// selected_indices = tf.image.non_max_suppression_v2( +/// boxes, scores, max_output_size, iou_threshold) +/// selected_boxes = tf.gather(boxes, selected_indices) +/// +/// - Parameters: +/// - boxes: A 2-D float tensor of shape `[num_boxes, 4]`. +/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single +/// score corresponding to each box (each row of boxes). +/// - max_output_size: A scalar integer tensor representing the maximum number of +/// boxes to be selected by non max suppression. +/// - iou_threshold: A 0-D float tensor representing the threshold for deciding whether +/// boxes overlap too much with respect to IOU. +/// +/// - Output selected_indices: A 1-D integer tensor of shape `[M]` representing the selected +/// indices from the boxes tensor, where `M <= max_output_size`. +@inlinable @inline(__always) +public static func nonMaxSuppressionV2( + boxes: Tensor, + scores: Tensor, + maxOutputSize: Tensor, + iouThreshold: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("NonMaxSuppressionV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(boxes) + op.addInput(scores) + op.addInput(maxOutputSize) + op.addInput(iouThreshold) + return op.execute(Int(1)) +} + +/// Greedily selects a subset of bounding boxes in descending order of score, +/// +/// pruning away boxes that have high intersection-over-union (IOU) overlap +/// with previously selected boxes. Bounding boxes with score less than +/// `score_threshold` are removed. Bounding boxes are supplied as +/// [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any +/// diagonal pair of box corners and the coordinates can be provided as normalized +/// (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm +/// is agnostic to where the origin is in the coordinate system and more +/// generally is invariant to orthogonal transformations and translations +/// of the coordinate system; thus translating or reflections of the coordinate +/// system result in the same boxes being selected by the algorithm. +/// The output of this operation is a set of integers indexing into the input +/// collection of bounding boxes representing the selected boxes. The bounding +/// box coordinates corresponding to the selected indices can then be obtained +/// using the `tf.gather operation`. For example: +/// selected_indices = tf.image.non_max_suppression_v2( +/// boxes, scores, max_output_size, iou_threshold, score_threshold) +/// selected_boxes = tf.gather(boxes, selected_indices) +/// +/// - Parameters: +/// - boxes: A 2-D float tensor of shape `[num_boxes, 4]`. +/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single +/// score corresponding to each box (each row of boxes). +/// - max_output_size: A scalar integer tensor representing the maximum number of +/// boxes to be selected by non max suppression. +/// - iou_threshold: A 0-D float tensor representing the threshold for deciding whether +/// boxes overlap too much with respect to IOU. +/// - score_threshold: A 0-D float tensor representing the threshold for deciding when to remove +/// boxes based on score. +/// +/// - Output selected_indices: A 1-D integer tensor of shape `[M]` representing the selected +/// indices from the boxes tensor, where `M <= max_output_size`. +@inlinable @inline(__always) +public static func nonMaxSuppressionV3( + boxes: Tensor, + scores: Tensor, + maxOutputSize: Tensor, + iouThreshold: Tensor, + scoreThreshold: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("NonMaxSuppressionV3", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(boxes) + op.addInput(scores) + op.addInput(maxOutputSize) + op.addInput(iouThreshold) + op.addInput(scoreThreshold) + return op.execute(Int(1)) +} + +/// Greedily selects a subset of bounding boxes in descending order of score, +/// +/// pruning away boxes that have high intersection-over-union (IOU) overlap +/// with previously selected boxes. Bounding boxes with score less than +/// `score_threshold` are removed. Bounding boxes are supplied as +/// [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any +/// diagonal pair of box corners and the coordinates can be provided as normalized +/// (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm +/// is agnostic to where the origin is in the coordinate system and more +/// generally is invariant to orthogonal transformations and translations +/// of the coordinate system; thus translating or reflections of the coordinate +/// system result in the same boxes being selected by the algorithm. +/// The output of this operation is a set of integers indexing into the input +/// collection of bounding boxes representing the selected boxes. The bounding +/// box coordinates corresponding to the selected indices can then be obtained +/// using the `tf.gather operation`. For example: +/// selected_indices = tf.image.non_max_suppression_v2( +/// boxes, scores, max_output_size, iou_threshold, score_threshold) +/// selected_boxes = tf.gather(boxes, selected_indices) +/// +/// - Parameters: +/// - boxes: A 2-D float tensor of shape `[num_boxes, 4]`. +/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single +/// score corresponding to each box (each row of boxes). +/// - max_output_size: A scalar integer tensor representing the maximum number of +/// boxes to be selected by non max suppression. +/// - iou_threshold: A 0-D float tensor representing the threshold for deciding whether +/// boxes overlap too much with respect to IOU. +/// - score_threshold: A 0-D float tensor representing the threshold for deciding when to remove +/// boxes based on score. +/// +/// - Attr pad_to_max_output_size: If true, the output `selected_indices` is padded to be of length +/// `max_output_size`. Defaults to false. +/// +/// - Outputs: +/// - selected_indices: A 1-D integer tensor of shape `[M]` representing the selected +/// indices from the boxes tensor, where `M <= max_output_size`. +/// - valid_outputs: A 0-D integer tensor representing the number of valid elements in +/// `selected_indices`, with the valid elements appearing first. +@inlinable @inline(__always) +public static func nonMaxSuppressionV4( + boxes: Tensor, + scores: Tensor, + maxOutputSize: Tensor, + iouThreshold: Tensor, + scoreThreshold: Tensor, + padToMaxOutputSize: Bool = false +) -> (selectedIndices: Tensor, validOutputs: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("NonMaxSuppressionV4", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("pad_to_max_output_size", padToMaxOutputSize) + op.addInput(boxes) + op.addInput(scores) + op.addInput(maxOutputSize) + op.addInput(iouThreshold) + op.addInput(scoreThreshold) + return op.execute(Int(1), Int(1)) +} + +/// Greedily selects a subset of bounding boxes in descending order of score, +/// +/// pruning away boxes that have high overlaps +/// with previously selected boxes. Bounding boxes with score less than +/// `score_threshold` are removed. N-by-n overlap values are supplied as square matrix, +/// which allows for defining a custom overlap criterium (eg. intersection over union, +/// intersection over area, etc.). +/// +/// The output of this operation is a set of integers indexing into the input +/// collection of bounding boxes representing the selected boxes. The bounding +/// box coordinates corresponding to the selected indices can then be obtained +/// using the `tf.gather operation`. For example: +/// +/// selected_indices = tf.image.non_max_suppression_with_overlaps( +/// overlaps, scores, max_output_size, overlap_threshold, score_threshold) +/// selected_boxes = tf.gather(boxes, selected_indices) +/// +/// - Parameters: +/// - overlaps: A 2-D float tensor of shape `[num_boxes, num_boxes]` representing +/// the n-by-n box overlap values. +/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single +/// score corresponding to each box (each row of boxes). +/// - max_output_size: A scalar integer tensor representing the maximum number of +/// boxes to be selected by non max suppression. +/// - overlap_threshold: A 0-D float tensor representing the threshold for deciding whether +/// boxes overlap too. +/// - score_threshold: A 0-D float tensor representing the threshold for deciding when to remove +/// boxes based on score. +/// +/// - Output selected_indices: A 1-D integer tensor of shape `[M]` representing the selected +/// indices from the boxes tensor, where `M <= max_output_size`. +@inlinable @inline(__always) +public static func nonMaxSuppressionWithOverlaps( + overlaps: Tensor, + scores: Tensor, + maxOutputSize: Tensor, + overlapThreshold: Tensor, + scoreThreshold: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("NonMaxSuppressionWithOverlaps", nOutputs) + op.addInput(overlaps) + op.addInput(scores) + op.addInput(maxOutputSize) + op.addInput(overlapThreshold) + op.addInput(scoreThreshold) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func none( +) { + let nOutputs = 0 + let op = makeOp("None", nOutputs) + + op.execute() +} + +/// Returns the truth value of (x != y) element-wise. +/// +/// *NOTE*: `NotEqual` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func notEqual( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("NotEqual", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns the truth value of (x != y) element-wise. +/// +/// *NOTE*: `NotEqual` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func notEqual( + _ x: StringTensor, + _ y: StringTensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("NotEqual", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Finds values of the `n`-th order statistic for the last dimension. +/// +/// If the input is a vector (rank-1), finds the entries which is the nth-smallest +/// value in the vector and outputs their values as scalar tensor. +/// +/// For matrices (resp. higher rank input), computes the entries which is the +/// nth-smallest value in each row (resp. vector along the last dimension). Thus, +/// +/// values.shape = input.shape[:-1] +/// +/// - Parameters: +/// - input: 1-D or higher with last dimension at least `n+1`. +/// - n: 0-D. Position of sorted vector to select along the last dimension (along +/// each row for matrices). Valid range of n is `[0, input.shape[:-1])` +/// +/// - Attr reverse: When set to True, find the nth-largest value in the vector and vice +/// versa. +/// +/// - Output values: The `n`-th order statistic along each last dimensional slice. +@inlinable @inline(__always) +public static func nthElement( + _ input: Tensor, + n: Tensor, + reverse: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("NthElement", nOutputs) + op.updateAttribute("reverse", reverse) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(n) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func old( +) { + let nOutputs = 0 + let op = makeOp("Old", nOutputs) + + op.execute() +} + +/// Returns a one-hot tensor. +/// +/// The locations represented by indices in `indices` take value `on_value`, +/// while all other locations take value `off_value`. +/// +/// If the input `indices` is rank `N`, the output will have rank `N+1`, +/// The new axis is created at dimension `axis` (default: the new axis is +/// appended at the end). +/// +/// If `indices` is a scalar the output shape will be a vector of length `depth`. +/// +/// If `indices` is a vector of length `features`, the output shape will be: +/// ``` +/// features x depth if axis == -1 +/// depth x features if axis == 0 +/// ``` +/// +/// If `indices` is a matrix (batch) with shape `[batch, features]`, +/// the output shape will be: +/// ``` +/// batch x features x depth if axis == -1 +/// batch x depth x features if axis == 1 +/// depth x batch x features if axis == 0 +/// ``` +/// +/// +/// Examples +/// ========= +/// +/// Suppose that +/// ``` +/// indices = [0, 2, -1, 1] +/// depth = 3 +/// on_value = 5.0 +/// off_value = 0.0 +/// axis = -1 +/// ``` +/// +/// Then output is `[4 x 3]`: +/// ``` +/// output = +/// [5.0 0.0 0.0] // one_hot(0) +/// [0.0 0.0 5.0] // one_hot(2) +/// [0.0 0.0 0.0] // one_hot(-1) +/// [0.0 5.0 0.0] // one_hot(1) +/// ``` +/// +/// Suppose that +/// ``` +/// indices = [0, 2, -1, 1] +/// depth = 3 +/// on_value = 0.0 +/// off_value = 3.0 +/// axis = 0 +/// ``` +/// +/// Then output is `[3 x 4]`: +/// ``` +/// output = +/// [0.0 3.0 3.0 3.0] +/// [3.0 3.0 3.0 0.0] +/// [3.0 3.0 3.0 3.0] +/// [3.0 0.0 3.0 3.0] +/// // ^ one_hot(0) +/// // ^ one_hot(2) +/// // ^ one_hot(-1) +/// // ^ one_hot(1) +/// ``` +/// +/// Suppose that +/// ``` +/// indices = [[0, 2], [1, -1]] +/// depth = 3 +/// on_value = 1.0 +/// off_value = 0.0 +/// axis = -1 +/// ``` +/// +/// Then output is `[2 x 2 x 3]`: +/// ``` +/// output = +/// [ +/// [1.0, 0.0, 0.0] // one_hot(0) +/// [0.0, 0.0, 1.0] // one_hot(2) +/// ][ +/// [0.0, 1.0, 0.0] // one_hot(1) +/// [0.0, 0.0, 0.0] // one_hot(-1) +/// ] +/// ``` +/// +/// - Parameters: +/// - indices: A tensor of indices. +/// - depth: A scalar defining the depth of the one hot dimension. +/// - on_value: A scalar defining the value to fill in output when `indices[j] = i`. +/// - off_value: A scalar defining the value to fill in output when `indices[j] != i`. +/// +/// - Attr axis: The axis to fill (default: -1, a new inner-most axis). +/// +/// - Output output: The one-hot tensor. +@inlinable @inline(__always) +public static func oneHot< + T: TensorFlowScalar, + Ti: BinaryInteger & TensorFlowScalar +>( + indices: Tensor, + depth: Tensor, + onValue: Tensor, + offValue: Tensor, + axis: Int64 = -1 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("OneHot", nOutputs) + op.updateAttribute("axis", axis) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("TI", Ti.tensorFlowDataType) + op.addInput(indices) + op.addInput(depth) + op.addInput(onValue) + op.addInput(offValue) + return op.execute(Int(1)) +} + +/// Makes a "one-shot" iterator that can be iterated only once. +/// +/// A one-shot iterator bundles the logic for defining the dataset and +/// the state of the iterator in a single op, which allows simple input +/// pipelines to be defined without an additional initialization +/// ("MakeIterator") step. +/// +/// One-shot iterators have the following limitations: +/// +/// * They do not support parameterization: all logic for creating the underlying +/// dataset must be bundled in the `dataset_factory` function. +/// * They are not resettable. Once a one-shot iterator reaches the end of its +/// underlying dataset, subsequent "IteratorGetNext" operations on that +/// iterator will always produce an `OutOfRange` error. +/// +/// For greater flexibility, use "Iterator" and "MakeIterator" to define +/// an iterator using an arbitrary subgraph, which may capture tensors +/// (including fed values) as parameters, and which may be reset multiple +/// times by rerunning "MakeIterator". +/// +/// - Attr dataset_factory: A function of type `() -> DT_VARIANT`, where the returned +/// DT_VARIANT is a dataset. +/// +/// - Output handle: A handle to the iterator that can be passed to an "IteratorGetNext" +/// op. +@inlinable @inline(__always) +public static func oneShotIterator( + datasetFactory: (DatasetfactoryIn) -> DatasetfactoryOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("OneShotIterator", nOutputs) + op.updateAttribute("dataset_factory", datasetFactory) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Returns a tensor of ones with the same shape and type as x. +/// +/// - Parameter x: a tensor of type T. +/// +/// - Output y: a tensor of the same shape and type as x but filled with ones. +@inlinable @inline(__always) +public static func onesLike( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("OnesLike", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func opWithDefaultAttr( + defaultFloat: Double = 123 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("OpWithDefaultAttr", nOutputs) + op.updateAttribute("default_float", defaultFloat) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func opWithFutureDefaultAttr( +) { + let nOutputs = 0 + let op = makeOp("OpWithFutureDefaultAttr", nOutputs) + + op.execute() +} + +/// Creates a dataset by applying optimizations to `input_dataset`. +/// +/// Creates a dataset by applying optimizations to `input_dataset`. +/// +/// - Parameters: +/// - input_dataset: A variant tensor representing the input dataset. +/// - optimizations: A `tf.string` vector `tf.Tensor` identifying optimizations to use. +@inlinable @inline(__always) +public static func optimizeDataset( + inputDataset: VariantHandle, + optimizations: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + optimizationConfigs: [String] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("OptimizeDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("optimization_configs", optimizationConfigs) + op.addInput(inputDataset) + op.addInput(optimizations) + return op.execute(Int(1)) +} + +/// Constructs an Optional variant from a tuple of tensors. +@inlinable @inline(__always) +public static func optionalFromValue( + components: ToutputTypes +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("OptionalFromValue", nOutputs) + op.updateAttribute("Toutput_types", components._typeList) + op.addInputList(components) + return op.execute(Int(1)) +} + +/// Returns the value stored in an Optional variant or raises an error if none exists. +@inlinable @inline(__always) +public static func optionalGetValue( + optional: VariantHandle, + outputShapes: [TensorShape?] +) -> OutputTypes { + let nOutputs = Int(OutputTypes._typeList.count) + let op = makeOp("OptionalGetValue", nOutputs) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(optional) + return op.execute(Int(OutputTypes._typeList.count)) +} + +/// Returns true if and only if the given Optional variant has a value. +@inlinable @inline(__always) +public static func optionalHasValue( + optional: VariantHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("OptionalHasValue", nOutputs) + op.addInput(optional) + return op.execute(Int(1)) +} + +/// Creates an Optional variant with no value. +@inlinable @inline(__always) +public static func optionalNone( +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("OptionalNone", nOutputs) + + return op.execute(Int(1)) +} + +/// Op removes all elements in the underlying container. +@inlinable @inline(__always) +public static func orderedMapClear( + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String +) { + let nOutputs = 0 + let op = makeOp("OrderedMapClear", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.execute() +} + +/// Op returns the number of incomplete elements in the underlying container. +@inlinable @inline(__always) +public static func orderedMapIncompleteSize( + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("OrderedMapIncompleteSize", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Op peeks at the values at the specified key. If the +/// +/// underlying container does not contain this key +/// this op will block until it does. This Op is optimized for +/// performance. +@inlinable @inline(__always) +public static func orderedMapPeek( + key: Tensor, + indices: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String +) -> Dtypes { + let nOutputs = Int(Dtypes._typeList.count) + let op = makeOp("OrderedMapPeek", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(key) + op.addInput(indices) + return op.execute(Int(Dtypes._typeList.count)) +} + +/// Op returns the number of elements in the underlying container. +@inlinable @inline(__always) +public static func orderedMapSize( + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("OrderedMapSize", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Stage (key, values) in the underlying container which behaves like a ordered +/// +/// associative container. Elements are ordered by key. +/// +/// - Parameters: +/// - key: int64 +/// - values: a list of tensors +/// dtypes A list of data types that inserted values should adhere to. +/// +/// - Attrs: +/// - capacity: Maximum number of elements in the Staging Area. If > 0, inserts +/// on the container will block when the capacity is reached. +/// - container: If non-empty, this queue is placed in the given container. Otherwise, +/// a default container is used. +/// - shared_name: It is necessary to match this name to the matching Unstage Op. +@inlinable @inline(__always) +public static func orderedMapStage( + key: Tensor, + indices: Tensor, + _ values: FakeDtypes, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String +) { + let nOutputs = 0 + let op = makeOp("OrderedMapStage", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("fake_dtypes", values._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(key) + op.addInput(indices) + op.addInputList(values) + op.execute() +} + +/// Op removes and returns the values associated with the key +/// +/// from the underlying container. If the underlying container +/// does not contain this key, the op will block until it does. +@inlinable @inline(__always) +public static func orderedMapUnstage( + key: Tensor, + indices: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String +) -> Dtypes { + let nOutputs = Int(Dtypes._typeList.count) + let op = makeOp("OrderedMapUnstage", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(key) + op.addInput(indices) + return op.execute(Int(Dtypes._typeList.count)) +} + +/// Op removes and returns the (key, value) element with the smallest +/// +/// key from the underlying container. If the underlying container +/// does not contain elements, the op will block until it does. +@inlinable @inline(__always) +public static func orderedMapUnstageNoKey( + indices: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String +) -> (key: Tensor, values: Dtypes) { + let nOutputs = Int(1) + Int(Dtypes._typeList.count) + let op = makeOp("OrderedMapUnstageNoKey", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(indices) + return op.execute(Int(1), Int(Dtypes._typeList.count)) +} + +@inlinable @inline(__always) +public static func outT( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("OutT", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func outTypeList( +) -> T { + let nOutputs = Int(T._typeList.count) + let op = makeOp("OutTypeList", nOutputs) + op.updateAttribute("T", T._typeList) + return op.execute(Int(T._typeList.count)) +} + +@inlinable @inline(__always) +public static func outTypeListRestrict( +) -> T { + let nOutputs = Int(T._typeList.count) + let op = makeOp("OutTypeListRestrict", nOutputs) + op.updateAttribute("t", T._typeList) + return op.execute(Int(T._typeList.count)) +} + +/// Retrieves a single tensor from the computation outfeed. +/// +/// This operation will block indefinitely until data is available. +/// +/// - Attrs: +/// - dtype: The type of elements in the tensor. +/// - shape: The shape of the tensor. +/// - device_ordinal: The TPU device to use. This should be -1 when the Op +/// is running on a TPU device, and >= 0 when the Op is running on the CPU +/// device. +/// +/// - Output output: A tensor that will be read from the device outfeed. +@inlinable @inline(__always) +public static func outfeedDequeue( + shape: TensorShape?, + deviceOrdinal: Int64 = -1 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("OutfeedDequeue", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.updateAttribute("device_ordinal", deviceOrdinal) + return op.execute(Int(1)) +} + +/// Retrieve multiple values from the computation outfeed. +/// +/// This operation will block indefinitely until data is available. Output `i` +/// corresponds to XLA tuple element `i`. +/// +/// - Attrs: +/// - dtypes: The element types of each element in `outputs`. +/// - shapes: The shapes of each tensor in `outputs`. +/// - device_ordinal: The TPU device to use. This should be -1 when the Op +/// is running on a TPU device, and >= 0 when the Op is running on the CPU +/// device. +/// +/// - Output outputs: A list of tensors that will be read from the outfeed. +@inlinable @inline(__always) +public static func outfeedDequeueTuple( + shapes: [TensorShape?], + deviceOrdinal: Int64 = -1 +) -> Dtypes { + let nOutputs = Int(Dtypes._typeList.count) + let op = makeOp("OutfeedDequeueTuple", nOutputs) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("shapes", shapes) + op.updateAttribute("device_ordinal", deviceOrdinal) + return op.execute(Int(Dtypes._typeList.count)) +} + +/// Enqueue a Tensor on the computation outfeed. +/// +/// - Parameter input: A tensor that will be inserted into the outfeed queue. +@inlinable @inline(__always) +public static func outfeedEnqueue( + _ input: Tensor +) { + let nOutputs = 0 + let op = makeOp("OutfeedEnqueue", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(input) + op.execute() +} + +/// Enqueue multiple Tensor values on the computation outfeed. +/// +/// - Parameter inputs: A list of tensors that will be inserted into the outfeed queue as an +/// XLA tuple. +@inlinable @inline(__always) +public static func outfeedEnqueueTuple( + inputs: Dtypes +) { + let nOutputs = 0 + let op = makeOp("OutfeedEnqueueTuple", nOutputs) + op.updateAttribute("dtypes", inputs._typeList) + op.addInputList(inputs) + op.execute() +} + +/// Packs a list of `N` rank-`R` tensors into one rank-`(R+1)` tensor. +/// +/// Packs the `N` tensors in `values` into a tensor with rank one higher than each +/// tensor in `values`, by packing them along the `axis` dimension. +/// Given a list of tensors of shape `(A, B, C)`; +/// +/// if `axis == 0` then the `output` tensor will have the shape `(N, A, B, C)`. +/// if `axis == 1` then the `output` tensor will have the shape `(A, N, B, C)`. +/// Etc. +/// +/// For example: +/// +/// ``` +/// # 'x' is [1, 4] +/// # 'y' is [2, 5] +/// # 'z' is [3, 6] +/// pack([x, y, z]) => [[1, 4], [2, 5], [3, 6]] # Pack along first dim. +/// pack([x, y, z], axis=1) => [[1, 2, 3], [4, 5, 6]] +/// ``` +/// +/// This is the opposite of `unpack`. +/// +/// - Parameter values: Must be of same shape and type. +/// +/// - Attr axis: Dimension along which to pack. Negative values wrap around, so the +/// valid range is `[-(R+1), R+1)`. +/// +/// - Output output: The packed tensor. +@inlinable @inline(__always) +public static func pack( + _ values: [Tensor], + axis: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Pack", nOutputs) + op.updateAttribute("N", values.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("axis", axis) + op.addInputList(values) + return op.execute(Int(1)) +} + +/// Pads a tensor with zeros. +/// +/// This operation pads a `input` with zeros according to the `paddings` you +/// specify. `paddings` is an integer tensor with shape `[Dn, 2]`, where n is the +/// rank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates +/// how many zeros to add before the contents of `input` in that dimension, and +/// `paddings[D, 1]` indicates how many zeros to add after the contents of `input` +/// in that dimension. +/// +/// The padded size of each dimension D of the output is: +/// +/// `paddings(D, 0) + input.dim_size(D) + paddings(D, 1)` +/// +/// For example: +/// +/// ``` +/// # 't' is [[1, 1], [2, 2]] +/// # 'paddings' is [[1, 1], [2, 2]] +/// # rank of 't' is 2 +/// pad(t, paddings) ==> [[0, 0, 0, 0, 0, 0] +/// [0, 0, 1, 1, 0, 0] +/// [0, 0, 2, 2, 0, 0] +/// [0, 0, 0, 0, 0, 0]] +/// ``` +/// +@inlinable @inline(__always) +public static func pad< + T: TensorFlowScalar, + Tpaddings: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + paddings: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Pad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) + op.addInput(input) + op.addInput(paddings) + return op.execute(Int(1)) +} + +/// Pads a tensor. +/// +/// This operation pads `input` according to the `paddings` and `constant_values` +/// you specify. `paddings` is an integer tensor with shape `[Dn, 2]`, where n is +/// the rank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates +/// how many padding values to add before the contents of `input` in that dimension, +/// and `paddings[D, 1]` indicates how many padding values to add after the contents +/// of `input` in that dimension. `constant_values` is a scalar tensor of the same +/// type as `input` that indicates the value to use for padding `input`. +/// +/// The padded size of each dimension D of the output is: +/// +/// `paddings(D, 0) + input.dim_size(D) + paddings(D, 1)` +/// +/// For example: +/// +/// ``` +/// # 't' is [[1, 1], [2, 2]] +/// # 'paddings' is [[1, 1], [2, 2]] +/// # 'constant_values' is 0 +/// # rank of 't' is 2 +/// pad(t, paddings) ==> [[0, 0, 0, 0, 0, 0] +/// [0, 0, 1, 1, 0, 0] +/// [0, 0, 2, 2, 0, 0] +/// [0, 0, 0, 0, 0, 0]] +/// ``` +@inlinable @inline(__always) +public static func padV2< + T: TensorFlowScalar, + Tpaddings: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + paddings: Tensor, + constantValues: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("PadV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) + op.addInput(input) + op.addInput(paddings) + op.addInput(constantValues) + return op.execute(Int(1)) +} + +/// Creates a dataset that batches and pads `batch_size` elements from the input. +/// +/// - Parameters: +/// - batch_size: A scalar representing the number of elements to accumulate in a +/// batch. +/// - padded_shapes: A list of int64 tensors representing the desired padded shapes +/// of the corresponding output components. These shapes may be partially +/// specified, using `-1` to indicate that a particular dimension should be +/// padded to the maximum size of all batch elements. +/// - padding_values: A list of scalars containing the padding value to use for +/// each of the outputs. +@inlinable @inline(__always) +public static func paddedBatchDataset( + inputDataset: VariantHandle, + batchSize: Tensor, + paddedShapes: [Tensor], + paddingValues: ToutputTypes, + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("PaddedBatchDataset", nOutputs) + op.updateAttribute("Toutput_types", paddingValues._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("N", paddedShapes.count) + op.addInput(inputDataset) + op.addInput(batchSize) + op.addInputList(paddedShapes) + op.addInputList(paddingValues) + return op.execute(Int(1)) +} + +/// Creates a dataset that batches and pads `batch_size` elements from the input. +/// +/// - Parameters: +/// - batch_size: A scalar representing the number of elements to accumulate in a +/// batch. +/// - padded_shapes: A list of int64 tensors representing the desired padded shapes +/// of the corresponding output components. These shapes may be partially +/// specified, using `-1` to indicate that a particular dimension should be +/// padded to the maximum size of all batch elements. +/// - padding_values: A list of scalars containing the padding value to use for +/// each of the outputs. +/// - drop_remainder: A scalar representing whether the last batch should be dropped in case its size +/// is smaller than desired. +@inlinable @inline(__always) +public static func paddedBatchDatasetV2( + inputDataset: VariantHandle, + batchSize: Tensor, + paddedShapes: [Tensor], + paddingValues: ToutputTypes, + dropRemainder: Tensor, + parallelCopy: Bool = false, + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("PaddedBatchDatasetV2", nOutputs) + op.updateAttribute("parallel_copy", parallelCopy) + op.updateAttribute("Toutput_types", paddingValues._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("N", paddedShapes.count) + op.addInput(inputDataset) + op.addInput(batchSize) + op.addInputList(paddedShapes) + op.addInputList(paddingValues) + op.addInput(dropRemainder) + return op.execute(Int(1)) +} + +/// A queue that produces elements in first-in first-out order. +/// +/// Variable-size shapes are allowed by setting the corresponding shape dimensions +/// to 0 in the shape attr. In this case DequeueMany will pad up to the maximum +/// size of any given element in the minibatch. See below for details. +/// +/// - Attrs: +/// - component_types: The type of each component in a value. +/// - shapes: The shape of each component in a value. The length of this attr must +/// be either 0 or the same as the length of component_types. +/// Shapes of fixed rank but variable size are allowed by setting +/// any shape dimension to -1. In this case, the inputs' shape may vary along +/// the given dimension, and DequeueMany will pad the given dimension with +/// zeros up to the maximum shape of all elements in the given batch. +/// If the length of this attr is 0, different queue elements may have +/// different ranks and shapes, but only one element may be dequeued at a time. +/// - capacity: The upper bound on the number of elements in this queue. +/// Negative numbers mean no limit. +/// - container: If non-empty, this queue is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this queue will be shared under the given name +/// across multiple sessions. +/// +/// - Output handle: The handle to the queue. +@inlinable @inline(__always) +public static func paddingFIFOQueueV2( + componentTypes: [TensorDataType], + shapes: [TensorShape?], + capacity: Int64 = -1, + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("PaddingFIFOQueueV2", nOutputs) + op.updateAttribute("component_types", componentTypes) + op.updateAttribute("shapes", shapes) + op.updateAttribute("capacity", capacity) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Concatenates a list of `N` tensors along the first dimension. +/// +/// The input tensors are all required to have size 1 in the first dimension. +/// +/// For example: +/// +/// ``` +/// # 'x' is [[1, 4]] +/// # 'y' is [[2, 5]] +/// # 'z' is [[3, 6]] +/// parallel_concat([x, y, z]) => [[1, 4], [2, 5], [3, 6]] # Pack along first dim. +/// ``` +/// +/// The difference between concat and parallel_concat is that concat requires all +/// of the inputs be computed before the operation will begin but doesn't require +/// that the input shapes be known during graph construction. Parallel concat +/// will copy pieces of the input into the output as they become available, in +/// some situations this can provide a performance benefit. +/// +/// - Parameter values: Tensors to be concatenated. All must have size 1 in the first dimension +/// and same shape. +/// +/// - Attr shape: the final shape of the result; should be equal to the shapes of any input +/// but with the number of input values in the first dimension. +/// +/// - Output output: The concatenated tensor. +@inlinable @inline(__always) +public static func parallelConcat( + _ values: [Tensor], + shape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ParallelConcat", nOutputs) + op.updateAttribute("N", values.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.addInputList(values) + return op.execute(Int(1)) +} + +/// Interleave the values from the `data` tensors into a single tensor. +/// +/// Builds a merged tensor such that +/// +/// ```python +/// merged[indices[m][i, ..., j], ...] = data[m][i, ..., j, ...] +/// ``` +/// +/// For example, if each `indices[m]` is scalar or vector, we have +/// +/// ```python +/// # Scalar indices: +/// merged[indices[m], ...] = data[m][...] +/// +/// # Vector indices: +/// merged[indices[m][i], ...] = data[m][i, ...] +/// ``` +/// +/// Each `data[i].shape` must start with the corresponding `indices[i].shape`, +/// and the rest of `data[i].shape` must be constant w.r.t. `i`. That is, we +/// must have `data[i].shape = indices[i].shape + constant`. In terms of this +/// `constant`, the output shape is +/// +/// merged.shape = [max(indices)] + constant +/// +/// Values may be merged in parallel, so if an index appears in both `indices[m][i]` +/// and `indices[n][j]`, the result may be invalid. This differs from the normal +/// DynamicStitch operator that defines the behavior in that case. +/// +/// For example: +/// +/// ```python +/// indices[0] = 6 +/// indices[1] = [4, 1] +/// indices[2] = [[5, 2], [0, 3]] +/// data[0] = [61, 62] +/// data[1] = [[41, 42], [11, 12]] +/// data[2] = [[[51, 52], [21, 22]], [[1, 2], [31, 32]]] +/// merged = [[1, 2], [11, 12], [21, 22], [31, 32], [41, 42], +/// [51, 52], [61, 62]] +/// ``` +/// +/// This method can be used to merge partitions created by `dynamic_partition` +/// as illustrated on the following example: +/// +/// ```python +/// # Apply function (increments x_i) on elements for which a certain condition +/// # apply (x_i != -1 in this example). +/// x=tf.constant([0.1, -1., 5.2, 4.3, -1., 7.4]) +/// condition_mask=tf.not_equal(x,tf.constant(-1.)) +/// partitioned_data = tf.dynamic_partition( +/// x, tf.cast(condition_mask, tf.int32) , 2) +/// partitioned_data[1] = partitioned_data[1] + 1.0 +/// condition_indices = tf.dynamic_partition( +/// tf.range(tf.shape(x)[0]), tf.cast(condition_mask, tf.int32) , 2) +/// x = tf.dynamic_stitch(condition_indices, partitioned_data) +/// # Here x=[1.1, -1., 6.2, 5.3, -1, 8.4], the -1. values remain +/// # unchanged. +/// ``` +/// +///
+/// +///
+@inlinable @inline(__always) +public static func parallelDynamicStitch( + indices: [Tensor], + data: [Tensor] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ParallelDynamicStitch", nOutputs) + op.updateAttribute("N", indices.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInputList(indices) + op.addInputList(data) + return op.execute(Int(1)) +} + +/// Creates a dataset that applies `f` to the outputs of `input_dataset`. +/// +/// - Attr f: A function mapping elements of `input_dataset`, concatenated with +/// `other_arguments`, to a Dataset variant that contains elements matching +/// `output_types` and `output_shapes`. +@inlinable @inline(__always) +public static func parallelInterleaveDatasetV2< + FIn: TensorGroup, + FOut: TensorGroup, + Targuments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + otherArguments: Targuments, + cycleLength: Tensor, + blockLength: Tensor, + numParallelCalls: Tensor, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + sloppy: Bool = false +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ParallelInterleaveDatasetV2", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("sloppy", sloppy) + op.addInput(inputDataset) + op.addInputList(otherArguments) + op.addInput(cycleLength) + op.addInput(blockLength) + op.addInput(numParallelCalls) + return op.execute(Int(1)) +} + +/// Creates a dataset that applies `f` to the outputs of `input_dataset`. +/// +/// Unlike a "MapDataset", which applies `f` sequentially, this dataset invokes up +/// to `num_parallel_calls` copies of `f` in parallel. +/// +/// - Parameter num_parallel_calls: The number of concurrent invocations of `f` that process +/// elements from `input_dataset` in parallel. +@inlinable @inline(__always) +public static func parallelMapDataset< + FIn: TensorGroup, + FOut: TensorGroup, + Targuments: TensorArrayProtocol +>( + inputDataset: VariantHandle, + otherArguments: Targuments, + numParallelCalls: Tensor, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + useInterOpParallelism: Bool = true, + sloppy: Bool = false, + preserveCardinality: Bool = false +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ParallelMapDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("use_inter_op_parallelism", useInterOpParallelism) + op.updateAttribute("sloppy", sloppy) + op.updateAttribute("preserve_cardinality", preserveCardinality) + op.addInput(inputDataset) + op.addInputList(otherArguments) + op.addInput(numParallelCalls) + return op.execute(Int(1)) +} + +/// Outputs random values from a normal distribution. The parameters may each be a +/// +/// scalar which applies to the entire output, or a vector of length shape[0] which +/// stores the parameters for each batch. +/// +/// - Parameters: +/// - shape: The shape of the output tensor. Batches are indexed by the 0th dimension. +/// - means: The mean parameter of each batch. +/// - stdevs: The standard deviation parameter of each batch. Must be greater than 0. +/// - minvals: The minimum cutoff. May be -infinity. +/// - maxvals: The maximum cutoff. May be +infinity, and must be more than the minval +/// for each batch. +/// +/// - Attrs: +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. +/// - dtype: The type of the output. +/// +/// - Output output: A matrix of shape num_batches x samples_per_batch, filled with random +/// truncated normal values using the parameters for each row. +@inlinable @inline(__always) +public static func parameterizedTruncatedNormal< + Dtype: FloatingPoint & TensorFlowScalar, + T: BinaryInteger & TensorFlowScalar +>( + shape: Tensor, + means: Tensor, + stdevs: Tensor, + minvals: Tensor, + maxvals: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ParameterizedTruncatedNormal", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(shape) + op.addInput(means) + op.addInput(stdevs) + op.addInput(minvals) + op.addInput(maxvals) + return op.execute(Int(1)) +} + +/// Transforms a vector of brain.Example protos (as strings) into typed tensors. +/// +/// - Parameters: +/// - serialized: A vector containing a batch of binary serialized Example protos. +/// - names: A vector containing the names of the serialized protos. +/// May contain, for example, table key (descriptive) names for the +/// corresponding serialized protos. These are purely useful for debugging +/// purposes, and the presence of values here has no effect on the output. +/// May also be an empty vector if no names are available. +/// If non-empty, this vector must be the same length as "serialized". +/// - sparse_keys: A list of Nsparse string Tensors (scalars). +/// The keys expected in the Examples' features associated with sparse values. +/// - dense_keys: A list of Ndense string Tensors (scalars). +/// The keys expected in the Examples' features associated with dense values. +/// - dense_defaults: A list of Ndense Tensors (some may be empty). +/// dense_defaults[j] provides default values +/// when the example's feature_map lacks dense_key[j]. If an empty Tensor is +/// provided for dense_defaults[j], then the Feature dense_keys[j] is required. +/// The input type is inferred from dense_defaults[j], even when it's empty. +/// If dense_defaults[j] is not empty, and dense_shapes[j] is fully defined, +/// then the shape of dense_defaults[j] must match that of dense_shapes[j]. +/// If dense_shapes[j] has an undefined major dimension (variable strides dense +/// feature), dense_defaults[j] must contain a single element: +/// the padding element. +/// +/// - Attrs: +/// - sparse_types: A list of Nsparse types; the data types of data in each Feature +/// given in sparse_keys. +/// Currently the ParseExample supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - dense_shapes: A list of Ndense shapes; the shapes of data in each Feature +/// given in dense_keys. +/// The number of elements in the Feature corresponding to dense_key[j] +/// must always equal dense_shapes[j].NumEntries(). +/// If dense_shapes[j] == (D0, D1, ..., DN) then the shape of output +/// Tensor dense_values[j] will be (|serialized|, D0, D1, ..., DN): +/// The dense outputs are just the inputs row-stacked by batch. +/// This works for dense_shapes[j] = (-1, D1, ..., DN). In this case +/// the shape of the output Tensor dense_values[j] will be +/// (|serialized|, M, D1, .., DN), where M is the maximum number of blocks +/// of elements of length D1 * .... * DN, across all minibatch entries +/// in the input. Any minibatch entry with less than M blocks of elements of +/// length D1 * ... * DN will be padded with the corresponding default_value +/// scalar element along the second dimension. +@inlinable @inline(__always) +public static func parseExample< + SparseTypes: TensorGroup, + Tdense: TensorArrayProtocol +>( + serialized: StringTensor, + names: StringTensor, + sparseKeys: [StringTensor], + denseKeys: [StringTensor], + denseDefaults: Tdense, + denseShapes: [TensorShape?] +) -> (sparseIndices: [Tensor], sparseValues: SparseTypes, sparseShapes: [Tensor], denseValues: Tdense) { + let nOutputs = Int(sparseKeys.count) + Int(SparseTypes._typeList.count) + Int(sparseKeys.count) + Int(denseDefaults._typeList.count) + let op = makeOp("ParseExample", nOutputs) + op.updateAttribute("Nsparse", sparseKeys.count) + op.updateAttribute("Ndense", denseKeys.count) + op.updateAttribute("sparse_types", SparseTypes._typeList) + op.updateAttribute("Tdense", denseDefaults._typeList) + op.updateAttribute("dense_shapes", denseShapes) + op.addInput(serialized) + op.addInput(names) + op.addInputList(sparseKeys) + op.addInputList(denseKeys) + op.addInputList(denseDefaults) + return op.execute(Int(sparseKeys.count), Int(SparseTypes._typeList.count), Int(sparseKeys.count), Int(denseDefaults._typeList.count)) +} + +/// Transforms a vector of brain.SequenceExample protos (as strings) into typed tensors. +/// +/// - Parameters: +/// - serialized: A vector containing binary serialized SequenceExample protos. +/// - debug_name: A vector containing the names of the serialized protos. +/// May contain, for example, table key (descriptive) name for the +/// corresponding serialized proto. This is purely useful for debugging +/// purposes, and the presence of values here has no effect on the output. +/// May also be an empty vector if no name is available. +/// - context_dense_defaults: A list of Ncontext_dense Tensors (some may be empty). +/// context_dense_defaults[j] provides default values +/// when the SequenceExample's context map lacks context_dense_key[j]. +/// If an empty Tensor is provided for context_dense_defaults[j], +/// then the Feature context_dense_keys[j] is required. +/// The input type is inferred from context_dense_defaults[j], even when it's +/// empty. If context_dense_defaults[j] is not empty, its shape must match +/// context_dense_shapes[j]. +/// +/// - Attrs: +/// - feature_list_dense_missing_assumed_empty: A vector listing the +/// FeatureList keys which may be missing from the SequenceExamples. If the +/// associated FeatureList is missing, it is treated as empty. By default, +/// any FeatureList not listed in this vector must exist in the SequenceExamples. +/// - context_sparse_keys: A list of Ncontext_sparse string Tensors (scalars). +/// The keys expected in the Examples' features associated with context_sparse +/// values. +/// - context_dense_keys: A list of Ncontext_dense string Tensors (scalars). +/// The keys expected in the SequenceExamples' context features associated with +/// dense values. +/// - feature_list_sparse_keys: A list of Nfeature_list_sparse string Tensors +/// (scalars). The keys expected in the FeatureLists associated with sparse +/// values. +/// - feature_list_dense_keys: A list of Nfeature_list_dense string Tensors (scalars). +/// The keys expected in the SequenceExamples' feature_lists associated +/// with lists of dense values. +/// - context_sparse_types: A list of Ncontext_sparse types; the data types of data in +/// each context Feature given in context_sparse_keys. +/// Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - context_dense_shapes: A list of Ncontext_dense shapes; the shapes of data in +/// each context Feature given in context_dense_keys. +/// The number of elements in the Feature corresponding to context_dense_key[j] +/// must always equal context_dense_shapes[j].NumEntries(). +/// The shape of context_dense_values[j] will match context_dense_shapes[j]. +/// - feature_list_sparse_types: A list of Nfeature_list_sparse types; the data types +/// of data in each FeatureList given in feature_list_sparse_keys. +/// Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - feature_list_dense_shapes: A list of Nfeature_list_dense shapes; the shapes of +/// data in each FeatureList given in feature_list_dense_keys. +/// The shape of each Feature in the FeatureList corresponding to +/// feature_list_dense_key[j] must always equal +/// feature_list_dense_shapes[j].NumEntries(). +@inlinable @inline(__always) +public static func parseSequenceExample< + ContextSparseTypes: TensorGroup, + TcontextDense: TensorArrayProtocol, + FeatureListDenseTypes: TensorGroup, + FeatureListSparseTypes: TensorGroup +>( + serialized: StringTensor, + debugName: StringTensor, + contextDenseDefaults: TcontextDense, + featureListDenseMissingAssumedEmpty: [String], + contextSparseKeys: [String], + contextDenseKeys: [String], + featureListSparseKeys: [String], + featureListDenseKeys: [String], + ncontextSparse: Int64 = 0, + ncontextDense: Int64 = 0, + nfeatureListSparse: Int64 = 0, + nfeatureListDense: Int64 = 0, + contextDenseShapes: [TensorShape?], + featureListDenseShapes: [TensorShape?] +) -> (contextSparseIndices: [Tensor], contextSparseValues: ContextSparseTypes, contextSparseShapes: [Tensor], contextDenseValues: TcontextDense, featureListSparseIndices: [Tensor], featureListSparseValues: FeatureListSparseTypes, featureListSparseShapes: [Tensor], featureListDenseValues: FeatureListDenseTypes, featureListDenseLengths: [Tensor]) { + let nOutputs = Int(ncontextSparse) + Int(ContextSparseTypes._typeList.count) + Int(ncontextSparse) + Int(contextDenseDefaults._typeList.count) + Int(nfeatureListSparse) + Int(FeatureListSparseTypes._typeList.count) + Int(nfeatureListSparse) + Int(FeatureListDenseTypes._typeList.count) + Int(nfeatureListDense) + let op = makeOp("ParseSequenceExample", nOutputs) + op.updateAttribute("feature_list_dense_missing_assumed_empty", featureListDenseMissingAssumedEmpty) + op.updateAttribute("context_sparse_keys", contextSparseKeys) + op.updateAttribute("context_dense_keys", contextDenseKeys) + op.updateAttribute("feature_list_sparse_keys", featureListSparseKeys) + op.updateAttribute("feature_list_dense_keys", featureListDenseKeys) + op.updateAttribute("Ncontext_sparse", ncontextSparse) + op.updateAttribute("Ncontext_dense", ncontextDense) + op.updateAttribute("Nfeature_list_sparse", nfeatureListSparse) + op.updateAttribute("Nfeature_list_dense", nfeatureListDense) + op.updateAttribute("context_sparse_types", ContextSparseTypes._typeList) + op.updateAttribute("Tcontext_dense", contextDenseDefaults._typeList) + op.updateAttribute("feature_list_dense_types", FeatureListDenseTypes._typeList) + op.updateAttribute("context_dense_shapes", contextDenseShapes) + op.updateAttribute("feature_list_sparse_types", FeatureListSparseTypes._typeList) + op.updateAttribute("feature_list_dense_shapes", featureListDenseShapes) + op.addInput(serialized) + op.addInput(debugName) + op.addInputList(contextDenseDefaults) + return op.execute(Int(ncontextSparse), Int(ContextSparseTypes._typeList.count), Int(ncontextSparse), Int(contextDenseDefaults._typeList.count), Int(nfeatureListSparse), Int(FeatureListSparseTypes._typeList.count), Int(nfeatureListSparse), Int(FeatureListDenseTypes._typeList.count), Int(nfeatureListDense)) +} + +/// Transforms a tf.Example proto (as a string) into typed tensors. +/// +/// - Parameters: +/// - serialized: A vector containing a batch of binary serialized Example protos. +/// - dense_defaults: A list of Tensors (some may be empty), whose length matches +/// the length of `dense_keys`. dense_defaults[j] provides default values +/// when the example's feature_map lacks dense_key[j]. If an empty Tensor is +/// provided for dense_defaults[j], then the Feature dense_keys[j] is required. +/// The input type is inferred from dense_defaults[j], even when it's empty. +/// If dense_defaults[j] is not empty, and dense_shapes[j] is fully defined, +/// then the shape of dense_defaults[j] must match that of dense_shapes[j]. +/// If dense_shapes[j] has an undefined major dimension (variable strides dense +/// feature), dense_defaults[j] must contain a single element: +/// the padding element. +/// +/// - Attrs: +/// - num_sparse: The number of sparse features to be parsed from the example. This +/// must match the lengths of `sparse_keys` and `sparse_types`. +/// - sparse_keys: A list of `num_sparse` strings. +/// The keys expected in the Examples' features associated with sparse values. +/// - dense_keys: The keys expected in the Examples' features associated with dense +/// values. +/// - sparse_types: A list of `num_sparse` types; the data types of data in each +/// Feature given in sparse_keys. +/// Currently the ParseSingleExample op supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - Tdense: The data types of data in each Feature given in dense_keys. +/// The length of this list must match the length of `dense_keys`. +/// Currently the ParseSingleExample op supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - dense_shapes: The shapes of data in each Feature given in dense_keys. +/// The length of this list must match the length of `dense_keys`. The +/// number of elements in the Feature corresponding to dense_key[j] must +/// always equal dense_shapes[j].NumEntries(). If dense_shapes[j] == +/// (D0, D1, ..., DN) then the shape of output Tensor dense_values[j] +/// will be (D0, D1, ..., DN): In the case dense_shapes[j] = (-1, D1, +/// ..., DN), the shape of the output Tensor dense_values[j] will be (M, +/// D1, .., DN), where M is the number of blocks of elements of length +/// D1 * .... * DN, in the input. +@inlinable @inline(__always) +public static func parseSingleExample< + SparseTypes: TensorGroup, + Tdense: TensorArrayProtocol +>( + serialized: StringTensor, + denseDefaults: Tdense, + numSparse: Int64, + sparseKeys: [String], + denseKeys: [String], + denseShapes: [TensorShape?] +) -> (sparseIndices: [Tensor], sparseValues: SparseTypes, sparseShapes: [Tensor], denseValues: Tdense) { + let nOutputs = Int(numSparse) + Int(SparseTypes._typeList.count) + Int(numSparse) + Int(denseDefaults._typeList.count) + let op = makeOp("ParseSingleExample", nOutputs) + op.updateAttribute("num_sparse", numSparse) + op.updateAttribute("sparse_keys", sparseKeys) + op.updateAttribute("dense_keys", denseKeys) + op.updateAttribute("sparse_types", SparseTypes._typeList) + op.updateAttribute("Tdense", denseDefaults._typeList) + op.updateAttribute("dense_shapes", denseShapes) + op.addInput(serialized) + op.addInputList(denseDefaults) + return op.execute(Int(numSparse), Int(SparseTypes._typeList.count), Int(numSparse), Int(denseDefaults._typeList.count)) +} + +/// Transforms a scalar brain.SequenceExample proto (as strings) into typed tensors. +/// +/// - Parameters: +/// - serialized: A scalar containing a binary serialized SequenceExample proto. +/// - feature_list_dense_missing_assumed_empty: A vector listing the +/// FeatureList keys which may be missing from the SequenceExample. If the +/// associated FeatureList is missing, it is treated as empty. By default, +/// any FeatureList not listed in this vector must exist in the SequenceExample. +/// - context_sparse_keys: A list of Ncontext_sparse string Tensors (scalars). +/// The keys expected in the Examples' features associated with context_sparse +/// values. +/// - context_dense_keys: A list of Ncontext_dense string Tensors (scalars). +/// The keys expected in the SequenceExamples' context features associated with +/// dense values. +/// - feature_list_sparse_keys: A list of Nfeature_list_sparse string Tensors +/// (scalars). The keys expected in the FeatureLists associated with sparse +/// values. +/// - feature_list_dense_keys: A list of Nfeature_list_dense string Tensors (scalars). +/// The keys expected in the SequenceExamples' feature_lists associated +/// with lists of dense values. +/// - context_dense_defaults: A list of Ncontext_dense Tensors (some may be empty). +/// context_dense_defaults[j] provides default values +/// when the SequenceExample's context map lacks context_dense_key[j]. +/// If an empty Tensor is provided for context_dense_defaults[j], +/// then the Feature context_dense_keys[j] is required. +/// The input type is inferred from context_dense_defaults[j], even when it's +/// empty. If context_dense_defaults[j] is not empty, its shape must match +/// context_dense_shapes[j]. +/// - debug_name: A scalar containing the name of the serialized proto. +/// May contain, for example, table key (descriptive) name for the +/// corresponding serialized proto. This is purely useful for debugging +/// purposes, and the presence of values here has no effect on the output. +/// May also be an empty scalar if no name is available. +/// +/// - Attrs: +/// - context_sparse_types: A list of Ncontext_sparse types; the data types of data in +/// each context Feature given in context_sparse_keys. +/// Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - context_dense_shapes: A list of Ncontext_dense shapes; the shapes of data in +/// each context Feature given in context_dense_keys. +/// The number of elements in the Feature corresponding to context_dense_key[j] +/// must always equal context_dense_shapes[j].NumEntries(). +/// The shape of context_dense_values[j] will match context_dense_shapes[j]. +/// - feature_list_sparse_types: A list of Nfeature_list_sparse types; the data types +/// of data in each FeatureList given in feature_list_sparse_keys. +/// Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - feature_list_dense_shapes: A list of Nfeature_list_dense shapes; the shapes of +/// data in each FeatureList given in feature_list_dense_keys. +/// The shape of each Feature in the FeatureList corresponding to +/// feature_list_dense_key[j] must always equal +/// feature_list_dense_shapes[j].NumEntries(). +@inlinable @inline(__always) +public static func parseSingleSequenceExample< + ContextSparseTypes: TensorGroup, + TcontextDense: TensorArrayProtocol, + FeatureListDenseTypes: TensorGroup, + FeatureListSparseTypes: TensorGroup +>( + serialized: StringTensor, + featureListDenseMissingAssumedEmpty: StringTensor, + contextSparseKeys: [StringTensor], + contextDenseKeys: [StringTensor], + featureListSparseKeys: [StringTensor], + featureListDenseKeys: [StringTensor], + contextDenseDefaults: TcontextDense, + debugName: StringTensor, + contextDenseShapes: [TensorShape?], + featureListDenseShapes: [TensorShape?] +) -> (contextSparseIndices: [Tensor], contextSparseValues: ContextSparseTypes, contextSparseShapes: [Tensor], contextDenseValues: TcontextDense, featureListSparseIndices: [Tensor], featureListSparseValues: FeatureListSparseTypes, featureListSparseShapes: [Tensor], featureListDenseValues: FeatureListDenseTypes) { + let nOutputs = Int(contextSparseKeys.count) + Int(ContextSparseTypes._typeList.count) + Int(contextSparseKeys.count) + Int(contextDenseDefaults._typeList.count) + Int(featureListSparseKeys.count) + Int(FeatureListSparseTypes._typeList.count) + Int(featureListSparseKeys.count) + Int(FeatureListDenseTypes._typeList.count) + let op = makeOp("ParseSingleSequenceExample", nOutputs) + op.updateAttribute("Ncontext_sparse", contextSparseKeys.count) + op.updateAttribute("Ncontext_dense", contextDenseKeys.count) + op.updateAttribute("Nfeature_list_sparse", featureListSparseKeys.count) + op.updateAttribute("Nfeature_list_dense", featureListDenseKeys.count) + op.updateAttribute("context_sparse_types", ContextSparseTypes._typeList) + op.updateAttribute("Tcontext_dense", contextDenseDefaults._typeList) + op.updateAttribute("feature_list_dense_types", FeatureListDenseTypes._typeList) + op.updateAttribute("context_dense_shapes", contextDenseShapes) + op.updateAttribute("feature_list_sparse_types", FeatureListSparseTypes._typeList) + op.updateAttribute("feature_list_dense_shapes", featureListDenseShapes) + op.addInput(serialized) + op.addInput(featureListDenseMissingAssumedEmpty) + op.addInputList(contextSparseKeys) + op.addInputList(contextDenseKeys) + op.addInputList(featureListSparseKeys) + op.addInputList(featureListDenseKeys) + op.addInputList(contextDenseDefaults) + op.addInput(debugName) + return op.execute(Int(contextSparseKeys.count), Int(ContextSparseTypes._typeList.count), Int(contextSparseKeys.count), Int(contextDenseDefaults._typeList.count), Int(featureListSparseKeys.count), Int(FeatureListSparseTypes._typeList.count), Int(featureListSparseKeys.count), Int(FeatureListDenseTypes._typeList.count)) +} + +/// Transforms a serialized tensorflow.TensorProto proto into a Tensor. +/// +/// - Parameter serialized: A scalar string containing a serialized TensorProto proto. +/// +/// - Attr out_type: The type of the serialized tensor. The provided type must match the +/// type of the serialized tensor and no implicit conversion will take place. +/// +/// - Output output: A Tensor of type `out_type`. +@inlinable @inline(__always) +public static func parseTensor( + serialized: StringTensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ParseTensor", nOutputs) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(serialized) + return op.execute(Int(1)) +} + +/// returns `f(inputs)`, where `f`'s body is placed and partitioned. +/// +/// - Parameter args: A list of input tensors. +/// +/// - Attrs: +/// - Tin: A list of input types. +/// - Tout: A list of output types. +/// - f: A function that takes 'args', a list of tensors, and returns 'output', +/// another list of tensors. Input and output types are specified by 'Tin' +/// and 'Tout'. The function body of f will be placed and partitioned across +/// devices, setting this op apart from the regular Call op. +/// +/// - Output output: A list of return values. +@inlinable @inline(__always) +public static func partitionedCall< + Tin: TensorArrayProtocol, + Tout: TensorGroup, + FIn: TensorGroup, + FOut: TensorGroup +>( + args: Tin, + f: (FIn) -> FOut, + config: String, + configProto: String, + executorType: String +) -> Tout { + let nOutputs = Int(Tout._typeList.count) + let op = makeOp("PartitionedCall", nOutputs) + op.updateAttribute("Tin", args._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("f", f) + op.updateAttribute("config", config) + op.updateAttribute("config_proto", configProto) + op.updateAttribute("executor_type", executorType) + op.addInputList(args) + return op.execute(Int(Tout._typeList.count)) +} + +/// A placeholder op for a value that will be fed into the computation. +/// +/// N.B. This operation will fail with an error if it is executed. It is +/// intended as a way to represent a value that will always be fed, and to +/// provide attrs that enable the fed value to be checked at runtime. +/// +/// - Attrs: +/// - dtype: The type of elements in the tensor. +/// - shape: (Optional) The shape of the tensor. If the shape has 0 dimensions, the +/// shape is unconstrained. +/// +/// - Output output: A placeholder tensor that must be replaced using the feed mechanism. +@inlinable @inline(__always) +public static func placeholder( + shape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Placeholder", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + return op.execute(Int(1)) +} + +/// A placeholder op for a value that will be fed into the computation. +/// +/// N.B. This operation will fail with an error if it is executed. It is +/// intended as a way to represent a value that will always be fed, and to +/// provide attrs that enable the fed value to be checked at runtime. +/// +/// - Attrs: +/// - dtype: The type of elements in the tensor. +/// - shape: The shape of the tensor. The shape can be any partially-specified +/// shape. To be unconstrained, pass in a shape with unknown rank. +/// +/// - Output output: A placeholder tensor that must be replaced using the feed mechanism. +@inlinable @inline(__always) +public static func placeholderV2( + shape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("PlaceholderV2", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + return op.execute(Int(1)) +} + +/// A placeholder op that passes through `input` when its output is not fed. +/// +/// - Parameter input: The default value to produce when `output` is not fed. +/// +/// - Attrs: +/// - dtype: The type of elements in the tensor. +/// - shape: The (possibly partial) shape of the tensor. +/// +/// - Output output: A placeholder tensor that defaults to `input` if it is not fed. +@inlinable @inline(__always) +public static func placeholderWithDefault( + _ input: Tensor, + shape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("PlaceholderWithDefault", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Compute the polygamma function \\(\psi^{(n)}(x)\\). +/// +/// The polygamma function is defined as: +/// +/// +/// \\(\psi^{(a)}(x) = \frac{d^a}{dx^a} \psi(x)\\) +/// +/// where \\(\psi(x)\\) is the digamma function. +/// The polygamma function is defined only for non-negative integer orders \\a\\. +@inlinable @inline(__always) +public static func polygamma( + _ a: Tensor, + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Polygamma", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(x) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func polymorphic( + _ a: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Polymorphic", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func polymorphicDefaultOut( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("PolymorphicDefaultOut", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func polymorphicOut( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("PolymorphicOut", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + return op.execute(Int(1)) +} + +/// Computes element-wise population count (a.k.a. popcount, bitsum, bitcount). +/// +/// For each entry in `x`, calculates the number of `1` (on) bits in the binary +/// representation of that entry. +/// +/// **NOTE**: It is more efficient to first `tf.bitcast` your tensors into +/// `int32` or `int64` and perform the bitcount on the result, than to feed in +/// 8- or 16-bit inputs and then aggregate the resulting counts. +@inlinable @inline(__always) +public static func populationCount( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("PopulationCount", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the power of one value to another. +/// +/// Given a tensor `x` and a tensor `y`, this operation computes \\(x^y\\) for +/// corresponding elements in `x` and `y`. For example: +/// +/// ``` +/// # tensor 'x' is [[2, 2]], [3, 3]] +/// # tensor 'y' is [[8, 16], [2, 3]] +/// tf.pow(x, y) ==> [[256, 65536], [9, 27]] +/// ``` +@inlinable @inline(__always) +public static func pow( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Pow", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Creates a dataset that asynchronously prefetches elements from `input_dataset`. +/// +/// - Parameter buffer_size: The maximum number of elements to buffer in an iterator over +/// this dataset. +@inlinable @inline(__always) +public static func prefetchDataset( + inputDataset: VariantHandle, + bufferSize: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + slackPeriod: Int64 = 0 +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("PrefetchDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("slack_period", slackPeriod) + op.addInput(inputDataset) + op.addInput(bufferSize) + return op.execute(Int(1)) +} + +/// An op which linearizes one Tensor value to an opaque variant tensor. +/// +/// - Parameter input: A tensor that will be linearized. +/// +/// - Attrs: +/// - dtype: The type of elements in the tensor. +/// - shape: The shape of the tensor. +/// - layout: A vector holding the requested layout in minor-to-major sequence. If a layout +/// attribute is passed but its values are all -1 the layout will be computed by +/// the infeed operation. +@inlinable @inline(__always) +public static func prelinearize( + _ input: Tensor, + shape: TensorShape?, + layout: [Int32] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("Prelinearize", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.updateAttribute("layout", layout) + op.addInput(input) + return op.execute(Int(1)) +} + +/// An op which linearizes multiple Tensor values to an opaque variant tensor. +/// +/// - Parameter inputs: A list of tensors that will be provided using the infeed mechanism. +/// +/// - Attrs: +/// - dtypes: The element types of each element in `inputs`. +/// - shapes: The shapes of each tensor in `inputs`. +/// - layouts: A vector holding the requested layout in minor-to-major sequence for all the +/// tuple shapes in the order the shapes appear in the "shapes" input. The layout +/// elements for a sub-shape can be set to -1 in which case the corresponding layout +/// will be computed by the infeed operation. +@inlinable @inline(__always) +public static func prelinearizeTuple( + inputs: Dtypes, + shapes: [TensorShape?], + layouts: [Int32] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("PrelinearizeTuple", nOutputs) + op.updateAttribute("dtypes", inputs._typeList) + op.updateAttribute("shapes", shapes) + op.updateAttribute("layouts", layouts) + op.addInputList(inputs) + return op.execute(Int(1)) +} + +/// An identity op that triggers an error if a gradient is requested. +/// +/// When executed in a graph, this op outputs its input tensor as-is. +/// +/// When building ops to compute gradients, the TensorFlow gradient system +/// will return an error when trying to lookup the gradient of this op, +/// because no gradient must ever be registered for this function. This +/// op exists to prevent subtle bugs from silently returning unimplemented +/// gradients in some corner cases. +/// +/// - Parameter input: any tensor. +/// +/// - Attr message: Will be printed in the error when anyone tries to differentiate +/// this operation. +/// +/// - Output output: the same input tensor. +@inlinable @inline(__always) +public static func preventGradient( + _ input: Tensor, + message: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("PreventGradient", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("message", message) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Prints a list of tensors. +/// +/// Passes `input` through to `output` and prints `data` when evaluating. +/// +/// - Parameters: +/// - input: The tensor passed to `output` +/// - data: A list of tensors to print out when op is evaluated. +/// +/// - Attrs: +/// - message: A string, prefix of the error message. +/// - first_n: Only log `first_n` number of times. -1 disables logging. +/// - summarize: Only print this many entries of each tensor. +/// +/// - Output output: = The unmodified `input` tensor +@inlinable @inline(__always) +public static func print< + T: TensorFlowScalar, + U: TensorArrayProtocol +>( + _ input: Tensor, + data: U, + message: String, + firstN: Int64 = -1, + summarize: Int64 = 3 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Print", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("U", data._typeList) + op.updateAttribute("message", message) + op.updateAttribute("first_n", firstN) + op.updateAttribute("summarize", summarize) + op.addInput(input) + op.addInputList(data) + return op.execute(Int(1)) +} + +/// Prints a string scalar. +/// +/// Prints a string scalar to the desired output_stream. +/// +/// - Parameter input: The string scalar to print. +/// +/// - Attr output_stream: A string specifying the output stream or logging level to print to. +@inlinable @inline(__always) +public static func printV2( + _ input: StringTensor, + outputStream: String = "stderr", + end: String = "" +) { + let nOutputs = 0 + let op = makeOp("PrintV2", nOutputs) + op.updateAttribute("output_stream", outputStream) + op.updateAttribute("end", end) + op.addInput(input) + op.execute() +} + +/// A queue that produces elements sorted by the first component value. +/// +/// Note that the PriorityQueue requires the first component of any element +/// to be a scalar int64, in addition to the other elements declared by +/// component_types. Therefore calls to Enqueue and EnqueueMany (resp. Dequeue +/// and DequeueMany) on a PriorityQueue will all require (resp. output) one extra +/// entry in their input (resp. output) lists. +/// +/// - Attrs: +/// - component_types: The type of each component in a value. +/// - shapes: The shape of each component in a value. The length of this attr must +/// be either 0 or the same as the length of component_types. If the length of +/// this attr is 0, the shapes of queue elements are not constrained, and +/// only one element may be dequeued at a time. +/// - capacity: The upper bound on the number of elements in this queue. +/// Negative numbers mean no limit. +/// - container: If non-empty, this queue is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this queue will be shared under the given name +/// across multiple sessions. +/// +/// - Output handle: The handle to the queue. +@inlinable @inline(__always) +public static func priorityQueueV2( + componentTypes: [TensorDataType], + shapes: [TensorShape?], + capacity: Int64 = -1, + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("PriorityQueueV2", nOutputs) + op.updateAttribute("component_types", componentTypes) + op.updateAttribute("shapes", shapes) + op.updateAttribute("capacity", capacity) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Computes the product of elements across dimensions of a tensor. +/// +/// Reduces `input` along the dimensions given in `axis`. Unless +/// `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in +/// `axis`. If `keep_dims` is true, the reduced dimensions are +/// retained with length 1. +/// +/// - Parameters: +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. +/// +/// - Attr keep_dims: If true, retain reduced dimensions with length 1. +/// +/// - Output output: The reduced tensor. +@inlinable @inline(__always) +public static func prod< + T: Numeric & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Prod", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) +} + +/// Invokes a python function to compute func(input)->output. +/// +/// This operation is considered stateful. For a stateless version, see +/// PyFuncStateless. +/// +/// - Parameter input: List of Tensors that will provide input to the Op. +/// +/// - Attrs: +/// - token: A token representing a registered python function in this address space. +/// - Tin: Data types of the inputs to the op. +/// - Tout: Data types of the outputs from the op. +/// The length of the list specifies the number of outputs. +/// +/// - Output output: The outputs from the Op. +@inlinable @inline(__always) +public static func pyFunc< + Tin: TensorArrayProtocol, + Tout: TensorGroup +>( + _ input: Tin, + token: String +) -> Tout { + let nOutputs = Int(Tout._typeList.count) + let op = makeOp("PyFunc", nOutputs) + op.updateAttribute("token", token) + op.updateAttribute("Tin", input._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.addInputList(input) + return op.execute(Int(Tout._typeList.count)) +} + +/// A stateless version of PyFunc. +@inlinable @inline(__always) +public static func pyFuncStateless< + Tin: TensorArrayProtocol, + Tout: TensorGroup +>( + _ input: Tin, + token: String +) -> Tout { + let nOutputs = Int(Tout._typeList.count) + let op = makeOp("PyFuncStateless", nOutputs) + op.updateAttribute("token", token) + op.updateAttribute("Tin", input._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.addInputList(input) + return op.execute(Int(Tout._typeList.count)) +} + +/// Computes the QR decompositions of one or more matrices. +/// +/// Computes the QR decomposition of each inner matrix in `tensor` such that +/// `tensor[..., :, :] = q[..., :, :] * r[..., :,:])` +/// +/// ```python +/// # a is a tensor. +/// # q is a tensor of orthonormal matrices. +/// # r is a tensor of upper triangular matrices. +/// q, r = qr(a) +/// q_full, r_full = qr(a, full_matrices=True) +/// ``` +/// +/// - Parameter input: A tensor of shape `[..., M, N]` whose inner-most 2 dimensions +/// form matrices of size `[M, N]`. Let `P` be the minimum of `M` and `N`. +/// +/// - Attr full_matrices: If true, compute full-sized `q` and `r`. If false +/// (the default), compute only the leading `P` columns of `q`. +/// +/// - Outputs: +/// - q: Orthonormal basis for range of `a`. If `full_matrices` is `False` then +/// shape is `[..., M, P]`; if `full_matrices` is `True` then shape is +/// `[..., M, M]`. +/// - r: Triangular factor. If `full_matrices` is `False` then shape is +/// `[..., P, N]`. If `full_matrices` is `True` then shape is `[..., M, N]`. +@inlinable @inline(__always) +public static func qr( + _ input: Tensor, + fullMatrices: Bool = false +) -> (q: Tensor, r: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("Qr", nOutputs) + op.updateAttribute("full_matrices", fullMatrices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) +} + +/// Use QuantizeAndDequantizeV2 instead. +@inlinable @inline(__always) +public static func quantizeAndDequantize( + _ input: Tensor, + signedInput: Bool = true, + numBits: Int64 = 8, + rangeGiven: Bool = false, + inputMin: Double = 0, + inputMax: Double = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("QuantizeAndDequantize", nOutputs) + op.updateAttribute("signed_input", signedInput) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("range_given", rangeGiven) + op.updateAttribute("input_min", inputMin) + op.updateAttribute("input_max", inputMax) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Quantizes then dequantizes a tensor. +/// +/// This op simulates the precision loss from the quantized forward pass by: +/// +/// 1. Quantizing the tensor to fixed point numbers, which should match the target +/// quantization method when it is used in inference. +/// 2. Dequantizing it back to floating point numbers for the following ops, most +/// likely matmul. +/// +/// There are different ways to quantize. This version uses only scaling, so 0.0 +/// maps to 0. +/// +/// From the specified 'num_bits' in the quantized output type, it determines +/// minimum and maximum representable quantized values. +/// +/// e.g. +/// +/// * [-128, 127] for signed, num_bits = 8, or +/// * [0, 255] for unsigned, num_bits = 8. +/// +/// If range_given == False, the initial input_min, input_max will be determined +/// automatically as the minimum and maximum values in the input tensor, otherwise +/// the specified values of input_min, input_max are used. +/// +/// Note: If the input_min, input_max are specified, they do not need to equal the +/// actual minimum and maximum values in the tensor. e.g. in some cases it may be +/// beneficial to specify these values such that the low probability extremes of the +/// input distribution are clipped. +/// +/// This op determines the maximum scale_factor that would map the initial +/// [input_min, input_max] range to a range that lies within the representable +/// quantized range. +/// +/// It determines the scale from one of input_min and input_max, then updates the +/// other one to maximize the respresentable range. +/// +/// e.g. +/// +/// * if the output is signed, num_bits = 8, [input_min, input_max] = [-10.0, +/// 5.0]: it would use a scale_factor of -128 / -10.0 = 12.8 In this case, it +/// would update input_max to be 127 / 12.8 = 9.921875 +/// * if the output is signed, num_bits = 8, [input_min, input_max] = [-10.0, +/// 10.0]: it would use a scale_factor of 127 / 10.0 = 12.7 In this case, it +/// would update input_min to be 128.0 / 12.7 = -10.07874 +/// * if the output is unsigned, input_min is forced to be 0, and only the +/// specified input_max is used. +/// +/// After determining the scale_factor and updating the input range, it applies the +/// following to each value in the 'input' tensor. +/// +/// output = round(clamp(value, input_min, input_max) * scale_factor) / scale_factor. +/// +/// The above round function rounds the value based on the given round_mode. +/// +/// +/// - Parameters: +/// - input: Tensor to quantize and then dequantize. +/// - input_min: If `range_given == True`, this specifies the minimum input value that needs to +/// be represented, otherwise it is determined from the min value of the `input` +/// tensor. +/// - input_max: If `range_given == True`, this specifies the maximum input value that needs to +/// be represented, otherwise it is determined from the max value of the `input` +/// tensor. +/// +/// - Attrs: +/// - signed_input: Whether the quantization is signed or unsigned. (actually this parameter should +/// have been called `signed_output`) +/// - num_bits: The bitwidth of the quantization. +/// - range_given: Whether the range is given or should be determined from the `input` tensor. +/// - round_mode: The 'round_mode' attribute controls which rounding tie-breaking algorithm is +/// used when rounding float values to their quantized equivalents. The following +/// rounding modes are currently supported: +/// +/// * HALF_TO_EVEN: this is the default round_mode. +/// * HALF_UP: round towards positive. In this mode 7.5 rounds up to 8 and -7.5 +/// rounds up to -7. +/// +@inlinable @inline(__always) +public static func quantizeAndDequantizeV2( + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor, + signedInput: Bool = true, + numBits: Int64 = 8, + rangeGiven: Bool = false, + roundMode: RoundMode = .halfToEven +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("QuantizeAndDequantizeV2", nOutputs) + op.updateAttribute("signed_input", signedInput) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("range_given", rangeGiven) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("round_mode", roundMode.cName) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + return op.execute(Int(1)) +} + +/// Quantizes then dequantizes a tensor. +/// +/// This is almost identical to QuantizeAndDequantizeV2, except that num_bits is a +/// tensor, so its value can change during training. +@inlinable @inline(__always) +public static func quantizeAndDequantizeV3( + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor, + numBits: Tensor, + signedInput: Bool = true, + rangeGiven: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("QuantizeAndDequantizeV3", nOutputs) + op.updateAttribute("signed_input", signedInput) + op.updateAttribute("range_given", rangeGiven) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + op.addInput(numBits) + return op.execute(Int(1)) +} + +/// Convert the quantized 'input' tensor into a lower-precision 'output', using the +/// +/// actual distribution of the values to maximize the usage of the lower bit depth +/// and adjusting the output min and max ranges accordingly. +/// +/// [input_min, input_max] are scalar floats that specify the range for the float +/// interpretation of the 'input' data. For example, if input_min is -1.0f and +/// input_max is 1.0f, and we are dealing with quint16 quantized data, then a 0 +/// value in the 16-bit data should be interpreted as -1.0f, and a 65535 means 1.0f. +/// +/// This operator tries to squeeze as much precision as possible into an output with +/// a lower bit depth by calculating the actual min and max values found in the +/// data. For example, maybe that quint16 input has no values lower than 16,384 and +/// none higher than 49,152. That means only half the range is actually needed, all +/// the float interpretations are between -0.5f and 0.5f, so if we want to compress +/// the data into a quint8 output, we can use that range rather than the theoretical +/// -1.0f to 1.0f that is suggested by the input min and max. +/// +/// In practice, this is most useful for taking output from operations like +/// QuantizedMatMul that can produce higher bit-depth outputs than their inputs and +/// may have large potential output ranges, but in practice have a distribution of +/// input values that only uses a small fraction of the possible range. By feeding +/// that output into this operator, we can reduce it from 32 bits down to 8 with +/// minimal loss of accuracy. +/// +/// - Parameters: +/// - input_min: The float value that the minimum quantized input value represents. +/// - input_max: The float value that the maximum quantized input value represents. +/// +/// - Attrs: +/// - Tinput: The type of the input. +/// - out_type: The type of the output. Should be a lower bit depth than Tinput. +/// +/// - Outputs: +/// - output_min: The float value that the minimum quantized output value represents. +/// - output_max: The float value that the maximum quantized output value represents. +@inlinable @inline(__always) +public static func quantizeDownAndShrinkRange< + Tinput: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor +) -> (output: Tensor, outputMin: Tensor, outputMax: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizeDownAndShrinkRange", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Quantize the 'input' tensor of type float to 'output' tensor of type 'T'. +/// +/// [min_range, max_range] are scalar floats that specify the range for +/// the 'input' data. The 'mode' attribute controls exactly which calculations are +/// used to convert the float values to their quantized equivalents. The +/// 'round_mode' attribute controls which rounding tie-breaking algorithm is used +/// when rounding float values to their quantized equivalents. +/// +/// In 'MIN_COMBINED' mode, each value of the tensor will undergo the following: +/// +/// ``` +/// out[i] = (in[i] - min_range) * range(T) / (max_range - min_range) +/// if T == qint8: out[i] -= (range(T) + 1) / 2.0 +/// ``` +/// +/// here `range(T) = numeric_limits::max() - numeric_limits::min()` +/// +/// *MIN_COMBINED Mode Example* +/// +/// Assume the input is type float and has a possible range of [0.0, 6.0] and the +/// output type is quint8 ([0, 255]). The min_range and max_range values should be +/// specified as 0.0 and 6.0. Quantizing from float to quint8 will multiply each +/// value of the input by 255/6 and cast to quint8. +/// +/// If the output type was qint8 ([-128, 127]), the operation will additionally +/// subtract each value by 128 prior to casting, so that the range of values aligns +/// with the range of qint8. +/// +/// If the mode is 'MIN_FIRST', then this approach is used: +/// +/// ``` +/// num_discrete_values = 1 << (# of bits in T) +/// range_adjust = num_discrete_values / (num_discrete_values - 1) +/// range = (range_max - range_min) * range_adjust +/// range_scale = num_discrete_values / range +/// quantized = round(input * range_scale) - round(range_min * range_scale) + +/// numeric_limits::min() +/// quantized = max(quantized, numeric_limits::min()) +/// quantized = min(quantized, numeric_limits::max()) +/// ``` +/// +/// The biggest difference between this and MIN_COMBINED is that the minimum range +/// is rounded first, before it's subtracted from the rounded value. With +/// MIN_COMBINED, a small bias is introduced where repeated iterations of quantizing +/// and dequantizing will introduce a larger and larger error. +/// +/// *SCALED mode Example* +/// +/// `SCALED` mode matches the quantization approach used in +/// `QuantizeAndDequantize{V2|V3}`. +/// +/// If the mode is `SCALED`, we do not use the full range of the output type, +/// choosing to elide the lowest possible value for symmetry (e.g., output range is +/// -127 to 127, not -128 to 127 for signed 8 bit quantization), so that 0.0 maps to +/// 0. +/// +/// We first find the range of values in our tensor. The +/// range we use is always centered on 0, so we find m such that +/// +/// ```c++ +/// m = max(abs(input_min), abs(input_max)) +/// ``` +/// +/// Our input tensor range is then `[-m, m]`. +/// +/// Next, we choose our fixed-point quantization buckets, `[min_fixed, max_fixed]`. +/// If T is signed, this is +/// +/// ``` +/// num_bits = sizeof(T) * 8 +/// [min_fixed, max_fixed] = +/// [-(1 << (num_bits - 1) - 1), (1 << (num_bits - 1)) - 1] +/// ``` +/// +/// Otherwise, if T is unsigned, the fixed-point range is +/// +/// ``` +/// [min_fixed, max_fixed] = [0, (1 << num_bits) - 1] +/// ``` +/// +/// From this we compute our scaling factor, s: +/// +/// ```c++ +/// s = (max_fixed - min_fixed) / (2 * m) +/// ``` +/// +/// Now we can quantize the elements of our tensor: +/// +/// ```c++ +/// result = round(input * s) +/// ``` +/// +/// One thing to watch out for is that the operator may choose to adjust the +/// requested minimum and maximum values slightly during the quantization process, +/// so you should always use the output ports as the range for further calculations. +/// For example, if the requested minimum and maximum values are close to equal, +/// they will be separated by a small epsilon value to prevent ill-formed quantized +/// buffers from being created. Otherwise, you can end up with buffers where all the +/// quantized values map to the same float value, which causes problems for +/// operations that have to perform further calculations on them. +/// +/// - Parameters: +/// - min_range: The minimum scalar value possibly produced for the input. +/// - max_range: The maximum scalar value possibly produced for the input. +/// +/// - Outputs: +/// - output: The quantized data produced from the float input. +/// - output_min: The actual minimum scalar value used for the output. +/// - output_max: The actual maximum scalar value used for the output. +@inlinable @inline(__always) +public static func quantizeV2( + _ input: Tensor, + minRange: Tensor, + maxRange: Tensor, + mode: Mode = .minCombined, + roundMode: RoundMode6 = .halfAwayFromZero +) -> (output: Tensor, outputMin: Tensor, outputMax: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizeV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("mode", mode.cName) + op.updateAttribute("round_mode", roundMode.cName) + op.addInput(input) + op.addInput(minRange) + op.addInput(maxRange) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Returns x + y element-wise, working on quantized buffers. +/// +/// - Parameters: +/// - min_x: The float value that the lowest quantized `x` value represents. +/// - max_x: The float value that the highest quantized `x` value represents. +/// - min_y: The float value that the lowest quantized `y` value represents. +/// - max_y: The float value that the highest quantized `y` value represents. +/// +/// - Outputs: +/// - min_z: The float value that the lowest quantized output value represents. +/// - max_z: The float value that the highest quantized output value represents. +/// +/// *NOTE*: `QuantizedAdd` supports limited forms of broadcasting. More about +/// broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func quantizedAdd< + T1: TensorFlowScalar, + T2: TensorFlowScalar, + Toutput: TensorFlowScalar +>( + _ x: Tensor, + _ y: Tensor, + minX: Tensor, + maxX: Tensor, + minY: Tensor, + maxY: Tensor +) -> (z: Tensor, minZ: Tensor, maxZ: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedAdd", nOutputs) + op.updateAttribute("T1", T1.tensorFlowDataType) + op.updateAttribute("T2", T2.tensorFlowDataType) + op.updateAttribute("Toutput", Toutput.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + op.addInput(minX) + op.addInput(maxX) + op.addInput(minY) + op.addInput(maxY) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Produces the average pool of the input tensor for quantized types. +/// +/// - Parameters: +/// - input: 4-D with shape `[batch, height, width, channels]`. +/// - min_input: The float value that the lowest quantized input value represents. +/// - max_input: The float value that the highest quantized input value represents. +/// +/// - Attrs: +/// - ksize: The size of the window for each dimension of the input tensor. +/// The length must be 4 to match the number of dimensions of the input. +/// - strides: The stride of the sliding window for each dimension of the input +/// tensor. The length must be 4 to match the number of dimensions of the input. +/// - padding: The type of padding algorithm to use. +/// +/// - Outputs: +/// - min_output: The float value that the lowest quantized output value represents. +/// - max_output: The float value that the highest quantized output value represents. +@inlinable @inline(__always) +public static func quantizedAvgPool( + _ input: Tensor, + minInput: Tensor, + maxInput: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedAvgPool", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(minInput) + op.addInput(maxInput) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Quantized Batch normalization. +/// +/// This op is deprecated and will be removed in the future. Prefer +/// `tf.nn.batch_normalization`. +/// +/// - Parameters: +/// - t: A 4D input Tensor. +/// - t_min: The value represented by the lowest quantized input. +/// - t_max: The value represented by the highest quantized input. +/// - m: A 1D mean Tensor with size matching the last dimension of t. +/// This is the first output from tf.nn.moments, +/// or a saved moving average thereof. +/// - m_min: The value represented by the lowest quantized mean. +/// - m_max: The value represented by the highest quantized mean. +/// - v: A 1D variance Tensor with size matching the last dimension of t. +/// This is the second output from tf.nn.moments, +/// or a saved moving average thereof. +/// - v_min: The value represented by the lowest quantized variance. +/// - v_max: The value represented by the highest quantized variance. +/// - beta: A 1D beta Tensor with size matching the last dimension of t. +/// An offset to be added to the normalized tensor. +/// - beta_min: The value represented by the lowest quantized offset. +/// - beta_max: The value represented by the highest quantized offset. +/// - gamma: A 1D gamma Tensor with size matching the last dimension of t. +/// If "scale_after_normalization" is true, this tensor will be multiplied +/// with the normalized tensor. +/// - gamma_min: The value represented by the lowest quantized gamma. +/// - gamma_max: The value represented by the highest quantized gamma. +/// +/// - Attrs: +/// - variance_epsilon: A small float number to avoid dividing by 0. +/// - scale_after_normalization: A bool indicating whether the resulted tensor +/// needs to be multiplied with gamma. +@inlinable @inline(__always) +public static func quantizedBatchNormWithGlobalNormalization< + Tinput: TensorFlowScalar, + OutType: TensorFlowScalar +>( + t: Tensor, + tMin: Tensor, + tMax: Tensor, + m: Tensor, + mMin: Tensor, + mMax: Tensor, + v: Tensor, + vMin: Tensor, + vMax: Tensor, + beta: Tensor, + betaMin: Tensor, + betaMax: Tensor, + gamma: Tensor, + gammaMin: Tensor, + gammaMax: Tensor, + varianceEpsilon: Double, + scaleAfterNormalization: Bool +) -> (result: Tensor, resultMin: Tensor, resultMax: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedBatchNormWithGlobalNormalization", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("variance_epsilon", varianceEpsilon) + op.updateAttribute("scale_after_normalization", scaleAfterNormalization) + op.addInput(t) + op.addInput(tMin) + op.addInput(tMax) + op.addInput(m) + op.addInput(mMin) + op.addInput(mMax) + op.addInput(v) + op.addInput(vMin) + op.addInput(vMax) + op.addInput(beta) + op.addInput(betaMin) + op.addInput(betaMax) + op.addInput(gamma) + op.addInput(gammaMin) + op.addInput(gammaMax) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Adds Tensor 'bias' to Tensor 'input' for Quantized types. +/// +/// Broadcasts the values of bias on dimensions 0..N-2 of 'input'. +/// +/// - Parameters: +/// - bias: A 1D bias Tensor with size matching the last dimension of 'input'. +/// - min_input: The float value that the lowest quantized input value represents. +/// - max_input: The float value that the highest quantized input value represents. +/// - min_bias: The float value that the lowest quantized bias value represents. +/// - max_bias: The float value that the highest quantized bias value represents. +/// +/// - Outputs: +/// - min_out: The float value that the lowest quantized output value represents. +/// - max_out: The float value that the highest quantized output value represents. +@inlinable @inline(__always) +public static func quantizedBiasAdd< + T1: TensorFlowScalar, + T2: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minBias: Tensor, + maxBias: Tensor +) -> (output: Tensor, minOut: Tensor, maxOut: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedBiasAdd", nOutputs) + op.updateAttribute("T1", T1.tensorFlowDataType) + op.updateAttribute("T2", T2.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minBias) + op.addInput(maxBias) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Concatenates quantized tensors along one dimension. +/// +/// - Parameters: +/// - concat_dim: 0-D. The dimension along which to concatenate. Must be in the +/// range [0, rank(values)). +/// - values: The `N` Tensors to concatenate. Their ranks and types must match, +/// and their sizes must match in all dimensions except `concat_dim`. +/// - input_mins: The minimum scalar values for each of the input tensors. +/// - input_maxes: The maximum scalar values for each of the input tensors. +/// +/// - Outputs: +/// - output: A `Tensor` with the concatenation of values stacked along the +/// `concat_dim` dimension. This tensor's shape matches that of `values` except +/// in `concat_dim` where it has the sum of the sizes. +/// - output_min: The float value that the minimum quantized output value represents. +/// - output_max: The float value that the maximum quantized output value represents. +@inlinable @inline(__always) +public static func quantizedConcat( + concatDim: Tensor, + _ values: [Tensor], + inputMins: [Tensor], + inputMaxes: [Tensor] +) -> (output: Tensor, outputMin: Tensor, outputMax: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedConcat", nOutputs) + op.updateAttribute("N", values.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(concatDim) + op.addInputList(values) + op.addInputList(inputMins) + op.addInputList(inputMaxes) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Computes a 2D convolution given quantized 4D input and filter tensors. +/// +/// The inputs are quantized tensors where the lowest value represents the real +/// number of the associated minimum, and the highest represents the maximum. +/// This means that you can only interpret the quantized output in the same way, by +/// taking the returned minimum and maximum values into account. +/// +/// - Parameters: +/// - filter: filter's input_depth dimension must match input's depth dimensions. +/// - min_input: The float value that the lowest quantized input value represents. +/// - max_input: The float value that the highest quantized input value represents. +/// - min_filter: The float value that the lowest quantized filter value represents. +/// - max_filter: The float value that the highest quantized filter value represents. +/// +/// - Attrs: +/// - strides: The stride of the sliding window for each dimension of the input +/// tensor. +/// - padding: The type of padding algorithm to use. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each +/// filter element on that dimension. The dimension order is determined by the +/// value of `data_format`, see above for details. Dilations in the batch and +/// depth dimensions must be 1. +/// +/// - Outputs: +/// - min_output: The float value that the lowest quantized output value represents. +/// - max_output: The float value that the highest quantized output value represents. +@inlinable @inline(__always) +public static func quantizedConv2D< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedConv2D", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func quantizedConv2DAndRelu< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedConv2DAndRelu", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func quantizedConv2DAndReluAndRequantize< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedConv2DAndReluAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + return op.execute(Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func quantizedConv2DAndRequantize< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedConv2DAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Computes QuantizedConv2D per channel. +/// +/// - Parameters: +/// - input: The original input tensor. +/// - filter: The original filter tensor. +/// - min_input: The minimum value of the input tensor +/// - max_input: The maximum value of the input tensor. +/// - min_filter: The minimum value of the filter tensor. +/// - max_filter: The maximum value of the filter tensor. +/// +/// - Attrs: +/// - Tinput: The quantized type of input tensor that needs to be converted. +/// - Tfilter: The quantized type of filter tensor that needs to be converted. +/// - out_type: The quantized type of output tensor that needs to be converted. +/// - strides: list of stride values. +/// - dilations: list of dilation values. +/// +/// - Outputs: +/// - output: The output tensor. +/// - min_output: The minimum value of the final output tensor. +/// - max_output: The maximum value of the final output tensor. +@inlinable @inline(__always) +public static func quantizedConv2DPerChannel< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedConv2DPerChannel", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func quantizedConv2DWithBias< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedConv2DWithBias", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func quantizedConv2DWithBiasAndRelu< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedConv2DWithBiasAndRelu", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func quantizedConv2DWithBiasAndReluAndRequantize< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + Tbias: FloatingPoint & TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedConv2DWithBiasAndReluAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("Tbias", Tbias.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + return op.execute(Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func quantizedConv2DWithBiasAndRequantize< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + Tbias: FloatingPoint & TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedConv2DWithBiasAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("Tbias", Tbias.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + return op.execute(Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func quantizedConv2DWithBiasSignedSumAndReluAndRequantize< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + Tbias: FloatingPoint & TensorFlowScalar, + Tsummand: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + summand: Tensor, + minSummand: Tensor, + maxSummand: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedConv2DWithBiasSignedSumAndReluAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("Tbias", Tbias.tensorFlowDataType) + op.updateAttribute("Tsummand", Tsummand.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + op.addInput(summand) + op.addInput(minSummand) + op.addInput(maxSummand) + return op.execute(Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func quantizedConv2DWithBiasSumAndRelu< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + summand: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedConv2DWithBiasSumAndRelu", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(summand) + return op.execute(Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func quantizedConv2DWithBiasSumAndReluAndRequantize< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + Tbias: FloatingPoint & TensorFlowScalar, + Tsummand: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + summand: Tensor, + minSummand: Tensor, + maxSummand: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedConv2DWithBiasSumAndReluAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("Tbias", Tbias.tensorFlowDataType) + op.updateAttribute("Tsummand", Tsummand.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + op.addInput(summand) + op.addInput(minSummand) + op.addInput(maxSummand) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Computes quantized depthwise Conv2D. +/// +/// - Parameters: +/// - input: The original input tensor. +/// - filter: The original filter tensor. +/// - min_input: The float value that the minimum quantized input value represents. +/// - max_input: The float value that the maximum quantized input value represents. +/// - min_filter: The float value that the minimum quantized filter value represents. +/// - max_filter: The float value that the maximum quantized filter value represents. +/// +/// - Attrs: +/// - Tinput: The type of the input. +/// - Tfilter: The type of the filter. +/// - out_type: The type of the output. +/// - strides: List of stride values. +/// - dilations: List of dilation values. +/// +/// - Outputs: +/// - output: The output tensor. +/// - min_output: The float value that the minimum quantized output value represents. +/// - max_output: The float value that the maximum quantized output value represents. +@inlinable @inline(__always) +public static func quantizedDepthwiseConv2D< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedDepthwiseConv2D", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Computes quantized depthwise Conv2D with Bias. +/// +/// - Parameters: +/// - input: The original input tensor. +/// - filter: The original filter tensor. +/// - bias: The original bias tensor. +/// - min_input: The float value that the minimum quantized input value represents. +/// - max_input: The float value that the maximum quantized input value represents. +/// - min_filter: The float value that the minimum quantized filter value represents. +/// - max_filter: The float value that the maximum quantized filter value represents. +/// +/// - Attrs: +/// - Tinput: The type of the input. +/// - Tfilter: The type of the filter. +/// - out_type: The type of the output. +/// - strides: List of stride values. +/// - dilations: List of dilation values. +/// +/// - Outputs: +/// - output: The output tensor. +/// - min_output: The float value that the minimum quantized output value represents. +/// - max_output: The float value that the maximum quantized output value represents. +@inlinable @inline(__always) +public static func quantizedDepthwiseConv2DWithBias< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedDepthwiseConv2DWithBias", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Computes quantized depthwise Conv2D with Bias and Relu. +/// +/// - Parameters: +/// - input: The original input tensor. +/// - filter: The original filter tensor. +/// - bias: The original bias tensor. +/// - min_input: The float value that the minimum quantized input value represents. +/// - max_input: The float value that the maximum quantized input value represents. +/// - min_filter: The float value that the minimum quantized filter value represents. +/// - max_filter: The float value that the maximum quantized filter value represents. +/// +/// - Attrs: +/// - Tinput: The type of the input. +/// - Tfilter: The type of the filter. +/// - out_type: The type of the output. +/// - strides: List of stride values. +/// - dilations: List of dilation values. +/// +/// - Outputs: +/// - output: The output tensor. +/// - min_output: The float value that the minimum quantized output value represents. +/// - max_output: The float value that the maximum quantized output value represents. +@inlinable @inline(__always) +public static func quantizedDepthwiseConv2DWithBiasAndRelu< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedDepthwiseConv2DWithBiasAndRelu", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Computes quantized depthwise Conv2D with Bias, Relu and Requantize. +/// +/// - Parameters: +/// - input: The original input tensor. +/// - filter: The original filter tensor. +/// - bias: The original bias tensor. +/// - min_input: The float value that the minimum quantized input value represents. +/// - max_input: The float value that the maximum quantized input value represents. +/// - min_filter: The float value that the minimum quantized filter value represents. +/// - max_filter: The float value that the maximum quantized filter value represents. +/// - min_freezed_output: The minimum float value of the output tensor. +/// - max_freezed_output: The maximum float value of the output tensor. +/// +/// - Attrs: +/// - Tinput: The type of the input. +/// - Tfilter: The type of the filter. +/// - Tbias: The type of the bias. +/// - out_type: The type of the output. +/// - strides: List of stride values. +/// - dilations: List of dilation values. +/// +/// - Outputs: +/// - output: The output tensor. +/// - min_output: The float value that the minimum quantized output value represents. +/// - max_output: The float value that the maximum quantized output value represents. +@inlinable @inline(__always) +public static func quantizedDepthwiseConv2DWithBiasAndReluAndRequantize< + Tinput: TensorFlowScalar, + Tfilter: TensorFlowScalar, + Tbias: FloatingPoint & TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1] +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("Tbias", Tbias.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Quantized Instance normalization. +/// +/// - Parameters: +/// - x: A 4D input Tensor. +/// - x_min: The value represented by the lowest quantized input. +/// - x_max: The value represented by the highest quantized input. +/// +/// - Attrs: +/// - output_range_given: If True, `given_y_min` and `given_y_min` +/// and `given_y_max` are used as the output range. Otherwise, +/// the implementation computes the output range. +/// - given_y_min: Output in `y_min` if `output_range_given` is True. +/// - given_y_max: Output in `y_max` if `output_range_given` is True. +/// - variance_epsilon: A small float number to avoid dividing by 0. +/// - min_separation: Minimum value of `y_max - y_min` +/// +/// - Outputs: +/// - y: A 4D Tensor. +/// - y_min: The value represented by the lowest quantized output. +/// - y_max: The value represented by the highest quantized output. +@inlinable @inline(__always) +public static func quantizedInstanceNorm( + _ x: Tensor, + xMin: Tensor, + xMax: Tensor, + outputRangeGiven: Bool = false, + givenYMin: Double = 0, + givenYMax: Double = 0, + varianceEpsilon: Double = 1e-05, + minSeparation: Double = 0.001 +) -> (y: Tensor, yMin: Tensor, yMax: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedInstanceNorm", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("output_range_given", outputRangeGiven) + op.updateAttribute("given_y_min", givenYMin) + op.updateAttribute("given_y_max", givenYMax) + op.updateAttribute("variance_epsilon", varianceEpsilon) + op.updateAttribute("min_separation", minSeparation) + op.addInput(x) + op.addInput(xMin) + op.addInput(xMax) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Perform a quantized matrix multiplication of `a` by the matrix `b`. +/// +/// The inputs must be two-dimensional matrices and the inner dimension of +/// `a` (after being transposed if `transpose_a` is non-zero) must match the +/// outer dimension of `b` (after being transposed if `transposed_b` is +/// non-zero). +/// +/// - Parameters: +/// - a: Must be a two-dimensional tensor. +/// - b: Must be a two-dimensional tensor. +/// - min_a: The float value that the lowest quantized `a` value represents. +/// - max_a: The float value that the highest quantized `a` value represents. +/// - min_b: The float value that the lowest quantized `b` value represents. +/// - max_b: The float value that the highest quantized `b` value represents. +/// +/// - Attrs: +/// - transpose_a: If true, `a` is transposed before multiplication. +/// - transpose_b: If true, `b` is transposed before multiplication. +/// - Tactivation: The type of output produced by activation function +/// following this operation. +/// +/// - Outputs: +/// - min_out: The float value that the lowest quantized output value represents. +/// - max_out: The float value that the highest quantized output value represents. +@inlinable @inline(__always) +public static func quantizedMatMul< + T1: TensorFlowScalar, + T2: TensorFlowScalar, + Toutput: TensorFlowScalar +>( + _ a: Tensor, + _ b: Tensor, + minA: Tensor, + maxA: Tensor, + minB: Tensor, + maxB: Tensor, + transposeA: Bool = false, + transposeB: Bool = false, + tactivation: TensorDataType +) -> (out: Tensor, minOut: Tensor, maxOut: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedMatMul", nOutputs) + op.updateAttribute("T1", T1.tensorFlowDataType) + op.updateAttribute("T2", T2.tensorFlowDataType) + op.updateAttribute("Toutput", Toutput.tensorFlowDataType) + op.updateAttribute("transpose_a", transposeA) + op.updateAttribute("transpose_b", transposeB) + op.updateAttribute("Tactivation", tactivation) + op.addInput(a) + op.addInput(b) + op.addInput(minA) + op.addInput(maxA) + op.addInput(minB) + op.addInput(maxB) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Produces the max pool of the input tensor for quantized types. +/// +/// - Parameters: +/// - input: The 4D (batch x rows x cols x depth) Tensor to MaxReduce over. +/// - min_input: The float value that the lowest quantized input value represents. +/// - max_input: The float value that the highest quantized input value represents. +/// +/// - Attrs: +/// - ksize: The size of the window for each dimension of the input tensor. +/// The length must be 4 to match the number of dimensions of the input. +/// - strides: The stride of the sliding window for each dimension of the input +/// tensor. The length must be 4 to match the number of dimensions of the input. +/// - padding: The type of padding algorithm to use. +/// +/// - Outputs: +/// - min_output: The float value that the lowest quantized output value represents. +/// - max_output: The float value that the highest quantized output value represents. +@inlinable @inline(__always) +public static func quantizedMaxPool( + _ input: Tensor, + minInput: Tensor, + maxInput: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding +) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedMaxPool", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(minInput) + op.addInput(maxInput) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Returns x * y element-wise, working on quantized buffers. +/// +/// - Parameters: +/// - min_x: The float value that the lowest quantized `x` value represents. +/// - max_x: The float value that the highest quantized `x` value represents. +/// - min_y: The float value that the lowest quantized `y` value represents. +/// - max_y: The float value that the highest quantized `y` value represents. +/// +/// - Outputs: +/// - min_z: The float value that the lowest quantized output value represents. +/// - max_z: The float value that the highest quantized output value represents. +/// +/// *NOTE*: `QuantizedMul` supports limited forms of broadcasting. More about +/// broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func quantizedMul< + T1: TensorFlowScalar, + T2: TensorFlowScalar, + Toutput: TensorFlowScalar +>( + _ x: Tensor, + _ y: Tensor, + minX: Tensor, + maxX: Tensor, + minY: Tensor, + maxY: Tensor +) -> (z: Tensor, minZ: Tensor, maxZ: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedMul", nOutputs) + op.updateAttribute("T1", T1.tensorFlowDataType) + op.updateAttribute("T2", T2.tensorFlowDataType) + op.updateAttribute("Toutput", Toutput.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + op.addInput(minX) + op.addInput(maxX) + op.addInput(minY) + op.addInput(maxY) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Computes Quantized Rectified Linear: `max(features, 0)` +/// +/// - Parameters: +/// - min_features: The float value that the lowest quantized value represents. +/// - max_features: The float value that the highest quantized value represents. +/// +/// - Outputs: +/// - activations: Has the same output shape as "features". +/// - min_activations: The float value that the lowest quantized value represents. +/// - max_activations: The float value that the highest quantized value represents. +@inlinable @inline(__always) +public static func quantizedRelu< + Tinput: TensorFlowScalar, + OutType: TensorFlowScalar +>( + features: Tensor, + minFeatures: Tensor, + maxFeatures: Tensor +) -> (activations: Tensor, minActivations: Tensor, maxActivations: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedRelu", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(features) + op.addInput(minFeatures) + op.addInput(maxFeatures) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Computes Quantized Rectified Linear 6: `min(max(features, 0), 6)` +/// +/// - Parameters: +/// - min_features: The float value that the lowest quantized value represents. +/// - max_features: The float value that the highest quantized value represents. +/// +/// - Outputs: +/// - activations: Has the same output shape as "features". +/// - min_activations: The float value that the lowest quantized value represents. +/// - max_activations: The float value that the highest quantized value represents. +@inlinable @inline(__always) +public static func quantizedRelu6< + Tinput: TensorFlowScalar, + OutType: TensorFlowScalar +>( + features: Tensor, + minFeatures: Tensor, + maxFeatures: Tensor +) -> (activations: Tensor, minActivations: Tensor, maxActivations: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedRelu6", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(features) + op.addInput(minFeatures) + op.addInput(maxFeatures) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Computes Quantized Rectified Linear X: `min(max(features, 0), max_value)` +/// +/// - Parameters: +/// - min_features: The float value that the lowest quantized value represents. +/// - max_features: The float value that the highest quantized value represents. +/// +/// - Outputs: +/// - activations: Has the same output shape as "features". +/// - min_activations: The float value that the lowest quantized value represents. +/// - max_activations: The float value that the highest quantized value represents. +@inlinable @inline(__always) +public static func quantizedReluX< + Tinput: TensorFlowScalar, + OutType: TensorFlowScalar +>( + features: Tensor, + maxValue: Tensor, + minFeatures: Tensor, + maxFeatures: Tensor +) -> (activations: Tensor, minActivations: Tensor, maxActivations: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedReluX", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(features) + op.addInput(maxValue) + op.addInput(minFeatures) + op.addInput(maxFeatures) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Reshapes a quantized tensor as per the Reshape op. +/// +/// ``` +/// +/// - Parameters: +/// - shape: Defines the shape of the output tensor. +/// - input_min: The minimum value of the input. +/// - input_max: The maximum value of the input. +/// +/// - Outputs: +/// - output_min: This value is copied from input_min. +/// - output_max: This value is copied from input_max. +@inlinable @inline(__always) +public static func quantizedReshape< + T: TensorFlowScalar, + Tshape: BinaryInteger & TensorFlowScalar +>( + _ tensor: Tensor, + shape: Tensor, + inputMin: Tensor, + inputMax: Tensor +) -> (output: Tensor, outputMin: Tensor, outputMax: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedReshape", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tshape", Tshape.tensorFlowDataType) + op.addInput(tensor) + op.addInput(shape) + op.addInput(inputMin) + op.addInput(inputMax) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Resize quantized `images` to `size` using quantized bilinear interpolation. +/// +/// Input images and output images must be quantized types. +/// +/// - Parameters: +/// - images: 4-D with shape `[batch, height, width, channels]`. +/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The +/// new size for the images. +/// +/// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and output tensors are +/// aligned, preserving the values at the corner pixels. Defaults to false. +/// +/// - Output resized_images: 4-D with shape +/// `[batch, new_height, new_width, channels]`. +@inlinable @inline(__always) +public static func quantizedResizeBilinear( + images: Tensor, + size: Tensor, + min: Tensor, + max: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false +) -> (resizedImages: Tensor, outMin: Tensor, outMax: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("QuantizedResizeBilinear", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(images) + op.addInput(size) + op.addInput(min) + op.addInput(max) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Closes the given queue. +/// +/// This operation signals that no more elements will be enqueued in the +/// given queue. Subsequent Enqueue(Many) operations will fail. +/// Subsequent Dequeue(Many) operations will continue to succeed if +/// sufficient elements remain in the queue. Subsequent Dequeue(Many) +/// operations that would block will fail immediately. +/// +/// - Parameter handle: The handle to a queue. +/// +/// - Attr cancel_pending_enqueues: If true, all pending enqueue requests that are +/// blocked on the given queue will be canceled. +@inlinable @inline(__always) +public static func queueCloseV2( + handle: ResourceHandle, + cancelPendingEnqueues: Bool = false +) { + let nOutputs = 0 + let op = makeOp("QueueCloseV2", nOutputs) + op.updateAttribute("cancel_pending_enqueues", cancelPendingEnqueues) + op.addInput(handle) + op.execute() +} + +/// Dequeues `n` tuples of one or more tensors from the given queue. +/// +/// If the queue is closed and there are fewer than `n` elements, then an +/// OutOfRange error is returned. +/// +/// This operation concatenates queue-element component tensors along the +/// 0th dimension to make a single component tensor. All of the components +/// in the dequeued tuple will have size `n` in the 0th dimension. +/// +/// This operation has `k` outputs, where `k` is the number of components in +/// the tuples stored in the given queue, and output `i` is the ith +/// component of the dequeued tuple. +/// +/// N.B. If the queue is empty, this operation will block until `n` elements +/// have been dequeued (or 'timeout_ms' elapses, if specified). +/// +/// - Parameters: +/// - handle: The handle to a queue. +/// - n: The number of tuples to dequeue. +/// +/// - Attrs: +/// - component_types: The type of each component in a tuple. +/// - timeout_ms: If the queue has fewer than n elements, this operation +/// will block for up to timeout_ms milliseconds. +/// Note: This option is not supported yet. +/// +/// - Output components: One or more tensors that were dequeued as a tuple. +@inlinable @inline(__always) +public static func queueDequeueManyV2( + handle: ResourceHandle, + n: Tensor, + timeoutMs: Int64 = -1 +) -> ComponentTypes { + let nOutputs = Int(ComponentTypes._typeList.count) + let op = makeOp("QueueDequeueManyV2", nOutputs) + op.updateAttribute("component_types", ComponentTypes._typeList) + op.updateAttribute("timeout_ms", timeoutMs) + op.addInput(handle) + op.addInput(n) + return op.execute(Int(ComponentTypes._typeList.count)) +} + +/// Dequeues `n` tuples of one or more tensors from the given queue. +/// +/// This operation is not supported by all queues. If a queue does not support +/// DequeueUpTo, then an Unimplemented error is returned. +/// +/// If the queue is closed and there are more than 0 but less than `n` +/// elements remaining, then instead of returning an OutOfRange error like +/// QueueDequeueMany, less than `n` elements are returned immediately. If +/// the queue is closed and there are 0 elements left in the queue, then +/// an OutOfRange error is returned just like in QueueDequeueMany. +/// Otherwise the behavior is identical to QueueDequeueMany: +/// +/// This operation concatenates queue-element component tensors along the +/// 0th dimension to make a single component tensor. All of the components +/// in the dequeued tuple will have size n in the 0th dimension. +/// +/// This operation has `k` outputs, where `k` is the number of components in +/// the tuples stored in the given queue, and output `i` is the ith +/// component of the dequeued tuple. +/// +/// - Parameters: +/// - handle: The handle to a queue. +/// - n: The number of tuples to dequeue. +/// +/// - Attrs: +/// - component_types: The type of each component in a tuple. +/// - timeout_ms: If the queue has fewer than n elements, this operation +/// will block for up to timeout_ms milliseconds. +/// Note: This option is not supported yet. +/// +/// - Output components: One or more tensors that were dequeued as a tuple. +@inlinable @inline(__always) +public static func queueDequeueUpToV2( + handle: ResourceHandle, + n: Tensor, + timeoutMs: Int64 = -1 +) -> ComponentTypes { + let nOutputs = Int(ComponentTypes._typeList.count) + let op = makeOp("QueueDequeueUpToV2", nOutputs) + op.updateAttribute("component_types", ComponentTypes._typeList) + op.updateAttribute("timeout_ms", timeoutMs) + op.addInput(handle) + op.addInput(n) + return op.execute(Int(ComponentTypes._typeList.count)) +} + +/// Dequeues a tuple of one or more tensors from the given queue. +/// +/// This operation has k outputs, where k is the number of components +/// in the tuples stored in the given queue, and output i is the ith +/// component of the dequeued tuple. +/// +/// N.B. If the queue is empty, this operation will block until an element +/// has been dequeued (or 'timeout_ms' elapses, if specified). +/// +/// - Parameter handle: The handle to a queue. +/// +/// - Attrs: +/// - component_types: The type of each component in a tuple. +/// - timeout_ms: If the queue is empty, this operation will block for up to +/// timeout_ms milliseconds. +/// Note: This option is not supported yet. +/// +/// - Output components: One or more tensors that were dequeued as a tuple. +@inlinable @inline(__always) +public static func queueDequeueV2( + handle: ResourceHandle, + timeoutMs: Int64 = -1 +) -> ComponentTypes { + let nOutputs = Int(ComponentTypes._typeList.count) + let op = makeOp("QueueDequeueV2", nOutputs) + op.updateAttribute("component_types", ComponentTypes._typeList) + op.updateAttribute("timeout_ms", timeoutMs) + op.addInput(handle) + return op.execute(Int(ComponentTypes._typeList.count)) +} + +/// Enqueues zero or more tuples of one or more tensors in the given queue. +/// +/// This operation slices each component tensor along the 0th dimension to +/// make multiple queue elements. All of the tuple components must have the +/// same size in the 0th dimension. +/// +/// The components input has k elements, which correspond to the components of +/// tuples stored in the given queue. +/// +/// N.B. If the queue is full, this operation will block until the given +/// elements have been enqueued (or 'timeout_ms' elapses, if specified). +/// +/// - Parameters: +/// - handle: The handle to a queue. +/// - components: One or more tensors from which the enqueued tensors should +/// be taken. +/// +/// - Attr timeout_ms: If the queue is too full, this operation will block for up +/// to timeout_ms milliseconds. +/// Note: This option is not supported yet. +@inlinable @inline(__always) +public static func queueEnqueueManyV2( + handle: ResourceHandle, + components: Tcomponents, + timeoutMs: Int64 = -1 +) { + let nOutputs = 0 + let op = makeOp("QueueEnqueueManyV2", nOutputs) + op.updateAttribute("Tcomponents", components._typeList) + op.updateAttribute("timeout_ms", timeoutMs) + op.addInput(handle) + op.addInputList(components) + op.execute() +} + +/// Enqueues a tuple of one or more tensors in the given queue. +/// +/// The components input has k elements, which correspond to the components of +/// tuples stored in the given queue. +/// +/// N.B. If the queue is full, this operation will block until the given +/// element has been enqueued (or 'timeout_ms' elapses, if specified). +/// +/// - Parameters: +/// - handle: The handle to a queue. +/// - components: One or more tensors from which the enqueued tensors should be taken. +/// +/// - Attr timeout_ms: If the queue is full, this operation will block for up to +/// timeout_ms milliseconds. +/// Note: This option is not supported yet. +@inlinable @inline(__always) +public static func queueEnqueueV2( + handle: ResourceHandle, + components: Tcomponents, + timeoutMs: Int64 = -1 +) { + let nOutputs = 0 + let op = makeOp("QueueEnqueueV2", nOutputs) + op.updateAttribute("Tcomponents", components._typeList) + op.updateAttribute("timeout_ms", timeoutMs) + op.addInput(handle) + op.addInputList(components) + op.execute() +} + +/// Returns true if queue is closed. +/// +/// This operation returns true if the queue is closed and false if the queue +/// is open. +/// +/// - Parameter handle: The handle to a queue. +@inlinable @inline(__always) +public static func queueIsClosedV2( + handle: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("QueueIsClosedV2", nOutputs) + op.addInput(handle) + return op.execute(Int(1)) +} + +/// Computes the number of elements in the given queue. +/// +/// - Parameter handle: The handle to a queue. +/// +/// - Output size: The number of elements in the given queue. +@inlinable @inline(__always) +public static func queueSizeV2( + handle: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("QueueSizeV2", nOutputs) + op.addInput(handle) + return op.execute(Int(1)) +} + +/// Converts one or more images from RGB to HSV. +/// +/// Outputs a tensor of the same shape as the `images` tensor, containing the HSV +/// value of the pixels. The output is only well defined if the value in `images` +/// are in `[0,1]`. +/// +/// `output[..., 0]` contains hue, `output[..., 1]` contains saturation, and +/// `output[..., 2]` contains value. All HSV values are in `[0,1]`. A hue of 0 +/// corresponds to pure red, hue 1/3 is pure green, and 2/3 is pure blue. +/// +/// - Parameter images: 1-D or higher rank. RGB data to convert. Last dimension must be size 3. +/// +/// - Output output: `images` converted to HSV. +@inlinable @inline(__always) +public static func rGBToHSV( + images: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RGBToHSV", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + return op.execute(Int(1)) +} + +/// Gather ragged slices from `params` axis `0` according to `indices`. +/// +/// Outputs a `RaggedTensor` output composed from `output_dense_values` and +/// `output_nested_splits`, such that: +/// +/// ```python +/// output.shape = indices.shape + params.shape[1:] +/// output.ragged_rank = indices.shape.ndims + params.ragged_rank +/// output[i...j, d0...dn] = params[indices[i...j], d0...dn] +/// ``` +/// +/// where +/// +/// * `params = +/// ragged.from_nested_row_splits(params_dense_values, params_nested_splits)` +/// provides the values that should be gathered. +/// * `indices` ia a dense tensor with dtype `int32` or `int64`, indicating which +/// values should be gathered. +/// * `output = +/// ragged.from_nested_row_splits(output_dense_values, output_nested_splits)` +/// is the output tensor. +/// +/// (Note: This c++ op is used to implement the higher-level python +/// `tf.ragged.gather` op, which also supports ragged indices.) +/// +/// +/// - Parameters: +/// - params_nested_splits: The `nested_row_splits` tensors that define the row-partitioning for the +/// `params` RaggedTensor input. +/// - params_dense_values: The `flat_values` for the `params` RaggedTensor. There was a terminology change +/// at the python level from dense_values to flat_values, so dense_values is the +/// deprecated name. +/// - indices: Indices in the outermost dimension of `params` of the values that should be +/// gathered. +/// +/// - Attrs: +/// - PARAMS_RAGGED_RANK: The ragged rank of the `params` RaggedTensor. `params_nested_splits` should +/// contain this number of `row_splits` tensors. This value should equal +/// `params.ragged_rank`. +/// - OUTPUT_RAGGED_RANK: The ragged rank of the output RaggedTensor. `output_nested_splits` will contain +/// this number of `row_splits` tensors. This value should equal +/// `indices.shape.ndims + params.ragged_rank - 1`. +/// +/// - Outputs: +/// - output_nested_splits: The `nested_row_splits` tensors that define the row-partitioning for the +/// returned RaggedTensor. +/// - output_dense_values: The `flat_values` for the returned RaggedTensor. +@inlinable @inline(__always) +public static func raggedGather< + Tvalues: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar, + Tsplits: BinaryInteger & TensorFlowScalar +>( + paramsNestedSplits: [Tensor], + paramsDenseValues: Tensor, + indices: Tensor, + oUTPUTRAGGEDRANK: Int64 +) -> (outputNestedSplits: [Tensor], outputDenseValues: Tensor) { + let nOutputs = Int(oUTPUTRAGGEDRANK) + Int(1) + let op = makeOp("RaggedGather", nOutputs) + op.updateAttribute("Tvalues", Tvalues.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) + op.updateAttribute("PARAMS_RAGGED_RANK", paramsNestedSplits.count) + op.updateAttribute("OUTPUT_RAGGED_RANK", oUTPUTRAGGEDRANK) + op.addInputList(paramsNestedSplits) + op.addInput(paramsDenseValues) + op.addInput(indices) + return op.execute(Int(oUTPUTRAGGEDRANK), Int(1)) +} + +/// Returns a `RaggedTensor` containing the specified sequences of numbers. +/// +/// +/// Returns a `RaggedTensor` `result` composed from `rt_dense_values` and +/// `rt_nested_splits`, such that +/// `result[i] = range(starts[i], limits[i], deltas[i])`. +/// +/// ```python +/// >>> (rt_nested_splits, rt_dense_values) = gen_ragged_ops.ragged_range( +/// ... starts=[2, 5, 8], limits=[3, 5, 12], deltas=1) +/// >>> result = ragged.from_nested_row_splits(rt_dense_values, rt_nested_splits) +/// >>> print result.eval().tolist() +/// [[2], # result[0] = range(2, 3) +/// [], # result[1] = range(5, 5) +/// [8, 9, 10, 11]] # result[2] = range(8, 12) +/// ``` +/// +/// The input tensors `starts`, `limits`, and `deltas` may be scalars or vectors. +/// The vector inputs must all have the same size. Scalar inputs are broadcast +/// to match the size of the vector inputs. +/// +/// - Parameters: +/// - starts: The starts of each range. +/// - limits: The limits of each range. +/// - deltas: The deltas of each range. +/// +/// - Outputs: +/// - rt_nested_splits: The `row_splits` for the returned `RaggedTensor`. +/// - rt_dense_values: The `flat_values` for the returned `RaggedTensor`. +@inlinable @inline(__always) +public static func raggedRange< + T: Numeric & TensorFlowScalar, + Tsplits: BinaryInteger & TensorFlowScalar +>( + starts: Tensor, + limits: Tensor, + deltas: Tensor +) -> (rtNestedSplits: Tensor, rtDenseValues: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("RaggedRange", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) + op.addInput(starts) + op.addInput(limits) + op.addInput(deltas) + return op.execute(Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func raggedTensorFromVariant< + Tvalues: TensorFlowScalar, + Tsplits: BinaryInteger & TensorFlowScalar +>( + encodedRagged: VariantHandle, + inputRaggedRank: Int64, + outputRaggedRank: Int64 +) -> (outputNestedSplits: [Tensor], outputDenseValues: Tensor) { + let nOutputs = Int(outputRaggedRank) + Int(1) + let op = makeOp("RaggedTensorFromVariant", nOutputs) + op.updateAttribute("input_ragged_rank", inputRaggedRank) + op.updateAttribute("output_ragged_rank", outputRaggedRank) + op.updateAttribute("Tvalues", Tvalues.tensorFlowDataType) + op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) + op.addInput(encodedRagged) + return op.execute(Int(outputRaggedRank), Int(1)) +} + +/// Converts a `RaggedTensor` into a `SparseTensor` with the same values. +/// +/// input=ragged.from_nested_row_splits(rt_dense_values, rt_nested_splits) +/// output=SparseTensor(indices=sparse_indices, values=sparse_values, +/// dense_shape=sparse_dense_shape) +/// +/// - Parameters: +/// - rt_nested_splits: The `row_splits` for the `RaggedTensor`. +/// - rt_dense_values: The `flat_values` for the `RaggedTensor`. +/// +/// - Attr RAGGED_RANK: The ragged rank of the input RaggedTensor. `rt_nested_splits` should contain +/// this number of ragged-splits tensors. This value should equal +/// `input.ragged_rank`. +/// +/// - Outputs: +/// - sparse_indices: The indices for the `SparseTensor`. +/// - sparse_values: The values of the `SparseTensor`. +/// - sparse_dense_shape: `sparse_dense_shape` is a tight bounding box of the input `RaggedTensor`. +@inlinable @inline(__always) +public static func raggedTensorToSparse< + T: TensorFlowScalar, + Tsplits: BinaryInteger & TensorFlowScalar +>( + rtNestedSplits: [Tensor], + rtDenseValues: Tensor +) -> (sparseIndices: Tensor, sparseValues: Tensor, sparseDenseShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("RaggedTensorToSparse", nOutputs) + op.updateAttribute("RAGGED_RANK", rtNestedSplits.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) + op.addInputList(rtNestedSplits) + op.addInput(rtDenseValues) + return op.execute(Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func raggedTensorToVariant< + Tvalues: TensorFlowScalar, + Tsplits: BinaryInteger & TensorFlowScalar +>( + rtNestedSplits: [Tensor], + rtDenseValues: Tensor, + batchedInput: Bool +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("RaggedTensorToVariant", nOutputs) + op.updateAttribute("RAGGED_RANK", rtNestedSplits.count) + op.updateAttribute("Tvalues", Tvalues.tensorFlowDataType) + op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) + op.updateAttribute("batched_input", batchedInput) + op.addInputList(rtNestedSplits) + op.addInput(rtDenseValues) + return op.execute(Int(1)) +} + +/// Randomly crop `image`. +/// +/// `size` is a 1-D int64 tensor with 2 elements representing the crop height and +/// width. The values must be non negative. +/// +/// This Op picks a random location in `image` and crops a `height` by `width` +/// rectangle from that location. The random location is picked so the cropped +/// area will fit inside the original image. +/// +/// - Parameters: +/// - image: 3-D of shape `[height, width, channels]`. +/// - size: 1-D of length 2 containing: `crop_height`, `crop_width`.. +/// +/// - Attrs: +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. +/// +/// - Output output: 3-D of shape `[crop_height, crop_width, channels].` +@inlinable @inline(__always) +public static func randomCrop( + image: Tensor, + size: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RandomCrop", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(image) + op.addInput(size) + return op.execute(Int(1)) +} + +/// Outputs random values from the Gamma distribution(s) described by alpha. +/// +/// This op uses the algorithm by Marsaglia et al. to acquire samples via +/// transformation-rejection from pairs of uniform and normal random variables. +/// See http://dl.acm.org/citation.cfm?id=358414 +/// +/// - Parameters: +/// - shape: 1-D integer tensor. Shape of independent samples to draw from each +/// distribution described by the shape parameters given in alpha. +/// - alpha: A tensor in which each scalar is a "shape" parameter describing the +/// associated gamma distribution. +/// +/// - Attrs: +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. +/// +/// - Output output: A tensor with shape `shape + shape(alpha)`. Each slice +/// `[:, ..., :, i0, i1, ...iN]` contains the samples drawn for +/// `alpha[i0, i1, ...iN]`. The dtype of the output matches the dtype of alpha. +@inlinable @inline(__always) +public static func randomGamma< + S: BinaryInteger & TensorFlowScalar, + T: FloatingPoint & TensorFlowScalar +>( + shape: Tensor, + alpha: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RandomGamma", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("S", S.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(shape) + op.addInput(alpha) + return op.execute(Int(1)) +} + +/// Computes the derivative of a Gamma random sample w.r.t. `alpha`. +@inlinable @inline(__always) +public static func randomGammaGrad( + alpha: Tensor, + sample: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RandomGammaGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(alpha) + op.addInput(sample) + return op.execute(Int(1)) +} + +/// Use RandomPoissonV2 instead. +@inlinable @inline(__always) +public static func randomPoisson< + S: BinaryInteger & TensorFlowScalar, + Dtype: FloatingPoint & TensorFlowScalar +>( + shape: Tensor, + rate: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RandomPoisson", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("S", S.tensorFlowDataType) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(shape) + op.addInput(rate) + return op.execute(Int(1)) +} + +/// Outputs random values from the Poisson distribution(s) described by rate. +/// +/// This op uses two algorithms, depending on rate. If rate >= 10, then +/// the algorithm by Hormann is used to acquire samples via +/// transformation-rejection. +/// See http://www.sciencedirect.com/science/article/pii/0167668793909974. +/// +/// Otherwise, Knuth's algorithm is used to acquire samples via multiplying uniform +/// random variables. +/// See Donald E. Knuth (1969). Seminumerical Algorithms. The Art of Computer +/// Programming, Volume 2. Addison Wesley +/// +/// - Parameters: +/// - shape: 1-D integer tensor. Shape of independent samples to draw from each +/// distribution described by the shape parameters given in rate. +/// - rate: A tensor in which each scalar is a "rate" parameter describing the +/// associated poisson distribution. +/// +/// - Attrs: +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. +/// +/// - Output output: A tensor with shape `shape + shape(rate)`. Each slice +/// `[:, ..., :, i0, i1, ...iN]` contains the samples drawn for +/// `rate[i0, i1, ...iN]`. +@inlinable @inline(__always) +public static func randomPoissonV2< + S: BinaryInteger & TensorFlowScalar, + R: Numeric & TensorFlowScalar, + Dtype: Numeric & TensorFlowScalar +>( + shape: Tensor, + rate: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RandomPoissonV2", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("S", S.tensorFlowDataType) + op.updateAttribute("R", R.tensorFlowDataType) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(shape) + op.addInput(rate) + return op.execute(Int(1)) +} + +/// Randomly shuffles a tensor along its first dimension. +/// +/// The tensor is shuffled along dimension 0, such that each `value[j]` is mapped +/// to one and only one `output[i]`. For example, a mapping that might occur for a +/// 3x2 tensor is: +/// +/// ``` +/// [[1, 2], [[5, 6], +/// [3, 4], ==> [1, 2], +/// [5, 6]] [3, 4]] +/// ``` +/// +/// - Parameter value: The tensor to be shuffled. +/// +/// - Attrs: +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. +/// +/// - Output output: A tensor of same shape and type as `value`, shuffled along its first +/// dimension. +@inlinable @inline(__always) +public static func randomShuffle( + value: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RandomShuffle", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + return op.execute(Int(1)) +} + +/// A queue that randomizes the order of elements. +/// +/// - Attrs: +/// - component_types: The type of each component in a value. +/// - shapes: The shape of each component in a value. The length of this attr must +/// be either 0 or the same as the length of component_types. If the length of +/// this attr is 0, the shapes of queue elements are not constrained, and +/// only one element may be dequeued at a time. +/// - capacity: The upper bound on the number of elements in this queue. +/// Negative numbers mean no limit. +/// - min_after_dequeue: Dequeue will block unless there would be this +/// many elements after the dequeue or the queue is closed. This +/// ensures a minimum level of mixing of elements. +/// - seed: If either seed or seed2 is set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, a random seed is used. +/// - seed2: A second seed to avoid seed collision. +/// - container: If non-empty, this queue is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this queue will be shared under the given name +/// across multiple sessions. +/// +/// - Output handle: The handle to the queue. +@inlinable @inline(__always) +public static func randomShuffleQueueV2( + componentTypes: [TensorDataType], + shapes: [TensorShape?], + capacity: Int64 = -1, + minAfterDequeue: Int64 = 0, + seed: Int64 = 0, + seed2: Int64 = 0, + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("RandomShuffleQueueV2", nOutputs) + op.updateAttribute("component_types", componentTypes) + op.updateAttribute("shapes", shapes) + op.updateAttribute("capacity", capacity) + op.updateAttribute("min_after_dequeue", minAfterDequeue) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Outputs random values from a normal distribution. +/// +/// The generated values will have mean 0 and standard deviation 1. +/// +/// - Parameter shape: The shape of the output tensor. +/// +/// - Attrs: +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. +/// - dtype: The type of the output. +/// +/// - Output output: A tensor of the specified shape filled with random normal values. +@inlinable @inline(__always) +public static func randomStandardNormal< + Dtype: FloatingPoint & TensorFlowScalar, + T: BinaryInteger & TensorFlowScalar +>( + shape: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RandomStandardNormal", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(shape) + return op.execute(Int(1)) +} + +/// Outputs random values from a uniform distribution. +/// +/// The generated values follow a uniform distribution in the range `[0, 1)`. The +/// lower bound 0 is included in the range, while the upper bound 1 is excluded. +/// +/// - Parameter shape: The shape of the output tensor. +/// +/// - Attrs: +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. +/// - dtype: The type of the output. +/// +/// - Output output: A tensor of the specified shape filled with uniform random values. +@inlinable @inline(__always) +public static func randomUniform< + Dtype: FloatingPoint & TensorFlowScalar, + T: BinaryInteger & TensorFlowScalar +>( + shape: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RandomUniform", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(shape) + return op.execute(Int(1)) +} + +/// Outputs random integers from a uniform distribution. +/// +/// The generated values are uniform integers in the range `[minval, maxval)`. +/// The lower bound `minval` is included in the range, while the upper bound +/// `maxval` is excluded. +/// +/// The random integers are slightly biased unless `maxval - minval` is an exact +/// power of two. The bias is small for values of `maxval - minval` significantly +/// smaller than the range of the output (either `2^32` or `2^64`). +/// +/// - Parameters: +/// - shape: The shape of the output tensor. +/// - minval: 0-D. Inclusive lower bound on the generated integers. +/// - maxval: 0-D. Exclusive upper bound on the generated integers. +/// +/// - Attrs: +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. +/// +/// - Output output: A tensor of the specified shape filled with uniform random integers. +@inlinable @inline(__always) +public static func randomUniformInt< + Tout: BinaryInteger & TensorFlowScalar, + T: BinaryInteger & TensorFlowScalar +>( + shape: Tensor, + minval: Tensor, + maxval: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RandomUniformInt", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(shape) + op.addInput(minval) + op.addInput(maxval) + return op.execute(Int(1)) +} + +/// Creates a sequence of numbers. +/// +/// This operation creates a sequence of numbers that begins at `start` and +/// extends by increments of `delta` up to but not including `limit`. +/// +/// For example: +/// +/// ``` +/// # 'start' is 3 +/// # 'limit' is 18 +/// # 'delta' is 3 +/// tf.range(start, limit, delta) ==> [3, 6, 9, 12, 15] +/// ``` +/// +/// - Parameters: +/// - start: 0-D (scalar). First entry in the sequence. +/// - limit: 0-D (scalar). Upper limit of sequence, exclusive. +/// - delta: 0-D (scalar). Optional. Default is 1. Number that increments `start`. +/// +/// - Output output: 1-D. +@inlinable @inline(__always) +public static func range( + start: Tensor, + limit: Tensor, + delta: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Range", nOutputs) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(start) + op.addInput(limit) + op.addInput(delta) + return op.execute(Int(1)) +} + +/// Creates a dataset with a range of values. Corresponds to python's xrange. +/// +/// - Parameters: +/// - start: corresponds to start in python's xrange(). +/// - stop: corresponds to stop in python's xrange(). +/// - step: corresponds to step in python's xrange(). +@inlinable @inline(__always) +public static func rangeDataset( + start: Tensor, + stop: Tensor, + step: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("RangeDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(start) + op.addInput(stop) + op.addInput(step) + return op.execute(Int(1)) +} + +/// Returns the rank of a tensor. +/// +/// This operation returns an integer representing the rank of `input`. +/// +/// For example: +/// +/// ``` +/// # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] +/// # shape of tensor 't' is [2, 2, 3] +/// rank(t) ==> 3 +/// ``` +/// +/// **Note**: The rank of a tensor is not the same as the rank of a matrix. The rank +/// of a tensor is the number of indices required to uniquely select each element +/// of the tensor. Rank is also known as "order", "degree", or "ndims." +@inlinable @inline(__always) +public static func rank( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Rank", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Reads and outputs the entire contents of the input filename. +@inlinable @inline(__always) +public static func readFile( + filename: StringTensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("ReadFile", nOutputs) + op.addInput(filename) + return op.execute(Int(1)) +} + +/// Reads the value of a variable. +/// +/// The tensor returned by this operation is immutable. +/// +/// The value returned by this operation is guaranteed to be influenced by all the +/// writes on which this operation depends directly or indirectly, and to not be +/// influenced by any of the writes which depend directly or indirectly on this +/// operation. +/// +/// - Parameter resource: handle to the resource in which to store the variable. +/// +/// - Attr dtype: the dtype of the value. +@inlinable @inline(__always) +public static func readVariableOp( + resource: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ReadVariableOp", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(resource) + return op.execute(Int(1)) +} + +/// Returns the number of records this Reader has produced. +/// +/// This is the same as the number of ReaderRead executions that have +/// succeeded. +/// +/// - Parameter reader_handle: Handle to a Reader. +@inlinable @inline(__always) +public static func readerNumRecordsProducedV2( + readerHandle: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ReaderNumRecordsProducedV2", nOutputs) + op.addInput(readerHandle) + return op.execute(Int(1)) +} + +/// Returns the number of work units this Reader has finished processing. +/// +/// - Parameter reader_handle: Handle to a Reader. +@inlinable @inline(__always) +public static func readerNumWorkUnitsCompletedV2( + readerHandle: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ReaderNumWorkUnitsCompletedV2", nOutputs) + op.addInput(readerHandle) + return op.execute(Int(1)) +} + +/// Returns up to `num_records` (key, value) pairs produced by a Reader. +/// +/// Will dequeue from the input queue if necessary (e.g. when the +/// Reader needs to start reading from a new file since it has finished +/// with the previous file). +/// It may return less than `num_records` even before the last batch. +/// +/// - Parameters: +/// - reader_handle: Handle to a `Reader`. +/// - queue_handle: Handle to a `Queue`, with string work items. +/// - num_records: number of records to read from `Reader`. +/// +/// - Outputs: +/// - keys: A 1-D tensor. +/// - values: A 1-D tensor. +@inlinable @inline(__always) +public static func readerReadUpToV2( + readerHandle: ResourceHandle, + queueHandle: ResourceHandle, + numRecords: Tensor +) -> (keys: StringTensor, values: StringTensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("ReaderReadUpToV2", nOutputs) + op.addInput(readerHandle) + op.addInput(queueHandle) + op.addInput(numRecords) + return op.execute(Int(1), Int(1)) +} + +/// Returns the next record (key, value pair) produced by a Reader. +/// +/// Will dequeue from the input queue if necessary (e.g. when the +/// Reader needs to start reading from a new file since it has finished +/// with the previous file). +/// +/// - Parameters: +/// - reader_handle: Handle to a Reader. +/// - queue_handle: Handle to a Queue, with string work items. +/// +/// - Outputs: +/// - key: A scalar. +/// - value: A scalar. +@inlinable @inline(__always) +public static func readerReadV2( + readerHandle: ResourceHandle, + queueHandle: ResourceHandle +) -> (key: StringTensor, value: StringTensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("ReaderReadV2", nOutputs) + op.addInput(readerHandle) + op.addInput(queueHandle) + return op.execute(Int(1), Int(1)) +} + +/// Restore a Reader to its initial clean state. +/// +/// - Parameter reader_handle: Handle to a Reader. +@inlinable @inline(__always) +public static func readerResetV2( + readerHandle: ResourceHandle +) { + let nOutputs = 0 + let op = makeOp("ReaderResetV2", nOutputs) + op.addInput(readerHandle) + op.execute() +} + +/// Restore a reader to a previously saved state. +/// +/// Not all Readers support being restored, so this can produce an +/// Unimplemented error. +/// +/// - Parameters: +/// - reader_handle: Handle to a Reader. +/// - state: Result of a ReaderSerializeState of a Reader with type +/// matching reader_handle. +@inlinable @inline(__always) +public static func readerRestoreStateV2( + readerHandle: ResourceHandle, + state: StringTensor +) { + let nOutputs = 0 + let op = makeOp("ReaderRestoreStateV2", nOutputs) + op.addInput(readerHandle) + op.addInput(state) + op.execute() +} + +/// Produce a string tensor that encodes the state of a Reader. +/// +/// Not all Readers support being serialized, so this can produce an +/// Unimplemented error. +/// +/// - Parameter reader_handle: Handle to a Reader. +@inlinable @inline(__always) +public static func readerSerializeStateV2( + readerHandle: ResourceHandle +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("ReaderSerializeStateV2", nOutputs) + op.addInput(readerHandle) + return op.execute(Int(1)) +} + +/// Returns the real part of a complex number. +/// +/// Given a tensor `input` of complex numbers, this operation returns a tensor of +/// type `float` that is the real part of each element in `input`. All elements in +/// `input` must be complex numbers of the form \\(a + bj\\), where *a* is the real +/// part returned by this operation and *b* is the imaginary part. +/// +/// For example: +/// +/// ``` +/// # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] +/// tf.real(input) ==> [-2.25, 3.25] +/// ``` +@inlinable @inline(__always) +public static func real< + T: TensorFlowScalar, + Tout: FloatingPoint & TensorFlowScalar +>( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Real", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Returns x / y element-wise for real types. +/// +/// If `x` and `y` are reals, this will return the floating-point division. +/// +/// *NOTE*: `Div` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func realDiv( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RealDiv", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Computes the reciprocal of x element-wise. +/// +/// I.e., \\(y = 1 / x\\). +@inlinable @inline(__always) +public static func reciprocal( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Reciprocal", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the gradient for the inverse of `x` wrt its input. +/// +/// Specifically, `grad = -dy * y*y`, where `y = 1/x`, and `dy` +/// is the corresponding input gradient. +@inlinable @inline(__always) +public static func reciprocalGrad( + _ y: Tensor, + dy: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ReciprocalGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(dy) + return op.execute(Int(1)) +} + +/// Emits randomized records. +/// +/// - Attrs: +/// - file_pattern: Glob pattern for the data files. +/// - file_random_seed: Random seeds used to produce randomized records. +/// - file_shuffle_shift_ratio: Shifts the list of files after the list is randomly +/// shuffled. +/// - file_buffer_size: The randomization shuffling buffer. +/// - file_parallelism: How many sstables are opened and concurrently iterated over. +/// - batch_size: The batch size. +/// - compression_type: The type of compression for the file. Currently ZLIB and +/// GZIP are supported. Defaults to none. +/// +/// - Output records: A tensor of shape [batch_size]. +@inlinable @inline(__always) +public static func recordInput( + filePattern: String, + fileRandomSeed: Int64 = 301, + fileShuffleShiftRatio: Double = 0, + fileBufferSize: Int64 = 10000, + fileParallelism: Int64 = 16, + batchSize: Int64 = 32, + compressionType: String +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("RecordInput", nOutputs) + op.updateAttribute("file_pattern", filePattern) + op.updateAttribute("file_random_seed", fileRandomSeed) + op.updateAttribute("file_shuffle_shift_ratio", fileShuffleShiftRatio) + op.updateAttribute("file_buffer_size", fileBufferSize) + op.updateAttribute("file_parallelism", fileParallelism) + op.updateAttribute("batch_size", batchSize) + op.updateAttribute("compression_type", compressionType) + return op.execute(Int(1)) +} + +/// An op that receives embedding activations on the TPU. +/// +/// The TPU system performs the embedding lookups and aggregations specified by +/// the arguments to TPUEmbeddingEnqueue(Integer/Sparse/SparseTensor)Batch. The +/// results of these aggregations are visible to the Tensorflow Graph as the +/// outputs of a RecvTPUEmbeddingActivations op. This op returns a list containing +/// one Tensor of activations per table specified in the model. There can be at +/// most one RecvTPUEmbeddingActivations op in the TPU graph. +/// +/// - Attrs: +/// - num_outputs: The number of output activation tensors, equal to the number of +/// embedding tables in the model. +/// - config: Serialized TPUEmbeddingConfiguration proto. +/// +/// - Output outputs: A TensorList of embedding activations containing one Tensor per +/// embedding table in the model. +@inlinable @inline(__always) +public static func recvTPUEmbeddingActivations( + numOutputs: Int64, + config: String +) -> [Tensor] { + let nOutputs = Int(numOutputs) + let op = makeOp("RecvTPUEmbeddingActivations", nOutputs) + op.updateAttribute("num_outputs", numOutputs) + op.updateAttribute("config", config) + return op.execute(Int(numOutputs)) +} + +/// Reduces the input dataset to a singleton using a reduce function. +/// +/// - Parameters: +/// - input_dataset: A variant tensor representing the input dataset. +/// - initial_state: A nested structure of tensors, representing the initial state of the +/// transformation. +/// +/// - Attr f: A function that maps `(old_state, input_element)` to `new_state`. It must take +/// two arguments and return a nested structures of tensors. The structure of +/// `new_state` must match the structure of `initial_state`. +@inlinable @inline(__always) +public static func reduceDataset< + FIn: TensorGroup, + FOut: TensorGroup, + Tstate: TensorArrayProtocol, + Targuments: TensorArrayProtocol, + OutputTypes: TensorGroup +>( + inputDataset: VariantHandle, + initialState: Tstate, + otherArguments: Targuments, + f: (FIn) -> FOut, + outputShapes: [TensorShape?], + useInterOpParallelism: Bool = true +) -> OutputTypes { + let nOutputs = Int(OutputTypes._typeList.count) + let op = makeOp("ReduceDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Tstate", initialState._typeList) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("use_inter_op_parallelism", useInterOpParallelism) + op.addInput(inputDataset) + op.addInputList(initialState) + op.addInputList(otherArguments) + return op.execute(Int(OutputTypes._typeList.count)) +} + +/// Joins a string Tensor across the given dimensions. +/// +/// Computes the string join across dimensions in the given string Tensor of shape +/// `[\\(d_0, d_1, ..., d_{n-1}\\)]`. Returns a new Tensor created by joining the input +/// strings with the given separator (default: empty string). Negative indices are +/// counted backwards from the end, with `-1` being equivalent to `n - 1`. If +/// indices are not specified, joins across all dimensions beginning from `n - 1` +/// through `0`. +/// +/// For example: +/// +/// ```python +/// # tensor `a` is [["a", "b"], ["c", "d"]] +/// tf.reduce_join(a, 0) ==> ["ac", "bd"] +/// tf.reduce_join(a, 1) ==> ["ab", "cd"] +/// tf.reduce_join(a, -2) = tf.reduce_join(a, 0) ==> ["ac", "bd"] +/// tf.reduce_join(a, -1) = tf.reduce_join(a, 1) ==> ["ab", "cd"] +/// tf.reduce_join(a, 0, keep_dims=True) ==> [["ac", "bd"]] +/// tf.reduce_join(a, 1, keep_dims=True) ==> [["ab"], ["cd"]] +/// tf.reduce_join(a, 0, separator=".") ==> ["a.c", "b.d"] +/// tf.reduce_join(a, [0, 1]) ==> "acbd" +/// tf.reduce_join(a, [1, 0]) ==> "abcd" +/// tf.reduce_join(a, []) ==> [["a", "b"], ["c", "d"]] +/// tf.reduce_join(a) = tf.reduce_join(a, [1, 0]) ==> "abcd" +/// ``` +/// +/// - Parameters: +/// - inputs: The input to be joined. All reduced indices must have non-zero size. +/// - reduction_indices: The dimensions to reduce over. Dimensions are reduced in the +/// order specified. Omitting `reduction_indices` is equivalent to passing +/// `[n-1, n-2, ..., 0]`. Negative indices from `-n` to `-1` are supported. +/// +/// - Attrs: +/// - keep_dims: If `True`, retain reduced dimensions with length `1`. +/// - separator: The separator to use when joining. +/// +/// - Output output: Has shape equal to that of the input with reduced dimensions removed or +/// set to `1` depending on `keep_dims`. +@inlinable @inline(__always) +public static func reduceJoin( + inputs: StringTensor, + reductionIndices: Tensor, + keepDims: Bool = false, + separator: String +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("ReduceJoin", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("separator", separator) + op.addInput(inputs) + op.addInput(reductionIndices) + return op.execute(Int(1)) +} + +/// Check if the input matches the regex pattern. +/// +/// The input is a string tensor of any shape. The pattern is a scalar +/// string tensor which is applied to every element of the input tensor. +/// The boolean values (True or False) of the output tensor indicate +/// if the input matches the regex pattern provided. +/// +/// The pattern follows the re2 syntax (https://github.com/google/re2/wiki/Syntax) +/// +/// - Parameters: +/// - input: A string tensor of the text to be processed. +/// - pattern: A scalar string tensor containing the regular expression to match the input. +/// +/// - Output output: A bool tensor with the same shape as `input`. +@inlinable @inline(__always) +public static func regexFullMatch( + _ input: StringTensor, + pattern: StringTensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RegexFullMatch", nOutputs) + op.addInput(input) + op.addInput(pattern) + return op.execute(Int(1)) +} + +/// Replaces matches of the `pattern` regular expression in `input` with the +/// replacement string provided in `rewrite`. +/// +/// It follows the re2 syntax (https://github.com/google/re2/wiki/Syntax) +/// +/// - Parameters: +/// - input: The text to be processed. +/// - pattern: The regular expression to be matched in the `input` strings. +/// - rewrite: The rewrite string to be substituted for the `pattern` expression where it is +/// matched in the `input` strings. +/// +/// - Attr replace_global: If True, the replacement is global (that is, all matches of the `pattern` regular +/// expression in each input string are rewritten), otherwise the `rewrite` +/// substitution is only made for the first `pattern` match. +/// +/// - Output output: The text after applying pattern match and rewrite substitution. +@inlinable @inline(__always) +public static func regexReplace( + _ input: StringTensor, + pattern: StringTensor, + rewrite: StringTensor, + replaceGlobal: Bool = true +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("RegexReplace", nOutputs) + op.updateAttribute("replace_global", replaceGlobal) + op.addInput(input) + op.addInput(pattern) + op.addInput(rewrite) + return op.execute(Int(1)) +} + +/// Computes rectified linear: `max(features, 0)`. +@inlinable @inline(__always) +public static func relu( + features: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Relu", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) +} + +/// Computes rectified linear 6: `min(max(features, 0), 6)`. +@inlinable @inline(__always) +public static func relu6( + features: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Relu6", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) +} + +/// Computes rectified linear 6 gradients for a Relu6 operation. +/// +/// - Parameters: +/// - gradients: The backpropagated gradients to the corresponding Relu6 operation. +/// - features: The features passed as input to the corresponding Relu6 operation, or +/// its output; using either one produces the same result. +/// +/// - Output backprops: The gradients: +/// `gradients * (features > 0) * (features < 6)`. +@inlinable @inline(__always) +public static func relu6Grad( + gradients: Tensor, + features: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Relu6Grad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(features) + return op.execute(Int(1)) +} + +/// Computes rectified linear gradients for a Relu operation. +/// +/// - Parameters: +/// - gradients: The backpropagated gradients to the corresponding Relu operation. +/// - features: The features passed as input to the corresponding Relu operation, OR +/// the outputs of that operation (both work equivalently). +/// +/// - Output backprops: `gradients * (features > 0)`. +@inlinable @inline(__always) +public static func reluGrad( + gradients: Tensor, + features: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ReluGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(features) + return op.execute(Int(1)) +} + +/// Runs function `f` on a remote device indicated by `target`. +/// +/// - Parameters: +/// - target: A fully specified device name where we want to run the function. +/// - args: A list of arguments for the function. +/// +/// - Attrs: +/// - Tin: The type list for the arguments. +/// - Tout: The type list for the return values. +/// - f: The function to run remotely. +/// +/// - Output output: A list of return values. +@inlinable @inline(__always) +public static func remoteCall< + Tin: TensorArrayProtocol, + Tout: TensorGroup, + FIn: TensorGroup, + FOut: TensorGroup +>( + target: StringTensor, + args: Tin, + f: (FIn) -> FOut +) -> Tout { + let nOutputs = Int(Tout._typeList.count) + let op = makeOp("RemoteCall", nOutputs) + op.updateAttribute("Tin", args._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("f", f) + op.addInput(target) + op.addInputList(args) + return op.execute(Int(Tout._typeList.count)) +} + +/// Execute a sub graph on a remote processor. +/// +/// The graph specifications(such as graph itself, input tensors and output names) +/// are stored as a serialized protocol buffer of RemoteFusedGraphExecuteInfo +/// as serialized_remote_fused_graph_execute_info. +/// The specifications will be passed to a dedicated registered +/// remote fused graph executor. The executor will send the graph specifications +/// to a remote processor and execute that graph. The execution results +/// will be passed to consumer nodes as outputs of this node. +/// +/// - Parameter inputs: Arbitrary number of tensors with arbitrary data types +/// +/// - Attr serialized_remote_fused_graph_execute_info: Serialized protocol buffer +/// of RemoteFusedGraphExecuteInfo which contains graph specifications. +/// +/// - Output outputs: Arbitrary number of tensors with arbitrary data types +@inlinable @inline(__always) +public static func remoteFusedGraphExecute< + Tinputs: TensorArrayProtocol, + Toutputs: TensorGroup +>( + inputs: Tinputs, + serializedRemoteFusedGraphExecuteInfo: String +) -> Toutputs { + let nOutputs = Int(Toutputs._typeList.count) + let op = makeOp("RemoteFusedGraphExecute", nOutputs) + op.updateAttribute("Tinputs", inputs._typeList) + op.updateAttribute("Toutputs", Toutputs._typeList) + op.updateAttribute("serialized_remote_fused_graph_execute_info", serializedRemoteFusedGraphExecuteInfo) + op.addInputList(inputs) + return op.execute(Int(Toutputs._typeList.count)) +} + +/// Creates a dataset that emits the outputs of `input_dataset` `count` times. +/// +/// - Parameter count: A scalar representing the number of times that `input_dataset` should +/// be repeated. A value of `-1` indicates that it should be repeated infinitely. +@inlinable @inline(__always) +public static func repeatDataset( + inputDataset: VariantHandle, + count: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("RepeatDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(count) + return op.execute(Int(1)) +} + +/// Computes a range that covers the actual values present in a quantized tensor. +/// +/// Given a quantized tensor described by `(input, input_min, input_max)`, outputs a +/// range that covers the actual values present in that tensor. This op is typically +/// used to produce the `requested_output_min` and `requested_output_max` for +/// `Requantize`. +/// +/// - Parameters: +/// - input_min: The float value that the minimum quantized input value represents. +/// - input_max: The float value that the maximum quantized input value represents. +/// +/// - Attr Tinput: The type of the input. +/// +/// - Outputs: +/// - output_min: The computed min output. +/// - output_max: the computed max output. +@inlinable @inline(__always) +public static func requantizationRange( + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor +) -> (outputMin: Tensor, outputMax: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("RequantizationRange", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + return op.execute(Int(1), Int(1)) +} + +/// Computes requantization range per channel. +/// +/// - Parameters: +/// - input: The original input tensor. +/// - input_min: The minimum value of the input tensor +/// - input_max: The maximum value of the input tensor. +/// +/// - Attrs: +/// - T: The quantized type of input tensor that needs to be converted. +/// - clip_value_max: The maximum value of the output that needs to be clipped. +/// Example: set this to 6 for Relu6. +/// +/// - Outputs: +/// - output_min: The minimum value of the final output tensor +/// - output_max: The maximum value of the final output tensor. +@inlinable @inline(__always) +public static func requantizationRangePerChannel( + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor, + clipValueMax: Double +) -> (outputMin: Tensor, outputMax: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("RequantizationRangePerChannel", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("clip_value_max", clipValueMax) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + return op.execute(Int(1), Int(1)) +} + +/// Converts the quantized `input` tensor into a lower-precision `output`. +/// +/// Converts the quantized `input` tensor into a lower-precision `output`, using the +/// output range specified with `requested_output_min` and `requested_output_max`. +/// +/// `[input_min, input_max]` are scalar floats that specify the range for the float +/// interpretation of the `input` data. For example, if `input_min` is -1.0f and +/// `input_max` is 1.0f, and we are dealing with `quint16` quantized data, then a 0 +/// value in the 16-bit data should be interpreted as -1.0f, and a 65535 means 1.0f. +/// +/// - Parameters: +/// - input_min: The float value that the minimum quantized input value represents. +/// - input_max: The float value that the maximum quantized input value represents. +/// - requested_output_min: The float value that the minimum quantized output value represents. +/// - requested_output_max: The float value that the maximum quantized output value represents. +/// +/// - Attrs: +/// - Tinput: The type of the input. +/// - out_type: The type of the output. Should be a lower bit depth than Tinput. +/// +/// - Outputs: +/// - output_min: The requested_output_min value is copied into this output. +/// - output_max: The requested_output_max value is copied into this output. +@inlinable @inline(__always) +public static func requantize< + Tinput: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor, + requestedOutputMin: Tensor, + requestedOutputMax: Tensor +) -> (output: Tensor, outputMin: Tensor, outputMax: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("Requantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + op.addInput(requestedOutputMin) + op.addInput(requestedOutputMax) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Requantizes input with min and max values known per channel. +/// +/// - Parameters: +/// - input: The original input tensor. +/// - input_min: The minimum value of the input tensor +/// - input_max: The maximum value of the input tensor. +/// - requested_output_min: The minimum value of the output tensor requested. +/// - requested_output_max: The maximum value of the output tensor requested. +/// +/// - Attrs: +/// - T: The quantized type of input tensor that needs to be converted. +/// - out_type: The quantized type of output tensor that needs to be converted. +/// +/// - Outputs: +/// - output: Output tensor. +/// - output_min: The minimum value of the final output tensor +/// - output_max: The maximum value of the final output tensor. +@inlinable @inline(__always) +public static func requantizePerChannel< + T: TensorFlowScalar, + OutType: TensorFlowScalar +>( + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor, + requestedOutputMin: Tensor, + requestedOutputMax: Tensor +) -> (output: Tensor, outputMin: Tensor, outputMax: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("RequantizePerChannel", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + op.addInput(requestedOutputMin) + op.addInput(requestedOutputMax) + return op.execute(Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func requiresOlderGraphVersion( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RequiresOlderGraphVersion", nOutputs) + + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func reservedAttr( + range: Int64 +) { + let nOutputs = 0 + let op = makeOp("ReservedAttr", nOutputs) + op.updateAttribute("range", range) + op.execute() +} + +@inlinable @inline(__always) +public static func reservedInput( + _ input: Tensor +) { + let nOutputs = 0 + let op = makeOp("ReservedInput", nOutputs) + op.addInput(input) + op.execute() +} + +/// Reshapes a tensor. +/// +/// Given `tensor`, this operation returns a tensor that has the same values +/// as `tensor` with shape `shape`. +/// +/// If one component of `shape` is the special value -1, the size of that dimension +/// is computed so that the total size remains constant. In particular, a `shape` +/// of `[-1]` flattens into 1-D. At most one component of `shape` can be -1. +/// +/// If `shape` is 1-D or higher, then the operation returns a tensor with shape +/// `shape` filled with the values of `tensor`. In this case, the number of elements +/// implied by `shape` must be the same as the number of elements in `tensor`. +/// +/// For example: +/// +/// ``` +/// # tensor 't' is [1, 2, 3, 4, 5, 6, 7, 8, 9] +/// # tensor 't' has shape [9] +/// reshape(t, [3, 3]) ==> [[1, 2, 3], +/// [4, 5, 6], +/// [7, 8, 9]] +/// +/// # tensor 't' is [[[1, 1], [2, 2]], +/// # [[3, 3], [4, 4]]] +/// # tensor 't' has shape [2, 2, 2] +/// reshape(t, [2, 4]) ==> [[1, 1, 2, 2], +/// [3, 3, 4, 4]] +/// +/// # tensor 't' is [[[1, 1, 1], +/// # [2, 2, 2]], +/// # [[3, 3, 3], +/// # [4, 4, 4]], +/// # [[5, 5, 5], +/// # [6, 6, 6]]] +/// # tensor 't' has shape [3, 2, 3] +/// # pass '[-1]' to flatten 't' +/// reshape(t, [-1]) ==> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6] +/// +/// # -1 can also be used to infer the shape +/// +/// # -1 is inferred to be 9: +/// reshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3], +/// [4, 4, 4, 5, 5, 5, 6, 6, 6]] +/// # -1 is inferred to be 2: +/// reshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3], +/// [4, 4, 4, 5, 5, 5, 6, 6, 6]] +/// # -1 is inferred to be 3: +/// reshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1], +/// [2, 2, 2], +/// [3, 3, 3]], +/// [[4, 4, 4], +/// [5, 5, 5], +/// [6, 6, 6]]] +/// +/// # tensor 't' is [7] +/// # shape `[]` reshapes to a scalar +/// reshape(t, []) ==> 7 +/// ``` +/// +/// - Parameter shape: Defines the shape of the output tensor. +@inlinable @inline(__always) +public static func reshape< + T: TensorFlowScalar, + Tshape: BinaryInteger & TensorFlowScalar +>( + _ tensor: Tensor, + shape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Reshape", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tshape", Tshape.tensorFlowDataType) + op.addInput(tensor) + op.addInput(shape) + return op.execute(Int(1)) +} + +/// Resize `images` to `size` using area interpolation. +/// +/// Input images can be of different types but output images are always float. +/// +/// The range of pixel values for the output image might be slightly different +/// from the range for the input image because of limited numerical precision. +/// To guarantee an output range, for example `[0.0, 1.0]`, apply +/// `tf.clip_by_value` to the output. +/// +/// Each output pixel is computed by first transforming the pixel's footprint into +/// the input tensor and then averaging the pixels that intersect the footprint. An +/// input pixel's contribution to the average is weighted by the fraction of its +/// area that intersects the footprint. This is the same as OpenCV's INTER_AREA. +/// +/// - Parameters: +/// - images: 4-D with shape `[batch, height, width, channels]`. +/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The +/// new size for the images. +/// +/// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and output tensors are +/// aligned, preserving the values at the corner pixels. Defaults to false. +/// +/// - Output resized_images: 4-D with shape +/// `[batch, new_height, new_width, channels]`. +@inlinable @inline(__always) +public static func resizeArea( + images: Tensor, + size: Tensor, + alignCorners: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ResizeArea", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.addInput(images) + op.addInput(size) + return op.execute(Int(1)) +} + +/// Resize `images` to `size` using bicubic interpolation. +/// +/// Input images can be of different types but output images are always float. +/// +/// - Parameters: +/// - images: 4-D with shape `[batch, height, width, channels]`. +/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The +/// new size for the images. +/// +/// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and output tensors are +/// aligned, preserving the values at the corner pixels. Defaults to false. +/// +/// - Output resized_images: 4-D with shape +/// `[batch, new_height, new_width, channels]`. +@inlinable @inline(__always) +public static func resizeBicubic( + images: Tensor, + size: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ResizeBicubic", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(images) + op.addInput(size) + return op.execute(Int(1)) +} + +/// Computes the gradient of bicubic interpolation. +/// +/// - Parameters: +/// - grads: 4-D with shape `[batch, height, width, channels]`. +/// - original_image: 4-D with shape `[batch, orig_height, orig_width, channels]`, +/// The image tensor that was resized. +/// +/// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and grad tensors are +/// aligned. Defaults to false. +/// +/// - Output output: 4-D with shape `[batch, orig_height, orig_width, channels]`. +/// Gradients with respect to the input image. Input image must have been +/// float or double. +@inlinable @inline(__always) +public static func resizeBicubicGrad( + grads: Tensor, + originalImage: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ResizeBicubicGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(grads) + op.addInput(originalImage) + return op.execute(Int(1)) +} + +/// Resize `images` to `size` using bilinear interpolation. +/// +/// Input images can be of different types but output images are always float. +/// +/// - Parameters: +/// - images: 4-D with shape `[batch, height, width, channels]`. +/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The +/// new size for the images. +/// +/// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and output tensors are +/// aligned, preserving the values at the corner pixels. Defaults to false. +/// +/// - Output resized_images: 4-D with shape +/// `[batch, new_height, new_width, channels]`. +@inlinable @inline(__always) +public static func resizeBilinear( + images: Tensor, + size: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ResizeBilinear", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(images) + op.addInput(size) + return op.execute(Int(1)) +} + +/// Computes the gradient of bilinear interpolation. +/// +/// - Parameters: +/// - grads: 4-D with shape `[batch, height, width, channels]`. +/// - original_image: 4-D with shape `[batch, orig_height, orig_width, channels]`, +/// The image tensor that was resized. +/// +/// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and grad tensors are +/// aligned. Defaults to false. +/// +/// - Output output: 4-D with shape `[batch, orig_height, orig_width, channels]`. +/// Gradients with respect to the input image. Input image must have been +/// float or double. +@inlinable @inline(__always) +public static func resizeBilinearGrad( + grads: Tensor, + originalImage: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ResizeBilinearGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(grads) + op.addInput(originalImage) + return op.execute(Int(1)) +} + +/// Resize `images` to `size` using nearest neighbor interpolation. +/// +/// - Parameters: +/// - images: 4-D with shape `[batch, height, width, channels]`. +/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The +/// new size for the images. +/// +/// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and output tensors are +/// aligned, preserving the values at the corner pixels. Defaults to false. +/// +/// - Output resized_images: 4-D with shape +/// `[batch, new_height, new_width, channels]`. +@inlinable @inline(__always) +public static func resizeNearestNeighbor( + images: Tensor, + size: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ResizeNearestNeighbor", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(images) + op.addInput(size) + return op.execute(Int(1)) +} + +/// Computes the gradient of nearest neighbor interpolation. +/// +/// - Parameters: +/// - grads: 4-D with shape `[batch, height, width, channels]`. +/// - size: = A 1-D int32 Tensor of 2 elements: `orig_height, orig_width`. The +/// original input size. +/// +/// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and grad tensors are +/// aligned. Defaults to false. +/// +/// - Output output: 4-D with shape `[batch, orig_height, orig_width, channels]`. Gradients +/// with respect to the input image. +@inlinable @inline(__always) +public static func resizeNearestNeighborGrad( + grads: Tensor, + size: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ResizeNearestNeighborGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(grads) + op.addInput(size) + return op.execute(Int(1)) +} + +/// Update '*var' according to the AdaMax algorithm. +/// +/// m_t <- beta1 * m_{t-1} + (1 - beta1) * g +/// v_t <- max(beta2 * v_{t-1}, abs(g)) +/// variable <- variable - learning_rate / (1 - beta1^t) * m_t / (v_t + epsilon) +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - m: Should be from a Variable(). +/// - v: Should be from a Variable(). +/// - beta1_power: Must be a scalar. +/// - lr: Scaling factor. Must be a scalar. +/// - beta1: Momentum factor. Must be a scalar. +/// - beta2: Momentum factor. Must be a scalar. +/// - epsilon: Ridge term. Must be a scalar. +/// - grad: The gradient. +/// +/// - Attr use_locking: If `True`, updating of the var, m, and v tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceApplyAdaMax( + var_: ResourceHandle, + m: ResourceHandle, + v: ResourceHandle, + beta1Power: Tensor, + lr: Tensor, + beta1: Tensor, + beta2: Tensor, + epsilon: Tensor, + grad: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyAdaMax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(m) + op.addInput(v) + op.addInput(beta1Power) + op.addInput(lr) + op.addInput(beta1) + op.addInput(beta2) + op.addInput(epsilon) + op.addInput(grad) + op.execute() +} + +/// Update '*var' according to the adadelta scheme. +/// +/// accum = rho() * accum + (1 - rho()) * grad.square(); +/// update = (update_accum + epsilon).sqrt() * (accum + epsilon()).rsqrt() * grad; +/// update_accum = rho() * update_accum + (1 - rho()) * update.square(); +/// var -= update; +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - accum_update: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - rho: Decay factor. Must be a scalar. +/// - epsilon: Constant factor. Must be a scalar. +/// - grad: The gradient. +/// +/// - Attr use_locking: If True, updating of the var, accum and update_accum tensors will be protected by +/// a lock; otherwise the behavior is undefined, but may exhibit less contention. +@inlinable @inline(__always) +public static func resourceApplyAdadelta( + var_: ResourceHandle, + accum: ResourceHandle, + accumUpdate: ResourceHandle, + lr: Tensor, + rho: Tensor, + epsilon: Tensor, + grad: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyAdadelta", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(accumUpdate) + op.addInput(lr) + op.addInput(rho) + op.addInput(epsilon) + op.addInput(grad) + op.execute() +} + +/// Update '*var' according to the adagrad scheme. +/// +/// accum += grad * grad +/// var -= lr * grad * (1 / sqrt(accum)) +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - grad: The gradient. +/// +/// - Attr use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceApplyAdagrad( + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + grad: Tensor, + useLocking: Bool = false, + updateSlots: Bool = true +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyAdagrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("update_slots", updateSlots) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(grad) + op.execute() +} + +/// Update '*var' according to the proximal adagrad scheme. +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - gradient_accumulator: Should be from a Variable(). +/// - gradient_squared_accumulator: Should be from a Variable(). +/// - grad: The gradient. +/// - lr: Scaling factor. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - global_step: Training step number. Must be a scalar. +/// +/// - Attr use_locking: If True, updating of the var and accum tensors will be protected by +/// a lock; otherwise the behavior is undefined, but may exhibit less contention. +@inlinable @inline(__always) +public static func resourceApplyAdagradDA( + var_: ResourceHandle, + gradientAccumulator: ResourceHandle, + gradientSquaredAccumulator: ResourceHandle, + grad: Tensor, + lr: Tensor, + l1: Tensor, + l2: Tensor, + globalStep: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyAdagradDA", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(gradientAccumulator) + op.addInput(gradientSquaredAccumulator) + op.addInput(grad) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(globalStep) + op.execute() +} + +/// Update '*var' according to the Adam algorithm. +/// +/// $$lr_t := \text{learning\_rate} * \sqrt{1 - beta_2^t} / (1 - beta_1^t)$$ +/// $$m_t := beta_1 * m_{t-1} + (1 - beta_1) * g$$ +/// $$v_t := beta_2 * v_{t-1} + (1 - beta_2) * g * g$$ +/// $$variable := variable - lr_t * m_t / (\sqrt{v_t} + \epsilon)$$ +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - m: Should be from a Variable(). +/// - v: Should be from a Variable(). +/// - beta1_power: Must be a scalar. +/// - beta2_power: Must be a scalar. +/// - lr: Scaling factor. Must be a scalar. +/// - beta1: Momentum factor. Must be a scalar. +/// - beta2: Momentum factor. Must be a scalar. +/// - epsilon: Ridge term. Must be a scalar. +/// - grad: The gradient. +/// +/// - Attrs: +/// - use_locking: If `True`, updating of the var, m, and v tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +/// - use_nesterov: If `True`, uses the nesterov update. +@inlinable @inline(__always) +public static func resourceApplyAdam( + var_: ResourceHandle, + m: ResourceHandle, + v: ResourceHandle, + beta1Power: Tensor, + beta2Power: Tensor, + lr: Tensor, + beta1: Tensor, + beta2: Tensor, + epsilon: Tensor, + grad: Tensor, + useLocking: Bool = false, + useNesterov: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyAdam", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("use_nesterov", useNesterov) + op.addInput(var_) + op.addInput(m) + op.addInput(v) + op.addInput(beta1Power) + op.addInput(beta2Power) + op.addInput(lr) + op.addInput(beta1) + op.addInput(beta2) + op.addInput(epsilon) + op.addInput(grad) + op.execute() +} + +/// Update '*var' according to the Adam algorithm. +/// +/// $$lr_t := \text{learning\_rate} * \sqrt{1 - beta_2^t} / (1 - beta_1^t)$$ +/// $$m_t := beta_1 * m_{t-1} + (1 - beta_1) * g$$ +/// $$v_t := beta_2 * v_{t-1} + (1 - beta_2) * g * g$$ +/// $$vhat_t := max{vhat_{t-1}, v_t}$$ +/// $$variable := variable - lr_t * m_t / (\sqrt{vhat_t} + \epsilon)$$ +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - m: Should be from a Variable(). +/// - v: Should be from a Variable(). +/// - vhat: Should be from a Variable(). +/// - beta1_power: Must be a scalar. +/// - beta2_power: Must be a scalar. +/// - lr: Scaling factor. Must be a scalar. +/// - beta1: Momentum factor. Must be a scalar. +/// - beta2: Momentum factor. Must be a scalar. +/// - epsilon: Ridge term. Must be a scalar. +/// - grad: The gradient. +/// +/// - Attr use_locking: If `True`, updating of the var, m, and v tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceApplyAdamWithAmsgrad( + var_: ResourceHandle, + m: ResourceHandle, + v: ResourceHandle, + vhat: ResourceHandle, + beta1Power: Tensor, + beta2Power: Tensor, + lr: Tensor, + beta1: Tensor, + beta2: Tensor, + epsilon: Tensor, + grad: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyAdamWithAmsgrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(m) + op.addInput(v) + op.addInput(vhat) + op.addInput(beta1Power) + op.addInput(beta2Power) + op.addInput(lr) + op.addInput(beta1) + op.addInput(beta2) + op.addInput(epsilon) + op.addInput(grad) + op.execute() +} + +/// Update '*var' according to the AddSign update. +/// +/// m_t <- beta1 * m_{t-1} + (1 - beta1) * g +/// update <- (alpha + sign_decay * sign(g) *sign(m)) * g +/// variable <- variable - lr_t * update +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - m: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - alpha: Must be a scalar. +/// - sign_decay: Must be a scalar. +/// - beta: Must be a scalar. +/// - grad: The gradient. +/// +/// - Attr use_locking: If `True`, updating of the var and m tensors is +/// protected by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceApplyAddSign( + var_: ResourceHandle, + m: ResourceHandle, + lr: Tensor, + alpha: Tensor, + signDecay: Tensor, + beta: Tensor, + grad: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyAddSign", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(m) + op.addInput(lr) + op.addInput(alpha) + op.addInput(signDecay) + op.addInput(beta) + op.addInput(grad) + op.execute() +} + +/// Update '*var' according to the centered RMSProp algorithm. +/// +/// The centered RMSProp algorithm uses an estimate of the centered second moment +/// (i.e., the variance) for normalization, as opposed to regular RMSProp, which +/// uses the (uncentered) second moment. This often helps with training, but is +/// slightly more expensive in terms of computation and memory. +/// +/// Note that in dense implementation of this algorithm, mg, ms, and mom will +/// update even if the grad is zero, but in this sparse implementation, mg, ms, +/// and mom will not update in iterations during which the grad is zero. +/// +/// mean_square = decay * mean_square + (1-decay) * gradient ** 2 +/// mean_grad = decay * mean_grad + (1-decay) * gradient +/// +/// Delta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2) +/// +/// mg <- rho * mg_{t-1} + (1-rho) * grad +/// ms <- rho * ms_{t-1} + (1-rho) * grad * grad +/// mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms - mg * mg + epsilon) +/// var <- var - mom +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - mg: Should be from a Variable(). +/// - ms: Should be from a Variable(). +/// - mom: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - rho: Decay rate. Must be a scalar. +/// - epsilon: Ridge term. Must be a scalar. +/// - grad: The gradient. +/// +/// - Attr use_locking: If `True`, updating of the var, mg, ms, and mom tensors is +/// protected by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceApplyCenteredRMSProp( + var_: ResourceHandle, + mg: ResourceHandle, + ms: ResourceHandle, + mom: ResourceHandle, + lr: Tensor, + rho: Tensor, + momentum: Tensor, + epsilon: Tensor, + grad: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyCenteredRMSProp", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(mg) + op.addInput(ms) + op.addInput(mom) + op.addInput(lr) + op.addInput(rho) + op.addInput(momentum) + op.addInput(epsilon) + op.addInput(grad) + op.execute() +} + +/// Update '*var' according to the Ftrl-proximal scheme. +/// +/// accum_new = accum + grad * grad +/// linear += grad - (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var +/// quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2 +/// var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0 +/// accum = accum_new +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - linear: Should be from a Variable(). +/// - grad: The gradient. +/// - lr: Scaling factor. Must be a scalar. +/// - l1: L1 regulariation. Must be a scalar. +/// - l2: L2 regulariation. Must be a scalar. +/// - lr_power: Scaling factor. Must be a scalar. +/// +/// - Attr use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceApplyFtrl( + var_: ResourceHandle, + accum: ResourceHandle, + linear: ResourceHandle, + grad: Tensor, + lr: Tensor, + l1: Tensor, + l2: Tensor, + lrPower: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyFtrl", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(linear) + op.addInput(grad) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(lrPower) + op.execute() +} + +/// Update '*var' according to the Ftrl-proximal scheme. +/// +/// grad_with_shrinkage = grad + 2 * l2_shrinkage * var +/// accum_new = accum + grad_with_shrinkage * grad_with_shrinkage +/// linear += grad_with_shrinkage + +/// (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var +/// quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2 +/// var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0 +/// accum = accum_new +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - linear: Should be from a Variable(). +/// - grad: The gradient. +/// - lr: Scaling factor. Must be a scalar. +/// - l1: L1 regulariation. Must be a scalar. +/// - l2: L2 shrinkage regulariation. Must be a scalar. +/// - lr_power: Scaling factor. Must be a scalar. +/// +/// - Attr use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceApplyFtrlV2( + var_: ResourceHandle, + accum: ResourceHandle, + linear: ResourceHandle, + grad: Tensor, + lr: Tensor, + l1: Tensor, + l2: Tensor, + l2Shrinkage: Tensor, + lrPower: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyFtrlV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(linear) + op.addInput(grad) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(l2Shrinkage) + op.addInput(lrPower) + op.execute() +} + +/// Update '*var' by subtracting 'alpha' * 'delta' from it. +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - alpha: Scaling factor. Must be a scalar. +/// - delta: The change. +/// +/// - Attr use_locking: If `True`, the subtraction will be protected by a lock; +/// otherwise the behavior is undefined, but may exhibit less contention. +@inlinable @inline(__always) +public static func resourceApplyGradientDescent( + var_: ResourceHandle, + alpha: Tensor, + delta: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyGradientDescent", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(alpha) + op.addInput(delta) + op.execute() +} + +/// Update '*var' according to the momentum scheme. Set use_nesterov = True if you +/// +/// want to use Nesterov momentum. +/// +/// accum = accum * momentum - lr * grad +/// var += accum +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - grad: The gradient. +/// - momentum: Momentum. Must be a scalar. +/// +/// - Attrs: +/// - use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +/// - use_nesterov: If `True`, the tensor passed to compute grad will be +/// var + momentum * accum, so in the end, the var you get is actually +/// var + momentum * accum. +@inlinable @inline(__always) +public static func resourceApplyKerasMomentum( + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + grad: Tensor, + momentum: Tensor, + useLocking: Bool = false, + useNesterov: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyKerasMomentum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("use_nesterov", useNesterov) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(grad) + op.addInput(momentum) + op.execute() +} + +/// Update '*var' according to the momentum scheme. Set use_nesterov = True if you +/// +/// want to use Nesterov momentum. +/// +/// accum = accum * momentum + grad +/// var -= lr * accum +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - grad: The gradient. +/// - momentum: Momentum. Must be a scalar. +/// +/// - Attrs: +/// - use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +/// - use_nesterov: If `True`, the tensor passed to compute grad will be +/// var - lr * momentum * accum, so in the end, the var you get is actually +/// var - lr * momentum * accum. +@inlinable @inline(__always) +public static func resourceApplyMomentum( + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + grad: Tensor, + momentum: Tensor, + useLocking: Bool = false, + useNesterov: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyMomentum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("use_nesterov", useNesterov) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(grad) + op.addInput(momentum) + op.execute() +} + +/// Update '*var' according to the AddSign update. +/// +/// m_t <- beta1 * m_{t-1} + (1 - beta1) * g +/// update <- exp(logbase * sign_decay * sign(g) * sign(m_t)) * g +/// variable <- variable - lr_t * update +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - m: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - logbase: Must be a scalar. +/// - sign_decay: Must be a scalar. +/// - beta: Must be a scalar. +/// - grad: The gradient. +/// +/// - Attr use_locking: If `True`, updating of the var and m tensors is +/// protected by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceApplyPowerSign( + var_: ResourceHandle, + m: ResourceHandle, + lr: Tensor, + logbase: Tensor, + signDecay: Tensor, + beta: Tensor, + grad: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyPowerSign", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(m) + op.addInput(lr) + op.addInput(logbase) + op.addInput(signDecay) + op.addInput(beta) + op.addInput(grad) + op.execute() +} + +/// Update '*var' and '*accum' according to FOBOS with Adagrad learning rate. +/// +/// accum += grad * grad +/// prox_v = var - lr * grad * (1 / sqrt(accum)) +/// var = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0} +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - grad: The gradient. +/// +/// - Attr use_locking: If True, updating of the var and accum tensors will be protected by +/// a lock; otherwise the behavior is undefined, but may exhibit less contention. +@inlinable @inline(__always) +public static func resourceApplyProximalAdagrad( + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + l1: Tensor, + l2: Tensor, + grad: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyProximalAdagrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(grad) + op.execute() +} + +/// Update '*var' as FOBOS algorithm with fixed learning rate. +/// +/// prox_v = var - alpha * delta +/// var = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0} +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - alpha: Scaling factor. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - delta: The change. +/// +/// - Attr use_locking: If True, the subtraction will be protected by a lock; +/// otherwise the behavior is undefined, but may exhibit less contention. +@inlinable @inline(__always) +public static func resourceApplyProximalGradientDescent( + var_: ResourceHandle, + alpha: Tensor, + l1: Tensor, + l2: Tensor, + delta: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyProximalGradientDescent", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(alpha) + op.addInput(l1) + op.addInput(l2) + op.addInput(delta) + op.execute() +} + +/// Update '*var' according to the RMSProp algorithm. +/// +/// Note that in dense implementation of this algorithm, ms and mom will +/// update even if the grad is zero, but in this sparse implementation, ms +/// and mom will not update in iterations during which the grad is zero. +/// +/// mean_square = decay * mean_square + (1-decay) * gradient ** 2 +/// Delta = learning_rate * gradient / sqrt(mean_square + epsilon) +/// +/// ms <- rho * ms_{t-1} + (1-rho) * grad * grad +/// mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon) +/// var <- var - mom +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - ms: Should be from a Variable(). +/// - mom: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - rho: Decay rate. Must be a scalar. +/// - epsilon: Ridge term. Must be a scalar. +/// - grad: The gradient. +/// +/// - Attr use_locking: If `True`, updating of the var, ms, and mom tensors is protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceApplyRMSProp( + var_: ResourceHandle, + ms: ResourceHandle, + mom: ResourceHandle, + lr: Tensor, + rho: Tensor, + momentum: Tensor, + epsilon: Tensor, + grad: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceApplyRMSProp", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(ms) + op.addInput(mom) + op.addInput(lr) + op.addInput(rho) + op.addInput(momentum) + op.addInput(epsilon) + op.addInput(grad) + op.execute() +} + +/// Increments variable pointed to by 'resource' until it reaches 'limit'. +/// +/// - Parameter resource: Should be from a scalar `Variable` node. +/// +/// - Attr limit: If incrementing ref would bring it above limit, instead generates an +/// 'OutOfRange' error. +/// +/// - Output output: A copy of the input before increment. If nothing else modifies the +/// input, the values produced will all be distinct. +@inlinable @inline(__always) +public static func resourceCountUpTo( + resource: ResourceHandle, + limit: Int64 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ResourceCountUpTo", nOutputs) + op.updateAttribute("limit", limit) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(resource) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func resourceCreateOp( + resource: ResourceHandle +) { + let nOutputs = 0 + let op = makeOp("ResourceCreateOp", nOutputs) + op.addInput(resource) + op.execute() +} + +/// Gather slices from the variable pointed to by `resource` according to `indices`. +/// +/// `indices` must be an integer tensor of any dimension (usually 0-D or 1-D). +/// Produces an output tensor with shape `indices.shape + params.shape[1:]` where: +/// +/// ```python +/// # Scalar indices +/// output[:, ..., :] = params[indices, :, ... :] +/// +/// # Vector indices +/// output[i, :, ..., :] = params[indices[i], :, ... :] +/// +/// # Higher rank indices +/// output[i, ..., j, :, ... :] = params[indices[i, ..., j], :, ..., :] +/// ``` +@inlinable @inline(__always) +public static func resourceGather< + Dtype: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + resource: ResourceHandle, + indices: Tensor, + batchDims: Int64 = 0, + validateIndices: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ResourceGather", nOutputs) + op.updateAttribute("batch_dims", batchDims) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func resourceGatherNd< + Dtype: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + resource: ResourceHandle, + indices: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ResourceGatherNd", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func resourceInitializedOp( + resource: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ResourceInitializedOp", nOutputs) + op.addInput(resource) + return op.execute(Int(1)) +} + +/// Adds sparse updates to the variable referenced by `resource`. +/// +/// This operation computes +/// +/// # Scalar indices +/// ref[indices, ...] += updates[...] +/// +/// # Vector indices (for each i) +/// ref[indices[i], ...] += updates[i, ...] +/// +/// # High rank indices (for each i, ..., j) +/// ref[indices[i, ..., j], ...] += updates[i, ..., j, ...] +/// +/// Duplicate entries are handled correctly: if multiple `indices` reference +/// the same location, their contributions add. +/// +/// Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. +/// +///
+/// +///
+/// +/// - Parameters: +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. +@inlinable @inline(__always) +public static func resourceScatterAdd< + Dtype: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + resource: ResourceHandle, + indices: Tensor, + updates: Tensor +) { + let nOutputs = 0 + let op = makeOp("ResourceScatterAdd", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() +} + +/// Divides sparse updates into the variable referenced by `resource`. +/// +/// This operation computes +/// +/// # Scalar indices +/// ref[indices, ...] /= updates[...] +/// +/// # Vector indices (for each i) +/// ref[indices[i], ...] /= updates[i, ...] +/// +/// # High rank indices (for each i, ..., j) +/// ref[indices[i, ..., j], ...] /= updates[i, ..., j, ...] +/// +/// Duplicate entries are handled correctly: if multiple `indices` reference +/// the same location, their contributions multiply. +/// +/// Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. +/// +///
+/// +///
+/// +/// - Parameters: +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. +@inlinable @inline(__always) +public static func resourceScatterDiv< + Dtype: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + resource: ResourceHandle, + indices: Tensor, + updates: Tensor +) { + let nOutputs = 0 + let op = makeOp("ResourceScatterDiv", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() +} + +/// Reduces sparse updates into the variable referenced by `resource` using the `max` operation. +/// +/// This operation computes +/// +/// # Scalar indices +/// ref[indices, ...] = max(ref[indices, ...], updates[...]) +/// +/// # Vector indices (for each i) +/// ref[indices[i], ...] = max(ref[indices[i], ...], updates[i, ...]) +/// +/// # High rank indices (for each i, ..., j) +/// ref[indices[i, ..., j], ...] = max(ref[indices[i, ..., j], ...], updates[i, ..., j, ...]) +/// +/// Duplicate entries are handled correctly: if multiple `indices` reference +/// the same location, their contributions are combined. +/// +/// Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. +/// +///
+/// +///
+/// +/// - Parameters: +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. +@inlinable @inline(__always) +public static func resourceScatterMax< + Dtype: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + resource: ResourceHandle, + indices: Tensor, + updates: Tensor +) { + let nOutputs = 0 + let op = makeOp("ResourceScatterMax", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() +} + +/// Reduces sparse updates into the variable referenced by `resource` using the `min` operation. +/// +/// This operation computes +/// +/// # Scalar indices +/// ref[indices, ...] = min(ref[indices, ...], updates[...]) +/// +/// # Vector indices (for each i) +/// ref[indices[i], ...] = min(ref[indices[i], ...], updates[i, ...]) +/// +/// # High rank indices (for each i, ..., j) +/// ref[indices[i, ..., j], ...] = min(ref[indices[i, ..., j], ...], updates[i, ..., j, ...]) +/// +/// Duplicate entries are handled correctly: if multiple `indices` reference +/// the same location, their contributions are combined. +/// +/// Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. +/// +///
+/// +///
+/// +/// - Parameters: +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. +@inlinable @inline(__always) +public static func resourceScatterMin< + Dtype: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + resource: ResourceHandle, + indices: Tensor, + updates: Tensor +) { + let nOutputs = 0 + let op = makeOp("ResourceScatterMin", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() +} + +/// Multiplies sparse updates into the variable referenced by `resource`. +/// +/// This operation computes +/// +/// # Scalar indices +/// ref[indices, ...] *= updates[...] +/// +/// # Vector indices (for each i) +/// ref[indices[i], ...] *= updates[i, ...] +/// +/// # High rank indices (for each i, ..., j) +/// ref[indices[i, ..., j], ...] *= updates[i, ..., j, ...] +/// +/// Duplicate entries are handled correctly: if multiple `indices` reference +/// the same location, their contributions multiply. +/// +/// Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. +/// +///
+/// +///
+/// +/// - Parameters: +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. +@inlinable @inline(__always) +public static func resourceScatterMul< + Dtype: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + resource: ResourceHandle, + indices: Tensor, + updates: Tensor +) { + let nOutputs = 0 + let op = makeOp("ResourceScatterMul", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() +} + +/// Applies sparse addition to individual values or slices in a Variable. +/// +/// `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. +/// +/// `indices` must be integer tensor, containing indices into `ref`. +/// It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. +/// +/// The innermost dimension of `indices` (with length `K`) corresponds to +/// indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th +/// dimension of `ref`. +/// +/// `updates` is `Tensor` of rank `Q-1+P-K` with shape: +/// +/// ``` +/// [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]] +/// ``` +/// +/// For example, say we want to add 4 scattered elements to a rank-1 tensor to +/// 8 elements. In Python, that addition would look like this: +/// +/// ```python +/// ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8], use_resource=True) +/// indices = tf.constant([[4], [3], [1], [7]]) +/// updates = tf.constant([9, 10, 11, 12]) +/// add = tf.scatter_nd_add(ref, indices, updates) +/// with tf.Session() as sess: +/// print sess.run(add) +/// ``` +/// +/// The resulting update to ref would look like this: +/// +/// [1, 13, 3, 14, 14, 6, 7, 20] +/// +/// See `tf.scatter_nd` for more details about how to make updates to +/// slices. +/// +/// - Parameters: +/// - ref: A resource handle. Must be from a VarHandleOp. +/// - indices: A Tensor. Must be one of the following types: int32, int64. +/// A tensor of indices into ref. +/// - updates: A Tensor. Must have the same type as ref. A tensor of +/// values to add to ref. +/// +/// - Attr use_locking: An optional bool. Defaults to True. If True, the assignment will +/// be protected by a lock; otherwise the behavior is undefined, +/// but may exhibit less contention. +@inlinable @inline(__always) +public static func resourceScatterNdAdd< + T: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + ref: ResourceHandle, + indices: Tensor, + updates: Tensor, + useLocking: Bool = true +) { + let nOutputs = 0 + let op = makeOp("ResourceScatterNdAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(ref) + op.addInput(indices) + op.addInput(updates) + op.execute() +} + +/// Applies sparse subtraction to individual values or slices in a Variable. +/// +/// `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. +/// +/// `indices` must be integer tensor, containing indices into `ref`. +/// It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. +/// +/// The innermost dimension of `indices` (with length `K`) corresponds to +/// indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th +/// dimension of `ref`. +/// +/// `updates` is `Tensor` of rank `Q-1+P-K` with shape: +/// +/// ``` +/// [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]] +/// ``` +/// +/// For example, say we want to subtract 4 scattered elements from a rank-1 tensor +/// with 8 elements. In Python, that subtraction would look like this: +/// +/// ```python +/// ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8], use_resource=True) +/// indices = tf.constant([[4], [3], [1], [7]]) +/// updates = tf.constant([9, 10, 11, 12]) +/// sub = tf.scatter_nd_sub(ref, indices, updates) +/// with tf.Session() as sess: +/// print sess.run(sub) +/// ``` +/// +/// The resulting update to ref would look like this: +/// +/// [1, -9, 3, -6, -4, 6, 7, -4] +/// +/// See `tf.scatter_nd` for more details about how to make updates to +/// slices. +/// +/// - Parameters: +/// - ref: A resource handle. Must be from a VarHandleOp. +/// - indices: A Tensor. Must be one of the following types: int32, int64. +/// A tensor of indices into ref. +/// - updates: A Tensor. Must have the same type as ref. A tensor of +/// values to add to ref. +/// +/// - Attr use_locking: An optional bool. Defaults to True. If True, the assignment will +/// be protected by a lock; otherwise the behavior is undefined, +/// but may exhibit less contention. +@inlinable @inline(__always) +public static func resourceScatterNdSub< + T: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + ref: ResourceHandle, + indices: Tensor, + updates: Tensor, + useLocking: Bool = true +) { + let nOutputs = 0 + let op = makeOp("ResourceScatterNdSub", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(ref) + op.addInput(indices) + op.addInput(updates) + op.execute() +} + +/// Applies sparse `updates` to individual values or slices within a given +/// +/// variable according to `indices`. +/// +/// `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. +/// +/// `indices` must be integer tensor, containing indices into `ref`. +/// It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. +/// +/// The innermost dimension of `indices` (with length `K`) corresponds to +/// indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th +/// dimension of `ref`. +/// +/// `updates` is `Tensor` of rank `Q-1+P-K` with shape: +/// +/// ``` +/// [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. +/// ``` +/// +/// For example, say we want to update 4 scattered elements to a rank-1 tensor to +/// 8 elements. In Python, that update would look like this: +/// +/// ```python +/// ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) +/// indices = tf.constant([[4], [3], [1] ,[7]]) +/// updates = tf.constant([9, 10, 11, 12]) +/// update = tf.scatter_nd_update(ref, indices, updates) +/// with tf.Session() as sess: +/// print sess.run(update) +/// ``` +/// +/// The resulting update to ref would look like this: +/// +/// [1, 11, 3, 10, 9, 6, 7, 12] +/// +/// See `tf.scatter_nd` for more details about how to make updates to +/// slices. +/// +/// - Parameters: +/// - ref: A resource handle. Must be from a VarHandleOp. +/// - indices: A Tensor. Must be one of the following types: int32, int64. +/// A tensor of indices into ref. +/// - updates: A Tensor. Must have the same type as ref. A tensor of updated +/// values to add to ref. +/// +/// - Attr use_locking: An optional bool. Defaults to True. If True, the assignment will +/// be protected by a lock; otherwise the behavior is undefined, +/// but may exhibit less contention. +@inlinable @inline(__always) +public static func resourceScatterNdUpdate< + T: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + ref: ResourceHandle, + indices: Tensor, + updates: Tensor, + useLocking: Bool = true +) { + let nOutputs = 0 + let op = makeOp("ResourceScatterNdUpdate", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(ref) + op.addInput(indices) + op.addInput(updates) + op.execute() +} + +/// Subtracts sparse updates from the variable referenced by `resource`. +/// +/// This operation computes +/// +/// # Scalar indices +/// ref[indices, ...] -= updates[...] +/// +/// # Vector indices (for each i) +/// ref[indices[i], ...] -= updates[i, ...] +/// +/// # High rank indices (for each i, ..., j) +/// ref[indices[i, ..., j], ...] -= updates[i, ..., j, ...] +/// +/// Duplicate entries are handled correctly: if multiple `indices` reference +/// the same location, their contributions add. +/// +/// Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. +/// +///
+/// +///
+/// +/// - Parameters: +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. +@inlinable @inline(__always) +public static func resourceScatterSub< + Dtype: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + resource: ResourceHandle, + indices: Tensor, + updates: Tensor +) { + let nOutputs = 0 + let op = makeOp("ResourceScatterSub", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() +} + +/// Assigns sparse updates to the variable referenced by `resource`. +/// +/// This operation computes +/// +/// # Scalar indices +/// ref[indices, ...] = updates[...] +/// +/// # Vector indices (for each i) +/// ref[indices[i], ...] = updates[i, ...] +/// +/// # High rank indices (for each i, ..., j) +/// ref[indices[i, ..., j], ...] = updates[i, ..., j, ...] +/// +/// - Parameters: +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. +@inlinable @inline(__always) +public static func resourceScatterUpdate< + Dtype: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + resource: ResourceHandle, + indices: Tensor, + updates: Tensor +) { + let nOutputs = 0 + let op = makeOp("ResourceScatterUpdate", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() +} + +/// var: Should be from a Variable(). +/// +/// - Parameters: +/// - accum: Should be from a Variable(). +/// - accum_update: : Should be from a Variable(). +/// - lr: Learning rate. Must be a scalar. +/// - rho: Decay factor. Must be a scalar. +/// - epsilon: Constant factor. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// +/// - Attr use_locking: If True, updating of the var and accum tensors will be protected by +/// a lock; otherwise the behavior is undefined, but may exhibit less contention. +@inlinable @inline(__always) +public static func resourceSparseApplyAdadelta< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + var_: ResourceHandle, + accum: ResourceHandle, + accumUpdate: ResourceHandle, + lr: Tensor, + rho: Tensor, + epsilon: Tensor, + grad: Tensor, + indices: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceSparseApplyAdadelta", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(accumUpdate) + op.addInput(lr) + op.addInput(rho) + op.addInput(epsilon) + op.addInput(grad) + op.addInput(indices) + op.execute() +} + +/// Update relevant entries in '*var' and '*accum' according to the adagrad scheme. +/// +/// That is for rows we have grad for, we update var and accum as follows: +/// accum += grad * grad +/// var -= lr * grad * (1 / sqrt(accum)) +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Learning rate. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// +/// - Attr use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceSparseApplyAdagrad< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + grad: Tensor, + indices: Tensor, + useLocking: Bool = false, + updateSlots: Bool = true +) { + let nOutputs = 0 + let op = makeOp("ResourceSparseApplyAdagrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("update_slots", updateSlots) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(grad) + op.addInput(indices) + op.execute() +} + +/// Update entries in '*var' and '*accum' according to the proximal adagrad scheme. +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - gradient_accumulator: Should be from a Variable(). +/// - gradient_squared_accumulator: Should be from a Variable(). +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// - lr: Learning rate. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - global_step: Training step number. Must be a scalar. +/// +/// - Attr use_locking: If True, updating of the var and accum tensors will be protected by +/// a lock; otherwise the behavior is undefined, but may exhibit less contention. +@inlinable @inline(__always) +public static func resourceSparseApplyAdagradDA< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + var_: ResourceHandle, + gradientAccumulator: ResourceHandle, + gradientSquaredAccumulator: ResourceHandle, + grad: Tensor, + indices: Tensor, + lr: Tensor, + l1: Tensor, + l2: Tensor, + globalStep: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceSparseApplyAdagradDA", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(gradientAccumulator) + op.addInput(gradientSquaredAccumulator) + op.addInput(grad) + op.addInput(indices) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(globalStep) + op.execute() +} + +/// Update '*var' according to the centered RMSProp algorithm. +/// +/// The centered RMSProp algorithm uses an estimate of the centered second moment +/// (i.e., the variance) for normalization, as opposed to regular RMSProp, which +/// uses the (uncentered) second moment. This often helps with training, but is +/// slightly more expensive in terms of computation and memory. +/// +/// Note that in dense implementation of this algorithm, mg, ms, and mom will +/// update even if the grad is zero, but in this sparse implementation, mg, ms, +/// and mom will not update in iterations during which the grad is zero. +/// +/// mean_square = decay * mean_square + (1-decay) * gradient ** 2 +/// mean_grad = decay * mean_grad + (1-decay) * gradient +/// Delta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2) +/// +/// ms <- rho * ms_{t-1} + (1-rho) * grad * grad +/// mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon) +/// var <- var - mom +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - mg: Should be from a Variable(). +/// - ms: Should be from a Variable(). +/// - mom: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - rho: Decay rate. Must be a scalar. +/// - epsilon: Ridge term. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var, ms and mom. +/// +/// - Attr use_locking: If `True`, updating of the var, mg, ms, and mom tensors is +/// protected by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceSparseApplyCenteredRMSProp< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + var_: ResourceHandle, + mg: ResourceHandle, + ms: ResourceHandle, + mom: ResourceHandle, + lr: Tensor, + rho: Tensor, + momentum: Tensor, + epsilon: Tensor, + grad: Tensor, + indices: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceSparseApplyCenteredRMSProp", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(mg) + op.addInput(ms) + op.addInput(mom) + op.addInput(lr) + op.addInput(rho) + op.addInput(momentum) + op.addInput(epsilon) + op.addInput(grad) + op.addInput(indices) + op.execute() +} + +/// Update relevant entries in '*var' according to the Ftrl-proximal scheme. +/// +/// That is for rows we have grad for, we update var, accum and linear as follows: +/// accum_new = accum + grad * grad +/// linear += grad + (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var +/// quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2 +/// var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0 +/// accum = accum_new +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - linear: Should be from a Variable(). +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// - lr: Scaling factor. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - lr_power: Scaling factor. Must be a scalar. +/// +/// - Attr use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceSparseApplyFtrl< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + var_: ResourceHandle, + accum: ResourceHandle, + linear: ResourceHandle, + grad: Tensor, + indices: Tensor, + lr: Tensor, + l1: Tensor, + l2: Tensor, + lrPower: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceSparseApplyFtrl", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(linear) + op.addInput(grad) + op.addInput(indices) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(lrPower) + op.execute() +} + +/// Update relevant entries in '*var' according to the Ftrl-proximal scheme. +/// +/// That is for rows we have grad for, we update var, accum and linear as follows: +/// grad_with_shrinkage = grad + 2 * l2_shrinkage * var +/// accum_new = accum + grad_with_shrinkage * grad_with_shrinkage +/// linear += grad_with_shrinkage + +/// (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var +/// quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2 +/// var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0 +/// accum = accum_new +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - linear: Should be from a Variable(). +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// - lr: Scaling factor. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 shrinkage regulariation. Must be a scalar. +/// - lr_power: Scaling factor. Must be a scalar. +/// +/// - Attr use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceSparseApplyFtrlV2< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + var_: ResourceHandle, + accum: ResourceHandle, + linear: ResourceHandle, + grad: Tensor, + indices: Tensor, + lr: Tensor, + l1: Tensor, + l2: Tensor, + l2Shrinkage: Tensor, + lrPower: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceSparseApplyFtrlV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(linear) + op.addInput(grad) + op.addInput(indices) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(l2Shrinkage) + op.addInput(lrPower) + op.execute() +} + +/// Update relevant entries in '*var' and '*accum' according to the momentum scheme. +/// +/// Set use_nesterov = True if you want to use Nesterov momentum. +/// +/// That is for rows we have grad for, we update var and accum as follows: +/// +/// accum = accum * momentum - lr * grad +/// var += accum +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Learning rate. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// - momentum: Momentum. Must be a scalar. +/// +/// - Attrs: +/// - use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +/// - use_nesterov: If `True`, the tensor passed to compute grad will be +/// var + momentum * accum, so in the end, the var you get is actually +/// var + momentum * accum. +@inlinable @inline(__always) +public static func resourceSparseApplyKerasMomentum< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + grad: Tensor, + indices: Tensor, + momentum: Tensor, + useLocking: Bool = false, + useNesterov: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceSparseApplyKerasMomentum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("use_nesterov", useNesterov) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(grad) + op.addInput(indices) + op.addInput(momentum) + op.execute() +} + +/// Update relevant entries in '*var' and '*accum' according to the momentum scheme. +/// +/// Set use_nesterov = True if you want to use Nesterov momentum. +/// +/// That is for rows we have grad for, we update var and accum as follows: +/// +/// accum = accum * momentum + grad +/// var -= lr * accum +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Learning rate. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// - momentum: Momentum. Must be a scalar. +/// +/// - Attrs: +/// - use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +/// - use_nesterov: If `True`, the tensor passed to compute grad will be +/// var - lr * momentum * accum, so in the end, the var you get is actually +/// var - lr * momentum * accum. +@inlinable @inline(__always) +public static func resourceSparseApplyMomentum< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + grad: Tensor, + indices: Tensor, + momentum: Tensor, + useLocking: Bool = false, + useNesterov: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceSparseApplyMomentum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("use_nesterov", useNesterov) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(grad) + op.addInput(indices) + op.addInput(momentum) + op.execute() +} + +/// Sparse update entries in '*var' and '*accum' according to FOBOS algorithm. +/// +/// That is for rows we have grad for, we update var and accum as follows: +/// accum += grad * grad +/// prox_v = var +/// prox_v -= lr * grad * (1 / sqrt(accum)) +/// var = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0} +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Learning rate. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// +/// - Attr use_locking: If True, updating of the var and accum tensors will be protected by +/// a lock; otherwise the behavior is undefined, but may exhibit less contention. +@inlinable @inline(__always) +public static func resourceSparseApplyProximalAdagrad< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + l1: Tensor, + l2: Tensor, + grad: Tensor, + indices: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceSparseApplyProximalAdagrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(grad) + op.addInput(indices) + op.execute() +} + +/// Sparse update '*var' as FOBOS algorithm with fixed learning rate. +/// +/// That is for rows we have grad for, we update var as follows: +/// prox_v = var - alpha * grad +/// var = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0} +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - alpha: Scaling factor. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// +/// - Attr use_locking: If True, the subtraction will be protected by a lock; +/// otherwise the behavior is undefined, but may exhibit less contention. +@inlinable @inline(__always) +public static func resourceSparseApplyProximalGradientDescent< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + var_: ResourceHandle, + alpha: Tensor, + l1: Tensor, + l2: Tensor, + grad: Tensor, + indices: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceSparseApplyProximalGradientDescent", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(alpha) + op.addInput(l1) + op.addInput(l2) + op.addInput(grad) + op.addInput(indices) + op.execute() +} + +/// Update '*var' according to the RMSProp algorithm. +/// +/// Note that in dense implementation of this algorithm, ms and mom will +/// update even if the grad is zero, but in this sparse implementation, ms +/// and mom will not update in iterations during which the grad is zero. +/// +/// mean_square = decay * mean_square + (1-decay) * gradient ** 2 +/// Delta = learning_rate * gradient / sqrt(mean_square + epsilon) +/// +/// ms <- rho * ms_{t-1} + (1-rho) * grad * grad +/// mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon) +/// var <- var - mom +/// +/// - Parameters: +/// - var: Should be from a Variable(). +/// - ms: Should be from a Variable(). +/// - mom: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - rho: Decay rate. Must be a scalar. +/// - epsilon: Ridge term. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var, ms and mom. +/// +/// - Attr use_locking: If `True`, updating of the var, ms, and mom tensors is protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +@inlinable @inline(__always) +public static func resourceSparseApplyRMSProp< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + var_: ResourceHandle, + ms: ResourceHandle, + mom: ResourceHandle, + lr: Tensor, + rho: Tensor, + momentum: Tensor, + epsilon: Tensor, + grad: Tensor, + indices: Tensor, + useLocking: Bool = false +) { + let nOutputs = 0 + let op = makeOp("ResourceSparseApplyRMSProp", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(ms) + op.addInput(mom) + op.addInput(lr) + op.addInput(rho) + op.addInput(momentum) + op.addInput(epsilon) + op.addInput(grad) + op.addInput(indices) + op.execute() +} + +/// Assign `value` to the sliced l-value reference of `ref`. +/// +/// The values of `value` are assigned to the positions in the variable +/// `ref` that are selected by the slice parameters. The slice parameters +/// `begin, `end`, `strides`, etc. work exactly as in `StridedSlice`. +/// +/// NOTE this op currently does not support broadcasting and so `value`'s +/// shape must be exactly the shape produced by the slice of `ref`. +@inlinable @inline(__always) +public static func resourceStridedSliceAssign< + T: TensorFlowScalar, + Index: BinaryInteger & TensorFlowScalar +>( + ref: ResourceHandle, + begin: Tensor, + end: Tensor, + strides: Tensor, + value: Tensor, + beginMask: Int64 = 0, + endMask: Int64 = 0, + ellipsisMask: Int64 = 0, + newAxisMask: Int64 = 0, + shrinkAxisMask: Int64 = 0 +) { + let nOutputs = 0 + let op = makeOp("ResourceStridedSliceAssign", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Index", Index.tensorFlowDataType) + op.updateAttribute("begin_mask", beginMask) + op.updateAttribute("end_mask", endMask) + op.updateAttribute("ellipsis_mask", ellipsisMask) + op.updateAttribute("new_axis_mask", newAxisMask) + op.updateAttribute("shrink_axis_mask", shrinkAxisMask) + op.addInput(ref) + op.addInput(begin) + op.addInput(end) + op.addInput(strides) + op.addInput(value) + op.execute() +} + +@inlinable @inline(__always) +public static func resourceUsingOp( + resource: ResourceHandle +) { + let nOutputs = 0 + let op = makeOp("ResourceUsingOp", nOutputs) + op.addInput(resource) + op.execute() +} + +/// Restores a tensor from checkpoint files. +/// +/// Reads a tensor stored in one or several files. If there are several files (for +/// instance because a tensor was saved as slices), `file_pattern` may contain +/// wildcard symbols (`*` and `?`) in the filename portion only, not in the +/// directory portion. +/// +/// If a `file_pattern` matches several files, `preferred_shard` can be used to hint +/// in which file the requested tensor is likely to be found. This op will first +/// open the file at index `preferred_shard` in the list of matching files and try +/// to restore tensors from that file. Only if some tensors or tensor slices are +/// not found in that first file, then the Op opens all the files. Setting +/// `preferred_shard` to match the value passed as the `shard` input +/// of a matching `Save` Op may speed up Restore. This attribute only affects +/// performance, not correctness. The default value -1 means files are processed in +/// order. +/// +/// See also `RestoreSlice`. +/// +/// - Parameters: +/// - file_pattern: Must have a single element. The pattern of the files from +/// which we read the tensor. +/// - tensor_name: Must have a single element. The name of the tensor to be +/// restored. +/// +/// - Attrs: +/// - dt: The type of the tensor to be restored. +/// - preferred_shard: Index of file to open first if multiple files match +/// `file_pattern`. +/// +/// - Output tensor: The restored tensor. +@inlinable @inline(__always) +public static func restore( + filePattern: StringTensor, + tensorName: StringTensor, + preferredShard: Int64 = -1 +) -> Tensor
{ + let nOutputs = Int(1) + let op = makeOp("Restore", nOutputs) + op.updateAttribute("dt", Dt.tensorFlowDataType) + op.updateAttribute("preferred_shard", preferredShard) + op.addInput(filePattern) + op.addInput(tensorName) + return op.execute(Int(1)) +} + +/// Restores a tensor from checkpoint files. +/// +/// This is like `Restore` except that restored tensor can be listed as filling +/// only a slice of a larger tensor. `shape_and_slice` specifies the shape of the +/// larger tensor and the slice that the restored tensor covers. +/// +/// The `shape_and_slice` input has the same format as the +/// elements of the `shapes_and_slices` input of the `SaveSlices` op. +/// +/// - Parameters: +/// - file_pattern: Must have a single element. The pattern of the files from +/// which we read the tensor. +/// - tensor_name: Must have a single element. The name of the tensor to be +/// restored. +/// - shape_and_slice: Scalar. The shapes and slice specifications to use when +/// restoring a tensors. +/// +/// - Attrs: +/// - dt: The type of the tensor to be restored. +/// - preferred_shard: Index of file to open first if multiple files match +/// `file_pattern`. See the documentation for `Restore`. +/// +/// - Output tensor: The restored tensor. +@inlinable @inline(__always) +public static func restoreSlice( + filePattern: StringTensor, + tensorName: StringTensor, + shapeAndSlice: StringTensor, + preferredShard: Int64 = -1 +) -> Tensor
{ + let nOutputs = Int(1) + let op = makeOp("RestoreSlice", nOutputs) + op.updateAttribute("dt", Dt.tensorFlowDataType) + op.updateAttribute("preferred_shard", preferredShard) + op.addInput(filePattern) + op.addInput(tensorName) + op.addInput(shapeAndSlice) + return op.execute(Int(1)) +} + +/// Restores tensors from a V2 checkpoint. +/// +/// For backward compatibility with the V1 format, this Op currently allows +/// restoring from a V1 checkpoint as well: +/// - This Op first attempts to find the V2 index file pointed to by "prefix", and +/// if found proceed to read it as a V2 checkpoint; +/// - Otherwise the V1 read path is invoked. +/// Relying on this behavior is not recommended, as the ability to fall back to read +/// V1 might be deprecated and eventually removed. +/// +/// By default, restores the named tensors in full. If the caller wishes to restore +/// specific slices of stored tensors, "shape_and_slices" should be non-empty +/// strings and correspondingly well-formed. +/// +/// Callers must ensure all the named tensors are indeed stored in the checkpoint. +/// +/// - Parameters: +/// - prefix: Must have a single element. The prefix of a V2 checkpoint. +/// - tensor_names: shape {N}. The names of the tensors to be restored. +/// - shape_and_slices: shape {N}. The slice specs of the tensors to be restored. +/// Empty strings indicate that they are non-partitioned tensors. +/// +/// - Attr dtypes: shape {N}. The list of expected dtype for the tensors. Must match +/// those stored in the checkpoint. +/// +/// - Output tensors: shape {N}. The restored tensors, whose shapes are read from the +/// checkpoint directly. +@inlinable @inline(__always) +public static func restoreV2( + prefix: StringTensor, + tensorNames: StringTensor, + shapeAndSlices: StringTensor +) -> Dtypes { + let nOutputs = Int(Dtypes._typeList.count) + let op = makeOp("RestoreV2", nOutputs) + op.updateAttribute("dtypes", Dtypes._typeList) + op.addInput(prefix) + op.addInput(tensorNames) + op.addInput(shapeAndSlices) + return op.execute(Int(Dtypes._typeList.count)) +} + +@inlinable @inline(__always) +public static func restrict( + _ a: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Restrict", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func restrict( + _ a: StringTensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("Restrict", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(a) + return op.execute(Int(1)) +} + +/// Retrieve ADAM embedding parameters. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the ADAM optimization algorithm. +/// - momenta: Parameter momenta updated by the ADAM optimization algorithm. +/// - velocities: Parameter velocities updated by the ADAM optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingADAMParameters( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, momenta: Tensor, velocities: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingADAMParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Retrieve ADAM embedding parameters with debug support. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the ADAM optimization algorithm. +/// - momenta: Parameter momenta updated by the ADAM optimization algorithm. +/// - velocities: Parameter velocities updated by the ADAM optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the ADAM optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingADAMParametersGradAccumDebug( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, momenta: Tensor, velocities: Tensor, gradientAccumulators: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingADAMParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Retrieve Adadelta embedding parameters. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the Adadelta optimization algorithm. +/// - accumulators: Parameter accumulators updated by the Adadelta optimization algorithm. +/// - updates: Parameter updates updated by the Adadelta optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingAdadeltaParameters( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, accumulators: Tensor, updates: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingAdadeltaParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Retrieve Adadelta embedding parameters with debug support. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the Adadelta optimization algorithm. +/// - accumulators: Parameter accumulators updated by the Adadelta optimization algorithm. +/// - updates: Parameter updates updated by the Adadelta optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the Adadelta optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingAdadeltaParametersGradAccumDebug( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, accumulators: Tensor, updates: Tensor, gradientAccumulators: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingAdadeltaParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Retrieve Adagrad embedding parameters. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the Adagrad optimization algorithm. +/// - accumulators: Parameter accumulators updated by the Adagrad optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingAdagradParameters( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, accumulators: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingAdagradParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1)) +} + +/// Retrieve Adagrad embedding parameters with debug support. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the Adagrad optimization algorithm. +/// - accumulators: Parameter accumulators updated by the Adagrad optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the Adagrad optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingAdagradParametersGradAccumDebug( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, accumulators: Tensor, gradientAccumulators: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingAdagradParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Retrieve centered RMSProp embedding parameters. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the centered RMSProp optimization algorithm. +/// - ms: Parameter ms updated by the centered RMSProp optimization algorithm. +/// - mom: Parameter mom updated by the centered RMSProp optimization algorithm. +/// - mg: Parameter mg updated by the centered RMSProp optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingCenteredRMSPropParameters( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, ms: Tensor, mom: Tensor, mg: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingCenteredRMSPropParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Retrieve FTRL embedding parameters. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the FTRL optimization algorithm. +/// - accumulators: Parameter accumulators updated by the FTRL optimization algorithm. +/// - linears: Parameter linears updated by the FTRL optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingFTRLParameters( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, accumulators: Tensor, linears: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingFTRLParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Retrieve FTRL embedding parameters with debug support. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the FTRL optimization algorithm. +/// - accumulators: Parameter accumulators updated by the FTRL optimization algorithm. +/// - linears: Parameter linears updated by the FTRL optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the FTRL optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingFTRLParametersGradAccumDebug( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, accumulators: Tensor, linears: Tensor, gradientAccumulators: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingFTRLParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Retrieve MDL Adagrad Light embedding parameters. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the MDL Adagrad Light optimization algorithm. +/// - accumulators: Parameter accumulators updated by the MDL Adagrad Light optimization algorithm. +/// - weights: Parameter weights updated by the MDL Adagrad Light optimization algorithm. +/// - benefits: Parameter benefits updated by the MDL Adagrad Light optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingMDLAdagradLightParameters( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, accumulators: Tensor, weights: Tensor, benefits: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingMDLAdagradLightParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Retrieve Momentum embedding parameters. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the Momentum optimization algorithm. +/// - momenta: Parameter momenta updated by the Momentum optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingMomentumParameters( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, momenta: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingMomentumParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1)) +} + +/// Retrieve Momentum embedding parameters with debug support. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the Momentum optimization algorithm. +/// - momenta: Parameter momenta updated by the Momentum optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the Momentum optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingMomentumParametersGradAccumDebug( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, momenta: Tensor, gradientAccumulators: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingMomentumParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Retrieve proximal Adagrad embedding parameters. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the proximal Adagrad optimization algorithm. +/// - accumulators: Parameter accumulators updated by the proximal Adagrad optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingProximalAdagradParameters( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, accumulators: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingProximalAdagradParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1)) +} + +/// Retrieve proximal Adagrad embedding parameters with debug support. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the proximal Adagrad optimization algorithm. +/// - accumulators: Parameter accumulators updated by the proximal Adagrad optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the proximal Adagrad optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingProximalAdagradParametersGradAccumDebug( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, accumulators: Tensor, gradientAccumulators: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingProximalAdagradParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Retrieve RMSProp embedding parameters. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the RMSProp optimization algorithm. +/// - ms: Parameter ms updated by the RMSProp optimization algorithm. +/// - mom: Parameter mom updated by the RMSProp optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingRMSPropParameters( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, ms: Tensor, mom: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingRMSPropParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Retrieve RMSProp embedding parameters with debug support. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Outputs: +/// - parameters: Parameter parameters updated by the RMSProp optimization algorithm. +/// - ms: Parameter ms updated by the RMSProp optimization algorithm. +/// - mom: Parameter mom updated by the RMSProp optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the RMSProp optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingRMSPropParametersGradAccumDebug( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> (parameters: Tensor, ms: Tensor, mom: Tensor, gradientAccumulators: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("RetrieveTPUEmbeddingRMSPropParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// Retrieve SGD embedding parameters. +/// +/// An op that retrieves optimization parameters from embedding to host +/// memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up +/// the correct embedding table configuration. For example, this op is +/// used to retrieve updated parameters before saving a checkpoint. +/// +/// - Output parameters: Parameter parameters updated by the stochastic gradient descent optimization algorithm. +@inlinable @inline(__always) +public static func retrieveTPUEmbeddingStochasticGradientDescentParameters( + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RetrieveTPUEmbeddingStochasticGradientDescentParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1)) +} + +/// Reverses specific dimensions of a tensor. +/// +/// Given a `tensor`, and a `bool` tensor `dims` representing the dimensions +/// of `tensor`, this operation reverses each dimension i of `tensor` where +/// `dims[i]` is `True`. +/// +/// `tensor` can have up to 8 dimensions. The number of dimensions +/// of `tensor` must equal the number of elements in `dims`. In other words: +/// +/// `rank(tensor) = size(dims)` +/// +/// For example: +/// +/// ``` +/// # tensor 't' is [[[[ 0, 1, 2, 3], +/// # [ 4, 5, 6, 7], +/// # [ 8, 9, 10, 11]], +/// # [[12, 13, 14, 15], +/// # [16, 17, 18, 19], +/// # [20, 21, 22, 23]]]] +/// # tensor 't' shape is [1, 2, 3, 4] +/// +/// # 'dims' is [False, False, False, True] +/// reverse(t, dims) ==> [[[[ 3, 2, 1, 0], +/// [ 7, 6, 5, 4], +/// [ 11, 10, 9, 8]], +/// [[15, 14, 13, 12], +/// [19, 18, 17, 16], +/// [23, 22, 21, 20]]]] +/// +/// # 'dims' is [False, True, False, False] +/// reverse(t, dims) ==> [[[[12, 13, 14, 15], +/// [16, 17, 18, 19], +/// [20, 21, 22, 23] +/// [[ 0, 1, 2, 3], +/// [ 4, 5, 6, 7], +/// [ 8, 9, 10, 11]]]] +/// +/// # 'dims' is [False, False, True, False] +/// reverse(t, dims) ==> [[[[8, 9, 10, 11], +/// [4, 5, 6, 7], +/// [0, 1, 2, 3]] +/// [[20, 21, 22, 23], +/// [16, 17, 18, 19], +/// [12, 13, 14, 15]]]] +/// ``` +/// +/// - Parameters: +/// - tensor: Up to 8-D. +/// - dims: 1-D. The dimensions to reverse. +/// +/// - Output output: The same shape as `tensor`. +@inlinable @inline(__always) +public static func reverse( + _ tensor: Tensor, + dims: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Reverse", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(tensor) + op.addInput(dims) + return op.execute(Int(1)) +} + +/// Reverses specific dimensions of a tensor. +/// +/// Given a `tensor`, and a `bool` tensor `dims` representing the dimensions +/// of `tensor`, this operation reverses each dimension i of `tensor` where +/// `dims[i]` is `True`. +/// +/// `tensor` can have up to 8 dimensions. The number of dimensions +/// of `tensor` must equal the number of elements in `dims`. In other words: +/// +/// `rank(tensor) = size(dims)` +/// +/// For example: +/// +/// ``` +/// # tensor 't' is [[[[ 0, 1, 2, 3], +/// # [ 4, 5, 6, 7], +/// # [ 8, 9, 10, 11]], +/// # [[12, 13, 14, 15], +/// # [16, 17, 18, 19], +/// # [20, 21, 22, 23]]]] +/// # tensor 't' shape is [1, 2, 3, 4] +/// +/// # 'dims' is [False, False, False, True] +/// reverse(t, dims) ==> [[[[ 3, 2, 1, 0], +/// [ 7, 6, 5, 4], +/// [ 11, 10, 9, 8]], +/// [[15, 14, 13, 12], +/// [19, 18, 17, 16], +/// [23, 22, 21, 20]]]] +/// +/// # 'dims' is [False, True, False, False] +/// reverse(t, dims) ==> [[[[12, 13, 14, 15], +/// [16, 17, 18, 19], +/// [20, 21, 22, 23] +/// [[ 0, 1, 2, 3], +/// [ 4, 5, 6, 7], +/// [ 8, 9, 10, 11]]]] +/// +/// # 'dims' is [False, False, True, False] +/// reverse(t, dims) ==> [[[[8, 9, 10, 11], +/// [4, 5, 6, 7], +/// [0, 1, 2, 3]] +/// [[20, 21, 22, 23], +/// [16, 17, 18, 19], +/// [12, 13, 14, 15]]]] +/// ``` +/// +/// - Parameters: +/// - tensor: Up to 8-D. +/// - dims: 1-D. The dimensions to reverse. +/// +/// - Output output: The same shape as `tensor`. +@inlinable @inline(__always) +public static func reverse( + _ tensor: StringTensor, + dims: Tensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("Reverse", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(tensor) + op.addInput(dims) + return op.execute(Int(1)) +} + +/// Reverses variable length slices. +/// +/// This op first slices `input` along the dimension `batch_dim`, and for each +/// slice `i`, reverses the first `seq_lengths[i]` elements along +/// the dimension `seq_dim`. +/// +/// The elements of `seq_lengths` must obey `seq_lengths[i] <= input.dims[seq_dim]`, +/// and `seq_lengths` must be a vector of length `input.dims[batch_dim]`. +/// +/// The output slice `i` along dimension `batch_dim` is then given by input +/// slice `i`, with the first `seq_lengths[i]` slices along dimension +/// `seq_dim` reversed. +/// +/// For example: +/// +/// ``` +/// # Given this: +/// batch_dim = 0 +/// seq_dim = 1 +/// input.dims = (4, 8, ...) +/// seq_lengths = [7, 2, 3, 5] +/// +/// # then slices of input are reversed on seq_dim, but only up to seq_lengths: +/// output[0, 0:7, :, ...] = input[0, 7:0:-1, :, ...] +/// output[1, 0:2, :, ...] = input[1, 2:0:-1, :, ...] +/// output[2, 0:3, :, ...] = input[2, 3:0:-1, :, ...] +/// output[3, 0:5, :, ...] = input[3, 5:0:-1, :, ...] +/// +/// # while entries past seq_lens are copied through: +/// output[0, 7:, :, ...] = input[0, 7:, :, ...] +/// output[1, 2:, :, ...] = input[1, 2:, :, ...] +/// output[2, 3:, :, ...] = input[2, 3:, :, ...] +/// output[3, 2:, :, ...] = input[3, 2:, :, ...] +/// ``` +/// +/// In contrast, if: +/// +/// ``` +/// # Given this: +/// batch_dim = 2 +/// seq_dim = 0 +/// input.dims = (8, ?, 4, ...) +/// seq_lengths = [7, 2, 3, 5] +/// +/// # then slices of input are reversed on seq_dim, but only up to seq_lengths: +/// output[0:7, :, 0, :, ...] = input[7:0:-1, :, 0, :, ...] +/// output[0:2, :, 1, :, ...] = input[2:0:-1, :, 1, :, ...] +/// output[0:3, :, 2, :, ...] = input[3:0:-1, :, 2, :, ...] +/// output[0:5, :, 3, :, ...] = input[5:0:-1, :, 3, :, ...] +/// +/// # while entries past seq_lens are copied through: +/// output[7:, :, 0, :, ...] = input[7:, :, 0, :, ...] +/// output[2:, :, 1, :, ...] = input[2:, :, 1, :, ...] +/// output[3:, :, 2, :, ...] = input[3:, :, 2, :, ...] +/// output[2:, :, 3, :, ...] = input[2:, :, 3, :, ...] +/// ``` +/// +/// - Parameters: +/// - input: The input to reverse. +/// - seq_lengths: 1-D with length `input.dims(batch_dim)` and +/// `max(seq_lengths) <= input.dims(seq_dim)` +/// +/// - Attrs: +/// - seq_dim: The dimension which is partially reversed. +/// - batch_dim: The dimension along which reversal is performed. +/// +/// - Output output: The partially reversed input. It has the same shape as `input`. +@inlinable @inline(__always) +public static func reverseSequence< + T: TensorFlowScalar, + Tlen: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + seqLengths: Tensor, + seqDim: Int64, + batchDim: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ReverseSequence", nOutputs) + op.updateAttribute("seq_dim", seqDim) + op.updateAttribute("batch_dim", batchDim) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tlen", Tlen.tensorFlowDataType) + op.addInput(input) + op.addInput(seqLengths) + return op.execute(Int(1)) +} + +/// Reverses specific dimensions of a tensor. +/// +/// NOTE `tf.reverse` has now changed behavior in preparation for 1.0. +/// `tf.reverse_v2` is currently an alias that will be deprecated before TF 1.0. +/// +/// Given a `tensor`, and a `int32` tensor `axis` representing the set of +/// dimensions of `tensor` to reverse. This operation reverses each dimension +/// `i` for which there exists `j` s.t. `axis[j] == i`. +/// +/// `tensor` can have up to 8 dimensions. The number of dimensions specified +/// in `axis` may be 0 or more entries. If an index is specified more than +/// once, a InvalidArgument error is raised. +/// +/// For example: +/// +/// ``` +/// # tensor 't' is [[[[ 0, 1, 2, 3], +/// # [ 4, 5, 6, 7], +/// # [ 8, 9, 10, 11]], +/// # [[12, 13, 14, 15], +/// # [16, 17, 18, 19], +/// # [20, 21, 22, 23]]]] +/// # tensor 't' shape is [1, 2, 3, 4] +/// +/// # 'dims' is [3] or 'dims' is [-1] +/// reverse(t, dims) ==> [[[[ 3, 2, 1, 0], +/// [ 7, 6, 5, 4], +/// [ 11, 10, 9, 8]], +/// [[15, 14, 13, 12], +/// [19, 18, 17, 16], +/// [23, 22, 21, 20]]]] +/// +/// # 'dims' is '[1]' (or 'dims' is '[-3]') +/// reverse(t, dims) ==> [[[[12, 13, 14, 15], +/// [16, 17, 18, 19], +/// [20, 21, 22, 23] +/// [[ 0, 1, 2, 3], +/// [ 4, 5, 6, 7], +/// [ 8, 9, 10, 11]]]] +/// +/// # 'dims' is '[2]' (or 'dims' is '[-2]') +/// reverse(t, dims) ==> [[[[8, 9, 10, 11], +/// [4, 5, 6, 7], +/// [0, 1, 2, 3]] +/// [[20, 21, 22, 23], +/// [16, 17, 18, 19], +/// [12, 13, 14, 15]]]] +/// ``` +/// +/// - Parameters: +/// - tensor: Up to 8-D. +/// - axis: 1-D. The indices of the dimensions to reverse. Must be in the range +/// `[-rank(tensor), rank(tensor))`. +/// +/// - Output output: The same shape as `tensor`. +@inlinable @inline(__always) +public static func reverseV2< + Tidx: BinaryInteger & TensorFlowScalar, + T: TensorFlowScalar +>( + _ tensor: Tensor, + axis: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ReverseV2", nOutputs) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(tensor) + op.addInput(axis) + return op.execute(Int(1)) +} + +/// Reverses specific dimensions of a tensor. +/// +/// NOTE `tf.reverse` has now changed behavior in preparation for 1.0. +/// `tf.reverse_v2` is currently an alias that will be deprecated before TF 1.0. +/// +/// Given a `tensor`, and a `int32` tensor `axis` representing the set of +/// dimensions of `tensor` to reverse. This operation reverses each dimension +/// `i` for which there exists `j` s.t. `axis[j] == i`. +/// +/// `tensor` can have up to 8 dimensions. The number of dimensions specified +/// in `axis` may be 0 or more entries. If an index is specified more than +/// once, a InvalidArgument error is raised. +/// +/// For example: +/// +/// ``` +/// # tensor 't' is [[[[ 0, 1, 2, 3], +/// # [ 4, 5, 6, 7], +/// # [ 8, 9, 10, 11]], +/// # [[12, 13, 14, 15], +/// # [16, 17, 18, 19], +/// # [20, 21, 22, 23]]]] +/// # tensor 't' shape is [1, 2, 3, 4] +/// +/// # 'dims' is [3] or 'dims' is [-1] +/// reverse(t, dims) ==> [[[[ 3, 2, 1, 0], +/// [ 7, 6, 5, 4], +/// [ 11, 10, 9, 8]], +/// [[15, 14, 13, 12], +/// [19, 18, 17, 16], +/// [23, 22, 21, 20]]]] +/// +/// # 'dims' is '[1]' (or 'dims' is '[-3]') +/// reverse(t, dims) ==> [[[[12, 13, 14, 15], +/// [16, 17, 18, 19], +/// [20, 21, 22, 23] +/// [[ 0, 1, 2, 3], +/// [ 4, 5, 6, 7], +/// [ 8, 9, 10, 11]]]] +/// +/// # 'dims' is '[2]' (or 'dims' is '[-2]') +/// reverse(t, dims) ==> [[[[8, 9, 10, 11], +/// [4, 5, 6, 7], +/// [0, 1, 2, 3]] +/// [[20, 21, 22, 23], +/// [16, 17, 18, 19], +/// [12, 13, 14, 15]]]] +/// ``` +/// +/// - Parameters: +/// - tensor: Up to 8-D. +/// - axis: 1-D. The indices of the dimensions to reverse. Must be in the range +/// `[-rank(tensor), rank(tensor))`. +/// +/// - Output output: The same shape as `tensor`. +@inlinable @inline(__always) +public static func reverseV2( + _ tensor: StringTensor, + axis: Tensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("ReverseV2", nOutputs) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(tensor) + op.addInput(axis) + return op.execute(Int(1)) +} + +/// Elementwise computes the bitwise right-shift of `x` and `y`. +/// +/// Performs a logical shift for unsigned integer types, and an arithmetic shift +/// for signed integer types. +/// +/// If `y` is negative, or greater than or equal to than the width of `x` in bits +/// the result is implementation defined. +@inlinable @inline(__always) +public static func rightShift( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RightShift", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns element-wise integer closest to x. +/// +/// If the result is midway between two representable values, +/// the even representable is chosen. +/// For example: +/// +/// ``` +/// rint(-1.5) ==> -2.0 +/// rint(0.5000001) ==> 1.0 +/// rint([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) ==> [-2., -2., -0., 0., 2., 2., 2.] +/// ``` +@inlinable @inline(__always) +public static func rint( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Rint", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func rngSkip( + resource: ResourceHandle, + algorithm: Tensor, + delta: Tensor +) { + let nOutputs = 0 + let op = makeOp("RngSkip", nOutputs) + op.addInput(resource) + op.addInput(algorithm) + op.addInput(delta) + op.execute() +} + +/// Rolls the elements of a tensor along an axis. +/// +/// The elements are shifted positively (towards larger indices) by the offset of +/// `shift` along the dimension of `axis`. Negative `shift` values will shift +/// elements in the opposite direction. Elements that roll passed the last position +/// will wrap around to the first and vice versa. Multiple shifts along multiple +/// axes may be specified. +/// +/// For example: +/// +/// ``` +/// # 't' is [0, 1, 2, 3, 4] +/// roll(t, shift=2, axis=0) ==> [3, 4, 0, 1, 2] +/// +/// # shifting along multiple dimensions +/// # 't' is [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] +/// roll(t, shift=[1, -2], axis=[0, 1]) ==> [[7, 8, 9, 5, 6], [2, 3, 4, 0, 1]] +/// +/// # shifting along the same axis multiple times +/// # 't' is [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] +/// roll(t, shift=[2, -3], axis=[1, 1]) ==> [[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]] +/// ``` +/// +/// - Parameters: +/// - shift: Dimension must be 0-D or 1-D. `shift[i]` specifies the number of places by which +/// elements are shifted positively (towards larger indices) along the dimension +/// specified by `axis[i]`. Negative shifts will roll the elements in the opposite +/// direction. +/// - axis: Dimension must be 0-D or 1-D. `axis[i]` specifies the dimension that the shift +/// `shift[i]` should occur. If the same axis is referenced more than once, the +/// total shift for that axis will be the sum of all the shifts that belong to that +/// axis. +/// +/// - Output output: Has the same shape and size as the input. The elements are shifted +/// positively (towards larger indices) by the offsets of `shift` along the +/// dimensions of `axis`. +@inlinable @inline(__always) +public static func roll< + T: TensorFlowScalar, + Tshift: BinaryInteger & TensorFlowScalar, + Taxis: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + shift: Tensor, + axis: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Roll", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tshift", Tshift.tensorFlowDataType) + op.updateAttribute("Taxis", Taxis.tensorFlowDataType) + op.addInput(input) + op.addInput(shift) + op.addInput(axis) + return op.execute(Int(1)) +} + +/// Rounds the values of a tensor to the nearest integer, element-wise. +/// +/// Rounds half to even. Also known as bankers rounding. If you want to round +/// according to the current system rounding mode use std::cint. +@inlinable @inline(__always) +public static func round( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Round", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Perform batches of RPC requests. +/// +/// This op asynchronously performs either a single RPC request, or a batch +/// of requests. RPC requests are defined by three main parameters: +/// +/// - `address` (the host+port or BNS address of the request) +/// - `method` (the RPC method name for the request) +/// - `request` (the serialized proto string, or vector of strings, +/// of the RPC request argument). +/// +/// For example, if you have an RPC service running on port localhost:2345, +/// and its interface is configured with the following proto declaration: +/// +/// ``` +/// service MyService { +/// rpc MyMethod(MyRequestProto) returns (MyResponseProto) { +/// } +/// }; +/// ``` +/// +/// then call this op with arguments: +/// +/// ``` +/// address = "localhost:2345" +/// method = "MyService/MyMethod" +/// ``` +/// +/// The `request` tensor is a string tensor representing serialized `MyRequestProto` +/// strings; and the output string tensor `response` will have the same shape +/// and contain (upon successful completion) corresponding serialized +/// `MyResponseProto` strings. +/// +/// For example, to send a single, empty, `MyRequestProto`, call +/// this op with `request = ""`. To send 5 **parallel** empty requests, +/// call this op with `request = ["", "", "", "", ""]`. +/// +/// More generally, one can create a batch of `MyRequestProto` serialized protos +/// from regular batched tensors using the `encode_proto` op, and convert +/// the response `MyResponseProto` serialized protos to batched tensors +/// using the `decode_proto` op. +/// +/// **NOTE** Working with serialized proto strings is faster than instantiating +/// actual proto objects in memory, so no performance degradation is expected +/// compared to writing custom kernels for this workflow. +/// +/// If the connection fails or the remote worker returns an error +/// status, the op reraises this exception locally. +/// +/// See the `TryRpc` op if you prefer to handle RPC failures manually in the graph. +/// +/// - Parameters: +/// - address: `0-D` or `1-D`. The address (i.e. host_name:port) of the RPC server. +/// If this tensor has more than 1 element, then multiple parallel rpc requests +/// are sent. This argument broadcasts with `method` and `request`. +/// - method: `0-D` or `1-D`. The method address on the RPC server. +/// If this tensor has more than 1 element, then multiple parallel rpc requests +/// are sent. This argument broadcasts with `address` and `request`. +/// - request: `0-D` or `1-D`. Serialized proto strings: the rpc request argument. +/// If this tensor has more than 1 element, then multiple parallel rpc requests +/// are sent. This argument broadcasts with `address` and `method`. +/// +/// - Attrs: +/// - protocol: RPC protocol to use. Empty string means use the default protocol. +/// Options include 'grpc'. +/// - fail_fast: `boolean`. If `true` (default), then failures to connect +/// (i.e., the server does not immediately respond) cause an RPC failure. +/// - timeout_in_ms: `int`. If `0` (default), then the kernel will run the RPC +/// request and only time out if the RPC deadline passes or the session times out. +/// If this value is greater than `0`, then the op will raise an exception if +/// the RPC takes longer than `timeout_in_ms`. +/// +/// - Output response: Same shape as `request`. Serialized proto strings: the rpc responses. +@inlinable @inline(__always) +public static func rpc( + address: StringTensor, + method: StringTensor, + request: StringTensor, + protocol_: String, + failFast: Bool = true, + timeoutInMs: Int64 = 0 +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("Rpc", nOutputs) + op.updateAttribute("protocol", protocol_) + op.updateAttribute("fail_fast", failFast) + op.updateAttribute("timeout_in_ms", timeoutInMs) + op.addInput(address) + op.addInput(method) + op.addInput(request) + return op.execute(Int(1)) +} + +/// Computes reciprocal of square root of x element-wise. +/// +/// I.e., \\(y = 1 / \sqrt{x}\\). +@inlinable @inline(__always) +public static func rsqrt( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Rsqrt", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the gradient for the rsqrt of `x` wrt its input. +/// +/// Specifically, `grad = dy * -0.5 * y^3`, where `y = rsqrt(x)`, and `dy` +/// is the corresponding input gradient. +@inlinable @inline(__always) +public static func rsqrtGrad( + _ y: Tensor, + dy: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("RsqrtGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(dy) + return op.execute(Int(1)) +} + +/// Generate a single randomly distorted bounding box for an image. +/// +/// Bounding box annotations are often supplied in addition to ground-truth labels +/// in image recognition or object localization tasks. A common technique for +/// training such a system is to randomly distort an image while preserving +/// its content, i.e. *data augmentation*. This Op outputs a randomly distorted +/// localization of an object, i.e. bounding box, given an `image_size`, +/// `bounding_boxes` and a series of constraints. +/// +/// The output of this Op is a single bounding box that may be used to crop the +/// original image. The output is returned as 3 tensors: `begin`, `size` and +/// `bboxes`. The first 2 tensors can be fed directly into `tf.slice` to crop the +/// image. The latter may be supplied to `tf.image.draw_bounding_boxes` to visualize +/// what the bounding box looks like. +/// +/// Bounding boxes are supplied and returned as `[y_min, x_min, y_max, x_max]`. The +/// bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and +/// height of the underlying image. +/// +/// For example, +/// +/// ```python +/// # Generate a single distorted bounding box. +/// begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box( +/// tf.shape(image), +/// bounding_boxes=bounding_boxes) +/// +/// # Draw the bounding box in an image summary. +/// image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0), +/// bbox_for_draw) +/// tf.summary.image('images_with_box', image_with_box) +/// +/// # Employ the bounding box to distort the image. +/// distorted_image = tf.slice(image, begin, size) +/// ``` +/// +/// Note that if no bounding box information is available, setting +/// `use_image_if_no_bounding_boxes = true` will assume there is a single implicit +/// bounding box covering the whole image. If `use_image_if_no_bounding_boxes` is +/// false and no bounding boxes are supplied, an error is raised. +/// +/// - Parameters: +/// - image_size: 1-D, containing `[height, width, channels]`. +/// - bounding_boxes: 3-D with shape `[batch, N, 4]` describing the N bounding boxes +/// associated with the image. +/// +/// - Attrs: +/// - seed: If either `seed` or `seed2` are set to non-zero, the random number +/// generator is seeded by the given `seed`. Otherwise, it is seeded by a random +/// seed. +/// - seed2: A second seed to avoid seed collision. +/// - min_object_covered: The cropped area of the image must contain at least this +/// fraction of any bounding box supplied. The value of this parameter should be +/// non-negative. In the case of 0, the cropped area does not need to overlap +/// any of the bounding boxes supplied. +/// - aspect_ratio_range: The cropped area of the image must have an aspect ratio = +/// width / height within this range. +/// - area_range: The cropped area of the image must contain a fraction of the +/// supplied image within this range. +/// - max_attempts: Number of attempts at generating a cropped region of the image +/// of the specified constraints. After `max_attempts` failures, return the entire +/// image. +/// - use_image_if_no_bounding_boxes: Controls behavior if no bounding boxes supplied. +/// If true, assume an implicit bounding box covering the whole input. If false, +/// raise an error. +/// +/// - Outputs: +/// - begin: 1-D, containing `[offset_height, offset_width, 0]`. Provide as input to +/// `tf.slice`. +/// - size: 1-D, containing `[target_height, target_width, -1]`. Provide as input to +/// `tf.slice`. +/// - bboxes: 3-D with shape `[1, 1, 4]` containing the distorted bounding box. +/// Provide as input to `tf.image.draw_bounding_boxes`. +@inlinable @inline(__always) +public static func sampleDistortedBoundingBox( + imageSize: Tensor, + boundingBoxes: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0, + minObjectCovered: Double = 0.1, + aspectRatioRange: [Double] = [0.75, 1.33], + areaRange: [Double] = [0.05, 1], + maxAttempts: Int64 = 100, + useImageIfNoBoundingBoxes: Bool = false +) -> (begin: Tensor, size: Tensor, bboxes: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("SampleDistortedBoundingBox", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("min_object_covered", minObjectCovered) + op.updateAttribute("aspect_ratio_range", aspectRatioRange) + op.updateAttribute("area_range", areaRange) + op.updateAttribute("max_attempts", maxAttempts) + op.updateAttribute("use_image_if_no_bounding_boxes", useImageIfNoBoundingBoxes) + op.addInput(imageSize) + op.addInput(boundingBoxes) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Generate a single randomly distorted bounding box for an image. +/// +/// Bounding box annotations are often supplied in addition to ground-truth labels +/// in image recognition or object localization tasks. A common technique for +/// training such a system is to randomly distort an image while preserving +/// its content, i.e. *data augmentation*. This Op outputs a randomly distorted +/// localization of an object, i.e. bounding box, given an `image_size`, +/// `bounding_boxes` and a series of constraints. +/// +/// The output of this Op is a single bounding box that may be used to crop the +/// original image. The output is returned as 3 tensors: `begin`, `size` and +/// `bboxes`. The first 2 tensors can be fed directly into `tf.slice` to crop the +/// image. The latter may be supplied to `tf.image.draw_bounding_boxes` to visualize +/// what the bounding box looks like. +/// +/// Bounding boxes are supplied and returned as `[y_min, x_min, y_max, x_max]`. The +/// bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and +/// height of the underlying image. +/// +/// For example, +/// +/// ```python +/// # Generate a single distorted bounding box. +/// begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box( +/// tf.shape(image), +/// bounding_boxes=bounding_boxes) +/// +/// # Draw the bounding box in an image summary. +/// image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0), +/// bbox_for_draw) +/// tf.summary.image('images_with_box', image_with_box) +/// +/// # Employ the bounding box to distort the image. +/// distorted_image = tf.slice(image, begin, size) +/// ``` +/// +/// Note that if no bounding box information is available, setting +/// `use_image_if_no_bounding_boxes = true` will assume there is a single implicit +/// bounding box covering the whole image. If `use_image_if_no_bounding_boxes` is +/// false and no bounding boxes are supplied, an error is raised. +/// +/// - Parameters: +/// - image_size: 1-D, containing `[height, width, channels]`. +/// - bounding_boxes: 3-D with shape `[batch, N, 4]` describing the N bounding boxes +/// associated with the image. +/// - min_object_covered: The cropped area of the image must contain at least this +/// fraction of any bounding box supplied. The value of this parameter should be +/// non-negative. In the case of 0, the cropped area does not need to overlap +/// any of the bounding boxes supplied. +/// +/// - Attrs: +/// - seed: If either `seed` or `seed2` are set to non-zero, the random number +/// generator is seeded by the given `seed`. Otherwise, it is seeded by a random +/// seed. +/// - seed2: A second seed to avoid seed collision. +/// - aspect_ratio_range: The cropped area of the image must have an aspect ratio = +/// width / height within this range. +/// - area_range: The cropped area of the image must contain a fraction of the +/// supplied image within this range. +/// - max_attempts: Number of attempts at generating a cropped region of the image +/// of the specified constraints. After `max_attempts` failures, return the entire +/// image. +/// - use_image_if_no_bounding_boxes: Controls behavior if no bounding boxes supplied. +/// If true, assume an implicit bounding box covering the whole input. If false, +/// raise an error. +/// +/// - Outputs: +/// - begin: 1-D, containing `[offset_height, offset_width, 0]`. Provide as input to +/// `tf.slice`. +/// - size: 1-D, containing `[target_height, target_width, -1]`. Provide as input to +/// `tf.slice`. +/// - bboxes: 3-D with shape `[1, 1, 4]` containing the distorted bounding box. +/// Provide as input to `tf.image.draw_bounding_boxes`. +@inlinable @inline(__always) +public static func sampleDistortedBoundingBoxV2( + imageSize: Tensor, + boundingBoxes: Tensor, + minObjectCovered: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0, + aspectRatioRange: [Double] = [0.75, 1.33], + areaRange: [Double] = [0.05, 1], + maxAttempts: Int64 = 100, + useImageIfNoBoundingBoxes: Bool = false +) -> (begin: Tensor, size: Tensor, bboxes: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("SampleDistortedBoundingBoxV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("aspect_ratio_range", aspectRatioRange) + op.updateAttribute("area_range", areaRange) + op.updateAttribute("max_attempts", maxAttempts) + op.updateAttribute("use_image_if_no_bounding_boxes", useImageIfNoBoundingBoxes) + op.addInput(imageSize) + op.addInput(boundingBoxes) + op.addInput(minObjectCovered) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Creates a dataset that contains `rate` elements from the `input_dataset`. +/// +/// - Parameters: +/// - rate: A scalar representing the sample rate of elements from the `input_dataset` +/// that should be taken. +/// - seed: A scalar representing seed of random number generator. +/// - seed2: A scalar representing seed2 of random number generator. +@inlinable @inline(__always) +public static func samplingDataset( + inputDataset: VariantHandle, + rate: Tensor, + seed: Tensor, + seed2: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("SamplingDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(rate) + op.addInput(seed) + op.addInput(seed2) + return op.execute(Int(1)) +} + +/// Saves the input tensors to disk. +/// +/// The size of `tensor_names` must match the number of tensors in `data`. `data[i]` +/// is written to `filename` with name `tensor_names[i]`. +/// +/// See also `SaveSlices`. +/// +/// - Parameters: +/// - filename: Must have a single element. The name of the file to which we write +/// the tensor. +/// - tensor_names: Shape `[N]`. The names of the tensors to be saved. +/// - data: `N` tensors to save. +@inlinable @inline(__always) +public static func save( + filename: StringTensor, + tensorNames: StringTensor, + data: T +) { + let nOutputs = 0 + let op = makeOp("Save", nOutputs) + op.updateAttribute("T", data._typeList) + op.addInput(filename) + op.addInput(tensorNames) + op.addInputList(data) + op.execute() +} + +/// Saves input tensors slices to disk. +/// +/// This is like `Save` except that tensors can be listed in the saved file as being +/// a slice of a larger tensor. `shapes_and_slices` specifies the shape of the +/// larger tensor and the slice that this tensor covers. `shapes_and_slices` must +/// have as many elements as `tensor_names`. +/// +/// Elements of the `shapes_and_slices` input must either be: +/// +/// * The empty string, in which case the corresponding tensor is +/// saved normally. +/// * A string of the form `dim0 dim1 ... dimN-1 slice-spec` where the +/// `dimI` are the dimensions of the larger tensor and `slice-spec` +/// specifies what part is covered by the tensor to save. +/// +/// `slice-spec` itself is a `:`-separated list: `slice0:slice1:...:sliceN-1` +/// where each `sliceI` is either: +/// +/// * The string `-` meaning that the slice covers all indices of this dimension +/// * `start,length` where `start` and `length` are integers. In that +/// case the slice covers `length` indices starting at `start`. +/// +/// See also `Save`. +/// +/// - Parameters: +/// - filename: Must have a single element. The name of the file to which we write the +/// tensor. +/// - tensor_names: Shape `[N]`. The names of the tensors to be saved. +/// - shapes_and_slices: Shape `[N]`. The shapes and slice specifications to use when +/// saving the tensors. +/// - data: `N` tensors to save. +@inlinable @inline(__always) +public static func saveSlices( + filename: StringTensor, + tensorNames: StringTensor, + shapesAndSlices: StringTensor, + data: T +) { + let nOutputs = 0 + let op = makeOp("SaveSlices", nOutputs) + op.updateAttribute("T", data._typeList) + op.addInput(filename) + op.addInput(tensorNames) + op.addInput(shapesAndSlices) + op.addInputList(data) + op.execute() +} + +/// Saves tensors in V2 checkpoint format. +/// +/// By default, saves the named tensors in full. If the caller wishes to save +/// specific slices of full tensors, "shape_and_slices" should be non-empty strings +/// and correspondingly well-formed. +/// +/// - Parameters: +/// - prefix: Must have a single element. The prefix of the V2 checkpoint to which we +/// write the tensors. +/// - tensor_names: shape {N}. The names of the tensors to be saved. +/// - shape_and_slices: shape {N}. The slice specs of the tensors to be saved. +/// Empty strings indicate that they are non-partitioned tensors. +/// - tensors: `N` tensors to save. +@inlinable @inline(__always) +public static func saveV2( + prefix: StringTensor, + tensorNames: StringTensor, + shapeAndSlices: StringTensor, + tensors: Dtypes +) { + let nOutputs = 0 + let op = makeOp("SaveV2", nOutputs) + op.updateAttribute("dtypes", tensors._typeList) + op.addInput(prefix) + op.addInput(tensorNames) + op.addInput(shapeAndSlices) + op.addInputList(tensors) + op.execute() +} + +/// Outputs a `Summary` protocol buffer with scalar values. +/// +/// The input `tags` and `values` must have the same shape. The generated summary +/// has a summary value for each tag-value pair in `tags` and `values`. +/// +/// - Parameters: +/// - tags: Tags for the summary. +/// - values: Same shape as `tags. Values for the summary. +/// +/// - Output summary: Scalar. Serialized `Summary` protocol buffer. +@inlinable @inline(__always) +public static func scalarSummary( + tags: StringTensor, + _ values: Tensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("ScalarSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(tags) + op.addInput(values) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func scaleAndTranslate( + images: Tensor, + size: Tensor, + scale: Tensor, + translation: Tensor, + kernelType: String = "lanczos3", + antialias: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ScaleAndTranslate", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("kernel_type", kernelType) + op.updateAttribute("antialias", antialias) + op.addInput(images) + op.addInput(size) + op.addInput(scale) + op.addInput(translation) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func scaleAndTranslateGrad( + grads: Tensor, + originalImage: Tensor, + scale: Tensor, + translation: Tensor, + kernelType: String = "lanczos3", + antialias: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ScaleAndTranslateGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("kernel_type", kernelType) + op.updateAttribute("antialias", antialias) + op.addInput(grads) + op.addInput(originalImage) + op.addInput(scale) + op.addInput(translation) + return op.execute(Int(1)) +} + +/// Scatter `updates` into a new tensor according to `indices`. +/// +/// Creates a new tensor by applying sparse `updates` to individual values or +/// slices within a tensor (initially zero for numeric, empty for string) of +/// the given `shape` according to indices. This operator is the inverse of the +/// `tf.gather_nd` operator which extracts values or slices from a given tensor. +/// +/// This operation is similar to tensor_scatter_add, except that the tensor is +/// zero-initialized. Calling `tf.scatter_nd(indices, values, shape)` is identical +/// to `tensor_scatter_add(tf.zeros(shape, values.dtype), indices, values)` +/// +/// If `indices` contains duplicates, then their updates are accumulated (summed). +/// +/// **WARNING**: The order in which updates are applied is nondeterministic, so the +/// output will be nondeterministic if `indices` contains duplicates -- because +/// of some numerical approximation issues, numbers summed in different order +/// may yield different results. +/// +/// `indices` is an integer tensor containing indices into a new tensor of shape +/// `shape`. The last dimension of `indices` can be at most the rank of `shape`: +/// +/// indices.shape[-1] <= shape.rank +/// +/// The last dimension of `indices` corresponds to indices into elements +/// (if `indices.shape[-1] = shape.rank`) or slices +/// (if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of +/// `shape`. `updates` is a tensor with shape +/// +/// indices.shape[:-1] + shape[indices.shape[-1]:] +/// +/// The simplest form of scatter is to insert individual elements in a tensor by +/// index. For example, say we want to insert 4 scattered elements in a rank-1 +/// tensor with 8 elements. +/// +///
+/// +///
+/// +/// In Python, this scatter operation would look like this: +/// +/// ```python +/// indices = tf.constant([[4], [3], [1], [7]]) +/// updates = tf.constant([9, 10, 11, 12]) +/// shape = tf.constant([8]) +/// scatter = tf.scatter_nd(indices, updates, shape) +/// with tf.Session() as sess: +/// print(sess.run(scatter)) +/// ``` +/// +/// The resulting tensor would look like this: +/// +/// [0, 11, 0, 10, 9, 0, 0, 12] +/// +/// We can also, insert entire slices of a higher rank tensor all at once. For +/// example, if we wanted to insert two slices in the first dimension of a +/// rank-3 tensor with two matrices of new values. +/// +///
+/// +///
+/// +/// In Python, this scatter operation would look like this: +/// +/// ```python +/// indices = tf.constant([[0], [2]]) +/// updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6], +/// [7, 7, 7, 7], [8, 8, 8, 8]], +/// [[5, 5, 5, 5], [6, 6, 6, 6], +/// [7, 7, 7, 7], [8, 8, 8, 8]]]) +/// shape = tf.constant([4, 4, 4]) +/// scatter = tf.scatter_nd(indices, updates, shape) +/// with tf.Session() as sess: +/// print(sess.run(scatter)) +/// ``` +/// +/// The resulting tensor would look like this: +/// +/// [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], +/// [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], +/// [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], +/// [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]] +/// +/// Note that on CPU, if an out of bound index is found, an error is returned. +/// On GPU, if an out of bound index is found, the index is ignored. +/// +/// - Parameters: +/// - indices: Index tensor. +/// - updates: Updates to scatter into output. +/// - shape: 1-D. The shape of the resulting tensor. +/// +/// - Output output: A new tensor with the given shape and updates applied according +/// to the indices. +@inlinable @inline(__always) +public static func scatterNd< + T: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + indices: Tensor, + updates: Tensor, + shape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ScatterNd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(indices) + op.addInput(updates) + op.addInput(shape) + return op.execute(Int(1)) +} + +/// Applies sparse addition to `input` using individual values or slices +/// +/// from `updates` according to indices `indices`. The updates are non-aliasing: +/// `input` is only modified in-place if no other operations will use it. +/// Otherwise, a copy of `input` is made. This operation has a gradient with +/// respect to both `input` and `updates`. +/// +/// `input` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. +/// +/// `indices` must be integer tensor, containing indices into `input`. +/// It must be shape \\([d_0, ..., d_{Q-2}, K]\\) where `0 < K <= P`. +/// +/// The innermost dimension of `indices` (with length `K`) corresponds to +/// indices into elements (if `K = P`) or `(P-K)`-dimensional slices +/// (if `K < P`) along the `K`th dimension of `input`. +/// +/// `updates` is `Tensor` of rank `Q-1+P-K` with shape: +/// +/// $$[d_0, ..., d_{Q-2}, input.shape[K], ..., input.shape[P-1]].$$ +/// +/// For example, say we want to add 4 scattered elements to a rank-1 tensor to 8 +/// elements. In Python, that addition would look like this: +/// +/// input = tf.constant([1, 2, 3, 4, 5, 6, 7, 8]) +/// indices = tf.constant([[4], [3], [1], [7]]) +/// updates = tf.constant([9, 10, 11, 12]) +/// output = tf.scatter_nd_non_aliasing_add(input, indices, updates) +/// with tf.Session() as sess: +/// print(sess.run(output)) +/// +/// The resulting value `output` would look like this: +/// +/// [1, 13, 3, 14, 14, 6, 7, 20] +/// +/// See `tf.scatter_nd` for more details about how to make updates to slices. +/// +/// - Parameters: +/// - input: A Tensor. +/// - indices: A Tensor. Must be one of the following types: `int32`, `int64`. +/// A tensor of indices into `input`. +/// - updates: A Tensor. Must have the same type as ref. A tensor of updated values +/// to add to `input`. +/// +/// - Output output: A `Tensor` with the same shape as `input`, containing values of `input` +/// updated with `updates`. +@inlinable @inline(__always) +public static func scatterNdNonAliasingAdd< + T: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + indices: Tensor, + updates: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ScatterNdNonAliasingAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(input) + op.addInput(indices) + op.addInput(updates) + return op.execute(Int(1)) +} + +/// Computes fingerprints of the input strings. +/// +/// - Parameter input: vector of strings to compute fingerprints on. +/// +/// - Output output: a (N,2) shaped matrix where N is the number of elements in the input +/// vector. Each row contains the low and high parts of the fingerprint. +@inlinable @inline(__always) +public static func sdcaFprint( + _ input: StringTensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SdcaFprint", nOutputs) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for +/// +/// linear models with L1 + L2 regularization. As global optimization objective is +/// strongly-convex, the optimizer optimizes the dual objective at each step. The +/// optimizer applies each update one example at a time. Examples are sampled +/// uniformly, and the optimizer is learning rate free and enjoys linear convergence +/// rate. +/// +/// [Proximal Stochastic Dual Coordinate Ascent](http://arxiv.org/pdf/1211.2717v1.pdf).
+/// Shai Shalev-Shwartz, Tong Zhang. 2012 +/// +/// $$Loss Objective = \sum f_{i} (wx_{i}) + (l2 / 2) * |w|^2 + l1 * |w|$$ +/// +/// [Adding vs. Averaging in Distributed Primal-Dual Optimization](http://arxiv.org/abs/1502.03508).
+/// Chenxin Ma, Virginia Smith, Martin Jaggi, Michael I. Jordan, +/// Peter Richtarik, Martin Takac. 2015 +/// +/// [Stochastic Dual Coordinate Ascent with Adaptive Probabilities](https://arxiv.org/abs/1502.08053).
+/// Dominik Csiba, Zheng Qu, Peter Richtarik. 2015 +/// +/// - Parameters: +/// - sparse_example_indices: a list of vectors which contain example indices. +/// - sparse_feature_indices: a list of vectors which contain feature indices. +/// - sparse_feature_values: a list of vectors which contains feature value +/// associated with each feature group. +/// - dense_features: a list of matrices which contains the dense feature values. +/// - example_weights: a vector which contains the weight associated with each +/// example. +/// - example_labels: a vector which contains the label/target associated with each +/// example. +/// - sparse_indices: a list of vectors where each value is the indices which has +/// corresponding weights in sparse_weights. This field maybe omitted for the +/// dense approach. +/// - sparse_weights: a list of vectors where each value is the weight associated with +/// a sparse feature group. +/// - dense_weights: a list of vectors where the values are the weights associated +/// with a dense feature group. +/// - example_state_data: a list of vectors containing the example state data. +/// +/// - Attrs: +/// - loss_type: Type of the primal loss. Currently SdcaSolver supports logistic, +/// squared and hinge losses. +/// - adaptative: Whether to use Adaptive SDCA for the inner loop. +/// - num_sparse_features: Number of sparse feature groups to train on. +/// - num_sparse_features_with_values: Number of sparse feature groups with values +/// associated with it, otherwise implicitly treats values as 1.0. +/// - num_dense_features: Number of dense feature groups to train on. +/// - l1: Symmetric l1 regularization strength. +/// - l2: Symmetric l2 regularization strength. +/// - num_loss_partitions: Number of partitions of the global loss function. +/// - num_inner_iterations: Number of iterations per mini-batch. +/// +/// - Outputs: +/// - out_example_state_data: a list of vectors containing the updated example state +/// data. +/// - out_delta_sparse_weights: a list of vectors where each value is the delta +/// weights associated with a sparse feature group. +/// - out_delta_dense_weights: a list of vectors where the values are the delta +/// weights associated with a dense feature group. +@inlinable @inline(__always) +public static func sdcaOptimizer( + sparseExampleIndices: [Tensor], + sparseFeatureIndices: [Tensor], + sparseFeatureValues: [Tensor], + denseFeatures: [Tensor], + exampleWeights: Tensor, + exampleLabels: Tensor, + sparseIndices: [Tensor], + sparseWeights: [Tensor], + denseWeights: [Tensor], + exampleStateData: Tensor, + lossType: LossType, + adaptative: Bool = false, + l1: Double, + l2: Double, + numLossPartitions: Int64, + numInnerIterations: Int64 +) -> (outExampleStateData: Tensor, outDeltaSparseWeights: [Tensor], outDeltaDenseWeights: [Tensor]) { + let nOutputs = Int(1) + Int(sparseExampleIndices.count) + Int(denseFeatures.count) + let op = makeOp("SdcaOptimizer", nOutputs) + op.updateAttribute("loss_type", lossType.cName) + op.updateAttribute("adaptative", adaptative) + op.updateAttribute("num_sparse_features", sparseExampleIndices.count) + op.updateAttribute("num_sparse_features_with_values", sparseFeatureValues.count) + op.updateAttribute("num_dense_features", denseFeatures.count) + op.updateAttribute("l1", l1) + op.updateAttribute("l2", l2) + op.updateAttribute("num_loss_partitions", numLossPartitions) + op.updateAttribute("num_inner_iterations", numInnerIterations) + op.addInputList(sparseExampleIndices) + op.addInputList(sparseFeatureIndices) + op.addInputList(sparseFeatureValues) + op.addInputList(denseFeatures) + op.addInput(exampleWeights) + op.addInput(exampleLabels) + op.addInputList(sparseIndices) + op.addInputList(sparseWeights) + op.addInputList(denseWeights) + op.addInput(exampleStateData) + return op.execute(Int(1), Int(sparseExampleIndices.count), Int(denseFeatures.count)) +} + +/// Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for +/// +/// linear models with L1 + L2 regularization. As global optimization objective is +/// strongly-convex, the optimizer optimizes the dual objective at each step. The +/// optimizer applies each update one example at a time. Examples are sampled +/// uniformly, and the optimizer is learning rate free and enjoys linear convergence +/// rate. +/// +/// [Proximal Stochastic Dual Coordinate Ascent](http://arxiv.org/pdf/1211.2717v1.pdf).
+/// Shai Shalev-Shwartz, Tong Zhang. 2012 +/// +/// $$Loss Objective = \sum f_{i} (wx_{i}) + (l2 / 2) * |w|^2 + l1 * |w|$$ +/// +/// [Adding vs. Averaging in Distributed Primal-Dual Optimization](http://arxiv.org/abs/1502.03508).
+/// Chenxin Ma, Virginia Smith, Martin Jaggi, Michael I. Jordan, +/// Peter Richtarik, Martin Takac. 2015 +/// +/// [Stochastic Dual Coordinate Ascent with Adaptive Probabilities](https://arxiv.org/abs/1502.08053).
+/// Dominik Csiba, Zheng Qu, Peter Richtarik. 2015 +/// +/// - Parameters: +/// - sparse_example_indices: a list of vectors which contain example indices. +/// - sparse_feature_indices: a list of vectors which contain feature indices. +/// - sparse_feature_values: a list of vectors which contains feature value +/// associated with each feature group. +/// - dense_features: a list of matrices which contains the dense feature values. +/// - example_weights: a vector which contains the weight associated with each +/// example. +/// - example_labels: a vector which contains the label/target associated with each +/// example. +/// - sparse_indices: a list of vectors where each value is the indices which has +/// corresponding weights in sparse_weights. This field maybe omitted for the +/// dense approach. +/// - sparse_weights: a list of vectors where each value is the weight associated with +/// a sparse feature group. +/// - dense_weights: a list of vectors where the values are the weights associated +/// with a dense feature group. +/// - example_state_data: a list of vectors containing the example state data. +/// +/// - Attrs: +/// - loss_type: Type of the primal loss. Currently SdcaSolver supports logistic, +/// squared and hinge losses. +/// - adaptive: Whether to use Adaptive SDCA for the inner loop. +/// - num_sparse_features: Number of sparse feature groups to train on. +/// - num_sparse_features_with_values: Number of sparse feature groups with values +/// associated with it, otherwise implicitly treats values as 1.0. +/// - num_dense_features: Number of dense feature groups to train on. +/// - l1: Symmetric l1 regularization strength. +/// - l2: Symmetric l2 regularization strength. +/// - num_loss_partitions: Number of partitions of the global loss function. +/// - num_inner_iterations: Number of iterations per mini-batch. +/// +/// - Outputs: +/// - out_example_state_data: a list of vectors containing the updated example state +/// data. +/// - out_delta_sparse_weights: a list of vectors where each value is the delta +/// weights associated with a sparse feature group. +/// - out_delta_dense_weights: a list of vectors where the values are the delta +/// weights associated with a dense feature group. +@inlinable @inline(__always) +public static func sdcaOptimizerV2( + sparseExampleIndices: [Tensor], + sparseFeatureIndices: [Tensor], + sparseFeatureValues: [Tensor], + denseFeatures: [Tensor], + exampleWeights: Tensor, + exampleLabels: Tensor, + sparseIndices: [Tensor], + sparseWeights: [Tensor], + denseWeights: [Tensor], + exampleStateData: Tensor, + lossType: LossType, + adaptive: Bool = false, + l1: Double, + l2: Double, + numLossPartitions: Int64, + numInnerIterations: Int64 +) -> (outExampleStateData: Tensor, outDeltaSparseWeights: [Tensor], outDeltaDenseWeights: [Tensor]) { + let nOutputs = Int(1) + Int(sparseExampleIndices.count) + Int(denseFeatures.count) + let op = makeOp("SdcaOptimizerV2", nOutputs) + op.updateAttribute("loss_type", lossType.cName) + op.updateAttribute("adaptive", adaptive) + op.updateAttribute("num_sparse_features", sparseExampleIndices.count) + op.updateAttribute("num_sparse_features_with_values", sparseFeatureValues.count) + op.updateAttribute("num_dense_features", denseFeatures.count) + op.updateAttribute("l1", l1) + op.updateAttribute("l2", l2) + op.updateAttribute("num_loss_partitions", numLossPartitions) + op.updateAttribute("num_inner_iterations", numInnerIterations) + op.addInputList(sparseExampleIndices) + op.addInputList(sparseFeatureIndices) + op.addInputList(sparseFeatureValues) + op.addInputList(denseFeatures) + op.addInput(exampleWeights) + op.addInput(exampleLabels) + op.addInputList(sparseIndices) + op.addInputList(sparseWeights) + op.addInputList(denseWeights) + op.addInput(exampleStateData) + return op.execute(Int(1), Int(sparseExampleIndices.count), Int(denseFeatures.count)) +} + +/// Computes the maximum along segments of a tensor. +/// +/// Read +/// [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) +/// for an explanation of segments. +/// +/// Computes a tensor such that +/// \\(output_i = \max_j(data_j)\\) where `max` is over `j` such +/// that `segment_ids[j] == i`. +/// +/// If the max is empty for a given segment ID `i`, `output[i] = 0`. +/// +///
+/// +///
+/// +/// For example: +/// +/// ``` +/// c = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]]) +/// tf.segment_max(c, tf.constant([0, 0, 1])) +/// # ==> [[4, 3, 3, 4], +/// # [5, 6, 7, 8]] +/// ``` +/// +/// +/// - Parameter segment_ids: A 1-D tensor whose size is equal to the size of `data`'s +/// first dimension. Values should be sorted and can be repeated. +/// +/// - Output output: Has same shape as data, except for dimension 0 which +/// has size `k`, the number of segments. +@inlinable @inline(__always) +public static func segmentMax< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + segmentIds: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SegmentMax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + return op.execute(Int(1)) +} + +/// Computes the mean along segments of a tensor. +/// +/// Read +/// [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) +/// for an explanation of segments. +/// +/// Computes a tensor such that +/// \\(output_i = \frac{\sum_j data_j}{N}\\) where `mean` is +/// over `j` such that `segment_ids[j] == i` and `N` is the total number of +/// values summed. +/// +/// If the mean is empty for a given segment ID `i`, `output[i] = 0`. +/// +///
+/// +///
+/// +/// For example: +/// +/// ``` +/// c = tf.constant([[1.0,2,3,4], [4, 3, 2, 1], [5,6,7,8]]) +/// tf.segment_mean(c, tf.constant([0, 0, 1])) +/// # ==> [[2.5, 2.5, 2.5, 2.5], +/// # [5, 6, 7, 8]] +/// ``` +/// +/// +/// - Parameter segment_ids: A 1-D tensor whose size is equal to the size of `data`'s +/// first dimension. Values should be sorted and can be repeated. +/// +/// - Output output: Has same shape as data, except for dimension 0 which +/// has size `k`, the number of segments. +@inlinable @inline(__always) +public static func segmentMean< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + segmentIds: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SegmentMean", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + return op.execute(Int(1)) +} + +/// Computes the minimum along segments of a tensor. +/// +/// Read +/// [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) +/// for an explanation of segments. +/// +/// Computes a tensor such that +/// \\(output_i = \min_j(data_j)\\) where `min` is over `j` such +/// that `segment_ids[j] == i`. +/// +/// If the min is empty for a given segment ID `i`, `output[i] = 0`. +/// +///
+/// +///
+/// +/// For example: +/// +/// ``` +/// c = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]]) +/// tf.segment_min(c, tf.constant([0, 0, 1])) +/// # ==> [[1, 2, 2, 1], +/// # [5, 6, 7, 8]] +/// ``` +/// +/// - Parameter segment_ids: A 1-D tensor whose size is equal to the size of `data`'s +/// first dimension. Values should be sorted and can be repeated. +/// +/// - Output output: Has same shape as data, except for dimension 0 which +/// has size `k`, the number of segments. +@inlinable @inline(__always) +public static func segmentMin< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + segmentIds: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SegmentMin", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + return op.execute(Int(1)) +} + +/// Computes the product along segments of a tensor. +/// +/// Read +/// [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) +/// for an explanation of segments. +/// +/// Computes a tensor such that +/// \\(output_i = \prod_j data_j\\) where the product is over `j` such +/// that `segment_ids[j] == i`. +/// +/// If the product is empty for a given segment ID `i`, `output[i] = 1`. +/// +///
+/// +///
+/// +/// For example: +/// +/// ``` +/// c = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]]) +/// tf.segment_prod(c, tf.constant([0, 0, 1])) +/// # ==> [[4, 6, 6, 4], +/// # [5, 6, 7, 8]] +/// ``` +/// +/// +/// - Parameter segment_ids: A 1-D tensor whose size is equal to the size of `data`'s +/// first dimension. Values should be sorted and can be repeated. +/// +/// - Output output: Has same shape as data, except for dimension 0 which +/// has size `k`, the number of segments. +@inlinable @inline(__always) +public static func segmentProd< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + segmentIds: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SegmentProd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + return op.execute(Int(1)) +} + +/// Computes the sum along segments of a tensor. +/// +/// Read +/// [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) +/// for an explanation of segments. +/// +/// Computes a tensor such that +/// \\(output_i = \sum_j data_j\\) where sum is over `j` such +/// that `segment_ids[j] == i`. +/// +/// If the sum is empty for a given segment ID `i`, `output[i] = 0`. +/// +///
+/// +///
+/// +/// For example: +/// +/// ``` +/// c = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]]) +/// tf.segment_sum(c, tf.constant([0, 0, 1])) +/// # ==> [[5, 5, 5, 5], +/// # [5, 6, 7, 8]] +/// ``` +/// +/// +/// - Parameter segment_ids: A 1-D tensor whose size is equal to the size of `data`'s +/// first dimension. Values should be sorted and can be repeated. +/// +/// - Output output: Has same shape as data, except for dimension 0 which +/// has size `k`, the number of segments. +@inlinable @inline(__always) +public static func segmentSum< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + segmentIds: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SegmentSum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + return op.execute(Int(1)) +} + +/// Selects elements from `x` or `y`, depending on `condition`. +/// +/// The `x`, and `y` tensors must all have the same shape, and the +/// output will also have that shape. +/// +/// The `condition` tensor must be a scalar if `x` and `y` are scalars. +/// If `x` and `y` are vectors or higher rank, then `condition` must be either a +/// scalar, a vector with size matching the first dimension of `x`, or must have +/// the same shape as `x`. +/// +/// The `condition` tensor acts as a mask that chooses, based on the value at each +/// element, whether the corresponding element / row in the output should be +/// taken from `x` (if true) or `y` (if false). +/// +/// If `condition` is a vector and `x` and `y` are higher rank matrices, then +/// it chooses which row (outer dimension) to copy from `x` and `y`. +/// If `condition` has the same shape as `x` and `y`, then it chooses which +/// element to copy from `x` and `y`. +/// +/// For example: +/// +/// ```python +/// # 'condition' tensor is [[True, False] +/// # [False, True]] +/// # 't' is [[1, 2], +/// # [3, 4]] +/// # 'e' is [[5, 6], +/// # [7, 8]] +/// select(condition, t, e) # => [[1, 6], [7, 4]] +/// +/// +/// # 'condition' tensor is [True, False] +/// # 't' is [[1, 2], +/// # [3, 4]] +/// # 'e' is [[5, 6], +/// # [7, 8]] +/// select(condition, t, e) ==> [[1, 2], +/// [7, 8]] +/// +/// ``` +/// +/// - Parameters: +/// - t: = A `Tensor` which may have the same shape as `condition`. +/// If `condition` is rank 1, `x` may have higher rank, +/// but its first dimension must match the size of `condition`. +/// - e: = A `Tensor` with the same type and shape as `x`. +/// +/// - Output output: = A `Tensor` with the same type and shape as `x` and `y`. +@inlinable @inline(__always) +public static func select( + condition: Tensor, + t: Tensor, + e: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Select", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(condition) + op.addInput(t) + op.addInput(e) + return op.execute(Int(1)) +} + +/// Computes the Eigen Decomposition of a batch of square self-adjoint matrices. +/// +/// The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions +/// form square matrices, with the same constraints as the single matrix +/// SelfAdjointEig. +/// +/// The result is a [..., M+1, M] matrix with [..., 0,:] containing the +/// eigenvalues, and subsequent [...,1:, :] containing the eigenvectors. The eigenvalues +/// are sorted in non-decreasing order. +/// +/// - Parameter input: Shape is `[..., M, M]`. +/// +/// - Output output: Shape is `[..., M+1, M]`. +@inlinable @inline(__always) +public static func selfAdjointEig( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SelfAdjointEig", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Computes the eigen decomposition of one or more square self-adjoint matrices. +/// +/// Computes the eigenvalues and (optionally) eigenvectors of each inner matrix in +/// `input` such that `input[..., :, :] = v[..., :, :] * diag(e[..., :])`. The eigenvalues +/// are sorted in non-decreasing order. +/// +/// ```python +/// # a is a tensor. +/// # e is a tensor of eigenvalues. +/// # v is a tensor of eigenvectors. +/// e, v = self_adjoint_eig(a) +/// e = self_adjoint_eig(a, compute_v=False) +/// ``` +/// +/// - Parameter input: `Tensor` input of shape `[N, N]`. +/// +/// - Attr compute_v: If `True` then eigenvectors will be computed and returned in `v`. +/// Otherwise, only the eigenvalues will be computed. +/// +/// - Outputs: +/// - e: Eigenvalues. Shape is `[N]`. +/// - v: Eigenvectors. Shape is `[N, N]`. +@inlinable @inline(__always) +public static func selfAdjointEigV2( + _ input: Tensor, + computeV: Bool = true +) -> (e: Tensor, v: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("SelfAdjointEigV2", nOutputs) + op.updateAttribute("compute_v", computeV) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) +} + +/// Computes scaled exponential linear: `scale * alpha * (exp(features) - 1)` +/// +/// if < 0, `scale * features` otherwise. +/// +/// To be used together with +/// `initializer = tf.variance_scaling_initializer(factor=1.0, mode='FAN_IN')`. +/// For correct dropout, use `tf.contrib.nn.alpha_dropout`. +/// +/// See [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515) +@inlinable @inline(__always) +public static func selu( + features: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Selu", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) +} + +/// Computes gradients for the scaled exponential linear (Selu) operation. +/// +/// - Parameters: +/// - gradients: The backpropagated gradients to the corresponding Selu operation. +/// - outputs: The outputs of the corresponding Selu operation. +/// +/// - Output backprops: The gradients: `gradients * (outputs + scale * alpha)` +/// if outputs < 0, `scale * gradients` otherwise. +@inlinable @inline(__always) +public static func seluGrad( + gradients: Tensor, + outputs: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SeluGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(outputs) + return op.execute(Int(1)) +} + +/// Performs gradient updates of embedding tables. +/// +/// - Parameters: +/// - inputs: A TensorList of gradients with which to update embedding tables. +/// This argument has the same length and shapes as the return value of +/// RecvTPUEmbeddingActivations, but contains gradients of the model's loss +/// with respect to the embedding activations. The embedding tables are updated +/// from these gradients via the optimizer specified in the TPU embedding +/// configuration given to tpu.initialize_system. +/// - learning_rates: A TensorList of float32 scalars, one for each dynamic learning +/// rate tag: see the comments in +/// //third_party/tensorflow/core/protobuf/tpu/optimization_parameters.proto. +/// Multiple tables can share the same dynamic learning rate tag as specified +/// in the configuration. If the learning rates for all tables are constant, +/// this list should be empty. +/// +/// - Attr config: Serialized TPUEmbeddingConfiguration proto. +@inlinable @inline(__always) +public static func sendTPUEmbeddingGradients( + inputs: [Tensor], + learningRates: [Tensor], + config: String +) { + let nOutputs = 0 + let op = makeOp("SendTPUEmbeddingGradients", nOutputs) + op.updateAttribute("N", inputs.count) + op.updateAttribute("NN", learningRates.count) + op.updateAttribute("config", config) + op.addInputList(inputs) + op.addInputList(learningRates) + op.execute() +} + +/// Converts the given `resource_handle` representing an iterator to a variant tensor. +/// +/// - Parameter resource_handle: A handle to an iterator resource. +/// +/// - Output serialized: A variant tensor storing the state of the iterator contained in the +/// resource. +@inlinable @inline(__always) +public static func serializeIterator( + resourceHandle: ResourceHandle +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("SerializeIterator", nOutputs) + op.addInput(resourceHandle) + return op.execute(Int(1)) +} + +/// Serialize an `N`-minibatch `SparseTensor` into an `[N, 3]` `Tensor` object. +/// +/// The `SparseTensor` must have rank `R` greater than 1, and the first dimension +/// is treated as the minibatch dimension. Elements of the `SparseTensor` +/// must be sorted in increasing order of this first dimension. The serialized +/// `SparseTensor` objects going into each row of `serialized_sparse` will have +/// rank `R-1`. +/// +/// The minibatch size `N` is extracted from `sparse_shape[0]`. +/// +/// - Parameters: +/// - sparse_indices: 2-D. The `indices` of the minibatch `SparseTensor`. +/// - sparse_values: 1-D. The `values` of the minibatch `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the minibatch `SparseTensor`. +/// +/// - Attr out_type: The `dtype` to use for serialization; the supported types are `string` +/// (default) and `variant`. +@inlinable @inline(__always) +public static func serializeManySparse< + T: TensorFlowScalar, + OutType: TensorFlowScalar +>( + sparseIndices: Tensor, + sparseValues: Tensor, + sparseShape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SerializeManySparse", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(sparseIndices) + op.addInput(sparseValues) + op.addInput(sparseShape) + return op.execute(Int(1)) +} + +/// Serialize an `N`-minibatch `SparseTensor` into an `[N, 3]` `Tensor` object. +/// +/// The `SparseTensor` must have rank `R` greater than 1, and the first dimension +/// is treated as the minibatch dimension. Elements of the `SparseTensor` +/// must be sorted in increasing order of this first dimension. The serialized +/// `SparseTensor` objects going into each row of `serialized_sparse` will have +/// rank `R-1`. +/// +/// The minibatch size `N` is extracted from `sparse_shape[0]`. +/// +/// - Parameters: +/// - sparse_indices: 2-D. The `indices` of the minibatch `SparseTensor`. +/// - sparse_values: 1-D. The `values` of the minibatch `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the minibatch `SparseTensor`. +/// +/// - Attr out_type: The `dtype` to use for serialization; the supported types are `string` +/// (default) and `variant`. +@inlinable @inline(__always) +public static func serializeManySparse( + sparseIndices: Tensor, + sparseValues: Tensor, + sparseShape: Tensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("SerializeManySparse", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", TensorDataType(TF_STRING)) + op.addInput(sparseIndices) + op.addInput(sparseValues) + op.addInput(sparseShape) + return op.execute(Int(1)) +} + +/// Serialize a `SparseTensor` into a `[3]` `Tensor` object. +/// +/// - Parameters: +/// - sparse_indices: 2-D. The `indices` of the `SparseTensor`. +/// - sparse_values: 1-D. The `values` of the `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the `SparseTensor`. +/// +/// - Attr out_type: The `dtype` to use for serialization; the supported types are `string` +/// (default) and `variant`. +@inlinable @inline(__always) +public static func serializeSparse< + T: TensorFlowScalar, + OutType: TensorFlowScalar +>( + sparseIndices: Tensor, + sparseValues: Tensor, + sparseShape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SerializeSparse", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(sparseIndices) + op.addInput(sparseValues) + op.addInput(sparseShape) + return op.execute(Int(1)) +} + +/// Serialize a `SparseTensor` into a `[3]` `Tensor` object. +/// +/// - Parameters: +/// - sparse_indices: 2-D. The `indices` of the `SparseTensor`. +/// - sparse_values: 1-D. The `values` of the `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the `SparseTensor`. +/// +/// - Attr out_type: The `dtype` to use for serialization; the supported types are `string` +/// (default) and `variant`. +@inlinable @inline(__always) +public static func serializeSparse( + sparseIndices: Tensor, + sparseValues: Tensor, + sparseShape: Tensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("SerializeSparse", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", TensorDataType(TF_STRING)) + op.addInput(sparseIndices) + op.addInput(sparseValues) + op.addInput(sparseShape) + return op.execute(Int(1)) +} + +/// Transforms a Tensor into a serialized TensorProto proto. +/// +/// - Parameter tensor: A Tensor of type `T`. +/// +/// - Attr T: The type of the input tensor. +/// +/// - Output serialized: A serialized TensorProto proto of the input tensor. +@inlinable @inline(__always) +public static func serializeTensor( + _ tensor: Tensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("SerializeTensor", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(tensor) + return op.execute(Int(1)) +} + +/// Number of unique elements along last dimension of input `set`. +/// +/// Input `set` is a `SparseTensor` represented by `set_indices`, `set_values`, +/// and `set_shape`. The last dimension contains values in a set, duplicates are +/// allowed but ignored. +/// +/// If `validate_indices` is `True`, this op validates the order and range of `set` +/// indices. +/// +/// - Parameters: +/// - set_indices: 2D `Tensor`, indices of a `SparseTensor`. +/// - set_values: 1D `Tensor`, values of a `SparseTensor`. +/// - set_shape: 1D `Tensor`, shape of a `SparseTensor`. +/// +/// - Output size: For `set` ranked `n`, this is a `Tensor` with rank `n-1`, and the same 1st +/// `n-1` dimensions as `set`. Each value is the number of unique elements in +/// the corresponding `[0...n-1]` dimension of `set`. +@inlinable @inline(__always) +public static func setSize( + setIndices: Tensor, + setValues: Tensor, + setShape: Tensor, + validateIndices: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SetSize", nOutputs) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(setIndices) + op.addInput(setValues) + op.addInput(setShape) + return op.execute(Int(1)) +} + +/// Number of unique elements along last dimension of input `set`. +/// +/// Input `set` is a `SparseTensor` represented by `set_indices`, `set_values`, +/// and `set_shape`. The last dimension contains values in a set, duplicates are +/// allowed but ignored. +/// +/// If `validate_indices` is `True`, this op validates the order and range of `set` +/// indices. +/// +/// - Parameters: +/// - set_indices: 2D `Tensor`, indices of a `SparseTensor`. +/// - set_values: 1D `Tensor`, values of a `SparseTensor`. +/// - set_shape: 1D `Tensor`, shape of a `SparseTensor`. +/// +/// - Output size: For `set` ranked `n`, this is a `Tensor` with rank `n-1`, and the same 1st +/// `n-1` dimensions as `set`. Each value is the number of unique elements in +/// the corresponding `[0...n-1]` dimension of `set`. +@inlinable @inline(__always) +public static func setSize( + setIndices: Tensor, + setValues: StringTensor, + setShape: Tensor, + validateIndices: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SetSize", nOutputs) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(setIndices) + op.addInput(setValues) + op.addInput(setShape) + return op.execute(Int(1)) +} + +/// Returns the shape of a tensor. +/// +/// This operation returns a 1-D integer tensor representing the shape of `input`. +/// +/// For example: +/// +/// ``` +/// # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] +/// shape(t) ==> [2, 2, 3] +/// ``` +@inlinable @inline(__always) +public static func shape< + T: TensorFlowScalar, + OutType: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Shape", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Returns shape of tensors. +/// +/// This operation returns N 1-D integer tensors representing shape of `input[i]s`. +@inlinable @inline(__always) +public static func shapeN< + T: TensorFlowScalar, + OutType: BinaryInteger & TensorFlowScalar +>( + _ input: [Tensor] +) -> [Tensor] { + let nOutputs = Int(input.count) + let op = makeOp("ShapeN", nOutputs) + op.updateAttribute("N", input.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInputList(input) + return op.execute(Int(input.count)) +} + +/// Creates a `Dataset` that includes only 1/`num_shards` of this dataset. +/// +/// - Parameters: +/// - num_shards: An integer representing the number of shards operating in parallel. +/// - index: An integer representing the current worker index. +@inlinable @inline(__always) +public static func shardDataset( + inputDataset: VariantHandle, + numShards: Tensor, + index: Tensor, + requireNonEmpty: Bool = false, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ShardDataset", nOutputs) + op.updateAttribute("require_non_empty", requireNonEmpty) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(numShards) + op.addInput(index) + return op.execute(Int(1)) +} + +/// Generate a sharded filename. The filename is printf formatted as +/// +/// %s-%05d-of-%05d, basename, shard, num_shards. +@inlinable @inline(__always) +public static func shardedFilename( + basename: StringTensor, + shard: Tensor, + numShards: Tensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("ShardedFilename", nOutputs) + op.addInput(basename) + op.addInput(shard) + op.addInput(numShards) + return op.execute(Int(1)) +} + +/// Generate a glob pattern matching all sharded file names. +@inlinable @inline(__always) +public static func shardedFilespec( + basename: StringTensor, + numShards: Tensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("ShardedFilespec", nOutputs) + op.addInput(basename) + op.addInput(numShards) + return op.execute(Int(1)) +} + +/// Creates a dataset that shuffles and repeats elements from `input_dataset` +/// +/// pseudorandomly. +/// +/// - Parameters: +/// - buffer_size: The number of output elements to buffer in an iterator over +/// this dataset. Compare with the `min_after_dequeue` attr when creating a +/// `RandomShuffleQueue`. +/// - seed: A scalar seed for the random number generator. If either `seed` or +/// `seed2` is set to be non-zero, the random number generator is seeded +/// by the given seed. Otherwise, a random seed is used. +/// - seed2: A second scalar seed to avoid seed collision. +/// - count: A scalar representing the number of times the underlying dataset +/// should be repeated. The default is `-1`, which results in infinite repetition. +@inlinable @inline(__always) +public static func shuffleAndRepeatDataset( + inputDataset: VariantHandle, + bufferSize: Tensor, + seed: Tensor, + seed2: Tensor, + count: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ShuffleAndRepeatDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(bufferSize) + op.addInput(seed) + op.addInput(seed2) + op.addInput(count) + return op.execute(Int(1)) +} + +/// Creates a dataset that shuffles elements from `input_dataset` pseudorandomly. +/// +/// - Parameters: +/// - buffer_size: The number of output elements to buffer in an iterator over +/// this dataset. Compare with the `min_after_dequeue` attr when creating a +/// `RandomShuffleQueue`. +/// - seed: A scalar seed for the random number generator. If either `seed` or +/// `seed2` is set to be non-zero, the random number generator is seeded +/// by the given seed. Otherwise, a random seed is used. +/// - seed2: A second scalar seed to avoid seed collision. +/// +/// - Attr reshuffle_each_iteration: If true, each iterator over this dataset will be given +/// a different pseudorandomly generated seed, based on a sequence seeded by the +/// `seed` and `seed2` inputs. If false, each iterator will be given the same +/// seed, and repeated iteration over this dataset will yield the exact same +/// sequence of results. +@inlinable @inline(__always) +public static func shuffleDataset( + inputDataset: VariantHandle, + bufferSize: Tensor, + seed: Tensor, + seed2: Tensor, + reshuffleEachIteration: Bool = true, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ShuffleDataset", nOutputs) + op.updateAttribute("reshuffle_each_iteration", reshuffleEachIteration) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(bufferSize) + op.addInput(seed) + op.addInput(seed2) + return op.execute(Int(1)) +} + +/// Shuts down a running distributed TPU system. +/// +/// The op returns an error if no system is running. +@inlinable @inline(__always) +public static func shutdownDistributedTPU( +) { + let nOutputs = 0 + let op = makeOp("ShutdownDistributedTPU", nOutputs) + + op.execute() +} + +/// Computes sigmoid of `x` element-wise. +/// +/// Specifically, `y = 1 / (1 + exp(-x))`. +@inlinable @inline(__always) +public static func sigmoid( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Sigmoid", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the gradient of the sigmoid of `x` wrt its input. +/// +/// Specifically, `grad = dy * y * (1 - y)`, where `y = sigmoid(x)`, and +/// `dy` is the corresponding input gradient. +@inlinable @inline(__always) +public static func sigmoidGrad( + _ y: Tensor, + dy: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SigmoidGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(dy) + return op.execute(Int(1)) +} + +/// Returns an element-wise indication of the sign of a number. +/// +/// `y = sign(x) = -1` if `x < 0`; 0 if `x == 0`; 1 if `x > 0`. +/// +/// For complex numbers, `y = sign(x) = x / |x|` if `x != 0`, otherwise `y = 0`. +@inlinable @inline(__always) +public static func sign( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Sign", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func simple( + _ a: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Simple", nOutputs) + op.addInput(a) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func simpleStruct( + nA: Int64 +) -> [Tensor] { + let nOutputs = Int(nA) + let op = makeOp("SimpleStruct", nOutputs) + op.updateAttribute("n_a", nA) + return op.execute(Int(nA)) +} + +/// Computes sin of x element-wise. +@inlinable @inline(__always) +public static func sin( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Sin", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes hyperbolic sine of x element-wise. +@inlinable @inline(__always) +public static func sinh( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Sinh", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Returns the size of a tensor. +/// +/// This operation returns an integer representing the number of elements in +/// `input`. +/// +/// For example: +/// +/// ``` +/// # 't' is [[[1, 1,, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]] +/// size(t) ==> 12 +/// ``` +@inlinable @inline(__always) +public static func size< + T: TensorFlowScalar, + OutType: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Size", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Creates a dataset that skips `count` elements from the `input_dataset`. +/// +/// - Parameter count: A scalar representing the number of elements from the `input_dataset` +/// that should be skipped. If count is -1, skips everything. +@inlinable @inline(__always) +public static func skipDataset( + inputDataset: VariantHandle, + count: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("SkipDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(count) + return op.execute(Int(1)) +} + +/// Parses a text file and creates a batch of examples. +/// +/// - Attrs: +/// - filename: The corpus's text file name. +/// - batch_size: The size of produced batch. +/// - window_size: The number of words to predict to the left and right of the target. +/// - min_count: The minimum number of word occurrences for it to be included in the +/// vocabulary. +/// - subsample: Threshold for word occurrence. Words that appear with higher +/// frequency will be randomly down-sampled. Set to 0 to disable. +/// +/// - Outputs: +/// - vocab_word: A vector of words in the corpus. +/// - vocab_freq: Frequencies of words. Sorted in the non-ascending order. +/// - words_per_epoch: Number of words per epoch in the data file. +/// - current_epoch: The current epoch number. +/// - total_words_processed: The total number of words processed so far. +/// - examples: A vector of word ids. +/// - labels: A vector of word ids. +@inlinable @inline(__always) +public static func skipgram( + filename: String, + batchSize: Int64, + windowSize: Int64 = 5, + minCount: Int64 = 5, + subsample: Double = 0.001 +) -> (vocabWord: StringTensor, vocabFreq: Tensor, wordsPerEpoch: Tensor, currentEpoch: Tensor, totalWordsProcessed: Tensor, examples: Tensor, labels: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("Skipgram", nOutputs) + op.updateAttribute("filename", filename) + op.updateAttribute("batch_size", batchSize) + op.updateAttribute("window_size", windowSize) + op.updateAttribute("min_count", minCount) + op.updateAttribute("subsample", subsample) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) +} + +/// Return a slice from 'input'. +/// +/// The output tensor is a tensor with dimensions described by 'size' +/// whose values are extracted from 'input' starting at the offsets in +/// 'begin'. +/// +/// *Requirements*: +/// 0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n) +/// +/// - Parameters: +/// - begin: begin[i] specifies the offset into the 'i'th dimension of +/// 'input' to slice from. +/// - size: size[i] specifies the number of elements of the 'i'th dimension +/// of 'input' to slice. If size[i] is -1, all remaining elements in dimension +/// i are included in the slice (i.e. this is equivalent to setting +/// size[i] = input.dim_size(i) - begin[i]). +@inlinable @inline(__always) +public static func slice< + T: TensorFlowScalar, + Index: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + begin: Tensor, + size: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Slice", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Index", Index.tensorFlowDataType) + op.addInput(input) + op.addInput(begin) + op.addInput(size) + return op.execute(Int(1)) +} + +/// Returns a copy of the input tensor. +@inlinable @inline(__always) +public static func snapshot( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Snapshot", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func snapshotDataset( + inputDataset: VariantHandle, + path: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("SnapshotDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(path) + return op.execute(Int(1)) +} + +/// Computes softmax activations. +/// +/// For each batch `i` and class `j` we have +/// +/// $$softmax[i, j] = exp(logits[i, j]) / sum_j(exp(logits[i, j]))$$ +/// +/// - Parameter logits: 2-D with shape `[batch_size, num_classes]`. +/// +/// - Output softmax: Same shape as `logits`. +@inlinable @inline(__always) +public static func softmax( + logits: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Softmax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(logits) + return op.execute(Int(1)) +} + +/// Computes softmax cross entropy cost and gradients to backpropagate. +/// +/// Inputs are the logits, not probabilities. +/// +/// - Parameters: +/// - features: batch_size x num_classes matrix +/// - labels: batch_size x num_classes matrix +/// The caller must ensure that each batch of labels represents a valid +/// probability distribution. +/// +/// - Outputs: +/// - loss: Per example loss (batch_size vector). +/// - backprop: backpropagated gradients (batch_size x num_classes matrix). +@inlinable @inline(__always) +public static func softmaxCrossEntropyWithLogits( + features: Tensor, + labels: Tensor +) -> (loss: Tensor, backprop: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("SoftmaxCrossEntropyWithLogits", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + op.addInput(labels) + return op.execute(Int(1), Int(1)) +} + +/// Computes softplus: `log(exp(features) + 1)`. +@inlinable @inline(__always) +public static func softplus( + features: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Softplus", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) +} + +/// Computes softplus gradients for a softplus operation. +/// +/// - Parameters: +/// - gradients: The backpropagated gradients to the corresponding softplus operation. +/// - features: The features passed as input to the corresponding softplus operation. +/// +/// - Output backprops: The gradients: `gradients / (1 + exp(-features))`. +@inlinable @inline(__always) +public static func softplusGrad( + gradients: Tensor, + features: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SoftplusGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(features) + return op.execute(Int(1)) +} + +/// Computes softsign: `features / (abs(features) + 1)`. +@inlinable @inline(__always) +public static func softsign( + features: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Softsign", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) +} + +/// Computes softsign gradients for a softsign operation. +/// +/// - Parameters: +/// - gradients: The backpropagated gradients to the corresponding softsign operation. +/// - features: The features passed as input to the corresponding softsign operation. +/// +/// - Output backprops: The gradients: `gradients / (1 + abs(features)) ** 2`. +@inlinable @inline(__always) +public static func softsignGrad( + gradients: Tensor, + features: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SoftsignGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(features) + return op.execute(Int(1)) +} + +/// SpaceToBatch for 4-D tensors of type T. +/// +/// This is a legacy version of the more general SpaceToBatchND. +/// +/// Zero-pads and then rearranges (permutes) blocks of spatial data into batch. +/// More specifically, this op outputs a copy of the input tensor where values from +/// the `height` and `width` dimensions are moved to the `batch` dimension. After +/// the zero-padding, both `height` and `width` of the input must be divisible by the +/// block size. +/// +/// - Parameters: +/// - input: 4-D with shape `[batch, height, width, depth]`. +/// - paddings: 2-D tensor of non-negative integers with shape `[2, 2]`. It specifies +/// the padding of the input with zeros across the spatial dimensions as follows: +/// +/// paddings = [[pad_top, pad_bottom], [pad_left, pad_right]] +/// +/// The effective spatial dimensions of the zero-padded input tensor will be: +/// +/// height_pad = pad_top + height + pad_bottom +/// width_pad = pad_left + width + pad_right +/// +/// The attr `block_size` must be greater than one. It indicates the block size. +/// +/// * Non-overlapping blocks of size `block_size x block size` in the height and +/// width dimensions are rearranged into the batch dimension at each location. +/// * The batch of the output tensor is `batch * block_size * block_size`. +/// * Both height_pad and width_pad must be divisible by block_size. +/// +/// The shape of the output will be: +/// +/// [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, +/// depth] +/// +/// Some examples: +/// +/// (1) For the following input of shape `[1, 2, 2, 1]` and block_size of 2: +/// +/// ``` +/// x = [[[[1], [2]], [[3], [4]]]] +/// ``` +/// +/// The output tensor has shape `[4, 1, 1, 1]` and value: +/// +/// ``` +/// [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] +/// ``` +/// +/// (2) For the following input of shape `[1, 2, 2, 3]` and block_size of 2: +/// +/// ``` +/// x = [[[[1, 2, 3], [4, 5, 6]], +/// [[7, 8, 9], [10, 11, 12]]]] +/// ``` +/// +/// The output tensor has shape `[4, 1, 1, 3]` and value: +/// +/// ``` +/// [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] +/// ``` +/// +/// (3) For the following input of shape `[1, 4, 4, 1]` and block_size of 2: +/// +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]], +/// [[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` +/// +/// The output tensor has shape `[4, 2, 2, 1]` and value: +/// +/// ``` +/// x = [[[[1], [3]], [[9], [11]]], +/// [[[2], [4]], [[10], [12]]], +/// [[[5], [7]], [[13], [15]]], +/// [[[6], [8]], [[14], [16]]]] +/// ``` +/// +/// (4) For the following input of shape `[2, 2, 4, 1]` and block_size of 2: +/// +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]]], +/// [[[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` +/// +/// The output tensor has shape `[8, 1, 2, 1]` and value: +/// +/// ``` +/// x = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]], +/// [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]] +/// ``` +/// +/// Among others, this operation is useful for reducing atrous convolution into +/// regular convolution. +@inlinable @inline(__always) +public static func spaceToBatch< + T: TensorFlowScalar, + Tpaddings: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + paddings: Tensor, + blockSize: Int64 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SpaceToBatch", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) + op.updateAttribute("block_size", blockSize) + op.addInput(input) + op.addInput(paddings) + return op.execute(Int(1)) +} + +/// SpaceToBatch for N-D tensors of type T. +/// +/// This operation divides "spatial" dimensions `[1, ..., M]` of the input into a +/// grid of blocks of shape `block_shape`, and interleaves these blocks with the +/// "batch" dimension (0) such that in the output, the spatial dimensions +/// `[1, ..., M]` correspond to the position within the grid, and the batch +/// dimension combines both the position within a spatial block and the original +/// batch position. Prior to division into blocks, the spatial dimensions of the +/// input are optionally zero padded according to `paddings`. See below for a +/// precise description. +/// +/// - Parameters: +/// - input: N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`, +/// where spatial_shape has `M` dimensions. +/// - block_shape: 1-D with shape `[M]`, all values must be >= 1. +/// - paddings: 2-D with shape `[M, 2]`, all values must be >= 0. +/// `paddings[i] = [pad_start, pad_end]` specifies the padding for input dimension +/// `i + 1`, which corresponds to spatial dimension `i`. It is required that +/// `block_shape[i]` divides `input_shape[i + 1] + pad_start + pad_end`. +/// +/// This operation is equivalent to the following steps: +/// +/// 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the +/// input according to `paddings` to produce `padded` of shape `padded_shape`. +/// +/// 2. Reshape `padded` to `reshaped_padded` of shape: +/// +/// [batch] + +/// [padded_shape[1] / block_shape[0], +/// block_shape[0], +/// ..., +/// padded_shape[M] / block_shape[M-1], +/// block_shape[M-1]] + +/// remaining_shape +/// +/// 3. Permute dimensions of `reshaped_padded` to produce +/// `permuted_reshaped_padded` of shape: +/// +/// block_shape + +/// [batch] + +/// [padded_shape[1] / block_shape[0], +/// ..., +/// padded_shape[M] / block_shape[M-1]] + +/// remaining_shape +/// +/// 4. Reshape `permuted_reshaped_padded` to flatten `block_shape` into the batch +/// dimension, producing an output tensor of shape: +/// +/// [batch * prod(block_shape)] + +/// [padded_shape[1] / block_shape[0], +/// ..., +/// padded_shape[M] / block_shape[M-1]] + +/// remaining_shape +/// +/// Some examples: +/// +/// (1) For the following input of shape `[1, 2, 2, 1]`, `block_shape = [2, 2]`, and +/// `paddings = [[0, 0], [0, 0]]`: +/// +/// ``` +/// x = [[[[1], [2]], [[3], [4]]]] +/// ``` +/// +/// The output tensor has shape `[4, 1, 1, 1]` and value: +/// +/// ``` +/// [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] +/// ``` +/// +/// (2) For the following input of shape `[1, 2, 2, 3]`, `block_shape = [2, 2]`, and +/// `paddings = [[0, 0], [0, 0]]`: +/// +/// ``` +/// x = [[[[1, 2, 3], [4, 5, 6]], +/// [[7, 8, 9], [10, 11, 12]]]] +/// ``` +/// +/// The output tensor has shape `[4, 1, 1, 3]` and value: +/// +/// ``` +/// [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] +/// ``` +/// +/// (3) For the following input of shape `[1, 4, 4, 1]`, `block_shape = [2, 2]`, and +/// `paddings = [[0, 0], [0, 0]]`: +/// +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]], +/// [[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` +/// +/// The output tensor has shape `[4, 2, 2, 1]` and value: +/// +/// ``` +/// x = [[[[1], [3]], [[9], [11]]], +/// [[[2], [4]], [[10], [12]]], +/// [[[5], [7]], [[13], [15]]], +/// [[[6], [8]], [[14], [16]]]] +/// ``` +/// +/// (4) For the following input of shape `[2, 2, 4, 1]`, block_shape = `[2, 2]`, and +/// paddings = `[[0, 0], [2, 0]]`: +/// +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]]], +/// [[[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` +/// +/// The output tensor has shape `[8, 1, 3, 1]` and value: +/// +/// ``` +/// x = [[[[0], [1], [3]]], [[[0], [9], [11]]], +/// [[[0], [2], [4]]], [[[0], [10], [12]]], +/// [[[0], [5], [7]]], [[[0], [13], [15]]], +/// [[[0], [6], [8]]], [[[0], [14], [16]]]] +/// ``` +/// +/// Among others, this operation is useful for reducing atrous convolution into +/// regular convolution. +@inlinable @inline(__always) +public static func spaceToBatchND< + T: TensorFlowScalar, + TblockShape: BinaryInteger & TensorFlowScalar, + Tpaddings: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + blockShape: Tensor, + paddings: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SpaceToBatchND", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tblock_shape", TblockShape.tensorFlowDataType) + op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) + op.addInput(input) + op.addInput(blockShape) + op.addInput(paddings) + return op.execute(Int(1)) +} + +/// SpaceToDepth for tensors of type T. +/// +/// Rearranges blocks of spatial data, into depth. More specifically, +/// this op outputs a copy of the input tensor where values from the `height` +/// and `width` dimensions are moved to the `depth` dimension. +/// The attr `block_size` indicates the input block size. +/// +/// * Non-overlapping blocks of size `block_size x block size` are rearranged +/// into depth at each location. +/// * The depth of the output tensor is `block_size * block_size * input_depth`. +/// * The Y, X coordinates within each block of the input become the high order +/// component of the output channel index. +/// * The input tensor's height and width must be divisible by block_size. +/// +/// The `data_format` attr specifies the layout of the input and output tensors +/// with the following options: +/// "NHWC": `[ batch, height, width, channels ]` +/// "NCHW": `[ batch, channels, height, width ]` +/// "NCHW_VECT_C": +/// `qint8 [ batch, channels / 4, height, width, 4 ]` +/// +/// It is useful to consider the operation as transforming a 6-D Tensor. +/// e.g. for data_format = NHWC, +/// Each element in the input tensor can be specified via 6 coordinates, +/// ordered by decreasing memory layout significance as: +/// n,oY,bY,oX,bX,iC (where n=batch index, oX, oY means X or Y coordinates +/// within the output image, bX, bY means coordinates +/// within the input block, iC means input channels). +/// The output would be a transpose to the following layout: +/// n,oY,oX,bY,bX,iC +/// +/// This operation is useful for resizing the activations between convolutions +/// (but keeping all data), e.g. instead of pooling. It is also useful for training +/// purely convolutional models. +/// +/// For example, given an input of shape `[1, 2, 2, 1]`, data_format = "NHWC" and +/// block_size = 2: +/// +/// ``` +/// x = [[[[1], [2]], +/// [[3], [4]]]] +/// ``` +/// +/// This operation will output a tensor of shape `[1, 1, 1, 4]`: +/// +/// ``` +/// [[[[1, 2, 3, 4]]]] +/// ``` +/// +/// Here, the input has a batch of 1 and each batch element has shape `[2, 2, 1]`, +/// the corresponding output will have a single element (i.e. width and height are +/// both 1) and will have a depth of 4 channels (1 * block_size * block_size). +/// The output element shape is `[1, 1, 4]`. +/// +/// For an input tensor with larger depth, here of shape `[1, 2, 2, 3]`, e.g. +/// +/// ``` +/// x = [[[[1, 2, 3], [4, 5, 6]], +/// [[7, 8, 9], [10, 11, 12]]]] +/// ``` +/// +/// This operation, for block_size of 2, will return the following tensor of shape +/// `[1, 1, 1, 12]` +/// +/// ``` +/// [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]] +/// ``` +/// +/// Similarly, for the following input of shape `[1 4 4 1]`, and a block size of 2: +/// +/// ``` +/// x = [[[[1], [2], [5], [6]], +/// [[3], [4], [7], [8]], +/// [[9], [10], [13], [14]], +/// [[11], [12], [15], [16]]]] +/// ``` +/// +/// the operator will return the following tensor of shape `[1 2 2 4]`: +/// +/// ``` +/// x = [[[[1, 2, 3, 4], +/// [5, 6, 7, 8]], +/// [[9, 10, 11, 12], +/// [13, 14, 15, 16]]]] +/// ``` +/// +/// - Attr block_size: The size of the spatial block. +@inlinable @inline(__always) +public static func spaceToDepth( + _ input: Tensor, + blockSize: Int64, + dataFormat: DataFormat4 = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SpaceToDepth", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("block_size", blockSize) + op.updateAttribute("data_format", dataFormat.cName) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Adds two `SparseTensor` objects to produce another `SparseTensor`. +/// +/// The input `SparseTensor` objects' indices are assumed ordered in standard +/// lexicographic order. If this is not the case, before this step run +/// `SparseReorder` to restore index ordering. +/// +/// By default, if two values sum to zero at some index, the output `SparseTensor` +/// would still include that particular location in its index, storing a zero in the +/// corresponding value slot. To override this, callers can specify `thresh`, +/// indicating that if the sum has a magnitude strictly smaller than `thresh`, its +/// corresponding value and index would then not be included. In particular, +/// `thresh == 0` (default) means everything is kept and actual thresholding happens +/// only for a positive value. +/// +/// In the following shapes, `nnz` is the count after taking `thresh` into account. +/// +/// - Parameters: +/// - a_indices: 2-D. The `indices` of the first `SparseTensor`, size `[nnz, ndims]` Matrix. +/// - a_values: 1-D. The `values` of the first `SparseTensor`, size `[nnz]` Vector. +/// - a_shape: 1-D. The `shape` of the first `SparseTensor`, size `[ndims]` Vector. +/// - b_indices: 2-D. The `indices` of the second `SparseTensor`, size `[nnz, ndims]` Matrix. +/// - b_values: 1-D. The `values` of the second `SparseTensor`, size `[nnz]` Vector. +/// - b_shape: 1-D. The `shape` of the second `SparseTensor`, size `[ndims]` Vector. +/// - thresh: 0-D. The magnitude threshold that determines if an output value/index +/// pair takes space. +@inlinable @inline(__always) +public static func sparseAdd< + T: Numeric & TensorFlowScalar, + Treal: Numeric & TensorFlowScalar +>( + aIndices: Tensor, + aValues: Tensor, + aShape: Tensor, + bIndices: Tensor, + bValues: Tensor, + bShape: Tensor, + thresh: Tensor +) -> (sumIndices: Tensor, sumValues: Tensor, sumShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("SparseAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Treal", Treal.tensorFlowDataType) + op.addInput(aIndices) + op.addInput(aValues) + op.addInput(aShape) + op.addInput(bIndices) + op.addInput(bValues) + op.addInput(bShape) + op.addInput(thresh) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// The gradient operator for the SparseAdd op. +/// +/// The SparseAdd op calculates A + B, where A, B, and the sum are all represented +/// as `SparseTensor` objects. This op takes in the upstream gradient w.r.t. +/// non-empty values of the sum, and outputs the gradients w.r.t. the non-empty +/// values of A and B. +/// +/// - Parameters: +/// - backprop_val_grad: 1-D with shape `[nnz(sum)]`. The gradient with respect to +/// the non-empty values of the sum. +/// - a_indices: 2-D. The `indices` of the `SparseTensor` A, size `[nnz(A), ndims]`. +/// - b_indices: 2-D. The `indices` of the `SparseTensor` B, size `[nnz(B), ndims]`. +/// - sum_indices: 2-D. The `indices` of the sum `SparseTensor`, size +/// `[nnz(sum), ndims]`. +/// +/// - Outputs: +/// - a_val_grad: 1-D with shape `[nnz(A)]`. The gradient with respect to the +/// non-empty values of A. +/// - b_val_grad: 1-D with shape `[nnz(B)]`. The gradient with respect to the +/// non-empty values of B. +@inlinable @inline(__always) +public static func sparseAddGrad( + backpropValGrad: Tensor, + aIndices: Tensor, + bIndices: Tensor, + sumIndices: Tensor +) -> (aValGrad: Tensor, bValGrad: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("SparseAddGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(backpropValGrad) + op.addInput(aIndices) + op.addInput(bIndices) + op.addInput(sumIndices) + return op.execute(Int(1), Int(1)) +} + +/// Concatenates a list of `SparseTensor` along the specified dimension. +/// +/// Concatenation is with respect to the dense versions of these sparse tensors. +/// It is assumed that each input is a `SparseTensor` whose elements are ordered +/// along increasing dimension number. +/// +/// All inputs' shapes must match, except for the concat dimension. The +/// `indices`, `values`, and `shapes` lists must have the same length. +/// +/// The output shape is identical to the inputs', except along the concat +/// dimension, where it is the sum of the inputs' sizes along that dimension. +/// +/// The output elements will be resorted to preserve the sort order along +/// increasing dimension number. +/// +/// This op runs in `O(M log M)` time, where `M` is the total number of non-empty +/// values across all inputs. This is due to the need for an internal sort in +/// order to concatenate efficiently across an arbitrary dimension. +/// +/// For example, if `concat_dim = 1` and the inputs are +/// +/// sp_inputs[0]: shape = [2, 3] +/// [0, 2]: "a" +/// [1, 0]: "b" +/// [1, 1]: "c" +/// +/// sp_inputs[1]: shape = [2, 4] +/// [0, 1]: "d" +/// [0, 2]: "e" +/// +/// then the output will be +/// +/// shape = [2, 7] +/// [0, 2]: "a" +/// [0, 4]: "d" +/// [0, 5]: "e" +/// [1, 0]: "b" +/// [1, 1]: "c" +/// +/// Graphically this is equivalent to doing +/// +/// [ a] concat [ d e ] = [ a d e ] +/// [b c ] [ ] [b c ] +/// +/// - Parameters: +/// - indices: 2-D. Indices of each input `SparseTensor`. +/// - values: 1-D. Non-empty values of each `SparseTensor`. +/// - shapes: 1-D. Shapes of each `SparseTensor`. +/// +/// - Attr concat_dim: Dimension to concatenate along. Must be in range [-rank, rank), +/// where rank is the number of dimensions in each input `SparseTensor`. +/// +/// - Outputs: +/// - output_indices: 2-D. Indices of the concatenated `SparseTensor`. +/// - output_values: 1-D. Non-empty values of the concatenated `SparseTensor`. +/// - output_shape: 1-D. Shape of the concatenated `SparseTensor`. +@inlinable @inline(__always) +public static func sparseConcat( + indices: [Tensor], + _ values: [Tensor], + shapes: [Tensor], + concatDim: Int64 +) -> (outputIndices: Tensor, outputValues: Tensor, outputShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("SparseConcat", nOutputs) + op.updateAttribute("concat_dim", concatDim) + op.updateAttribute("N", indices.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInputList(indices) + op.addInputList(values) + op.addInputList(shapes) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Generates sparse cross from a list of sparse and dense tensors. +/// +/// The op takes two lists, one of 2D `SparseTensor` and one of 2D `Tensor`, each +/// representing features of one feature column. It outputs a 2D `SparseTensor` with +/// the batchwise crosses of these features. +/// +/// For example, if the inputs are +/// +/// inputs[0]: SparseTensor with shape = [2, 2] +/// [0, 0]: "a" +/// [1, 0]: "b" +/// [1, 1]: "c" +/// +/// inputs[1]: SparseTensor with shape = [2, 1] +/// [0, 0]: "d" +/// [1, 0]: "e" +/// +/// inputs[2]: Tensor [["f"], ["g"]] +/// +/// then the output will be +/// +/// shape = [2, 2] +/// [0, 0]: "a_X_d_X_f" +/// [1, 0]: "b_X_e_X_g" +/// [1, 1]: "c_X_e_X_g" +/// +/// if hashed_output=true then the output will be +/// +/// shape = [2, 2] +/// [0, 0]: FingerprintCat64( +/// Fingerprint64("f"), FingerprintCat64( +/// Fingerprint64("d"), Fingerprint64("a"))) +/// [1, 0]: FingerprintCat64( +/// Fingerprint64("g"), FingerprintCat64( +/// Fingerprint64("e"), Fingerprint64("b"))) +/// [1, 1]: FingerprintCat64( +/// Fingerprint64("g"), FingerprintCat64( +/// Fingerprint64("e"), Fingerprint64("c"))) +/// +/// - Parameters: +/// - indices: 2-D. Indices of each input `SparseTensor`. +/// - values: 1-D. values of each `SparseTensor`. +/// - shapes: 1-D. Shapes of each `SparseTensor`. +/// - dense_inputs: 2-D. Columns represented by dense `Tensor`. +/// +/// - Attrs: +/// - hashed_output: If true, returns the hash of the cross instead of the string. +/// This will allow us avoiding string manipulations. +/// - num_buckets: It is used if hashed_output is true. +/// output = hashed_value%num_buckets if num_buckets > 0 else hashed_value. +/// - hash_key: Specify the hash_key that will be used by the `FingerprintCat64` +/// function to combine the crosses fingerprints. +/// +/// - Outputs: +/// - output_indices: 2-D. Indices of the concatenated `SparseTensor`. +/// - output_values: 1-D. Non-empty values of the concatenated or hashed +/// `SparseTensor`. +/// - output_shape: 1-D. Shape of the concatenated `SparseTensor`. +@inlinable @inline(__always) +public static func sparseCross< + SparseTypes: TensorArrayProtocol, + DenseTypes: TensorArrayProtocol, + OutType: BinaryInteger & TensorFlowScalar +>( + indices: [Tensor], + _ values: SparseTypes, + shapes: [Tensor], + denseInputs: DenseTypes, + hashedOutput: Bool, + numBuckets: Int64, + hashKey: Int64, + internalType: TensorDataType +) -> (outputIndices: Tensor, outputValues: Tensor, outputShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("SparseCross", nOutputs) + op.updateAttribute("N", indices.count) + op.updateAttribute("hashed_output", hashedOutput) + op.updateAttribute("num_buckets", numBuckets) + op.updateAttribute("hash_key", hashKey) + op.updateAttribute("sparse_types", values._typeList) + op.updateAttribute("dense_types", denseInputs._typeList) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("internal_type", internalType) + op.addInputList(indices) + op.addInputList(values) + op.addInputList(shapes) + op.addInputList(denseInputs) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Generates sparse cross from a list of sparse and dense tensors. +/// +/// The op takes two lists, one of 2D `SparseTensor` and one of 2D `Tensor`, each +/// representing features of one feature column. It outputs a 2D `SparseTensor` with +/// the batchwise crosses of these features. +/// +/// For example, if the inputs are +/// +/// inputs[0]: SparseTensor with shape = [2, 2] +/// [0, 0]: "a" +/// [1, 0]: "b" +/// [1, 1]: "c" +/// +/// inputs[1]: SparseTensor with shape = [2, 1] +/// [0, 0]: "d" +/// [1, 0]: "e" +/// +/// inputs[2]: Tensor [["f"], ["g"]] +/// +/// then the output will be +/// +/// shape = [2, 2] +/// [0, 0]: "a_X_d_X_f" +/// [1, 0]: "b_X_e_X_g" +/// [1, 1]: "c_X_e_X_g" +/// +/// if hashed_output=true then the output will be +/// +/// shape = [2, 2] +/// [0, 0]: FingerprintCat64( +/// Fingerprint64("f"), FingerprintCat64( +/// Fingerprint64("d"), Fingerprint64("a"))) +/// [1, 0]: FingerprintCat64( +/// Fingerprint64("g"), FingerprintCat64( +/// Fingerprint64("e"), Fingerprint64("b"))) +/// [1, 1]: FingerprintCat64( +/// Fingerprint64("g"), FingerprintCat64( +/// Fingerprint64("e"), Fingerprint64("c"))) +/// +/// - Parameters: +/// - indices: 2-D. Indices of each input `SparseTensor`. +/// - values: 1-D. values of each `SparseTensor`. +/// - shapes: 1-D. Shapes of each `SparseTensor`. +/// - dense_inputs: 2-D. Columns represented by dense `Tensor`. +/// +/// - Attrs: +/// - hashed_output: If true, returns the hash of the cross instead of the string. +/// This will allow us avoiding string manipulations. +/// - num_buckets: It is used if hashed_output is true. +/// output = hashed_value%num_buckets if num_buckets > 0 else hashed_value. +/// - hash_key: Specify the hash_key that will be used by the `FingerprintCat64` +/// function to combine the crosses fingerprints. +/// +/// - Outputs: +/// - output_indices: 2-D. Indices of the concatenated `SparseTensor`. +/// - output_values: 1-D. Non-empty values of the concatenated or hashed +/// `SparseTensor`. +/// - output_shape: 1-D. Shape of the concatenated `SparseTensor`. +@inlinable @inline(__always) +public static func sparseCross< + SparseTypes: TensorArrayProtocol, + DenseTypes: TensorArrayProtocol +>( + indices: [Tensor], + _ values: SparseTypes, + shapes: [Tensor], + denseInputs: DenseTypes, + hashedOutput: Bool, + numBuckets: Int64, + hashKey: Int64, + internalType: TensorDataType +) -> (outputIndices: Tensor, outputValues: StringTensor, outputShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("SparseCross", nOutputs) + op.updateAttribute("N", indices.count) + op.updateAttribute("hashed_output", hashedOutput) + op.updateAttribute("num_buckets", numBuckets) + op.updateAttribute("hash_key", hashKey) + op.updateAttribute("sparse_types", values._typeList) + op.updateAttribute("dense_types", denseInputs._typeList) + op.updateAttribute("out_type", TensorDataType(TF_STRING)) + op.updateAttribute("internal_type", internalType) + op.addInputList(indices) + op.addInputList(values) + op.addInputList(shapes) + op.addInputList(denseInputs) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Adds up a SparseTensor and a dense Tensor, using these special rules: +/// +/// (1) Broadcasts the dense side to have the same shape as the sparse side, if +/// eligible; +/// (2) Then, only the dense values pointed to by the indices of the SparseTensor +/// participate in the cwise addition. +/// +/// By these rules, the result is a logical SparseTensor with exactly the same +/// indices and shape, but possibly with different non-zero values. The output of +/// this Op is the resultant non-zero values. +/// +/// - Parameters: +/// - sp_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - sp_values: 1-D. `N` non-empty values corresponding to `sp_indices`. +/// - sp_shape: 1-D. Shape of the input SparseTensor. +/// - dense: `R`-D. The dense Tensor operand. +/// +/// - Output output: 1-D. The `N` values that are operated on. +@inlinable @inline(__always) +public static func sparseDenseCwiseAdd( + spIndices: Tensor, + spValues: Tensor, + spShape: Tensor, + dense: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseDenseCwiseAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(spIndices) + op.addInput(spValues) + op.addInput(spShape) + op.addInput(dense) + return op.execute(Int(1)) +} + +/// Component-wise divides a SparseTensor by a dense Tensor. +/// +/// *Limitation*: this Op only broadcasts the dense side to the sparse side, but not +/// the other direction. +/// +/// - Parameters: +/// - sp_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - sp_values: 1-D. `N` non-empty values corresponding to `sp_indices`. +/// - sp_shape: 1-D. Shape of the input SparseTensor. +/// - dense: `R`-D. The dense Tensor operand. +/// +/// - Output output: 1-D. The `N` values that are operated on. +@inlinable @inline(__always) +public static func sparseDenseCwiseDiv( + spIndices: Tensor, + spValues: Tensor, + spShape: Tensor, + dense: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseDenseCwiseDiv", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(spIndices) + op.addInput(spValues) + op.addInput(spShape) + op.addInput(dense) + return op.execute(Int(1)) +} + +/// Component-wise multiplies a SparseTensor by a dense Tensor. +/// +/// The output locations corresponding to the implicitly zero elements in the sparse +/// tensor will be zero (i.e., will not take up storage space), regardless of the +/// contents of the dense tensor (even if it's +/-INF and that INF*0 == NaN). +/// +/// *Limitation*: this Op only broadcasts the dense side to the sparse side, but not +/// the other direction. +/// +/// - Parameters: +/// - sp_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - sp_values: 1-D. `N` non-empty values corresponding to `sp_indices`. +/// - sp_shape: 1-D. Shape of the input SparseTensor. +/// - dense: `R`-D. The dense Tensor operand. +/// +/// - Output output: 1-D. The `N` values that are operated on. +@inlinable @inline(__always) +public static func sparseDenseCwiseMul( + spIndices: Tensor, + spValues: Tensor, + spShape: Tensor, + dense: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseDenseCwiseMul", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(spIndices) + op.addInput(spValues) + op.addInput(spShape) + op.addInput(dense) + return op.execute(Int(1)) +} + +/// Fills empty rows in the input 2-D `SparseTensor` with a default value. +/// +/// The input `SparseTensor` is represented via the tuple of inputs +/// (`indices`, `values`, `dense_shape`). The output `SparseTensor` has the +/// same `dense_shape` but with indices `output_indices` and values +/// `output_values`. +/// +/// This op inserts a single entry for every row that doesn't have any values. +/// The index is created as `[row, 0, ..., 0]` and the inserted value +/// is `default_value`. +/// +/// For example, suppose `sp_input` has shape `[5, 6]` and non-empty values: +/// +/// [0, 1]: a +/// [0, 3]: b +/// [2, 0]: c +/// [3, 1]: d +/// +/// Rows 1 and 4 are empty, so the output will be of shape `[5, 6]` with values: +/// +/// [0, 1]: a +/// [0, 3]: b +/// [1, 0]: default_value +/// [2, 0]: c +/// [3, 1]: d +/// [4, 0]: default_value +/// +/// The output `SparseTensor` will be in row-major order and will have the +/// same shape as the input. +/// +/// This op also returns an indicator vector shaped `[dense_shape[0]]` such that +/// +/// empty_row_indicator[i] = True iff row i was an empty row. +/// +/// And a reverse index map vector shaped `[indices.shape[0]]` that is used during +/// backpropagation, +/// +/// reverse_index_map[j] = out_j s.t. indices[j, :] == output_indices[out_j, :] +/// +/// - Parameters: +/// - indices: 2-D. the indices of the sparse tensor. +/// - values: 1-D. the values of the sparse tensor. +/// - dense_shape: 1-D. the shape of the sparse tensor. +/// - default_value: 0-D. default value to insert into location `[row, 0, ..., 0]` +/// for rows missing from the input sparse tensor. +/// output indices: 2-D. the indices of the filled sparse tensor. +/// +/// - Outputs: +/// - output_values: 1-D. the values of the filled sparse tensor. +/// - empty_row_indicator: 1-D. whether the dense row was missing in the +/// input sparse tensor. +/// - reverse_index_map: 1-D. a map from the input indices to the output indices. +@inlinable @inline(__always) +public static func sparseFillEmptyRows( + indices: Tensor, + _ values: Tensor, + denseShape: Tensor, + defaultValue: Tensor +) -> (outputIndices: Tensor, outputValues: Tensor, emptyRowIndicator: Tensor, reverseIndexMap: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + let op = makeOp("SparseFillEmptyRows", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(indices) + op.addInput(values) + op.addInput(denseShape) + op.addInput(defaultValue) + return op.execute(Int(1), Int(1), Int(1), Int(1)) +} + +/// The gradient of SparseFillEmptyRows. +/// +/// Takes vectors reverse_index_map, shaped `[N]`, and grad_values, +/// shaped `[N_full]`, where `N_full >= N` and copies data into either +/// `d_values` or `d_default_value`. Here `d_values` is shaped `[N]` and +/// `d_default_value` is a scalar. +/// +/// d_values[j] = grad_values[reverse_index_map[j]] +/// d_default_value = sum_{k : 0 .. N_full - 1} ( +/// grad_values[k] * 1{k not in reverse_index_map}) +/// +/// - Parameters: +/// - reverse_index_map: 1-D. The reverse index map from SparseFillEmptyRows. +/// - grad_values: 1-D. The gradients from backprop. +/// +/// - Outputs: +/// - d_values: 1-D. The backprop into values. +/// - d_default_value: 0-D. The backprop into default_value. +@inlinable @inline(__always) +public static func sparseFillEmptyRowsGrad( + reverseIndexMap: Tensor, + gradValues: Tensor +) -> (dValues: Tensor, dDefaultValue: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("SparseFillEmptyRowsGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(reverseIndexMap) + op.addInput(gradValues) + return op.execute(Int(1), Int(1)) +} + +/// Multiply matrix "a" by matrix "b". +/// +/// The inputs must be two-dimensional matrices and the inner dimension of "a" must +/// match the outer dimension of "b". Both "a" and "b" must be `Tensor`s not +/// `SparseTensor`s. This op is optimized for the case where at least one of "a" or +/// "b" is sparse, in the sense that they have a large proportion of zero values. +/// The breakeven for using this versus a dense matrix multiply on one platform was +/// 30% zero values in the sparse matrix. +/// +/// The gradient computation of this operation will only take advantage of sparsity +/// in the input gradient when that gradient comes from a Relu. +@inlinable @inline(__always) +public static func sparseMatMul< + Ta: FloatingPoint & TensorFlowScalar, + Tb: FloatingPoint & TensorFlowScalar +>( + _ a: Tensor, + _ b: Tensor, + transposeA: Bool = false, + transposeB: Bool = false, + aIsSparse: Bool = false, + bIsSparse: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseMatMul", nOutputs) + op.updateAttribute("transpose_a", transposeA) + op.updateAttribute("transpose_b", transposeB) + op.updateAttribute("a_is_sparse", aIsSparse) + op.updateAttribute("b_is_sparse", bIsSparse) + op.updateAttribute("Ta", Ta.tensorFlowDataType) + op.updateAttribute("Tb", Tb.tensorFlowDataType) + op.addInput(a) + op.addInput(b) + return op.execute(Int(1)) +} + +/// Computes the max of elements across dimensions of a SparseTensor. +/// +/// This Op takes a SparseTensor and is the sparse counterpart to +/// `tf.reduce_max()`. In particular, this Op also returns a dense `Tensor` +/// instead of a sparse one. +/// +/// Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless +/// `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in +/// `reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained +/// with length 1. +/// +/// If `reduction_axes` has no entries, all dimensions are reduced, and a tensor +/// with a single element is returned. Additionally, the axes can be negative, +/// which are interpreted according to the indexing rules in Python. +/// +/// - Parameters: +/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. +/// - input_shape: 1-D. Shape of the input SparseTensor. +/// - reduction_axes: 1-D. Length-`K` vector containing the reduction axes. +/// +/// - Attr keep_dims: If true, retain reduced dimensions with length 1. +/// +/// - Output output: `R-K`-D. The reduced Tensor. +@inlinable @inline(__always) +public static func sparseReduceMax( + inputIndices: Tensor, + inputValues: Tensor, + inputShape: Tensor, + reductionAxes: Tensor, + keepDims: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseReduceMax", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(inputIndices) + op.addInput(inputValues) + op.addInput(inputShape) + op.addInput(reductionAxes) + return op.execute(Int(1)) +} + +/// Computes the max of elements across dimensions of a SparseTensor. +/// +/// This Op takes a SparseTensor and is the sparse counterpart to +/// `tf.reduce_max()`. In contrast to SparseReduceMax, this Op returns a +/// SparseTensor. +/// +/// Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless +/// `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in +/// `reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained +/// with length 1. +/// +/// If `reduction_axes` has no entries, all dimensions are reduced, and a tensor +/// with a single element is returned. Additionally, the axes can be negative, +/// which are interpreted according to the indexing rules in Python. +/// +/// - Parameters: +/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. +/// - input_shape: 1-D. Shape of the input SparseTensor. +/// - reduction_axes: 1-D. Length-`K` vector containing the reduction axes. +/// +/// - Attr keep_dims: If true, retain reduced dimensions with length 1. +@inlinable @inline(__always) +public static func sparseReduceMaxSparse( + inputIndices: Tensor, + inputValues: Tensor, + inputShape: Tensor, + reductionAxes: Tensor, + keepDims: Bool = false +) -> (outputIndices: Tensor, outputValues: Tensor, outputShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("SparseReduceMaxSparse", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(inputIndices) + op.addInput(inputValues) + op.addInput(inputShape) + op.addInput(reductionAxes) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Computes the sum of elements across dimensions of a SparseTensor. +/// +/// This Op takes a SparseTensor and is the sparse counterpart to +/// `tf.reduce_sum()`. In particular, this Op also returns a dense `Tensor` +/// instead of a sparse one. +/// +/// Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless +/// `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in +/// `reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained +/// with length 1. +/// +/// If `reduction_axes` has no entries, all dimensions are reduced, and a tensor +/// with a single element is returned. Additionally, the axes can be negative, +/// which are interpreted according to the indexing rules in Python. +/// +/// - Parameters: +/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. +/// - input_shape: 1-D. Shape of the input SparseTensor. +/// - reduction_axes: 1-D. Length-`K` vector containing the reduction axes. +/// +/// - Attr keep_dims: If true, retain reduced dimensions with length 1. +/// +/// - Output output: `R-K`-D. The reduced Tensor. +@inlinable @inline(__always) +public static func sparseReduceSum( + inputIndices: Tensor, + inputValues: Tensor, + inputShape: Tensor, + reductionAxes: Tensor, + keepDims: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseReduceSum", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(inputIndices) + op.addInput(inputValues) + op.addInput(inputShape) + op.addInput(reductionAxes) + return op.execute(Int(1)) +} + +/// Computes the sum of elements across dimensions of a SparseTensor. +/// +/// This Op takes a SparseTensor and is the sparse counterpart to +/// `tf.reduce_sum()`. In contrast to SparseReduceSum, this Op returns a +/// SparseTensor. +/// +/// Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless +/// `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in +/// `reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained +/// with length 1. +/// +/// If `reduction_axes` has no entries, all dimensions are reduced, and a tensor +/// with a single element is returned. Additionally, the axes can be negative, +/// which are interpreted according to the indexing rules in Python. +/// +/// - Parameters: +/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. +/// - input_shape: 1-D. Shape of the input SparseTensor. +/// - reduction_axes: 1-D. Length-`K` vector containing the reduction axes. +/// +/// - Attr keep_dims: If true, retain reduced dimensions with length 1. +@inlinable @inline(__always) +public static func sparseReduceSumSparse( + inputIndices: Tensor, + inputValues: Tensor, + inputShape: Tensor, + reductionAxes: Tensor, + keepDims: Bool = false +) -> (outputIndices: Tensor, outputValues: Tensor, outputShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("SparseReduceSumSparse", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(inputIndices) + op.addInput(inputValues) + op.addInput(inputShape) + op.addInput(reductionAxes) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Reorders a SparseTensor into the canonical, row-major ordering. +/// +/// Note that by convention, all sparse ops preserve the canonical ordering along +/// increasing dimension number. The only time ordering can be violated is during +/// manual manipulation of the indices and values vectors to add entries. +/// +/// Reordering does not affect the shape of the SparseTensor. +/// +/// If the tensor has rank `R` and `N` non-empty values, `input_indices` has +/// shape `[N, R]`, input_values has length `N`, and input_shape has length `R`. +/// +/// - Parameters: +/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. +/// - input_shape: 1-D. Shape of the input SparseTensor. +/// +/// - Outputs: +/// - output_indices: 2-D. `N x R` matrix with the same indices as input_indices, but +/// in canonical row-major ordering. +/// - output_values: 1-D. `N` non-empty values corresponding to `output_indices`. +@inlinable @inline(__always) +public static func sparseReorder( + inputIndices: Tensor, + inputValues: Tensor, + inputShape: Tensor +) -> (outputIndices: Tensor, outputValues: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("SparseReorder", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(inputIndices) + op.addInput(inputValues) + op.addInput(inputShape) + return op.execute(Int(1), Int(1)) +} + +/// Reshapes a SparseTensor to represent values in a new dense shape. +/// +/// This operation has the same semantics as reshape on the represented dense +/// tensor. The `input_indices` are recomputed based on the requested `new_shape`. +/// +/// If one component of `new_shape` is the special value -1, the size of that +/// dimension is computed so that the total dense size remains constant. At +/// most one component of `new_shape` can be -1. The number of dense elements +/// implied by `new_shape` must be the same as the number of dense elements +/// originally implied by `input_shape`. +/// +/// Reshaping does not affect the order of values in the SparseTensor. +/// +/// If the input tensor has rank `R_in` and `N` non-empty values, and `new_shape` +/// has length `R_out`, then `input_indices` has shape `[N, R_in]`, +/// `input_shape` has length `R_in`, `output_indices` has shape `[N, R_out]`, and +/// `output_shape` has length `R_out`. +/// +/// - Parameters: +/// - input_indices: 2-D. `N x R_in` matrix with the indices of non-empty values in a +/// SparseTensor. +/// - input_shape: 1-D. `R_in` vector with the input SparseTensor's dense shape. +/// - new_shape: 1-D. `R_out` vector with the requested new dense shape. +/// +/// - Outputs: +/// - output_indices: 2-D. `N x R_out` matrix with the updated indices of non-empty +/// values in the output SparseTensor. +/// - output_shape: 1-D. `R_out` vector with the full dense shape of the output +/// SparseTensor. This is the same as `new_shape` but with any -1 dimensions +/// filled in. +@inlinable @inline(__always) +public static func sparseReshape( + inputIndices: Tensor, + inputShape: Tensor, + newShape: Tensor +) -> (outputIndices: Tensor, outputShape: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("SparseReshape", nOutputs) + op.addInput(inputIndices) + op.addInput(inputShape) + op.addInput(newShape) + return op.execute(Int(1), Int(1)) +} + +/// Computes the mean along sparse segments of a tensor. +/// +/// See `tf.sparse.segment_sum` for usage examples. +/// +/// Like `SegmentMean`, but `segment_ids` can have rank less than `data`'s first +/// dimension, selecting a subset of dimension 0, specified by `indices`. +/// +/// - Parameters: +/// - indices: A 1-D tensor. Has same rank as `segment_ids`. +/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. +/// +/// - Output output: Has same shape as data, except for dimension 0 which +/// has size `k`, the number of segments. +@inlinable @inline(__always) +public static func sparseSegmentMean< + T: FloatingPoint & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + indices: Tensor, + segmentIds: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseSegmentMean", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(data) + op.addInput(indices) + op.addInput(segmentIds) + return op.execute(Int(1)) +} + +/// Computes gradients for SparseSegmentMean. +/// +/// Returns tensor "output" with same shape as grad, except for dimension 0 whose +/// value is output_dim0. +/// +/// - Parameters: +/// - grad: gradient propagated to the SparseSegmentMean op. +/// - indices: indices passed to the corresponding SparseSegmentMean op. +/// - segment_ids: segment_ids passed to the corresponding SparseSegmentMean op. +/// - output_dim0: dimension 0 of "data" passed to SparseSegmentMean op. +@inlinable @inline(__always) +public static func sparseSegmentMeanGrad< + T: FloatingPoint & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + grad: Tensor, + indices: Tensor, + segmentIds: Tensor, + outputDim0: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseSegmentMeanGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(grad) + op.addInput(indices) + op.addInput(segmentIds) + op.addInput(outputDim0) + return op.execute(Int(1)) +} + +/// Computes the mean along sparse segments of a tensor. +/// +/// Like `SparseSegmentMean`, but allows missing ids in `segment_ids`. If an id is +/// misisng, the `output` tensor at that position will be zeroed. +/// +/// Read +/// [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) +/// for an explanation of segments. +/// +/// - Parameters: +/// - indices: A 1-D tensor. Has same rank as `segment_ids`. +/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. +/// - num_segments: Should equal the number of distinct segment IDs. +/// +/// - Output output: Has same shape as data, except for dimension 0 which has size +/// `num_segments`. +@inlinable @inline(__always) +public static func sparseSegmentMeanWithNumSegments< + T: FloatingPoint & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar, + Tnumsegments: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + indices: Tensor, + segmentIds: Tensor, + numSegments: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseSegmentMeanWithNumSegments", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(indices) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) +} + +/// Computes the sum along sparse segments of a tensor divided by the sqrt of N. +/// +/// N is the size of the segment being reduced. +/// +/// See `tf.sparse.segment_sum` for usage examples. +/// +/// +/// - Parameters: +/// - indices: A 1-D tensor. Has same rank as `segment_ids`. +/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. +/// +/// - Output output: Has same shape as data, except for dimension 0 which +/// has size `k`, the number of segments. +@inlinable @inline(__always) +public static func sparseSegmentSqrtN< + T: FloatingPoint & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + indices: Tensor, + segmentIds: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseSegmentSqrtN", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(data) + op.addInput(indices) + op.addInput(segmentIds) + return op.execute(Int(1)) +} + +/// Computes gradients for SparseSegmentSqrtN. +/// +/// Returns tensor "output" with same shape as grad, except for dimension 0 whose +/// value is output_dim0. +/// +/// - Parameters: +/// - grad: gradient propagated to the SparseSegmentSqrtN op. +/// - indices: indices passed to the corresponding SparseSegmentSqrtN op. +/// - segment_ids: segment_ids passed to the corresponding SparseSegmentSqrtN op. +/// - output_dim0: dimension 0 of "data" passed to SparseSegmentSqrtN op. +@inlinable @inline(__always) +public static func sparseSegmentSqrtNGrad< + T: FloatingPoint & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + grad: Tensor, + indices: Tensor, + segmentIds: Tensor, + outputDim0: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseSegmentSqrtNGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(grad) + op.addInput(indices) + op.addInput(segmentIds) + op.addInput(outputDim0) + return op.execute(Int(1)) +} + +/// Computes the sum along sparse segments of a tensor divided by the sqrt of N. +/// +/// N is the size of the segment being reduced. +/// +/// Like `SparseSegmentSqrtN`, but allows missing ids in `segment_ids`. If an id is +/// misisng, the `output` tensor at that position will be zeroed. +/// +/// Read +/// [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) +/// for an explanation of segments. +/// +/// - Parameters: +/// - indices: A 1-D tensor. Has same rank as `segment_ids`. +/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. +/// - num_segments: Should equal the number of distinct segment IDs. +/// +/// - Output output: Has same shape as data, except for dimension 0 which +/// has size `k`, the number of segments. +@inlinable @inline(__always) +public static func sparseSegmentSqrtNWithNumSegments< + T: FloatingPoint & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar, + Tnumsegments: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + indices: Tensor, + segmentIds: Tensor, + numSegments: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseSegmentSqrtNWithNumSegments", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(indices) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) +} + +/// Computes the sum along sparse segments of a tensor. +/// +/// Read +/// [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) +/// for an explanation of segments. +/// +/// Like `SegmentSum`, but `segment_ids` can have rank less than `data`'s first +/// dimension, selecting a subset of dimension 0, specified by `indices`. +/// +/// For example: +/// +/// ```python +/// c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]) +/// +/// # Select two rows, one segment. +/// tf.sparse_segment_sum(c, tf.constant([0, 1]), tf.constant([0, 0])) +/// # => [[0 0 0 0]] +/// +/// # Select two rows, two segment. +/// tf.sparse_segment_sum(c, tf.constant([0, 1]), tf.constant([0, 1])) +/// # => [[ 1 2 3 4] +/// # [-1 -2 -3 -4]] +/// +/// # Select all rows, two segments. +/// tf.sparse_segment_sum(c, tf.constant([0, 1, 2]), tf.constant([0, 0, 1])) +/// # => [[0 0 0 0] +/// # [5 6 7 8]] +/// +/// # Which is equivalent to: +/// tf.segment_sum(c, tf.constant([0, 0, 1])) +/// ``` +/// +/// - Parameters: +/// - indices: A 1-D tensor. Has same rank as `segment_ids`. +/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. +/// +/// - Output output: Has same shape as data, except for dimension 0 which +/// has size `k`, the number of segments. +@inlinable @inline(__always) +public static func sparseSegmentSum< + T: Numeric & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + indices: Tensor, + segmentIds: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseSegmentSum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(data) + op.addInput(indices) + op.addInput(segmentIds) + return op.execute(Int(1)) +} + +/// Computes the sum along sparse segments of a tensor. +/// +/// Like `SparseSegmentSum`, but allows missing ids in `segment_ids`. If an id is +/// misisng, the `output` tensor at that position will be zeroed. +/// +/// Read +/// [the section on segmentation](https://tensorflow.org/api_docs/python/tf/sparse#Segmentation) +/// for an explanation of segments. +/// +/// For example: +/// +/// ```python +/// c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]) +/// +/// tf.sparse_segment_sum_with_num_segments( +/// c, tf.constant([0, 1]), tf.constant([0, 0]), num_segments=3) +/// # => [[0 0 0 0] +/// # [0 0 0 0] +/// # [0 0 0 0]] +/// +/// tf.sparse_segment_sum_with_num_segments(c, +/// tf.constant([0, 1]), +/// tf.constant([0, 2], +/// num_segments=4)) +/// # => [[ 1 2 3 4] +/// # [ 0 0 0 0] +/// # [-1 -2 -3 -4] +/// # [ 0 0 0 0]] +/// ``` +/// +/// - Parameters: +/// - indices: A 1-D tensor. Has same rank as `segment_ids`. +/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. +/// - num_segments: Should equal the number of distinct segment IDs. +/// +/// - Output output: Has same shape as data, except for dimension 0 which +/// has size `num_segments`. +@inlinable @inline(__always) +public static func sparseSegmentSumWithNumSegments< + T: Numeric & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar, + Tnumsegments: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + indices: Tensor, + segmentIds: Tensor, + numSegments: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseSegmentSumWithNumSegments", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(indices) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) +} + +/// Slice a `SparseTensor` based on the `start` and `size`. +/// +/// For example, if the input is +/// +/// input_tensor = shape = [2, 7] +/// [ a d e ] +/// [b c ] +/// +/// Graphically the output tensors are: +/// +/// sparse_slice([0, 0], [2, 4]) = shape = [2, 4] +/// [ a ] +/// [b c ] +/// +/// sparse_slice([0, 4], [2, 3]) = shape = [2, 3] +/// [ d e ] +/// [ ] +/// +/// - Parameters: +/// - indices: 2-D tensor represents the indices of the sparse tensor. +/// - values: 1-D tensor represents the values of the sparse tensor. +/// - shape: 1-D. tensor represents the shape of the sparse tensor. +/// - start: 1-D. tensor represents the start of the slice. +/// - size: 1-D. tensor represents the size of the slice. +/// output indices: A list of 1-D tensors represents the indices of the output +/// sparse tensors. +/// +/// - Outputs: +/// - output_values: A list of 1-D tensors represents the values of the output sparse +/// tensors. +/// - output_shape: A list of 1-D tensors represents the shape of the output sparse +/// tensors. +@inlinable @inline(__always) +public static func sparseSlice( + indices: Tensor, + _ values: Tensor, + shape: Tensor, + start: Tensor, + size: Tensor +) -> (outputIndices: Tensor, outputValues: Tensor, outputShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("SparseSlice", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(indices) + op.addInput(values) + op.addInput(shape) + op.addInput(start) + op.addInput(size) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// The gradient operator for the SparseSlice op. +/// +/// This op takes in the upstream gradient w.r.t. non-empty values of +/// the sliced `SparseTensor`, and outputs the gradients w.r.t. +/// the non-empty values of input `SparseTensor`. +/// +/// - Parameters: +/// - backprop_val_grad: 1-D. The gradient with respect to +/// the non-empty values of the sliced `SparseTensor`. +/// - input_indices: 2-D. The `indices` of the input `SparseTensor`. +/// - input_start: 1-D. tensor represents the start of the slice. +/// - output_indices: 2-D. The `indices` of the sliced `SparseTensor`. +/// +/// - Output val_grad: 1-D. The gradient with respect to the non-empty values of input `SparseTensor`. +@inlinable @inline(__always) +public static func sparseSliceGrad( + backpropValGrad: Tensor, + inputIndices: Tensor, + inputStart: Tensor, + outputIndices: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseSliceGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(backpropValGrad) + op.addInput(inputIndices) + op.addInput(inputStart) + op.addInput(outputIndices) + return op.execute(Int(1)) +} + +/// Applies softmax to a batched N-D `SparseTensor`. +/// +/// The inputs represent an N-D SparseTensor with logical shape `[..., B, C]` +/// (where `N >= 2`), and with indices sorted in the canonical lexicographic order. +/// +/// This op is equivalent to applying the normal `tf.nn.softmax()` to each innermost +/// logical submatrix with shape `[B, C]`, but with the catch that *the implicitly +/// zero elements do not participate*. Specifically, the algorithm is equivalent +/// to the following: +/// +/// (1) Applies `tf.nn.softmax()` to a densified view of each innermost submatrix +/// with shape `[B, C]`, along the size-C dimension; +/// (2) Masks out the original implicitly-zero locations; +/// (3) Renormalizes the remaining elements. +/// +/// Hence, the `SparseTensor` result has exactly the same non-zero indices and +/// shape. +/// +/// - Parameters: +/// - sp_indices: 2-D. `NNZ x R` matrix with the indices of non-empty values in a +/// SparseTensor, in canonical ordering. +/// - sp_values: 1-D. `NNZ` non-empty values corresponding to `sp_indices`. +/// - sp_shape: 1-D. Shape of the input SparseTensor. +/// +/// - Output output: 1-D. The `NNZ` values for the result `SparseTensor`. +@inlinable @inline(__always) +public static func sparseSoftmax( + spIndices: Tensor, + spValues: Tensor, + spShape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseSoftmax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(spIndices) + op.addInput(spValues) + op.addInput(spShape) + return op.execute(Int(1)) +} + +/// Computes softmax cross entropy cost and gradients to backpropagate. +/// +/// Unlike `SoftmaxCrossEntropyWithLogits`, this operation does not accept +/// a matrix of label probabilities, but rather a single label per row +/// of features. This label is considered to have probability 1.0 for the +/// given row. +/// +/// Inputs are the logits, not probabilities. +/// +/// - Parameters: +/// - features: batch_size x num_classes matrix +/// - labels: batch_size vector with values in [0, num_classes). +/// This is the label for the given minibatch entry. +/// +/// - Outputs: +/// - loss: Per example loss (batch_size vector). +/// - backprop: backpropagated gradients (batch_size x num_classes matrix). +@inlinable @inline(__always) +public static func sparseSoftmaxCrossEntropyWithLogits< + T: FloatingPoint & TensorFlowScalar, + Tlabels: BinaryInteger & TensorFlowScalar +>( + features: Tensor, + labels: Tensor +) -> (loss: Tensor, backprop: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("SparseSoftmaxCrossEntropyWithLogits", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tlabels", Tlabels.tensorFlowDataType) + op.addInput(features) + op.addInput(labels) + return op.execute(Int(1), Int(1)) +} + +/// Returns the element-wise max of two SparseTensors. +/// +/// Assumes the two SparseTensors have the same shape, i.e., no broadcasting. +/// +/// - Parameters: +/// - a_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, in the canonical lexicographic ordering. +/// - a_values: 1-D. `N` non-empty values corresponding to `a_indices`. +/// - a_shape: 1-D. Shape of the input SparseTensor. +/// - b_indices: counterpart to `a_indices` for the other operand. +/// - b_values: counterpart to `a_values` for the other operand; must be of the same dtype. +/// - b_shape: counterpart to `a_shape` for the other operand; the two shapes must be equal. +/// +/// - Outputs: +/// - output_indices: 2-D. The indices of the output SparseTensor. +/// - output_values: 1-D. The values of the output SparseTensor. +@inlinable @inline(__always) +public static func sparseSparseMaximum( + aIndices: Tensor, + aValues: Tensor, + aShape: Tensor, + bIndices: Tensor, + bValues: Tensor, + bShape: Tensor +) -> (outputIndices: Tensor, outputValues: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("SparseSparseMaximum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(aIndices) + op.addInput(aValues) + op.addInput(aShape) + op.addInput(bIndices) + op.addInput(bValues) + op.addInput(bShape) + return op.execute(Int(1), Int(1)) +} + +/// Returns the element-wise min of two SparseTensors. +/// +/// Assumes the two SparseTensors have the same shape, i.e., no broadcasting. +/// +/// - Parameters: +/// - a_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, in the canonical lexicographic ordering. +/// - a_values: 1-D. `N` non-empty values corresponding to `a_indices`. +/// - a_shape: 1-D. Shape of the input SparseTensor. +/// - b_indices: counterpart to `a_indices` for the other operand. +/// - b_values: counterpart to `a_values` for the other operand; must be of the same dtype. +/// - b_shape: counterpart to `a_shape` for the other operand; the two shapes must be equal. +/// +/// - Outputs: +/// - output_indices: 2-D. The indices of the output SparseTensor. +/// - output_values: 1-D. The values of the output SparseTensor. +@inlinable @inline(__always) +public static func sparseSparseMinimum( + aIndices: Tensor, + aValues: Tensor, + aShape: Tensor, + bIndices: Tensor, + bValues: Tensor, + bShape: Tensor +) -> (outputIndices: Tensor, outputValues: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("SparseSparseMinimum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(aIndices) + op.addInput(aValues) + op.addInput(aShape) + op.addInput(bIndices) + op.addInput(bValues) + op.addInput(bShape) + return op.execute(Int(1), Int(1)) +} + +/// Split a `SparseTensor` into `num_split` tensors along one dimension. +/// +/// If the `shape[split_dim]` is not an integer multiple of `num_split`. Slices +/// `[0 : shape[split_dim] % num_split]` gets one extra dimension. +/// For example, if `split_dim = 1` and `num_split = 2` and the input is +/// +/// input_tensor = shape = [2, 7] +/// [ a d e ] +/// [b c ] +/// +/// Graphically the output tensors are: +/// +/// output_tensor[0] = shape = [2, 4] +/// [ a ] +/// [b c ] +/// +/// output_tensor[1] = shape = [2, 3] +/// [ d e ] +/// [ ] +/// +/// - Parameters: +/// - split_dim: 0-D. The dimension along which to split. Must be in the range +/// `[0, rank(shape))`. +/// - indices: 2-D tensor represents the indices of the sparse tensor. +/// - values: 1-D tensor represents the values of the sparse tensor. +/// - shape: 1-D. tensor represents the shape of the sparse tensor. +/// output indices: A list of 1-D tensors represents the indices of the output +/// sparse tensors. +/// +/// - Attr num_split: The number of ways to split. +/// +/// - Outputs: +/// - output_values: A list of 1-D tensors represents the values of the output sparse +/// tensors. +/// - output_shape: A list of 1-D tensors represents the shape of the output sparse +/// tensors. +@inlinable @inline(__always) +public static func sparseSplit( + splitDim: Tensor, + indices: Tensor, + _ values: Tensor, + shape: Tensor, + numSplit: Int64 +) -> (outputIndices: [Tensor], outputValues: [Tensor], outputShape: [Tensor]) { + let nOutputs = Int(numSplit) + Int(numSplit) + Int(numSplit) + let op = makeOp("SparseSplit", nOutputs) + op.updateAttribute("num_split", numSplit) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(splitDim) + op.addInput(indices) + op.addInput(values) + op.addInput(shape) + return op.execute(Int(numSplit), Int(numSplit), Int(numSplit)) +} + +/// Adds up a `SparseTensor` and a dense `Tensor`, producing a dense `Tensor`. +/// +/// This Op does not require `a_indices` be sorted in standard lexicographic order. +/// +/// - Parameters: +/// - a_indices: 2-D. The `indices` of the `SparseTensor`, with shape `[nnz, ndims]`. +/// - a_values: 1-D. The `values` of the `SparseTensor`, with shape `[nnz]`. +/// - a_shape: 1-D. The `shape` of the `SparseTensor`, with shape `[ndims]`. +/// - b: `ndims`-D Tensor. With shape `a_shape`. +@inlinable @inline(__always) +public static func sparseTensorDenseAdd< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + aIndices: Tensor, + aValues: Tensor, + aShape: Tensor, + _ b: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseTensorDenseAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(aIndices) + op.addInput(aValues) + op.addInput(aShape) + op.addInput(b) + return op.execute(Int(1)) +} + +/// Multiply SparseTensor (of rank 2) "A" by dense matrix "B". +/// +/// No validity checking is performed on the indices of A. However, the following +/// input format is recommended for optimal behavior: +/// +/// if adjoint_a == false: +/// A should be sorted in lexicographically increasing order. Use SparseReorder +/// if you're not sure. +/// if adjoint_a == true: +/// A should be sorted in order of increasing dimension 1 (i.e., "column major" +/// order instead of "row major" order). +/// +/// - Parameters: +/// - a_indices: 2-D. The `indices` of the `SparseTensor`, size `[nnz, 2]` Matrix. +/// - a_values: 1-D. The `values` of the `SparseTensor`, size `[nnz]` Vector. +/// - a_shape: 1-D. The `shape` of the `SparseTensor`, size `[2]` Vector. +/// - b: 2-D. A dense Matrix. +/// +/// - Attrs: +/// - adjoint_a: Use the adjoint of A in the matrix multiply. If A is complex, this +/// is transpose(conj(A)). Otherwise it's transpose(A). +/// - adjoint_b: Use the adjoint of B in the matrix multiply. If B is complex, this +/// is transpose(conj(B)). Otherwise it's transpose(B). +@inlinable @inline(__always) +public static func sparseTensorDenseMatMul< + T: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + aIndices: Tensor, + aValues: Tensor, + aShape: Tensor, + _ b: Tensor, + adjointA: Bool = false, + adjointB: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseTensorDenseMatMul", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("adjoint_a", adjointA) + op.updateAttribute("adjoint_b", adjointB) + op.addInput(aIndices) + op.addInput(aValues) + op.addInput(aShape) + op.addInput(b) + return op.execute(Int(1)) +} + +/// Creates a dataset that splits a SparseTensor into elements row-wise. +@inlinable @inline(__always) +public static func sparseTensorSliceDataset( + indices: Tensor, + _ values: Tensor, + denseShape: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("SparseTensorSliceDataset", nOutputs) + op.updateAttribute("Tvalues", Tvalues.tensorFlowDataType) + op.addInput(indices) + op.addInput(values) + op.addInput(denseShape) + return op.execute(Int(1)) +} + +/// Converts a sparse representation into a dense tensor. +/// +/// Builds an array `dense` with shape `output_shape` such that +/// +/// ``` +/// # If sparse_indices is scalar +/// dense[i] = (i == sparse_indices ? sparse_values : default_value) +/// +/// # If sparse_indices is a vector, then for each i +/// dense[sparse_indices[i]] = sparse_values[i] +/// +/// # If sparse_indices is an n by d matrix, then for each i in [0, n) +/// dense[sparse_indices[i][0], ..., sparse_indices[i][d-1]] = sparse_values[i] +/// ``` +/// +/// All other values in `dense` are set to `default_value`. If `sparse_values` is a +/// scalar, all sparse indices are set to this single value. +/// +/// Indices should be sorted in lexicographic order, and indices must not +/// contain any repeats. If `validate_indices` is true, these properties +/// are checked during execution. +/// +/// - Parameters: +/// - sparse_indices: 0-D, 1-D, or 2-D. `sparse_indices[i]` contains the complete +/// index where `sparse_values[i]` will be placed. +/// - output_shape: 1-D. Shape of the dense output tensor. +/// - sparse_values: 1-D. Values corresponding to each row of `sparse_indices`, +/// or a scalar value to be used for all sparse indices. +/// - default_value: Scalar value to set for indices not specified in +/// `sparse_indices`. +/// +/// - Attr validate_indices: If true, indices are checked to make sure they are sorted in +/// lexicographic order and that there are no repeats. +/// +/// - Output dense: Dense output tensor of shape `output_shape`. +@inlinable @inline(__always) +public static func sparseToDense< + T: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + sparseIndices: Tensor, + outputShape: Tensor, + sparseValues: Tensor, + defaultValue: Tensor, + validateIndices: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseToDense", nOutputs) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(sparseIndices) + op.addInput(outputShape) + op.addInput(sparseValues) + op.addInput(defaultValue) + return op.execute(Int(1)) +} + +/// Applies set operation along last dimension of 2 `SparseTensor` inputs. +/// +/// See SetOperationOp::SetOperationFromContext for values of `set_operation`. +/// +/// If `validate_indices` is `True`, `SparseToSparseSetOperation` validates the +/// order and range of `set1` and `set2` indices. +/// +/// Input `set1` is a `SparseTensor` represented by `set1_indices`, `set1_values`, +/// and `set1_shape`. For `set1` ranked `n`, 1st `n-1` dimensions must be the same +/// as `set2`. Dimension `n` contains values in a set, duplicates are allowed but +/// ignored. +/// +/// Input `set2` is a `SparseTensor` represented by `set2_indices`, `set2_values`, +/// and `set2_shape`. For `set2` ranked `n`, 1st `n-1` dimensions must be the same +/// as `set1`. Dimension `n` contains values in a set, duplicates are allowed but +/// ignored. +/// +/// If `validate_indices` is `True`, this op validates the order and range of `set1` +/// and `set2` indices. +/// +/// Output `result` is a `SparseTensor` represented by `result_indices`, +/// `result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this +/// has rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth` +/// dimension contains the result of `set_operation` applied to the corresponding +/// `[0...n-1]` dimension of `set`. +/// +/// - Parameters: +/// - set1_indices: 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major +/// order. +/// - set1_values: 1D `Tensor`, values of a `SparseTensor`. Must be in row-major +/// order. +/// - set1_shape: 1D `Tensor`, shape of a `SparseTensor`. `set1_shape[0...n-1]` must +/// be the same as `set2_shape[0...n-1]`, `set1_shape[n]` is the +/// max set size across `0...n-1` dimensions. +/// - set2_indices: 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major +/// order. +/// - set2_values: 1D `Tensor`, values of a `SparseTensor`. Must be in row-major +/// order. +/// - set2_shape: 1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must +/// be the same as `set1_shape[0...n-1]`, `set2_shape[n]` is the +/// max set size across `0...n-1` dimensions. +/// +/// - Outputs: +/// - result_indices: 2D indices of a `SparseTensor`. +/// - result_values: 1D values of a `SparseTensor`. +/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is +/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` +/// is the max result set size across all `0...n-1` dimensions. +@inlinable @inline(__always) +public static func sparseToSparseSetOperation( + set1Indices: Tensor, + set1Values: Tensor, + set1Shape: Tensor, + set2Indices: Tensor, + set2Values: Tensor, + set2Shape: Tensor, + setOperation: String, + validateIndices: Bool = true +) -> (resultIndices: Tensor, resultValues: Tensor, resultShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("SparseToSparseSetOperation", nOutputs) + op.updateAttribute("set_operation", setOperation) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(set1Indices) + op.addInput(set1Values) + op.addInput(set1Shape) + op.addInput(set2Indices) + op.addInput(set2Values) + op.addInput(set2Shape) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Applies set operation along last dimension of 2 `SparseTensor` inputs. +/// +/// See SetOperationOp::SetOperationFromContext for values of `set_operation`. +/// +/// If `validate_indices` is `True`, `SparseToSparseSetOperation` validates the +/// order and range of `set1` and `set2` indices. +/// +/// Input `set1` is a `SparseTensor` represented by `set1_indices`, `set1_values`, +/// and `set1_shape`. For `set1` ranked `n`, 1st `n-1` dimensions must be the same +/// as `set2`. Dimension `n` contains values in a set, duplicates are allowed but +/// ignored. +/// +/// Input `set2` is a `SparseTensor` represented by `set2_indices`, `set2_values`, +/// and `set2_shape`. For `set2` ranked `n`, 1st `n-1` dimensions must be the same +/// as `set1`. Dimension `n` contains values in a set, duplicates are allowed but +/// ignored. +/// +/// If `validate_indices` is `True`, this op validates the order and range of `set1` +/// and `set2` indices. +/// +/// Output `result` is a `SparseTensor` represented by `result_indices`, +/// `result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this +/// has rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth` +/// dimension contains the result of `set_operation` applied to the corresponding +/// `[0...n-1]` dimension of `set`. +/// +/// - Parameters: +/// - set1_indices: 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major +/// order. +/// - set1_values: 1D `Tensor`, values of a `SparseTensor`. Must be in row-major +/// order. +/// - set1_shape: 1D `Tensor`, shape of a `SparseTensor`. `set1_shape[0...n-1]` must +/// be the same as `set2_shape[0...n-1]`, `set1_shape[n]` is the +/// max set size across `0...n-1` dimensions. +/// - set2_indices: 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major +/// order. +/// - set2_values: 1D `Tensor`, values of a `SparseTensor`. Must be in row-major +/// order. +/// - set2_shape: 1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must +/// be the same as `set1_shape[0...n-1]`, `set2_shape[n]` is the +/// max set size across `0...n-1` dimensions. +/// +/// - Outputs: +/// - result_indices: 2D indices of a `SparseTensor`. +/// - result_values: 1D values of a `SparseTensor`. +/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is +/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` +/// is the max result set size across all `0...n-1` dimensions. +@inlinable @inline(__always) +public static func sparseToSparseSetOperation( + set1Indices: Tensor, + set1Values: StringTensor, + set1Shape: Tensor, + set2Indices: Tensor, + set2Values: StringTensor, + set2Shape: Tensor, + setOperation: String, + validateIndices: Bool = true +) -> (resultIndices: Tensor, resultValues: StringTensor, resultShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("SparseToSparseSetOperation", nOutputs) + op.updateAttribute("set_operation", setOperation) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(set1Indices) + op.addInput(set1Values) + op.addInput(set1Shape) + op.addInput(set2Indices) + op.addInput(set2Values) + op.addInput(set2Shape) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Splits a tensor into `num_split` tensors along one dimension. +/// +/// - Parameters: +/// - split_dim: 0-D. The dimension along which to split. Must be in the range +/// `[-rank(value), rank(value))`. +/// - value: The tensor to split. +/// +/// - Attr num_split: The number of ways to split. Must evenly divide +/// `value.shape[split_dim]`. +/// +/// - Output output: They are identically shaped tensors, whose shape matches that of `value` +/// except along `axis`, where their sizes are +/// `values.shape[split_dim] / num_split`. +@inlinable @inline(__always) +public static func split( + splitDim: Tensor, + value: Tensor, + numSplit: Int64 +) -> [Tensor] { + let nOutputs = Int(numSplit) + let op = makeOp("Split", nOutputs) + op.updateAttribute("num_split", numSplit) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(splitDim) + op.addInput(value) + return op.execute(Int(numSplit)) +} + +/// Splits a tensor into `num_split` tensors along one dimension. +/// +/// - Parameters: +/// - value: The tensor to split. +/// - size_splits: list containing the sizes of each output tensor along the split +/// dimension. Must sum to the dimension of value along split_dim. +/// Can contain one -1 indicating that dimension is to be inferred. +/// - split_dim: 0-D. The dimension along which to split. Must be in the range +/// `[-rank(value), rank(value))`. +/// +/// - Output output: Tensors whose shape matches that of `value` +/// except along `axis`, where their sizes are +/// `size_splits[i]`. +@inlinable @inline(__always) +public static func splitV< + T: TensorFlowScalar, + Tlen: BinaryInteger & TensorFlowScalar +>( + value: Tensor, + sizeSplits: Tensor, + splitDim: Tensor, + numSplit: Int64 +) -> [Tensor] { + let nOutputs = Int(numSplit) + let op = makeOp("SplitV", nOutputs) + op.updateAttribute("num_split", numSplit) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tlen", Tlen.tensorFlowDataType) + op.addInput(value) + op.addInput(sizeSplits) + op.addInput(splitDim) + return op.execute(Int(numSplit)) +} + +/// Computes square root of x element-wise. +/// +/// I.e., \\(y = \sqrt{x} = x^{1/2}\\). +@inlinable @inline(__always) +public static func sqrt( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Sqrt", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the gradient for the sqrt of `x` wrt its input. +/// +/// Specifically, `grad = dy * 0.5 / y`, where `y = sqrt(x)`, and `dy` +/// is the corresponding input gradient. +@inlinable @inline(__always) +public static func sqrtGrad( + _ y: Tensor, + dy: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SqrtGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(dy) + return op.execute(Int(1)) +} + +/// Computes square of x element-wise. +/// +/// I.e., \\(y = x * x = x^2\\). +@inlinable @inline(__always) +public static func square( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Square", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Returns (x - y)(x - y) element-wise. +/// +/// *NOTE*: `SquaredDifference` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func squaredDifference( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SquaredDifference", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Removes dimensions of size 1 from the shape of a tensor. +/// +/// Given a tensor `input`, this operation returns a tensor of the same type with +/// all dimensions of size 1 removed. If you don't want to remove all size 1 +/// dimensions, you can remove specific size 1 dimensions by specifying +/// `axis`. +/// +/// For example: +/// +/// ``` +/// # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] +/// shape(squeeze(t)) ==> [2, 3] +/// ``` +/// +/// Or, to remove specific size 1 dimensions: +/// +/// ``` +/// # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] +/// shape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1] +/// ``` +/// +/// - Parameter input: The `input` to squeeze. +/// +/// - Attr squeeze_dims: If specified, only squeezes the dimensions listed. The dimension +/// index starts at 0. It is an error to squeeze a dimension that is not 1. Must +/// be in the range `[-rank(input), rank(input))`. +/// +/// - Output output: Contains the same data as `input`, but has one or more dimensions of +/// size 1 removed. +@inlinable @inline(__always) +public static func squeeze( + _ input: Tensor, + squeezeDims: [Int32] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Squeeze", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("squeeze_dims", squeezeDims) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Delete the stack from its resource container. +/// +/// - Parameter handle: The handle to a stack. +@inlinable @inline(__always) +public static func stackCloseV2( + handle: ResourceHandle +) { + let nOutputs = 0 + let op = makeOp("StackCloseV2", nOutputs) + op.addInput(handle) + op.execute() +} + +/// Pop the element at the top of the stack. +/// +/// - Parameter handle: The handle to a stack. +/// +/// - Attr elem_type: The type of the elem that is popped. +/// +/// - Output elem: The tensor that is popped from the top of the stack. +@inlinable @inline(__always) +public static func stackPopV2( + handle: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StackPopV2", nOutputs) + op.updateAttribute("elem_type", ElemType.tensorFlowDataType) + op.addInput(handle) + return op.execute(Int(1)) +} + +/// Push an element onto the stack. +/// +/// - Parameters: +/// - handle: The handle to a stack. +/// - elem: The tensor to be pushed onto the stack. +/// +/// - Attr swap_memory: Swap `elem` to CPU. Default to false. +/// +/// - Output output: The same tensor as the input 'elem'. +@inlinable @inline(__always) +public static func stackPushV2( + handle: ResourceHandle, + elem: Tensor, + swapMemory: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StackPushV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("swap_memory", swapMemory) + op.addInput(handle) + op.addInput(elem) + return op.execute(Int(1)) +} + +/// A stack that produces elements in first-in last-out order. +/// +/// - Parameter max_size: The maximum size of the stack if non-negative. If negative, the stack +/// size is unlimited. +/// +/// - Attrs: +/// - elem_type: The type of the elements on the stack. +/// - stack_name: Overrides the name used for the temporary stack resource. Default +/// value is the name of the 'Stack' op (which is guaranteed unique). +/// +/// - Output handle: The handle to the stack. +@inlinable @inline(__always) +public static func stackV2( + maxSize: Tensor, + elemType: TensorDataType, + stackName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("StackV2", nOutputs) + op.updateAttribute("elem_type", elemType) + op.updateAttribute("stack_name", stackName) + op.addInput(maxSize) + return op.execute(Int(1)) +} + +/// Stage values similar to a lightweight Enqueue. +/// +/// The basic functionality of this Op is similar to a queue with many +/// fewer capabilities and options. This Op is optimized for performance. +/// +/// - Parameter values: a list of tensors +/// dtypes A list of data types that inserted values should adhere to. +/// +/// - Attrs: +/// - capacity: Maximum number of elements in the Staging Area. If > 0, inserts +/// on the container will block when the capacity is reached. +/// - memory_limit: The maximum number of bytes allowed for Tensors in the Staging Area. +/// If > 0, inserts will block until sufficient space is available. +/// - container: If non-empty, this queue is placed in the given container. Otherwise, +/// a default container is used. +/// - shared_name: It is necessary to match this name to the matching Unstage Op. +@inlinable @inline(__always) +public static func stage( + _ values: Dtypes, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String +) { + let nOutputs = 0 + let op = makeOp("Stage", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", values._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInputList(values) + op.execute() +} + +/// Op removes all elements in the underlying container. +@inlinable @inline(__always) +public static func stageClear( + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String +) { + let nOutputs = 0 + let op = makeOp("StageClear", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.execute() +} + +/// Op peeks at the values at the specified index. If the +/// +/// underlying container does not contain sufficient elements +/// this op will block until it does. This Op is optimized for +/// performance. +@inlinable @inline(__always) +public static func stagePeek( + index: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String +) -> Dtypes { + let nOutputs = Int(Dtypes._typeList.count) + let op = makeOp("StagePeek", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(index) + return op.execute(Int(Dtypes._typeList.count)) +} + +/// Op returns the number of elements in the underlying container. +@inlinable @inline(__always) +public static func stageSize( + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StageSize", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// returns `f(inputs)`, where `f`'s body is placed and partitioned. +/// +/// - Parameter args: A list of input tensors. +/// +/// - Attrs: +/// - Tin: A list of input types. +/// - Tout: A list of output types. +/// - f: A function that takes 'args', a list of tensors, and returns 'output', +/// another list of tensors. Input and output types are specified by 'Tin' +/// and 'Tout'. The function body of f will be placed and partitioned across +/// devices, setting this op apart from the regular Call op. This op is +/// stateful. +/// +/// - Output output: A list of return values. +@inlinable @inline(__always) +public static func statefulPartitionedCall< + Tin: TensorArrayProtocol, + Tout: TensorGroup, + FIn: TensorGroup, + FOut: TensorGroup +>( + args: Tin, + f: (FIn) -> FOut, + config: String, + configProto: String, + executorType: String +) -> Tout { + let nOutputs = Int(Tout._typeList.count) + let op = makeOp("StatefulPartitionedCall", nOutputs) + op.updateAttribute("Tin", args._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("f", f) + op.updateAttribute("config", config) + op.updateAttribute("config_proto", configProto) + op.updateAttribute("executor_type", executorType) + op.addInputList(args) + return op.execute(Int(Tout._typeList.count)) +} + +@inlinable @inline(__always) +public static func statefulRandomBinomial< + S: BinaryInteger & TensorFlowScalar, + T: Numeric & TensorFlowScalar, + Dtype: Numeric & TensorFlowScalar +>( + resource: ResourceHandle, + algorithm: Tensor, + shape: Tensor, + counts: Tensor, + probs: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StatefulRandomBinomial", nOutputs) + op.updateAttribute("S", S.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(algorithm) + op.addInput(shape) + op.addInput(counts) + op.addInput(probs) + return op.execute(Int(1)) +} + +/// Outputs random values from a normal distribution. This op is deprecated in favor of op 'StatefulStandardNormalV2' +/// +/// The generated values will have mean 0 and standard deviation 1. +/// +/// - Parameters: +/// - resource: The handle of the resource variable that stores the state of the RNG. +/// - shape: The shape of the output tensor. +/// +/// - Attr dtype: The type of the output. +/// +/// - Output output: A tensor of the specified shape filled with random normal values. +@inlinable @inline(__always) +public static func statefulStandardNormal< + Dtype: TensorFlowScalar, + ShapeDtype: TensorFlowScalar +>( + resource: ResourceHandle, + shape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StatefulStandardNormal", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(shape) + return op.execute(Int(1)) +} + +/// Outputs random values from a normal distribution. +/// +/// The generated values will have mean 0 and standard deviation 1. +/// +/// - Parameters: +/// - resource: The handle of the resource variable that stores the state of the RNG. +/// - algorithm: The RNG algorithm. +/// - shape: The shape of the output tensor. +/// +/// - Attr dtype: The type of the output. +/// +/// - Output output: A tensor of the specified shape filled with random normal values. +@inlinable @inline(__always) +public static func statefulStandardNormalV2< + Dtype: TensorFlowScalar, + ShapeDtype: TensorFlowScalar +>( + resource: ResourceHandle, + algorithm: Tensor, + shape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StatefulStandardNormalV2", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(algorithm) + op.addInput(shape) + return op.execute(Int(1)) +} + +/// Outputs random values from a truncated normal distribution. +/// +/// The generated values follow a normal distribution with mean 0 and standard +/// deviation 1, except that values whose magnitude is more than 2 standard +/// deviations from the mean are dropped and re-picked. +/// +/// - Parameters: +/// - resource: The handle of the resource variable that stores the state of the RNG. +/// - algorithm: The RNG algorithm. +/// - shape: The shape of the output tensor. +/// +/// - Attr dtype: The type of the output. +/// +/// - Output output: Random values with specified shape. +@inlinable @inline(__always) +public static func statefulTruncatedNormal< + Dtype: TensorFlowScalar, + ShapeDtype: TensorFlowScalar +>( + resource: ResourceHandle, + algorithm: Tensor, + shape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StatefulTruncatedNormal", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(algorithm) + op.addInput(shape) + return op.execute(Int(1)) +} + +/// Outputs random values from a uniform distribution. +/// +/// The generated values follow a uniform distribution in the range `[0, 1)`. The +/// lower bound 0 is included in the range, while the upper bound 1 is excluded. +/// +/// - Parameters: +/// - resource: The handle of the resource variable that stores the state of the RNG. +/// - algorithm: The RNG algorithm. +/// - shape: The shape of the output tensor. +/// +/// - Attr dtype: The type of the output. +/// +/// - Output output: Random values with specified shape. +@inlinable @inline(__always) +public static func statefulUniform< + Dtype: TensorFlowScalar, + ShapeDtype: TensorFlowScalar +>( + resource: ResourceHandle, + algorithm: Tensor, + shape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StatefulUniform", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(algorithm) + op.addInput(shape) + return op.execute(Int(1)) +} + +/// Outputs random integers from a uniform distribution. +/// +/// The generated values are uniform integers covering the whole range of `dtype`. +/// +/// - Parameters: +/// - resource: The handle of the resource variable that stores the state of the RNG. +/// - algorithm: The RNG algorithm. +/// - shape: The shape of the output tensor. +/// +/// - Attr dtype: The type of the output. +/// +/// - Output output: Random values with specified shape. +@inlinable @inline(__always) +public static func statefulUniformFullInt< + Dtype: TensorFlowScalar, + ShapeDtype: TensorFlowScalar +>( + resource: ResourceHandle, + algorithm: Tensor, + shape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StatefulUniformFullInt", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(algorithm) + op.addInput(shape) + return op.execute(Int(1)) +} + +/// Outputs random integers from a uniform distribution. +/// +/// The generated values are uniform integers in the range `[minval, maxval)`. +/// The lower bound `minval` is included in the range, while the upper bound +/// `maxval` is excluded. +/// +/// The random integers are slightly biased unless `maxval - minval` is an exact +/// power of two. The bias is small for values of `maxval - minval` significantly +/// smaller than the range of the output (either `2^32` or `2^64`). +/// +/// - Parameters: +/// - resource: The handle of the resource variable that stores the state of the RNG. +/// - algorithm: The RNG algorithm. +/// - shape: The shape of the output tensor. +/// - minval: Minimum value (inclusive, scalar). +/// - maxval: Maximum value (exclusive, scalar). +/// +/// - Attr dtype: The type of the output. +/// +/// - Output output: Random values with specified shape. +@inlinable @inline(__always) +public static func statefulUniformInt< + Dtype: TensorFlowScalar, + ShapeDtype: TensorFlowScalar +>( + resource: ResourceHandle, + algorithm: Tensor, + shape: Tensor, + minval: Tensor, + maxval: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StatefulUniformInt", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(algorithm) + op.addInput(shape) + op.addInput(minval) + op.addInput(maxval) + return op.execute(Int(1)) +} + +/// output = cond ? then_branch(input) : else_branch(input) +/// +/// - Parameters: +/// - cond: A Tensor. If the tensor is a scalar of non-boolean type, the +/// scalar is converted to a boolean according to the +/// following rule: if the scalar is a numerical value, non-zero means +/// `True` and zero means False; if the scalar is a string, non-empty +/// means `True` and empty means `False`. If the tensor is not a scalar, +/// being empty means False and being non-empty means True. +/// +/// This should only be used when the if then/else body functions do not +/// have stateful ops. +/// - input: A list of input tensors. +/// +/// - Attrs: +/// - Tin: A list of input types. +/// - Tout: A list of output types. +/// - then_branch: A function that takes 'inputs' and returns a list of tensors, whose +/// types are the same as what else_branch returns. +/// - else_branch: A function that takes 'inputs' and returns a list of tensors, whose +/// types are the same as what then_branch returns. +/// +/// - Output output: A list of return values. +@inlinable @inline(__always) +public static func statelessIf< + Tcond: TensorFlowScalar, + Tin: TensorArrayProtocol, + Tout: TensorGroup, + ThenbranchIn: TensorGroup, + ThenbranchOut: TensorGroup, + ElsebranchIn: TensorGroup, + ElsebranchOut: TensorGroup +>( + cond: Tensor, + _ input: Tin, + thenBranch: (ThenbranchIn) -> ThenbranchOut, + elseBranch: (ElsebranchIn) -> ElsebranchOut +) -> Tout { + let nOutputs = Int(Tout._typeList.count) + let op = makeOp("StatelessIf", nOutputs) + op.updateAttribute("Tcond", Tcond.tensorFlowDataType) + op.updateAttribute("Tin", input._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("then_branch", thenBranch) + op.updateAttribute("else_branch", elseBranch) + op.addInput(cond) + op.addInputList(input) + return op.execute(Int(Tout._typeList.count)) +} + +/// Draws samples from a multinomial distribution. +/// +/// - Parameters: +/// - logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]` +/// represents the unnormalized log probabilities for all classes. +/// - num_samples: 0-D. Number of independent samples to draw for each row slice. +/// - seed: 2 seeds (shape [2]). +/// +/// - Output output: 2-D Tensor with shape `[batch_size, num_samples]`. Each slice `[i, :]` +/// contains the drawn class labels with range `[0, num_classes)`. +@inlinable @inline(__always) +public static func statelessMultinomial< + T: Numeric & TensorFlowScalar, + Tseed: BinaryInteger & TensorFlowScalar, + OutputDtype: BinaryInteger & TensorFlowScalar +>( + logits: Tensor, + numSamples: Tensor, + seed: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StatelessMultinomial", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tseed", Tseed.tensorFlowDataType) + op.updateAttribute("output_dtype", OutputDtype.tensorFlowDataType) + op.addInput(logits) + op.addInput(numSamples) + op.addInput(seed) + return op.execute(Int(1)) +} + +/// Outputs deterministic pseudorandom values from a normal distribution. +/// +/// The generated values will have mean 0 and standard deviation 1. +/// +/// The outputs are a deterministic function of `shape` and `seed`. +/// +/// - Parameters: +/// - shape: The shape of the output tensor. +/// - seed: 2 seeds (shape [2]). +/// +/// - Attr dtype: The type of the output. +/// +/// - Output output: Random values with specified shape. +@inlinable @inline(__always) +public static func statelessRandomNormal< + Dtype: FloatingPoint & TensorFlowScalar, + T: BinaryInteger & TensorFlowScalar, + Tseed: BinaryInteger & TensorFlowScalar +>( + shape: Tensor, + seed: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StatelessRandomNormal", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tseed", Tseed.tensorFlowDataType) + op.addInput(shape) + op.addInput(seed) + return op.execute(Int(1)) +} + +/// Outputs deterministic pseudorandom random values from a uniform distribution. +/// +/// The generated values follow a uniform distribution in the range `[0, 1)`. The +/// lower bound 0 is included in the range, while the upper bound 1 is excluded. +/// +/// The outputs are a deterministic function of `shape` and `seed`. +/// +/// - Parameters: +/// - shape: The shape of the output tensor. +/// - seed: 2 seeds (shape [2]). +/// +/// - Attr dtype: The type of the output. +/// +/// - Output output: Random values with specified shape. +@inlinable @inline(__always) +public static func statelessRandomUniform< + Dtype: FloatingPoint & TensorFlowScalar, + T: BinaryInteger & TensorFlowScalar, + Tseed: BinaryInteger & TensorFlowScalar +>( + shape: Tensor, + seed: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StatelessRandomUniform", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tseed", Tseed.tensorFlowDataType) + op.addInput(shape) + op.addInput(seed) + return op.execute(Int(1)) +} + +/// Outputs deterministic pseudorandom random integers from a uniform distribution. +/// +/// The generated values follow a uniform distribution in the range `[minval, maxval)`. +/// +/// The outputs are a deterministic function of `shape`, `seed`, `minval`, and `maxval`. +/// +/// - Parameters: +/// - shape: The shape of the output tensor. +/// - seed: 2 seeds (shape [2]). +/// - minval: Minimum value (inclusive, scalar). +/// - maxval: Maximum value (exclusive, scalar). +/// +/// - Attr dtype: The type of the output. +/// +/// - Output output: Random values with specified shape. +@inlinable @inline(__always) +public static func statelessRandomUniformInt< + Dtype: BinaryInteger & TensorFlowScalar, + T: BinaryInteger & TensorFlowScalar, + Tseed: BinaryInteger & TensorFlowScalar +>( + shape: Tensor, + seed: Tensor, + minval: Tensor, + maxval: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StatelessRandomUniformInt", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tseed", Tseed.tensorFlowDataType) + op.addInput(shape) + op.addInput(seed) + op.addInput(minval) + op.addInput(maxval) + return op.execute(Int(1)) +} + +/// Outputs deterministic pseudorandom values from a truncated normal distribution. +/// +/// The generated values follow a normal distribution with mean 0 and standard +/// deviation 1, except that values whose magnitude is more than 2 standard +/// deviations from the mean are dropped and re-picked. +/// +/// The outputs are a deterministic function of `shape` and `seed`. +/// +/// - Parameters: +/// - shape: The shape of the output tensor. +/// - seed: 2 seeds (shape [2]). +/// +/// - Attr dtype: The type of the output. +/// +/// - Output output: Random values with specified shape. +@inlinable @inline(__always) +public static func statelessTruncatedNormal< + Dtype: FloatingPoint & TensorFlowScalar, + T: BinaryInteger & TensorFlowScalar, + Tseed: BinaryInteger & TensorFlowScalar +>( + shape: Tensor, + seed: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StatelessTruncatedNormal", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tseed", Tseed.tensorFlowDataType) + op.addInput(shape) + op.addInput(seed) + return op.execute(Int(1)) +} + +/// output = input; While (Cond(output)) { output = Body(output) } +/// +/// - Parameter input: A list of input tensors whose types are T. +/// +/// - Attrs: +/// - T: dtype in use. +/// - cond: A function takes 'input' and returns a tensor. If the tensor is +/// a scalar of non-boolean, the scalar is converted to a boolean +/// according to the following rule: if the scalar is a numerical +/// value, non-zero means True and zero means False; if the scalar is +/// a string, non-empty means True and empty means False. If the +/// tensor is not a scalar, non-emptiness means True and False +/// otherwise. +/// +/// This should only be used when the while condition and body functions +/// do not have stateful ops. +/// - body: A function that takes a list of tensors and returns another +/// list of tensors. Both lists have the same types as specified +/// by T. +/// +/// - Output output: A list of output tensors whose types are T. +@inlinable @inline(__always) +public static func statelessWhile< + T: TensorArrayProtocol, + CondIn: TensorGroup, + CondOut: TensorGroup, + BodyIn: TensorGroup, + BodyOut: TensorGroup +>( + _ input: T, + cond: (CondIn) -> CondOut, + body: (BodyIn) -> BodyOut +) -> T { + let nOutputs = Int(input._typeList.count) + let op = makeOp("StatelessWhile", nOutputs) + op.updateAttribute("T", input._typeList) + op.updateAttribute("cond", cond) + op.updateAttribute("body", body) + op.addInputList(input) + return op.execute(Int(input._typeList.count)) +} + +/// Check if the input matches the regex pattern. +/// +/// The input is a string tensor of any shape. The pattern is the +/// regular expression to be matched with every element of the input tensor. +/// The boolean values (True or False) of the output tensor indicate +/// if the input matches the regex pattern provided. +/// +/// The pattern follows the re2 syntax (https://github.com/google/re2/wiki/Syntax) +/// +/// - Parameter input: A string tensor of the text to be processed. +/// +/// - Attr pattern: The regular expression to match the input. +/// +/// - Output output: A bool tensor with the same shape as `input`. +@inlinable @inline(__always) +public static func staticRegexFullMatch( + _ input: StringTensor, + pattern: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StaticRegexFullMatch", nOutputs) + op.updateAttribute("pattern", pattern) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Replaces the match of pattern in input with rewrite. +/// +/// It follows the re2 syntax (https://github.com/google/re2/wiki/Syntax) +/// +/// - Parameter input: The text to be processed. +/// +/// - Attrs: +/// - pattern: The regular expression to match the input. +/// - rewrite: The rewrite to be applied to the matched expression. +/// - replace_global: If True, the replacement is global, otherwise the replacement +/// is done only on the first match. +/// +/// - Output output: The text after applying pattern and rewrite. +@inlinable @inline(__always) +public static func staticRegexReplace( + _ input: StringTensor, + pattern: String, + rewrite: String, + replaceGlobal: Bool = true +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("StaticRegexReplace", nOutputs) + op.updateAttribute("pattern", pattern) + op.updateAttribute("rewrite", rewrite) + op.updateAttribute("replace_global", replaceGlobal) + op.addInput(input) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func statsAggregatorHandleV2( + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("StatsAggregatorHandleV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Set a summary_writer_interface to record statistics using given stats_aggregator. +@inlinable @inline(__always) +public static func statsAggregatorSetSummaryWriter( + statsAggregator: ResourceHandle, + summary: ResourceHandle +) { + let nOutputs = 0 + let op = makeOp("StatsAggregatorSetSummaryWriter", nOutputs) + op.addInput(statsAggregator) + op.addInput(summary) + op.execute() +} + +/// Stops gradient computation. +/// +/// When executed in a graph, this op outputs its input tensor as-is. +/// +/// When building ops to compute gradients, this op prevents the contribution of +/// its inputs to be taken into account. Normally, the gradient generator adds ops +/// to a graph to compute the derivatives of a specified 'loss' by recursively +/// finding out inputs that contributed to its computation. If you insert this op +/// in the graph it inputs are masked from the gradient generator. They are not +/// taken into account for computing gradients. +/// +/// This is useful any time you want to compute a value with TensorFlow but need +/// to pretend that the value was a constant. Some examples include: +/// +/// * The *EM* algorithm where the *M-step* should not involve backpropagation +/// through the output of the *E-step*. +/// * Contrastive divergence training of Boltzmann machines where, when +/// differentiating the energy function, the training must not backpropagate +/// through the graph that generated the samples from the model. +/// * Adversarial training, where no backprop should happen through the adversarial +/// example generation process. +@inlinable @inline(__always) +public static func stopGradient( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StopGradient", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Return a strided slice from `input`. +/// +/// Note, most python users will want to use the Python `Tensor.__getitem__` +/// or `Variable.__getitem__` rather than this op directly. +/// +/// The goal of this op is to produce a new tensor with a subset of +/// the elements from the `n` dimensional `input` tensor. The subset is chosen using +/// a sequence of `m` sparse range specifications encoded into the arguments +/// of this function. Note, in some cases +/// `m` could be equal to `n`, but this need not be the case. Each +/// range specification entry can be one of the following: +/// +/// - An ellipsis (...). Ellipses are used to imply zero or more +/// dimensions of full-dimension selection and are produced using +/// `ellipsis_mask`. For example, `foo[...]` is the identity slice. +/// +/// - A new axis. This is used to insert a new shape=1 dimension and is +/// produced using `new_axis_mask`. For example, `foo[:, ...]` where +/// `foo` is shape `(3, 4)` produces a `(1, 3, 4)` tensor. +/// +/// +/// - A range `begin:end:stride`. This is used to specify how much to choose from +/// a given dimension. `stride` can be any integer but 0. `begin` is an integer +/// which represents the index of the first value to select while `end` represents +/// the index of the last value to select. The number of values selected in each +/// dimension is `end - begin` if `stride > 0` and `begin - end` if `stride < 0`. +/// `begin` and `end` can be negative where `-1` is the last element, `-2` is +/// the second to last. `begin_mask` controls whether to replace the explicitly +/// given `begin` with an implicit effective value of `0` if `stride > 0` and +/// `-1` if `stride < 0`. `end_mask` is analogous but produces the number +/// required to create the largest open interval. For example, given a shape +/// `(3,)` tensor `foo[:]`, the effective `begin` and `end` are `0` and `3`. Do +/// not assume this is equivalent to `foo[0:-1]` which has an effective `begin` +/// and `end` of `0` and `2`. Another example is `foo[-2::-1]` which reverses the +/// first dimension of a tensor while dropping the last two (in the original +/// order elements). For example `foo = [1,2,3,4]; foo[-2::-1]` is `[4,3]`. +/// +/// - A single index. This is used to keep only elements that have a given +/// index. For example (`foo[2, :]` on a shape `(5,6)` tensor produces a +/// shape `(6,)` tensor. This is encoded in `begin` and `end` and +/// `shrink_axis_mask`. +/// +/// Each conceptual range specification is encoded in the op's argument. This +/// encoding is best understand by considering a non-trivial example. In +/// particular, +/// `foo[1, 2:4, None, ..., :-3:-1, :]` will be encoded as +/// +/// ``` +/// begin = [1, 2, x, x, 0, x] # x denotes don't care (usually 0) +/// end = [2, 4, x, x, -3, x] +/// strides = [1, 1, x, x, -1, 1] +/// begin_mask = 1<<4 | 1 << 5 = 48 +/// end_mask = 1<<5 = 32 +/// ellipsis_mask = 1<<3 = 8 +/// new_axis_mask = 1<<2 4 +/// shrink_axis_mask = 1<<0 +/// ``` +/// +/// In this case if `foo.shape` is (5, 5, 5, 5, 5, 5) the final shape of +/// the slice becomes (2, 1, 5, 5, 2, 5). +/// Let us walk step by step through each argument specification. +/// +/// 1. The first argument in the example slice is turned into `begin = 1` and +/// `end = begin + 1 = 2`. To disambiguate from the original spec `2:4` we +/// also set the appropriate bit in `shrink_axis_mask`. +/// +/// 2. `2:4` is contributes 2, 4, 1 to begin, end, and stride. All masks have +/// zero bits contributed. +/// +/// 3. None is a synonym for `tf.newaxis`. This means insert a dimension of size 1 +/// dimension in the final shape. Dummy values are contributed to begin, +/// end and stride, while the new_axis_mask bit is set. +/// +/// 4. `...` grab the full ranges from as many dimensions as needed to +/// fully specify a slice for every dimension of the input shape. +/// +/// 5. `:-3:-1` shows the use of negative indices. A negative index `i` associated +/// with a dimension that has shape `s` is converted to a positive index +/// `s + i`. So `-1` becomes `s-1` (i.e. the last element). This conversion +/// is done internally so begin, end and strides receive x, -3, and -1. +/// The appropriate begin_mask bit is set to indicate the start range is the +/// full range (ignoring the x). +/// +/// 6. `:` indicates that the entire contents of the corresponding dimension +/// is selected. This is equivalent to `::` or `0::1`. begin, end, and strides +/// receive 0, 0, and 1, respectively. The appropriate bits in `begin_mask` and +/// `end_mask` are also set. +/// +/// *Requirements*: +/// `0 != strides[i] for i in [0, m)` +/// `ellipsis_mask must be a power of two (only one ellipsis)` +/// +/// - Parameters: +/// - begin: `begin[k]` specifies the offset into the `k`th range specification. +/// The exact dimension this corresponds to will be determined by context. +/// Out-of-bounds values will be silently clamped. If the `k`th bit of +/// `begin_mask` then `begin[k]` is ignored and the full range of the +/// appropriate dimension is used instead. Negative values causes indexing +/// to start from the highest element e.g. If `foo==[1,2,3]` then `foo[-1]==3`. +/// - end: `end[i]` is like `begin` with the exception that `end_mask` is +/// used to determine full ranges. +/// - strides: `strides[i]` specifies the increment in the `i`th specification +/// after extracting a given element. Negative indices will reverse +/// the original order. Out or range values are +/// clamped to `[0,dim[i]) if slice[i]>0` or `[-1,dim[i]-1] if slice[i] < 0` +/// +/// - Attrs: +/// - begin_mask: a bitmask where a bit i being 1 means to ignore the begin +/// value and instead use the largest interval possible. At runtime +/// begin[i] will be replaced with `[0, n-1)` if `stride[i] > 0` or +/// `[-1, n-1]` if `stride[i] < 0` +/// - end_mask: analogous to `begin_mask` +/// - ellipsis_mask: a bitmask where bit `i` being 1 means the `i`th +/// position is actually an ellipsis. One bit at most can be 1. +/// If `ellipsis_mask == 0`, then an implicit ellipsis mask of `1 << (m+1)` +/// is provided. This means that `foo[3:5] == foo[3:5, ...]`. An ellipsis +/// implicitly creates as many range specifications as necessary to fully +/// specify the sliced range for every dimension. For example for a 4-dimensional +/// tensor `foo` the slice `foo[2, ..., 5:8]` implies `foo[2, :, :, 5:8]`. +/// - new_axis_mask: a bitmask where bit `i` being 1 means the `i`th +/// specification creates a new shape 1 dimension. For example +/// `foo[:4, tf.newaxis, :2]` would produce a shape `(4, 1, 2)` tensor. +/// - shrink_axis_mask: a bitmask where bit `i` implies that the `i`th +/// specification should shrink the dimensionality. begin and end +/// must imply a slice of size 1 in the dimension. For example in +/// python one might do `foo[:, 3, :]` which would result in +/// `shrink_axis_mask` being 2. +@inlinable @inline(__always) +public static func stridedSlice< + T: TensorFlowScalar, + Index: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + begin: Tensor, + end: Tensor, + strides: Tensor, + beginMask: Int64 = 0, + endMask: Int64 = 0, + ellipsisMask: Int64 = 0, + newAxisMask: Int64 = 0, + shrinkAxisMask: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StridedSlice", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Index", Index.tensorFlowDataType) + op.updateAttribute("begin_mask", beginMask) + op.updateAttribute("end_mask", endMask) + op.updateAttribute("ellipsis_mask", ellipsisMask) + op.updateAttribute("new_axis_mask", newAxisMask) + op.updateAttribute("shrink_axis_mask", shrinkAxisMask) + op.addInput(input) + op.addInput(begin) + op.addInput(end) + op.addInput(strides) + return op.execute(Int(1)) +} + +/// Returns the gradient of `StridedSlice`. +/// +/// Since `StridedSlice` cuts out pieces of its `input` which is size +/// `shape`, its gradient will have the same shape (which is passed here +/// as `shape`). The gradient will be zero in any element that the slice +/// does not select. +/// +/// Arguments are the same as StridedSliceGrad with the exception that +/// `dy` is the input gradient to be propagated and `shape` is the +/// shape of `StridedSlice`'s `input`. +@inlinable @inline(__always) +public static func stridedSliceGrad< + T: TensorFlowScalar, + Index: BinaryInteger & TensorFlowScalar +>( + shape: Tensor, + begin: Tensor, + end: Tensor, + strides: Tensor, + dy: Tensor, + beginMask: Int64 = 0, + endMask: Int64 = 0, + ellipsisMask: Int64 = 0, + newAxisMask: Int64 = 0, + shrinkAxisMask: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StridedSliceGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Index", Index.tensorFlowDataType) + op.updateAttribute("begin_mask", beginMask) + op.updateAttribute("end_mask", endMask) + op.updateAttribute("ellipsis_mask", ellipsisMask) + op.updateAttribute("new_axis_mask", newAxisMask) + op.updateAttribute("shrink_axis_mask", shrinkAxisMask) + op.addInput(shape) + op.addInput(begin) + op.addInput(end) + op.addInput(strides) + op.addInput(dy) + return op.execute(Int(1)) +} + +/// Formats a string template using a list of tensors. +/// +/// Formats a string template using a list of tensors, pretty-printing tensor summaries. +/// +/// - Parameter inputs: The list of tensors to format into the placeholder string. +/// +/// - Attrs: +/// - template: A string, the template to format tensor summaries into. +/// - placeholder: A string, at each placeholder in the template a subsequent tensor summary will be inserted. +/// - summarize: When formatting the tensor summaries print the first and last summarize entries of each tensor dimension. +/// +/// - Output output: = The resulting string scalar. +@inlinable @inline(__always) +public static func stringFormat( + inputs: T, + template: String = "%s", + placeholder: String = "%s", + summarize: Int64 = 3 +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("StringFormat", nOutputs) + op.updateAttribute("T", inputs._typeList) + op.updateAttribute("template", template) + op.updateAttribute("placeholder", placeholder) + op.updateAttribute("summarize", summarize) + op.addInputList(inputs) + return op.execute(Int(1)) +} + +/// Joins the strings in the given list of string tensors into one tensor; +/// +/// with the given separator (default is an empty separator). +/// +/// - Parameter inputs: A list of string tensors. The tensors must all have the same shape, +/// or be scalars. Scalars may be mixed in; these will be broadcast to the shape +/// of non-scalar inputs. +/// +/// - Attr separator: string, an optional join separator. +@inlinable @inline(__always) +public static func stringJoin( + inputs: [StringTensor], + separator: String +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("StringJoin", nOutputs) + op.updateAttribute("N", inputs.count) + op.updateAttribute("separator", separator) + op.addInputList(inputs) + return op.execute(Int(1)) +} + +/// String lengths of `input`. +/// +/// Computes the length of each string given in the input tensor. +/// +/// - Parameter input: The string for which to compute the length. +/// +/// - Attr unit: The unit that is counted to compute string length. One of: `"BYTE"` (for +/// the number of bytes in each string) or `"UTF8_CHAR"` (for the number of UTF-8 +/// encoded Unicode code points in each string). Results are undefined +/// if `unit=UTF8_CHAR` and the `input` strings do not contain structurally +/// valid UTF-8. +/// +/// - Output output: Integer tensor that has the same shape as `input`. The output contains the +/// element-wise string lengths of `input`. +@inlinable @inline(__always) +public static func stringLength( + _ input: StringTensor, + unit: Unit = .byte +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StringLength", nOutputs) + op.updateAttribute("unit", unit.cName) + op.addInput(input) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func stringListAttr( + _ a: [String], + _ b: String +) { + let nOutputs = 0 + let op = makeOp("StringListAttr", nOutputs) + op.updateAttribute("a", a) + op.updateAttribute("b", b) + op.execute() +} + +@inlinable @inline(__always) +public static func stringLower( + _ input: StringTensor, + encoding: String +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("StringLower", nOutputs) + op.updateAttribute("encoding", encoding) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Split elements of `input` based on `delimiter` into a `SparseTensor`. +/// +/// Let N be the size of source (typically N will be the batch size). Split each +/// element of `input` based on `delimiter` and return a `SparseTensor` +/// containing the splitted tokens. Empty tokens are ignored. +/// +/// `delimiter` can be empty, or a string of split characters. If `delimiter` is an +/// empty string, each element of `input` is split into individual single-byte +/// character strings, including splitting of UTF-8 multibyte sequences. Otherwise +/// every character of `delimiter` is a potential split point. +/// +/// For example: +/// N = 2, input[0] is 'hello world' and input[1] is 'a b c', then the output +/// will be +/// +/// indices = [0, 0; +/// 0, 1; +/// 1, 0; +/// 1, 1; +/// 1, 2] +/// shape = [2, 3] +/// values = ['hello', 'world', 'a', 'b', 'c'] +/// +/// - Parameters: +/// - input: 1-D. Strings to split. +/// - delimiter: 0-D. Delimiter characters (bytes), or empty string. +/// +/// - Attr skip_empty: A `bool`. If `True`, skip the empty strings from the result. +/// +/// - Outputs: +/// - indices: A dense matrix of int64 representing the indices of the sparse tensor. +/// - values: A vector of strings corresponding to the splited values. +/// - shape: a length-2 vector of int64 representing the shape of the sparse +/// tensor, where the first value is N and the second value is the maximum number +/// of tokens in a single input entry. +@inlinable @inline(__always) +public static func stringSplit( + _ input: StringTensor, + delimiter: StringTensor, + skipEmpty: Bool = true +) -> (indices: Tensor, values: StringTensor, shape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("StringSplit", nOutputs) + op.updateAttribute("skip_empty", skipEmpty) + op.addInput(input) + op.addInput(delimiter) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Split elements of `source` based on `sep` into a `SparseTensor`. +/// +/// Let N be the size of source (typically N will be the batch size). Split each +/// element of `source` based on `sep` and return a `SparseTensor` +/// containing the split tokens. Empty tokens are ignored. +/// +/// For example, N = 2, source[0] is 'hello world' and source[1] is 'a b c', +/// then the output will be +/// ``` +/// st.indices = [0, 0; +/// 0, 1; +/// 1, 0; +/// 1, 1; +/// 1, 2] +/// st.shape = [2, 3] +/// st.values = ['hello', 'world', 'a', 'b', 'c'] +/// ``` +/// +/// If `sep` is given, consecutive delimiters are not grouped together and are +/// deemed to delimit empty strings. For example, source of `"1<>2<><>3"` and +/// sep of `"<>"` returns `["1", "2", "", "3"]`. If `sep` is None or an empty +/// string, consecutive whitespace are regarded as a single separator, and the +/// result will contain no empty strings at the startor end if the string has +/// leading or trailing whitespace. +/// +/// Note that the above mentioned behavior matches python's str.split. +/// +/// - Parameters: +/// - input: `1-D` string `Tensor`, the strings to split. +/// - sep: `0-D` string `Tensor`, the delimiter character. +/// +/// - Attr maxsplit: An `int`. If `maxsplit > 0`, limit of the split of the result. +@inlinable @inline(__always) +public static func stringSplitV2( + _ input: StringTensor, + sep: StringTensor, + maxsplit: Int64 = -1 +) -> (indices: Tensor, values: StringTensor, shape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("StringSplitV2", nOutputs) + op.updateAttribute("maxsplit", maxsplit) + op.addInput(input) + op.addInput(sep) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Strip leading and trailing whitespaces from the Tensor. +/// +/// - Parameter input: A string `Tensor` of any shape. +/// +/// - Output output: A string `Tensor` of the same shape as the input. +@inlinable @inline(__always) +public static func stringStrip( + _ input: StringTensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("StringStrip", nOutputs) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Converts each string in the input Tensor to its hash mod by a number of buckets. +/// +/// The hash function is deterministic on the content of the string within the +/// process. +/// +/// Note that the hash function may change from time to time. +/// This functionality will be deprecated and it's recommended to use +/// `tf.string_to_hash_bucket_fast()` or `tf.string_to_hash_bucket_strong()`. +/// +/// - Attr num_buckets: The number of buckets. +/// +/// - Output output: A Tensor of the same shape as the input `string_tensor`. +@inlinable @inline(__always) +public static func stringToHashBucket( + stringTensor: StringTensor, + numBuckets: Int64 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StringToHashBucket", nOutputs) + op.updateAttribute("num_buckets", numBuckets) + op.addInput(stringTensor) + return op.execute(Int(1)) +} + +/// Converts each string in the input Tensor to its hash mod by a number of buckets. +/// +/// The hash function is deterministic on the content of the string within the +/// process and will never change. However, it is not suitable for cryptography. +/// This function may be used when CPU time is scarce and inputs are trusted or +/// unimportant. There is a risk of adversaries constructing inputs that all hash +/// to the same bucket. To prevent this problem, use a strong hash function with +/// `tf.string_to_hash_bucket_strong`. +/// +/// - Parameter input: The strings to assign a hash bucket. +/// +/// - Attr num_buckets: The number of buckets. +/// +/// - Output output: A Tensor of the same shape as the input `string_tensor`. +@inlinable @inline(__always) +public static func stringToHashBucketFast( + _ input: StringTensor, + numBuckets: Int64 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StringToHashBucketFast", nOutputs) + op.updateAttribute("num_buckets", numBuckets) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Converts each string in the input Tensor to its hash mod by a number of buckets. +/// +/// The hash function is deterministic on the content of the string within the +/// process. The hash function is a keyed hash function, where attribute `key` +/// defines the key of the hash function. `key` is an array of 2 elements. +/// +/// A strong hash is important when inputs may be malicious, e.g. URLs with +/// additional components. Adversaries could try to make their inputs hash to the +/// same bucket for a denial-of-service attack or to skew the results. A strong +/// hash prevents this by making it difficult, if not infeasible, to compute inputs +/// that hash to the same bucket. This comes at a cost of roughly 4x higher compute +/// time than `tf.string_to_hash_bucket_fast`. +/// +/// - Parameter input: The strings to assign a hash bucket. +/// +/// - Attrs: +/// - num_buckets: The number of buckets. +/// - key: The key for the keyed hash function passed as a list of two uint64 +/// elements. +/// +/// - Output output: A Tensor of the same shape as the input `string_tensor`. +@inlinable @inline(__always) +public static func stringToHashBucketStrong( + _ input: StringTensor, + numBuckets: Int64, + key: [Int32] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StringToHashBucketStrong", nOutputs) + op.updateAttribute("num_buckets", numBuckets) + op.updateAttribute("key", key) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Converts each string in the input Tensor to the specified numeric type. +/// +/// (Note that int32 overflow results in an error while float overflow +/// results in a rounded value.) +/// +/// - Attr out_type: The numeric type to interpret each string in `string_tensor` as. +/// +/// - Output output: A Tensor of the same shape as the input `string_tensor`. +@inlinable @inline(__always) +public static func stringToNumber( + stringTensor: StringTensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StringToNumber", nOutputs) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(stringTensor) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func stringUpper( + _ input: StringTensor, + encoding: String +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("StringUpper", nOutputs) + op.updateAttribute("encoding", encoding) + op.addInput(input) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func stubResourceHandleOp( + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("StubResourceHandleOp", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Returns x - y element-wise. +/// +/// *NOTE*: `Subtract` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func sub( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Sub", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Return substrings from `Tensor` of strings. +/// +/// For each string in the input `Tensor`, creates a substring starting at index +/// `pos` with a total length of `len`. +/// +/// If `len` defines a substring that would extend beyond the length of the input +/// string, then as many characters as possible are used. +/// +/// A negative `pos` indicates distance within the string backwards from the end. +/// +/// If `pos` specifies an index which is out of range for any of the input strings, +/// then an `InvalidArgumentError` is thrown. +/// +/// `pos` and `len` must have the same shape, otherwise a `ValueError` is thrown on +/// Op creation. +/// +/// *NOTE*: `Substr` supports broadcasting up to two dimensions. More about +/// broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +/// +/// --- +/// +/// Examples +/// +/// Using scalar `pos` and `len`: +/// +/// ```python +/// input = [b'Hello', b'World'] +/// position = 1 +/// length = 3 +/// +/// output = [b'ell', b'orl'] +/// ``` +/// +/// Using `pos` and `len` with same shape as `input`: +/// +/// ```python +/// input = [[b'ten', b'eleven', b'twelve'], +/// [b'thirteen', b'fourteen', b'fifteen'], +/// [b'sixteen', b'seventeen', b'eighteen']] +/// position = [[1, 2, 3], +/// [1, 2, 3], +/// [1, 2, 3]] +/// length = [[2, 3, 4], +/// [4, 3, 2], +/// [5, 5, 5]] +/// +/// output = [[b'en', b'eve', b'lve'], +/// [b'hirt', b'urt', b'te'], +/// [b'ixtee', b'vente', b'hteen']] +/// ``` +/// +/// Broadcasting `pos` and `len` onto `input`: +/// +/// ``` +/// input = [[b'ten', b'eleven', b'twelve'], +/// [b'thirteen', b'fourteen', b'fifteen'], +/// [b'sixteen', b'seventeen', b'eighteen'], +/// [b'nineteen', b'twenty', b'twentyone']] +/// position = [1, 2, 3] +/// length = [1, 2, 3] +/// +/// output = [[b'e', b'ev', b'lve'], +/// [b'h', b'ur', b'tee'], +/// [b'i', b've', b'hte'], +/// [b'i', b'en', b'nty']] +/// ``` +/// +/// Broadcasting `input` onto `pos` and `len`: +/// +/// ``` +/// input = b'thirteen' +/// position = [1, 5, 7] +/// length = [3, 2, 1] +/// +/// output = [b'hir', b'ee', b'n'] +/// ``` +/// +/// - Parameters: +/// - input: Tensor of strings +/// - pos: Scalar defining the position of first character in each substring +/// - len: Scalar defining the number of characters to include in each substring +/// +/// - Attr unit: The unit that is used to create the substring. One of: `"BYTE"` (for +/// defining position and length by bytes) or `"UTF8_CHAR"` (for the UTF-8 +/// encoded Unicode code points). The default is `"BYTE"`. Results are undefined if +/// `unit=UTF8_CHAR` and the `input` strings do not contain structurally valid +/// UTF-8. +/// +/// - Output output: Tensor of substrings +@inlinable @inline(__always) +public static func substr( + _ input: StringTensor, + pos: Tensor, + len: Tensor, + unit: Unit = .byte +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("Substr", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("unit", unit.cName) + op.addInput(input) + op.addInput(pos) + op.addInput(len) + return op.execute(Int(1)) +} + +/// Computes the sum of elements across dimensions of a tensor. +/// +/// Reduces `input` along the dimensions given in `axis`. Unless +/// `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in +/// `axis`. If `keep_dims` is true, the reduced dimensions are +/// retained with length 1. +/// +/// - Parameters: +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. +/// +/// - Attr keep_dims: If true, retain reduced dimensions with length 1. +/// +/// - Output output: The reduced tensor. +@inlinable @inline(__always) +public static func sum< + T: Numeric & TensorFlowScalar, + Tidx: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Sum", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func summaryWriter( + sharedName: String, + container: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("SummaryWriter", nOutputs) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("container", container) + return op.execute(Int(1)) +} + +/// Computes the singular value decompositions of one or more matrices. +/// +/// Computes the SVD of each inner matrix in `input` such that +/// `input[..., :, :] = u[..., :, :] * diag(s[..., :, :]) * transpose(v[..., :, :])` +/// +/// ```python +/// # a is a tensor containing a batch of matrices. +/// # s is a tensor of singular values for each matrix. +/// # u is the tensor containing of left singular vectors for each matrix. +/// # v is the tensor containing of right singular vectors for each matrix. +/// s, u, v = svd(a) +/// s, _, _ = svd(a, compute_uv=False) +/// ``` +/// +/// - Parameter input: A tensor of shape `[..., M, N]` whose inner-most 2 dimensions +/// form matrices of size `[M, N]`. Let `P` be the minimum of `M` and `N`. +/// +/// - Attrs: +/// - compute_uv: If true, left and right singular vectors will be +/// computed and returned in `u` and `v`, respectively. +/// If false, `u` and `v` are not set and should never referenced. +/// - full_matrices: If true, compute full-sized `u` and `v`. If false +/// (the default), compute only the leading `P` singular vectors. +/// Ignored if `compute_uv` is `False`. +/// +/// - Outputs: +/// - s: Singular values. Shape is `[..., P]`. +/// - u: Left singular vectors. If `full_matrices` is `False` then shape is +/// `[..., M, P]`; if `full_matrices` is `True` then shape is +/// `[..., M, M]`. Undefined if `compute_uv` is `False`. +/// - v: Left singular vectors. If `full_matrices` is `False` then shape is +/// `[..., N, P]`. If `full_matrices` is `True` then shape is `[..., N, N]`. +/// Undefined if `compute_uv` is false. +@inlinable @inline(__always) +public static func svd( + _ input: Tensor, + computeUv: Bool = true, + fullMatrices: Bool = false +) -> (s: Tensor, u: Tensor, v: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("Svd", nOutputs) + op.updateAttribute("compute_uv", computeUv) + op.updateAttribute("full_matrices", fullMatrices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Forwards `data` to the output port determined by `pred`. +/// +/// If `pred` is true, the `data` input is forwarded to `output_true`. Otherwise, +/// the data goes to `output_false`. +/// +/// See also `RefSwitch` and `Merge`. +/// +/// - Parameters: +/// - data: The tensor to be forwarded to the appropriate output. +/// - pred: A scalar that specifies which output port will receive data. +/// +/// - Outputs: +/// - output_false: If `pred` is false, data will be forwarded to this output. +/// - output_true: If `pred` is true, data will be forwarded to this output. +@inlinable @inline(__always) +public static func switch_( + data: Tensor, + pred: Tensor +) -> (outputFalse: Tensor, outputTrue: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("Switch", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(data) + op.addInput(pred) + return op.execute(Int(1), Int(1)) +} + +/// Computes the gradient function for function f via backpropagation. +/// +/// - Parameter input: a list of input tensors of size N + M; +/// +/// - Attrs: +/// - Tin: the type list for the input list. +/// - Tout: the type list for the input list. +/// - f: The function we want to compute the gradient for. +/// +/// The function 'f' must be a numerical function which takes N inputs and +/// produces M outputs. Its gradient function 'g', which is computed by +/// this SymbolicGradient op is a function taking N + M inputs and +/// produces N outputs. +/// +/// I.e. if we have +/// (y1, y2, ..., y_M) = f(x1, x2, ..., x_N), +/// then, g is +/// (dL/dx1, dL/dx2, ..., dL/dx_N) = g(x1, x2, ..., x_N, +/// dL/dy1, dL/dy2, ..., dL/dy_M), +/// +/// where L is a scalar-value function of (x1, x2, ..., xN) (e.g., the +/// loss function). dL/dx_i is the partial derivative of L with respect +/// to x_i. +/// +/// (Needs some math expert to say the comment above better.) +/// +/// - Output output: a list of output tensors of size N; +@inlinable @inline(__always) +public static func symbolicGradient< + Tin: TensorArrayProtocol, + Tout: TensorGroup, + FIn: TensorGroup, + FOut: TensorGroup +>( + _ input: Tin, + f: (FIn) -> FOut +) -> Tout { + let nOutputs = Int(Tout._typeList.count) + let op = makeOp("SymbolicGradient", nOutputs) + op.updateAttribute("Tin", input._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("f", f) + op.addInputList(input) + return op.execute(Int(Tout._typeList.count)) +} + +/// Creates a dataset that emits the records from one or more TFRecord files. +/// +/// - Parameters: +/// - filenames: A scalar or vector containing the name(s) of the file(s) to be +/// read. +/// - compression_type: A scalar containing either (i) the empty string (no +/// compression), (ii) "ZLIB", or (iii) "GZIP". +/// - buffer_size: A scalar representing the number of bytes to buffer. A value of +/// 0 means no buffering will be performed. +@inlinable @inline(__always) +public static func tFRecordDataset( + filenames: StringTensor, + compressionType: StringTensor, + bufferSize: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TFRecordDataset", nOutputs) + op.addInput(filenames) + op.addInput(compressionType) + op.addInput(bufferSize) + return op.execute(Int(1)) +} + +/// A Reader that outputs the records from a TensorFlow Records file. +/// +/// - Attrs: +/// - container: If non-empty, this reader is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this reader is named in the given bucket +/// with this shared_name. Otherwise, the node name is used instead. +/// +/// - Output reader_handle: The handle to reference the Reader. +@inlinable @inline(__always) +public static func tFRecordReaderV2( + container: String, + sharedName: String, + compressionType: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("TFRecordReaderV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("compression_type", compressionType) + return op.execute(Int(1)) +} + +/// CompilationResultProto indicating the status of the TPU compilation. +@inlinable @inline(__always) +public static func tPUCompilationResult( +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("TPUCompilationResult", nOutputs) + + return op.execute(Int(1)) +} + +/// An op enabling differentiation of TPU Embeddings. +/// +/// This op simply returns its first input, which is assumed to have been sliced +/// from the Tensors returned by TPUEmbeddingDequeueActivations. The presence of +/// this op, and its first argument being a trainable Variable, enables automatic +/// differentiation of graphs containing embeddings via the TPU Embedding Python +/// libraries. +/// +/// - Parameters: +/// - embedding_variable: A trainable variable, enabling optimizers to find this op. +/// - sliced_activations: The embedding activations Tensor to return. +/// +/// - Attrs: +/// - table_id: The id of the table in the embedding layer configuration from which +/// these activations were computed. +/// - lookup_id: Identifier of the set of embedding indices which produced these +/// activations. +@inlinable @inline(__always) +public static func tPUEmbeddingActivations( + embeddingVariable: Tensor, + slicedActivations: Tensor, + tableId: Int64, + lookupId: Int64 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TPUEmbeddingActivations", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("lookup_id", lookupId) + op.addInput(embeddingVariable) + op.addInput(slicedActivations) + return op.execute(Int(1)) +} + +/// A TPU core selector Op. +/// +/// This Op produces a set of TPU cores (for warm-up) or a single TPU core +/// (for regular inference) to execute the TPU program on. The output is +/// consumed by TPUPartitionedCall. +/// +/// - Output device_ordinals: A vector 1 or more TPU cores. +@inlinable @inline(__always) +public static func tPUOrdinalSelector( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TPUOrdinalSelector", nOutputs) + + return op.execute(Int(1)) +} + +/// Calls a function placed on a specified TPU device. +/// +/// - Parameters: +/// - args: The arguments to the function. +/// - device_ordinal: The TPU device ordinal to run the function on. +/// +/// - Attrs: +/// - Tin: The types of the arguments to the function. +/// - Tout: The types of the outputs of the function. +/// - f: The function to call. +/// +/// - Output output: The output of the function call. +@inlinable @inline(__always) +public static func tPUPartitionedCall< + Tin: TensorArrayProtocol, + Tout: TensorGroup, + FIn: TensorGroup, + FOut: TensorGroup +>( + args: Tin, + deviceOrdinal: Tensor, + f: (FIn) -> FOut +) -> Tout { + let nOutputs = Int(Tout._typeList.count) + let op = makeOp("TPUPartitionedCall", nOutputs) + op.updateAttribute("Tin", args._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("f", f) + op.addInputList(args) + op.addInput(deviceOrdinal) + return op.execute(Int(Tout._typeList.count)) +} + +/// Runs replicated computations on a distributed TPU system. +/// +/// - Parameters: +/// - inputs: the inputs to 'computation', flattened, in replica-major order. +/// - broadcast_inputs: additional arguments to broadcast to all replicas. The +/// broadcast inputs are appended to the per-replica inputs when calling +/// computation. +/// - guaranteed_constants: arguments which have been guaranteed to not +/// change their values during the session lifetime. These contain tensors marked as +/// constant using the GuaranteeConstOp. +/// +/// - Attrs: +/// - computation: a function containing the computation to run. +/// - num_replicas: the number of replicas of the computation to run. +/// - num_cores_per_replica: the number of logical cores in each replica. +/// - topology: A serialized tensorflow.tpu.TopologyProto that describes the TPU +/// topology. +/// - use_tpu: a bool indicating if this computation will run on TPU or CPU/GPU. +/// Currently, only supports a default placement (computation is placed on GPU +/// if one is available, and on CPU if not). +/// - device_assignment: a flattened array with shape +/// [replica, num_cores_per_replica, mesh_dimension] that maps the coordinates +/// of logical cores in each replica of a computation to physical coordinates in +/// the TPU topology. +/// - Tinputs: the types of the arguments to 'computation'. +/// - Tbroadcast_inputs: the types of the additional arguments to broadcast to all +/// replicas. +/// - Tguaranteed_constants: the types of the arguments to 'guaranteed_constants'. +/// - output_types: the types of the outputs of 'computation'. +/// +/// - Output outputs: the outputs of 'computation'. +@inlinable @inline(__always) +public static func tPUReplicate< + ComputationIn: TensorGroup, + ComputationOut: TensorGroup, + Tinputs: TensorArrayProtocol, + TbroadcastInputs: TensorArrayProtocol, + TguaranteedConstants: TensorArrayProtocol, + OutputTypes: TensorGroup +>( + inputs: Tinputs, + broadcastInputs: TbroadcastInputs, + variables: [ResourceHandle], + guaranteedConstants: TguaranteedConstants, + computation: (ComputationIn) -> ComputationOut, + numReplicas: Int64, + numCoresPerReplica: Int64 = 1, + topology: String, + useTpu: Bool = true, + deviceAssignment: [Int32], + hostComputeCore: [String], + paddingMap: [String], + stepMarkerLocation: String = "STEP_MARK_AT_ENTRY" +) -> OutputTypes { + let nOutputs = Int(OutputTypes._typeList.count) + let op = makeOp("TPUReplicate", nOutputs) + op.updateAttribute("computation", computation) + op.updateAttribute("num_replicas", numReplicas) + op.updateAttribute("num_cores_per_replica", numCoresPerReplica) + op.updateAttribute("topology", topology) + op.updateAttribute("use_tpu", useTpu) + op.updateAttribute("device_assignment", deviceAssignment) + op.updateAttribute("host_compute_core", hostComputeCore) + op.updateAttribute("Tinputs", inputs._typeList) + op.updateAttribute("Tbroadcast_inputs", broadcastInputs._typeList) + op.updateAttribute("NumVariables", variables.count) + op.updateAttribute("Tguaranteed_constants", guaranteedConstants._typeList) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("padding_map", paddingMap) + op.updateAttribute("step_marker_location", stepMarkerLocation) + op.addInputList(inputs) + op.addInputList(broadcastInputs) + op.addInputList(variables) + op.addInputList(guaranteedConstants) + return op.execute(Int(OutputTypes._typeList.count)) +} + +/// Metadata indicaitng how the TPU computation should be replicated. +/// +/// - Attrs: +/// - num_replicas: Number of replicas of the computation +/// - num_cores_per_replica: Number of cores per replica. Used for model parallelism. +/// - topology: TopologyProto indicating the topology of the TPU pod slice. +/// - use_tpu: Whether to place the computation on the TPU. +/// - device_assignment: The assignment of devices for the computation. +/// - computation_shape: DEPRECATED. Use num_cores_per_replica instead. +@inlinable @inline(__always) +public static func tPUReplicateMetadata( + numReplicas: Int64, + numCoresPerReplica: Int64 = 1, + topology: String, + useTpu: Bool = true, + deviceAssignment: [Int32], + computationShape: [Int32], + hostComputeCore: [String], + paddingMap: [String], + stepMarkerLocation: String = "STEP_MARK_AT_ENTRY" +) { + let nOutputs = 0 + let op = makeOp("TPUReplicateMetadata", nOutputs) + op.updateAttribute("num_replicas", numReplicas) + op.updateAttribute("num_cores_per_replica", numCoresPerReplica) + op.updateAttribute("topology", topology) + op.updateAttribute("use_tpu", useTpu) + op.updateAttribute("device_assignment", deviceAssignment) + op.updateAttribute("computation_shape", computationShape) + op.updateAttribute("host_compute_core", hostComputeCore) + op.updateAttribute("padding_map", paddingMap) + op.updateAttribute("step_marker_location", stepMarkerLocation) + op.execute() +} + +/// Connects N inputs to an N-way replicated TPU computation. +@inlinable @inline(__always) +public static func tPUReplicatedInput( + inputs: [Tensor] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TPUReplicatedInput", nOutputs) + op.updateAttribute("N", inputs.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInputList(inputs) + return op.execute(Int(1)) +} + +/// Connects outputs of an N-way replicated computation to N outputs. +@inlinable @inline(__always) +public static func tPUReplicatedOutput( + _ input: Tensor, + numReplicas: Int64 +) -> [Tensor] { + let nOutputs = Int(numReplicas) + let op = makeOp("TPUReplicatedOutput", nOutputs) + op.updateAttribute("num_replicas", numReplicas) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(numReplicas)) +} + +/// Creates a dataset that contains `count` elements from the `input_dataset`. +/// +/// - Parameter count: A scalar representing the number of elements from the `input_dataset` +/// that should be taken. A value of `-1` indicates that all of `input_dataset` +/// is taken. +@inlinable @inline(__always) +public static func takeDataset( + inputDataset: VariantHandle, + count: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TakeDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(count) + return op.execute(Int(1)) +} + +/// Read `SparseTensors` from a `SparseTensorsMap` and concatenate them. +/// +/// The input `sparse_handles` must be an `int64` matrix of shape `[N, 1]` where +/// `N` is the minibatch size and the rows correspond to the output handles of +/// `AddSparseToTensorsMap` or `AddManySparseToTensorsMap`. The ranks of the +/// original `SparseTensor` objects that went into the given input ops must all +/// match. When the final `SparseTensor` is created, it has rank one +/// higher than the ranks of the incoming `SparseTensor` objects +/// (they have been concatenated along a new row dimension on the left). +/// +/// The output `SparseTensor` object's shape values for all dimensions but the +/// first are the max across the input `SparseTensor` objects' shape values +/// for the corresponding dimensions. Its first shape value is `N`, the minibatch +/// size. +/// +/// The input `SparseTensor` objects' indices are assumed ordered in +/// standard lexicographic order. If this is not the case, after this +/// step run `SparseReorder` to restore index ordering. +/// +/// For example, if the handles represent an input, which is a `[2, 3]` matrix +/// representing two original `SparseTensor` objects: +/// +/// ``` +/// index = [ 0] +/// [10] +/// [20] +/// values = [1, 2, 3] +/// shape = [50] +/// ``` +/// +/// and +/// +/// ``` +/// index = [ 2] +/// [10] +/// values = [4, 5] +/// shape = [30] +/// ``` +/// +/// then the final `SparseTensor` will be: +/// +/// ``` +/// index = [0 0] +/// [0 10] +/// [0 20] +/// [1 2] +/// [1 10] +/// values = [1, 2, 3, 4, 5] +/// shape = [2 50] +/// ``` +/// +/// - Parameter sparse_handles: 1-D, The `N` serialized `SparseTensor` objects. +/// Shape: `[N]`. +/// +/// - Attrs: +/// - dtype: The `dtype` of the `SparseTensor` objects stored in the +/// `SparseTensorsMap`. +/// - container: The container name for the `SparseTensorsMap` read by this op. +/// - shared_name: The shared name for the `SparseTensorsMap` read by this op. +/// It should not be blank; rather the `shared_name` or unique Operation name +/// of the Op that created the original `SparseTensorsMap` should be used. +/// +/// - Outputs: +/// - sparse_indices: 2-D. The `indices` of the minibatch `SparseTensor`. +/// - sparse_values: 1-D. The `values` of the minibatch `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the minibatch `SparseTensor`. +@inlinable @inline(__always) +public static func takeManySparseFromTensorsMap( + sparseHandles: Tensor, + container: String, + sharedName: String +) -> (sparseIndices: Tensor, sparseValues: Tensor, sparseShape: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("TakeManySparseFromTensorsMap", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(sparseHandles) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Computes tan of x element-wise. +@inlinable @inline(__always) +public static func tan( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Tan", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes hyperbolic tangent of `x` element-wise. +@inlinable @inline(__always) +public static func tanh( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Tanh", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Computes the gradient for the tanh of `x` wrt its input. +/// +/// Specifically, `grad = dy * (1 - y*y)`, where `y = tanh(x)`, and `dy` +/// is the corresponding input gradient. +@inlinable @inline(__always) +public static func tanhGrad( + _ y: Tensor, + dy: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TanhGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(dy) + return op.execute(Int(1)) +} + +/// Deprecated. Use TensorArrayCloseV3 +@inlinable @inline(__always) +public static func tensorArrayCloseV2( + handle: StringTensor +) { + let nOutputs = 0 + let op = makeOp("TensorArrayCloseV2", nOutputs) + op.addInput(handle) + op.execute() +} + +/// Delete the TensorArray from its resource container. +/// +/// This enables the user to close and release the resource in the middle +/// of a step/run. +/// +/// - Parameter handle: The handle to a TensorArray (output of TensorArray or TensorArrayGrad). +@inlinable @inline(__always) +public static func tensorArrayCloseV3( + handle: ResourceHandle +) { + let nOutputs = 0 + let op = makeOp("TensorArrayCloseV3", nOutputs) + op.addInput(handle) + op.execute() +} + +/// Deprecated. Use TensorArrayConcatV3 +@inlinable @inline(__always) +public static func tensorArrayConcatV2( + handle: StringTensor, + flowIn: Tensor, + elementShapeExcept0: TensorShape? +) -> (value: Tensor, lengths: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("TensorArrayConcatV2", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("element_shape_except0", elementShapeExcept0) + op.addInput(handle) + op.addInput(flowIn) + return op.execute(Int(1), Int(1)) +} + +/// Concat the elements from the TensorArray into value `value`. +/// +/// Takes `T` elements of shapes +/// +/// ``` +/// (n0 x d0 x d1 x ...), (n1 x d0 x d1 x ...), ..., (n(T-1) x d0 x d1 x ...) +/// ``` +/// +/// and concatenates them into a Tensor of shape: +/// +/// ```(n0 + n1 + ... + n(T-1) x d0 x d1 x ...)``` +/// +/// All elements must have the same shape (excepting the first dimension). +/// +/// - Parameters: +/// - handle: The handle to a TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. +/// +/// - Attrs: +/// - dtype: The type of the elem that is returned. +/// - element_shape_except0: The expected shape of an element, if known, +/// excluding the first dimension. Used to validate the shapes of +/// TensorArray elements. If this shape is not fully specified, concatenating +/// zero-size TensorArrays is an error. +/// +/// - Outputs: +/// - value: All of the elements in the TensorArray, concatenated along the first +/// axis. +/// - lengths: A vector of the row sizes of the original T elements in the +/// value output. In the example above, this would be the values: +/// `(n1, n2, ..., n(T-1))`. +@inlinable @inline(__always) +public static func tensorArrayConcatV3( + handle: ResourceHandle, + flowIn: Tensor, + elementShapeExcept0: TensorShape? +) -> (value: Tensor, lengths: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("TensorArrayConcatV3", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("element_shape_except0", elementShapeExcept0) + op.addInput(handle) + op.addInput(flowIn) + return op.execute(Int(1), Int(1)) +} + +/// Deprecated. Use TensorArrayGatherV3 +@inlinable @inline(__always) +public static func tensorArrayGatherV2( + handle: StringTensor, + indices: Tensor, + flowIn: Tensor, + elementShape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorArrayGatherV2", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("element_shape", elementShape) + op.addInput(handle) + op.addInput(indices) + op.addInput(flowIn) + return op.execute(Int(1)) +} + +/// Gather specific elements from the TensorArray into output `value`. +/// +/// All elements selected by `indices` must have the same shape. +/// +/// - Parameters: +/// - handle: The handle to a TensorArray. +/// - indices: The locations in the TensorArray from which to read tensor elements. +/// - flow_in: A float scalar that enforces proper chaining of operations. +/// +/// - Attrs: +/// - dtype: The type of the elem that is returned. +/// - element_shape: The expected shape of an element, if known. Used to +/// validate the shapes of TensorArray elements. If this shape is not +/// fully specified, gathering zero-size TensorArrays is an error. +/// +/// - Output value: All of the elements in the TensorArray, concatenated along a new +/// axis (the new dimension 0). +@inlinable @inline(__always) +public static func tensorArrayGatherV3( + handle: ResourceHandle, + indices: Tensor, + flowIn: Tensor, + elementShape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorArrayGatherV3", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("element_shape", elementShape) + op.addInput(handle) + op.addInput(indices) + op.addInput(flowIn) + return op.execute(Int(1)) +} + +/// Deprecated. Use TensorArrayGradV3 +@inlinable @inline(__always) +public static func tensorArrayGradV2( + handle: StringTensor, + flowIn: Tensor, + source: String +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("TensorArrayGradV2", nOutputs) + op.updateAttribute("source", source) + op.addInput(handle) + op.addInput(flowIn) + return op.execute(Int(1)) +} + +/// Creates a TensorArray for storing the gradients of values in the given handle. +/// +/// If the given TensorArray gradient already exists, returns a reference to it. +/// +/// Locks the size of the original TensorArray by disabling its dynamic size flag. +/// +/// **A note about the input flow_in:** +/// +/// The handle flow_in forces the execution of the gradient lookup to occur +/// only after certain other operations have occurred. For example, when +/// the forward TensorArray is dynamically sized, writes to this TensorArray +/// may resize the object. The gradient TensorArray is statically sized based +/// on the size of the forward TensorArray when this operation executes. +/// Furthermore, the size of the forward TensorArray is frozen by this call. +/// As a result, the flow is used to ensure that the call to generate the gradient +/// TensorArray only happens after all writes are executed. +/// +/// In the case of dynamically sized TensorArrays, gradient computation should +/// only be performed on read operations that have themselves been chained via +/// flow to occur only after all writes have executed. That way the final size +/// of the forward TensorArray is known when this operation is called. +/// +/// **A note about the source attribute:** +/// +/// TensorArray gradient calls use an accumulator TensorArray object. If +/// multiple gradients are calculated and run in the same session, the multiple +/// gradient nodes may accidentally flow through the same accumulator TensorArray. +/// This double counts and generally breaks the TensorArray gradient flow. +/// +/// The solution is to identify which gradient call this particular +/// TensorArray gradient is being called in. This is performed by identifying +/// a unique string (e.g. "gradients", "gradients_1", ...) from the input +/// gradient Tensor's name. This string is used as a suffix when creating +/// the TensorArray gradient object here (the attribute `source`). +/// +/// The attribute `source` is added as a suffix to the forward TensorArray's +/// name when performing the creation / lookup, so that each separate gradient +/// calculation gets its own TensorArray accumulator. +/// +/// - Parameters: +/// - handle: The handle to the forward TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. +/// +/// - Attr source: The gradient source string, used to decide which gradient TensorArray +/// to return. +@inlinable @inline(__always) +public static func tensorArrayGradV3( + handle: ResourceHandle, + flowIn: Tensor, + source: String +) -> (gradHandle: ResourceHandle, flowOut: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("TensorArrayGradV3", nOutputs) + op.updateAttribute("source", source) + op.addInput(handle) + op.addInput(flowIn) + return op.execute(Int(1), Int(1)) +} + +/// Creates a TensorArray for storing multiple gradients of values in the given handle. +/// +/// Similar to TensorArrayGradV3. However it creates an accumulator with an +/// expanded shape compared to the input TensorArray whose gradient is being +/// computed. This enables multiple gradients for the same TensorArray to be +/// calculated using the same accumulator. +/// +/// - Parameters: +/// - handle: The handle to the forward TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. +/// - shape_to_prepend: An int32 vector representing a shape. Elements in the gradient accumulator will +/// have shape which is this shape_to_prepend value concatenated with shape of the +/// elements in the TensorArray corresponding to the input handle. +/// +/// - Attr source: The gradient source string, used to decide which gradient TensorArray +/// to return. +@inlinable @inline(__always) +public static func tensorArrayGradWithShape( + handle: ResourceHandle, + flowIn: Tensor, + shapeToPrepend: Tensor, + source: String +) -> (gradHandle: ResourceHandle, flowOut: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("TensorArrayGradWithShape", nOutputs) + op.updateAttribute("source", source) + op.addInput(handle) + op.addInput(flowIn) + op.addInput(shapeToPrepend) + return op.execute(Int(1), Int(1)) +} + +/// Deprecated. Use TensorArrayReadV3 +@inlinable @inline(__always) +public static func tensorArrayReadV2( + handle: StringTensor, + index: Tensor, + flowIn: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorArrayReadV2", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(handle) + op.addInput(index) + op.addInput(flowIn) + return op.execute(Int(1)) +} + +/// Read an element from the TensorArray into output `value`. +/// +/// - Parameters: +/// - handle: The handle to a TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. +/// +/// - Attr dtype: The type of the elem that is returned. +/// +/// - Output value: The tensor that is read from the TensorArray. +@inlinable @inline(__always) +public static func tensorArrayReadV3( + handle: ResourceHandle, + index: Tensor, + flowIn: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorArrayReadV3", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(handle) + op.addInput(index) + op.addInput(flowIn) + return op.execute(Int(1)) +} + +/// Deprecated. Use TensorArrayScatterV3 +@inlinable @inline(__always) +public static func tensorArrayScatterV2( + handle: StringTensor, + indices: Tensor, + value: Tensor, + flowIn: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorArrayScatterV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(handle) + op.addInput(indices) + op.addInput(value) + op.addInput(flowIn) + return op.execute(Int(1)) +} + +/// Scatter the data from the input value into specific TensorArray elements. +/// +/// `indices` must be a vector, its length must match the first dim of `value`. +/// +/// - Parameters: +/// - handle: The handle to a TensorArray. +/// - indices: The locations at which to write the tensor elements. +/// - value: The concatenated tensor to write to the TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. +/// +/// - Output flow_out: A float scalar that enforces proper chaining of operations. +@inlinable @inline(__always) +public static func tensorArrayScatterV3( + handle: ResourceHandle, + indices: Tensor, + value: Tensor, + flowIn: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorArrayScatterV3", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(handle) + op.addInput(indices) + op.addInput(value) + op.addInput(flowIn) + return op.execute(Int(1)) +} + +/// Deprecated. Use TensorArraySizeV3 +@inlinable @inline(__always) +public static func tensorArraySizeV2( + handle: StringTensor, + flowIn: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorArraySizeV2", nOutputs) + op.addInput(handle) + op.addInput(flowIn) + return op.execute(Int(1)) +} + +/// Get the current size of the TensorArray. +/// +/// - Parameters: +/// - handle: The handle to a TensorArray (output of TensorArray or TensorArrayGrad). +/// - flow_in: A float scalar that enforces proper chaining of operations. +/// +/// - Output size: The current size of the TensorArray. +@inlinable @inline(__always) +public static func tensorArraySizeV3( + handle: ResourceHandle, + flowIn: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorArraySizeV3", nOutputs) + op.addInput(handle) + op.addInput(flowIn) + return op.execute(Int(1)) +} + +/// Deprecated. Use TensorArraySplitV3 +@inlinable @inline(__always) +public static func tensorArraySplitV2( + handle: StringTensor, + value: Tensor, + lengths: Tensor, + flowIn: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorArraySplitV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(handle) + op.addInput(value) + op.addInput(lengths) + op.addInput(flowIn) + return op.execute(Int(1)) +} + +/// Split the data from the input value into TensorArray elements. +/// +/// Assuming that `lengths` takes on values +/// +/// ```(n0, n1, ..., n(T-1))``` +/// +/// and that `value` has shape +/// +/// ```(n0 + n1 + ... + n(T-1) x d0 x d1 x ...)```, +/// +/// this splits values into a TensorArray with T tensors. +/// +/// TensorArray index t will be the subtensor of values with starting position +/// +/// ```(n0 + n1 + ... + n(t-1), 0, 0, ...)``` +/// +/// and having size +/// +/// ```nt x d0 x d1 x ...``` +/// +/// - Parameters: +/// - handle: The handle to a TensorArray. +/// - value: The concatenated tensor to write to the TensorArray. +/// - lengths: The vector of lengths, how to split the rows of value into the +/// TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. +/// +/// - Output flow_out: A float scalar that enforces proper chaining of operations. +@inlinable @inline(__always) +public static func tensorArraySplitV3( + handle: ResourceHandle, + value: Tensor, + lengths: Tensor, + flowIn: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorArraySplitV3", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(handle) + op.addInput(value) + op.addInput(lengths) + op.addInput(flowIn) + return op.execute(Int(1)) +} + +/// Deprecated. Use TensorArrayV3 +@inlinable @inline(__always) +public static func tensorArrayV2( + size: Tensor, + dtype: TensorDataType, + elementShape: TensorShape?, + dynamicSize: Bool = false, + clearAfterRead: Bool = true, + tensorArrayName: String +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("TensorArrayV2", nOutputs) + op.updateAttribute("dtype", dtype) + op.updateAttribute("element_shape", elementShape) + op.updateAttribute("dynamic_size", dynamicSize) + op.updateAttribute("clear_after_read", clearAfterRead) + op.updateAttribute("tensor_array_name", tensorArrayName) + op.addInput(size) + return op.execute(Int(1)) +} + +/// An array of Tensors of given size. +/// +/// Write data via Write and read via Read or Pack. +/// +/// - Parameter size: The size of the array. +/// +/// - Attrs: +/// - dtype: The type of the elements on the tensor_array. +/// - element_shape: The expected shape of an element, if known. Used to +/// validate the shapes of TensorArray elements. If this shape is not +/// fully specified, gathering zero-size TensorArrays is an error. +/// - dynamic_size: A boolean that determines whether writes to the TensorArray +/// are allowed to grow the size. By default, this is not allowed. +/// - clear_after_read: If true (default), Tensors in the TensorArray are cleared +/// after being read. This disables multiple read semantics but allows early +/// release of memory. +/// - identical_element_shapes: If true (default is false), then all +/// elements in the TensorArray will be expected to have have identical shapes. +/// This allows certain behaviors, like dynamically checking for +/// consistent shapes on write, and being able to fill in properly +/// shaped zero tensors on stack -- even if the element_shape attribute +/// is not fully defined. +/// - tensor_array_name: Overrides the name used for the temporary tensor_array +/// resource. Default value is the name of the 'TensorArray' op (which +/// is guaranteed unique). +/// +/// - Outputs: +/// - handle: The handle to the TensorArray. +/// - flow: A scalar used to control gradient flow. +@inlinable @inline(__always) +public static func tensorArrayV3( + size: Tensor, + dtype: TensorDataType, + elementShape: TensorShape?, + dynamicSize: Bool = false, + clearAfterRead: Bool = true, + identicalElementShapes: Bool = false, + tensorArrayName: String +) -> (handle: ResourceHandle, flow: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("TensorArrayV3", nOutputs) + op.updateAttribute("dtype", dtype) + op.updateAttribute("element_shape", elementShape) + op.updateAttribute("dynamic_size", dynamicSize) + op.updateAttribute("clear_after_read", clearAfterRead) + op.updateAttribute("identical_element_shapes", identicalElementShapes) + op.updateAttribute("tensor_array_name", tensorArrayName) + op.addInput(size) + return op.execute(Int(1), Int(1)) +} + +/// Deprecated. Use TensorArrayGradV3 +@inlinable @inline(__always) +public static func tensorArrayWriteV2( + handle: StringTensor, + index: Tensor, + value: Tensor, + flowIn: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorArrayWriteV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(handle) + op.addInput(index) + op.addInput(value) + op.addInput(flowIn) + return op.execute(Int(1)) +} + +/// Push an element onto the tensor_array. +/// +/// - Parameters: +/// - handle: The handle to a TensorArray. +/// - index: The position to write to inside the TensorArray. +/// - value: The tensor to write to the TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. +/// +/// - Output flow_out: A float scalar that enforces proper chaining of operations. +@inlinable @inline(__always) +public static func tensorArrayWriteV3( + handle: ResourceHandle, + index: Tensor, + value: Tensor, + flowIn: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorArrayWriteV3", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(handle) + op.addInput(index) + op.addInput(value) + op.addInput(flowIn) + return op.execute(Int(1)) +} + +/// Creates a dataset that emits `components` as a tuple of tensors once. +@inlinable @inline(__always) +public static func tensorDataset( + components: ToutputTypes, + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TensorDataset", nOutputs) + op.updateAttribute("Toutput_types", components._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInputList(components) + return op.execute(Int(1)) +} + +/// Creates a tree resource and returns a handle to it. +/// +/// - Parameters: +/// - tree_handle: Handle to the tree resource to be created. +/// - tree_config: Serialized proto string of the boosted_trees.Tree. +@inlinable @inline(__always) +public static func tensorForestCreateTreeVariable( + treeHandle: ResourceHandle, + treeConfig: StringTensor +) { + let nOutputs = 0 + let op = makeOp("TensorForestCreateTreeVariable", nOutputs) + op.addInput(treeHandle) + op.addInput(treeConfig) + op.execute() +} + +/// Deserializes a proto into the tree handle +/// +/// - Parameters: +/// - tree_handle: Handle to the tree resource to be restored. +/// - tree_config: Serialied proto string of the boosted_trees.Tree proto. +@inlinable @inline(__always) +public static func tensorForestTreeDeserialize( + treeHandle: ResourceHandle, + treeConfig: StringTensor +) { + let nOutputs = 0 + let op = makeOp("TensorForestTreeDeserialize", nOutputs) + op.addInput(treeHandle) + op.addInput(treeConfig) + op.execute() +} + +/// Checks whether a tree has been initialized. +/// +/// - Parameter tree_handle: Handle to the tree. +/// +/// - Output is_initialized: Whether the tree is initialized. +@inlinable @inline(__always) +public static func tensorForestTreeIsInitializedOp( + treeHandle: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorForestTreeIsInitializedOp", nOutputs) + op.addInput(treeHandle) + return op.execute(Int(1)) +} + +/// Output the logits for the given input data +/// +/// - Parameters: +/// - tree_handle: Handle to the tree resource. +/// - dense_features: Rank 2 dense features tensor. +/// +/// - Attr logits_dimension: Scalar, dimension of the logits. +/// +/// - Output logits: The logits predictions from the tree for each instance in the batch. +@inlinable @inline(__always) +public static func tensorForestTreePredict( + treeHandle: ResourceHandle, + denseFeatures: Tensor, + logitsDimension: Int64 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorForestTreePredict", nOutputs) + op.updateAttribute("logits_dimension", logitsDimension) + op.addInput(treeHandle) + op.addInput(denseFeatures) + return op.execute(Int(1)) +} + +/// Creates a handle to a TensorForestTreeResource +@inlinable @inline(__always) +public static func tensorForestTreeResourceHandleOp( + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("TensorForestTreeResourceHandleOp", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Serializes the tree handle to a proto +/// +/// - Parameter tree_handle: Handle to the tree resource to be serialized. +/// +/// - Output tree_config: Serialied proto string of the tree resource. +@inlinable @inline(__always) +public static func tensorForestTreeSerialize( + treeHandle: ResourceHandle +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("TensorForestTreeSerialize", nOutputs) + op.addInput(treeHandle) + return op.execute(Int(1)) +} + +/// Get the number of nodes in a tree +/// +/// - Parameter tree_handle: Handle to the tree resource. +/// +/// - Output tree_size: The size of the tree. +@inlinable @inline(__always) +public static func tensorForestTreeSize( + treeHandle: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorForestTreeSize", nOutputs) + op.addInput(treeHandle) + return op.execute(Int(1)) +} + +/// Concats all tensors in the list along the 0th dimension. +/// +/// Requires that all tensors have the same shape except the first dimension. +/// +/// input_handle: The input list. +/// tensor: The concated result. +/// lengths: Output tensor containing sizes of the 0th dimension of tensors in the list, used for computing the gradient. +/// +@inlinable @inline(__always) +public static func tensorListConcat( + inputHandle: VariantHandle, + elementShape: TensorShape? +) -> (tensor: Tensor, lengths: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("TensorListConcat", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("element_shape", elementShape) + op.addInput(inputHandle) + return op.execute(Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func tensorListConcatLists( + inputA: VariantHandle, + inputB: VariantHandle, + elementDtype: TensorDataType +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TensorListConcatLists", nOutputs) + op.updateAttribute("element_dtype", elementDtype) + op.addInput(inputA) + op.addInput(inputB) + return op.execute(Int(1)) +} + +/// Concats all tensors in the list along the 0th dimension. +/// +/// Requires that all tensors have the same shape except the first dimension. +/// +/// input_handle: The input list. +/// element_shape: The shape of the uninitialized elements in the list. If the first +/// dimension is not -1, it is assumed that all list elements have the same +/// leading dim. +/// leading_dims: The list of leading dims of uninitialized list elements. Used if +/// the leading dim of input_handle.element_shape or the element_shape input arg +/// is not already set. +/// tensor: The concated result. +/// lengths: Output tensor containing sizes of the 0th dimension of tensors in the list, used for computing the gradient. +/// +@inlinable @inline(__always) +public static func tensorListConcatV2< + ElementDtype: TensorFlowScalar, + ShapeType: BinaryInteger & TensorFlowScalar +>( + inputHandle: VariantHandle, + elementShape: Tensor, + leadingDims: Tensor +) -> (tensor: Tensor, lengths: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("TensorListConcatV2", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(elementShape) + op.addInput(leadingDims) + return op.execute(Int(1), Int(1)) +} + +/// The shape of the elements of the given list, as a tensor. +/// +/// input_handle: the list +/// element_shape: the shape of elements of the list +@inlinable @inline(__always) +public static func tensorListElementShape( + inputHandle: VariantHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorListElementShape", nOutputs) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(inputHandle) + return op.execute(Int(1)) +} + +/// Creates a TensorList which, when stacked, has the value of `tensor`. +/// +/// Each tensor in the result list corresponds to one row of the input tensor. +/// +/// tensor: The input tensor. +/// output_handle: The list. +@inlinable @inline(__always) +public static func tensorListFromTensor< + ElementDtype: TensorFlowScalar, + ShapeType: BinaryInteger & TensorFlowScalar +>( + _ tensor: Tensor, + elementShape: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TensorListFromTensor", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(tensor) + op.addInput(elementShape) + return op.execute(Int(1)) +} + +/// Creates a Tensor by indexing into the TensorList. +/// +/// Each row in the produced Tensor corresponds to the element in the TensorList +/// specified by the given index (see `tf.gather`). +/// +/// input_handle: The input tensor list. +/// indices: The indices used to index into the list. +/// values: The tensor. +@inlinable @inline(__always) +public static func tensorListGather( + inputHandle: VariantHandle, + indices: Tensor, + elementShape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorListGather", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(indices) + op.addInput(elementShape) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func tensorListGetItem( + inputHandle: VariantHandle, + index: Tensor, + elementShape: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorListGetItem", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(index) + op.addInput(elementShape) + return op.execute(Int(1)) +} + +/// Returns the number of tensors in the input tensor list. +/// +/// input_handle: the input list +/// length: the number of tensors in the list +@inlinable @inline(__always) +public static func tensorListLength( + inputHandle: VariantHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorListLength", nOutputs) + op.addInput(inputHandle) + return op.execute(Int(1)) +} + +/// Returns the last element of the input list as well as a list with all but that element. +/// +/// Fails if the list is empty. +/// +/// input_handle: the input list +/// tensor: the withdrawn last element of the list +/// element_dtype: the type of elements in the list +/// element_shape: the shape of the output tensor +@inlinable @inline(__always) +public static func tensorListPopBack( + inputHandle: VariantHandle, + elementShape: Tensor +) -> (outputHandle: VariantHandle, tensor: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("TensorListPopBack", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(elementShape) + return op.execute(Int(1), Int(1)) +} + +/// Returns a list list which has the passed-in `Tensor` as last element and the other elements of the given list in `input_handle`. +/// +/// tensor: The tensor to put on the list. +/// input_handle: The old list. +/// output_handle: A list with the elements of the old list followed by tensor. +/// element_dtype: the type of elements in the list. +/// element_shape: a shape compatible with that of elements in the list. +@inlinable @inline(__always) +public static func tensorListPushBack( + inputHandle: VariantHandle, + _ tensor: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TensorListPushBack", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(tensor) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func tensorListPushBackBatch( + inputHandles: VariantHandle, + _ tensor: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TensorListPushBackBatch", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandles) + op.addInput(tensor) + return op.execute(Int(1)) +} + +/// List of the given size with empty elements. +/// +/// element_shape: the shape of the future elements of the list +/// num_elements: the number of elements to reserve +/// handle: the output list +/// element_dtype: the desired type of elements in the list. +@inlinable @inline(__always) +public static func tensorListReserve( + elementShape: Tensor, + numElements: Tensor, + elementDtype: TensorDataType +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TensorListReserve", nOutputs) + op.updateAttribute("element_dtype", elementDtype) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(elementShape) + op.addInput(numElements) + return op.execute(Int(1)) +} + +/// Resizes the list. +/// +/// +/// input_handle: the input list +/// size: size of the output list +/// +@inlinable @inline(__always) +public static func tensorListResize( + inputHandle: VariantHandle, + size: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TensorListResize", nOutputs) + op.addInput(inputHandle) + op.addInput(size) + return op.execute(Int(1)) +} + +/// Creates a TensorList by indexing into a Tensor. +/// +/// Each member of the TensorList corresponds to one row of the input tensor, +/// specified by the given index (see `tf.gather`). +/// +/// tensor: The input tensor. +/// indices: The indices used to index into the list. +/// element_shape: The shape of the elements in the list (can be less specified than +/// the shape of the tensor). +/// output_handle: The TensorList. +@inlinable @inline(__always) +public static func tensorListScatter< + ElementDtype: TensorFlowScalar, + ShapeType: BinaryInteger & TensorFlowScalar +>( + _ tensor: Tensor, + indices: Tensor, + elementShape: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TensorListScatter", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(tensor) + op.addInput(indices) + op.addInput(elementShape) + return op.execute(Int(1)) +} + +/// Scatters tensor at indices in an input list. +/// +/// Each member of the TensorList corresponds to one row of the input tensor, +/// specified by the given index (see `tf.gather`). +/// +/// input_handle: The list to scatter into. +/// tensor: The input tensor. +/// indices: The indices used to index into the list. +/// output_handle: The TensorList. +@inlinable @inline(__always) +public static func tensorListScatterIntoExistingList( + inputHandle: VariantHandle, + _ tensor: Tensor, + indices: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TensorListScatterIntoExistingList", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(tensor) + op.addInput(indices) + return op.execute(Int(1)) +} + +/// Creates a TensorList by indexing into a Tensor. +/// +/// Each member of the TensorList corresponds to one row of the input tensor, +/// specified by the given index (see `tf.gather`). +/// +/// tensor: The input tensor. +/// indices: The indices used to index into the list. +/// element_shape: The shape of the elements in the list (can be less specified than +/// the shape of the tensor). +/// num_elements: The size of the output list. Must be large enough to accommodate +/// the largest index in indices. If -1, the list is just large enough to include +/// the largest index in indices. +/// output_handle: The TensorList. +@inlinable @inline(__always) +public static func tensorListScatterV2< + ElementDtype: TensorFlowScalar, + ShapeType: BinaryInteger & TensorFlowScalar +>( + _ tensor: Tensor, + indices: Tensor, + elementShape: Tensor, + numElements: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TensorListScatterV2", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(tensor) + op.addInput(indices) + op.addInput(elementShape) + op.addInput(numElements) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func tensorListSetItem( + inputHandle: VariantHandle, + index: Tensor, + item: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TensorListSetItem", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(index) + op.addInput(item) + return op.execute(Int(1)) +} + +/// Splits a tensor into a list. +/// +/// list[i] corresponds to lengths[i] tensors from the input tensor. +/// The tensor must have rank at least 1 and contain exactly sum(lengths) elements. +/// +/// tensor: The input tensor. +/// element_shape: A shape compatible with that of elements in the tensor. +/// lengths: Vector of sizes of the 0th dimension of tensors in the list. +/// output_handle: The list. +@inlinable @inline(__always) +public static func tensorListSplit< + ElementDtype: TensorFlowScalar, + ShapeType: BinaryInteger & TensorFlowScalar +>( + _ tensor: Tensor, + elementShape: Tensor, + lengths: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TensorListSplit", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(tensor) + op.addInput(elementShape) + op.addInput(lengths) + return op.execute(Int(1)) +} + +/// Stacks all tensors in the list. +/// +/// Requires that all tensors have the same shape. +/// +/// input_handle: the input list +/// tensor: the gathered result +/// num_elements: optional. If not -1, the number of elements in the list. +/// +@inlinable @inline(__always) +public static func tensorListStack( + inputHandle: VariantHandle, + elementShape: Tensor, + numElements: Int64 = -1 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorListStack", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("num_elements", numElements) + op.addInput(inputHandle) + op.addInput(elementShape) + return op.execute(Int(1)) +} + +/// Adds sparse `updates` to an existing tensor according to `indices`. +/// +/// This operation creates a new tensor by adding sparse `updates` to the passed +/// in `tensor`. +/// This operation is very similar to `tf.scatter_nd_add`, except that the updates +/// are added onto an existing tensor (as opposed to a variable). If the memory +/// for the existing tensor cannot be re-used, a copy is made and updated. +/// +/// `indices` is an integer tensor containing indices into a new tensor of shape +/// `shape`. The last dimension of `indices` can be at most the rank of `shape`: +/// +/// indices.shape[-1] <= shape.rank +/// +/// The last dimension of `indices` corresponds to indices into elements +/// (if `indices.shape[-1] = shape.rank`) or slices +/// (if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of +/// `shape`. `updates` is a tensor with shape +/// +/// indices.shape[:-1] + shape[indices.shape[-1]:] +/// +/// The simplest form of tensor_scatter_add is to add individual elements to a +/// tensor by index. For example, say we want to add 4 elements in a rank-1 +/// tensor with 8 elements. +/// +/// In Python, this scatter add operation would look like this: +/// +/// ```python +/// indices = tf.constant([[4], [3], [1], [7]]) +/// updates = tf.constant([9, 10, 11, 12]) +/// tensor = tf.ones([8], dtype=tf.int32) +/// updated = tf.tensor_scatter_add(tensor, indices, updates) +/// with tf.Session() as sess: +/// print(sess.run(scatter)) +/// ``` +/// +/// The resulting tensor would look like this: +/// +/// [1, 12, 1, 11, 10, 1, 1, 13] +/// +/// We can also, insert entire slices of a higher rank tensor all at once. For +/// example, if we wanted to insert two slices in the first dimension of a +/// rank-3 tensor with two matrices of new values. +/// +/// In Python, this scatter add operation would look like this: +/// +/// ```python +/// indices = tf.constant([[0], [2]]) +/// updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6], +/// [7, 7, 7, 7], [8, 8, 8, 8]], +/// [[5, 5, 5, 5], [6, 6, 6, 6], +/// [7, 7, 7, 7], [8, 8, 8, 8]]]) +/// tensor = tf.ones([4, 4, 4]) +/// updated = tf.tensor_scatter_add(tensor, indices, updates) +/// with tf.Session() as sess: +/// print(sess.run(scatter)) +/// ``` +/// +/// The resulting tensor would look like this: +/// +/// [[[6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8], [9, 9, 9, 9]], +/// [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], +/// [[6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8], [9, 9, 9, 9]], +/// [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]] +/// +/// Note that on CPU, if an out of bound index is found, an error is returned. +/// On GPU, if an out of bound index is found, the index is ignored. +/// +/// - Parameters: +/// - tensor: Tensor to copy/update. +/// - indices: Index tensor. +/// - updates: Updates to scatter into output. +/// +/// - Output output: A new tensor copied from tensor and updates added according to the indices. +@inlinable @inline(__always) +public static func tensorScatterAdd< + T: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + _ tensor: Tensor, + indices: Tensor, + updates: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorScatterAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(tensor) + op.addInput(indices) + op.addInput(updates) + return op.execute(Int(1)) +} + +/// Subtracts sparse `updates` from an existing tensor according to `indices`. +/// +/// This operation creates a new tensor by subtracting sparse `updates` from the +/// passed in `tensor`. +/// This operation is very similar to `tf.scatter_nd_sub`, except that the updates +/// are subtracted from an existing tensor (as opposed to a variable). If the memory +/// for the existing tensor cannot be re-used, a copy is made and updated. +/// +/// `indices` is an integer tensor containing indices into a new tensor of shape +/// `shape`. The last dimension of `indices` can be at most the rank of `shape`: +/// +/// indices.shape[-1] <= shape.rank +/// +/// The last dimension of `indices` corresponds to indices into elements +/// (if `indices.shape[-1] = shape.rank`) or slices +/// (if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of +/// `shape`. `updates` is a tensor with shape +/// +/// indices.shape[:-1] + shape[indices.shape[-1]:] +/// +/// The simplest form of tensor_scatter_sub is to subtract individual elements +/// from a tensor by index. For example, say we want to insert 4 scattered elements +/// in a rank-1 tensor with 8 elements. +/// +/// In Python, this scatter subtract operation would look like this: +/// +/// ```python +/// indices = tf.constant([[4], [3], [1], [7]]) +/// updates = tf.constant([9, 10, 11, 12]) +/// tensor = tf.ones([8], dtype=tf.int32) +/// updated = tf.tensor_scatter_sub(tensor, indices, updates) +/// with tf.Session() as sess: +/// print(sess.run(scatter)) +/// ``` +/// +/// The resulting tensor would look like this: +/// +/// [1, -10, 1, -9, -8, 1, 1, -11] +/// +/// We can also, insert entire slices of a higher rank tensor all at once. For +/// example, if we wanted to insert two slices in the first dimension of a +/// rank-3 tensor with two matrices of new values. +/// +/// In Python, this scatter add operation would look like this: +/// +/// ```python +/// indices = tf.constant([[0], [2]]) +/// updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6], +/// [7, 7, 7, 7], [8, 8, 8, 8]], +/// [[5, 5, 5, 5], [6, 6, 6, 6], +/// [7, 7, 7, 7], [8, 8, 8, 8]]]) +/// tensor = tf.ones([4, 4, 4]) +/// updated = tf.tensor_scatter_sub(tensor, indices, updates) +/// with tf.Session() as sess: +/// print(sess.run(scatter)) +/// ``` +/// +/// The resulting tensor would look like this: +/// +/// [[[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]], +/// [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], +/// [[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]], +/// [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]] +/// +/// Note that on CPU, if an out of bound index is found, an error is returned. +/// On GPU, if an out of bound index is found, the index is ignored. +/// +/// - Parameters: +/// - tensor: Tensor to copy/update. +/// - indices: Index tensor. +/// - updates: Updates to scatter into output. +/// +/// - Output output: A new tensor copied from tensor and updates subtracted according to the indices. +@inlinable @inline(__always) +public static func tensorScatterSub< + T: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + _ tensor: Tensor, + indices: Tensor, + updates: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorScatterSub", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(tensor) + op.addInput(indices) + op.addInput(updates) + return op.execute(Int(1)) +} + +/// Scatter `updates` into an existing tensor according to `indices`. +/// +/// This operation creates a new tensor by applying sparse `updates` to the passed +/// in `tensor`. +/// This operation is very similar to `tf.scatter_nd`, except that the updates are +/// scattered onto an existing tensor (as opposed to a zero-tensor). If the memory +/// for the existing tensor cannot be re-used, a copy is made and updated. +/// +/// If `indices` contains duplicates, then their updates are accumulated (summed). +/// +/// **WARNING**: The order in which updates are applied is nondeterministic, so the +/// output will be nondeterministic if `indices` contains duplicates -- because +/// of some numerical approximation issues, numbers summed in different order +/// may yield different results. +/// +/// `indices` is an integer tensor containing indices into a new tensor of shape +/// `shape`. The last dimension of `indices` can be at most the rank of `shape`: +/// +/// indices.shape[-1] <= shape.rank +/// +/// The last dimension of `indices` corresponds to indices into elements +/// (if `indices.shape[-1] = shape.rank`) or slices +/// (if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of +/// `shape`. `updates` is a tensor with shape +/// +/// indices.shape[:-1] + shape[indices.shape[-1]:] +/// +/// The simplest form of scatter is to insert individual elements in a tensor by +/// index. For example, say we want to insert 4 scattered elements in a rank-1 +/// tensor with 8 elements. +/// +///
+/// +///
+/// +/// In Python, this scatter operation would look like this: +/// +/// ```python +/// indices = tf.constant([[4], [3], [1], [7]]) +/// updates = tf.constant([9, 10, 11, 12]) +/// tensor = tf.ones([8], dtype=tf.int32) +/// updated = tf.tensor_scatter_update(tensor, indices, updates) +/// with tf.Session() as sess: +/// print(sess.run(scatter)) +/// ``` +/// +/// The resulting tensor would look like this: +/// +/// [1, 11, 1, 10, 9, 1, 1, 12] +/// +/// We can also, insert entire slices of a higher rank tensor all at once. For +/// example, if we wanted to insert two slices in the first dimension of a +/// rank-3 tensor with two matrices of new values. +/// +/// In Python, this scatter operation would look like this: +/// +/// ```python +/// indices = tf.constant([[0], [2]]) +/// updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6], +/// [7, 7, 7, 7], [8, 8, 8, 8]], +/// [[5, 5, 5, 5], [6, 6, 6, 6], +/// [7, 7, 7, 7], [8, 8, 8, 8]]]) +/// tensor = tf.ones([4, 4, 4]) +/// updated = tf.tensor_scatter_update(tensor, indices, updates) +/// with tf.Session() as sess: +/// print(sess.run(scatter)) +/// ``` +/// +/// The resulting tensor would look like this: +/// +/// [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], +/// [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], +/// [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], +/// [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]] +/// +/// Note that on CPU, if an out of bound index is found, an error is returned. +/// On GPU, if an out of bound index is found, the index is ignored. +/// +/// - Parameters: +/// - tensor: Tensor to copy/update. +/// - indices: Index tensor. +/// - updates: Updates to scatter into output. +/// +/// - Output output: A new tensor with the given shape and updates applied according +/// to the indices. +@inlinable @inline(__always) +public static func tensorScatterUpdate< + T: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + _ tensor: Tensor, + indices: Tensor, + updates: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorScatterUpdate", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(tensor) + op.addInput(indices) + op.addInput(updates) + return op.execute(Int(1)) +} + +/// Creates a dataset that emits each dim-0 slice of `components` once. +@inlinable @inline(__always) +public static func tensorSliceDataset( + components: ToutputTypes, + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TensorSliceDataset", nOutputs) + op.updateAttribute("Toutput_types", components._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInputList(components) + return op.execute(Int(1)) +} + +/// Assign `value` to the sliced l-value reference of `input`. +/// +/// The values of `value` are assigned to the positions in the tensor `input` that +/// are selected by the slice parameters. The slice parameters `begin` `end` +/// `strides` etc. work exactly as in `StridedSlice`. +/// +/// NOTE this op currently does not support broadcasting and so `value`'s shape +/// must be exactly the shape produced by the slice of `input`. +@inlinable @inline(__always) +public static func tensorStridedSliceUpdate< + T: TensorFlowScalar, + Index: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + begin: Tensor, + end: Tensor, + strides: Tensor, + value: Tensor, + beginMask: Int64 = 0, + endMask: Int64 = 0, + ellipsisMask: Int64 = 0, + newAxisMask: Int64 = 0, + shrinkAxisMask: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorStridedSliceUpdate", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Index", Index.tensorFlowDataType) + op.updateAttribute("begin_mask", beginMask) + op.updateAttribute("end_mask", endMask) + op.updateAttribute("ellipsis_mask", ellipsisMask) + op.updateAttribute("new_axis_mask", newAxisMask) + op.updateAttribute("shrink_axis_mask", shrinkAxisMask) + op.addInput(input) + op.addInput(begin) + op.addInput(end) + op.addInput(strides) + op.addInput(value) + return op.execute(Int(1)) +} + +/// Outputs a `Summary` protocol buffer with a tensor. +/// +/// This op is being phased out in favor of TensorSummaryV2, which lets callers pass +/// a tag as well as a serialized SummaryMetadata proto string that contains +/// plugin-specific data. We will keep this op to maintain backwards compatibility. +/// +/// - Parameter tensor: A tensor to serialize. +/// +/// - Attrs: +/// - description: A json-encoded SummaryDescription proto. +/// - labels: An unused list of strings. +/// - display_name: An unused string. +@inlinable @inline(__always) +public static func tensorSummary( + _ tensor: Tensor, + description: String, + labels: [String], + displayName: String +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("TensorSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("description", description) + op.updateAttribute("labels", labels) + op.updateAttribute("display_name", displayName) + op.addInput(tensor) + return op.execute(Int(1)) +} + +/// Outputs a `Summary` protocol buffer with a tensor and per-plugin data. +/// +/// - Parameters: +/// - tag: A string attached to this summary. Used for organization in TensorBoard. +/// - tensor: A tensor to serialize. +/// - serialized_summary_metadata: A serialized SummaryMetadata proto. Contains plugin +/// data. +@inlinable @inline(__always) +public static func tensorSummaryV2( + tag: StringTensor, + _ tensor: Tensor, + serializedSummaryMetadata: StringTensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("TensorSummaryV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(tag) + op.addInput(tensor) + op.addInput(serializedSummaryMetadata) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func testAttr( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TestAttr", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func testStringOutput( + _ input: Tensor +) -> (output1: Tensor, output2: StringTensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("TestStringOutput", nOutputs) + op.addInput(input) + return op.execute(Int(1), Int(1)) +} + +/// Creates a dataset that emits the lines of one or more text files. +/// +/// - Parameters: +/// - filenames: A scalar or a vector containing the name(s) of the file(s) to be +/// read. +/// - compression_type: A scalar containing either (i) the empty string (no +/// compression), (ii) "ZLIB", or (iii) "GZIP". +/// - buffer_size: A scalar containing the number of bytes to buffer. +@inlinable @inline(__always) +public static func textLineDataset( + filenames: StringTensor, + compressionType: StringTensor, + bufferSize: Tensor +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("TextLineDataset", nOutputs) + op.addInput(filenames) + op.addInput(compressionType) + op.addInput(bufferSize) + return op.execute(Int(1)) +} + +/// A Reader that outputs the lines of a file delimited by '\n'. +/// +/// - Attrs: +/// - skip_header_lines: Number of lines to skip from the beginning of every file. +/// - container: If non-empty, this reader is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this reader is named in the given bucket +/// with this shared_name. Otherwise, the node name is used instead. +/// +/// - Output reader_handle: The handle to reference the Reader. +@inlinable @inline(__always) +public static func textLineReaderV2( + skipHeaderLines: Int64 = 0, + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("TextLineReaderV2", nOutputs) + op.updateAttribute("skip_header_lines", skipHeaderLines) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// Generates labels for candidate sampling with a learned unigram distribution. +/// +/// See explanations of candidate sampling and the data formats at +/// go/candidate-sampling. +/// +/// For each batch, this op picks a single set of sampled candidate labels. +/// +/// The advantages of sampling candidates per-batch are simplicity and the +/// possibility of efficient dense matrix multiplication. The disadvantage is that +/// the sampled candidates must be chosen independently of the context and of the +/// true labels. +/// +/// - Parameter true_classes: A batch_size * num_true matrix, in which each row contains the +/// IDs of the num_true target_classes in the corresponding original label. +/// +/// - Attrs: +/// - num_true: Number of true labels per context. +/// - num_sampled: Number of candidates to randomly sample. +/// - unique: If unique is true, we sample with rejection, so that all sampled +/// candidates in a batch are unique. This requires some approximation to +/// estimate the post-rejection sampling probabilities. +/// - range_max: The sampler will sample integers from the interval [0, range_max). +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. +/// +/// - Outputs: +/// - sampled_candidates: A vector of length num_sampled, in which each element is +/// the ID of a sampled candidate. +/// - true_expected_count: A batch_size * num_true matrix, representing +/// the number of times each candidate is expected to occur in a batch +/// of sampled candidates. If unique=true, then this is a probability. +/// - sampled_expected_count: A vector of length num_sampled, for each sampled +/// candidate representing the number of times the candidate is expected +/// to occur in a batch of sampled candidates. If unique=true, then this is a +/// probability. +@inlinable @inline(__always) +public static func threadUnsafeUnigramCandidateSampler( + trueClasses: Tensor, + numTrue: Int64, + numSampled: Int64, + unique: Bool, + rangeMax: Int64, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> (sampledCandidates: Tensor, trueExpectedCount: Tensor, sampledExpectedCount: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("ThreadUnsafeUnigramCandidateSampler", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("num_sampled", numSampled) + op.updateAttribute("unique", unique) + op.updateAttribute("range_max", rangeMax) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Constructs a tensor by tiling a given tensor. +/// +/// This operation creates a new tensor by replicating `input` `multiples` times. +/// The output tensor's i'th dimension has `input.dims(i) * multiples[i]` elements, +/// and the values of `input` are replicated `multiples[i]` times along the 'i'th +/// dimension. For example, tiling `[a b c d]` by `[2]` produces +/// `[a b c d a b c d]`. +/// +/// - Parameters: +/// - input: 1-D or higher. +/// - multiples: 1-D. Length must be the same as the number of dimensions in `input` +@inlinable @inline(__always) +public static func tile< + T: TensorFlowScalar, + Tmultiples: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + multiples: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Tile", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tmultiples", Tmultiples.tensorFlowDataType) + op.addInput(input) + op.addInput(multiples) + return op.execute(Int(1)) +} + +/// Returns the gradient of `Tile`. +/// +/// Since `Tile` takes an input and repeats the input `multiples` times +/// along each dimension, `TileGrad` takes in `multiples` and aggregates +/// each repeated tile of `input` into `output`. +@inlinable @inline(__always) +public static func tileGrad( + _ input: Tensor, + multiples: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TileGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(multiples) + return op.execute(Int(1)) +} + +/// Provides the time since epoch in seconds. +/// +/// Returns the timestamp as a `float64` for seconds since the Unix epoch. +/// +/// Note: the timestamp is computed when the op is executed, not when it is added +/// to the graph. +@inlinable @inline(__always) +public static func timestamp( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Timestamp", nOutputs) + + return op.execute(Int(1)) +} + +/// Finds values and indices of the `k` largest elements for the last dimension. +/// +/// If the input is a vector (rank-1), finds the `k` largest entries in the vector +/// and outputs their values and indices as vectors. Thus `values[j]` is the +/// `j`-th largest entry in `input`, and its index is `indices[j]`. +/// +/// For matrices (resp. higher rank input), computes the top `k` entries in each +/// row (resp. vector along the last dimension). Thus, +/// +/// values.shape = indices.shape = input.shape[:-1] + [k] +/// +/// If two elements are equal, the lower-index element appears first. +/// +/// If `k` varies dynamically, use `TopKV2` below. +/// +/// - Parameter input: 1-D or higher with last dimension at least `k`. +/// +/// - Attrs: +/// - k: Number of top elements to look for along the last dimension (along each +/// row for matrices). +/// - sorted: If true the resulting `k` elements will be sorted by the values in +/// descending order. +/// +/// - Outputs: +/// - values: The `k` largest elements along each last dimensional slice. +/// - indices: The indices of `values` within the last dimension of `input`. +@inlinable @inline(__always) +public static func topK( + _ input: Tensor, + k: Int64, + sorted: Bool = true +) -> (values: Tensor, indices: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("TopK", nOutputs) + op.updateAttribute("k", k) + op.updateAttribute("sorted", sorted) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) +} + +/// Finds values and indices of the `k` largest elements for the last dimension. +/// +/// If the input is a vector (rank-1), finds the `k` largest entries in the vector +/// and outputs their values and indices as vectors. Thus `values[j]` is the +/// `j`-th largest entry in `input`, and its index is `indices[j]`. +/// +/// For matrices (resp. higher rank input), computes the top `k` entries in each +/// row (resp. vector along the last dimension). Thus, +/// +/// values.shape = indices.shape = input.shape[:-1] + [k] +/// +/// If two elements are equal, the lower-index element appears first. +/// +/// - Parameters: +/// - input: 1-D or higher with last dimension at least `k`. +/// - k: 0-D. Number of top elements to look for along the last dimension (along each +/// row for matrices). +/// +/// - Attr sorted: If true the resulting `k` elements will be sorted by the values in +/// descending order. +/// +/// - Outputs: +/// - values: The `k` largest elements along each last dimensional slice. +/// - indices: The indices of `values` within the last dimension of `input`. +@inlinable @inline(__always) +public static func topKV2( + _ input: Tensor, + k: Tensor, + sorted: Bool = true +) -> (values: Tensor, indices: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("TopKV2", nOutputs) + op.updateAttribute("sorted", sorted) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(k) + return op.execute(Int(1), Int(1)) +} + +/// Shuffle dimensions of x according to a permutation. +/// +/// The output `y` has the same rank as `x`. The shapes of `x` and `y` satisfy: +/// `y.shape[i] == x.shape[perm[i]] for i in [0, 1, ..., rank(x) - 1]` +@inlinable @inline(__always) +public static func transpose< + T: TensorFlowScalar, + Tperm: BinaryInteger & TensorFlowScalar +>( + _ x: Tensor, + perm: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Transpose", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tperm", Tperm.tensorFlowDataType) + op.addInput(x) + op.addInput(perm) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func tridiagonalMatMul( + superdiag: Tensor, + maindiag: Tensor, + subdiag: Tensor, + rhs: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TridiagonalMatMul", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(superdiag) + op.addInput(maindiag) + op.addInput(subdiag) + op.addInput(rhs) + return op.execute(Int(1)) +} + +/// Solves tridiagonal systems of equations. +/// +/// `diagonals` is a tensor of shape `[..., 3, M]` whose inner-most 2 dimensions +/// represent matrices with three rows being the superdiagonal, diagonals, and +/// subdiagonals, in order. The last element of the superdiagonal and the first +/// element of the subdiagonal is ignored. +/// `rhs` is a tensor of shape `[..., M, K]`, representing K right-hand sides per +/// each left-hand side. +/// The output is a tensor of shape `[..., M, K]` containing the solutions. +/// +/// - Parameters: +/// - diagonals: Shape is `[..., 3, M]`. +/// - rhs: Shape is `[..., M, K]`. +/// +/// - Output output: Shape is `[..., M, K]`. +@inlinable @inline(__always) +public static func tridiagonalSolve( + diagonals: Tensor, + rhs: Tensor, + partialPivoting: Bool = true +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TridiagonalSolve", nOutputs) + op.updateAttribute("partial_pivoting", partialPivoting) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(diagonals) + op.addInput(rhs) + return op.execute(Int(1)) +} + +/// Returns x / y element-wise for integer types. +/// +/// Truncation designates that negative numbers will round fractional quantities +/// toward zero. I.e. -7 / 5 = -1. This matches C semantics but it is different +/// than Python semantics. See `FloorDiv` for a division function that matches +/// Python Semantics. +/// +/// *NOTE*: `TruncateDiv` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func truncateDiv( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TruncateDiv", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns element-wise remainder of division. This emulates C semantics in that +/// +/// the result here is consistent with a truncating divide. E.g. `truncate(x / y) * +/// y + truncate_mod(x, y) = x`. +/// +/// *NOTE*: `TruncateMod` supports broadcasting. More about broadcasting +/// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +@inlinable @inline(__always) +public static func truncateMod( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TruncateMod", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Outputs random values from a truncated normal distribution. +/// +/// The generated values follow a normal distribution with mean 0 and standard +/// deviation 1, except that values whose magnitude is more than 2 standard +/// deviations from the mean are dropped and re-picked. +/// +/// - Parameter shape: The shape of the output tensor. +/// +/// - Attrs: +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. +/// - dtype: The type of the output. +/// +/// - Output output: A tensor of the specified shape filled with random truncated normal +/// values. +@inlinable @inline(__always) +public static func truncatedNormal< + Dtype: FloatingPoint & TensorFlowScalar, + T: BinaryInteger & TensorFlowScalar +>( + shape: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TruncatedNormal", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(shape) + return op.execute(Int(1)) +} + +/// Perform batches of RPC requests. +/// +/// This op asynchronously performs either a single RPC request, or a batch +/// of requests. RPC requests are defined by three main parameters: +/// +/// - `address` (the host+port or BNS address of the request) +/// - `method` (the method name for the request) +/// - `request` (the serialized proto string, or vector of strings, +/// of the RPC request argument). +/// +/// For example, if you have an RPC service running on port localhost:2345, +/// and its interface is configured with the following proto declaration: +/// +/// ``` +/// service MyService { +/// rpc MyMethod(MyRequestProto) returns (MyResponseProto) { +/// } +/// }; +/// ``` +/// +/// then call this op with arguments: +/// +/// ``` +/// address = "localhost:2345" +/// method = "MyService/MyMethod" +/// ``` +/// +/// The `request` tensor is a string tensor representing serialized `MyRequestProto` +/// strings; and the output string tensor `response` will have the same shape +/// and contain (upon successful completion) corresponding serialized +/// `MyResponseProto` strings. +/// +/// For example, to send a single, empty, `MyRequestProto`, call +/// this op with `request = ""`. To send 5 **parallel** empty requests, +/// call this op with `request = ["", "", "", "", ""]`. +/// +/// More generally, one can create a batch of `MyRequestProto` serialized protos +/// from regular batched tensors using the `encode_proto` op, and convert +/// the response `MyResponseProto` serialized protos to batched tensors +/// using the `decode_proto` op. +/// +/// **NOTE** Working with serialized proto strings is faster than instantiating +/// actual proto objects in memory, so no performance degradation is expected +/// compared to writing custom kernels for this workflow. +/// +/// Unlike the standard `Rpc` op, if the connection fails or the remote worker +/// returns an error status, this op does **not** reraise the exception. +/// Instead, the `status_code` and `status_message` entry for the corresponding RPC +/// call is set with the error returned from the RPC call. The `response` tensor +/// will contain valid response values for those minibatch entries whose RPCs did +/// not fail; the rest of the entries will have empty strings. +/// +/// - Parameters: +/// - address: `0-D` or `1-D`. The address (i.e. host_name:port) of the RPC server. +/// If this tensor has more than 1 element, then multiple parallel rpc requests +/// are sent. This argument broadcasts with `method` and `request`. +/// - method: `0-D` or `1-D`. The method address on the RPC server. +/// If this tensor has more than 1 element, then multiple parallel rpc requests +/// are sent. This argument broadcasts with `address` and `request`. +/// - request: `0-D` or `1-D`. Serialized proto strings: the rpc request argument. +/// If this tensor has more than 1 element, then multiple parallel rpc requests +/// are sent. This argument broadcasts with `address` and `method`. +/// +/// - Attrs: +/// - protocol: RPC protocol to use. Empty string means use the default protocol. +/// Options include 'grpc'. +/// - fail_fast: `boolean`. If `true` (default), then failures to connect +/// (i.e., the server does not immediately respond) cause an RPC failure. +/// - timeout_in_ms: `int`. If `0` (default), then the kernel will run the RPC +/// request and only time out if the RPC deadline passes or the session times out. +/// If this value is greater than `0`, then the op will raise an exception if +/// the RPC takes longer than `timeout_in_ms`. +/// +/// - Outputs: +/// - response: Same shape as `request`. Serialized proto strings: the rpc responses. +/// - status_code: Same shape as `request`. Values correspond to tensorflow Status enum codes. +/// - status_message: Same shape as `request`. Values correspond to Status messages +/// returned from the RPC calls. +@inlinable @inline(__always) +public static func tryRpc( + address: StringTensor, + method: StringTensor, + request: StringTensor, + protocol_: String, + failFast: Bool = true, + timeoutInMs: Int64 = 0 +) -> (response: StringTensor, statusCode: Tensor, statusMessage: StringTensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("TryRpc", nOutputs) + op.updateAttribute("protocol", protocol_) + op.updateAttribute("fail_fast", failFast) + op.updateAttribute("timeout_in_ms", timeoutInMs) + op.addInput(address) + op.addInput(method) + op.addInput(request) + return op.execute(Int(1), Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func twoFloatInputs( + _ a: Tensor, + _ b: Tensor +) { + let nOutputs = 0 + let op = makeOp("TwoFloatInputs", nOutputs) + op.addInput(a) + op.addInput(b) + op.execute() +} + +@inlinable @inline(__always) +public static func twoFloatInputsFloatOutput( + _ a: Tensor, + _ b: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TwoFloatInputsFloatOutput", nOutputs) + op.addInput(a) + op.addInput(b) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func twoFloatInputsIntOutput( + _ a: Tensor, + _ b: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TwoFloatInputsIntOutput", nOutputs) + op.addInput(a) + op.addInput(b) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func twoFloatOutputs( +) -> (a: Tensor, b: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("TwoFloatOutputs", nOutputs) + + return op.execute(Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func twoIntInputs( + _ a: Tensor, + _ b: Tensor +) { + let nOutputs = 0 + let op = makeOp("TwoIntInputs", nOutputs) + op.addInput(a) + op.addInput(b) + op.execute() +} + +@inlinable @inline(__always) +public static func twoIntOutputs( +) -> (a: Tensor, b: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("TwoIntOutputs", nOutputs) + + return op.execute(Int(1), Int(1)) +} + +@inlinable @inline(__always) +public static func typeList( + _ a: T +) { + let nOutputs = 0 + let op = makeOp("TypeList", nOutputs) + op.updateAttribute("T", a._typeList) + op.addInputList(a) + op.execute() +} + +@inlinable @inline(__always) +public static func typeListRestrict( + _ a: T +) { + let nOutputs = 0 + let op = makeOp("TypeListRestrict", nOutputs) + op.updateAttribute("T", a._typeList) + op.addInputList(a) + op.execute() +} + +@inlinable @inline(__always) +public static func typeListTwice( + _ a: T, + _ b: T +) { + let nOutputs = 0 + let op = makeOp("TypeListTwice", nOutputs) + op.updateAttribute("T", a._typeList) + op.addInputList(a) + op.addInputList(b) + op.execute() +} + +@inlinable @inline(__always) +public static func unary( + _ a: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Unary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + return op.execute(Int(1)) +} + +/// Reverses the operation of Batch for a single output Tensor. +/// +/// An instance of Unbatch either receives an empty batched_tensor, in which case it +/// asynchronously waits until the values become available from a concurrently +/// running instance of Unbatch with the same container and shared_name, or receives +/// a non-empty batched_tensor in which case it finalizes all other concurrently +/// running instances and outputs its own element from the batch. +/// +/// batched_tensor: The possibly transformed output of Batch. The size of the first +/// dimension should remain unchanged by the transformations for the operation to +/// work. +/// batch_index: The matching batch_index obtained from Batch. +/// id: The id scalar emitted by Batch. +/// unbatched_tensor: The Tensor corresponding to this execution. +/// timeout_micros: Maximum amount of time (in microseconds) to wait to receive the +/// batched input tensor associated with a given invocation of the op. +/// container: Container to control resource sharing. +/// shared_name: Instances of Unbatch with the same container and shared_name are +/// assumed to possibly belong to the same batch. If left empty, the op name will +/// be used as the shared name. +@inlinable @inline(__always) +public static func unbatch( + batchedTensor: Tensor, + batchIndex: Tensor, + id: Tensor, + timeoutMicros: Int64, + container: String, + sharedName: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Unbatch", nOutputs) + op.updateAttribute("timeout_micros", timeoutMicros) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(batchedTensor) + op.addInput(batchIndex) + op.addInput(id) + return op.execute(Int(1)) +} + +/// Gradient of Unbatch. +/// +/// Acts like Batch but using the given batch_index index of batching things as they +/// become available. This ensures that the gradients are propagated back in the +/// same session which did the forward pass. +/// +/// original_input: The input to the Unbatch operation this is the gradient of. +/// batch_index: The batch_index given to the Unbatch operation this is the gradient +/// of. +/// grad: The downstream gradient. +/// id: The id scalar emitted by Batch. +/// batched_grad: The return value, either an empty tensor or the batched gradient. +/// container: Container to control resource sharing. +/// shared_name: Instances of UnbatchGrad with the same container and shared_name +/// are assumed to possibly belong to the same batch. If left empty, the op name +/// will be used as the shared name. +@inlinable @inline(__always) +public static func unbatchGrad( + originalInput: Tensor, + batchIndex: Tensor, + grad: Tensor, + id: Tensor, + container: String, + sharedName: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("UnbatchGrad", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(originalInput) + op.addInput(batchIndex) + op.addInput(grad) + op.addInput(id) + return op.execute(Int(1)) +} + +/// Decodes each string in `input` into a sequence of Unicode code points. +/// +/// The character codepoints for all strings are returned using a single vector +/// `char_values`, with strings expanded to characters in row-major order. +/// +/// The `row_splits` tensor indicates where the codepoints for +/// each input string begin and end within the `char_values` tensor. +/// In particular, the values for the `i`th +/// string (in row-major order) are stored in the slice +/// `[row_splits[i]:row_splits[i+1]]`. Thus: +/// +/// * `char_values[row_splits[i]+j]` is the Unicode codepoint for the `j`th +/// character in the `i`th string (in row-major order). +/// * `row_splits[i+1] - row_splits[i]` is the number of characters in the `i`th +/// string (in row-major order). +/// +/// - Parameter input: The text to be decoded. Can have any shape. Note that the output is flattened +/// to a vector of char values. +/// +/// - Attrs: +/// - input_encoding: Text encoding of the input strings. This is any of the encodings supported +/// by ICU ucnv algorithmic converters. Examples: `"UTF-16", "US ASCII", "UTF-8"`. +/// - errors: Error handling policy when there is invalid formatting found in the input. +/// The value of 'strict' will cause the operation to produce a InvalidArgument +/// error on any invalid input formatting. A value of 'replace' (the default) will +/// cause the operation to replace any invalid formatting in the input with the +/// `replacement_char` codepoint. A value of 'ignore' will cause the operation to +/// skip any invalid formatting in the input and produce no corresponding output +/// character. +/// - replacement_char: The replacement character codepoint to be used in place of any invalid +/// formatting in the input when `errors='replace'`. Any valid unicode codepoint may +/// be used. The default value is the default unicode replacement character is +/// 0xFFFD or U+65533.) +/// - replace_control_characters: Whether to replace the C0 control characters (00-1F) with the +/// `replacement_char`. Default is false. +/// +/// - Outputs: +/// - row_splits: A 1D int32 tensor containing the row splits. +/// - char_values: A 1D int32 Tensor containing the decoded codepoints. +@inlinable @inline(__always) +public static func unicodeDecode( + _ input: StringTensor, + inputEncoding: String, + errors: Errors = .replace, + replacementChar: Int64 = 65533, + replaceControlCharacters: Bool = false +) -> (rowSplits: Tensor, charValues: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("UnicodeDecode", nOutputs) + op.updateAttribute("input_encoding", inputEncoding) + op.updateAttribute("errors", errors.cName) + op.updateAttribute("replacement_char", replacementChar) + op.updateAttribute("replace_control_characters", replaceControlCharacters) + op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) +} + +/// Decodes each string in `input` into a sequence of Unicode code points. +/// +/// The character codepoints for all strings are returned using a single vector +/// `char_values`, with strings expanded to characters in row-major order. +/// Similarly, the character start byte offsets are returned using a single vector +/// `char_to_byte_starts`, with strings expanded in row-major order. +/// +/// The `row_splits` tensor indicates where the codepoints and start offsets for +/// each input string begin and end within the `char_values` and +/// `char_to_byte_starts` tensors. In particular, the values for the `i`th +/// string (in row-major order) are stored in the slice +/// `[row_splits[i]:row_splits[i+1]]`. Thus: +/// +/// * `char_values[row_splits[i]+j]` is the Unicode codepoint for the `j`th +/// character in the `i`th string (in row-major order). +/// * `char_to_bytes_starts[row_splits[i]+j]` is the start byte offset for the `j`th +/// character in the `i`th string (in row-major order). +/// * `row_splits[i+1] - row_splits[i]` is the number of characters in the `i`th +/// string (in row-major order). +/// +/// - Parameter input: The text to be decoded. Can have any shape. Note that the output is flattened +/// to a vector of char values. +/// +/// - Attrs: +/// - input_encoding: Text encoding of the input strings. This is any of the encodings supported +/// by ICU ucnv algorithmic converters. Examples: `"UTF-16", "US ASCII", "UTF-8"`. +/// - errors: Error handling policy when there is invalid formatting found in the input. +/// The value of 'strict' will cause the operation to produce a InvalidArgument +/// error on any invalid input formatting. A value of 'replace' (the default) will +/// cause the operation to replace any invalid formatting in the input with the +/// `replacement_char` codepoint. A value of 'ignore' will cause the operation to +/// skip any invalid formatting in the input and produce no corresponding output +/// character. +/// - replacement_char: The replacement character codepoint to be used in place of any invalid +/// formatting in the input when `errors='replace'`. Any valid unicode codepoint may +/// be used. The default value is the default unicode replacement character is +/// 0xFFFD or U+65533.) +/// - replace_control_characters: Whether to replace the C0 control characters (00-1F) with the +/// `replacement_char`. Default is false. +/// +/// - Outputs: +/// - row_splits: A 1D int32 tensor containing the row splits. +/// - char_values: A 1D int32 Tensor containing the decoded codepoints. +/// - char_to_byte_starts: A 1D int32 Tensor containing the byte index in the input string where each +/// character in `char_values` starts. +@inlinable @inline(__always) +public static func unicodeDecodeWithOffsets( + _ input: StringTensor, + inputEncoding: String, + errors: Errors = .replace, + replacementChar: Int64 = 65533, + replaceControlCharacters: Bool = false +) -> (rowSplits: Tensor, charValues: Tensor, charToByteStarts: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("UnicodeDecodeWithOffsets", nOutputs) + op.updateAttribute("input_encoding", inputEncoding) + op.updateAttribute("errors", errors.cName) + op.updateAttribute("replacement_char", replacementChar) + op.updateAttribute("replace_control_characters", replaceControlCharacters) + op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Encode a tensor of ints into unicode strings. +/// +/// Returns a vector of strings, where `output[i]` is constructed by encoding the +/// Unicode codepoints in `input_values[input_splits[i]:input_splits[i+1]]` +/// using `output_encoding`. +/// +/// --- +/// +/// Example: +/// +/// ``` +/// input_values = [72, 101, 108, 108, 111, 87, 111, 114, 108, 100] +/// input_splits = [0, 5, 10] +/// output_encoding = 'UTF-8' +/// +/// output = ['Hello', 'World'] +/// ``` +/// +/// - Parameters: +/// - input_values: A 1D tensor containing the unicode codepoints that should be encoded. +/// - input_splits: A 1D tensor specifying how the unicode codepoints should be split into strings. +/// In particular, `output[i]` is constructed by encoding the codepoints in the +/// slice `input_values[input_splits[i]:input_splits[i+1]]`. +/// +/// - Attrs: +/// - errors: Error handling policy when there is invalid formatting found in the input. +/// The value of 'strict' will cause the operation to produce a InvalidArgument +/// error on any invalid input formatting. A value of 'replace' (the default) will +/// cause the operation to replace any invalid formatting in the input with the +/// `replacement_char` codepoint. A value of 'ignore' will cause the operation to +/// skip any invalid formatting in the input and produce no corresponding output +/// character. +/// - output_encoding: Unicode encoding of the output strings. Valid encodings are: `"UTF-8", +/// "UTF-16-BE", and "UTF-32-BE"`. +/// - replacement_char: The replacement character codepoint to be used in place of any invalid +/// formatting in the input when `errors='replace'`. Any valid unicode codepoint may +/// be used. The default value is the default unicode replacement character is +/// 0xFFFD (U+65533). +/// +/// - Output output: The 1-D Tensor of strings encoded from the provided unicode codepoints. +@inlinable @inline(__always) +public static func unicodeEncode( + inputValues: Tensor, + inputSplits: Tensor, + errors: Errors = .replace, + outputEncoding: OutputEncoding, + replacementChar: Int64 = 65533 +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("UnicodeEncode", nOutputs) + op.updateAttribute("errors", errors.cName) + op.updateAttribute("output_encoding", outputEncoding.cName) + op.updateAttribute("replacement_char", replacementChar) + op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) + op.addInput(inputValues) + op.addInput(inputSplits) + return op.execute(Int(1)) +} + +/// Determine the script codes of a given tensor of Unicode integer code points. +/// +/// This operation converts Unicode code points to script codes corresponding to +/// each code point. Script codes correspond to International Components for +/// Unicode (ICU) UScriptCode values. See http://icu-project.org/apiref/icu4c/uscript_8h.html. +/// Returns -1 (USCRIPT_INVALID_CODE) for invalid codepoints. Output shape will +/// match input shape. +/// +/// - Parameter input: A Tensor of int32 Unicode code points. +/// +/// - Output output: A Tensor of int32 script codes corresponding to each input code point. +@inlinable @inline(__always) +public static func unicodeScript( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("UnicodeScript", nOutputs) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Transcode the input text from a source encoding to a destination encoding. +/// +/// The input is a string tensor of any shape. The output is a string tensor of +/// the same shape containing the transcoded strings. Output strings are always +/// valid unicode. If the input contains invalid encoding positions, the +/// `errors` attribute sets the policy for how to deal with them. If the default +/// error-handling policy is used, invalid formatting will be substituted in the +/// output by the `replacement_char`. If the errors policy is to `ignore`, any +/// invalid encoding positions in the input are skipped and not included in the +/// output. If it set to `strict` then any invalid formatting will result in an +/// InvalidArgument error. +/// +/// This operation can be used with `output_encoding = input_encoding` to enforce +/// correct formatting for inputs even if they are already in the desired encoding. +/// +/// If the input is prefixed by a Byte Order Mark needed to determine encoding +/// (e.g. if the encoding is UTF-16 and the BOM indicates big-endian), then that +/// BOM will be consumed and not emitted into the output. If the input encoding +/// is marked with an explicit endianness (e.g. UTF-16-BE), then the BOM is +/// interpreted as a non-breaking-space and is preserved in the output (including +/// always for UTF-8). +/// +/// The end result is that if the input is marked as an explicit endianness the +/// transcoding is faithful to all codepoints in the source. If it is not marked +/// with an explicit endianness, the BOM is not considered part of the string itself +/// but as metadata, and so is not preserved in the output. +/// +/// - Parameter input: The text to be processed. Can have any shape. +/// +/// - Attrs: +/// - input_encoding: Text encoding of the input strings. This is any of the encodings supported +/// by ICU ucnv algorithmic converters. Examples: `"UTF-16", "US ASCII", "UTF-8"`. +/// - output_encoding: The unicode encoding to use in the output. Must be one of +/// `"UTF-8", "UTF-16-BE", "UTF-32-BE"`. Multi-byte encodings will be big-endian. +/// - errors: Error handling policy when there is invalid formatting found in the input. +/// The value of 'strict' will cause the operation to produce a InvalidArgument +/// error on any invalid input formatting. A value of 'replace' (the default) will +/// cause the operation to replace any invalid formatting in the input with the +/// `replacement_char` codepoint. A value of 'ignore' will cause the operation to +/// skip any invalid formatting in the input and produce no corresponding output +/// character. +/// - replacement_char: The replacement character codepoint to be used in place of any invalid +/// formatting in the input when `errors='replace'`. Any valid unicode codepoint may +/// be used. The default value is the default unicode replacement character is +/// 0xFFFD or U+65533.) +/// +/// Note that for UTF-8, passing a replacement character expressible in 1 byte, such +/// as ' ', will preserve string alignment to the source since invalid bytes will be +/// replaced with a 1-byte replacement. For UTF-16-BE and UTF-16-LE, any 1 or 2 byte +/// replacement character will preserve byte alignment to the source. +/// - replace_control_characters: Whether to replace the C0 control characters (00-1F) with the +/// `replacement_char`. Default is false. +/// +/// - Output output: A string tensor containing unicode text encoded using `output_encoding`. +@inlinable @inline(__always) +public static func unicodeTranscode( + _ input: StringTensor, + inputEncoding: String, + outputEncoding: OutputEncoding, + errors: Errors = .replace, + replacementChar: Int64 = 65533, + replaceControlCharacters: Bool = false +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("UnicodeTranscode", nOutputs) + op.updateAttribute("input_encoding", inputEncoding) + op.updateAttribute("output_encoding", outputEncoding.cName) + op.updateAttribute("errors", errors.cName) + op.updateAttribute("replacement_char", replacementChar) + op.updateAttribute("replace_control_characters", replaceControlCharacters) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Generates labels for candidate sampling with a uniform distribution. +/// +/// See explanations of candidate sampling and the data formats at +/// go/candidate-sampling. +/// +/// For each batch, this op picks a single set of sampled candidate labels. +/// +/// The advantages of sampling candidates per-batch are simplicity and the +/// possibility of efficient dense matrix multiplication. The disadvantage is that +/// the sampled candidates must be chosen independently of the context and of the +/// true labels. +/// +/// - Parameter true_classes: A batch_size * num_true matrix, in which each row contains the +/// IDs of the num_true target_classes in the corresponding original label. +/// +/// - Attrs: +/// - num_true: Number of true labels per context. +/// - num_sampled: Number of candidates to randomly sample. +/// - unique: If unique is true, we sample with rejection, so that all sampled +/// candidates in a batch are unique. This requires some approximation to +/// estimate the post-rejection sampling probabilities. +/// - range_max: The sampler will sample integers from the interval [0, range_max). +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. +/// +/// - Outputs: +/// - sampled_candidates: A vector of length num_sampled, in which each element is +/// the ID of a sampled candidate. +/// - true_expected_count: A batch_size * num_true matrix, representing +/// the number of times each candidate is expected to occur in a batch +/// of sampled candidates. If unique=true, then this is a probability. +/// - sampled_expected_count: A vector of length num_sampled, for each sampled +/// candidate representing the number of times the candidate is expected +/// to occur in a batch of sampled candidates. If unique=true, then this is a +/// probability. +@inlinable @inline(__always) +public static func uniformCandidateSampler( + trueClasses: Tensor, + numTrue: Int64, + numSampled: Int64, + unique: Bool, + rangeMax: Int64, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> (sampledCandidates: Tensor, trueExpectedCount: Tensor, sampledExpectedCount: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("UniformCandidateSampler", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("num_sampled", numSampled) + op.updateAttribute("unique", unique) + op.updateAttribute("range_max", rangeMax) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Finds unique elements in a 1-D tensor. +/// +/// This operation returns a tensor `y` containing all of the unique elements of `x` +/// sorted in the same order that they occur in `x`. This operation also returns a +/// tensor `idx` the same size as `x` that contains the index of each value of `x` +/// in the unique output `y`. In other words: +/// +/// `y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]` +/// +/// For example: +/// +/// ``` +/// # tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8] +/// y, idx = unique(x) +/// y ==> [1, 2, 4, 7, 8] +/// idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4] +/// ``` +/// +/// - Parameter x: 1-D. +/// +/// - Outputs: +/// - y: 1-D. +/// - idx: 1-D. +@inlinable @inline(__always) +public static func unique< + T: TensorFlowScalar, + OutIdx: BinaryInteger & TensorFlowScalar +>( + _ x: Tensor +) -> (y: Tensor, idx: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("Unique", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1), Int(1)) +} + +/// Finds unique elements along an axis of a tensor. +/// +/// This operation either returns a tensor `y` containing unique elements +/// along the `axis` of a tensor. The returned unique elements is sorted +/// in the same order as they occur along `axis` in `x`. +/// This operation also returns a tensor `idx` that is the same size as +/// the number of the elements in `x` along the `axis` dimension. It +/// contains the index in the unique output `y`. +/// In other words, for an `1-D` tensor `x` with `axis = None: +/// +/// `y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]` +/// +/// For example: +/// +/// ``` +/// # tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8] +/// y, idx = unique(x) +/// y ==> [1, 2, 4, 7, 8] +/// idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4] +/// ``` +/// +/// For an `2-D` tensor `x` with `axis = 0`: +/// +/// ``` +/// # tensor 'x' is [[1, 0, 0], +/// # [1, 0, 0], +/// # [2, 0, 0]] +/// y, idx = unique(x, axis=0) +/// y ==> [[1, 0, 0], +/// [2, 0, 0]] +/// idx ==> [0, 0, 1] +/// ``` +/// +/// For an `2-D` tensor `x` with `axis = 1`: +/// +/// ``` +/// # tensor 'x' is [[1, 0, 0], +/// # [1, 0, 0], +/// # [2, 0, 0]] +/// y, idx = unique(x, axis=1) +/// y ==> [[1, 0], +/// [1, 0], +/// [2, 0]] +/// idx ==> [0, 1, 1] +/// ``` +/// +/// - Parameters: +/// - x: A `Tensor`. +/// - axis: A `Tensor` of type `int32` (default: None). The axis of the Tensor to +/// find the unique elements. +/// +/// - Outputs: +/// - y: A `Tensor`. Unique elements along the `axis` of `Tensor` x. +/// - idx: A 1-D Tensor. Has the same type as x that contains the index of each +/// value of x in the output y. +@inlinable @inline(__always) +public static func uniqueV2< + T: TensorFlowScalar, + Taxis: BinaryInteger & TensorFlowScalar, + OutIdx: BinaryInteger & TensorFlowScalar +>( + _ x: Tensor, + axis: Tensor +) -> (y: Tensor, idx: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("UniqueV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Taxis", Taxis.tensorFlowDataType) + op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) + op.addInput(x) + op.addInput(axis) + return op.execute(Int(1), Int(1)) +} + +/// Finds unique elements in a 1-D tensor. +/// +/// This operation returns a tensor `y` containing all of the unique elements of `x` +/// sorted in the same order that they occur in `x`. This operation also returns a +/// tensor `idx` the same size as `x` that contains the index of each value of `x` +/// in the unique output `y`. Finally, it returns a third tensor `count` that +/// contains the count of each element of `y` in `x`. In other words: +/// +/// `y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]` +/// +/// For example: +/// +/// ``` +/// # tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8] +/// y, idx, count = unique_with_counts(x) +/// y ==> [1, 2, 4, 7, 8] +/// idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4] +/// count ==> [2, 1, 3, 1, 2] +/// ``` +/// +/// - Parameter x: 1-D. +/// +/// - Outputs: +/// - y: 1-D. +/// - idx: 1-D. +/// - count: 1-D. +@inlinable @inline(__always) +public static func uniqueWithCounts< + T: TensorFlowScalar, + OutIdx: BinaryInteger & TensorFlowScalar +>( + _ x: Tensor +) -> (y: Tensor, idx: Tensor, count: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("UniqueWithCounts", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Finds unique elements along an axis of a tensor. +/// +/// This operation either returns a tensor `y` containing unique elements +/// along the `axis` of a tensor. The returned unique elements is sorted +/// in the same order as they occur along `axis` in `x`. +/// This operation also returns a tensor `idx` and a tensor `count` +/// that are the same size as the number of the elements in `x` along the +/// `axis` dimension. The `idx` contains the index in the unique output `y` +/// and the `count` contains the count in the unique output `y`. +/// In other words, for an `1-D` tensor `x` with `axis = None: +/// +/// `y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]` +/// +/// For example: +/// +/// ``` +/// # tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8] +/// y, idx, count = unique_with_counts(x) +/// y ==> [1, 2, 4, 7, 8] +/// idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4] +/// count ==> [2, 1, 3, 1, 2] +/// ``` +/// +/// For an `2-D` tensor `x` with `axis = 0`: +/// +/// ``` +/// # tensor 'x' is [[1, 0, 0], +/// # [1, 0, 0], +/// # [2, 0, 0]] +/// y, idx, count = unique_with_counts(x, axis=0) +/// y ==> [[1, 0, 0], +/// [2, 0, 0]] +/// idx ==> [0, 0, 1] +/// count ==> [2, 1] +/// ``` +/// +/// For an `2-D` tensor `x` with `axis = 1`: +/// +/// ``` +/// # tensor 'x' is [[1, 0, 0], +/// # [1, 0, 0], +/// # [2, 0, 0]] +/// y, idx, count = unique_with_counts(x, axis=1) +/// y ==> [[1, 0], +/// [1, 0], +/// [2, 0]] +/// idx ==> [0, 1, 1] +/// count ==> [1, 2] +/// ``` +/// +/// - Parameters: +/// - x: A `Tensor`. +/// - axis: A `Tensor` of type `int32` (default: None). The axis of the Tensor to +/// find the unique elements. +/// +/// - Outputs: +/// - y: A `Tensor`. Unique elements along the `axis` of `Tensor` x. +/// - idx: A 1-D Tensor. Has the same type as x that contains the index of each +/// value of x in the output y. +/// - count: A 1-D Tensor. The count of each value of x in the output y. +@inlinable @inline(__always) +public static func uniqueWithCountsV2< + T: TensorFlowScalar, + Taxis: BinaryInteger & TensorFlowScalar, + OutIdx: BinaryInteger & TensorFlowScalar +>( + _ x: Tensor, + axis: Tensor +) -> (y: Tensor, idx: Tensor, count: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("UniqueWithCountsV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Taxis", Taxis.tensorFlowDataType) + op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) + op.addInput(x) + op.addInput(axis) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// Unpacks a given dimension of a rank-`R` tensor into `num` rank-`(R-1)` tensors. +/// +/// Unpacks `num` tensors from `value` by chipping it along the `axis` dimension. +/// For example, given a tensor of shape `(A, B, C, D)`; +/// +/// If `axis == 0` then the i'th tensor in `output` is the slice `value[i, :, :, :]` +/// and each tensor in `output` will have shape `(B, C, D)`. (Note that the +/// dimension unpacked along is gone, unlike `split`). +/// +/// If `axis == 1` then the i'th tensor in `output` is the slice `value[:, i, :, :]` +/// and each tensor in `output` will have shape `(A, C, D)`. +/// Etc. +/// +/// This is the opposite of `pack`. +/// +/// - Parameter value: 1-D or higher, with `axis` dimension size equal to `num`. +/// +/// - Attr axis: Dimension along which to unpack. Negative values wrap around, so the +/// valid range is `[-R, R)`. +/// +/// - Output output: The list of tensors unpacked from `value`. +@inlinable @inline(__always) +public static func unpack( + value: Tensor, + num: Int64, + axis: Int64 = 0 +) -> [Tensor] { + let nOutputs = Int(num) + let op = makeOp("Unpack", nOutputs) + op.updateAttribute("num", num) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("axis", axis) + op.addInput(value) + return op.execute(Int(num)) +} + +/// Converts a flat index or array of flat indices into a tuple of +/// +/// coordinate arrays. +/// +/// @compatibility(numpy) +/// Equivalent to np.unravel_index +/// @end_compatibility +/// +/// - Parameters: +/// - indices: An 0-D or 1-D `int` Tensor whose elements are indices into the +/// flattened version of an array of dimensions dims. +/// - dims: An 1-D `int` Tensor. The shape of the array to use for unraveling +/// indices. +/// +/// - Output output: An 2-D (or 1-D if indices is 0-D) tensor where each row has the +/// same shape as the indices array. +@inlinable @inline(__always) +public static func unravelIndex( + indices: Tensor, + dims: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("UnravelIndex", nOutputs) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(indices) + op.addInput(dims) + return op.execute(Int(1)) +} + +/// Computes the maximum along segments of a tensor. +/// +/// Read +/// [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) +/// for an explanation of segments. +/// +/// This operator is similar to the unsorted segment sum operator found +/// [(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum). +/// Instead of computing the sum over segments, it computes the maximum such that: +/// +/// \\(output_i = \max_{j...} data[j...]\\) where max is over tuples `j...` such +/// that `segment_ids[j...] == i`. +/// +/// If the maximum is empty for a given segment ID `i`, it outputs the smallest +/// possible value for the specific numeric type, +/// `output[i] = numeric_limits::lowest()`. +/// +/// If the given segment ID `i` is negative, then the corresponding value is +/// dropped, and will not be included in the result. +/// +///
+/// +///
+/// +/// For example: +/// +/// ``` python +/// c = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]]) +/// tf.unsorted_segment_max(c, tf.constant([0, 1, 0]), num_segments=2) +/// # ==> [[ 4, 3, 3, 4], +/// # [5, 6, 7, 8]] +/// ``` +/// +/// +/// - Parameter segment_ids: A tensor whose shape is a prefix of `data.shape`. +/// +/// - Output output: Has same shape as data, except for the first `segment_ids.rank` +/// dimensions, which are replaced with a single dimension which has size +/// `num_segments`. +@inlinable @inline(__always) +public static func unsortedSegmentMax< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar, + Tnumsegments: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + segmentIds: Tensor, + numSegments: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("UnsortedSegmentMax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) +} + +/// Computes the minimum along segments of a tensor. +/// +/// Read +/// [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) +/// for an explanation of segments. +/// +/// This operator is similar to the unsorted segment sum operator found +/// [(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum). +/// Instead of computing the sum over segments, it computes the minimum such that: +/// +/// \\(output_i = \min_{j...} data_[j...]\\) where min is over tuples `j...` such +/// that `segment_ids[j...] == i`. +/// +/// If the minimum is empty for a given segment ID `i`, it outputs the largest +/// possible value for the specific numeric type, +/// `output[i] = numeric_limits::max()`. +/// +/// For example: +/// +/// ``` python +/// c = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]]) +/// tf.unsorted_segment_min(c, tf.constant([0, 1, 0]), num_segments=2) +/// # ==> [[ 1, 2, 2, 1], +/// # [5, 6, 7, 8]] +/// ``` +/// +/// If the given segment ID `i` is negative, then the corresponding value is +/// dropped, and will not be included in the result. +/// +/// - Parameter segment_ids: A tensor whose shape is a prefix of `data.shape`. +/// +/// - Output output: Has same shape as data, except for the first `segment_ids.rank` +/// dimensions, which are replaced with a single dimension which has size +/// `num_segments`. +@inlinable @inline(__always) +public static func unsortedSegmentMin< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar, + Tnumsegments: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + segmentIds: Tensor, + numSegments: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("UnsortedSegmentMin", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) +} + +/// Computes the product along segments of a tensor. +/// +/// Read +/// [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) +/// for an explanation of segments. +/// +/// This operator is similar to the unsorted segment sum operator found +/// [(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum). +/// Instead of computing the sum over segments, it computes the product of all +/// entries belonging to a segment such that: +/// +/// \\(output_i = \prod_{j...} data[j...]\\) where the product is over tuples +/// `j...` such that `segment_ids[j...] == i`. +/// +/// For example: +/// +/// ``` python +/// c = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]]) +/// tf.unsorted_segment_prod(c, tf.constant([0, 1, 0]), num_segments=2) +/// # ==> [[ 4, 6, 6, 4], +/// # [5, 6, 7, 8]] +/// ``` +/// +/// If there is no entry for a given segment ID `i`, it outputs 1. +/// +/// If the given segment ID `i` is negative, then the corresponding value is +/// dropped, and will not be included in the result. +/// +/// - Parameter segment_ids: A tensor whose shape is a prefix of `data.shape`. +/// +/// - Output output: Has same shape as data, except for the first `segment_ids.rank` +/// dimensions, which are replaced with a single dimension which has size +/// `num_segments`. +@inlinable @inline(__always) +public static func unsortedSegmentProd< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar, + Tnumsegments: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + segmentIds: Tensor, + numSegments: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("UnsortedSegmentProd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) +} + +/// Computes the sum along segments of a tensor. +/// +/// Read +/// [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) +/// for an explanation of segments. +/// +/// Computes a tensor such that +/// \\(output[i] = \sum_{j...} data[j...]\\) where the sum is over tuples `j...` such +/// that `segment_ids[j...] == i`. Unlike `SegmentSum`, `segment_ids` +/// need not be sorted and need not cover all values in the full +/// range of valid values. +/// +/// If the sum is empty for a given segment ID `i`, `output[i] = 0`. +/// If the given segment ID `i` is negative, the value is dropped and will not be +/// added to the sum of the segment. +/// +/// `num_segments` should equal the number of distinct segment IDs. +/// +///
+/// +///
+/// +/// ``` python +/// c = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]]) +/// tf.unsorted_segment_sum(c, tf.constant([0, 1, 0]), num_segments=2) +/// # ==> [[ 5, 5, 5, 5], +/// # [5, 6, 7, 8]] +/// ``` +/// +/// +/// - Parameter segment_ids: A tensor whose shape is a prefix of `data.shape`. +/// +/// - Output output: Has same shape as data, except for the first `segment_ids.rank` +/// dimensions, which are replaced with a single dimension which has size +/// `num_segments`. +@inlinable @inline(__always) +public static func unsortedSegmentSum< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar, + Tnumsegments: BinaryInteger & TensorFlowScalar +>( + data: Tensor, + segmentIds: Tensor, + numSegments: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("UnsortedSegmentSum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) +} + +/// Op is similar to a lightweight Dequeue. +/// +/// The basic functionality is similar to dequeue with many fewer +/// capabilities and options. This Op is optimized for performance. +@inlinable @inline(__always) +public static func unstage( + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String +) -> Dtypes { + let nOutputs = Int(Dtypes._typeList.count) + let op = makeOp("Unstage", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(Dtypes._typeList.count)) +} + +@inlinable @inline(__always) +public static func unwrapDatasetVariant( + inputHandle: VariantHandle +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("UnwrapDatasetVariant", nOutputs) + op.addInput(inputHandle) + return op.execute(Int(1)) +} + +/// Applies upper_bound(sorted_search_values, values) along each row. +/// +/// Each set of rows with the same index in (sorted_inputs, values) is treated +/// independently. The resulting row is the equivalent of calling +/// `np.searchsorted(sorted_inputs, values, side='right')`. +/// +/// The result is not a global index to the entire +/// `Tensor`, but rather just the index in the last dimension. +/// +/// A 2-D example: +/// sorted_sequence = [[0, 3, 9, 9, 10], +/// [1, 2, 3, 4, 5]] +/// values = [[2, 4, 9], +/// [0, 2, 6]] +/// +/// result = UpperBound(sorted_sequence, values) +/// +/// result == [[1, 2, 4], +/// [0, 2, 5]] +/// +/// - Parameters: +/// - sorted_inputs: 2-D Tensor where each row is ordered. +/// - values: 2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains +/// the values that will be searched for in `sorted_search_values`. +/// +/// - Output output: A `Tensor` with the same shape as `values`. It contains the last scalar index +/// into the last dimension where values can be inserted without changing the +/// ordered property. +@inlinable @inline(__always) +public static func upperBound< + T: TensorFlowScalar, + OutType: BinaryInteger & TensorFlowScalar +>( + sortedInputs: Tensor, + _ values: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("UpperBound", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(sortedInputs) + op.addInput(values) + return op.execute(Int(1)) +} + +/// Creates a handle to a Variable resource. +/// +/// - Attrs: +/// - container: the container this variable is placed in. +/// - shared_name: the name by which this variable is referred to. +/// - dtype: the type of this variable. Must agree with the dtypes +/// of all ops using this variable. +/// - shape: The (possibly partially specified) shape of this variable. +@inlinable @inline(__always) +public static func varHandleOp( + container: String, + sharedName: String, + dtype: TensorDataType, + shape: TensorShape? +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("VarHandleOp", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("dtype", dtype) + op.updateAttribute("shape", shape) + return op.execute(Int(1)) +} + +/// Checks whether a resource handle-based variable has been initialized. +/// +/// - Parameter resource: the input resource handle. +/// +/// - Output is_initialized: a scalar boolean which is true if the variable has been +/// initialized. +@inlinable @inline(__always) +public static func varIsInitializedOp( + resource: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("VarIsInitializedOp", nOutputs) + op.addInput(resource) + return op.execute(Int(1)) +} + +/// Returns the shape of the variable pointed to by `resource`. +/// +/// This operation returns a 1-D integer tensor representing the shape of `input`. +/// +/// For example: +/// +/// ``` +/// # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] +/// shape(t) ==> [2, 2, 3] +/// ``` +@inlinable @inline(__always) +public static func variableShape( + _ input: ResourceHandle +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("VariableShape", nOutputs) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Returns locations of nonzero / true values in a tensor. +/// +/// This operation returns the coordinates of true elements in `condition`. The +/// coordinates are returned in a 2-D tensor where the first dimension (rows) +/// represents the number of true elements, and the second dimension (columns) +/// represents the coordinates of the true elements. Keep in mind, the shape of +/// the output tensor can vary depending on how many true values there are in +/// `condition`. Indices are output in row-major order. +/// +/// For example: +/// +/// ``` +/// # 'input' tensor is [[True, False] +/// # [True, False]] +/// # 'input' has two true values, so output has two coordinates. +/// # 'input' has rank of 2, so coordinates have two indices. +/// where(input) ==> [[0, 0], +/// [1, 0]] +/// +/// # `condition` tensor is [[[True, False] +/// # [True, False]] +/// # [[False, True] +/// # [False, True]] +/// # [[False, False] +/// # [False, True]]] +/// # 'input' has 5 true values, so output has 5 coordinates. +/// # 'input' has rank of 3, so coordinates have three indices. +/// where(input) ==> [[0, 0, 0], +/// [0, 1, 0], +/// [1, 0, 1], +/// [1, 1, 1], +/// [2, 1, 1]] +/// +/// # `condition` tensor is [[[1.5, 0.0] +/// # [-0.5, 0.0]] +/// # [[0.0, 0.25] +/// # [0.0, 0.75]] +/// # [[0.0, 0.0] +/// # [0.0, 0.01]]] +/// # 'input' has 5 nonzero values, so output has 5 coordinates. +/// # 'input' has rank of 3, so coordinates have three indices. +/// where(input) ==> [[0, 0, 0], +/// [0, 1, 0], +/// [1, 0, 1], +/// [1, 1, 1], +/// [2, 1, 1]] +/// +/// # `condition` tensor is [[[1.5 + 0.0j, 0.0 + 0.0j] +/// # [0.0 + 0.5j, 0.0 + 0.0j]] +/// # [[0.0 + 0.0j, 0.25 + 1.5j] +/// # [0.0 + 0.0j, 0.75 + 0.0j]] +/// # [[0.0 + 0.0j, 0.0 + 0.0j] +/// # [0.0 + 0.0j, 0.01 + 0.0j]]] +/// # 'input' has 5 nonzero magnitude values, so output has 5 coordinates. +/// # 'input' has rank of 3, so coordinates have three indices. +/// where(input) ==> [[0, 0, 0], +/// [0, 1, 0], +/// [1, 0, 1], +/// [1, 1, 1], +/// [2, 1, 1]] +/// ``` +@inlinable @inline(__always) +public static func where_( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Where", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// output = input; While (Cond(output)) { output = Body(output) } +/// +/// - Parameter input: A list of input tensors whose types are T. +/// +/// - Attrs: +/// - T: dtype in use. +/// - cond: A function takes 'input' and returns a tensor. If the tensor is +/// a scalar of non-boolean, the scalar is converted to a boolean +/// according to the following rule: if the scalar is a numerical +/// value, non-zero means True and zero means False; if the scalar is +/// a string, non-empty means True and empty means False. If the +/// tensor is not a scalar, non-emptiness means True and False +/// otherwise. +/// - body: A function that takes a list of tensors and returns another +/// list of tensors. Both lists have the same types as specified +/// by T. +/// +/// - Output output: A list of output tensors whose types are T. +@inlinable @inline(__always) +public static func while_< + T: TensorArrayProtocol, + CondIn: TensorGroup, + CondOut: TensorGroup, + BodyIn: TensorGroup, + BodyOut: TensorGroup +>( + _ input: T, + cond: (CondIn) -> CondOut, + body: (BodyIn) -> BodyOut, + outputShapes: [TensorShape?], + parallelIterations: Int64 = 10 +) -> T { + let nOutputs = Int(input._typeList.count) + let op = makeOp("While", nOutputs) + op.updateAttribute("T", input._typeList) + op.updateAttribute("cond", cond) + op.updateAttribute("body", body) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("parallel_iterations", parallelIterations) + op.addInputList(input) + return op.execute(Int(input._typeList.count)) +} + +/// A Reader that outputs the entire contents of a file as a value. +/// +/// To use, enqueue filenames in a Queue. The output of ReaderRead will +/// be a filename (key) and the contents of that file (value). +/// +/// - Attrs: +/// - container: If non-empty, this reader is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this reader is named in the given bucket +/// with this shared_name. Otherwise, the node name is used instead. +/// +/// - Output reader_handle: The handle to reference the Reader. +@inlinable @inline(__always) +public static func wholeFileReaderV2( + container: String, + sharedName: String +) -> ResourceHandle { + let nOutputs = Int(1) + let op = makeOp("WholeFileReaderV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) +} + +/// A dataset that creates window datasets from the input dataset. +/// +/// - Parameters: +/// - size: A scalar representing the number of elements to accumulate in a window. +/// - shift: A scalar representing the steps moving the sliding window forward in one +/// iteration. It must be positive. +/// - stride: A scalar representing the stride of the input elements of the sliding window. +/// It must be positive. +/// - drop_remainder: A scalar representing whether a window should be dropped in case its size is +/// smaller than desired. +@inlinable @inline(__always) +public static func windowDataset( + inputDataset: VariantHandle, + size: Tensor, + shift: Tensor, + stride: Tensor, + dropRemainder: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("WindowDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(size) + op.addInput(shift) + op.addInput(stride) + op.addInput(dropRemainder) + return op.execute(Int(1)) +} + +/// Worker heartbeat op. +/// +/// Heartbeats may be sent periodically to indicate the coordinator is still active, +/// to retrieve the current worker status and to expedite shutdown when necessary. +/// +/// - Parameter request: A string tensor containing a serialized WorkerHeartbeatRequest +/// +/// - Output response: A string tensor containing a serialized WorkerHeartbeatResponse +@inlinable @inline(__always) +public static func workerHeartbeat( + request: StringTensor +) -> StringTensor { + let nOutputs = Int(1) + let op = makeOp("WorkerHeartbeat", nOutputs) + op.addInput(request) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func wrapDatasetVariant( + inputHandle: VariantHandle +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("WrapDatasetVariant", nOutputs) + op.addInput(inputHandle) + return op.execute(Int(1)) +} + +@inlinable @inline(__always) +public static func writeAudioSummary( + writer: ResourceHandle, + step: Tensor, + tag: StringTensor, + _ tensor: Tensor, + sampleRate: Tensor, + maxOutputs: Int64 = 3 +) { + let nOutputs = 0 + let op = makeOp("WriteAudioSummary", nOutputs) + op.updateAttribute("max_outputs", maxOutputs) + op.addInput(writer) + op.addInput(step) + op.addInput(tag) + op.addInput(tensor) + op.addInput(sampleRate) + op.execute() +} + +/// Writes contents to the file at input filename. Creates file and recursively +/// +/// creates directory if not existing. +/// +/// - Parameters: +/// - filename: scalar. The name of the file to which we write the contents. +/// - contents: scalar. The content to be written to the output file. +@inlinable @inline(__always) +public static func writeFile( + filename: StringTensor, + contents: StringTensor +) { + let nOutputs = 0 + let op = makeOp("WriteFile", nOutputs) + op.addInput(filename) + op.addInput(contents) + op.execute() +} + +@inlinable @inline(__always) +public static func writeGraphSummary( + writer: ResourceHandle, + step: Tensor, + _ tensor: StringTensor +) { + let nOutputs = 0 + let op = makeOp("WriteGraphSummary", nOutputs) + op.addInput(writer) + op.addInput(step) + op.addInput(tensor) + op.execute() +} + +@inlinable @inline(__always) +public static func writeHistogramSummary( + writer: ResourceHandle, + step: Tensor, + tag: StringTensor, + _ values: Tensor +) { + let nOutputs = 0 + let op = makeOp("WriteHistogramSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(writer) + op.addInput(step) + op.addInput(tag) + op.addInput(values) + op.execute() +} + +@inlinable @inline(__always) +public static func writeImageSummary( + writer: ResourceHandle, + step: Tensor, + tag: StringTensor, + _ tensor: Tensor, + badColor: Tensor, + maxImages: Int64 = 3 +) { + let nOutputs = 0 + let op = makeOp("WriteImageSummary", nOutputs) + op.updateAttribute("max_images", maxImages) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(writer) + op.addInput(step) + op.addInput(tag) + op.addInput(tensor) + op.addInput(badColor) + op.execute() +} + +@inlinable @inline(__always) +public static func writeRawProtoSummary( + writer: ResourceHandle, + step: Tensor, + _ tensor: StringTensor +) { + let nOutputs = 0 + let op = makeOp("WriteRawProtoSummary", nOutputs) + op.addInput(writer) + op.addInput(step) + op.addInput(tensor) + op.execute() +} + +@inlinable @inline(__always) +public static func writeScalarSummary( + writer: ResourceHandle, + step: Tensor, + tag: StringTensor, + value: Tensor +) { + let nOutputs = 0 + let op = makeOp("WriteScalarSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(writer) + op.addInput(step) + op.addInput(tag) + op.addInput(value) + op.execute() +} + +@inlinable @inline(__always) +public static func writeSummary( + writer: ResourceHandle, + step: Tensor, + _ tensor: Tensor, + tag: StringTensor, + summaryMetadata: StringTensor +) { + let nOutputs = 0 + let op = makeOp("WriteSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(writer) + op.addInput(step) + op.addInput(tensor) + op.addInput(tag) + op.addInput(summaryMetadata) + op.execute() +} + +/// Returns 0 if x == 0, and x / y otherwise, elementwise. +@inlinable @inline(__always) +public static func xdivy( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Xdivy", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Helper operator for performing XLA-style broadcasts +/// +/// Broadcasts `lhs` and `rhs` to the same rank, by adding size 1 dimensions to +/// whichever of `lhs` and `rhs` has the lower rank, using XLA's broadcasting rules +/// for binary operators. +/// +/// - Parameters: +/// - lhs: the LHS input tensor +/// - rhs: the RHS input tensor +/// - broadcast_dims: an XLA-style broadcast dimension specification +/// +/// - Outputs: +/// - lhs_output: the broadcasted LHS tensor +/// - rhs_output: the broadcasted RHS tensor +@inlinable @inline(__always) +public static func xlaBroadcastHelper< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + lhs: Tensor, + rhs: Tensor, + broadcastDims: Tensor +) -> (lhsOutput: Tensor, rhsOutput: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("XlaBroadcastHelper", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(lhs) + op.addInput(rhs) + op.addInput(broadcastDims) + return op.execute(Int(1), Int(1)) +} + +/// Operator that connects the output of an XLA computation to other consumer graph nodes. +@inlinable @inline(__always) +public static func xlaClusterOutput( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("XlaClusterOutput", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Wraps the XLA ConvGeneralDilated operator, documented at +/// +/// https://www.tensorflow.org/performance/xla/operation_semantics#conv_convolution +/// . +/// +/// - Parameters: +/// - lhs: the input tensor +/// - rhs: the kernel tensor +/// - window_strides: the inter-window strides +/// - padding: the padding to apply at the start and end of each input dimensions +/// - lhs_dilation: dilation to apply between input elements +/// - rhs_dilation: dilation to apply between kernel elements +/// - feature_group_count: number of feature groups for grouped convolution. +/// +/// - Attrs: +/// - dimension_numbers: a serialized xla::ConvolutionDimensionNumbers proto. +/// - precision_config: a serialized xla::PrecisionConfig proto. +@inlinable @inline(__always) +public static func xlaConv< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + lhs: Tensor, + rhs: Tensor, + windowStrides: Tensor, + padding: Tensor, + lhsDilation: Tensor, + rhsDilation: Tensor, + featureGroupCount: Tensor, + dimensionNumbers: String, + precisionConfig: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("XlaConv", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("dimension_numbers", dimensionNumbers) + op.updateAttribute("precision_config", precisionConfig) + op.addInput(lhs) + op.addInput(rhs) + op.addInput(windowStrides) + op.addInput(padding) + op.addInput(lhsDilation) + op.addInput(rhsDilation) + op.addInput(featureGroupCount) + return op.execute(Int(1)) +} + +/// Wraps the XLA ConvGeneralDilated operator, documented at +/// +/// https://www.tensorflow.org/performance/xla/operation_semantics#dotgeneral +/// . +/// +/// - Parameters: +/// - lhs: the LHS tensor +/// - rhs: the RHS tensor +/// +/// - Attrs: +/// - dimension_numbers: a serialized xla::DotDimensionNumbers proto. +/// - precision_config: a serialized xla::PrecisionConfig proto. +@inlinable @inline(__always) +public static func xlaDot( + lhs: Tensor, + rhs: Tensor, + dimensionNumbers: String, + precisionConfig: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("XlaDot", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("dimension_numbers", dimensionNumbers) + op.updateAttribute("precision_config", precisionConfig) + op.addInput(lhs) + op.addInput(rhs) + return op.execute(Int(1)) +} + +/// Wraps the XLA DynamicSlice operator, documented at +/// +/// https://www.tensorflow.org/performance/xla/operation_semantics#dynamicslice +/// . +/// +/// DynamicSlice extracts a sub-array from the input array at dynamic +/// start_indices. The size of the slice in each dimension is passed in +/// size_indices, which specify the end point of exclusive slice intervals in each +/// dimension -- [start, start + size). The shape of start_indices must have rank 1, +/// with dimension size equal to the rank of operand. +/// +/// - Parameters: +/// - input: A `Tensor` of type T. +/// - start_indices: List of N integers containing the slice size for each +/// dimension. Each value must be strictly greater than zero, and start + size +/// must be less than or equal to the size of the dimension to avoid +/// implementation defined behavior. +@inlinable @inline(__always) +public static func xlaDynamicSlice< + T: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + startIndices: Tensor, + sizeIndices: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("XlaDynamicSlice", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(input) + op.addInput(startIndices) + op.addInput(sizeIndices) + return op.execute(Int(1)) +} + +/// Wraps the XLA DynamicUpdateSlice operator, documented at +/// +/// https://www.tensorflow.org/performance/xla/operation_semantics#dynamicupdateslice +/// . +/// +/// XlaDynamicUpdateSlice generates a result which is the value of the `input` +/// operand, with a slice update overwritten at `indices`. The shape of `update` +/// determines the shape of the sub-array of the result which is updated. The shape +/// of indices must be rank == 1, with dimension size equal to the rank of `input`. +/// +/// Handling of out-of-bounds slice indices is implementation-defined. +/// +/// - Parameters: +/// - input: A `Tensor` of type T. +/// - update: A `Tensor` of type T. Same rank as `input`. +/// - indices: A vector of indices into `input`. Must have length equal to the rank of +/// `input`. +/// +/// - Output output: A `Tensor` of type T. +@inlinable @inline(__always) +public static func xlaDynamicUpdateSlice< + T: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + update: Tensor, + indices: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("XlaDynamicUpdateSlice", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(input) + op.addInput(update) + op.addInput(indices) + return op.execute(Int(1)) +} + +/// An op which supports basic einsum op with 2 inputs and 1 output. +/// +/// This op has better TPU performnce since it doesn't have explicitly reshape and +/// transpose operations as tf.einsum does. +@inlinable @inline(__always) +public static func xlaEinsum( + _ a: Tensor, + _ b: Tensor, + equation: String +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("XlaEinsum", nOutputs) + op.updateAttribute("equation", equation) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(b) + return op.execute(Int(1)) +} + +/// output = cond ? then_branch(inputs) : else_branch(inputs). +/// +/// - Parameters: +/// - cond: A boolean scalar. +/// - inputs: A list of input tensors. +/// +/// - Attrs: +/// - then_branch: A function takes 'inputs' and returns a list of tensors, +/// whose types are the same as what else_branch returns. +/// - else_branch: A function takes 'inputs' and returns a list of tensors. +/// whose types are the same as what then_branch returns. +/// +/// - Output output: A list of tensors returned by either then_branch(inputs) or +/// else_branch(inputs). The input shapes of the then_branch and +/// else_branch must match. +@inlinable @inline(__always) +public static func xlaIf< + Tcond: TensorFlowScalar, + ThenbranchIn: TensorGroup, + ThenbranchOut: TensorGroup, + ElsebranchIn: TensorGroup, + ElsebranchOut: TensorGroup, + Tin: TensorArrayProtocol, + Tout: TensorGroup +>( + cond: Tensor, + inputs: Tin, + thenBranch: (ThenbranchIn) -> ThenbranchOut, + elseBranch: (ElsebranchIn) -> ElsebranchOut +) -> Tout { + let nOutputs = Int(Tout._typeList.count) + let op = makeOp("XlaIf", nOutputs) + op.updateAttribute("Tcond", Tcond.tensorFlowDataType) + op.updateAttribute("then_branch", thenBranch) + op.updateAttribute("else_branch", elseBranch) + op.updateAttribute("Tin", inputs._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.addInput(cond) + op.addInputList(inputs) + return op.execute(Int(Tout._typeList.count)) +} + +/// Wraps the XLA Sort operator, documented at +/// +/// https://www.tensorflow.org/performance/xla/operation_semantics#sort +/// . +/// +/// Sorts a tensor. Currently only sorts in ascending order are supported. +/// +/// - Parameters: +/// - keys: A `Tensor` of type K. +/// - values: A `Tensor` of type V. +/// +/// - Outputs: +/// - sorted_keys: A `Tensor` of type K. +/// - sorted_values: A `Tensor` of type V. +@inlinable @inline(__always) +public static func xlaKeyValueSort< + K: Numeric & TensorFlowScalar, + V: TensorFlowScalar +>( + keys: Tensor, + _ values: Tensor +) -> (sortedKeys: Tensor, sortedValues: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("XlaKeyValueSort", nOutputs) + op.updateAttribute("K", K.tensorFlowDataType) + op.updateAttribute("V", V.tensorFlowDataType) + op.addInput(keys) + op.addInput(values) + return op.execute(Int(1), Int(1)) +} + +/// XLA Launch Op. For use by the XLA JIT only. +@inlinable @inline(__always) +public static func xlaLaunch< + Tconstants: TensorArrayProtocol, + Targs: TensorArrayProtocol, + Tresults: TensorGroup, + FunctionIn: TensorGroup, + FunctionOut: TensorGroup +>( + constants: Tconstants, + args: Targs, + resources: [ResourceHandle], + function: (FunctionIn) -> FunctionOut +) -> Tresults { + let nOutputs = Int(Tresults._typeList.count) + let op = makeOp("XlaLaunch", nOutputs) + op.updateAttribute("Tconstants", constants._typeList) + op.updateAttribute("Targs", args._typeList) + op.updateAttribute("Nresources", resources.count) + op.updateAttribute("Tresults", Tresults._typeList) + op.updateAttribute("function", function) + op.addInputList(constants) + op.addInputList(args) + op.addInputList(resources) + return op.execute(Int(Tresults._typeList.count)) +} + +/// Wraps the XLA Pad operator, documented at +/// +/// https://www.tensorflow.org/performance/xla/operation_semantics#pad +/// . +/// +/// - Parameters: +/// - input: A `Tensor` of type T. +/// - padding_value: A scalar `Tensor` of type T. +/// - padding_low: the padding to apply at the start of each input dimensions +/// - padding_high: the padding to apply at the end of each input dimension. +/// - padding_interior: the padding to apply between each input element. +/// +/// - Output output: A `Tensor` of type T. +@inlinable @inline(__always) +public static func xlaPad< + T: TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar +>( + _ input: Tensor, + paddingValue: Tensor, + paddingLow: Tensor, + paddingHigh: Tensor, + paddingInterior: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("XlaPad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(input) + op.addInput(paddingValue) + op.addInput(paddingLow) + op.addInput(paddingHigh) + op.addInput(paddingInterior) + return op.execute(Int(1)) +} + +/// Receives the named tensor from another XLA computation. Wraps the XLA Recv +/// +/// operator documented at +/// https://www.tensorflow.org/performance/xla/operation_semantics#recv . +/// +/// - Attrs: +/// - dtype: The type of the tensor. +/// - tensor_name: A string key that identifies the channel. +/// - shape: The shape of the tensor. +/// +/// - Output tensor: The tensor to receive. +@inlinable @inline(__always) +public static func xlaRecv( + tensorName: String, + shape: TensorShape? +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("XlaRecv", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("tensor_name", tensorName) + op.updateAttribute("shape", shape) + return op.execute(Int(1)) +} + +/// Wraps the XLA Reduce operator, documented at +/// +/// https://www.tensorflow.org/performance/xla/operation_semantics#reduce . +/// +/// - Parameters: +/// - input: the input tensor +/// - init_value: a scalar representing the initial value for the reduction +/// +/// - Attrs: +/// - dimensions_to_reduce: dimension numbers over which to reduce +/// - reducer: a reducer function to apply +@inlinable @inline(__always) +public static func xlaReduce< + T: Numeric & TensorFlowScalar, + ReducerIn: TensorGroup, + ReducerOut: TensorGroup +>( + _ input: Tensor, + initValue: Tensor, + dimensionsToReduce: [Int32], + reducer: (ReducerIn) -> ReducerOut +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("XlaReduce", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("dimensions_to_reduce", dimensionsToReduce) + op.updateAttribute("reducer", reducer) + op.addInput(input) + op.addInput(initValue) + return op.execute(Int(1)) +} + +/// Wraps the XLA ReduceWindow operator, documented at +/// +/// https://www.tensorflow.org/performance/xla/operation_semantics#reducewindow . +/// +/// - Parameters: +/// - input: the input tensor +/// - init_value: a scalar representing the initial value for the reduction +/// - window_dimensions: the shape of the window +/// - window_strides: the inter-window strides +/// - padding: the padding to apply at the start and end of each input dimensions +/// +/// - Attr computation: a reducer function to apply +@inlinable @inline(__always) +public static func xlaReduceWindow< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar, + ComputationIn: TensorGroup, + ComputationOut: TensorGroup +>( + _ input: Tensor, + initValue: Tensor, + windowDimensions: Tensor, + windowStrides: Tensor, + baseDilations: Tensor, + windowDilations: Tensor, + padding: Tensor, + computation: (ComputationIn) -> ComputationOut +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("XlaReduceWindow", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("computation", computation) + op.addInput(input) + op.addInput(initValue) + op.addInput(windowDimensions) + op.addInput(windowStrides) + op.addInput(baseDilations) + op.addInput(windowDilations) + op.addInput(padding) + return op.execute(Int(1)) +} + +/// Replica ID. +@inlinable @inline(__always) +public static func xlaReplicaId( +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("XlaReplicaId", nOutputs) + + return op.execute(Int(1)) +} + +/// Wraps the XLA SelectAndScatter operator, documented at +/// +/// https://www.tensorflow.org/performance/xla/operation_semantics#selectandscatter +/// . +/// +/// - Parameters: +/// - operand: the input tensor +/// - window_dimensions: the shape of the window +/// - window_strides: the inter-window strides +/// - padding: the padding to apply at the start and end of each input dimensions +/// - source: a tensor of values to scatter +/// - init_value: a scalar representing the initial value for the output tensor +/// +/// - Attrs: +/// - select: a selection function to apply +/// - scatter: a scatter function to apply +@inlinable @inline(__always) +public static func xlaSelectAndScatter< + T: Numeric & TensorFlowScalar, + Tindices: BinaryInteger & TensorFlowScalar, + SelectIn: TensorGroup, + SelectOut: TensorGroup, + ScatterIn: TensorGroup, + ScatterOut: TensorGroup +>( + operand: Tensor, + windowDimensions: Tensor, + windowStrides: Tensor, + padding: Tensor, + source: Tensor, + initValue: Tensor, + select: (SelectIn) -> SelectOut, + scatter: (ScatterIn) -> ScatterOut +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("XlaSelectAndScatter", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("select", select) + op.updateAttribute("scatter", scatter) + op.addInput(operand) + op.addInput(windowDimensions) + op.addInput(windowStrides) + op.addInput(padding) + op.addInput(source) + op.addInput(initValue) + return op.execute(Int(1)) +} + +/// Computes the eigen decomposition of a batch of self-adjoint matrices +/// +/// (Note: Only real inputs are supported). +/// +/// Computes the eigenvalues and eigenvectors of the innermost N-by-N matrices in +/// tensor such that tensor[...,:,:] * v[..., :,i] = e[..., i] * v[...,:,i], for +/// i=0...N-1. +/// +/// - Parameter a: the input tensor. +/// +/// - Attrs: +/// - lower: a boolean specifies whether the calculation is done with the lower +/// triangular part or the upper triangular part. +/// - max_iter: maximum number of sweep update, i.e., the whole lower triangular +/// part or upper triangular part based on parameter lower. Heuristically, it has +/// been argued that approximatly logN sweeps are needed in practice (Ref: Golub & +/// van Loan "Matrix Computation"). +/// - epsilon: the tolerance ratio. +/// +/// - Outputs: +/// - w: The eigenvalues in ascending order, each repeated according to its +/// multiplicity. +/// - v: The column v[..., :, i] is the normalized eigenvector corresponding to the +/// eigenvalue w[..., i]. +@inlinable @inline(__always) +public static func xlaSelfAdjointEig( + _ a: Tensor, + lower: Bool, + maxIter: Int64, + epsilon: Double +) -> (w: Tensor, v: Tensor) { + let nOutputs = Int(1) + Int(1) + let op = makeOp("XlaSelfAdjointEig", nOutputs) + op.updateAttribute("lower", lower) + op.updateAttribute("max_iter", maxIter) + op.updateAttribute("epsilon", epsilon) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + return op.execute(Int(1), Int(1)) +} + +/// Sends the named tensor to another XLA computation. Wraps the XLA Send operator +/// +/// documented at +/// https://www.tensorflow.org/performance/xla/operation_semantics#send . +/// +/// - Parameter tensor: The tensor to send. +/// +/// - Attr tensor_name: A string key that identifies the channel. +@inlinable @inline(__always) +public static func xlaSend( + _ tensor: Tensor, + tensorName: String +) { + let nOutputs = 0 + let op = makeOp("XlaSend", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("tensor_name", tensorName) + op.addInput(tensor) + op.execute() +} + +/// Wraps the XLA Sort operator, documented at +/// +/// https://www.tensorflow.org/performance/xla/operation_semantics#sort +/// . +/// +/// Sorts a tensor. Currently only sorts in ascending order are supported. +/// +/// - Parameter input: A `Tensor` of type T. +/// +/// - Output output: A `Tensor` of type T. +@inlinable @inline(__always) +public static func xlaSort( + _ input: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("XlaSort", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) +} + +/// Computes the eigen decomposition of a batch of self-adjoint matrices +/// +/// (Note: Only real inputs are supported). +/// +/// Computes the eigenvalues and eigenvectors of the innermost M-by-N matrices in +/// tensor such that tensor[...,:,:] = u[..., :, :] * Diag(s[..., :]) * Transpose(v[...,:,:]). +/// +/// - Parameter a: the input tensor. +/// +/// - Attrs: +/// - max_iter: maximum number of sweep update, i.e., the whole lower triangular +/// part or upper triangular part based on parameter lower. Heuristically, it has +/// been argued that approximatly log(min (M, N)) sweeps are needed in practice +/// (Ref: Golub & van Loan "Matrix Computation"). +/// - epsilon: the tolerance ratio. +/// - precision_config: a serialized xla::PrecisionConfig proto. +/// +/// - Outputs: +/// - s: Singular values. The values are sorted in reverse order of magnitude, so +/// s[..., 0] is the largest value, s[..., 1] is the second largest, etc. +/// - u: Left singular vectors. +/// - v: Right singular vectors. +@inlinable @inline(__always) +public static func xlaSvd( + _ a: Tensor, + maxIter: Int64, + epsilon: Double, + precisionConfig: String +) -> (s: Tensor, u: Tensor, v: Tensor) { + let nOutputs = Int(1) + Int(1) + Int(1) + let op = makeOp("XlaSvd", nOutputs) + op.updateAttribute("max_iter", maxIter) + op.updateAttribute("epsilon", epsilon) + op.updateAttribute("precision_config", precisionConfig) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + return op.execute(Int(1), Int(1), Int(1)) +} + +/// output = input; While (Cond(output)) { output = Body(output) } +/// +/// - Parameter input: A list of input tensors whose types are T. +/// +/// - Attrs: +/// - cond: A function takes 'input' and returns a tensor. If the tensor is +/// a scalar of non-boolean, the scalar is converted to a boolean +/// according to the following rule: if the scalar is a numerical +/// value, non-zero means True and zero means False; if the scalar is +/// a string, non-empty means True and empty means False. If the +/// tensor is not a scalar, non-emptiness means True and False +/// otherwise. +/// - body: A function that takes a list of tensors and returns another +/// list of tensors. Both lists have the same types as specified by T. +/// +/// - Output output: A list of output tensors whose types are T. +@inlinable @inline(__always) +public static func xlaWhile< + T: TensorArrayProtocol, + CondIn: TensorGroup, + CondOut: TensorGroup, + BodyIn: TensorGroup, + BodyOut: TensorGroup +>( + _ input: T, + cond: (CondIn) -> CondOut, + body: (BodyIn) -> BodyOut +) -> T { + let nOutputs = Int(input._typeList.count) + let op = makeOp("XlaWhile", nOutputs) + op.updateAttribute("T", input._typeList) + op.updateAttribute("cond", cond) + op.updateAttribute("body", body) + op.addInputList(input) + return op.execute(Int(input._typeList.count)) +} + +/// Returns 0 if x == 0, and x * log(y) otherwise, elementwise. +@inlinable @inline(__always) +public static func xlogy( + _ x: Tensor, + _ y: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Xlogy", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) +} + +/// Returns a tensor of zeros with the same shape and type as x. +/// +/// - Parameter x: a tensor of type T. +/// +/// - Output y: a tensor of the same shape and type as x but filled with zeros. +@inlinable @inline(__always) +public static func zerosLike( + _ x: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("ZerosLike", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) +} + +/// Compute the Hurwitz zeta function \\(\zeta(x, q)\\). +/// +/// The Hurwitz zeta function is defined as: +/// +/// +/// \\(\zeta(x, q) = \sum_{n=0}^{\infty} (q + n)^{-x}\\) +@inlinable @inline(__always) +public static func zeta( + _ x: Tensor, + q: Tensor +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Zeta", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(q) + return op.execute(Int(1)) +} + +/// Creates a dataset that zips together `input_datasets`. +@inlinable @inline(__always) +public static func zipDataset( + inputDatasets: [VariantHandle], + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] +) -> VariantHandle { + let nOutputs = Int(1) + let op = makeOp("ZipDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("N", inputDatasets.count) + op.addInputList(inputDatasets) + return op.execute(Int(1)) +} + +} diff --git a/Sources/DeepLearning/Bindings/TFTensorOperation.swift b/Sources/DeepLearning/Bindings/TFTensorOperation.swift new file mode 100644 index 000000000..419eecb73 --- /dev/null +++ b/Sources/DeepLearning/Bindings/TFTensorOperation.swift @@ -0,0 +1,137 @@ + +// A protocol for a tensor operation. +public protocol TensorOperation { + // We use functions instead of fields to give freedom in the + // representation for the conforming types. + init(_ name: String, _ outputCount: Int) + + func updateAttribute(_ name: String, _ value: Bool) + func updateAttribute(_ name: String, _ value: Int) + func updateAttribute(_ name: String, _ value: Int32) + func updateAttribute(_ name: String, _ value: Int64) + func updateAttribute(_ name: String, _ value: Float) + func updateAttribute(_ name: String, _ value: Double) + func updateAttribute(_ name: String, _ value: String) + func updateAttribute(_ name: String, _ value: [Bool]) + func updateAttribute(_ name: String, _ value: [Int]) + func updateAttribute(_ name: String, _ value: [Int32]) + func updateAttribute(_ name: String, _ value: [Int64]) + func updateAttribute(_ name: String, _ value: [Float]) + func updateAttribute(_ name: String, _ value: [Double]) + func updateAttribute(_ name: String, _ value: [String]) + + // TODO(https://bugs.swift.org/browse/TF-522): When we are able to + // use opaque return types everywhere, we should add an + // associatedtype requirement and add the following methods so that + // we can work with non-tensorflow backends if neeeded. + // + // associatedtype TensorValueHandle + // + // func addInput(_ input : TensorValueHandle) + // func evaluate() -> ([TensorValueHandle]) +} + +// A protocol for a tensor operation in TensorFlow library. +public protocol TFTensorOperation : TensorOperation { + func addInput(_ input: Tensor) + func addInput(_ input: StringTensor) + func addInput(_ input: VariantHandle) + func addInput(_ input: ResourceHandle) + func addInputList(_ input: T) + + func updateAttribute(_ name: String, _ value: TensorDataType) + func updateAttribute(_ name: String, _ value: TensorShape) + func updateAttribute(_ name: String, _ value: TensorShape?) + func updateAttribute(_ name: String, _ value: [TensorDataType]) + func updateAttribute(_ name: String, _ value: [TensorShape]) + func updateAttribute(_ name: String, _ value: [TensorShape?]) + func updateAttribute( + _ name: String, _ value: (In) -> Out) + + func execute() + + func execute( + _ count0: Int + ) -> (T0) + + func execute( + _ count0: Int, + _ count1: Int + ) -> (T0, T1) + + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int + ) -> (T0, T1, T2) + + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int + ) -> (T0, T1, T2, T3) + + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int + ) -> (T0, T1, T2, T3, T4) + + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int + ) -> (T0, T1, T2, T3, T4, T5) + + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int + ) -> (T0, T1, T2, T3, T4, T5, T6) + + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int, + _ count7: Int + ) -> (T0, T1, T2, T3, T4, T5, T6, T7) + + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int, + _ count7: Int, + _ count8: Int + ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8) + + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int, + _ count7: Int, + _ count8: Int, + _ count9: Int + ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9) +} diff --git a/Sources/DeepLearning/Bindings/generate_wrappers.py b/Sources/DeepLearning/Bindings/generate_wrappers.py new file mode 100644 index 000000000..1a57dc52f --- /dev/null +++ b/Sources/DeepLearning/Bindings/generate_wrappers.py @@ -0,0 +1,717 @@ +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Generates some swift wrapper from some ops description protobuf.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import six +import tensorflow as tf + +from tensorflow.core.framework import types_pb2 +from tensorflow.python.framework import c_api_util + +flags = tf.flags +FLAGS = flags.FLAGS + +flags.DEFINE_string( + 'api_def_path', + None, + 'path to the api_def directory, e.g. tensorflow/core/api_def/base_api') + +flags.DEFINE_string( + 'output_path', + None, + 'path for the generated swift file') + +_WARNING = """// !!! THIS CODE IS AUTOMATICALLY GENERATED, DO NOT EDIT BY HAND !!! +// +""" + +_HEADER = """// Copyright 2018-19 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +""" + +_OUTPUT_FILE = 'RawOpsGenerated.swift' +_RENAMED_KEYWORDS = { + '': 'empty', + 'in': 'in_', + 'var': 'var_', + 'where': 'where_', + 'if': 'if_', + 'for': 'for_', + 'while': 'while_', + 'switch': 'switch_', + 'protocol': 'protocol_', + 'init': 'init_'} + +_TYPE_PROTOCOLS = [ + (set(), 'TensorFlowScalar'), + ({types_pb2.DT_UINT8, + types_pb2.DT_UINT16, + types_pb2.DT_UINT32, + types_pb2.DT_UINT64}, 'UnsignedInteger & TensorFlowScalar'), + ({types_pb2.DT_UINT8, + types_pb2.DT_UINT16, + types_pb2.DT_UINT32, + types_pb2.DT_UINT64, + types_pb2.DT_INT8, + types_pb2.DT_INT16, + types_pb2.DT_INT32, + types_pb2.DT_INT64}, 'BinaryInteger & TensorFlowScalar'), + ({types_pb2.DT_FLOAT, + types_pb2.DT_DOUBLE, + types_pb2.DT_HALF, + types_pb2.DT_BFLOAT16}, 'FloatingPoint & TensorFlowScalar'), + ({types_pb2.DT_UINT8, + types_pb2.DT_UINT16, + types_pb2.DT_UINT32, + types_pb2.DT_UINT64, + types_pb2.DT_INT8, + types_pb2.DT_INT16, + types_pb2.DT_INT32, + types_pb2.DT_INT64, + types_pb2.DT_FLOAT, + types_pb2.DT_DOUBLE, + types_pb2.DT_HALF, + types_pb2.DT_BFLOAT16}, 'Numeric & TensorFlowScalar')] + +_SWIFTIFIED_TYPES = { + types_pb2.DT_FLOAT: 'Float', + types_pb2.DT_DOUBLE: 'Double', + types_pb2.DT_INT32: 'Int32', + types_pb2.DT_UINT8: 'UInt8', + types_pb2.DT_INT16: 'Int16', + types_pb2.DT_INT8: 'Int8', + types_pb2.DT_INT64: 'Int64', + types_pb2.DT_BOOL: 'Bool', + types_pb2.DT_UINT16: 'UInt16', + types_pb2.DT_UINT32: 'UInt32', + types_pb2.DT_UINT64: 'UInt64'} + +_SWIFTIFIED_ATTR_TYPES = { + 'int': 'Int64', + 'float': 'Double', + 'bool': 'Bool', + 'string': 'String', + 'type': 'TensorDataType', + 'shape': 'TensorShape?', + 'list(int)': '[Int32]', + 'list(float)': '[Double]', + 'list(bool)': '[Bool]', + 'list(string)': '[String]', + 'list(type)': '[TensorDataType]', + 'list(shape)': '[TensorShape?]'} + +_OMITTED_PARAMETER_NAMES = { + 'x', 'y', 'a', 'b', 'input', 'tensor', 'values'} + +_START_COMMENT = '///' + + +class UnableToGenerateCodeError(Exception): + def __init__(self, details): + self.details = details + super(UnableToGenerateCodeError, self).__init__() + + def __str__(self): + return self.details + + +class Op(object): + def __init__(self, op_def, api_def, enum_store, string_valued=False): + self.op_def = op_def + self.api_def = api_def + self.enum_store = enum_store + self.string_valued = string_valued + self.inferred_counts = dict() + + # Collect all the input and output arguments. + self.input_args = [ + Argument(arg_def, op=self) + for arg_def in self.op_def.input_arg] + self.output_args = [ + Argument(arg_def, op=self) + for arg_def in self.op_def.output_arg] + + # Collect all attributes. + self.attrs = [ + Attribute(attr, op=self) + for attr in op_def.attr] + self.type_attrs = [ + attr for attr in self.attrs + if attr.is_type_attr] + + def swift_function(self): + return ''' +{documentation}@inlinable @inline(__always) +public static func {name}{generics}({input_args} +){return_type} {{ + {body} +}}'''.format( + documentation=self._swift_documentation(), + name=self._swift_name(), + generics=self._swift_generics(), + input_args=self._swift_input_args(), + return_type=self._swift_return_type(), + body=self._swift_body()) + + def _swift_documentation(self): + def comment_block(text, indent_level): + """Returns a commented block of text with some specified indentation.""" + def indent(line_index): + if indent_level == 0: + return '' + if line_index: + return ' ' * indent_level + return ' ' * (indent_level - 1) + '- ' + + return ''.join([ + (_START_COMMENT + ' ' + indent(line_index) + line + '\n' + if line else _START_COMMENT + '\n') + for line_index, line in enumerate(text.split('\n')) + ]) + + def append_list(doc, args, arg_type): + """Returns the documentation for lists of inputs/outputs/attributes.""" + args = [arg for arg in args if arg.description] + if len(args) == 1: + block = '%s %s: %s' % (arg_type, args[0].name, args[0].description) + doc += _START_COMMENT + '\n' + doc += comment_block(block, indent_level=1) + elif len(args) > 1: + doc += '%s\n%s - %ss:\n' % (_START_COMMENT, _START_COMMENT, arg_type) + for arg in args: + block = '%s: %s' % (arg.name, arg.description) + doc += comment_block(block, indent_level=2) + return doc + + doc = '' + if self.api_def.summary: + doc = comment_block(self.api_def.summary, indent_level=0) + if self.api_def.description: + doc += _START_COMMENT + '\n' + doc += comment_block(self.api_def.description, indent_level=0) + doc = append_list(doc, self.api_def.in_arg, 'Parameter') + doc = append_list(doc, self.api_def.attr, 'Attr') + doc = append_list(doc, self.api_def.out_arg, 'Output') + if doc and not doc.endswith('\n'): + doc = doc + '\n' + return doc + + def _swift_name(self): + return swift_compatible_identifier( + self.op_def.name[0].lower() + self.op_def.name[1:]) + + def _swift_generics(self): + constraints = [ + attr.generic_constraints(self.string_valued) + for attr in self.attrs] + constraints = [c for c in constraints if c is not None] + if len(constraints) == 1: + return '<' + ', '.join(constraints) + '>' + if len(constraints) > 1: + return '<\n ' + ',\n '.join(constraints) + '\n>' + return '' + + def _swift_input_args(self): + args = '' + for arg in self.input_args: + args += '\n %s: %s,' % (arg.swift_arg_name, str(arg.swift_type(self.string_valued))) + for attr in self.attrs: + if not attr.is_inferred_type_attr and not attr.is_inferred_number_attr: + args += '\n %s: %s%s,' % (attr.swift_arg_name, attr.swift_type, attr.swift_default) + if args != '': + args = args[:-1] + return args + + def _swift_return_type(self): + return_type = '' + if len(self.output_args) == 1: + return_type = ' -> ' + str(self.output_args[0].swift_type(self.string_valued)) + elif len(self.output_args) > 1: + named_types = [ + arg.swift_name + ': ' + str(arg.swift_type(self.string_valued)) + for arg in self.output_args] + return_type = ' -> (' + ', '.join(named_types) + ')' + return return_type + + def _swift_body(self): + setters = [] + for attr in self.attrs: + setters.append(attr.swift_setter(self.string_valued)) + for arg in self.input_args: + setters.append(arg.swift_setter()) + counts = ['Int({})'.format(arg.swift_count) for arg in self.output_args] + if len(self.output_args) == 0: + body = 'let nOutputs = 0' + else: + body = 'let nOutputs = {}'.format(' + '.join(counts)) + body += '\n let op = makeOp("{}", nOutputs)\n '.format(self.op_def.name) + body += '\n '.join(setters) + if len(self.output_args) == 0: + return body + '\n op.execute()' + body += '\n return op.execute({})'.format(', '.join(counts)) + return body + + +class Argument(object): + def __init__(self, arg_def, op): + self.arg_def = arg_def + self.op = op + self.is_list = arg_def.number_attr is not '' \ + or arg_def.type_list_attr is not '' + + @property + def name(self): + return self.arg_def.name + + @property + def swift_name(self): + return swift_compatible_identifier( + self.name[0].lower() + self.name[1:]) + + @property + def swift_arg_name(self): + name = self.swift_name + if name in _OMITTED_PARAMETER_NAMES: + name = '_ ' + name + return name + + def swift_type(self, string_valued=False): + return self.type.swift_type( + string_valued=self.allows_string and string_valued) + + def swift_setter(self): + if self.is_list: + return 'op.addInputList({})'.format(self.swift_name) + else: + return 'op.addInput({})'.format(self.swift_name) + + @property + def swift_count(self): + number_attr = self.arg_def.number_attr + if number_attr and number_attr in self.op.inferred_counts: + return self.op.inferred_counts[number_attr] + if self.arg_def.type_list_attr: + return self.op.inferred_counts[self.arg_def.type_list_attr] + return '1' + + @property + def type(self): + number = self.arg_def.number_attr + if self.arg_def.type_attr: + type_attr = next( + attr for attr in self.op.type_attrs + if attr.name == self.arg_def.type_attr) + return Type('Tensor', base_type=type_attr.swift_name, number=number) + if self.arg_def.type_list_attr: + type_attr = next( + attr for attr in self.op.type_attrs + if attr.name == self.arg_def.type_list_attr) + # There are never any numbered type lists. + return Type(type_attr.swift_name) + if self.arg_def.type in _SWIFTIFIED_TYPES: + base_type = _SWIFTIFIED_TYPES[self.arg_def.type] + return Type('Tensor', base_type=base_type, number=number) + if self.arg_def.type == types_pb2.DT_STRING: + return Type('Tensor', base_type='String', number=number) + if self.arg_def.type == types_pb2.DT_RESOURCE: + return Type('ResourceHandle', number=number) + if self.arg_def.type == types_pb2.DT_VARIANT: + return Type('VariantHandle', number=number) + raise UnableToGenerateCodeError( + 'Unsupported type for argument "%s".' % self.name) + + @property + def allows_string(self): + if self.arg_def.type_attr: + type_attr = next( + attr for attr in self.op.type_attrs + if attr.name == self.arg_def.type_attr) + return types_pb2.DT_STRING in type_attr.attr_def.allowed_values.list.type + return False + + +class Type(object): + def __init__(self, kind, base_type=None, number=None): + self.kind = kind + self.base_type = base_type + self.number = number + + @property + def count(self): + return self.number if self.number else 1 + + def swift_type(self, string_valued=False): + if self.kind == 'Tensor': + if self.base_type == 'String' or string_valued: + name = 'StringTensor' + else: + name = 'Tensor<' + self.base_type + '>' + elif self.kind == 'TensorHandle': + name = 'TensorHandle<' + self.base_type + '>' + elif self.kind == 'ResourceHandle': + name = 'ResourceHandle' + elif self.kind == 'VariantHandle': + name = 'VariantHandle' + else: + name = self.kind + return ('[%s]' % name) if self.number else name + + +class Attribute(object): + """Represents information extracted from op `type` and `list(type)` attributes.""" + + def __init__(self, attr_def, op): + self.attr_def = attr_def + self.op = op + self.is_type_attr = attr_def.type in ['type', 'list(type)'] + + # Check whether the value of this attribute can be + # inferred automatically (this only applies to + # type-valued attributes). + input_args = list(op.op_def.input_arg) + output_args = list(op.op_def.output_arg) + input_arg_type_attrs = set( + [arg.type_attr for arg in input_args] + + [arg.type_list_attr for arg in input_args]) + output_arg_type_attrs = set( + [arg.type_attr for arg in output_args] + + [arg.type_list_attr for arg in output_args]) + arg_type_attrs = input_arg_type_attrs.union(output_arg_type_attrs) + self.is_inferred_type_attr = attr_def.name in arg_type_attrs + self.is_output_type_attr = attr_def.name in output_arg_type_attrs + self.is_func_attr = self.attr_def.type == 'func' + + # We use this for obtaining the `_typeList` property. + self.input_arg = None + self.is_inferred_number_attr = False + for arg in self.op.input_args: + if self.attr_def.name in [arg.arg_def.type_attr, + arg.arg_def.type_list_attr] or \ + self.attr_def.name == arg.arg_def.number_attr: + self.input_arg = arg + self.is_inferred_number_attr = True + break + + # The following properties are only relevant for + # non-inferred-type-valued attributes. + self._swift_type = '' + self._use_enum = False + if not self.is_inferred_type_attr and not self.is_func_attr: + if self.attr_def.type not in _SWIFTIFIED_ATTR_TYPES: + raise UnableToGenerateCodeError( + 'Unsupported type for attribute "%s".' + % self.attr_def.name) + + # Get the arg type. + self._swift_type = _SWIFTIFIED_ATTR_TYPES[self.attr_def.type] + + # Check if the arg is an enum type. + self._use_enum = False + if self.attr_def.type == 'string': + allowed_values = tuple(sorted(self.attr_def.allowed_values.list.s)) + if allowed_values: + self._swift_type = self.op.enum_store.maybe_add( + allowed_values, self.attr_def.name) + self._use_enum = True + if self.is_func_attr: + input_type = self.swift_name.capitalize() + 'In' + output_type = self.swift_name.capitalize() + 'Out' + self._swift_type = '({}) -> {}'.format(input_type, output_type) + + @property + def name(self): + return self.attr_def.name + + @property + def swift_name(self): + if self.is_inferred_type_attr: + return swift_compatible_identifier( + self.name, capitalize=True) + return swift_compatible_identifier( + self.name[0].lower() + self.name[1:]) + + @property + def swift_arg_name(self): + name = self.swift_name + if name in _OMITTED_PARAMETER_NAMES: + name = '_ ' + name + return name + + @property + def swift_type(self): + return self._swift_type + + @property + def swift_default(self): + def swift_float(f): + if f == float('inf'): return 'Double.infinity' + if f == float('-inf'): return '-Double.infinity' + return '%g' % f + + if not self.is_inferred_type_attr and self.attr_def.default_value: + default_value = self.attr_def.default_value + if default_value.HasField('b'): + default_value = str(default_value.b).lower() + elif default_value.HasField('i'): + default_value = str(default_value.i) + elif default_value.HasField('f'): + default_value = swift_float(default_value.f) + elif default_value.HasField('s') and default_value.s: + s = str(default_value.s, encoding='utf-8') + default_value = '.' + swift_compatible_identifier(s.lower()) \ + if self._use_enum else '"' + s + '"' + elif default_value.HasField('list'): + if default_value.list.i: + default_values = [str(s) for s in default_value.list.i] + default_value = '[' + ', '.join(default_values) + ']' + elif default_value.list.f: + default_values = [swift_float(s) for s in default_value.list.f] + default_value = '[' + ', '.join(default_values) + ']' + else: + default_value = None + else: + default_value = None + if default_value is not None: + default_value = default_value.replace("\t", "\\t") + return ' = ' + default_value + return '' + + def swift_setter(self, string_valued=False): + # Inferred-type-valued attributes. + if self.is_inferred_type_attr: + name = self.swift_name + if self.input_arg is not None: + name = self.input_arg.swift_name + if self.attr_def.type == 'list(type)' or self.is_inferred_number_attr: + self.op.inferred_counts[self.name] = name + '._typeList.count' + if self.attr_def.type == 'list(type)': + return 'op.updateAttribute("{}", {}._typeList)'.format(self.name, name) + if string_valued and self.allows_string: + return 'op.updateAttribute("{}", TensorDataType(TF_STRING))'.format(self.name) + return 'op.updateAttribute("{}", {}.tensorFlowDataType)'.format(self.name, self.swift_name) + + if self.is_inferred_number_attr: + # The following is used for inferring the lengths of output lists. + self.op.inferred_counts[self.name] = self.input_arg.swift_name + '.count' + return 'op.updateAttribute("{}", {}.count)'.format(self.name, self.input_arg.swift_name) + + if self.attr_def.type == 'int': + # The following is used for inferring the lengths of output lists. + self.op.inferred_counts[self.name] = self.swift_name + + # Remaining attributes. + value = self.swift_name + '.cName' if self._use_enum else self.swift_name + return 'op.updateAttribute("{}", {})'.format(self.name, value) + + def generic_constraints(self, string_valued): + # We use this for obtaining the `_typeList` property. + input_arg = None + if self.attr_def.type == 'list(type)': + for arg in self.op.input_args: + if self.attr_def.name in [arg.arg_def.type_attr, + arg.arg_def.type_list_attr]: + input_arg = arg + break + if self.is_func_attr: + input_type = self.swift_name.capitalize() + 'In' + output_type = self.swift_name.capitalize() + 'Out' + return '{}: TensorGroup,\n {}: TensorGroup'.format( + input_type, output_type) + if not self.is_inferred_type_attr: + return None + protocol = None + if self.attr_def.type == 'list(type)' and input_arg is None: + protocol = 'TensorGroup' + elif self.attr_def.type == 'list(type)': + protocol = 'TensorArrayProtocol' + elif self.attr_def.type == 'type': + if string_valued and self.allows_string: + return None + protocol = 'TensorFlowScalar' + allowed_types = set(self.attr_def.allowed_values.list.type) + allowed_types &= set(_SWIFTIFIED_TYPES.keys()) + for types, protocol_name in _TYPE_PROTOCOLS: + if allowed_types.issubset(types): + protocol = protocol_name + break + if protocol is not None: + return self.swift_name + ': ' + protocol + return None + + @property + def allows_string(self): + return types_pb2.DT_STRING in self.attr_def.allowed_values.list.type + + +def swift_compatible_identifier(s, capitalize=False): + """Transforms an identifier to be more swift idiomatic.""" + if s in _RENAMED_KEYWORDS: + return _RENAMED_KEYWORDS[s] + if capitalize: + s = s.capitalize() + without_underscores = [] + capitalize_next_char = False + for c in s: + if c == '-' or c == '_' or c == '(' or c == ')': + capitalize_next_char = True + elif capitalize_next_char: + capitalize_next_char = False + without_underscores.append(c.upper()) + else: + without_underscores.append(c) + return ''.join(without_underscores) + + +class EnumStore(object): + """Stores details on string attributes represented as swift enums.""" + + def __init__(self): + self._entries = {} + self._type_names = set() + self._counter = 1 + + def enum_codes(self): + """Generates the swift code for enums.""" + codes = [] + entries = list(six.iteritems(self._entries)) + for allowed_values, type_name in sorted(entries, key=lambda x: x[1]): + allowed_values = [str(a, encoding='utf-8') for a in allowed_values] + codes.append( + # FIXME: Re-add `@_frozen` after SR-9739 is resolved. + # https://bugs.swift.org/browse/SR-9739 + # '@_frozen\n' + + '// @_frozen // SR-9739\n' + + 'public enum {} {{\n'.format(type_name) + + '\n'.join([' case {}'.format( + swift_compatible_identifier(a.lower())) + for a in allowed_values]) + + '\n\n' + + ' @inlinable\n' + + ' var cName: String {\n' + + ' @inline(__always)\n' + + ' get {\n' + + ' switch self {\n' + + '\n'.join([' case .{}: return "{}"'.format( + swift_compatible_identifier(a.lower()), a) + for a in allowed_values]) + + '\n' + + ' }\n' + + ' }\n' + + ' }\n' + + '}') + return codes + + def maybe_add(self, allowed_values, attr_def_name): + if allowed_values in self._entries: + return self._entries[allowed_values] + type_name = swift_compatible_identifier(attr_def_name, capitalize=True) + while type_name in self._type_names: + type_name += str(self._counter) + self._counter += 1 + self._type_names.add(type_name) + self._entries[allowed_values] = type_name + return type_name + + +def main(argv): + del argv # Unused. + if FLAGS.output_path is None: + raise ValueError('No output_path has been set') + + api_def_map = c_api_util.ApiDefMap() + + op_codes = [] + enum_store = EnumStore() + op_names = api_def_map.op_names() + if FLAGS.api_def_path is not None: + for op_name in op_names: + path = os.path.join(FLAGS.api_def_path, 'api_def_%s.pbtxt' % op_name) + if not tf.gfile.Exists(path): + continue + with tf.gfile.Open(path, 'r') as fobj: + data = fobj.read() + try: + api_def_map.put_api_def(data) + except Exception as e: + print('Cannot load api def for %s: %s' % (op_name, str(e))) + + num_generated = 0 + for op_name in sorted(op_names): + try: + if op_name[0] == '_': continue + op_def = api_def_map.get_op_def(op_name) + if any(a.is_ref for a in op_def.input_arg): + raise UnableToGenerateCodeError('has ref-valued input') + if any(a.is_ref for a in op_def.output_arg): + raise UnableToGenerateCodeError('has ref-valued output') + api_def = api_def_map.get_api_def(bytes(op_name, 'utf8')) + + # It would be nicer to handle `StringTensor` in a more + # general way by having `String` conform to `TensorFlowScalar`. + default_op = Op(op_def, api_def, enum_store, string_valued=False) + string_valued_op = Op(op_def, api_def, enum_store, string_valued=True) + default_code = default_op.swift_function() + string_valued_code = string_valued_op.swift_function() + op_codes.append(default_code) + if string_valued_code != default_code: + op_codes.append(string_valued_code) + num_generated += 1 + except UnableToGenerateCodeError as e: + print('Cannot generate code for %s: %s' % (op_name, e.details)) + print('Generated code for %d/%d ops.' % (num_generated, len(op_names))) + + version_codes = [ + 'static let generatedTensorFlowVersion = "%s"' % tf.__version__, + 'static let generatedTensorFlowGitVersion = "%s"' % tf.__git_version__] + + swift_code = ( + _WARNING + + _HEADER + + 'import CTensorFlow\n\n' + + '@inlinable @inline(__always)\n' + + 'func makeOp(_ name: String, _ nOutputs: Int)'+ + ' -> TFTensorOperation {\n' + + ' _ExecutionContext.makeOp(name, nOutputs)\n' + + '}\n'+ + '\npublic enum Raw {\n\n' + + '\n'.join(version_codes) + + '\n\n' + + '\n\n'.join(enum_store.enum_codes()) + + '\n\n' + + '\n'.join(op_codes) + + '\n\n}\n') + with tf.gfile.Open(FLAGS.output_path, 'w') as f: + f.write(swift_code) + + +if __name__ == '__main__': + tf.app.run(main) diff --git a/clone_tensorflow_bindings.sh b/clone_tensorflow_bindings.sh deleted file mode 100644 index 2037a386f..000000000 --- a/clone_tensorflow_bindings.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -git clone git@github.com:tensorflow/swift-bindings.git Sources/DeepLearning/Bindings From 95f6f4c9a7bd8b7a9bfdeebeb13414d8ce492876 Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 16:27:17 -0400 Subject: [PATCH 04/14] Updated the copyright notices. --- Sources/DeepLearning/Bindings/EagerExecution.swift | 4 ++-- .../DeepLearning/Bindings/EagerExecution.swift.gyb | 4 ++-- Sources/DeepLearning/Bindings/RawOpsGenerated.swift | 4 ++-- .../DeepLearning/Bindings/TFTensorOperation.swift | 13 +++++++++++++ Sources/DeepLearning/Bindings/generate_wrappers.py | 8 ++++---- 5 files changed, 23 insertions(+), 10 deletions(-) diff --git a/Sources/DeepLearning/Bindings/EagerExecution.swift b/Sources/DeepLearning/Bindings/EagerExecution.swift index ba1bf75ce..e007c9bc4 100644 --- a/Sources/DeepLearning/Bindings/EagerExecution.swift +++ b/Sources/DeepLearning/Bindings/EagerExecution.swift @@ -1,12 +1,12 @@ // !!! THIS CODE IS AUTOMATICALLY GENERATED, DO NOT EDIT BY HAND !!! // -// Copyright 2018-19 Google LLC +// Copyright 2018 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// https://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Sources/DeepLearning/Bindings/EagerExecution.swift.gyb b/Sources/DeepLearning/Bindings/EagerExecution.swift.gyb index 14e8f1d0f..ffa16b1b3 100644 --- a/Sources/DeepLearning/Bindings/EagerExecution.swift.gyb +++ b/Sources/DeepLearning/Bindings/EagerExecution.swift.gyb @@ -1,12 +1,12 @@ // !!! THIS CODE IS AUTOMATICALLY GENERATED, DO NOT EDIT BY HAND !!! // -// Copyright 2018-19 Google LLC +// Copyright 2018 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// https://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Sources/DeepLearning/Bindings/RawOpsGenerated.swift b/Sources/DeepLearning/Bindings/RawOpsGenerated.swift index 51aa03bd2..0006cad9a 100644 --- a/Sources/DeepLearning/Bindings/RawOpsGenerated.swift +++ b/Sources/DeepLearning/Bindings/RawOpsGenerated.swift @@ -1,12 +1,12 @@ // !!! THIS CODE IS AUTOMATICALLY GENERATED, DO NOT EDIT BY HAND !!! // -// Copyright 2018-19 Google LLC +// Copyright 2018 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// https://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Sources/DeepLearning/Bindings/TFTensorOperation.swift b/Sources/DeepLearning/Bindings/TFTensorOperation.swift index 419eecb73..acd8cc18b 100644 --- a/Sources/DeepLearning/Bindings/TFTensorOperation.swift +++ b/Sources/DeepLearning/Bindings/TFTensorOperation.swift @@ -1,3 +1,16 @@ +// Copyright 2018 The TensorFlow Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. // A protocol for a tensor operation. public protocol TensorOperation { diff --git a/Sources/DeepLearning/Bindings/generate_wrappers.py b/Sources/DeepLearning/Bindings/generate_wrappers.py index 1a57dc52f..c1e276254 100644 --- a/Sources/DeepLearning/Bindings/generate_wrappers.py +++ b/Sources/DeepLearning/Bindings/generate_wrappers.py @@ -1,10 +1,10 @@ -# Copyright 2018 Google LLC +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, @@ -42,13 +42,13 @@ // """ -_HEADER = """// Copyright 2018-19 Google LLC +_HEADER = """// Copyright 2018 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// https://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, From 89cb75576bfc8fcc75d4219682e41cb5d9c274aa Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 16:43:53 -0400 Subject: [PATCH 05/14] Fixed the format of the bindings files. --- .../Bindings/EagerExecution.swift | 1057 +- .../Bindings/EagerExecution.swift.gyb | 535 +- .../Bindings/RawOpsGenerated.swift | 34480 ++++++++-------- .../Bindings/TFTensorOperation.swift | 235 +- .../Bindings/generate_wrappers.py | 39 +- 5 files changed, 17724 insertions(+), 18622 deletions(-) diff --git a/Sources/DeepLearning/Bindings/EagerExecution.swift b/Sources/DeepLearning/Bindings/EagerExecution.swift index e007c9bc4..aa0c94c12 100644 --- a/Sources/DeepLearning/Bindings/EagerExecution.swift +++ b/Sources/DeepLearning/Bindings/EagerExecution.swift @@ -21,537 +21,540 @@ import CTensorFlow /// eager op object not being freed. If called more than once, then a SEGFAULT may occur due to /// trying to execute a TensorFlow eager op that has already been freed. @usableFromInline -internal struct TFE_Op : TFTensorOperation { - @usableFromInline internal let status: CTFStatus - @usableFromInline internal let op: CTFEOp - @usableFromInline internal let outputCount: Int - - @usableFromInline - internal init(_ name: String, _ outputCount: Int) { - self.status = TF_NewStatus() - self.op = TFE_NewOp(_ExecutionContext.global.eagerContext, name, status) - self.outputCount = outputCount - } - - @inlinable @inline(__always) - internal func addInput(_ input: _AnyTensorHandle) { - TFE_OpAddInput(op, input._cTensorHandle, status) - checkOk(status) - } - - @inlinable @inline(__always) - internal func addInput(_ input: Tensor) { - TFE_OpAddInput(op, input.handle._cTensorHandle, status) - checkOk(status) - } - - @inlinable @inline(__always) - internal func addInput(_ input: StringTensor) { - TFE_OpAddInput(op, input.handle._cTensorHandle, status) - checkOk(status) - } - - @inlinable @inline(__always) - internal func addInput(_ input: ResourceHandle) { - TFE_OpAddInput(op, input._cTensorHandle, status) - checkOk(status) - } - - @inlinable @inline(__always) - internal func addInput(_ input: VariantHandle) { - TFE_OpAddInput(op, input._cTensorHandle, status) - checkOk(status) - } - - @inlinable @inline(__always) - internal func addInputList(_ input: T) { - let count = input._tensorHandleCount - var buffer = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) - defer { buffer.deallocate() } - let pointer = UnsafeMutablePointer(buffer.baseAddress) - input._unpackTensorHandles(into: buffer.baseAddress) - TFE_OpAddInputList(op, pointer, count, status) - // TODO: checkOk(status) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: Bool) { - TFE_OpSetAttrBool(op, name, value ? 1 : 0) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: Int) { - TFE_OpSetAttrInt(op, name, Int64(value)) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: Int32) { - TFE_OpSetAttrInt(op, name, Int64(value)) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: Int64) { - TFE_OpSetAttrInt(op, name, value) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: Float) { - TFE_OpSetAttrFloat(op, name, value) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: Double) { - TFE_OpSetAttrFloat(op, name, Float(value)) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: String) { - value.utf8CString.withUnsafeBufferPointer { buffer in - // utf8CString is null-terminated; TFE_OpSetAttrString wants - // non-null-terminated. - TFE_OpSetAttrString(op, name, buffer.baseAddress, buffer.count - 1) - } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: TensorDataType) { - TFE_OpSetAttrType(op, name, value._cDataType) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: TensorShape) { - let dimensions: [Int64] = value.dimensions.map(Int64.init) - dimensions.withUnsafeBufferPointer { buffer in - TFE_OpSetAttrShape(op, name, buffer.baseAddress, Int32(buffer.count), status) - } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: TensorShape?) { - guard let shape = value else { - TFE_OpSetAttrShape(op, name, nil, -1, status) - return - } - updateAttribute(name, shape) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [Bool]) { - value.map({ $0 ? UInt8(1) : UInt8(0) }).withUnsafeBufferPointer { buffer in - TFE_OpSetAttrBoolList(op, name, buffer.baseAddress, Int32(buffer.count)) - } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [Int]) { - updateAttribute(name, value.map(Int64.init)) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [Int32]) { - updateAttribute(name, value.map(Int64.init)) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [Int64]) { - value.withUnsafeBufferPointer { buffer in - TFE_OpSetAttrIntList(op, name, buffer.baseAddress, Int32(buffer.count)) - } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [Float]) { - value.withUnsafeBufferPointer { buffer in - TFE_OpSetAttrFloatList(op, name, buffer.baseAddress, Int32(buffer.count)) - } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [Double]) { - updateAttribute(name, value.map(Float.init)) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [String]) { - // Collect all the strings' utf8 bytes into a single array so that we can - // address all the strings with a single - // `flattenedStringBytes.withUnsafeBufferPointer`. - var flattenedStringBytes: [CChar] = [] - var lengths: [Int] = [] - for string in value { - // Don't include the null-terminator because TFE_OpSetAttrStringList uses - // lengths instead of null-terminators. - let stringBytes = string.utf8CString.dropLast() - flattenedStringBytes.append(contentsOf: stringBytes) - lengths.append(stringBytes.count) - } - - // Calculate the addresses of all the strings within our single buffer, and - // then call TFE_OpSetAttrStringList. - flattenedStringBytes.withUnsafeBufferPointer { flattenedStringBytesBuffer in - var stringAddrs: [UnsafeRawPointer?] = [] - var currentStringAddr = - flattenedStringBytesBuffer.baseAddress.map(UnsafeRawPointer.init) - for length in lengths { - stringAddrs.append(currentStringAddr) - currentStringAddr = currentStringAddr?.advanced(by: length) - } - - stringAddrs.withUnsafeBufferPointer { stringAddrsBuffer in - lengths.withUnsafeBufferPointer { lengthsBuffer in - TFE_OpSetAttrStringList(op, name, stringAddrsBuffer.baseAddress, - lengthsBuffer.baseAddress, Int32(value.count)) +internal struct TFE_Op: TFTensorOperation { + @usableFromInline internal let status: CTFStatus + @usableFromInline internal let op: CTFEOp + @usableFromInline internal let outputCount: Int + + @usableFromInline + internal init(_ name: String, _ outputCount: Int) { + self.status = TF_NewStatus() + self.op = TFE_NewOp(_ExecutionContext.global.eagerContext, name, status) + self.outputCount = outputCount + } + + @inlinable @inline(__always) + internal func addInput(_ input: _AnyTensorHandle) { + TFE_OpAddInput(op, input._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: Tensor) { + TFE_OpAddInput(op, input.handle._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: StringTensor) { + TFE_OpAddInput(op, input.handle._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: ResourceHandle) { + TFE_OpAddInput(op, input._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: VariantHandle) { + TFE_OpAddInput(op, input._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInputList(_ input: T) { + let count = input._tensorHandleCount + var buffer = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) + defer { buffer.deallocate() } + let pointer = UnsafeMutablePointer(buffer.baseAddress) + input._unpackTensorHandles(into: buffer.baseAddress) + TFE_OpAddInputList(op, pointer, count, status) + // TODO: checkOk(status) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Bool) { + TFE_OpSetAttrBool(op, name, value ? 1 : 0) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Int) { + TFE_OpSetAttrInt(op, name, Int64(value)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Int32) { + TFE_OpSetAttrInt(op, name, Int64(value)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Int64) { + TFE_OpSetAttrInt(op, name, value) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Float) { + TFE_OpSetAttrFloat(op, name, value) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Double) { + TFE_OpSetAttrFloat(op, name, Float(value)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: String) { + value.utf8CString.withUnsafeBufferPointer { buffer in + // utf8CString is null-terminated; TFE_OpSetAttrString wants non-null-terminated. + TFE_OpSetAttrString(op, name, buffer.baseAddress, buffer.count - 1) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: TensorDataType) { + TFE_OpSetAttrType(op, name, value._cDataType) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: TensorShape) { + let dimensions: [Int64] = value.dimensions.map(Int64.init) + dimensions.withUnsafeBufferPointer { buffer in + TFE_OpSetAttrShape(op, name, buffer.baseAddress, Int32(buffer.count), status) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: TensorShape?) { + guard let shape = value else { + TFE_OpSetAttrShape(op, name, nil, -1, status) + return + } + updateAttribute(name, shape) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Bool]) { + value.map({ $0 ? UInt8(1) : UInt8(0) }).withUnsafeBufferPointer { buffer in + TFE_OpSetAttrBoolList(op, name, buffer.baseAddress, Int32(buffer.count)) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Int]) { + updateAttribute(name, value.map(Int64.init)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Int32]) { + updateAttribute(name, value.map(Int64.init)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Int64]) { + value.withUnsafeBufferPointer { buffer in + TFE_OpSetAttrIntList(op, name, buffer.baseAddress, Int32(buffer.count)) } - } - } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [TensorDataType]) { - value.withUnsafeBufferPointer { buffer in - buffer.withMemoryRebound(to: TF_DataType.self) { reboundBuffer in - TFE_OpSetAttrTypeList(op, name, reboundBuffer.baseAddress, Int32(reboundBuffer.count)) - } - } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [TensorShape]) { - let flattenedDims = value.flatMap { $0.dimensions.map(Int64.init) } - let ranks = value.map { Int32($0.rank) } - flattenedDims.withUnsafeBufferPointer { flattenedDimsBuffer in - var dimsPtr: UnsafePointer? = flattenedDimsBuffer.baseAddress - var dims: [UnsafePointer?] = [] - for rank in ranks { - dims.append(dimsPtr) - if rank >= 0 { - dimsPtr = dimsPtr.map { $0.advanced(by: Int(rank)) } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Float]) { + value.withUnsafeBufferPointer { buffer in + TFE_OpSetAttrFloatList(op, name, buffer.baseAddress, Int32(buffer.count)) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Double]) { + updateAttribute(name, value.map(Float.init)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [String]) { + // Collect all the strings' utf8 bytes into a single array so that we can + // address all the strings with a single + // `flattenedStringBytes.withUnsafeBufferPointer`. + var flattenedStringBytes: [CChar] = [] + var lengths: [Int] = [] + for string in value { + // Don't include the null-terminator because TFE_OpSetAttrStringList uses + // lengths instead of null-terminators. + let stringBytes = string.utf8CString.dropLast() + flattenedStringBytes.append(contentsOf: stringBytes) + lengths.append(stringBytes.count) + } + + // Calculate the addresses of all the strings within our single buffer, and then call + // TFE_OpSetAttrStringList. + flattenedStringBytes.withUnsafeBufferPointer { flattenedStringBytesBuffer in + var stringAddrs: [UnsafeRawPointer?] = [] + var currentStringAddr = + flattenedStringBytesBuffer.baseAddress.map(UnsafeRawPointer.init) + for length in lengths { + stringAddrs.append(currentStringAddr) + currentStringAddr = currentStringAddr?.advanced(by: length) + } + + stringAddrs.withUnsafeBufferPointer { stringAddrsBuffer in + lengths.withUnsafeBufferPointer { lengthsBuffer in + TFE_OpSetAttrStringList(op, name, stringAddrsBuffer.baseAddress, + lengthsBuffer.baseAddress, Int32(value.count)) + } + } + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [TensorDataType]) { + value.withUnsafeBufferPointer { buffer in + buffer.withMemoryRebound(to: TF_DataType.self) { reboundBuffer in + TFE_OpSetAttrTypeList( + op, name, reboundBuffer.baseAddress, Int32(reboundBuffer.count)) + } } - } - dims.withUnsafeMutableBufferPointer { dimsBuffer in - ranks.withUnsafeBufferPointer { ranksBuffer in - TFE_OpSetAttrShapeList( - op, name, dimsBuffer.baseAddress, ranksBuffer.baseAddress, - Int32(ranksBuffer.count), status) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [TensorShape]) { + let flattenedDims = value.flatMap { $0.dimensions.map(Int64.init) } + let ranks = value.map { Int32($0.rank) } + flattenedDims.withUnsafeBufferPointer { flattenedDimsBuffer in + var dimsPtr: UnsafePointer? = flattenedDimsBuffer.baseAddress + var dims: [UnsafePointer?] = [] + for rank in ranks { + dims.append(dimsPtr) + if rank >= 0 { + dimsPtr = dimsPtr.map { $0.advanced(by: Int(rank)) } + } + } + dims.withUnsafeMutableBufferPointer { dimsBuffer in + ranks.withUnsafeBufferPointer { ranksBuffer in + TFE_OpSetAttrShapeList( + op, name, dimsBuffer.baseAddress, ranksBuffer.baseAddress, + Int32(ranksBuffer.count), status) + } + } } - } - } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [TensorShape?]) { - let flattenedDims = value.flatMap { (tensorShapeOpt) -> [Int64] in - if let tensorShape = tensorShapeOpt { - return tensorShape.dimensions.map(Int64.init) - } - return [] - } - let ranks = value.map { shape in (shape?.rank).map(Int32.init) ?? -1 } - flattenedDims.withUnsafeBufferPointer { flattenedDimsBuffer in - var dimsPtr: UnsafePointer? = flattenedDimsBuffer.baseAddress - var dims: [UnsafePointer?] = [] - for rank in ranks { - dims.append(dimsPtr) - if rank >= 0 { - dimsPtr = dimsPtr.map { $0.advanced(by: Int(rank)) } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [TensorShape?]) { + let flattenedDims = value.flatMap { (tensorShapeOpt) -> [Int64] in + if let tensorShape = tensorShapeOpt { + return tensorShape.dimensions.map(Int64.init) + } + return [] } - } - dims.withUnsafeMutableBufferPointer { dimsBuffer in - ranks.withUnsafeBufferPointer { ranksBuffer in - TFE_OpSetAttrShapeList( - op, name, dimsBuffer.baseAddress, ranksBuffer.baseAddress, - Int32(ranksBuffer.count), status) + let ranks = value.map { shape in (shape?.rank).map(Int32.init) ?? -1 } + flattenedDims.withUnsafeBufferPointer { flattenedDimsBuffer in + var dimsPtr: UnsafePointer? = flattenedDimsBuffer.baseAddress + var dims: [UnsafePointer?] = [] + for rank in ranks { + dims.append(dimsPtr) + if rank >= 0 { + dimsPtr = dimsPtr.map { $0.advanced(by: Int(rank)) } + } + } + dims.withUnsafeMutableBufferPointer { dimsBuffer in + ranks.withUnsafeBufferPointer { ranksBuffer in + TFE_OpSetAttrShapeList( + op, name, dimsBuffer.baseAddress, ranksBuffer.baseAddress, + Int32(ranksBuffer.count), status) + } + } } - } - } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: (In) -> Out) { - _tffunc(value).utf8CString.withUnsafeBufferPointer { buffer in - // utf8CString is null-terminated; TFE_OpSetAttrFunctionName wants - // non-null-terminated. - TFE_OpSetAttrFunctionName(op, name, buffer.baseAddress, buffer.count - 1) - } - } - - /// **WARNING:** After constructing a `TFE_Op`, any one of its `execute` methods must be called - /// *exactly once*. If not called, then a memory leak is introduced due to the underlying - /// TensorFlow eager op object not being freed. If called more than once, then a SEGFAULT may - /// occur due to trying to execute a TensorFlow eager op that has already been freed. - - @inlinable @inline(__always) - internal func evaluateUnsafe() -> UnsafeMutablePointer { - var count: Int32 = Int32(self.outputCount) - let buffer: UnsafeMutablePointer = - UnsafeMutablePointer.allocate(capacity: Int(count)) - _TFCOpSetDeviceFromScope(op, status) - checkOk(status) - _TFCEagerExecute(op, UnsafeMutablePointer(buffer), &count, status) - checkOk(status) - TFE_DeleteOp(op) - TF_DeleteStatus(status) - return buffer - } - - @inlinable @inline(__always) - internal func execute() { - let _ = evaluateUnsafe() - } - - @inlinable @inline(__always) - internal func execute( - _ count0: Int - ) -> (T0) { - let buffer = evaluateUnsafe() - let offset0 = Int32(0) - let result = ( - T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0)) - buffer.deallocate() - return result - } - - @inlinable @inline(__always) - internal func execute( - _ count0: Int, - _ count1: Int - ) -> (T0, T1) { - let buffer = evaluateUnsafe() - let offset0 = Int32(0) - let offset1 = offset0 + Int32(count0) - let result = ( - T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), - T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1)) - buffer.deallocate() - return result - } - - @inlinable @inline(__always) - internal func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int - ) -> (T0, T1, T2) { - let buffer = evaluateUnsafe() - let offset0 = Int32(0) - let offset1 = offset0 + Int32(count0) - let offset2 = offset1 + Int32(count1) - let result = ( - T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), - T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), - T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2)) - buffer.deallocate() - return result - } - - @inlinable @inline(__always) - internal func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int - ) -> (T0, T1, T2, T3) { - let buffer = evaluateUnsafe() - let offset0 = Int32(0) - let offset1 = offset0 + Int32(count0) - let offset2 = offset1 + Int32(count1) - let offset3 = offset2 + Int32(count2) - let result = ( - T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), - T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), - T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), - T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3)) - buffer.deallocate() - return result - } - - @inlinable @inline(__always) - internal func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int, - _ count4: Int - ) -> (T0, T1, T2, T3, T4) { - let buffer = evaluateUnsafe() - let offset0 = Int32(0) - let offset1 = offset0 + Int32(count0) - let offset2 = offset1 + Int32(count1) - let offset3 = offset2 + Int32(count2) - let offset4 = offset3 + Int32(count3) - let result = ( - T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), - T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), - T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), - T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), - T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4)) - buffer.deallocate() - return result - } - - @inlinable @inline(__always) - internal func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int, - _ count4: Int, - _ count5: Int - ) -> (T0, T1, T2, T3, T4, T5) { - let buffer = evaluateUnsafe() - let offset0 = Int32(0) - let offset1 = offset0 + Int32(count0) - let offset2 = offset1 + Int32(count1) - let offset3 = offset2 + Int32(count2) - let offset4 = offset3 + Int32(count3) - let offset5 = offset4 + Int32(count4) - let result = ( - T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), - T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), - T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), - T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), - T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), - T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5)) - buffer.deallocate() - return result - } - - @inlinable @inline(__always) - internal func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int, - _ count4: Int, - _ count5: Int, - _ count6: Int - ) -> (T0, T1, T2, T3, T4, T5, T6) { - let buffer = evaluateUnsafe() - let offset0 = Int32(0) - let offset1 = offset0 + Int32(count0) - let offset2 = offset1 + Int32(count1) - let offset3 = offset2 + Int32(count2) - let offset4 = offset3 + Int32(count3) - let offset5 = offset4 + Int32(count4) - let offset6 = offset5 + Int32(count5) - let result = ( - T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), - T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), - T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), - T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), - T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), - T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5), - T6.init(_owning: buffer.advanced(by: Int(offset6)), count: count6)) - buffer.deallocate() - return result - } - - @inlinable @inline(__always) - internal func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int, - _ count4: Int, - _ count5: Int, - _ count6: Int, - _ count7: Int - ) -> (T0, T1, T2, T3, T4, T5, T6, T7) { - let buffer = evaluateUnsafe() - let offset0 = Int32(0) - let offset1 = offset0 + Int32(count0) - let offset2 = offset1 + Int32(count1) - let offset3 = offset2 + Int32(count2) - let offset4 = offset3 + Int32(count3) - let offset5 = offset4 + Int32(count4) - let offset6 = offset5 + Int32(count5) - let offset7 = offset6 + Int32(count6) - let result = ( - T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), - T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), - T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), - T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), - T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), - T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5), - T6.init(_owning: buffer.advanced(by: Int(offset6)), count: count6), - T7.init(_owning: buffer.advanced(by: Int(offset7)), count: count7)) - buffer.deallocate() - return result - } - - @inlinable @inline(__always) - internal func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int, - _ count4: Int, - _ count5: Int, - _ count6: Int, - _ count7: Int, - _ count8: Int - ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8) { - let buffer = evaluateUnsafe() - let offset0 = Int32(0) - let offset1 = offset0 + Int32(count0) - let offset2 = offset1 + Int32(count1) - let offset3 = offset2 + Int32(count2) - let offset4 = offset3 + Int32(count3) - let offset5 = offset4 + Int32(count4) - let offset6 = offset5 + Int32(count5) - let offset7 = offset6 + Int32(count6) - let offset8 = offset7 + Int32(count7) - let result = ( - T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), - T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), - T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), - T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), - T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), - T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5), - T6.init(_owning: buffer.advanced(by: Int(offset6)), count: count6), - T7.init(_owning: buffer.advanced(by: Int(offset7)), count: count7), - T8.init(_owning: buffer.advanced(by: Int(offset8)), count: count8)) - buffer.deallocate() - return result - } - - @inlinable @inline(__always) - internal func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int, - _ count4: Int, - _ count5: Int, - _ count6: Int, - _ count7: Int, - _ count8: Int, - _ count9: Int - ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9) { - let buffer = evaluateUnsafe() - let offset0 = Int32(0) - let offset1 = offset0 + Int32(count0) - let offset2 = offset1 + Int32(count1) - let offset3 = offset2 + Int32(count2) - let offset4 = offset3 + Int32(count3) - let offset5 = offset4 + Int32(count4) - let offset6 = offset5 + Int32(count5) - let offset7 = offset6 + Int32(count6) - let offset8 = offset7 + Int32(count7) - let offset9 = offset8 + Int32(count8) - let result = ( - T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), - T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), - T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), - T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), - T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), - T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5), - T6.init(_owning: buffer.advanced(by: Int(offset6)), count: count6), - T7.init(_owning: buffer.advanced(by: Int(offset7)), count: count7), - T8.init(_owning: buffer.advanced(by: Int(offset8)), count: count8), - T9.init(_owning: buffer.advanced(by: Int(offset9)), count: count9)) - buffer.deallocate() - return result - } + } + + @inlinable @inline(__always) + internal func updateAttribute( + _ name: String, + _ value: (In) -> Out + ) { + _tffunc(value).utf8CString.withUnsafeBufferPointer { buffer in + // utf8CString is null-terminated; TFE_OpSetAttrFunctionName wants + // non-null-terminated. + TFE_OpSetAttrFunctionName(op, name, buffer.baseAddress, buffer.count - 1) + } + } + + /// **WARNING:** After constructing a `TFE_Op`, any one of its `execute` methods must be called + /// *exactly once*. If not called, then a memory leak is introduced due to the underlying + /// TensorFlow eager op object not being freed. If called more than once, then a SEGFAULT may + /// occur due to trying to execute a TensorFlow eager op that has already been freed. + + @inlinable @inline(__always) + internal func evaluateUnsafe() -> UnsafeMutablePointer { + var count: Int32 = Int32(self.outputCount) + let buffer: UnsafeMutablePointer = + UnsafeMutablePointer.allocate(capacity: Int(count)) + _TFCOpSetDeviceFromScope(op, status) + checkOk(status) + _TFCEagerExecute(op, UnsafeMutablePointer(buffer), &count, status) + checkOk(status) + TFE_DeleteOp(op) + TF_DeleteStatus(status) + return buffer + } + + @inlinable @inline(__always) + internal func execute() { + let _ = evaluateUnsafe() + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int + ) -> (T0) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int + ) -> (T0, T1) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int + ) -> (T0, T1, T2) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int + ) -> (T0, T1, T2, T3) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int + ) -> (T0, T1, T2, T3, T4) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let offset4 = offset3 + Int32(count3) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), + T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int + ) -> (T0, T1, T2, T3, T4, T5) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let offset4 = offset3 + Int32(count3) + let offset5 = offset4 + Int32(count4) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), + T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), + T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int + ) -> (T0, T1, T2, T3, T4, T5, T6) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let offset4 = offset3 + Int32(count3) + let offset5 = offset4 + Int32(count4) + let offset6 = offset5 + Int32(count5) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), + T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), + T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5), + T6.init(_owning: buffer.advanced(by: Int(offset6)), count: count6)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int, + _ count7: Int + ) -> (T0, T1, T2, T3, T4, T5, T6, T7) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let offset4 = offset3 + Int32(count3) + let offset5 = offset4 + Int32(count4) + let offset6 = offset5 + Int32(count5) + let offset7 = offset6 + Int32(count6) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), + T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), + T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5), + T6.init(_owning: buffer.advanced(by: Int(offset6)), count: count6), + T7.init(_owning: buffer.advanced(by: Int(offset7)), count: count7)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int, + _ count7: Int, + _ count8: Int + ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let offset4 = offset3 + Int32(count3) + let offset5 = offset4 + Int32(count4) + let offset6 = offset5 + Int32(count5) + let offset7 = offset6 + Int32(count6) + let offset8 = offset7 + Int32(count7) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), + T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), + T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5), + T6.init(_owning: buffer.advanced(by: Int(offset6)), count: count6), + T7.init(_owning: buffer.advanced(by: Int(offset7)), count: count7), + T8.init(_owning: buffer.advanced(by: Int(offset8)), count: count8)) + buffer.deallocate() + return result + } + + @inlinable @inline(__always) + internal func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int, + _ count7: Int, + _ count8: Int, + _ count9: Int + ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9) { + let buffer = evaluateUnsafe() + let offset0 = Int32(0) + let offset1 = offset0 + Int32(count0) + let offset2 = offset1 + Int32(count1) + let offset3 = offset2 + Int32(count2) + let offset4 = offset3 + Int32(count3) + let offset5 = offset4 + Int32(count4) + let offset6 = offset5 + Int32(count5) + let offset7 = offset6 + Int32(count6) + let offset8 = offset7 + Int32(count7) + let offset9 = offset8 + Int32(count8) + let result = ( + T0.init(_owning: buffer.advanced(by: Int(offset0)), count: count0), + T1.init(_owning: buffer.advanced(by: Int(offset1)), count: count1), + T2.init(_owning: buffer.advanced(by: Int(offset2)), count: count2), + T3.init(_owning: buffer.advanced(by: Int(offset3)), count: count3), + T4.init(_owning: buffer.advanced(by: Int(offset4)), count: count4), + T5.init(_owning: buffer.advanced(by: Int(offset5)), count: count5), + T6.init(_owning: buffer.advanced(by: Int(offset6)), count: count6), + T7.init(_owning: buffer.advanced(by: Int(offset7)), count: count7), + T8.init(_owning: buffer.advanced(by: Int(offset8)), count: count8), + T9.init(_owning: buffer.advanced(by: Int(offset9)), count: count9)) + buffer.deallocate() + return result + } } diff --git a/Sources/DeepLearning/Bindings/EagerExecution.swift.gyb b/Sources/DeepLearning/Bindings/EagerExecution.swift.gyb index ffa16b1b3..75cf2d549 100644 --- a/Sources/DeepLearning/Bindings/EagerExecution.swift.gyb +++ b/Sources/DeepLearning/Bindings/EagerExecution.swift.gyb @@ -21,298 +21,301 @@ import CTensorFlow /// eager op object not being freed. If called more than once, then a SEGFAULT may occur due to /// trying to execute a TensorFlow eager op that has already been freed. @usableFromInline -internal struct TFE_Op : TFTensorOperation { - @usableFromInline internal let status: CTFStatus - @usableFromInline internal let op: CTFEOp - @usableFromInline internal let outputCount: Int - - @usableFromInline - internal init(_ name: String, _ outputCount: Int) { - self.status = TF_NewStatus() - self.op = TFE_NewOp(_ExecutionContext.global.eagerContext, name, status) - self.outputCount = outputCount - } - - @inlinable @inline(__always) - internal func addInput(_ input: _AnyTensorHandle) { - TFE_OpAddInput(op, input._cTensorHandle, status) - checkOk(status) - } - - @inlinable @inline(__always) - internal func addInput(_ input: Tensor) { - TFE_OpAddInput(op, input.handle._cTensorHandle, status) - checkOk(status) - } - - @inlinable @inline(__always) - internal func addInput(_ input: StringTensor) { - TFE_OpAddInput(op, input.handle._cTensorHandle, status) - checkOk(status) - } - - @inlinable @inline(__always) - internal func addInput(_ input: ResourceHandle) { - TFE_OpAddInput(op, input._cTensorHandle, status) - checkOk(status) - } - - @inlinable @inline(__always) - internal func addInput(_ input: VariantHandle) { - TFE_OpAddInput(op, input._cTensorHandle, status) - checkOk(status) - } - - @inlinable @inline(__always) - internal func addInputList(_ input: T) { - let count = input._tensorHandleCount - var buffer = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) - defer { buffer.deallocate() } - let pointer = UnsafeMutablePointer(buffer.baseAddress) - input._unpackTensorHandles(into: buffer.baseAddress) - TFE_OpAddInputList(op, pointer, count, status) - // TODO: checkOk(status) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: Bool) { - TFE_OpSetAttrBool(op, name, value ? 1 : 0) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: Int) { - TFE_OpSetAttrInt(op, name, Int64(value)) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: Int32) { - TFE_OpSetAttrInt(op, name, Int64(value)) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: Int64) { - TFE_OpSetAttrInt(op, name, value) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: Float) { - TFE_OpSetAttrFloat(op, name, value) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: Double) { - TFE_OpSetAttrFloat(op, name, Float(value)) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: String) { - value.utf8CString.withUnsafeBufferPointer { buffer in - // utf8CString is null-terminated; TFE_OpSetAttrString wants - // non-null-terminated. - TFE_OpSetAttrString(op, name, buffer.baseAddress, buffer.count - 1) +internal struct TFE_Op: TFTensorOperation { + @usableFromInline internal let status: CTFStatus + @usableFromInline internal let op: CTFEOp + @usableFromInline internal let outputCount: Int + + @usableFromInline + internal init(_ name: String, _ outputCount: Int) { + self.status = TF_NewStatus() + self.op = TFE_NewOp(_ExecutionContext.global.eagerContext, name, status) + self.outputCount = outputCount } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: TensorDataType) { - TFE_OpSetAttrType(op, name, value._cDataType) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: TensorShape) { - let dimensions: [Int64] = value.dimensions.map(Int64.init) - dimensions.withUnsafeBufferPointer { buffer in - TFE_OpSetAttrShape(op, name, buffer.baseAddress, Int32(buffer.count), status) + + @inlinable @inline(__always) + internal func addInput(_ input: _AnyTensorHandle) { + TFE_OpAddInput(op, input._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: Tensor) { + TFE_OpAddInput(op, input.handle._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: StringTensor) { + TFE_OpAddInput(op, input.handle._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: ResourceHandle) { + TFE_OpAddInput(op, input._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInput(_ input: VariantHandle) { + TFE_OpAddInput(op, input._cTensorHandle, status) + checkOk(status) + } + + @inlinable @inline(__always) + internal func addInputList(_ input: T) { + let count = input._tensorHandleCount + var buffer = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) + defer { buffer.deallocate() } + let pointer = UnsafeMutablePointer(buffer.baseAddress) + input._unpackTensorHandles(into: buffer.baseAddress) + TFE_OpAddInputList(op, pointer, count, status) + // TODO: checkOk(status) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Bool) { + TFE_OpSetAttrBool(op, name, value ? 1 : 0) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Int) { + TFE_OpSetAttrInt(op, name, Int64(value)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Int32) { + TFE_OpSetAttrInt(op, name, Int64(value)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Int64) { + TFE_OpSetAttrInt(op, name, value) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Float) { + TFE_OpSetAttrFloat(op, name, value) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: Double) { + TFE_OpSetAttrFloat(op, name, Float(value)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: String) { + value.utf8CString.withUnsafeBufferPointer { buffer in + // utf8CString is null-terminated; TFE_OpSetAttrString wants non-null-terminated. + TFE_OpSetAttrString(op, name, buffer.baseAddress, buffer.count - 1) + } } - } - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: TensorShape?) { - guard let shape = value else { - TFE_OpSetAttrShape(op, name, nil, -1, status) - return + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: TensorDataType) { + TFE_OpSetAttrType(op, name, value._cDataType) } - updateAttribute(name, shape) - } - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [Bool]) { - value.map({ $0 ? UInt8(1) : UInt8(0) }).withUnsafeBufferPointer { buffer in - TFE_OpSetAttrBoolList(op, name, buffer.baseAddress, Int32(buffer.count)) + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: TensorShape) { + let dimensions: [Int64] = value.dimensions.map(Int64.init) + dimensions.withUnsafeBufferPointer { buffer in + TFE_OpSetAttrShape(op, name, buffer.baseAddress, Int32(buffer.count), status) + } } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [Int]) { - updateAttribute(name, value.map(Int64.init)) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [Int32]) { - updateAttribute(name, value.map(Int64.init)) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [Int64]) { - value.withUnsafeBufferPointer { buffer in - TFE_OpSetAttrIntList(op, name, buffer.baseAddress, Int32(buffer.count)) + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: TensorShape?) { + guard let shape = value else { + TFE_OpSetAttrShape(op, name, nil, -1, status) + return + } + updateAttribute(name, shape) } - } - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [Float]) { - value.withUnsafeBufferPointer { buffer in - TFE_OpSetAttrFloatList(op, name, buffer.baseAddress, Int32(buffer.count)) + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Bool]) { + value.map({ $0 ? UInt8(1) : UInt8(0) }).withUnsafeBufferPointer { buffer in + TFE_OpSetAttrBoolList(op, name, buffer.baseAddress, Int32(buffer.count)) + } } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [Double]) { - updateAttribute(name, value.map(Float.init)) - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [String]) { - // Collect all the strings' utf8 bytes into a single array so that we can - // address all the strings with a single - // `flattenedStringBytes.withUnsafeBufferPointer`. - var flattenedStringBytes: [CChar] = [] - var lengths: [Int] = [] - for string in value { - // Don't include the null-terminator because TFE_OpSetAttrStringList uses - // lengths instead of null-terminators. - let stringBytes = string.utf8CString.dropLast() - flattenedStringBytes.append(contentsOf: stringBytes) - lengths.append(stringBytes.count) + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Int]) { + updateAttribute(name, value.map(Int64.init)) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Int32]) { + updateAttribute(name, value.map(Int64.init)) } - // Calculate the addresses of all the strings within our single buffer, and - // then call TFE_OpSetAttrStringList. - flattenedStringBytes.withUnsafeBufferPointer { flattenedStringBytesBuffer in - var stringAddrs: [UnsafeRawPointer?] = [] - var currentStringAddr = - flattenedStringBytesBuffer.baseAddress.map(UnsafeRawPointer.init) - for length in lengths { - stringAddrs.append(currentStringAddr) - currentStringAddr = currentStringAddr?.advanced(by: length) - } - - stringAddrs.withUnsafeBufferPointer { stringAddrsBuffer in - lengths.withUnsafeBufferPointer { lengthsBuffer in - TFE_OpSetAttrStringList(op, name, stringAddrsBuffer.baseAddress, - lengthsBuffer.baseAddress, Int32(value.count)) + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Int64]) { + value.withUnsafeBufferPointer { buffer in + TFE_OpSetAttrIntList(op, name, buffer.baseAddress, Int32(buffer.count)) } - } } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [TensorDataType]) { - value.withUnsafeBufferPointer { buffer in - buffer.withMemoryRebound(to: TF_DataType.self) { reboundBuffer in - TFE_OpSetAttrTypeList(op, name, reboundBuffer.baseAddress, Int32(reboundBuffer.count)) - } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Float]) { + value.withUnsafeBufferPointer { buffer in + TFE_OpSetAttrFloatList(op, name, buffer.baseAddress, Int32(buffer.count)) + } + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [Double]) { + updateAttribute(name, value.map(Float.init)) } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [TensorShape]) { - let flattenedDims = value.flatMap { $0.dimensions.map(Int64.init) } - let ranks = value.map { Int32($0.rank) } - flattenedDims.withUnsafeBufferPointer { flattenedDimsBuffer in - var dimsPtr: UnsafePointer? = flattenedDimsBuffer.baseAddress - var dims: [UnsafePointer?] = [] - for rank in ranks { - dims.append(dimsPtr) - if rank >= 0 { - dimsPtr = dimsPtr.map { $0.advanced(by: Int(rank)) } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [String]) { + // Collect all the strings' utf8 bytes into a single array so that we can + // address all the strings with a single + // `flattenedStringBytes.withUnsafeBufferPointer`. + var flattenedStringBytes: [CChar] = [] + var lengths: [Int] = [] + for string in value { + // Don't include the null-terminator because TFE_OpSetAttrStringList uses + // lengths instead of null-terminators. + let stringBytes = string.utf8CString.dropLast() + flattenedStringBytes.append(contentsOf: stringBytes) + lengths.append(stringBytes.count) + } + + // Calculate the addresses of all the strings within our single buffer, and then call + // TFE_OpSetAttrStringList. + flattenedStringBytes.withUnsafeBufferPointer { flattenedStringBytesBuffer in + var stringAddrs: [UnsafeRawPointer?] = [] + var currentStringAddr = + flattenedStringBytesBuffer.baseAddress.map(UnsafeRawPointer.init) + for length in lengths { + stringAddrs.append(currentStringAddr) + currentStringAddr = currentStringAddr?.advanced(by: length) + } + + stringAddrs.withUnsafeBufferPointer { stringAddrsBuffer in + lengths.withUnsafeBufferPointer { lengthsBuffer in + TFE_OpSetAttrStringList(op, name, stringAddrsBuffer.baseAddress, + lengthsBuffer.baseAddress, Int32(value.count)) + } + } } - } - dims.withUnsafeMutableBufferPointer { dimsBuffer in - ranks.withUnsafeBufferPointer { ranksBuffer in - TFE_OpSetAttrShapeList( - op, name, dimsBuffer.baseAddress, ranksBuffer.baseAddress, - Int32(ranksBuffer.count), status) + } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [TensorDataType]) { + value.withUnsafeBufferPointer { buffer in + buffer.withMemoryRebound(to: TF_DataType.self) { reboundBuffer in + TFE_OpSetAttrTypeList( + op, name, reboundBuffer.baseAddress, Int32(reboundBuffer.count)) + } } - } } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: [TensorShape?]) { - let flattenedDims = value.flatMap { (tensorShapeOpt) -> [Int64] in - if let tensorShape = tensorShapeOpt { - return tensorShape.dimensions.map(Int64.init) - } - return [] + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [TensorShape]) { + let flattenedDims = value.flatMap { $0.dimensions.map(Int64.init) } + let ranks = value.map { Int32($0.rank) } + flattenedDims.withUnsafeBufferPointer { flattenedDimsBuffer in + var dimsPtr: UnsafePointer? = flattenedDimsBuffer.baseAddress + var dims: [UnsafePointer?] = [] + for rank in ranks { + dims.append(dimsPtr) + if rank >= 0 { + dimsPtr = dimsPtr.map { $0.advanced(by: Int(rank)) } + } + } + dims.withUnsafeMutableBufferPointer { dimsBuffer in + ranks.withUnsafeBufferPointer { ranksBuffer in + TFE_OpSetAttrShapeList( + op, name, dimsBuffer.baseAddress, ranksBuffer.baseAddress, + Int32(ranksBuffer.count), status) + } + } + } } - let ranks = value.map { shape in (shape?.rank).map(Int32.init) ?? -1 } - flattenedDims.withUnsafeBufferPointer { flattenedDimsBuffer in - var dimsPtr: UnsafePointer? = flattenedDimsBuffer.baseAddress - var dims: [UnsafePointer?] = [] - for rank in ranks { - dims.append(dimsPtr) - if rank >= 0 { - dimsPtr = dimsPtr.map { $0.advanced(by: Int(rank)) } + + @inlinable @inline(__always) + internal func updateAttribute(_ name: String, _ value: [TensorShape?]) { + let flattenedDims = value.flatMap { (tensorShapeOpt) -> [Int64] in + if let tensorShape = tensorShapeOpt { + return tensorShape.dimensions.map(Int64.init) + } + return [] } - } - dims.withUnsafeMutableBufferPointer { dimsBuffer in - ranks.withUnsafeBufferPointer { ranksBuffer in - TFE_OpSetAttrShapeList( - op, name, dimsBuffer.baseAddress, ranksBuffer.baseAddress, - Int32(ranksBuffer.count), status) + let ranks = value.map { shape in (shape?.rank).map(Int32.init) ?? -1 } + flattenedDims.withUnsafeBufferPointer { flattenedDimsBuffer in + var dimsPtr: UnsafePointer? = flattenedDimsBuffer.baseAddress + var dims: [UnsafePointer?] = [] + for rank in ranks { + dims.append(dimsPtr) + if rank >= 0 { + dimsPtr = dimsPtr.map { $0.advanced(by: Int(rank)) } + } + } + dims.withUnsafeMutableBufferPointer { dimsBuffer in + ranks.withUnsafeBufferPointer { ranksBuffer in + TFE_OpSetAttrShapeList( + op, name, dimsBuffer.baseAddress, ranksBuffer.baseAddress, + Int32(ranksBuffer.count), status) + } + } } - } } - } - - @inlinable @inline(__always) - internal func updateAttribute(_ name: String, _ value: (In) -> Out) { - _tffunc(value).utf8CString.withUnsafeBufferPointer { buffer in - // utf8CString is null-terminated; TFE_OpSetAttrFunctionName wants - // non-null-terminated. - TFE_OpSetAttrFunctionName(op, name, buffer.baseAddress, buffer.count - 1) + + @inlinable @inline(__always) + internal func updateAttribute( + _ name: String, + _ value: (In) -> Out + ) { + _tffunc(value).utf8CString.withUnsafeBufferPointer { buffer in + // utf8CString is null-terminated; TFE_OpSetAttrFunctionName wants + // non-null-terminated. + TFE_OpSetAttrFunctionName(op, name, buffer.baseAddress, buffer.count - 1) + } + } + + /// **WARNING:** After constructing a `TFE_Op`, any one of its `execute` methods must be called + /// *exactly once*. If not called, then a memory leak is introduced due to the underlying + /// TensorFlow eager op object not being freed. If called more than once, then a SEGFAULT may + /// occur due to trying to execute a TensorFlow eager op that has already been freed. + + @inlinable @inline(__always) + internal func evaluateUnsafe() -> UnsafeMutablePointer { + var count: Int32 = Int32(self.outputCount) + let buffer: UnsafeMutablePointer = + UnsafeMutablePointer.allocate(capacity: Int(count)) + _TFCOpSetDeviceFromScope(op, status) + checkOk(status) + _TFCEagerExecute(op, UnsafeMutablePointer(buffer), &count, status) + checkOk(status) + TFE_DeleteOp(op) + TF_DeleteStatus(status) + return buffer + } + + @inlinable @inline(__always) + internal func execute() { + let _ = evaluateUnsafe() } - } - - /// **WARNING:** After constructing a `TFE_Op`, any one of its `execute` methods must be called - /// *exactly once*. If not called, then a memory leak is introduced due to the underlying - /// TensorFlow eager op object not being freed. If called more than once, then a SEGFAULT may - /// occur due to trying to execute a TensorFlow eager op that has already been freed. - - @inlinable @inline(__always) - internal func evaluateUnsafe() -> UnsafeMutablePointer { - var count: Int32 = Int32(self.outputCount) - let buffer: UnsafeMutablePointer = - UnsafeMutablePointer.allocate(capacity: Int(count)) - _TFCOpSetDeviceFromScope(op, status) - checkOk(status) - _TFCEagerExecute(op, UnsafeMutablePointer(buffer), &count, status) - checkOk(status) - TFE_DeleteOp(op) - TF_DeleteStatus(status) - return buffer - } - - @inlinable @inline(__always) - internal func execute() { - let _ = evaluateUnsafe() - } %for n in range(1, 10 + 1): - @inlinable @inline(__always) - internal func execute<${", ".join(["T" + str(i) + " : TensorArrayProtocol" for i in range(n)])}>( - ${",\n ".join(["_ count" + str(i) + ": Int" for i in range(n)])} - ) -> (${", ".join(["T" + str(i) for i in range(n)])}) { - let buffer = evaluateUnsafe() + @inlinable @inline(__always) + internal func execute<${", ".join(["T" + str(i) + ": TensorArrayProtocol" for i in range(n)])}>( + ${",\n ".join(["_ count" + str(i) + ": Int" for i in range(n)])} + ) -> (${", ".join(["T" + str(i) for i in range(n)])}) { + let buffer = evaluateUnsafe() %for i in range(n): - let offset${i} = ${"Int32(0)" if i == 0 else "offset" + str(i - 1) + " + Int32(count" + str(i - 1) + ")"} + let offset${i} = ${"Int32(0)" if i == 0 else "offset" + str(i - 1) + " + Int32(count" + str(i - 1) + ")"} %end - let result = ( - ${",\n ".join(["T" + str(i) + ".init(_owning: buffer.advanced(by: Int(offset" + str(i) + ")), count: count" + str(i) + ")" for i in range(n)])}) - buffer.deallocate() - return result - } + let result = ( + ${",\n ".join(["T" + str(i) + ".init(_owning: buffer.advanced(by: Int(offset" + str(i) + ")), count: count" + str(i) + ")" for i in range(n)])}) + buffer.deallocate() + return result + } %end } diff --git a/Sources/DeepLearning/Bindings/RawOpsGenerated.swift b/Sources/DeepLearning/Bindings/RawOpsGenerated.swift index 0006cad9a..3dbf89c99 100644 --- a/Sources/DeepLearning/Bindings/RawOpsGenerated.swift +++ b/Sources/DeepLearning/Bindings/RawOpsGenerated.swift @@ -18,465 +18,465 @@ import CTensorFlow @inlinable @inline(__always) func makeOp(_ name: String, _ nOutputs: Int) -> TFTensorOperation { - _ExecutionContext.makeOp(name, nOutputs) + _ExecutionContext.makeOp(name, nOutputs) } public enum Raw { -static let generatedTensorFlowVersion = "1.14.1-dev20190516" -static let generatedTensorFlowGitVersion = "v1.12.1-2080-g4e3a33a1d2" +static let generatedTensorFlowVersion = "1.14.1-dev20190421" +static let generatedTensorFlowGitVersion = "v1.12.1-149-gd57b65578c" // @_frozen // SR-9739 public enum A { - case apples - case oranges - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .apples: return "apples" - case .oranges: return "oranges" - } + case apples + case oranges + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .apples: return "apples" + case .oranges: return "oranges" + } + } } - } } // @_frozen // SR-9739 public enum DataFormat { - case nchw - case nhwc - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .nchw: return "NCHW" - case .nhwc: return "NHWC" - } + case nchw + case nhwc + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .nchw: return "NCHW" + case .nhwc: return "NHWC" + } + } } - } } // @_frozen // SR-9739 public enum DataFormat1 { - case ncdhw - case ndhwc - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .ncdhw: return "NCDHW" - case .ndhwc: return "NDHWC" - } + case ncdhw + case ndhwc + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .ncdhw: return "NCDHW" + case .ndhwc: return "NDHWC" + } + } } - } } // @_frozen // SR-9739 public enum DataFormat4 { - case nchw - case nchwVectC - case nhwc - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .nchw: return "NCHW" - case .nchwVectC: return "NCHW_VECT_C" - case .nhwc: return "NHWC" - } + case nchw + case nchwVectC + case nhwc + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .nchw: return "NCHW" + case .nchwVectC: return "NCHW_VECT_C" + case .nhwc: return "NHWC" + } + } } - } } // @_frozen // SR-9739 public enum DensityUnit { - case cm - case in_ - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .cm: return "cm" - case .in_: return "in" - } + case cm + case in_ + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .cm: return "cm" + case .in_: return "in" + } + } } - } } // @_frozen // SR-9739 public enum Direction { - case bidirectional - case unidirectional - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .bidirectional: return "bidirectional" - case .unidirectional: return "unidirectional" - } + case bidirectional + case unidirectional + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .bidirectional: return "bidirectional" + case .unidirectional: return "unidirectional" + } + } } - } } // @_frozen // SR-9739 public enum Errors { - case ignore - case replace - case strict - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .ignore: return "ignore" - case .replace: return "replace" - case .strict: return "strict" - } + case ignore + case replace + case strict + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .ignore: return "ignore" + case .replace: return "replace" + case .strict: return "strict" + } + } } - } } // @_frozen // SR-9739 public enum FinalOp { - case div - case id - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .div: return "Div" - case .id: return "Id" - } + case div + case id + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .div: return "Div" + case .id: return "Id" + } + } } - } } // @_frozen // SR-9739 public enum Format { - case empty - case grayscale - case rgb - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .empty: return "" - case .grayscale: return "grayscale" - case .rgb: return "rgb" - } + case empty + case grayscale + case rgb + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .empty: return "" + case .grayscale: return "grayscale" + case .rgb: return "rgb" + } + } } - } } // @_frozen // SR-9739 public enum InputMode { - case autoSelect - case linearInput - case skipInput - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .autoSelect: return "auto_select" - case .linearInput: return "linear_input" - case .skipInput: return "skip_input" - } + case autoSelect + case linearInput + case skipInput + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .autoSelect: return "auto_select" + case .linearInput: return "linear_input" + case .skipInput: return "skip_input" + } + } } - } } // @_frozen // SR-9739 public enum LossType { - case hingeLoss - case logisticLoss - case poissonLoss - case smoothHingeLoss - case squaredLoss - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .hingeLoss: return "hinge_loss" - case .logisticLoss: return "logistic_loss" - case .poissonLoss: return "poisson_loss" - case .smoothHingeLoss: return "smooth_hinge_loss" - case .squaredLoss: return "squared_loss" - } + case hingeLoss + case logisticLoss + case poissonLoss + case smoothHingeLoss + case squaredLoss + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .hingeLoss: return "hinge_loss" + case .logisticLoss: return "logistic_loss" + case .poissonLoss: return "poisson_loss" + case .smoothHingeLoss: return "smooth_hinge_loss" + case .squaredLoss: return "squared_loss" + } + } } - } } // @_frozen // SR-9739 public enum MergeOp { - case add - case max - case min - case mul - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .add: return "Add" - case .max: return "Max" - case .min: return "Min" - case .mul: return "Mul" - } + case add + case max + case min + case mul + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .add: return "Add" + case .max: return "Max" + case .min: return "Min" + case .mul: return "Mul" + } + } } - } } // @_frozen // SR-9739 public enum Method { - case bilinear - case nearest - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .bilinear: return "bilinear" - case .nearest: return "nearest" - } + case bilinear + case nearest + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .bilinear: return "bilinear" + case .nearest: return "nearest" + } + } } - } } // @_frozen // SR-9739 public enum Method3 { - case bilinear - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .bilinear: return "bilinear" - } + case bilinear + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .bilinear: return "bilinear" + } + } } - } } // @_frozen // SR-9739 public enum Mode { - case minCombined - case minFirst - case scaled - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .minCombined: return "MIN_COMBINED" - case .minFirst: return "MIN_FIRST" - case .scaled: return "SCALED" - } + case minCombined + case minFirst + case scaled + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .minCombined: return "MIN_COMBINED" + case .minFirst: return "MIN_FIRST" + case .scaled: return "SCALED" + } + } } - } } // @_frozen // SR-9739 public enum Mode5 { - case reflect - case symmetric - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .reflect: return "REFLECT" - case .symmetric: return "SYMMETRIC" - } + case reflect + case symmetric + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .reflect: return "REFLECT" + case .symmetric: return "SYMMETRIC" + } + } } - } } // @_frozen // SR-9739 public enum OutputEncoding { - case utf16Be - case utf32Be - case utf8 - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .utf16Be: return "UTF-16-BE" - case .utf32Be: return "UTF-32-BE" - case .utf8: return "UTF-8" - } + case utf16Be + case utf32Be + case utf8 + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .utf16Be: return "UTF-16-BE" + case .utf32Be: return "UTF-32-BE" + case .utf8: return "UTF-8" + } + } } - } } // @_frozen // SR-9739 public enum Padding { - case same - case valid - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .same: return "SAME" - case .valid: return "VALID" - } + case same + case valid + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .same: return "SAME" + case .valid: return "VALID" + } + } } - } } // @_frozen // SR-9739 public enum Padding2 { - case explicit - case same - case valid - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .explicit: return "EXPLICIT" - case .same: return "SAME" - case .valid: return "VALID" - } + case explicit + case same + case valid + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .explicit: return "EXPLICIT" + case .same: return "SAME" + case .valid: return "VALID" + } + } } - } } // @_frozen // SR-9739 public enum Reduction { - case max - case min - case prod - case sum - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .max: return "max" - case .min: return "min" - case .prod: return "prod" - case .sum: return "sum" - } + case max + case min + case prod + case sum + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .max: return "max" + case .min: return "min" + case .prod: return "prod" + case .sum: return "sum" + } + } } - } } // @_frozen // SR-9739 public enum RnnMode { - case gru - case lstm - case rnnRelu - case rnnTanh - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .gru: return "gru" - case .lstm: return "lstm" - case .rnnRelu: return "rnn_relu" - case .rnnTanh: return "rnn_tanh" - } + case gru + case lstm + case rnnRelu + case rnnTanh + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .gru: return "gru" + case .lstm: return "lstm" + case .rnnRelu: return "rnn_relu" + case .rnnTanh: return "rnn_tanh" + } + } } - } } // @_frozen // SR-9739 public enum RoundMode { - case halfToEven - case halfUp - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .halfToEven: return "HALF_TO_EVEN" - case .halfUp: return "HALF_UP" - } + case halfToEven + case halfUp + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .halfToEven: return "HALF_TO_EVEN" + case .halfUp: return "HALF_UP" + } + } } - } } // @_frozen // SR-9739 public enum RoundMode6 { - case halfAwayFromZero - case halfToEven - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .halfAwayFromZero: return "HALF_AWAY_FROM_ZERO" - case .halfToEven: return "HALF_TO_EVEN" - } + case halfAwayFromZero + case halfToEven + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .halfAwayFromZero: return "HALF_AWAY_FROM_ZERO" + case .halfToEven: return "HALF_TO_EVEN" + } + } } - } } // @_frozen // SR-9739 public enum SplitType { - case inequality - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .inequality: return "inequality" - } + case inequality + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .inequality: return "inequality" + } + } } - } } // @_frozen // SR-9739 public enum Unit { - case byte - case utf8Char - - @inlinable - var cName: String { - @inline(__always) - get { - switch self { - case .byte: return "BYTE" - case .utf8Char: return "UTF8_CHAR" - } + case byte + case utf8Char + + @inlinable + var cName: String { + @inline(__always) + get { + switch self { + case .byte: return "BYTE" + case .utf8Char: return "UTF8_CHAR" + } + } } - } } @@ -484,9 +484,9 @@ public enum Unit { public static func a( ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("A", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("A", nOutputs) + + return op.execute(Int(1)) } /// Raise a exception to abort the process when called. @@ -499,14 +499,14 @@ public static func a( /// - Attr error_msg: A string which is the message associated with the exception. @inlinable @inline(__always) public static func abort( - errorMsg: String, - exitWithoutError: Bool = false + errorMsg: String, + exitWithoutError: Bool = false ) { let nOutputs = 0 - let op = makeOp("Abort", nOutputs) - op.updateAttribute("error_msg", errorMsg) - op.updateAttribute("exit_without_error", exitWithoutError) - op.execute() + let op = makeOp("Abort", nOutputs) + op.updateAttribute("error_msg", errorMsg) + op.updateAttribute("exit_without_error", exitWithoutError) + op.execute() } /// Computes the absolute value of a tensor. @@ -516,13 +516,13 @@ public static func abort( /// an output element, this operation computes \\(y = |x|\\). @inlinable @inline(__always) public static func abs( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Abs", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Abs", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Returns the element-wise sum of a list of tensors. @@ -541,40 +541,40 @@ public static func abs( /// - Attr shape: Shape of elements of `inputs`. @inlinable @inline(__always) public static func accumulateNV2( - inputs: [Tensor], - shape: TensorShape? + inputs: [Tensor], + shape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AccumulateNV2", nOutputs) - op.updateAttribute("N", inputs.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("shape", shape) - op.addInputList(inputs) - return op.execute(Int(1)) + let op = makeOp("AccumulateNV2", nOutputs) + op.updateAttribute("N", inputs.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.addInputList(inputs) + return op.execute(Int(1)) } /// Computes acos of x element-wise. @inlinable @inline(__always) public static func acos( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Acos", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Acos", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes inverse hyperbolic cosine of x element-wise. @inlinable @inline(__always) public static func acosh( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Acosh", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Acosh", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Returns x + y element-wise. @@ -583,15 +583,15 @@ public static func acosh( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func add( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Add", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Add", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns x + y element-wise. @@ -600,15 +600,15 @@ public static func add( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func add( - _ x: StringTensor, - _ y: StringTensor + _ x: StringTensor, + _ y: StringTensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("Add", nOutputs) - op.updateAttribute("T", TensorDataType(TF_STRING)) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Add", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Add an `N`-minibatch `SparseTensor` to a `SparseTensorsMap`, return `N` handles. @@ -637,36 +637,36 @@ public static func add( /// `TakeManySparseFromTensorsMap`. Ensure the Operations are colocated. /// /// - Parameters: -/// - sparse_indices: 2-D. The `indices` of the minibatch `SparseTensor`. -/// `sparse_indices[:, 0]` must be ordered values in `[0, N)`. -/// - sparse_values: 1-D. The `values` of the minibatch `SparseTensor`. -/// - sparse_shape: 1-D. The `shape` of the minibatch `SparseTensor`. -/// The minibatch size `N == sparse_shape[0]`. +/// - sparse_indices: 2-D. The `indices` of the minibatch `SparseTensor`. +/// `sparse_indices[:, 0]` must be ordered values in `[0, N)`. +/// - sparse_values: 1-D. The `values` of the minibatch `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the minibatch `SparseTensor`. +/// The minibatch size `N == sparse_shape[0]`. /// /// - Attrs: -/// - container: The container name for the `SparseTensorsMap` created by this op. -/// - shared_name: The shared name for the `SparseTensorsMap` created by this op. -/// If blank, the new Operation's unique name is used. +/// - container: The container name for the `SparseTensorsMap` created by this op. +/// - shared_name: The shared name for the `SparseTensorsMap` created by this op. +/// If blank, the new Operation's unique name is used. /// /// - Output sparse_handles: 1-D. The handles of the `SparseTensor` now stored in the -/// `SparseTensorsMap`. Shape: `[N]`. +/// `SparseTensorsMap`. Shape: `[N]`. @inlinable @inline(__always) public static func addManySparseToTensorsMap( - sparseIndices: Tensor, - sparseValues: Tensor, - sparseShape: Tensor, - container: String, - sharedName: String + sparseIndices: Tensor, + sparseValues: Tensor, + sparseShape: Tensor, + container: String, + sharedName: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AddManySparseToTensorsMap", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.addInput(sparseIndices) - op.addInput(sparseValues) - op.addInput(sparseShape) - return op.execute(Int(1)) + let op = makeOp("AddManySparseToTensorsMap", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(sparseIndices) + op.addInput(sparseValues) + op.addInput(sparseShape) + return op.execute(Int(1)) } /// Add all input tensors element wise. @@ -674,14 +674,14 @@ public static func addManySparseToTensorsMap( /// - Parameter inputs: Must all be the same size and shape. @inlinable @inline(__always) public static func addN( - inputs: [Tensor] + inputs: [Tensor] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AddN", nOutputs) - op.updateAttribute("N", inputs.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInputList(inputs) - return op.execute(Int(1)) + let op = makeOp("AddN", nOutputs) + op.updateAttribute("N", inputs.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInputList(inputs) + return op.execute(Int(1)) } /// Add a `SparseTensor` to a `SparseTensorsMap` return its handle. @@ -702,34 +702,34 @@ public static func addN( /// `TakeManySparseFromTensorsMap`. Ensure the Operations are colocated. /// /// - Parameters: -/// - sparse_indices: 2-D. The `indices` of the `SparseTensor`. -/// - sparse_values: 1-D. The `values` of the `SparseTensor`. -/// - sparse_shape: 1-D. The `shape` of the `SparseTensor`. +/// - sparse_indices: 2-D. The `indices` of the `SparseTensor`. +/// - sparse_values: 1-D. The `values` of the `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the `SparseTensor`. /// /// - Attrs: -/// - container: The container name for the `SparseTensorsMap` created by this op. -/// - shared_name: The shared name for the `SparseTensorsMap` created by this op. -/// If blank, the new Operation's unique name is used. +/// - container: The container name for the `SparseTensorsMap` created by this op. +/// - shared_name: The shared name for the `SparseTensorsMap` created by this op. +/// If blank, the new Operation's unique name is used. /// /// - Output sparse_handle: 0-D. The handle of the `SparseTensor` now stored in the -/// `SparseTensorsMap`. +/// `SparseTensorsMap`. @inlinable @inline(__always) public static func addSparseToTensorsMap( - sparseIndices: Tensor, - sparseValues: Tensor, - sparseShape: Tensor, - container: String, - sharedName: String + sparseIndices: Tensor, + sparseValues: Tensor, + sparseShape: Tensor, + container: String, + sharedName: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AddSparseToTensorsMap", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.addInput(sparseIndices) - op.addInput(sparseValues) - op.addInput(sparseShape) - return op.execute(Int(1)) + let op = makeOp("AddSparseToTensorsMap", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(sparseIndices) + op.addInput(sparseValues) + op.addInput(sparseShape) + return op.execute(Int(1)) } /// Returns x + y element-wise. @@ -738,33 +738,33 @@ public static func addSparseToTensorsMap( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func addV2( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AddV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("AddV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Deprecated. Disallowed in GraphDef version >= 2. @inlinable @inline(__always) public static func adjustContrast( - images: Tensor, - contrastFactor: Tensor, - minValue: Tensor, - maxValue: Tensor + images: Tensor, + contrastFactor: Tensor, + minValue: Tensor, + maxValue: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AdjustContrast", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(images) - op.addInput(contrastFactor) - op.addInput(minValue) - op.addInput(maxValue) - return op.execute(Int(1)) + let op = makeOp("AdjustContrast", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + op.addInput(contrastFactor) + op.addInput(minValue) + op.addInput(maxValue) + return op.execute(Int(1)) } /// Adjust the contrast of one or more images. @@ -780,21 +780,21 @@ public static func adjustContrast( /// `(x - mean) * contrast_factor + mean`. /// /// - Parameters: -/// - images: Images to adjust. At least 3-D. -/// - contrast_factor: A float multiplier for adjusting contrast. +/// - images: Images to adjust. At least 3-D. +/// - contrast_factor: A float multiplier for adjusting contrast. /// /// - Output output: The contrast-adjusted image or images. @inlinable @inline(__always) public static func adjustContrastv2( - images: Tensor, - contrastFactor: Tensor + images: Tensor, + contrastFactor: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AdjustContrastv2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(images) - op.addInput(contrastFactor) - return op.execute(Int(1)) + let op = makeOp("AdjustContrastv2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + op.addInput(contrastFactor) + return op.execute(Int(1)) } /// Adjust the hue of one or more images. @@ -807,21 +807,21 @@ public static func adjustContrastv2( /// and then remapped back to RGB colorspace. /// /// - Parameters: -/// - images: Images to adjust. At least 3-D. -/// - delta: A float delta to add to the hue. +/// - images: Images to adjust. At least 3-D. +/// - delta: A float delta to add to the hue. /// /// - Output output: The hue-adjusted image or images. @inlinable @inline(__always) public static func adjustHue( - images: Tensor, - delta: Tensor + images: Tensor, + delta: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AdjustHue", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(images) - op.addInput(delta) - return op.execute(Int(1)) + let op = makeOp("AdjustHue", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + op.addInput(delta) + return op.execute(Int(1)) } /// Adjust the saturation of one or more images. @@ -834,21 +834,21 @@ public static func adjustHue( /// values, and then remapped back to RGB colorspace. /// /// - Parameters: -/// - images: Images to adjust. At least 3-D. -/// - scale: A float scale to add to the saturation. +/// - images: Images to adjust. At least 3-D. +/// - scale: A float scale to add to the saturation. /// /// - Output output: The hue-adjusted image or images. @inlinable @inline(__always) public static func adjustSaturation( - images: Tensor, - scale: Tensor + images: Tensor, + scale: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AdjustSaturation", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(images) - op.addInput(scale) - return op.execute(Int(1)) + let op = makeOp("AdjustSaturation", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + op.addInput(scale) + return op.execute(Int(1)) } /// Computes the "logical and" of elements across dimensions of a tensor. @@ -859,26 +859,26 @@ public static func adjustSaturation( /// retained with length 1. /// /// - Parameters: -/// - input: The tensor to reduce. -/// - reduction_indices: The dimensions to reduce. Must be in the range -/// `[-rank(input), rank(input))`. +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. /// /// - Attr keep_dims: If true, retain reduced dimensions with length 1. /// /// - Output output: The reduced tensor. @inlinable @inline(__always) public static func all( - _ input: Tensor, - reductionIndices: Tensor, - keepDims: Bool = false + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("All", nOutputs) - op.updateAttribute("keep_dims", keepDims) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(input) - op.addInput(reductionIndices) - return op.execute(Int(1)) + let op = makeOp("All", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) } /// Generates labels for candidate sampling with a learned unigram distribution. @@ -894,47 +894,47 @@ public static func all( /// true labels. /// /// - Parameter true_classes: A batch_size * num_true matrix, in which each row contains the -/// IDs of the num_true target_classes in the corresponding original label. +/// IDs of the num_true target_classes in the corresponding original label. /// /// - Attrs: -/// - num_true: Number of true labels per context. -/// - num_sampled: Number of candidates to produce. -/// - unique: If unique is true, we sample with rejection, so that all sampled -/// candidates in a batch are unique. This requires some approximation to -/// estimate the post-rejection sampling probabilities. -/// - seed: If either seed or seed2 are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: An second seed to avoid seed collision. +/// - num_true: Number of true labels per context. +/// - num_sampled: Number of candidates to produce. +/// - unique: If unique is true, we sample with rejection, so that all sampled +/// candidates in a batch are unique. This requires some approximation to +/// estimate the post-rejection sampling probabilities. +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. /// /// - Outputs: -/// - sampled_candidates: A vector of length num_sampled, in which each element is -/// the ID of a sampled candidate. -/// - true_expected_count: A batch_size * num_true matrix, representing -/// the number of times each candidate is expected to occur in a batch -/// of sampled candidates. If unique=true, then this is a probability. -/// - sampled_expected_count: A vector of length num_sampled, for each sampled -/// candidate representing the number of times the candidate is expected -/// to occur in a batch of sampled candidates. If unique=true, then this is a -/// probability. +/// - sampled_candidates: A vector of length num_sampled, in which each element is +/// the ID of a sampled candidate. +/// - true_expected_count: A batch_size * num_true matrix, representing +/// the number of times each candidate is expected to occur in a batch +/// of sampled candidates. If unique=true, then this is a probability. +/// - sampled_expected_count: A vector of length num_sampled, for each sampled +/// candidate representing the number of times the candidate is expected +/// to occur in a batch of sampled candidates. If unique=true, then this is a +/// probability. @inlinable @inline(__always) public static func allCandidateSampler( - trueClasses: Tensor, - numTrue: Int64, - numSampled: Int64, - unique: Bool, - seed: Int64 = 0, - seed2: Int64 = 0 + trueClasses: Tensor, + numTrue: Int64, + numSampled: Int64, + unique: Bool, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> (sampledCandidates: Tensor, trueExpectedCount: Tensor, sampledExpectedCount: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("AllCandidateSampler", nOutputs) - op.updateAttribute("num_true", numTrue) - op.updateAttribute("num_sampled", numSampled) - op.updateAttribute("unique", unique) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.addInput(trueClasses) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("AllCandidateSampler", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("num_sampled", numSampled) + op.updateAttribute("unique", unique) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + return op.execute(Int(1), Int(1), Int(1)) } /// An Op to exchange data across TPU replicas. @@ -957,36 +957,36 @@ public static func allCandidateSampler( /// replica 1's output: `[[B], [D]]` /// /// - Parameters: -/// - input: The local input to the sum. -/// - group_assignment: An int32 tensor with shape -/// [num_groups, num_replicas_per_group]. `group_assignment[i]` represents the -/// replica ids in the ith subgroup. +/// - input: The local input to the sum. +/// - group_assignment: An int32 tensor with shape +/// [num_groups, num_replicas_per_group]. `group_assignment[i]` represents the +/// replica ids in the ith subgroup. /// /// - Attrs: -/// - T: The type of elements to be exchanged. -/// - concat_dimension: The dimension number to concatenate. -/// - split_dimension: The dimension number to split. -/// - split_count: The number of splits, this number must equal to the sub-group -/// size(group_assignment.get_shape()[1]) +/// - T: The type of elements to be exchanged. +/// - concat_dimension: The dimension number to concatenate. +/// - split_dimension: The dimension number to split. +/// - split_count: The number of splits, this number must equal to the sub-group +/// size(group_assignment.get_shape()[1]) /// /// - Output output: The exchanged result. @inlinable @inline(__always) public static func allToAll( - _ input: Tensor, - groupAssignment: Tensor, - concatDimension: Int64, - splitDimension: Int64, - splitCount: Int64 + _ input: Tensor, + groupAssignment: Tensor, + concatDimension: Int64, + splitDimension: Int64, + splitCount: Int64 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AllToAll", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("concat_dimension", concatDimension) - op.updateAttribute("split_dimension", splitDimension) - op.updateAttribute("split_count", splitCount) - op.addInput(input) - op.addInput(groupAssignment) - return op.execute(Int(1)) + let op = makeOp("AllToAll", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("concat_dimension", concatDimension) + op.updateAttribute("split_dimension", splitDimension) + op.updateAttribute("split_count", splitCount) + op.addInput(input) + op.addInput(groupAssignment) + return op.execute(Int(1)) } /// Returns the argument of a complex number. @@ -1013,52 +1013,52 @@ public static func angle< T: TensorFlowScalar, Tout: FloatingPoint & TensorFlowScalar >( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Angle", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tout", Tout.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Angle", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// A container for an iterator resource. /// /// - Output handle: A handle to the iterator that can be passed to a "MakeIterator" or -/// "IteratorGetNext" op. In contrast to Iterator, AnonymousIterator prevents -/// resource sharing by name, and does not keep a reference to the resource -/// container. +/// "IteratorGetNext" op. In contrast to Iterator, AnonymousIterator prevents +/// resource sharing by name, and does not keep a reference to the resource +/// container. @inlinable @inline(__always) public static func anonymousIterator( - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("AnonymousIterator", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - return op.execute(Int(1)) + let op = makeOp("AnonymousIterator", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + return op.execute(Int(1)) } /// A container for an iterator resource. /// /// - Outputs: -/// - handle: A handle to the iterator that can be passed to a "MakeIterator" or -/// "IteratorGetNext" op. In contrast to Iterator, AnonymousIterator prevents -/// resource sharing by name, and does not keep a reference to the resource -/// container. -/// - deleter: A variant deleter that should be passed into the op that deletes the iterator. +/// - handle: A handle to the iterator that can be passed to a "MakeIterator" or +/// "IteratorGetNext" op. In contrast to Iterator, AnonymousIterator prevents +/// resource sharing by name, and does not keep a reference to the resource +/// container. +/// - deleter: A variant deleter that should be passed into the op that deletes the iterator. @inlinable @inline(__always) public static func anonymousIteratorV2( - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> (handle: ResourceHandle, deleter: VariantHandle) { let nOutputs = Int(1) + Int(1) - let op = makeOp("AnonymousIteratorV2", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - return op.execute(Int(1), Int(1)) + let op = makeOp("AnonymousIteratorV2", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + return op.execute(Int(1), Int(1)) } /// Computes the "logical or" of elements across dimensions of a tensor. @@ -1069,42 +1069,42 @@ public static func anonymousIteratorV2( /// retained with length 1. /// /// - Parameters: -/// - input: The tensor to reduce. -/// - reduction_indices: The dimensions to reduce. Must be in the range -/// `[-rank(input), rank(input))`. +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. /// /// - Attr keep_dims: If true, retain reduced dimensions with length 1. /// /// - Output output: The reduced tensor. @inlinable @inline(__always) public static func any( - _ input: Tensor, - reductionIndices: Tensor, - keepDims: Bool = false + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Any", nOutputs) - op.updateAttribute("keep_dims", keepDims) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(input) - op.addInput(reductionIndices) - return op.execute(Int(1)) + let op = makeOp("Any", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) } /// Returns the truth value of abs(x-y) < tolerance element-wise. @inlinable @inline(__always) public static func approximateEqual( - _ x: Tensor, - _ y: Tensor, - tolerance: Double = 1e-05 + _ x: Tensor, + _ y: Tensor, + tolerance: Double = 1e-05 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ApproximateEqual", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("tolerance", tolerance) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("ApproximateEqual", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("tolerance", tolerance) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns the index with the largest value across dimensions of a tensor. @@ -1122,25 +1122,25 @@ public static func approximateEqual( /// ``` /// /// - Parameter dimension: int32 or int64, must be in the range `[-rank(input), rank(input))`. -/// Describes which dimension of the input Tensor to reduce across. For vectors, -/// use dimension = 0. +/// Describes which dimension of the input Tensor to reduce across. For vectors, +/// use dimension = 0. @inlinable @inline(__always) public static func argMax< T: Numeric & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar, OutputType: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - dimension: Tensor + _ input: Tensor, + dimension: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ArgMax", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.updateAttribute("output_type", OutputType.tensorFlowDataType) - op.addInput(input) - op.addInput(dimension) - return op.execute(Int(1)) + let op = makeOp("ArgMax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("output_type", OutputType.tensorFlowDataType) + op.addInput(input) + op.addInput(dimension) + return op.execute(Int(1)) } /// Returns the index with the smallest value across dimensions of a tensor. @@ -1158,25 +1158,25 @@ public static func argMax< /// ``` /// /// - Parameter dimension: int32 or int64, must be in the range `[-rank(input), rank(input))`. -/// Describes which dimension of the input Tensor to reduce across. For vectors, -/// use dimension = 0. +/// Describes which dimension of the input Tensor to reduce across. For vectors, +/// use dimension = 0. @inlinable @inline(__always) public static func argMin< T: Numeric & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar, OutputType: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - dimension: Tensor + _ input: Tensor, + dimension: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ArgMin", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.updateAttribute("output_type", OutputType.tensorFlowDataType) - op.addInput(input) - op.addInput(dimension) - return op.execute(Int(1)) + let op = makeOp("ArgMin", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("output_type", OutputType.tensorFlowDataType) + op.addInput(input) + op.addInput(dimension) + return op.execute(Int(1)) } /// Converts each entry in the given tensor to strings. Supports many numeric @@ -1184,35 +1184,35 @@ public static func argMin< /// types and boolean. /// /// - Attrs: -/// - precision: The post-decimal precision to use for floating point numbers. -/// Only used if precision > -1. -/// - scientific: Use scientific notation for floating point numbers. -/// - shortest: Use shortest representation (either scientific or standard) for -/// floating point numbers. -/// - width: Pad pre-decimal numbers to this width. -/// Applies to both floating point and integer numbers. -/// Only used if width > -1. -/// - fill: The value to pad if width > -1. If empty, pads with spaces. -/// Another typical value is '0'. String cannot be longer than 1 character. +/// - precision: The post-decimal precision to use for floating point numbers. +/// Only used if precision > -1. +/// - scientific: Use scientific notation for floating point numbers. +/// - shortest: Use shortest representation (either scientific or standard) for +/// floating point numbers. +/// - width: Pad pre-decimal numbers to this width. +/// Applies to both floating point and integer numbers. +/// Only used if width > -1. +/// - fill: The value to pad if width > -1. If empty, pads with spaces. +/// Another typical value is '0'. String cannot be longer than 1 character. @inlinable @inline(__always) public static func asString( - _ input: Tensor, - precision: Int64 = -1, - scientific: Bool = false, - shortest: Bool = false, - width: Int64 = -1, - fill: String + _ input: Tensor, + precision: Int64 = -1, + scientific: Bool = false, + shortest: Bool = false, + width: Int64 = -1, + fill: String ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("AsString", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("precision", precision) - op.updateAttribute("scientific", scientific) - op.updateAttribute("shortest", shortest) - op.updateAttribute("width", width) - op.updateAttribute("fill", fill) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("AsString", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("precision", precision) + op.updateAttribute("scientific", scientific) + op.updateAttribute("shortest", shortest) + op.updateAttribute("width", width) + op.updateAttribute("fill", fill) + op.addInput(input) + return op.execute(Int(1)) } /// Computes the trignometric inverse sine of x element-wise. @@ -1235,25 +1235,25 @@ public static func asString( /// @inlinable @inline(__always) public static func asin( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Asin", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Asin", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes inverse hyperbolic sine of x element-wise. @inlinable @inline(__always) public static func asinh( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Asinh", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Asinh", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Asserts that the given condition is true. @@ -1262,23 +1262,23 @@ public static func asinh( /// `summarize` determines how many entries of the tensors to print. /// /// - Parameters: -/// - condition: The condition to evaluate. -/// - data: The tensors to print out when condition is false. +/// - condition: The condition to evaluate. +/// - data: The tensors to print out when condition is false. /// /// - Attr summarize: Print this many entries of each tensor. @inlinable @inline(__always) public static func assert( - condition: Tensor, - data: T, - summarize: Int64 = 3 + condition: Tensor, + data: T, + summarize: Int64 = 3 ) { let nOutputs = 0 - let op = makeOp("Assert", nOutputs) - op.updateAttribute("T", data._typeList) - op.updateAttribute("summarize", summarize) - op.addInput(condition) - op.addInputList(data) - op.execute() + let op = makeOp("Assert", nOutputs) + op.updateAttribute("T", data._typeList) + op.updateAttribute("summarize", summarize) + op.addInput(condition) + op.addInputList(data) + op.execute() } /// Adds a value to the current value of a variable. @@ -1287,21 +1287,21 @@ public static func assert( /// see the incremented value or a subsequent newer one. /// /// - Parameters: -/// - resource: handle to the resource in which to store the variable. -/// - value: the value by which the variable will be incremented. +/// - resource: handle to the resource in which to store the variable. +/// - value: the value by which the variable will be incremented. /// /// - Attr dtype: the dtype of the value. @inlinable @inline(__always) public static func assignAddVariableOp( - resource: ResourceHandle, - value: Tensor + resource: ResourceHandle, + value: Tensor ) { let nOutputs = 0 - let op = makeOp("AssignAddVariableOp", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(resource) - op.addInput(value) - op.execute() + let op = makeOp("AssignAddVariableOp", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(value) + op.execute() } /// Subtracts a value from the current value of a variable. @@ -1310,21 +1310,21 @@ public static func assignAddVariableOp( /// see the decremented value or a subsequent newer one. /// /// - Parameters: -/// - resource: handle to the resource in which to store the variable. -/// - value: the value by which the variable will be incremented. +/// - resource: handle to the resource in which to store the variable. +/// - value: the value by which the variable will be incremented. /// /// - Attr dtype: the dtype of the value. @inlinable @inline(__always) public static func assignSubVariableOp( - resource: ResourceHandle, - value: Tensor + resource: ResourceHandle, + value: Tensor ) { let nOutputs = 0 - let op = makeOp("AssignSubVariableOp", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(resource) - op.addInput(value) - op.execute() + let op = makeOp("AssignSubVariableOp", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(value) + op.execute() } /// Assigns a new value to a variable. @@ -1333,21 +1333,21 @@ public static func assignSubVariableOp( /// this value or a subsequent newer value of the variable. /// /// - Parameters: -/// - resource: handle to the resource in which to store the variable. -/// - value: the value to set the new tensor to use. +/// - resource: handle to the resource in which to store the variable. +/// - value: the value to set the new tensor to use. /// /// - Attr dtype: the dtype of the value. @inlinable @inline(__always) public static func assignVariableOp( - resource: ResourceHandle, - value: Tensor + resource: ResourceHandle, + value: Tensor ) { let nOutputs = 0 - let op = makeOp("AssignVariableOp", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(resource) - op.addInput(value) - op.execute() + let op = makeOp("AssignVariableOp", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(value) + op.execute() } /// Computes the trignometric inverse tangent of x element-wise. @@ -1370,13 +1370,13 @@ public static func assignVariableOp( /// @inlinable @inline(__always) public static func atan( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Atan", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Atan", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes arctangent of `y/x` element-wise, respecting signs of the arguments. @@ -1388,202 +1388,202 @@ public static func atan( /// where \(r = \sqrt(x^2 + y^2) \). @inlinable @inline(__always) public static func atan2( - _ y: Tensor, - _ x: Tensor + _ y: Tensor, + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Atan2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(y) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Atan2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(x) + return op.execute(Int(1)) } /// Computes inverse hyperbolic tangent of x element-wise. @inlinable @inline(__always) public static func atanh( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Atanh", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Atanh", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func attr( - _ a: Int64 + _ a: Int64 ) { let nOutputs = 0 - let op = makeOp("Attr", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("Attr", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrBool( - _ a: Bool + _ a: Bool ) { let nOutputs = 0 - let op = makeOp("AttrBool", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("AttrBool", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrBoolList( - _ a: [Bool] + _ a: [Bool] ) { let nOutputs = 0 - let op = makeOp("AttrBoolList", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("AttrBoolList", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrDefault( - _ a: String = "banana" + _ a: String = "banana" ) { let nOutputs = 0 - let op = makeOp("AttrDefault", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("AttrDefault", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrEmptyListDefault( - _ a: [Double] + _ a: [Double] ) { let nOutputs = 0 - let op = makeOp("AttrEmptyListDefault", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("AttrEmptyListDefault", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrEnum( - _ a: A + _ a: A ) { let nOutputs = 0 - let op = makeOp("AttrEnum", nOutputs) - op.updateAttribute("a", a.cName) - op.execute() + let op = makeOp("AttrEnum", nOutputs) + op.updateAttribute("a", a.cName) + op.execute() } @inlinable @inline(__always) public static func attrEnumList( - _ a: [String] + _ a: [String] ) { let nOutputs = 0 - let op = makeOp("AttrEnumList", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("AttrEnumList", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrFloat( - _ a: Double + _ a: Double ) { let nOutputs = 0 - let op = makeOp("AttrFloat", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("AttrFloat", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrListDefault( - _ a: [Int32] = [5, 15] + _ a: [Int32] = [5, 15] ) { let nOutputs = 0 - let op = makeOp("AttrListDefault", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("AttrListDefault", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrListMin( - _ a: [Int32] + _ a: [Int32] ) { let nOutputs = 0 - let op = makeOp("AttrListMin", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("AttrListMin", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrListTypeDefault( - _ a: [Tensor], - _ b: [Tensor] + _ a: [Tensor], + _ b: [Tensor] ) { let nOutputs = 0 - let op = makeOp("AttrListTypeDefault", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("N", a.count) - op.addInputList(a) - op.addInputList(b) - op.execute() + let op = makeOp("AttrListTypeDefault", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.addInputList(b) + op.execute() } @inlinable @inline(__always) public static func attrMin( - _ a: Int64 + _ a: Int64 ) { let nOutputs = 0 - let op = makeOp("AttrMin", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("AttrMin", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrPartialShape( - _ a: TensorShape? + _ a: TensorShape? ) { let nOutputs = 0 - let op = makeOp("AttrPartialShape", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("AttrPartialShape", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrPartialShapeList( - _ a: [TensorShape?] + _ a: [TensorShape?] ) { let nOutputs = 0 - let op = makeOp("AttrPartialShapeList", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("AttrPartialShapeList", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrShape( - _ a: TensorShape? + _ a: TensorShape? ) { let nOutputs = 0 - let op = makeOp("AttrShape", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("AttrShape", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrShapeList( - _ a: [TensorShape?] + _ a: [TensorShape?] ) { let nOutputs = 0 - let op = makeOp("AttrShapeList", nOutputs) - op.updateAttribute("a", a) - op.execute() + let op = makeOp("AttrShapeList", nOutputs) + op.updateAttribute("a", a) + op.execute() } @inlinable @inline(__always) public static func attrTypeDefault( - _ a: Tensor + _ a: Tensor ) { let nOutputs = 0 - let op = makeOp("AttrTypeDefault", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - op.execute() + let op = makeOp("AttrTypeDefault", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.execute() } /// Produces a visualization of audio data over time. @@ -1617,27 +1617,27 @@ public static func attrTypeDefault( /// - Parameter input: Float representation of audio data. /// /// - Attrs: -/// - window_size: How wide the input window is in samples. For the highest efficiency -/// this should be a power of two, but other values are accepted. -/// - stride: How widely apart the center of adjacent sample windows should be. -/// - magnitude_squared: Whether to return the squared magnitude or just the -/// magnitude. Using squared magnitude can avoid extra calculations. +/// - window_size: How wide the input window is in samples. For the highest efficiency +/// this should be a power of two, but other values are accepted. +/// - stride: How widely apart the center of adjacent sample windows should be. +/// - magnitude_squared: Whether to return the squared magnitude or just the +/// magnitude. Using squared magnitude can avoid extra calculations. /// /// - Output spectrogram: 3D representation of the audio frequencies as an image. @inlinable @inline(__always) public static func audioSpectrogram( - _ input: Tensor, - windowSize: Int64, - stride: Int64, - magnitudeSquared: Bool = false + _ input: Tensor, + windowSize: Int64, + stride: Int64, + magnitudeSquared: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AudioSpectrogram", nOutputs) - op.updateAttribute("window_size", windowSize) - op.updateAttribute("stride", stride) - op.updateAttribute("magnitude_squared", magnitudeSquared) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("AudioSpectrogram", nOutputs) + op.updateAttribute("window_size", windowSize) + op.updateAttribute("stride", stride) + op.updateAttribute("magnitude_squared", magnitudeSquared) + op.addInput(input) + return op.execute(Int(1)) } /// Outputs a `Summary` protocol buffer with audio. @@ -1655,28 +1655,28 @@ public static func audioSpectrogram( /// generated sequentially as '*tag*/audio/0', '*tag*/audio/1', etc. /// /// - Parameters: -/// - tag: Scalar. Used to build the `tag` attribute of the summary values. -/// - tensor: 2-D of shape `[batch_size, frames]`. +/// - tag: Scalar. Used to build the `tag` attribute of the summary values. +/// - tensor: 2-D of shape `[batch_size, frames]`. /// /// - Attrs: -/// - sample_rate: The sample rate of the signal in hertz. -/// - max_outputs: Max number of batch elements to generate audio for. +/// - sample_rate: The sample rate of the signal in hertz. +/// - max_outputs: Max number of batch elements to generate audio for. /// /// - Output summary: Scalar. Serialized `Summary` protocol buffer. @inlinable @inline(__always) public static func audioSummary( - tag: StringTensor, - _ tensor: Tensor, - sampleRate: Double, - maxOutputs: Int64 = 3 + tag: StringTensor, + _ tensor: Tensor, + sampleRate: Double, + maxOutputs: Int64 = 3 ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("AudioSummary", nOutputs) - op.updateAttribute("sample_rate", sampleRate) - op.updateAttribute("max_outputs", maxOutputs) - op.addInput(tag) - op.addInput(tensor) - return op.execute(Int(1)) + let op = makeOp("AudioSummary", nOutputs) + op.updateAttribute("sample_rate", sampleRate) + op.updateAttribute("max_outputs", maxOutputs) + op.addInput(tag) + op.addInput(tensor) + return op.execute(Int(1)) } /// Outputs a `Summary` protocol buffer with audio. @@ -1694,27 +1694,27 @@ public static func audioSummary( /// generated sequentially as '*tag*/audio/0', '*tag*/audio/1', etc. /// /// - Parameters: -/// - tag: Scalar. Used to build the `tag` attribute of the summary values. -/// - tensor: 2-D of shape `[batch_size, frames]`. -/// - sample_rate: The sample rate of the signal in hertz. +/// - tag: Scalar. Used to build the `tag` attribute of the summary values. +/// - tensor: 2-D of shape `[batch_size, frames]`. +/// - sample_rate: The sample rate of the signal in hertz. /// /// - Attr max_outputs: Max number of batch elements to generate audio for. /// /// - Output summary: Scalar. Serialized `Summary` protocol buffer. @inlinable @inline(__always) public static func audioSummaryV2( - tag: StringTensor, - _ tensor: Tensor, - sampleRate: Tensor, - maxOutputs: Int64 = 3 + tag: StringTensor, + _ tensor: Tensor, + sampleRate: Tensor, + maxOutputs: Int64 = 3 ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("AudioSummaryV2", nOutputs) - op.updateAttribute("max_outputs", maxOutputs) - op.addInput(tag) - op.addInput(tensor) - op.addInput(sampleRate) - return op.execute(Int(1)) + let op = makeOp("AudioSummaryV2", nOutputs) + op.updateAttribute("max_outputs", maxOutputs) + op.addInput(tag) + op.addInput(tensor) + op.addInput(sampleRate) + return op.execute(Int(1)) } /// Performs average pooling on the input. @@ -1725,33 +1725,33 @@ public static func audioSummaryV2( /// - Parameter value: 4-D with shape `[batch, height, width, channels]`. /// /// - Attrs: -/// - ksize: The size of the sliding window for each dimension of `value`. -/// - strides: The stride of the sliding window for each dimension of `value`. -/// - padding: The type of padding algorithm to use. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, in_channels, in_height, in_width]. +/// - ksize: The size of the sliding window for each dimension of `value`. +/// - strides: The stride of the sliding window for each dimension of `value`. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. /// /// - Output output: The average pooled output tensor. @inlinable @inline(__always) public static func avgPool( - value: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding, - dataFormat: DataFormat = .nhwc + value: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AvgPool", nOutputs) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(value) - return op.execute(Int(1)) + let op = makeOp("AvgPool", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + return op.execute(Int(1)) } /// Performs 3D average pooling on the input. @@ -1759,123 +1759,123 @@ public static func avgPool( /// - Parameter input: Shape `[batch, depth, rows, cols, channels]` tensor to pool over. /// /// - Attrs: -/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of -/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. -/// - strides: 1-D tensor of length 5. The stride of the sliding window for each -/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. -/// - padding: The type of padding algorithm to use. -/// - data_format: The data format of the input and output data. With the -/// default format "NDHWC", the data is stored in the order of: -/// [batch, in_depth, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCDHW", the data storage order is: -/// [batch, in_channels, in_depth, in_height, in_width]. +/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of +/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. /// /// - Output output: The average pooled output tensor. @inlinable @inline(__always) public static func avgPool3D( - _ input: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding, - dataFormat: DataFormat1 = .ndhwc + _ input: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AvgPool3D", nOutputs) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("AvgPool3D", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Computes gradients of average pooling function. /// /// - Parameters: -/// - orig_input_shape: The original input dimensions. -/// - grad: Output backprop of shape `[batch, depth, rows, cols, channels]`. +/// - orig_input_shape: The original input dimensions. +/// - grad: Output backprop of shape `[batch, depth, rows, cols, channels]`. /// /// - Attrs: -/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of -/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. -/// - strides: 1-D tensor of length 5. The stride of the sliding window for each -/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. -/// - padding: The type of padding algorithm to use. -/// - data_format: The data format of the input and output data. With the -/// default format "NDHWC", the data is stored in the order of: -/// [batch, in_depth, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCDHW", the data storage order is: -/// [batch, in_channels, in_depth, in_height, in_width]. +/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of +/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. /// /// - Output output: The backprop for input. @inlinable @inline(__always) public static func avgPool3DGrad( - origInputShape: Tensor, - grad: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding, - dataFormat: DataFormat1 = .ndhwc + origInputShape: Tensor, + grad: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AvgPool3DGrad", nOutputs) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(origInputShape) - op.addInput(grad) - return op.execute(Int(1)) + let op = makeOp("AvgPool3DGrad", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInputShape) + op.addInput(grad) + return op.execute(Int(1)) } /// Computes gradients of the average pooling function. /// /// - Parameters: -/// - orig_input_shape: 1-D. Shape of the original input to `avg_pool`. -/// - grad: 4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. -/// the output of `avg_pool`. +/// - orig_input_shape: 1-D. Shape of the original input to `avg_pool`. +/// - grad: 4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. +/// the output of `avg_pool`. /// /// - Attrs: -/// - ksize: The size of the sliding window for each dimension of the input. -/// - strides: The stride of the sliding window for each dimension of the input. -/// - padding: The type of padding algorithm to use. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, in_channels, in_height, in_width]. +/// - ksize: The size of the sliding window for each dimension of the input. +/// - strides: The stride of the sliding window for each dimension of the input. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. /// /// - Output output: 4-D. Gradients w.r.t. the input of `avg_pool`. @inlinable @inline(__always) public static func avgPoolGrad( - origInputShape: Tensor, - grad: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding, - dataFormat: DataFormat = .nhwc + origInputShape: Tensor, + grad: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("AvgPoolGrad", nOutputs) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(origInputShape) - op.addInput(grad) - return op.execute(Int(1)) + let op = makeOp("AvgPoolGrad", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInputShape) + op.addInput(grad) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func b( ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("B", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("B", nOutputs) + + return op.execute(Int(1)) } /// Batches all input tensors nondeterministically. @@ -1918,101 +1918,101 @@ public static func b( /// T: the types of tensors to be batched. @inlinable @inline(__always) public static func batch( - inTensors: T, - numBatchThreads: Int64, - maxBatchSize: Int64, - maxEnqueuedBatches: Int64 = 10, - batchTimeoutMicros: Int64, - allowedBatchSizes: [Int32], - gradTimeoutMicros: Int64, - container: String, - sharedName: String, - batchingQueue: String + inTensors: T, + numBatchThreads: Int64, + maxBatchSize: Int64, + maxEnqueuedBatches: Int64 = 10, + batchTimeoutMicros: Int64, + allowedBatchSizes: [Int32], + gradTimeoutMicros: Int64, + container: String, + sharedName: String, + batchingQueue: String ) -> (batchedTensors: T, batchIndex: Tensor, id: Tensor) { let nOutputs = Int(inTensors._typeList.count) + Int(1) + Int(1) - let op = makeOp("Batch", nOutputs) - op.updateAttribute("num_batch_threads", numBatchThreads) - op.updateAttribute("max_batch_size", maxBatchSize) - op.updateAttribute("max_enqueued_batches", maxEnqueuedBatches) - op.updateAttribute("batch_timeout_micros", batchTimeoutMicros) - op.updateAttribute("allowed_batch_sizes", allowedBatchSizes) - op.updateAttribute("grad_timeout_micros", gradTimeoutMicros) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("batching_queue", batchingQueue) - op.updateAttribute("T", inTensors._typeList) - op.addInputList(inTensors) - return op.execute(Int(inTensors._typeList.count), Int(1), Int(1)) + let op = makeOp("Batch", nOutputs) + op.updateAttribute("num_batch_threads", numBatchThreads) + op.updateAttribute("max_batch_size", maxBatchSize) + op.updateAttribute("max_enqueued_batches", maxEnqueuedBatches) + op.updateAttribute("batch_timeout_micros", batchTimeoutMicros) + op.updateAttribute("allowed_batch_sizes", allowedBatchSizes) + op.updateAttribute("grad_timeout_micros", gradTimeoutMicros) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("batching_queue", batchingQueue) + op.updateAttribute("T", inTensors._typeList) + op.addInputList(inTensors) + return op.execute(Int(inTensors._typeList.count), Int(1), Int(1)) } @inlinable @inline(__always) public static func batchCholesky( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchCholesky", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("BatchCholesky", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func batchCholeskyGrad( - l: Tensor, - grad: Tensor + l: Tensor, + grad: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchCholeskyGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(l) - op.addInput(grad) - return op.execute(Int(1)) + let op = makeOp("BatchCholeskyGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(l) + op.addInput(grad) + return op.execute(Int(1)) } /// Creates a dataset that batches `batch_size` elements from `input_dataset`. /// /// - Parameter batch_size: A scalar representing the number of elements to accumulate in a -/// batch. +/// batch. @inlinable @inline(__always) public static func batchDataset( - inputDataset: VariantHandle, - batchSize: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + batchSize: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("BatchDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(batchSize) - return op.execute(Int(1)) + let op = makeOp("BatchDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(batchSize) + return op.execute(Int(1)) } /// Creates a dataset that batches `batch_size` elements from `input_dataset`. /// /// - Parameters: -/// - batch_size: A scalar representing the number of elements to accumulate in a batch. -/// - drop_remainder: A scalar representing whether the last batch should be dropped in case its size -/// is smaller than desired. +/// - batch_size: A scalar representing the number of elements to accumulate in a batch. +/// - drop_remainder: A scalar representing whether the last batch should be dropped in case its size +/// is smaller than desired. @inlinable @inline(__always) public static func batchDatasetV2( - inputDataset: VariantHandle, - batchSize: Tensor, - dropRemainder: Tensor, - parallelCopy: Bool = false, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + batchSize: Tensor, + dropRemainder: Tensor, + parallelCopy: Bool = false, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("BatchDatasetV2", nOutputs) - op.updateAttribute("parallel_copy", parallelCopy) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(batchSize) - op.addInput(dropRemainder) - return op.execute(Int(1)) + let op = makeOp("BatchDatasetV2", nOutputs) + op.updateAttribute("parallel_copy", parallelCopy) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(batchSize) + op.addInput(dropRemainder) + return op.execute(Int(1)) } /// Batches all the inputs tensors to the computation done by the function. @@ -2055,28 +2055,28 @@ public static func batchDatasetV2( /// must be a Tensor or a list/tuple of Tensors. /// /// - Parameters: -/// - in_tensors: The tensors to be batched. -/// - captured_tensors: The tensors which are captured in the function, and don't need -/// to be batched. +/// - in_tensors: The tensors to be batched. +/// - captured_tensors: The tensors which are captured in the function, and don't need +/// to be batched. /// /// - Attrs: -/// - num_batch_threads: Number of scheduling threads for processing batches of work. -/// Determines the number of batches processed in parallel. -/// - max_batch_size: Batch sizes will never be bigger than this. -/// - batch_timeout_micros: Maximum number of microseconds to wait before outputting -/// an incomplete batch. -/// - max_enqueued_batches: Maximum number of batches enqueued. Default: 10. -/// - allowed_batch_sizes: Optional list of allowed batch sizes. If left empty, does -/// nothing. Otherwise, supplies a list of batch sizes, causing the op to pad -/// batches up to one of those sizes. The entries must increase monotonically, and -/// the final entry must equal max_batch_size. -/// - container: Controls the scope of sharing of this batch. -/// - shared_name: Concurrently running instances of batch in the same device with the -/// same container and shared_name will batch their elements together. If left -/// empty, the op name will be used as the shared name. -/// - Tin: the types of tensors to be batched. -/// - Tcaptured: the types of the captured tensors. -/// - Tout: the types of the output tensors. +/// - num_batch_threads: Number of scheduling threads for processing batches of work. +/// Determines the number of batches processed in parallel. +/// - max_batch_size: Batch sizes will never be bigger than this. +/// - batch_timeout_micros: Maximum number of microseconds to wait before outputting +/// an incomplete batch. +/// - max_enqueued_batches: Maximum number of batches enqueued. Default: 10. +/// - allowed_batch_sizes: Optional list of allowed batch sizes. If left empty, does +/// nothing. Otherwise, supplies a list of batch sizes, causing the op to pad +/// batches up to one of those sizes. The entries must increase monotonically, and +/// the final entry must equal max_batch_size. +/// - container: Controls the scope of sharing of this batch. +/// - shared_name: Concurrently running instances of batch in the same device with the +/// same container and shared_name will batch their elements together. If left +/// empty, the op name will be used as the shared name. +/// - Tin: the types of tensors to be batched. +/// - Tcaptured: the types of the captured tensors. +/// - Tout: the types of the output tensors. /// /// - Output out_tensors: The output tensors. @inlinable @inline(__always) @@ -2087,35 +2087,35 @@ public static func batchFunction< Tcaptured: TensorArrayProtocol, Tout: TensorGroup >( - inTensors: Tin, - capturedTensors: Tcaptured, - f: (FIn) -> FOut, - numBatchThreads: Int64, - maxBatchSize: Int64, - batchTimeoutMicros: Int64, - maxEnqueuedBatches: Int64 = 10, - allowedBatchSizes: [Int32], - container: String, - sharedName: String, - batchingQueue: String + inTensors: Tin, + capturedTensors: Tcaptured, + f: (FIn) -> FOut, + numBatchThreads: Int64, + maxBatchSize: Int64, + batchTimeoutMicros: Int64, + maxEnqueuedBatches: Int64 = 10, + allowedBatchSizes: [Int32], + container: String, + sharedName: String, + batchingQueue: String ) -> Tout { let nOutputs = Int(Tout._typeList.count) - let op = makeOp("BatchFunction", nOutputs) - op.updateAttribute("f", f) - op.updateAttribute("num_batch_threads", numBatchThreads) - op.updateAttribute("max_batch_size", maxBatchSize) - op.updateAttribute("batch_timeout_micros", batchTimeoutMicros) - op.updateAttribute("max_enqueued_batches", maxEnqueuedBatches) - op.updateAttribute("allowed_batch_sizes", allowedBatchSizes) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("batching_queue", batchingQueue) - op.updateAttribute("Tin", inTensors._typeList) - op.updateAttribute("Tcaptured", capturedTensors._typeList) - op.updateAttribute("Tout", Tout._typeList) - op.addInputList(inTensors) - op.addInputList(capturedTensors) - return op.execute(Int(Tout._typeList.count)) + let op = makeOp("BatchFunction", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("num_batch_threads", numBatchThreads) + op.updateAttribute("max_batch_size", maxBatchSize) + op.updateAttribute("batch_timeout_micros", batchTimeoutMicros) + op.updateAttribute("max_enqueued_batches", maxEnqueuedBatches) + op.updateAttribute("allowed_batch_sizes", allowedBatchSizes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("batching_queue", batchingQueue) + op.updateAttribute("Tin", inTensors._typeList) + op.updateAttribute("Tcaptured", capturedTensors._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.addInputList(inTensors) + op.addInputList(capturedTensors) + return op.execute(Int(Tout._typeList.count)) } /// Multiplies slices of two tensors in batches. @@ -2140,29 +2140,29 @@ public static func batchFunction< /// output[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :]) /// /// - Parameters: -/// - x: 2-D or higher with shape `[..., r_x, c_x]`. -/// - y: 2-D or higher with shape `[..., r_y, c_y]`. +/// - x: 2-D or higher with shape `[..., r_x, c_x]`. +/// - y: 2-D or higher with shape `[..., r_y, c_y]`. /// /// - Attrs: -/// - adj_x: If `True`, adjoint the slices of `x`. Defaults to `False`. -/// - adj_y: If `True`, adjoint the slices of `y`. Defaults to `False`. +/// - adj_x: If `True`, adjoint the slices of `x`. Defaults to `False`. +/// - adj_y: If `True`, adjoint the slices of `y`. Defaults to `False`. /// /// - Output output: 3-D or higher with shape `[..., r_o, c_o]` @inlinable @inline(__always) public static func batchMatMul( - _ x: Tensor, - _ y: Tensor, - adjX: Bool = false, - adjY: Bool = false + _ x: Tensor, + _ y: Tensor, + adjX: Bool = false, + adjY: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchMatMul", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("adj_x", adjX) - op.updateAttribute("adj_y", adjY) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("BatchMatMul", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("adj_x", adjX) + op.updateAttribute("adj_y", adjY) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Multiplies slices of two tensors in batches. @@ -2192,152 +2192,152 @@ public static func batchMatMul( /// /// /// - Parameters: -/// - x: 2-D or higher with shape `[..., r_x, c_x]`. -/// - y: 2-D or higher with shape `[..., r_y, c_y]`. +/// - x: 2-D or higher with shape `[..., r_x, c_x]`. +/// - y: 2-D or higher with shape `[..., r_y, c_y]`. /// /// - Attrs: -/// - adj_x: If `True`, adjoint the slices of `x`. Defaults to `False`. -/// - adj_y: If `True`, adjoint the slices of `y`. Defaults to `False`. +/// - adj_x: If `True`, adjoint the slices of `x`. Defaults to `False`. +/// - adj_y: If `True`, adjoint the slices of `y`. Defaults to `False`. /// /// - Output output: 3-D or higher with shape `[..., r_o, c_o]` @inlinable @inline(__always) public static func batchMatMulV2( - _ x: Tensor, - _ y: Tensor, - adjX: Bool = false, - adjY: Bool = false + _ x: Tensor, + _ y: Tensor, + adjX: Bool = false, + adjY: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchMatMulV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("adj_x", adjX) - op.updateAttribute("adj_y", adjY) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("BatchMatMulV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("adj_x", adjX) + op.updateAttribute("adj_y", adjY) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func batchMatrixBandPart( - _ input: Tensor, - numLower: Tensor, - numUpper: Tensor + _ input: Tensor, + numLower: Tensor, + numUpper: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchMatrixBandPart", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - op.addInput(numLower) - op.addInput(numUpper) - return op.execute(Int(1)) + let op = makeOp("BatchMatrixBandPart", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(numLower) + op.addInput(numUpper) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func batchMatrixDeterminant( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchMatrixDeterminant", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("BatchMatrixDeterminant", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func batchMatrixDiag( - diagonal: Tensor + diagonal: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchMatrixDiag", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(diagonal) - return op.execute(Int(1)) + let op = makeOp("BatchMatrixDiag", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(diagonal) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func batchMatrixDiagPart( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchMatrixDiagPart", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("BatchMatrixDiagPart", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func batchMatrixInverse( - _ input: Tensor, - adjoint: Bool = false + _ input: Tensor, + adjoint: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchMatrixInverse", nOutputs) - op.updateAttribute("adjoint", adjoint) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("BatchMatrixInverse", nOutputs) + op.updateAttribute("adjoint", adjoint) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func batchMatrixSetDiag( - _ input: Tensor, - diagonal: Tensor + _ input: Tensor, + diagonal: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchMatrixSetDiag", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - op.addInput(diagonal) - return op.execute(Int(1)) + let op = makeOp("BatchMatrixSetDiag", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(diagonal) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func batchMatrixSolve( - matrix: Tensor, - rhs: Tensor, - adjoint: Bool = false + matrix: Tensor, + rhs: Tensor, + adjoint: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchMatrixSolve", nOutputs) - op.updateAttribute("adjoint", adjoint) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(matrix) - op.addInput(rhs) - return op.execute(Int(1)) + let op = makeOp("BatchMatrixSolve", nOutputs) + op.updateAttribute("adjoint", adjoint) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(matrix) + op.addInput(rhs) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func batchMatrixSolveLs( - matrix: Tensor, - rhs: Tensor, - l2Regularizer: Tensor, - fast: Bool = true + matrix: Tensor, + rhs: Tensor, + l2Regularizer: Tensor, + fast: Bool = true ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchMatrixSolveLs", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("fast", fast) - op.addInput(matrix) - op.addInput(rhs) - op.addInput(l2Regularizer) - return op.execute(Int(1)) + let op = makeOp("BatchMatrixSolveLs", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("fast", fast) + op.addInput(matrix) + op.addInput(rhs) + op.addInput(l2Regularizer) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func batchMatrixTriangularSolve( - matrix: Tensor, - rhs: Tensor, - lower: Bool = true, - adjoint: Bool = false + matrix: Tensor, + rhs: Tensor, + lower: Bool = true, + adjoint: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchMatrixTriangularSolve", nOutputs) - op.updateAttribute("lower", lower) - op.updateAttribute("adjoint", adjoint) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(matrix) - op.addInput(rhs) - return op.execute(Int(1)) + let op = makeOp("BatchMatrixTriangularSolve", nOutputs) + op.updateAttribute("lower", lower) + op.updateAttribute("adjoint", adjoint) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(matrix) + op.addInput(rhs) + return op.execute(Int(1)) } /// Batch normalization. @@ -2345,44 +2345,44 @@ public static func batchMatrixTriangularSolve( - t: Tensor, - m: Tensor, - v: Tensor, - beta: Tensor, - gamma: Tensor, - varianceEpsilon: Double, - scaleAfterNormalization: Bool -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("BatchNormWithGlobalNormalization", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("variance_epsilon", varianceEpsilon) - op.updateAttribute("scale_after_normalization", scaleAfterNormalization) - op.addInput(t) - op.addInput(m) - op.addInput(v) - op.addInput(beta) - op.addInput(gamma) - return op.execute(Int(1)) + t: Tensor, + m: Tensor, + v: Tensor, + beta: Tensor, + gamma: Tensor, + varianceEpsilon: Double, + scaleAfterNormalization: Bool +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("BatchNormWithGlobalNormalization", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("variance_epsilon", varianceEpsilon) + op.updateAttribute("scale_after_normalization", scaleAfterNormalization) + op.addInput(t) + op.addInput(m) + op.addInput(v) + op.addInput(beta) + op.addInput(gamma) + return op.execute(Int(1)) } /// Gradients for batch normalization. @@ -2390,89 +2390,89 @@ public static func batchNormWithGlobalNormalization( - t: Tensor, - m: Tensor, - v: Tensor, - gamma: Tensor, - backprop: Tensor, - varianceEpsilon: Double, - scaleAfterNormalization: Bool + t: Tensor, + m: Tensor, + v: Tensor, + gamma: Tensor, + backprop: Tensor, + varianceEpsilon: Double, + scaleAfterNormalization: Bool ) -> (dx: Tensor, dm: Tensor, dv: Tensor, db: Tensor, dg: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("BatchNormWithGlobalNormalizationGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("variance_epsilon", varianceEpsilon) - op.updateAttribute("scale_after_normalization", scaleAfterNormalization) - op.addInput(t) - op.addInput(m) - op.addInput(v) - op.addInput(gamma) - op.addInput(backprop) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("BatchNormWithGlobalNormalizationGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("variance_epsilon", varianceEpsilon) + op.updateAttribute("scale_after_normalization", scaleAfterNormalization) + op.addInput(t) + op.addInput(m) + op.addInput(v) + op.addInput(gamma) + op.addInput(backprop) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) } @inlinable @inline(__always) public static func batchSelfAdjointEig( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchSelfAdjointEig", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("BatchSelfAdjointEig", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func batchSelfAdjointEigV2( - _ input: Tensor, - computeV: Bool = true + _ input: Tensor, + computeV: Bool = true ) -> (e: Tensor, v: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("BatchSelfAdjointEigV2", nOutputs) - op.updateAttribute("compute_v", computeV) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1), Int(1)) + let op = makeOp("BatchSelfAdjointEigV2", nOutputs) + op.updateAttribute("compute_v", computeV) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) } @inlinable @inline(__always) public static func batchSvd( - _ input: Tensor, - computeUv: Bool = true, - fullMatrices: Bool = false + _ input: Tensor, + computeUv: Bool = true, + fullMatrices: Bool = false ) -> (s: Tensor, u: Tensor, v: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("BatchSvd", nOutputs) - op.updateAttribute("compute_uv", computeUv) - op.updateAttribute("full_matrices", fullMatrices) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("BatchSvd", nOutputs) + op.updateAttribute("compute_uv", computeUv) + op.updateAttribute("full_matrices", fullMatrices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1), Int(1)) } /// BatchToSpace for 4-D tensors of type T. @@ -2486,100 +2486,100 @@ public static func batchSvd( /// followed by cropping along the `height` and `width` dimensions. /// /// - Parameters: -/// - input: 4-D tensor with shape -/// `[batch*block_size*block_size, height_pad/block_size, width_pad/block_size, -/// depth]`. Note that the batch size of the input tensor must be divisible by -/// `block_size * block_size`. -/// - crops: 2-D tensor of non-negative integers with shape `[2, 2]`. It specifies -/// how many elements to crop from the intermediate result across the spatial -/// dimensions as follows: +/// - input: 4-D tensor with shape +/// `[batch*block_size*block_size, height_pad/block_size, width_pad/block_size, +/// depth]`. Note that the batch size of the input tensor must be divisible by +/// `block_size * block_size`. +/// - crops: 2-D tensor of non-negative integers with shape `[2, 2]`. It specifies +/// how many elements to crop from the intermediate result across the spatial +/// dimensions as follows: /// -/// crops = [[crop_top, crop_bottom], [crop_left, crop_right]] +/// crops = [[crop_top, crop_bottom], [crop_left, crop_right]] /// /// - Output output: 4-D with shape `[batch, height, width, depth]`, where: /// -/// height = height_pad - crop_top - crop_bottom -/// width = width_pad - crop_left - crop_right +/// height = height_pad - crop_top - crop_bottom +/// width = width_pad - crop_left - crop_right /// -/// The attr `block_size` must be greater than one. It indicates the block size. +/// The attr `block_size` must be greater than one. It indicates the block size. /// -/// Some examples: +/// Some examples: /// -/// (1) For the following input of shape `[4, 1, 1, 1]` and block_size of 2: +/// (1) For the following input of shape `[4, 1, 1, 1]` and block_size of 2: /// -/// ``` -/// [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] -/// ``` +/// ``` +/// [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] +/// ``` /// -/// The output tensor has shape `[1, 2, 2, 1]` and value: +/// The output tensor has shape `[1, 2, 2, 1]` and value: /// -/// ``` -/// x = [[[[1], [2]], [[3], [4]]]] -/// ``` +/// ``` +/// x = [[[[1], [2]], [[3], [4]]]] +/// ``` /// -/// (2) For the following input of shape `[4, 1, 1, 3]` and block_size of 2: +/// (2) For the following input of shape `[4, 1, 1, 3]` and block_size of 2: /// -/// ``` -/// [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] -/// ``` +/// ``` +/// [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] +/// ``` /// -/// The output tensor has shape `[1, 2, 2, 3]` and value: +/// The output tensor has shape `[1, 2, 2, 3]` and value: /// -/// ``` -/// x = [[[[1, 2, 3], [4, 5, 6]], -/// [[7, 8, 9], [10, 11, 12]]]] -/// ``` +/// ``` +/// x = [[[[1, 2, 3], [4, 5, 6]], +/// [[7, 8, 9], [10, 11, 12]]]] +/// ``` /// -/// (3) For the following input of shape `[4, 2, 2, 1]` and block_size of 2: +/// (3) For the following input of shape `[4, 2, 2, 1]` and block_size of 2: /// -/// ``` -/// x = [[[[1], [3]], [[9], [11]]], -/// [[[2], [4]], [[10], [12]]], -/// [[[5], [7]], [[13], [15]]], -/// [[[6], [8]], [[14], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [3]], [[9], [11]]], +/// [[[2], [4]], [[10], [12]]], +/// [[[5], [7]], [[13], [15]]], +/// [[[6], [8]], [[14], [16]]]] +/// ``` /// -/// The output tensor has shape `[1, 4, 4, 1]` and value: +/// The output tensor has shape `[1, 4, 4, 1]` and value: /// -/// ``` -/// x = [[[[1], [2], [3], [4]], -/// [[5], [6], [7], [8]], -/// [[9], [10], [11], [12]], -/// [[13], [14], [15], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]], +/// [[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` /// -/// (4) For the following input of shape `[8, 1, 2, 1]` and block_size of 2: +/// (4) For the following input of shape `[8, 1, 2, 1]` and block_size of 2: /// -/// ``` -/// x = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]], -/// [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]], +/// [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]] +/// ``` /// -/// The output tensor has shape `[2, 2, 4, 1]` and value: +/// The output tensor has shape `[2, 2, 4, 1]` and value: /// -/// ``` -/// x = [[[[1], [3]], [[5], [7]]], -/// [[[2], [4]], [[10], [12]]], -/// [[[5], [7]], [[13], [15]]], -/// [[[6], [8]], [[14], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [3]], [[5], [7]]], +/// [[[2], [4]], [[10], [12]]], +/// [[[5], [7]], [[13], [15]]], +/// [[[6], [8]], [[14], [16]]]] +/// ``` @inlinable @inline(__always) public static func batchToSpace< T: TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - crops: Tensor, - blockSize: Int64 + _ input: Tensor, + crops: Tensor, + blockSize: Int64 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchToSpace", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("block_size", blockSize) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(input) - op.addInput(crops) - return op.execute(Int(1)) + let op = makeOp("BatchToSpace", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("block_size", blockSize) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(crops) + return op.execute(Int(1)) } /// BatchToSpace for N-D tensors of type T. @@ -2592,137 +2592,137 @@ public static func batchToSpace< /// reverse of SpaceToBatch. See below for a precise description. /// /// - Parameters: -/// - input: N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`, -/// where spatial_shape has M dimensions. -/// - block_shape: 1-D with shape `[M]`, all values must be >= 1. -/// - crops: 2-D with shape `[M, 2]`, all values must be >= 0. -/// `crops[i] = [crop_start, crop_end]` specifies the amount to crop from input -/// dimension `i + 1`, which corresponds to spatial dimension `i`. It is -/// required that -/// `crop_start[i] + crop_end[i] <= block_shape[i] * input_shape[i + 1]`. +/// - input: N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`, +/// where spatial_shape has M dimensions. +/// - block_shape: 1-D with shape `[M]`, all values must be >= 1. +/// - crops: 2-D with shape `[M, 2]`, all values must be >= 0. +/// `crops[i] = [crop_start, crop_end]` specifies the amount to crop from input +/// dimension `i + 1`, which corresponds to spatial dimension `i`. It is +/// required that +/// `crop_start[i] + crop_end[i] <= block_shape[i] * input_shape[i + 1]`. /// -/// This operation is equivalent to the following steps: +/// This operation is equivalent to the following steps: /// -/// 1. Reshape `input` to `reshaped` of shape: -/// [block_shape[0], ..., block_shape[M-1], -/// batch / prod(block_shape), -/// input_shape[1], ..., input_shape[N-1]] +/// 1. Reshape `input` to `reshaped` of shape: +/// [block_shape[0], ..., block_shape[M-1], +/// batch / prod(block_shape), +/// input_shape[1], ..., input_shape[N-1]] /// -/// 2. Permute dimensions of `reshaped` to produce `permuted` of shape -/// [batch / prod(block_shape), +/// 2. Permute dimensions of `reshaped` to produce `permuted` of shape +/// [batch / prod(block_shape), /// -/// input_shape[1], block_shape[0], -/// ..., -/// input_shape[M], block_shape[M-1], +/// input_shape[1], block_shape[0], +/// ..., +/// input_shape[M], block_shape[M-1], /// -/// input_shape[M+1], ..., input_shape[N-1]] +/// input_shape[M+1], ..., input_shape[N-1]] /// -/// 3. Reshape `permuted` to produce `reshaped_permuted` of shape -/// [batch / prod(block_shape), +/// 3. Reshape `permuted` to produce `reshaped_permuted` of shape +/// [batch / prod(block_shape), /// -/// input_shape[1] * block_shape[0], -/// ..., -/// input_shape[M] * block_shape[M-1], +/// input_shape[1] * block_shape[0], +/// ..., +/// input_shape[M] * block_shape[M-1], /// -/// input_shape[M+1], -/// ..., -/// input_shape[N-1]] +/// input_shape[M+1], +/// ..., +/// input_shape[N-1]] /// -/// 4. Crop the start and end of dimensions `[1, ..., M]` of -/// `reshaped_permuted` according to `crops` to produce the output of shape: -/// [batch / prod(block_shape), +/// 4. Crop the start and end of dimensions `[1, ..., M]` of +/// `reshaped_permuted` according to `crops` to produce the output of shape: +/// [batch / prod(block_shape), /// -/// input_shape[1] * block_shape[0] - crops[0,0] - crops[0,1], -/// ..., -/// input_shape[M] * block_shape[M-1] - crops[M-1,0] - crops[M-1,1], +/// input_shape[1] * block_shape[0] - crops[0,0] - crops[0,1], +/// ..., +/// input_shape[M] * block_shape[M-1] - crops[M-1,0] - crops[M-1,1], /// -/// input_shape[M+1], ..., input_shape[N-1]] +/// input_shape[M+1], ..., input_shape[N-1]] /// -/// Some examples: +/// Some examples: /// -/// (1) For the following input of shape `[4, 1, 1, 1]`, `block_shape = [2, 2]`, and -/// `crops = [[0, 0], [0, 0]]`: +/// (1) For the following input of shape `[4, 1, 1, 1]`, `block_shape = [2, 2]`, and +/// `crops = [[0, 0], [0, 0]]`: /// -/// ``` -/// [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] -/// ``` +/// ``` +/// [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] +/// ``` /// -/// The output tensor has shape `[1, 2, 2, 1]` and value: +/// The output tensor has shape `[1, 2, 2, 1]` and value: /// -/// ``` -/// x = [[[[1], [2]], [[3], [4]]]] -/// ``` +/// ``` +/// x = [[[[1], [2]], [[3], [4]]]] +/// ``` /// -/// (2) For the following input of shape `[4, 1, 1, 3]`, `block_shape = [2, 2]`, and -/// `crops = [[0, 0], [0, 0]]`: +/// (2) For the following input of shape `[4, 1, 1, 3]`, `block_shape = [2, 2]`, and +/// `crops = [[0, 0], [0, 0]]`: /// -/// ``` -/// [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] -/// ``` +/// ``` +/// [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] +/// ``` /// -/// The output tensor has shape `[1, 2, 2, 3]` and value: +/// The output tensor has shape `[1, 2, 2, 3]` and value: /// -/// ``` -/// x = [[[[1, 2, 3], [4, 5, 6]], -/// [[7, 8, 9], [10, 11, 12]]]] -/// ``` +/// ``` +/// x = [[[[1, 2, 3], [4, 5, 6]], +/// [[7, 8, 9], [10, 11, 12]]]] +/// ``` /// -/// (3) For the following input of shape `[4, 2, 2, 1]`, `block_shape = [2, 2]`, and -/// `crops = [[0, 0], [0, 0]]`: +/// (3) For the following input of shape `[4, 2, 2, 1]`, `block_shape = [2, 2]`, and +/// `crops = [[0, 0], [0, 0]]`: /// -/// ``` -/// x = [[[[1], [3]], [[9], [11]]], -/// [[[2], [4]], [[10], [12]]], -/// [[[5], [7]], [[13], [15]]], -/// [[[6], [8]], [[14], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [3]], [[9], [11]]], +/// [[[2], [4]], [[10], [12]]], +/// [[[5], [7]], [[13], [15]]], +/// [[[6], [8]], [[14], [16]]]] +/// ``` /// -/// The output tensor has shape `[1, 4, 4, 1]` and value: +/// The output tensor has shape `[1, 4, 4, 1]` and value: /// -/// ``` -/// x = [[[[1], [2], [3], [4]], -/// [[5], [6], [7], [8]], -/// [[9], [10], [11], [12]], -/// [[13], [14], [15], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]], +/// [[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` /// -/// (4) For the following input of shape `[8, 1, 3, 1]`, `block_shape = [2, 2]`, and -/// `crops = [[0, 0], [2, 0]]`: +/// (4) For the following input of shape `[8, 1, 3, 1]`, `block_shape = [2, 2]`, and +/// `crops = [[0, 0], [2, 0]]`: /// -/// ``` -/// x = [[[[0], [1], [3]]], [[[0], [9], [11]]], -/// [[[0], [2], [4]]], [[[0], [10], [12]]], -/// [[[0], [5], [7]]], [[[0], [13], [15]]], -/// [[[0], [6], [8]]], [[[0], [14], [16]]]] -/// ``` +/// ``` +/// x = [[[[0], [1], [3]]], [[[0], [9], [11]]], +/// [[[0], [2], [4]]], [[[0], [10], [12]]], +/// [[[0], [5], [7]]], [[[0], [13], [15]]], +/// [[[0], [6], [8]]], [[[0], [14], [16]]]] +/// ``` /// -/// The output tensor has shape `[2, 2, 4, 1]` and value: +/// The output tensor has shape `[2, 2, 4, 1]` and value: /// -/// ``` -/// x = [[[[1], [2], [3], [4]], -/// [[5], [6], [7], [8]]], -/// [[[9], [10], [11], [12]], -/// [[13], [14], [15], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]]], +/// [[[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` @inlinable @inline(__always) public static func batchToSpaceND< T: TensorFlowScalar, TblockShape: BinaryInteger & TensorFlowScalar, Tcrops: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - blockShape: Tensor, - crops: Tensor + _ input: Tensor, + blockShape: Tensor, + crops: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BatchToSpaceND", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tblock_shape", TblockShape.tensorFlowDataType) - op.updateAttribute("Tcrops", Tcrops.tensorFlowDataType) - op.addInput(input) - op.addInput(blockShape) - op.addInput(crops) - return op.execute(Int(1)) + let op = makeOp("BatchToSpaceND", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tblock_shape", TblockShape.tensorFlowDataType) + op.updateAttribute("Tcrops", Tcrops.tensorFlowDataType) + op.addInput(input) + op.addInput(blockShape) + op.addInput(crops) + return op.execute(Int(1)) } /// Computes the Bessel i0e function of `x` element-wise. @@ -2733,13 +2733,13 @@ public static func batchToSpaceND< /// This function is faster and numerically stabler than `bessel_i0(x)`. @inlinable @inline(__always) public static func besselI0e( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BesselI0e", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("BesselI0e", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the Bessel i1e function of `x` element-wise. @@ -2750,13 +2750,13 @@ public static func besselI0e( /// This function is faster and numerically stabler than `bessel_i1(x)`. @inlinable @inline(__always) public static func besselI1e( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BesselI1e", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("BesselI1e", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Compute the regularized incomplete beta integral \\(I_x(a, b)\\). @@ -2776,17 +2776,17 @@ public static func besselI1e( /// beta function. @inlinable @inline(__always) public static func betainc( - _ a: Tensor, - _ b: Tensor, - _ x: Tensor + _ a: Tensor, + _ b: Tensor, + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Betainc", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - op.addInput(b) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Betainc", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(b) + op.addInput(x) + return op.execute(Int(1)) } /// Adds `bias` to `value`. @@ -2795,31 +2795,31 @@ public static func betainc( /// Broadcasting is supported, so `value` may have any number of dimensions. /// /// - Parameters: -/// - value: Any number of dimensions. -/// - bias: 1-D with size the last dimension of `value`. +/// - value: Any number of dimensions. +/// - bias: 1-D with size the last dimension of `value`. /// /// - Attr data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the bias tensor will be added to the last dimension -/// of the value tensor. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, in_channels, in_height, in_width]. -/// The tensor will be added to "in_channels", the third-to-the-last -/// dimension. +/// default format "NHWC", the bias tensor will be added to the last dimension +/// of the value tensor. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// The tensor will be added to "in_channels", the third-to-the-last +/// dimension. /// /// - Output output: Broadcasted sum of `value` and `bias`. @inlinable @inline(__always) public static func biasAdd( - value: Tensor, - bias: Tensor, - dataFormat: DataFormat = .nhwc + value: Tensor, + bias: Tensor, + dataFormat: DataFormat = .nhwc ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BiasAdd", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("data_format", dataFormat.cName) - op.addInput(value) - op.addInput(bias) - return op.execute(Int(1)) + let op = makeOp("BiasAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("data_format", dataFormat.cName) + op.addInput(value) + op.addInput(bias) + return op.execute(Int(1)) } /// The backward operation for "BiasAdd" on the "bias" tensor. @@ -2831,25 +2831,25 @@ public static func biasAdd( /// - Parameter out_backprop: Any number of dimensions. /// /// - Attr data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the bias tensor will be added to the last dimension -/// of the value tensor. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, in_channels, in_height, in_width]. -/// The tensor will be added to "in_channels", the third-to-the-last -/// dimension. +/// default format "NHWC", the bias tensor will be added to the last dimension +/// of the value tensor. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// The tensor will be added to "in_channels", the third-to-the-last +/// dimension. /// /// - Output output: 1-D with size the feature dimension of `out_backprop`. @inlinable @inline(__always) public static func biasAddGrad( - outBackprop: Tensor, - dataFormat: DataFormat = .nhwc + outBackprop: Tensor, + dataFormat: DataFormat = .nhwc ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BiasAddGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("data_format", dataFormat.cName) - op.addInput(outBackprop) - return op.execute(Int(1)) + let op = makeOp("BiasAddGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("data_format", dataFormat.cName) + op.addInput(outBackprop) + return op.execute(Int(1)) } /// Adds `bias` to `value`. @@ -2860,34 +2860,34 @@ public static func biasAddGrad( /// Broadcasting is supported, so `value` may have any number of dimensions. /// /// - Parameters: -/// - value: Any number of dimensions. -/// - bias: 1-D with size the last dimension of `value`. +/// - value: Any number of dimensions. +/// - bias: 1-D with size the last dimension of `value`. /// /// - Output output: Broadcasted sum of `value` and `bias`. @inlinable @inline(__always) public static func biasAddV1( - value: Tensor, - bias: Tensor + value: Tensor, + bias: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BiasAddV1", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(value) - op.addInput(bias) - return op.execute(Int(1)) + let op = makeOp("BiasAddV1", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + op.addInput(bias) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func binary( - _ a: Tensor, - _ b: Tensor + _ a: Tensor, + _ b: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Binary", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - op.addInput(b) - return op.execute(Int(1)) + let op = makeOp("Binary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(b) + return op.execute(Int(1)) } /// Counts the number of occurrences of each value in an integer array. @@ -2901,27 +2901,27 @@ public static func binary( /// Values in `arr` outside of the range [0, size) are ignored. /// /// - Parameters: -/// - arr: int32 `Tensor`. -/// - size: non-negative int32 scalar `Tensor`. -/// - weights: is an int32, int64, float32, or float64 `Tensor` with the same -/// shape as `arr`, or a length-0 `Tensor`, in which case it acts as all weights -/// equal to 1. +/// - arr: int32 `Tensor`. +/// - size: non-negative int32 scalar `Tensor`. +/// - weights: is an int32, int64, float32, or float64 `Tensor` with the same +/// shape as `arr`, or a length-0 `Tensor`, in which case it acts as all weights +/// equal to 1. /// /// - Output bins: 1D `Tensor` with length equal to `size`. The counts or summed weights for -/// each value in the range [0, size). +/// each value in the range [0, size). @inlinable @inline(__always) public static func bincount( - arr: Tensor, - size: Tensor, - weights: Tensor + arr: Tensor, + size: Tensor, + weights: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Bincount", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(arr) - op.addInput(size) - op.addInput(weights) - return op.execute(Int(1)) + let op = makeOp("Bincount", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(arr) + op.addInput(size) + op.addInput(weights) + return op.execute(Int(1)) } /// Bitcasts a tensor from one type to another without copying data. @@ -2980,14 +2980,14 @@ public static func bitcast< T: Numeric & TensorFlowScalar, Type: Numeric & TensorFlowScalar >( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Bitcast", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("type", Type.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Bitcast", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("type", Type.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Elementwise computes the bitwise AND of `x` and `y`. @@ -2996,15 +2996,15 @@ public static func bitcast< /// computation is performed on the underlying representations of `x` and `y`. @inlinable @inline(__always) public static func bitwiseAnd( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BitwiseAnd", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("BitwiseAnd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Elementwise computes the bitwise OR of `x` and `y`. @@ -3013,15 +3013,15 @@ public static func bitwiseAnd( /// computation is performed on the underlying representations of `x` and `y`. @inlinable @inline(__always) public static func bitwiseOr( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BitwiseOr", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("BitwiseOr", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Elementwise computes the bitwise XOR of `x` and `y`. @@ -3030,15 +3030,15 @@ public static func bitwiseOr( /// computation is performed on the underlying representations of `x` and `y`. @inlinable @inline(__always) public static func bitwiseXor( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BitwiseXor", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("BitwiseXor", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Computes the LSTM cell forward propagation for all the time steps. @@ -3062,61 +3062,61 @@ public static func bitwiseXor( /// ``` /// /// - Parameters: -/// - seq_len_max: Maximum time length actually used by this input. Outputs are padded -/// with zeros beyond this length. -/// - x: The sequence input to the LSTM, shape (timelen, batch_size, num_inputs). -/// - cs_prev: Value of the initial cell state. -/// - h_prev: Initial output of cell (to be used for peephole). -/// - w: The weight matrix. -/// - wci: The weight matrix for input gate peephole connection. -/// - wcf: The weight matrix for forget gate peephole connection. -/// - wco: The weight matrix for output gate peephole connection. -/// - b: The bias vector. +/// - seq_len_max: Maximum time length actually used by this input. Outputs are padded +/// with zeros beyond this length. +/// - x: The sequence input to the LSTM, shape (timelen, batch_size, num_inputs). +/// - cs_prev: Value of the initial cell state. +/// - h_prev: Initial output of cell (to be used for peephole). +/// - w: The weight matrix. +/// - wci: The weight matrix for input gate peephole connection. +/// - wcf: The weight matrix for forget gate peephole connection. +/// - wco: The weight matrix for output gate peephole connection. +/// - b: The bias vector. /// /// - Attrs: -/// - forget_bias: The forget gate bias. -/// - cell_clip: Value to clip the 'cs' value to. -/// - use_peephole: Whether to use peephole weights. +/// - forget_bias: The forget gate bias. +/// - cell_clip: Value to clip the 'cs' value to. +/// - use_peephole: Whether to use peephole weights. /// /// - Outputs: -/// - i: The input gate over the whole time sequence. -/// - cs: The cell state before the tanh over the whole time sequence. -/// - f: The forget gate over the whole time sequence. -/// - o: The output gate over the whole time sequence. -/// - ci: The cell input over the whole time sequence. -/// - co: The cell after the tanh over the whole time sequence. -/// - h: The output h vector over the whole time sequence. +/// - i: The input gate over the whole time sequence. +/// - cs: The cell state before the tanh over the whole time sequence. +/// - f: The forget gate over the whole time sequence. +/// - o: The output gate over the whole time sequence. +/// - ci: The cell input over the whole time sequence. +/// - co: The cell after the tanh over the whole time sequence. +/// - h: The output h vector over the whole time sequence. @inlinable @inline(__always) public static func blockLSTM( - seqLenMax: Tensor, - _ x: Tensor, - csPrev: Tensor, - hPrev: Tensor, - w: Tensor, - wci: Tensor, - wcf: Tensor, - wco: Tensor, - _ b: Tensor, - forgetBias: Double = 1, - cellClip: Double = 3, - usePeephole: Bool = false + seqLenMax: Tensor, + _ x: Tensor, + csPrev: Tensor, + hPrev: Tensor, + w: Tensor, + wci: Tensor, + wcf: Tensor, + wco: Tensor, + _ b: Tensor, + forgetBias: Double = 1, + cellClip: Double = 3, + usePeephole: Bool = false ) -> (i: Tensor, cs: Tensor, f: Tensor, o: Tensor, ci: Tensor, co: Tensor, h: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("BlockLSTM", nOutputs) - op.updateAttribute("forget_bias", forgetBias) - op.updateAttribute("cell_clip", cellClip) - op.updateAttribute("use_peephole", usePeephole) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(seqLenMax) - op.addInput(x) - op.addInput(csPrev) - op.addInput(hPrev) - op.addInput(w) - op.addInput(wci) - op.addInput(wcf) - op.addInput(wco) - op.addInput(b) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("BlockLSTM", nOutputs) + op.updateAttribute("forget_bias", forgetBias) + op.updateAttribute("cell_clip", cellClip) + op.updateAttribute("use_peephole", usePeephole) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(seqLenMax) + op.addInput(x) + op.addInput(csPrev) + op.addInput(hPrev) + op.addInput(w) + op.addInput(wci) + op.addInput(wcf) + op.addInput(wco) + op.addInput(b) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) } /// Computes the LSTM cell backward propagation for the entire time sequence. @@ -3124,82 +3124,82 @@ public static func blockLSTM( /// This implementation is to be used in conjunction of LSTMBlock. /// /// - Parameters: -/// - seq_len_max: Maximum time length actually used by this input. Outputs are padded -/// with zeros beyond this length. -/// - x: The sequence input to the LSTM, shape (timelen, batch_size, num_inputs). -/// - cs_prev: Value of the initial cell state. -/// - h_prev: Initial output of cell (to be used for peephole). -/// - w: The weight matrix. -/// - wci: The weight matrix for input gate peephole connection. -/// - wcf: The weight matrix for forget gate peephole connection. -/// - wco: The weight matrix for output gate peephole connection. -/// - b: The bias vector. -/// - i: The input gate over the whole time sequence. -/// - cs: The cell state before the tanh over the whole time sequence. -/// - f: The forget gate over the whole time sequence. -/// - o: The output gate over the whole time sequence. -/// - ci: The cell input over the whole time sequence. -/// - co: The cell after the tanh over the whole time sequence. -/// - h: The output h vector over the whole time sequence. -/// - cs_grad: The current gradient of cs. -/// - h_grad: The gradient of h vector. +/// - seq_len_max: Maximum time length actually used by this input. Outputs are padded +/// with zeros beyond this length. +/// - x: The sequence input to the LSTM, shape (timelen, batch_size, num_inputs). +/// - cs_prev: Value of the initial cell state. +/// - h_prev: Initial output of cell (to be used for peephole). +/// - w: The weight matrix. +/// - wci: The weight matrix for input gate peephole connection. +/// - wcf: The weight matrix for forget gate peephole connection. +/// - wco: The weight matrix for output gate peephole connection. +/// - b: The bias vector. +/// - i: The input gate over the whole time sequence. +/// - cs: The cell state before the tanh over the whole time sequence. +/// - f: The forget gate over the whole time sequence. +/// - o: The output gate over the whole time sequence. +/// - ci: The cell input over the whole time sequence. +/// - co: The cell after the tanh over the whole time sequence. +/// - h: The output h vector over the whole time sequence. +/// - cs_grad: The current gradient of cs. +/// - h_grad: The gradient of h vector. /// /// - Attr use_peephole: Whether to use peephole weights. /// /// - Outputs: -/// - x_grad: The gradient of x to be back-propped. -/// - cs_prev_grad: The gradient of cs_prev to be back-propped. -/// - h_prev_grad: The gradient of h_prev to be back-propped. -/// - w_grad: The gradient for w to be back-propped. -/// - wci_grad: The gradient for wci to be back-propped. -/// - wcf_grad: The gradient for wcf to be back-propped. -/// - wco_grad: The gradient for wco to be back-propped. -/// - b_grad: The gradient for w to be back-propped. +/// - x_grad: The gradient of x to be back-propped. +/// - cs_prev_grad: The gradient of cs_prev to be back-propped. +/// - h_prev_grad: The gradient of h_prev to be back-propped. +/// - w_grad: The gradient for w to be back-propped. +/// - wci_grad: The gradient for wci to be back-propped. +/// - wcf_grad: The gradient for wcf to be back-propped. +/// - wco_grad: The gradient for wco to be back-propped. +/// - b_grad: The gradient for w to be back-propped. @inlinable @inline(__always) public static func blockLSTMGrad( - seqLenMax: Tensor, - _ x: Tensor, - csPrev: Tensor, - hPrev: Tensor, - w: Tensor, - wci: Tensor, - wcf: Tensor, - wco: Tensor, - _ b: Tensor, - i: Tensor, - cs: Tensor, - f: Tensor, - o: Tensor, - ci: Tensor, - co: Tensor, - h: Tensor, - csGrad: Tensor, - hGrad: Tensor, - usePeephole: Bool + seqLenMax: Tensor, + _ x: Tensor, + csPrev: Tensor, + hPrev: Tensor, + w: Tensor, + wci: Tensor, + wcf: Tensor, + wco: Tensor, + _ b: Tensor, + i: Tensor, + cs: Tensor, + f: Tensor, + o: Tensor, + ci: Tensor, + co: Tensor, + h: Tensor, + csGrad: Tensor, + hGrad: Tensor, + usePeephole: Bool ) -> (xGrad: Tensor, csPrevGrad: Tensor, hPrevGrad: Tensor, wGrad: Tensor, wciGrad: Tensor, wcfGrad: Tensor, wcoGrad: Tensor, bGrad: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("BlockLSTMGrad", nOutputs) - op.updateAttribute("use_peephole", usePeephole) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(seqLenMax) - op.addInput(x) - op.addInput(csPrev) - op.addInput(hPrev) - op.addInput(w) - op.addInput(wci) - op.addInput(wcf) - op.addInput(wco) - op.addInput(b) - op.addInput(i) - op.addInput(cs) - op.addInput(f) - op.addInput(o) - op.addInput(ci) - op.addInput(co) - op.addInput(h) - op.addInput(csGrad) - op.addInput(hGrad) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("BlockLSTMGrad", nOutputs) + op.updateAttribute("use_peephole", usePeephole) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(seqLenMax) + op.addInput(x) + op.addInput(csPrev) + op.addInput(hPrev) + op.addInput(w) + op.addInput(wci) + op.addInput(wcf) + op.addInput(wco) + op.addInput(b) + op.addInput(i) + op.addInput(cs) + op.addInput(f) + op.addInput(o) + op.addInput(ci) + op.addInput(co) + op.addInput(h) + op.addInput(csGrad) + op.addInput(hGrad) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) } /// Aggregates the summary of accumulated stats for the batch. @@ -3207,35 +3207,35 @@ public static func blockLSTMGrad( /// The summary stats contains gradients and hessians accumulated for each node, feature dimension id and bucket. /// /// - Parameters: -/// - node_ids: int32; Rank 1 Tensor containing node ids for each example, shape [batch_size]. -/// - gradients: float32; Rank 2 Tensor (shape=[batch_size, logits_dimension]) with gradients for each example. -/// - hessians: float32; Rank 2 Tensor (shape=[batch_size, hessian_dimension]) with hessians for each example. -/// - feature: int32; Rank 2 feature Tensors (shape=[batch_size, feature_dimension]). +/// - node_ids: int32; Rank 1 Tensor containing node ids for each example, shape [batch_size]. +/// - gradients: float32; Rank 2 Tensor (shape=[batch_size, logits_dimension]) with gradients for each example. +/// - hessians: float32; Rank 2 Tensor (shape=[batch_size, hessian_dimension]) with hessians for each example. +/// - feature: int32; Rank 2 feature Tensors (shape=[batch_size, feature_dimension]). /// /// - Attrs: -/// - max_splits: int; the maximum number of splits possible in the whole tree. -/// - num_buckets: int; equals to the maximum possible value of bucketized feature. +/// - max_splits: int; the maximum number of splits possible in the whole tree. +/// - num_buckets: int; equals to the maximum possible value of bucketized feature. /// /// - Output stats_summary: output Rank 4 Tensor (shape=[splits, feature_dimension, buckets, logits_dimension + hessian_dimension]) -/// containing accumulated stats for each node, feature dimension and bucket. +/// containing accumulated stats for each node, feature dimension and bucket. @inlinable @inline(__always) public static func boostedTreesAggregateStats( - nodeIds: Tensor, - gradients: Tensor, - hessians: Tensor, - feature: Tensor, - maxSplits: Int64, - numBuckets: Int64 + nodeIds: Tensor, + gradients: Tensor, + hessians: Tensor, + feature: Tensor, + maxSplits: Int64, + numBuckets: Int64 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BoostedTreesAggregateStats", nOutputs) - op.updateAttribute("max_splits", maxSplits) - op.updateAttribute("num_buckets", numBuckets) - op.addInput(nodeIds) - op.addInput(gradients) - op.addInput(hessians) - op.addInput(feature) - return op.execute(Int(1)) + let op = makeOp("BoostedTreesAggregateStats", nOutputs) + op.updateAttribute("max_splits", maxSplits) + op.updateAttribute("num_buckets", numBuckets) + op.addInput(nodeIds) + op.addInput(gradients) + op.addInput(hessians) + op.addInput(feature) + return op.execute(Int(1)) } /// Bucketize each feature based on bucket boundaries. @@ -3244,24 +3244,24 @@ public static func boostedTreesAggregateStats( /// bucketized values for a single feature. /// /// - Parameters: -/// - float_values: float; List of Rank 1 Tensor each containing float values for a single feature. -/// - bucket_boundaries: float; List of Rank 1 Tensors each containing the bucket boundaries for a single -/// feature. +/// - float_values: float; List of Rank 1 Tensor each containing float values for a single feature. +/// - bucket_boundaries: float; List of Rank 1 Tensors each containing the bucket boundaries for a single +/// feature. /// /// - Attr num_features: inferred int; number of features. /// /// - Output buckets: int; List of Rank 1 Tensors each containing the bucketized values for a single feature. @inlinable @inline(__always) public static func boostedTreesBucketize( - floatValues: [Tensor], - bucketBoundaries: [Tensor] + floatValues: [Tensor], + bucketBoundaries: [Tensor] ) -> [Tensor] { let nOutputs = Int(floatValues.count) - let op = makeOp("BoostedTreesBucketize", nOutputs) - op.updateAttribute("num_features", floatValues.count) - op.addInputList(floatValues) - op.addInputList(bucketBoundaries) - return op.execute(Int(floatValues.count)) + let op = makeOp("BoostedTreesBucketize", nOutputs) + op.updateAttribute("num_features", floatValues.count) + op.addInputList(floatValues) + op.addInputList(bucketBoundaries) + return op.execute(Int(floatValues.count)) } /// Calculates gains for each feature and returns the best possible split information for the feature. @@ -3275,48 +3275,48 @@ public static func boostedTreesBucketize( /// The output shapes are compatible in a way that the first dimension of all tensors are the same and equal to the number of possible split nodes for each feature. /// /// - Parameters: -/// - node_id_range: A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive). -/// - stats_summary: A Rank 4 tensor (#shape=[max_splits, feature_dims, bucket, stats_dims]) for accumulated stats summary (gradient/hessian) per node, per dimension, per buckets for each feature. -/// The first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used. -/// - l1: l1 regularization factor on leaf weights, per instance based. -/// - l2: l2 regularization factor on leaf weights, per instance based. -/// - tree_complexity: adjustment to the gain, per leaf based. -/// - min_node_weight: mininum avg of hessians in a node before required for the node to be considered for splitting. +/// - node_id_range: A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive). +/// - stats_summary: A Rank 4 tensor (#shape=[max_splits, feature_dims, bucket, stats_dims]) for accumulated stats summary (gradient/hessian) per node, per dimension, per buckets for each feature. +/// The first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used. +/// - l1: l1 regularization factor on leaf weights, per instance based. +/// - l2: l2 regularization factor on leaf weights, per instance based. +/// - tree_complexity: adjustment to the gain, per leaf based. +/// - min_node_weight: mininum avg of hessians in a node before required for the node to be considered for splitting. /// /// - Attrs: -/// - logits_dimension: The dimension of logit, i.e., number of classes. -/// - split_type: A string indicating if this Op should perform inequality split or equality split. +/// - logits_dimension: The dimension of logit, i.e., number of classes. +/// - split_type: A string indicating if this Op should perform inequality split or equality split. /// /// - Outputs: -/// - node_ids: A Rank 1 tensors indicating possible split node ids for each feature. The length of the list is num_features, but each tensor has different size as each feature provides different possible nodes. See above for details like shapes and sizes. -/// - gains: A Rank 1 tensors indicating the best gains for each feature to split for certain nodes. See above for details like shapes and sizes. -/// - feature_dimensions: A Rank 1 tensors indicating the best feature dimension for each feature to split for certain nodes if the feature is multi-dimension. See above for details like shapes and sizes. -/// - thresholds: A Rank 1 tensors indicating the bucket id to compare with (as a threshold) for split in each node. See above for details like shapes and sizes. -/// - left_node_contribs: A Rank 2 tensors indicating the contribution of the left nodes when branching from parent nodes (given by the tensor element in the output node_ids_list) to the left direction by the given threshold for each feature. This value will be used to make the left node value by adding to the parent node value. Second dimension size is 1 for 1-dimensional logits, but would be larger for multi-class problems. See above for details like shapes and sizes. -/// - right_node_contribs: A Rank 2 tensors, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node. -/// - split_with_default_directions: A Rank 1 tensors indicating the which direction to go if data is missing. See above for details like shapes and sizes. +/// - node_ids: A Rank 1 tensors indicating possible split node ids for each feature. The length of the list is num_features, but each tensor has different size as each feature provides different possible nodes. See above for details like shapes and sizes. +/// - gains: A Rank 1 tensors indicating the best gains for each feature to split for certain nodes. See above for details like shapes and sizes. +/// - feature_dimensions: A Rank 1 tensors indicating the best feature dimension for each feature to split for certain nodes if the feature is multi-dimension. See above for details like shapes and sizes. +/// - thresholds: A Rank 1 tensors indicating the bucket id to compare with (as a threshold) for split in each node. See above for details like shapes and sizes. +/// - left_node_contribs: A Rank 2 tensors indicating the contribution of the left nodes when branching from parent nodes (given by the tensor element in the output node_ids_list) to the left direction by the given threshold for each feature. This value will be used to make the left node value by adding to the parent node value. Second dimension size is 1 for 1-dimensional logits, but would be larger for multi-class problems. See above for details like shapes and sizes. +/// - right_node_contribs: A Rank 2 tensors, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node. +/// - split_with_default_directions: A Rank 1 tensors indicating the which direction to go if data is missing. See above for details like shapes and sizes. @inlinable @inline(__always) public static func boostedTreesCalculateBestFeatureSplit( - nodeIdRange: Tensor, - statsSummary: Tensor, - l1: Tensor, - l2: Tensor, - treeComplexity: Tensor, - minNodeWeight: Tensor, - logitsDimension: Int64, - splitType: SplitType = .inequality + nodeIdRange: Tensor, + statsSummary: Tensor, + l1: Tensor, + l2: Tensor, + treeComplexity: Tensor, + minNodeWeight: Tensor, + logitsDimension: Int64, + splitType: SplitType = .inequality ) -> (nodeIds: Tensor, gains: Tensor, featureDimensions: Tensor, thresholds: Tensor, leftNodeContribs: Tensor, rightNodeContribs: Tensor, splitWithDefaultDirections: StringTensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("BoostedTreesCalculateBestFeatureSplit", nOutputs) - op.updateAttribute("logits_dimension", logitsDimension) - op.updateAttribute("split_type", splitType.cName) - op.addInput(nodeIdRange) - op.addInput(statsSummary) - op.addInput(l1) - op.addInput(l2) - op.addInput(treeComplexity) - op.addInput(minNodeWeight) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("BoostedTreesCalculateBestFeatureSplit", nOutputs) + op.updateAttribute("logits_dimension", logitsDimension) + op.updateAttribute("split_type", splitType.cName) + op.addInput(nodeIdRange) + op.addInput(statsSummary) + op.addInput(l1) + op.addInput(l2) + op.addInput(treeComplexity) + op.addInput(minNodeWeight) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) } /// Calculates gains for each feature and returns the best possible split information for the feature. @@ -3331,116 +3331,116 @@ public static func boostedTreesCalculateBestFeatureSplit( /// The output shapes are compatible in a way that the first dimension of all tensors of all lists are the same and equal to the number of possible split nodes for each feature. /// /// - Parameters: -/// - node_id_range: A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive). -/// - stats_summary_list: A list of Rank 3 tensor (#shape=[max_splits, bucket, 2]) for accumulated stats summary (gradient/hessian) per node per buckets for each feature. The first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used. -/// - l1: l1 regularization factor on leaf weights, per instance based. -/// - l2: l2 regularization factor on leaf weights, per instance based. -/// - tree_complexity: adjustment to the gain, per leaf based. -/// - min_node_weight: mininum avg of hessians in a node before required for the node to be considered for splitting. +/// - node_id_range: A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive). +/// - stats_summary_list: A list of Rank 3 tensor (#shape=[max_splits, bucket, 2]) for accumulated stats summary (gradient/hessian) per node per buckets for each feature. The first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used. +/// - l1: l1 regularization factor on leaf weights, per instance based. +/// - l2: l2 regularization factor on leaf weights, per instance based. +/// - tree_complexity: adjustment to the gain, per leaf based. +/// - min_node_weight: mininum avg of hessians in a node before required for the node to be considered for splitting. /// /// - Attrs: -/// - max_splits: the number of nodes that can be split in the whole tree. Used as a dimension of output tensors. -/// - num_features: inferred from the size of `stats_summary_list`; the number of total features. +/// - max_splits: the number of nodes that can be split in the whole tree. Used as a dimension of output tensors. +/// - num_features: inferred from the size of `stats_summary_list`; the number of total features. /// /// - Outputs: -/// - node_ids_list: An output list of Rank 1 tensors indicating possible split node ids for each feature. The length of the list is num_features, but each tensor has different size as each feature provides different possible nodes. See above for details like shapes and sizes. -/// - gains_list: An output list of Rank 1 tensors indicating the best gains for each feature to split for certain nodes. See above for details like shapes and sizes. -/// - thresholds_list: An output list of Rank 1 tensors indicating the bucket id to compare with (as a threshold) for split in each node. See above for details like shapes and sizes. -/// - left_node_contribs_list: A list of Rank 2 tensors indicating the contribution of the left nodes when branching from parent nodes (given by the tensor element in the output node_ids_list) to the left direction by the given threshold for each feature. This value will be used to make the left node value by adding to the parent node value. Second dimension size is 1 for 1-dimensional logits, but would be larger for multi-class problems. See above for details like shapes and sizes. -/// - right_node_contribs_list: A list of Rank 2 tensors, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node. +/// - node_ids_list: An output list of Rank 1 tensors indicating possible split node ids for each feature. The length of the list is num_features, but each tensor has different size as each feature provides different possible nodes. See above for details like shapes and sizes. +/// - gains_list: An output list of Rank 1 tensors indicating the best gains for each feature to split for certain nodes. See above for details like shapes and sizes. +/// - thresholds_list: An output list of Rank 1 tensors indicating the bucket id to compare with (as a threshold) for split in each node. See above for details like shapes and sizes. +/// - left_node_contribs_list: A list of Rank 2 tensors indicating the contribution of the left nodes when branching from parent nodes (given by the tensor element in the output node_ids_list) to the left direction by the given threshold for each feature. This value will be used to make the left node value by adding to the parent node value. Second dimension size is 1 for 1-dimensional logits, but would be larger for multi-class problems. See above for details like shapes and sizes. +/// - right_node_contribs_list: A list of Rank 2 tensors, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node. @inlinable @inline(__always) public static func boostedTreesCalculateBestGainsPerFeature( - nodeIdRange: Tensor, - statsSummaryList: [Tensor], - l1: Tensor, - l2: Tensor, - treeComplexity: Tensor, - minNodeWeight: Tensor, - maxSplits: Int64 + nodeIdRange: Tensor, + statsSummaryList: [Tensor], + l1: Tensor, + l2: Tensor, + treeComplexity: Tensor, + minNodeWeight: Tensor, + maxSplits: Int64 ) -> (nodeIdsList: [Tensor], gainsList: [Tensor], thresholdsList: [Tensor], leftNodeContribsList: [Tensor], rightNodeContribsList: [Tensor]) { let nOutputs = Int(statsSummaryList.count) + Int(statsSummaryList.count) + Int(statsSummaryList.count) + Int(statsSummaryList.count) + Int(statsSummaryList.count) - let op = makeOp("BoostedTreesCalculateBestGainsPerFeature", nOutputs) - op.updateAttribute("max_splits", maxSplits) - op.updateAttribute("num_features", statsSummaryList.count) - op.addInput(nodeIdRange) - op.addInputList(statsSummaryList) - op.addInput(l1) - op.addInput(l2) - op.addInput(treeComplexity) - op.addInput(minNodeWeight) - return op.execute(Int(statsSummaryList.count), Int(statsSummaryList.count), Int(statsSummaryList.count), Int(statsSummaryList.count), Int(statsSummaryList.count)) + let op = makeOp("BoostedTreesCalculateBestGainsPerFeature", nOutputs) + op.updateAttribute("max_splits", maxSplits) + op.updateAttribute("num_features", statsSummaryList.count) + op.addInput(nodeIdRange) + op.addInputList(statsSummaryList) + op.addInput(l1) + op.addInput(l2) + op.addInput(treeComplexity) + op.addInput(minNodeWeight) + return op.execute(Int(statsSummaryList.count), Int(statsSummaryList.count), Int(statsSummaryList.count), Int(statsSummaryList.count), Int(statsSummaryList.count)) } /// Calculates the prior from the training data (the bias) and fills in the first node with the logits' prior. Returns a boolean indicating whether to continue centering. /// /// - Parameters: -/// - tree_ensemble_handle: Handle to the tree ensemble. -/// - mean_gradients: A tensor with shape=[logits_dimension] with mean of gradients for a first node. -/// - mean_hessians: A tensor with shape=[logits_dimension] mean of hessians for a first node. -/// - l1: l1 regularization factor on leaf weights, per instance based. -/// - l2: l2 regularization factor on leaf weights, per instance based. +/// - tree_ensemble_handle: Handle to the tree ensemble. +/// - mean_gradients: A tensor with shape=[logits_dimension] with mean of gradients for a first node. +/// - mean_hessians: A tensor with shape=[logits_dimension] mean of hessians for a first node. +/// - l1: l1 regularization factor on leaf weights, per instance based. +/// - l2: l2 regularization factor on leaf weights, per instance based. /// /// - Output continue_centering: Bool, whether to continue bias centering. @inlinable @inline(__always) public static func boostedTreesCenterBias( - treeEnsembleHandle: ResourceHandle, - meanGradients: Tensor, - meanHessians: Tensor, - l1: Tensor, - l2: Tensor + treeEnsembleHandle: ResourceHandle, + meanGradients: Tensor, + meanHessians: Tensor, + l1: Tensor, + l2: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BoostedTreesCenterBias", nOutputs) - op.addInput(treeEnsembleHandle) - op.addInput(meanGradients) - op.addInput(meanHessians) - op.addInput(l1) - op.addInput(l2) - return op.execute(Int(1)) + let op = makeOp("BoostedTreesCenterBias", nOutputs) + op.addInput(treeEnsembleHandle) + op.addInput(meanGradients) + op.addInput(meanHessians) + op.addInput(l1) + op.addInput(l2) + return op.execute(Int(1)) } /// Creates a tree ensemble model and returns a handle to it. /// /// - Parameters: -/// - tree_ensemble_handle: Handle to the tree ensemble resource to be created. -/// - stamp_token: Token to use as the initial value of the resource stamp. -/// - tree_ensemble_serialized: Serialized proto of the tree ensemble. +/// - tree_ensemble_handle: Handle to the tree ensemble resource to be created. +/// - stamp_token: Token to use as the initial value of the resource stamp. +/// - tree_ensemble_serialized: Serialized proto of the tree ensemble. @inlinable @inline(__always) public static func boostedTreesCreateEnsemble( - treeEnsembleHandle: ResourceHandle, - stampToken: Tensor, - treeEnsembleSerialized: StringTensor + treeEnsembleHandle: ResourceHandle, + stampToken: Tensor, + treeEnsembleSerialized: StringTensor ) { let nOutputs = 0 - let op = makeOp("BoostedTreesCreateEnsemble", nOutputs) - op.addInput(treeEnsembleHandle) - op.addInput(stampToken) - op.addInput(treeEnsembleSerialized) - op.execute() + let op = makeOp("BoostedTreesCreateEnsemble", nOutputs) + op.addInput(treeEnsembleHandle) + op.addInput(stampToken) + op.addInput(treeEnsembleSerialized) + op.execute() } /// Create the Resource for Quantile Streams. /// /// - Parameters: -/// - quantile_stream_resource_handle: resource; Handle to quantile stream resource. -/// - epsilon: float; The required approximation error of the stream resource. -/// - num_streams: int; The number of streams managed by the resource that shares the same epsilon. +/// - quantile_stream_resource_handle: resource; Handle to quantile stream resource. +/// - epsilon: float; The required approximation error of the stream resource. +/// - num_streams: int; The number of streams managed by the resource that shares the same epsilon. /// /// - Attr max_elements: int; The maximum number of data points that can be fed to the stream. @inlinable @inline(__always) public static func boostedTreesCreateQuantileStreamResource( - quantileStreamResourceHandle: ResourceHandle, - epsilon: Tensor, - numStreams: Tensor, - maxElements: Int64 = 1099511627776 + quantileStreamResourceHandle: ResourceHandle, + epsilon: Tensor, + numStreams: Tensor, + maxElements: Int64 = 1099511627776 ) { let nOutputs = 0 - let op = makeOp("BoostedTreesCreateQuantileStreamResource", nOutputs) - op.updateAttribute("max_elements", maxElements) - op.addInput(quantileStreamResourceHandle) - op.addInput(epsilon) - op.addInput(numStreams) - op.execute() + let op = makeOp("BoostedTreesCreateQuantileStreamResource", nOutputs) + op.updateAttribute("max_elements", maxElements) + op.addInput(quantileStreamResourceHandle) + op.addInput(epsilon) + op.addInput(numStreams) + op.execute() } /// Deserializes a serialized tree ensemble config and replaces current tree @@ -3448,34 +3448,34 @@ public static func boostedTreesCreateQuantileStreamResource( /// ensemble. /// /// - Parameters: -/// - tree_ensemble_handle: Handle to the tree ensemble. -/// - stamp_token: Token to use as the new value of the resource stamp. -/// - tree_ensemble_serialized: Serialized proto of the ensemble. +/// - tree_ensemble_handle: Handle to the tree ensemble. +/// - stamp_token: Token to use as the new value of the resource stamp. +/// - tree_ensemble_serialized: Serialized proto of the ensemble. @inlinable @inline(__always) public static func boostedTreesDeserializeEnsemble( - treeEnsembleHandle: ResourceHandle, - stampToken: Tensor, - treeEnsembleSerialized: StringTensor + treeEnsembleHandle: ResourceHandle, + stampToken: Tensor, + treeEnsembleSerialized: StringTensor ) { let nOutputs = 0 - let op = makeOp("BoostedTreesDeserializeEnsemble", nOutputs) - op.addInput(treeEnsembleHandle) - op.addInput(stampToken) - op.addInput(treeEnsembleSerialized) - op.execute() + let op = makeOp("BoostedTreesDeserializeEnsemble", nOutputs) + op.addInput(treeEnsembleHandle) + op.addInput(stampToken) + op.addInput(treeEnsembleSerialized) + op.execute() } /// Creates a handle to a BoostedTreesEnsembleResource @inlinable @inline(__always) public static func boostedTreesEnsembleResourceHandleOp( - container: String, - sharedName: String + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("BoostedTreesEnsembleResourceHandleOp", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("BoostedTreesEnsembleResourceHandleOp", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Debugging/model interpretability outputs for each example. @@ -3485,27 +3485,27 @@ public static func boostedTreesEnsembleResourceHandleOp( /// path used to compute directional feature contributions. /// /// - Parameter bucketized_features: A list of rank 1 Tensors containing bucket id for each -/// feature. +/// feature. /// /// - Attrs: -/// - num_bucketized_features: Inferred. -/// - logits_dimension: scalar, dimension of the logits, to be used for constructing the protos in -/// examples_debug_outputs_serialized. +/// - num_bucketized_features: Inferred. +/// - logits_dimension: scalar, dimension of the logits, to be used for constructing the protos in +/// examples_debug_outputs_serialized. /// /// - Output examples_debug_outputs_serialized: Output rank 1 Tensor containing a proto serialized as a string for each example. @inlinable @inline(__always) public static func boostedTreesExampleDebugOutputs( - treeEnsembleHandle: ResourceHandle, - bucketizedFeatures: [Tensor], - logitsDimension: Int64 + treeEnsembleHandle: ResourceHandle, + bucketizedFeatures: [Tensor], + logitsDimension: Int64 ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("BoostedTreesExampleDebugOutputs", nOutputs) - op.updateAttribute("num_bucketized_features", bucketizedFeatures.count) - op.updateAttribute("logits_dimension", logitsDimension) - op.addInput(treeEnsembleHandle) - op.addInputList(bucketizedFeatures) - return op.execute(Int(1)) + let op = makeOp("BoostedTreesExampleDebugOutputs", nOutputs) + op.updateAttribute("num_bucketized_features", bucketizedFeatures.count) + op.updateAttribute("logits_dimension", logitsDimension) + op.addInput(treeEnsembleHandle) + op.addInputList(bucketizedFeatures) + return op.execute(Int(1)) } /// Retrieves the tree ensemble resource stamp token, number of trees and growing statistics. @@ -3513,20 +3513,20 @@ public static func boostedTreesExampleDebugOutputs( /// - Parameter tree_ensemble_handle: Handle to the tree ensemble. /// /// - Outputs: -/// - stamp_token: Stamp token of the tree ensemble resource. -/// - num_trees: The number of trees in the tree ensemble resource. -/// - num_finalized_trees: The number of trees that were finished successfully. -/// - num_attempted_layers: The number of layers we attempted to build (but not necessarily succeeded). -/// - last_layer_nodes_range: Rank size 2 tensor that contains start and end ids of the nodes in the latest -/// layer. +/// - stamp_token: Stamp token of the tree ensemble resource. +/// - num_trees: The number of trees in the tree ensemble resource. +/// - num_finalized_trees: The number of trees that were finished successfully. +/// - num_attempted_layers: The number of layers we attempted to build (but not necessarily succeeded). +/// - last_layer_nodes_range: Rank size 2 tensor that contains start and end ids of the nodes in the latest +/// layer. @inlinable @inline(__always) public static func boostedTreesGetEnsembleStates( - treeEnsembleHandle: ResourceHandle + treeEnsembleHandle: ResourceHandle ) -> (stampToken: Tensor, numTrees: Tensor, numFinalizedTrees: Tensor, numAttemptedLayers: Tensor, lastLayerNodesRange: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("BoostedTreesGetEnsembleStates", nOutputs) - op.addInput(treeEnsembleHandle) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("BoostedTreesGetEnsembleStates", nOutputs) + op.addInput(treeEnsembleHandle) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) } /// Makes the summary of quantiles for the batch. @@ -3535,28 +3535,28 @@ public static func boostedTreesGetEnsembleStates( /// quantile summaries for each tensor. /// /// - Parameters: -/// - float_values: float; List of Rank 1 Tensors each containing values for a single feature. -/// - example_weights: float; Rank 1 Tensor with weights per instance. -/// - epsilon: float; The required maximum approximation error. +/// - float_values: float; List of Rank 1 Tensors each containing values for a single feature. +/// - example_weights: float; Rank 1 Tensor with weights per instance. +/// - epsilon: float; The required maximum approximation error. /// /// - Attr num_features: int; Inferred from the size of float_values. -/// The number of float features. +/// The number of float features. /// /// - Output summaries: float; List of Rank 2 Tensors each containing the quantile summary -/// (value, weight, min_rank, max_rank) of a single feature. +/// (value, weight, min_rank, max_rank) of a single feature. @inlinable @inline(__always) public static func boostedTreesMakeQuantileSummaries( - floatValues: [Tensor], - exampleWeights: Tensor, - epsilon: Tensor + floatValues: [Tensor], + exampleWeights: Tensor, + epsilon: Tensor ) -> [Tensor] { let nOutputs = Int(floatValues.count) - let op = makeOp("BoostedTreesMakeQuantileSummaries", nOutputs) - op.updateAttribute("num_features", floatValues.count) - op.addInputList(floatValues) - op.addInput(exampleWeights) - op.addInput(epsilon) - return op.execute(Int(floatValues.count)) + let op = makeOp("BoostedTreesMakeQuantileSummaries", nOutputs) + op.updateAttribute("num_features", floatValues.count) + op.addInputList(floatValues) + op.addInput(exampleWeights) + op.addInput(epsilon) + return op.execute(Int(floatValues.count)) } /// Makes the summary of accumulated stats for the batch. @@ -3564,36 +3564,36 @@ public static func boostedTreesMakeQuantileSummaries( /// The summary stats contains gradients and hessians accumulated into the corresponding node and bucket for each example. /// /// - Parameters: -/// - node_ids: int32 Rank 1 Tensor containing node ids, which each example falls into for the requested layer. -/// - gradients: float32; Rank 2 Tensor (shape=[#examples, 1]) for gradients. -/// - hessians: float32; Rank 2 Tensor (shape=[#examples, 1]) for hessians. -/// - bucketized_features_list: int32 list of Rank 1 Tensors, each containing the bucketized feature (for each feature column). +/// - node_ids: int32 Rank 1 Tensor containing node ids, which each example falls into for the requested layer. +/// - gradients: float32; Rank 2 Tensor (shape=[#examples, 1]) for gradients. +/// - hessians: float32; Rank 2 Tensor (shape=[#examples, 1]) for hessians. +/// - bucketized_features_list: int32 list of Rank 1 Tensors, each containing the bucketized feature (for each feature column). /// /// - Attrs: -/// - max_splits: int; the maximum number of splits possible in the whole tree. -/// - num_buckets: int; equals to the maximum possible value of bucketized feature. -/// - num_features: int; inferred from the size of bucketized_features_list; the number of features. +/// - max_splits: int; the maximum number of splits possible in the whole tree. +/// - num_buckets: int; equals to the maximum possible value of bucketized feature. +/// - num_features: int; inferred from the size of bucketized_features_list; the number of features. /// /// - Output stats_summary: output Rank 4 Tensor (shape=[#features, #splits, #buckets, 2]) containing accumulated stats put into the corresponding node and bucket. The first index of 4th dimension refers to gradients, and the second to hessians. @inlinable @inline(__always) public static func boostedTreesMakeStatsSummary( - nodeIds: Tensor, - gradients: Tensor, - hessians: Tensor, - bucketizedFeaturesList: [Tensor], - maxSplits: Int64, - numBuckets: Int64 + nodeIds: Tensor, + gradients: Tensor, + hessians: Tensor, + bucketizedFeaturesList: [Tensor], + maxSplits: Int64, + numBuckets: Int64 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BoostedTreesMakeStatsSummary", nOutputs) - op.updateAttribute("max_splits", maxSplits) - op.updateAttribute("num_buckets", numBuckets) - op.updateAttribute("num_features", bucketizedFeaturesList.count) - op.addInput(nodeIds) - op.addInput(gradients) - op.addInput(hessians) - op.addInputList(bucketizedFeaturesList) - return op.execute(Int(1)) + let op = makeOp("BoostedTreesMakeStatsSummary", nOutputs) + op.updateAttribute("max_splits", maxSplits) + op.updateAttribute("num_buckets", numBuckets) + op.updateAttribute("num_features", bucketizedFeaturesList.count) + op.addInput(nodeIds) + op.addInput(gradients) + op.addInput(hessians) + op.addInputList(bucketizedFeaturesList) + return op.execute(Int(1)) } /// Runs multiple additive regression ensemble predictors on input instances and @@ -3602,27 +3602,27 @@ public static func boostedTreesMakeStatsSummary( /// It traverses all the trees and calculates the final score for each instance. /// /// - Parameter bucketized_features: A list of rank 1 Tensors containing bucket id for each -/// feature. +/// feature. /// /// - Attrs: -/// - num_bucketized_features: Inferred. -/// - logits_dimension: scalar, dimension of the logits, to be used for partial logits -/// shape. +/// - num_bucketized_features: Inferred. +/// - logits_dimension: scalar, dimension of the logits, to be used for partial logits +/// shape. /// /// - Output logits: Output rank 2 Tensor containing logits for each example. @inlinable @inline(__always) public static func boostedTreesPredict( - treeEnsembleHandle: ResourceHandle, - bucketizedFeatures: [Tensor], - logitsDimension: Int64 + treeEnsembleHandle: ResourceHandle, + bucketizedFeatures: [Tensor], + logitsDimension: Int64 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BoostedTreesPredict", nOutputs) - op.updateAttribute("num_bucketized_features", bucketizedFeatures.count) - op.updateAttribute("logits_dimension", logitsDimension) - op.addInput(treeEnsembleHandle) - op.addInputList(bucketizedFeatures) - return op.execute(Int(1)) + let op = makeOp("BoostedTreesPredict", nOutputs) + op.updateAttribute("num_bucketized_features", bucketizedFeatures.count) + op.updateAttribute("logits_dimension", logitsDimension) + op.addInput(treeEnsembleHandle) + op.addInputList(bucketizedFeatures) + return op.execute(Int(1)) } /// Add the quantile summaries to each quantile stream resource. @@ -3632,19 +3632,19 @@ public static func boostedTreesPredict( /// for a single feature. /// /// - Parameters: -/// - quantile_stream_resource_handle: resource handle referring to a QuantileStreamResource. -/// - summaries: string; List of Rank 2 Tensor each containing the summaries for a single feature. +/// - quantile_stream_resource_handle: resource handle referring to a QuantileStreamResource. +/// - summaries: string; List of Rank 2 Tensor each containing the summaries for a single feature. @inlinable @inline(__always) public static func boostedTreesQuantileStreamResourceAddSummaries( - quantileStreamResourceHandle: ResourceHandle, - summaries: [Tensor] + quantileStreamResourceHandle: ResourceHandle, + summaries: [Tensor] ) { let nOutputs = 0 - let op = makeOp("BoostedTreesQuantileStreamResourceAddSummaries", nOutputs) - op.updateAttribute("num_features", summaries.count) - op.addInput(quantileStreamResourceHandle) - op.addInputList(summaries) - op.execute() + let op = makeOp("BoostedTreesQuantileStreamResourceAddSummaries", nOutputs) + op.updateAttribute("num_features", summaries.count) + op.addInput(quantileStreamResourceHandle) + op.addInputList(summaries) + op.execute() } /// Deserialize bucket boundaries and ready flag into current QuantileAccumulator. @@ -3652,21 +3652,21 @@ public static func boostedTreesQuantileStreamResourceAddSummaries( /// An op that deserializes bucket boundaries and are boundaries ready flag into current QuantileAccumulator. /// /// - Parameters: -/// - quantile_stream_resource_handle: resource handle referring to a QuantileStreamResource. -/// - bucket_boundaries: float; List of Rank 1 Tensors each containing the bucket boundaries for a feature. +/// - quantile_stream_resource_handle: resource handle referring to a QuantileStreamResource. +/// - bucket_boundaries: float; List of Rank 1 Tensors each containing the bucket boundaries for a feature. /// /// - Attr num_streams: inferred int; number of features to get bucket boundaries for. @inlinable @inline(__always) public static func boostedTreesQuantileStreamResourceDeserialize( - quantileStreamResourceHandle: ResourceHandle, - bucketBoundaries: [Tensor] + quantileStreamResourceHandle: ResourceHandle, + bucketBoundaries: [Tensor] ) { let nOutputs = 0 - let op = makeOp("BoostedTreesQuantileStreamResourceDeserialize", nOutputs) - op.updateAttribute("num_streams", bucketBoundaries.count) - op.addInput(quantileStreamResourceHandle) - op.addInputList(bucketBoundaries) - op.execute() + let op = makeOp("BoostedTreesQuantileStreamResourceDeserialize", nOutputs) + op.updateAttribute("num_streams", bucketBoundaries.count) + op.addInput(quantileStreamResourceHandle) + op.addInputList(bucketBoundaries) + op.execute() } /// Flush the summaries for a quantile stream resource. @@ -3674,27 +3674,27 @@ public static func boostedTreesQuantileStreamResourceDeserialize( /// An op that flushes the summaries for a quantile stream resource. /// /// - Parameters: -/// - quantile_stream_resource_handle: resource handle referring to a QuantileStreamResource. -/// - num_buckets: int; approximate number of buckets unless using generate_quantiles. +/// - quantile_stream_resource_handle: resource handle referring to a QuantileStreamResource. +/// - num_buckets: int; approximate number of buckets unless using generate_quantiles. /// /// - Attr generate_quantiles: bool; If True, the output will be the num_quantiles for each stream where the ith -/// entry is the ith quantile of the input with an approximation error of epsilon. -/// Duplicate values may be present. -/// If False, the output will be the points in the histogram that we got which roughly -/// translates to 1/epsilon boundaries and without any duplicates. -/// Default to False. +/// entry is the ith quantile of the input with an approximation error of epsilon. +/// Duplicate values may be present. +/// If False, the output will be the points in the histogram that we got which roughly +/// translates to 1/epsilon boundaries and without any duplicates. +/// Default to False. @inlinable @inline(__always) public static func boostedTreesQuantileStreamResourceFlush( - quantileStreamResourceHandle: ResourceHandle, - numBuckets: Tensor, - generateQuantiles: Bool = false + quantileStreamResourceHandle: ResourceHandle, + numBuckets: Tensor, + generateQuantiles: Bool = false ) { let nOutputs = 0 - let op = makeOp("BoostedTreesQuantileStreamResourceFlush", nOutputs) - op.updateAttribute("generate_quantiles", generateQuantiles) - op.addInput(quantileStreamResourceHandle) - op.addInput(numBuckets) - op.execute() + let op = makeOp("BoostedTreesQuantileStreamResourceFlush", nOutputs) + op.updateAttribute("generate_quantiles", generateQuantiles) + op.addInput(quantileStreamResourceHandle) + op.addInput(numBuckets) + op.execute() } /// Generate the bucket boundaries for each feature based on accumulated summaries. @@ -3709,27 +3709,27 @@ public static func boostedTreesQuantileStreamResourceFlush( /// - Output bucket_boundaries: float; List of Rank 1 Tensors each containing the bucket boundaries for a feature. @inlinable @inline(__always) public static func boostedTreesQuantileStreamResourceGetBucketBoundaries( - quantileStreamResourceHandle: ResourceHandle, - numFeatures: Int64 + quantileStreamResourceHandle: ResourceHandle, + numFeatures: Int64 ) -> [Tensor] { let nOutputs = Int(numFeatures) - let op = makeOp("BoostedTreesQuantileStreamResourceGetBucketBoundaries", nOutputs) - op.updateAttribute("num_features", numFeatures) - op.addInput(quantileStreamResourceHandle) - return op.execute(Int(numFeatures)) + let op = makeOp("BoostedTreesQuantileStreamResourceGetBucketBoundaries", nOutputs) + op.updateAttribute("num_features", numFeatures) + op.addInput(quantileStreamResourceHandle) + return op.execute(Int(numFeatures)) } /// Creates a handle to a BoostedTreesQuantileStreamResource. @inlinable @inline(__always) public static func boostedTreesQuantileStreamResourceHandleOp( - container: String, - sharedName: String + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("BoostedTreesQuantileStreamResourceHandleOp", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("BoostedTreesQuantileStreamResourceHandleOp", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Serializes the tree ensemble to a proto. @@ -3737,16 +3737,16 @@ public static func boostedTreesQuantileStreamResourceHandleOp( /// - Parameter tree_ensemble_handle: Handle to the tree ensemble. /// /// - Outputs: -/// - stamp_token: Stamp token of the tree ensemble resource. -/// - tree_ensemble_serialized: Serialized proto of the ensemble. +/// - stamp_token: Stamp token of the tree ensemble resource. +/// - tree_ensemble_serialized: Serialized proto of the ensemble. @inlinable @inline(__always) public static func boostedTreesSerializeEnsemble( - treeEnsembleHandle: ResourceHandle + treeEnsembleHandle: ResourceHandle ) -> (stampToken: Tensor, treeEnsembleSerialized: StringTensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("BoostedTreesSerializeEnsemble", nOutputs) - op.addInput(treeEnsembleHandle) - return op.execute(Int(1), Int(1)) + let op = makeOp("BoostedTreesSerializeEnsemble", nOutputs) + op.addInput(treeEnsembleHandle) + return op.execute(Int(1), Int(1)) } /// Runs multiple additive regression ensemble predictors on input instances and @@ -3756,40 +3756,40 @@ public static func boostedTreesSerializeEnsemble( /// calculates the updates to be pushed to the cache. /// /// - Parameters: -/// - cached_tree_ids: Rank 1 Tensor containing cached tree ids which is the starting -/// tree of prediction. -/// - cached_node_ids: Rank 1 Tensor containing cached node id which is the starting -/// node of prediction. -/// - bucketized_features: A list of rank 1 Tensors containing bucket id for each -/// feature. +/// - cached_tree_ids: Rank 1 Tensor containing cached tree ids which is the starting +/// tree of prediction. +/// - cached_node_ids: Rank 1 Tensor containing cached node id which is the starting +/// node of prediction. +/// - bucketized_features: A list of rank 1 Tensors containing bucket id for each +/// feature. /// /// - Attrs: -/// - num_bucketized_features: Inferred. -/// - logits_dimension: scalar, dimension of the logits, to be used for partial logits -/// shape. +/// - num_bucketized_features: Inferred. +/// - logits_dimension: scalar, dimension of the logits, to be used for partial logits +/// shape. /// /// - Outputs: -/// - partial_logits: Rank 2 Tensor containing logits update (with respect to cached -/// values stored) for each example. -/// - tree_ids: Rank 1 Tensor containing new tree ids for each example. -/// - node_ids: Rank 1 Tensor containing new node ids in the new tree_ids. +/// - partial_logits: Rank 2 Tensor containing logits update (with respect to cached +/// values stored) for each example. +/// - tree_ids: Rank 1 Tensor containing new tree ids for each example. +/// - node_ids: Rank 1 Tensor containing new node ids in the new tree_ids. @inlinable @inline(__always) public static func boostedTreesTrainingPredict( - treeEnsembleHandle: ResourceHandle, - cachedTreeIds: Tensor, - cachedNodeIds: Tensor, - bucketizedFeatures: [Tensor], - logitsDimension: Int64 + treeEnsembleHandle: ResourceHandle, + cachedTreeIds: Tensor, + cachedNodeIds: Tensor, + bucketizedFeatures: [Tensor], + logitsDimension: Int64 ) -> (partialLogits: Tensor, treeIds: Tensor, nodeIds: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("BoostedTreesTrainingPredict", nOutputs) - op.updateAttribute("num_bucketized_features", bucketizedFeatures.count) - op.updateAttribute("logits_dimension", logitsDimension) - op.addInput(treeEnsembleHandle) - op.addInput(cachedTreeIds) - op.addInput(cachedNodeIds) - op.addInputList(bucketizedFeatures) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("BoostedTreesTrainingPredict", nOutputs) + op.updateAttribute("num_bucketized_features", bucketizedFeatures.count) + op.updateAttribute("logits_dimension", logitsDimension) + op.addInput(treeEnsembleHandle) + op.addInput(cachedTreeIds) + op.addInput(cachedNodeIds) + op.addInputList(bucketizedFeatures) + return op.execute(Int(1), Int(1), Int(1)) } /// Updates the tree ensemble by either adding a layer to the last tree being grown @@ -3797,54 +3797,54 @@ public static func boostedTreesTrainingPredict( /// or by starting a new tree. /// /// - Parameters: -/// - tree_ensemble_handle: Handle to the ensemble variable. -/// - feature_ids: Rank 1 tensor with ids for each feature. This is the real id of -/// the feature that will be used in the split. -/// - node_ids: List of rank 1 tensors representing the nodes for which this feature -/// has a split. -/// - gains: List of rank 1 tensors representing the gains for each of the feature's -/// split. -/// - thresholds: List of rank 1 tensors representing the thesholds for each of the -/// feature's split. -/// - left_node_contribs: List of rank 2 tensors with left leaf contribs for each of -/// the feature's splits. Will be added to the previous node values to constitute -/// the values of the left nodes. -/// - right_node_contribs: List of rank 2 tensors with right leaf contribs for each -/// of the feature's splits. Will be added to the previous node values to constitute -/// the values of the right nodes. -/// - max_depth: Max depth of the tree to build. -/// - learning_rate: shrinkage const for each new tree. +/// - tree_ensemble_handle: Handle to the ensemble variable. +/// - feature_ids: Rank 1 tensor with ids for each feature. This is the real id of +/// the feature that will be used in the split. +/// - node_ids: List of rank 1 tensors representing the nodes for which this feature +/// has a split. +/// - gains: List of rank 1 tensors representing the gains for each of the feature's +/// split. +/// - thresholds: List of rank 1 tensors representing the thesholds for each of the +/// feature's split. +/// - left_node_contribs: List of rank 2 tensors with left leaf contribs for each of +/// the feature's splits. Will be added to the previous node values to constitute +/// the values of the left nodes. +/// - right_node_contribs: List of rank 2 tensors with right leaf contribs for each +/// of the feature's splits. Will be added to the previous node values to constitute +/// the values of the right nodes. +/// - max_depth: Max depth of the tree to build. +/// - learning_rate: shrinkage const for each new tree. /// /// - Attrs: -/// - pruning_mode: 0-No pruning, 1-Pre-pruning, 2-Post-pruning. -/// - num_features: Number of features that have best splits returned. INFERRED. +/// - pruning_mode: 0-No pruning, 1-Pre-pruning, 2-Post-pruning. +/// - num_features: Number of features that have best splits returned. INFERRED. @inlinable @inline(__always) public static func boostedTreesUpdateEnsemble( - treeEnsembleHandle: ResourceHandle, - featureIds: Tensor, - nodeIds: [Tensor], - gains: [Tensor], - thresholds: [Tensor], - leftNodeContribs: [Tensor], - rightNodeContribs: [Tensor], - maxDepth: Tensor, - learningRate: Tensor, - pruningMode: Int64 + treeEnsembleHandle: ResourceHandle, + featureIds: Tensor, + nodeIds: [Tensor], + gains: [Tensor], + thresholds: [Tensor], + leftNodeContribs: [Tensor], + rightNodeContribs: [Tensor], + maxDepth: Tensor, + learningRate: Tensor, + pruningMode: Int64 ) { let nOutputs = 0 - let op = makeOp("BoostedTreesUpdateEnsemble", nOutputs) - op.updateAttribute("pruning_mode", pruningMode) - op.updateAttribute("num_features", nodeIds.count) - op.addInput(treeEnsembleHandle) - op.addInput(featureIds) - op.addInputList(nodeIds) - op.addInputList(gains) - op.addInputList(thresholds) - op.addInputList(leftNodeContribs) - op.addInputList(rightNodeContribs) - op.addInput(maxDepth) - op.addInput(learningRate) - op.execute() + let op = makeOp("BoostedTreesUpdateEnsemble", nOutputs) + op.updateAttribute("pruning_mode", pruningMode) + op.updateAttribute("num_features", nodeIds.count) + op.addInput(treeEnsembleHandle) + op.addInput(featureIds) + op.addInputList(nodeIds) + op.addInputList(gains) + op.addInputList(thresholds) + op.addInputList(leftNodeContribs) + op.addInputList(rightNodeContribs) + op.addInput(maxDepth) + op.addInput(learningRate) + op.execute() } /// Return the shape of s0 op s1 with broadcast. @@ -3853,15 +3853,15 @@ public static func boostedTreesUpdateEnsemble( /// broadcasted shape. `s0`, `s1` and `r0` are all integer vectors. @inlinable @inline(__always) public static func broadcastArgs( - s0: Tensor, - s1: Tensor + s0: Tensor, + s1: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BroadcastArgs", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(s0) - op.addInput(s1) - return op.execute(Int(1)) + let op = makeOp("BroadcastArgs", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(s0) + op.addInput(s1) + return op.execute(Int(1)) } /// Return the reduction indices for computing gradients of s0 op s1 with broadcast. @@ -3869,15 +3869,15 @@ public static func broadcastArgs( /// This is typically used by gradient computations for a broadcasting operation. @inlinable @inline(__always) public static func broadcastGradientArgs( - s0: Tensor, - s1: Tensor + s0: Tensor, + s1: Tensor ) -> (r0: Tensor, r1: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("BroadcastGradientArgs", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(s0) - op.addInput(s1) - return op.execute(Int(1), Int(1)) + let op = makeOp("BroadcastGradientArgs", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(s0) + op.addInput(s1) + return op.execute(Int(1), Int(1)) } /// Broadcast an array for a compatible shape. @@ -3901,8 +3901,8 @@ public static func broadcastGradientArgs( /// is broadcasted to output Tensor with shape of `[3, 3]`. /// /// - Parameters: -/// - input: A Tensor to broadcast. -/// - shape: An 1-D `int` Tensor. The shape of the desired output. +/// - input: A Tensor to broadcast. +/// - shape: An 1-D `int` Tensor. The shape of the desired output. /// /// - Output output: A Tensor. @inlinable @inline(__always) @@ -3910,16 +3910,16 @@ public static func broadcastTo< T: TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - shape: Tensor + _ input: Tensor, + shape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("BroadcastTo", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(input) - op.addInput(shape) - return op.execute(Int(1)) + let op = makeOp("BroadcastTo", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(shape) + return op.execute(Int(1)) } /// Bucketizes 'input' based on 'boundaries'. @@ -3941,20 +3941,20 @@ public static func broadcastTo< /// /// - Output output: Same shape with 'input', each value of input replaced with bucket index. /// -/// @compatibility(numpy) -/// Equivalent to np.digitize. -/// @end_compatibility +/// @compatibility(numpy) +/// Equivalent to np.digitize. +/// @end_compatibility @inlinable @inline(__always) public static func bucketize( - _ input: Tensor, - boundaries: [Double] + _ input: Tensor, + boundaries: [Double] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Bucketize", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("boundaries", boundaries) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Bucketize", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("boundaries", boundaries) + op.addInput(input) + return op.execute(Int(1)) } /// Performs beam search decoding on the logits given in input. @@ -3966,42 +3966,42 @@ public static func bucketize( /// returned if merge_repeated = False. /// /// - Parameters: -/// - inputs: 3-D, shape: `(max_time x batch_size x num_classes)`, the logits. -/// - sequence_length: A vector containing sequence lengths, size `(batch)`. +/// - inputs: 3-D, shape: `(max_time x batch_size x num_classes)`, the logits. +/// - sequence_length: A vector containing sequence lengths, size `(batch)`. /// /// - Attrs: -/// - beam_width: A scalar >= 0 (beam search beam width). -/// - top_paths: A scalar >= 0, <= beam_width (controls output size). -/// - merge_repeated: If true, merge repeated classes in output. +/// - beam_width: A scalar >= 0 (beam search beam width). +/// - top_paths: A scalar >= 0, <= beam_width (controls output size). +/// - merge_repeated: If true, merge repeated classes in output. /// /// - Outputs: -/// - decoded_indices: A list (length: top_paths) of indices matrices. Matrix j, -/// size `(total_decoded_outputs[j] x 2)`, has indices of a -/// `SparseTensor`. The rows store: [batch, time]. -/// - decoded_values: A list (length: top_paths) of values vectors. Vector j, -/// size `(length total_decoded_outputs[j])`, has the values of a -/// `SparseTensor`. The vector stores the decoded classes for beam j. -/// - decoded_shape: A list (length: top_paths) of shape vector. Vector j, -/// size `(2)`, stores the shape of the decoded `SparseTensor[j]`. -/// Its values are: `[batch_size, max_decoded_length[j]]`. -/// - log_probability: A matrix, shaped: `(batch_size x top_paths)`. The -/// sequence log-probabilities. +/// - decoded_indices: A list (length: top_paths) of indices matrices. Matrix j, +/// size `(total_decoded_outputs[j] x 2)`, has indices of a +/// `SparseTensor`. The rows store: [batch, time]. +/// - decoded_values: A list (length: top_paths) of values vectors. Vector j, +/// size `(length total_decoded_outputs[j])`, has the values of a +/// `SparseTensor`. The vector stores the decoded classes for beam j. +/// - decoded_shape: A list (length: top_paths) of shape vector. Vector j, +/// size `(2)`, stores the shape of the decoded `SparseTensor[j]`. +/// Its values are: `[batch_size, max_decoded_length[j]]`. +/// - log_probability: A matrix, shaped: `(batch_size x top_paths)`. The +/// sequence log-probabilities. @inlinable @inline(__always) public static func cTCBeamSearchDecoder( - inputs: Tensor, - sequenceLength: Tensor, - beamWidth: Int64, - topPaths: Int64, - mergeRepeated: Bool = true + inputs: Tensor, + sequenceLength: Tensor, + beamWidth: Int64, + topPaths: Int64, + mergeRepeated: Bool = true ) -> (decodedIndices: [Tensor], decodedValues: [Tensor], decodedShape: [Tensor], logProbability: Tensor) { let nOutputs = Int(topPaths) + Int(topPaths) + Int(topPaths) + Int(1) - let op = makeOp("CTCBeamSearchDecoder", nOutputs) - op.updateAttribute("beam_width", beamWidth) - op.updateAttribute("top_paths", topPaths) - op.updateAttribute("merge_repeated", mergeRepeated) - op.addInput(inputs) - op.addInput(sequenceLength) - return op.execute(Int(topPaths), Int(topPaths), Int(topPaths), Int(1)) + let op = makeOp("CTCBeamSearchDecoder", nOutputs) + op.updateAttribute("beam_width", beamWidth) + op.updateAttribute("top_paths", topPaths) + op.updateAttribute("merge_repeated", mergeRepeated) + op.addInput(inputs) + op.addInput(sequenceLength) + return op.execute(Int(topPaths), Int(topPaths), Int(topPaths), Int(1)) } /// Performs greedy decoding on the logits given in inputs. @@ -4017,32 +4017,32 @@ public static func cTCBeamSearchDecoder( /// element is emitted. /// /// - Parameters: -/// - inputs: 3-D, shape: `(max_time x batch_size x num_classes)`, the logits. -/// - sequence_length: A vector containing sequence lengths, size `(batch_size)`. +/// - inputs: 3-D, shape: `(max_time x batch_size x num_classes)`, the logits. +/// - sequence_length: A vector containing sequence lengths, size `(batch_size)`. /// /// - Attr merge_repeated: If True, merge repeated classes in output. /// /// - Outputs: -/// - decoded_indices: Indices matrix, size `(total_decoded_outputs x 2)`, -/// of a `SparseTensor`. The rows store: [batch, time]. -/// - decoded_values: Values vector, size: `(total_decoded_outputs)`, -/// of a `SparseTensor`. The vector stores the decoded classes. -/// - decoded_shape: Shape vector, size `(2)`, of the decoded SparseTensor. -/// Values are: `[batch_size, max_decoded_length]`. -/// - log_probability: Matrix, size `(batch_size x 1)`, containing sequence -/// log-probabilities. +/// - decoded_indices: Indices matrix, size `(total_decoded_outputs x 2)`, +/// of a `SparseTensor`. The rows store: [batch, time]. +/// - decoded_values: Values vector, size: `(total_decoded_outputs)`, +/// of a `SparseTensor`. The vector stores the decoded classes. +/// - decoded_shape: Shape vector, size `(2)`, of the decoded SparseTensor. +/// Values are: `[batch_size, max_decoded_length]`. +/// - log_probability: Matrix, size `(batch_size x 1)`, containing sequence +/// log-probabilities. @inlinable @inline(__always) public static func cTCGreedyDecoder( - inputs: Tensor, - sequenceLength: Tensor, - mergeRepeated: Bool = false + inputs: Tensor, + sequenceLength: Tensor, + mergeRepeated: Bool = false ) -> (decodedIndices: Tensor, decodedValues: Tensor, decodedShape: Tensor, logProbability: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("CTCGreedyDecoder", nOutputs) - op.updateAttribute("merge_repeated", mergeRepeated) - op.addInput(inputs) - op.addInput(sequenceLength) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("CTCGreedyDecoder", nOutputs) + op.updateAttribute("merge_repeated", mergeRepeated) + op.addInput(inputs) + op.addInput(sequenceLength) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Calculates the CTC Loss (log probability) for each batch entry. Also calculates @@ -4051,47 +4051,47 @@ public static func cTCGreedyDecoder( /// should be e.g. linear projections of outputs by an LSTM. /// /// - Parameters: -/// - inputs: 3-D, shape: `(max_time x batch_size x num_classes)`, the logits. -/// - labels_indices: The indices of a `SparseTensor`. -/// `labels_indices(i, :) == [b, t]` means `labels_values(i)` stores the id for -/// `(batch b, time t)`. -/// - labels_values: The values (labels) associated with the given batch and time. -/// - sequence_length: A vector containing sequence lengths (batch). +/// - inputs: 3-D, shape: `(max_time x batch_size x num_classes)`, the logits. +/// - labels_indices: The indices of a `SparseTensor`. +/// `labels_indices(i, :) == [b, t]` means `labels_values(i)` stores the id for +/// `(batch b, time t)`. +/// - labels_values: The values (labels) associated with the given batch and time. +/// - sequence_length: A vector containing sequence lengths (batch). /// /// - Attrs: -/// - preprocess_collapse_repeated: Scalar, if true then repeated labels are -/// collapsed prior to the CTC calculation. -/// - ctc_merge_repeated: Scalar. If set to false, *during* CTC calculation -/// repeated non-blank labels will not be merged and are interpreted as -/// individual labels. This is a simplified version of CTC. -/// - ignore_longer_outputs_than_inputs: Scalar. If set to true, during CTC -/// calculation, items that have longer output sequences than input sequences -/// are skipped: they don't contribute to the loss term and have zero-gradient. +/// - preprocess_collapse_repeated: Scalar, if true then repeated labels are +/// collapsed prior to the CTC calculation. +/// - ctc_merge_repeated: Scalar. If set to false, *during* CTC calculation +/// repeated non-blank labels will not be merged and are interpreted as +/// individual labels. This is a simplified version of CTC. +/// - ignore_longer_outputs_than_inputs: Scalar. If set to true, during CTC +/// calculation, items that have longer output sequences than input sequences +/// are skipped: they don't contribute to the loss term and have zero-gradient. /// /// - Outputs: -/// - loss: A vector (batch) containing log-probabilities. -/// - gradient: The gradient of `loss`. 3-D, shape: -/// `(max_time x batch_size x num_classes)`. +/// - loss: A vector (batch) containing log-probabilities. +/// - gradient: The gradient of `loss`. 3-D, shape: +/// `(max_time x batch_size x num_classes)`. @inlinable @inline(__always) public static func cTCLoss( - inputs: Tensor, - labelsIndices: Tensor, - labelsValues: Tensor, - sequenceLength: Tensor, - preprocessCollapseRepeated: Bool = false, - ctcMergeRepeated: Bool = true, - ignoreLongerOutputsThanInputs: Bool = false + inputs: Tensor, + labelsIndices: Tensor, + labelsValues: Tensor, + sequenceLength: Tensor, + preprocessCollapseRepeated: Bool = false, + ctcMergeRepeated: Bool = true, + ignoreLongerOutputsThanInputs: Bool = false ) -> (loss: Tensor, gradient: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("CTCLoss", nOutputs) - op.updateAttribute("preprocess_collapse_repeated", preprocessCollapseRepeated) - op.updateAttribute("ctc_merge_repeated", ctcMergeRepeated) - op.updateAttribute("ignore_longer_outputs_than_inputs", ignoreLongerOutputsThanInputs) - op.addInput(inputs) - op.addInput(labelsIndices) - op.addInput(labelsValues) - op.addInput(sequenceLength) - return op.execute(Int(1), Int(1)) + let op = makeOp("CTCLoss", nOutputs) + op.updateAttribute("preprocess_collapse_repeated", preprocessCollapseRepeated) + op.updateAttribute("ctc_merge_repeated", ctcMergeRepeated) + op.updateAttribute("ignore_longer_outputs_than_inputs", ignoreLongerOutputsThanInputs) + op.addInput(inputs) + op.addInput(labelsIndices) + op.addInput(labelsValues) + op.addInput(sequenceLength) + return op.execute(Int(1), Int(1)) } /// Creates a dataset that caches elements from `input_dataset`. @@ -4102,21 +4102,21 @@ public static func cTCLoss( /// will the returned when used. /// /// - Parameter filename: A path on the filesystem where we should cache the dataset. Note: this -/// will be a directory. +/// will be a directory. @inlinable @inline(__always) public static func cacheDataset( - inputDataset: VariantHandle, - filename: StringTensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + filename: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("CacheDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(filename) - return op.execute(Int(1)) + let op = makeOp("CacheDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(filename) + return op.execute(Int(1)) } /// Cast x of type SrcT to y of DstT. @@ -4125,28 +4125,28 @@ public static func cast< Srct: TensorFlowScalar, Dstt: TensorFlowScalar >( - _ x: Tensor, - truncate: Bool = false + _ x: Tensor, + truncate: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Cast", nOutputs) - op.updateAttribute("SrcT", Srct.tensorFlowDataType) - op.updateAttribute("DstT", Dstt.tensorFlowDataType) - op.updateAttribute("Truncate", truncate) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Cast", nOutputs) + op.updateAttribute("SrcT", Srct.tensorFlowDataType) + op.updateAttribute("DstT", Dstt.tensorFlowDataType) + op.updateAttribute("Truncate", truncate) + op.addInput(x) + return op.execute(Int(1)) } /// Returns element-wise smallest integer not less than x. @inlinable @inline(__always) public static func ceil( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Ceil", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Ceil", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Checks a tensor for NaN and Inf values. @@ -4157,15 +4157,15 @@ public static func ceil( /// - Attr message: Prefix of the error message. @inlinable @inline(__always) public static func checkNumerics( - _ tensor: Tensor, - message: String + _ tensor: Tensor, + message: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CheckNumerics", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("message", message) - op.addInput(tensor) - return op.execute(Int(1)) + let op = makeOp("CheckNumerics", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("message", message) + op.addInput(tensor) + return op.execute(Int(1)) } /// Computes the Cholesky decomposition of one or more square matrices. @@ -4189,13 +4189,13 @@ public static func checkNumerics( /// - Output output: Shape is `[..., M, M]`. @inlinable @inline(__always) public static func cholesky( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Cholesky", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Cholesky", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Computes the reverse mode backpropagated gradient of the Cholesky algorithm. @@ -4204,25 +4204,25 @@ public static func cholesky( /// Iain Murray http://arxiv.org/abs/1602.07527. /// /// - Parameters: -/// - l: Output of batch Cholesky algorithm l = cholesky(A). Shape is `[..., M, M]`. -/// Algorithm depends only on lower triangular part of the innermost matrices of -/// this tensor. -/// - grad: df/dl where f is some scalar function. Shape is `[..., M, M]`. -/// Algorithm depends only on lower triangular part of the innermost matrices of -/// this tensor. +/// - l: Output of batch Cholesky algorithm l = cholesky(A). Shape is `[..., M, M]`. +/// Algorithm depends only on lower triangular part of the innermost matrices of +/// this tensor. +/// - grad: df/dl where f is some scalar function. Shape is `[..., M, M]`. +/// Algorithm depends only on lower triangular part of the innermost matrices of +/// this tensor. /// /// - Output output: Symmetrized version of df/dA . Shape is `[..., M, M]` @inlinable @inline(__always) public static func choleskyGrad( - l: Tensor, - grad: Tensor + l: Tensor, + grad: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CholeskyGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(l) - op.addInput(grad) - return op.execute(Int(1)) + let op = makeOp("CholeskyGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(l) + op.addInput(grad) + return op.execute(Int(1)) } /// Clips tensor values to a specified min and max. @@ -4233,94 +4233,94 @@ public static func choleskyGrad( /// greater than `clip_value_max` are set to `clip_value_max`. /// /// - Parameters: -/// - t: A `Tensor`. -/// - clip_value_min: A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape -/// as `t`. The minimum value to clip by. -/// - clip_value_max: A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape -/// as `t`. The maximum value to clip by. +/// - t: A `Tensor`. +/// - clip_value_min: A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape +/// as `t`. The minimum value to clip by. +/// - clip_value_max: A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape +/// as `t`. The maximum value to clip by. /// /// - Output output: A clipped `Tensor` with the same shape as input 't'. @inlinable @inline(__always) public static func clipByValue( - t: Tensor, - clipValueMin: Tensor, - clipValueMax: Tensor + t: Tensor, + clipValueMin: Tensor, + clipValueMax: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ClipByValue", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(t) - op.addInput(clipValueMin) - op.addInput(clipValueMax) - return op.execute(Int(1)) + let op = makeOp("ClipByValue", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(t) + op.addInput(clipValueMin) + op.addInput(clipValueMax) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func closeSummaryWriter( - writer: ResourceHandle + writer: ResourceHandle ) { let nOutputs = 0 - let op = makeOp("CloseSummaryWriter", nOutputs) - op.addInput(writer) - op.execute() + let op = makeOp("CloseSummaryWriter", nOutputs) + op.addInput(writer) + op.execute() } /// Receives a tensor value broadcast from another device. @inlinable @inline(__always) public static func collectiveBcastRecv( - groupSize: Int64, - groupKey: Int64, - instanceKey: Int64, - shape: TensorShape? + groupSize: Int64, + groupKey: Int64, + instanceKey: Int64, + shape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CollectiveBcastRecv", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("group_size", groupSize) - op.updateAttribute("group_key", groupKey) - op.updateAttribute("instance_key", instanceKey) - op.updateAttribute("shape", shape) - return op.execute(Int(1)) + let op = makeOp("CollectiveBcastRecv", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("group_size", groupSize) + op.updateAttribute("group_key", groupKey) + op.updateAttribute("instance_key", instanceKey) + op.updateAttribute("shape", shape) + return op.execute(Int(1)) } /// Broadcasts a tensor value to one or more other devices. @inlinable @inline(__always) public static func collectiveBcastSend( - _ input: Tensor, - groupSize: Int64, - groupKey: Int64, - instanceKey: Int64, - shape: TensorShape? + _ input: Tensor, + groupSize: Int64, + groupKey: Int64, + instanceKey: Int64, + shape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CollectiveBcastSend", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("group_size", groupSize) - op.updateAttribute("group_key", groupKey) - op.updateAttribute("instance_key", instanceKey) - op.updateAttribute("shape", shape) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("CollectiveBcastSend", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("group_size", groupSize) + op.updateAttribute("group_key", groupKey) + op.updateAttribute("instance_key", instanceKey) + op.updateAttribute("shape", shape) + op.addInput(input) + return op.execute(Int(1)) } /// Mutually accumulates multiple tensors of identical type and shape. @inlinable @inline(__always) public static func collectiveGather( - _ input: Tensor, - groupSize: Int64, - groupKey: Int64, - instanceKey: Int64, - shape: TensorShape? + _ input: Tensor, + groupSize: Int64, + groupKey: Int64, + instanceKey: Int64, + shape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CollectiveGather", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("group_size", groupSize) - op.updateAttribute("group_key", groupKey) - op.updateAttribute("instance_key", instanceKey) - op.updateAttribute("shape", shape) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("CollectiveGather", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("group_size", groupSize) + op.updateAttribute("group_key", groupKey) + op.updateAttribute("instance_key", instanceKey) + op.updateAttribute("shape", shape) + op.addInput(input) + return op.execute(Int(1)) } /// An Op to permute tensors across replicated TPU instances. @@ -4332,50 +4332,50 @@ public static func collectiveGather( /// `[D, A, B, C]`. /// /// - Parameters: -/// - input: The local input to be permuted. Currently only supports float and -/// bfloat16. -/// - source_target_pairs: A tensor with shape [num_pairs, 2]. +/// - input: The local input to be permuted. Currently only supports float and +/// bfloat16. +/// - source_target_pairs: A tensor with shape [num_pairs, 2]. /// /// - Attr T: The type of elements to be exchanged. /// /// - Output output: The permuted input. @inlinable @inline(__always) public static func collectivePermute( - _ input: Tensor, - sourceTargetPairs: Tensor + _ input: Tensor, + sourceTargetPairs: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CollectivePermute", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - op.addInput(sourceTargetPairs) - return op.execute(Int(1)) + let op = makeOp("CollectivePermute", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(sourceTargetPairs) + return op.execute(Int(1)) } /// Mutually reduces multiple tensors of identical type and shape. @inlinable @inline(__always) public static func collectiveReduce( - _ input: Tensor, - groupSize: Int64, - groupKey: Int64, - instanceKey: Int64, - mergeOp: MergeOp, - finalOp: FinalOp, - subdivOffsets: [Int32], - waitFor: [Int32] -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("CollectiveReduce", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("group_size", groupSize) - op.updateAttribute("group_key", groupKey) - op.updateAttribute("instance_key", instanceKey) - op.updateAttribute("merge_op", mergeOp.cName) - op.updateAttribute("final_op", finalOp.cName) - op.updateAttribute("subdiv_offsets", subdivOffsets) - op.updateAttribute("wait_for", waitFor) - op.addInput(input) - return op.execute(Int(1)) + _ input: Tensor, + groupSize: Int64, + groupKey: Int64, + instanceKey: Int64, + mergeOp: MergeOp, + finalOp: FinalOp, + subdivOffsets: [Int32], + waitFor: [Int32] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CollectiveReduce", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("group_size", groupSize) + op.updateAttribute("group_key", groupKey) + op.updateAttribute("instance_key", instanceKey) + op.updateAttribute("merge_op", mergeOp.cName) + op.updateAttribute("final_op", finalOp.cName) + op.updateAttribute("subdiv_offsets", subdivOffsets) + op.updateAttribute("wait_for", waitFor) + op.addInput(input) + return op.execute(Int(1)) } /// Greedily selects a subset of bounding boxes in descending order of score, @@ -4395,62 +4395,62 @@ public static func collectiveReduce( /// returned after performing non_max_suppression. /// /// - Parameters: -/// - boxes: A 4-D float tensor of shape `[batch_size, num_boxes, q, 4]`. If `q` is 1 then -/// same boxes are used for all classes otherwise, if `q` is equal to number of -/// classes, class-specific boxes are used. -/// - scores: A 3-D float tensor of shape `[batch_size, num_boxes, num_classes]` -/// representing a single score corresponding to each box (each row of boxes). -/// - max_output_size_per_class: A scalar integer tensor representing the maximum number of -/// boxes to be selected by non max suppression per class -/// - max_total_size: A scalar representing maximum number of boxes retained over all classes. -/// - iou_threshold: A 0-D float tensor representing the threshold for deciding whether -/// boxes overlap too much with respect to IOU. -/// - score_threshold: A 0-D float tensor representing the threshold for deciding when to remove -/// boxes based on score. +/// - boxes: A 4-D float tensor of shape `[batch_size, num_boxes, q, 4]`. If `q` is 1 then +/// same boxes are used for all classes otherwise, if `q` is equal to number of +/// classes, class-specific boxes are used. +/// - scores: A 3-D float tensor of shape `[batch_size, num_boxes, num_classes]` +/// representing a single score corresponding to each box (each row of boxes). +/// - max_output_size_per_class: A scalar integer tensor representing the maximum number of +/// boxes to be selected by non max suppression per class +/// - max_total_size: A scalar representing maximum number of boxes retained over all classes. +/// - iou_threshold: A 0-D float tensor representing the threshold for deciding whether +/// boxes overlap too much with respect to IOU. +/// - score_threshold: A 0-D float tensor representing the threshold for deciding when to remove +/// boxes based on score. /// /// - Attrs: -/// - pad_per_class: If false, the output nmsed boxes, scores and classes -/// are padded/clipped to `max_total_size`. If true, the -/// output nmsed boxes, scores and classes are padded to be of length -/// `max_size_per_class`*`num_classes`, unless it exceeds `max_total_size` in -/// which case it is clipped to `max_total_size`. Defaults to false. -/// - clip_boxes: If true, assume the box coordinates are between [0, 1] and clip the output boxes -/// if they fall beyond [0, 1]. If false, do not do clipping and output the box -/// coordinates as it is. +/// - pad_per_class: If false, the output nmsed boxes, scores and classes +/// are padded/clipped to `max_total_size`. If true, the +/// output nmsed boxes, scores and classes are padded to be of length +/// `max_size_per_class`*`num_classes`, unless it exceeds `max_total_size` in +/// which case it is clipped to `max_total_size`. Defaults to false. +/// - clip_boxes: If true, assume the box coordinates are between [0, 1] and clip the output boxes +/// if they fall beyond [0, 1]. If false, do not do clipping and output the box +/// coordinates as it is. /// /// - Outputs: -/// - nmsed_boxes: A [batch_size, max_detections, 4] float32 tensor -/// containing the non-max suppressed boxes. -/// - nmsed_scores: A [batch_size, max_detections] float32 tensor -/// containing the scores for the boxes. -/// - nmsed_classes: A [batch_size, max_detections] float32 tensor -/// containing the classes for the boxes. -/// - valid_detections: A [batch_size] int32 tensor indicating the number of -/// valid detections per batch item. Only the top num_detections[i] entries in -/// nms_boxes[i], nms_scores[i] and nms_class[i] are valid. The rest of the -/// entries are zero paddings. +/// - nmsed_boxes: A [batch_size, max_detections, 4] float32 tensor +/// containing the non-max suppressed boxes. +/// - nmsed_scores: A [batch_size, max_detections] float32 tensor +/// containing the scores for the boxes. +/// - nmsed_classes: A [batch_size, max_detections] float32 tensor +/// containing the classes for the boxes. +/// - valid_detections: A [batch_size] int32 tensor indicating the number of +/// valid detections per batch item. Only the top num_detections[i] entries in +/// nms_boxes[i], nms_scores[i] and nms_class[i] are valid. The rest of the +/// entries are zero paddings. @inlinable @inline(__always) public static func combinedNonMaxSuppression( - boxes: Tensor, - scores: Tensor, - maxOutputSizePerClass: Tensor, - maxTotalSize: Tensor, - iouThreshold: Tensor, - scoreThreshold: Tensor, - padPerClass: Bool = false, - clipBoxes: Bool = true + boxes: Tensor, + scores: Tensor, + maxOutputSizePerClass: Tensor, + maxTotalSize: Tensor, + iouThreshold: Tensor, + scoreThreshold: Tensor, + padPerClass: Bool = false, + clipBoxes: Bool = true ) -> (nmsedBoxes: Tensor, nmsedScores: Tensor, nmsedClasses: Tensor, validDetections: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("CombinedNonMaxSuppression", nOutputs) - op.updateAttribute("pad_per_class", padPerClass) - op.updateAttribute("clip_boxes", clipBoxes) - op.addInput(boxes) - op.addInput(scores) - op.addInput(maxOutputSizePerClass) - op.addInput(maxTotalSize) - op.addInput(iouThreshold) - op.addInput(scoreThreshold) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("CombinedNonMaxSuppression", nOutputs) + op.updateAttribute("pad_per_class", padPerClass) + op.updateAttribute("clip_boxes", clipBoxes) + op.addInput(boxes) + op.addInput(scores) + op.addInput(maxOutputSizePerClass) + op.addInput(maxTotalSize) + op.addInput(iouThreshold) + op.addInput(scoreThreshold) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Compare values of `input` to `threshold` and pack resulting bits into a `uint8`. @@ -4480,23 +4480,23 @@ public static func combinedNonMaxSuppression( /// a `uint8` tensor shaped `[s0, s1, ..., s_n / 8]`. /// /// - Parameters: -/// - input: Values to compare against `threshold` and bitpack. -/// - threshold: Threshold to compare against. +/// - input: Values to compare against `threshold` and bitpack. +/// - threshold: Threshold to compare against. /// /// - Attr T: The type of the input and threshold. /// /// - Output output: The bitpacked comparisons. @inlinable @inline(__always) public static func compareAndBitpack( - _ input: Tensor, - threshold: Tensor + _ input: Tensor, + threshold: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CompareAndBitpack", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - op.addInput(threshold) - return op.execute(Int(1)) + let op = makeOp("CompareAndBitpack", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(threshold) + return op.execute(Int(1)) } /// Converts two real numbers to a complex number. @@ -4520,16 +4520,16 @@ public static func complex< T: FloatingPoint & TensorFlowScalar, Tout: TensorFlowScalar >( - real: Tensor, - imag: Tensor + real: Tensor, + imag: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Complex", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tout", Tout.tensorFlowDataType) - op.addInput(real) - op.addInput(imag) - return op.execute(Int(1)) + let op = makeOp("Complex", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(real) + op.addInput(imag) + return op.execute(Int(1)) } /// Computes the complex absolute value of a tensor. @@ -4543,27 +4543,27 @@ public static func complexAbs< T: TensorFlowScalar, Tout: FloatingPoint & TensorFlowScalar >( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ComplexAbs", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tout", Tout.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("ComplexAbs", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func complexStruct( - nA: Int64, - nB: Int64 + nA: Int64, + nB: Int64 ) -> (a: [Tensor], b: [Tensor], c: TC) { let nOutputs = Int(nA) + Int(nB) + Int(TC._typeList.count) - let op = makeOp("ComplexStruct", nOutputs) - op.updateAttribute("n_a", nA) - op.updateAttribute("n_b", nB) - op.updateAttribute("t_c", TC._typeList) - return op.execute(Int(nA), Int(nB), Int(TC._typeList.count)) + let op = makeOp("ComplexStruct", nOutputs) + op.updateAttribute("n_a", nA) + op.updateAttribute("n_b", nB) + op.updateAttribute("t_c", TC._typeList) + return op.execute(Int(nA), Int(nB), Int(TC._typeList.count)) } /// Computes the ids of the positions in sampled_candidates that match true_labels. @@ -4574,63 +4574,63 @@ public static func complexStruct( /// making the classifier sure that they are sampled labels. /// /// - Parameters: -/// - true_classes: The true_classes output of UnpackSparseLabels. -/// - sampled_candidates: The sampled_candidates output of CandidateSampler. +/// - true_classes: The true_classes output of UnpackSparseLabels. +/// - sampled_candidates: The sampled_candidates output of CandidateSampler. /// /// - Attrs: -/// - num_true: Number of true labels per context. -/// - seed: If either seed or seed2 are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: An second seed to avoid seed collision. +/// - num_true: Number of true labels per context. +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. /// /// - Outputs: -/// - indices: A vector of indices corresponding to rows of true_candidates. -/// - ids: A vector of IDs of positions in sampled_candidates that match a true_label -/// for the row with the corresponding index in indices. -/// - weights: A vector of the same length as indices and ids, in which each element -/// is -FLOAT_MAX. +/// - indices: A vector of indices corresponding to rows of true_candidates. +/// - ids: A vector of IDs of positions in sampled_candidates that match a true_label +/// for the row with the corresponding index in indices. +/// - weights: A vector of the same length as indices and ids, in which each element +/// is -FLOAT_MAX. @inlinable @inline(__always) public static func computeAccidentalHits( - trueClasses: Tensor, - sampledCandidates: Tensor, - numTrue: Int64, - seed: Int64 = 0, - seed2: Int64 = 0 + trueClasses: Tensor, + sampledCandidates: Tensor, + numTrue: Int64, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> (indices: Tensor, ids: Tensor, weights: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("ComputeAccidentalHits", nOutputs) - op.updateAttribute("num_true", numTrue) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.addInput(trueClasses) - op.addInput(sampledCandidates) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("ComputeAccidentalHits", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + op.addInput(sampledCandidates) + return op.execute(Int(1), Int(1), Int(1)) } /// Concatenates tensors along one dimension. /// /// - Parameters: -/// - concat_dim: 0-D. The dimension along which to concatenate. Must be in the -/// range [0, rank(values)). -/// - values: The `N` Tensors to concatenate. Their ranks and types must match, -/// and their sizes must match in all dimensions except `concat_dim`. +/// - concat_dim: 0-D. The dimension along which to concatenate. Must be in the +/// range [0, rank(values)). +/// - values: The `N` Tensors to concatenate. Their ranks and types must match, +/// and their sizes must match in all dimensions except `concat_dim`. /// /// - Output output: A `Tensor` with the concatenation of values stacked along the -/// `concat_dim` dimension. This tensor's shape matches that of `values` except -/// in `concat_dim` where it has the sum of the sizes. +/// `concat_dim` dimension. This tensor's shape matches that of `values` except +/// in `concat_dim` where it has the sum of the sizes. @inlinable @inline(__always) public static func concat( - concatDim: Tensor, - _ values: [Tensor] + concatDim: Tensor, + _ values: [Tensor] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Concat", nOutputs) - op.updateAttribute("N", values.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(concatDim) - op.addInputList(values) - return op.execute(Int(1)) + let op = makeOp("Concat", nOutputs) + op.updateAttribute("N", values.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(concatDim) + op.addInputList(values) + return op.execute(Int(1)) } /// Computes offsets of concat inputs within its output. @@ -4647,92 +4647,92 @@ public static func concat( /// This is typically used by gradient computations for a concat operation. /// /// - Parameters: -/// - concat_dim: The dimension along which to concatenate. -/// - shape: The `N` int32 vectors representing shape of tensors being concatenated. +/// - concat_dim: The dimension along which to concatenate. +/// - shape: The `N` int32 vectors representing shape of tensors being concatenated. /// /// - Output offset: The `N` int32 vectors representing the starting offset -/// of input tensors within the concatenated output. +/// of input tensors within the concatenated output. @inlinable @inline(__always) public static func concatOffset( - concatDim: Tensor, - shape: [Tensor] + concatDim: Tensor, + shape: [Tensor] ) -> [Tensor] { let nOutputs = Int(shape.count) - let op = makeOp("ConcatOffset", nOutputs) - op.updateAttribute("N", shape.count) - op.addInput(concatDim) - op.addInputList(shape) - return op.execute(Int(shape.count)) + let op = makeOp("ConcatOffset", nOutputs) + op.updateAttribute("N", shape.count) + op.addInput(concatDim) + op.addInputList(shape) + return op.execute(Int(shape.count)) } /// Concatenates tensors along one dimension. /// /// - Parameters: -/// - values: List of `N` Tensors to concatenate. Their ranks and types must match, -/// and their sizes must match in all dimensions except `concat_dim`. -/// - axis: 0-D. The dimension along which to concatenate. Must be in the -/// range [-rank(values), rank(values)). +/// - values: List of `N` Tensors to concatenate. Their ranks and types must match, +/// and their sizes must match in all dimensions except `concat_dim`. +/// - axis: 0-D. The dimension along which to concatenate. Must be in the +/// range [-rank(values), rank(values)). /// /// - Output output: A `Tensor` with the concatenation of values stacked along the -/// `concat_dim` dimension. This tensor's shape matches that of `values` except -/// in `concat_dim` where it has the sum of the sizes. +/// `concat_dim` dimension. This tensor's shape matches that of `values` except +/// in `concat_dim` where it has the sum of the sizes. @inlinable @inline(__always) public static func concatV2< T: TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - _ values: [Tensor], - axis: Tensor + _ values: [Tensor], + axis: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ConcatV2", nOutputs) - op.updateAttribute("N", values.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInputList(values) - op.addInput(axis) - return op.execute(Int(1)) + let op = makeOp("ConcatV2", nOutputs) + op.updateAttribute("N", values.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInputList(values) + op.addInput(axis) + return op.execute(Int(1)) } /// Creates a dataset that concatenates `input_dataset` with `another_dataset`. @inlinable @inline(__always) public static func concatenateDataset( - inputDataset: VariantHandle, - anotherDataset: VariantHandle, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + anotherDataset: VariantHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ConcatenateDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(anotherDataset) - return op.execute(Int(1)) + let op = makeOp("ConcatenateDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(anotherDataset) + return op.execute(Int(1)) } /// Sets up the centralized structures for a distributed TPU system. /// /// - Attrs: -/// - embedding_config: Reserved. Do not use. -/// - tpu_embedding_config: Serialized tensorflow.tpu.TPUEmbeddingConfiguration that -/// describes the embedding lookups of the program. -/// - is_global_init: Reserved. Do not use. +/// - embedding_config: Reserved. Do not use. +/// - tpu_embedding_config: Serialized tensorflow.tpu.TPUEmbeddingConfiguration that +/// describes the embedding lookups of the program. +/// - is_global_init: Reserved. Do not use. /// /// - Output topology: A serialized tensorflow.tpu.TopologyProto that describes the TPU -/// topology. +/// topology. @inlinable @inline(__always) public static func configureDistributedTPU( - embeddingConfig: String, - tpuEmbeddingConfig: String, - isGlobalInit: Bool = false + embeddingConfig: String, + tpuEmbeddingConfig: String, + isGlobalInit: Bool = false ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("ConfigureDistributedTPU", nOutputs) - op.updateAttribute("embedding_config", embeddingConfig) - op.updateAttribute("tpu_embedding_config", tpuEmbeddingConfig) - op.updateAttribute("is_global_init", isGlobalInit) - return op.execute(Int(1)) + let op = makeOp("ConfigureDistributedTPU", nOutputs) + op.updateAttribute("embedding_config", embeddingConfig) + op.updateAttribute("tpu_embedding_config", tpuEmbeddingConfig) + op.updateAttribute("is_global_init", isGlobalInit) + return op.execute(Int(1)) } /// Returns the complex conjugate of a complex number. @@ -4752,13 +4752,13 @@ public static func configureDistributedTPU( /// ``` @inlinable @inline(__always) public static func conj( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Conj", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Conj", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Shuffle dimensions of x according to a permutation and conjugate the result. @@ -4771,25 +4771,25 @@ public static func conjugateTranspose< T: TensorFlowScalar, Tperm: BinaryInteger & TensorFlowScalar >( - _ x: Tensor, - perm: Tensor + _ x: Tensor, + perm: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ConjugateTranspose", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tperm", Tperm.tensorFlowDataType) - op.addInput(x) - op.addInput(perm) - return op.execute(Int(1)) + let op = makeOp("ConjugateTranspose", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tperm", Tperm.tensorFlowDataType) + op.addInput(x) + op.addInput(perm) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func constructionFails( ) { let nOutputs = 0 - let op = makeOp("ConstructionFails", nOutputs) - - op.execute() + let op = makeOp("ConstructionFails", nOutputs) + + op.execute() } /// This op consumes a lock created by `MutexLock`. @@ -4805,12 +4805,12 @@ public static func constructionFails( /// - Parameter mutex_lock: A tensor returned by `MutexLock`. @inlinable @inline(__always) public static func consumeMutexLock( - mutexLock: VariantHandle + mutexLock: VariantHandle ) { let nOutputs = 0 - let op = makeOp("ConsumeMutexLock", nOutputs) - op.addInput(mutexLock) - op.execute() + let op = makeOp("ConsumeMutexLock", nOutputs) + op.addInput(mutexLock) + op.execute() } /// Does nothing. Serves as a control trigger for scheduling. @@ -4820,9 +4820,9 @@ public static func consumeMutexLock( public static func controlTrigger( ) { let nOutputs = 0 - let op = makeOp("ControlTrigger", nOutputs) - - op.execute() + let op = makeOp("ControlTrigger", nOutputs) + + op.execute() } /// Computes a 2-D convolution given 4-D `input` and `filter` tensors. @@ -4850,175 +4850,175 @@ public static func controlTrigger( /// horizontal and vertices strides, `strides = [1, stride, stride, 1]`. /// /// - Parameters: -/// - input: A 4-D tensor. The dimension order is interpreted according to the value -/// of `data_format`, see below for details. -/// - filter: A 4-D tensor of shape -/// `[filter_height, filter_width, in_channels, out_channels]` +/// - input: A 4-D tensor. The dimension order is interpreted according to the value +/// of `data_format`, see below for details. +/// - filter: A 4-D tensor of shape +/// `[filter_height, filter_width, in_channels, out_channels]` /// /// - Attrs: -/// - strides: 1-D tensor of length 4. The stride of the sliding window for each -/// dimension of `input`. The dimension order is determined by the value of -/// `data_format`, see below for details. -/// - padding: The type of padding algorithm to use. -/// - explicit_paddings: If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith -/// dimension, the amount of padding inserted before and after the dimension is -/// `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If -/// `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, height, width, channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, channels, height, width]. -/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of -/// `input`. If set to k > 1, there will be k-1 skipped cells between each -/// filter element on that dimension. The dimension order is determined by the -/// value of `data_format`, see above for details. Dilations in the batch and -/// depth dimensions must be 1. +/// - strides: 1-D tensor of length 4. The stride of the sliding window for each +/// dimension of `input`. The dimension order is determined by the value of +/// `data_format`, see below for details. +/// - padding: The type of padding algorithm to use. +/// - explicit_paddings: If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith +/// dimension, the amount of padding inserted before and after the dimension is +/// `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If +/// `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, height, width, channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, channels, height, width]. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each +/// filter element on that dimension. The dimension order is determined by the +/// value of `data_format`, see above for details. Dilations in the batch and +/// depth dimensions must be 1. /// /// - Output output: A 4-D tensor. The dimension order is determined by the value of -/// `data_format`, see below for details. +/// `data_format`, see below for details. @inlinable @inline(__always) public static func conv2D( - _ input: Tensor, - filter: Tensor, - strides: [Int32], - useCudnnOnGpu: Bool = true, - padding: Padding2, - explicitPaddings: [Int32], - dataFormat: DataFormat = .nhwc, - dilations: [Int32] = [1, 1, 1, 1] -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("Conv2D", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("use_cudnn_on_gpu", useCudnnOnGpu) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("explicit_paddings", explicitPaddings) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filter) - return op.execute(Int(1)) + _ input: Tensor, + filter: Tensor, + strides: [Int32], + useCudnnOnGpu: Bool = true, + padding: Padding2, + explicitPaddings: [Int32], + dataFormat: DataFormat = .nhwc, + dilations: [Int32] = [1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conv2D", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("use_cudnn_on_gpu", useCudnnOnGpu) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("explicit_paddings", explicitPaddings) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + return op.execute(Int(1)) } /// Computes the gradients of convolution with respect to the filter. /// /// - Parameters: -/// - input: 4-D with shape `[batch, in_height, in_width, in_channels]`. -/// - filter_sizes: An integer vector representing the tensor shape of `filter`, -/// where `filter` is a 4-D -/// `[filter_height, filter_width, in_channels, out_channels]` tensor. -/// - out_backprop: 4-D with shape `[batch, out_height, out_width, out_channels]`. -/// Gradients w.r.t. the output of the convolution. +/// - input: 4-D with shape `[batch, in_height, in_width, in_channels]`. +/// - filter_sizes: An integer vector representing the tensor shape of `filter`, +/// where `filter` is a 4-D +/// `[filter_height, filter_width, in_channels, out_channels]` tensor. +/// - out_backprop: 4-D with shape `[batch, out_height, out_width, out_channels]`. +/// Gradients w.r.t. the output of the convolution. /// /// - Attrs: -/// - strides: The stride of the sliding window for each dimension of the input -/// of the convolution. Must be in the same order as the dimension specified with -/// format. -/// - padding: The type of padding algorithm to use. -/// - explicit_paddings: If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith -/// dimension, the amount of padding inserted before and after the dimension is -/// `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If -/// `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, in_channels, in_height, in_width]. -/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of -/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter -/// element on that dimension. The dimension order is determined by the value of -/// `data_format`, see above for details. Dilations in the batch and depth -/// dimensions must be 1. +/// - strides: The stride of the sliding window for each dimension of the input +/// of the convolution. Must be in the same order as the dimension specified with +/// format. +/// - padding: The type of padding algorithm to use. +/// - explicit_paddings: If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith +/// dimension, the amount of padding inserted before and after the dimension is +/// `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If +/// `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter +/// element on that dimension. The dimension order is determined by the value of +/// `data_format`, see above for details. Dilations in the batch and depth +/// dimensions must be 1. /// /// - Output output: 4-D with shape -/// `[filter_height, filter_width, in_channels, out_channels]`. Gradient w.r.t. -/// the `filter` input of the convolution. +/// `[filter_height, filter_width, in_channels, out_channels]`. Gradient w.r.t. +/// the `filter` input of the convolution. @inlinable @inline(__always) public static func conv2DBackpropFilter( - _ input: Tensor, - filterSizes: Tensor, - outBackprop: Tensor, - strides: [Int32], - useCudnnOnGpu: Bool = true, - padding: Padding2, - explicitPaddings: [Int32], - dataFormat: DataFormat = .nhwc, - dilations: [Int32] = [1, 1, 1, 1] -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("Conv2DBackpropFilter", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("use_cudnn_on_gpu", useCudnnOnGpu) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("explicit_paddings", explicitPaddings) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filterSizes) - op.addInput(outBackprop) - return op.execute(Int(1)) + _ input: Tensor, + filterSizes: Tensor, + outBackprop: Tensor, + strides: [Int32], + useCudnnOnGpu: Bool = true, + padding: Padding2, + explicitPaddings: [Int32], + dataFormat: DataFormat = .nhwc, + dilations: [Int32] = [1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conv2DBackpropFilter", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("use_cudnn_on_gpu", useCudnnOnGpu) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("explicit_paddings", explicitPaddings) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filterSizes) + op.addInput(outBackprop) + return op.execute(Int(1)) } /// Computes the gradients of convolution with respect to the input. /// /// - Parameters: -/// - input_sizes: An integer vector representing the shape of `input`, -/// where `input` is a 4-D `[batch, height, width, channels]` tensor. -/// - filter: 4-D with shape -/// `[filter_height, filter_width, in_channels, out_channels]`. -/// - out_backprop: 4-D with shape `[batch, out_height, out_width, out_channels]`. -/// Gradients w.r.t. the output of the convolution. +/// - input_sizes: An integer vector representing the shape of `input`, +/// where `input` is a 4-D `[batch, height, width, channels]` tensor. +/// - filter: 4-D with shape +/// `[filter_height, filter_width, in_channels, out_channels]`. +/// - out_backprop: 4-D with shape `[batch, out_height, out_width, out_channels]`. +/// Gradients w.r.t. the output of the convolution. /// /// - Attrs: -/// - strides: The stride of the sliding window for each dimension of the input -/// of the convolution. Must be in the same order as the dimension specified with -/// format. -/// - padding: The type of padding algorithm to use. -/// - explicit_paddings: If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith -/// dimension, the amount of padding inserted before and after the dimension is -/// `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If -/// `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, in_channels, in_height, in_width]. -/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of -/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter -/// element on that dimension. The dimension order is determined by the value of -/// `data_format`, see above for details. Dilations in the batch and depth -/// dimensions must be 1. +/// - strides: The stride of the sliding window for each dimension of the input +/// of the convolution. Must be in the same order as the dimension specified with +/// format. +/// - padding: The type of padding algorithm to use. +/// - explicit_paddings: If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith +/// dimension, the amount of padding inserted before and after the dimension is +/// `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If +/// `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter +/// element on that dimension. The dimension order is determined by the value of +/// `data_format`, see above for details. Dilations in the batch and depth +/// dimensions must be 1. /// /// - Output output: 4-D with shape `[batch, in_height, in_width, in_channels]`. Gradient -/// w.r.t. the input of the convolution. +/// w.r.t. the input of the convolution. @inlinable @inline(__always) public static func conv2DBackpropInput( - inputSizes: Tensor, - filter: Tensor, - outBackprop: Tensor, - strides: [Int32], - useCudnnOnGpu: Bool = true, - padding: Padding2, - explicitPaddings: [Int32], - dataFormat: DataFormat = .nhwc, - dilations: [Int32] = [1, 1, 1, 1] -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("Conv2DBackpropInput", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("use_cudnn_on_gpu", useCudnnOnGpu) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("explicit_paddings", explicitPaddings) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("dilations", dilations) - op.addInput(inputSizes) - op.addInput(filter) - op.addInput(outBackprop) - return op.execute(Int(1)) + inputSizes: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + useCudnnOnGpu: Bool = true, + padding: Padding2, + explicitPaddings: [Int32], + dataFormat: DataFormat = .nhwc, + dilations: [Int32] = [1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conv2DBackpropInput", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("use_cudnn_on_gpu", useCudnnOnGpu) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("explicit_paddings", explicitPaddings) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(inputSizes) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) } /// Computes a 3-D convolution given 5-D `input` and `filter` tensors. @@ -5030,211 +5030,211 @@ public static func conv2DBackpropInput( /// Our Conv3D implements a form of cross-correlation. /// /// - Parameters: -/// - input: Shape `[batch, in_depth, in_height, in_width, in_channels]`. -/// - filter: Shape `[filter_depth, filter_height, filter_width, in_channels, -/// out_channels]`. `in_channels` must match between `input` and `filter`. +/// - input: Shape `[batch, in_depth, in_height, in_width, in_channels]`. +/// - filter: Shape `[filter_depth, filter_height, filter_width, in_channels, +/// out_channels]`. `in_channels` must match between `input` and `filter`. /// /// - Attrs: -/// - strides: 1-D tensor of length 5. The stride of the sliding window for each -/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. -/// - padding: The type of padding algorithm to use. -/// - data_format: The data format of the input and output data. With the -/// default format "NDHWC", the data is stored in the order of: -/// [batch, in_depth, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCDHW", the data storage order is: -/// [batch, in_channels, in_depth, in_height, in_width]. -/// - dilations: 1-D tensor of length 5. The dilation factor for each dimension of -/// `input`. If set to k > 1, there will be k-1 skipped cells between each -/// filter element on that dimension. The dimension order is determined by the -/// value of `data_format`, see above for details. Dilations in the batch and -/// depth dimensions must be 1. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. +/// - dilations: 1-D tensor of length 5. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each +/// filter element on that dimension. The dimension order is determined by the +/// value of `data_format`, see above for details. Dilations in the batch and +/// depth dimensions must be 1. @inlinable @inline(__always) public static func conv3D( - _ input: Tensor, - filter: Tensor, - strides: [Int32], - padding: Padding, - dataFormat: DataFormat1 = .ndhwc, - dilations: [Int32] = [1, 1, 1, 1, 1] + _ input: Tensor, + filter: Tensor, + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc, + dilations: [Int32] = [1, 1, 1, 1, 1] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Conv3D", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filter) - return op.execute(Int(1)) + let op = makeOp("Conv3D", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + return op.execute(Int(1)) } /// Computes the gradients of 3-D convolution with respect to the filter. /// /// - Parameters: -/// - input: Shape `[batch, depth, rows, cols, in_channels]`. -/// - filter: Shape `[depth, rows, cols, in_channels, out_channels]`. -/// `in_channels` must match between `input` and `filter`. -/// - out_backprop: Backprop signal of shape `[batch, out_depth, out_rows, out_cols, -/// out_channels]`. +/// - input: Shape `[batch, depth, rows, cols, in_channels]`. +/// - filter: Shape `[depth, rows, cols, in_channels, out_channels]`. +/// `in_channels` must match between `input` and `filter`. +/// - out_backprop: Backprop signal of shape `[batch, out_depth, out_rows, out_cols, +/// out_channels]`. /// /// - Attrs: -/// - strides: 1-D tensor of length 5. The stride of the sliding window for each -/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. -/// - padding: The type of padding algorithm to use. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. @inlinable @inline(__always) public static func conv3DBackpropFilter( - _ input: Tensor, - filter: Tensor, - outBackprop: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1, 1] + _ input: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1, 1] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Conv3DBackpropFilter", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filter) - op.addInput(outBackprop) - return op.execute(Int(1)) + let op = makeOp("Conv3DBackpropFilter", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) } /// Computes the gradients of 3-D convolution with respect to the filter. /// /// - Parameters: -/// - input: Shape `[batch, depth, rows, cols, in_channels]`. -/// - filter_sizes: An integer vector representing the tensor shape of `filter`, -/// where `filter` is a 5-D -/// `[filter_depth, filter_height, filter_width, in_channels, out_channels]` -/// tensor. -/// - out_backprop: Backprop signal of shape `[batch, out_depth, out_rows, out_cols, -/// out_channels]`. +/// - input: Shape `[batch, depth, rows, cols, in_channels]`. +/// - filter_sizes: An integer vector representing the tensor shape of `filter`, +/// where `filter` is a 5-D +/// `[filter_depth, filter_height, filter_width, in_channels, out_channels]` +/// tensor. +/// - out_backprop: Backprop signal of shape `[batch, out_depth, out_rows, out_cols, +/// out_channels]`. /// /// - Attrs: -/// - strides: 1-D tensor of length 5. The stride of the sliding window for each -/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. -/// - padding: The type of padding algorithm to use. -/// - data_format: The data format of the input and output data. With the -/// default format "NDHWC", the data is stored in the order of: -/// [batch, in_depth, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCDHW", the data storage order is: -/// [batch, in_channels, in_depth, in_height, in_width]. -/// - dilations: 1-D tensor of length 5. The dilation factor for each dimension of -/// `input`. If set to k > 1, there will be k-1 skipped cells between each -/// filter element on that dimension. The dimension order is determined by the -/// value of `data_format`, see above for details. Dilations in the batch and -/// depth dimensions must be 1. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. +/// - dilations: 1-D tensor of length 5. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each +/// filter element on that dimension. The dimension order is determined by the +/// value of `data_format`, see above for details. Dilations in the batch and +/// depth dimensions must be 1. @inlinable @inline(__always) public static func conv3DBackpropFilterV2( - _ input: Tensor, - filterSizes: Tensor, - outBackprop: Tensor, - strides: [Int32], - padding: Padding, - dataFormat: DataFormat1 = .ndhwc, - dilations: [Int32] = [1, 1, 1, 1, 1] -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("Conv3DBackpropFilterV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filterSizes) - op.addInput(outBackprop) - return op.execute(Int(1)) + _ input: Tensor, + filterSizes: Tensor, + outBackprop: Tensor, + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc, + dilations: [Int32] = [1, 1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conv3DBackpropFilterV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filterSizes) + op.addInput(outBackprop) + return op.execute(Int(1)) } /// Computes the gradients of 3-D convolution with respect to the input. /// /// - Parameters: -/// - input: Shape `[batch, depth, rows, cols, in_channels]`. -/// - filter: Shape `[depth, rows, cols, in_channels, out_channels]`. -/// `in_channels` must match between `input` and `filter`. -/// - out_backprop: Backprop signal of shape `[batch, out_depth, out_rows, out_cols, -/// out_channels]`. +/// - input: Shape `[batch, depth, rows, cols, in_channels]`. +/// - filter: Shape `[depth, rows, cols, in_channels, out_channels]`. +/// `in_channels` must match between `input` and `filter`. +/// - out_backprop: Backprop signal of shape `[batch, out_depth, out_rows, out_cols, +/// out_channels]`. /// /// - Attrs: -/// - strides: 1-D tensor of length 5. The stride of the sliding window for each -/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. -/// - padding: The type of padding algorithm to use. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. @inlinable @inline(__always) public static func conv3DBackpropInput( - _ input: Tensor, - filter: Tensor, - outBackprop: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1, 1] + _ input: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1, 1] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Conv3DBackpropInput", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filter) - op.addInput(outBackprop) - return op.execute(Int(1)) + let op = makeOp("Conv3DBackpropInput", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) } /// Computes the gradients of 3-D convolution with respect to the input. /// /// - Parameters: -/// - input_sizes: An integer vector representing the tensor shape of `input`, -/// where `input` is a 5-D -/// `[batch, depth, rows, cols, in_channels]` tensor. -/// - filter: Shape `[depth, rows, cols, in_channels, out_channels]`. -/// `in_channels` must match between `input` and `filter`. -/// - out_backprop: Backprop signal of shape `[batch, out_depth, out_rows, out_cols, -/// out_channels]`. +/// - input_sizes: An integer vector representing the tensor shape of `input`, +/// where `input` is a 5-D +/// `[batch, depth, rows, cols, in_channels]` tensor. +/// - filter: Shape `[depth, rows, cols, in_channels, out_channels]`. +/// `in_channels` must match between `input` and `filter`. +/// - out_backprop: Backprop signal of shape `[batch, out_depth, out_rows, out_cols, +/// out_channels]`. /// /// - Attrs: -/// - strides: 1-D tensor of length 5. The stride of the sliding window for each -/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. -/// - padding: The type of padding algorithm to use. -/// - data_format: The data format of the input and output data. With the -/// default format "NDHWC", the data is stored in the order of: -/// [batch, in_depth, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCDHW", the data storage order is: -/// [batch, in_channels, in_depth, in_height, in_width]. -/// - dilations: 1-D tensor of length 5. The dilation factor for each dimension of -/// `input`. If set to k > 1, there will be k-1 skipped cells between each -/// filter element on that dimension. The dimension order is determined by the -/// value of `data_format`, see above for details. Dilations in the batch and -/// depth dimensions must be 1. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. +/// - dilations: 1-D tensor of length 5. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each +/// filter element on that dimension. The dimension order is determined by the +/// value of `data_format`, see above for details. Dilations in the batch and +/// depth dimensions must be 1. @inlinable @inline(__always) public static func conv3DBackpropInputV2< T: FloatingPoint & TensorFlowScalar, Tshape: BinaryInteger & TensorFlowScalar >( - inputSizes: Tensor, - filter: Tensor, - outBackprop: Tensor, - strides: [Int32], - padding: Padding, - dataFormat: DataFormat1 = .ndhwc, - dilations: [Int32] = [1, 1, 1, 1, 1] -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("Conv3DBackpropInputV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("dilations", dilations) - op.updateAttribute("Tshape", Tshape.tensorFlowDataType) - op.addInput(inputSizes) - op.addInput(filter) - op.addInput(outBackprop) - return op.execute(Int(1)) + inputSizes: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc, + dilations: [Int32] = [1, 1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("Conv3DBackpropInputV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("Tshape", Tshape.tensorFlowDataType) + op.addInput(inputSizes) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) } /// Copy Op. @@ -5251,27 +5251,27 @@ public static func conv3DBackpropInputV2< /// - Parameter input: Input tensor. /// /// - Attrs: -/// - tensor_name: The name of the input tensor. -/// - debug_ops_spec: A list of debug op spec (op, url, gated_grpc) for attached debug -/// ops. Each element of the list has the format -/// ;;, wherein gated_grpc is boolean represented -/// as 0/1. E.g., "DebugIdentity;grpc://foo:3333;1", -/// "DebugIdentity;file:///tmp/tfdbg_1;0". +/// - tensor_name: The name of the input tensor. +/// - debug_ops_spec: A list of debug op spec (op, url, gated_grpc) for attached debug +/// ops. Each element of the list has the format +/// ;;, wherein gated_grpc is boolean represented +/// as 0/1. E.g., "DebugIdentity;grpc://foo:3333;1", +/// "DebugIdentity;file:///tmp/tfdbg_1;0". /// /// - Output output: Output tensor, deep-copied from input. @inlinable @inline(__always) public static func copy( - _ input: Tensor, - tensorName: String, - debugOpsSpec: [String] + _ input: Tensor, + tensorName: String, + debugOpsSpec: [String] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Copy", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("tensor_name", tensorName) - op.updateAttribute("debug_ops_spec", debugOpsSpec) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Copy", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("tensor_name", tensorName) + op.updateAttribute("debug_ops_spec", debugOpsSpec) + op.addInput(input) + return op.execute(Int(1)) } /// Copy Host Op. @@ -5286,98 +5286,98 @@ public static func copy( /// - Parameter input: Input tensor. /// /// - Attrs: -/// - tensor_name: The name of the input tensor. -/// - debug_ops_spec: A list of debug op spec (op, url, gated_grpc) for attached debug -/// ops. Each element of the list has the format -/// ;;, wherein gated_grpc is boolean represented -/// as 0/1. E.g., "DebugIdentity;grpc://foo:3333;1", -/// "DebugIdentity;file:///tmp/tfdbg_1;0". +/// - tensor_name: The name of the input tensor. +/// - debug_ops_spec: A list of debug op spec (op, url, gated_grpc) for attached debug +/// ops. Each element of the list has the format +/// ;;, wherein gated_grpc is boolean represented +/// as 0/1. E.g., "DebugIdentity;grpc://foo:3333;1", +/// "DebugIdentity;file:///tmp/tfdbg_1;0". /// /// - Output output: Output tensor, deep-copied from input. @inlinable @inline(__always) public static func copyHost( - _ input: Tensor, - tensorName: String, - debugOpsSpec: [String] + _ input: Tensor, + tensorName: String, + debugOpsSpec: [String] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CopyHost", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("tensor_name", tensorName) - op.updateAttribute("debug_ops_spec", debugOpsSpec) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("CopyHost", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("tensor_name", tensorName) + op.updateAttribute("debug_ops_spec", debugOpsSpec) + op.addInput(input) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func copyOp( - _ a: Tensor + _ a: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CopyOp", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - return op.execute(Int(1)) + let op = makeOp("CopyOp", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + return op.execute(Int(1)) } /// Computes cos of x element-wise. @inlinable @inline(__always) public static func cos( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Cos", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Cos", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes hyperbolic cosine of x element-wise. @inlinable @inline(__always) public static func cosh( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Cosh", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Cosh", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func createSummaryDbWriter( - writer: ResourceHandle, - dbUri: StringTensor, - experimentName: StringTensor, - runName: StringTensor, - userName: StringTensor + writer: ResourceHandle, + dbUri: StringTensor, + experimentName: StringTensor, + runName: StringTensor, + userName: StringTensor ) { let nOutputs = 0 - let op = makeOp("CreateSummaryDbWriter", nOutputs) - op.addInput(writer) - op.addInput(dbUri) - op.addInput(experimentName) - op.addInput(runName) - op.addInput(userName) - op.execute() + let op = makeOp("CreateSummaryDbWriter", nOutputs) + op.addInput(writer) + op.addInput(dbUri) + op.addInput(experimentName) + op.addInput(runName) + op.addInput(userName) + op.execute() } @inlinable @inline(__always) public static func createSummaryFileWriter( - writer: ResourceHandle, - logdir: StringTensor, - maxQueue: Tensor, - flushMillis: Tensor, - filenameSuffix: StringTensor + writer: ResourceHandle, + logdir: StringTensor, + maxQueue: Tensor, + flushMillis: Tensor, + filenameSuffix: StringTensor ) { let nOutputs = 0 - let op = makeOp("CreateSummaryFileWriter", nOutputs) - op.addInput(writer) - op.addInput(logdir) - op.addInput(maxQueue) - op.addInput(flushMillis) - op.addInput(filenameSuffix) - op.execute() + let op = makeOp("CreateSummaryFileWriter", nOutputs) + op.addInput(writer) + op.addInput(logdir) + op.addInput(maxQueue) + op.addInput(flushMillis) + op.addInput(filenameSuffix) + op.execute() } /// Extracts crops from the input image tensor and resizes them. @@ -5399,136 +5399,136 @@ public static func createSummaryFileWriter( /// `align_corners=True`. /// /// - Parameters: -/// - image: A 4-D tensor of shape `[batch, image_height, image_width, depth]`. -/// Both `image_height` and `image_width` need to be positive. -/// - boxes: A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor -/// specifies the coordinates of a box in the `box_ind[i]` image and is specified -/// in normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of -/// `y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the -/// `[0, 1]` interval of normalized image height is mapped to -/// `[0, image_height - 1]` in image height coordinates. We do allow `y1` > `y2`, in -/// which case the sampled crop is an up-down flipped version of the original -/// image. The width dimension is treated similarly. Normalized coordinates -/// outside the `[0, 1]` range are allowed, in which case we use -/// `extrapolation_value` to extrapolate the input image values. -/// - box_ind: A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`. -/// The value of `box_ind[i]` specifies the image that the `i`-th box refers to. -/// - crop_size: A 1-D tensor of 2 elements, `size = [crop_height, crop_width]`. All -/// cropped image patches are resized to this size. The aspect ratio of the image -/// content is not preserved. Both `crop_height` and `crop_width` need to be -/// positive. +/// - image: A 4-D tensor of shape `[batch, image_height, image_width, depth]`. +/// Both `image_height` and `image_width` need to be positive. +/// - boxes: A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor +/// specifies the coordinates of a box in the `box_ind[i]` image and is specified +/// in normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of +/// `y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the +/// `[0, 1]` interval of normalized image height is mapped to +/// `[0, image_height - 1]` in image height coordinates. We do allow `y1` > `y2`, in +/// which case the sampled crop is an up-down flipped version of the original +/// image. The width dimension is treated similarly. Normalized coordinates +/// outside the `[0, 1]` range are allowed, in which case we use +/// `extrapolation_value` to extrapolate the input image values. +/// - box_ind: A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`. +/// The value of `box_ind[i]` specifies the image that the `i`-th box refers to. +/// - crop_size: A 1-D tensor of 2 elements, `size = [crop_height, crop_width]`. All +/// cropped image patches are resized to this size. The aspect ratio of the image +/// content is not preserved. Both `crop_height` and `crop_width` need to be +/// positive. /// /// - Attrs: -/// - method: A string specifying the sampling method for resizing. It can be either -/// `"bilinear"` or `"nearest"` and default to `"bilinear"`. Currently two sampling -/// methods are supported: Bilinear and Nearest Neighbor. -/// - extrapolation_value: Value used for extrapolation, when applicable. +/// - method: A string specifying the sampling method for resizing. It can be either +/// `"bilinear"` or `"nearest"` and default to `"bilinear"`. Currently two sampling +/// methods are supported: Bilinear and Nearest Neighbor. +/// - extrapolation_value: Value used for extrapolation, when applicable. /// /// - Output crops: A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`. @inlinable @inline(__always) public static func cropAndResize( - image: Tensor, - boxes: Tensor, - boxInd: Tensor, - cropSize: Tensor, - method: Method = .bilinear, - extrapolationValue: Double = 0 + image: Tensor, + boxes: Tensor, + boxInd: Tensor, + cropSize: Tensor, + method: Method = .bilinear, + extrapolationValue: Double = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CropAndResize", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("method", method.cName) - op.updateAttribute("extrapolation_value", extrapolationValue) - op.addInput(image) - op.addInput(boxes) - op.addInput(boxInd) - op.addInput(cropSize) - return op.execute(Int(1)) + let op = makeOp("CropAndResize", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("method", method.cName) + op.updateAttribute("extrapolation_value", extrapolationValue) + op.addInput(image) + op.addInput(boxes) + op.addInput(boxInd) + op.addInput(cropSize) + return op.execute(Int(1)) } /// Computes the gradient of the crop_and_resize op wrt the input boxes tensor. /// /// - Parameters: -/// - grads: A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`. -/// - image: A 4-D tensor of shape `[batch, image_height, image_width, depth]`. -/// Both `image_height` and `image_width` need to be positive. -/// - boxes: A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor -/// specifies the coordinates of a box in the `box_ind[i]` image and is specified -/// in normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of -/// `y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the -/// `[0, 1]` interval of normalized image height is mapped to -/// `[0, image_height - 1] in image height coordinates. We do allow y1 > y2, in -/// which case the sampled crop is an up-down flipped version of the original -/// image. The width dimension is treated similarly. Normalized coordinates -/// outside the `[0, 1]` range are allowed, in which case we use -/// `extrapolation_value` to extrapolate the input image values. -/// - box_ind: A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`. -/// The value of `box_ind[i]` specifies the image that the `i`-th box refers to. +/// - grads: A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`. +/// - image: A 4-D tensor of shape `[batch, image_height, image_width, depth]`. +/// Both `image_height` and `image_width` need to be positive. +/// - boxes: A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor +/// specifies the coordinates of a box in the `box_ind[i]` image and is specified +/// in normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of +/// `y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the +/// `[0, 1]` interval of normalized image height is mapped to +/// `[0, image_height - 1] in image height coordinates. We do allow y1 > y2, in +/// which case the sampled crop is an up-down flipped version of the original +/// image. The width dimension is treated similarly. Normalized coordinates +/// outside the `[0, 1]` range are allowed, in which case we use +/// `extrapolation_value` to extrapolate the input image values. +/// - box_ind: A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`. +/// The value of `box_ind[i]` specifies the image that the `i`-th box refers to. /// /// - Attr method: A string specifying the interpolation method. Only 'bilinear' is -/// supported for now. +/// supported for now. /// /// - Output output: A 2-D tensor of shape `[num_boxes, 4]`. @inlinable @inline(__always) public static func cropAndResizeGradBoxes( - grads: Tensor, - image: Tensor, - boxes: Tensor, - boxInd: Tensor, - method: Method3 = .bilinear + grads: Tensor, + image: Tensor, + boxes: Tensor, + boxInd: Tensor, + method: Method3 = .bilinear ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CropAndResizeGradBoxes", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("method", method.cName) - op.addInput(grads) - op.addInput(image) - op.addInput(boxes) - op.addInput(boxInd) - return op.execute(Int(1)) + let op = makeOp("CropAndResizeGradBoxes", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("method", method.cName) + op.addInput(grads) + op.addInput(image) + op.addInput(boxes) + op.addInput(boxInd) + return op.execute(Int(1)) } /// Computes the gradient of the crop_and_resize op wrt the input image tensor. /// /// - Parameters: -/// - grads: A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`. -/// - boxes: A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor -/// specifies the coordinates of a box in the `box_ind[i]` image and is specified -/// in normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of -/// `y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the -/// `[0, 1]` interval of normalized image height is mapped to -/// `[0, image_height - 1] in image height coordinates. We do allow y1 > y2, in -/// which case the sampled crop is an up-down flipped version of the original -/// image. The width dimension is treated similarly. Normalized coordinates -/// outside the `[0, 1]` range are allowed, in which case we use -/// `extrapolation_value` to extrapolate the input image values. -/// - box_ind: A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`. -/// The value of `box_ind[i]` specifies the image that the `i`-th box refers to. -/// - image_size: A 1-D tensor with value `[batch, image_height, image_width, depth]` -/// containing the original image size. Both `image_height` and `image_width` need -/// to be positive. +/// - grads: A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`. +/// - boxes: A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor +/// specifies the coordinates of a box in the `box_ind[i]` image and is specified +/// in normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of +/// `y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the +/// `[0, 1]` interval of normalized image height is mapped to +/// `[0, image_height - 1] in image height coordinates. We do allow y1 > y2, in +/// which case the sampled crop is an up-down flipped version of the original +/// image. The width dimension is treated similarly. Normalized coordinates +/// outside the `[0, 1]` range are allowed, in which case we use +/// `extrapolation_value` to extrapolate the input image values. +/// - box_ind: A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`. +/// The value of `box_ind[i]` specifies the image that the `i`-th box refers to. +/// - image_size: A 1-D tensor with value `[batch, image_height, image_width, depth]` +/// containing the original image size. Both `image_height` and `image_width` need +/// to be positive. /// /// - Attr method: A string specifying the interpolation method. Only 'bilinear' is -/// supported for now. +/// supported for now. /// /// - Output output: A 4-D tensor of shape `[batch, image_height, image_width, depth]`. @inlinable @inline(__always) public static func cropAndResizeGradImage( - grads: Tensor, - boxes: Tensor, - boxInd: Tensor, - imageSize: Tensor, - method: Method = .bilinear + grads: Tensor, + boxes: Tensor, + boxInd: Tensor, + imageSize: Tensor, + method: Method = .bilinear ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CropAndResizeGradImage", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("method", method.cName) - op.addInput(grads) - op.addInput(boxes) - op.addInput(boxInd) - op.addInput(imageSize) - return op.execute(Int(1)) + let op = makeOp("CropAndResizeGradImage", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("method", method.cName) + op.addInput(grads) + op.addInput(boxes) + op.addInput(boxInd) + op.addInput(imageSize) + return op.execute(Int(1)) } /// Compute the pairwise cross product. @@ -5538,21 +5538,21 @@ public static func cropAndResizeGradImage( /// of corresponding 3-element vectors is cross-multiplied independently. /// /// - Parameters: -/// - a: A tensor containing 3-element vectors. -/// - b: Another tensor, of same type and shape as `a`. +/// - a: A tensor containing 3-element vectors. +/// - b: Another tensor, of same type and shape as `a`. /// /// - Output product: Pairwise cross product of the vectors in `a` and `b`. @inlinable @inline(__always) public static func cross( - _ a: Tensor, - _ b: Tensor + _ a: Tensor, + _ b: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Cross", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - op.addInput(b) - return op.execute(Int(1)) + let op = makeOp("Cross", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(b) + return op.execute(Int(1)) } /// An Op to sum inputs across replicated TPU instances. @@ -5565,25 +5565,25 @@ public static func cross( /// `[A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H]`. /// /// - Parameters: -/// - input: The local input to the sum. -/// - group_assignment: An int32 tensor with shape -/// [num_groups, num_replicas_per_group]. `group_assignment[i]` represents the -/// replica ids in the ith subgroup. +/// - input: The local input to the sum. +/// - group_assignment: An int32 tensor with shape +/// [num_groups, num_replicas_per_group]. `group_assignment[i]` represents the +/// replica ids in the ith subgroup. /// /// - Attr T: The type of elements to be summed. /// /// - Output output: The sum of all the distributed inputs. @inlinable @inline(__always) public static func crossReplicaSum( - _ input: Tensor, - groupAssignment: Tensor + _ input: Tensor, + groupAssignment: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CrossReplicaSum", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - op.addInput(groupAssignment) - return op.execute(Int(1)) + let op = makeOp("CrossReplicaSum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(groupAssignment) + return op.execute(Int(1)) } /// A RNN backed by cuDNN. @@ -5620,33 +5620,33 @@ public static func crossReplicaSum( /// is only produced if is_training is false. @inlinable @inline(__always) public static func cudnnRNN( - _ input: Tensor, - inputH: Tensor, - inputC: Tensor, - params: Tensor, - rnnMode: RnnMode = .lstm, - inputMode: InputMode = .linearInput, - direction: Direction = .unidirectional, - dropout: Double = 0, - seed: Int64 = 0, - seed2: Int64 = 0, - isTraining: Bool = true + _ input: Tensor, + inputH: Tensor, + inputC: Tensor, + params: Tensor, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0, + isTraining: Bool = true ) -> (output: Tensor, outputH: Tensor, outputC: Tensor, reserveSpace: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("CudnnRNN", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("rnn_mode", rnnMode.cName) - op.updateAttribute("input_mode", inputMode.cName) - op.updateAttribute("direction", direction.cName) - op.updateAttribute("dropout", dropout) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("is_training", isTraining) - op.addInput(input) - op.addInput(inputH) - op.addInput(inputC) - op.addInput(params) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("CudnnRNN", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("is_training", isTraining) + op.addInput(input) + op.addInput(inputH) + op.addInput(inputC) + op.addInput(params) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Backprop step of CudnnRNN. @@ -5692,45 +5692,45 @@ public static func cudnnRNN( /// same shape as params. @inlinable @inline(__always) public static func cudnnRNNBackprop( - _ input: Tensor, - inputH: Tensor, - inputC: Tensor, - params: Tensor, - output: Tensor, - outputH: Tensor, - outputC: Tensor, - outputBackprop: Tensor, - outputHBackprop: Tensor, - outputCBackprop: Tensor, - reserveSpace: Tensor, - rnnMode: RnnMode = .lstm, - inputMode: InputMode = .linearInput, - direction: Direction = .unidirectional, - dropout: Double = 0, - seed: Int64 = 0, - seed2: Int64 = 0 + _ input: Tensor, + inputH: Tensor, + inputC: Tensor, + params: Tensor, + output: Tensor, + outputH: Tensor, + outputC: Tensor, + outputBackprop: Tensor, + outputHBackprop: Tensor, + outputCBackprop: Tensor, + reserveSpace: Tensor, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> (inputBackprop: Tensor, inputHBackprop: Tensor, inputCBackprop: Tensor, paramsBackprop: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("CudnnRNNBackprop", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("rnn_mode", rnnMode.cName) - op.updateAttribute("input_mode", inputMode.cName) - op.updateAttribute("direction", direction.cName) - op.updateAttribute("dropout", dropout) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.addInput(input) - op.addInput(inputH) - op.addInput(inputC) - op.addInput(params) - op.addInput(output) - op.addInput(outputH) - op.addInput(outputC) - op.addInput(outputBackprop) - op.addInput(outputHBackprop) - op.addInput(outputCBackprop) - op.addInput(reserveSpace) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("CudnnRNNBackprop", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(input) + op.addInput(inputH) + op.addInput(inputC) + op.addInput(params) + op.addInput(output) + op.addInput(outputH) + op.addInput(outputC) + op.addInput(outputBackprop) + op.addInput(outputHBackprop) + op.addInput(outputCBackprop) + op.addInput(reserveSpace) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Backprop step of CudnnRNN. @@ -5779,47 +5779,47 @@ public static func cudnnRNNBackprop( /// same shape as params. @inlinable @inline(__always) public static func cudnnRNNBackpropV2( - _ input: Tensor, - inputH: Tensor, - inputC: Tensor, - params: Tensor, - output: Tensor, - outputH: Tensor, - outputC: Tensor, - outputBackprop: Tensor, - outputHBackprop: Tensor, - outputCBackprop: Tensor, - reserveSpace: Tensor, - hostReserved: Tensor, - rnnMode: RnnMode = .lstm, - inputMode: InputMode = .linearInput, - direction: Direction = .unidirectional, - dropout: Double = 0, - seed: Int64 = 0, - seed2: Int64 = 0 + _ input: Tensor, + inputH: Tensor, + inputC: Tensor, + params: Tensor, + output: Tensor, + outputH: Tensor, + outputC: Tensor, + outputBackprop: Tensor, + outputHBackprop: Tensor, + outputCBackprop: Tensor, + reserveSpace: Tensor, + hostReserved: Tensor, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> (inputBackprop: Tensor, inputHBackprop: Tensor, inputCBackprop: Tensor, paramsBackprop: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("CudnnRNNBackpropV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("rnn_mode", rnnMode.cName) - op.updateAttribute("input_mode", inputMode.cName) - op.updateAttribute("direction", direction.cName) - op.updateAttribute("dropout", dropout) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.addInput(input) - op.addInput(inputH) - op.addInput(inputC) - op.addInput(params) - op.addInput(output) - op.addInput(outputH) - op.addInput(outputC) - op.addInput(outputBackprop) - op.addInput(outputHBackprop) - op.addInput(outputCBackprop) - op.addInput(reserveSpace) - op.addInput(hostReserved) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("CudnnRNNBackpropV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(input) + op.addInput(inputH) + op.addInput(inputC) + op.addInput(params) + op.addInput(output) + op.addInput(outputH) + op.addInput(outputC) + op.addInput(outputBackprop) + op.addInput(outputHBackprop) + op.addInput(outputCBackprop) + op.addInput(reserveSpace) + op.addInput(hostReserved) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Backprop step of CudnnRNNV3. @@ -5873,51 +5873,51 @@ public static func cudnnRNNBackpropV2( /// same shape as params. @inlinable @inline(__always) public static func cudnnRNNBackpropV3( - _ input: Tensor, - inputH: Tensor, - inputC: Tensor, - params: Tensor, - sequenceLengths: Tensor, - output: Tensor, - outputH: Tensor, - outputC: Tensor, - outputBackprop: Tensor, - outputHBackprop: Tensor, - outputCBackprop: Tensor, - reserveSpace: Tensor, - hostReserved: Tensor, - rnnMode: RnnMode = .lstm, - inputMode: InputMode = .linearInput, - direction: Direction = .unidirectional, - dropout: Double = 0, - seed: Int64 = 0, - seed2: Int64 = 0, - timeMajor: Bool = true + _ input: Tensor, + inputH: Tensor, + inputC: Tensor, + params: Tensor, + sequenceLengths: Tensor, + output: Tensor, + outputH: Tensor, + outputC: Tensor, + outputBackprop: Tensor, + outputHBackprop: Tensor, + outputCBackprop: Tensor, + reserveSpace: Tensor, + hostReserved: Tensor, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0, + timeMajor: Bool = true ) -> (inputBackprop: Tensor, inputHBackprop: Tensor, inputCBackprop: Tensor, paramsBackprop: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("CudnnRNNBackpropV3", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("rnn_mode", rnnMode.cName) - op.updateAttribute("input_mode", inputMode.cName) - op.updateAttribute("direction", direction.cName) - op.updateAttribute("dropout", dropout) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("time_major", timeMajor) - op.addInput(input) - op.addInput(inputH) - op.addInput(inputC) - op.addInput(params) - op.addInput(sequenceLengths) - op.addInput(output) - op.addInput(outputH) - op.addInput(outputC) - op.addInput(outputBackprop) - op.addInput(outputHBackprop) - op.addInput(outputCBackprop) - op.addInput(reserveSpace) - op.addInput(hostReserved) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("CudnnRNNBackpropV3", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("time_major", timeMajor) + op.addInput(input) + op.addInput(inputH) + op.addInput(inputC) + op.addInput(params) + op.addInput(sequenceLengths) + op.addInput(output) + op.addInput(outputH) + op.addInput(outputC) + op.addInput(outputBackprop) + op.addInput(outputHBackprop) + op.addInput(outputCBackprop) + op.addInput(reserveSpace) + op.addInput(hostReserved) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Converts CudnnRNN params from canonical form to usable form. @@ -5953,34 +5953,34 @@ public static func cudnnRNNBackpropV3( /// seed2: the 2nd part of a seed to initialize dropout. @inlinable @inline(__always) public static func cudnnRNNCanonicalToParams( - numLayers: Tensor, - numUnits: Tensor, - inputSize: Tensor, - weights: [Tensor], - biases: [Tensor], - rnnMode: RnnMode = .lstm, - inputMode: InputMode = .linearInput, - direction: Direction = .unidirectional, - dropout: Double = 0, - seed: Int64 = 0, - seed2: Int64 = 0 -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("CudnnRNNCanonicalToParams", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("num_params", weights.count) - op.updateAttribute("rnn_mode", rnnMode.cName) - op.updateAttribute("input_mode", inputMode.cName) - op.updateAttribute("direction", direction.cName) - op.updateAttribute("dropout", dropout) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.addInput(numLayers) - op.addInput(numUnits) - op.addInput(inputSize) - op.addInputList(weights) - op.addInputList(biases) - return op.execute(Int(1)) + numLayers: Tensor, + numUnits: Tensor, + inputSize: Tensor, + weights: [Tensor], + biases: [Tensor], + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("CudnnRNNCanonicalToParams", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("num_params", weights.count) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(numLayers) + op.addInput(numUnits) + op.addInput(inputSize) + op.addInputList(weights) + op.addInputList(biases) + return op.execute(Int(1)) } /// Computes size of weights that can be used by a Cudnn RNN model. @@ -6008,31 +6008,31 @@ public static func cudnnRNNCanonicalToParams( - numLayers: Tensor, - numUnits: Tensor, - inputSize: Tensor, - t: TensorDataType, - rnnMode: RnnMode = .lstm, - inputMode: InputMode = .linearInput, - direction: Direction = .unidirectional, - dropout: Double = 0, - seed: Int64 = 0, - seed2: Int64 = 0 + numLayers: Tensor, + numUnits: Tensor, + inputSize: Tensor, + t: TensorDataType, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("CudnnRNNParamsSize", nOutputs) - op.updateAttribute("T", t) - op.updateAttribute("S", S.tensorFlowDataType) - op.updateAttribute("rnn_mode", rnnMode.cName) - op.updateAttribute("input_mode", inputMode.cName) - op.updateAttribute("direction", direction.cName) - op.updateAttribute("dropout", dropout) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.addInput(numLayers) - op.addInput(numUnits) - op.addInput(inputSize) - return op.execute(Int(1)) + let op = makeOp("CudnnRNNParamsSize", nOutputs) + op.updateAttribute("T", t) + op.updateAttribute("S", S.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(numLayers) + op.addInput(numUnits) + op.addInput(inputSize) + return op.execute(Int(1)) } /// Retrieves CudnnRNN params in canonical form. @@ -6068,33 +6068,33 @@ public static func cudnnRNNParamsSize( /// seed2: the 2nd part of a seed to initialize dropout. @inlinable @inline(__always) public static func cudnnRNNParamsToCanonical( - numLayers: Tensor, - numUnits: Tensor, - inputSize: Tensor, - params: Tensor, - numParams: Int64, - rnnMode: RnnMode = .lstm, - inputMode: InputMode = .linearInput, - direction: Direction = .unidirectional, - dropout: Double = 0, - seed: Int64 = 0, - seed2: Int64 = 0 + numLayers: Tensor, + numUnits: Tensor, + inputSize: Tensor, + params: Tensor, + numParams: Int64, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> (weights: [Tensor], biases: [Tensor]) { let nOutputs = Int(numParams) + Int(numParams) - let op = makeOp("CudnnRNNParamsToCanonical", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("num_params", numParams) - op.updateAttribute("rnn_mode", rnnMode.cName) - op.updateAttribute("input_mode", inputMode.cName) - op.updateAttribute("direction", direction.cName) - op.updateAttribute("dropout", dropout) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.addInput(numLayers) - op.addInput(numUnits) - op.addInput(inputSize) - op.addInput(params) - return op.execute(Int(numParams), Int(numParams)) + let op = makeOp("CudnnRNNParamsToCanonical", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("num_params", numParams) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(numLayers) + op.addInput(numUnits) + op.addInput(inputSize) + op.addInput(params) + return op.execute(Int(numParams), Int(numParams)) } /// A RNN backed by cuDNN. @@ -6134,33 +6134,33 @@ public static func cudnnRNNParamsToCanonical( - _ input: Tensor, - inputH: Tensor, - inputC: Tensor, - params: Tensor, - rnnMode: RnnMode = .lstm, - inputMode: InputMode = .linearInput, - direction: Direction = .unidirectional, - dropout: Double = 0, - seed: Int64 = 0, - seed2: Int64 = 0, - isTraining: Bool = true + _ input: Tensor, + inputH: Tensor, + inputC: Tensor, + params: Tensor, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0, + isTraining: Bool = true ) -> (output: Tensor, outputH: Tensor, outputC: Tensor, reserveSpace: Tensor, hostReserved: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("CudnnRNNV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("rnn_mode", rnnMode.cName) - op.updateAttribute("input_mode", inputMode.cName) - op.updateAttribute("direction", direction.cName) - op.updateAttribute("dropout", dropout) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("is_training", isTraining) - op.addInput(input) - op.addInput(inputH) - op.addInput(inputC) - op.addInput(params) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("CudnnRNNV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("is_training", isTraining) + op.addInput(input) + op.addInput(inputH) + op.addInput(inputC) + op.addInput(params) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) } /// A RNN backed by cuDNN. @@ -6204,37 +6204,37 @@ public static func cudnnRNNV2( /// is only produced if is_training is true. @inlinable @inline(__always) public static func cudnnRNNV3( - _ input: Tensor, - inputH: Tensor, - inputC: Tensor, - params: Tensor, - sequenceLengths: Tensor, - rnnMode: RnnMode = .lstm, - inputMode: InputMode = .linearInput, - direction: Direction = .unidirectional, - dropout: Double = 0, - seed: Int64 = 0, - seed2: Int64 = 0, - isTraining: Bool = true, - timeMajor: Bool = true + _ input: Tensor, + inputH: Tensor, + inputC: Tensor, + params: Tensor, + sequenceLengths: Tensor, + rnnMode: RnnMode = .lstm, + inputMode: InputMode = .linearInput, + direction: Direction = .unidirectional, + dropout: Double = 0, + seed: Int64 = 0, + seed2: Int64 = 0, + isTraining: Bool = true, + timeMajor: Bool = true ) -> (output: Tensor, outputH: Tensor, outputC: Tensor, reserveSpace: Tensor, hostReserved: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("CudnnRNNV3", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("rnn_mode", rnnMode.cName) - op.updateAttribute("input_mode", inputMode.cName) - op.updateAttribute("direction", direction.cName) - op.updateAttribute("dropout", dropout) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("is_training", isTraining) - op.updateAttribute("time_major", timeMajor) - op.addInput(input) - op.addInput(inputH) - op.addInput(inputC) - op.addInput(params) - op.addInput(sequenceLengths) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("CudnnRNNV3", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("rnn_mode", rnnMode.cName) + op.updateAttribute("input_mode", inputMode.cName) + op.updateAttribute("direction", direction.cName) + op.updateAttribute("dropout", dropout) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("is_training", isTraining) + op.updateAttribute("time_major", timeMajor) + op.addInput(input) + op.addInput(inputH) + op.addInput(inputC) + op.addInput(params) + op.addInput(sequenceLengths) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) } /// Compute the cumulative product of the tensor `x` along `axis`. @@ -6269,34 +6269,34 @@ public static func cudnnRNNV3( /// ``` /// /// - Parameters: -/// - x: A `Tensor`. Must be one of the following types: `float32`, `float64`, -/// `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, -/// `complex128`, `qint8`, `quint8`, `qint32`, `half`. -/// - axis: A `Tensor` of type `int32` (default: 0). Must be in the range -/// `[-rank(x), rank(x))`. +/// - x: A `Tensor`. Must be one of the following types: `float32`, `float64`, +/// `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, +/// `complex128`, `qint8`, `quint8`, `qint32`, `half`. +/// - axis: A `Tensor` of type `int32` (default: 0). Must be in the range +/// `[-rank(x), rank(x))`. /// /// - Attrs: -/// - exclusive: If `True`, perform exclusive cumprod. -/// - reverse: A `bool` (default: False). +/// - exclusive: If `True`, perform exclusive cumprod. +/// - reverse: A `bool` (default: False). @inlinable @inline(__always) public static func cumprod< T: Numeric & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - _ x: Tensor, - axis: Tensor, - exclusive: Bool = false, - reverse: Bool = false + _ x: Tensor, + axis: Tensor, + exclusive: Bool = false, + reverse: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Cumprod", nOutputs) - op.updateAttribute("exclusive", exclusive) - op.updateAttribute("reverse", reverse) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(x) - op.addInput(axis) - return op.execute(Int(1)) + let op = makeOp("Cumprod", nOutputs) + op.updateAttribute("exclusive", exclusive) + op.updateAttribute("reverse", reverse) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(x) + op.addInput(axis) + return op.execute(Int(1)) } /// Compute the cumulative sum of the tensor `x` along `axis`. @@ -6331,34 +6331,34 @@ public static func cumprod< /// ``` /// /// - Parameters: -/// - x: A `Tensor`. Must be one of the following types: `float32`, `float64`, -/// `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, -/// `complex128`, `qint8`, `quint8`, `qint32`, `half`. -/// - axis: A `Tensor` of type `int32` (default: 0). Must be in the range -/// `[-rank(x), rank(x))`. +/// - x: A `Tensor`. Must be one of the following types: `float32`, `float64`, +/// `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, +/// `complex128`, `qint8`, `quint8`, `qint32`, `half`. +/// - axis: A `Tensor` of type `int32` (default: 0). Must be in the range +/// `[-rank(x), rank(x))`. /// /// - Attrs: -/// - exclusive: If `True`, perform exclusive cumsum. -/// - reverse: A `bool` (default: False). +/// - exclusive: If `True`, perform exclusive cumsum. +/// - reverse: A `bool` (default: False). @inlinable @inline(__always) public static func cumsum< T: Numeric & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - _ x: Tensor, - axis: Tensor, - exclusive: Bool = false, - reverse: Bool = false + _ x: Tensor, + axis: Tensor, + exclusive: Bool = false, + reverse: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Cumsum", nOutputs) - op.updateAttribute("exclusive", exclusive) - op.updateAttribute("reverse", reverse) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(x) - op.addInput(axis) - return op.execute(Int(1)) + let op = makeOp("Cumsum", nOutputs) + op.updateAttribute("exclusive", exclusive) + op.updateAttribute("reverse", reverse) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(x) + op.addInput(axis) + return op.execute(Int(1)) } /// Returns the dimension index in the destination data format given the one in @@ -6366,26 +6366,26 @@ public static func cumsum< /// the source data format. /// /// - Parameter x: A Tensor with each element as a dimension index in source data format. -/// Must be in the range [-4, 4). +/// Must be in the range [-4, 4). /// /// - Attrs: -/// - src_format: source data format. -/// - dst_format: destination data format. +/// - src_format: source data format. +/// - dst_format: destination data format. /// /// - Output y: A Tensor with each element as a dimension index in destination data format. @inlinable @inline(__always) public static func dataFormatDimMap( - _ x: Tensor, - srcFormat: String = "NHWC", - dstFormat: String = "NCHW" + _ x: Tensor, + srcFormat: String = "NHWC", + dstFormat: String = "NCHW" ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DataFormatDimMap", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("src_format", srcFormat) - op.updateAttribute("dst_format", dstFormat) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("DataFormatDimMap", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("src_format", srcFormat) + op.updateAttribute("dst_format", dstFormat) + op.addInput(x) + return op.execute(Int(1)) } /// Returns the permuted vector/tensor in the destination data format given the @@ -6395,23 +6395,23 @@ public static func dataFormatDimMap( /// - Parameter x: Vector of size 4 or Tensor of shape (4, 2) in source data format. /// /// - Attrs: -/// - src_format: source data format. -/// - dst_format: destination data format. +/// - src_format: source data format. +/// - dst_format: destination data format. /// /// - Output y: Vector of size 4 or Tensor of shape (4, 2) in destination data format. @inlinable @inline(__always) public static func dataFormatVecPermute( - _ x: Tensor, - srcFormat: String = "NHWC", - dstFormat: String = "NCHW" + _ x: Tensor, + srcFormat: String = "NHWC", + dstFormat: String = "NCHW" ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DataFormatVecPermute", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("src_format", srcFormat) - op.updateAttribute("dst_format", dstFormat) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("DataFormatVecPermute", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("src_format", srcFormat) + op.updateAttribute("dst_format", dstFormat) + op.addInput(x) + return op.execute(Int(1)) } /// Returns a serialized GraphDef representing `input_dataset`. @@ -6423,12 +6423,12 @@ public static func dataFormatVecPermute( /// - Output graph: The graph representation of the dataset (as serialized GraphDef). @inlinable @inline(__always) public static func datasetToGraph( - inputDataset: VariantHandle + inputDataset: VariantHandle ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("DatasetToGraph", nOutputs) - op.addInput(inputDataset) - return op.execute(Int(1)) + let op = makeOp("DatasetToGraph", nOutputs) + op.addInput(inputDataset) + return op.execute(Int(1)) } /// Outputs the single element from the given dataset. @@ -6438,15 +6438,15 @@ public static func datasetToGraph( /// - Output components: The components of the single element of `input`. @inlinable @inline(__always) public static func datasetToSingleElement( - dataset: VariantHandle, - outputShapes: [TensorShape?] + dataset: VariantHandle, + outputShapes: [TensorShape?] ) -> OutputTypes { let nOutputs = Int(OutputTypes._typeList.count) - let op = makeOp("DatasetToSingleElement", nOutputs) - op.updateAttribute("output_types", OutputTypes._typeList) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(dataset) - return op.execute(Int(OutputTypes._typeList.count)) + let op = makeOp("DatasetToSingleElement", nOutputs) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(dataset) + return op.execute(Int(OutputTypes._typeList.count)) } /// Identity op for gradient debugging. @@ -6456,13 +6456,13 @@ public static func datasetToSingleElement( /// This op operates on non-reference-type tensors. @inlinable @inline(__always) public static func debugGradientIdentity( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DebugGradientIdentity", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("DebugGradientIdentity", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Debug Identity Op. @@ -6472,34 +6472,34 @@ public static func debugGradientIdentity( /// - Parameter input: Input tensor, non-Reference type. /// /// - Attrs: -/// - tensor_name: Name of the input tensor. -/// - debug_urls: List of URLs to debug targets, e.g., -/// file:///foo/tfdbg_dump, grpc:://localhost:11011 -/// - gated_grpc: Whether this op will be gated. If any of the debug_urls of this -/// debug node is of the grpc:// scheme, when the value of this attribute is set -/// to True, the data will not actually be sent via the grpc stream unless this -/// debug op has been enabled at the debug_url. If all of the debug_urls of this -/// debug node are of the grpc:// scheme and the debug op is enabled at none of -/// them, the output will be an empty Tensor. +/// - tensor_name: Name of the input tensor. +/// - debug_urls: List of URLs to debug targets, e.g., +/// file:///foo/tfdbg_dump, grpc:://localhost:11011 +/// - gated_grpc: Whether this op will be gated. If any of the debug_urls of this +/// debug node is of the grpc:// scheme, when the value of this attribute is set +/// to True, the data will not actually be sent via the grpc stream unless this +/// debug op has been enabled at the debug_url. If all of the debug_urls of this +/// debug node are of the grpc:// scheme and the debug op is enabled at none of +/// them, the output will be an empty Tensor. /// /// - Output output: Output tensor that equals the input tensor. @inlinable @inline(__always) public static func debugIdentity( - _ input: Tensor, - deviceName: String, - tensorName: String, - debugUrls: [String], - gatedGrpc: Bool = false + _ input: Tensor, + deviceName: String, + tensorName: String, + debugUrls: [String], + gatedGrpc: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DebugIdentity", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("device_name", deviceName) - op.updateAttribute("tensor_name", tensorName) - op.updateAttribute("debug_urls", debugUrls) - op.updateAttribute("gated_grpc", gatedGrpc) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("DebugIdentity", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("device_name", deviceName) + op.updateAttribute("tensor_name", tensorName) + op.updateAttribute("debug_urls", debugUrls) + op.updateAttribute("gated_grpc", gatedGrpc) + op.addInput(input) + return op.execute(Int(1)) } /// Debug NaN Value Counter Op @@ -6509,34 +6509,34 @@ public static func debugIdentity( /// - Parameter input: Input tensor, non-Reference type. /// /// - Attrs: -/// - tensor_name: Name of the input tensor. -/// - debug_urls: List of URLs to debug targets, e.g., -/// file:///foo/tfdbg_dump, grpc:://localhost:11011. -/// - gated_grpc: Whether this op will be gated. If any of the debug_urls of this -/// debug node is of the grpc:// scheme, when the value of this attribute is set -/// to True, the data will not actually be sent via the grpc stream unless this -/// debug op has been enabled at the debug_url. If all of the debug_urls of this -/// debug node are of the grpc:// scheme and the debug op is enabled at none of -/// them, the output will be an empty Tensor. +/// - tensor_name: Name of the input tensor. +/// - debug_urls: List of URLs to debug targets, e.g., +/// file:///foo/tfdbg_dump, grpc:://localhost:11011. +/// - gated_grpc: Whether this op will be gated. If any of the debug_urls of this +/// debug node is of the grpc:// scheme, when the value of this attribute is set +/// to True, the data will not actually be sent via the grpc stream unless this +/// debug op has been enabled at the debug_url. If all of the debug_urls of this +/// debug node are of the grpc:// scheme and the debug op is enabled at none of +/// them, the output will be an empty Tensor. /// /// - Output output: An integer output tensor that is the number of NaNs in the input. @inlinable @inline(__always) public static func debugNanCount( - _ input: Tensor, - deviceName: String, - tensorName: String, - debugUrls: [String], - gatedGrpc: Bool = false + _ input: Tensor, + deviceName: String, + tensorName: String, + debugUrls: [String], + gatedGrpc: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DebugNanCount", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("device_name", deviceName) - op.updateAttribute("tensor_name", tensorName) - op.updateAttribute("debug_urls", debugUrls) - op.updateAttribute("gated_grpc", gatedGrpc) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("DebugNanCount", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("device_name", deviceName) + op.updateAttribute("tensor_name", tensorName) + op.updateAttribute("debug_urls", debugUrls) + op.updateAttribute("gated_grpc", gatedGrpc) + op.addInput(input) + return op.execute(Int(1)) } /// Debug Numeric Summary Op. @@ -6546,73 +6546,73 @@ public static func debugNanCount( /// - Parameter input: Input tensor, non-Reference type, float or double. /// /// - Attrs: -/// - tensor_name: Name of the input tensor. -/// - debug_urls: List of URLs to debug targets, e.g., -/// file:///foo/tfdbg_dump, grpc:://localhost:11011 -/// - lower_bound: (float) The lower bound <= which values will be included in the -/// generalized -inf count. Default: -inf. -/// - upper_bound: (float) The upper bound >= which values will be included in the -/// generalized +inf count. Default: +inf. -/// - mute_if_healthy: (bool) Do not send data to the debug URLs unless at least one -/// of elements [2], [3] and [7] (i.e., the nan count and the generalized -inf and -/// inf counts) is non-zero. -/// - gated_grpc: Whether this op will be gated. If any of the debug_urls of this -/// debug node is of the grpc:// scheme, when the value of this attribute is set -/// to True, the data will not actually be sent via the grpc stream unless this -/// debug op has been enabled at the debug_url. If all of the debug_urls of this -/// debug node are of the grpc:// scheme and the debug op is enabled at none of -/// them, the output will be an empty Tensor. +/// - tensor_name: Name of the input tensor. +/// - debug_urls: List of URLs to debug targets, e.g., +/// file:///foo/tfdbg_dump, grpc:://localhost:11011 +/// - lower_bound: (float) The lower bound <= which values will be included in the +/// generalized -inf count. Default: -inf. +/// - upper_bound: (float) The upper bound >= which values will be included in the +/// generalized +inf count. Default: +inf. +/// - mute_if_healthy: (bool) Do not send data to the debug URLs unless at least one +/// of elements [2], [3] and [7] (i.e., the nan count and the generalized -inf and +/// inf counts) is non-zero. +/// - gated_grpc: Whether this op will be gated. If any of the debug_urls of this +/// debug node is of the grpc:// scheme, when the value of this attribute is set +/// to True, the data will not actually be sent via the grpc stream unless this +/// debug op has been enabled at the debug_url. If all of the debug_urls of this +/// debug node are of the grpc:// scheme and the debug op is enabled at none of +/// them, the output will be an empty Tensor. /// /// - Output output: A double tensor of shape [14 + nDimensions], where nDimensions is the -/// the number of dimensions of the tensor's shape. The elements of output are: -/// [0]: is initialized (1.0) or not (0.0). -/// [1]: total number of elements -/// [2]: NaN element count -/// [3]: generalized -inf count: elements <= lower_bound. lower_bound is -inf by -/// default. -/// [4]: negative element count (excluding -inf), if lower_bound is the default -/// -inf. Otherwise, this is the count of elements > lower_bound and < 0. -/// [5]: zero element count -/// [6]: positive element count (excluding +inf), if upper_bound is the default -/// -inf. Otherwise, this is the count of elements < upper_bound and > 0. -/// [7]: generalized +inf count, elements >= upper_bound. upper_bound is +inf by -/// default. -/// Output elements [1:8] are all zero, if the tensor is uninitialized. -/// [8]: minimum of all non-inf and non-NaN elements. -/// If uninitialized or no such element exists: +inf. -/// [9]: maximum of all non-inf and non-NaN elements. -/// If uninitialized or no such element exists: -inf. -/// [10]: mean of all non-inf and non-NaN elements. -/// If uninitialized or no such element exists: NaN. -/// [11]: variance of all non-inf and non-NaN elements. -/// If uninitialized or no such element exists: NaN. -/// [12]: Data type of the tensor encoded as an enum integer. See the DataType -/// proto for more details. -/// [13]: Number of dimensions of the tensor (ndims). -/// [14+]: Sizes of the dimensions. +/// the number of dimensions of the tensor's shape. The elements of output are: +/// [0]: is initialized (1.0) or not (0.0). +/// [1]: total number of elements +/// [2]: NaN element count +/// [3]: generalized -inf count: elements <= lower_bound. lower_bound is -inf by +/// default. +/// [4]: negative element count (excluding -inf), if lower_bound is the default +/// -inf. Otherwise, this is the count of elements > lower_bound and < 0. +/// [5]: zero element count +/// [6]: positive element count (excluding +inf), if upper_bound is the default +/// -inf. Otherwise, this is the count of elements < upper_bound and > 0. +/// [7]: generalized +inf count, elements >= upper_bound. upper_bound is +inf by +/// default. +/// Output elements [1:8] are all zero, if the tensor is uninitialized. +/// [8]: minimum of all non-inf and non-NaN elements. +/// If uninitialized or no such element exists: +inf. +/// [9]: maximum of all non-inf and non-NaN elements. +/// If uninitialized or no such element exists: -inf. +/// [10]: mean of all non-inf and non-NaN elements. +/// If uninitialized or no such element exists: NaN. +/// [11]: variance of all non-inf and non-NaN elements. +/// If uninitialized or no such element exists: NaN. +/// [12]: Data type of the tensor encoded as an enum integer. See the DataType +/// proto for more details. +/// [13]: Number of dimensions of the tensor (ndims). +/// [14+]: Sizes of the dimensions. @inlinable @inline(__always) public static func debugNumericSummary( - _ input: Tensor, - deviceName: String, - tensorName: String, - debugUrls: [String], - lowerBound: Double = -Double.infinity, - upperBound: Double = Double.infinity, - muteIfHealthy: Bool = false, - gatedGrpc: Bool = false + _ input: Tensor, + deviceName: String, + tensorName: String, + debugUrls: [String], + lowerBound: Double = -Double.infinity, + upperBound: Double = Double.infinity, + muteIfHealthy: Bool = false, + gatedGrpc: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DebugNumericSummary", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("device_name", deviceName) - op.updateAttribute("tensor_name", tensorName) - op.updateAttribute("debug_urls", debugUrls) - op.updateAttribute("lower_bound", lowerBound) - op.updateAttribute("upper_bound", upperBound) - op.updateAttribute("mute_if_healthy", muteIfHealthy) - op.updateAttribute("gated_grpc", gatedGrpc) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("DebugNumericSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("device_name", deviceName) + op.updateAttribute("tensor_name", tensorName) + op.updateAttribute("debug_urls", debugUrls) + op.updateAttribute("lower_bound", lowerBound) + op.updateAttribute("upper_bound", upperBound) + op.updateAttribute("mute_if_healthy", muteIfHealthy) + op.updateAttribute("gated_grpc", gatedGrpc) + op.addInput(input) + return op.execute(Int(1)) } /// Decode and Crop a JPEG-encoded image to a uint8 tensor. @@ -6638,47 +6638,47 @@ public static func debugNumericSummary( /// decoding partial jpeg image. /// /// - Parameters: -/// - contents: 0-D. The JPEG-encoded image. -/// - crop_window: 1-D. The crop window: [crop_y, crop_x, crop_height, crop_width]. +/// - contents: 0-D. The JPEG-encoded image. +/// - crop_window: 1-D. The crop window: [crop_y, crop_x, crop_height, crop_width]. /// /// - Attrs: -/// - channels: Number of color channels for the decoded image. -/// - ratio: Downscaling ratio. -/// - fancy_upscaling: If true use a slower but nicer upscaling of the -/// chroma planes (yuv420/422 only). -/// - try_recover_truncated: If true try to recover an image from truncated input. -/// - acceptable_fraction: The minimum required fraction of lines before a truncated -/// input is accepted. -/// - dct_method: string specifying a hint about the algorithm used for -/// decompression. Defaults to "" which maps to a system-specific -/// default. Currently valid values are ["INTEGER_FAST", -/// "INTEGER_ACCURATE"]. The hint may be ignored (e.g., the internal -/// jpeg library changes to a version that does not have that specific -/// option.) +/// - channels: Number of color channels for the decoded image. +/// - ratio: Downscaling ratio. +/// - fancy_upscaling: If true use a slower but nicer upscaling of the +/// chroma planes (yuv420/422 only). +/// - try_recover_truncated: If true try to recover an image from truncated input. +/// - acceptable_fraction: The minimum required fraction of lines before a truncated +/// input is accepted. +/// - dct_method: string specifying a hint about the algorithm used for +/// decompression. Defaults to "" which maps to a system-specific +/// default. Currently valid values are ["INTEGER_FAST", +/// "INTEGER_ACCURATE"]. The hint may be ignored (e.g., the internal +/// jpeg library changes to a version that does not have that specific +/// option.) /// /// - Output image: 3-D with shape `[height, width, channels]`.. @inlinable @inline(__always) public static func decodeAndCropJpeg( - contents: StringTensor, - cropWindow: Tensor, - channels: Int64 = 0, - ratio: Int64 = 1, - fancyUpscaling: Bool = true, - tryRecoverTruncated: Bool = false, - acceptableFraction: Double = 1, - dctMethod: String + contents: StringTensor, + cropWindow: Tensor, + channels: Int64 = 0, + ratio: Int64 = 1, + fancyUpscaling: Bool = true, + tryRecoverTruncated: Bool = false, + acceptableFraction: Double = 1, + dctMethod: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DecodeAndCropJpeg", nOutputs) - op.updateAttribute("channels", channels) - op.updateAttribute("ratio", ratio) - op.updateAttribute("fancy_upscaling", fancyUpscaling) - op.updateAttribute("try_recover_truncated", tryRecoverTruncated) - op.updateAttribute("acceptable_fraction", acceptableFraction) - op.updateAttribute("dct_method", dctMethod) - op.addInput(contents) - op.addInput(cropWindow) - return op.execute(Int(1)) + let op = makeOp("DecodeAndCropJpeg", nOutputs) + op.updateAttribute("channels", channels) + op.updateAttribute("ratio", ratio) + op.updateAttribute("fancy_upscaling", fancyUpscaling) + op.updateAttribute("try_recover_truncated", tryRecoverTruncated) + op.updateAttribute("acceptable_fraction", acceptableFraction) + op.updateAttribute("dct_method", dctMethod) + op.addInput(contents) + op.addInput(cropWindow) + return op.execute(Int(1)) } /// Decode web-safe base64-encoded strings. @@ -6691,12 +6691,12 @@ public static func decodeAndCropJpeg( /// - Output output: Decoded strings. @inlinable @inline(__always) public static func decodeBase64( - _ input: StringTensor + _ input: StringTensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("DecodeBase64", nOutputs) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("DecodeBase64", nOutputs) + op.addInput(input) + return op.execute(Int(1)) } /// Decode the first frame of a BMP-encoded image to a uint8 tensor. @@ -6715,14 +6715,14 @@ public static func decodeBase64( /// - Output image: 3-D with shape `[height, width, channels]`. RGB order @inlinable @inline(__always) public static func decodeBmp( - contents: StringTensor, - channels: Int64 = 0 + contents: StringTensor, + channels: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DecodeBmp", nOutputs) - op.updateAttribute("channels", channels) - op.addInput(contents) - return op.execute(Int(1)) + let op = makeOp("DecodeBmp", nOutputs) + op.updateAttribute("channels", channels) + op.addInput(contents) + return op.execute(Int(1)) } /// Convert CSV records to tensors. Each column maps to one tensor. @@ -6732,39 +6732,39 @@ public static func decodeBmp( /// Note that we allow leading and trailing spaces with int or float field. /// /// - Parameters: -/// - records: Each string is a record/row in the csv and all records should have -/// the same format. -/// - record_defaults: One tensor per column of the input record, with either a -/// scalar default value for that column or an empty vector if the column is -/// required. +/// - records: Each string is a record/row in the csv and all records should have +/// the same format. +/// - record_defaults: One tensor per column of the input record, with either a +/// scalar default value for that column or an empty vector if the column is +/// required. /// /// - Attrs: -/// - field_delim: char delimiter to separate fields in a record. -/// - use_quote_delim: If false, treats double quotation marks as regular -/// characters inside of the string fields (ignoring RFC 4180, Section 2, -/// Bullet 5). -/// - na_value: Additional string to recognize as NA/NaN. +/// - field_delim: char delimiter to separate fields in a record. +/// - use_quote_delim: If false, treats double quotation marks as regular +/// characters inside of the string fields (ignoring RFC 4180, Section 2, +/// Bullet 5). +/// - na_value: Additional string to recognize as NA/NaN. /// /// - Output output: Each tensor will have the same shape as records. @inlinable @inline(__always) public static func decodeCSV( - records: StringTensor, - recordDefaults: OutType, - fieldDelim: String = ",", - useQuoteDelim: Bool = true, - naValue: String, - selectCols: [Int32] + records: StringTensor, + recordDefaults: OutType, + fieldDelim: String = ",", + useQuoteDelim: Bool = true, + naValue: String, + selectCols: [Int32] ) -> OutType { let nOutputs = Int(recordDefaults._typeList.count) - let op = makeOp("DecodeCSV", nOutputs) - op.updateAttribute("OUT_TYPE", recordDefaults._typeList) - op.updateAttribute("field_delim", fieldDelim) - op.updateAttribute("use_quote_delim", useQuoteDelim) - op.updateAttribute("na_value", naValue) - op.updateAttribute("select_cols", selectCols) - op.addInput(records) - op.addInputList(recordDefaults) - return op.execute(Int(recordDefaults._typeList.count)) + let op = makeOp("DecodeCSV", nOutputs) + op.updateAttribute("OUT_TYPE", recordDefaults._typeList) + op.updateAttribute("field_delim", fieldDelim) + op.updateAttribute("use_quote_delim", useQuoteDelim) + op.updateAttribute("na_value", naValue) + op.updateAttribute("select_cols", selectCols) + op.addInput(records) + op.addInputList(recordDefaults) + return op.execute(Int(recordDefaults._typeList.count)) } /// Decompress strings. @@ -6779,20 +6779,20 @@ public static func decodeCSV( /// - Parameter bytes: A Tensor of string which is compressed. /// /// - Attr compression_type: A scalar containing either (i) the empty string (no -/// compression), (ii) "ZLIB", or (iii) "GZIP". +/// compression), (ii) "ZLIB", or (iii) "GZIP". /// /// - Output output: A Tensor with the same shape as input `bytes`, uncompressed -/// from bytes. +/// from bytes. @inlinable @inline(__always) public static func decodeCompressed( - bytes: StringTensor, - compressionType: String + bytes: StringTensor, + compressionType: String ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("DecodeCompressed", nOutputs) - op.updateAttribute("compression_type", compressionType) - op.addInput(bytes) - return op.execute(Int(1)) + let op = makeOp("DecodeCompressed", nOutputs) + op.updateAttribute("compression_type", compressionType) + op.addInput(bytes) + return op.execute(Int(1)) } /// Decode the frame(s) of a GIF-encoded image to a uint8 tensor. @@ -6811,12 +6811,12 @@ public static func decodeCompressed( /// - Output image: 4-D with shape `[num_frames, height, width, 3]`. RGB channel order. @inlinable @inline(__always) public static func decodeGif( - contents: StringTensor + contents: StringTensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DecodeGif", nOutputs) - op.addInput(contents) - return op.execute(Int(1)) + let op = makeOp("DecodeGif", nOutputs) + op.addInput(contents) + return op.execute(Int(1)) } /// Convert JSON-encoded Example records to binary protocol buffer strings. @@ -6829,18 +6829,18 @@ public static func decodeGif( /// Example-parsing ops. /// /// - Parameter json_examples: Each string is a JSON object serialized according to the JSON -/// mapping of the Example proto. +/// mapping of the Example proto. /// /// - Output binary_examples: Each string is a binary Example protocol buffer corresponding -/// to the respective element of `json_examples`. +/// to the respective element of `json_examples`. @inlinable @inline(__always) public static func decodeJSONExample( - jsonExamples: StringTensor + jsonExamples: StringTensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("DecodeJSONExample", nOutputs) - op.addInput(jsonExamples) - return op.execute(Int(1)) + let op = makeOp("DecodeJSONExample", nOutputs) + op.addInput(jsonExamples) + return op.execute(Int(1)) } /// Decode a JPEG-encoded image to a uint8 tensor. @@ -6868,56 +6868,56 @@ public static func decodeJSONExample( /// - Parameter contents: 0-D. The JPEG-encoded image. /// /// - Attrs: -/// - channels: Number of color channels for the decoded image. -/// - ratio: Downscaling ratio. -/// - fancy_upscaling: If true use a slower but nicer upscaling of the -/// chroma planes (yuv420/422 only). -/// - try_recover_truncated: If true try to recover an image from truncated input. -/// - acceptable_fraction: The minimum required fraction of lines before a truncated -/// input is accepted. -/// - dct_method: string specifying a hint about the algorithm used for -/// decompression. Defaults to "" which maps to a system-specific -/// default. Currently valid values are ["INTEGER_FAST", -/// "INTEGER_ACCURATE"]. The hint may be ignored (e.g., the internal -/// jpeg library changes to a version that does not have that specific -/// option.) +/// - channels: Number of color channels for the decoded image. +/// - ratio: Downscaling ratio. +/// - fancy_upscaling: If true use a slower but nicer upscaling of the +/// chroma planes (yuv420/422 only). +/// - try_recover_truncated: If true try to recover an image from truncated input. +/// - acceptable_fraction: The minimum required fraction of lines before a truncated +/// input is accepted. +/// - dct_method: string specifying a hint about the algorithm used for +/// decompression. Defaults to "" which maps to a system-specific +/// default. Currently valid values are ["INTEGER_FAST", +/// "INTEGER_ACCURATE"]. The hint may be ignored (e.g., the internal +/// jpeg library changes to a version that does not have that specific +/// option.) /// /// - Output image: 3-D with shape `[height, width, channels]`.. @inlinable @inline(__always) public static func decodeJpeg( - contents: StringTensor, - channels: Int64 = 0, - ratio: Int64 = 1, - fancyUpscaling: Bool = true, - tryRecoverTruncated: Bool = false, - acceptableFraction: Double = 1, - dctMethod: String + contents: StringTensor, + channels: Int64 = 0, + ratio: Int64 = 1, + fancyUpscaling: Bool = true, + tryRecoverTruncated: Bool = false, + acceptableFraction: Double = 1, + dctMethod: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DecodeJpeg", nOutputs) - op.updateAttribute("channels", channels) - op.updateAttribute("ratio", ratio) - op.updateAttribute("fancy_upscaling", fancyUpscaling) - op.updateAttribute("try_recover_truncated", tryRecoverTruncated) - op.updateAttribute("acceptable_fraction", acceptableFraction) - op.updateAttribute("dct_method", dctMethod) - op.addInput(contents) - return op.execute(Int(1)) + let op = makeOp("DecodeJpeg", nOutputs) + op.updateAttribute("channels", channels) + op.updateAttribute("ratio", ratio) + op.updateAttribute("fancy_upscaling", fancyUpscaling) + op.updateAttribute("try_recover_truncated", tryRecoverTruncated) + op.updateAttribute("acceptable_fraction", acceptableFraction) + op.updateAttribute("dct_method", dctMethod) + op.addInput(contents) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func decodePaddedRaw( - inputBytes: StringTensor, - fixedLength: Tensor, - littleEndian: Bool = true + inputBytes: StringTensor, + fixedLength: Tensor, + littleEndian: Bool = true ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DecodePaddedRaw", nOutputs) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("little_endian", littleEndian) - op.addInput(inputBytes) - op.addInput(fixedLength) - return op.execute(Int(1)) + let op = makeOp("DecodePaddedRaw", nOutputs) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("little_endian", littleEndian) + op.addInput(inputBytes) + op.addInput(fixedLength) + return op.execute(Int(1)) } /// Decode a PNG-encoded image to a uint8 or uint16 tensor. @@ -6945,15 +6945,15 @@ public static func decodePaddedRaw( /// - Output image: 3-D with shape `[height, width, channels]`. @inlinable @inline(__always) public static func decodePng( - contents: StringTensor, - channels: Int64 = 0 + contents: StringTensor, + channels: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DecodePng", nOutputs) - op.updateAttribute("channels", channels) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(contents) - return op.execute(Int(1)) + let op = makeOp("DecodePng", nOutputs) + op.updateAttribute("channels", channels) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(contents) + return op.execute(Int(1)) } /// The op extracts fields from a serialized protocol buffers message into tensors. @@ -7011,41 +7011,41 @@ public static func decodePng( /// - Parameter bytes: Tensor of serialized protos with shape `batch_shape`. /// /// - Attrs: -/// - message_type: Name of the proto message type to decode. -/// - field_names: List of strings containing proto field names. An extension field can be decoded -/// by using its full name, e.g. EXT_PACKAGE.EXT_FIELD_NAME. -/// - output_types: List of TF types to use for the respective field in field_names. -/// - descriptor_source: Either the special value `local://` or a path to a file containing -/// a serialized `FileDescriptorSet`. -/// - message_format: Either `binary` or `text`. -/// - sanitize: Whether to sanitize the result or not. +/// - message_type: Name of the proto message type to decode. +/// - field_names: List of strings containing proto field names. An extension field can be decoded +/// by using its full name, e.g. EXT_PACKAGE.EXT_FIELD_NAME. +/// - output_types: List of TF types to use for the respective field in field_names. +/// - descriptor_source: Either the special value `local://` or a path to a file containing +/// a serialized `FileDescriptorSet`. +/// - message_format: Either `binary` or `text`. +/// - sanitize: Whether to sanitize the result or not. /// /// - Outputs: -/// - sizes: Tensor of int32 with shape `[batch_shape, len(field_names)]`. -/// Each entry is the number of values found for the corresponding field. -/// Optional fields may have 0 or 1 values. -/// - values: List of tensors containing values for the corresponding field. -/// `values[i]` has datatype `output_types[i]` -/// and shape `[batch_shape, max(sizes[...,i])]`. +/// - sizes: Tensor of int32 with shape `[batch_shape, len(field_names)]`. +/// Each entry is the number of values found for the corresponding field. +/// Optional fields may have 0 or 1 values. +/// - values: List of tensors containing values for the corresponding field. +/// `values[i]` has datatype `output_types[i]` +/// and shape `[batch_shape, max(sizes[...,i])]`. @inlinable @inline(__always) public static func decodeProtoV2( - bytes: StringTensor, - messageType: String, - fieldNames: [String], - descriptorSource: String = "local://", - messageFormat: String = "binary", - sanitize: Bool = false + bytes: StringTensor, + messageType: String, + fieldNames: [String], + descriptorSource: String = "local://", + messageFormat: String = "binary", + sanitize: Bool = false ) -> (sizes: Tensor, values: OutputTypes) { let nOutputs = Int(1) + Int(OutputTypes._typeList.count) - let op = makeOp("DecodeProtoV2", nOutputs) - op.updateAttribute("message_type", messageType) - op.updateAttribute("field_names", fieldNames) - op.updateAttribute("output_types", OutputTypes._typeList) - op.updateAttribute("descriptor_source", descriptorSource) - op.updateAttribute("message_format", messageFormat) - op.updateAttribute("sanitize", sanitize) - op.addInput(bytes) - return op.execute(Int(1), Int(OutputTypes._typeList.count)) + let op = makeOp("DecodeProtoV2", nOutputs) + op.updateAttribute("message_type", messageType) + op.updateAttribute("field_names", fieldNames) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("descriptor_source", descriptorSource) + op.updateAttribute("message_format", messageFormat) + op.updateAttribute("sanitize", sanitize) + op.addInput(bytes) + return op.execute(Int(1), Int(OutputTypes._typeList.count)) } /// Reinterpret the bytes of a string as a vector of numbers. @@ -7053,23 +7053,23 @@ public static func decodeProtoV2( /// - Parameter bytes: All the elements must have the same length. /// /// - Attr little_endian: Whether the input `bytes` are in little-endian order. -/// Ignored for `out_type` values that are stored in a single byte like -/// `uint8`. +/// Ignored for `out_type` values that are stored in a single byte like +/// `uint8`. /// /// - Output output: A Tensor with one more dimension than the input `bytes`. The -/// added dimension will have size equal to the length of the elements -/// of `bytes` divided by the number of bytes to represent `out_type`. +/// added dimension will have size equal to the length of the elements +/// of `bytes` divided by the number of bytes to represent `out_type`. @inlinable @inline(__always) public static func decodeRaw( - bytes: StringTensor, - littleEndian: Bool = true + bytes: StringTensor, + littleEndian: Bool = true ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DecodeRaw", nOutputs) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("little_endian", littleEndian) - op.addInput(bytes) - return op.execute(Int(1)) + let op = makeOp("DecodeRaw", nOutputs) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("little_endian", littleEndian) + op.addInput(bytes) + return op.execute(Int(1)) } /// Decode a 16-bit PCM WAV file to a float tensor. @@ -7092,24 +7092,24 @@ public static func decodeRaw( /// - Parameter contents: The WAV-encoded audio, usually from a file. /// /// - Attrs: -/// - desired_channels: Number of sample channels wanted. -/// - desired_samples: Length of audio requested. +/// - desired_channels: Number of sample channels wanted. +/// - desired_samples: Length of audio requested. /// /// - Outputs: -/// - audio: 2-D with shape `[length, channels]`. -/// - sample_rate: Scalar holding the sample rate found in the WAV header. +/// - audio: 2-D with shape `[length, channels]`. +/// - sample_rate: Scalar holding the sample rate found in the WAV header. @inlinable @inline(__always) public static func decodeWav( - contents: StringTensor, - desiredChannels: Int64 = -1, - desiredSamples: Int64 = -1 + contents: StringTensor, + desiredChannels: Int64 = -1, + desiredSamples: Int64 = -1 ) -> (audio: Tensor, sampleRate: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("DecodeWav", nOutputs) - op.updateAttribute("desired_channels", desiredChannels) - op.updateAttribute("desired_samples", desiredSamples) - op.addInput(contents) - return op.execute(Int(1), Int(1)) + let op = makeOp("DecodeWav", nOutputs) + op.updateAttribute("desired_channels", desiredChannels) + op.updateAttribute("desired_samples", desiredSamples) + op.addInput(contents) + return op.execute(Int(1), Int(1)) } /// Makes a copy of `x`. @@ -7117,33 +7117,33 @@ public static func decodeWav( /// - Parameter x: The source tensor of type `T`. /// /// - Output y: y: A `Tensor` of type `T`. A copy of `x`. Guaranteed that `y` -/// is not an alias of `x`. +/// is not an alias of `x`. @inlinable @inline(__always) public static func deepCopy( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DeepCopy", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("DeepCopy", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// A container for an iterator resource. /// /// - Parameters: -/// - handle: A handle to the iterator to delete. -/// - deleter: A variant deleter. +/// - handle: A handle to the iterator to delete. +/// - deleter: A variant deleter. @inlinable @inline(__always) public static func deleteIterator( - handle: ResourceHandle, - deleter: VariantHandle + handle: ResourceHandle, + deleter: VariantHandle ) { let nOutputs = 0 - let op = makeOp("DeleteIterator", nOutputs) - op.addInput(handle) - op.addInput(deleter) - op.execute() + let op = makeOp("DeleteIterator", nOutputs) + op.addInput(handle) + op.addInput(deleter) + op.execute() } /// Delete the tensor specified by its handle in the session. @@ -7151,12 +7151,12 @@ public static func deleteIterator( /// - Parameter handle: The handle for a tensor stored in the session state. @inlinable @inline(__always) public static func deleteSessionTensor( - handle: StringTensor + handle: StringTensor ) { let nOutputs = 0 - let op = makeOp("DeleteSessionTensor", nOutputs) - op.addInput(handle) - op.execute() + let op = makeOp("DeleteSessionTensor", nOutputs) + op.addInput(handle) + op.execute() } /// Applies set operation along last dimension of 2 `Tensor` inputs. @@ -7170,32 +7170,32 @@ public static func deleteSessionTensor( /// `[0...n-1]` dimension of `set`. /// /// - Parameters: -/// - set1: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`. -/// Dimension `n` contains values in a set, duplicates are allowed but ignored. -/// - set2: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set1`. -/// Dimension `n` contains values in a set, duplicates are allowed but ignored. +/// - set1: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`. +/// Dimension `n` contains values in a set, duplicates are allowed but ignored. +/// - set2: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set1`. +/// Dimension `n` contains values in a set, duplicates are allowed but ignored. /// /// - Outputs: -/// - result_indices: 2D indices of a `SparseTensor`. -/// - result_values: 1D values of a `SparseTensor`. -/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is -/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` -/// is the max result set size across all `0...n-1` dimensions. +/// - result_indices: 2D indices of a `SparseTensor`. +/// - result_values: 1D values of a `SparseTensor`. +/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is +/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` +/// is the max result set size across all `0...n-1` dimensions. @inlinable @inline(__always) public static func denseToDenseSetOperation( - set1: Tensor, - set2: Tensor, - setOperation: String, - validateIndices: Bool = true + set1: Tensor, + set2: Tensor, + setOperation: String, + validateIndices: Bool = true ) -> (resultIndices: Tensor, resultValues: Tensor, resultShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("DenseToDenseSetOperation", nOutputs) - op.updateAttribute("set_operation", setOperation) - op.updateAttribute("validate_indices", validateIndices) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(set1) - op.addInput(set2) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("DenseToDenseSetOperation", nOutputs) + op.updateAttribute("set_operation", setOperation) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(set1) + op.addInput(set2) + return op.execute(Int(1), Int(1), Int(1)) } /// Applies set operation along last dimension of 2 `Tensor` inputs. @@ -7209,32 +7209,32 @@ public static func denseToDenseSetOperation /// `[0...n-1]` dimension of `set`. /// /// - Parameters: -/// - set1: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`. -/// Dimension `n` contains values in a set, duplicates are allowed but ignored. -/// - set2: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set1`. -/// Dimension `n` contains values in a set, duplicates are allowed but ignored. +/// - set1: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`. +/// Dimension `n` contains values in a set, duplicates are allowed but ignored. +/// - set2: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set1`. +/// Dimension `n` contains values in a set, duplicates are allowed but ignored. /// /// - Outputs: -/// - result_indices: 2D indices of a `SparseTensor`. -/// - result_values: 1D values of a `SparseTensor`. -/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is -/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` -/// is the max result set size across all `0...n-1` dimensions. +/// - result_indices: 2D indices of a `SparseTensor`. +/// - result_values: 1D values of a `SparseTensor`. +/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is +/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` +/// is the max result set size across all `0...n-1` dimensions. @inlinable @inline(__always) public static func denseToDenseSetOperation( - set1: StringTensor, - set2: StringTensor, - setOperation: String, - validateIndices: Bool = true + set1: StringTensor, + set2: StringTensor, + setOperation: String, + validateIndices: Bool = true ) -> (resultIndices: Tensor, resultValues: StringTensor, resultShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("DenseToDenseSetOperation", nOutputs) - op.updateAttribute("set_operation", setOperation) - op.updateAttribute("validate_indices", validateIndices) - op.updateAttribute("T", TensorDataType(TF_STRING)) - op.addInput(set1) - op.addInput(set2) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("DenseToDenseSetOperation", nOutputs) + op.updateAttribute("set_operation", setOperation) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(set1) + op.addInput(set2) + return op.execute(Int(1), Int(1), Int(1)) } /// Applies set operation along last dimension of `Tensor` and `SparseTensor`. @@ -7256,41 +7256,41 @@ public static func denseToDenseSetOperation( /// `[0...n-1]` dimension of `set`. /// /// - Parameters: -/// - set1: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`. -/// Dimension `n` contains values in a set, duplicates are allowed but ignored. -/// - set2_indices: 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major -/// order. -/// - set2_values: 1D `Tensor`, values of a `SparseTensor`. Must be in row-major -/// order. -/// - set2_shape: 1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must -/// be the same as the 1st `n-1` dimensions of `set1`, `result_shape[n]` is the -/// max set size across `n-1` dimensions. +/// - set1: `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`. +/// Dimension `n` contains values in a set, duplicates are allowed but ignored. +/// - set2_indices: 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major +/// order. +/// - set2_values: 1D `Tensor`, values of a `SparseTensor`. Must be in row-major +/// order. +/// - set2_shape: 1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must +/// be the same as the 1st `n-1` dimensions of `set1`, `result_shape[n]` is the +/// max set size across `n-1` dimensions. /// /// - Outputs: -/// - result_indices: 2D indices of a `SparseTensor`. -/// - result_values: 1D values of a `SparseTensor`. -/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is -/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` -/// is the max result set size across all `0...n-1` dimensions. +/// - result_indices: 2D indices of a `SparseTensor`. +/// - result_values: 1D values of a `SparseTensor`. +/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is +/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` +/// is the max result set size across all `0...n-1` dimensions. @inlinable @inline(__always) public static func denseToSparseSetOperation( - set1: Tensor, - set2Indices: Tensor, - set2Values: Tensor, - set2Shape: Tensor, - setOperation: String, - validateIndices: Bool = true + set1: Tensor, + set2Indices: Tensor, + set2Values: Tensor, + set2Shape: Tensor, + setOperation: String, + validateIndices: Bool = true ) -> (resultIndices: Tensor, resultValues: Tensor, resultShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("DenseToSparseSetOperation", nOutputs) - op.updateAttribute("set_operation", setOperation) - op.updateAttribute("validate_indices", validateIndices) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(set1) - op.addInput(set2Indices) - op.addInput(set2Values) - op.addInput(set2Shape) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("DenseToSparseSetOperation", nOutputs) + op.updateAttribute("set_operation", setOperation) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(set1) + op.addInput(set2Indices) + op.addInput(set2Values) + op.addInput(set2Shape) + return op.execute(Int(1), Int(1), Int(1)) } /// Applies set operation along last dimension of `Tensor` and `SparseTensor`. @@ -7312,41 +7312,41 @@ public static func denseToSparseSetOperation, - set2Values: StringTensor, - set2Shape: Tensor, - setOperation: String, - validateIndices: Bool = true + set1: StringTensor, + set2Indices: Tensor, + set2Values: StringTensor, + set2Shape: Tensor, + setOperation: String, + validateIndices: Bool = true ) -> (resultIndices: Tensor, resultValues: StringTensor, resultShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("DenseToSparseSetOperation", nOutputs) - op.updateAttribute("set_operation", setOperation) - op.updateAttribute("validate_indices", validateIndices) - op.updateAttribute("T", TensorDataType(TF_STRING)) - op.addInput(set1) - op.addInput(set2Indices) - op.addInput(set2Values) - op.addInput(set2Shape) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("DenseToSparseSetOperation", nOutputs) + op.updateAttribute("set_operation", setOperation) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(set1) + op.addInput(set2Indices) + op.addInput(set2Values) + op.addInput(set2Shape) + return op.execute(Int(1), Int(1), Int(1)) } /// DepthToSpace for tensors of type T. @@ -7444,17 +7444,17 @@ public static func denseToSparseSetOperation( /// - Attr block_size: The size of the spatial block, same as in Space2Depth. @inlinable @inline(__always) public static func depthToSpace( - _ input: Tensor, - blockSize: Int64, - dataFormat: DataFormat4 = .nhwc + _ input: Tensor, + blockSize: Int64, + dataFormat: DataFormat4 = .nhwc ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DepthToSpace", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("block_size", blockSize) - op.updateAttribute("data_format", dataFormat.cName) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("DepthToSpace", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("block_size", blockSize) + op.updateAttribute("data_format", dataFormat.cName) + op.addInput(input) + return op.execute(Int(1)) } /// Computes a 2-D depthwise convolution given 4-D `input` and `filter` tensors. @@ -7479,148 +7479,148 @@ public static func depthToSpace( /// horizontal and vertices strides, `strides = [1, stride, stride, 1]`. /// /// - Attrs: -/// - strides: 1-D of length 4. The stride of the sliding window for each dimension -/// of `input`. -/// - padding: The type of padding algorithm to use. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, height, width, channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, channels, height, width]. -/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of -/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter -/// element on that dimension. The dimension order is determined by the value of -/// `data_format`, see above for details. Dilations in the batch and depth -/// dimensions must be 1. +/// - strides: 1-D of length 4. The stride of the sliding window for each dimension +/// of `input`. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, height, width, channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, channels, height, width]. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter +/// element on that dimension. The dimension order is determined by the value of +/// `data_format`, see above for details. Dilations in the batch and depth +/// dimensions must be 1. @inlinable @inline(__always) public static func depthwiseConv2dNative( - _ input: Tensor, - filter: Tensor, - strides: [Int32], - padding: Padding, - dataFormat: DataFormat = .nhwc, - dilations: [Int32] = [1, 1, 1, 1] + _ input: Tensor, + filter: Tensor, + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc, + dilations: [Int32] = [1, 1, 1, 1] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DepthwiseConv2dNative", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filter) - return op.execute(Int(1)) + let op = makeOp("DepthwiseConv2dNative", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + return op.execute(Int(1)) } /// Computes the gradients of depthwise convolution with respect to the filter. /// /// - Parameters: -/// - input: 4-D with shape based on `data_format`. For example, if -/// `data_format` is 'NHWC' then `input` is a 4-D `[batch, in_height, -/// in_width, in_channels]` tensor. -/// - filter_sizes: An integer vector representing the tensor shape of `filter`, -/// where `filter` is a 4-D -/// `[filter_height, filter_width, in_channels, depthwise_multiplier]` tensor. -/// - out_backprop: 4-D with shape based on `data_format`. -/// For example, if `data_format` is 'NHWC' then -/// out_backprop shape is `[batch, out_height, out_width, out_channels]`. -/// Gradients w.r.t. the output of the convolution. +/// - input: 4-D with shape based on `data_format`. For example, if +/// `data_format` is 'NHWC' then `input` is a 4-D `[batch, in_height, +/// in_width, in_channels]` tensor. +/// - filter_sizes: An integer vector representing the tensor shape of `filter`, +/// where `filter` is a 4-D +/// `[filter_height, filter_width, in_channels, depthwise_multiplier]` tensor. +/// - out_backprop: 4-D with shape based on `data_format`. +/// For example, if `data_format` is 'NHWC' then +/// out_backprop shape is `[batch, out_height, out_width, out_channels]`. +/// Gradients w.r.t. the output of the convolution. /// /// - Attrs: -/// - strides: The stride of the sliding window for each dimension of the input -/// of the convolution. -/// - padding: The type of padding algorithm to use. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, height, width, channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, channels, height, width]. -/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of -/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter -/// element on that dimension. The dimension order is determined by the value of -/// `data_format`, see above for details. Dilations in the batch and depth -/// dimensions must be 1. +/// - strides: The stride of the sliding window for each dimension of the input +/// of the convolution. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, height, width, channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, channels, height, width]. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter +/// element on that dimension. The dimension order is determined by the value of +/// `data_format`, see above for details. Dilations in the batch and depth +/// dimensions must be 1. /// /// - Output output: 4-D with shape -/// `[filter_height, filter_width, in_channels, out_channels]`. Gradient w.r.t. -/// the `filter` input of the convolution. +/// `[filter_height, filter_width, in_channels, out_channels]`. Gradient w.r.t. +/// the `filter` input of the convolution. @inlinable @inline(__always) public static func depthwiseConv2dNativeBackpropFilter( - _ input: Tensor, - filterSizes: Tensor, - outBackprop: Tensor, - strides: [Int32], - padding: Padding, - dataFormat: DataFormat = .nhwc, - dilations: [Int32] = [1, 1, 1, 1] -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("DepthwiseConv2dNativeBackpropFilter", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filterSizes) - op.addInput(outBackprop) - return op.execute(Int(1)) + _ input: Tensor, + filterSizes: Tensor, + outBackprop: Tensor, + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc, + dilations: [Int32] = [1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DepthwiseConv2dNativeBackpropFilter", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filterSizes) + op.addInput(outBackprop) + return op.execute(Int(1)) } /// Computes the gradients of depthwise convolution with respect to the input. /// /// - Parameters: -/// - input_sizes: An integer vector representing the shape of `input`, based -/// on `data_format`. For example, if `data_format` is 'NHWC' then -/// `input` is a 4-D `[batch, height, width, channels]` tensor. -/// - filter: 4-D with shape -/// `[filter_height, filter_width, in_channels, depthwise_multiplier]`. -/// - out_backprop: 4-D with shape based on `data_format`. -/// For example, if `data_format` is 'NHWC' then -/// out_backprop shape is `[batch, out_height, out_width, out_channels]`. -/// Gradients w.r.t. the output of the convolution. +/// - input_sizes: An integer vector representing the shape of `input`, based +/// on `data_format`. For example, if `data_format` is 'NHWC' then +/// `input` is a 4-D `[batch, height, width, channels]` tensor. +/// - filter: 4-D with shape +/// `[filter_height, filter_width, in_channels, depthwise_multiplier]`. +/// - out_backprop: 4-D with shape based on `data_format`. +/// For example, if `data_format` is 'NHWC' then +/// out_backprop shape is `[batch, out_height, out_width, out_channels]`. +/// Gradients w.r.t. the output of the convolution. /// /// - Attrs: -/// - strides: The stride of the sliding window for each dimension of the input -/// of the convolution. -/// - padding: The type of padding algorithm to use. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, height, width, channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, channels, height, width]. -/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of -/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter -/// element on that dimension. The dimension order is determined by the value of -/// `data_format`, see above for details. Dilations in the batch and depth -/// dimensions must be 1. +/// - strides: The stride of the sliding window for each dimension of the input +/// of the convolution. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, height, width, channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, channels, height, width]. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each filter +/// element on that dimension. The dimension order is determined by the value of +/// `data_format`, see above for details. Dilations in the batch and depth +/// dimensions must be 1. /// /// - Output output: 4-D with shape according to `data_format`. For example, if -/// `data_format` is 'NHWC', output shape is `[batch, in_height, -/// in_width, in_channels]`. Gradient w.r.t. the input of the -/// convolution. +/// `data_format` is 'NHWC', output shape is `[batch, in_height, +/// in_width, in_channels]`. Gradient w.r.t. the input of the +/// convolution. @inlinable @inline(__always) public static func depthwiseConv2dNativeBackpropInput( - inputSizes: Tensor, - filter: Tensor, - outBackprop: Tensor, - strides: [Int32], - padding: Padding, - dataFormat: DataFormat = .nhwc, - dilations: [Int32] = [1, 1, 1, 1] -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("DepthwiseConv2dNativeBackpropInput", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("dilations", dilations) - op.addInput(inputSizes) - op.addInput(filter) - op.addInput(outBackprop) - return op.execute(Int(1)) + inputSizes: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc, + dilations: [Int32] = [1, 1, 1, 1] +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("DepthwiseConv2dNativeBackpropInput", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("dilations", dilations) + op.addInput(inputSizes) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) } /// Dequantize the 'input' tensor into a float Tensor. @@ -7700,41 +7700,41 @@ public static func depthwiseConv2dNativeBackpropInput( - _ input: Tensor, - minRange: Tensor, - maxRange: Tensor, - mode: Mode = .minCombined + _ input: Tensor, + minRange: Tensor, + maxRange: Tensor, + mode: Mode = .minCombined ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Dequantize", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("mode", mode.cName) - op.addInput(input) - op.addInput(minRange) - op.addInput(maxRange) - return op.execute(Int(1)) + let op = makeOp("Dequantize", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("mode", mode.cName) + op.addInput(input) + op.addInput(minRange) + op.addInput(maxRange) + return op.execute(Int(1)) } /// Converts the given variant tensor to an iterator and stores it in the given resource. /// /// - Parameters: -/// - resource_handle: A handle to an iterator resource. -/// - serialized: A variant tensor storing the state of the iterator contained in the -/// resource. +/// - resource_handle: A handle to an iterator resource. +/// - serialized: A variant tensor storing the state of the iterator contained in the +/// resource. @inlinable @inline(__always) public static func deserializeIterator( - resourceHandle: ResourceHandle, - serialized: VariantHandle + resourceHandle: ResourceHandle, + serialized: VariantHandle ) { let nOutputs = 0 - let op = makeOp("DeserializeIterator", nOutputs) - op.addInput(resourceHandle) - op.addInput(serialized) - op.execute() + let op = makeOp("DeserializeIterator", nOutputs) + op.addInput(resourceHandle) + op.addInput(serialized) + op.execute() } /// Deserialize and concatenate `SparseTensors` from a serialized minibatch. @@ -7782,18 +7782,18 @@ public static func deserializeIterator( /// shape = [2 50] /// /// - Parameter serialized_sparse: 2-D, The `N` serialized `SparseTensor` objects. -/// Must have 3 columns. +/// Must have 3 columns. /// /// - Attr dtype: The `dtype` of the serialized `SparseTensor` objects. @inlinable @inline(__always) public static func deserializeManySparse( - serializedSparse: StringTensor + serializedSparse: StringTensor ) -> (sparseIndices: Tensor, sparseValues: Tensor, sparseShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("DeserializeManySparse", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(serializedSparse) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("DeserializeManySparse", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(serializedSparse) + return op.execute(Int(1), Int(1), Int(1)) } /// Deserialize `SparseTensor` objects. @@ -7841,7 +7841,7 @@ public static func deserializeManySparse( /// shape = [2 50] /// /// - Parameter serialized_sparse: The serialized `SparseTensor` objects. The last dimension -/// must have 3 columns. +/// must have 3 columns. /// /// - Attr dtype: The `dtype` of the serialized `SparseTensor` objects. @inlinable @inline(__always) @@ -7849,14 +7849,14 @@ public static func deserializeSparse< Dtype: TensorFlowScalar, Tserialized: TensorFlowScalar >( - serializedSparse: Tensor + serializedSparse: Tensor ) -> (sparseIndices: Tensor, sparseValues: Tensor, sparseShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("DeserializeSparse", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("Tserialized", Tserialized.tensorFlowDataType) - op.addInput(serializedSparse) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("DeserializeSparse", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tserialized", Tserialized.tensorFlowDataType) + op.addInput(serializedSparse) + return op.execute(Int(1), Int(1), Int(1)) } /// Deserialize `SparseTensor` objects. @@ -7904,19 +7904,19 @@ public static func deserializeSparse< /// shape = [2 50] /// /// - Parameter serialized_sparse: The serialized `SparseTensor` objects. The last dimension -/// must have 3 columns. +/// must have 3 columns. /// /// - Attr dtype: The `dtype` of the serialized `SparseTensor` objects. @inlinable @inline(__always) public static func deserializeSparse( - serializedSparse: StringTensor + serializedSparse: StringTensor ) -> (sparseIndices: Tensor, sparseValues: Tensor, sparseShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("DeserializeSparse", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("Tserialized", TensorDataType(TF_STRING)) - op.addInput(serializedSparse) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("DeserializeSparse", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tserialized", TensorDataType(TF_STRING)) + op.addInput(serializedSparse) + return op.execute(Int(1), Int(1), Int(1)) } /// Deletes the resource specified by the handle. @@ -7927,26 +7927,26 @@ public static func deserializeSparse( /// - Parameter resource: handle to the resource to delete. /// /// - Attr ignore_lookup_error: whether to ignore the error when the resource -/// doesn't exist. +/// doesn't exist. @inlinable @inline(__always) public static func destroyResourceOp( - resource: ResourceHandle, - ignoreLookupError: Bool = true + resource: ResourceHandle, + ignoreLookupError: Bool = true ) { let nOutputs = 0 - let op = makeOp("DestroyResourceOp", nOutputs) - op.updateAttribute("ignore_lookup_error", ignoreLookupError) - op.addInput(resource) - op.execute() + let op = makeOp("DestroyResourceOp", nOutputs) + op.updateAttribute("ignore_lookup_error", ignoreLookupError) + op.addInput(resource) + op.execute() } @inlinable @inline(__always) public static func devicePlacementOp( ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("DevicePlacementOp", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("DevicePlacementOp", nOutputs) + + return op.execute(Int(1)) } /// Returns a diagonal tensor with a given diagonal values. @@ -7972,13 +7972,13 @@ public static func devicePlacementOp( /// - Parameter diagonal: Rank k tensor where k is at most 1. @inlinable @inline(__always) public static func diag( - diagonal: Tensor + diagonal: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Diag", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(diagonal) - return op.execute(Int(1)) + let op = makeOp("Diag", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(diagonal) + return op.execute(Int(1)) } /// Returns the diagonal part of the tensor. @@ -8007,13 +8007,13 @@ public static func diag( /// - Output diagonal: The extracted diagonal. @inlinable @inline(__always) public static func diagPart( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DiagPart", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("DiagPart", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Computes Psi, the derivative of Lgamma (the log of the absolute value of @@ -8021,13 +8021,13 @@ public static func diagPart( /// `Gamma(x)`), element-wise. @inlinable @inline(__always) public static func digamma( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Digamma", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Digamma", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the grayscale dilation of 4-D `input` and 3-D `filter` tensors. @@ -8057,106 +8057,106 @@ public static func digamma( /// negation of the erosion of `-input` by the reflected `filter`. /// /// - Parameters: -/// - input: 4-D with shape `[batch, in_height, in_width, depth]`. -/// - filter: 3-D with shape `[filter_height, filter_width, depth]`. +/// - input: 4-D with shape `[batch, in_height, in_width, depth]`. +/// - filter: 3-D with shape `[filter_height, filter_width, depth]`. /// /// - Attrs: -/// - strides: The stride of the sliding window for each dimension of the input -/// tensor. Must be: `[1, stride_height, stride_width, 1]`. -/// - rates: The input stride for atrous morphological dilation. Must be: -/// `[1, rate_height, rate_width, 1]`. -/// - padding: The type of padding algorithm to use. +/// - strides: The stride of the sliding window for each dimension of the input +/// tensor. Must be: `[1, stride_height, stride_width, 1]`. +/// - rates: The input stride for atrous morphological dilation. Must be: +/// `[1, rate_height, rate_width, 1]`. +/// - padding: The type of padding algorithm to use. /// /// - Output output: 4-D with shape `[batch, out_height, out_width, depth]`. @inlinable @inline(__always) public static func dilation2D( - _ input: Tensor, - filter: Tensor, - strides: [Int32], - rates: [Int32], - padding: Padding + _ input: Tensor, + filter: Tensor, + strides: [Int32], + rates: [Int32], + padding: Padding ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Dilation2D", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("rates", rates) - op.updateAttribute("padding", padding.cName) - op.addInput(input) - op.addInput(filter) - return op.execute(Int(1)) + let op = makeOp("Dilation2D", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("rates", rates) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(filter) + return op.execute(Int(1)) } /// Computes the gradient of morphological 2-D dilation with respect to the filter. /// /// - Parameters: -/// - input: 4-D with shape `[batch, in_height, in_width, depth]`. -/// - filter: 3-D with shape `[filter_height, filter_width, depth]`. -/// - out_backprop: 4-D with shape `[batch, out_height, out_width, depth]`. +/// - input: 4-D with shape `[batch, in_height, in_width, depth]`. +/// - filter: 3-D with shape `[filter_height, filter_width, depth]`. +/// - out_backprop: 4-D with shape `[batch, out_height, out_width, depth]`. /// /// - Attrs: -/// - strides: 1-D of length 4. The stride of the sliding window for each dimension of -/// the input tensor. Must be: `[1, stride_height, stride_width, 1]`. -/// - rates: 1-D of length 4. The input stride for atrous morphological dilation. -/// Must be: `[1, rate_height, rate_width, 1]`. -/// - padding: The type of padding algorithm to use. +/// - strides: 1-D of length 4. The stride of the sliding window for each dimension of +/// the input tensor. Must be: `[1, stride_height, stride_width, 1]`. +/// - rates: 1-D of length 4. The input stride for atrous morphological dilation. +/// Must be: `[1, rate_height, rate_width, 1]`. +/// - padding: The type of padding algorithm to use. /// /// - Output filter_backprop: 3-D with shape `[filter_height, filter_width, depth]`. @inlinable @inline(__always) public static func dilation2DBackpropFilter( - _ input: Tensor, - filter: Tensor, - outBackprop: Tensor, - strides: [Int32], - rates: [Int32], - padding: Padding + _ input: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + rates: [Int32], + padding: Padding ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Dilation2DBackpropFilter", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("rates", rates) - op.updateAttribute("padding", padding.cName) - op.addInput(input) - op.addInput(filter) - op.addInput(outBackprop) - return op.execute(Int(1)) + let op = makeOp("Dilation2DBackpropFilter", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("rates", rates) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) } /// Computes the gradient of morphological 2-D dilation with respect to the input. /// /// - Parameters: -/// - input: 4-D with shape `[batch, in_height, in_width, depth]`. -/// - filter: 3-D with shape `[filter_height, filter_width, depth]`. -/// - out_backprop: 4-D with shape `[batch, out_height, out_width, depth]`. +/// - input: 4-D with shape `[batch, in_height, in_width, depth]`. +/// - filter: 3-D with shape `[filter_height, filter_width, depth]`. +/// - out_backprop: 4-D with shape `[batch, out_height, out_width, depth]`. /// /// - Attrs: -/// - strides: 1-D of length 4. The stride of the sliding window for each dimension of -/// the input tensor. Must be: `[1, stride_height, stride_width, 1]`. -/// - rates: 1-D of length 4. The input stride for atrous morphological dilation. -/// Must be: `[1, rate_height, rate_width, 1]`. -/// - padding: The type of padding algorithm to use. +/// - strides: 1-D of length 4. The stride of the sliding window for each dimension of +/// the input tensor. Must be: `[1, stride_height, stride_width, 1]`. +/// - rates: 1-D of length 4. The input stride for atrous morphological dilation. +/// Must be: `[1, rate_height, rate_width, 1]`. +/// - padding: The type of padding algorithm to use. /// /// - Output in_backprop: 4-D with shape `[batch, in_height, in_width, depth]`. @inlinable @inline(__always) public static func dilation2DBackpropInput( - _ input: Tensor, - filter: Tensor, - outBackprop: Tensor, - strides: [Int32], - rates: [Int32], - padding: Padding + _ input: Tensor, + filter: Tensor, + outBackprop: Tensor, + strides: [Int32], + rates: [Int32], + padding: Padding ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Dilation2DBackpropInput", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("rates", rates) - op.updateAttribute("padding", padding.cName) - op.addInput(input) - op.addInput(filter) - op.addInput(outBackprop) - return op.execute(Int(1)) + let op = makeOp("Dilation2DBackpropInput", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("rates", rates) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(filter) + op.addInput(outBackprop) + return op.execute(Int(1)) } /// Returns x / y element-wise. @@ -8165,15 +8165,15 @@ public static func dilation2DBackpropInput( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func div( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Div", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Div", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns 0 if the denominator is zero. @@ -8183,15 +8183,15 @@ public static func div( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func divNoNan( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DivNoNan", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("DivNoNan", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Draw bounding boxes on a batch of images. @@ -8209,23 +8209,23 @@ public static func divNoNan( /// Parts of the bounding box may fall outside the image. /// /// - Parameters: -/// - images: 4-D with shape `[batch, height, width, depth]`. A batch of images. -/// - boxes: 3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding -/// boxes. +/// - images: 4-D with shape `[batch, height, width, depth]`. A batch of images. +/// - boxes: 3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding +/// boxes. /// /// - Output output: 4-D with the same shape as `images`. The batch of input images with -/// bounding boxes drawn on the images. +/// bounding boxes drawn on the images. @inlinable @inline(__always) public static func drawBoundingBoxes( - images: Tensor, - boxes: Tensor + images: Tensor, + boxes: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DrawBoundingBoxes", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(images) - op.addInput(boxes) - return op.execute(Int(1)) + let op = makeOp("DrawBoundingBoxes", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + op.addInput(boxes) + return op.execute(Int(1)) } /// Draw bounding boxes on a batch of images. @@ -8243,26 +8243,26 @@ public static func drawBoundingBoxes( /// Parts of the bounding box may fall outside the image. /// /// - Parameters: -/// - images: 4-D with shape `[batch, height, width, depth]`. A batch of images. -/// - boxes: 3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding -/// boxes. -/// - colors: 2-D. A list of RGBA colors to cycle through for the boxes. +/// - images: 4-D with shape `[batch, height, width, depth]`. A batch of images. +/// - boxes: 3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding +/// boxes. +/// - colors: 2-D. A list of RGBA colors to cycle through for the boxes. /// /// - Output output: 4-D with the same shape as `images`. The batch of input images with -/// bounding boxes drawn on the images. +/// bounding boxes drawn on the images. @inlinable @inline(__always) public static func drawBoundingBoxesV2( - images: Tensor, - boxes: Tensor, - colors: Tensor + images: Tensor, + boxes: Tensor, + colors: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DrawBoundingBoxesV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(images) - op.addInput(boxes) - op.addInput(colors) - return op.execute(Int(1)) + let op = makeOp("DrawBoundingBoxesV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + op.addInput(boxes) + op.addInput(colors) + return op.execute(Int(1)) } /// Partitions `data` into `num_partitions` tensors using indices from `partitions`. @@ -8310,17 +8310,17 @@ public static func drawBoundingBoxesV2( /// - Attr num_partitions: The number of partitions to output. @inlinable @inline(__always) public static func dynamicPartition( - data: Tensor, - partitions: Tensor, - numPartitions: Int64 + data: Tensor, + partitions: Tensor, + numPartitions: Int64 ) -> [Tensor] { let nOutputs = Int(numPartitions) - let op = makeOp("DynamicPartition", nOutputs) - op.updateAttribute("num_partitions", numPartitions) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(data) - op.addInput(partitions) - return op.execute(Int(numPartitions)) + let op = makeOp("DynamicPartition", nOutputs) + op.updateAttribute("num_partitions", numPartitions) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(data) + op.addInput(partitions) + return op.execute(Int(numPartitions)) } /// Interleave the values from the `data` tensors into a single tensor. @@ -8389,16 +8389,16 @@ public static func dynamicPartition( /// @inlinable @inline(__always) public static func dynamicStitch( - indices: [Tensor], - data: [Tensor] + indices: [Tensor], + data: [Tensor] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("DynamicStitch", nOutputs) - op.updateAttribute("N", indices.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInputList(indices) - op.addInputList(data) - return op.execute(Int(1)) + let op = makeOp("DynamicStitch", nOutputs) + op.updateAttribute("N", indices.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInputList(indices) + op.addInputList(data) + return op.execute(Int(1)) } /// Eagerly executes a python function to compute func(input)->output. The @@ -8410,16 +8410,16 @@ public static func eagerPyFunc< Tin: TensorArrayProtocol, Tout: TensorGroup >( - _ input: Tin, - token: String + _ input: Tin, + token: String ) -> Tout { let nOutputs = Int(Tout._typeList.count) - let op = makeOp("EagerPyFunc", nOutputs) - op.updateAttribute("token", token) - op.updateAttribute("Tin", input._typeList) - op.updateAttribute("Tout", Tout._typeList) - op.addInputList(input) - return op.execute(Int(Tout._typeList.count)) + let op = makeOp("EagerPyFunc", nOutputs) + op.updateAttribute("token", token) + op.updateAttribute("Tin", input._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.addInputList(input) + return op.execute(Int(Tout._typeList.count)) } /// Computes the (possibly normalized) Levenshtein Edit Distance. @@ -8432,73 +8432,73 @@ public static func eagerPyFunc< /// The inputs are: /// /// - Parameters: -/// - hypothesis_indices: The indices of the hypothesis list SparseTensor. -/// This is an N x R int64 matrix. -/// - hypothesis_values: The values of the hypothesis list SparseTensor. -/// This is an N-length vector. -/// - hypothesis_shape: The shape of the hypothesis list SparseTensor. -/// This is an R-length vector. -/// - truth_indices: The indices of the truth list SparseTensor. -/// This is an M x R int64 matrix. -/// - truth_values: The values of the truth list SparseTensor. -/// This is an M-length vector. -/// - truth_shape: truth indices, vector. +/// - hypothesis_indices: The indices of the hypothesis list SparseTensor. +/// This is an N x R int64 matrix. +/// - hypothesis_values: The values of the hypothesis list SparseTensor. +/// This is an N-length vector. +/// - hypothesis_shape: The shape of the hypothesis list SparseTensor. +/// This is an R-length vector. +/// - truth_indices: The indices of the truth list SparseTensor. +/// This is an M x R int64 matrix. +/// - truth_values: The values of the truth list SparseTensor. +/// This is an M-length vector. +/// - truth_shape: truth indices, vector. /// /// - Attr normalize: boolean (if true, edit distances are normalized by length of truth). /// -/// The output is: +/// The output is: /// /// - Output output: A dense float tensor with rank R - 1. /// -/// For the example input: -/// -/// // hypothesis represents a 2x1 matrix with variable-length values: -/// // (0,0) = ["a"] -/// // (1,0) = ["b"] -/// hypothesis_indices = [[0, 0, 0], -/// [1, 0, 0]] -/// hypothesis_values = ["a", "b"] -/// hypothesis_shape = [2, 1, 1] -/// -/// // truth represents a 2x2 matrix with variable-length values: -/// // (0,0) = [] -/// // (0,1) = ["a"] -/// // (1,0) = ["b", "c"] -/// // (1,1) = ["a"] -/// truth_indices = [[0, 1, 0], -/// [1, 0, 0], -/// [1, 0, 1], -/// [1, 1, 0]] -/// truth_values = ["a", "b", "c", "a"] -/// truth_shape = [2, 2, 2] -/// normalize = true -/// -/// The output will be: -/// -/// // output is a 2x2 matrix with edit distances normalized by truth lengths. -/// output = [[inf, 1.0], // (0,0): no truth, (0,1): no hypothesis -/// [0.5, 1.0]] // (1,0): addition, (1,1): no hypothesis +/// For the example input: +/// +/// // hypothesis represents a 2x1 matrix with variable-length values: +/// // (0,0) = ["a"] +/// // (1,0) = ["b"] +/// hypothesis_indices = [[0, 0, 0], +/// [1, 0, 0]] +/// hypothesis_values = ["a", "b"] +/// hypothesis_shape = [2, 1, 1] +/// +/// // truth represents a 2x2 matrix with variable-length values: +/// // (0,0) = [] +/// // (0,1) = ["a"] +/// // (1,0) = ["b", "c"] +/// // (1,1) = ["a"] +/// truth_indices = [[0, 1, 0], +/// [1, 0, 0], +/// [1, 0, 1], +/// [1, 1, 0]] +/// truth_values = ["a", "b", "c", "a"] +/// truth_shape = [2, 2, 2] +/// normalize = true +/// +/// The output will be: +/// +/// // output is a 2x2 matrix with edit distances normalized by truth lengths. +/// output = [[inf, 1.0], // (0,0): no truth, (0,1): no hypothesis +/// [0.5, 1.0]] // (1,0): addition, (1,1): no hypothesis @inlinable @inline(__always) public static func editDistance( - hypothesisIndices: Tensor, - hypothesisValues: Tensor, - hypothesisShape: Tensor, - truthIndices: Tensor, - truthValues: Tensor, - truthShape: Tensor, - normalize: Bool = true + hypothesisIndices: Tensor, + hypothesisValues: Tensor, + hypothesisShape: Tensor, + truthIndices: Tensor, + truthValues: Tensor, + truthShape: Tensor, + normalize: Bool = true ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("EditDistance", nOutputs) - op.updateAttribute("normalize", normalize) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(hypothesisIndices) - op.addInput(hypothesisValues) - op.addInput(hypothesisShape) - op.addInput(truthIndices) - op.addInput(truthValues) - op.addInput(truthShape) - return op.execute(Int(1)) + let op = makeOp("EditDistance", nOutputs) + op.updateAttribute("normalize", normalize) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(hypothesisIndices) + op.addInput(hypothesisValues) + op.addInput(hypothesisShape) + op.addInput(truthIndices) + op.addInput(truthValues) + op.addInput(truthShape) + return op.execute(Int(1)) } /// Computes exponential linear: `exp(features) - 1` if < 0, `features` otherwise. @@ -8507,34 +8507,34 @@ public static func editDistance( /// ](http://arxiv.org/abs/1511.07289) @inlinable @inline(__always) public static func elu( - features: Tensor + features: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Elu", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(features) - return op.execute(Int(1)) + let op = makeOp("Elu", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) } /// Computes gradients for the exponential linear (Elu) operation. /// /// - Parameters: -/// - gradients: The backpropagated gradients to the corresponding Elu operation. -/// - outputs: The outputs of the corresponding Elu operation. +/// - gradients: The backpropagated gradients to the corresponding Elu operation. +/// - outputs: The outputs of the corresponding Elu operation. /// /// - Output backprops: The gradients: `gradients * (outputs + 1)` if outputs < 0, -/// `gradients` otherwise. +/// `gradients` otherwise. @inlinable @inline(__always) public static func eluGrad( - gradients: Tensor, - outputs: Tensor + gradients: Tensor, + outputs: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("EluGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(gradients) - op.addInput(outputs) - return op.execute(Int(1)) + let op = makeOp("EluGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(outputs) + return op.execute(Int(1)) } /// Creates a tensor with the given shape. @@ -8548,15 +8548,15 @@ public static func eluGrad( /// - Output output: A `Tensor` of type `T`. @inlinable @inline(__always) public static func empty( - shape: Tensor, - init_: Bool = false + shape: Tensor, + init_: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Empty", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("init", init_) - op.addInput(shape) - return op.execute(Int(1)) + let op = makeOp("Empty", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("init", init_) + op.addInput(shape) + return op.execute(Int(1)) } /// Creates and returns an empty tensor list. @@ -8569,17 +8569,17 @@ public static func empty( /// element_shape: a shape compatible with that of elements in the list. @inlinable @inline(__always) public static func emptyTensorList( - elementShape: Tensor, - maxNumElements: Tensor, - elementDtype: TensorDataType + elementShape: Tensor, + maxNumElements: Tensor, + elementDtype: TensorDataType ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("EmptyTensorList", nOutputs) - op.updateAttribute("element_dtype", elementDtype) - op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) - op.addInput(elementShape) - op.addInput(maxNumElements) - return op.execute(Int(1)) + let op = makeOp("EmptyTensorList", nOutputs) + op.updateAttribute("element_dtype", elementDtype) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(elementShape) + op.addInput(maxNumElements) + return op.execute(Int(1)) } /// Encode strings into web-safe base64 format. @@ -8598,14 +8598,14 @@ public static func emptyTensorList( /// - Output output: Input strings encoded in base64. @inlinable @inline(__always) public static func encodeBase64( - _ input: StringTensor, - pad: Bool = false + _ input: StringTensor, + pad: Bool = false ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("EncodeBase64", nOutputs) - op.updateAttribute("pad", pad) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("EncodeBase64", nOutputs) + op.updateAttribute("pad", pad) + op.addInput(input) + return op.execute(Int(1)) } /// JPEG-encode an image. @@ -8630,44 +8630,44 @@ public static func encodeBase64( /// - Parameter image: 3-D with shape `[height, width, channels]`. /// /// - Attrs: -/// - format: Per pixel image format. -/// - quality: Quality of the compression from 0 to 100 (higher is better and slower). -/// - progressive: If True, create a JPEG that loads progressively (coarse to fine). -/// - optimize_size: If True, spend CPU/RAM to reduce size with no quality change. -/// - chroma_downsampling: See http://en.wikipedia.org/wiki/Chroma_subsampling. -/// - density_unit: Unit used to specify `x_density` and `y_density`: -/// pixels per inch (`'in'`) or centimeter (`'cm'`). -/// - x_density: Horizontal pixels per density unit. -/// - y_density: Vertical pixels per density unit. -/// - xmp_metadata: If not empty, embed this XMP metadata in the image header. +/// - format: Per pixel image format. +/// - quality: Quality of the compression from 0 to 100 (higher is better and slower). +/// - progressive: If True, create a JPEG that loads progressively (coarse to fine). +/// - optimize_size: If True, spend CPU/RAM to reduce size with no quality change. +/// - chroma_downsampling: See http://en.wikipedia.org/wiki/Chroma_subsampling. +/// - density_unit: Unit used to specify `x_density` and `y_density`: +/// pixels per inch (`'in'`) or centimeter (`'cm'`). +/// - x_density: Horizontal pixels per density unit. +/// - y_density: Vertical pixels per density unit. +/// - xmp_metadata: If not empty, embed this XMP metadata in the image header. /// /// - Output contents: 0-D. JPEG-encoded image. @inlinable @inline(__always) public static func encodeJpeg( - image: Tensor, - format: Format, - quality: Int64 = 95, - progressive: Bool = false, - optimizeSize: Bool = false, - chromaDownsampling: Bool = true, - densityUnit: DensityUnit = .in_, - xDensity: Int64 = 300, - yDensity: Int64 = 300, - xmpMetadata: String + image: Tensor, + format: Format, + quality: Int64 = 95, + progressive: Bool = false, + optimizeSize: Bool = false, + chromaDownsampling: Bool = true, + densityUnit: DensityUnit = .in_, + xDensity: Int64 = 300, + yDensity: Int64 = 300, + xmpMetadata: String ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("EncodeJpeg", nOutputs) - op.updateAttribute("format", format.cName) - op.updateAttribute("quality", quality) - op.updateAttribute("progressive", progressive) - op.updateAttribute("optimize_size", optimizeSize) - op.updateAttribute("chroma_downsampling", chromaDownsampling) - op.updateAttribute("density_unit", densityUnit.cName) - op.updateAttribute("x_density", xDensity) - op.updateAttribute("y_density", yDensity) - op.updateAttribute("xmp_metadata", xmpMetadata) - op.addInput(image) - return op.execute(Int(1)) + let op = makeOp("EncodeJpeg", nOutputs) + op.updateAttribute("format", format.cName) + op.updateAttribute("quality", quality) + op.updateAttribute("progressive", progressive) + op.updateAttribute("optimize_size", optimizeSize) + op.updateAttribute("chroma_downsampling", chromaDownsampling) + op.updateAttribute("density_unit", densityUnit.cName) + op.updateAttribute("x_density", xDensity) + op.updateAttribute("y_density", yDensity) + op.updateAttribute("xmp_metadata", xmpMetadata) + op.addInput(image) + return op.execute(Int(1)) } /// JPEG encode input image with provided compression quality. @@ -8677,20 +8677,20 @@ public static func encodeJpeg( /// /// /// - Parameters: -/// - images: Images to adjust. At least 3-D. -/// - quality: An int quality to encode to. +/// - images: Images to adjust. At least 3-D. +/// - quality: An int quality to encode to. /// /// - Output contents: 0-D. JPEG-encoded image. @inlinable @inline(__always) public static func encodeJpegVariableQuality( - images: Tensor, - quality: Tensor + images: Tensor, + quality: Tensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("EncodeJpegVariableQuality", nOutputs) - op.addInput(images) - op.addInput(quality) - return op.execute(Int(1)) + let op = makeOp("EncodeJpegVariableQuality", nOutputs) + op.addInput(images) + op.addInput(quality) + return op.execute(Int(1)) } /// PNG-encode an image. @@ -8714,15 +8714,15 @@ public static func encodeJpegVariableQuality( /// - Output contents: 0-D. PNG-encoded image. @inlinable @inline(__always) public static func encodePng( - image: Tensor, - compression: Int64 = -1 + image: Tensor, + compression: Int64 = -1 ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("EncodePng", nOutputs) - op.updateAttribute("compression", compression) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(image) - return op.execute(Int(1)) + let op = makeOp("EncodePng", nOutputs) + op.updateAttribute("compression", compression) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(image) + return op.execute(Int(1)) } /// The op serializes protobuf messages provided in the input tensors. @@ -8766,32 +8766,32 @@ public static func encodePng( /// with sign wrapping if the input is of type `tf.int32`. /// /// - Parameters: -/// - sizes: Tensor of int32 with shape `[batch_shape, len(field_names)]`. -/// - values: List of tensors containing values for the corresponding field. +/// - sizes: Tensor of int32 with shape `[batch_shape, len(field_names)]`. +/// - values: List of tensors containing values for the corresponding field. /// /// - Attrs: -/// - field_names: List of strings containing proto field names. -/// - message_type: Name of the proto message type to decode. -/// - Tinput_types: The input types. +/// - field_names: List of strings containing proto field names. +/// - message_type: Name of the proto message type to decode. +/// - Tinput_types: The input types. /// /// - Output bytes: Tensor of serialized protos with shape `batch_shape`. @inlinable @inline(__always) public static func encodeProto( - sizes: Tensor, - _ values: TinputTypes, - fieldNames: [String], - messageType: String, - descriptorSource: String = "local://" + sizes: Tensor, + _ values: TinputTypes, + fieldNames: [String], + messageType: String, + descriptorSource: String = "local://" ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("EncodeProto", nOutputs) - op.updateAttribute("field_names", fieldNames) - op.updateAttribute("message_type", messageType) - op.updateAttribute("descriptor_source", descriptorSource) - op.updateAttribute("Tinput_types", values._typeList) - op.addInput(sizes) - op.addInputList(values) - return op.execute(Int(1)) + let op = makeOp("EncodeProto", nOutputs) + op.updateAttribute("field_names", fieldNames) + op.updateAttribute("message_type", messageType) + op.updateAttribute("descriptor_source", descriptorSource) + op.updateAttribute("Tinput_types", values._typeList) + op.addInput(sizes) + op.addInputList(values) + return op.execute(Int(1)) } /// Encode audio data using the WAV file format. @@ -8805,47 +8805,47 @@ public static func encodeProto( /// `sample_rate` is a scalar Tensor holding the rate to use (e.g. 44100). /// /// - Parameters: -/// - audio: 2-D with shape `[length, channels]`. -/// - sample_rate: Scalar containing the sample frequency. +/// - audio: 2-D with shape `[length, channels]`. +/// - sample_rate: Scalar containing the sample frequency. /// /// - Output contents: 0-D. WAV-encoded file contents. @inlinable @inline(__always) public static func encodeWav( - audio: Tensor, - sampleRate: Tensor + audio: Tensor, + sampleRate: Tensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("EncodeWav", nOutputs) - op.addInput(audio) - op.addInput(sampleRate) - return op.execute(Int(1)) + let op = makeOp("EncodeWav", nOutputs) + op.addInput(audio) + op.addInput(sampleRate) + return op.execute(Int(1)) } /// An op that enqueues a list of input batch tensors to TPUEmbedding. /// /// - Parameters: -/// - batch: A list of 1D tensors, one for each embedding table, containing the -/// indices into the tables. -/// - mode_override: A string input that overrides the mode specified in the -/// TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', -/// 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set -/// in TPUEmbeddingConfiguration is used, otherwise mode_override is used. +/// - batch: A list of 1D tensors, one for each embedding table, containing the +/// indices into the tables. +/// - mode_override: A string input that overrides the mode specified in the +/// TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', +/// 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set +/// in TPUEmbeddingConfiguration is used, otherwise mode_override is used. /// /// - Attr device_ordinal: The TPU device to use. Should be >= 0 and less than the number -/// of TPU cores in the task on which the node is placed. +/// of TPU cores in the task on which the node is placed. @inlinable @inline(__always) public static func enqueueTPUEmbeddingIntegerBatch( - batch: [Tensor], - modeOverride: StringTensor, - deviceOrdinal: Int64 = -1 + batch: [Tensor], + modeOverride: StringTensor, + deviceOrdinal: Int64 = -1 ) { let nOutputs = 0 - let op = makeOp("EnqueueTPUEmbeddingIntegerBatch", nOutputs) - op.updateAttribute("N", batch.count) - op.updateAttribute("device_ordinal", deviceOrdinal) - op.addInputList(batch) - op.addInput(modeOverride) - op.execute() + let op = makeOp("EnqueueTPUEmbeddingIntegerBatch", nOutputs) + op.updateAttribute("N", batch.count) + op.updateAttribute("device_ordinal", deviceOrdinal) + op.addInputList(batch) + op.addInput(modeOverride) + op.execute() } /// An op that enqueues TPUEmbedding input indices from a SparseTensor. @@ -8861,54 +8861,54 @@ public static func enqueueTPUEmbeddingIntegerBatch( /// number of lookups into the table described by the corresponding table_id. /// /// - Parameters: -/// - sample_indices: A list of rank 1 Tensors specifying the training example and -/// feature to which the corresponding embedding_indices and aggregation_weights -/// values belong. sample_indices[i] must equal b * nf + f, where nf is the -/// number of features from the corresponding table, f is in [0, nf), and -/// b is in [0, batch size). -/// - embedding_indices: A list of rank 1 Tensors, indices into the embedding tables. -/// - aggregation_weights: A list of rank 1 Tensors containing per sample -- i.e. per -/// (training example, feature) -- aggregation weights. -/// - mode_override: A string input that overrides the mode specified in the -/// TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', -/// 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set -/// in TPUEmbeddingConfiguration is used, otherwise mode_override is used. +/// - sample_indices: A list of rank 1 Tensors specifying the training example and +/// feature to which the corresponding embedding_indices and aggregation_weights +/// values belong. sample_indices[i] must equal b * nf + f, where nf is the +/// number of features from the corresponding table, f is in [0, nf), and +/// b is in [0, batch size). +/// - embedding_indices: A list of rank 1 Tensors, indices into the embedding tables. +/// - aggregation_weights: A list of rank 1 Tensors containing per sample -- i.e. per +/// (training example, feature) -- aggregation weights. +/// - mode_override: A string input that overrides the mode specified in the +/// TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', +/// 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set +/// in TPUEmbeddingConfiguration is used, otherwise mode_override is used. /// /// - Attrs: -/// - device_ordinal: The TPU device to use. Should be >= 0 and less than the number -/// of TPU cores in the task on which the node is placed. -/// - combiners: A list of string scalars, one for each embedding table that specify -/// how to normalize the embedding activations after weighted summation. -/// Supported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have -/// the sum of the weights be 0 for 'mean' or the sum of the squared weights be -/// 0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for -/// all tables. +/// - device_ordinal: The TPU device to use. Should be >= 0 and less than the number +/// of TPU cores in the task on which the node is placed. +/// - combiners: A list of string scalars, one for each embedding table that specify +/// how to normalize the embedding activations after weighted summation. +/// Supported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have +/// the sum of the weights be 0 for 'mean' or the sum of the squared weights be +/// 0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for +/// all tables. @inlinable @inline(__always) public static func enqueueTPUEmbeddingSparseBatch< T1: BinaryInteger & TensorFlowScalar, T2: BinaryInteger & TensorFlowScalar, T3: FloatingPoint & TensorFlowScalar >( - sampleIndices: [Tensor], - embeddingIndices: [Tensor], - aggregationWeights: [Tensor], - modeOverride: StringTensor, - deviceOrdinal: Int64 = -1, - combiners: [String] + sampleIndices: [Tensor], + embeddingIndices: [Tensor], + aggregationWeights: [Tensor], + modeOverride: StringTensor, + deviceOrdinal: Int64 = -1, + combiners: [String] ) { let nOutputs = 0 - let op = makeOp("EnqueueTPUEmbeddingSparseBatch", nOutputs) - op.updateAttribute("T1", T1.tensorFlowDataType) - op.updateAttribute("T2", T2.tensorFlowDataType) - op.updateAttribute("T3", T3.tensorFlowDataType) - op.updateAttribute("N", sampleIndices.count) - op.updateAttribute("device_ordinal", deviceOrdinal) - op.updateAttribute("combiners", combiners) - op.addInputList(sampleIndices) - op.addInputList(embeddingIndices) - op.addInputList(aggregationWeights) - op.addInput(modeOverride) - op.execute() + let op = makeOp("EnqueueTPUEmbeddingSparseBatch", nOutputs) + op.updateAttribute("T1", T1.tensorFlowDataType) + op.updateAttribute("T2", T2.tensorFlowDataType) + op.updateAttribute("T3", T3.tensorFlowDataType) + op.updateAttribute("N", sampleIndices.count) + op.updateAttribute("device_ordinal", deviceOrdinal) + op.updateAttribute("combiners", combiners) + op.addInputList(sampleIndices) + op.addInputList(embeddingIndices) + op.addInputList(aggregationWeights) + op.addInput(modeOverride) + op.execute() } /// Eases the porting of code that uses tf.nn.embedding_lookup_sparse(). @@ -8923,63 +8923,63 @@ public static func enqueueTPUEmbeddingSparseBatch< /// the corresponding feature. /// /// - Parameters: -/// - sample_indices: A list of rank 1 Tensors specifying the training example to -/// which the corresponding embedding_indices and aggregation_weights values -/// belong. It corresponds to sp_ids.indices[:,0] in embedding_lookup_sparse(). -/// - embedding_indices: A list of rank 1 Tensors, indices into the embedding tables. -/// It corresponds to sp_ids.values in embedding_lookup_sparse(). -/// - aggregation_weights: A list of rank 1 Tensors containing per training example -/// aggregation weights. It corresponds to sp_weights.values in -/// embedding_lookup_sparse(). -/// - mode_override: A string input that overrides the mode specified in the -/// TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', -/// 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set -/// in TPUEmbeddingConfiguration is used, otherwise mode_override is used. +/// - sample_indices: A list of rank 1 Tensors specifying the training example to +/// which the corresponding embedding_indices and aggregation_weights values +/// belong. It corresponds to sp_ids.indices[:,0] in embedding_lookup_sparse(). +/// - embedding_indices: A list of rank 1 Tensors, indices into the embedding tables. +/// It corresponds to sp_ids.values in embedding_lookup_sparse(). +/// - aggregation_weights: A list of rank 1 Tensors containing per training example +/// aggregation weights. It corresponds to sp_weights.values in +/// embedding_lookup_sparse(). +/// - mode_override: A string input that overrides the mode specified in the +/// TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', +/// 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set +/// in TPUEmbeddingConfiguration is used, otherwise mode_override is used. /// /// - Attrs: -/// - device_ordinal: The TPU device to use. Should be >= 0 and less than the number -/// of TPU cores in the task on which the node is placed. -/// - combiners: A list of string scalars, one for each embedding table that specify -/// how to normalize the embedding activations after weighted summation. -/// Supported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have -/// the sum of the weights be 0 for 'mean' or the sum of the squared weights be -/// 0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for -/// all tables. -/// - table_ids: A list of integers specifying the identifier of the embedding table -/// (offset of TableDescriptor in the TPUEmbeddingConfiguration) to lookup the -/// corresponding input. The ith input is looked up using table_ids[i]. The size -/// of the table_ids list must be equal to that of sample_indices, -/// embedding_indices and aggregation_weights. +/// - device_ordinal: The TPU device to use. Should be >= 0 and less than the number +/// of TPU cores in the task on which the node is placed. +/// - combiners: A list of string scalars, one for each embedding table that specify +/// how to normalize the embedding activations after weighted summation. +/// Supported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have +/// the sum of the weights be 0 for 'mean' or the sum of the squared weights be +/// 0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for +/// all tables. +/// - table_ids: A list of integers specifying the identifier of the embedding table +/// (offset of TableDescriptor in the TPUEmbeddingConfiguration) to lookup the +/// corresponding input. The ith input is looked up using table_ids[i]. The size +/// of the table_ids list must be equal to that of sample_indices, +/// embedding_indices and aggregation_weights. @inlinable @inline(__always) public static func enqueueTPUEmbeddingSparseTensorBatch< T1: BinaryInteger & TensorFlowScalar, T2: BinaryInteger & TensorFlowScalar, T3: FloatingPoint & TensorFlowScalar >( - sampleIndices: [Tensor], - embeddingIndices: [Tensor], - aggregationWeights: [Tensor], - modeOverride: StringTensor, - deviceOrdinal: Int64 = -1, - combiners: [String], - tableIds: [Int32], - maxSequenceLengths: [Int32] + sampleIndices: [Tensor], + embeddingIndices: [Tensor], + aggregationWeights: [Tensor], + modeOverride: StringTensor, + deviceOrdinal: Int64 = -1, + combiners: [String], + tableIds: [Int32], + maxSequenceLengths: [Int32] ) { let nOutputs = 0 - let op = makeOp("EnqueueTPUEmbeddingSparseTensorBatch", nOutputs) - op.updateAttribute("T1", T1.tensorFlowDataType) - op.updateAttribute("T2", T2.tensorFlowDataType) - op.updateAttribute("T3", T3.tensorFlowDataType) - op.updateAttribute("N", sampleIndices.count) - op.updateAttribute("device_ordinal", deviceOrdinal) - op.updateAttribute("combiners", combiners) - op.updateAttribute("table_ids", tableIds) - op.updateAttribute("max_sequence_lengths", maxSequenceLengths) - op.addInputList(sampleIndices) - op.addInputList(embeddingIndices) - op.addInputList(aggregationWeights) - op.addInput(modeOverride) - op.execute() + let op = makeOp("EnqueueTPUEmbeddingSparseTensorBatch", nOutputs) + op.updateAttribute("T1", T1.tensorFlowDataType) + op.updateAttribute("T2", T2.tensorFlowDataType) + op.updateAttribute("T3", T3.tensorFlowDataType) + op.updateAttribute("N", sampleIndices.count) + op.updateAttribute("device_ordinal", deviceOrdinal) + op.updateAttribute("combiners", combiners) + op.updateAttribute("table_ids", tableIds) + op.updateAttribute("max_sequence_lengths", maxSequenceLengths) + op.addInputList(sampleIndices) + op.addInputList(embeddingIndices) + op.addInputList(aggregationWeights) + op.addInput(modeOverride) + op.execute() } /// Ensures that the tensor's shape matches the expected shape. @@ -8994,15 +8994,15 @@ public static func enqueueTPUEmbeddingSparseTensorBatch< /// - Output output: A tensor with the same shape and contents as the input tensor or value. @inlinable @inline(__always) public static func ensureShape( - _ input: Tensor, - shape: TensorShape? + _ input: Tensor, + shape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("EnsureShape", nOutputs) - op.updateAttribute("shape", shape) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("EnsureShape", nOutputs) + op.updateAttribute("shape", shape) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Creates or finds a child frame, and makes `data` available to the child frame. @@ -9016,26 +9016,26 @@ public static func ensureShape( /// - Parameter data: The tensor to be made available to the child frame. /// /// - Attrs: -/// - frame_name: The name of the child frame. -/// - is_constant: If true, the output is constant within the child frame. -/// - parallel_iterations: The number of iterations allowed to run in parallel. +/// - frame_name: The name of the child frame. +/// - is_constant: If true, the output is constant within the child frame. +/// - parallel_iterations: The number of iterations allowed to run in parallel. /// /// - Output output: The same tensor as `data`. @inlinable @inline(__always) public static func enter( - data: Tensor, - frameName: String, - isConstant: Bool = false, - parallelIterations: Int64 = 10 + data: Tensor, + frameName: String, + isConstant: Bool = false, + parallelIterations: Int64 = 10 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Enter", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("frame_name", frameName) - op.updateAttribute("is_constant", isConstant) - op.updateAttribute("parallel_iterations", parallelIterations) - op.addInput(data) - return op.execute(Int(1)) + let op = makeOp("Enter", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("frame_name", frameName) + op.updateAttribute("is_constant", isConstant) + op.updateAttribute("parallel_iterations", parallelIterations) + op.addInput(data) + return op.execute(Int(1)) } /// Returns the truth value of (x == y) element-wise. @@ -9044,15 +9044,15 @@ public static func enter( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func equal( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Equal", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Equal", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns the truth value of (x == y) element-wise. @@ -9061,39 +9061,39 @@ public static func equal( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func equal( - _ x: StringTensor, - _ y: StringTensor + _ x: StringTensor, + _ y: StringTensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Equal", nOutputs) - op.updateAttribute("T", TensorDataType(TF_STRING)) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Equal", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Computes the Gauss error function of `x` element-wise. @inlinable @inline(__always) public static func erf( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Erf", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Erf", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the complementary error function of `x` element-wise. @inlinable @inline(__always) public static func erfc( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Erfc", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Erfc", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the euclidean norm of elements across dimensions of a tensor. @@ -9104,9 +9104,9 @@ public static func erfc( /// retained with length 1. /// /// - Parameters: -/// - input: The tensor to reduce. -/// - reduction_indices: The dimensions to reduce. Must be in the range -/// `[-rank(input), rank(input))`. +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. /// /// - Attr keep_dims: If true, retain reduced dimensions with length 1. /// @@ -9116,18 +9116,18 @@ public static func euclideanNorm< T: Numeric & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - reductionIndices: Tensor, - keepDims: Bool = false + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("EuclideanNorm", nOutputs) - op.updateAttribute("keep_dims", keepDims) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(input) - op.addInput(reductionIndices) - return op.execute(Int(1)) + let op = makeOp("EuclideanNorm", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) } /// Exits the current frame to its parent frame. @@ -9139,25 +9139,25 @@ public static func euclideanNorm< /// - Output output: The same tensor as `data`. @inlinable @inline(__always) public static func exit( - data: Tensor + data: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Exit", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(data) - return op.execute(Int(1)) + let op = makeOp("Exit", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(data) + return op.execute(Int(1)) } /// Computes exponential of x element-wise. \\(y = e^x\\). @inlinable @inline(__always) public static func exp( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Exp", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Exp", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Inserts a dimension of 1 into a tensor's shape. @@ -9194,42 +9194,42 @@ public static func exp( /// size 1. /// /// - Parameter dim: 0-D (scalar). Specifies the dimension index at which to -/// expand the shape of `input`. Must be in the range -/// `[-rank(input) - 1, rank(input)]`. +/// expand the shape of `input`. Must be in the range +/// `[-rank(input) - 1, rank(input)]`. /// /// - Output output: Contains the same data as `input`, but its shape has an additional -/// dimension of size 1 added. +/// dimension of size 1 added. @inlinable @inline(__always) public static func expandDims< T: TensorFlowScalar, Tdim: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - dim: Tensor + _ input: Tensor, + dim: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ExpandDims", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tdim", Tdim.tensorFlowDataType) - op.addInput(input) - op.addInput(dim) - return op.execute(Int(1)) + let op = makeOp("ExpandDims", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tdim", Tdim.tensorFlowDataType) + op.addInput(input) + op.addInput(dim) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func experimentalAssertNextDataset( - inputDataset: VariantHandle, - transformations: StringTensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + transformations: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalAssertNextDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(transformations) - return op.execute(Int(1)) + let op = makeOp("ExperimentalAssertNextDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(transformations) + return op.execute(Int(1)) } /// Creates a dataset that shards the input dataset. @@ -9243,88 +9243,88 @@ public static func experimentalAssertNextDataset( /// automatically. /// /// - Parameters: -/// - input_dataset: A variant tensor representing the input dataset. -/// - num_workers: A scalar representing the number of workers to distribute this dataset across. -/// - index: A scalar representing the index of the current worker out of num_workers. +/// - input_dataset: A variant tensor representing the input dataset. +/// - num_workers: A scalar representing the number of workers to distribute this dataset across. +/// - index: A scalar representing the index of the current worker out of num_workers. @inlinable @inline(__always) public static func experimentalAutoShardDataset( - inputDataset: VariantHandle, - numWorkers: Tensor, - index: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + numWorkers: Tensor, + index: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalAutoShardDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(numWorkers) - op.addInput(index) - return op.execute(Int(1)) + let op = makeOp("ExperimentalAutoShardDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(numWorkers) + op.addInput(index) + return op.execute(Int(1)) } /// Records the bytes size of each element of `input_dataset` in a StatsAggregator. @inlinable @inline(__always) public static func experimentalBytesProducedStatsDataset( - inputDataset: VariantHandle, - tag: StringTensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + tag: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalBytesProducedStatsDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(tag) - return op.execute(Int(1)) + let op = makeOp("ExperimentalBytesProducedStatsDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(tag) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func experimentalCSVDataset( - filenames: StringTensor, - compressionType: StringTensor, - bufferSize: Tensor, - header: Tensor, - fieldDelim: StringTensor, - useQuoteDelim: Tensor, - naValue: StringTensor, - selectCols: Tensor, - recordDefaults: OutputTypes, - outputShapes: [TensorShape?] + filenames: StringTensor, + compressionType: StringTensor, + bufferSize: Tensor, + header: Tensor, + fieldDelim: StringTensor, + useQuoteDelim: Tensor, + naValue: StringTensor, + selectCols: Tensor, + recordDefaults: OutputTypes, + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalCSVDataset", nOutputs) - op.updateAttribute("output_types", recordDefaults._typeList) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(filenames) - op.addInput(compressionType) - op.addInput(bufferSize) - op.addInput(header) - op.addInput(fieldDelim) - op.addInput(useQuoteDelim) - op.addInput(naValue) - op.addInput(selectCols) - op.addInputList(recordDefaults) - return op.execute(Int(1)) + let op = makeOp("ExperimentalCSVDataset", nOutputs) + op.updateAttribute("output_types", recordDefaults._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(filenames) + op.addInput(compressionType) + op.addInput(bufferSize) + op.addInput(header) + op.addInput(fieldDelim) + op.addInput(useQuoteDelim) + op.addInput(naValue) + op.addInput(selectCols) + op.addInputList(recordDefaults) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func experimentalChooseFastestDataset( - inputDatasets: [VariantHandle], - numExperiments: Int64, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDatasets: [VariantHandle], + numExperiments: Int64, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalChooseFastestDataset", nOutputs) - op.updateAttribute("N", inputDatasets.count) - op.updateAttribute("num_experiments", numExperiments) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInputList(inputDatasets) - return op.execute(Int(1)) + let op = makeOp("ExperimentalChooseFastestDataset", nOutputs) + op.updateAttribute("N", inputDatasets.count) + op.updateAttribute("num_experiments", numExperiments) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInputList(inputDatasets) + return op.execute(Int(1)) } /// Returns the cardinality of `input_dataset`. @@ -9334,87 +9334,87 @@ public static func experimentalChooseFastestDataset( /// - Parameter input_dataset: A variant tensor representing the dataset to return cardinality for. /// /// - Output cardinality: The cardinality of `input_dataset`. Named constants are used to represent -/// infinite and unknown cardinality. +/// infinite and unknown cardinality. @inlinable @inline(__always) public static func experimentalDatasetCardinality( - inputDataset: VariantHandle + inputDataset: VariantHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ExperimentalDatasetCardinality", nOutputs) - op.addInput(inputDataset) - return op.execute(Int(1)) + let op = makeOp("ExperimentalDatasetCardinality", nOutputs) + op.addInput(inputDataset) + return op.execute(Int(1)) } /// Writes the given dataset to the given file using the TFRecord format. /// /// - Parameters: -/// - input_dataset: A variant tensor representing the dataset to write. -/// - filename: A scalar string tensor representing the filename to use. -/// - compression_type: A scalar string tensor containing either (i) the empty string (no -/// compression), (ii) "ZLIB", or (iii) "GZIP". +/// - input_dataset: A variant tensor representing the dataset to write. +/// - filename: A scalar string tensor representing the filename to use. +/// - compression_type: A scalar string tensor containing either (i) the empty string (no +/// compression), (ii) "ZLIB", or (iii) "GZIP". @inlinable @inline(__always) public static func experimentalDatasetToTFRecord( - inputDataset: VariantHandle, - filename: StringTensor, - compressionType: StringTensor + inputDataset: VariantHandle, + filename: StringTensor, + compressionType: StringTensor ) { let nOutputs = 0 - let op = makeOp("ExperimentalDatasetToTFRecord", nOutputs) - op.addInput(inputDataset) - op.addInput(filename) - op.addInput(compressionType) - op.execute() + let op = makeOp("ExperimentalDatasetToTFRecord", nOutputs) + op.addInput(inputDataset) + op.addInput(filename) + op.addInput(compressionType) + op.execute() } /// Creates a dataset that batches input elements into a SparseTensor. /// /// - Parameters: -/// - input_dataset: A handle to an input dataset. Must have a single component. -/// - batch_size: A scalar representing the number of elements to accumulate in a -/// batch. -/// - row_shape: A vector representing the dense shape of each row in the produced -/// SparseTensor. The shape may be partially specified, using `-1` to indicate -/// that a particular dimension should use the maximum size of all batch elements. +/// - input_dataset: A handle to an input dataset. Must have a single component. +/// - batch_size: A scalar representing the number of elements to accumulate in a +/// batch. +/// - row_shape: A vector representing the dense shape of each row in the produced +/// SparseTensor. The shape may be partially specified, using `-1` to indicate +/// that a particular dimension should use the maximum size of all batch elements. @inlinable @inline(__always) public static func experimentalDenseToSparseBatchDataset( - inputDataset: VariantHandle, - batchSize: Tensor, - rowShape: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + batchSize: Tensor, + rowShape: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalDenseToSparseBatchDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(batchSize) - op.addInput(rowShape) - return op.execute(Int(1)) + let op = makeOp("ExperimentalDenseToSparseBatchDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(batchSize) + op.addInput(rowShape) + return op.execute(Int(1)) } /// A substitute for `InterleaveDataset` on a fixed list of `N` datasets. /// /// - Parameters: -/// - selector_input_dataset: A dataset of scalar `DT_INT64` elements that determines which of the -/// `N` data inputs should produce the next output element. -/// - data_input_datasets: `N` datasets with the same type that will be interleaved according to -/// the values of `selector_input_dataset`. +/// - selector_input_dataset: A dataset of scalar `DT_INT64` elements that determines which of the +/// `N` data inputs should produce the next output element. +/// - data_input_datasets: `N` datasets with the same type that will be interleaved according to +/// the values of `selector_input_dataset`. @inlinable @inline(__always) public static func experimentalDirectedInterleaveDataset( - selectorInputDataset: VariantHandle, - dataInputDatasets: [VariantHandle], - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + selectorInputDataset: VariantHandle, + dataInputDatasets: [VariantHandle], + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalDirectedInterleaveDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("N", dataInputDatasets.count) - op.addInput(selectorInputDataset) - op.addInputList(dataInputDatasets) - return op.execute(Int(1)) + let op = makeOp("ExperimentalDirectedInterleaveDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("N", dataInputDatasets.count) + op.addInput(selectorInputDataset) + op.addInputList(dataInputDatasets) + return op.execute(Int(1)) } /// Creates a dataset that computes a group-by on `input_dataset`. @@ -9422,24 +9422,24 @@ public static func experimentalDirectedInterleaveDataset( /// Creates a dataset that computes a group-by on `input_dataset`. /// /// - Parameters: -/// - input_dataset: A variant tensor representing the input dataset. -/// - key_func_other_arguments: A list of tensors, typically values that were captured when -/// building a closure for `key_func`. -/// - init_func_other_arguments: A list of tensors, typically values that were captured when -/// building a closure for `init_func`. -/// - reduce_func_other_arguments: A list of tensors, typically values that were captured when -/// building a closure for `reduce_func`. -/// - finalize_func_other_arguments: A list of tensors, typically values that were captured when -/// building a closure for `finalize_func`. +/// - input_dataset: A variant tensor representing the input dataset. +/// - key_func_other_arguments: A list of tensors, typically values that were captured when +/// building a closure for `key_func`. +/// - init_func_other_arguments: A list of tensors, typically values that were captured when +/// building a closure for `init_func`. +/// - reduce_func_other_arguments: A list of tensors, typically values that were captured when +/// building a closure for `reduce_func`. +/// - finalize_func_other_arguments: A list of tensors, typically values that were captured when +/// building a closure for `finalize_func`. /// /// - Attrs: -/// - key_func: A function mapping an element of `input_dataset`, concatenated -/// with `key_func_other_arguments` to a scalar value of type DT_INT64. -/// - init_func: A function mapping a key of type DT_INT64, concatenated with -/// `init_func_other_arguments` to the initial reducer state. -/// - reduce_func: A function mapping the current reducer state and an element of `input_dataset`, -/// concatenated with `reduce_func_other_arguments` to a new reducer state. -/// - finalize_func: A function mapping the final reducer state to an output element. +/// - key_func: A function mapping an element of `input_dataset`, concatenated +/// with `key_func_other_arguments` to a scalar value of type DT_INT64. +/// - init_func: A function mapping a key of type DT_INT64, concatenated with +/// `init_func_other_arguments` to the initial reducer state. +/// - reduce_func: A function mapping the current reducer state and an element of `input_dataset`, +/// concatenated with `reduce_func_other_arguments` to a new reducer state. +/// - finalize_func: A function mapping the final reducer state to an output element. @inlinable @inline(__always) public static func experimentalGroupByReducerDataset< KeyfuncIn: TensorGroup, @@ -9455,36 +9455,36 @@ public static func experimentalGroupByReducerDataset< TreduceFuncOtherArguments: TensorArrayProtocol, TfinalizeFuncOtherArguments: TensorArrayProtocol >( - inputDataset: VariantHandle, - keyFuncOtherArguments: TkeyFuncOtherArguments, - initFuncOtherArguments: TinitFuncOtherArguments, - reduceFuncOtherArguments: TreduceFuncOtherArguments, - finalizeFuncOtherArguments: TfinalizeFuncOtherArguments, - keyFunc: (KeyfuncIn) -> KeyfuncOut, - initFunc: (InitfuncIn) -> InitfuncOut, - reduceFunc: (ReducefuncIn) -> ReducefuncOut, - finalizeFunc: (FinalizefuncIn) -> FinalizefuncOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + keyFuncOtherArguments: TkeyFuncOtherArguments, + initFuncOtherArguments: TinitFuncOtherArguments, + reduceFuncOtherArguments: TreduceFuncOtherArguments, + finalizeFuncOtherArguments: TfinalizeFuncOtherArguments, + keyFunc: (KeyfuncIn) -> KeyfuncOut, + initFunc: (InitfuncIn) -> InitfuncOut, + reduceFunc: (ReducefuncIn) -> ReducefuncOut, + finalizeFunc: (FinalizefuncIn) -> FinalizefuncOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalGroupByReducerDataset", nOutputs) - op.updateAttribute("key_func", keyFunc) - op.updateAttribute("init_func", initFunc) - op.updateAttribute("reduce_func", reduceFunc) - op.updateAttribute("finalize_func", finalizeFunc) - op.updateAttribute("Tkey_func_other_arguments", keyFuncOtherArguments._typeList) - op.updateAttribute("Tinit_func_other_arguments", initFuncOtherArguments._typeList) - op.updateAttribute("Treduce_func_other_arguments", reduceFuncOtherArguments._typeList) - op.updateAttribute("Tfinalize_func_other_arguments", finalizeFuncOtherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInputList(keyFuncOtherArguments) - op.addInputList(initFuncOtherArguments) - op.addInputList(reduceFuncOtherArguments) - op.addInputList(finalizeFuncOtherArguments) - return op.execute(Int(1)) + let op = makeOp("ExperimentalGroupByReducerDataset", nOutputs) + op.updateAttribute("key_func", keyFunc) + op.updateAttribute("init_func", initFunc) + op.updateAttribute("reduce_func", reduceFunc) + op.updateAttribute("finalize_func", finalizeFunc) + op.updateAttribute("Tkey_func_other_arguments", keyFuncOtherArguments._typeList) + op.updateAttribute("Tinit_func_other_arguments", initFuncOtherArguments._typeList) + op.updateAttribute("Treduce_func_other_arguments", reduceFuncOtherArguments._typeList) + op.updateAttribute("Tfinalize_func_other_arguments", finalizeFuncOtherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(keyFuncOtherArguments) + op.addInputList(initFuncOtherArguments) + op.addInputList(reduceFuncOtherArguments) + op.addInputList(finalizeFuncOtherArguments) + return op.execute(Int(1)) } /// Creates a dataset that computes a windowed group-by on `input_dataset`. @@ -9492,7 +9492,7 @@ public static func experimentalGroupByReducerDataset< /// // TODO(mrry): Support non-int64 keys. /// /// - Attr key_func: A function mapping an element of `input_dataset`, concatenated -/// with `key_func_other_arguments` to a scalar value of type DT_INT64. +/// with `key_func_other_arguments` to a scalar value of type DT_INT64. @inlinable @inline(__always) public static func experimentalGroupByWindowDataset< KeyfuncIn: TensorGroup, @@ -9505,125 +9505,125 @@ public static func experimentalGroupByWindowDataset< TreduceFuncOtherArguments: TensorArrayProtocol, TwindowSizeFuncOtherArguments: TensorArrayProtocol >( - inputDataset: VariantHandle, - keyFuncOtherArguments: TkeyFuncOtherArguments, - reduceFuncOtherArguments: TreduceFuncOtherArguments, - windowSizeFuncOtherArguments: TwindowSizeFuncOtherArguments, - keyFunc: (KeyfuncIn) -> KeyfuncOut, - reduceFunc: (ReducefuncIn) -> ReducefuncOut, - windowSizeFunc: (WindowsizefuncIn) -> WindowsizefuncOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + keyFuncOtherArguments: TkeyFuncOtherArguments, + reduceFuncOtherArguments: TreduceFuncOtherArguments, + windowSizeFuncOtherArguments: TwindowSizeFuncOtherArguments, + keyFunc: (KeyfuncIn) -> KeyfuncOut, + reduceFunc: (ReducefuncIn) -> ReducefuncOut, + windowSizeFunc: (WindowsizefuncIn) -> WindowsizefuncOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalGroupByWindowDataset", nOutputs) - op.updateAttribute("key_func", keyFunc) - op.updateAttribute("reduce_func", reduceFunc) - op.updateAttribute("window_size_func", windowSizeFunc) - op.updateAttribute("Tkey_func_other_arguments", keyFuncOtherArguments._typeList) - op.updateAttribute("Treduce_func_other_arguments", reduceFuncOtherArguments._typeList) - op.updateAttribute("Twindow_size_func_other_arguments", windowSizeFuncOtherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInputList(keyFuncOtherArguments) - op.addInputList(reduceFuncOtherArguments) - op.addInputList(windowSizeFuncOtherArguments) - return op.execute(Int(1)) + let op = makeOp("ExperimentalGroupByWindowDataset", nOutputs) + op.updateAttribute("key_func", keyFunc) + op.updateAttribute("reduce_func", reduceFunc) + op.updateAttribute("window_size_func", windowSizeFunc) + op.updateAttribute("Tkey_func_other_arguments", keyFuncOtherArguments._typeList) + op.updateAttribute("Treduce_func_other_arguments", reduceFuncOtherArguments._typeList) + op.updateAttribute("Twindow_size_func_other_arguments", windowSizeFuncOtherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(keyFuncOtherArguments) + op.addInputList(reduceFuncOtherArguments) + op.addInputList(windowSizeFuncOtherArguments) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func experimentalIdentityIndexedDataset( - size: Tensor + size: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalIdentityIndexedDataset", nOutputs) - op.addInput(size) - return op.execute(Int(1)) + let op = makeOp("ExperimentalIdentityIndexedDataset", nOutputs) + op.addInput(size) + return op.execute(Int(1)) } /// Creates a dataset that contains the elements of `input_dataset` ignoring errors. @inlinable @inline(__always) public static func experimentalIgnoreErrorsDataset( - inputDataset: VariantHandle, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalIgnoreErrorsDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - return op.execute(Int(1)) + let op = makeOp("ExperimentalIgnoreErrorsDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func experimentalIndexedDatasetGet( - materialized: ResourceHandle, - index: Tensor, - outputShapes: [TensorShape?] + materialized: ResourceHandle, + index: Tensor, + outputShapes: [TensorShape?] ) -> OutputTypes { let nOutputs = Int(OutputTypes._typeList.count) - let op = makeOp("ExperimentalIndexedDatasetGet", nOutputs) - op.updateAttribute("output_types", OutputTypes._typeList) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(materialized) - op.addInput(index) - return op.execute(Int(OutputTypes._typeList.count)) + let op = makeOp("ExperimentalIndexedDatasetGet", nOutputs) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(materialized) + op.addInput(index) + return op.execute(Int(OutputTypes._typeList.count)) } @inlinable @inline(__always) public static func experimentalIndexedDatasetMaterialize( - dataset: VariantHandle, - materialized: ResourceHandle + dataset: VariantHandle, + materialized: ResourceHandle ) { let nOutputs = 0 - let op = makeOp("ExperimentalIndexedDatasetMaterialize", nOutputs) - op.addInput(dataset) - op.addInput(materialized) - op.execute() + let op = makeOp("ExperimentalIndexedDatasetMaterialize", nOutputs) + op.addInput(dataset) + op.addInput(materialized) + op.execute() } /// Returns the name of the device on which `resource` has been placed. @inlinable @inline(__always) public static func experimentalIteratorGetDevice( - resource: ResourceHandle + resource: ResourceHandle ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("ExperimentalIteratorGetDevice", nOutputs) - op.addInput(resource) - return op.execute(Int(1)) + let op = makeOp("ExperimentalIteratorGetDevice", nOutputs) + op.addInput(resource) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func experimentalLMDBDataset( - filenames: StringTensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + filenames: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalLMDBDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(filenames) - return op.execute(Int(1)) + let op = makeOp("ExperimentalLMDBDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(filenames) + return op.execute(Int(1)) } /// Records the latency of producing `input_dataset` elements in a StatsAggregator. @inlinable @inline(__always) public static func experimentalLatencyStatsDataset( - inputDataset: VariantHandle, - tag: StringTensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + tag: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalLatencyStatsDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(tag) - return op.execute(Int(1)) + let op = makeOp("ExperimentalLatencyStatsDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(tag) + return op.execute(Int(1)) } /// Creates a dataset that fuses mapping with batching. @@ -9635,17 +9635,17 @@ public static func experimentalLatencyStatsDataset( /// to `batch_size * num_parallel_batches` copies of `f` in parallel. /// /// - Parameters: -/// - input_dataset: A variant tensor representing the input dataset. -/// - other_arguments: A list of tensors, typically values that were captured when building a closure -/// for `f`. -/// - batch_size: A scalar representing the number of elements to accumulate in a -/// batch. It determines the number of concurrent invocations of `f` that process -/// elements from `input_dataset` in parallel. -/// - num_parallel_calls: A scalar representing the maximum number of parallel invocations of the `map_fn` -/// function. Applying the `map_fn` on consecutive input elements in parallel has -/// the potential to improve input pipeline throughput. -/// - drop_remainder: A scalar representing whether the last batch should be dropped in case its size -/// is smaller than desired. +/// - input_dataset: A variant tensor representing the input dataset. +/// - other_arguments: A list of tensors, typically values that were captured when building a closure +/// for `f`. +/// - batch_size: A scalar representing the number of elements to accumulate in a +/// batch. It determines the number of concurrent invocations of `f` that process +/// elements from `input_dataset` in parallel. +/// - num_parallel_calls: A scalar representing the maximum number of parallel invocations of the `map_fn` +/// function. Applying the `map_fn` on consecutive input elements in parallel has +/// the potential to improve input pipeline throughput. +/// - drop_remainder: A scalar representing whether the last batch should be dropped in case its size +/// is smaller than desired. /// /// - Attr f: A function to apply to the outputs of `input_dataset`. @inlinable @inline(__always) @@ -9654,29 +9654,29 @@ public static func experimentalMapAndBatchDataset< FOut: TensorGroup, Targuments: TensorArrayProtocol >( - inputDataset: VariantHandle, - otherArguments: Targuments, - batchSize: Tensor, - numParallelCalls: Tensor, - dropRemainder: Tensor, - f: (FIn) -> FOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?], - preserveCardinality: Bool = false + inputDataset: VariantHandle, + otherArguments: Targuments, + batchSize: Tensor, + numParallelCalls: Tensor, + dropRemainder: Tensor, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + preserveCardinality: Bool = false ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalMapAndBatchDataset", nOutputs) - op.updateAttribute("f", f) - op.updateAttribute("Targuments", otherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("preserve_cardinality", preserveCardinality) - op.addInput(inputDataset) - op.addInputList(otherArguments) - op.addInput(batchSize) - op.addInput(numParallelCalls) - op.addInput(dropRemainder) - return op.execute(Int(1)) + let op = makeOp("ExperimentalMapAndBatchDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("preserve_cardinality", preserveCardinality) + op.addInput(inputDataset) + op.addInputList(otherArguments) + op.addInput(batchSize) + op.addInput(numParallelCalls) + op.addInput(dropRemainder) + return op.execute(Int(1)) } /// Creates a dataset that applies `f` to the outputs of `input_dataset`. @@ -9686,51 +9686,51 @@ public static func experimentalMapDataset< FOut: TensorGroup, Targuments: TensorArrayProtocol >( - inputDataset: VariantHandle, - otherArguments: Targuments, - f: (FIn) -> FOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?], - useInterOpParallelism: Bool = true, - preserveCardinality: Bool = false + inputDataset: VariantHandle, + otherArguments: Targuments, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + useInterOpParallelism: Bool = true, + preserveCardinality: Bool = false ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalMapDataset", nOutputs) - op.updateAttribute("f", f) - op.updateAttribute("Targuments", otherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("use_inter_op_parallelism", useInterOpParallelism) - op.updateAttribute("preserve_cardinality", preserveCardinality) - op.addInput(inputDataset) - op.addInputList(otherArguments) - return op.execute(Int(1)) + let op = makeOp("ExperimentalMapDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("use_inter_op_parallelism", useInterOpParallelism) + op.updateAttribute("preserve_cardinality", preserveCardinality) + op.addInput(inputDataset) + op.addInputList(otherArguments) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func experimentalMatchingFilesDataset( - patterns: StringTensor + patterns: StringTensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalMatchingFilesDataset", nOutputs) - op.addInput(patterns) - return op.execute(Int(1)) + let op = makeOp("ExperimentalMatchingFilesDataset", nOutputs) + op.addInput(patterns) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func experimentalMaterializedIndexDatasetHandle( - container: String, - sharedName: String, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + container: String, + sharedName: String, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalMaterializedIndexDatasetHandle", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - return op.execute(Int(1)) + let op = makeOp("ExperimentalMaterializedIndexDatasetHandle", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + return op.execute(Int(1)) } /// Creates a dataset that overrides the maximum intra-op parallelism. @@ -9738,32 +9738,32 @@ public static func experimentalMaterializedIndexDatasetHandle( /// - Parameter max_intra_op_parallelism: Identifies the maximum intra-op parallelism to use. @inlinable @inline(__always) public static func experimentalMaxIntraOpParallelismDataset( - inputDataset: VariantHandle, - maxIntraOpParallelism: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + maxIntraOpParallelism: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalMaxIntraOpParallelismDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(maxIntraOpParallelism) - return op.execute(Int(1)) + let op = makeOp("ExperimentalMaxIntraOpParallelismDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(maxIntraOpParallelism) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func experimentalNonSerializableDataset( - inputDataset: VariantHandle, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalNonSerializableDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - return op.execute(Int(1)) + let op = makeOp("ExperimentalNonSerializableDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + return op.execute(Int(1)) } /// Creates a dataset that fuses mapping with batching. @@ -9779,17 +9779,17 @@ public static func experimentalNonSerializableDataset( /// function-based control flow ops. /// /// - Parameters: -/// - input_dataset: A variant tensor representing the input dataset. -/// - other_arguments: A list of tensors, typically values that were captured when building a closure -/// for `f`. -/// - batch_size: A scalar representing the number of elements to accumulate in a -/// batch. It determines the number of concurrent invocations of `f` that process -/// elements from `input_dataset` in parallel. -/// - num_parallel_calls: A scalar representing the maximum number of parallel invocations of the `map_fn` -/// function. Applying the `map_fn` on consecutive input elements in parallel has -/// the potential to improve input pipeline throughput. -/// - drop_remainder: A scalar representing whether the last batch should be dropped in case its size -/// is smaller than desired. +/// - input_dataset: A variant tensor representing the input dataset. +/// - other_arguments: A list of tensors, typically values that were captured when building a closure +/// for `f`. +/// - batch_size: A scalar representing the number of elements to accumulate in a +/// batch. It determines the number of concurrent invocations of `f` that process +/// elements from `input_dataset` in parallel. +/// - num_parallel_calls: A scalar representing the maximum number of parallel invocations of the `map_fn` +/// function. Applying the `map_fn` on consecutive input elements in parallel has +/// the potential to improve input pipeline throughput. +/// - drop_remainder: A scalar representing whether the last batch should be dropped in case its size +/// is smaller than desired. /// /// - Attr f: A function to apply to the outputs of `input_dataset`. @inlinable @inline(__always) @@ -9798,29 +9798,29 @@ public static func experimentalNumaMapAndBatchDataset< FOut: TensorGroup, Targuments: TensorArrayProtocol >( - inputDataset: VariantHandle, - otherArguments: Targuments, - batchSize: Tensor, - numParallelCalls: Tensor, - dropRemainder: Tensor, - f: (FIn) -> FOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?], - preserveCardinality: Bool = false + inputDataset: VariantHandle, + otherArguments: Targuments, + batchSize: Tensor, + numParallelCalls: Tensor, + dropRemainder: Tensor, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + preserveCardinality: Bool = false ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalNumaMapAndBatchDataset", nOutputs) - op.updateAttribute("f", f) - op.updateAttribute("Targuments", otherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("preserve_cardinality", preserveCardinality) - op.addInput(inputDataset) - op.addInputList(otherArguments) - op.addInput(batchSize) - op.addInput(numParallelCalls) - op.addInput(dropRemainder) - return op.execute(Int(1)) + let op = makeOp("ExperimentalNumaMapAndBatchDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("preserve_cardinality", preserveCardinality) + op.addInput(inputDataset) + op.addInputList(otherArguments) + op.addInput(batchSize) + op.addInput(numParallelCalls) + op.addInput(dropRemainder) + return op.execute(Int(1)) } /// Creates a dataset that applies `f` to the outputs of `input_dataset`. @@ -9834,96 +9834,96 @@ public static func experimentalNumaMapAndBatchDataset< /// !! WARNING !! This dataset is not deterministic! /// /// - Attr f: A function mapping elements of `input_dataset`, concatenated with -/// `other_arguments`, to a Dataset variant that contains elements matching -/// `output_types` and `output_shapes`. +/// `other_arguments`, to a Dataset variant that contains elements matching +/// `output_types` and `output_shapes`. @inlinable @inline(__always) public static func experimentalParallelInterleaveDataset< FIn: TensorGroup, FOut: TensorGroup, Targuments: TensorArrayProtocol >( - inputDataset: VariantHandle, - otherArguments: Targuments, - cycleLength: Tensor, - blockLength: Tensor, - sloppy: Tensor, - bufferOutputElements: Tensor, - prefetchInputElements: Tensor, - f: (FIn) -> FOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + otherArguments: Targuments, + cycleLength: Tensor, + blockLength: Tensor, + sloppy: Tensor, + bufferOutputElements: Tensor, + prefetchInputElements: Tensor, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalParallelInterleaveDataset", nOutputs) - op.updateAttribute("f", f) - op.updateAttribute("Targuments", otherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInputList(otherArguments) - op.addInput(cycleLength) - op.addInput(blockLength) - op.addInput(sloppy) - op.addInput(bufferOutputElements) - op.addInput(prefetchInputElements) - return op.execute(Int(1)) + let op = makeOp("ExperimentalParallelInterleaveDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(otherArguments) + op.addInput(cycleLength) + op.addInput(blockLength) + op.addInput(sloppy) + op.addInput(bufferOutputElements) + op.addInput(prefetchInputElements) + return op.execute(Int(1)) } /// Transforms `input_dataset` containing `Example` protos as vectors of DT_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features. /// /// - Parameter dense_defaults: A dict mapping string keys to `Tensor`s. -/// The keys of the dict must match the dense_keys of the feature. +/// The keys of the dict must match the dense_keys of the feature. /// /// - Attrs: -/// - sparse_keys: A list of string keys in the examples features. -/// The results for these keys will be returned as `SparseTensor` objects. -/// - dense_keys: A list of Ndense string Tensors (scalars). -/// The keys expected in the Examples features associated with dense values. -/// - sparse_types: A list of `DTypes` of the same length as `sparse_keys`. -/// Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`), -/// and `tf.string` (`BytesList`) are supported. -/// - Tdense: A list of DTypes of the same length as `dense_keys`. -/// Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`), -/// and `tf.string` (`BytesList`) are supported. -/// -/// - dense_shapes: List of tuples with the same length as `dense_keys`. -/// The shape of the data for each dense feature referenced by `dense_keys`. -/// Required for any input tensors identified by `dense_keys`. Must be -/// either fully defined, or may contain an unknown first dimension. -/// An unknown first dimension means the feature is treated as having -/// a variable number of blocks, and the output shape along this dimension -/// is considered unknown at graph build time. Padding is applied for -/// minibatch elements smaller than the maximum number of blocks for the -/// given feature along this dimension. -/// - output_types: The type list for the return values. -/// - output_shapes: The list of shapes being produced. +/// - sparse_keys: A list of string keys in the examples features. +/// The results for these keys will be returned as `SparseTensor` objects. +/// - dense_keys: A list of Ndense string Tensors (scalars). +/// The keys expected in the Examples features associated with dense values. +/// - sparse_types: A list of `DTypes` of the same length as `sparse_keys`. +/// Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`), +/// and `tf.string` (`BytesList`) are supported. +/// - Tdense: A list of DTypes of the same length as `dense_keys`. +/// Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`), +/// and `tf.string` (`BytesList`) are supported. +/// +/// - dense_shapes: List of tuples with the same length as `dense_keys`. +/// The shape of the data for each dense feature referenced by `dense_keys`. +/// Required for any input tensors identified by `dense_keys`. Must be +/// either fully defined, or may contain an unknown first dimension. +/// An unknown first dimension means the feature is treated as having +/// a variable number of blocks, and the output shape along this dimension +/// is considered unknown at graph build time. Padding is applied for +/// minibatch elements smaller than the maximum number of blocks for the +/// given feature along this dimension. +/// - output_types: The type list for the return values. +/// - output_shapes: The list of shapes being produced. @inlinable @inline(__always) public static func experimentalParseExampleDataset( - inputDataset: VariantHandle, - numParallelCalls: Tensor, - denseDefaults: Tdense, - sparseKeys: [String], - denseKeys: [String], - sparseTypes: [TensorDataType], - denseShapes: [TensorShape?], - outputTypes: [TensorDataType], - outputShapes: [TensorShape?], - sloppy: Bool = false + inputDataset: VariantHandle, + numParallelCalls: Tensor, + denseDefaults: Tdense, + sparseKeys: [String], + denseKeys: [String], + sparseTypes: [TensorDataType], + denseShapes: [TensorShape?], + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + sloppy: Bool = false ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalParseExampleDataset", nOutputs) - op.updateAttribute("sparse_keys", sparseKeys) - op.updateAttribute("dense_keys", denseKeys) - op.updateAttribute("sparse_types", sparseTypes) - op.updateAttribute("Tdense", denseDefaults._typeList) - op.updateAttribute("dense_shapes", denseShapes) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("sloppy", sloppy) - op.addInput(inputDataset) - op.addInput(numParallelCalls) - op.addInputList(denseDefaults) - return op.execute(Int(1)) + let op = makeOp("ExperimentalParseExampleDataset", nOutputs) + op.updateAttribute("sparse_keys", sparseKeys) + op.updateAttribute("dense_keys", denseKeys) + op.updateAttribute("sparse_types", sparseTypes) + op.updateAttribute("Tdense", denseDefaults._typeList) + op.updateAttribute("dense_shapes", denseShapes) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("sloppy", sloppy) + op.addInput(inputDataset) + op.addInput(numParallelCalls) + op.addInputList(denseDefaults) + return op.execute(Int(1)) } /// Creates a dataset that uses a custom thread pool to compute `input_dataset`. @@ -9931,41 +9931,41 @@ public static func experimentalParseExampleDataset( /// - Parameter num_threads: Identifies the number of threads to use for the private threadpool. @inlinable @inline(__always) public static func experimentalPrivateThreadPoolDataset( - inputDataset: VariantHandle, - numThreads: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + numThreads: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalPrivateThreadPoolDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(numThreads) - return op.execute(Int(1)) + let op = makeOp("ExperimentalPrivateThreadPoolDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(numThreads) + return op.execute(Int(1)) } /// Creates a Dataset that returns pseudorandom numbers. /// /// - Parameters: -/// - seed: A scalar seed for the random number generator. If either seed or -/// seed2 is set to be non-zero, the random number generator is seeded -/// by the given seed. Otherwise, a random seed is used. -/// - seed2: A second scalar seed to avoid seed collision. +/// - seed: A scalar seed for the random number generator. If either seed or +/// seed2 is set to be non-zero, the random number generator is seeded +/// by the given seed. Otherwise, a random seed is used. +/// - seed2: A second scalar seed to avoid seed collision. @inlinable @inline(__always) public static func experimentalRandomDataset( - seed: Tensor, - seed2: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + seed: Tensor, + seed2: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalRandomDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(seed) - op.addInput(seed2) - return op.execute(Int(1)) + let op = makeOp("ExperimentalRandomDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(seed) + op.addInput(seed2) + return op.execute(Int(1)) } /// Creates a dataset that changes the batch size. @@ -9974,24 +9974,24 @@ public static func experimentalRandomDataset( /// size // num_workers. /// /// - Parameters: -/// - input_dataset: A variant tensor representing the input dataset. -/// - num_workers: A scalar representing the number of workers to distribute this batch across. As -/// a result of this transformation the current batch size would end up being -/// divided by this parameter. +/// - input_dataset: A variant tensor representing the input dataset. +/// - num_workers: A scalar representing the number of workers to distribute this batch across. As +/// a result of this transformation the current batch size would end up being +/// divided by this parameter. @inlinable @inline(__always) public static func experimentalRebatchDataset( - inputDataset: VariantHandle, - numWorkers: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + numWorkers: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalRebatchDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(numWorkers) - return op.execute(Int(1)) + let op = makeOp("ExperimentalRebatchDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(numWorkers) + return op.execute(Int(1)) } /// Creates a dataset successively reduces `f` over the elements of `input_dataset`. @@ -10002,139 +10002,139 @@ public static func experimentalScanDataset< Tstate: TensorArrayProtocol, Targuments: TensorArrayProtocol >( - inputDataset: VariantHandle, - initialState: Tstate, - otherArguments: Targuments, - f: (FIn) -> FOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?], - preserveCardinality: Bool = false + inputDataset: VariantHandle, + initialState: Tstate, + otherArguments: Targuments, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + preserveCardinality: Bool = false ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalScanDataset", nOutputs) - op.updateAttribute("f", f) - op.updateAttribute("Tstate", initialState._typeList) - op.updateAttribute("Targuments", otherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("preserve_cardinality", preserveCardinality) - op.addInput(inputDataset) - op.addInputList(initialState) - op.addInputList(otherArguments) - return op.execute(Int(1)) + let op = makeOp("ExperimentalScanDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Tstate", initialState._typeList) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("preserve_cardinality", preserveCardinality) + op.addInput(inputDataset) + op.addInputList(initialState) + op.addInputList(otherArguments) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func experimentalSetStatsAggregatorDataset( - inputDataset: VariantHandle, - statsAggregator: ResourceHandle, - tag: StringTensor, - counterPrefix: StringTensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + statsAggregator: ResourceHandle, + tag: StringTensor, + counterPrefix: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalSetStatsAggregatorDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(statsAggregator) - op.addInput(tag) - op.addInput(counterPrefix) - return op.execute(Int(1)) + let op = makeOp("ExperimentalSetStatsAggregatorDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(statsAggregator) + op.addInput(tag) + op.addInput(counterPrefix) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func experimentalSleepDataset( - inputDataset: VariantHandle, - sleepMicroseconds: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + sleepMicroseconds: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalSleepDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(sleepMicroseconds) - return op.execute(Int(1)) + let op = makeOp("ExperimentalSleepDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(sleepMicroseconds) + return op.execute(Int(1)) } /// Creates a dataset that passes a sliding window over `input_dataset`. /// /// - Parameters: -/// - window_size: A scalar representing the number of elements in the -/// sliding window. -/// - window_shift: A scalar representing the steps moving the sliding window -/// forward in one iteration. It must be positive. -/// - window_stride: A scalar representing the stride of the input elements of the sliding window. -/// It must be positive. +/// - window_size: A scalar representing the number of elements in the +/// sliding window. +/// - window_shift: A scalar representing the steps moving the sliding window +/// forward in one iteration. It must be positive. +/// - window_stride: A scalar representing the stride of the input elements of the sliding window. +/// It must be positive. @inlinable @inline(__always) public static func experimentalSlidingWindowDataset( - inputDataset: VariantHandle, - windowSize: Tensor, - windowShift: Tensor, - windowStride: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + windowSize: Tensor, + windowShift: Tensor, + windowStride: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalSlidingWindowDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(windowSize) - op.addInput(windowShift) - op.addInput(windowStride) - return op.execute(Int(1)) + let op = makeOp("ExperimentalSlidingWindowDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(windowSize) + op.addInput(windowShift) + op.addInput(windowStride) + return op.execute(Int(1)) } /// Creates a dataset that executes a SQL query and emits rows of the result set. /// /// - Parameters: -/// - driver_name: The database type. Currently, the only supported type is 'sqlite'. -/// - data_source_name: A connection string to connect to the database. -/// - query: A SQL query to execute. +/// - driver_name: The database type. Currently, the only supported type is 'sqlite'. +/// - data_source_name: A connection string to connect to the database. +/// - query: A SQL query to execute. @inlinable @inline(__always) public static func experimentalSqlDataset( - driverName: StringTensor, - dataSourceName: StringTensor, - query: StringTensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + driverName: StringTensor, + dataSourceName: StringTensor, + query: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalSqlDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(driverName) - op.addInput(dataSourceName) - op.addInput(query) - return op.execute(Int(1)) + let op = makeOp("ExperimentalSqlDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(driverName) + op.addInput(dataSourceName) + op.addInput(query) + return op.execute(Int(1)) } /// Creates a statistics manager resource. @inlinable @inline(__always) public static func experimentalStatsAggregatorHandle( - container: String, - sharedName: String + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalStatsAggregatorHandle", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("ExperimentalStatsAggregatorHandle", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Produces a summary of any statistics recorded by the given statistics manager. @inlinable @inline(__always) public static func experimentalStatsAggregatorSummary( - iterator: ResourceHandle + iterator: ResourceHandle ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("ExperimentalStatsAggregatorSummary", nOutputs) - op.addInput(iterator) - return op.execute(Int(1)) + let op = makeOp("ExperimentalStatsAggregatorSummary", nOutputs) + op.addInput(iterator) + return op.execute(Int(1)) } /// Creates a dataset that stops iteration when predicate` is false. @@ -10146,7 +10146,7 @@ public static func experimentalStatsAggregatorSummary( /// * One tensor for each value in `other_arguments`. /// /// - Parameter other_arguments: A list of tensors, typically values that were captured when -/// building a closure for `predicate`. +/// building a closure for `predicate`. /// /// - Attr predicate: A function returning a scalar boolean. @inlinable @inline(__always) @@ -10155,21 +10155,21 @@ public static func experimentalTakeWhileDataset< PredicateOut: TensorGroup, Targuments: TensorArrayProtocol >( - inputDataset: VariantHandle, - otherArguments: Targuments, - predicate: (PredicateIn) -> PredicateOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + otherArguments: Targuments, + predicate: (PredicateIn) -> PredicateOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalTakeWhileDataset", nOutputs) - op.updateAttribute("predicate", predicate) - op.updateAttribute("Targuments", otherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInputList(otherArguments) - return op.execute(Int(1)) + let op = makeOp("ExperimentalTakeWhileDataset", nOutputs) + op.updateAttribute("predicate", predicate) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(otherArguments) + return op.execute(Int(1)) } /// Creates a dataset that uses a custom thread pool to compute `input_dataset`. @@ -10177,78 +10177,78 @@ public static func experimentalTakeWhileDataset< /// - Parameter thread_pool: A resource produced by the ThreadPoolHandle op. @inlinable @inline(__always) public static func experimentalThreadPoolDataset( - inputDataset: VariantHandle, - threadPool: ResourceHandle, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + threadPool: ResourceHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalThreadPoolDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(threadPool) - return op.execute(Int(1)) + let op = makeOp("ExperimentalThreadPoolDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(threadPool) + return op.execute(Int(1)) } /// Creates a dataset that uses a custom thread pool to compute `input_dataset`. /// /// - Attrs: -/// - num_threads: The number of threads in the thread pool. -/// - max_intra_op_parallelism: The maximum degree of parallelism to use within operations that execute on this -/// threadpool. -/// - display_name: A human-readable name for the threads that may be visible in some -/// visualizations. -/// threadpool. +/// - num_threads: The number of threads in the thread pool. +/// - max_intra_op_parallelism: The maximum degree of parallelism to use within operations that execute on this +/// threadpool. +/// - display_name: A human-readable name for the threads that may be visible in some +/// visualizations. +/// threadpool. /// /// - Output handle: A resource that can be consumed by one or more ExperimentalThreadPoolDataset -/// ops. +/// ops. @inlinable @inline(__always) public static func experimentalThreadPoolHandle( - numThreads: Int64, - maxIntraOpParallelism: Int64 = 1, - displayName: String, - container: String, - sharedName: String + numThreads: Int64, + maxIntraOpParallelism: Int64 = 1, + displayName: String, + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalThreadPoolHandle", nOutputs) - op.updateAttribute("num_threads", numThreads) - op.updateAttribute("max_intra_op_parallelism", maxIntraOpParallelism) - op.updateAttribute("display_name", displayName) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("ExperimentalThreadPoolHandle", nOutputs) + op.updateAttribute("num_threads", numThreads) + op.updateAttribute("max_intra_op_parallelism", maxIntraOpParallelism) + op.updateAttribute("display_name", displayName) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// A dataset that splits the elements of its input into multiple elements. @inlinable @inline(__always) public static func experimentalUnbatchDataset( - inputDataset: VariantHandle, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalUnbatchDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - return op.execute(Int(1)) + let op = makeOp("ExperimentalUnbatchDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + return op.execute(Int(1)) } /// Creates a dataset that contains the unique elements of `input_dataset`. @inlinable @inline(__always) public static func experimentalUniqueDataset( - inputDataset: VariantHandle, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ExperimentalUniqueDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - return op.execute(Int(1)) + let op = makeOp("ExperimentalUniqueDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + return op.execute(Int(1)) } /// Computes exponential of x - 1 element-wise. @@ -10256,13 +10256,13 @@ public static func experimentalUniqueDataset( /// I.e., \\(y = (\exp x) - 1\\). @inlinable @inline(__always) public static func expm1( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Expm1", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Expm1", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Extracts a glimpse from the input tensor. @@ -10290,47 +10290,47 @@ public static func expm1( /// numbers of pixels. /// /// - Parameters: -/// - input: A 4-D float tensor of shape `[batch_size, height, width, channels]`. -/// - size: A 1-D tensor of 2 elements containing the size of the glimpses -/// to extract. The glimpse height must be specified first, following -/// by the glimpse width. -/// - offsets: A 2-D integer tensor of shape `[batch_size, 2]` containing -/// the y, x locations of the center of each window. +/// - input: A 4-D float tensor of shape `[batch_size, height, width, channels]`. +/// - size: A 1-D tensor of 2 elements containing the size of the glimpses +/// to extract. The glimpse height must be specified first, following +/// by the glimpse width. +/// - offsets: A 2-D integer tensor of shape `[batch_size, 2]` containing +/// the y, x locations of the center of each window. /// /// - Attrs: -/// - centered: indicates if the offset coordinates are centered relative to -/// the image, in which case the (0, 0) offset is relative to the center -/// of the input images. If false, the (0,0) offset corresponds to the -/// upper left corner of the input images. -/// - normalized: indicates if the offset coordinates are normalized. -/// - uniform_noise: indicates if the noise should be generated using a -/// uniform distribution or a Gaussian distribution. -/// - noise: indicates if the noise should `uniform`, `gaussian`, or -/// `zero`. The default is `uniform` which means the the noise type -/// will be decided by `uniform_noise`. +/// - centered: indicates if the offset coordinates are centered relative to +/// the image, in which case the (0, 0) offset is relative to the center +/// of the input images. If false, the (0,0) offset corresponds to the +/// upper left corner of the input images. +/// - normalized: indicates if the offset coordinates are normalized. +/// - uniform_noise: indicates if the noise should be generated using a +/// uniform distribution or a Gaussian distribution. +/// - noise: indicates if the noise should `uniform`, `gaussian`, or +/// `zero`. The default is `uniform` which means the the noise type +/// will be decided by `uniform_noise`. /// /// - Output glimpse: A tensor representing the glimpses `[batch_size, -/// glimpse_height, glimpse_width, channels]`. +/// glimpse_height, glimpse_width, channels]`. @inlinable @inline(__always) public static func extractGlimpse( - _ input: Tensor, - size: Tensor, - offsets: Tensor, - centered: Bool = true, - normalized: Bool = true, - uniformNoise: Bool = true, - noise: String = "uniform" + _ input: Tensor, + size: Tensor, + offsets: Tensor, + centered: Bool = true, + normalized: Bool = true, + uniformNoise: Bool = true, + noise: String = "uniform" ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ExtractGlimpse", nOutputs) - op.updateAttribute("centered", centered) - op.updateAttribute("normalized", normalized) - op.updateAttribute("uniform_noise", uniformNoise) - op.updateAttribute("noise", noise) - op.addInput(input) - op.addInput(size) - op.addInput(offsets) - return op.execute(Int(1)) + let op = makeOp("ExtractGlimpse", nOutputs) + op.updateAttribute("centered", centered) + op.updateAttribute("normalized", normalized) + op.updateAttribute("uniform_noise", uniformNoise) + op.updateAttribute("noise", noise) + op.addInput(input) + op.addInput(size) + op.addInput(offsets) + return op.execute(Int(1)) } /// Extract `patches` from `images` and put them in the "depth" output dimension. @@ -10338,46 +10338,46 @@ public static func extractGlimpse( /// - Parameter images: 4-D Tensor with shape `[batch, in_rows, in_cols, depth]`. /// /// - Attrs: -/// - ksizes: The size of the sliding window for each dimension of `images`. -/// - strides: 1-D of length 4. How far the centers of two consecutive patches are in -/// the images. Must be: `[1, stride_rows, stride_cols, 1]`. -/// - rates: 1-D of length 4. Must be: `[1, rate_rows, rate_cols, 1]`. This is the -/// input stride, specifying how far two consecutive patch samples are in the -/// input. Equivalent to extracting patches with -/// `patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1)`, followed by -/// subsampling them spatially by a factor of `rates`. This is equivalent to -/// `rate` in dilated (a.k.a. Atrous) convolutions. -/// - padding: The type of padding algorithm to use. -/// -/// We specify the size-related attributes as: -/// -/// ```python -/// ksizes = [1, ksize_rows, ksize_cols, 1] -/// strides = [1, strides_rows, strides_cols, 1] -/// rates = [1, rates_rows, rates_cols, 1] -/// ``` +/// - ksizes: The size of the sliding window for each dimension of `images`. +/// - strides: 1-D of length 4. How far the centers of two consecutive patches are in +/// the images. Must be: `[1, stride_rows, stride_cols, 1]`. +/// - rates: 1-D of length 4. Must be: `[1, rate_rows, rate_cols, 1]`. This is the +/// input stride, specifying how far two consecutive patch samples are in the +/// input. Equivalent to extracting patches with +/// `patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1)`, followed by +/// subsampling them spatially by a factor of `rates`. This is equivalent to +/// `rate` in dilated (a.k.a. Atrous) convolutions. +/// - padding: The type of padding algorithm to use. +/// +/// We specify the size-related attributes as: +/// +/// ```python +/// ksizes = [1, ksize_rows, ksize_cols, 1] +/// strides = [1, strides_rows, strides_cols, 1] +/// rates = [1, rates_rows, rates_cols, 1] +/// ``` /// /// - Output patches: 4-D Tensor with shape `[batch, out_rows, out_cols, ksize_rows * -/// ksize_cols * depth]` containing image patches with size -/// `ksize_rows x ksize_cols x depth` vectorized in the "depth" dimension. Note -/// `out_rows` and `out_cols` are the dimensions of the output patches. +/// ksize_cols * depth]` containing image patches with size +/// `ksize_rows x ksize_cols x depth` vectorized in the "depth" dimension. Note +/// `out_rows` and `out_cols` are the dimensions of the output patches. @inlinable @inline(__always) public static func extractImagePatches( - images: Tensor, - ksizes: [Int32], - strides: [Int32], - rates: [Int32], - padding: Padding + images: Tensor, + ksizes: [Int32], + strides: [Int32], + rates: [Int32], + padding: Padding ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ExtractImagePatches", nOutputs) - op.updateAttribute("ksizes", ksizes) - op.updateAttribute("strides", strides) - op.updateAttribute("rates", rates) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("padding", padding.cName) - op.addInput(images) - return op.execute(Int(1)) + let op = makeOp("ExtractImagePatches", nOutputs) + op.updateAttribute("ksizes", ksizes) + op.updateAttribute("strides", strides) + op.updateAttribute("rates", rates) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("padding", padding.cName) + op.addInput(images) + return op.execute(Int(1)) } /// Extract the shape information of a JPEG-encoded image. @@ -10387,18 +10387,18 @@ public static func extractImagePatches( /// - Parameter contents: 0-D. The JPEG-encoded image. /// /// - Attr output_type: (Optional) The output type of the operation (int32 or int64). -/// Defaults to int32. +/// Defaults to int32. /// /// - Output image_shape: 1-D. The image shape with format [height, width, channels]. @inlinable @inline(__always) public static func extractJpegShape( - contents: StringTensor + contents: StringTensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ExtractJpegShape", nOutputs) - op.updateAttribute("output_type", OutputType.tensorFlowDataType) - op.addInput(contents) - return op.execute(Int(1)) + let op = makeOp("ExtractJpegShape", nOutputs) + op.updateAttribute("output_type", OutputType.tensorFlowDataType) + op.addInput(contents) + return op.execute(Int(1)) } /// Extract `patches` from `input` and put them in the "depth" output dimension. 3D extension of `extract_image_patches`. @@ -10406,38 +10406,38 @@ public static func extractJpegShape( - _ input: Tensor, - ksizes: [Int32], - strides: [Int32], - padding: Padding + _ input: Tensor, + ksizes: [Int32], + strides: [Int32], + padding: Padding ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ExtractVolumePatches", nOutputs) - op.updateAttribute("ksizes", ksizes) - op.updateAttribute("strides", strides) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("padding", padding.cName) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("ExtractVolumePatches", nOutputs) + op.updateAttribute("ksizes", ksizes) + op.updateAttribute("strides", strides) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + return op.execute(Int(1)) } /// Fast Fourier transform. @@ -10448,20 +10448,20 @@ public static func extractVolumePatches( /// - Parameter input: A complex tensor. /// /// - Output output: A complex tensor of the same shape as `input`. The inner-most -/// dimension of `input` is replaced with its 1D Fourier transform. +/// dimension of `input` is replaced with its 1D Fourier transform. /// -/// @compatibility(numpy) -/// Equivalent to np.fft.fft -/// @end_compatibility +/// @compatibility(numpy) +/// Equivalent to np.fft.fft +/// @end_compatibility @inlinable @inline(__always) public static func fFT( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FFT", nOutputs) - op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("FFT", nOutputs) + op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// 2D fast Fourier transform. @@ -10472,20 +10472,20 @@ public static func fFT( /// - Parameter input: A complex tensor. /// /// - Output output: A complex tensor of the same shape as `input`. The inner-most 2 -/// dimensions of `input` are replaced with their 2D Fourier transform. +/// dimensions of `input` are replaced with their 2D Fourier transform. /// -/// @compatibility(numpy) -/// Equivalent to np.fft.fft2 -/// @end_compatibility +/// @compatibility(numpy) +/// Equivalent to np.fft.fft2 +/// @end_compatibility @inlinable @inline(__always) public static func fFT2D( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FFT2D", nOutputs) - op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("FFT2D", nOutputs) + op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// 3D fast Fourier transform. @@ -10496,54 +10496,54 @@ public static func fFT2D( /// - Parameter input: A complex64 tensor. /// /// - Output output: A complex64 tensor of the same shape as `input`. The inner-most 3 -/// dimensions of `input` are replaced with their 3D Fourier transform. +/// dimensions of `input` are replaced with their 3D Fourier transform. /// -/// @compatibility(numpy) -/// Equivalent to np.fft.fftn with 3 dimensions. -/// @end_compatibility +/// @compatibility(numpy) +/// Equivalent to np.fft.fftn with 3 dimensions. +/// @end_compatibility @inlinable @inline(__always) public static func fFT3D( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FFT3D", nOutputs) - op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("FFT3D", nOutputs) + op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// A queue that produces elements in first-in first-out order. /// /// - Attrs: -/// - component_types: The type of each component in a value. -/// - shapes: The shape of each component in a value. The length of this attr must -/// be either 0 or the same as the length of component_types. If the length of -/// this attr is 0, the shapes of queue elements are not constrained, and -/// only one element may be dequeued at a time. -/// - capacity: The upper bound on the number of elements in this queue. -/// Negative numbers mean no limit. -/// - container: If non-empty, this queue is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this queue will be shared under the given name -/// across multiple sessions. +/// - component_types: The type of each component in a value. +/// - shapes: The shape of each component in a value. The length of this attr must +/// be either 0 or the same as the length of component_types. If the length of +/// this attr is 0, the shapes of queue elements are not constrained, and +/// only one element may be dequeued at a time. +/// - capacity: The upper bound on the number of elements in this queue. +/// Negative numbers mean no limit. +/// - container: If non-empty, this queue is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this queue will be shared under the given name +/// across multiple sessions. /// /// - Output handle: The handle to the queue. @inlinable @inline(__always) public static func fIFOQueueV2( - componentTypes: [TensorDataType], - shapes: [TensorShape?], - capacity: Int64 = -1, - container: String, - sharedName: String + componentTypes: [TensorDataType], + shapes: [TensorShape?], + capacity: Int64 = -1, + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("FIFOQueueV2", nOutputs) - op.updateAttribute("component_types", componentTypes) - op.updateAttribute("shapes", shapes) - op.updateAttribute("capacity", capacity) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("FIFOQueueV2", nOutputs) + op.updateAttribute("component_types", componentTypes) + op.updateAttribute("shapes", shapes) + op.updateAttribute("capacity", capacity) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Output a fact about factorials. @@ -10551,9 +10551,9 @@ public static func fIFOQueueV2( public static func fact( ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("Fact", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("Fact", nOutputs) + + return op.execute(Int(1)) } /// This op is used as a placeholder in If branch functions. It doesn't provide a @@ -10562,20 +10562,20 @@ public static func fact( /// intermediate output needed for the gradient computation of the other branch). /// /// - Attrs: -/// - dtype: The type of the output. -/// - shape: The purported shape of the output. This is only used for shape inference; -/// the output will not necessarily have this shape. Can be a partial shape. +/// - dtype: The type of the output. +/// - shape: The purported shape of the output. This is only used for shape inference; +/// the output will not necessarily have this shape. Can be a partial shape. /// /// - Output output: \"Fake\" output value. This should not be consumed by another op. @inlinable @inline(__always) public static func fakeParam( - shape: TensorShape? + shape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FakeParam", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape", shape) - return op.execute(Int(1)) + let op = makeOp("FakeParam", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + return op.execute(Int(1)) } /// Fake-quantize the 'inputs' tensor, type float to 'outputs' tensor of same type. @@ -10598,48 +10598,48 @@ public static func fakeParam( /// Quantization is called fake since the output is still in floating point. @inlinable @inline(__always) public static func fakeQuantWithMinMaxArgs( - inputs: Tensor, - min: Double = -6, - max: Double = 6, - numBits: Int64 = 8, - narrowRange: Bool = false + inputs: Tensor, + min: Double = -6, + max: Double = 6, + numBits: Int64 = 8, + narrowRange: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FakeQuantWithMinMaxArgs", nOutputs) - op.updateAttribute("min", min) - op.updateAttribute("max", max) - op.updateAttribute("num_bits", numBits) - op.updateAttribute("narrow_range", narrowRange) - op.addInput(inputs) - return op.execute(Int(1)) + let op = makeOp("FakeQuantWithMinMaxArgs", nOutputs) + op.updateAttribute("min", min) + op.updateAttribute("max", max) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("narrow_range", narrowRange) + op.addInput(inputs) + return op.execute(Int(1)) } /// Compute gradients for a FakeQuantWithMinMaxArgs operation. /// /// - Parameters: -/// - gradients: Backpropagated gradients above the FakeQuantWithMinMaxArgs operation. -/// - inputs: Values passed as inputs to the FakeQuantWithMinMaxArgs operation. +/// - gradients: Backpropagated gradients above the FakeQuantWithMinMaxArgs operation. +/// - inputs: Values passed as inputs to the FakeQuantWithMinMaxArgs operation. /// /// - Output backprops: Backpropagated gradients below the FakeQuantWithMinMaxArgs operation: -/// `gradients * (inputs >= min && inputs <= max)`. +/// `gradients * (inputs >= min && inputs <= max)`. @inlinable @inline(__always) public static func fakeQuantWithMinMaxArgsGradient( - gradients: Tensor, - inputs: Tensor, - min: Double = -6, - max: Double = 6, - numBits: Int64 = 8, - narrowRange: Bool = false + gradients: Tensor, + inputs: Tensor, + min: Double = -6, + max: Double = 6, + numBits: Int64 = 8, + narrowRange: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FakeQuantWithMinMaxArgsGradient", nOutputs) - op.updateAttribute("min", min) - op.updateAttribute("max", max) - op.updateAttribute("num_bits", numBits) - op.updateAttribute("narrow_range", narrowRange) - op.addInput(gradients) - op.addInput(inputs) - return op.execute(Int(1)) + let op = makeOp("FakeQuantWithMinMaxArgsGradient", nOutputs) + op.updateAttribute("min", min) + op.updateAttribute("max", max) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("narrow_range", narrowRange) + op.addInput(gradients) + op.addInput(inputs) + return op.execute(Int(1)) } /// Fake-quantize the 'inputs' tensor of type float via global float scalars `min` @@ -10665,58 +10665,58 @@ public static func fakeQuantWithMinMaxArgsGradient( /// values. @inlinable @inline(__always) public static func fakeQuantWithMinMaxVars( - inputs: Tensor, - min: Tensor, - max: Tensor, - numBits: Int64 = 8, - narrowRange: Bool = false + inputs: Tensor, + min: Tensor, + max: Tensor, + numBits: Int64 = 8, + narrowRange: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FakeQuantWithMinMaxVars", nOutputs) - op.updateAttribute("num_bits", numBits) - op.updateAttribute("narrow_range", narrowRange) - op.addInput(inputs) - op.addInput(min) - op.addInput(max) - return op.execute(Int(1)) + let op = makeOp("FakeQuantWithMinMaxVars", nOutputs) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("narrow_range", narrowRange) + op.addInput(inputs) + op.addInput(min) + op.addInput(max) + return op.execute(Int(1)) } /// Compute gradients for a FakeQuantWithMinMaxVars operation. /// /// - Parameters: -/// - gradients: Backpropagated gradients above the FakeQuantWithMinMaxVars operation. -/// - inputs: Values passed as inputs to the FakeQuantWithMinMaxVars operation. -/// min, max: Quantization interval, scalar floats. +/// - gradients: Backpropagated gradients above the FakeQuantWithMinMaxVars operation. +/// - inputs: Values passed as inputs to the FakeQuantWithMinMaxVars operation. +/// min, max: Quantization interval, scalar floats. /// /// - Attrs: -/// - num_bits: The bitwidth of the quantization; between 2 and 8, inclusive. -/// - narrow_range: Whether to quantize into 2^num_bits - 1 distinct values. +/// - num_bits: The bitwidth of the quantization; between 2 and 8, inclusive. +/// - narrow_range: Whether to quantize into 2^num_bits - 1 distinct values. /// /// - Outputs: -/// - backprops_wrt_input: Backpropagated gradients w.r.t. inputs: -/// `gradients * (inputs >= min && inputs <= max)`. -/// - backprop_wrt_min: Backpropagated gradients w.r.t. min parameter: -/// `sum(gradients * (inputs < min))`. -/// - backprop_wrt_max: Backpropagated gradients w.r.t. max parameter: -/// `sum(gradients * (inputs > max))`. +/// - backprops_wrt_input: Backpropagated gradients w.r.t. inputs: +/// `gradients * (inputs >= min && inputs <= max)`. +/// - backprop_wrt_min: Backpropagated gradients w.r.t. min parameter: +/// `sum(gradients * (inputs < min))`. +/// - backprop_wrt_max: Backpropagated gradients w.r.t. max parameter: +/// `sum(gradients * (inputs > max))`. @inlinable @inline(__always) public static func fakeQuantWithMinMaxVarsGradient( - gradients: Tensor, - inputs: Tensor, - min: Tensor, - max: Tensor, - numBits: Int64 = 8, - narrowRange: Bool = false + gradients: Tensor, + inputs: Tensor, + min: Tensor, + max: Tensor, + numBits: Int64 = 8, + narrowRange: Bool = false ) -> (backpropsWrtInput: Tensor, backpropWrtMin: Tensor, backpropWrtMax: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("FakeQuantWithMinMaxVarsGradient", nOutputs) - op.updateAttribute("num_bits", numBits) - op.updateAttribute("narrow_range", narrowRange) - op.addInput(gradients) - op.addInput(inputs) - op.addInput(min) - op.addInput(max) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("FakeQuantWithMinMaxVarsGradient", nOutputs) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("narrow_range", narrowRange) + op.addInput(gradients) + op.addInput(inputs) + op.addInput(min) + op.addInput(max) + return op.execute(Int(1), Int(1), Int(1)) } /// Fake-quantize the 'inputs' tensor of type float and one of the shapes: `[d]`, @@ -10743,61 +10743,61 @@ public static func fakeQuantWithMinMaxVarsGradient( /// values. @inlinable @inline(__always) public static func fakeQuantWithMinMaxVarsPerChannel( - inputs: Tensor, - min: Tensor, - max: Tensor, - numBits: Int64 = 8, - narrowRange: Bool = false + inputs: Tensor, + min: Tensor, + max: Tensor, + numBits: Int64 = 8, + narrowRange: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FakeQuantWithMinMaxVarsPerChannel", nOutputs) - op.updateAttribute("num_bits", numBits) - op.updateAttribute("narrow_range", narrowRange) - op.addInput(inputs) - op.addInput(min) - op.addInput(max) - return op.execute(Int(1)) + let op = makeOp("FakeQuantWithMinMaxVarsPerChannel", nOutputs) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("narrow_range", narrowRange) + op.addInput(inputs) + op.addInput(min) + op.addInput(max) + return op.execute(Int(1)) } /// Compute gradients for a FakeQuantWithMinMaxVarsPerChannel operation. /// /// - Parameters: -/// - gradients: Backpropagated gradients above the FakeQuantWithMinMaxVars operation, -/// shape one of: `[d]`, `[b, d]`, `[b, h, w, d]`. -/// - inputs: Values passed as inputs to the FakeQuantWithMinMaxVars operation, shape -/// same as `gradients`. -/// min, max: Quantization interval, floats of shape `[d]`. +/// - gradients: Backpropagated gradients above the FakeQuantWithMinMaxVars operation, +/// shape one of: `[d]`, `[b, d]`, `[b, h, w, d]`. +/// - inputs: Values passed as inputs to the FakeQuantWithMinMaxVars operation, shape +/// same as `gradients`. +/// min, max: Quantization interval, floats of shape `[d]`. /// /// - Attrs: -/// - num_bits: The bitwidth of the quantization; between 2 and 16, inclusive. -/// - narrow_range: Whether to quantize into 2^num_bits - 1 distinct values. +/// - num_bits: The bitwidth of the quantization; between 2 and 16, inclusive. +/// - narrow_range: Whether to quantize into 2^num_bits - 1 distinct values. /// /// - Outputs: -/// - backprops_wrt_input: Backpropagated gradients w.r.t. inputs, shape same as -/// `inputs`: -/// `gradients * (inputs >= min && inputs <= max)`. -/// - backprop_wrt_min: Backpropagated gradients w.r.t. min parameter, shape `[d]`: -/// `sum_per_d(gradients * (inputs < min))`. -/// - backprop_wrt_max: Backpropagated gradients w.r.t. max parameter, shape `[d]`: -/// `sum_per_d(gradients * (inputs > max))`. +/// - backprops_wrt_input: Backpropagated gradients w.r.t. inputs, shape same as +/// `inputs`: +/// `gradients * (inputs >= min && inputs <= max)`. +/// - backprop_wrt_min: Backpropagated gradients w.r.t. min parameter, shape `[d]`: +/// `sum_per_d(gradients * (inputs < min))`. +/// - backprop_wrt_max: Backpropagated gradients w.r.t. max parameter, shape `[d]`: +/// `sum_per_d(gradients * (inputs > max))`. @inlinable @inline(__always) public static func fakeQuantWithMinMaxVarsPerChannelGradient( - gradients: Tensor, - inputs: Tensor, - min: Tensor, - max: Tensor, - numBits: Int64 = 8, - narrowRange: Bool = false + gradients: Tensor, + inputs: Tensor, + min: Tensor, + max: Tensor, + numBits: Int64 = 8, + narrowRange: Bool = false ) -> (backpropsWrtInput: Tensor, backpropWrtMin: Tensor, backpropWrtMax: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("FakeQuantWithMinMaxVarsPerChannelGradient", nOutputs) - op.updateAttribute("num_bits", numBits) - op.updateAttribute("narrow_range", narrowRange) - op.addInput(gradients) - op.addInput(inputs) - op.addInput(min) - op.addInput(max) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("FakeQuantWithMinMaxVarsPerChannelGradient", nOutputs) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("narrow_range", narrowRange) + op.addInput(gradients) + op.addInput(inputs) + op.addInput(min) + op.addInput(max) + return op.execute(Int(1), Int(1), Int(1)) } /// Creates a tensor filled with a scalar value. @@ -10823,42 +10823,42 @@ public static func fakeQuantWithMinMaxVarsPerChannelGradient( /// based on other runtime Tensors, unlike `tf.constant`. /// /// - Parameters: -/// - dims: 1-D. Represents the shape of the output tensor. -/// - value: 0-D (scalar). Value to fill the returned tensor. +/// - dims: 1-D. Represents the shape of the output tensor. +/// - value: 0-D (scalar). Value to fill the returned tensor. /// -/// @compatibility(numpy) -/// Equivalent to np.full -/// @end_compatibility +/// @compatibility(numpy) +/// Equivalent to np.full +/// @end_compatibility @inlinable @inline(__always) public static func fill< T: TensorFlowScalar, IndexType: BinaryInteger & TensorFlowScalar >( - dims: Tensor, - value: Tensor + dims: Tensor, + value: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Fill", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("index_type", IndexType.tensorFlowDataType) - op.addInput(dims) - op.addInput(value) - return op.execute(Int(1)) + let op = makeOp("Fill", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("index_type", IndexType.tensorFlowDataType) + op.addInput(dims) + op.addInput(value) + return op.execute(Int(1)) } /// Creates a dataset containing elements of first component of `input_dataset` having true in the last component. @inlinable @inline(__always) public static func filterByLastComponentDataset( - inputDataset: VariantHandle, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("FilterByLastComponentDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - return op.execute(Int(1)) + let op = makeOp("FilterByLastComponentDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + return op.execute(Int(1)) } /// Creates a dataset containing elements of `input_dataset` matching `predicate`. @@ -10870,7 +10870,7 @@ public static func filterByLastComponentDataset( /// * One tensor for each value in `other_arguments`. /// /// - Parameter other_arguments: A list of tensors, typically values that were captured when -/// building a closure for `predicate`. +/// building a closure for `predicate`. /// /// - Attr predicate: A function returning a scalar boolean. @inlinable @inline(__always) @@ -10879,130 +10879,117 @@ public static func filterDataset< PredicateOut: TensorGroup, Targuments: TensorArrayProtocol >( - inputDataset: VariantHandle, - otherArguments: Targuments, - predicate: (PredicateIn) -> PredicateOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + otherArguments: Targuments, + predicate: (PredicateIn) -> PredicateOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("FilterDataset", nOutputs) - op.updateAttribute("predicate", predicate) - op.updateAttribute("Targuments", otherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInputList(otherArguments) - return op.execute(Int(1)) -} - -@inlinable @inline(__always) -public static func fingerprint( - data: Tensor, - method: StringTensor -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("Fingerprint", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(data) - op.addInput(method) - return op.execute(Int(1)) + let op = makeOp("FilterDataset", nOutputs) + op.updateAttribute("predicate", predicate) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(otherArguments) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func fiveFloatOutputs( ) -> (a: Tensor, b: Tensor, c: Tensor, d: Tensor, e: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("FiveFloatOutputs", nOutputs) - - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("FiveFloatOutputs", nOutputs) + + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) } /// Creates a dataset that emits the records from one or more binary files. /// /// - Parameters: -/// - filenames: A scalar or a vector containing the name(s) of the file(s) to be -/// read. -/// - header_bytes: A scalar representing the number of bytes to skip at the -/// beginning of a file. -/// - record_bytes: A scalar representing the number of bytes in each record. -/// - footer_bytes: A scalar representing the number of bytes to skip at the end -/// of a file. -/// - buffer_size: A scalar representing the number of bytes to buffer. Must be > 0. +/// - filenames: A scalar or a vector containing the name(s) of the file(s) to be +/// read. +/// - header_bytes: A scalar representing the number of bytes to skip at the +/// beginning of a file. +/// - record_bytes: A scalar representing the number of bytes in each record. +/// - footer_bytes: A scalar representing the number of bytes to skip at the end +/// of a file. +/// - buffer_size: A scalar representing the number of bytes to buffer. Must be > 0. @inlinable @inline(__always) public static func fixedLengthRecordDataset( - filenames: StringTensor, - headerBytes: Tensor, - recordBytes: Tensor, - footerBytes: Tensor, - bufferSize: Tensor + filenames: StringTensor, + headerBytes: Tensor, + recordBytes: Tensor, + footerBytes: Tensor, + bufferSize: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("FixedLengthRecordDataset", nOutputs) - op.addInput(filenames) - op.addInput(headerBytes) - op.addInput(recordBytes) - op.addInput(footerBytes) - op.addInput(bufferSize) - return op.execute(Int(1)) + let op = makeOp("FixedLengthRecordDataset", nOutputs) + op.addInput(filenames) + op.addInput(headerBytes) + op.addInput(recordBytes) + op.addInput(footerBytes) + op.addInput(bufferSize) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func fixedLengthRecordDatasetV2( - filenames: StringTensor, - headerBytes: Tensor, - recordBytes: Tensor, - footerBytes: Tensor, - bufferSize: Tensor, - compressionType: StringTensor + filenames: StringTensor, + headerBytes: Tensor, + recordBytes: Tensor, + footerBytes: Tensor, + bufferSize: Tensor, + compressionType: StringTensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("FixedLengthRecordDatasetV2", nOutputs) - op.addInput(filenames) - op.addInput(headerBytes) - op.addInput(recordBytes) - op.addInput(footerBytes) - op.addInput(bufferSize) - op.addInput(compressionType) - return op.execute(Int(1)) + let op = makeOp("FixedLengthRecordDatasetV2", nOutputs) + op.addInput(filenames) + op.addInput(headerBytes) + op.addInput(recordBytes) + op.addInput(footerBytes) + op.addInput(bufferSize) + op.addInput(compressionType) + return op.execute(Int(1)) } /// A Reader that outputs fixed-length records from a file. /// /// - Attrs: -/// - header_bytes: Number of bytes in the header, defaults to 0. -/// - record_bytes: Number of bytes in the record. -/// - footer_bytes: Number of bytes in the footer, defaults to 0. -/// - hop_bytes: Number of bytes to hop before each read. Default of 0 means using -/// record_bytes. -/// - container: If non-empty, this reader is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this reader is named in the given bucket -/// with this shared_name. Otherwise, the node name is used instead. -/// - encoding: The type of encoding for the file. Currently ZLIB and GZIP -/// are supported. Defaults to none. +/// - header_bytes: Number of bytes in the header, defaults to 0. +/// - record_bytes: Number of bytes in the record. +/// - footer_bytes: Number of bytes in the footer, defaults to 0. +/// - hop_bytes: Number of bytes to hop before each read. Default of 0 means using +/// record_bytes. +/// - container: If non-empty, this reader is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this reader is named in the given bucket +/// with this shared_name. Otherwise, the node name is used instead. +/// - encoding: The type of encoding for the file. Currently ZLIB and GZIP +/// are supported. Defaults to none. /// /// - Output reader_handle: The handle to reference the Reader. @inlinable @inline(__always) public static func fixedLengthRecordReaderV2( - headerBytes: Int64 = 0, - recordBytes: Int64, - footerBytes: Int64 = 0, - hopBytes: Int64 = 0, - container: String, - sharedName: String, - encoding: String + headerBytes: Int64 = 0, + recordBytes: Int64, + footerBytes: Int64 = 0, + hopBytes: Int64 = 0, + container: String, + sharedName: String, + encoding: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("FixedLengthRecordReaderV2", nOutputs) - op.updateAttribute("header_bytes", headerBytes) - op.updateAttribute("record_bytes", recordBytes) - op.updateAttribute("footer_bytes", footerBytes) - op.updateAttribute("hop_bytes", hopBytes) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("encoding", encoding) - return op.execute(Int(1)) + let op = makeOp("FixedLengthRecordReaderV2", nOutputs) + op.updateAttribute("header_bytes", headerBytes) + op.updateAttribute("record_bytes", recordBytes) + op.updateAttribute("footer_bytes", footerBytes) + op.updateAttribute("hop_bytes", hopBytes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("encoding", encoding) + return op.execute(Int(1)) } /// Generates labels for candidate sampling with a learned unigram distribution. @@ -11023,85 +11010,85 @@ public static func fixedLengthRecordReaderV2( /// true labels. /// /// - Parameter true_classes: A batch_size * num_true matrix, in which each row contains the -/// IDs of the num_true target_classes in the corresponding original label. +/// IDs of the num_true target_classes in the corresponding original label. /// /// - Attrs: -/// - num_true: Number of true labels per context. -/// - num_sampled: Number of candidates to randomly sample. -/// - unique: If unique is true, we sample with rejection, so that all sampled -/// candidates in a batch are unique. This requires some approximation to -/// estimate the post-rejection sampling probabilities. -/// - range_max: The sampler will sample integers from the interval [0, range_max). -/// - vocab_file: Each valid line in this file (which should have a CSV-like format) -/// corresponds to a valid word ID. IDs are in sequential order, starting from -/// num_reserved_ids. The last entry in each line is expected to be a value -/// corresponding to the count or relative probability. Exactly one of vocab_file -/// and unigrams needs to be passed to this op. -/// - distortion: The distortion is used to skew the unigram probability distribution. -/// Each weight is first raised to the distortion's power before adding to the -/// internal unigram distribution. As a result, distortion = 1.0 gives regular -/// unigram sampling (as defined by the vocab file), and distortion = 0.0 gives -/// a uniform distribution. -/// - num_reserved_ids: Optionally some reserved IDs can be added in the range [0, -/// ..., num_reserved_ids) by the users. One use case is that a special unknown -/// word token is used as ID 0. These IDs will have a sampling probability of 0. -/// - num_shards: A sampler can be used to sample from a subset of the original range -/// in order to speed up the whole computation through parallelism. This parameter -/// (together with 'shard') indicates the number of partitions that are being -/// used in the overall computation. -/// - shard: A sampler can be used to sample from a subset of the original range -/// in order to speed up the whole computation through parallelism. This parameter -/// (together with 'num_shards') indicates the particular partition number of a -/// sampler op, when partitioning is being used. -/// - unigrams: A list of unigram counts or probabilities, one per ID in sequential -/// order. Exactly one of vocab_file and unigrams should be passed to this op. -/// - seed: If either seed or seed2 are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: An second seed to avoid seed collision. +/// - num_true: Number of true labels per context. +/// - num_sampled: Number of candidates to randomly sample. +/// - unique: If unique is true, we sample with rejection, so that all sampled +/// candidates in a batch are unique. This requires some approximation to +/// estimate the post-rejection sampling probabilities. +/// - range_max: The sampler will sample integers from the interval [0, range_max). +/// - vocab_file: Each valid line in this file (which should have a CSV-like format) +/// corresponds to a valid word ID. IDs are in sequential order, starting from +/// num_reserved_ids. The last entry in each line is expected to be a value +/// corresponding to the count or relative probability. Exactly one of vocab_file +/// and unigrams needs to be passed to this op. +/// - distortion: The distortion is used to skew the unigram probability distribution. +/// Each weight is first raised to the distortion's power before adding to the +/// internal unigram distribution. As a result, distortion = 1.0 gives regular +/// unigram sampling (as defined by the vocab file), and distortion = 0.0 gives +/// a uniform distribution. +/// - num_reserved_ids: Optionally some reserved IDs can be added in the range [0, +/// ..., num_reserved_ids) by the users. One use case is that a special unknown +/// word token is used as ID 0. These IDs will have a sampling probability of 0. +/// - num_shards: A sampler can be used to sample from a subset of the original range +/// in order to speed up the whole computation through parallelism. This parameter +/// (together with 'shard') indicates the number of partitions that are being +/// used in the overall computation. +/// - shard: A sampler can be used to sample from a subset of the original range +/// in order to speed up the whole computation through parallelism. This parameter +/// (together with 'num_shards') indicates the particular partition number of a +/// sampler op, when partitioning is being used. +/// - unigrams: A list of unigram counts or probabilities, one per ID in sequential +/// order. Exactly one of vocab_file and unigrams should be passed to this op. +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. /// /// - Outputs: -/// - sampled_candidates: A vector of length num_sampled, in which each element is -/// the ID of a sampled candidate. -/// - true_expected_count: A batch_size * num_true matrix, representing -/// the number of times each candidate is expected to occur in a batch -/// of sampled candidates. If unique=true, then this is a probability. -/// - sampled_expected_count: A vector of length num_sampled, for each sampled -/// candidate representing the number of times the candidate is expected -/// to occur in a batch of sampled candidates. If unique=true, then this is a -/// probability. +/// - sampled_candidates: A vector of length num_sampled, in which each element is +/// the ID of a sampled candidate. +/// - true_expected_count: A batch_size * num_true matrix, representing +/// the number of times each candidate is expected to occur in a batch +/// of sampled candidates. If unique=true, then this is a probability. +/// - sampled_expected_count: A vector of length num_sampled, for each sampled +/// candidate representing the number of times the candidate is expected +/// to occur in a batch of sampled candidates. If unique=true, then this is a +/// probability. @inlinable @inline(__always) public static func fixedUnigramCandidateSampler( - trueClasses: Tensor, - numTrue: Int64, - numSampled: Int64, - unique: Bool, - rangeMax: Int64, - vocabFile: String, - distortion: Double = 1, - numReservedIds: Int64 = 0, - numShards: Int64 = 1, - shard: Int64 = 0, - unigrams: [Double], - seed: Int64 = 0, - seed2: Int64 = 0 + trueClasses: Tensor, + numTrue: Int64, + numSampled: Int64, + unique: Bool, + rangeMax: Int64, + vocabFile: String, + distortion: Double = 1, + numReservedIds: Int64 = 0, + numShards: Int64 = 1, + shard: Int64 = 0, + unigrams: [Double], + seed: Int64 = 0, + seed2: Int64 = 0 ) -> (sampledCandidates: Tensor, trueExpectedCount: Tensor, sampledExpectedCount: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("FixedUnigramCandidateSampler", nOutputs) - op.updateAttribute("num_true", numTrue) - op.updateAttribute("num_sampled", numSampled) - op.updateAttribute("unique", unique) - op.updateAttribute("range_max", rangeMax) - op.updateAttribute("vocab_file", vocabFile) - op.updateAttribute("distortion", distortion) - op.updateAttribute("num_reserved_ids", numReservedIds) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard", shard) - op.updateAttribute("unigrams", unigrams) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.addInput(trueClasses) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("FixedUnigramCandidateSampler", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("num_sampled", numSampled) + op.updateAttribute("unique", unique) + op.updateAttribute("range_max", rangeMax) + op.updateAttribute("vocab_file", vocabFile) + op.updateAttribute("distortion", distortion) + op.updateAttribute("num_reserved_ids", numReservedIds) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard", shard) + op.updateAttribute("unigrams", unigrams) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + return op.execute(Int(1), Int(1), Int(1)) } /// Creates a dataset that applies `f` to the outputs of `input_dataset`. @@ -11111,69 +11098,69 @@ public static func fixedUnigramCandidateSampler( /// into a single Dataset. /// /// - Attr f: A function mapping elements of `input_dataset`, concatenated with -/// `other_arguments`, to a Dataset variant that contains elements matching -/// `output_types` and `output_shapes`. +/// `other_arguments`, to a Dataset variant that contains elements matching +/// `output_types` and `output_shapes`. @inlinable @inline(__always) public static func flatMapDataset< FIn: TensorGroup, FOut: TensorGroup, Targuments: TensorArrayProtocol >( - inputDataset: VariantHandle, - otherArguments: Targuments, - f: (FIn) -> FOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + otherArguments: Targuments, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("FlatMapDataset", nOutputs) - op.updateAttribute("f", f) - op.updateAttribute("Targuments", otherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInputList(otherArguments) - return op.execute(Int(1)) + let op = makeOp("FlatMapDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(otherArguments) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func floatInput( - _ a: Tensor + _ a: Tensor ) { let nOutputs = 0 - let op = makeOp("FloatInput", nOutputs) - op.addInput(a) - op.execute() + let op = makeOp("FloatInput", nOutputs) + op.addInput(a) + op.execute() } @inlinable @inline(__always) public static func floatOutput( ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FloatOutput", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("FloatOutput", nOutputs) + + return op.execute(Int(1)) } @inlinable @inline(__always) public static func floatOutputStringOutput( ) -> (a: Tensor, b: StringTensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("FloatOutputStringOutput", nOutputs) - - return op.execute(Int(1), Int(1)) + let op = makeOp("FloatOutputStringOutput", nOutputs) + + return op.execute(Int(1), Int(1)) } /// Returns element-wise largest integer not greater than x. @inlinable @inline(__always) public static func floor( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Floor", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Floor", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Returns x // y element-wise. @@ -11182,15 +11169,15 @@ public static func floor( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func floorDiv( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FloorDiv", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("FloorDiv", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns element-wise remainder of division. When `x < 0` xor `y < 0` is @@ -11202,67 +11189,67 @@ public static func floorDiv( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func floorMod( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FloorMod", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("FloorMod", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func flushSummaryWriter( - writer: ResourceHandle + writer: ResourceHandle ) { let nOutputs = 0 - let op = makeOp("FlushSummaryWriter", nOutputs) - op.addInput(writer) - op.execute() + let op = makeOp("FlushSummaryWriter", nOutputs) + op.addInput(writer) + op.execute() } @inlinable @inline(__always) public static func foo1( - _ a: Tensor, - _ b: Tensor, - c: Tensor + _ a: Tensor, + _ b: Tensor, + c: Tensor ) -> (d: Tensor, e: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("Foo1", nOutputs) - op.addInput(a) - op.addInput(b) - op.addInput(c) - return op.execute(Int(1), Int(1)) + let op = makeOp("Foo1", nOutputs) + op.addInput(a) + op.addInput(b) + op.addInput(c) + return op.execute(Int(1), Int(1)) } @inlinable @inline(__always) public static func foo2( - _ a: Tensor, - _ b: StringTensor, - c: StringTensor + _ a: Tensor, + _ b: StringTensor, + c: StringTensor ) -> (d: Tensor, e: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("Foo2", nOutputs) - op.addInput(a) - op.addInput(b) - op.addInput(c) - return op.execute(Int(1), Int(1)) + let op = makeOp("Foo2", nOutputs) + op.addInput(a) + op.addInput(b) + op.addInput(c) + return op.execute(Int(1), Int(1)) } @inlinable @inline(__always) public static func foo3( - _ a: Tensor, - _ b: StringTensor, - c: Tensor + _ a: Tensor, + _ b: StringTensor, + c: Tensor ) -> (d: Tensor, e: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("Foo3", nOutputs) - op.addInput(a) - op.addInput(b) - op.addInput(c) - return op.execute(Int(1), Int(1)) + let op = makeOp("Foo3", nOutputs) + op.addInput(a) + op.addInput(b) + op.addInput(c) + return op.execute(Int(1), Int(1)) } /// ```python @@ -11272,15 +11259,15 @@ public static func foo3( /// ``` /// /// - Parameters: -/// - start: The lower bound. An int32 -/// - limit: The upper bound. An int32 -/// - delta: The increment. An int32 -/// - input: A list of input tensors whose types are T. +/// - start: The lower bound. An int32 +/// - limit: The upper bound. An int32 +/// - delta: The increment. An int32 +/// - input: A list of input tensors whose types are T. /// /// - Attrs: -/// - T: A list of dtypes. -/// - body: A function that takes a list of tensors (int32, T) and returns another -/// list of tensors (T). +/// - T: A list of dtypes. +/// - body: A function that takes a list of tensors (int32, T) and returns another +/// list of tensors (T). /// /// - Output output: A list of output tensors whose types are T. @inlinable @inline(__always) @@ -11289,21 +11276,21 @@ public static func for_< BodyIn: TensorGroup, BodyOut: TensorGroup >( - start: Tensor, - limit: Tensor, - delta: Tensor, - _ input: T, - body: (BodyIn) -> BodyOut + start: Tensor, + limit: Tensor, + delta: Tensor, + _ input: T, + body: (BodyIn) -> BodyOut ) -> T { let nOutputs = Int(input._typeList.count) - let op = makeOp("For", nOutputs) - op.updateAttribute("T", input._typeList) - op.updateAttribute("body", body) - op.addInput(start) - op.addInput(limit) - op.addInput(delta) - op.addInputList(input) - return op.execute(Int(input._typeList.count)) + let op = makeOp("For", nOutputs) + op.updateAttribute("T", input._typeList) + op.updateAttribute("body", body) + op.addInput(start) + op.addInput(limit) + op.addInput(delta) + op.addInputList(input) + return op.execute(Int(input._typeList.count)) } /// Performs fractional average pooling on the input. @@ -11316,58 +11303,58 @@ public static func for_< /// - Parameter value: 4-D with shape `[batch, height, width, channels]`. /// /// - Attrs: -/// - pooling_ratio: Pooling ratio for each dimension of `value`, currently only -/// supports row and col dimension and should be >= 1.0. For example, a valid -/// pooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements -/// must be 1.0 because we don't allow pooling on batch and channels -/// dimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions -/// respectively. -/// - pseudo_random: When set to True, generates the pooling sequence in a -/// pseudorandom fashion, otherwise, in a random fashion. Check paper [Benjamin -/// Graham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) for -/// difference between pseudorandom and random. -/// - overlapping: When set to True, it means when pooling, the values at the boundary -/// of adjacent pooling cells are used by both cells. For example: -/// -/// `index 0 1 2 3 4` -/// -/// `value 20 5 16 3 7` -/// -/// If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. -/// The result would be [41/3, 26/3] for fractional avg pooling. -/// - deterministic: When set to True, a fixed pooling region will be used when -/// iterating over a FractionalAvgPool node in the computation graph. Mainly used -/// in unit test to make FractionalAvgPool deterministic. -/// - seed: If either seed or seed2 are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: An second seed to avoid seed collision. +/// - pooling_ratio: Pooling ratio for each dimension of `value`, currently only +/// supports row and col dimension and should be >= 1.0. For example, a valid +/// pooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements +/// must be 1.0 because we don't allow pooling on batch and channels +/// dimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions +/// respectively. +/// - pseudo_random: When set to True, generates the pooling sequence in a +/// pseudorandom fashion, otherwise, in a random fashion. Check paper [Benjamin +/// Graham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) for +/// difference between pseudorandom and random. +/// - overlapping: When set to True, it means when pooling, the values at the boundary +/// of adjacent pooling cells are used by both cells. For example: +/// +/// `index 0 1 2 3 4` +/// +/// `value 20 5 16 3 7` +/// +/// If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. +/// The result would be [41/3, 26/3] for fractional avg pooling. +/// - deterministic: When set to True, a fixed pooling region will be used when +/// iterating over a FractionalAvgPool node in the computation graph. Mainly used +/// in unit test to make FractionalAvgPool deterministic. +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. /// /// - Outputs: -/// - output: output tensor after fractional avg pooling. -/// - row_pooling_sequence: row pooling sequence, needed to calculate gradient. -/// - col_pooling_sequence: column pooling sequence, needed to calculate gradient. +/// - output: output tensor after fractional avg pooling. +/// - row_pooling_sequence: row pooling sequence, needed to calculate gradient. +/// - col_pooling_sequence: column pooling sequence, needed to calculate gradient. @inlinable @inline(__always) public static func fractionalAvgPool( - value: Tensor, - poolingRatio: [Double], - pseudoRandom: Bool = false, - overlapping: Bool = false, - deterministic: Bool = false, - seed: Int64 = 0, - seed2: Int64 = 0 + value: Tensor, + poolingRatio: [Double], + pseudoRandom: Bool = false, + overlapping: Bool = false, + deterministic: Bool = false, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> (output: Tensor, rowPoolingSequence: Tensor, colPoolingSequence: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("FractionalAvgPool", nOutputs) - op.updateAttribute("pooling_ratio", poolingRatio) - op.updateAttribute("pseudo_random", pseudoRandom) - op.updateAttribute("overlapping", overlapping) - op.updateAttribute("deterministic", deterministic) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(value) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("FractionalAvgPool", nOutputs) + op.updateAttribute("pooling_ratio", poolingRatio) + op.updateAttribute("pseudo_random", pseudoRandom) + op.updateAttribute("overlapping", overlapping) + op.updateAttribute("deterministic", deterministic) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + return op.execute(Int(1), Int(1), Int(1)) } /// Computes gradient of the FractionalAvgPool function. @@ -11379,42 +11366,42 @@ public static func fractionalAvgPool( /// tensor. /// /// - Parameters: -/// - orig_input_tensor_shape: Original input tensor shape for `fractional_avg_pool` -/// - out_backprop: 4-D with shape `[batch, height, width, channels]`. Gradients -/// w.r.t. the output of `fractional_avg_pool`. -/// - row_pooling_sequence: row pooling sequence, form pooling region with -/// col_pooling_sequence. -/// - col_pooling_sequence: column pooling sequence, form pooling region with -/// row_pooling sequence. +/// - orig_input_tensor_shape: Original input tensor shape for `fractional_avg_pool` +/// - out_backprop: 4-D with shape `[batch, height, width, channels]`. Gradients +/// w.r.t. the output of `fractional_avg_pool`. +/// - row_pooling_sequence: row pooling sequence, form pooling region with +/// col_pooling_sequence. +/// - col_pooling_sequence: column pooling sequence, form pooling region with +/// row_pooling sequence. /// /// - Attr overlapping: When set to True, it means when pooling, the values at the boundary -/// of adjacent pooling cells are used by both cells. For example: +/// of adjacent pooling cells are used by both cells. For example: /// -/// `index 0 1 2 3 4` +/// `index 0 1 2 3 4` /// -/// `value 20 5 16 3 7` +/// `value 20 5 16 3 7` /// -/// If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. -/// The result would be [41/3, 26/3] for fractional avg pooling. +/// If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. +/// The result would be [41/3, 26/3] for fractional avg pooling. /// /// - Output output: 4-D. Gradients w.r.t. the input of `fractional_avg_pool`. @inlinable @inline(__always) public static func fractionalAvgPoolGrad( - origInputTensorShape: Tensor, - outBackprop: Tensor, - rowPoolingSequence: Tensor, - colPoolingSequence: Tensor, - overlapping: Bool = false + origInputTensorShape: Tensor, + outBackprop: Tensor, + rowPoolingSequence: Tensor, + colPoolingSequence: Tensor, + overlapping: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FractionalAvgPoolGrad", nOutputs) - op.updateAttribute("overlapping", overlapping) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(origInputTensorShape) - op.addInput(outBackprop) - op.addInput(rowPoolingSequence) - op.addInput(colPoolingSequence) - return op.execute(Int(1)) + let op = makeOp("FractionalAvgPoolGrad", nOutputs) + op.updateAttribute("overlapping", overlapping) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInputTensorShape) + op.addInput(outBackprop) + op.addInput(rowPoolingSequence) + op.addInput(colPoolingSequence) + return op.execute(Int(1)) } /// Performs fractional max pooling on the input. @@ -11451,113 +11438,113 @@ public static func fractionalAvgPoolGrad( /// - Parameter value: 4-D with shape `[batch, height, width, channels]`. /// /// - Attrs: -/// - pooling_ratio: Pooling ratio for each dimension of `value`, currently only -/// supports row and col dimension and should be >= 1.0. For example, a valid -/// pooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements -/// must be 1.0 because we don't allow pooling on batch and channels -/// dimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions -/// respectively. -/// - pseudo_random: When set to True, generates the pooling sequence in a -/// pseudorandom fashion, otherwise, in a random fashion. Check paper [Benjamin -/// Graham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) for -/// difference between pseudorandom and random. -/// - overlapping: When set to True, it means when pooling, the values at the boundary -/// of adjacent pooling cells are used by both cells. For example: -/// -/// `index 0 1 2 3 4` -/// -/// `value 20 5 16 3 7` -/// -/// If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. -/// The result would be [20, 16] for fractional max pooling. -/// - deterministic: When set to True, a fixed pooling region will be used when -/// iterating over a FractionalMaxPool node in the computation graph. Mainly used -/// in unit test to make FractionalMaxPool deterministic. -/// - seed: If either seed or seed2 are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: An second seed to avoid seed collision. +/// - pooling_ratio: Pooling ratio for each dimension of `value`, currently only +/// supports row and col dimension and should be >= 1.0. For example, a valid +/// pooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements +/// must be 1.0 because we don't allow pooling on batch and channels +/// dimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions +/// respectively. +/// - pseudo_random: When set to True, generates the pooling sequence in a +/// pseudorandom fashion, otherwise, in a random fashion. Check paper [Benjamin +/// Graham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) for +/// difference between pseudorandom and random. +/// - overlapping: When set to True, it means when pooling, the values at the boundary +/// of adjacent pooling cells are used by both cells. For example: +/// +/// `index 0 1 2 3 4` +/// +/// `value 20 5 16 3 7` +/// +/// If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. +/// The result would be [20, 16] for fractional max pooling. +/// - deterministic: When set to True, a fixed pooling region will be used when +/// iterating over a FractionalMaxPool node in the computation graph. Mainly used +/// in unit test to make FractionalMaxPool deterministic. +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. /// /// - Outputs: -/// - output: output tensor after fractional max pooling. -/// - row_pooling_sequence: row pooling sequence, needed to calculate gradient. -/// - col_pooling_sequence: column pooling sequence, needed to calculate gradient. +/// - output: output tensor after fractional max pooling. +/// - row_pooling_sequence: row pooling sequence, needed to calculate gradient. +/// - col_pooling_sequence: column pooling sequence, needed to calculate gradient. @inlinable @inline(__always) public static func fractionalMaxPool( - value: Tensor, - poolingRatio: [Double], - pseudoRandom: Bool = false, - overlapping: Bool = false, - deterministic: Bool = false, - seed: Int64 = 0, - seed2: Int64 = 0 + value: Tensor, + poolingRatio: [Double], + pseudoRandom: Bool = false, + overlapping: Bool = false, + deterministic: Bool = false, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> (output: Tensor, rowPoolingSequence: Tensor, colPoolingSequence: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("FractionalMaxPool", nOutputs) - op.updateAttribute("pooling_ratio", poolingRatio) - op.updateAttribute("pseudo_random", pseudoRandom) - op.updateAttribute("overlapping", overlapping) - op.updateAttribute("deterministic", deterministic) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(value) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("FractionalMaxPool", nOutputs) + op.updateAttribute("pooling_ratio", poolingRatio) + op.updateAttribute("pseudo_random", pseudoRandom) + op.updateAttribute("overlapping", overlapping) + op.updateAttribute("deterministic", deterministic) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + return op.execute(Int(1), Int(1), Int(1)) } /// Computes gradient of the FractionalMaxPool function. /// /// - Parameters: -/// - orig_input: Original input for `fractional_max_pool` -/// - orig_output: Original output for `fractional_max_pool` -/// - out_backprop: 4-D with shape `[batch, height, width, channels]`. Gradients -/// w.r.t. the output of `fractional_max_pool`. -/// - row_pooling_sequence: row pooling sequence, form pooling region with -/// col_pooling_sequence. -/// - col_pooling_sequence: column pooling sequence, form pooling region with -/// row_pooling sequence. +/// - orig_input: Original input for `fractional_max_pool` +/// - orig_output: Original output for `fractional_max_pool` +/// - out_backprop: 4-D with shape `[batch, height, width, channels]`. Gradients +/// w.r.t. the output of `fractional_max_pool`. +/// - row_pooling_sequence: row pooling sequence, form pooling region with +/// col_pooling_sequence. +/// - col_pooling_sequence: column pooling sequence, form pooling region with +/// row_pooling sequence. /// /// - Attr overlapping: When set to True, it means when pooling, the values at the boundary -/// of adjacent pooling cells are used by both cells. For example: +/// of adjacent pooling cells are used by both cells. For example: /// -/// `index 0 1 2 3 4` +/// `index 0 1 2 3 4` /// -/// `value 20 5 16 3 7` +/// `value 20 5 16 3 7` /// -/// If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. -/// The result would be [20, 16] for fractional max pooling. +/// If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. +/// The result would be [20, 16] for fractional max pooling. /// /// - Output output: 4-D. Gradients w.r.t. the input of `fractional_max_pool`. @inlinable @inline(__always) public static func fractionalMaxPoolGrad( - origInput: Tensor, - origOutput: Tensor, - outBackprop: Tensor, - rowPoolingSequence: Tensor, - colPoolingSequence: Tensor, - overlapping: Bool = false + origInput: Tensor, + origOutput: Tensor, + outBackprop: Tensor, + rowPoolingSequence: Tensor, + colPoolingSequence: Tensor, + overlapping: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FractionalMaxPoolGrad", nOutputs) - op.updateAttribute("overlapping", overlapping) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(origInput) - op.addInput(origOutput) - op.addInput(outBackprop) - op.addInput(rowPoolingSequence) - op.addInput(colPoolingSequence) - return op.execute(Int(1)) + let op = makeOp("FractionalMaxPoolGrad", nOutputs) + op.updateAttribute("overlapping", overlapping) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(outBackprop) + op.addInput(rowPoolingSequence) + op.addInput(colPoolingSequence) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func funcAttr( - f: (FIn) -> FOut + f: (FIn) -> FOut ) { let nOutputs = 0 - let op = makeOp("FuncAttr", nOutputs) - op.updateAttribute("f", f) - op.execute() + let op = makeOp("FuncAttr", nOutputs) + op.updateAttribute("f", f) + op.execute() } /// Batch normalization. @@ -11566,54 +11553,54 @@ public static func funcAttr( - _ x: Tensor, - scale: Tensor, - offset: Tensor, - mean: Tensor, - variance: Tensor, - epsilon: Double = 0.0001, - dataFormat: DataFormat = .nhwc, - isTraining: Bool = true + _ x: Tensor, + scale: Tensor, + offset: Tensor, + mean: Tensor, + variance: Tensor, + epsilon: Double = 0.0001, + dataFormat: DataFormat = .nhwc, + isTraining: Bool = true ) -> (y: Tensor, batchMean: Tensor, batchVariance: Tensor, reserveSpace1: Tensor, reserveSpace2: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("FusedBatchNorm", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("epsilon", epsilon) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("is_training", isTraining) - op.addInput(x) - op.addInput(scale) - op.addInput(offset) - op.addInput(mean) - op.addInput(variance) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("FusedBatchNorm", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("epsilon", epsilon) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("is_training", isTraining) + op.addInput(x) + op.addInput(scale) + op.addInput(offset) + op.addInput(mean) + op.addInput(variance) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) } /// Gradient for batch normalization. @@ -11622,57 +11609,57 @@ public static func fusedBatchNorm( /// The size of 1D Tensors matches the dimension C of the 4D Tensors. /// /// - Parameters: -/// - y_backprop: A 4D Tensor for the gradient with respect to y. -/// - x: A 4D Tensor for input data. -/// - scale: A 1D Tensor for scaling factor, to scale the normalized x. -/// - reserve_space_1: When is_training is True, a 1D Tensor for the computed batch -/// mean to be reused in gradient computation. When is_training is -/// False, a 1D Tensor for the population mean to be reused in both -/// 1st and 2nd order gradient computation. -/// - reserve_space_2: When is_training is True, a 1D Tensor for the computed batch -/// variance (inverted variance in the cuDNN case) to be reused in -/// gradient computation. When is_training is False, a 1D Tensor -/// for the population variance to be reused in both 1st and 2nd -/// order gradient computation. +/// - y_backprop: A 4D Tensor for the gradient with respect to y. +/// - x: A 4D Tensor for input data. +/// - scale: A 1D Tensor for scaling factor, to scale the normalized x. +/// - reserve_space_1: When is_training is True, a 1D Tensor for the computed batch +/// mean to be reused in gradient computation. When is_training is +/// False, a 1D Tensor for the population mean to be reused in both +/// 1st and 2nd order gradient computation. +/// - reserve_space_2: When is_training is True, a 1D Tensor for the computed batch +/// variance (inverted variance in the cuDNN case) to be reused in +/// gradient computation. When is_training is False, a 1D Tensor +/// for the population variance to be reused in both 1st and 2nd +/// order gradient computation. /// /// - Attrs: -/// - T: The data type for the elements of input and output Tensors. -/// - epsilon: A small float number added to the variance of x. -/// - data_format: The data format for y_backprop, x, x_backprop. -/// Either "NHWC" (default) or "NCHW". -/// - is_training: A bool value to indicate the operation is for training (default) -/// or inference. +/// - T: The data type for the elements of input and output Tensors. +/// - epsilon: A small float number added to the variance of x. +/// - data_format: The data format for y_backprop, x, x_backprop. +/// Either "NHWC" (default) or "NCHW". +/// - is_training: A bool value to indicate the operation is for training (default) +/// or inference. /// /// - Outputs: -/// - x_backprop: A 4D Tensor for the gradient with respect to x. -/// - scale_backprop: A 1D Tensor for the gradient with respect to scale. -/// - offset_backprop: A 1D Tensor for the gradient with respect to offset. -/// - reserve_space_3: Unused placeholder to match the mean input in FusedBatchNorm. -/// - reserve_space_4: Unused placeholder to match the variance input -/// in FusedBatchNorm. +/// - x_backprop: A 4D Tensor for the gradient with respect to x. +/// - scale_backprop: A 1D Tensor for the gradient with respect to scale. +/// - offset_backprop: A 1D Tensor for the gradient with respect to offset. +/// - reserve_space_3: Unused placeholder to match the mean input in FusedBatchNorm. +/// - reserve_space_4: Unused placeholder to match the variance input +/// in FusedBatchNorm. @inlinable @inline(__always) public static func fusedBatchNormGrad( - yBackprop: Tensor, - _ x: Tensor, - scale: Tensor, - reserveSpace1: Tensor, - reserveSpace2: Tensor, - epsilon: Double = 0.0001, - dataFormat: DataFormat = .nhwc, - isTraining: Bool = true + yBackprop: Tensor, + _ x: Tensor, + scale: Tensor, + reserveSpace1: Tensor, + reserveSpace2: Tensor, + epsilon: Double = 0.0001, + dataFormat: DataFormat = .nhwc, + isTraining: Bool = true ) -> (xBackprop: Tensor, scaleBackprop: Tensor, offsetBackprop: Tensor, reserveSpace3: Tensor, reserveSpace4: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("FusedBatchNormGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("epsilon", epsilon) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("is_training", isTraining) - op.addInput(yBackprop) - op.addInput(x) - op.addInput(scale) - op.addInput(reserveSpace1) - op.addInput(reserveSpace2) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("FusedBatchNormGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("epsilon", epsilon) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("is_training", isTraining) + op.addInput(yBackprop) + op.addInput(x) + op.addInput(scale) + op.addInput(reserveSpace1) + op.addInput(reserveSpace2) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) } /// Gradient for batch normalization. @@ -11681,62 +11668,62 @@ public static func fusedBatchNormGrad( /// The size of 1D Tensors matches the dimension C of the 4D Tensors. /// /// - Parameters: -/// - y_backprop: A 4D Tensor for the gradient with respect to y. -/// - x: A 4D Tensor for input data. -/// - scale: A 1D Tensor for scaling factor, to scale the normalized x. -/// - reserve_space_1: When is_training is True, a 1D Tensor for the computed batch -/// mean to be reused in gradient computation. When is_training is -/// False, a 1D Tensor for the population mean to be reused in both -/// 1st and 2nd order gradient computation. -/// - reserve_space_2: When is_training is True, a 1D Tensor for the computed batch -/// variance (inverted variance in the cuDNN case) to be reused in -/// gradient computation. When is_training is False, a 1D Tensor -/// for the population variance to be reused in both 1st and 2nd -/// order gradient computation. +/// - y_backprop: A 4D Tensor for the gradient with respect to y. +/// - x: A 4D Tensor for input data. +/// - scale: A 1D Tensor for scaling factor, to scale the normalized x. +/// - reserve_space_1: When is_training is True, a 1D Tensor for the computed batch +/// mean to be reused in gradient computation. When is_training is +/// False, a 1D Tensor for the population mean to be reused in both +/// 1st and 2nd order gradient computation. +/// - reserve_space_2: When is_training is True, a 1D Tensor for the computed batch +/// variance (inverted variance in the cuDNN case) to be reused in +/// gradient computation. When is_training is False, a 1D Tensor +/// for the population variance to be reused in both 1st and 2nd +/// order gradient computation. /// /// - Attrs: -/// - T: The data type for the elements of input and output Tensors. -/// - U: The data type for the scale, offset, mean, and variance. -/// - epsilon: A small float number added to the variance of x. -/// - data_format: The data format for y_backprop, x, x_backprop. -/// Either "NHWC" (default) or "NCHW". -/// - is_training: A bool value to indicate the operation is for training (default) -/// or inference. +/// - T: The data type for the elements of input and output Tensors. +/// - U: The data type for the scale, offset, mean, and variance. +/// - epsilon: A small float number added to the variance of x. +/// - data_format: The data format for y_backprop, x, x_backprop. +/// Either "NHWC" (default) or "NCHW". +/// - is_training: A bool value to indicate the operation is for training (default) +/// or inference. /// /// - Outputs: -/// - x_backprop: A 4D Tensor for the gradient with respect to x. -/// - scale_backprop: A 1D Tensor for the gradient with respect to scale. -/// - offset_backprop: A 1D Tensor for the gradient with respect to offset. -/// - reserve_space_3: Unused placeholder to match the mean input in FusedBatchNorm. -/// - reserve_space_4: Unused placeholder to match the variance input -/// in FusedBatchNorm. +/// - x_backprop: A 4D Tensor for the gradient with respect to x. +/// - scale_backprop: A 1D Tensor for the gradient with respect to scale. +/// - offset_backprop: A 1D Tensor for the gradient with respect to offset. +/// - reserve_space_3: Unused placeholder to match the mean input in FusedBatchNorm. +/// - reserve_space_4: Unused placeholder to match the variance input +/// in FusedBatchNorm. @inlinable @inline(__always) public static func fusedBatchNormGradV2< T: FloatingPoint & TensorFlowScalar, U: FloatingPoint & TensorFlowScalar >( - yBackprop: Tensor, - _ x: Tensor, - scale: Tensor, - reserveSpace1: Tensor, - reserveSpace2: Tensor, - epsilon: Double = 0.0001, - dataFormat: DataFormat = .nhwc, - isTraining: Bool = true + yBackprop: Tensor, + _ x: Tensor, + scale: Tensor, + reserveSpace1: Tensor, + reserveSpace2: Tensor, + epsilon: Double = 0.0001, + dataFormat: DataFormat = .nhwc, + isTraining: Bool = true ) -> (xBackprop: Tensor, scaleBackprop: Tensor, offsetBackprop: Tensor, reserveSpace3: Tensor, reserveSpace4: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("FusedBatchNormGradV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("U", U.tensorFlowDataType) - op.updateAttribute("epsilon", epsilon) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("is_training", isTraining) - op.addInput(yBackprop) - op.addInput(x) - op.addInput(scale) - op.addInput(reserveSpace1) - op.addInput(reserveSpace2) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("FusedBatchNormGradV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("U", U.tensorFlowDataType) + op.updateAttribute("epsilon", epsilon) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("is_training", isTraining) + op.addInput(yBackprop) + op.addInput(x) + op.addInput(scale) + op.addInput(reserveSpace1) + op.addInput(reserveSpace2) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) } /// Batch normalization. @@ -11745,59 +11732,59 @@ public static func fusedBatchNormGradV2< /// The size of 1D Tensors matches the dimension C of the 4D Tensors. /// /// - Parameters: -/// - x: A 4D Tensor for input data. -/// - scale: A 1D Tensor for scaling factor, to scale the normalized x. -/// - offset: A 1D Tensor for offset, to shift to the normalized x. -/// - mean: A 1D Tensor for population mean. Used for inference only; -/// must be empty for training. -/// - variance: A 1D Tensor for population variance. Used for inference only; -/// must be empty for training. +/// - x: A 4D Tensor for input data. +/// - scale: A 1D Tensor for scaling factor, to scale the normalized x. +/// - offset: A 1D Tensor for offset, to shift to the normalized x. +/// - mean: A 1D Tensor for population mean. Used for inference only; +/// must be empty for training. +/// - variance: A 1D Tensor for population variance. Used for inference only; +/// must be empty for training. /// /// - Attrs: -/// - T: The data type for the elements of input and output Tensors. -/// - U: The data type for the scale, offset, mean, and variance. -/// - epsilon: A small float number added to the variance of x. -/// - data_format: The data format for x and y. Either "NHWC" (default) or "NCHW". -/// - is_training: A bool value to indicate the operation is for training (default) -/// or inference. +/// - T: The data type for the elements of input and output Tensors. +/// - U: The data type for the scale, offset, mean, and variance. +/// - epsilon: A small float number added to the variance of x. +/// - data_format: The data format for x and y. Either "NHWC" (default) or "NCHW". +/// - is_training: A bool value to indicate the operation is for training (default) +/// or inference. /// /// - Outputs: -/// - y: A 4D Tensor for output data. -/// - batch_mean: A 1D Tensor for the computed batch mean, to be used by TensorFlow -/// to compute the running mean. -/// - batch_variance: A 1D Tensor for the computed batch variance, to be used by -/// TensorFlow to compute the running variance. -/// - reserve_space_1: A 1D Tensor for the computed batch mean, to be reused -/// in the gradient computation. -/// - reserve_space_2: A 1D Tensor for the computed batch variance (inverted variance -/// in the cuDNN case), to be reused in the gradient computation. +/// - y: A 4D Tensor for output data. +/// - batch_mean: A 1D Tensor for the computed batch mean, to be used by TensorFlow +/// to compute the running mean. +/// - batch_variance: A 1D Tensor for the computed batch variance, to be used by +/// TensorFlow to compute the running variance. +/// - reserve_space_1: A 1D Tensor for the computed batch mean, to be reused +/// in the gradient computation. +/// - reserve_space_2: A 1D Tensor for the computed batch variance (inverted variance +/// in the cuDNN case), to be reused in the gradient computation. @inlinable @inline(__always) public static func fusedBatchNormV2< T: FloatingPoint & TensorFlowScalar, U: FloatingPoint & TensorFlowScalar >( - _ x: Tensor, - scale: Tensor, - offset: Tensor, - mean: Tensor, - variance: Tensor, - epsilon: Double = 0.0001, - dataFormat: DataFormat = .nhwc, - isTraining: Bool = true + _ x: Tensor, + scale: Tensor, + offset: Tensor, + mean: Tensor, + variance: Tensor, + epsilon: Double = 0.0001, + dataFormat: DataFormat = .nhwc, + isTraining: Bool = true ) -> (y: Tensor, batchMean: Tensor, batchVariance: Tensor, reserveSpace1: Tensor, reserveSpace2: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("FusedBatchNormV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("U", U.tensorFlowDataType) - op.updateAttribute("epsilon", epsilon) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("is_training", isTraining) - op.addInput(x) - op.addInput(scale) - op.addInput(offset) - op.addInput(mean) - op.addInput(variance) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("FusedBatchNormV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("U", U.tensorFlowDataType) + op.updateAttribute("epsilon", epsilon) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("is_training", isTraining) + op.addInput(x) + op.addInput(scale) + op.addInput(offset) + op.addInput(mean) + op.addInput(variance) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) } /// Performs a padding as a preprocess during a convolution. @@ -11815,35 +11802,35 @@ public static func fusedBatchNormV2< /// operator is primarily an optimization to minimize memory usage. /// /// - Parameters: -/// - input: 4-D with shape `[batch, in_height, in_width, in_channels]`. -/// - paddings: A two-column matrix specifying the padding sizes. The number of -/// rows must be the same as the rank of `input`. -/// - filter: 4-D with shape -/// `[filter_height, filter_width, in_channels, out_channels]`. +/// - input: 4-D with shape `[batch, in_height, in_width, in_channels]`. +/// - paddings: A two-column matrix specifying the padding sizes. The number of +/// rows must be the same as the rank of `input`. +/// - filter: 4-D with shape +/// `[filter_height, filter_width, in_channels, out_channels]`. /// /// - Attrs: -/// - strides: 1-D of length 4. The stride of the sliding window for each dimension -/// of `input`. Must be in the same order as the dimension specified with format. -/// - padding: The type of padding algorithm to use. +/// - strides: 1-D of length 4. The stride of the sliding window for each dimension +/// of `input`. Must be in the same order as the dimension specified with format. +/// - padding: The type of padding algorithm to use. @inlinable @inline(__always) public static func fusedPadConv2D( - _ input: Tensor, - paddings: Tensor, - filter: Tensor, - mode: Mode5, - strides: [Int32], - padding: Padding + _ input: Tensor, + paddings: Tensor, + filter: Tensor, + mode: Mode5, + strides: [Int32], + padding: Padding ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("FusedPadConv2D", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("mode", mode.cName) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.addInput(input) - op.addInput(paddings) - op.addInput(filter) - return op.execute(Int(1)) + let op = makeOp("FusedPadConv2D", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("mode", mode.cName) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(paddings) + op.addInput(filter) + return op.execute(Int(1)) } /// Performs a resize and padding as a preprocess during a convolution. @@ -11860,43 +11847,43 @@ public static func fusedPadConv2D( /// operator is primarily an optimization to minimize memory usage. /// /// - Parameters: -/// - input: 4-D with shape `[batch, in_height, in_width, in_channels]`. -/// - size: A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The -/// new size for the images. -/// - paddings: A two-column matrix specifying the padding sizes. The number of -/// rows must be the same as the rank of `input`. -/// - filter: 4-D with shape -/// `[filter_height, filter_width, in_channels, out_channels]`. +/// - input: 4-D with shape `[batch, in_height, in_width, in_channels]`. +/// - size: A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The +/// new size for the images. +/// - paddings: A two-column matrix specifying the padding sizes. The number of +/// rows must be the same as the rank of `input`. +/// - filter: 4-D with shape +/// `[filter_height, filter_width, in_channels, out_channels]`. /// /// - Attrs: -/// - resize_align_corners: If true, the centers of the 4 corner pixels of the input and output tensors are -/// aligned, preserving the values at the corner pixels. Defaults to false. -/// - strides: 1-D of length 4. The stride of the sliding window for each dimension -/// of `input`. Must be in the same order as the dimension specified with format. -/// - padding: The type of padding algorithm to use. +/// - resize_align_corners: If true, the centers of the 4 corner pixels of the input and output tensors are +/// aligned, preserving the values at the corner pixels. Defaults to false. +/// - strides: 1-D of length 4. The stride of the sliding window for each dimension +/// of `input`. Must be in the same order as the dimension specified with format. +/// - padding: The type of padding algorithm to use. @inlinable @inline(__always) public static func fusedResizeAndPadConv2D( - _ input: Tensor, - size: Tensor, - paddings: Tensor, - filter: Tensor, - resizeAlignCorners: Bool = false, - mode: Mode5, - strides: [Int32], - padding: Padding -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("FusedResizeAndPadConv2D", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("resize_align_corners", resizeAlignCorners) - op.updateAttribute("mode", mode.cName) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.addInput(input) - op.addInput(size) - op.addInput(paddings) - op.addInput(filter) - return op.execute(Int(1)) + _ input: Tensor, + size: Tensor, + paddings: Tensor, + filter: Tensor, + resizeAlignCorners: Bool = false, + mode: Mode5, + strides: [Int32], + padding: Padding +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("FusedResizeAndPadConv2D", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("resize_align_corners", resizeAlignCorners) + op.updateAttribute("mode", mode.cName) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(size) + op.addInput(paddings) + op.addInput(filter) + return op.execute(Int(1)) } /// Computes the GRU cell forward propagation for 1 time step. @@ -11947,23 +11934,23 @@ public static func fusedResizeAndPadConv2D( /// ``` @inlinable @inline(__always) public static func gRUBlockCell( - _ x: Tensor, - hPrev: Tensor, - wRu: Tensor, - wC: Tensor, - bRu: Tensor, - bC: Tensor + _ x: Tensor, + hPrev: Tensor, + wRu: Tensor, + wC: Tensor, + bRu: Tensor, + bC: Tensor ) -> (r: Tensor, u: Tensor, c: Tensor, h: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("GRUBlockCell", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(hPrev) - op.addInput(wRu) - op.addInput(wC) - op.addInput(bRu) - op.addInput(bC) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("GRUBlockCell", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(hPrev) + op.addInput(wRu) + op.addInput(wC) + op.addInput(bRu) + op.addInput(bC) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Computes the GRU cell back-propagation for 1 time step. @@ -12050,31 +12037,31 @@ public static func gRUBlockCell( /// ``` @inlinable @inline(__always) public static func gRUBlockCellGrad( - _ x: Tensor, - hPrev: Tensor, - wRu: Tensor, - wC: Tensor, - bRu: Tensor, - bC: Tensor, - r: Tensor, - u: Tensor, - c: Tensor, - dH: Tensor + _ x: Tensor, + hPrev: Tensor, + wRu: Tensor, + wC: Tensor, + bRu: Tensor, + bC: Tensor, + r: Tensor, + u: Tensor, + c: Tensor, + dH: Tensor ) -> (dX: Tensor, dHPrev: Tensor, dCBar: Tensor, dRBarUBar: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("GRUBlockCellGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(hPrev) - op.addInput(wRu) - op.addInput(wC) - op.addInput(bRu) - op.addInput(bC) - op.addInput(r) - op.addInput(u) - op.addInput(c) - op.addInput(dH) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("GRUBlockCellGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(hPrev) + op.addInput(wRu) + op.addInput(wC) + op.addInput(bRu) + op.addInput(bC) + op.addInput(r) + op.addInput(u) + op.addInput(c) + op.addInput(dH) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Gather slices from `params` according to `indices`. @@ -12109,18 +12096,18 @@ public static func gather< Tparams: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - params: Tensor, - indices: Tensor, - validateIndices: Bool = true + params: Tensor, + indices: Tensor, + validateIndices: Bool = true ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Gather", nOutputs) - op.updateAttribute("validate_indices", validateIndices) - op.updateAttribute("Tparams", Tparams.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(params) - op.addInput(indices) - return op.execute(Int(1)) + let op = makeOp("Gather", nOutputs) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("Tparams", Tparams.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(params) + op.addInput(indices) + return op.execute(Int(1)) } /// Gather slices from `params` into a Tensor with shape specified by `indices`. @@ -12231,26 +12218,26 @@ public static func gather< /// See also `tf.gather` and `tf.batch_gather`. /// /// - Parameters: -/// - params: The tensor from which to gather values. -/// - indices: Index tensor. +/// - params: The tensor from which to gather values. +/// - indices: Index tensor. /// /// - Output output: Values from `params` gathered from indices given by `indices`, with -/// shape `indices.shape[:-1] + params.shape[indices.shape[-1]:]`. +/// shape `indices.shape[:-1] + params.shape[indices.shape[-1]:]`. @inlinable @inline(__always) public static func gatherNd< Tparams: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - params: Tensor, - indices: Tensor + params: Tensor, + indices: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("GatherNd", nOutputs) - op.updateAttribute("Tparams", Tparams.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(params) - op.addInput(indices) - return op.execute(Int(1)) + let op = makeOp("GatherNd", nOutputs) + op.updateAttribute("Tparams", Tparams.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(params) + op.addInput(indices) + return op.execute(Int(1)) } /// Gather slices from `params` axis `axis` according to `indices`. @@ -12284,33 +12271,33 @@ public static func gatherNd< /// See also `tf.batch_gather` and `tf.gather_nd`. /// /// - Parameters: -/// - params: The tensor from which to gather values. Must be at least rank -/// `axis + 1`. -/// - indices: Index tensor. Must be in range `[0, params.shape[axis])`. -/// - axis: The axis in `params` to gather `indices` from. Defaults to the first -/// dimension. Supports negative indexes. +/// - params: The tensor from which to gather values. Must be at least rank +/// `axis + 1`. +/// - indices: Index tensor. Must be in range `[0, params.shape[axis])`. +/// - axis: The axis in `params` to gather `indices` from. Defaults to the first +/// dimension. Supports negative indexes. /// /// - Output output: Values from `params` gathered from indices given by `indices`, with -/// shape `params.shape[:axis] + indices.shape + params.shape[axis + 1:]`. +/// shape `params.shape[:axis] + indices.shape + params.shape[axis + 1:]`. @inlinable @inline(__always) public static func gatherV2< Tparams: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar, Taxis: BinaryInteger & TensorFlowScalar >( - params: Tensor, - indices: Tensor, - axis: Tensor + params: Tensor, + indices: Tensor, + axis: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("GatherV2", nOutputs) - op.updateAttribute("Tparams", Tparams.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("Taxis", Taxis.tensorFlowDataType) - op.addInput(params) - op.addInput(indices) - op.addInput(axis) - return op.execute(Int(1)) + let op = makeOp("GatherV2", nOutputs) + op.updateAttribute("Tparams", Tparams.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("Taxis", Taxis.tensorFlowDataType) + op.addInput(params) + op.addInput(indices) + op.addInput(axis) + return op.execute(Int(1)) } /// Re-configures the GCS block cache with the new configuration values. @@ -12320,16 +12307,16 @@ public static func gatherV2< /// new block cache is created fresh. @inlinable @inline(__always) public static func gcsConfigureBlockCache( - maxCacheSize: Tensor, - blockSize: Tensor, - maxStaleness: Tensor + maxCacheSize: Tensor, + blockSize: Tensor, + maxStaleness: Tensor ) { let nOutputs = 0 - let op = makeOp("GcsConfigureBlockCache", nOutputs) - op.addInput(maxCacheSize) - op.addInput(blockSize) - op.addInput(maxStaleness) - op.execute() + let op = makeOp("GcsConfigureBlockCache", nOutputs) + op.addInput(maxCacheSize) + op.addInput(blockSize) + op.addInput(maxStaleness) + op.execute() } /// Configures the credentials used by the GCS client of the local TF runtime. @@ -12363,12 +12350,12 @@ public static func gcsConfigureBlockCache( /// or in other ways be persisted or exfiltrated. @inlinable @inline(__always) public static func gcsConfigureCredentials( - json: StringTensor + json: StringTensor ) { let nOutputs = 0 - let op = makeOp("GcsConfigureCredentials", nOutputs) - op.addInput(json) - op.execute() + let op = makeOp("GcsConfigureCredentials", nOutputs) + op.addInput(json) + op.execute() } /// Generates serialized partition messages suitable for batch reads. @@ -12377,37 +12364,37 @@ public static func gcsConfigureCredentials( /// bigquery_reader_ops.py file defines a clean interface to the reader. /// /// - Attrs: -/// - project_id: GCP project ID. -/// - dataset_id: BigQuery Dataset ID. -/// - table_id: Table to read. -/// - columns: List of columns to read. Leave empty to read all columns. -/// - timestamp_millis: Table snapshot timestamp in millis since epoch. Relative -/// (negative or zero) snapshot times are not allowed. For more details, see -/// 'Table Decorators' in BigQuery docs. -/// - num_partitions: Number of partitions to split the table into. -/// - test_end_point: Do not use. For testing purposes only. +/// - project_id: GCP project ID. +/// - dataset_id: BigQuery Dataset ID. +/// - table_id: Table to read. +/// - columns: List of columns to read. Leave empty to read all columns. +/// - timestamp_millis: Table snapshot timestamp in millis since epoch. Relative +/// (negative or zero) snapshot times are not allowed. For more details, see +/// 'Table Decorators' in BigQuery docs. +/// - num_partitions: Number of partitions to split the table into. +/// - test_end_point: Do not use. For testing purposes only. /// /// - Output partitions: Serialized table partitions. @inlinable @inline(__always) public static func generateBigQueryReaderPartitions( - projectId: String, - datasetId: String, - tableId: String, - columns: [String], - timestampMillis: Int64, - numPartitions: Int64, - testEndPoint: String + projectId: String, + datasetId: String, + tableId: String, + columns: [String], + timestampMillis: Int64, + numPartitions: Int64, + testEndPoint: String ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("GenerateBigQueryReaderPartitions", nOutputs) - op.updateAttribute("project_id", projectId) - op.updateAttribute("dataset_id", datasetId) - op.updateAttribute("table_id", tableId) - op.updateAttribute("columns", columns) - op.updateAttribute("timestamp_millis", timestampMillis) - op.updateAttribute("num_partitions", numPartitions) - op.updateAttribute("test_end_point", testEndPoint) - return op.execute(Int(1)) + let op = makeOp("GenerateBigQueryReaderPartitions", nOutputs) + op.updateAttribute("project_id", projectId) + op.updateAttribute("dataset_id", datasetId) + op.updateAttribute("table_id", tableId) + op.updateAttribute("columns", columns) + op.updateAttribute("timestamp_millis", timestampMillis) + op.updateAttribute("num_partitions", numPartitions) + op.updateAttribute("test_end_point", testEndPoint) + return op.execute(Int(1)) } /// Given a path to new and old vocabulary files, returns a remapping Tensor of @@ -12442,36 +12429,36 @@ public static func generateBigQueryReaderPartitions( /// does (as opposed to tf.feature_to_id(), which uses a CuckooTable). /// /// - Parameters: -/// - new_vocab_file: Path to the new vocab file. -/// - old_vocab_file: Path to the old vocab file. +/// - new_vocab_file: Path to the new vocab file. +/// - old_vocab_file: Path to the old vocab file. /// /// - Attrs: -/// - new_vocab_offset: How many entries into the new vocab file to start reading. -/// - num_new_vocab: Number of entries in the new vocab file to remap. -/// - old_vocab_size: Number of entries in the old vocab file to consider. If -1, -/// use the entire old vocabulary. +/// - new_vocab_offset: How many entries into the new vocab file to start reading. +/// - num_new_vocab: Number of entries in the new vocab file to remap. +/// - old_vocab_size: Number of entries in the old vocab file to consider. If -1, +/// use the entire old vocabulary. /// /// - Outputs: -/// - remapping: A Tensor of length num_new_vocab where the element at index i -/// is equal to the old ID that maps to the new ID i. This element is -1 for any -/// new ID that is not found in the old vocabulary. -/// - num_present: Number of new vocab entries found in old vocab. +/// - remapping: A Tensor of length num_new_vocab where the element at index i +/// is equal to the old ID that maps to the new ID i. This element is -1 for any +/// new ID that is not found in the old vocabulary. +/// - num_present: Number of new vocab entries found in old vocab. @inlinable @inline(__always) public static func generateVocabRemapping( - newVocabFile: StringTensor, - oldVocabFile: StringTensor, - newVocabOffset: Int64, - numNewVocab: Int64, - oldVocabSize: Int64 = -1 + newVocabFile: StringTensor, + oldVocabFile: StringTensor, + newVocabOffset: Int64, + numNewVocab: Int64, + oldVocabSize: Int64 = -1 ) -> (remapping: Tensor, numPresent: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("GenerateVocabRemapping", nOutputs) - op.updateAttribute("new_vocab_offset", newVocabOffset) - op.updateAttribute("num_new_vocab", numNewVocab) - op.updateAttribute("old_vocab_size", oldVocabSize) - op.addInput(newVocabFile) - op.addInput(oldVocabFile) - return op.execute(Int(1), Int(1)) + let op = makeOp("GenerateVocabRemapping", nOutputs) + op.updateAttribute("new_vocab_offset", newVocabOffset) + op.updateAttribute("num_new_vocab", numNewVocab) + op.updateAttribute("old_vocab_size", oldVocabSize) + op.addInput(newVocabFile) + op.addInput(oldVocabFile) + return op.execute(Int(1), Int(1)) } /// Creates a dataset that invokes a function to generate elements. @@ -12487,29 +12474,29 @@ public static func generatorDataset< TnextFuncArgs: TensorArrayProtocol, TfinalizeFuncArgs: TensorArrayProtocol >( - initFuncOtherArgs: TinitFuncArgs, - nextFuncOtherArgs: TnextFuncArgs, - finalizeFuncOtherArgs: TfinalizeFuncArgs, - initFunc: (InitfuncIn) -> InitfuncOut, - nextFunc: (NextfuncIn) -> NextfuncOut, - finalizeFunc: (FinalizefuncIn) -> FinalizefuncOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + initFuncOtherArgs: TinitFuncArgs, + nextFuncOtherArgs: TnextFuncArgs, + finalizeFuncOtherArgs: TfinalizeFuncArgs, + initFunc: (InitfuncIn) -> InitfuncOut, + nextFunc: (NextfuncIn) -> NextfuncOut, + finalizeFunc: (FinalizefuncIn) -> FinalizefuncOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("GeneratorDataset", nOutputs) - op.updateAttribute("init_func", initFunc) - op.updateAttribute("next_func", nextFunc) - op.updateAttribute("finalize_func", finalizeFunc) - op.updateAttribute("Tinit_func_args", initFuncOtherArgs._typeList) - op.updateAttribute("Tnext_func_args", nextFuncOtherArgs._typeList) - op.updateAttribute("Tfinalize_func_args", finalizeFuncOtherArgs._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInputList(initFuncOtherArgs) - op.addInputList(nextFuncOtherArgs) - op.addInputList(finalizeFuncOtherArgs) - return op.execute(Int(1)) + let op = makeOp("GeneratorDataset", nOutputs) + op.updateAttribute("init_func", initFunc) + op.updateAttribute("next_func", nextFunc) + op.updateAttribute("finalize_func", finalizeFunc) + op.updateAttribute("Tinit_func_args", initFuncOtherArgs._typeList) + op.updateAttribute("Tnext_func_args", nextFuncOtherArgs._typeList) + op.updateAttribute("Tfinalize_func_args", finalizeFuncOtherArgs._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInputList(initFuncOtherArgs) + op.addInputList(nextFuncOtherArgs) + op.addInputList(finalizeFuncOtherArgs) + return op.execute(Int(1)) } /// Store the input tensor in the state of the current session. @@ -12517,16 +12504,16 @@ public static func generatorDataset< /// - Parameter value: The tensor to be stored. /// /// - Output handle: The handle for the tensor stored in the session state, represented -/// as a string. +/// as a string. @inlinable @inline(__always) public static func getSessionHandle( - value: Tensor + value: Tensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("GetSessionHandle", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(value) - return op.execute(Int(1)) + let op = makeOp("GetSessionHandle", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + return op.execute(Int(1)) } /// Store the input tensor in the state of the current session. @@ -12534,16 +12521,16 @@ public static func getSessionHandle( /// - Parameter value: The tensor to be stored. /// /// - Output handle: The handle for the tensor stored in the session state, represented -/// as a ResourceHandle object. +/// as a ResourceHandle object. @inlinable @inline(__always) public static func getSessionHandleV2( - value: Tensor + value: Tensor ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("GetSessionHandleV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(value) - return op.execute(Int(1)) + let op = makeOp("GetSessionHandleV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + return op.execute(Int(1)) } /// Get the value of the tensor specified by its handle. @@ -12555,22 +12542,22 @@ public static func getSessionHandleV2( /// - Output value: The tensor for the given handle. @inlinable @inline(__always) public static func getSessionTensor( - handle: StringTensor + handle: StringTensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("GetSessionTensor", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(handle) - return op.execute(Int(1)) + let op = makeOp("GetSessionTensor", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(handle) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func graphDefVersion( ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("GraphDefVersion", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("GraphDefVersion", nOutputs) + + return op.execute(Int(1)) } /// Returns the truth value of (x > y) element-wise. @@ -12579,15 +12566,15 @@ public static func graphDefVersion( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func greater( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Greater", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Greater", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns the truth value of (x >= y) element-wise. @@ -12596,15 +12583,15 @@ public static func greater( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func greaterEqual( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("GreaterEqual", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("GreaterEqual", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Gives a guarantee to the TF runtime that the input tensor is a constant. @@ -12617,13 +12604,13 @@ public static func greaterEqual( /// Returns the input tensor without modification. @inlinable @inline(__always) public static func guaranteeConst( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("GuaranteeConst", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("GuaranteeConst", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Convert one or more images from HSV to RGB. @@ -12639,13 +12626,13 @@ public static func guaranteeConst( /// - Output output: `images` converted to RGB. @inlinable @inline(__always) public static func hSVToRGB( - images: Tensor + images: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("HSVToRGB", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(images) - return op.execute(Int(1)) + let op = makeOp("HSVToRGB", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + return op.execute(Int(1)) } /// Creates a non-initialized hash table. @@ -12655,32 +12642,32 @@ public static func hSVToRGB( /// table will be immutable. /// /// - Attrs: -/// - container: If non-empty, this table is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this table is shared under the given name across -/// multiple sessions. -/// - use_node_name_sharing: If true and shared_name is empty, the table is shared -/// using the node name. -/// - key_dtype: Type of the table keys. -/// - value_dtype: Type of the table values. +/// - container: If non-empty, this table is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this table is shared under the given name across +/// multiple sessions. +/// - use_node_name_sharing: If true and shared_name is empty, the table is shared +/// using the node name. +/// - key_dtype: Type of the table keys. +/// - value_dtype: Type of the table values. /// /// - Output table_handle: Handle to a table. @inlinable @inline(__always) public static func hashTableV2( - container: String, - sharedName: String, - useNodeNameSharing: Bool = false, - keyDtype: TensorDataType, - valueDtype: TensorDataType + container: String, + sharedName: String, + useNodeNameSharing: Bool = false, + keyDtype: TensorDataType, + valueDtype: TensorDataType ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("HashTableV2", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("use_node_name_sharing", useNodeNameSharing) - op.updateAttribute("key_dtype", keyDtype) - op.updateAttribute("value_dtype", valueDtype) - return op.execute(Int(1)) + let op = makeOp("HashTableV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("use_node_name_sharing", useNodeNameSharing) + op.updateAttribute("key_dtype", keyDtype) + op.updateAttribute("value_dtype", valueDtype) + return op.execute(Int(1)) } /// Return histogram of values. @@ -12702,11 +12689,11 @@ public static func hashTableV2( /// ``` /// /// - Parameters: -/// - values: Numeric `Tensor`. -/// - value_range: Shape [2] `Tensor` of same `dtype` as `values`. -/// values <= value_range[0] will be mapped to hist[0], -/// values >= value_range[1] will be mapped to hist[-1]. -/// - nbins: Scalar `int32 Tensor`. Number of histogram bins. +/// - values: Numeric `Tensor`. +/// - value_range: Shape [2] `Tensor` of same `dtype` as `values`. +/// values <= value_range[0] will be mapped to hist[0], +/// values >= value_range[1] will be mapped to hist[-1]. +/// - nbins: Scalar `int32 Tensor`. Number of histogram bins. /// /// - Output out: A 1-D `Tensor` holding histogram of values. @inlinable @inline(__always) @@ -12714,18 +12701,18 @@ public static func histogramFixedWidth< T: Numeric & TensorFlowScalar, Dtype: BinaryInteger & TensorFlowScalar >( - _ values: Tensor, - valueRange: Tensor, - nbins: Tensor + _ values: Tensor, + valueRange: Tensor, + nbins: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("HistogramFixedWidth", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(values) - op.addInput(valueRange) - op.addInput(nbins) - return op.execute(Int(1)) + let op = makeOp("HistogramFixedWidth", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(values) + op.addInput(valueRange) + op.addInput(nbins) + return op.execute(Int(1)) } /// Outputs a `Summary` protocol buffer with a histogram. @@ -12737,21 +12724,21 @@ public static func histogramFixedWidth< /// This op reports an `InvalidArgument` error if any value is not finite. /// /// - Parameters: -/// - tag: Scalar. Tag to use for the `Summary.Value`. -/// - values: Any shape. Values to use to build the histogram. +/// - tag: Scalar. Tag to use for the `Summary.Value`. +/// - values: Any shape. Values to use to build the histogram. /// /// - Output summary: Scalar. Serialized `Summary` protocol buffer. @inlinable @inline(__always) public static func histogramSummary( - tag: StringTensor, - _ values: Tensor + tag: StringTensor, + _ values: Tensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("HistogramSummary", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(tag) - op.addInput(values) - return op.execute(Int(1)) + let op = makeOp("HistogramSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(tag) + op.addInput(values) + return op.execute(Int(1)) } /// Inverse fast Fourier transform. @@ -12762,20 +12749,20 @@ public static func histogramSummary( /// - Parameter input: A complex tensor. /// /// - Output output: A complex tensor of the same shape as `input`. The inner-most -/// dimension of `input` is replaced with its inverse 1D Fourier transform. +/// dimension of `input` is replaced with its inverse 1D Fourier transform. /// -/// @compatibility(numpy) -/// Equivalent to np.fft.ifft -/// @end_compatibility +/// @compatibility(numpy) +/// Equivalent to np.fft.ifft +/// @end_compatibility @inlinable @inline(__always) public static func iFFT( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("IFFT", nOutputs) - op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("IFFT", nOutputs) + op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Inverse 2D fast Fourier transform. @@ -12786,20 +12773,20 @@ public static func iFFT( /// - Parameter input: A complex tensor. /// /// - Output output: A complex tensor of the same shape as `input`. The inner-most 2 -/// dimensions of `input` are replaced with their inverse 2D Fourier transform. +/// dimensions of `input` are replaced with their inverse 2D Fourier transform. /// -/// @compatibility(numpy) -/// Equivalent to np.fft.ifft2 -/// @end_compatibility +/// @compatibility(numpy) +/// Equivalent to np.fft.ifft2 +/// @end_compatibility @inlinable @inline(__always) public static func iFFT2D( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("IFFT2D", nOutputs) - op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("IFFT2D", nOutputs) + op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Inverse 3D fast Fourier transform. @@ -12810,32 +12797,32 @@ public static func iFFT2D( /// - Parameter input: A complex64 tensor. /// /// - Output output: A complex64 tensor of the same shape as `input`. The inner-most 3 -/// dimensions of `input` are replaced with their inverse 3D Fourier transform. +/// dimensions of `input` are replaced with their inverse 3D Fourier transform. /// -/// @compatibility(numpy) -/// Equivalent to np.fft.ifftn with 3 dimensions. -/// @end_compatibility +/// @compatibility(numpy) +/// Equivalent to np.fft.ifftn with 3 dimensions. +/// @end_compatibility @inlinable @inline(__always) public static func iFFT3D( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("IFFT3D", nOutputs) - op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("IFFT3D", nOutputs) + op.updateAttribute("Tcomplex", Tcomplex.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Return a tensor with the same shape and contents as the input tensor or value. @inlinable @inline(__always) public static func identity( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Identity", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Identity", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Returns a list of tensors with the same shapes and contents as the input @@ -12857,13 +12844,13 @@ public static func identity( /// ``` @inlinable @inline(__always) public static func identityN( - _ input: T + _ input: T ) -> T { let nOutputs = Int(input._typeList.count) - let op = makeOp("IdentityN", nOutputs) - op.updateAttribute("T", input._typeList) - op.addInputList(input) - return op.execute(Int(input._typeList.count)) + let op = makeOp("IdentityN", nOutputs) + op.updateAttribute("T", input._typeList) + op.addInputList(input) + return op.execute(Int(input._typeList.count)) } /// A Reader that outputs the queued work as both the key and value. @@ -12872,42 +12859,42 @@ public static func identityN( /// work string and output (work, work). /// /// - Attrs: -/// - container: If non-empty, this reader is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this reader is named in the given bucket -/// with this shared_name. Otherwise, the node name is used instead. +/// - container: If non-empty, this reader is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this reader is named in the given bucket +/// with this shared_name. Otherwise, the node name is used instead. /// /// - Output reader_handle: The handle to reference the Reader. @inlinable @inline(__always) public static func identityReaderV2( - container: String, - sharedName: String + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("IdentityReaderV2", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("IdentityReaderV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// output = cond ? then_branch(input) : else_branch(input) /// /// - Parameters: -/// - cond: A Tensor. If the tensor is a scalar of non-boolean type, the -/// scalar is converted to a boolean according to the -/// following rule: if the scalar is a numerical value, non-zero means -/// `True` and zero means False; if the scalar is a string, non-empty -/// means `True` and empty means `False`. If the tensor is not a scalar, -/// being empty means False and being non-empty means True. -/// - input: A list of input tensors. +/// - cond: A Tensor. If the tensor is a scalar of non-boolean type, the +/// scalar is converted to a boolean according to the +/// following rule: if the scalar is a numerical value, non-zero means +/// `True` and zero means False; if the scalar is a string, non-empty +/// means `True` and empty means `False`. If the tensor is not a scalar, +/// being empty means False and being non-empty means True. +/// - input: A list of input tensors. /// /// - Attrs: -/// - Tin: A list of input types. -/// - Tout: A list of output types. -/// - then_branch: A function that takes 'inputs' and returns a list of tensors, whose -/// types are the same as what else_branch returns. -/// - else_branch: A function that takes 'inputs' and returns a list of tensors, whose -/// types are the same as what then_branch returns. +/// - Tin: A list of input types. +/// - Tout: A list of output types. +/// - then_branch: A function that takes 'inputs' and returns a list of tensors, whose +/// types are the same as what else_branch returns. +/// - else_branch: A function that takes 'inputs' and returns a list of tensors, whose +/// types are the same as what then_branch returns. /// /// - Output output: A list of return values. @inlinable @inline(__always) @@ -12920,23 +12907,23 @@ public static func if_< ElsebranchIn: TensorGroup, ElsebranchOut: TensorGroup >( - cond: Tensor, - _ input: Tin, - thenBranch: (ThenbranchIn) -> ThenbranchOut, - elseBranch: (ElsebranchIn) -> ElsebranchOut, - outputShapes: [TensorShape?] + cond: Tensor, + _ input: Tin, + thenBranch: (ThenbranchIn) -> ThenbranchOut, + elseBranch: (ElsebranchIn) -> ElsebranchOut, + outputShapes: [TensorShape?] ) -> Tout { let nOutputs = Int(Tout._typeList.count) - let op = makeOp("If", nOutputs) - op.updateAttribute("Tcond", Tcond.tensorFlowDataType) - op.updateAttribute("Tin", input._typeList) - op.updateAttribute("Tout", Tout._typeList) - op.updateAttribute("then_branch", thenBranch) - op.updateAttribute("else_branch", elseBranch) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(cond) - op.addInputList(input) - return op.execute(Int(Tout._typeList.count)) + let op = makeOp("If", nOutputs) + op.updateAttribute("Tcond", Tcond.tensorFlowDataType) + op.updateAttribute("Tin", input._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("then_branch", thenBranch) + op.updateAttribute("else_branch", elseBranch) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(cond) + op.addInputList(input) + return op.execute(Int(Tout._typeList.count)) } /// Compute the lower regularized incomplete Gamma function `P(a, x)`. @@ -12956,29 +12943,29 @@ public static func if_< /// Gamma function. @inlinable @inline(__always) public static func igamma( - _ a: Tensor, - _ x: Tensor + _ a: Tensor, + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Igamma", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Igamma", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the gradient of `igamma(a, x)` wrt `a`. @inlinable @inline(__always) public static func igammaGradA( - _ a: Tensor, - _ x: Tensor + _ a: Tensor, + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("IgammaGradA", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("IgammaGradA", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(x) + return op.execute(Int(1)) } /// Compute the upper regularized incomplete Gamma function `Q(a, x)`. @@ -12997,15 +12984,15 @@ public static func igammaGradA( /// Gamma function. @inlinable @inline(__always) public static func igammac( - _ a: Tensor, - _ x: Tensor + _ a: Tensor, + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Igammac", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Igammac", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(x) + return op.execute(Int(1)) } /// Returns the imaginary part of a complex number. @@ -13026,14 +13013,14 @@ public static func imag< T: TensorFlowScalar, Tout: FloatingPoint & TensorFlowScalar >( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Imag", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tout", Tout.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Imag", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Returns immutable tensor from memory region. @@ -13041,48 +13028,48 @@ public static func imag< /// The current implementation memmaps the tensor from a file. /// /// - Attrs: -/// - dtype: Type of the returned tensor. -/// - shape: Shape of the returned tensor. -/// - memory_region_name: Name of readonly memory region used by the tensor, see -/// NewReadOnlyMemoryRegionFromFile in tensorflow::Env. +/// - dtype: Type of the returned tensor. +/// - shape: Shape of the returned tensor. +/// - memory_region_name: Name of readonly memory region used by the tensor, see +/// NewReadOnlyMemoryRegionFromFile in tensorflow::Env. @inlinable @inline(__always) public static func immutableConst( - shape: TensorShape?, - memoryRegionName: String + shape: TensorShape?, + memoryRegionName: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ImmutableConst", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape", shape) - op.updateAttribute("memory_region_name", memoryRegionName) - return op.execute(Int(1)) + let op = makeOp("ImmutableConst", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.updateAttribute("memory_region_name", memoryRegionName) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func importEvent( - writer: ResourceHandle, - event: StringTensor + writer: ResourceHandle, + event: StringTensor ) { let nOutputs = 0 - let op = makeOp("ImportEvent", nOutputs) - op.addInput(writer) - op.addInput(event) - op.execute() + let op = makeOp("ImportEvent", nOutputs) + op.addInput(writer) + op.addInput(event) + op.execute() } @inlinable @inline(__always) public static func inPolymorphicTwice( - _ a: [Tensor], - _ b: [Tensor] + _ a: [Tensor], + _ b: [Tensor] ) { let nOutputs = 0 - let op = makeOp("InPolymorphicTwice", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("N", a.count) - op.updateAttribute("M", b.count) - op.addInputList(a) - op.addInputList(b) - op.execute() + let op = makeOp("InPolymorphicTwice", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", a.count) + op.updateAttribute("M", b.count) + op.addInputList(a) + op.addInputList(b) + op.execute() } /// Says whether the targets are in the top `K` predictions. @@ -13103,25 +13090,25 @@ public static func inPolymorphicTwice( /// $$out_i = predictions_{i, targets_i} \in TopKIncludingTies(predictions_i)$$ /// /// - Parameters: -/// - predictions: A `batch_size` x `classes` tensor. -/// - targets: A `batch_size` vector of class ids. +/// - predictions: A `batch_size` x `classes` tensor. +/// - targets: A `batch_size` vector of class ids. /// /// - Attr k: Number of top elements to look at for computing precision. /// /// - Output precision: Computed Precision at `k` as a `bool Tensor`. @inlinable @inline(__always) public static func inTopK( - predictions: Tensor, - targets: Tensor, - k: Int64 + predictions: Tensor, + targets: Tensor, + k: Int64 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("InTopK", nOutputs) - op.updateAttribute("k", k) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(predictions) - op.addInput(targets) - return op.execute(Int(1)) + let op = makeOp("InTopK", nOutputs) + op.updateAttribute("k", k) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(predictions) + op.addInput(targets) + return op.execute(Int(1)) } /// Says whether the targets are in the top `K` predictions. @@ -13142,60 +13129,60 @@ public static func inTopK( /// $$out_i = predictions_{i, targets_i} \in TopKIncludingTies(predictions_i)$$ /// /// - Parameters: -/// - predictions: A `batch_size` x `classes` tensor. -/// - targets: A `batch_size` vector of class ids. -/// - k: Number of top elements to look at for computing precision. +/// - predictions: A `batch_size` x `classes` tensor. +/// - targets: A `batch_size` vector of class ids. +/// - k: Number of top elements to look at for computing precision. /// /// - Output precision: Computed precision at `k` as a `bool Tensor`. @inlinable @inline(__always) public static func inTopKV2( - predictions: Tensor, - targets: Tensor, - k: Tensor + predictions: Tensor, + targets: Tensor, + k: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("InTopKV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(predictions) - op.addInput(targets) - op.addInput(k) - return op.execute(Int(1)) + let op = makeOp("InTopKV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(predictions) + op.addInput(targets) + op.addInput(k) + return op.execute(Int(1)) } /// A placeholder op for a value that will be fed into the computation. /// /// - Attrs: -/// - dtype: The type of elements in the tensor. -/// - shape: The shape of the tensor. +/// - dtype: The type of elements in the tensor. +/// - shape: The shape of the tensor. /// /// - Output output: A tensor that will be provided using the infeed mechanism. @inlinable @inline(__always) public static func infeedDequeue( - shape: TensorShape? + shape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("InfeedDequeue", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape", shape) - return op.execute(Int(1)) + let op = makeOp("InfeedDequeue", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + return op.execute(Int(1)) } /// Fetches multiple values from infeed as an XLA tuple. /// /// - Attrs: -/// - dtypes: The element types of each element in `outputs`. -/// - shapes: The shapes of each tensor in `outputs`. +/// - dtypes: The element types of each element in `outputs`. +/// - shapes: The shapes of each tensor in `outputs`. /// /// - Output outputs: A list of tensors that will be provided using the infeed mechanism. @inlinable @inline(__always) public static func infeedDequeueTuple( - shapes: [TensorShape?] + shapes: [TensorShape?] ) -> Dtypes { let nOutputs = Int(Dtypes._typeList.count) - let op = makeOp("InfeedDequeueTuple", nOutputs) - op.updateAttribute("dtypes", Dtypes._typeList) - op.updateAttribute("shapes", shapes) - return op.execute(Int(Dtypes._typeList.count)) + let op = makeOp("InfeedDequeueTuple", nOutputs) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("shapes", shapes) + return op.execute(Int(Dtypes._typeList.count)) } /// An op which feeds a single Tensor value into the computation. @@ -13203,29 +13190,29 @@ public static func infeedDequeueTuple( /// - Parameter input: A tensor that will be provided using the infeed mechanism. /// /// - Attrs: -/// - dtype: The type of elements in the tensor. -/// - shape: The shape of the tensor. -/// - layout: A vector holding the requested layout in minor-to-major sequence. -/// If a layout attribute is passed, but its values are all -1, the layout will -/// be computed by the infeed operation. -/// - device_ordinal: The TPU device to use. This should be -1 when the Op -/// is running on a TPU device, and >= 0 when the Op is running on the CPU -/// device. +/// - dtype: The type of elements in the tensor. +/// - shape: The shape of the tensor. +/// - layout: A vector holding the requested layout in minor-to-major sequence. +/// If a layout attribute is passed, but its values are all -1, the layout will +/// be computed by the infeed operation. +/// - device_ordinal: The TPU device to use. This should be -1 when the Op +/// is running on a TPU device, and >= 0 when the Op is running on the CPU +/// device. @inlinable @inline(__always) public static func infeedEnqueue( - _ input: Tensor, - shape: TensorShape?, - layout: [Int32], - deviceOrdinal: Int64 = -1 + _ input: Tensor, + shape: TensorShape?, + layout: [Int32], + deviceOrdinal: Int64 = -1 ) { let nOutputs = 0 - let op = makeOp("InfeedEnqueue", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape", shape) - op.updateAttribute("layout", layout) - op.updateAttribute("device_ordinal", deviceOrdinal) - op.addInput(input) - op.execute() + let op = makeOp("InfeedEnqueue", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.updateAttribute("layout", layout) + op.updateAttribute("device_ordinal", deviceOrdinal) + op.addInput(input) + op.execute() } /// An op which enqueues prelinearized buffer into TPU infeed. @@ -13233,17 +13220,17 @@ public static func infeedEnqueue( /// - Parameter input: A variant tensor representing linearized output. /// /// - Attr device_ordinal: The TPU device to use. This should be -1 when the Op is running on a TPU device -/// and = 0 when the Op is running on the CPU device. +/// and = 0 when the Op is running on the CPU device. @inlinable @inline(__always) public static func infeedEnqueuePrelinearizedBuffer( - _ input: VariantHandle, - deviceOrdinal: Int64 = -1 + _ input: VariantHandle, + deviceOrdinal: Int64 = -1 ) { let nOutputs = 0 - let op = makeOp("InfeedEnqueuePrelinearizedBuffer", nOutputs) - op.updateAttribute("device_ordinal", deviceOrdinal) - op.addInput(input) - op.execute() + let op = makeOp("InfeedEnqueuePrelinearizedBuffer", nOutputs) + op.updateAttribute("device_ordinal", deviceOrdinal) + op.addInput(input) + op.execute() } /// Feeds multiple Tensor values into the computation as an XLA tuple. @@ -13251,30 +13238,30 @@ public static func infeedEnqueuePrelinearizedBuffer( /// - Parameter inputs: A list of tensors that will be provided using the infeed mechanism. /// /// - Attrs: -/// - dtypes: The element types of each element in `inputs`. -/// - shapes: The shapes of each tensor in `inputs`. -/// - layouts: A vector holding the requested layout in minor-to-major sequence for -/// all the tuple shapes, in the order the shapes appear in the "shapes" input. -/// The layout elements for a sub-shape can be set to -1, in which case the -/// corresponding layout will be computed by the infeed operation. -/// - device_ordinal: The TPU device to use. This should be -1 when the Op -/// is running on a TPU device, and >= 0 when the Op is running on the CPU -/// device. +/// - dtypes: The element types of each element in `inputs`. +/// - shapes: The shapes of each tensor in `inputs`. +/// - layouts: A vector holding the requested layout in minor-to-major sequence for +/// all the tuple shapes, in the order the shapes appear in the "shapes" input. +/// The layout elements for a sub-shape can be set to -1, in which case the +/// corresponding layout will be computed by the infeed operation. +/// - device_ordinal: The TPU device to use. This should be -1 when the Op +/// is running on a TPU device, and >= 0 when the Op is running on the CPU +/// device. @inlinable @inline(__always) public static func infeedEnqueueTuple( - inputs: Dtypes, - shapes: [TensorShape?], - layouts: [Int32], - deviceOrdinal: Int64 = -1 + inputs: Dtypes, + shapes: [TensorShape?], + layouts: [Int32], + deviceOrdinal: Int64 = -1 ) { let nOutputs = 0 - let op = makeOp("InfeedEnqueueTuple", nOutputs) - op.updateAttribute("dtypes", inputs._typeList) - op.updateAttribute("shapes", shapes) - op.updateAttribute("layouts", layouts) - op.updateAttribute("device_ordinal", deviceOrdinal) - op.addInputList(inputs) - op.execute() + let op = makeOp("InfeedEnqueueTuple", nOutputs) + op.updateAttribute("dtypes", inputs._typeList) + op.updateAttribute("shapes", shapes) + op.updateAttribute("layouts", layouts) + op.updateAttribute("device_ordinal", deviceOrdinal) + op.addInputList(inputs) + op.execute() } /// Initializes a table from a text file. @@ -13291,58 +13278,58 @@ public static func infeedEnqueueTuple( /// on `delimiter`. /// /// - Parameters: -/// - table_handle: Handle to a table which will be initialized. -/// - filename: Filename of a vocabulary text file. +/// - table_handle: Handle to a table which will be initialized. +/// - filename: Filename of a vocabulary text file. /// /// - Attrs: -/// - key_index: Column index in a line to get the table `key` values from. -/// - value_index: Column index that represents information of a line to get the table -/// `value` values from. -/// - vocab_size: Number of elements of the file, use -1 if unknown. -/// - delimiter: Delimiter to separate fields in a line. +/// - key_index: Column index in a line to get the table `key` values from. +/// - value_index: Column index that represents information of a line to get the table +/// `value` values from. +/// - vocab_size: Number of elements of the file, use -1 if unknown. +/// - delimiter: Delimiter to separate fields in a line. @inlinable @inline(__always) public static func initializeTableFromTextFileV2( - tableHandle: ResourceHandle, - filename: StringTensor, - keyIndex: Int64, - valueIndex: Int64, - vocabSize: Int64 = -1, - delimiter: String = "\t" + tableHandle: ResourceHandle, + filename: StringTensor, + keyIndex: Int64, + valueIndex: Int64, + vocabSize: Int64 = -1, + delimiter: String = "\t" ) { let nOutputs = 0 - let op = makeOp("InitializeTableFromTextFileV2", nOutputs) - op.updateAttribute("key_index", keyIndex) - op.updateAttribute("value_index", valueIndex) - op.updateAttribute("vocab_size", vocabSize) - op.updateAttribute("delimiter", delimiter) - op.addInput(tableHandle) - op.addInput(filename) - op.execute() + let op = makeOp("InitializeTableFromTextFileV2", nOutputs) + op.updateAttribute("key_index", keyIndex) + op.updateAttribute("value_index", valueIndex) + op.updateAttribute("vocab_size", vocabSize) + op.updateAttribute("delimiter", delimiter) + op.addInput(tableHandle) + op.addInput(filename) + op.execute() } /// Table initializer that takes two tensors for keys and values respectively. /// /// - Parameters: -/// - table_handle: Handle to a table which will be initialized. -/// - keys: Keys of type Tkey. -/// - values: Values of type Tval. +/// - table_handle: Handle to a table which will be initialized. +/// - keys: Keys of type Tkey. +/// - values: Values of type Tval. @inlinable @inline(__always) public static func initializeTableV2< Tkey: TensorFlowScalar, Tval: TensorFlowScalar >( - tableHandle: ResourceHandle, - keys: Tensor, - _ values: Tensor + tableHandle: ResourceHandle, + keys: Tensor, + _ values: Tensor ) { let nOutputs = 0 - let op = makeOp("InitializeTableV2", nOutputs) - op.updateAttribute("Tkey", Tkey.tensorFlowDataType) - op.updateAttribute("Tval", Tval.tensorFlowDataType) - op.addInput(tableHandle) - op.addInput(keys) - op.addInput(values) - op.execute() + let op = makeOp("InitializeTableV2", nOutputs) + op.updateAttribute("Tkey", Tkey.tensorFlowDataType) + op.updateAttribute("Tval", Tval.tensorFlowDataType) + op.addInput(tableHandle) + op.addInput(keys) + op.addInput(values) + op.execute() } /// Adds v into specified rows of x. @@ -13350,24 +13337,24 @@ public static func initializeTableV2< /// Computes y = x; y[i, :] += v; return y. /// /// - Parameters: -/// - x: A `Tensor` of type T. -/// - i: A vector. Indices into the left-most dimension of `x`. -/// - v: A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. +/// - x: A `Tensor` of type T. +/// - i: A vector. Indices into the left-most dimension of `x`. +/// - v: A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. /// /// - Output y: A `Tensor` of type T. An alias of `x`. The content of `y` is undefined if there are duplicates in `i`. @inlinable @inline(__always) public static func inplaceAdd( - _ x: Tensor, - i: Tensor, - v: Tensor + _ x: Tensor, + i: Tensor, + v: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("InplaceAdd", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(i) - op.addInput(v) - return op.execute(Int(1)) + let op = makeOp("InplaceAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(i) + op.addInput(v) + return op.execute(Int(1)) } /// Subtracts `v` into specified rows of `x`. @@ -13375,24 +13362,24 @@ public static func inplaceAdd( /// Computes y = x; y[i, :] -= v; return y. /// /// - Parameters: -/// - x: A `Tensor` of type T. -/// - i: A vector. Indices into the left-most dimension of `x`. -/// - v: A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. +/// - x: A `Tensor` of type T. +/// - i: A vector. Indices into the left-most dimension of `x`. +/// - v: A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. /// /// - Output y: A `Tensor` of type T. An alias of `x`. The content of `y` is undefined if there are duplicates in `i`. @inlinable @inline(__always) public static func inplaceSub( - _ x: Tensor, - i: Tensor, - v: Tensor + _ x: Tensor, + i: Tensor, + v: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("InplaceSub", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(i) - op.addInput(v) - return op.execute(Int(1)) + let op = makeOp("InplaceSub", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(i) + op.addInput(v) + return op.execute(Int(1)) } /// Updates specified rows with values in `v`. @@ -13400,93 +13387,93 @@ public static func inplaceSub( /// Computes `x[i, :] = v; return x`. /// /// - Parameters: -/// - x: A tensor of type `T`. -/// - i: A vector. Indices into the left-most dimension of `x`. -/// - v: A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. +/// - x: A tensor of type `T`. +/// - i: A vector. Indices into the left-most dimension of `x`. +/// - v: A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. /// /// - Output y: A `Tensor` of type T. An alias of `x`. The content of `y` is undefined if there are duplicates in `i`. @inlinable @inline(__always) public static func inplaceUpdate( - _ x: Tensor, - i: Tensor, - v: Tensor + _ x: Tensor, + i: Tensor, + v: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("InplaceUpdate", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(i) - op.addInput(v) - return op.execute(Int(1)) + let op = makeOp("InplaceUpdate", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(i) + op.addInput(v) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func int64Output( ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Int64Output", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("Int64Output", nOutputs) + + return op.execute(Int(1)) } @inlinable @inline(__always) public static func intAttr( - foo: Int64 = 1 + foo: Int64 = 1 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("IntAttr", nOutputs) - op.updateAttribute("foo", foo) - return op.execute(Int(1)) + let op = makeOp("IntAttr", nOutputs) + op.updateAttribute("foo", foo) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func intInput( - _ a: Tensor + _ a: Tensor ) { let nOutputs = 0 - let op = makeOp("IntInput", nOutputs) - op.addInput(a) - op.execute() + let op = makeOp("IntInput", nOutputs) + op.addInput(a) + op.execute() } @inlinable @inline(__always) public static func intInputFloatInput( - _ a: Tensor, - _ b: Tensor + _ a: Tensor, + _ b: Tensor ) { let nOutputs = 0 - let op = makeOp("IntInputFloatInput", nOutputs) - op.addInput(a) - op.addInput(b) - op.execute() + let op = makeOp("IntInputFloatInput", nOutputs) + op.addInput(a) + op.addInput(b) + op.execute() } @inlinable @inline(__always) public static func intInputIntOutput( - _ a: Tensor + _ a: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("IntInputIntOutput", nOutputs) - op.addInput(a) - return op.execute(Int(1)) + let op = makeOp("IntInputIntOutput", nOutputs) + op.addInput(a) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func intOutput( ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("IntOutput", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("IntOutput", nOutputs) + + return op.execute(Int(1)) } @inlinable @inline(__always) public static func intOutputFloatOutput( ) -> (a: Tensor, b: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("IntOutputFloatOutput", nOutputs) - - return op.execute(Int(1), Int(1)) + let op = makeOp("IntOutputFloatOutput", nOutputs) + + return op.execute(Int(1), Int(1)) } /// Creates a dataset that applies `f` to the outputs of `input_dataset`. @@ -13498,33 +13485,33 @@ public static func intOutputFloatOutput( /// consecutive elements from `cycle_length` input elements. /// /// - Attr f: A function mapping elements of `input_dataset`, concatenated with -/// `other_arguments`, to a Dataset variant that contains elements matching -/// `output_types` and `output_shapes`. +/// `other_arguments`, to a Dataset variant that contains elements matching +/// `output_types` and `output_shapes`. @inlinable @inline(__always) public static func interleaveDataset< FIn: TensorGroup, FOut: TensorGroup, Targuments: TensorArrayProtocol >( - inputDataset: VariantHandle, - otherArguments: Targuments, - cycleLength: Tensor, - blockLength: Tensor, - f: (FIn) -> FOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + otherArguments: Targuments, + cycleLength: Tensor, + blockLength: Tensor, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("InterleaveDataset", nOutputs) - op.updateAttribute("f", f) - op.updateAttribute("Targuments", otherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInputList(otherArguments) - op.addInput(cycleLength) - op.addInput(blockLength) - return op.execute(Int(1)) + let op = makeOp("InterleaveDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInputList(otherArguments) + op.addInput(cycleLength) + op.addInput(blockLength) + return op.execute(Int(1)) } /// Computes the reciprocal of x element-wise. @@ -13532,13 +13519,13 @@ public static func interleaveDataset< /// I.e., \\(y = 1 / x\\). @inlinable @inline(__always) public static func inv( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Inv", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Inv", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the gradient for the inverse of `x` wrt its input. @@ -13547,15 +13534,15 @@ public static func inv( /// is the corresponding input gradient. @inlinable @inline(__always) public static func invGrad( - _ y: Tensor, - dy: Tensor + _ y: Tensor, + dy: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("InvGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(y) - op.addInput(dy) - return op.execute(Int(1)) + let op = makeOp("InvGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(dy) + return op.execute(Int(1)) } /// Flips all bits elementwise. @@ -13564,13 +13551,13 @@ public static func invGrad( /// computation is performed on the underlying representation of x. @inlinable @inline(__always) public static func invert( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Invert", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Invert", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the inverse permutation of a tensor. @@ -13596,13 +13583,13 @@ public static func invert( /// - Output y: 1-D. @inlinable @inline(__always) public static func invertPermutation( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("InvertPermutation", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("InvertPermutation", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Checks whether a tree ensemble has been initialized. @@ -13612,12 +13599,12 @@ public static func invertPermutation( /// - Output is_initialized: output boolean on whether it is initialized or not. @inlinable @inline(__always) public static func isBoostedTreesEnsembleInitialized( - treeEnsembleHandle: ResourceHandle + treeEnsembleHandle: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("IsBoostedTreesEnsembleInitialized", nOutputs) - op.addInput(treeEnsembleHandle) - return op.execute(Int(1)) + let op = makeOp("IsBoostedTreesEnsembleInitialized", nOutputs) + op.addInput(treeEnsembleHandle) + return op.execute(Int(1)) } /// Checks whether a quantile stream has been initialized. @@ -13629,12 +13616,12 @@ public static func isBoostedTreesEnsembleInitialized( /// - Output is_initialized: bool; True if the resource is initialized, False otherwise. @inlinable @inline(__always) public static func isBoostedTreesQuantileStreamResourceInitialized( - quantileStreamResourceHandle: ResourceHandle + quantileStreamResourceHandle: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("IsBoostedTreesQuantileStreamResourceInitialized", nOutputs) - op.addInput(quantileStreamResourceHandle) - return op.execute(Int(1)) + let op = makeOp("IsBoostedTreesQuantileStreamResourceInitialized", nOutputs) + op.addInput(quantileStreamResourceHandle) + return op.execute(Int(1)) } /// Returns which elements of x are finite. @@ -13644,13 +13631,13 @@ public static func isBoostedTreesQuantileStreamResourceInitialized( /// @end_compatibility @inlinable @inline(__always) public static func isFinite( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("IsFinite", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("IsFinite", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Returns which elements of x are Inf. @@ -13660,13 +13647,13 @@ public static func isFinite( /// @end_compatibility @inlinable @inline(__always) public static func isInf( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("IsInf", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("IsInf", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Returns which elements of x are NaN. @@ -13676,33 +13663,33 @@ public static func isInf( /// @end_compatibility @inlinable @inline(__always) public static func isNan( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("IsNan", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("IsNan", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// A container for an iterator resource. /// /// - Output handle: A handle to the iterator that can be passed to a "MakeIterator" -/// or "IteratorGetNext" op. +/// or "IteratorGetNext" op. @inlinable @inline(__always) public static func iterator( - sharedName: String, - container: String, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + sharedName: String, + container: String, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("Iterator", nOutputs) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("container", container) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - return op.execute(Int(1)) + let op = makeOp("Iterator", nOutputs) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("container", container) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + return op.execute(Int(1)) } /// Converts the given string representing a handle to an iterator to a resource. @@ -13710,67 +13697,67 @@ public static func iterator( /// - Parameter string_handle: A string representation of the given handle. /// /// - Attrs: -/// - output_types: If specified, defines the type of each tuple component in an -/// element produced by the resulting iterator. -/// - output_shapes: If specified, defines the shape of each tuple component in an -/// element produced by the resulting iterator. +/// - output_types: If specified, defines the type of each tuple component in an +/// element produced by the resulting iterator. +/// - output_shapes: If specified, defines the shape of each tuple component in an +/// element produced by the resulting iterator. /// /// - Output resource_handle: A handle to an iterator resource. @inlinable @inline(__always) public static func iteratorFromStringHandle( - stringHandle: StringTensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + stringHandle: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("IteratorFromStringHandle", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(stringHandle) - return op.execute(Int(1)) + let op = makeOp("IteratorFromStringHandle", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(stringHandle) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func iteratorFromStringHandleV2( - stringHandle: StringTensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + stringHandle: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("IteratorFromStringHandleV2", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(stringHandle) - return op.execute(Int(1)) + let op = makeOp("IteratorFromStringHandleV2", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(stringHandle) + return op.execute(Int(1)) } /// Gets the next output from the given iterator . @inlinable @inline(__always) public static func iteratorGetNext( - iterator: ResourceHandle, - outputShapes: [TensorShape?] + iterator: ResourceHandle, + outputShapes: [TensorShape?] ) -> OutputTypes { let nOutputs = Int(OutputTypes._typeList.count) - let op = makeOp("IteratorGetNext", nOutputs) - op.updateAttribute("output_types", OutputTypes._typeList) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(iterator) - return op.execute(Int(OutputTypes._typeList.count)) + let op = makeOp("IteratorGetNext", nOutputs) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(iterator) + return op.execute(Int(OutputTypes._typeList.count)) } /// Gets the next output from the given iterator as an Optional variant. @inlinable @inline(__always) public static func iteratorGetNextAsOptional( - iterator: ResourceHandle, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + iterator: ResourceHandle, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("IteratorGetNextAsOptional", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(iterator) - return op.execute(Int(1)) + let op = makeOp("IteratorGetNextAsOptional", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(iterator) + return op.execute(Int(1)) } /// Gets the next output from the given iterator. @@ -13781,15 +13768,15 @@ public static func iteratorGetNextAsOptional( /// operations (e.g. in eager mode). @inlinable @inline(__always) public static func iteratorGetNextSync( - iterator: ResourceHandle, - outputShapes: [TensorShape?] + iterator: ResourceHandle, + outputShapes: [TensorShape?] ) -> OutputTypes { let nOutputs = Int(OutputTypes._typeList.count) - let op = makeOp("IteratorGetNextSync", nOutputs) - op.updateAttribute("output_types", OutputTypes._typeList) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(iterator) - return op.execute(Int(OutputTypes._typeList.count)) + let op = makeOp("IteratorGetNextSync", nOutputs) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(iterator) + return op.execute(Int(OutputTypes._typeList.count)) } /// Converts the given `resource_handle` representing an iterator to a string. @@ -13799,28 +13786,28 @@ public static func iteratorGetNextSync( /// - Output string_handle: A string representation of the given handle. @inlinable @inline(__always) public static func iteratorToStringHandle( - resourceHandle: ResourceHandle + resourceHandle: ResourceHandle ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("IteratorToStringHandle", nOutputs) - op.addInput(resourceHandle) - return op.execute(Int(1)) + let op = makeOp("IteratorToStringHandle", nOutputs) + op.addInput(resourceHandle) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func iteratorV2( - sharedName: String, - container: String, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + sharedName: String, + container: String, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("IteratorV2", nOutputs) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("container", container) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - return op.execute(Int(1)) + let op = makeOp("IteratorV2", nOutputs) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("container", container) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + return op.execute(Int(1)) } /// Returns the index of a data point that should be added to the seed set. @@ -13831,40 +13818,40 @@ public static func iteratorV2( /// as an additional cluster center. /// /// - Parameters: -/// - distances: Vector with squared distances to the closest previously sampled cluster center -/// for each candidate point. -/// - seed: Scalar. Seed for initializing the random number generator. +/// - distances: Vector with squared distances to the closest previously sampled cluster center +/// for each candidate point. +/// - seed: Scalar. Seed for initializing the random number generator. /// /// - Output index: Scalar with the index of the sampled point. @inlinable @inline(__always) public static func kMC2ChainInitialization( - distances: Tensor, - seed: Tensor + distances: Tensor, + seed: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("KMC2ChainInitialization", nOutputs) - op.addInput(distances) - op.addInput(seed) - return op.execute(Int(1)) + let op = makeOp("KMC2ChainInitialization", nOutputs) + op.addInput(distances) + op.addInput(seed) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func kernelLabel( ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("KernelLabel", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("KernelLabel", nOutputs) + + return op.execute(Int(1)) } @inlinable @inline(__always) public static func kernelLabelRequired( - _ input: Tensor + _ input: Tensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("KernelLabelRequired", nOutputs) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("KernelLabelRequired", nOutputs) + op.addInput(input) + return op.execute(Int(1)) } /// Selects num_to_sample rows of input using the KMeans++ criterion. @@ -13875,29 +13862,29 @@ public static func kernelLabelRequired( /// been sampled. /// /// - Parameters: -/// - points: Matrix of shape (n, d). Rows are assumed to be input points. -/// - num_to_sample: Scalar. The number of rows to sample. This value must not be larger than n. -/// - seed: Scalar. Seed for initializing the random number generator. -/// - num_retries_per_sample: Scalar. For each row that is sampled, this parameter -/// specifies the number of additional points to draw from the current -/// distribution before selecting the best. If a negative value is specified, a -/// heuristic is used to sample O(log(num_to_sample)) additional points. +/// - points: Matrix of shape (n, d). Rows are assumed to be input points. +/// - num_to_sample: Scalar. The number of rows to sample. This value must not be larger than n. +/// - seed: Scalar. Seed for initializing the random number generator. +/// - num_retries_per_sample: Scalar. For each row that is sampled, this parameter +/// specifies the number of additional points to draw from the current +/// distribution before selecting the best. If a negative value is specified, a +/// heuristic is used to sample O(log(num_to_sample)) additional points. /// /// - Output samples: Matrix of shape (num_to_sample, d). The sampled rows. @inlinable @inline(__always) public static func kmeansPlusPlusInitialization( - points: Tensor, - numToSample: Tensor, - seed: Tensor, - numRetriesPerSample: Tensor + points: Tensor, + numToSample: Tensor, + seed: Tensor, + numRetriesPerSample: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("KmeansPlusPlusInitialization", nOutputs) - op.addInput(points) - op.addInput(numToSample) - op.addInput(seed) - op.addInput(numRetriesPerSample) - return op.execute(Int(1)) + let op = makeOp("KmeansPlusPlusInitialization", nOutputs) + op.addInput(points) + op.addInput(numToSample) + op.addInput(seed) + op.addInput(numRetriesPerSample) + return op.execute(Int(1)) } /// L2 Loss. @@ -13911,13 +13898,13 @@ public static func kmeansPlusPlusInitialization( /// - Output output: 0-D. @inlinable @inline(__always) public static func l2Loss( - t: Tensor + t: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("L2Loss", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(t) - return op.execute(Int(1)) + let op = makeOp("L2Loss", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(t) + return op.execute(Int(1)) } /// Local Response Normalization. @@ -13937,64 +13924,64 @@ public static func l2Loss( /// - Parameter input: 4-D. /// /// - Attrs: -/// - depth_radius: 0-D. Half-width of the 1-D normalization window. -/// - bias: An offset (usually positive to avoid dividing by 0). -/// - alpha: A scale factor, usually positive. -/// - beta: An exponent. +/// - depth_radius: 0-D. Half-width of the 1-D normalization window. +/// - bias: An offset (usually positive to avoid dividing by 0). +/// - alpha: A scale factor, usually positive. +/// - beta: An exponent. @inlinable @inline(__always) public static func lRN( - _ input: Tensor, - depthRadius: Int64 = 5, - bias: Double = 1, - alpha: Double = 1, - beta: Double = 0.5 + _ input: Tensor, + depthRadius: Int64 = 5, + bias: Double = 1, + alpha: Double = 1, + beta: Double = 0.5 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LRN", nOutputs) - op.updateAttribute("depth_radius", depthRadius) - op.updateAttribute("bias", bias) - op.updateAttribute("alpha", alpha) - op.updateAttribute("beta", beta) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("LRN", nOutputs) + op.updateAttribute("depth_radius", depthRadius) + op.updateAttribute("bias", bias) + op.updateAttribute("alpha", alpha) + op.updateAttribute("beta", beta) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Gradients for Local Response Normalization. /// /// - Parameters: -/// - input_grads: 4-D with shape `[batch, height, width, channels]`. -/// - input_image: 4-D with shape `[batch, height, width, channels]`. -/// - output_image: 4-D with shape `[batch, height, width, channels]`. +/// - input_grads: 4-D with shape `[batch, height, width, channels]`. +/// - input_image: 4-D with shape `[batch, height, width, channels]`. +/// - output_image: 4-D with shape `[batch, height, width, channels]`. /// /// - Attrs: -/// - depth_radius: A depth radius. -/// - bias: An offset (usually > 0 to avoid dividing by 0). -/// - alpha: A scale factor, usually positive. -/// - beta: An exponent. +/// - depth_radius: A depth radius. +/// - bias: An offset (usually > 0 to avoid dividing by 0). +/// - alpha: A scale factor, usually positive. +/// - beta: An exponent. /// /// - Output output: The gradients for LRN. @inlinable @inline(__always) public static func lRNGrad( - inputGrads: Tensor, - inputImage: Tensor, - outputImage: Tensor, - depthRadius: Int64 = 5, - bias: Double = 1, - alpha: Double = 1, - beta: Double = 0.5 -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("LRNGrad", nOutputs) - op.updateAttribute("depth_radius", depthRadius) - op.updateAttribute("bias", bias) - op.updateAttribute("alpha", alpha) - op.updateAttribute("beta", beta) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(inputGrads) - op.addInput(inputImage) - op.addInput(outputImage) - return op.execute(Int(1)) + inputGrads: Tensor, + inputImage: Tensor, + outputImage: Tensor, + depthRadius: Int64 = 5, + bias: Double = 1, + alpha: Double = 1, + beta: Double = 0.5 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("LRNGrad", nOutputs) + op.updateAttribute("depth_radius", depthRadius) + op.updateAttribute("bias", bias) + op.updateAttribute("alpha", alpha) + op.updateAttribute("beta", beta) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(inputGrads) + op.addInput(inputImage) + op.addInput(outputImage) + return op.execute(Int(1)) } /// Computes the LSTM cell forward propagation for 1 time step. @@ -14025,57 +14012,57 @@ public static func lRNGrad( /// ``` /// /// - Parameters: -/// - x: The input to the LSTM cell, shape (batch_size, num_inputs). -/// - cs_prev: Value of the cell state at previous time step. -/// - h_prev: Output of the previous cell at previous time step. -/// - w: The weight matrix. -/// - wci: The weight matrix for input gate peephole connection. -/// - wcf: The weight matrix for forget gate peephole connection. -/// - wco: The weight matrix for output gate peephole connection. -/// - b: The bias vector. +/// - x: The input to the LSTM cell, shape (batch_size, num_inputs). +/// - cs_prev: Value of the cell state at previous time step. +/// - h_prev: Output of the previous cell at previous time step. +/// - w: The weight matrix. +/// - wci: The weight matrix for input gate peephole connection. +/// - wcf: The weight matrix for forget gate peephole connection. +/// - wco: The weight matrix for output gate peephole connection. +/// - b: The bias vector. /// /// - Attrs: -/// - forget_bias: The forget gate bias. -/// - cell_clip: Value to clip the 'cs' value to. -/// - use_peephole: Whether to use peephole weights. +/// - forget_bias: The forget gate bias. +/// - cell_clip: Value to clip the 'cs' value to. +/// - use_peephole: Whether to use peephole weights. /// /// - Outputs: -/// - i: The input gate. -/// - cs: The cell state before the tanh. -/// - f: The forget gate. -/// - o: The output gate. -/// - ci: The cell input. -/// - co: The cell after the tanh. -/// - h: The output h vector. +/// - i: The input gate. +/// - cs: The cell state before the tanh. +/// - f: The forget gate. +/// - o: The output gate. +/// - ci: The cell input. +/// - co: The cell after the tanh. +/// - h: The output h vector. @inlinable @inline(__always) public static func lSTMBlockCell( - _ x: Tensor, - csPrev: Tensor, - hPrev: Tensor, - w: Tensor, - wci: Tensor, - wcf: Tensor, - wco: Tensor, - _ b: Tensor, - forgetBias: Double = 1, - cellClip: Double = 3, - usePeephole: Bool = false + _ x: Tensor, + csPrev: Tensor, + hPrev: Tensor, + w: Tensor, + wci: Tensor, + wcf: Tensor, + wco: Tensor, + _ b: Tensor, + forgetBias: Double = 1, + cellClip: Double = 3, + usePeephole: Bool = false ) -> (i: Tensor, cs: Tensor, f: Tensor, o: Tensor, ci: Tensor, co: Tensor, h: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("LSTMBlockCell", nOutputs) - op.updateAttribute("forget_bias", forgetBias) - op.updateAttribute("cell_clip", cellClip) - op.updateAttribute("use_peephole", usePeephole) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(csPrev) - op.addInput(hPrev) - op.addInput(w) - op.addInput(wci) - op.addInput(wcf) - op.addInput(wco) - op.addInput(b) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("LSTMBlockCell", nOutputs) + op.updateAttribute("forget_bias", forgetBias) + op.updateAttribute("cell_clip", cellClip) + op.updateAttribute("use_peephole", usePeephole) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(csPrev) + op.addInput(hPrev) + op.addInput(w) + op.addInput(wci) + op.addInput(wcf) + op.addInput(wco) + op.addInput(b) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) } /// Computes the LSTM cell backward propagation for 1 timestep. @@ -14083,109 +14070,109 @@ public static func lSTMBlockCell( /// This implementation is to be used in conjunction of LSTMBlockCell. /// /// - Parameters: -/// - x: The input to the LSTM cell, shape (batch_size, num_inputs). -/// - cs_prev: The previous cell state. -/// - h_prev: The previous h state. -/// - w: The weight matrix. -/// - wci: The weight matrix for input gate peephole connection. -/// - wcf: The weight matrix for forget gate peephole connection. -/// - wco: The weight matrix for output gate peephole connection. -/// - b: The bias vector. -/// - i: The input gate. -/// - cs: The cell state before the tanh. -/// - f: The forget gate. -/// - o: The output gate. -/// - ci: The cell input. -/// - co: The cell after the tanh. -/// - cs_grad: The current gradient of cs. -/// - h_grad: The gradient of h vector. +/// - x: The input to the LSTM cell, shape (batch_size, num_inputs). +/// - cs_prev: The previous cell state. +/// - h_prev: The previous h state. +/// - w: The weight matrix. +/// - wci: The weight matrix for input gate peephole connection. +/// - wcf: The weight matrix for forget gate peephole connection. +/// - wco: The weight matrix for output gate peephole connection. +/// - b: The bias vector. +/// - i: The input gate. +/// - cs: The cell state before the tanh. +/// - f: The forget gate. +/// - o: The output gate. +/// - ci: The cell input. +/// - co: The cell after the tanh. +/// - cs_grad: The current gradient of cs. +/// - h_grad: The gradient of h vector. /// /// - Attr use_peephole: Whether the cell uses peephole connections. /// /// - Outputs: -/// - cs_prev_grad: The gradient of cs to be back-propped. -/// - dicfo: The derivative wrt to [i, cs, f, o]. -/// - wci_grad: The gradient for wci to be back-propped. -/// - wcf_grad: The gradient for wcf to be back-propped. -/// - wco_grad: The gradient for wco to be back-propped. +/// - cs_prev_grad: The gradient of cs to be back-propped. +/// - dicfo: The derivative wrt to [i, cs, f, o]. +/// - wci_grad: The gradient for wci to be back-propped. +/// - wcf_grad: The gradient for wcf to be back-propped. +/// - wco_grad: The gradient for wco to be back-propped. @inlinable @inline(__always) public static func lSTMBlockCellGrad( - _ x: Tensor, - csPrev: Tensor, - hPrev: Tensor, - w: Tensor, - wci: Tensor, - wcf: Tensor, - wco: Tensor, - _ b: Tensor, - i: Tensor, - cs: Tensor, - f: Tensor, - o: Tensor, - ci: Tensor, - co: Tensor, - csGrad: Tensor, - hGrad: Tensor, - usePeephole: Bool + _ x: Tensor, + csPrev: Tensor, + hPrev: Tensor, + w: Tensor, + wci: Tensor, + wcf: Tensor, + wco: Tensor, + _ b: Tensor, + i: Tensor, + cs: Tensor, + f: Tensor, + o: Tensor, + ci: Tensor, + co: Tensor, + csGrad: Tensor, + hGrad: Tensor, + usePeephole: Bool ) -> (csPrevGrad: Tensor, dicfo: Tensor, wciGrad: Tensor, wcfGrad: Tensor, wcoGrad: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("LSTMBlockCellGrad", nOutputs) - op.updateAttribute("use_peephole", usePeephole) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(csPrev) - op.addInput(hPrev) - op.addInput(w) - op.addInput(wci) - op.addInput(wcf) - op.addInput(wco) - op.addInput(b) - op.addInput(i) - op.addInput(cs) - op.addInput(f) - op.addInput(o) - op.addInput(ci) - op.addInput(co) - op.addInput(csGrad) - op.addInput(hGrad) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("LSTMBlockCellGrad", nOutputs) + op.updateAttribute("use_peephole", usePeephole) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(csPrev) + op.addInput(hPrev) + op.addInput(w) + op.addInput(wci) + op.addInput(wcf) + op.addInput(wco) + op.addInput(b) + op.addInput(i) + op.addInput(cs) + op.addInput(f) + op.addInput(o) + op.addInput(ci) + op.addInput(co) + op.addInput(csGrad) + op.addInput(hGrad) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1)) } /// Computes rectified linear: `max(features, features * alpha)`. @inlinable @inline(__always) public static func leakyRelu( - features: Tensor, - alpha: Double = 0.2 + features: Tensor, + alpha: Double = 0.2 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LeakyRelu", nOutputs) - op.updateAttribute("alpha", alpha) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(features) - return op.execute(Int(1)) + let op = makeOp("LeakyRelu", nOutputs) + op.updateAttribute("alpha", alpha) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) } /// Computes rectified linear gradients for a LeakyRelu operation. /// /// - Parameters: -/// - gradients: The backpropagated gradients to the corresponding LeakyRelu operation. -/// - features: The features passed as input to the corresponding LeakyRelu operation, -/// OR the outputs of that operation (both work equivalently). +/// - gradients: The backpropagated gradients to the corresponding LeakyRelu operation. +/// - features: The features passed as input to the corresponding LeakyRelu operation, +/// OR the outputs of that operation (both work equivalently). /// /// - Output backprops: `gradients * (features > 0) + alpha * gradients * (featurs <= 0)`. @inlinable @inline(__always) public static func leakyReluGrad( - gradients: Tensor, - features: Tensor, - alpha: Double = 0.2 + gradients: Tensor, + features: Tensor, + alpha: Double = 0.2 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LeakyReluGrad", nOutputs) - op.updateAttribute("alpha", alpha) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(gradients) - op.addInput(features) - return op.execute(Int(1)) + let op = makeOp("LeakyReluGrad", nOutputs) + op.updateAttribute("alpha", alpha) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(features) + return op.execute(Int(1)) } /// Generates labels for candidate sampling with a learned unigram distribution. @@ -14201,50 +14188,50 @@ public static func leakyReluGrad( /// true labels. /// /// - Parameter true_classes: A batch_size * num_true matrix, in which each row contains the -/// IDs of the num_true target_classes in the corresponding original label. +/// IDs of the num_true target_classes in the corresponding original label. /// /// - Attrs: -/// - num_true: Number of true labels per context. -/// - num_sampled: Number of candidates to randomly sample. -/// - unique: If unique is true, we sample with rejection, so that all sampled -/// candidates in a batch are unique. This requires some approximation to -/// estimate the post-rejection sampling probabilities. -/// - range_max: The sampler will sample integers from the interval [0, range_max). -/// - seed: If either seed or seed2 are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: An second seed to avoid seed collision. +/// - num_true: Number of true labels per context. +/// - num_sampled: Number of candidates to randomly sample. +/// - unique: If unique is true, we sample with rejection, so that all sampled +/// candidates in a batch are unique. This requires some approximation to +/// estimate the post-rejection sampling probabilities. +/// - range_max: The sampler will sample integers from the interval [0, range_max). +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. /// /// - Outputs: -/// - sampled_candidates: A vector of length num_sampled, in which each element is -/// the ID of a sampled candidate. -/// - true_expected_count: A batch_size * num_true matrix, representing -/// the number of times each candidate is expected to occur in a batch -/// of sampled candidates. If unique=true, then this is a probability. -/// - sampled_expected_count: A vector of length num_sampled, for each sampled -/// candidate representing the number of times the candidate is expected -/// to occur in a batch of sampled candidates. If unique=true, then this is a -/// probability. +/// - sampled_candidates: A vector of length num_sampled, in which each element is +/// the ID of a sampled candidate. +/// - true_expected_count: A batch_size * num_true matrix, representing +/// the number of times each candidate is expected to occur in a batch +/// of sampled candidates. If unique=true, then this is a probability. +/// - sampled_expected_count: A vector of length num_sampled, for each sampled +/// candidate representing the number of times the candidate is expected +/// to occur in a batch of sampled candidates. If unique=true, then this is a +/// probability. @inlinable @inline(__always) public static func learnedUnigramCandidateSampler( - trueClasses: Tensor, - numTrue: Int64, - numSampled: Int64, - unique: Bool, - rangeMax: Int64, - seed: Int64 = 0, - seed2: Int64 = 0 + trueClasses: Tensor, + numTrue: Int64, + numSampled: Int64, + unique: Bool, + rangeMax: Int64, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> (sampledCandidates: Tensor, trueExpectedCount: Tensor, sampledExpectedCount: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("LearnedUnigramCandidateSampler", nOutputs) - op.updateAttribute("num_true", numTrue) - op.updateAttribute("num_sampled", numSampled) - op.updateAttribute("unique", unique) - op.updateAttribute("range_max", rangeMax) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.addInput(trueClasses) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("LearnedUnigramCandidateSampler", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("num_sampled", numSampled) + op.updateAttribute("unique", unique) + op.updateAttribute("range_max", rangeMax) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + return op.execute(Int(1), Int(1), Int(1)) } /// Elementwise computes the bitwise left-shift of `x` and `y`. @@ -14253,15 +14240,15 @@ public static func learnedUnigramCandidateSampler( /// result is implementation defined. @inlinable @inline(__always) public static func leftShift( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LeftShift", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("LeftShift", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns the truth value of (x < y) element-wise. @@ -14270,15 +14257,15 @@ public static func leftShift( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func less( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Less", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Less", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns the truth value of (x <= y) element-wise. @@ -14287,27 +14274,27 @@ public static func less( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func lessEqual( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LessEqual", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("LessEqual", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Computes the log of the absolute value of `Gamma(x)` element-wise. @inlinable @inline(__always) public static func lgamma( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Lgamma", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Lgamma", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Generates values in an interval. @@ -14323,9 +14310,9 @@ public static func lgamma( /// ``` /// /// - Parameters: -/// - start: 0-D tensor. First entry in the range. -/// - stop: 0-D tensor. Last entry in the range. -/// - num: 0-D tensor. Number of values to generate. +/// - start: 0-D tensor. First entry in the range. +/// - stop: 0-D tensor. Last entry in the range. +/// - num: 0-D tensor. Number of values to generate. /// /// - Output output: 1-D. The generated values. @inlinable @inline(__always) @@ -14333,18 +14320,18 @@ public static func linSpace< T: FloatingPoint & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - start: Tensor, - stop: Tensor, - num: Tensor + start: Tensor, + stop: Tensor, + num: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LinSpace", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(start) - op.addInput(stop) - op.addInput(num) - return op.execute(Int(1)) + let op = makeOp("LinSpace", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(start) + op.addInput(stop) + op.addInput(num) + return op.execute(Int(1)) } /// Computes the difference between two lists of numbers or strings. @@ -14372,48 +14359,48 @@ public static func linSpace< /// ``` /// /// - Parameters: -/// - x: 1-D. Values to keep. -/// - y: 1-D. Values to remove. +/// - x: 1-D. Values to keep. +/// - y: 1-D. Values to remove. /// /// - Outputs: -/// - out: 1-D. Values present in `x` but not in `y`. -/// - idx: 1-D. Positions of `x` values preserved in `out`. +/// - out: 1-D. Values present in `x` but not in `y`. +/// - idx: 1-D. Positions of `x` values preserved in `out`. @inlinable @inline(__always) public static func listDiff< T: TensorFlowScalar, OutIdx: BinaryInteger & TensorFlowScalar >( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> (out: Tensor, idx: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("ListDiff", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1), Int(1)) + let op = makeOp("ListDiff", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1), Int(1)) } @inlinable @inline(__always) public static func listInput( - _ a: [Tensor] + _ a: [Tensor] ) { let nOutputs = 0 - let op = makeOp("ListInput", nOutputs) - op.updateAttribute("N", a.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInputList(a) - op.execute() + let op = makeOp("ListInput", nOutputs) + op.updateAttribute("N", a.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInputList(a) + op.execute() } @inlinable @inline(__always) public static func listOutput( ) -> T { let nOutputs = Int(T._typeList.count) - let op = makeOp("ListOutput", nOutputs) - op.updateAttribute("T", T._typeList) - return op.execute(Int(T._typeList.count)) + let op = makeOp("ListOutput", nOutputs) + op.updateAttribute("T", T._typeList) + return op.execute(Int(T._typeList.count)) } /// Loads a 2-D (matrix) `Tensor` with name `old_tensor_name` from the checkpoint @@ -14454,51 +14441,51 @@ public static func listOutput( /// [0.25, -0.25, 42]] /// /// - Parameters: -/// - ckpt_path: Path to the TensorFlow checkpoint (version 2, `TensorBundle`) from -/// which the old matrix `Tensor` will be loaded. -/// - old_tensor_name: Name of the 2-D `Tensor` to load from checkpoint. -/// - row_remapping: An int `Tensor` of row remappings (generally created by -/// `generate_vocab_remapping`). Even if no row remapping is needed, this must -/// still be an index-valued Tensor (e.g. [0, 1, 2, ...]), or a shifted -/// index-valued `Tensor` (e.g. [8, 9, 10, ...], for partitioned `Variables`). -/// - col_remapping: An int `Tensor` of column remappings (generally created by -/// `generate_vocab_remapping`). May be a size-0 `Tensor` if only row remapping -/// is to be done (e.g. column ordering is the same). -/// - initializing_values: A float `Tensor` containing values to fill in for cells -/// in the output matrix that are not loaded from the checkpoint. Length must be -/// exactly the same as the number of missing / new cells. +/// - ckpt_path: Path to the TensorFlow checkpoint (version 2, `TensorBundle`) from +/// which the old matrix `Tensor` will be loaded. +/// - old_tensor_name: Name of the 2-D `Tensor` to load from checkpoint. +/// - row_remapping: An int `Tensor` of row remappings (generally created by +/// `generate_vocab_remapping`). Even if no row remapping is needed, this must +/// still be an index-valued Tensor (e.g. [0, 1, 2, ...]), or a shifted +/// index-valued `Tensor` (e.g. [8, 9, 10, ...], for partitioned `Variables`). +/// - col_remapping: An int `Tensor` of column remappings (generally created by +/// `generate_vocab_remapping`). May be a size-0 `Tensor` if only row remapping +/// is to be done (e.g. column ordering is the same). +/// - initializing_values: A float `Tensor` containing values to fill in for cells +/// in the output matrix that are not loaded from the checkpoint. Length must be +/// exactly the same as the number of missing / new cells. /// /// - Attrs: -/// - num_rows: Number of rows (length of the 1st dimension) in the output matrix. -/// - num_cols: Number of columns (length of the 2nd dimension) in the output matrix. -/// - max_rows_in_memory: The maximum number of rows to load from the checkpoint at -/// once. If less than or equal to 0, the entire matrix will be loaded into -/// memory. Setting this arg trades increased disk reads for lower memory usage. +/// - num_rows: Number of rows (length of the 1st dimension) in the output matrix. +/// - num_cols: Number of columns (length of the 2nd dimension) in the output matrix. +/// - max_rows_in_memory: The maximum number of rows to load from the checkpoint at +/// once. If less than or equal to 0, the entire matrix will be loaded into +/// memory. Setting this arg trades increased disk reads for lower memory usage. /// /// - Output output_matrix: Output matrix containing existing values loaded from the -/// checkpoint, and with any missing values filled in from initializing_values. +/// checkpoint, and with any missing values filled in from initializing_values. @inlinable @inline(__always) public static func loadAndRemapMatrix( - ckptPath: StringTensor, - oldTensorName: StringTensor, - rowRemapping: Tensor, - colRemapping: Tensor, - initializingValues: Tensor, - numRows: Int64, - numCols: Int64, - maxRowsInMemory: Int64 = -1 + ckptPath: StringTensor, + oldTensorName: StringTensor, + rowRemapping: Tensor, + colRemapping: Tensor, + initializingValues: Tensor, + numRows: Int64, + numCols: Int64, + maxRowsInMemory: Int64 = -1 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LoadAndRemapMatrix", nOutputs) - op.updateAttribute("num_rows", numRows) - op.updateAttribute("num_cols", numCols) - op.updateAttribute("max_rows_in_memory", maxRowsInMemory) - op.addInput(ckptPath) - op.addInput(oldTensorName) - op.addInput(rowRemapping) - op.addInput(colRemapping) - op.addInput(initializingValues) - return op.execute(Int(1)) + let op = makeOp("LoadAndRemapMatrix", nOutputs) + op.updateAttribute("num_rows", numRows) + op.updateAttribute("num_cols", numCols) + op.updateAttribute("max_rows_in_memory", maxRowsInMemory) + op.addInput(ckptPath) + op.addInput(oldTensorName) + op.addInput(rowRemapping) + op.addInput(colRemapping) + op.addInput(initializingValues) + return op.execute(Int(1)) } /// Load ADAM embedding parameters. @@ -14510,29 +14497,29 @@ public static func loadAndRemapMatrix( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the ADAM optimization algorithm. -/// - momenta: Value of momenta used in the ADAM optimization algorithm. -/// - velocities: Value of velocities used in the ADAM optimization algorithm. +/// - parameters: Value of parameters used in the ADAM optimization algorithm. +/// - momenta: Value of momenta used in the ADAM optimization algorithm. +/// - velocities: Value of velocities used in the ADAM optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingADAMParameters( - parameters: Tensor, - momenta: Tensor, - velocities: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + momenta: Tensor, + velocities: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingADAMParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(momenta) - op.addInput(velocities) - op.execute() + let op = makeOp("LoadTPUEmbeddingADAMParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(momenta) + op.addInput(velocities) + op.execute() } /// Load ADAM embedding parameters with debug support. @@ -14544,32 +14531,32 @@ public static func loadTPUEmbeddingADAMParameters( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the ADAM optimization algorithm. -/// - momenta: Value of momenta used in the ADAM optimization algorithm. -/// - velocities: Value of velocities used in the ADAM optimization algorithm. -/// - gradient_accumulators: Value of gradient_accumulators used in the ADAM optimization algorithm. +/// - parameters: Value of parameters used in the ADAM optimization algorithm. +/// - momenta: Value of momenta used in the ADAM optimization algorithm. +/// - velocities: Value of velocities used in the ADAM optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the ADAM optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingADAMParametersGradAccumDebug( - parameters: Tensor, - momenta: Tensor, - velocities: Tensor, - gradientAccumulators: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + momenta: Tensor, + velocities: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingADAMParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(momenta) - op.addInput(velocities) - op.addInput(gradientAccumulators) - op.execute() + let op = makeOp("LoadTPUEmbeddingADAMParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(momenta) + op.addInput(velocities) + op.addInput(gradientAccumulators) + op.execute() } /// Load Adadelta embedding parameters. @@ -14581,29 +14568,29 @@ public static func loadTPUEmbeddingADAMParametersGradAccumDebug( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the Adadelta optimization algorithm. -/// - accumulators: Value of accumulators used in the Adadelta optimization algorithm. -/// - updates: Value of updates used in the Adadelta optimization algorithm. +/// - parameters: Value of parameters used in the Adadelta optimization algorithm. +/// - accumulators: Value of accumulators used in the Adadelta optimization algorithm. +/// - updates: Value of updates used in the Adadelta optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingAdadeltaParameters( - parameters: Tensor, - accumulators: Tensor, - updates: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + accumulators: Tensor, + updates: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingAdadeltaParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(accumulators) - op.addInput(updates) - op.execute() + let op = makeOp("LoadTPUEmbeddingAdadeltaParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(updates) + op.execute() } /// Load Adadelta parameters with debug support. @@ -14615,32 +14602,32 @@ public static func loadTPUEmbeddingAdadeltaParameters( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the Adadelta optimization algorithm. -/// - accumulators: Value of accumulators used in the Adadelta optimization algorithm. -/// - updates: Value of updates used in the Adadelta optimization algorithm. -/// - gradient_accumulators: Value of gradient_accumulators used in the Adadelta optimization algorithm. +/// - parameters: Value of parameters used in the Adadelta optimization algorithm. +/// - accumulators: Value of accumulators used in the Adadelta optimization algorithm. +/// - updates: Value of updates used in the Adadelta optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the Adadelta optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingAdadeltaParametersGradAccumDebug( - parameters: Tensor, - accumulators: Tensor, - updates: Tensor, - gradientAccumulators: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + accumulators: Tensor, + updates: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingAdadeltaParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(accumulators) - op.addInput(updates) - op.addInput(gradientAccumulators) - op.execute() + let op = makeOp("LoadTPUEmbeddingAdadeltaParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(updates) + op.addInput(gradientAccumulators) + op.execute() } /// Load Adagrad embedding parameters. @@ -14652,26 +14639,26 @@ public static func loadTPUEmbeddingAdadeltaParametersGradAccumDebug( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the Adagrad optimization algorithm. -/// - accumulators: Value of accumulators used in the Adagrad optimization algorithm. +/// - parameters: Value of parameters used in the Adagrad optimization algorithm. +/// - accumulators: Value of accumulators used in the Adagrad optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingAdagradParameters( - parameters: Tensor, - accumulators: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + accumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingAdagradParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(accumulators) - op.execute() + let op = makeOp("LoadTPUEmbeddingAdagradParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.execute() } /// Load Adagrad embedding parameters with debug support. @@ -14683,29 +14670,29 @@ public static func loadTPUEmbeddingAdagradParameters( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the Adagrad optimization algorithm. -/// - accumulators: Value of accumulators used in the Adagrad optimization algorithm. -/// - gradient_accumulators: Value of gradient_accumulators used in the Adagrad optimization algorithm. +/// - parameters: Value of parameters used in the Adagrad optimization algorithm. +/// - accumulators: Value of accumulators used in the Adagrad optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the Adagrad optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingAdagradParametersGradAccumDebug( - parameters: Tensor, - accumulators: Tensor, - gradientAccumulators: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + accumulators: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingAdagradParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(accumulators) - op.addInput(gradientAccumulators) - op.execute() + let op = makeOp("LoadTPUEmbeddingAdagradParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(gradientAccumulators) + op.execute() } /// Load centered RMSProp embedding parameters. @@ -14717,32 +14704,32 @@ public static func loadTPUEmbeddingAdagradParametersGradAccumDebug( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the centered RMSProp optimization algorithm. -/// - ms: Value of ms used in the centered RMSProp optimization algorithm. -/// - mom: Value of mom used in the centered RMSProp optimization algorithm. -/// - mg: Value of mg used in the centered RMSProp optimization algorithm. +/// - parameters: Value of parameters used in the centered RMSProp optimization algorithm. +/// - ms: Value of ms used in the centered RMSProp optimization algorithm. +/// - mom: Value of mom used in the centered RMSProp optimization algorithm. +/// - mg: Value of mg used in the centered RMSProp optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingCenteredRMSPropParameters( - parameters: Tensor, - ms: Tensor, - mom: Tensor, - mg: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + ms: Tensor, + mom: Tensor, + mg: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingCenteredRMSPropParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(ms) - op.addInput(mom) - op.addInput(mg) - op.execute() + let op = makeOp("LoadTPUEmbeddingCenteredRMSPropParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(ms) + op.addInput(mom) + op.addInput(mg) + op.execute() } /// Load FTRL embedding parameters. @@ -14754,29 +14741,29 @@ public static func loadTPUEmbeddingCenteredRMSPropParameters( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the FTRL optimization algorithm. -/// - accumulators: Value of accumulators used in the FTRL optimization algorithm. -/// - linears: Value of linears used in the FTRL optimization algorithm. +/// - parameters: Value of parameters used in the FTRL optimization algorithm. +/// - accumulators: Value of accumulators used in the FTRL optimization algorithm. +/// - linears: Value of linears used in the FTRL optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingFTRLParameters( - parameters: Tensor, - accumulators: Tensor, - linears: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + accumulators: Tensor, + linears: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingFTRLParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(accumulators) - op.addInput(linears) - op.execute() + let op = makeOp("LoadTPUEmbeddingFTRLParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(linears) + op.execute() } /// Load FTRL embedding parameters with debug support. @@ -14788,32 +14775,32 @@ public static func loadTPUEmbeddingFTRLParameters( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the FTRL optimization algorithm. -/// - accumulators: Value of accumulators used in the FTRL optimization algorithm. -/// - linears: Value of linears used in the FTRL optimization algorithm. -/// - gradient_accumulators: Value of gradient_accumulators used in the FTRL optimization algorithm. +/// - parameters: Value of parameters used in the FTRL optimization algorithm. +/// - accumulators: Value of accumulators used in the FTRL optimization algorithm. +/// - linears: Value of linears used in the FTRL optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the FTRL optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingFTRLParametersGradAccumDebug( - parameters: Tensor, - accumulators: Tensor, - linears: Tensor, - gradientAccumulators: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + accumulators: Tensor, + linears: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingFTRLParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(accumulators) - op.addInput(linears) - op.addInput(gradientAccumulators) - op.execute() + let op = makeOp("LoadTPUEmbeddingFTRLParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(linears) + op.addInput(gradientAccumulators) + op.execute() } /// Load MDL Adagrad Light embedding parameters. @@ -14825,32 +14812,32 @@ public static func loadTPUEmbeddingFTRLParametersGradAccumDebug( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the MDL Adagrad Light optimization algorithm. -/// - accumulators: Value of accumulators used in the MDL Adagrad Light optimization algorithm. -/// - weights: Value of weights used in the MDL Adagrad Light optimization algorithm. -/// - benefits: Value of benefits used in the MDL Adagrad Light optimization algorithm. +/// - parameters: Value of parameters used in the MDL Adagrad Light optimization algorithm. +/// - accumulators: Value of accumulators used in the MDL Adagrad Light optimization algorithm. +/// - weights: Value of weights used in the MDL Adagrad Light optimization algorithm. +/// - benefits: Value of benefits used in the MDL Adagrad Light optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingMDLAdagradLightParameters( - parameters: Tensor, - accumulators: Tensor, - weights: Tensor, - benefits: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + accumulators: Tensor, + weights: Tensor, + benefits: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingMDLAdagradLightParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(accumulators) - op.addInput(weights) - op.addInput(benefits) - op.execute() + let op = makeOp("LoadTPUEmbeddingMDLAdagradLightParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(weights) + op.addInput(benefits) + op.execute() } /// Load Momentum embedding parameters. @@ -14862,26 +14849,26 @@ public static func loadTPUEmbeddingMDLAdagradLightParameters( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the Momentum optimization algorithm. -/// - momenta: Value of momenta used in the Momentum optimization algorithm. +/// - parameters: Value of parameters used in the Momentum optimization algorithm. +/// - momenta: Value of momenta used in the Momentum optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingMomentumParameters( - parameters: Tensor, - momenta: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + momenta: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingMomentumParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(momenta) - op.execute() + let op = makeOp("LoadTPUEmbeddingMomentumParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(momenta) + op.execute() } /// Load Momentum embedding parameters with debug support. @@ -14893,29 +14880,29 @@ public static func loadTPUEmbeddingMomentumParameters( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the Momentum optimization algorithm. -/// - momenta: Value of momenta used in the Momentum optimization algorithm. -/// - gradient_accumulators: Value of gradient_accumulators used in the Momentum optimization algorithm. +/// - parameters: Value of parameters used in the Momentum optimization algorithm. +/// - momenta: Value of momenta used in the Momentum optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the Momentum optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingMomentumParametersGradAccumDebug( - parameters: Tensor, - momenta: Tensor, - gradientAccumulators: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + momenta: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingMomentumParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(momenta) - op.addInput(gradientAccumulators) - op.execute() + let op = makeOp("LoadTPUEmbeddingMomentumParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(momenta) + op.addInput(gradientAccumulators) + op.execute() } /// Load proximal Adagrad embedding parameters. @@ -14927,26 +14914,26 @@ public static func loadTPUEmbeddingMomentumParametersGradAccumDebug( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the proximal Adagrad optimization algorithm. -/// - accumulators: Value of accumulators used in the proximal Adagrad optimization algorithm. +/// - parameters: Value of parameters used in the proximal Adagrad optimization algorithm. +/// - accumulators: Value of accumulators used in the proximal Adagrad optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingProximalAdagradParameters( - parameters: Tensor, - accumulators: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + accumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingProximalAdagradParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(accumulators) - op.execute() + let op = makeOp("LoadTPUEmbeddingProximalAdagradParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.execute() } /// Load proximal Adagrad embedding parameters with debug support. @@ -14958,29 +14945,29 @@ public static func loadTPUEmbeddingProximalAdagradParameters( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the proximal Adagrad optimization algorithm. -/// - accumulators: Value of accumulators used in the proximal Adagrad optimization algorithm. -/// - gradient_accumulators: Value of gradient_accumulators used in the proximal Adagrad optimization algorithm. +/// - parameters: Value of parameters used in the proximal Adagrad optimization algorithm. +/// - accumulators: Value of accumulators used in the proximal Adagrad optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the proximal Adagrad optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingProximalAdagradParametersGradAccumDebug( - parameters: Tensor, - accumulators: Tensor, - gradientAccumulators: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + accumulators: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingProximalAdagradParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(accumulators) - op.addInput(gradientAccumulators) - op.execute() + let op = makeOp("LoadTPUEmbeddingProximalAdagradParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(accumulators) + op.addInput(gradientAccumulators) + op.execute() } /// Load RMSProp embedding parameters. @@ -14992,29 +14979,29 @@ public static func loadTPUEmbeddingProximalAdagradParametersGradAccumDebug( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the RMSProp optimization algorithm. -/// - ms: Value of ms used in the RMSProp optimization algorithm. -/// - mom: Value of mom used in the RMSProp optimization algorithm. +/// - parameters: Value of parameters used in the RMSProp optimization algorithm. +/// - ms: Value of ms used in the RMSProp optimization algorithm. +/// - mom: Value of mom used in the RMSProp optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingRMSPropParameters( - parameters: Tensor, - ms: Tensor, - mom: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + ms: Tensor, + mom: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingRMSPropParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(ms) - op.addInput(mom) - op.execute() + let op = makeOp("LoadTPUEmbeddingRMSPropParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(ms) + op.addInput(mom) + op.execute() } /// Load RMSProp embedding parameters with debug support. @@ -15026,32 +15013,32 @@ public static func loadTPUEmbeddingRMSPropParameters( /// executed. /// /// - Parameters: -/// - parameters: Value of parameters used in the RMSProp optimization algorithm. -/// - ms: Value of ms used in the RMSProp optimization algorithm. -/// - mom: Value of mom used in the RMSProp optimization algorithm. -/// - gradient_accumulators: Value of gradient_accumulators used in the RMSProp optimization algorithm. +/// - parameters: Value of parameters used in the RMSProp optimization algorithm. +/// - ms: Value of ms used in the RMSProp optimization algorithm. +/// - mom: Value of mom used in the RMSProp optimization algorithm. +/// - gradient_accumulators: Value of gradient_accumulators used in the RMSProp optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingRMSPropParametersGradAccumDebug( - parameters: Tensor, - ms: Tensor, - mom: Tensor, - gradientAccumulators: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + ms: Tensor, + mom: Tensor, + gradientAccumulators: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingRMSPropParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.addInput(ms) - op.addInput(mom) - op.addInput(gradientAccumulators) - op.execute() + let op = makeOp("LoadTPUEmbeddingRMSPropParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.addInput(ms) + op.addInput(mom) + op.addInput(gradientAccumulators) + op.execute() } /// Load SGD embedding parameters. @@ -15065,20 +15052,20 @@ public static func loadTPUEmbeddingRMSPropParametersGradAccumDebug( /// - Parameter parameters: Value of parameters used in the stochastic gradient descent optimization algorithm. @inlinable @inline(__always) public static func loadTPUEmbeddingStochasticGradientDescentParameters( - parameters: Tensor, - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + parameters: Tensor, + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) { let nOutputs = 0 - let op = makeOp("LoadTPUEmbeddingStochasticGradientDescentParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - op.addInput(parameters) - op.execute() + let op = makeOp("LoadTPUEmbeddingStochasticGradientDescentParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + op.addInput(parameters) + op.execute() } /// Computes natural logarithm of x element-wise. @@ -15086,13 +15073,13 @@ public static func loadTPUEmbeddingStochasticGradientDescentParameters( /// I.e., \\(y = \log_e x\\). @inlinable @inline(__always) public static func log( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Log", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Log", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes natural logarithm of (1 + x) element-wise. @@ -15100,13 +15087,13 @@ public static func log( /// I.e., \\(y = \log_e (1 + x)\\). @inlinable @inline(__always) public static func log1p( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Log1p", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Log1p", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the sign and the log of the absolute value of the determinant of @@ -15124,18 +15111,18 @@ public static func log1p( /// - Parameter input: Shape is `[N, M, M]`. /// /// - Outputs: -/// - sign: The signs of the log determinants of the inputs. Shape is `[N]`. -/// - log_abs_determinant: The logs of the absolute values of the determinants -/// of the N input matrices. Shape is `[N]`. +/// - sign: The signs of the log determinants of the inputs. Shape is `[N]`. +/// - log_abs_determinant: The logs of the absolute values of the determinants +/// of the N input matrices. Shape is `[N]`. @inlinable @inline(__always) public static func logMatrixDeterminant( - _ input: Tensor + _ input: Tensor ) -> (sign: Tensor, logAbsDeterminant: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("LogMatrixDeterminant", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1), Int(1)) + let op = makeOp("LogMatrixDeterminant", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) } /// Computes log softmax activations. @@ -15149,13 +15136,13 @@ public static func logMatrixDeterminant( /// - Output logsoftmax: Same shape as `logits`. @inlinable @inline(__always) public static func logSoftmax( - logits: Tensor + logits: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LogSoftmax", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(logits) - return op.execute(Int(1)) + let op = makeOp("LogSoftmax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(logits) + return op.execute(Int(1)) } /// Generates labels for candidate sampling with a log-uniform distribution. @@ -15171,50 +15158,50 @@ public static func logSoftmax( /// true labels. /// /// - Parameter true_classes: A batch_size * num_true matrix, in which each row contains the -/// IDs of the num_true target_classes in the corresponding original label. +/// IDs of the num_true target_classes in the corresponding original label. /// /// - Attrs: -/// - num_true: Number of true labels per context. -/// - num_sampled: Number of candidates to randomly sample. -/// - unique: If unique is true, we sample with rejection, so that all sampled -/// candidates in a batch are unique. This requires some approximation to -/// estimate the post-rejection sampling probabilities. -/// - range_max: The sampler will sample integers from the interval [0, range_max). -/// - seed: If either seed or seed2 are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: An second seed to avoid seed collision. +/// - num_true: Number of true labels per context. +/// - num_sampled: Number of candidates to randomly sample. +/// - unique: If unique is true, we sample with rejection, so that all sampled +/// candidates in a batch are unique. This requires some approximation to +/// estimate the post-rejection sampling probabilities. +/// - range_max: The sampler will sample integers from the interval [0, range_max). +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. /// /// - Outputs: -/// - sampled_candidates: A vector of length num_sampled, in which each element is -/// the ID of a sampled candidate. -/// - true_expected_count: A batch_size * num_true matrix, representing -/// the number of times each candidate is expected to occur in a batch -/// of sampled candidates. If unique=true, then this is a probability. -/// - sampled_expected_count: A vector of length num_sampled, for each sampled -/// candidate representing the number of times the candidate is expected -/// to occur in a batch of sampled candidates. If unique=true, then this is a -/// probability. +/// - sampled_candidates: A vector of length num_sampled, in which each element is +/// the ID of a sampled candidate. +/// - true_expected_count: A batch_size * num_true matrix, representing +/// the number of times each candidate is expected to occur in a batch +/// of sampled candidates. If unique=true, then this is a probability. +/// - sampled_expected_count: A vector of length num_sampled, for each sampled +/// candidate representing the number of times the candidate is expected +/// to occur in a batch of sampled candidates. If unique=true, then this is a +/// probability. @inlinable @inline(__always) public static func logUniformCandidateSampler( - trueClasses: Tensor, - numTrue: Int64, - numSampled: Int64, - unique: Bool, - rangeMax: Int64, - seed: Int64 = 0, - seed2: Int64 = 0 + trueClasses: Tensor, + numTrue: Int64, + numSampled: Int64, + unique: Bool, + rangeMax: Int64, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> (sampledCandidates: Tensor, trueExpectedCount: Tensor, sampledExpectedCount: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("LogUniformCandidateSampler", nOutputs) - op.updateAttribute("num_true", numTrue) - op.updateAttribute("num_sampled", numSampled) - op.updateAttribute("unique", unique) - op.updateAttribute("range_max", rangeMax) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.addInput(trueClasses) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("LogUniformCandidateSampler", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("num_sampled", numSampled) + op.updateAttribute("unique", unique) + op.updateAttribute("range_max", rangeMax) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + return op.execute(Int(1), Int(1), Int(1)) } /// Returns the truth value of x AND y element-wise. @@ -15223,25 +15210,25 @@ public static func logUniformCandidateSampler( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func logicalAnd( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LogicalAnd", nOutputs) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("LogicalAnd", nOutputs) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns the truth value of NOT x element-wise. @inlinable @inline(__always) public static func logicalNot( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LogicalNot", nOutputs) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("LogicalNot", nOutputs) + op.addInput(x) + return op.execute(Int(1)) } /// Returns the truth value of x OR y element-wise. @@ -15250,14 +15237,14 @@ public static func logicalNot( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func logicalOr( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LogicalOr", nOutputs) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("LogicalOr", nOutputs) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Outputs all keys and values in the table. @@ -15265,21 +15252,21 @@ public static func logicalOr( /// - Parameter table_handle: Handle to the table. /// /// - Outputs: -/// - keys: Vector of all keys present in the table. -/// - values: Tensor of all values in the table. Indexed in parallel with `keys`. +/// - keys: Vector of all keys present in the table. +/// - values: Tensor of all values in the table. Indexed in parallel with `keys`. @inlinable @inline(__always) public static func lookupTableExportV2< Tkeys: TensorFlowScalar, Tvalues: TensorFlowScalar >( - tableHandle: ResourceHandle + tableHandle: ResourceHandle ) -> (keys: Tensor, values: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("LookupTableExportV2", nOutputs) - op.updateAttribute("Tkeys", Tkeys.tensorFlowDataType) - op.updateAttribute("Tvalues", Tvalues.tensorFlowDataType) - op.addInput(tableHandle) - return op.execute(Int(1), Int(1)) + let op = makeOp("LookupTableExportV2", nOutputs) + op.updateAttribute("Tkeys", Tkeys.tensorFlowDataType) + op.updateAttribute("Tvalues", Tvalues.tensorFlowDataType) + op.addInput(tableHandle) + return op.execute(Int(1), Int(1)) } /// Looks up keys in a table, outputs the corresponding values. @@ -15291,28 +15278,28 @@ public static func lookupTableExportV2< /// table. It must also be of the same type as the table values. /// /// - Parameters: -/// - table_handle: Handle to the table. -/// - keys: Any shape. Keys to look up. +/// - table_handle: Handle to the table. +/// - keys: Any shape. Keys to look up. /// /// - Output values: Same shape as `keys`. Values found in the table, or `default_values` -/// for missing keys. +/// for missing keys. @inlinable @inline(__always) public static func lookupTableFindV2< Tin: TensorFlowScalar, Tout: TensorFlowScalar >( - tableHandle: ResourceHandle, - keys: Tensor, - defaultValue: Tensor + tableHandle: ResourceHandle, + keys: Tensor, + defaultValue: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LookupTableFindV2", nOutputs) - op.updateAttribute("Tin", Tin.tensorFlowDataType) - op.updateAttribute("Tout", Tout.tensorFlowDataType) - op.addInput(tableHandle) - op.addInput(keys) - op.addInput(defaultValue) - return op.execute(Int(1)) + let op = makeOp("LookupTableFindV2", nOutputs) + op.updateAttribute("Tin", Tin.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(tableHandle) + op.addInput(keys) + op.addInput(defaultValue) + return op.execute(Int(1)) } /// Replaces the contents of the table with the specified keys and values. @@ -15321,26 +15308,26 @@ public static func lookupTableFindV2< /// The tensor `values` must be of the type of the table values. /// /// - Parameters: -/// - table_handle: Handle to the table. -/// - keys: Any shape. Keys to look up. -/// - values: Values to associate with keys. +/// - table_handle: Handle to the table. +/// - keys: Any shape. Keys to look up. +/// - values: Values to associate with keys. @inlinable @inline(__always) public static func lookupTableImportV2< Tin: TensorFlowScalar, Tout: TensorFlowScalar >( - tableHandle: ResourceHandle, - keys: Tensor, - _ values: Tensor + tableHandle: ResourceHandle, + keys: Tensor, + _ values: Tensor ) { let nOutputs = 0 - let op = makeOp("LookupTableImportV2", nOutputs) - op.updateAttribute("Tin", Tin.tensorFlowDataType) - op.updateAttribute("Tout", Tout.tensorFlowDataType) - op.addInput(tableHandle) - op.addInput(keys) - op.addInput(values) - op.execute() + let op = makeOp("LookupTableImportV2", nOutputs) + op.updateAttribute("Tin", Tin.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(tableHandle) + op.addInput(keys) + op.addInput(values) + op.execute() } /// Updates the table to associates keys with values. @@ -15349,26 +15336,26 @@ public static func lookupTableImportV2< /// The tensor `values` must be of the type of the table values. /// /// - Parameters: -/// - table_handle: Handle to the table. -/// - keys: Any shape. Keys to look up. -/// - values: Values to associate with keys. +/// - table_handle: Handle to the table. +/// - keys: Any shape. Keys to look up. +/// - values: Values to associate with keys. @inlinable @inline(__always) public static func lookupTableInsertV2< Tin: TensorFlowScalar, Tout: TensorFlowScalar >( - tableHandle: ResourceHandle, - keys: Tensor, - _ values: Tensor + tableHandle: ResourceHandle, + keys: Tensor, + _ values: Tensor ) { let nOutputs = 0 - let op = makeOp("LookupTableInsertV2", nOutputs) - op.updateAttribute("Tin", Tin.tensorFlowDataType) - op.updateAttribute("Tout", Tout.tensorFlowDataType) - op.addInput(tableHandle) - op.addInput(keys) - op.addInput(values) - op.execute() + let op = makeOp("LookupTableInsertV2", nOutputs) + op.updateAttribute("Tin", Tin.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(tableHandle) + op.addInput(keys) + op.addInput(values) + op.execute() } /// Removes keys and its associated values from a table. @@ -15377,19 +15364,19 @@ public static func lookupTableInsertV2< /// already in the table are silently ignored. /// /// - Parameters: -/// - table_handle: Handle to the table. -/// - keys: Any shape. Keys of the elements to remove. +/// - table_handle: Handle to the table. +/// - keys: Any shape. Keys of the elements to remove. @inlinable @inline(__always) public static func lookupTableRemoveV2( - tableHandle: ResourceHandle, - keys: Tensor + tableHandle: ResourceHandle, + keys: Tensor ) { let nOutputs = 0 - let op = makeOp("LookupTableRemoveV2", nOutputs) - op.updateAttribute("Tin", Tin.tensorFlowDataType) - op.addInput(tableHandle) - op.addInput(keys) - op.execute() + let op = makeOp("LookupTableRemoveV2", nOutputs) + op.updateAttribute("Tin", Tin.tensorFlowDataType) + op.addInput(tableHandle) + op.addInput(keys) + op.execute() } /// Computes the number of elements in the given table. @@ -15399,12 +15386,12 @@ public static func lookupTableRemoveV2( /// - Output size: Scalar that contains number of elements in the table. @inlinable @inline(__always) public static func lookupTableSizeV2( - tableHandle: ResourceHandle + tableHandle: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LookupTableSizeV2", nOutputs) - op.addInput(tableHandle) - return op.execute(Int(1)) + let op = makeOp("LookupTableSizeV2", nOutputs) + op.addInput(tableHandle) + return op.execute(Int(1)) } /// Forwards the input to the output. @@ -15417,12 +15404,12 @@ public static func lookupTableSizeV2( /// - Output output: The same tensor as `input`. @inlinable @inline(__always) public static func loopCond( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LoopCond", nOutputs) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("LoopCond", nOutputs) + op.addInput(input) + return op.execute(Int(1)) } /// Applies lower_bound(sorted_search_values, values) along each row. @@ -15446,28 +15433,28 @@ public static func loopCond( /// [0, 1, 5]] /// /// - Parameters: -/// - sorted_inputs: 2-D Tensor where each row is ordered. -/// - values: 2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains -/// the values that will be searched for in `sorted_search_values`. +/// - sorted_inputs: 2-D Tensor where each row is ordered. +/// - values: 2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains +/// the values that will be searched for in `sorted_search_values`. /// /// - Output output: A `Tensor` with the same shape as `values`. It contains the first scalar index -/// into the last dimension where values can be inserted without changing the -/// ordered property. +/// into the last dimension where values can be inserted without changing the +/// ordered property. @inlinable @inline(__always) public static func lowerBound< T: TensorFlowScalar, OutType: BinaryInteger & TensorFlowScalar >( - sortedInputs: Tensor, - _ values: Tensor + sortedInputs: Tensor, + _ values: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("LowerBound", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(sortedInputs) - op.addInput(values) - return op.execute(Int(1)) + let op = makeOp("LowerBound", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(sortedInputs) + op.addInput(values) + return op.execute(Int(1)) } /// Computes the LU decomposition of one or more square matrices. @@ -15491,33 +15478,33 @@ public static func lowerBound< /// P, then the L, U and P satisfies P_mat * input = L * U. /// /// - Parameter input: A tensor of shape `[..., M, M]` whose inner-most 2 dimensions form matrices of -/// size `[M, M]`. +/// size `[M, M]`. /// /// - Outputs: -/// - lu: A tensor of shape `[..., M, M]` whose strictly lower triangular part denotes the -/// lower triangular factor `L` with unit diagonal, and whose upper triangular part -/// denotes the upper triangular factor `U`. -/// - p: Permutation of the rows encoded as a list of indices in `0..M-1`. Shape is -/// `[..., M]`. -/// @compatibility(scipy) -/// Similar to `scipy.linalg.lu`, except the triangular factors `L` and `U` are -/// packed into a single tensor, the permutation is applied to `input` instead of -/// the right hand side and the permutation `P` is returned as a list of indices -/// instead of a permutation matrix. -/// @end_compatibility +/// - lu: A tensor of shape `[..., M, M]` whose strictly lower triangular part denotes the +/// lower triangular factor `L` with unit diagonal, and whose upper triangular part +/// denotes the upper triangular factor `U`. +/// - p: Permutation of the rows encoded as a list of indices in `0..M-1`. Shape is +/// `[..., M]`. +/// @compatibility(scipy) +/// Similar to `scipy.linalg.lu`, except the triangular factors `L` and `U` are +/// packed into a single tensor, the permutation is applied to `input` instead of +/// the right hand side and the permutation `P` is returned as a list of indices +/// instead of a permutation matrix. +/// @end_compatibility @inlinable @inline(__always) public static func lu< T: FloatingPoint & TensorFlowScalar, OutputIdxType: BinaryInteger & TensorFlowScalar >( - _ input: Tensor + _ input: Tensor ) -> (lu: Tensor, p: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("Lu", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("output_idx_type", OutputIdxType.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1), Int(1)) + let op = makeOp("Lu", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("output_idx_type", OutputIdxType.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) } /// Makes a new iterator from the given `dataset` and stores it in `iterator`. @@ -15526,33 +15513,33 @@ public static func lu< /// iterator in `iterator` to the first element of `dataset`. @inlinable @inline(__always) public static func makeIterator( - dataset: VariantHandle, - iterator: ResourceHandle + dataset: VariantHandle, + iterator: ResourceHandle ) { let nOutputs = 0 - let op = makeOp("MakeIterator", nOutputs) - op.addInput(dataset) - op.addInput(iterator) - op.execute() + let op = makeOp("MakeIterator", nOutputs) + op.addInput(dataset) + op.addInput(iterator) + op.execute() } /// Op removes all elements in the underlying container. @inlinable @inline(__always) public static func mapClear( - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - dtypes: [TensorDataType], - container: String, - sharedName: String + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String ) { let nOutputs = 0 - let op = makeOp("MapClear", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", dtypes) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.execute() + let op = makeOp("MapClear", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.execute() } /// Creates a dataset that applies `f` to the outputs of `input_dataset`. @@ -15562,25 +15549,25 @@ public static func mapDataset< FOut: TensorGroup, Targuments: TensorArrayProtocol >( - inputDataset: VariantHandle, - otherArguments: Targuments, - f: (FIn) -> FOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?], - useInterOpParallelism: Bool = true, - preserveCardinality: Bool = false + inputDataset: VariantHandle, + otherArguments: Targuments, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + useInterOpParallelism: Bool = true, + preserveCardinality: Bool = false ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("MapDataset", nOutputs) - op.updateAttribute("f", f) - op.updateAttribute("Targuments", otherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("use_inter_op_parallelism", useInterOpParallelism) - op.updateAttribute("preserve_cardinality", preserveCardinality) - op.addInput(inputDataset) - op.addInputList(otherArguments) - return op.execute(Int(1)) + let op = makeOp("MapDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("use_inter_op_parallelism", useInterOpParallelism) + op.updateAttribute("preserve_cardinality", preserveCardinality) + op.addInput(inputDataset) + op.addInputList(otherArguments) + return op.execute(Int(1)) } /// Maps a function on the list of tensors unpacked from arguments on dimension 0. @@ -15597,20 +15584,20 @@ public static func mapDataset< /// rewrites. /// /// - Parameters: -/// - arguments: A list of tensors whose types are `Targuments`, corresponding to the inputs -/// the function should be mapped over. -/// - captured_inputs: A list of tensors whose types are `Tcaptured`, corresponding to the captured -/// inputs of the defun. +/// - arguments: A list of tensors whose types are `Targuments`, corresponding to the inputs +/// the function should be mapped over. +/// - captured_inputs: A list of tensors whose types are `Tcaptured`, corresponding to the captured +/// inputs of the defun. /// /// - Attrs: -/// - Targuments: A list of types. -/// - Tcaptured: A list of types. -/// - output_types: A list of types. -/// - output_shapes: A list of shapes. +/// - Targuments: A list of types. +/// - Tcaptured: A list of types. +/// - output_types: A list of types. +/// - output_shapes: A list of shapes. /// /// - Output output: A list of output tensors whose types are `output_types` and whose dimensions -/// 0 are the same as the dimensions 0 of the tensors in `arguments`, and whose -/// remaining dimensions correspond to those in `output_shapes`. +/// 0 are the same as the dimensions 0 of the tensors in `arguments`, and whose +/// remaining dimensions correspond to those in `output_shapes`. @inlinable @inline(__always) public static func mapDefun< Targuments: TensorArrayProtocol, @@ -15619,42 +15606,42 @@ public static func mapDefun< FIn: TensorGroup, FOut: TensorGroup >( - arguments: Targuments, - capturedInputs: Tcaptured, - outputShapes: [TensorShape?], - f: (FIn) -> FOut, - maxIntraOpParallelism: Int64 = 1 + arguments: Targuments, + capturedInputs: Tcaptured, + outputShapes: [TensorShape?], + f: (FIn) -> FOut, + maxIntraOpParallelism: Int64 = 1 ) -> OutputTypes { let nOutputs = Int(OutputTypes._typeList.count) - let op = makeOp("MapDefun", nOutputs) - op.updateAttribute("Targuments", arguments._typeList) - op.updateAttribute("Tcaptured", capturedInputs._typeList) - op.updateAttribute("output_types", OutputTypes._typeList) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("f", f) - op.updateAttribute("max_intra_op_parallelism", maxIntraOpParallelism) - op.addInputList(arguments) - op.addInputList(capturedInputs) - return op.execute(Int(OutputTypes._typeList.count)) + let op = makeOp("MapDefun", nOutputs) + op.updateAttribute("Targuments", arguments._typeList) + op.updateAttribute("Tcaptured", capturedInputs._typeList) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("f", f) + op.updateAttribute("max_intra_op_parallelism", maxIntraOpParallelism) + op.addInputList(arguments) + op.addInputList(capturedInputs) + return op.execute(Int(OutputTypes._typeList.count)) } /// Op returns the number of incomplete elements in the underlying container. @inlinable @inline(__always) public static func mapIncompleteSize( - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - dtypes: [TensorDataType], - container: String, - sharedName: String + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MapIncompleteSize", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", dtypes) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("MapIncompleteSize", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Op peeks at the values at the specified key. If the @@ -15663,80 +15650,80 @@ public static func mapIncompleteSize( /// this op will block until it does. @inlinable @inline(__always) public static func mapPeek( - key: Tensor, - indices: Tensor, - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - container: String, - sharedName: String + key: Tensor, + indices: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String ) -> Dtypes { let nOutputs = Int(Dtypes._typeList.count) - let op = makeOp("MapPeek", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", Dtypes._typeList) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.addInput(key) - op.addInput(indices) - return op.execute(Int(Dtypes._typeList.count)) + let op = makeOp("MapPeek", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(key) + op.addInput(indices) + return op.execute(Int(Dtypes._typeList.count)) } /// Op returns the number of elements in the underlying container. @inlinable @inline(__always) public static func mapSize( - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - dtypes: [TensorDataType], - container: String, - sharedName: String + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MapSize", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", dtypes) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("MapSize", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Stage (key, values) in the underlying container which behaves like a hashtable. /// /// - Parameters: -/// - key: int64 -/// - values: a list of tensors -/// dtypes A list of data types that inserted values should adhere to. +/// - key: int64 +/// - values: a list of tensors +/// dtypes A list of data types that inserted values should adhere to. /// /// - Attrs: -/// - capacity: Maximum number of elements in the Staging Area. If > 0, inserts -/// on the container will block when the capacity is reached. -/// - container: If non-empty, this queue is placed in the given container. Otherwise, -/// a default container is used. -/// - shared_name: It is necessary to match this name to the matching Unstage Op. +/// - capacity: Maximum number of elements in the Staging Area. If > 0, inserts +/// on the container will block when the capacity is reached. +/// - container: If non-empty, this queue is placed in the given container. Otherwise, +/// a default container is used. +/// - shared_name: It is necessary to match this name to the matching Unstage Op. @inlinable @inline(__always) public static func mapStage( - key: Tensor, - indices: Tensor, - _ values: FakeDtypes, - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - dtypes: [TensorDataType], - container: String, - sharedName: String + key: Tensor, + indices: Tensor, + _ values: FakeDtypes, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String ) { let nOutputs = 0 - let op = makeOp("MapStage", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", dtypes) - op.updateAttribute("fake_dtypes", values._typeList) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.addInput(key) - op.addInput(indices) - op.addInputList(values) - op.execute() + let op = makeOp("MapStage", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("fake_dtypes", values._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(key) + op.addInput(indices) + op.addInputList(values) + op.execute() } /// Op removes and returns the values associated with the key @@ -15745,23 +15732,23 @@ public static func mapStage( /// does not contain this key, the op will block until it does. @inlinable @inline(__always) public static func mapUnstage( - key: Tensor, - indices: Tensor, - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - container: String, - sharedName: String + key: Tensor, + indices: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String ) -> Dtypes { let nOutputs = Int(Dtypes._typeList.count) - let op = makeOp("MapUnstage", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", Dtypes._typeList) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.addInput(key) - op.addInput(indices) - return op.execute(Int(Dtypes._typeList.count)) + let op = makeOp("MapUnstage", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(key) + op.addInput(indices) + return op.execute(Int(Dtypes._typeList.count)) } /// Op removes and returns a random (key, value) @@ -15770,21 +15757,21 @@ public static func mapUnstage( /// does not contain elements, the op will block until it does. @inlinable @inline(__always) public static func mapUnstageNoKey( - indices: Tensor, - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - container: String, - sharedName: String + indices: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String ) -> (key: Tensor, values: Dtypes) { let nOutputs = Int(1) + Int(Dtypes._typeList.count) - let op = makeOp("MapUnstageNoKey", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", Dtypes._typeList) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.addInput(indices) - return op.execute(Int(1), Int(Dtypes._typeList.count)) + let op = makeOp("MapUnstageNoKey", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(indices) + return op.execute(Int(1), Int(Dtypes._typeList.count)) } /// Multiply the matrix "a" by the matrix "b". @@ -15798,23 +15785,23 @@ public static func mapUnstageNoKey( /// cublas. /// /// - Attrs: -/// - transpose_a: If true, "a" is transposed before multiplication. -/// - transpose_b: If true, "b" is transposed before multiplication. +/// - transpose_a: If true, "a" is transposed before multiplication. +/// - transpose_b: If true, "b" is transposed before multiplication. @inlinable @inline(__always) public static func matMul( - _ a: Tensor, - _ b: Tensor, - transposeA: Bool = false, - transposeB: Bool = false + _ a: Tensor, + _ b: Tensor, + transposeA: Bool = false, + transposeB: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MatMul", nOutputs) - op.updateAttribute("transpose_a", transposeA) - op.updateAttribute("transpose_b", transposeB) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - op.addInput(b) - return op.execute(Int(1)) + let op = makeOp("MatMul", nOutputs) + op.updateAttribute("transpose_a", transposeA) + op.updateAttribute("transpose_b", transposeB) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(b) + return op.execute(Int(1)) } /// Returns the set of files matching one or more glob patterns. @@ -15828,12 +15815,12 @@ public static func matMul( /// - Output filenames: A vector of matching filenames. @inlinable @inline(__always) public static func matchingFiles( - pattern: StringTensor + pattern: StringTensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("MatchingFiles", nOutputs) - op.addInput(pattern) - return op.execute(Int(1)) + let op = makeOp("MatchingFiles", nOutputs) + op.addInput(pattern) + return op.execute(Int(1)) } /// Copy a tensor setting everything outside a central band in each innermost matrix @@ -15879,11 +15866,11 @@ public static func matchingFiles( /// ``` /// /// - Parameters: -/// - input: Rank `k` tensor. -/// - num_lower: 0-D tensor. Number of subdiagonals to keep. If negative, keep entire -/// lower triangle. -/// - num_upper: 0-D tensor. Number of superdiagonals to keep. If negative, keep -/// entire upper triangle. +/// - input: Rank `k` tensor. +/// - num_lower: 0-D tensor. Number of subdiagonals to keep. If negative, keep entire +/// lower triangle. +/// - num_upper: 0-D tensor. Number of superdiagonals to keep. If negative, keep +/// entire upper triangle. /// /// - Output band: Rank `k` tensor of the same shape as input. The extracted banded tensor. @inlinable @inline(__always) @@ -15891,18 +15878,18 @@ public static func matrixBandPart< T: TensorFlowScalar, Tindex: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - numLower: Tensor, - numUpper: Tensor + _ input: Tensor, + numLower: Tensor, + numUpper: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MatrixBandPart", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindex", Tindex.tensorFlowDataType) - op.addInput(input) - op.addInput(numLower) - op.addInput(numUpper) - return op.execute(Int(1)) + let op = makeOp("MatrixBandPart", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindex", Tindex.tensorFlowDataType) + op.addInput(input) + op.addInput(numLower) + op.addInput(numUpper) + return op.execute(Int(1)) } /// Computes the determinant of one or more square matrices. @@ -15916,13 +15903,13 @@ public static func matrixBandPart< /// - Output output: Shape is `[...]`. @inlinable @inline(__always) public static func matrixDeterminant( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MatrixDeterminant", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("MatrixDeterminant", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Returns a batched diagonal tensor with a given batched diagonal values. @@ -15959,13 +15946,13 @@ public static func matrixDeterminant( /// - Output output: Rank `k+1`, with `output.shape = diagonal.shape + [diagonal.shape[-1]]`. @inlinable @inline(__always) public static func matrixDiag( - diagonal: Tensor + diagonal: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MatrixDiag", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(diagonal) - return op.execute(Int(1)) + let op = makeOp("MatrixDiag", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(diagonal) + return op.execute(Int(1)) } /// Returns the batched diagonal part of a batched tensor. @@ -16002,28 +15989,28 @@ public static func matrixDiag( /// - Parameter input: Rank `k` tensor where `k >= 2`. /// /// - Output diagonal: The extracted diagonal(s) having shape -/// `diagonal.shape = input.shape[:-2] + [min(input.shape[-2:])]`. +/// `diagonal.shape = input.shape[:-2] + [min(input.shape[-2:])]`. @inlinable @inline(__always) public static func matrixDiagPart( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MatrixDiagPart", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("MatrixDiagPart", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Deprecated, use python implementation tf.linalg.matrix_exponential. @inlinable @inline(__always) public static func matrixExponential( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MatrixExponential", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("MatrixExponential", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Computes the inverse of one or more square invertible matrices or their @@ -16044,20 +16031,20 @@ public static func matrixExponential( /// /// - Output output: Shape is `[..., M, M]`. /// -/// @compatibility(numpy) -/// Equivalent to np.linalg.inv -/// @end_compatibility +/// @compatibility(numpy) +/// Equivalent to np.linalg.inv +/// @end_compatibility @inlinable @inline(__always) public static func matrixInverse( - _ input: Tensor, - adjoint: Bool = false + _ input: Tensor, + adjoint: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MatrixInverse", nOutputs) - op.updateAttribute("adjoint", adjoint) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("MatrixInverse", nOutputs) + op.updateAttribute("adjoint", adjoint) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Computes the matrix logarithm of one or more square matrices: @@ -16082,18 +16069,18 @@ public static func matrixInverse( /// /// - Output output: Shape is `[..., M, M]`. /// -/// @compatibility(scipy) -/// Equivalent to scipy.linalg.logm -/// @end_compatibility +/// @compatibility(scipy) +/// Equivalent to scipy.linalg.logm +/// @end_compatibility @inlinable @inline(__always) public static func matrixLogarithm( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MatrixLogarithm", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("MatrixLogarithm", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Returns a batched matrix tensor with new batched diagonal values. @@ -16112,21 +16099,21 @@ public static func matrixLogarithm( /// * `output[i, j, k, ..., m, n] = input[i, j, k, ..., m, n]` for `m != n`. /// /// - Parameters: -/// - input: Rank `k+1`, where `k >= 1`. -/// - diagonal: Rank `k`, where `k >= 1`. +/// - input: Rank `k+1`, where `k >= 1`. +/// - diagonal: Rank `k`, where `k >= 1`. /// /// - Output output: Rank `k+1`, with `output.shape = input.shape`. @inlinable @inline(__always) public static func matrixSetDiag( - _ input: Tensor, - diagonal: Tensor + _ input: Tensor, + diagonal: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MatrixSetDiag", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - op.addInput(diagonal) - return op.execute(Int(1)) + let op = makeOp("MatrixSetDiag", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(diagonal) + return op.execute(Int(1)) } /// Solves systems of linear equations. @@ -16139,26 +16126,26 @@ public static func matrixSetDiag( /// `adjoint(matrix[..., :, :]) * output[..., :, :] = rhs[..., :, :]`. /// /// - Parameters: -/// - matrix: Shape is `[..., M, M]`. -/// - rhs: Shape is `[..., M, K]`. +/// - matrix: Shape is `[..., M, M]`. +/// - rhs: Shape is `[..., M, K]`. /// /// - Attr adjoint: Boolean indicating whether to solve with `matrix` or its (block-wise) -/// adjoint. +/// adjoint. /// /// - Output output: Shape is `[..., M, K]`. @inlinable @inline(__always) public static func matrixSolve( - matrix: Tensor, - rhs: Tensor, - adjoint: Bool = false + matrix: Tensor, + rhs: Tensor, + adjoint: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MatrixSolve", nOutputs) - op.updateAttribute("adjoint", adjoint) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(matrix) - op.addInput(rhs) - return op.execute(Int(1)) + let op = makeOp("MatrixSolve", nOutputs) + op.updateAttribute("adjoint", adjoint) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(matrix) + op.addInput(rhs) + return op.execute(Int(1)) } /// Solves one or more linear least-squares problems. @@ -16199,30 +16186,30 @@ public static func matrixSolve( /// `l2_regularizer` is ignored. /// /// - Parameters: -/// - matrix: Shape is `[..., M, N]`. -/// - rhs: Shape is `[..., M, K]`. -/// - l2_regularizer: Scalar tensor. +/// - matrix: Shape is `[..., M, N]`. +/// - rhs: Shape is `[..., M, K]`. +/// - l2_regularizer: Scalar tensor. /// -/// @compatibility(numpy) -/// Equivalent to np.linalg.lstsq -/// @end_compatibility +/// @compatibility(numpy) +/// Equivalent to np.linalg.lstsq +/// @end_compatibility /// /// - Output output: Shape is `[..., N, K]`. @inlinable @inline(__always) public static func matrixSolveLs( - matrix: Tensor, - rhs: Tensor, - l2Regularizer: Tensor, - fast: Bool = true + matrix: Tensor, + rhs: Tensor, + l2Regularizer: Tensor, + fast: Bool = true ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MatrixSolveLs", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("fast", fast) - op.addInput(matrix) - op.addInput(rhs) - op.addInput(l2Regularizer) - return op.execute(Int(1)) + let op = makeOp("MatrixSolveLs", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("fast", fast) + op.addInput(matrix) + op.addInput(rhs) + op.addInput(l2Regularizer) + return op.execute(Int(1)) } /// Computes the matrix square root of one or more square matrices: @@ -16247,18 +16234,18 @@ public static func matrixSolveLs( /// /// - Output output: Shape is `[..., M, M]`. /// -/// @compatibility(scipy) -/// Equivalent to scipy.linalg.sqrtm -/// @end_compatibility +/// @compatibility(scipy) +/// Equivalent to scipy.linalg.sqrtm +/// @end_compatibility @inlinable @inline(__always) public static func matrixSquareRoot( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MatrixSquareRoot", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("MatrixSquareRoot", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Solves systems of linear equations with upper or lower triangular matrices by @@ -16280,35 +16267,35 @@ public static func matrixSquareRoot( /// `adjoint(matrix[..., i, k]) * output[..., k, j] = rhs[..., i, j]`. /// /// - Parameters: -/// - matrix: Shape is `[..., M, M]`. -/// - rhs: Shape is `[..., M, K]`. +/// - matrix: Shape is `[..., M, M]`. +/// - rhs: Shape is `[..., M, K]`. /// /// - Attrs: -/// - lower: Boolean indicating whether the innermost matrices in `matrix` are -/// lower or upper triangular. -/// - adjoint: Boolean indicating whether to solve with `matrix` or its (block-wise) -/// adjoint. +/// - lower: Boolean indicating whether the innermost matrices in `matrix` are +/// lower or upper triangular. +/// - adjoint: Boolean indicating whether to solve with `matrix` or its (block-wise) +/// adjoint. /// -/// @compatibility(numpy) -/// Equivalent to scipy.linalg.solve_triangular -/// @end_compatibility +/// @compatibility(numpy) +/// Equivalent to scipy.linalg.solve_triangular +/// @end_compatibility /// /// - Output output: Shape is `[..., M, K]`. @inlinable @inline(__always) public static func matrixTriangularSolve( - matrix: Tensor, - rhs: Tensor, - lower: Bool = true, - adjoint: Bool = false + matrix: Tensor, + rhs: Tensor, + lower: Bool = true, + adjoint: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MatrixTriangularSolve", nOutputs) - op.updateAttribute("lower", lower) - op.updateAttribute("adjoint", adjoint) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(matrix) - op.addInput(rhs) - return op.execute(Int(1)) + let op = makeOp("MatrixTriangularSolve", nOutputs) + op.updateAttribute("lower", lower) + op.updateAttribute("adjoint", adjoint) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(matrix) + op.addInput(rhs) + return op.execute(Int(1)) } /// Computes the maximum of elements across dimensions of a tensor. @@ -16319,9 +16306,9 @@ public static func matrixTriangularSolve( /// retained with length 1. /// /// - Parameters: -/// - input: The tensor to reduce. -/// - reduction_indices: The dimensions to reduce. Must be in the range -/// `[-rank(input), rank(input))`. +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. /// /// - Attr keep_dims: If true, retain reduced dimensions with length 1. /// @@ -16331,18 +16318,18 @@ public static func max< T: Numeric & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - reductionIndices: Tensor, - keepDims: Bool = false + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Max", nOutputs) - op.updateAttribute("keep_dims", keepDims) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(input) - op.addInput(reductionIndices) - return op.execute(Int(1)) + let op = makeOp("Max", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) } /// Performs max pooling on the input. @@ -16350,34 +16337,34 @@ public static func max< /// - Parameter input: 4-D input to pool over. /// /// - Attrs: -/// - ksize: The size of the window for each dimension of the input tensor. -/// - strides: The stride of the sliding window for each dimension of the -/// input tensor. -/// - padding: The type of padding algorithm to use. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, in_channels, in_height, in_width]. +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. /// /// - Output output: The max pooled output tensor. @inlinable @inline(__always) public static func maxPool( - _ input: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding, - dataFormat: DataFormat4 = .nhwc + _ input: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat4 = .nhwc ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MaxPool", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("MaxPool", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.addInput(input) + return op.execute(Int(1)) } /// Performs 3D max pooling on the input. @@ -16385,265 +16372,265 @@ public static func maxPool( /// - Parameter input: Shape `[batch, depth, rows, cols, channels]` tensor to pool over. /// /// - Attrs: -/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of -/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. -/// - strides: 1-D tensor of length 5. The stride of the sliding window for each -/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. -/// - padding: The type of padding algorithm to use. -/// - data_format: The data format of the input and output data. With the -/// default format "NDHWC", the data is stored in the order of: -/// [batch, in_depth, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCDHW", the data storage order is: -/// [batch, in_channels, in_depth, in_height, in_width]. +/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of +/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. /// /// - Output output: The max pooled output tensor. @inlinable @inline(__always) public static func maxPool3D( - _ input: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding, - dataFormat: DataFormat1 = .ndhwc + _ input: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MaxPool3D", nOutputs) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("MaxPool3D", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Computes gradients of max pooling function. /// /// - Parameters: -/// - orig_input: The original input tensor. -/// - orig_output: The original output tensor. -/// - grad: Output backprop of shape `[batch, depth, rows, cols, channels]`. +/// - orig_input: The original input tensor. +/// - orig_output: The original output tensor. +/// - grad: Output backprop of shape `[batch, depth, rows, cols, channels]`. /// /// - Attrs: -/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of -/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. -/// - strides: 1-D tensor of length 5. The stride of the sliding window for each -/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. -/// - padding: The type of padding algorithm to use. -/// - data_format: The data format of the input and output data. With the -/// default format "NDHWC", the data is stored in the order of: -/// [batch, in_depth, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCDHW", the data storage order is: -/// [batch, in_channels, in_depth, in_height, in_width]. +/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of +/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. @inlinable @inline(__always) public static func maxPool3DGrad< T: FloatingPoint & TensorFlowScalar, Tinput: FloatingPoint & TensorFlowScalar >( - origInput: Tensor, - origOutput: Tensor, - grad: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding, - dataFormat: DataFormat1 = .ndhwc -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("MaxPool3DGrad", nOutputs) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("TInput", Tinput.tensorFlowDataType) - op.addInput(origInput) - op.addInput(origOutput) - op.addInput(grad) - return op.execute(Int(1)) + origInput: Tensor, + origOutput: Tensor, + grad: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPool3DGrad", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("TInput", Tinput.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(grad) + return op.execute(Int(1)) } /// Computes second-order gradients of the maxpooling function. /// /// - Parameters: -/// - orig_input: The original input tensor. -/// - orig_output: The original output tensor. -/// - grad: Output backprop of shape `[batch, depth, rows, cols, channels]`. +/// - orig_input: The original input tensor. +/// - orig_output: The original output tensor. +/// - grad: Output backprop of shape `[batch, depth, rows, cols, channels]`. /// /// - Attrs: -/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of -/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. -/// - strides: 1-D tensor of length 5. The stride of the sliding window for each -/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. -/// - padding: The type of padding algorithm to use. -/// - data_format: The data format of the input and output data. With the -/// default format "NDHWC", the data is stored in the order of: -/// [batch, in_depth, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCDHW", the data storage order is: -/// [batch, in_channels, in_depth, in_height, in_width]. +/// - ksize: 1-D tensor of length 5. The size of the window for each dimension of +/// the input tensor. Must have `ksize[0] = ksize[4] = 1`. +/// - strides: 1-D tensor of length 5. The stride of the sliding window for each +/// dimension of `input`. Must have `strides[0] = strides[4] = 1`. +/// - padding: The type of padding algorithm to use. +/// - data_format: The data format of the input and output data. With the +/// default format "NDHWC", the data is stored in the order of: +/// [batch, in_depth, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCDHW", the data storage order is: +/// [batch, in_channels, in_depth, in_height, in_width]. /// /// - Output output: Gradients of gradients w.r.t. the input to `max_pool`. @inlinable @inline(__always) public static func maxPool3DGradGrad( - origInput: Tensor, - origOutput: Tensor, - grad: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding, - dataFormat: DataFormat1 = .ndhwc -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("MaxPool3DGradGrad", nOutputs) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(origInput) - op.addInput(origOutput) - op.addInput(grad) - return op.execute(Int(1)) + origInput: Tensor, + origOutput: Tensor, + grad: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat1 = .ndhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPool3DGradGrad", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(grad) + return op.execute(Int(1)) } /// Computes gradients of the maxpooling function. /// /// - Parameters: -/// - orig_input: The original input tensor. -/// - orig_output: The original output tensor. -/// - grad: 4-D. Gradients w.r.t. the output of `max_pool`. +/// - orig_input: The original input tensor. +/// - orig_output: The original output tensor. +/// - grad: 4-D. Gradients w.r.t. the output of `max_pool`. /// /// - Attrs: -/// - ksize: The size of the window for each dimension of the input tensor. -/// - strides: The stride of the sliding window for each dimension of the -/// input tensor. -/// - padding: The type of padding algorithm to use. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, in_channels, in_height, in_width]. +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. /// /// - Output output: Gradients w.r.t. the input to `max_pool`. @inlinable @inline(__always) public static func maxPoolGrad( - origInput: Tensor, - origOutput: Tensor, - grad: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding, - dataFormat: DataFormat = .nhwc -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("MaxPoolGrad", nOutputs) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(origInput) - op.addInput(origOutput) - op.addInput(grad) - return op.execute(Int(1)) + origInput: Tensor, + origOutput: Tensor, + grad: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPoolGrad", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(grad) + return op.execute(Int(1)) } /// Computes second-order gradients of the maxpooling function. /// /// - Parameters: -/// - orig_input: The original input tensor. -/// - orig_output: The original output tensor. -/// - grad: 4-D. Gradients of gradients w.r.t. the input of `max_pool`. +/// - orig_input: The original input tensor. +/// - orig_output: The original output tensor. +/// - grad: 4-D. Gradients of gradients w.r.t. the input of `max_pool`. /// /// - Attrs: -/// - ksize: The size of the window for each dimension of the input tensor. -/// - strides: The stride of the sliding window for each dimension of the -/// input tensor. -/// - padding: The type of padding algorithm to use. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, in_channels, in_height, in_width]. +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. /// /// - Output output: Gradients of gradients w.r.t. the input to `max_pool`. @inlinable @inline(__always) public static func maxPoolGradGrad( - origInput: Tensor, - origOutput: Tensor, - grad: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding, - dataFormat: DataFormat = .nhwc -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("MaxPoolGradGrad", nOutputs) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(origInput) - op.addInput(origOutput) - op.addInput(grad) - return op.execute(Int(1)) + origInput: Tensor, + origOutput: Tensor, + grad: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + dataFormat: DataFormat = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPoolGradGrad", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(grad) + return op.execute(Int(1)) } /// Computes second-order gradients of the maxpooling function. /// /// - Parameters: -/// - orig_input: The original input tensor. -/// - orig_output: The original output tensor. -/// - grad: 4-D. Gradients of gradients w.r.t. the input of `max_pool`. -/// - ksize: The size of the window for each dimension of the input tensor. -/// - strides: The stride of the sliding window for each dimension of the -/// input tensor. +/// - orig_input: The original input tensor. +/// - orig_output: The original output tensor. +/// - grad: 4-D. Gradients of gradients w.r.t. the input of `max_pool`. +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. /// /// - Attrs: -/// - padding: The type of padding algorithm to use. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, in_channels, in_height, in_width]. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. /// /// - Output output: Gradients of gradients w.r.t. the input to `max_pool`. @inlinable @inline(__always) public static func maxPoolGradGradV2( - origInput: Tensor, - origOutput: Tensor, - grad: Tensor, - ksize: Tensor, - strides: Tensor, - padding: Padding, - dataFormat: DataFormat = .nhwc -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("MaxPoolGradGradV2", nOutputs) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(origInput) - op.addInput(origOutput) - op.addInput(grad) - op.addInput(ksize) - op.addInput(strides) - return op.execute(Int(1)) + origInput: Tensor, + origOutput: Tensor, + grad: Tensor, + ksize: Tensor, + strides: Tensor, + padding: Padding, + dataFormat: DataFormat = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPoolGradGradV2", nOutputs) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(grad) + op.addInput(ksize) + op.addInput(strides) + return op.execute(Int(1)) } /// Computes second-order gradients of the maxpooling function. /// /// - Parameters: -/// - input: The original input. -/// - grad: 4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. the -/// input of `max_pool`. -/// - argmax: The indices of the maximum values chosen for each output of `max_pool`. +/// - input: The original input. +/// - grad: 4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. the +/// input of `max_pool`. +/// - argmax: The indices of the maximum values chosen for each output of `max_pool`. /// /// - Attrs: -/// - ksize: The size of the window for each dimension of the input tensor. -/// - strides: The stride of the sliding window for each dimension of the -/// input tensor. -/// - padding: The type of padding algorithm to use. -/// - include_batch_in_index: Whether to include batch dimension in flattened index of `argmax`. +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// - padding: The type of padding algorithm to use. +/// - include_batch_in_index: Whether to include batch dimension in flattened index of `argmax`. /// /// - Output output: Gradients of gradients w.r.t. the input of `max_pool`. @inlinable @inline(__always) @@ -16651,84 +16638,84 @@ public static func maxPoolGradGradWithArgmax< Targmax: BinaryInteger & TensorFlowScalar, T: Numeric & TensorFlowScalar >( - _ input: Tensor, - grad: Tensor, - argmax: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding, - includeBatchInIndex: Bool = false -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("MaxPoolGradGradWithArgmax", nOutputs) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("include_batch_in_index", includeBatchInIndex) - op.updateAttribute("Targmax", Targmax.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - op.addInput(grad) - op.addInput(argmax) - return op.execute(Int(1)) + _ input: Tensor, + grad: Tensor, + argmax: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + includeBatchInIndex: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPoolGradGradWithArgmax", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("include_batch_in_index", includeBatchInIndex) + op.updateAttribute("Targmax", Targmax.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(grad) + op.addInput(argmax) + return op.execute(Int(1)) } /// Computes gradients of the maxpooling function. /// /// - Parameters: -/// - orig_input: The original input tensor. -/// - orig_output: The original output tensor. -/// - grad: 4-D. Gradients w.r.t. the output of `max_pool`. -/// - ksize: The size of the window for each dimension of the input tensor. -/// - strides: The stride of the sliding window for each dimension of the -/// input tensor. +/// - orig_input: The original input tensor. +/// - orig_output: The original output tensor. +/// - grad: 4-D. Gradients w.r.t. the output of `max_pool`. +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. /// /// - Attrs: -/// - padding: The type of padding algorithm to use. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, in_channels, in_height, in_width]. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. /// /// - Output output: Gradients w.r.t. the input to `max_pool`. @inlinable @inline(__always) public static func maxPoolGradV2( - origInput: Tensor, - origOutput: Tensor, - grad: Tensor, - ksize: Tensor, - strides: Tensor, - padding: Padding, - dataFormat: DataFormat = .nhwc -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("MaxPoolGradV2", nOutputs) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(origInput) - op.addInput(origOutput) - op.addInput(grad) - op.addInput(ksize) - op.addInput(strides) - return op.execute(Int(1)) + origInput: Tensor, + origOutput: Tensor, + grad: Tensor, + ksize: Tensor, + strides: Tensor, + padding: Padding, + dataFormat: DataFormat = .nhwc +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPoolGradV2", nOutputs) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(origInput) + op.addInput(origOutput) + op.addInput(grad) + op.addInput(ksize) + op.addInput(strides) + return op.execute(Int(1)) } /// Computes gradients of the maxpooling function. /// /// - Parameters: -/// - input: The original input. -/// - grad: 4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. the -/// output of `max_pool`. -/// - argmax: The indices of the maximum values chosen for each output of `max_pool`. +/// - input: The original input. +/// - grad: 4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. the +/// output of `max_pool`. +/// - argmax: The indices of the maximum values chosen for each output of `max_pool`. /// /// - Attrs: -/// - ksize: The size of the window for each dimension of the input tensor. -/// - strides: The stride of the sliding window for each dimension of the -/// input tensor. -/// - padding: The type of padding algorithm to use. -/// - include_batch_in_index: Whether to include batch dimension in flattened index of `argmax`. +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// - padding: The type of padding algorithm to use. +/// - include_batch_in_index: Whether to include batch dimension in flattened index of `argmax`. /// /// - Output output: Gradients w.r.t. the input of `max_pool`. @inlinable @inline(__always) @@ -16736,62 +16723,62 @@ public static func maxPoolGradWithArgmax< Targmax: BinaryInteger & TensorFlowScalar, T: Numeric & TensorFlowScalar >( - _ input: Tensor, - grad: Tensor, - argmax: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding, - includeBatchInIndex: Bool = false -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("MaxPoolGradWithArgmax", nOutputs) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("include_batch_in_index", includeBatchInIndex) - op.updateAttribute("Targmax", Targmax.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - op.addInput(grad) - op.addInput(argmax) - return op.execute(Int(1)) + _ input: Tensor, + grad: Tensor, + argmax: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + includeBatchInIndex: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("MaxPoolGradWithArgmax", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("include_batch_in_index", includeBatchInIndex) + op.updateAttribute("Targmax", Targmax.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(grad) + op.addInput(argmax) + return op.execute(Int(1)) } /// Performs max pooling on the input. /// /// - Parameters: -/// - input: 4-D input to pool over. -/// - ksize: The size of the window for each dimension of the input tensor. -/// - strides: The stride of the sliding window for each dimension of the -/// input tensor. +/// - input: 4-D input to pool over. +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. /// /// - Attrs: -/// - padding: The type of padding algorithm to use. -/// - data_format: Specify the data format of the input and output data. With the -/// default format "NHWC", the data is stored in the order of: -/// [batch, in_height, in_width, in_channels]. -/// Alternatively, the format could be "NCHW", the data storage order of: -/// [batch, in_channels, in_height, in_width]. +/// - padding: The type of padding algorithm to use. +/// - data_format: Specify the data format of the input and output data. With the +/// default format "NHWC", the data is stored in the order of: +/// [batch, in_height, in_width, in_channels]. +/// Alternatively, the format could be "NCHW", the data storage order of: +/// [batch, in_channels, in_height, in_width]. /// /// - Output output: The max pooled output tensor. @inlinable @inline(__always) public static func maxPoolV2( - _ input: Tensor, - ksize: Tensor, - strides: Tensor, - padding: Padding, - dataFormat: DataFormat4 = .nhwc + _ input: Tensor, + ksize: Tensor, + strides: Tensor, + padding: Padding, + dataFormat: DataFormat4 = .nhwc ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MaxPoolV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("data_format", dataFormat.cName) - op.addInput(input) - op.addInput(ksize) - op.addInput(strides) - return op.execute(Int(1)) + let op = makeOp("MaxPoolV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("data_format", dataFormat.cName) + op.addInput(input) + op.addInput(ksize) + op.addInput(strides) + return op.execute(Int(1)) } /// Performs max pooling on the input and outputs both max values and indices. @@ -16809,36 +16796,36 @@ public static func maxPoolV2( /// - Parameter input: 4-D with shape `[batch, height, width, channels]`. Input to pool over. /// /// - Attrs: -/// - ksize: The size of the window for each dimension of the input tensor. -/// - strides: The stride of the sliding window for each dimension of the -/// input tensor. -/// - padding: The type of padding algorithm to use. -/// - include_batch_in_index: Whether to include batch dimension in flattened index of `argmax`. +/// - ksize: The size of the window for each dimension of the input tensor. +/// - strides: The stride of the sliding window for each dimension of the +/// input tensor. +/// - padding: The type of padding algorithm to use. +/// - include_batch_in_index: Whether to include batch dimension in flattened index of `argmax`. /// /// - Outputs: -/// - output: The max pooled output tensor. -/// - argmax: 4-D. The flattened indices of the max values chosen for each output. +/// - output: The max pooled output tensor. +/// - argmax: 4-D. The flattened indices of the max values chosen for each output. @inlinable @inline(__always) public static func maxPoolWithArgmax< Targmax: BinaryInteger & TensorFlowScalar, T: Numeric & TensorFlowScalar >( - _ input: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding, - includeBatchInIndex: Bool = false + _ input: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding, + includeBatchInIndex: Bool = false ) -> (output: Tensor, argmax: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("MaxPoolWithArgmax", nOutputs) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("Targmax", Targmax.tensorFlowDataType) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("include_batch_in_index", includeBatchInIndex) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1), Int(1)) + let op = makeOp("MaxPoolWithArgmax", nOutputs) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("Targmax", Targmax.tensorFlowDataType) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("include_batch_in_index", includeBatchInIndex) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) } /// Returns the max of x and y (i.e. x > y ? x : y) element-wise. @@ -16847,15 +16834,15 @@ public static func maxPoolWithArgmax< /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func maximum( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Maximum", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Maximum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Computes the mean of elements across dimensions of a tensor. @@ -16866,9 +16853,9 @@ public static func maximum( /// retained with length 1. /// /// - Parameters: -/// - input: The tensor to reduce. -/// - reduction_indices: The dimensions to reduce. Must be in the range -/// `[-rank(input), rank(input))`. +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. /// /// - Attr keep_dims: If true, retain reduced dimensions with length 1. /// @@ -16878,18 +16865,18 @@ public static func mean< T: Numeric & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - reductionIndices: Tensor, - keepDims: Bool = false + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Mean", nOutputs) - op.updateAttribute("keep_dims", keepDims) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(input) - op.addInput(reductionIndices) - return op.execute(Int(1)) + let op = makeOp("Mean", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) } /// Forwards the value of an available tensor from `inputs` to `output`. @@ -16903,18 +16890,18 @@ public static func mean< /// - Parameter inputs: The input tensors, exactly one of which will become available. /// /// - Outputs: -/// - output: Will be set to the available input tensor. -/// - value_index: The index of the chosen input tensor in `inputs`. +/// - output: Will be set to the available input tensor. +/// - value_index: The index of the chosen input tensor in `inputs`. @inlinable @inline(__always) public static func merge( - inputs: [Tensor] + inputs: [Tensor] ) -> (output: Tensor, valueIndex: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("Merge", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("N", inputs.count) - op.addInputList(inputs) - return op.execute(Int(1), Int(1)) + let op = makeOp("Merge", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", inputs.count) + op.addInputList(inputs) + return op.execute(Int(1), Int(1)) } /// Merges summaries. @@ -16928,18 +16915,18 @@ public static func merge( /// in the summaries to merge use the same tag. /// /// - Parameter inputs: Can be of any shape. Each must contain serialized `Summary` protocol -/// buffers. +/// buffers. /// /// - Output summary: Scalar. Serialized `Summary` protocol buffer. @inlinable @inline(__always) public static func mergeSummary( - inputs: [StringTensor] + inputs: [StringTensor] ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("MergeSummary", nOutputs) - op.updateAttribute("N", inputs.count) - op.addInputList(inputs) - return op.execute(Int(1)) + let op = makeOp("MergeSummary", nOutputs) + op.updateAttribute("N", inputs.count) + op.addInputList(inputs) + return op.execute(Int(1)) } /// V2 format specific: merges the metadata files of sharded checkpoints. The @@ -16954,23 +16941,23 @@ public static func mergeSummary( /// user-facing temporary locations. /// /// - Parameters: -/// - checkpoint_prefixes: prefixes of V2 checkpoints to merge. -/// - destination_prefix: scalar. The desired final prefix. Allowed to be the same -/// as one of the checkpoint_prefixes. +/// - checkpoint_prefixes: prefixes of V2 checkpoints to merge. +/// - destination_prefix: scalar. The desired final prefix. Allowed to be the same +/// as one of the checkpoint_prefixes. /// /// - Attr delete_old_dirs: see above. @inlinable @inline(__always) public static func mergeV2Checkpoints( - checkpointPrefixes: StringTensor, - destinationPrefix: StringTensor, - deleteOldDirs: Bool = true + checkpointPrefixes: StringTensor, + destinationPrefix: StringTensor, + deleteOldDirs: Bool = true ) { let nOutputs = 0 - let op = makeOp("MergeV2Checkpoints", nOutputs) - op.updateAttribute("delete_old_dirs", deleteOldDirs) - op.addInput(checkpointPrefixes) - op.addInput(destinationPrefix) - op.execute() + let op = makeOp("MergeV2Checkpoints", nOutputs) + op.updateAttribute("delete_old_dirs", deleteOldDirs) + op.addInput(checkpointPrefixes) + op.addInput(destinationPrefix) + op.execute() } /// Transforms a spectrogram into a form that's useful for speech recognition. @@ -16983,35 +16970,35 @@ public static func mergeV2Checkpoints( /// is a good resource to learn more. /// /// - Parameters: -/// - spectrogram: Typically produced by the Spectrogram op, with magnitude_squared -/// set to true. -/// - sample_rate: How many samples per second the source audio used. +/// - spectrogram: Typically produced by the Spectrogram op, with magnitude_squared +/// set to true. +/// - sample_rate: How many samples per second the source audio used. /// /// - Attrs: -/// - upper_frequency_limit: The highest frequency to use when calculating the -/// ceptstrum. -/// - lower_frequency_limit: The lowest frequency to use when calculating the -/// ceptstrum. -/// - filterbank_channel_count: Resolution of the Mel bank used internally. -/// - dct_coefficient_count: How many output channels to produce per time slice. +/// - upper_frequency_limit: The highest frequency to use when calculating the +/// ceptstrum. +/// - lower_frequency_limit: The lowest frequency to use when calculating the +/// ceptstrum. +/// - filterbank_channel_count: Resolution of the Mel bank used internally. +/// - dct_coefficient_count: How many output channels to produce per time slice. @inlinable @inline(__always) public static func mfcc( - spectrogram: Tensor, - sampleRate: Tensor, - upperFrequencyLimit: Double = 4000, - lowerFrequencyLimit: Double = 20, - filterbankChannelCount: Int64 = 40, - dctCoefficientCount: Int64 = 13 + spectrogram: Tensor, + sampleRate: Tensor, + upperFrequencyLimit: Double = 4000, + lowerFrequencyLimit: Double = 20, + filterbankChannelCount: Int64 = 40, + dctCoefficientCount: Int64 = 13 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Mfcc", nOutputs) - op.updateAttribute("upper_frequency_limit", upperFrequencyLimit) - op.updateAttribute("lower_frequency_limit", lowerFrequencyLimit) - op.updateAttribute("filterbank_channel_count", filterbankChannelCount) - op.updateAttribute("dct_coefficient_count", dctCoefficientCount) - op.addInput(spectrogram) - op.addInput(sampleRate) - return op.execute(Int(1)) + let op = makeOp("Mfcc", nOutputs) + op.updateAttribute("upper_frequency_limit", upperFrequencyLimit) + op.updateAttribute("lower_frequency_limit", lowerFrequencyLimit) + op.updateAttribute("filterbank_channel_count", filterbankChannelCount) + op.updateAttribute("dct_coefficient_count", dctCoefficientCount) + op.addInput(spectrogram) + op.addInput(sampleRate) + return op.execute(Int(1)) } /// Computes the minimum of elements across dimensions of a tensor. @@ -17022,9 +17009,9 @@ public static func mfcc( /// retained with length 1. /// /// - Parameters: -/// - input: The tensor to reduce. -/// - reduction_indices: The dimensions to reduce. Must be in the range -/// `[-rank(input), rank(input))`. +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. /// /// - Attr keep_dims: If true, retain reduced dimensions with length 1. /// @@ -17034,18 +17021,18 @@ public static func min< T: Numeric & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - reductionIndices: Tensor, - keepDims: Bool = false + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Min", nOutputs) - op.updateAttribute("keep_dims", keepDims) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(input) - op.addInput(reductionIndices) - return op.execute(Int(1)) + let op = makeOp("Min", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) } /// Returns the min of x and y (i.e. x < y ? x : y) element-wise. @@ -17054,15 +17041,15 @@ public static func min< /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func minimum( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Minimum", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Minimum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Pads a tensor with mirrored values. @@ -17094,15 +17081,15 @@ public static func minimum( /// ``` /// /// - Parameters: -/// - input: The input tensor to be padded. -/// - paddings: A two-column matrix specifying the padding sizes. The number of -/// rows must be the same as the rank of `input`. +/// - input: The input tensor to be padded. +/// - paddings: A two-column matrix specifying the padding sizes. The number of +/// rows must be the same as the rank of `input`. /// /// - Attr mode: Either `REFLECT` or `SYMMETRIC`. In reflect mode the padded regions -/// do not include the borders, while in symmetric mode the padded regions -/// do include the borders. For example, if `input` is `[1, 2, 3]` and `paddings` -/// is `[0, 2]`, then the output is `[1, 2, 3, 2, 1]` in reflect mode, and -/// it is `[1, 2, 3, 3, 2]` in symmetric mode. +/// do not include the borders, while in symmetric mode the padded regions +/// do include the borders. For example, if `input` is `[1, 2, 3]` and `paddings` +/// is `[0, 2]`, then the output is `[1, 2, 3, 2, 1]` in reflect mode, and +/// it is `[1, 2, 3, 3, 2]` in symmetric mode. /// /// - Output output: The padded tensor. @inlinable @inline(__always) @@ -17110,18 +17097,18 @@ public static func mirrorPad< T: TensorFlowScalar, Tpaddings: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - paddings: Tensor, - mode: Mode5 + _ input: Tensor, + paddings: Tensor, + mode: Mode5 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MirrorPad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) - op.updateAttribute("mode", mode.cName) - op.addInput(input) - op.addInput(paddings) - return op.execute(Int(1)) + let op = makeOp("MirrorPad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) + op.updateAttribute("mode", mode.cName) + op.addInput(input) + op.addInput(paddings) + return op.execute(Int(1)) } /// Gradient op for `MirrorPad` op. This op folds a mirror-padded tensor. @@ -17146,9 +17133,9 @@ public static func mirrorPad< /// ``` /// /// - Parameters: -/// - input: The input tensor to be folded. -/// - paddings: A two-column matrix specifying the padding sizes. The number of -/// rows must be the same as the rank of `input`. +/// - input: The input tensor to be folded. +/// - paddings: A two-column matrix specifying the padding sizes. The number of +/// rows must be the same as the rank of `input`. /// /// - Attr mode: The mode used in the `MirrorPad` op. /// @@ -17158,28 +17145,28 @@ public static func mirrorPadGrad< T: TensorFlowScalar, Tpaddings: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - paddings: Tensor, - mode: Mode5 + _ input: Tensor, + paddings: Tensor, + mode: Mode5 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MirrorPadGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) - op.updateAttribute("mode", mode.cName) - op.addInput(input) - op.addInput(paddings) - return op.execute(Int(1)) + let op = makeOp("MirrorPadGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) + op.updateAttribute("mode", mode.cName) + op.addInput(input) + op.addInput(paddings) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func mixedStruct( - nA: Int64 + nA: Int64 ) -> (a: [Tensor], b: Tensor) { let nOutputs = Int(nA) + Int(1) - let op = makeOp("MixedStruct", nOutputs) - op.updateAttribute("n_a", nA) - return op.execute(Int(nA), Int(1)) + let op = makeOp("MixedStruct", nOutputs) + op.updateAttribute("n_a", nA) + return op.execute(Int(nA), Int(1)) } /// Returns element-wise remainder of division. This emulates C semantics in that @@ -17191,15 +17178,15 @@ public static func mixedStruct( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func mod( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Mod", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Mod", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Identity transformation that models performance. @@ -17209,18 +17196,18 @@ public static func mod( /// - Parameter input_dataset: A variant tensor representing the input dataset. @inlinable @inline(__always) public static func modelDataset( - inputDataset: VariantHandle, - cpuBudget: Int64 = 0, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + cpuBudget: Int64 = 0, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ModelDataset", nOutputs) - op.updateAttribute("cpu_budget", cpuBudget) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - return op.execute(Int(1)) + let op = makeOp("ModelDataset", nOutputs) + op.updateAttribute("cpu_budget", cpuBudget) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + return op.execute(Int(1)) } /// Returns x * y element-wise. @@ -17229,15 +17216,15 @@ public static func modelDataset( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func mul( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Mul", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Mul", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns x * y element-wise. Returns zero if y is zero, even if x if infinite or NaN. @@ -17246,45 +17233,45 @@ public static func mul( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func mulNoNan( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MulNoNan", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("MulNoNan", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Creates a MultiDeviceIterator resource. /// /// - Attrs: -/// - devices: A list of devices the iterator works across. -/// - shared_name: If non-empty, this resource will be shared under the given name -/// across multiple sessions. -/// - container: If non-empty, this resource is placed in the given container. -/// Otherwise, a default container is used. -/// - output_types: The type list for the return values. -/// - output_shapes: The list of shapes being produced. +/// - devices: A list of devices the iterator works across. +/// - shared_name: If non-empty, this resource will be shared under the given name +/// across multiple sessions. +/// - container: If non-empty, this resource is placed in the given container. +/// Otherwise, a default container is used. +/// - output_types: The type list for the return values. +/// - output_shapes: The list of shapes being produced. /// /// - Output handle: Handle to the resource created. @inlinable @inline(__always) public static func multiDeviceIterator( - devices: [String], - sharedName: String, - container: String, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + devices: [String], + sharedName: String, + container: String, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("MultiDeviceIterator", nOutputs) - op.updateAttribute("devices", devices) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("container", container) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - return op.execute(Int(1)) + let op = makeOp("MultiDeviceIterator", nOutputs) + op.updateAttribute("devices", devices) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("container", container) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + return op.execute(Int(1)) } /// Generates a MultiDeviceIterator resource from its provided string handle. @@ -17292,74 +17279,74 @@ public static func multiDeviceIterator( /// - Parameter string_handle: String representing the resource. /// /// - Attrs: -/// - output_types: The type list for the return values. -/// - output_shapes: The list of shapes being produced. +/// - output_types: The type list for the return values. +/// - output_shapes: The list of shapes being produced. /// /// - Output multi_device_iterator: A MultiDeviceIterator resource. @inlinable @inline(__always) public static func multiDeviceIteratorFromStringHandle( - stringHandle: StringTensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + stringHandle: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("MultiDeviceIteratorFromStringHandle", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(stringHandle) - return op.execute(Int(1)) + let op = makeOp("MultiDeviceIteratorFromStringHandle", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(stringHandle) + return op.execute(Int(1)) } /// Gets next element for the provided shard number. /// /// - Parameters: -/// - multi_device_iterator: A MultiDeviceIterator resource. -/// - shard_num: Integer representing which shard to fetch data for. -/// - incarnation_id: Which incarnation of the MultiDeviceIterator is running. +/// - multi_device_iterator: A MultiDeviceIterator resource. +/// - shard_num: Integer representing which shard to fetch data for. +/// - incarnation_id: Which incarnation of the MultiDeviceIterator is running. /// /// - Attrs: -/// - output_types: The type list for the return values. -/// - output_shapes: The list of shapes being produced. +/// - output_types: The type list for the return values. +/// - output_shapes: The list of shapes being produced. /// /// - Output components: Result of the get_next on the dataset. @inlinable @inline(__always) public static func multiDeviceIteratorGetNextFromShard( - multiDeviceIterator: ResourceHandle, - shardNum: Tensor, - incarnationId: Tensor, - outputShapes: [TensorShape?] + multiDeviceIterator: ResourceHandle, + shardNum: Tensor, + incarnationId: Tensor, + outputShapes: [TensorShape?] ) -> OutputTypes { let nOutputs = Int(OutputTypes._typeList.count) - let op = makeOp("MultiDeviceIteratorGetNextFromShard", nOutputs) - op.updateAttribute("output_types", OutputTypes._typeList) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(multiDeviceIterator) - op.addInput(shardNum) - op.addInput(incarnationId) - return op.execute(Int(OutputTypes._typeList.count)) + let op = makeOp("MultiDeviceIteratorGetNextFromShard", nOutputs) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(multiDeviceIterator) + op.addInput(shardNum) + op.addInput(incarnationId) + return op.execute(Int(OutputTypes._typeList.count)) } /// Initializes the multi device iterator with the given dataset. /// /// - Parameters: -/// - dataset: Dataset to be iterated upon. -/// - multi_device_iterator: A MultiDeviceIteratorResource. -/// - max_buffer_size: The maximum size of the host side per device buffer to keep. +/// - dataset: Dataset to be iterated upon. +/// - multi_device_iterator: A MultiDeviceIteratorResource. +/// - max_buffer_size: The maximum size of the host side per device buffer to keep. /// /// - Output incarnation_id: An int64 indicating which incarnation of the MultiDeviceIterator -/// is running. +/// is running. @inlinable @inline(__always) public static func multiDeviceIteratorInit( - dataset: VariantHandle, - multiDeviceIterator: ResourceHandle, - maxBufferSize: Tensor + dataset: VariantHandle, + multiDeviceIterator: ResourceHandle, + maxBufferSize: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("MultiDeviceIteratorInit", nOutputs) - op.addInput(dataset) - op.addInput(multiDeviceIterator) - op.addInput(maxBufferSize) - return op.execute(Int(1)) + let op = makeOp("MultiDeviceIteratorInit", nOutputs) + op.addInput(dataset) + op.addInput(multiDeviceIterator) + op.addInput(maxBufferSize) + return op.execute(Int(1)) } /// Produces a string handle for the given MultiDeviceIterator. @@ -17369,47 +17356,47 @@ public static func multiDeviceIteratorInit( /// - Output string_handle: A string representing the resource. @inlinable @inline(__always) public static func multiDeviceIteratorToStringHandle( - multiDeviceIterator: ResourceHandle + multiDeviceIterator: ResourceHandle ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("MultiDeviceIteratorToStringHandle", nOutputs) - op.addInput(multiDeviceIterator) - return op.execute(Int(1)) + let op = makeOp("MultiDeviceIteratorToStringHandle", nOutputs) + op.addInput(multiDeviceIterator) + return op.execute(Int(1)) } /// Draws samples from a multinomial distribution. /// /// - Parameters: -/// - logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]` -/// represents the unnormalized log probabilities for all classes. -/// - num_samples: 0-D. Number of independent samples to draw for each row slice. +/// - logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]` +/// represents the unnormalized log probabilities for all classes. +/// - num_samples: 0-D. Number of independent samples to draw for each row slice. /// /// - Attrs: -/// - seed: If either seed or seed2 is set to be non-zero, the internal random number -/// generator is seeded by the given seed. Otherwise, a random seed is used. -/// - seed2: A second seed to avoid seed collision. +/// - seed: If either seed or seed2 is set to be non-zero, the internal random number +/// generator is seeded by the given seed. Otherwise, a random seed is used. +/// - seed2: A second seed to avoid seed collision. /// /// - Output output: 2-D Tensor with shape `[batch_size, num_samples]`. Each slice `[i, :]` -/// contains the drawn class labels with range `[0, num_classes)`. +/// contains the drawn class labels with range `[0, num_classes)`. @inlinable @inline(__always) public static func multinomial< T: Numeric & TensorFlowScalar, OutputDtype: BinaryInteger & TensorFlowScalar >( - logits: Tensor, - numSamples: Tensor, - seed: Int64 = 0, - seed2: Int64 = 0 + logits: Tensor, + numSamples: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Multinomial", nOutputs) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("output_dtype", OutputDtype.tensorFlowDataType) - op.addInput(logits) - op.addInput(numSamples) - return op.execute(Int(1)) + let op = makeOp("Multinomial", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("output_dtype", OutputDtype.tensorFlowDataType) + op.addInput(logits) + op.addInput(numSamples) + return op.execute(Int(1)) } /// Creates an empty hash table that uses tensors as the backing store. @@ -17422,47 +17409,47 @@ public static func multinomial< /// the insert operations. It does not support the initialization operation. /// /// - Parameter empty_key: The key used to represent empty key buckets internally. Must not -/// be used in insert or lookup operations. +/// be used in insert or lookup operations. /// /// - Attrs: -/// - container: If non-empty, this table is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this table is shared under the given name across -/// multiple sessions. -/// - key_dtype: Type of the table keys. -/// - value_dtype: Type of the table values. -/// - value_shape: The shape of each value. -/// - initial_num_buckets: The initial number of hash table buckets. Must be a power -/// to 2. -/// - max_load_factor: The maximum ratio between number of entries and number of -/// buckets before growing the table. Must be between 0 and 1. +/// - container: If non-empty, this table is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this table is shared under the given name across +/// multiple sessions. +/// - key_dtype: Type of the table keys. +/// - value_dtype: Type of the table values. +/// - value_shape: The shape of each value. +/// - initial_num_buckets: The initial number of hash table buckets. Must be a power +/// to 2. +/// - max_load_factor: The maximum ratio between number of entries and number of +/// buckets before growing the table. Must be between 0 and 1. /// /// - Output table_handle: Handle to a table. @inlinable @inline(__always) public static func mutableDenseHashTableV2( - emptyKey: Tensor, - deletedKey: Tensor, - container: String, - sharedName: String, - useNodeNameSharing: Bool = false, - valueDtype: TensorDataType, - valueShape: TensorShape?, - initialNumBuckets: Int64 = 131072, - maxLoadFactor: Double = 0.8 + emptyKey: Tensor, + deletedKey: Tensor, + container: String, + sharedName: String, + useNodeNameSharing: Bool = false, + valueDtype: TensorDataType, + valueShape: TensorShape?, + initialNumBuckets: Int64 = 131072, + maxLoadFactor: Double = 0.8 ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("MutableDenseHashTableV2", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("use_node_name_sharing", useNodeNameSharing) - op.updateAttribute("key_dtype", KeyDtype.tensorFlowDataType) - op.updateAttribute("value_dtype", valueDtype) - op.updateAttribute("value_shape", valueShape) - op.updateAttribute("initial_num_buckets", initialNumBuckets) - op.updateAttribute("max_load_factor", maxLoadFactor) - op.addInput(emptyKey) - op.addInput(deletedKey) - return op.execute(Int(1)) + let op = makeOp("MutableDenseHashTableV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("use_node_name_sharing", useNodeNameSharing) + op.updateAttribute("key_dtype", KeyDtype.tensorFlowDataType) + op.updateAttribute("value_dtype", valueDtype) + op.updateAttribute("value_shape", valueShape) + op.updateAttribute("initial_num_buckets", initialNumBuckets) + op.updateAttribute("max_load_factor", maxLoadFactor) + op.addInput(emptyKey) + op.addInput(deletedKey) + return op.execute(Int(1)) } /// Creates an empty hash table. @@ -17472,32 +17459,32 @@ public static func mutableDenseHashTableV2( /// the insert operations. It does not support the initialization operation. /// /// - Attrs: -/// - container: If non-empty, this table is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this table is shared under the given name across -/// multiple sessions. -/// - key_dtype: Type of the table keys. -/// - value_dtype: Type of the table values. +/// - container: If non-empty, this table is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this table is shared under the given name across +/// multiple sessions. +/// - key_dtype: Type of the table keys. +/// - value_dtype: Type of the table values. /// /// - Output table_handle: Handle to a table. @inlinable @inline(__always) public static func mutableHashTableOfTensorsV2( - container: String, - sharedName: String, - useNodeNameSharing: Bool = false, - keyDtype: TensorDataType, - valueDtype: TensorDataType, - valueShape: TensorShape? + container: String, + sharedName: String, + useNodeNameSharing: Bool = false, + keyDtype: TensorDataType, + valueDtype: TensorDataType, + valueShape: TensorShape? ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("MutableHashTableOfTensorsV2", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("use_node_name_sharing", useNodeNameSharing) - op.updateAttribute("key_dtype", keyDtype) - op.updateAttribute("value_dtype", valueDtype) - op.updateAttribute("value_shape", valueShape) - return op.execute(Int(1)) + let op = makeOp("MutableHashTableOfTensorsV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("use_node_name_sharing", useNodeNameSharing) + op.updateAttribute("key_dtype", keyDtype) + op.updateAttribute("value_dtype", valueDtype) + op.updateAttribute("value_shape", valueShape) + return op.execute(Int(1)) } /// Creates an empty hash table. @@ -17507,32 +17494,32 @@ public static func mutableHashTableOfTensorsV2( /// the insert operations. It does not support the initialization operation. /// /// - Attrs: -/// - container: If non-empty, this table is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this table is shared under the given name across -/// multiple sessions. -/// - use_node_name_sharing: If true and shared_name is empty, the table is shared -/// using the node name. -/// - key_dtype: Type of the table keys. -/// - value_dtype: Type of the table values. +/// - container: If non-empty, this table is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this table is shared under the given name across +/// multiple sessions. +/// - use_node_name_sharing: If true and shared_name is empty, the table is shared +/// using the node name. +/// - key_dtype: Type of the table keys. +/// - value_dtype: Type of the table values. /// /// - Output table_handle: Handle to a table. @inlinable @inline(__always) public static func mutableHashTableV2( - container: String, - sharedName: String, - useNodeNameSharing: Bool = false, - keyDtype: TensorDataType, - valueDtype: TensorDataType + container: String, + sharedName: String, + useNodeNameSharing: Bool = false, + keyDtype: TensorDataType, + valueDtype: TensorDataType ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("MutableHashTableV2", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("use_node_name_sharing", useNodeNameSharing) - op.updateAttribute("key_dtype", keyDtype) - op.updateAttribute("value_dtype", valueDtype) - return op.execute(Int(1)) + let op = makeOp("MutableHashTableV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("use_node_name_sharing", useNodeNameSharing) + op.updateAttribute("key_dtype", keyDtype) + op.updateAttribute("value_dtype", valueDtype) + return op.execute(Int(1)) } /// Locks a mutex resource. The output is the lock. So long as the lock tensor @@ -17579,64 +17566,64 @@ public static func mutableHashTableV2( /// - Parameter mutex: The mutex resource to lock. /// /// - Output mutex_lock: A tensor that keeps a shared pointer to a lock on the mutex; -/// when the Tensor is destroyed, the use count on the shared pointer is decreased -/// by 1. When it reaches 0, the lock is released. +/// when the Tensor is destroyed, the use count on the shared pointer is decreased +/// by 1. When it reaches 0, the lock is released. @inlinable @inline(__always) public static func mutexLock( - mutex: ResourceHandle + mutex: ResourceHandle ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("MutexLock", nOutputs) - op.addInput(mutex) - return op.execute(Int(1)) + let op = makeOp("MutexLock", nOutputs) + op.addInput(mutex) + return op.execute(Int(1)) } /// Creates a Mutex resource that can be locked by `MutexLock`. /// /// - Attrs: -/// - container: If non-empty, this variable is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this variable is named in the given bucket -/// with this shared_name. Otherwise, the node name is used instead. +/// - container: If non-empty, this variable is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this variable is named in the given bucket +/// with this shared_name. Otherwise, the node name is used instead. /// /// - Output resource: The mutex resource. @inlinable @inline(__always) public static func mutexV2( - container: String, - sharedName: String + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("MutexV2", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("MutexV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func nInPolymorphicTwice( - _ a: [Tensor], - _ b: [Tensor] + _ a: [Tensor], + _ b: [Tensor] ) { let nOutputs = 0 - let op = makeOp("NInPolymorphicTwice", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("N", a.count) - op.addInputList(a) - op.addInputList(b) - op.execute() + let op = makeOp("NInPolymorphicTwice", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.addInputList(b) + op.execute() } @inlinable @inline(__always) public static func nInTwice( - _ a: [Tensor], - _ b: [StringTensor] + _ a: [Tensor], + _ b: [StringTensor] ) { let nOutputs = 0 - let op = makeOp("NInTwice", nOutputs) - op.updateAttribute("N", a.count) - op.addInputList(a) - op.addInputList(b) - op.execute() + let op = makeOp("NInTwice", nOutputs) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.addInputList(b) + op.execute() } @inlinable @inline(__always) @@ -17644,128 +17631,128 @@ public static func nInTwoTypeVariables< S: TensorFlowScalar, T: TensorFlowScalar >( - _ a: [Tensor], - _ b: [Tensor] + _ a: [Tensor], + _ b: [Tensor] ) { let nOutputs = 0 - let op = makeOp("NInTwoTypeVariables", nOutputs) - op.updateAttribute("S", S.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("N", a.count) - op.addInputList(a) - op.addInputList(b) - op.execute() + let op = makeOp("NInTwoTypeVariables", nOutputs) + op.updateAttribute("S", S.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.addInputList(b) + op.execute() } @inlinable @inline(__always) public static func nIntsIn( - _ a: [Tensor] + _ a: [Tensor] ) { let nOutputs = 0 - let op = makeOp("NIntsIn", nOutputs) - op.updateAttribute("N", a.count) - op.addInputList(a) - op.execute() + let op = makeOp("NIntsIn", nOutputs) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.execute() } @inlinable @inline(__always) public static func nIntsOut( - n: Int64 + n: Int64 ) -> [Tensor] { let nOutputs = Int(n) - let op = makeOp("NIntsOut", nOutputs) - op.updateAttribute("N", n) - return op.execute(Int(n)) + let op = makeOp("NIntsOut", nOutputs) + op.updateAttribute("N", n) + return op.execute(Int(n)) } @inlinable @inline(__always) public static func nIntsOutDefault( - n: Int64 = 3 + n: Int64 = 3 ) -> [Tensor] { let nOutputs = Int(n) - let op = makeOp("NIntsOutDefault", nOutputs) - op.updateAttribute("N", n) - return op.execute(Int(n)) + let op = makeOp("NIntsOutDefault", nOutputs) + op.updateAttribute("N", n) + return op.execute(Int(n)) } @inlinable @inline(__always) public static func nPolymorphicIn( - _ a: [Tensor] + _ a: [Tensor] ) { let nOutputs = 0 - let op = makeOp("NPolymorphicIn", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("N", a.count) - op.addInputList(a) - op.execute() + let op = makeOp("NPolymorphicIn", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.execute() } @inlinable @inline(__always) public static func nPolymorphicOut( - n: Int64 + n: Int64 ) -> [Tensor] { let nOutputs = Int(n) - let op = makeOp("NPolymorphicOut", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("N", n) - return op.execute(Int(n)) + let op = makeOp("NPolymorphicOut", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", n) + return op.execute(Int(n)) } @inlinable @inline(__always) public static func nPolymorphicOutDefault( - n: Int64 = 2 + n: Int64 = 2 ) -> [Tensor] { let nOutputs = Int(n) - let op = makeOp("NPolymorphicOutDefault", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("N", n) - return op.execute(Int(n)) + let op = makeOp("NPolymorphicOutDefault", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", n) + return op.execute(Int(n)) } @inlinable @inline(__always) public static func nPolymorphicRestrictIn( - _ a: [Tensor] + _ a: [Tensor] ) { let nOutputs = 0 - let op = makeOp("NPolymorphicRestrictIn", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("N", a.count) - op.addInputList(a) - op.execute() + let op = makeOp("NPolymorphicRestrictIn", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.execute() } @inlinable @inline(__always) public static func nPolymorphicRestrictIn( - _ a: [StringTensor] + _ a: [StringTensor] ) { let nOutputs = 0 - let op = makeOp("NPolymorphicRestrictIn", nOutputs) - op.updateAttribute("T", TensorDataType(TF_STRING)) - op.updateAttribute("N", a.count) - op.addInputList(a) - op.execute() + let op = makeOp("NPolymorphicRestrictIn", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.updateAttribute("N", a.count) + op.addInputList(a) + op.execute() } @inlinable @inline(__always) public static func nPolymorphicRestrictOut( - n: Int64 + n: Int64 ) -> [Tensor] { let nOutputs = Int(n) - let op = makeOp("NPolymorphicRestrictOut", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("N", n) - return op.execute(Int(n)) + let op = makeOp("NPolymorphicRestrictOut", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("N", n) + return op.execute(Int(n)) } @inlinable @inline(__always) public static func nPolymorphicRestrictOut( - n: Int64 + n: Int64 ) -> [StringTensor] { let nOutputs = Int(n) - let op = makeOp("NPolymorphicRestrictOut", nOutputs) - op.updateAttribute("T", TensorDataType(TF_STRING)) - op.updateAttribute("N", n) - return op.execute(Int(n)) + let op = makeOp("NPolymorphicRestrictOut", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.updateAttribute("N", n) + return op.execute(Int(n)) } /// Outputs a tensor containing the reduction across all input tensors. @@ -17784,19 +17771,19 @@ public static func nPolymorphicRestrictOut( /// shared_name: Identifier that shared between ops of the same reduction. @inlinable @inline(__always) public static func ncclAllReduce( - _ input: Tensor, - reduction: Reduction, - numDevices: Int64, - sharedName: String + _ input: Tensor, + reduction: Reduction, + numDevices: Int64, + sharedName: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("NcclAllReduce", nOutputs) - op.updateAttribute("reduction", reduction.cName) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("num_devices", numDevices) - op.updateAttribute("shared_name", sharedName) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("NcclAllReduce", nOutputs) + op.updateAttribute("reduction", reduction.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("num_devices", numDevices) + op.updateAttribute("shared_name", sharedName) + op.addInput(input) + return op.execute(Int(1)) } /// Sends `input` to all devices that are connected to the output. @@ -17812,15 +17799,15 @@ public static func ncclAllReduce( /// @inlinable @inline(__always) public static func ncclBroadcast( - _ input: Tensor, - shape: TensorShape? + _ input: Tensor, + shape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("NcclBroadcast", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("shape", shape) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("NcclBroadcast", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.addInput(input) + return op.execute(Int(1)) } /// Reduces `input` from `num_devices` using `reduction` to a single device. @@ -17835,16 +17822,16 @@ public static func ncclBroadcast( /// reduction: the reduction operation to perform. @inlinable @inline(__always) public static func ncclReduce( - _ input: [Tensor], - reduction: Reduction + _ input: [Tensor], + reduction: Reduction ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("NcclReduce", nOutputs) - op.updateAttribute("reduction", reduction.cName) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("num_devices", input.count) - op.addInputList(input) - return op.execute(Int(1)) + let op = makeOp("NcclReduce", nOutputs) + op.updateAttribute("reduction", reduction.cName) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("num_devices", input.count) + op.addInputList(input) + return op.execute(Int(1)) } /// Selects the k nearest centers for each point. @@ -17854,28 +17841,28 @@ public static func ncclReduce( /// distance to it are computed. /// /// - Parameters: -/// - points: Matrix of shape (n, d). Rows are assumed to be input points. -/// - centers: Matrix of shape (m, d). Rows are assumed to be centers. -/// - k: Number of nearest centers to return for each point. If k is larger than m, then -/// only m centers are returned. +/// - points: Matrix of shape (n, d). Rows are assumed to be input points. +/// - centers: Matrix of shape (m, d). Rows are assumed to be centers. +/// - k: Number of nearest centers to return for each point. If k is larger than m, then +/// only m centers are returned. /// /// - Outputs: -/// - nearest_center_indices: Matrix of shape (n, min(m, k)). Each row contains the indices of the centers -/// closest to the corresponding point, ordered by increasing distance. -/// - nearest_center_distances: Matrix of shape (n, min(m, k)). Each row contains the squared L2 distance to the -/// corresponding center in nearest_center_indices. +/// - nearest_center_indices: Matrix of shape (n, min(m, k)). Each row contains the indices of the centers +/// closest to the corresponding point, ordered by increasing distance. +/// - nearest_center_distances: Matrix of shape (n, min(m, k)). Each row contains the squared L2 distance to the +/// corresponding center in nearest_center_indices. @inlinable @inline(__always) public static func nearestNeighbors( - points: Tensor, - centers: Tensor, - k: Tensor + points: Tensor, + centers: Tensor, + k: Tensor ) -> (nearestCenterIndices: Tensor, nearestCenterDistances: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("NearestNeighbors", nOutputs) - op.addInput(points) - op.addInput(centers) - op.addInput(k) - return op.execute(Int(1), Int(1)) + let op = makeOp("NearestNeighbors", nOutputs) + op.addInput(points) + op.addInput(centers) + op.addInput(k) + return op.execute(Int(1), Int(1)) } /// Computes numerical negative value element-wise. @@ -17883,13 +17870,13 @@ public static func nearestNeighbors( /// I.e., \\(y = -x\\). @inlinable @inline(__always) public static func neg( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Neg", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Neg", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Returns the next representable value of `x1` in the direction of `x2`, element-wise. @@ -17903,15 +17890,15 @@ public static func neg( /// @end_compatibility @inlinable @inline(__always) public static func nextAfter( - x1: Tensor, - x2: Tensor + x1: Tensor, + x2: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("NextAfter", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x1) - op.addInput(x2) - return op.execute(Int(1)) + let op = makeOp("NextAfter", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x1) + op.addInput(x2) + return op.execute(Int(1)) } /// Makes its input available to the next iteration. @@ -17921,13 +17908,13 @@ public static func nextAfter( /// - Output output: The same tensor as `data`. @inlinable @inline(__always) public static func nextIteration( - data: Tensor + data: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("NextIteration", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(data) - return op.execute(Int(1)) + let op = makeOp("NextIteration", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(data) + return op.execute(Int(1)) } /// Does nothing. Only useful as a placeholder for control edges. @@ -17935,9 +17922,9 @@ public static func nextIteration( public static func noOp( ) { let nOutputs = 0 - let op = makeOp("NoOp", nOutputs) - - op.execute() + let op = makeOp("NoOp", nOutputs) + + op.execute() } /// Non-deterministically generates some integers. @@ -17954,14 +17941,14 @@ public static func nonDeterministicInts< Dtype: TensorFlowScalar, ShapeDtype: TensorFlowScalar >( - shape: Tensor + shape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("NonDeterministicInts", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) - op.addInput(shape) - return op.execute(Int(1)) + let op = makeOp("NonDeterministicInts", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(shape) + return op.execute(Int(1)) } /// Greedily selects a subset of bounding boxes in descending order of score, @@ -17984,31 +17971,31 @@ public static func nonDeterministicInts< /// selected_boxes = tf.gather(boxes, selected_indices) /// /// - Parameters: -/// - boxes: A 2-D float tensor of shape `[num_boxes, 4]`. -/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single -/// score corresponding to each box (each row of boxes). -/// - max_output_size: A scalar integer tensor representing the maximum number of -/// boxes to be selected by non max suppression. +/// - boxes: A 2-D float tensor of shape `[num_boxes, 4]`. +/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single +/// score corresponding to each box (each row of boxes). +/// - max_output_size: A scalar integer tensor representing the maximum number of +/// boxes to be selected by non max suppression. /// /// - Attr iou_threshold: A float representing the threshold for deciding whether boxes -/// overlap too much with respect to IOU. +/// overlap too much with respect to IOU. /// /// - Output selected_indices: A 1-D integer tensor of shape `[M]` representing the selected -/// indices from the boxes tensor, where `M <= max_output_size`. +/// indices from the boxes tensor, where `M <= max_output_size`. @inlinable @inline(__always) public static func nonMaxSuppression( - boxes: Tensor, - scores: Tensor, - maxOutputSize: Tensor, - iouThreshold: Double = 0.5 + boxes: Tensor, + scores: Tensor, + maxOutputSize: Tensor, + iouThreshold: Double = 0.5 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("NonMaxSuppression", nOutputs) - op.updateAttribute("iou_threshold", iouThreshold) - op.addInput(boxes) - op.addInput(scores) - op.addInput(maxOutputSize) - return op.execute(Int(1)) + let op = makeOp("NonMaxSuppression", nOutputs) + op.updateAttribute("iou_threshold", iouThreshold) + op.addInput(boxes) + op.addInput(scores) + op.addInput(maxOutputSize) + return op.execute(Int(1)) } /// Greedily selects a subset of bounding boxes in descending order of score, @@ -18033,31 +18020,31 @@ public static func nonMaxSuppression( /// selected_boxes = tf.gather(boxes, selected_indices) /// /// - Parameters: -/// - boxes: A 2-D float tensor of shape `[num_boxes, 4]`. -/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single -/// score corresponding to each box (each row of boxes). -/// - max_output_size: A scalar integer tensor representing the maximum number of -/// boxes to be selected by non max suppression. -/// - iou_threshold: A 0-D float tensor representing the threshold for deciding whether -/// boxes overlap too much with respect to IOU. +/// - boxes: A 2-D float tensor of shape `[num_boxes, 4]`. +/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single +/// score corresponding to each box (each row of boxes). +/// - max_output_size: A scalar integer tensor representing the maximum number of +/// boxes to be selected by non max suppression. +/// - iou_threshold: A 0-D float tensor representing the threshold for deciding whether +/// boxes overlap too much with respect to IOU. /// /// - Output selected_indices: A 1-D integer tensor of shape `[M]` representing the selected -/// indices from the boxes tensor, where `M <= max_output_size`. +/// indices from the boxes tensor, where `M <= max_output_size`. @inlinable @inline(__always) public static func nonMaxSuppressionV2( - boxes: Tensor, - scores: Tensor, - maxOutputSize: Tensor, - iouThreshold: Tensor + boxes: Tensor, + scores: Tensor, + maxOutputSize: Tensor, + iouThreshold: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("NonMaxSuppressionV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(boxes) - op.addInput(scores) - op.addInput(maxOutputSize) - op.addInput(iouThreshold) - return op.execute(Int(1)) + let op = makeOp("NonMaxSuppressionV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(boxes) + op.addInput(scores) + op.addInput(maxOutputSize) + op.addInput(iouThreshold) + return op.execute(Int(1)) } /// Greedily selects a subset of bounding boxes in descending order of score, @@ -18081,35 +18068,35 @@ public static func nonMaxSuppressionV2( /// selected_boxes = tf.gather(boxes, selected_indices) /// /// - Parameters: -/// - boxes: A 2-D float tensor of shape `[num_boxes, 4]`. -/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single -/// score corresponding to each box (each row of boxes). -/// - max_output_size: A scalar integer tensor representing the maximum number of -/// boxes to be selected by non max suppression. -/// - iou_threshold: A 0-D float tensor representing the threshold for deciding whether -/// boxes overlap too much with respect to IOU. -/// - score_threshold: A 0-D float tensor representing the threshold for deciding when to remove -/// boxes based on score. +/// - boxes: A 2-D float tensor of shape `[num_boxes, 4]`. +/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single +/// score corresponding to each box (each row of boxes). +/// - max_output_size: A scalar integer tensor representing the maximum number of +/// boxes to be selected by non max suppression. +/// - iou_threshold: A 0-D float tensor representing the threshold for deciding whether +/// boxes overlap too much with respect to IOU. +/// - score_threshold: A 0-D float tensor representing the threshold for deciding when to remove +/// boxes based on score. /// /// - Output selected_indices: A 1-D integer tensor of shape `[M]` representing the selected -/// indices from the boxes tensor, where `M <= max_output_size`. +/// indices from the boxes tensor, where `M <= max_output_size`. @inlinable @inline(__always) public static func nonMaxSuppressionV3( - boxes: Tensor, - scores: Tensor, - maxOutputSize: Tensor, - iouThreshold: Tensor, - scoreThreshold: Tensor + boxes: Tensor, + scores: Tensor, + maxOutputSize: Tensor, + iouThreshold: Tensor, + scoreThreshold: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("NonMaxSuppressionV3", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(boxes) - op.addInput(scores) - op.addInput(maxOutputSize) - op.addInput(iouThreshold) - op.addInput(scoreThreshold) - return op.execute(Int(1)) + let op = makeOp("NonMaxSuppressionV3", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(boxes) + op.addInput(scores) + op.addInput(maxOutputSize) + op.addInput(iouThreshold) + op.addInput(scoreThreshold) + return op.execute(Int(1)) } /// Greedily selects a subset of bounding boxes in descending order of score, @@ -18133,43 +18120,43 @@ public static func nonMaxSuppressionV3( /// selected_boxes = tf.gather(boxes, selected_indices) /// /// - Parameters: -/// - boxes: A 2-D float tensor of shape `[num_boxes, 4]`. -/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single -/// score corresponding to each box (each row of boxes). -/// - max_output_size: A scalar integer tensor representing the maximum number of -/// boxes to be selected by non max suppression. -/// - iou_threshold: A 0-D float tensor representing the threshold for deciding whether -/// boxes overlap too much with respect to IOU. -/// - score_threshold: A 0-D float tensor representing the threshold for deciding when to remove -/// boxes based on score. +/// - boxes: A 2-D float tensor of shape `[num_boxes, 4]`. +/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single +/// score corresponding to each box (each row of boxes). +/// - max_output_size: A scalar integer tensor representing the maximum number of +/// boxes to be selected by non max suppression. +/// - iou_threshold: A 0-D float tensor representing the threshold for deciding whether +/// boxes overlap too much with respect to IOU. +/// - score_threshold: A 0-D float tensor representing the threshold for deciding when to remove +/// boxes based on score. /// /// - Attr pad_to_max_output_size: If true, the output `selected_indices` is padded to be of length -/// `max_output_size`. Defaults to false. +/// `max_output_size`. Defaults to false. /// /// - Outputs: -/// - selected_indices: A 1-D integer tensor of shape `[M]` representing the selected -/// indices from the boxes tensor, where `M <= max_output_size`. -/// - valid_outputs: A 0-D integer tensor representing the number of valid elements in -/// `selected_indices`, with the valid elements appearing first. +/// - selected_indices: A 1-D integer tensor of shape `[M]` representing the selected +/// indices from the boxes tensor, where `M <= max_output_size`. +/// - valid_outputs: A 0-D integer tensor representing the number of valid elements in +/// `selected_indices`, with the valid elements appearing first. @inlinable @inline(__always) public static func nonMaxSuppressionV4( - boxes: Tensor, - scores: Tensor, - maxOutputSize: Tensor, - iouThreshold: Tensor, - scoreThreshold: Tensor, - padToMaxOutputSize: Bool = false + boxes: Tensor, + scores: Tensor, + maxOutputSize: Tensor, + iouThreshold: Tensor, + scoreThreshold: Tensor, + padToMaxOutputSize: Bool = false ) -> (selectedIndices: Tensor, validOutputs: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("NonMaxSuppressionV4", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("pad_to_max_output_size", padToMaxOutputSize) - op.addInput(boxes) - op.addInput(scores) - op.addInput(maxOutputSize) - op.addInput(iouThreshold) - op.addInput(scoreThreshold) - return op.execute(Int(1), Int(1)) + let op = makeOp("NonMaxSuppressionV4", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("pad_to_max_output_size", padToMaxOutputSize) + op.addInput(boxes) + op.addInput(scores) + op.addInput(maxOutputSize) + op.addInput(iouThreshold) + op.addInput(scoreThreshold) + return op.execute(Int(1), Int(1)) } /// Greedily selects a subset of bounding boxes in descending order of score, @@ -18190,44 +18177,44 @@ public static func nonMaxSuppressionV4( /// selected_boxes = tf.gather(boxes, selected_indices) /// /// - Parameters: -/// - overlaps: A 2-D float tensor of shape `[num_boxes, num_boxes]` representing -/// the n-by-n box overlap values. -/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single -/// score corresponding to each box (each row of boxes). -/// - max_output_size: A scalar integer tensor representing the maximum number of -/// boxes to be selected by non max suppression. -/// - overlap_threshold: A 0-D float tensor representing the threshold for deciding whether -/// boxes overlap too. -/// - score_threshold: A 0-D float tensor representing the threshold for deciding when to remove -/// boxes based on score. +/// - overlaps: A 2-D float tensor of shape `[num_boxes, num_boxes]` representing +/// the n-by-n box overlap values. +/// - scores: A 1-D float tensor of shape `[num_boxes]` representing a single +/// score corresponding to each box (each row of boxes). +/// - max_output_size: A scalar integer tensor representing the maximum number of +/// boxes to be selected by non max suppression. +/// - overlap_threshold: A 0-D float tensor representing the threshold for deciding whether +/// boxes overlap too. +/// - score_threshold: A 0-D float tensor representing the threshold for deciding when to remove +/// boxes based on score. /// /// - Output selected_indices: A 1-D integer tensor of shape `[M]` representing the selected -/// indices from the boxes tensor, where `M <= max_output_size`. +/// indices from the boxes tensor, where `M <= max_output_size`. @inlinable @inline(__always) public static func nonMaxSuppressionWithOverlaps( - overlaps: Tensor, - scores: Tensor, - maxOutputSize: Tensor, - overlapThreshold: Tensor, - scoreThreshold: Tensor + overlaps: Tensor, + scores: Tensor, + maxOutputSize: Tensor, + overlapThreshold: Tensor, + scoreThreshold: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("NonMaxSuppressionWithOverlaps", nOutputs) - op.addInput(overlaps) - op.addInput(scores) - op.addInput(maxOutputSize) - op.addInput(overlapThreshold) - op.addInput(scoreThreshold) - return op.execute(Int(1)) + let op = makeOp("NonMaxSuppressionWithOverlaps", nOutputs) + op.addInput(overlaps) + op.addInput(scores) + op.addInput(maxOutputSize) + op.addInput(overlapThreshold) + op.addInput(scoreThreshold) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func none( ) { let nOutputs = 0 - let op = makeOp("None", nOutputs) - - op.execute() + let op = makeOp("None", nOutputs) + + op.execute() } /// Returns the truth value of (x != y) element-wise. @@ -18236,15 +18223,15 @@ public static func none( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func notEqual( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("NotEqual", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("NotEqual", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns the truth value of (x != y) element-wise. @@ -18253,15 +18240,15 @@ public static func notEqual( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func notEqual( - _ x: StringTensor, - _ y: StringTensor + _ x: StringTensor, + _ y: StringTensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("NotEqual", nOutputs) - op.updateAttribute("T", TensorDataType(TF_STRING)) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("NotEqual", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Finds values of the `n`-th order statistic for the last dimension. @@ -18275,36 +18262,36 @@ public static func notEqual( /// values.shape = input.shape[:-1] /// /// - Parameters: -/// - input: 1-D or higher with last dimension at least `n+1`. -/// - n: 0-D. Position of sorted vector to select along the last dimension (along -/// each row for matrices). Valid range of n is `[0, input.shape[:-1])` +/// - input: 1-D or higher with last dimension at least `n+1`. +/// - n: 0-D. Position of sorted vector to select along the last dimension (along +/// each row for matrices). Valid range of n is `[0, input.shape[:-1])` /// /// - Attr reverse: When set to True, find the nth-largest value in the vector and vice -/// versa. +/// versa. /// /// - Output values: The `n`-th order statistic along each last dimensional slice. @inlinable @inline(__always) public static func nthElement( - _ input: Tensor, - n: Tensor, - reverse: Bool = false + _ input: Tensor, + n: Tensor, + reverse: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("NthElement", nOutputs) - op.updateAttribute("reverse", reverse) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - op.addInput(n) - return op.execute(Int(1)) + let op = makeOp("NthElement", nOutputs) + op.updateAttribute("reverse", reverse) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(n) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func old( ) { let nOutputs = 0 - let op = makeOp("Old", nOutputs) - - op.execute() + let op = makeOp("Old", nOutputs) + + op.execute() } /// Returns a one-hot tensor. @@ -18398,10 +18385,10 @@ public static func old( /// ``` /// /// - Parameters: -/// - indices: A tensor of indices. -/// - depth: A scalar defining the depth of the one hot dimension. -/// - on_value: A scalar defining the value to fill in output when `indices[j] = i`. -/// - off_value: A scalar defining the value to fill in output when `indices[j] != i`. +/// - indices: A tensor of indices. +/// - depth: A scalar defining the depth of the one hot dimension. +/// - on_value: A scalar defining the value to fill in output when `indices[j] = i`. +/// - off_value: A scalar defining the value to fill in output when `indices[j] != i`. /// /// - Attr axis: The axis to fill (default: -1, a new inner-most axis). /// @@ -18411,22 +18398,22 @@ public static func oneHot< T: TensorFlowScalar, Ti: BinaryInteger & TensorFlowScalar >( - indices: Tensor, - depth: Tensor, - onValue: Tensor, - offValue: Tensor, - axis: Int64 = -1 + indices: Tensor, + depth: Tensor, + onValue: Tensor, + offValue: Tensor, + axis: Int64 = -1 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("OneHot", nOutputs) - op.updateAttribute("axis", axis) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("TI", Ti.tensorFlowDataType) - op.addInput(indices) - op.addInput(depth) - op.addInput(onValue) - op.addInput(offValue) - return op.execute(Int(1)) + let op = makeOp("OneHot", nOutputs) + op.updateAttribute("axis", axis) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("TI", Ti.tensorFlowDataType) + op.addInput(indices) + op.addInput(depth) + op.addInput(onValue) + op.addInput(offValue) + return op.execute(Int(1)) } /// Makes a "one-shot" iterator that can be iterated only once. @@ -18450,27 +18437,27 @@ public static func oneHot< /// times by rerunning "MakeIterator". /// /// - Attr dataset_factory: A function of type `() -> DT_VARIANT`, where the returned -/// DT_VARIANT is a dataset. +/// DT_VARIANT is a dataset. /// /// - Output handle: A handle to the iterator that can be passed to an "IteratorGetNext" -/// op. +/// op. @inlinable @inline(__always) public static func oneShotIterator( - datasetFactory: (DatasetfactoryIn) -> DatasetfactoryOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?], - container: String, - sharedName: String + datasetFactory: (DatasetfactoryIn) -> DatasetfactoryOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("OneShotIterator", nOutputs) - op.updateAttribute("dataset_factory", datasetFactory) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("OneShotIterator", nOutputs) + op.updateAttribute("dataset_factory", datasetFactory) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Returns a tensor of ones with the same shape and type as x. @@ -18480,32 +18467,32 @@ public static func oneShotIterator( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("OnesLike", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("OnesLike", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func opWithDefaultAttr( - defaultFloat: Double = 123 + defaultFloat: Double = 123 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("OpWithDefaultAttr", nOutputs) - op.updateAttribute("default_float", defaultFloat) - return op.execute(Int(1)) + let op = makeOp("OpWithDefaultAttr", nOutputs) + op.updateAttribute("default_float", defaultFloat) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func opWithFutureDefaultAttr( ) { let nOutputs = 0 - let op = makeOp("OpWithFutureDefaultAttr", nOutputs) - - op.execute() + let op = makeOp("OpWithFutureDefaultAttr", nOutputs) + + op.execute() } /// Creates a dataset by applying optimizations to `input_dataset`. @@ -18513,61 +18500,61 @@ public static func opWithFutureDefaultAttr( /// Creates a dataset by applying optimizations to `input_dataset`. /// /// - Parameters: -/// - input_dataset: A variant tensor representing the input dataset. -/// - optimizations: A `tf.string` vector `tf.Tensor` identifying optimizations to use. +/// - input_dataset: A variant tensor representing the input dataset. +/// - optimizations: A `tf.string` vector `tf.Tensor` identifying optimizations to use. @inlinable @inline(__always) public static func optimizeDataset( - inputDataset: VariantHandle, - optimizations: StringTensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?], - optimizationConfigs: [String] + inputDataset: VariantHandle, + optimizations: StringTensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + optimizationConfigs: [String] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("OptimizeDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("optimization_configs", optimizationConfigs) - op.addInput(inputDataset) - op.addInput(optimizations) - return op.execute(Int(1)) + let op = makeOp("OptimizeDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("optimization_configs", optimizationConfigs) + op.addInput(inputDataset) + op.addInput(optimizations) + return op.execute(Int(1)) } /// Constructs an Optional variant from a tuple of tensors. @inlinable @inline(__always) public static func optionalFromValue( - components: ToutputTypes + components: ToutputTypes ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("OptionalFromValue", nOutputs) - op.updateAttribute("Toutput_types", components._typeList) - op.addInputList(components) - return op.execute(Int(1)) + let op = makeOp("OptionalFromValue", nOutputs) + op.updateAttribute("Toutput_types", components._typeList) + op.addInputList(components) + return op.execute(Int(1)) } /// Returns the value stored in an Optional variant or raises an error if none exists. @inlinable @inline(__always) public static func optionalGetValue( - optional: VariantHandle, - outputShapes: [TensorShape?] + optional: VariantHandle, + outputShapes: [TensorShape?] ) -> OutputTypes { let nOutputs = Int(OutputTypes._typeList.count) - let op = makeOp("OptionalGetValue", nOutputs) - op.updateAttribute("output_types", OutputTypes._typeList) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(optional) - return op.execute(Int(OutputTypes._typeList.count)) + let op = makeOp("OptionalGetValue", nOutputs) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(optional) + return op.execute(Int(OutputTypes._typeList.count)) } /// Returns true if and only if the given Optional variant has a value. @inlinable @inline(__always) public static func optionalHasValue( - optional: VariantHandle + optional: VariantHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("OptionalHasValue", nOutputs) - op.addInput(optional) - return op.execute(Int(1)) + let op = makeOp("OptionalHasValue", nOutputs) + op.addInput(optional) + return op.execute(Int(1)) } /// Creates an Optional variant with no value. @@ -18575,47 +18562,47 @@ public static func optionalHasValue( public static func optionalNone( ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("OptionalNone", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("OptionalNone", nOutputs) + + return op.execute(Int(1)) } /// Op removes all elements in the underlying container. @inlinable @inline(__always) public static func orderedMapClear( - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - dtypes: [TensorDataType], - container: String, - sharedName: String + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String ) { let nOutputs = 0 - let op = makeOp("OrderedMapClear", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", dtypes) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.execute() + let op = makeOp("OrderedMapClear", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.execute() } /// Op returns the number of incomplete elements in the underlying container. @inlinable @inline(__always) public static func orderedMapIncompleteSize( - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - dtypes: [TensorDataType], - container: String, - sharedName: String + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("OrderedMapIncompleteSize", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", dtypes) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("OrderedMapIncompleteSize", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Op peeks at the values at the specified key. If the @@ -18625,42 +18612,42 @@ public static func orderedMapIncompleteSize( /// performance. @inlinable @inline(__always) public static func orderedMapPeek( - key: Tensor, - indices: Tensor, - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - container: String, - sharedName: String + key: Tensor, + indices: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String ) -> Dtypes { let nOutputs = Int(Dtypes._typeList.count) - let op = makeOp("OrderedMapPeek", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", Dtypes._typeList) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.addInput(key) - op.addInput(indices) - return op.execute(Int(Dtypes._typeList.count)) + let op = makeOp("OrderedMapPeek", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(key) + op.addInput(indices) + return op.execute(Int(Dtypes._typeList.count)) } /// Op returns the number of elements in the underlying container. @inlinable @inline(__always) public static func orderedMapSize( - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - dtypes: [TensorDataType], - container: String, - sharedName: String + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("OrderedMapSize", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", dtypes) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("OrderedMapSize", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Stage (key, values) in the underlying container which behaves like a ordered @@ -18668,39 +18655,39 @@ public static func orderedMapSize( /// associative container. Elements are ordered by key. /// /// - Parameters: -/// - key: int64 -/// - values: a list of tensors -/// dtypes A list of data types that inserted values should adhere to. +/// - key: int64 +/// - values: a list of tensors +/// dtypes A list of data types that inserted values should adhere to. /// /// - Attrs: -/// - capacity: Maximum number of elements in the Staging Area. If > 0, inserts -/// on the container will block when the capacity is reached. -/// - container: If non-empty, this queue is placed in the given container. Otherwise, -/// a default container is used. -/// - shared_name: It is necessary to match this name to the matching Unstage Op. +/// - capacity: Maximum number of elements in the Staging Area. If > 0, inserts +/// on the container will block when the capacity is reached. +/// - container: If non-empty, this queue is placed in the given container. Otherwise, +/// a default container is used. +/// - shared_name: It is necessary to match this name to the matching Unstage Op. @inlinable @inline(__always) public static func orderedMapStage( - key: Tensor, - indices: Tensor, - _ values: FakeDtypes, - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - dtypes: [TensorDataType], - container: String, - sharedName: String + key: Tensor, + indices: Tensor, + _ values: FakeDtypes, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String ) { let nOutputs = 0 - let op = makeOp("OrderedMapStage", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", dtypes) - op.updateAttribute("fake_dtypes", values._typeList) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.addInput(key) - op.addInput(indices) - op.addInputList(values) - op.execute() + let op = makeOp("OrderedMapStage", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("fake_dtypes", values._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(key) + op.addInput(indices) + op.addInputList(values) + op.execute() } /// Op removes and returns the values associated with the key @@ -18709,23 +18696,23 @@ public static func orderedMapStage( /// does not contain this key, the op will block until it does. @inlinable @inline(__always) public static func orderedMapUnstage( - key: Tensor, - indices: Tensor, - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - container: String, - sharedName: String + key: Tensor, + indices: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String ) -> Dtypes { let nOutputs = Int(Dtypes._typeList.count) - let op = makeOp("OrderedMapUnstage", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", Dtypes._typeList) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.addInput(key) - op.addInput(indices) - return op.execute(Int(Dtypes._typeList.count)) + let op = makeOp("OrderedMapUnstage", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(key) + op.addInput(indices) + return op.execute(Int(Dtypes._typeList.count)) } /// Op removes and returns the (key, value) element with the smallest @@ -18734,48 +18721,48 @@ public static func orderedMapUnstage( /// does not contain elements, the op will block until it does. @inlinable @inline(__always) public static func orderedMapUnstageNoKey( - indices: Tensor, - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - container: String, - sharedName: String + indices: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String ) -> (key: Tensor, values: Dtypes) { let nOutputs = Int(1) + Int(Dtypes._typeList.count) - let op = makeOp("OrderedMapUnstageNoKey", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", Dtypes._typeList) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.addInput(indices) - return op.execute(Int(1), Int(Dtypes._typeList.count)) + let op = makeOp("OrderedMapUnstageNoKey", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(indices) + return op.execute(Int(1), Int(Dtypes._typeList.count)) } @inlinable @inline(__always) public static func outT( ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("OutT", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - return op.execute(Int(1)) + let op = makeOp("OutT", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func outTypeList( ) -> T { let nOutputs = Int(T._typeList.count) - let op = makeOp("OutTypeList", nOutputs) - op.updateAttribute("T", T._typeList) - return op.execute(Int(T._typeList.count)) + let op = makeOp("OutTypeList", nOutputs) + op.updateAttribute("T", T._typeList) + return op.execute(Int(T._typeList.count)) } @inlinable @inline(__always) public static func outTypeListRestrict( ) -> T { let nOutputs = Int(T._typeList.count) - let op = makeOp("OutTypeListRestrict", nOutputs) - op.updateAttribute("t", T._typeList) - return op.execute(Int(T._typeList.count)) + let op = makeOp("OutTypeListRestrict", nOutputs) + op.updateAttribute("t", T._typeList) + return op.execute(Int(T._typeList.count)) } /// Retrieves a single tensor from the computation outfeed. @@ -18783,24 +18770,24 @@ public static func outTypeListRestrict( /// This operation will block indefinitely until data is available. /// /// - Attrs: -/// - dtype: The type of elements in the tensor. -/// - shape: The shape of the tensor. -/// - device_ordinal: The TPU device to use. This should be -1 when the Op -/// is running on a TPU device, and >= 0 when the Op is running on the CPU -/// device. +/// - dtype: The type of elements in the tensor. +/// - shape: The shape of the tensor. +/// - device_ordinal: The TPU device to use. This should be -1 when the Op +/// is running on a TPU device, and >= 0 when the Op is running on the CPU +/// device. /// /// - Output output: A tensor that will be read from the device outfeed. @inlinable @inline(__always) public static func outfeedDequeue( - shape: TensorShape?, - deviceOrdinal: Int64 = -1 + shape: TensorShape?, + deviceOrdinal: Int64 = -1 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("OutfeedDequeue", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape", shape) - op.updateAttribute("device_ordinal", deviceOrdinal) - return op.execute(Int(1)) + let op = makeOp("OutfeedDequeue", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.updateAttribute("device_ordinal", deviceOrdinal) + return op.execute(Int(1)) } /// Retrieve multiple values from the computation outfeed. @@ -18809,24 +18796,24 @@ public static func outfeedDequeue( /// corresponds to XLA tuple element `i`. /// /// - Attrs: -/// - dtypes: The element types of each element in `outputs`. -/// - shapes: The shapes of each tensor in `outputs`. -/// - device_ordinal: The TPU device to use. This should be -1 when the Op -/// is running on a TPU device, and >= 0 when the Op is running on the CPU -/// device. +/// - dtypes: The element types of each element in `outputs`. +/// - shapes: The shapes of each tensor in `outputs`. +/// - device_ordinal: The TPU device to use. This should be -1 when the Op +/// is running on a TPU device, and >= 0 when the Op is running on the CPU +/// device. /// /// - Output outputs: A list of tensors that will be read from the outfeed. @inlinable @inline(__always) public static func outfeedDequeueTuple( - shapes: [TensorShape?], - deviceOrdinal: Int64 = -1 + shapes: [TensorShape?], + deviceOrdinal: Int64 = -1 ) -> Dtypes { let nOutputs = Int(Dtypes._typeList.count) - let op = makeOp("OutfeedDequeueTuple", nOutputs) - op.updateAttribute("dtypes", Dtypes._typeList) - op.updateAttribute("shapes", shapes) - op.updateAttribute("device_ordinal", deviceOrdinal) - return op.execute(Int(Dtypes._typeList.count)) + let op = makeOp("OutfeedDequeueTuple", nOutputs) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("shapes", shapes) + op.updateAttribute("device_ordinal", deviceOrdinal) + return op.execute(Int(Dtypes._typeList.count)) } /// Enqueue a Tensor on the computation outfeed. @@ -18834,28 +18821,28 @@ public static func outfeedDequeueTuple( /// - Parameter input: A tensor that will be inserted into the outfeed queue. @inlinable @inline(__always) public static func outfeedEnqueue( - _ input: Tensor + _ input: Tensor ) { let nOutputs = 0 - let op = makeOp("OutfeedEnqueue", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(input) - op.execute() + let op = makeOp("OutfeedEnqueue", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(input) + op.execute() } /// Enqueue multiple Tensor values on the computation outfeed. /// /// - Parameter inputs: A list of tensors that will be inserted into the outfeed queue as an -/// XLA tuple. +/// XLA tuple. @inlinable @inline(__always) public static func outfeedEnqueueTuple( - inputs: Dtypes + inputs: Dtypes ) { let nOutputs = 0 - let op = makeOp("OutfeedEnqueueTuple", nOutputs) - op.updateAttribute("dtypes", inputs._typeList) - op.addInputList(inputs) - op.execute() + let op = makeOp("OutfeedEnqueueTuple", nOutputs) + op.updateAttribute("dtypes", inputs._typeList) + op.addInputList(inputs) + op.execute() } /// Packs a list of `N` rank-`R` tensors into one rank-`(R+1)` tensor. @@ -18883,21 +18870,21 @@ public static func outfeedEnqueueTuple( /// - Parameter values: Must be of same shape and type. /// /// - Attr axis: Dimension along which to pack. Negative values wrap around, so the -/// valid range is `[-(R+1), R+1)`. +/// valid range is `[-(R+1), R+1)`. /// /// - Output output: The packed tensor. @inlinable @inline(__always) public static func pack( - _ values: [Tensor], - axis: Int64 = 0 + _ values: [Tensor], + axis: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Pack", nOutputs) - op.updateAttribute("N", values.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("axis", axis) - op.addInputList(values) - return op.execute(Int(1)) + let op = makeOp("Pack", nOutputs) + op.updateAttribute("N", values.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("axis", axis) + op.addInputList(values) + return op.execute(Int(1)) } /// Pads a tensor with zeros. @@ -18930,16 +18917,16 @@ public static func pad< T: TensorFlowScalar, Tpaddings: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - paddings: Tensor + _ input: Tensor, + paddings: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Pad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) - op.addInput(input) - op.addInput(paddings) - return op.execute(Int(1)) + let op = makeOp("Pad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) + op.addInput(input) + op.addInput(paddings) + return op.execute(Int(1)) } /// Pads a tensor. @@ -18973,86 +18960,86 @@ public static func padV2< T: TensorFlowScalar, Tpaddings: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - paddings: Tensor, - constantValues: Tensor + _ input: Tensor, + paddings: Tensor, + constantValues: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("PadV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) - op.addInput(input) - op.addInput(paddings) - op.addInput(constantValues) - return op.execute(Int(1)) + let op = makeOp("PadV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) + op.addInput(input) + op.addInput(paddings) + op.addInput(constantValues) + return op.execute(Int(1)) } /// Creates a dataset that batches and pads `batch_size` elements from the input. /// /// - Parameters: -/// - batch_size: A scalar representing the number of elements to accumulate in a -/// batch. -/// - padded_shapes: A list of int64 tensors representing the desired padded shapes -/// of the corresponding output components. These shapes may be partially -/// specified, using `-1` to indicate that a particular dimension should be -/// padded to the maximum size of all batch elements. -/// - padding_values: A list of scalars containing the padding value to use for -/// each of the outputs. +/// - batch_size: A scalar representing the number of elements to accumulate in a +/// batch. +/// - padded_shapes: A list of int64 tensors representing the desired padded shapes +/// of the corresponding output components. These shapes may be partially +/// specified, using `-1` to indicate that a particular dimension should be +/// padded to the maximum size of all batch elements. +/// - padding_values: A list of scalars containing the padding value to use for +/// each of the outputs. @inlinable @inline(__always) public static func paddedBatchDataset( - inputDataset: VariantHandle, - batchSize: Tensor, - paddedShapes: [Tensor], - paddingValues: ToutputTypes, - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + batchSize: Tensor, + paddedShapes: [Tensor], + paddingValues: ToutputTypes, + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("PaddedBatchDataset", nOutputs) - op.updateAttribute("Toutput_types", paddingValues._typeList) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("N", paddedShapes.count) - op.addInput(inputDataset) - op.addInput(batchSize) - op.addInputList(paddedShapes) - op.addInputList(paddingValues) - return op.execute(Int(1)) + let op = makeOp("PaddedBatchDataset", nOutputs) + op.updateAttribute("Toutput_types", paddingValues._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("N", paddedShapes.count) + op.addInput(inputDataset) + op.addInput(batchSize) + op.addInputList(paddedShapes) + op.addInputList(paddingValues) + return op.execute(Int(1)) } /// Creates a dataset that batches and pads `batch_size` elements from the input. /// /// - Parameters: -/// - batch_size: A scalar representing the number of elements to accumulate in a -/// batch. -/// - padded_shapes: A list of int64 tensors representing the desired padded shapes -/// of the corresponding output components. These shapes may be partially -/// specified, using `-1` to indicate that a particular dimension should be -/// padded to the maximum size of all batch elements. -/// - padding_values: A list of scalars containing the padding value to use for -/// each of the outputs. -/// - drop_remainder: A scalar representing whether the last batch should be dropped in case its size -/// is smaller than desired. +/// - batch_size: A scalar representing the number of elements to accumulate in a +/// batch. +/// - padded_shapes: A list of int64 tensors representing the desired padded shapes +/// of the corresponding output components. These shapes may be partially +/// specified, using `-1` to indicate that a particular dimension should be +/// padded to the maximum size of all batch elements. +/// - padding_values: A list of scalars containing the padding value to use for +/// each of the outputs. +/// - drop_remainder: A scalar representing whether the last batch should be dropped in case its size +/// is smaller than desired. @inlinable @inline(__always) public static func paddedBatchDatasetV2( - inputDataset: VariantHandle, - batchSize: Tensor, - paddedShapes: [Tensor], - paddingValues: ToutputTypes, - dropRemainder: Tensor, - parallelCopy: Bool = false, - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + batchSize: Tensor, + paddedShapes: [Tensor], + paddingValues: ToutputTypes, + dropRemainder: Tensor, + parallelCopy: Bool = false, + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("PaddedBatchDatasetV2", nOutputs) - op.updateAttribute("parallel_copy", parallelCopy) - op.updateAttribute("Toutput_types", paddingValues._typeList) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("N", paddedShapes.count) - op.addInput(inputDataset) - op.addInput(batchSize) - op.addInputList(paddedShapes) - op.addInputList(paddingValues) - op.addInput(dropRemainder) - return op.execute(Int(1)) + let op = makeOp("PaddedBatchDatasetV2", nOutputs) + op.updateAttribute("parallel_copy", parallelCopy) + op.updateAttribute("Toutput_types", paddingValues._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("N", paddedShapes.count) + op.addInput(inputDataset) + op.addInput(batchSize) + op.addInputList(paddedShapes) + op.addInputList(paddingValues) + op.addInput(dropRemainder) + return op.execute(Int(1)) } /// A queue that produces elements in first-in first-out order. @@ -19062,39 +19049,39 @@ public static func paddedBatchDatasetV2( /// size of any given element in the minibatch. See below for details. /// /// - Attrs: -/// - component_types: The type of each component in a value. -/// - shapes: The shape of each component in a value. The length of this attr must -/// be either 0 or the same as the length of component_types. -/// Shapes of fixed rank but variable size are allowed by setting -/// any shape dimension to -1. In this case, the inputs' shape may vary along -/// the given dimension, and DequeueMany will pad the given dimension with -/// zeros up to the maximum shape of all elements in the given batch. -/// If the length of this attr is 0, different queue elements may have -/// different ranks and shapes, but only one element may be dequeued at a time. -/// - capacity: The upper bound on the number of elements in this queue. -/// Negative numbers mean no limit. -/// - container: If non-empty, this queue is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this queue will be shared under the given name -/// across multiple sessions. +/// - component_types: The type of each component in a value. +/// - shapes: The shape of each component in a value. The length of this attr must +/// be either 0 or the same as the length of component_types. +/// Shapes of fixed rank but variable size are allowed by setting +/// any shape dimension to -1. In this case, the inputs' shape may vary along +/// the given dimension, and DequeueMany will pad the given dimension with +/// zeros up to the maximum shape of all elements in the given batch. +/// If the length of this attr is 0, different queue elements may have +/// different ranks and shapes, but only one element may be dequeued at a time. +/// - capacity: The upper bound on the number of elements in this queue. +/// Negative numbers mean no limit. +/// - container: If non-empty, this queue is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this queue will be shared under the given name +/// across multiple sessions. /// /// - Output handle: The handle to the queue. @inlinable @inline(__always) public static func paddingFIFOQueueV2( - componentTypes: [TensorDataType], - shapes: [TensorShape?], - capacity: Int64 = -1, - container: String, - sharedName: String + componentTypes: [TensorDataType], + shapes: [TensorShape?], + capacity: Int64 = -1, + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("PaddingFIFOQueueV2", nOutputs) - op.updateAttribute("component_types", componentTypes) - op.updateAttribute("shapes", shapes) - op.updateAttribute("capacity", capacity) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("PaddingFIFOQueueV2", nOutputs) + op.updateAttribute("component_types", componentTypes) + op.updateAttribute("shapes", shapes) + op.updateAttribute("capacity", capacity) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Concatenates a list of `N` tensors along the first dimension. @@ -19117,24 +19104,24 @@ public static func paddingFIFOQueueV2( /// some situations this can provide a performance benefit. /// /// - Parameter values: Tensors to be concatenated. All must have size 1 in the first dimension -/// and same shape. +/// and same shape. /// /// - Attr shape: the final shape of the result; should be equal to the shapes of any input -/// but with the number of input values in the first dimension. +/// but with the number of input values in the first dimension. /// /// - Output output: The concatenated tensor. @inlinable @inline(__always) public static func parallelConcat( - _ values: [Tensor], - shape: TensorShape? + _ values: [Tensor], + shape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ParallelConcat", nOutputs) - op.updateAttribute("N", values.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("shape", shape) - op.addInputList(values) - return op.execute(Int(1)) + let op = makeOp("ParallelConcat", nOutputs) + op.updateAttribute("N", values.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.addInputList(values) + return op.execute(Int(1)) } /// Interleave the values from the `data` tensors into a single tensor. @@ -19202,52 +19189,52 @@ public static func parallelConcat( /// @inlinable @inline(__always) public static func parallelDynamicStitch( - indices: [Tensor], - data: [Tensor] + indices: [Tensor], + data: [Tensor] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ParallelDynamicStitch", nOutputs) - op.updateAttribute("N", indices.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInputList(indices) - op.addInputList(data) - return op.execute(Int(1)) + let op = makeOp("ParallelDynamicStitch", nOutputs) + op.updateAttribute("N", indices.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInputList(indices) + op.addInputList(data) + return op.execute(Int(1)) } /// Creates a dataset that applies `f` to the outputs of `input_dataset`. /// /// - Attr f: A function mapping elements of `input_dataset`, concatenated with -/// `other_arguments`, to a Dataset variant that contains elements matching -/// `output_types` and `output_shapes`. +/// `other_arguments`, to a Dataset variant that contains elements matching +/// `output_types` and `output_shapes`. @inlinable @inline(__always) public static func parallelInterleaveDatasetV2< FIn: TensorGroup, FOut: TensorGroup, Targuments: TensorArrayProtocol >( - inputDataset: VariantHandle, - otherArguments: Targuments, - cycleLength: Tensor, - blockLength: Tensor, - numParallelCalls: Tensor, - f: (FIn) -> FOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?], - sloppy: Bool = false + inputDataset: VariantHandle, + otherArguments: Targuments, + cycleLength: Tensor, + blockLength: Tensor, + numParallelCalls: Tensor, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + sloppy: Bool = false ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ParallelInterleaveDatasetV2", nOutputs) - op.updateAttribute("f", f) - op.updateAttribute("Targuments", otherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("sloppy", sloppy) - op.addInput(inputDataset) - op.addInputList(otherArguments) - op.addInput(cycleLength) - op.addInput(blockLength) - op.addInput(numParallelCalls) - return op.execute(Int(1)) + let op = makeOp("ParallelInterleaveDatasetV2", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("sloppy", sloppy) + op.addInput(inputDataset) + op.addInputList(otherArguments) + op.addInput(cycleLength) + op.addInput(blockLength) + op.addInput(numParallelCalls) + return op.execute(Int(1)) } /// Creates a dataset that applies `f` to the outputs of `input_dataset`. @@ -19256,36 +19243,36 @@ public static func parallelInterleaveDatasetV2< /// to `num_parallel_calls` copies of `f` in parallel. /// /// - Parameter num_parallel_calls: The number of concurrent invocations of `f` that process -/// elements from `input_dataset` in parallel. +/// elements from `input_dataset` in parallel. @inlinable @inline(__always) public static func parallelMapDataset< FIn: TensorGroup, FOut: TensorGroup, Targuments: TensorArrayProtocol >( - inputDataset: VariantHandle, - otherArguments: Targuments, - numParallelCalls: Tensor, - f: (FIn) -> FOut, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?], - useInterOpParallelism: Bool = true, - sloppy: Bool = false, - preserveCardinality: Bool = false + inputDataset: VariantHandle, + otherArguments: Targuments, + numParallelCalls: Tensor, + f: (FIn) -> FOut, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?], + useInterOpParallelism: Bool = true, + sloppy: Bool = false, + preserveCardinality: Bool = false ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ParallelMapDataset", nOutputs) - op.updateAttribute("f", f) - op.updateAttribute("Targuments", otherArguments._typeList) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("use_inter_op_parallelism", useInterOpParallelism) - op.updateAttribute("sloppy", sloppy) - op.updateAttribute("preserve_cardinality", preserveCardinality) - op.addInput(inputDataset) - op.addInputList(otherArguments) - op.addInput(numParallelCalls) - return op.execute(Int(1)) + let op = makeOp("ParallelMapDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("use_inter_op_parallelism", useInterOpParallelism) + op.updateAttribute("sloppy", sloppy) + op.updateAttribute("preserve_cardinality", preserveCardinality) + op.addInput(inputDataset) + op.addInputList(otherArguments) + op.addInput(numParallelCalls) + return op.execute(Int(1)) } /// Outputs random values from a normal distribution. The parameters may each be a @@ -19294,173 +19281,173 @@ public static func parallelMapDataset< /// stores the parameters for each batch. /// /// - Parameters: -/// - shape: The shape of the output tensor. Batches are indexed by the 0th dimension. -/// - means: The mean parameter of each batch. -/// - stdevs: The standard deviation parameter of each batch. Must be greater than 0. -/// - minvals: The minimum cutoff. May be -infinity. -/// - maxvals: The maximum cutoff. May be +infinity, and must be more than the minval -/// for each batch. +/// - shape: The shape of the output tensor. Batches are indexed by the 0th dimension. +/// - means: The mean parameter of each batch. +/// - stdevs: The standard deviation parameter of each batch. Must be greater than 0. +/// - minvals: The minimum cutoff. May be -infinity. +/// - maxvals: The maximum cutoff. May be +infinity, and must be more than the minval +/// for each batch. /// /// - Attrs: -/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: A second seed to avoid seed collision. -/// - dtype: The type of the output. +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. +/// - dtype: The type of the output. /// /// - Output output: A matrix of shape num_batches x samples_per_batch, filled with random -/// truncated normal values using the parameters for each row. +/// truncated normal values using the parameters for each row. @inlinable @inline(__always) public static func parameterizedTruncatedNormal< Dtype: FloatingPoint & TensorFlowScalar, T: BinaryInteger & TensorFlowScalar >( - shape: Tensor, - means: Tensor, - stdevs: Tensor, - minvals: Tensor, - maxvals: Tensor, - seed: Int64 = 0, - seed2: Int64 = 0 + shape: Tensor, + means: Tensor, + stdevs: Tensor, + minvals: Tensor, + maxvals: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ParameterizedTruncatedNormal", nOutputs) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(shape) - op.addInput(means) - op.addInput(stdevs) - op.addInput(minvals) - op.addInput(maxvals) - return op.execute(Int(1)) + let op = makeOp("ParameterizedTruncatedNormal", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(shape) + op.addInput(means) + op.addInput(stdevs) + op.addInput(minvals) + op.addInput(maxvals) + return op.execute(Int(1)) } /// Transforms a vector of brain.Example protos (as strings) into typed tensors. /// /// - Parameters: -/// - serialized: A vector containing a batch of binary serialized Example protos. -/// - names: A vector containing the names of the serialized protos. -/// May contain, for example, table key (descriptive) names for the -/// corresponding serialized protos. These are purely useful for debugging -/// purposes, and the presence of values here has no effect on the output. -/// May also be an empty vector if no names are available. -/// If non-empty, this vector must be the same length as "serialized". -/// - sparse_keys: A list of Nsparse string Tensors (scalars). -/// The keys expected in the Examples' features associated with sparse values. -/// - dense_keys: A list of Ndense string Tensors (scalars). -/// The keys expected in the Examples' features associated with dense values. -/// - dense_defaults: A list of Ndense Tensors (some may be empty). -/// dense_defaults[j] provides default values -/// when the example's feature_map lacks dense_key[j]. If an empty Tensor is -/// provided for dense_defaults[j], then the Feature dense_keys[j] is required. -/// The input type is inferred from dense_defaults[j], even when it's empty. -/// If dense_defaults[j] is not empty, and dense_shapes[j] is fully defined, -/// then the shape of dense_defaults[j] must match that of dense_shapes[j]. -/// If dense_shapes[j] has an undefined major dimension (variable strides dense -/// feature), dense_defaults[j] must contain a single element: -/// the padding element. +/// - serialized: A vector containing a batch of binary serialized Example protos. +/// - names: A vector containing the names of the serialized protos. +/// May contain, for example, table key (descriptive) names for the +/// corresponding serialized protos. These are purely useful for debugging +/// purposes, and the presence of values here has no effect on the output. +/// May also be an empty vector if no names are available. +/// If non-empty, this vector must be the same length as "serialized". +/// - sparse_keys: A list of Nsparse string Tensors (scalars). +/// The keys expected in the Examples' features associated with sparse values. +/// - dense_keys: A list of Ndense string Tensors (scalars). +/// The keys expected in the Examples' features associated with dense values. +/// - dense_defaults: A list of Ndense Tensors (some may be empty). +/// dense_defaults[j] provides default values +/// when the example's feature_map lacks dense_key[j]. If an empty Tensor is +/// provided for dense_defaults[j], then the Feature dense_keys[j] is required. +/// The input type is inferred from dense_defaults[j], even when it's empty. +/// If dense_defaults[j] is not empty, and dense_shapes[j] is fully defined, +/// then the shape of dense_defaults[j] must match that of dense_shapes[j]. +/// If dense_shapes[j] has an undefined major dimension (variable strides dense +/// feature), dense_defaults[j] must contain a single element: +/// the padding element. /// /// - Attrs: -/// - sparse_types: A list of Nsparse types; the data types of data in each Feature -/// given in sparse_keys. -/// Currently the ParseExample supports DT_FLOAT (FloatList), -/// DT_INT64 (Int64List), and DT_STRING (BytesList). -/// - dense_shapes: A list of Ndense shapes; the shapes of data in each Feature -/// given in dense_keys. -/// The number of elements in the Feature corresponding to dense_key[j] -/// must always equal dense_shapes[j].NumEntries(). -/// If dense_shapes[j] == (D0, D1, ..., DN) then the shape of output -/// Tensor dense_values[j] will be (|serialized|, D0, D1, ..., DN): -/// The dense outputs are just the inputs row-stacked by batch. -/// This works for dense_shapes[j] = (-1, D1, ..., DN). In this case -/// the shape of the output Tensor dense_values[j] will be -/// (|serialized|, M, D1, .., DN), where M is the maximum number of blocks -/// of elements of length D1 * .... * DN, across all minibatch entries -/// in the input. Any minibatch entry with less than M blocks of elements of -/// length D1 * ... * DN will be padded with the corresponding default_value -/// scalar element along the second dimension. +/// - sparse_types: A list of Nsparse types; the data types of data in each Feature +/// given in sparse_keys. +/// Currently the ParseExample supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - dense_shapes: A list of Ndense shapes; the shapes of data in each Feature +/// given in dense_keys. +/// The number of elements in the Feature corresponding to dense_key[j] +/// must always equal dense_shapes[j].NumEntries(). +/// If dense_shapes[j] == (D0, D1, ..., DN) then the shape of output +/// Tensor dense_values[j] will be (|serialized|, D0, D1, ..., DN): +/// The dense outputs are just the inputs row-stacked by batch. +/// This works for dense_shapes[j] = (-1, D1, ..., DN). In this case +/// the shape of the output Tensor dense_values[j] will be +/// (|serialized|, M, D1, .., DN), where M is the maximum number of blocks +/// of elements of length D1 * .... * DN, across all minibatch entries +/// in the input. Any minibatch entry with less than M blocks of elements of +/// length D1 * ... * DN will be padded with the corresponding default_value +/// scalar element along the second dimension. @inlinable @inline(__always) public static func parseExample< SparseTypes: TensorGroup, Tdense: TensorArrayProtocol >( - serialized: StringTensor, - names: StringTensor, - sparseKeys: [StringTensor], - denseKeys: [StringTensor], - denseDefaults: Tdense, - denseShapes: [TensorShape?] + serialized: StringTensor, + names: StringTensor, + sparseKeys: [StringTensor], + denseKeys: [StringTensor], + denseDefaults: Tdense, + denseShapes: [TensorShape?] ) -> (sparseIndices: [Tensor], sparseValues: SparseTypes, sparseShapes: [Tensor], denseValues: Tdense) { let nOutputs = Int(sparseKeys.count) + Int(SparseTypes._typeList.count) + Int(sparseKeys.count) + Int(denseDefaults._typeList.count) - let op = makeOp("ParseExample", nOutputs) - op.updateAttribute("Nsparse", sparseKeys.count) - op.updateAttribute("Ndense", denseKeys.count) - op.updateAttribute("sparse_types", SparseTypes._typeList) - op.updateAttribute("Tdense", denseDefaults._typeList) - op.updateAttribute("dense_shapes", denseShapes) - op.addInput(serialized) - op.addInput(names) - op.addInputList(sparseKeys) - op.addInputList(denseKeys) - op.addInputList(denseDefaults) - return op.execute(Int(sparseKeys.count), Int(SparseTypes._typeList.count), Int(sparseKeys.count), Int(denseDefaults._typeList.count)) + let op = makeOp("ParseExample", nOutputs) + op.updateAttribute("Nsparse", sparseKeys.count) + op.updateAttribute("Ndense", denseKeys.count) + op.updateAttribute("sparse_types", SparseTypes._typeList) + op.updateAttribute("Tdense", denseDefaults._typeList) + op.updateAttribute("dense_shapes", denseShapes) + op.addInput(serialized) + op.addInput(names) + op.addInputList(sparseKeys) + op.addInputList(denseKeys) + op.addInputList(denseDefaults) + return op.execute(Int(sparseKeys.count), Int(SparseTypes._typeList.count), Int(sparseKeys.count), Int(denseDefaults._typeList.count)) } /// Transforms a vector of brain.SequenceExample protos (as strings) into typed tensors. /// /// - Parameters: -/// - serialized: A vector containing binary serialized SequenceExample protos. -/// - debug_name: A vector containing the names of the serialized protos. -/// May contain, for example, table key (descriptive) name for the -/// corresponding serialized proto. This is purely useful for debugging -/// purposes, and the presence of values here has no effect on the output. -/// May also be an empty vector if no name is available. -/// - context_dense_defaults: A list of Ncontext_dense Tensors (some may be empty). -/// context_dense_defaults[j] provides default values -/// when the SequenceExample's context map lacks context_dense_key[j]. -/// If an empty Tensor is provided for context_dense_defaults[j], -/// then the Feature context_dense_keys[j] is required. -/// The input type is inferred from context_dense_defaults[j], even when it's -/// empty. If context_dense_defaults[j] is not empty, its shape must match -/// context_dense_shapes[j]. +/// - serialized: A vector containing binary serialized SequenceExample protos. +/// - debug_name: A vector containing the names of the serialized protos. +/// May contain, for example, table key (descriptive) name for the +/// corresponding serialized proto. This is purely useful for debugging +/// purposes, and the presence of values here has no effect on the output. +/// May also be an empty vector if no name is available. +/// - context_dense_defaults: A list of Ncontext_dense Tensors (some may be empty). +/// context_dense_defaults[j] provides default values +/// when the SequenceExample's context map lacks context_dense_key[j]. +/// If an empty Tensor is provided for context_dense_defaults[j], +/// then the Feature context_dense_keys[j] is required. +/// The input type is inferred from context_dense_defaults[j], even when it's +/// empty. If context_dense_defaults[j] is not empty, its shape must match +/// context_dense_shapes[j]. /// /// - Attrs: -/// - feature_list_dense_missing_assumed_empty: A vector listing the -/// FeatureList keys which may be missing from the SequenceExamples. If the -/// associated FeatureList is missing, it is treated as empty. By default, -/// any FeatureList not listed in this vector must exist in the SequenceExamples. -/// - context_sparse_keys: A list of Ncontext_sparse string Tensors (scalars). -/// The keys expected in the Examples' features associated with context_sparse -/// values. -/// - context_dense_keys: A list of Ncontext_dense string Tensors (scalars). -/// The keys expected in the SequenceExamples' context features associated with -/// dense values. -/// - feature_list_sparse_keys: A list of Nfeature_list_sparse string Tensors -/// (scalars). The keys expected in the FeatureLists associated with sparse -/// values. -/// - feature_list_dense_keys: A list of Nfeature_list_dense string Tensors (scalars). -/// The keys expected in the SequenceExamples' feature_lists associated -/// with lists of dense values. -/// - context_sparse_types: A list of Ncontext_sparse types; the data types of data in -/// each context Feature given in context_sparse_keys. -/// Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), -/// DT_INT64 (Int64List), and DT_STRING (BytesList). -/// - context_dense_shapes: A list of Ncontext_dense shapes; the shapes of data in -/// each context Feature given in context_dense_keys. -/// The number of elements in the Feature corresponding to context_dense_key[j] -/// must always equal context_dense_shapes[j].NumEntries(). -/// The shape of context_dense_values[j] will match context_dense_shapes[j]. -/// - feature_list_sparse_types: A list of Nfeature_list_sparse types; the data types -/// of data in each FeatureList given in feature_list_sparse_keys. -/// Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), -/// DT_INT64 (Int64List), and DT_STRING (BytesList). -/// - feature_list_dense_shapes: A list of Nfeature_list_dense shapes; the shapes of -/// data in each FeatureList given in feature_list_dense_keys. -/// The shape of each Feature in the FeatureList corresponding to -/// feature_list_dense_key[j] must always equal -/// feature_list_dense_shapes[j].NumEntries(). +/// - feature_list_dense_missing_assumed_empty: A vector listing the +/// FeatureList keys which may be missing from the SequenceExamples. If the +/// associated FeatureList is missing, it is treated as empty. By default, +/// any FeatureList not listed in this vector must exist in the SequenceExamples. +/// - context_sparse_keys: A list of Ncontext_sparse string Tensors (scalars). +/// The keys expected in the Examples' features associated with context_sparse +/// values. +/// - context_dense_keys: A list of Ncontext_dense string Tensors (scalars). +/// The keys expected in the SequenceExamples' context features associated with +/// dense values. +/// - feature_list_sparse_keys: A list of Nfeature_list_sparse string Tensors +/// (scalars). The keys expected in the FeatureLists associated with sparse +/// values. +/// - feature_list_dense_keys: A list of Nfeature_list_dense string Tensors (scalars). +/// The keys expected in the SequenceExamples' feature_lists associated +/// with lists of dense values. +/// - context_sparse_types: A list of Ncontext_sparse types; the data types of data in +/// each context Feature given in context_sparse_keys. +/// Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - context_dense_shapes: A list of Ncontext_dense shapes; the shapes of data in +/// each context Feature given in context_dense_keys. +/// The number of elements in the Feature corresponding to context_dense_key[j] +/// must always equal context_dense_shapes[j].NumEntries(). +/// The shape of context_dense_values[j] will match context_dense_shapes[j]. +/// - feature_list_sparse_types: A list of Nfeature_list_sparse types; the data types +/// of data in each FeatureList given in feature_list_sparse_keys. +/// Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - feature_list_dense_shapes: A list of Nfeature_list_dense shapes; the shapes of +/// data in each FeatureList given in feature_list_dense_keys. +/// The shape of each Feature in the FeatureList corresponding to +/// feature_list_dense_key[j] must always equal +/// feature_list_dense_shapes[j].NumEntries(). @inlinable @inline(__always) public static func parseSequenceExample< ContextSparseTypes: TensorGroup, @@ -19468,161 +19455,161 @@ public static func parseSequenceExample< FeatureListDenseTypes: TensorGroup, FeatureListSparseTypes: TensorGroup >( - serialized: StringTensor, - debugName: StringTensor, - contextDenseDefaults: TcontextDense, - featureListDenseMissingAssumedEmpty: [String], - contextSparseKeys: [String], - contextDenseKeys: [String], - featureListSparseKeys: [String], - featureListDenseKeys: [String], - ncontextSparse: Int64 = 0, - ncontextDense: Int64 = 0, - nfeatureListSparse: Int64 = 0, - nfeatureListDense: Int64 = 0, - contextDenseShapes: [TensorShape?], - featureListDenseShapes: [TensorShape?] + serialized: StringTensor, + debugName: StringTensor, + contextDenseDefaults: TcontextDense, + featureListDenseMissingAssumedEmpty: [String], + contextSparseKeys: [String], + contextDenseKeys: [String], + featureListSparseKeys: [String], + featureListDenseKeys: [String], + ncontextSparse: Int64 = 0, + ncontextDense: Int64 = 0, + nfeatureListSparse: Int64 = 0, + nfeatureListDense: Int64 = 0, + contextDenseShapes: [TensorShape?], + featureListDenseShapes: [TensorShape?] ) -> (contextSparseIndices: [Tensor], contextSparseValues: ContextSparseTypes, contextSparseShapes: [Tensor], contextDenseValues: TcontextDense, featureListSparseIndices: [Tensor], featureListSparseValues: FeatureListSparseTypes, featureListSparseShapes: [Tensor], featureListDenseValues: FeatureListDenseTypes, featureListDenseLengths: [Tensor]) { let nOutputs = Int(ncontextSparse) + Int(ContextSparseTypes._typeList.count) + Int(ncontextSparse) + Int(contextDenseDefaults._typeList.count) + Int(nfeatureListSparse) + Int(FeatureListSparseTypes._typeList.count) + Int(nfeatureListSparse) + Int(FeatureListDenseTypes._typeList.count) + Int(nfeatureListDense) - let op = makeOp("ParseSequenceExample", nOutputs) - op.updateAttribute("feature_list_dense_missing_assumed_empty", featureListDenseMissingAssumedEmpty) - op.updateAttribute("context_sparse_keys", contextSparseKeys) - op.updateAttribute("context_dense_keys", contextDenseKeys) - op.updateAttribute("feature_list_sparse_keys", featureListSparseKeys) - op.updateAttribute("feature_list_dense_keys", featureListDenseKeys) - op.updateAttribute("Ncontext_sparse", ncontextSparse) - op.updateAttribute("Ncontext_dense", ncontextDense) - op.updateAttribute("Nfeature_list_sparse", nfeatureListSparse) - op.updateAttribute("Nfeature_list_dense", nfeatureListDense) - op.updateAttribute("context_sparse_types", ContextSparseTypes._typeList) - op.updateAttribute("Tcontext_dense", contextDenseDefaults._typeList) - op.updateAttribute("feature_list_dense_types", FeatureListDenseTypes._typeList) - op.updateAttribute("context_dense_shapes", contextDenseShapes) - op.updateAttribute("feature_list_sparse_types", FeatureListSparseTypes._typeList) - op.updateAttribute("feature_list_dense_shapes", featureListDenseShapes) - op.addInput(serialized) - op.addInput(debugName) - op.addInputList(contextDenseDefaults) - return op.execute(Int(ncontextSparse), Int(ContextSparseTypes._typeList.count), Int(ncontextSparse), Int(contextDenseDefaults._typeList.count), Int(nfeatureListSparse), Int(FeatureListSparseTypes._typeList.count), Int(nfeatureListSparse), Int(FeatureListDenseTypes._typeList.count), Int(nfeatureListDense)) + let op = makeOp("ParseSequenceExample", nOutputs) + op.updateAttribute("feature_list_dense_missing_assumed_empty", featureListDenseMissingAssumedEmpty) + op.updateAttribute("context_sparse_keys", contextSparseKeys) + op.updateAttribute("context_dense_keys", contextDenseKeys) + op.updateAttribute("feature_list_sparse_keys", featureListSparseKeys) + op.updateAttribute("feature_list_dense_keys", featureListDenseKeys) + op.updateAttribute("Ncontext_sparse", ncontextSparse) + op.updateAttribute("Ncontext_dense", ncontextDense) + op.updateAttribute("Nfeature_list_sparse", nfeatureListSparse) + op.updateAttribute("Nfeature_list_dense", nfeatureListDense) + op.updateAttribute("context_sparse_types", ContextSparseTypes._typeList) + op.updateAttribute("Tcontext_dense", contextDenseDefaults._typeList) + op.updateAttribute("feature_list_dense_types", FeatureListDenseTypes._typeList) + op.updateAttribute("context_dense_shapes", contextDenseShapes) + op.updateAttribute("feature_list_sparse_types", FeatureListSparseTypes._typeList) + op.updateAttribute("feature_list_dense_shapes", featureListDenseShapes) + op.addInput(serialized) + op.addInput(debugName) + op.addInputList(contextDenseDefaults) + return op.execute(Int(ncontextSparse), Int(ContextSparseTypes._typeList.count), Int(ncontextSparse), Int(contextDenseDefaults._typeList.count), Int(nfeatureListSparse), Int(FeatureListSparseTypes._typeList.count), Int(nfeatureListSparse), Int(FeatureListDenseTypes._typeList.count), Int(nfeatureListDense)) } /// Transforms a tf.Example proto (as a string) into typed tensors. /// /// - Parameters: -/// - serialized: A vector containing a batch of binary serialized Example protos. -/// - dense_defaults: A list of Tensors (some may be empty), whose length matches -/// the length of `dense_keys`. dense_defaults[j] provides default values -/// when the example's feature_map lacks dense_key[j]. If an empty Tensor is -/// provided for dense_defaults[j], then the Feature dense_keys[j] is required. -/// The input type is inferred from dense_defaults[j], even when it's empty. -/// If dense_defaults[j] is not empty, and dense_shapes[j] is fully defined, -/// then the shape of dense_defaults[j] must match that of dense_shapes[j]. -/// If dense_shapes[j] has an undefined major dimension (variable strides dense -/// feature), dense_defaults[j] must contain a single element: -/// the padding element. +/// - serialized: A vector containing a batch of binary serialized Example protos. +/// - dense_defaults: A list of Tensors (some may be empty), whose length matches +/// the length of `dense_keys`. dense_defaults[j] provides default values +/// when the example's feature_map lacks dense_key[j]. If an empty Tensor is +/// provided for dense_defaults[j], then the Feature dense_keys[j] is required. +/// The input type is inferred from dense_defaults[j], even when it's empty. +/// If dense_defaults[j] is not empty, and dense_shapes[j] is fully defined, +/// then the shape of dense_defaults[j] must match that of dense_shapes[j]. +/// If dense_shapes[j] has an undefined major dimension (variable strides dense +/// feature), dense_defaults[j] must contain a single element: +/// the padding element. /// /// - Attrs: -/// - num_sparse: The number of sparse features to be parsed from the example. This -/// must match the lengths of `sparse_keys` and `sparse_types`. -/// - sparse_keys: A list of `num_sparse` strings. -/// The keys expected in the Examples' features associated with sparse values. -/// - dense_keys: The keys expected in the Examples' features associated with dense -/// values. -/// - sparse_types: A list of `num_sparse` types; the data types of data in each -/// Feature given in sparse_keys. -/// Currently the ParseSingleExample op supports DT_FLOAT (FloatList), -/// DT_INT64 (Int64List), and DT_STRING (BytesList). -/// - Tdense: The data types of data in each Feature given in dense_keys. -/// The length of this list must match the length of `dense_keys`. -/// Currently the ParseSingleExample op supports DT_FLOAT (FloatList), -/// DT_INT64 (Int64List), and DT_STRING (BytesList). -/// - dense_shapes: The shapes of data in each Feature given in dense_keys. -/// The length of this list must match the length of `dense_keys`. The -/// number of elements in the Feature corresponding to dense_key[j] must -/// always equal dense_shapes[j].NumEntries(). If dense_shapes[j] == -/// (D0, D1, ..., DN) then the shape of output Tensor dense_values[j] -/// will be (D0, D1, ..., DN): In the case dense_shapes[j] = (-1, D1, -/// ..., DN), the shape of the output Tensor dense_values[j] will be (M, -/// D1, .., DN), where M is the number of blocks of elements of length -/// D1 * .... * DN, in the input. +/// - num_sparse: The number of sparse features to be parsed from the example. This +/// must match the lengths of `sparse_keys` and `sparse_types`. +/// - sparse_keys: A list of `num_sparse` strings. +/// The keys expected in the Examples' features associated with sparse values. +/// - dense_keys: The keys expected in the Examples' features associated with dense +/// values. +/// - sparse_types: A list of `num_sparse` types; the data types of data in each +/// Feature given in sparse_keys. +/// Currently the ParseSingleExample op supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - Tdense: The data types of data in each Feature given in dense_keys. +/// The length of this list must match the length of `dense_keys`. +/// Currently the ParseSingleExample op supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - dense_shapes: The shapes of data in each Feature given in dense_keys. +/// The length of this list must match the length of `dense_keys`. The +/// number of elements in the Feature corresponding to dense_key[j] must +/// always equal dense_shapes[j].NumEntries(). If dense_shapes[j] == +/// (D0, D1, ..., DN) then the shape of output Tensor dense_values[j] +/// will be (D0, D1, ..., DN): In the case dense_shapes[j] = (-1, D1, +/// ..., DN), the shape of the output Tensor dense_values[j] will be (M, +/// D1, .., DN), where M is the number of blocks of elements of length +/// D1 * .... * DN, in the input. @inlinable @inline(__always) public static func parseSingleExample< SparseTypes: TensorGroup, Tdense: TensorArrayProtocol >( - serialized: StringTensor, - denseDefaults: Tdense, - numSparse: Int64, - sparseKeys: [String], - denseKeys: [String], - denseShapes: [TensorShape?] + serialized: StringTensor, + denseDefaults: Tdense, + numSparse: Int64, + sparseKeys: [String], + denseKeys: [String], + denseShapes: [TensorShape?] ) -> (sparseIndices: [Tensor], sparseValues: SparseTypes, sparseShapes: [Tensor], denseValues: Tdense) { let nOutputs = Int(numSparse) + Int(SparseTypes._typeList.count) + Int(numSparse) + Int(denseDefaults._typeList.count) - let op = makeOp("ParseSingleExample", nOutputs) - op.updateAttribute("num_sparse", numSparse) - op.updateAttribute("sparse_keys", sparseKeys) - op.updateAttribute("dense_keys", denseKeys) - op.updateAttribute("sparse_types", SparseTypes._typeList) - op.updateAttribute("Tdense", denseDefaults._typeList) - op.updateAttribute("dense_shapes", denseShapes) - op.addInput(serialized) - op.addInputList(denseDefaults) - return op.execute(Int(numSparse), Int(SparseTypes._typeList.count), Int(numSparse), Int(denseDefaults._typeList.count)) + let op = makeOp("ParseSingleExample", nOutputs) + op.updateAttribute("num_sparse", numSparse) + op.updateAttribute("sparse_keys", sparseKeys) + op.updateAttribute("dense_keys", denseKeys) + op.updateAttribute("sparse_types", SparseTypes._typeList) + op.updateAttribute("Tdense", denseDefaults._typeList) + op.updateAttribute("dense_shapes", denseShapes) + op.addInput(serialized) + op.addInputList(denseDefaults) + return op.execute(Int(numSparse), Int(SparseTypes._typeList.count), Int(numSparse), Int(denseDefaults._typeList.count)) } /// Transforms a scalar brain.SequenceExample proto (as strings) into typed tensors. /// /// - Parameters: -/// - serialized: A scalar containing a binary serialized SequenceExample proto. -/// - feature_list_dense_missing_assumed_empty: A vector listing the -/// FeatureList keys which may be missing from the SequenceExample. If the -/// associated FeatureList is missing, it is treated as empty. By default, -/// any FeatureList not listed in this vector must exist in the SequenceExample. -/// - context_sparse_keys: A list of Ncontext_sparse string Tensors (scalars). -/// The keys expected in the Examples' features associated with context_sparse -/// values. -/// - context_dense_keys: A list of Ncontext_dense string Tensors (scalars). -/// The keys expected in the SequenceExamples' context features associated with -/// dense values. -/// - feature_list_sparse_keys: A list of Nfeature_list_sparse string Tensors -/// (scalars). The keys expected in the FeatureLists associated with sparse -/// values. -/// - feature_list_dense_keys: A list of Nfeature_list_dense string Tensors (scalars). -/// The keys expected in the SequenceExamples' feature_lists associated -/// with lists of dense values. -/// - context_dense_defaults: A list of Ncontext_dense Tensors (some may be empty). -/// context_dense_defaults[j] provides default values -/// when the SequenceExample's context map lacks context_dense_key[j]. -/// If an empty Tensor is provided for context_dense_defaults[j], -/// then the Feature context_dense_keys[j] is required. -/// The input type is inferred from context_dense_defaults[j], even when it's -/// empty. If context_dense_defaults[j] is not empty, its shape must match -/// context_dense_shapes[j]. -/// - debug_name: A scalar containing the name of the serialized proto. -/// May contain, for example, table key (descriptive) name for the -/// corresponding serialized proto. This is purely useful for debugging -/// purposes, and the presence of values here has no effect on the output. -/// May also be an empty scalar if no name is available. +/// - serialized: A scalar containing a binary serialized SequenceExample proto. +/// - feature_list_dense_missing_assumed_empty: A vector listing the +/// FeatureList keys which may be missing from the SequenceExample. If the +/// associated FeatureList is missing, it is treated as empty. By default, +/// any FeatureList not listed in this vector must exist in the SequenceExample. +/// - context_sparse_keys: A list of Ncontext_sparse string Tensors (scalars). +/// The keys expected in the Examples' features associated with context_sparse +/// values. +/// - context_dense_keys: A list of Ncontext_dense string Tensors (scalars). +/// The keys expected in the SequenceExamples' context features associated with +/// dense values. +/// - feature_list_sparse_keys: A list of Nfeature_list_sparse string Tensors +/// (scalars). The keys expected in the FeatureLists associated with sparse +/// values. +/// - feature_list_dense_keys: A list of Nfeature_list_dense string Tensors (scalars). +/// The keys expected in the SequenceExamples' feature_lists associated +/// with lists of dense values. +/// - context_dense_defaults: A list of Ncontext_dense Tensors (some may be empty). +/// context_dense_defaults[j] provides default values +/// when the SequenceExample's context map lacks context_dense_key[j]. +/// If an empty Tensor is provided for context_dense_defaults[j], +/// then the Feature context_dense_keys[j] is required. +/// The input type is inferred from context_dense_defaults[j], even when it's +/// empty. If context_dense_defaults[j] is not empty, its shape must match +/// context_dense_shapes[j]. +/// - debug_name: A scalar containing the name of the serialized proto. +/// May contain, for example, table key (descriptive) name for the +/// corresponding serialized proto. This is purely useful for debugging +/// purposes, and the presence of values here has no effect on the output. +/// May also be an empty scalar if no name is available. /// /// - Attrs: -/// - context_sparse_types: A list of Ncontext_sparse types; the data types of data in -/// each context Feature given in context_sparse_keys. -/// Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), -/// DT_INT64 (Int64List), and DT_STRING (BytesList). -/// - context_dense_shapes: A list of Ncontext_dense shapes; the shapes of data in -/// each context Feature given in context_dense_keys. -/// The number of elements in the Feature corresponding to context_dense_key[j] -/// must always equal context_dense_shapes[j].NumEntries(). -/// The shape of context_dense_values[j] will match context_dense_shapes[j]. -/// - feature_list_sparse_types: A list of Nfeature_list_sparse types; the data types -/// of data in each FeatureList given in feature_list_sparse_keys. -/// Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), -/// DT_INT64 (Int64List), and DT_STRING (BytesList). -/// - feature_list_dense_shapes: A list of Nfeature_list_dense shapes; the shapes of -/// data in each FeatureList given in feature_list_dense_keys. -/// The shape of each Feature in the FeatureList corresponding to -/// feature_list_dense_key[j] must always equal -/// feature_list_dense_shapes[j].NumEntries(). +/// - context_sparse_types: A list of Ncontext_sparse types; the data types of data in +/// each context Feature given in context_sparse_keys. +/// Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - context_dense_shapes: A list of Ncontext_dense shapes; the shapes of data in +/// each context Feature given in context_dense_keys. +/// The number of elements in the Feature corresponding to context_dense_key[j] +/// must always equal context_dense_shapes[j].NumEntries(). +/// The shape of context_dense_values[j] will match context_dense_shapes[j]. +/// - feature_list_sparse_types: A list of Nfeature_list_sparse types; the data types +/// of data in each FeatureList given in feature_list_sparse_keys. +/// Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), +/// DT_INT64 (Int64List), and DT_STRING (BytesList). +/// - feature_list_dense_shapes: A list of Nfeature_list_dense shapes; the shapes of +/// data in each FeatureList given in feature_list_dense_keys. +/// The shape of each Feature in the FeatureList corresponding to +/// feature_list_dense_key[j] must always equal +/// feature_list_dense_shapes[j].NumEntries(). @inlinable @inline(__always) public static func parseSingleSequenceExample< ContextSparseTypes: TensorGroup, @@ -19630,38 +19617,38 @@ public static func parseSingleSequenceExample< FeatureListDenseTypes: TensorGroup, FeatureListSparseTypes: TensorGroup >( - serialized: StringTensor, - featureListDenseMissingAssumedEmpty: StringTensor, - contextSparseKeys: [StringTensor], - contextDenseKeys: [StringTensor], - featureListSparseKeys: [StringTensor], - featureListDenseKeys: [StringTensor], - contextDenseDefaults: TcontextDense, - debugName: StringTensor, - contextDenseShapes: [TensorShape?], - featureListDenseShapes: [TensorShape?] + serialized: StringTensor, + featureListDenseMissingAssumedEmpty: StringTensor, + contextSparseKeys: [StringTensor], + contextDenseKeys: [StringTensor], + featureListSparseKeys: [StringTensor], + featureListDenseKeys: [StringTensor], + contextDenseDefaults: TcontextDense, + debugName: StringTensor, + contextDenseShapes: [TensorShape?], + featureListDenseShapes: [TensorShape?] ) -> (contextSparseIndices: [Tensor], contextSparseValues: ContextSparseTypes, contextSparseShapes: [Tensor], contextDenseValues: TcontextDense, featureListSparseIndices: [Tensor], featureListSparseValues: FeatureListSparseTypes, featureListSparseShapes: [Tensor], featureListDenseValues: FeatureListDenseTypes) { let nOutputs = Int(contextSparseKeys.count) + Int(ContextSparseTypes._typeList.count) + Int(contextSparseKeys.count) + Int(contextDenseDefaults._typeList.count) + Int(featureListSparseKeys.count) + Int(FeatureListSparseTypes._typeList.count) + Int(featureListSparseKeys.count) + Int(FeatureListDenseTypes._typeList.count) - let op = makeOp("ParseSingleSequenceExample", nOutputs) - op.updateAttribute("Ncontext_sparse", contextSparseKeys.count) - op.updateAttribute("Ncontext_dense", contextDenseKeys.count) - op.updateAttribute("Nfeature_list_sparse", featureListSparseKeys.count) - op.updateAttribute("Nfeature_list_dense", featureListDenseKeys.count) - op.updateAttribute("context_sparse_types", ContextSparseTypes._typeList) - op.updateAttribute("Tcontext_dense", contextDenseDefaults._typeList) - op.updateAttribute("feature_list_dense_types", FeatureListDenseTypes._typeList) - op.updateAttribute("context_dense_shapes", contextDenseShapes) - op.updateAttribute("feature_list_sparse_types", FeatureListSparseTypes._typeList) - op.updateAttribute("feature_list_dense_shapes", featureListDenseShapes) - op.addInput(serialized) - op.addInput(featureListDenseMissingAssumedEmpty) - op.addInputList(contextSparseKeys) - op.addInputList(contextDenseKeys) - op.addInputList(featureListSparseKeys) - op.addInputList(featureListDenseKeys) - op.addInputList(contextDenseDefaults) - op.addInput(debugName) - return op.execute(Int(contextSparseKeys.count), Int(ContextSparseTypes._typeList.count), Int(contextSparseKeys.count), Int(contextDenseDefaults._typeList.count), Int(featureListSparseKeys.count), Int(FeatureListSparseTypes._typeList.count), Int(featureListSparseKeys.count), Int(FeatureListDenseTypes._typeList.count)) + let op = makeOp("ParseSingleSequenceExample", nOutputs) + op.updateAttribute("Ncontext_sparse", contextSparseKeys.count) + op.updateAttribute("Ncontext_dense", contextDenseKeys.count) + op.updateAttribute("Nfeature_list_sparse", featureListSparseKeys.count) + op.updateAttribute("Nfeature_list_dense", featureListDenseKeys.count) + op.updateAttribute("context_sparse_types", ContextSparseTypes._typeList) + op.updateAttribute("Tcontext_dense", contextDenseDefaults._typeList) + op.updateAttribute("feature_list_dense_types", FeatureListDenseTypes._typeList) + op.updateAttribute("context_dense_shapes", contextDenseShapes) + op.updateAttribute("feature_list_sparse_types", FeatureListSparseTypes._typeList) + op.updateAttribute("feature_list_dense_shapes", featureListDenseShapes) + op.addInput(serialized) + op.addInput(featureListDenseMissingAssumedEmpty) + op.addInputList(contextSparseKeys) + op.addInputList(contextDenseKeys) + op.addInputList(featureListSparseKeys) + op.addInputList(featureListDenseKeys) + op.addInputList(contextDenseDefaults) + op.addInput(debugName) + return op.execute(Int(contextSparseKeys.count), Int(ContextSparseTypes._typeList.count), Int(contextSparseKeys.count), Int(contextDenseDefaults._typeList.count), Int(featureListSparseKeys.count), Int(FeatureListSparseTypes._typeList.count), Int(featureListSparseKeys.count), Int(FeatureListDenseTypes._typeList.count)) } /// Transforms a serialized tensorflow.TensorProto proto into a Tensor. @@ -19669,18 +19656,18 @@ public static func parseSingleSequenceExample< /// - Parameter serialized: A scalar string containing a serialized TensorProto proto. /// /// - Attr out_type: The type of the serialized tensor. The provided type must match the -/// type of the serialized tensor and no implicit conversion will take place. +/// type of the serialized tensor and no implicit conversion will take place. /// /// - Output output: A Tensor of type `out_type`. @inlinable @inline(__always) public static func parseTensor( - serialized: StringTensor + serialized: StringTensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ParseTensor", nOutputs) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(serialized) - return op.execute(Int(1)) + let op = makeOp("ParseTensor", nOutputs) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(serialized) + return op.execute(Int(1)) } /// returns `f(inputs)`, where `f`'s body is placed and partitioned. @@ -19688,12 +19675,12 @@ public static func parseTensor( /// - Parameter args: A list of input tensors. /// /// - Attrs: -/// - Tin: A list of input types. -/// - Tout: A list of output types. -/// - f: A function that takes 'args', a list of tensors, and returns 'output', -/// another list of tensors. Input and output types are specified by 'Tin' -/// and 'Tout'. The function body of f will be placed and partitioned across -/// devices, setting this op apart from the regular Call op. +/// - Tin: A list of input types. +/// - Tout: A list of output types. +/// - f: A function that takes 'args', a list of tensors, and returns 'output', +/// another list of tensors. Input and output types are specified by 'Tin' +/// and 'Tout'. The function body of f will be placed and partitioned across +/// devices, setting this op apart from the regular Call op. /// /// - Output output: A list of return values. @inlinable @inline(__always) @@ -19703,22 +19690,22 @@ public static func partitionedCall< FIn: TensorGroup, FOut: TensorGroup >( - args: Tin, - f: (FIn) -> FOut, - config: String, - configProto: String, - executorType: String + args: Tin, + f: (FIn) -> FOut, + config: String, + configProto: String, + executorType: String ) -> Tout { let nOutputs = Int(Tout._typeList.count) - let op = makeOp("PartitionedCall", nOutputs) - op.updateAttribute("Tin", args._typeList) - op.updateAttribute("Tout", Tout._typeList) - op.updateAttribute("f", f) - op.updateAttribute("config", config) - op.updateAttribute("config_proto", configProto) - op.updateAttribute("executor_type", executorType) - op.addInputList(args) - return op.execute(Int(Tout._typeList.count)) + let op = makeOp("PartitionedCall", nOutputs) + op.updateAttribute("Tin", args._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("f", f) + op.updateAttribute("config", config) + op.updateAttribute("config_proto", configProto) + op.updateAttribute("executor_type", executorType) + op.addInputList(args) + return op.execute(Int(Tout._typeList.count)) } /// A placeholder op for a value that will be fed into the computation. @@ -19728,20 +19715,20 @@ public static func partitionedCall< /// provide attrs that enable the fed value to be checked at runtime. /// /// - Attrs: -/// - dtype: The type of elements in the tensor. -/// - shape: (Optional) The shape of the tensor. If the shape has 0 dimensions, the -/// shape is unconstrained. +/// - dtype: The type of elements in the tensor. +/// - shape: (Optional) The shape of the tensor. If the shape has 0 dimensions, the +/// shape is unconstrained. /// /// - Output output: A placeholder tensor that must be replaced using the feed mechanism. @inlinable @inline(__always) public static func placeholder( - shape: TensorShape? + shape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Placeholder", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape", shape) - return op.execute(Int(1)) + let op = makeOp("Placeholder", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + return op.execute(Int(1)) } /// A placeholder op for a value that will be fed into the computation. @@ -19751,20 +19738,20 @@ public static func placeholder( /// provide attrs that enable the fed value to be checked at runtime. /// /// - Attrs: -/// - dtype: The type of elements in the tensor. -/// - shape: The shape of the tensor. The shape can be any partially-specified -/// shape. To be unconstrained, pass in a shape with unknown rank. +/// - dtype: The type of elements in the tensor. +/// - shape: The shape of the tensor. The shape can be any partially-specified +/// shape. To be unconstrained, pass in a shape with unknown rank. /// /// - Output output: A placeholder tensor that must be replaced using the feed mechanism. @inlinable @inline(__always) public static func placeholderV2( - shape: TensorShape? + shape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("PlaceholderV2", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape", shape) - return op.execute(Int(1)) + let op = makeOp("PlaceholderV2", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + return op.execute(Int(1)) } /// A placeholder op that passes through `input` when its output is not fed. @@ -19772,21 +19759,21 @@ public static func placeholderV2( /// - Parameter input: The default value to produce when `output` is not fed. /// /// - Attrs: -/// - dtype: The type of elements in the tensor. -/// - shape: The (possibly partial) shape of the tensor. +/// - dtype: The type of elements in the tensor. +/// - shape: The (possibly partial) shape of the tensor. /// /// - Output output: A placeholder tensor that defaults to `input` if it is not fed. @inlinable @inline(__always) public static func placeholderWithDefault( - _ input: Tensor, - shape: TensorShape? + _ input: Tensor, + shape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("PlaceholderWithDefault", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape", shape) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("PlaceholderWithDefault", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.addInput(input) + return op.execute(Int(1)) } /// Compute the polygamma function \\(\psi^{(n)}(x)\\). @@ -19800,44 +19787,44 @@ public static func placeholderWithDefault( /// The polygamma function is defined only for non-negative integer orders \\a\\. @inlinable @inline(__always) public static func polygamma( - _ a: Tensor, - _ x: Tensor + _ a: Tensor, + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Polygamma", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Polygamma", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + op.addInput(x) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func polymorphic( - _ a: Tensor + _ a: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Polymorphic", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - return op.execute(Int(1)) + let op = makeOp("Polymorphic", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func polymorphicDefaultOut( ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("PolymorphicDefaultOut", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - return op.execute(Int(1)) + let op = makeOp("PolymorphicDefaultOut", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func polymorphicOut( ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("PolymorphicOut", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - return op.execute(Int(1)) + let op = makeOp("PolymorphicOut", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + return op.execute(Int(1)) } /// Computes element-wise population count (a.k.a. popcount, bitsum, bitcount). @@ -19850,13 +19837,13 @@ public static func polymorphicOut( /// 8- or 16-bit inputs and then aggregate the resulting counts. @inlinable @inline(__always) public static func populationCount( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("PopulationCount", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("PopulationCount", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the power of one value to another. @@ -19871,37 +19858,35 @@ public static func populationCount( /// ``` @inlinable @inline(__always) public static func pow( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Pow", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Pow", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Creates a dataset that asynchronously prefetches elements from `input_dataset`. /// /// - Parameter buffer_size: The maximum number of elements to buffer in an iterator over -/// this dataset. +/// this dataset. @inlinable @inline(__always) public static func prefetchDataset( - inputDataset: VariantHandle, - bufferSize: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?], - slackPeriod: Int64 = 0 + inputDataset: VariantHandle, + bufferSize: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("PrefetchDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("slack_period", slackPeriod) - op.addInput(inputDataset) - op.addInput(bufferSize) - return op.execute(Int(1)) + let op = makeOp("PrefetchDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(bufferSize) + return op.execute(Int(1)) } /// An op which linearizes one Tensor value to an opaque variant tensor. @@ -19909,24 +19894,24 @@ public static func prefetchDataset( /// - Parameter input: A tensor that will be linearized. /// /// - Attrs: -/// - dtype: The type of elements in the tensor. -/// - shape: The shape of the tensor. -/// - layout: A vector holding the requested layout in minor-to-major sequence. If a layout -/// attribute is passed but its values are all -1 the layout will be computed by -/// the infeed operation. +/// - dtype: The type of elements in the tensor. +/// - shape: The shape of the tensor. +/// - layout: A vector holding the requested layout in minor-to-major sequence. If a layout +/// attribute is passed but its values are all -1 the layout will be computed by +/// the infeed operation. @inlinable @inline(__always) public static func prelinearize( - _ input: Tensor, - shape: TensorShape?, - layout: [Int32] + _ input: Tensor, + shape: TensorShape?, + layout: [Int32] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("Prelinearize", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape", shape) - op.updateAttribute("layout", layout) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Prelinearize", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape", shape) + op.updateAttribute("layout", layout) + op.addInput(input) + return op.execute(Int(1)) } /// An op which linearizes multiple Tensor values to an opaque variant tensor. @@ -19934,25 +19919,25 @@ public static func prelinearize( /// - Parameter inputs: A list of tensors that will be provided using the infeed mechanism. /// /// - Attrs: -/// - dtypes: The element types of each element in `inputs`. -/// - shapes: The shapes of each tensor in `inputs`. -/// - layouts: A vector holding the requested layout in minor-to-major sequence for all the -/// tuple shapes in the order the shapes appear in the "shapes" input. The layout -/// elements for a sub-shape can be set to -1 in which case the corresponding layout -/// will be computed by the infeed operation. +/// - dtypes: The element types of each element in `inputs`. +/// - shapes: The shapes of each tensor in `inputs`. +/// - layouts: A vector holding the requested layout in minor-to-major sequence for all the +/// tuple shapes in the order the shapes appear in the "shapes" input. The layout +/// elements for a sub-shape can be set to -1 in which case the corresponding layout +/// will be computed by the infeed operation. @inlinable @inline(__always) public static func prelinearizeTuple( - inputs: Dtypes, - shapes: [TensorShape?], - layouts: [Int32] + inputs: Dtypes, + shapes: [TensorShape?], + layouts: [Int32] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("PrelinearizeTuple", nOutputs) - op.updateAttribute("dtypes", inputs._typeList) - op.updateAttribute("shapes", shapes) - op.updateAttribute("layouts", layouts) - op.addInputList(inputs) - return op.execute(Int(1)) + let op = makeOp("PrelinearizeTuple", nOutputs) + op.updateAttribute("dtypes", inputs._typeList) + op.updateAttribute("shapes", shapes) + op.updateAttribute("layouts", layouts) + op.addInputList(inputs) + return op.execute(Int(1)) } /// An identity op that triggers an error if a gradient is requested. @@ -19968,20 +19953,20 @@ public static func prelinearizeTuple( /// - Parameter input: any tensor. /// /// - Attr message: Will be printed in the error when anyone tries to differentiate -/// this operation. +/// this operation. /// /// - Output output: the same input tensor. @inlinable @inline(__always) public static func preventGradient( - _ input: Tensor, - message: String + _ input: Tensor, + message: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("PreventGradient", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("message", message) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("PreventGradient", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("message", message) + op.addInput(input) + return op.execute(Int(1)) } /// Prints a list of tensors. @@ -19989,13 +19974,13 @@ public static func preventGradient( /// Passes `input` through to `output` and prints `data` when evaluating. /// /// - Parameters: -/// - input: The tensor passed to `output` -/// - data: A list of tensors to print out when op is evaluated. +/// - input: The tensor passed to `output` +/// - data: A list of tensors to print out when op is evaluated. /// /// - Attrs: -/// - message: A string, prefix of the error message. -/// - first_n: Only log `first_n` number of times. -1 disables logging. -/// - summarize: Only print this many entries of each tensor. +/// - message: A string, prefix of the error message. +/// - first_n: Only log `first_n` number of times. -1 disables logging. +/// - summarize: Only print this many entries of each tensor. /// /// - Output output: = The unmodified `input` tensor @inlinable @inline(__always) @@ -20003,22 +19988,22 @@ public static func print< T: TensorFlowScalar, U: TensorArrayProtocol >( - _ input: Tensor, - data: U, - message: String, - firstN: Int64 = -1, - summarize: Int64 = 3 + _ input: Tensor, + data: U, + message: String, + firstN: Int64 = -1, + summarize: Int64 = 3 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Print", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("U", data._typeList) - op.updateAttribute("message", message) - op.updateAttribute("first_n", firstN) - op.updateAttribute("summarize", summarize) - op.addInput(input) - op.addInputList(data) - return op.execute(Int(1)) + let op = makeOp("Print", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("U", data._typeList) + op.updateAttribute("message", message) + op.updateAttribute("first_n", firstN) + op.updateAttribute("summarize", summarize) + op.addInput(input) + op.addInputList(data) + return op.execute(Int(1)) } /// Prints a string scalar. @@ -20030,16 +20015,14 @@ public static func print< /// - Attr output_stream: A string specifying the output stream or logging level to print to. @inlinable @inline(__always) public static func printV2( - _ input: StringTensor, - outputStream: String = "stderr", - end: String = "" + _ input: StringTensor, + outputStream: String = "stderr" ) { let nOutputs = 0 - let op = makeOp("PrintV2", nOutputs) - op.updateAttribute("output_stream", outputStream) - op.updateAttribute("end", end) - op.addInput(input) - op.execute() + let op = makeOp("PrintV2", nOutputs) + op.updateAttribute("output_stream", outputStream) + op.addInput(input) + op.execute() } /// A queue that produces elements sorted by the first component value. @@ -20051,35 +20034,35 @@ public static func printV2( /// entry in their input (resp. output) lists. /// /// - Attrs: -/// - component_types: The type of each component in a value. -/// - shapes: The shape of each component in a value. The length of this attr must -/// be either 0 or the same as the length of component_types. If the length of -/// this attr is 0, the shapes of queue elements are not constrained, and -/// only one element may be dequeued at a time. -/// - capacity: The upper bound on the number of elements in this queue. -/// Negative numbers mean no limit. -/// - container: If non-empty, this queue is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this queue will be shared under the given name -/// across multiple sessions. +/// - component_types: The type of each component in a value. +/// - shapes: The shape of each component in a value. The length of this attr must +/// be either 0 or the same as the length of component_types. If the length of +/// this attr is 0, the shapes of queue elements are not constrained, and +/// only one element may be dequeued at a time. +/// - capacity: The upper bound on the number of elements in this queue. +/// Negative numbers mean no limit. +/// - container: If non-empty, this queue is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this queue will be shared under the given name +/// across multiple sessions. /// /// - Output handle: The handle to the queue. @inlinable @inline(__always) public static func priorityQueueV2( - componentTypes: [TensorDataType], - shapes: [TensorShape?], - capacity: Int64 = -1, - container: String, - sharedName: String + componentTypes: [TensorDataType], + shapes: [TensorShape?], + capacity: Int64 = -1, + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("PriorityQueueV2", nOutputs) - op.updateAttribute("component_types", componentTypes) - op.updateAttribute("shapes", shapes) - op.updateAttribute("capacity", capacity) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("PriorityQueueV2", nOutputs) + op.updateAttribute("component_types", componentTypes) + op.updateAttribute("shapes", shapes) + op.updateAttribute("capacity", capacity) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Computes the product of elements across dimensions of a tensor. @@ -20090,9 +20073,9 @@ public static func priorityQueueV2( /// retained with length 1. /// /// - Parameters: -/// - input: The tensor to reduce. -/// - reduction_indices: The dimensions to reduce. Must be in the range -/// `[-rank(input), rank(input))`. +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. /// /// - Attr keep_dims: If true, retain reduced dimensions with length 1. /// @@ -20102,18 +20085,18 @@ public static func prod< T: Numeric & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - reductionIndices: Tensor, - keepDims: Bool = false + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Prod", nOutputs) - op.updateAttribute("keep_dims", keepDims) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(input) - op.addInput(reductionIndices) - return op.execute(Int(1)) + let op = makeOp("Prod", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) } /// Invokes a python function to compute func(input)->output. @@ -20124,10 +20107,10 @@ public static func prod< /// - Parameter input: List of Tensors that will provide input to the Op. /// /// - Attrs: -/// - token: A token representing a registered python function in this address space. -/// - Tin: Data types of the inputs to the op. -/// - Tout: Data types of the outputs from the op. -/// The length of the list specifies the number of outputs. +/// - token: A token representing a registered python function in this address space. +/// - Tin: Data types of the inputs to the op. +/// - Tout: Data types of the outputs from the op. +/// The length of the list specifies the number of outputs. /// /// - Output output: The outputs from the Op. @inlinable @inline(__always) @@ -20135,16 +20118,16 @@ public static func pyFunc< Tin: TensorArrayProtocol, Tout: TensorGroup >( - _ input: Tin, - token: String + _ input: Tin, + token: String ) -> Tout { let nOutputs = Int(Tout._typeList.count) - let op = makeOp("PyFunc", nOutputs) - op.updateAttribute("token", token) - op.updateAttribute("Tin", input._typeList) - op.updateAttribute("Tout", Tout._typeList) - op.addInputList(input) - return op.execute(Int(Tout._typeList.count)) + let op = makeOp("PyFunc", nOutputs) + op.updateAttribute("token", token) + op.updateAttribute("Tin", input._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.addInputList(input) + return op.execute(Int(Tout._typeList.count)) } /// A stateless version of PyFunc. @@ -20153,16 +20136,16 @@ public static func pyFuncStateless< Tin: TensorArrayProtocol, Tout: TensorGroup >( - _ input: Tin, - token: String + _ input: Tin, + token: String ) -> Tout { let nOutputs = Int(Tout._typeList.count) - let op = makeOp("PyFuncStateless", nOutputs) - op.updateAttribute("token", token) - op.updateAttribute("Tin", input._typeList) - op.updateAttribute("Tout", Tout._typeList) - op.addInputList(input) - return op.execute(Int(Tout._typeList.count)) + let op = makeOp("PyFuncStateless", nOutputs) + op.updateAttribute("token", token) + op.updateAttribute("Tin", input._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.addInputList(input) + return op.execute(Int(Tout._typeList.count)) } /// Computes the QR decompositions of one or more matrices. @@ -20179,50 +20162,50 @@ public static func pyFuncStateless< /// ``` /// /// - Parameter input: A tensor of shape `[..., M, N]` whose inner-most 2 dimensions -/// form matrices of size `[M, N]`. Let `P` be the minimum of `M` and `N`. +/// form matrices of size `[M, N]`. Let `P` be the minimum of `M` and `N`. /// /// - Attr full_matrices: If true, compute full-sized `q` and `r`. If false -/// (the default), compute only the leading `P` columns of `q`. +/// (the default), compute only the leading `P` columns of `q`. /// /// - Outputs: -/// - q: Orthonormal basis for range of `a`. If `full_matrices` is `False` then -/// shape is `[..., M, P]`; if `full_matrices` is `True` then shape is -/// `[..., M, M]`. -/// - r: Triangular factor. If `full_matrices` is `False` then shape is -/// `[..., P, N]`. If `full_matrices` is `True` then shape is `[..., M, N]`. +/// - q: Orthonormal basis for range of `a`. If `full_matrices` is `False` then +/// shape is `[..., M, P]`; if `full_matrices` is `True` then shape is +/// `[..., M, M]`. +/// - r: Triangular factor. If `full_matrices` is `False` then shape is +/// `[..., P, N]`. If `full_matrices` is `True` then shape is `[..., M, N]`. @inlinable @inline(__always) public static func qr( - _ input: Tensor, - fullMatrices: Bool = false + _ input: Tensor, + fullMatrices: Bool = false ) -> (q: Tensor, r: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("Qr", nOutputs) - op.updateAttribute("full_matrices", fullMatrices) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1), Int(1)) + let op = makeOp("Qr", nOutputs) + op.updateAttribute("full_matrices", fullMatrices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) } /// Use QuantizeAndDequantizeV2 instead. @inlinable @inline(__always) public static func quantizeAndDequantize( - _ input: Tensor, - signedInput: Bool = true, - numBits: Int64 = 8, - rangeGiven: Bool = false, - inputMin: Double = 0, - inputMax: Double = 0 + _ input: Tensor, + signedInput: Bool = true, + numBits: Int64 = 8, + rangeGiven: Bool = false, + inputMin: Double = 0, + inputMax: Double = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("QuantizeAndDequantize", nOutputs) - op.updateAttribute("signed_input", signedInput) - op.updateAttribute("num_bits", numBits) - op.updateAttribute("range_given", rangeGiven) - op.updateAttribute("input_min", inputMin) - op.updateAttribute("input_max", inputMax) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("QuantizeAndDequantize", nOutputs) + op.updateAttribute("signed_input", signedInput) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("range_given", rangeGiven) + op.updateAttribute("input_min", inputMin) + op.updateAttribute("input_max", inputMax) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Quantizes then dequantizes a tensor. @@ -20281,48 +20264,48 @@ public static func quantizeAndDequantize( /// /// /// - Parameters: -/// - input: Tensor to quantize and then dequantize. -/// - input_min: If `range_given == True`, this specifies the minimum input value that needs to -/// be represented, otherwise it is determined from the min value of the `input` -/// tensor. -/// - input_max: If `range_given == True`, this specifies the maximum input value that needs to -/// be represented, otherwise it is determined from the max value of the `input` -/// tensor. +/// - input: Tensor to quantize and then dequantize. +/// - input_min: If `range_given == True`, this specifies the minimum input value that needs to +/// be represented, otherwise it is determined from the min value of the `input` +/// tensor. +/// - input_max: If `range_given == True`, this specifies the maximum input value that needs to +/// be represented, otherwise it is determined from the max value of the `input` +/// tensor. /// /// - Attrs: -/// - signed_input: Whether the quantization is signed or unsigned. (actually this parameter should -/// have been called `signed_output`) -/// - num_bits: The bitwidth of the quantization. -/// - range_given: Whether the range is given or should be determined from the `input` tensor. -/// - round_mode: The 'round_mode' attribute controls which rounding tie-breaking algorithm is -/// used when rounding float values to their quantized equivalents. The following -/// rounding modes are currently supported: +/// - signed_input: Whether the quantization is signed or unsigned. (actually this parameter should +/// have been called `signed_output`) +/// - num_bits: The bitwidth of the quantization. +/// - range_given: Whether the range is given or should be determined from the `input` tensor. +/// - round_mode: The 'round_mode' attribute controls which rounding tie-breaking algorithm is +/// used when rounding float values to their quantized equivalents. The following +/// rounding modes are currently supported: /// -/// * HALF_TO_EVEN: this is the default round_mode. -/// * HALF_UP: round towards positive. In this mode 7.5 rounds up to 8 and -7.5 -/// rounds up to -7. +/// * HALF_TO_EVEN: this is the default round_mode. +/// * HALF_UP: round towards positive. In this mode 7.5 rounds up to 8 and -7.5 +/// rounds up to -7. /// @inlinable @inline(__always) public static func quantizeAndDequantizeV2( - _ input: Tensor, - inputMin: Tensor, - inputMax: Tensor, - signedInput: Bool = true, - numBits: Int64 = 8, - rangeGiven: Bool = false, - roundMode: RoundMode = .halfToEven -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("QuantizeAndDequantizeV2", nOutputs) - op.updateAttribute("signed_input", signedInput) - op.updateAttribute("num_bits", numBits) - op.updateAttribute("range_given", rangeGiven) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("round_mode", roundMode.cName) - op.addInput(input) - op.addInput(inputMin) - op.addInput(inputMax) - return op.execute(Int(1)) + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor, + signedInput: Bool = true, + numBits: Int64 = 8, + rangeGiven: Bool = false, + roundMode: RoundMode = .halfToEven +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("QuantizeAndDequantizeV2", nOutputs) + op.updateAttribute("signed_input", signedInput) + op.updateAttribute("num_bits", numBits) + op.updateAttribute("range_given", rangeGiven) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("round_mode", roundMode.cName) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + return op.execute(Int(1)) } /// Quantizes then dequantizes a tensor. @@ -20331,23 +20314,23 @@ public static func quantizeAndDequantizeV2( /// tensor, so its value can change during training. @inlinable @inline(__always) public static func quantizeAndDequantizeV3( - _ input: Tensor, - inputMin: Tensor, - inputMax: Tensor, - numBits: Tensor, - signedInput: Bool = true, - rangeGiven: Bool = true + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor, + numBits: Tensor, + signedInput: Bool = true, + rangeGiven: Bool = true ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("QuantizeAndDequantizeV3", nOutputs) - op.updateAttribute("signed_input", signedInput) - op.updateAttribute("range_given", rangeGiven) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - op.addInput(inputMin) - op.addInput(inputMax) - op.addInput(numBits) - return op.execute(Int(1)) + let op = makeOp("QuantizeAndDequantizeV3", nOutputs) + op.updateAttribute("signed_input", signedInput) + op.updateAttribute("range_given", rangeGiven) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + op.addInput(numBits) + return op.execute(Int(1)) } /// Convert the quantized 'input' tensor into a lower-precision 'output', using the @@ -20376,33 +20359,33 @@ public static func quantizeAndDequantizeV3( /// minimal loss of accuracy. /// /// - Parameters: -/// - input_min: The float value that the minimum quantized input value represents. -/// - input_max: The float value that the maximum quantized input value represents. +/// - input_min: The float value that the minimum quantized input value represents. +/// - input_max: The float value that the maximum quantized input value represents. /// /// - Attrs: -/// - Tinput: The type of the input. -/// - out_type: The type of the output. Should be a lower bit depth than Tinput. +/// - Tinput: The type of the input. +/// - out_type: The type of the output. Should be a lower bit depth than Tinput. /// /// - Outputs: -/// - output_min: The float value that the minimum quantized output value represents. -/// - output_max: The float value that the maximum quantized output value represents. +/// - output_min: The float value that the minimum quantized output value represents. +/// - output_max: The float value that the maximum quantized output value represents. @inlinable @inline(__always) public static func quantizeDownAndShrinkRange< Tinput: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - inputMin: Tensor, - inputMax: Tensor + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor ) -> (output: Tensor, outputMin: Tensor, outputMax: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizeDownAndShrinkRange", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(input) - op.addInput(inputMin) - op.addInput(inputMax) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizeDownAndShrinkRange", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + return op.execute(Int(1), Int(1), Int(1)) } /// Quantize the 'input' tensor of type float to 'output' tensor of type 'T'. @@ -20507,109 +20490,109 @@ public static func quantizeDownAndShrinkRange< /// operations that have to perform further calculations on them. /// /// - Parameters: -/// - min_range: The minimum scalar value possibly produced for the input. -/// - max_range: The maximum scalar value possibly produced for the input. +/// - min_range: The minimum scalar value possibly produced for the input. +/// - max_range: The maximum scalar value possibly produced for the input. /// /// - Outputs: -/// - output: The quantized data produced from the float input. -/// - output_min: The actual minimum scalar value used for the output. -/// - output_max: The actual maximum scalar value used for the output. +/// - output: The quantized data produced from the float input. +/// - output_min: The actual minimum scalar value used for the output. +/// - output_max: The actual maximum scalar value used for the output. @inlinable @inline(__always) public static func quantizeV2( - _ input: Tensor, - minRange: Tensor, - maxRange: Tensor, - mode: Mode = .minCombined, - roundMode: RoundMode6 = .halfAwayFromZero + _ input: Tensor, + minRange: Tensor, + maxRange: Tensor, + mode: Mode = .minCombined, + roundMode: RoundMode6 = .halfAwayFromZero ) -> (output: Tensor, outputMin: Tensor, outputMax: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizeV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("mode", mode.cName) - op.updateAttribute("round_mode", roundMode.cName) - op.addInput(input) - op.addInput(minRange) - op.addInput(maxRange) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizeV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("mode", mode.cName) + op.updateAttribute("round_mode", roundMode.cName) + op.addInput(input) + op.addInput(minRange) + op.addInput(maxRange) + return op.execute(Int(1), Int(1), Int(1)) } /// Returns x + y element-wise, working on quantized buffers. /// /// - Parameters: -/// - min_x: The float value that the lowest quantized `x` value represents. -/// - max_x: The float value that the highest quantized `x` value represents. -/// - min_y: The float value that the lowest quantized `y` value represents. -/// - max_y: The float value that the highest quantized `y` value represents. +/// - min_x: The float value that the lowest quantized `x` value represents. +/// - max_x: The float value that the highest quantized `x` value represents. +/// - min_y: The float value that the lowest quantized `y` value represents. +/// - max_y: The float value that the highest quantized `y` value represents. /// /// - Outputs: -/// - min_z: The float value that the lowest quantized output value represents. -/// - max_z: The float value that the highest quantized output value represents. +/// - min_z: The float value that the lowest quantized output value represents. +/// - max_z: The float value that the highest quantized output value represents. /// -/// *NOTE*: `QuantizedAdd` supports limited forms of broadcasting. More about -/// broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +/// *NOTE*: `QuantizedAdd` supports limited forms of broadcasting. More about +/// broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func quantizedAdd< T1: TensorFlowScalar, T2: TensorFlowScalar, Toutput: TensorFlowScalar >( - _ x: Tensor, - _ y: Tensor, - minX: Tensor, - maxX: Tensor, - minY: Tensor, - maxY: Tensor + _ x: Tensor, + _ y: Tensor, + minX: Tensor, + maxX: Tensor, + minY: Tensor, + maxY: Tensor ) -> (z: Tensor, minZ: Tensor, maxZ: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedAdd", nOutputs) - op.updateAttribute("T1", T1.tensorFlowDataType) - op.updateAttribute("T2", T2.tensorFlowDataType) - op.updateAttribute("Toutput", Toutput.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - op.addInput(minX) - op.addInput(maxX) - op.addInput(minY) - op.addInput(maxY) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedAdd", nOutputs) + op.updateAttribute("T1", T1.tensorFlowDataType) + op.updateAttribute("T2", T2.tensorFlowDataType) + op.updateAttribute("Toutput", Toutput.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + op.addInput(minX) + op.addInput(maxX) + op.addInput(minY) + op.addInput(maxY) + return op.execute(Int(1), Int(1), Int(1)) } /// Produces the average pool of the input tensor for quantized types. /// /// - Parameters: -/// - input: 4-D with shape `[batch, height, width, channels]`. -/// - min_input: The float value that the lowest quantized input value represents. -/// - max_input: The float value that the highest quantized input value represents. +/// - input: 4-D with shape `[batch, height, width, channels]`. +/// - min_input: The float value that the lowest quantized input value represents. +/// - max_input: The float value that the highest quantized input value represents. /// /// - Attrs: -/// - ksize: The size of the window for each dimension of the input tensor. -/// The length must be 4 to match the number of dimensions of the input. -/// - strides: The stride of the sliding window for each dimension of the input -/// tensor. The length must be 4 to match the number of dimensions of the input. -/// - padding: The type of padding algorithm to use. +/// - ksize: The size of the window for each dimension of the input tensor. +/// The length must be 4 to match the number of dimensions of the input. +/// - strides: The stride of the sliding window for each dimension of the input +/// tensor. The length must be 4 to match the number of dimensions of the input. +/// - padding: The type of padding algorithm to use. /// /// - Outputs: -/// - min_output: The float value that the lowest quantized output value represents. -/// - max_output: The float value that the highest quantized output value represents. +/// - min_output: The float value that the lowest quantized output value represents. +/// - max_output: The float value that the highest quantized output value represents. @inlinable @inline(__always) public static func quantizedAvgPool( - _ input: Tensor, - minInput: Tensor, - maxInput: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding + _ input: Tensor, + minInput: Tensor, + maxInput: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedAvgPool", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.addInput(input) - op.addInput(minInput) - op.addInput(maxInput) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedAvgPool", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(minInput) + op.addInput(maxInput) + return op.execute(Int(1), Int(1), Int(1)) } /// Quantized Batch normalization. @@ -20618,78 +20601,78 @@ public static func quantizedAvgPool( /// `tf.nn.batch_normalization`. /// /// - Parameters: -/// - t: A 4D input Tensor. -/// - t_min: The value represented by the lowest quantized input. -/// - t_max: The value represented by the highest quantized input. -/// - m: A 1D mean Tensor with size matching the last dimension of t. -/// This is the first output from tf.nn.moments, -/// or a saved moving average thereof. -/// - m_min: The value represented by the lowest quantized mean. -/// - m_max: The value represented by the highest quantized mean. -/// - v: A 1D variance Tensor with size matching the last dimension of t. -/// This is the second output from tf.nn.moments, -/// or a saved moving average thereof. -/// - v_min: The value represented by the lowest quantized variance. -/// - v_max: The value represented by the highest quantized variance. -/// - beta: A 1D beta Tensor with size matching the last dimension of t. -/// An offset to be added to the normalized tensor. -/// - beta_min: The value represented by the lowest quantized offset. -/// - beta_max: The value represented by the highest quantized offset. -/// - gamma: A 1D gamma Tensor with size matching the last dimension of t. -/// If "scale_after_normalization" is true, this tensor will be multiplied -/// with the normalized tensor. -/// - gamma_min: The value represented by the lowest quantized gamma. -/// - gamma_max: The value represented by the highest quantized gamma. +/// - t: A 4D input Tensor. +/// - t_min: The value represented by the lowest quantized input. +/// - t_max: The value represented by the highest quantized input. +/// - m: A 1D mean Tensor with size matching the last dimension of t. +/// This is the first output from tf.nn.moments, +/// or a saved moving average thereof. +/// - m_min: The value represented by the lowest quantized mean. +/// - m_max: The value represented by the highest quantized mean. +/// - v: A 1D variance Tensor with size matching the last dimension of t. +/// This is the second output from tf.nn.moments, +/// or a saved moving average thereof. +/// - v_min: The value represented by the lowest quantized variance. +/// - v_max: The value represented by the highest quantized variance. +/// - beta: A 1D beta Tensor with size matching the last dimension of t. +/// An offset to be added to the normalized tensor. +/// - beta_min: The value represented by the lowest quantized offset. +/// - beta_max: The value represented by the highest quantized offset. +/// - gamma: A 1D gamma Tensor with size matching the last dimension of t. +/// If "scale_after_normalization" is true, this tensor will be multiplied +/// with the normalized tensor. +/// - gamma_min: The value represented by the lowest quantized gamma. +/// - gamma_max: The value represented by the highest quantized gamma. /// /// - Attrs: -/// - variance_epsilon: A small float number to avoid dividing by 0. -/// - scale_after_normalization: A bool indicating whether the resulted tensor -/// needs to be multiplied with gamma. +/// - variance_epsilon: A small float number to avoid dividing by 0. +/// - scale_after_normalization: A bool indicating whether the resulted tensor +/// needs to be multiplied with gamma. @inlinable @inline(__always) public static func quantizedBatchNormWithGlobalNormalization< Tinput: TensorFlowScalar, OutType: TensorFlowScalar >( - t: Tensor, - tMin: Tensor, - tMax: Tensor, - m: Tensor, - mMin: Tensor, - mMax: Tensor, - v: Tensor, - vMin: Tensor, - vMax: Tensor, - beta: Tensor, - betaMin: Tensor, - betaMax: Tensor, - gamma: Tensor, - gammaMin: Tensor, - gammaMax: Tensor, - varianceEpsilon: Double, - scaleAfterNormalization: Bool + t: Tensor, + tMin: Tensor, + tMax: Tensor, + m: Tensor, + mMin: Tensor, + mMax: Tensor, + v: Tensor, + vMin: Tensor, + vMax: Tensor, + beta: Tensor, + betaMin: Tensor, + betaMax: Tensor, + gamma: Tensor, + gammaMin: Tensor, + gammaMax: Tensor, + varianceEpsilon: Double, + scaleAfterNormalization: Bool ) -> (result: Tensor, resultMin: Tensor, resultMax: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedBatchNormWithGlobalNormalization", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("variance_epsilon", varianceEpsilon) - op.updateAttribute("scale_after_normalization", scaleAfterNormalization) - op.addInput(t) - op.addInput(tMin) - op.addInput(tMax) - op.addInput(m) - op.addInput(mMin) - op.addInput(mMax) - op.addInput(v) - op.addInput(vMin) - op.addInput(vMax) - op.addInput(beta) - op.addInput(betaMin) - op.addInput(betaMax) - op.addInput(gamma) - op.addInput(gammaMin) - op.addInput(gammaMax) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedBatchNormWithGlobalNormalization", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("variance_epsilon", varianceEpsilon) + op.updateAttribute("scale_after_normalization", scaleAfterNormalization) + op.addInput(t) + op.addInput(tMin) + op.addInput(tMax) + op.addInput(m) + op.addInput(mMin) + op.addInput(mMax) + op.addInput(v) + op.addInput(vMin) + op.addInput(vMax) + op.addInput(beta) + op.addInput(betaMin) + op.addInput(betaMax) + op.addInput(gamma) + op.addInput(gammaMin) + op.addInput(gammaMax) + return op.execute(Int(1), Int(1), Int(1)) } /// Adds Tensor 'bias' to Tensor 'input' for Quantized types. @@ -20697,74 +20680,74 @@ public static func quantizedBatchNormWithGlobalNormalization< /// Broadcasts the values of bias on dimensions 0..N-2 of 'input'. /// /// - Parameters: -/// - bias: A 1D bias Tensor with size matching the last dimension of 'input'. -/// - min_input: The float value that the lowest quantized input value represents. -/// - max_input: The float value that the highest quantized input value represents. -/// - min_bias: The float value that the lowest quantized bias value represents. -/// - max_bias: The float value that the highest quantized bias value represents. +/// - bias: A 1D bias Tensor with size matching the last dimension of 'input'. +/// - min_input: The float value that the lowest quantized input value represents. +/// - max_input: The float value that the highest quantized input value represents. +/// - min_bias: The float value that the lowest quantized bias value represents. +/// - max_bias: The float value that the highest quantized bias value represents. /// /// - Outputs: -/// - min_out: The float value that the lowest quantized output value represents. -/// - max_out: The float value that the highest quantized output value represents. +/// - min_out: The float value that the lowest quantized output value represents. +/// - max_out: The float value that the highest quantized output value represents. @inlinable @inline(__always) public static func quantizedBiasAdd< T1: TensorFlowScalar, T2: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - bias: Tensor, - minInput: Tensor, - maxInput: Tensor, - minBias: Tensor, - maxBias: Tensor + _ input: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minBias: Tensor, + maxBias: Tensor ) -> (output: Tensor, minOut: Tensor, maxOut: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedBiasAdd", nOutputs) - op.updateAttribute("T1", T1.tensorFlowDataType) - op.updateAttribute("T2", T2.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(input) - op.addInput(bias) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minBias) - op.addInput(maxBias) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedBiasAdd", nOutputs) + op.updateAttribute("T1", T1.tensorFlowDataType) + op.updateAttribute("T2", T2.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minBias) + op.addInput(maxBias) + return op.execute(Int(1), Int(1), Int(1)) } /// Concatenates quantized tensors along one dimension. /// /// - Parameters: -/// - concat_dim: 0-D. The dimension along which to concatenate. Must be in the -/// range [0, rank(values)). -/// - values: The `N` Tensors to concatenate. Their ranks and types must match, -/// and their sizes must match in all dimensions except `concat_dim`. -/// - input_mins: The minimum scalar values for each of the input tensors. -/// - input_maxes: The maximum scalar values for each of the input tensors. +/// - concat_dim: 0-D. The dimension along which to concatenate. Must be in the +/// range [0, rank(values)). +/// - values: The `N` Tensors to concatenate. Their ranks and types must match, +/// and their sizes must match in all dimensions except `concat_dim`. +/// - input_mins: The minimum scalar values for each of the input tensors. +/// - input_maxes: The maximum scalar values for each of the input tensors. /// /// - Outputs: -/// - output: A `Tensor` with the concatenation of values stacked along the -/// `concat_dim` dimension. This tensor's shape matches that of `values` except -/// in `concat_dim` where it has the sum of the sizes. -/// - output_min: The float value that the minimum quantized output value represents. -/// - output_max: The float value that the maximum quantized output value represents. +/// - output: A `Tensor` with the concatenation of values stacked along the +/// `concat_dim` dimension. This tensor's shape matches that of `values` except +/// in `concat_dim` where it has the sum of the sizes. +/// - output_min: The float value that the minimum quantized output value represents. +/// - output_max: The float value that the maximum quantized output value represents. @inlinable @inline(__always) public static func quantizedConcat( - concatDim: Tensor, - _ values: [Tensor], - inputMins: [Tensor], - inputMaxes: [Tensor] + concatDim: Tensor, + _ values: [Tensor], + inputMins: [Tensor], + inputMaxes: [Tensor] ) -> (output: Tensor, outputMin: Tensor, outputMax: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedConcat", nOutputs) - op.updateAttribute("N", values.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(concatDim) - op.addInputList(values) - op.addInputList(inputMins) - op.addInputList(inputMaxes) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedConcat", nOutputs) + op.updateAttribute("N", values.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(concatDim) + op.addInputList(values) + op.addInputList(inputMins) + op.addInputList(inputMaxes) + return op.execute(Int(1), Int(1), Int(1)) } /// Computes a 2D convolution given quantized 4D input and filter tensors. @@ -20775,56 +20758,56 @@ public static func quantizedConcat( /// taking the returned minimum and maximum values into account. /// /// - Parameters: -/// - filter: filter's input_depth dimension must match input's depth dimensions. -/// - min_input: The float value that the lowest quantized input value represents. -/// - max_input: The float value that the highest quantized input value represents. -/// - min_filter: The float value that the lowest quantized filter value represents. -/// - max_filter: The float value that the highest quantized filter value represents. +/// - filter: filter's input_depth dimension must match input's depth dimensions. +/// - min_input: The float value that the lowest quantized input value represents. +/// - max_input: The float value that the highest quantized input value represents. +/// - min_filter: The float value that the lowest quantized filter value represents. +/// - max_filter: The float value that the highest quantized filter value represents. /// /// - Attrs: -/// - strides: The stride of the sliding window for each dimension of the input -/// tensor. -/// - padding: The type of padding algorithm to use. -/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of -/// `input`. If set to k > 1, there will be k-1 skipped cells between each -/// filter element on that dimension. The dimension order is determined by the -/// value of `data_format`, see above for details. Dilations in the batch and -/// depth dimensions must be 1. +/// - strides: The stride of the sliding window for each dimension of the input +/// tensor. +/// - padding: The type of padding algorithm to use. +/// - dilations: 1-D tensor of length 4. The dilation factor for each dimension of +/// `input`. If set to k > 1, there will be k-1 skipped cells between each +/// filter element on that dimension. The dimension order is determined by the +/// value of `data_format`, see above for details. Dilations in the batch and +/// depth dimensions must be 1. /// /// - Outputs: -/// - min_output: The float value that the lowest quantized output value represents. -/// - max_output: The float value that the highest quantized output value represents. +/// - min_output: The float value that the lowest quantized output value represents. +/// - max_output: The float value that the highest quantized output value represents. @inlinable @inline(__always) public static func quantizedConv2D< Tinput: TensorFlowScalar, Tfilter: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1] + _ input: Tensor, + filter: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedConv2D", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filter) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedConv2D", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) } @inlinable @inline(__always) @@ -20833,33 +20816,33 @@ public static func quantizedConv2DAndRelu< Tfilter: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1], - paddingList: [Int32] + _ input: Tensor, + filter: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedConv2DAndRelu", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.updateAttribute("padding_list", paddingList) - op.addInput(input) - op.addInput(filter) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedConv2DAndRelu", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) } @inlinable @inline(__always) @@ -20868,37 +20851,37 @@ public static func quantizedConv2DAndReluAndRequantize< Tfilter: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - minFreezedOutput: Tensor, - maxFreezedOutput: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1], - paddingList: [Int32] + _ input: Tensor, + filter: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedConv2DAndReluAndRequantize", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.updateAttribute("padding_list", paddingList) - op.addInput(input) - op.addInput(filter) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - op.addInput(minFreezedOutput) - op.addInput(maxFreezedOutput) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedConv2DAndReluAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + return op.execute(Int(1), Int(1), Int(1)) } @inlinable @inline(__always) @@ -20907,91 +20890,91 @@ public static func quantizedConv2DAndRequantize< Tfilter: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - minFreezedOutput: Tensor, - maxFreezedOutput: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1], - paddingList: [Int32] + _ input: Tensor, + filter: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedConv2DAndRequantize", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.updateAttribute("padding_list", paddingList) - op.addInput(input) - op.addInput(filter) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - op.addInput(minFreezedOutput) - op.addInput(maxFreezedOutput) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedConv2DAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + return op.execute(Int(1), Int(1), Int(1)) } /// Computes QuantizedConv2D per channel. /// /// - Parameters: -/// - input: The original input tensor. -/// - filter: The original filter tensor. -/// - min_input: The minimum value of the input tensor -/// - max_input: The maximum value of the input tensor. -/// - min_filter: The minimum value of the filter tensor. -/// - max_filter: The maximum value of the filter tensor. +/// - input: The original input tensor. +/// - filter: The original filter tensor. +/// - min_input: The minimum value of the input tensor +/// - max_input: The maximum value of the input tensor. +/// - min_filter: The minimum value of the filter tensor. +/// - max_filter: The maximum value of the filter tensor. /// /// - Attrs: -/// - Tinput: The quantized type of input tensor that needs to be converted. -/// - Tfilter: The quantized type of filter tensor that needs to be converted. -/// - out_type: The quantized type of output tensor that needs to be converted. -/// - strides: list of stride values. -/// - dilations: list of dilation values. +/// - Tinput: The quantized type of input tensor that needs to be converted. +/// - Tfilter: The quantized type of filter tensor that needs to be converted. +/// - out_type: The quantized type of output tensor that needs to be converted. +/// - strides: list of stride values. +/// - dilations: list of dilation values. /// /// - Outputs: -/// - output: The output tensor. -/// - min_output: The minimum value of the final output tensor. -/// - max_output: The maximum value of the final output tensor. +/// - output: The output tensor. +/// - min_output: The minimum value of the final output tensor. +/// - max_output: The maximum value of the final output tensor. @inlinable @inline(__always) public static func quantizedConv2DPerChannel< Tinput: TensorFlowScalar, Tfilter: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1] + _ input: Tensor, + filter: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedConv2DPerChannel", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filter) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedConv2DPerChannel", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) } @inlinable @inline(__always) @@ -21000,35 +20983,35 @@ public static func quantizedConv2DWithBias< Tfilter: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - bias: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1], - paddingList: [Int32] + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedConv2DWithBias", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.updateAttribute("padding_list", paddingList) - op.addInput(input) - op.addInput(filter) - op.addInput(bias) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedConv2DWithBias", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) } @inlinable @inline(__always) @@ -21037,35 +21020,35 @@ public static func quantizedConv2DWithBiasAndRelu< Tfilter: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - bias: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1], - paddingList: [Int32] + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedConv2DWithBiasAndRelu", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.updateAttribute("padding_list", paddingList) - op.addInput(input) - op.addInput(filter) - op.addInput(bias) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedConv2DWithBiasAndRelu", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) } @inlinable @inline(__always) @@ -21075,40 +21058,40 @@ public static func quantizedConv2DWithBiasAndReluAndRequantize< Tbias: FloatingPoint & TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - bias: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - minFreezedOutput: Tensor, - maxFreezedOutput: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1], - paddingList: [Int32] + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedConv2DWithBiasAndReluAndRequantize", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("Tbias", Tbias.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.updateAttribute("padding_list", paddingList) - op.addInput(input) - op.addInput(filter) - op.addInput(bias) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - op.addInput(minFreezedOutput) - op.addInput(maxFreezedOutput) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedConv2DWithBiasAndReluAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("Tbias", Tbias.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + return op.execute(Int(1), Int(1), Int(1)) } @inlinable @inline(__always) @@ -21118,40 +21101,40 @@ public static func quantizedConv2DWithBiasAndRequantize< Tbias: FloatingPoint & TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - bias: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - minFreezedOutput: Tensor, - maxFreezedOutput: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1], - paddingList: [Int32] + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedConv2DWithBiasAndRequantize", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("Tbias", Tbias.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.updateAttribute("padding_list", paddingList) - op.addInput(input) - op.addInput(filter) - op.addInput(bias) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - op.addInput(minFreezedOutput) - op.addInput(maxFreezedOutput) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedConv2DWithBiasAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("Tbias", Tbias.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + return op.execute(Int(1), Int(1), Int(1)) } @inlinable @inline(__always) @@ -21162,47 +21145,47 @@ public static func quantizedConv2DWithBiasSignedSumAndReluAndRequantize< Tsummand: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - bias: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - minFreezedOutput: Tensor, - maxFreezedOutput: Tensor, - summand: Tensor, - minSummand: Tensor, - maxSummand: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1], - paddingList: [Int32] + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + summand: Tensor, + minSummand: Tensor, + maxSummand: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedConv2DWithBiasSignedSumAndReluAndRequantize", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("Tbias", Tbias.tensorFlowDataType) - op.updateAttribute("Tsummand", Tsummand.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.updateAttribute("padding_list", paddingList) - op.addInput(input) - op.addInput(filter) - op.addInput(bias) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - op.addInput(minFreezedOutput) - op.addInput(maxFreezedOutput) - op.addInput(summand) - op.addInput(minSummand) - op.addInput(maxSummand) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedConv2DWithBiasSignedSumAndReluAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("Tbias", Tbias.tensorFlowDataType) + op.updateAttribute("Tsummand", Tsummand.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + op.addInput(summand) + op.addInput(minSummand) + op.addInput(maxSummand) + return op.execute(Int(1), Int(1), Int(1)) } @inlinable @inline(__always) @@ -21211,37 +21194,37 @@ public static func quantizedConv2DWithBiasSumAndRelu< Tfilter: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - bias: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - summand: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1], - paddingList: [Int32] + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + summand: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedConv2DWithBiasSumAndRelu", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.updateAttribute("padding_list", paddingList) - op.addInput(input) - op.addInput(filter) - op.addInput(bias) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - op.addInput(summand) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedConv2DWithBiasSumAndRelu", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(summand) + return op.execute(Int(1), Int(1), Int(1)) } @inlinable @inline(__always) @@ -21252,242 +21235,152 @@ public static func quantizedConv2DWithBiasSumAndReluAndRequantize< Tsummand: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - bias: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - minFreezedOutput: Tensor, - maxFreezedOutput: Tensor, - summand: Tensor, - minSummand: Tensor, - maxSummand: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1], - paddingList: [Int32] + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + summand: Tensor, + minSummand: Tensor, + maxSummand: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1], + paddingList: [Int32] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedConv2DWithBiasSumAndReluAndRequantize", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("Tbias", Tbias.tensorFlowDataType) - op.updateAttribute("Tsummand", Tsummand.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.updateAttribute("padding_list", paddingList) - op.addInput(input) - op.addInput(filter) - op.addInput(bias) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - op.addInput(minFreezedOutput) - op.addInput(maxFreezedOutput) - op.addInput(summand) - op.addInput(minSummand) - op.addInput(maxSummand) - return op.execute(Int(1), Int(1), Int(1)) -} - -/// Computes quantized depthwise Conv2D. -/// -/// - Parameters: -/// - input: The original input tensor. -/// - filter: The original filter tensor. -/// - min_input: The float value that the minimum quantized input value represents. -/// - max_input: The float value that the maximum quantized input value represents. -/// - min_filter: The float value that the minimum quantized filter value represents. -/// - max_filter: The float value that the maximum quantized filter value represents. -/// -/// - Attrs: -/// - Tinput: The type of the input. -/// - Tfilter: The type of the filter. -/// - out_type: The type of the output. -/// - strides: List of stride values. -/// - dilations: List of dilation values. -/// -/// - Outputs: -/// - output: The output tensor. -/// - min_output: The float value that the minimum quantized output value represents. -/// - max_output: The float value that the maximum quantized output value represents. + let op = makeOp("QuantizedConv2DWithBiasSumAndReluAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("Tbias", Tbias.tensorFlowDataType) + op.updateAttribute("Tsummand", Tsummand.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.updateAttribute("padding_list", paddingList) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + op.addInput(summand) + op.addInput(minSummand) + op.addInput(maxSummand) + return op.execute(Int(1), Int(1), Int(1)) +} + @inlinable @inline(__always) public static func quantizedDepthwiseConv2D< Tinput: TensorFlowScalar, Tfilter: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1] + _ input: Tensor, + filter: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedDepthwiseConv2D", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filter) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - return op.execute(Int(1), Int(1), Int(1)) -} - -/// Computes quantized depthwise Conv2D with Bias. -/// -/// - Parameters: -/// - input: The original input tensor. -/// - filter: The original filter tensor. -/// - bias: The original bias tensor. -/// - min_input: The float value that the minimum quantized input value represents. -/// - max_input: The float value that the maximum quantized input value represents. -/// - min_filter: The float value that the minimum quantized filter value represents. -/// - max_filter: The float value that the maximum quantized filter value represents. -/// -/// - Attrs: -/// - Tinput: The type of the input. -/// - Tfilter: The type of the filter. -/// - out_type: The type of the output. -/// - strides: List of stride values. -/// - dilations: List of dilation values. -/// -/// - Outputs: -/// - output: The output tensor. -/// - min_output: The float value that the minimum quantized output value represents. -/// - max_output: The float value that the maximum quantized output value represents. + let op = makeOp("QuantizedDepthwiseConv2D", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) +} + @inlinable @inline(__always) public static func quantizedDepthwiseConv2DWithBias< Tinput: TensorFlowScalar, Tfilter: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - bias: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1] + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedDepthwiseConv2DWithBias", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filter) - op.addInput(bias) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - return op.execute(Int(1), Int(1), Int(1)) -} - -/// Computes quantized depthwise Conv2D with Bias and Relu. -/// -/// - Parameters: -/// - input: The original input tensor. -/// - filter: The original filter tensor. -/// - bias: The original bias tensor. -/// - min_input: The float value that the minimum quantized input value represents. -/// - max_input: The float value that the maximum quantized input value represents. -/// - min_filter: The float value that the minimum quantized filter value represents. -/// - max_filter: The float value that the maximum quantized filter value represents. -/// -/// - Attrs: -/// - Tinput: The type of the input. -/// - Tfilter: The type of the filter. -/// - out_type: The type of the output. -/// - strides: List of stride values. -/// - dilations: List of dilation values. -/// -/// - Outputs: -/// - output: The output tensor. -/// - min_output: The float value that the minimum quantized output value represents. -/// - max_output: The float value that the maximum quantized output value represents. + let op = makeOp("QuantizedDepthwiseConv2DWithBias", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) +} + @inlinable @inline(__always) public static func quantizedDepthwiseConv2DWithBiasAndRelu< Tinput: TensorFlowScalar, Tfilter: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - bias: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1] + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedDepthwiseConv2DWithBiasAndRelu", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filter) - op.addInput(bias) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - return op.execute(Int(1), Int(1), Int(1)) -} - -/// Computes quantized depthwise Conv2D with Bias, Relu and Requantize. -/// -/// - Parameters: -/// - input: The original input tensor. -/// - filter: The original filter tensor. -/// - bias: The original bias tensor. -/// - min_input: The float value that the minimum quantized input value represents. -/// - max_input: The float value that the maximum quantized input value represents. -/// - min_filter: The float value that the minimum quantized filter value represents. -/// - max_filter: The float value that the maximum quantized filter value represents. -/// - min_freezed_output: The minimum float value of the output tensor. -/// - max_freezed_output: The maximum float value of the output tensor. -/// -/// - Attrs: -/// - Tinput: The type of the input. -/// - Tfilter: The type of the filter. -/// - Tbias: The type of the bias. -/// - out_type: The type of the output. -/// - strides: List of stride values. -/// - dilations: List of dilation values. -/// -/// - Outputs: -/// - output: The output tensor. -/// - min_output: The float value that the minimum quantized output value represents. -/// - max_output: The float value that the maximum quantized output value represents. + let op = makeOp("QuantizedDepthwiseConv2DWithBiasAndRelu", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + return op.execute(Int(1), Int(1), Int(1)) +} + @inlinable @inline(__always) public static func quantizedDepthwiseConv2DWithBiasAndReluAndRequantize< Tinput: TensorFlowScalar, @@ -21495,83 +21388,83 @@ public static func quantizedDepthwiseConv2DWithBiasAndReluAndRequantize< Tbias: FloatingPoint & TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - filter: Tensor, - bias: Tensor, - minInput: Tensor, - maxInput: Tensor, - minFilter: Tensor, - maxFilter: Tensor, - minFreezedOutput: Tensor, - maxFreezedOutput: Tensor, - strides: [Int32], - padding: Padding, - dilations: [Int32] = [1, 1, 1, 1] + _ input: Tensor, + filter: Tensor, + bias: Tensor, + minInput: Tensor, + maxInput: Tensor, + minFilter: Tensor, + maxFilter: Tensor, + minFreezedOutput: Tensor, + maxFreezedOutput: Tensor, + strides: [Int32], + padding: Padding, + dilations: [Int32] = [1, 1, 1, 1] ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) - op.updateAttribute("Tbias", Tbias.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.updateAttribute("dilations", dilations) - op.addInput(input) - op.addInput(filter) - op.addInput(bias) - op.addInput(minInput) - op.addInput(maxInput) - op.addInput(minFilter) - op.addInput(maxFilter) - op.addInput(minFreezedOutput) - op.addInput(maxFreezedOutput) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("Tfilter", Tfilter.tensorFlowDataType) + op.updateAttribute("Tbias", Tbias.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.updateAttribute("dilations", dilations) + op.addInput(input) + op.addInput(filter) + op.addInput(bias) + op.addInput(minInput) + op.addInput(maxInput) + op.addInput(minFilter) + op.addInput(maxFilter) + op.addInput(minFreezedOutput) + op.addInput(maxFreezedOutput) + return op.execute(Int(1), Int(1), Int(1)) } /// Quantized Instance normalization. /// /// - Parameters: -/// - x: A 4D input Tensor. -/// - x_min: The value represented by the lowest quantized input. -/// - x_max: The value represented by the highest quantized input. +/// - x: A 4D input Tensor. +/// - x_min: The value represented by the lowest quantized input. +/// - x_max: The value represented by the highest quantized input. /// /// - Attrs: -/// - output_range_given: If True, `given_y_min` and `given_y_min` -/// and `given_y_max` are used as the output range. Otherwise, -/// the implementation computes the output range. -/// - given_y_min: Output in `y_min` if `output_range_given` is True. -/// - given_y_max: Output in `y_max` if `output_range_given` is True. -/// - variance_epsilon: A small float number to avoid dividing by 0. -/// - min_separation: Minimum value of `y_max - y_min` +/// - output_range_given: If True, `given_y_min` and `given_y_min` +/// and `given_y_max` are used as the output range. Otherwise, +/// the implementation computes the output range. +/// - given_y_min: Output in `y_min` if `output_range_given` is True. +/// - given_y_max: Output in `y_max` if `output_range_given` is True. +/// - variance_epsilon: A small float number to avoid dividing by 0. +/// - min_separation: Minimum value of `y_max - y_min` /// /// - Outputs: -/// - y: A 4D Tensor. -/// - y_min: The value represented by the lowest quantized output. -/// - y_max: The value represented by the highest quantized output. +/// - y: A 4D Tensor. +/// - y_min: The value represented by the lowest quantized output. +/// - y_max: The value represented by the highest quantized output. @inlinable @inline(__always) public static func quantizedInstanceNorm( - _ x: Tensor, - xMin: Tensor, - xMax: Tensor, - outputRangeGiven: Bool = false, - givenYMin: Double = 0, - givenYMax: Double = 0, - varianceEpsilon: Double = 1e-05, - minSeparation: Double = 0.001 + _ x: Tensor, + xMin: Tensor, + xMax: Tensor, + outputRangeGiven: Bool = false, + givenYMin: Double = 0, + givenYMax: Double = 0, + varianceEpsilon: Double = 1e-05, + minSeparation: Double = 0.001 ) -> (y: Tensor, yMin: Tensor, yMax: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedInstanceNorm", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("output_range_given", outputRangeGiven) - op.updateAttribute("given_y_min", givenYMin) - op.updateAttribute("given_y_max", givenYMax) - op.updateAttribute("variance_epsilon", varianceEpsilon) - op.updateAttribute("min_separation", minSeparation) - op.addInput(x) - op.addInput(xMin) - op.addInput(xMax) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedInstanceNorm", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("output_range_given", outputRangeGiven) + op.updateAttribute("given_y_min", givenYMin) + op.updateAttribute("given_y_max", givenYMax) + op.updateAttribute("variance_epsilon", varianceEpsilon) + op.updateAttribute("min_separation", minSeparation) + op.addInput(x) + op.addInput(xMin) + op.addInput(xMax) + return op.execute(Int(1), Int(1), Int(1)) } /// Perform a quantized matrix multiplication of `a` by the matrix `b`. @@ -21582,221 +21475,221 @@ public static func quantizedInstanceNorm( /// non-zero). /// /// - Parameters: -/// - a: Must be a two-dimensional tensor. -/// - b: Must be a two-dimensional tensor. -/// - min_a: The float value that the lowest quantized `a` value represents. -/// - max_a: The float value that the highest quantized `a` value represents. -/// - min_b: The float value that the lowest quantized `b` value represents. -/// - max_b: The float value that the highest quantized `b` value represents. +/// - a: Must be a two-dimensional tensor. +/// - b: Must be a two-dimensional tensor. +/// - min_a: The float value that the lowest quantized `a` value represents. +/// - max_a: The float value that the highest quantized `a` value represents. +/// - min_b: The float value that the lowest quantized `b` value represents. +/// - max_b: The float value that the highest quantized `b` value represents. /// /// - Attrs: -/// - transpose_a: If true, `a` is transposed before multiplication. -/// - transpose_b: If true, `b` is transposed before multiplication. -/// - Tactivation: The type of output produced by activation function -/// following this operation. +/// - transpose_a: If true, `a` is transposed before multiplication. +/// - transpose_b: If true, `b` is transposed before multiplication. +/// - Tactivation: The type of output produced by activation function +/// following this operation. /// /// - Outputs: -/// - min_out: The float value that the lowest quantized output value represents. -/// - max_out: The float value that the highest quantized output value represents. +/// - min_out: The float value that the lowest quantized output value represents. +/// - max_out: The float value that the highest quantized output value represents. @inlinable @inline(__always) public static func quantizedMatMul< T1: TensorFlowScalar, T2: TensorFlowScalar, Toutput: TensorFlowScalar >( - _ a: Tensor, - _ b: Tensor, - minA: Tensor, - maxA: Tensor, - minB: Tensor, - maxB: Tensor, - transposeA: Bool = false, - transposeB: Bool = false, - tactivation: TensorDataType + _ a: Tensor, + _ b: Tensor, + minA: Tensor, + maxA: Tensor, + minB: Tensor, + maxB: Tensor, + transposeA: Bool = false, + transposeB: Bool = false, + tactivation: TensorDataType ) -> (out: Tensor, minOut: Tensor, maxOut: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedMatMul", nOutputs) - op.updateAttribute("T1", T1.tensorFlowDataType) - op.updateAttribute("T2", T2.tensorFlowDataType) - op.updateAttribute("Toutput", Toutput.tensorFlowDataType) - op.updateAttribute("transpose_a", transposeA) - op.updateAttribute("transpose_b", transposeB) - op.updateAttribute("Tactivation", tactivation) - op.addInput(a) - op.addInput(b) - op.addInput(minA) - op.addInput(maxA) - op.addInput(minB) - op.addInput(maxB) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedMatMul", nOutputs) + op.updateAttribute("T1", T1.tensorFlowDataType) + op.updateAttribute("T2", T2.tensorFlowDataType) + op.updateAttribute("Toutput", Toutput.tensorFlowDataType) + op.updateAttribute("transpose_a", transposeA) + op.updateAttribute("transpose_b", transposeB) + op.updateAttribute("Tactivation", tactivation) + op.addInput(a) + op.addInput(b) + op.addInput(minA) + op.addInput(maxA) + op.addInput(minB) + op.addInput(maxB) + return op.execute(Int(1), Int(1), Int(1)) } /// Produces the max pool of the input tensor for quantized types. /// /// - Parameters: -/// - input: The 4D (batch x rows x cols x depth) Tensor to MaxReduce over. -/// - min_input: The float value that the lowest quantized input value represents. -/// - max_input: The float value that the highest quantized input value represents. +/// - input: The 4D (batch x rows x cols x depth) Tensor to MaxReduce over. +/// - min_input: The float value that the lowest quantized input value represents. +/// - max_input: The float value that the highest quantized input value represents. /// /// - Attrs: -/// - ksize: The size of the window for each dimension of the input tensor. -/// The length must be 4 to match the number of dimensions of the input. -/// - strides: The stride of the sliding window for each dimension of the input -/// tensor. The length must be 4 to match the number of dimensions of the input. -/// - padding: The type of padding algorithm to use. +/// - ksize: The size of the window for each dimension of the input tensor. +/// The length must be 4 to match the number of dimensions of the input. +/// - strides: The stride of the sliding window for each dimension of the input +/// tensor. The length must be 4 to match the number of dimensions of the input. +/// - padding: The type of padding algorithm to use. /// /// - Outputs: -/// - min_output: The float value that the lowest quantized output value represents. -/// - max_output: The float value that the highest quantized output value represents. +/// - min_output: The float value that the lowest quantized output value represents. +/// - max_output: The float value that the highest quantized output value represents. @inlinable @inline(__always) public static func quantizedMaxPool( - _ input: Tensor, - minInput: Tensor, - maxInput: Tensor, - ksize: [Int32], - strides: [Int32], - padding: Padding + _ input: Tensor, + minInput: Tensor, + maxInput: Tensor, + ksize: [Int32], + strides: [Int32], + padding: Padding ) -> (output: Tensor, minOutput: Tensor, maxOutput: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedMaxPool", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("ksize", ksize) - op.updateAttribute("strides", strides) - op.updateAttribute("padding", padding.cName) - op.addInput(input) - op.addInput(minInput) - op.addInput(maxInput) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedMaxPool", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("ksize", ksize) + op.updateAttribute("strides", strides) + op.updateAttribute("padding", padding.cName) + op.addInput(input) + op.addInput(minInput) + op.addInput(maxInput) + return op.execute(Int(1), Int(1), Int(1)) } /// Returns x * y element-wise, working on quantized buffers. /// /// - Parameters: -/// - min_x: The float value that the lowest quantized `x` value represents. -/// - max_x: The float value that the highest quantized `x` value represents. -/// - min_y: The float value that the lowest quantized `y` value represents. -/// - max_y: The float value that the highest quantized `y` value represents. +/// - min_x: The float value that the lowest quantized `x` value represents. +/// - max_x: The float value that the highest quantized `x` value represents. +/// - min_y: The float value that the lowest quantized `y` value represents. +/// - max_y: The float value that the highest quantized `y` value represents. /// /// - Outputs: -/// - min_z: The float value that the lowest quantized output value represents. -/// - max_z: The float value that the highest quantized output value represents. +/// - min_z: The float value that the lowest quantized output value represents. +/// - max_z: The float value that the highest quantized output value represents. /// -/// *NOTE*: `QuantizedMul` supports limited forms of broadcasting. More about -/// broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) +/// *NOTE*: `QuantizedMul` supports limited forms of broadcasting. More about +/// broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func quantizedMul< T1: TensorFlowScalar, T2: TensorFlowScalar, Toutput: TensorFlowScalar >( - _ x: Tensor, - _ y: Tensor, - minX: Tensor, - maxX: Tensor, - minY: Tensor, - maxY: Tensor + _ x: Tensor, + _ y: Tensor, + minX: Tensor, + maxX: Tensor, + minY: Tensor, + maxY: Tensor ) -> (z: Tensor, minZ: Tensor, maxZ: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedMul", nOutputs) - op.updateAttribute("T1", T1.tensorFlowDataType) - op.updateAttribute("T2", T2.tensorFlowDataType) - op.updateAttribute("Toutput", Toutput.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - op.addInput(minX) - op.addInput(maxX) - op.addInput(minY) - op.addInput(maxY) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedMul", nOutputs) + op.updateAttribute("T1", T1.tensorFlowDataType) + op.updateAttribute("T2", T2.tensorFlowDataType) + op.updateAttribute("Toutput", Toutput.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + op.addInput(minX) + op.addInput(maxX) + op.addInput(minY) + op.addInput(maxY) + return op.execute(Int(1), Int(1), Int(1)) } /// Computes Quantized Rectified Linear: `max(features, 0)` /// /// - Parameters: -/// - min_features: The float value that the lowest quantized value represents. -/// - max_features: The float value that the highest quantized value represents. +/// - min_features: The float value that the lowest quantized value represents. +/// - max_features: The float value that the highest quantized value represents. /// /// - Outputs: -/// - activations: Has the same output shape as "features". -/// - min_activations: The float value that the lowest quantized value represents. -/// - max_activations: The float value that the highest quantized value represents. +/// - activations: Has the same output shape as "features". +/// - min_activations: The float value that the lowest quantized value represents. +/// - max_activations: The float value that the highest quantized value represents. @inlinable @inline(__always) public static func quantizedRelu< Tinput: TensorFlowScalar, OutType: TensorFlowScalar >( - features: Tensor, - minFeatures: Tensor, - maxFeatures: Tensor + features: Tensor, + minFeatures: Tensor, + maxFeatures: Tensor ) -> (activations: Tensor, minActivations: Tensor, maxActivations: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedRelu", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(features) - op.addInput(minFeatures) - op.addInput(maxFeatures) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedRelu", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(features) + op.addInput(minFeatures) + op.addInput(maxFeatures) + return op.execute(Int(1), Int(1), Int(1)) } /// Computes Quantized Rectified Linear 6: `min(max(features, 0), 6)` /// /// - Parameters: -/// - min_features: The float value that the lowest quantized value represents. -/// - max_features: The float value that the highest quantized value represents. +/// - min_features: The float value that the lowest quantized value represents. +/// - max_features: The float value that the highest quantized value represents. /// /// - Outputs: -/// - activations: Has the same output shape as "features". -/// - min_activations: The float value that the lowest quantized value represents. -/// - max_activations: The float value that the highest quantized value represents. +/// - activations: Has the same output shape as "features". +/// - min_activations: The float value that the lowest quantized value represents. +/// - max_activations: The float value that the highest quantized value represents. @inlinable @inline(__always) public static func quantizedRelu6< Tinput: TensorFlowScalar, OutType: TensorFlowScalar >( - features: Tensor, - minFeatures: Tensor, - maxFeatures: Tensor + features: Tensor, + minFeatures: Tensor, + maxFeatures: Tensor ) -> (activations: Tensor, minActivations: Tensor, maxActivations: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedRelu6", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(features) - op.addInput(minFeatures) - op.addInput(maxFeatures) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedRelu6", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(features) + op.addInput(minFeatures) + op.addInput(maxFeatures) + return op.execute(Int(1), Int(1), Int(1)) } /// Computes Quantized Rectified Linear X: `min(max(features, 0), max_value)` /// /// - Parameters: -/// - min_features: The float value that the lowest quantized value represents. -/// - max_features: The float value that the highest quantized value represents. +/// - min_features: The float value that the lowest quantized value represents. +/// - max_features: The float value that the highest quantized value represents. /// /// - Outputs: -/// - activations: Has the same output shape as "features". -/// - min_activations: The float value that the lowest quantized value represents. -/// - max_activations: The float value that the highest quantized value represents. +/// - activations: Has the same output shape as "features". +/// - min_activations: The float value that the lowest quantized value represents. +/// - max_activations: The float value that the highest quantized value represents. @inlinable @inline(__always) public static func quantizedReluX< Tinput: TensorFlowScalar, OutType: TensorFlowScalar >( - features: Tensor, - maxValue: Tensor, - minFeatures: Tensor, - maxFeatures: Tensor + features: Tensor, + maxValue: Tensor, + minFeatures: Tensor, + maxFeatures: Tensor ) -> (activations: Tensor, minActivations: Tensor, maxActivations: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedReluX", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(features) - op.addInput(maxValue) - op.addInput(minFeatures) - op.addInput(maxFeatures) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedReluX", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(features) + op.addInput(maxValue) + op.addInput(minFeatures) + op.addInput(maxFeatures) + return op.execute(Int(1), Int(1), Int(1)) } /// Reshapes a quantized tensor as per the Reshape op. @@ -21804,32 +21697,32 @@ public static func quantizedReluX< /// ``` /// /// - Parameters: -/// - shape: Defines the shape of the output tensor. -/// - input_min: The minimum value of the input. -/// - input_max: The maximum value of the input. +/// - shape: Defines the shape of the output tensor. +/// - input_min: The minimum value of the input. +/// - input_max: The maximum value of the input. /// /// - Outputs: -/// - output_min: This value is copied from input_min. -/// - output_max: This value is copied from input_max. +/// - output_min: This value is copied from input_min. +/// - output_max: This value is copied from input_max. @inlinable @inline(__always) public static func quantizedReshape< T: TensorFlowScalar, Tshape: BinaryInteger & TensorFlowScalar >( - _ tensor: Tensor, - shape: Tensor, - inputMin: Tensor, - inputMax: Tensor + _ tensor: Tensor, + shape: Tensor, + inputMin: Tensor, + inputMax: Tensor ) -> (output: Tensor, outputMin: Tensor, outputMax: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedReshape", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tshape", Tshape.tensorFlowDataType) - op.addInput(tensor) - op.addInput(shape) - op.addInput(inputMin) - op.addInput(inputMax) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedReshape", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tshape", Tshape.tensorFlowDataType) + op.addInput(tensor) + op.addInput(shape) + op.addInput(inputMin) + op.addInput(inputMax) + return op.execute(Int(1), Int(1), Int(1)) } /// Resize quantized `images` to `size` using quantized bilinear interpolation. @@ -21837,34 +21730,34 @@ public static func quantizedReshape< /// Input images and output images must be quantized types. /// /// - Parameters: -/// - images: 4-D with shape `[batch, height, width, channels]`. -/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The -/// new size for the images. +/// - images: 4-D with shape `[batch, height, width, channels]`. +/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The +/// new size for the images. /// /// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and output tensors are -/// aligned, preserving the values at the corner pixels. Defaults to false. +/// aligned, preserving the values at the corner pixels. Defaults to false. /// /// - Output resized_images: 4-D with shape -/// `[batch, new_height, new_width, channels]`. +/// `[batch, new_height, new_width, channels]`. @inlinable @inline(__always) public static func quantizedResizeBilinear( - images: Tensor, - size: Tensor, - min: Tensor, - max: Tensor, - alignCorners: Bool = false, - halfPixelCenters: Bool = false + images: Tensor, + size: Tensor, + min: Tensor, + max: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false ) -> (resizedImages: Tensor, outMin: Tensor, outMax: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("QuantizedResizeBilinear", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("align_corners", alignCorners) - op.updateAttribute("half_pixel_centers", halfPixelCenters) - op.addInput(images) - op.addInput(size) - op.addInput(min) - op.addInput(max) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("QuantizedResizeBilinear", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(images) + op.addInput(size) + op.addInput(min) + op.addInput(max) + return op.execute(Int(1), Int(1), Int(1)) } /// Closes the given queue. @@ -21878,17 +21771,17 @@ public static func quantizedResizeBilinear( /// - Parameter handle: The handle to a queue. /// /// - Attr cancel_pending_enqueues: If true, all pending enqueue requests that are -/// blocked on the given queue will be canceled. +/// blocked on the given queue will be canceled. @inlinable @inline(__always) public static func queueCloseV2( - handle: ResourceHandle, - cancelPendingEnqueues: Bool = false + handle: ResourceHandle, + cancelPendingEnqueues: Bool = false ) { let nOutputs = 0 - let op = makeOp("QueueCloseV2", nOutputs) - op.updateAttribute("cancel_pending_enqueues", cancelPendingEnqueues) - op.addInput(handle) - op.execute() + let op = makeOp("QueueCloseV2", nOutputs) + op.updateAttribute("cancel_pending_enqueues", cancelPendingEnqueues) + op.addInput(handle) + op.execute() } /// Dequeues `n` tuples of one or more tensors from the given queue. @@ -21908,29 +21801,29 @@ public static func queueCloseV2( /// have been dequeued (or 'timeout_ms' elapses, if specified). /// /// - Parameters: -/// - handle: The handle to a queue. -/// - n: The number of tuples to dequeue. +/// - handle: The handle to a queue. +/// - n: The number of tuples to dequeue. /// /// - Attrs: -/// - component_types: The type of each component in a tuple. -/// - timeout_ms: If the queue has fewer than n elements, this operation -/// will block for up to timeout_ms milliseconds. -/// Note: This option is not supported yet. +/// - component_types: The type of each component in a tuple. +/// - timeout_ms: If the queue has fewer than n elements, this operation +/// will block for up to timeout_ms milliseconds. +/// Note: This option is not supported yet. /// /// - Output components: One or more tensors that were dequeued as a tuple. @inlinable @inline(__always) public static func queueDequeueManyV2( - handle: ResourceHandle, - n: Tensor, - timeoutMs: Int64 = -1 + handle: ResourceHandle, + n: Tensor, + timeoutMs: Int64 = -1 ) -> ComponentTypes { let nOutputs = Int(ComponentTypes._typeList.count) - let op = makeOp("QueueDequeueManyV2", nOutputs) - op.updateAttribute("component_types", ComponentTypes._typeList) - op.updateAttribute("timeout_ms", timeoutMs) - op.addInput(handle) - op.addInput(n) - return op.execute(Int(ComponentTypes._typeList.count)) + let op = makeOp("QueueDequeueManyV2", nOutputs) + op.updateAttribute("component_types", ComponentTypes._typeList) + op.updateAttribute("timeout_ms", timeoutMs) + op.addInput(handle) + op.addInput(n) + return op.execute(Int(ComponentTypes._typeList.count)) } /// Dequeues `n` tuples of one or more tensors from the given queue. @@ -21954,29 +21847,29 @@ public static func queueDequeueManyV2( /// component of the dequeued tuple. /// /// - Parameters: -/// - handle: The handle to a queue. -/// - n: The number of tuples to dequeue. +/// - handle: The handle to a queue. +/// - n: The number of tuples to dequeue. /// /// - Attrs: -/// - component_types: The type of each component in a tuple. -/// - timeout_ms: If the queue has fewer than n elements, this operation -/// will block for up to timeout_ms milliseconds. -/// Note: This option is not supported yet. +/// - component_types: The type of each component in a tuple. +/// - timeout_ms: If the queue has fewer than n elements, this operation +/// will block for up to timeout_ms milliseconds. +/// Note: This option is not supported yet. /// /// - Output components: One or more tensors that were dequeued as a tuple. @inlinable @inline(__always) public static func queueDequeueUpToV2( - handle: ResourceHandle, - n: Tensor, - timeoutMs: Int64 = -1 + handle: ResourceHandle, + n: Tensor, + timeoutMs: Int64 = -1 ) -> ComponentTypes { let nOutputs = Int(ComponentTypes._typeList.count) - let op = makeOp("QueueDequeueUpToV2", nOutputs) - op.updateAttribute("component_types", ComponentTypes._typeList) - op.updateAttribute("timeout_ms", timeoutMs) - op.addInput(handle) - op.addInput(n) - return op.execute(Int(ComponentTypes._typeList.count)) + let op = makeOp("QueueDequeueUpToV2", nOutputs) + op.updateAttribute("component_types", ComponentTypes._typeList) + op.updateAttribute("timeout_ms", timeoutMs) + op.addInput(handle) + op.addInput(n) + return op.execute(Int(ComponentTypes._typeList.count)) } /// Dequeues a tuple of one or more tensors from the given queue. @@ -21991,23 +21884,23 @@ public static func queueDequeueUpToV2( /// - Parameter handle: The handle to a queue. /// /// - Attrs: -/// - component_types: The type of each component in a tuple. -/// - timeout_ms: If the queue is empty, this operation will block for up to -/// timeout_ms milliseconds. -/// Note: This option is not supported yet. +/// - component_types: The type of each component in a tuple. +/// - timeout_ms: If the queue is empty, this operation will block for up to +/// timeout_ms milliseconds. +/// Note: This option is not supported yet. /// /// - Output components: One or more tensors that were dequeued as a tuple. @inlinable @inline(__always) public static func queueDequeueV2( - handle: ResourceHandle, - timeoutMs: Int64 = -1 + handle: ResourceHandle, + timeoutMs: Int64 = -1 ) -> ComponentTypes { let nOutputs = Int(ComponentTypes._typeList.count) - let op = makeOp("QueueDequeueV2", nOutputs) - op.updateAttribute("component_types", ComponentTypes._typeList) - op.updateAttribute("timeout_ms", timeoutMs) - op.addInput(handle) - return op.execute(Int(ComponentTypes._typeList.count)) + let op = makeOp("QueueDequeueV2", nOutputs) + op.updateAttribute("component_types", ComponentTypes._typeList) + op.updateAttribute("timeout_ms", timeoutMs) + op.addInput(handle) + return op.execute(Int(ComponentTypes._typeList.count)) } /// Enqueues zero or more tuples of one or more tensors in the given queue. @@ -22023,26 +21916,26 @@ public static func queueDequeueV2( /// elements have been enqueued (or 'timeout_ms' elapses, if specified). /// /// - Parameters: -/// - handle: The handle to a queue. -/// - components: One or more tensors from which the enqueued tensors should -/// be taken. +/// - handle: The handle to a queue. +/// - components: One or more tensors from which the enqueued tensors should +/// be taken. /// /// - Attr timeout_ms: If the queue is too full, this operation will block for up -/// to timeout_ms milliseconds. -/// Note: This option is not supported yet. +/// to timeout_ms milliseconds. +/// Note: This option is not supported yet. @inlinable @inline(__always) public static func queueEnqueueManyV2( - handle: ResourceHandle, - components: Tcomponents, - timeoutMs: Int64 = -1 + handle: ResourceHandle, + components: Tcomponents, + timeoutMs: Int64 = -1 ) { let nOutputs = 0 - let op = makeOp("QueueEnqueueManyV2", nOutputs) - op.updateAttribute("Tcomponents", components._typeList) - op.updateAttribute("timeout_ms", timeoutMs) - op.addInput(handle) - op.addInputList(components) - op.execute() + let op = makeOp("QueueEnqueueManyV2", nOutputs) + op.updateAttribute("Tcomponents", components._typeList) + op.updateAttribute("timeout_ms", timeoutMs) + op.addInput(handle) + op.addInputList(components) + op.execute() } /// Enqueues a tuple of one or more tensors in the given queue. @@ -22054,25 +21947,25 @@ public static func queueEnqueueManyV2( /// element has been enqueued (or 'timeout_ms' elapses, if specified). /// /// - Parameters: -/// - handle: The handle to a queue. -/// - components: One or more tensors from which the enqueued tensors should be taken. +/// - handle: The handle to a queue. +/// - components: One or more tensors from which the enqueued tensors should be taken. /// /// - Attr timeout_ms: If the queue is full, this operation will block for up to -/// timeout_ms milliseconds. -/// Note: This option is not supported yet. +/// timeout_ms milliseconds. +/// Note: This option is not supported yet. @inlinable @inline(__always) public static func queueEnqueueV2( - handle: ResourceHandle, - components: Tcomponents, - timeoutMs: Int64 = -1 + handle: ResourceHandle, + components: Tcomponents, + timeoutMs: Int64 = -1 ) { let nOutputs = 0 - let op = makeOp("QueueEnqueueV2", nOutputs) - op.updateAttribute("Tcomponents", components._typeList) - op.updateAttribute("timeout_ms", timeoutMs) - op.addInput(handle) - op.addInputList(components) - op.execute() + let op = makeOp("QueueEnqueueV2", nOutputs) + op.updateAttribute("Tcomponents", components._typeList) + op.updateAttribute("timeout_ms", timeoutMs) + op.addInput(handle) + op.addInputList(components) + op.execute() } /// Returns true if queue is closed. @@ -22083,12 +21976,12 @@ public static func queueEnqueueV2( /// - Parameter handle: The handle to a queue. @inlinable @inline(__always) public static func queueIsClosedV2( - handle: ResourceHandle + handle: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("QueueIsClosedV2", nOutputs) - op.addInput(handle) - return op.execute(Int(1)) + let op = makeOp("QueueIsClosedV2", nOutputs) + op.addInput(handle) + return op.execute(Int(1)) } /// Computes the number of elements in the given queue. @@ -22098,12 +21991,12 @@ public static func queueIsClosedV2( /// - Output size: The number of elements in the given queue. @inlinable @inline(__always) public static func queueSizeV2( - handle: ResourceHandle + handle: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("QueueSizeV2", nOutputs) - op.addInput(handle) - return op.execute(Int(1)) + let op = makeOp("QueueSizeV2", nOutputs) + op.addInput(handle) + return op.execute(Int(1)) } /// Converts one or more images from RGB to HSV. @@ -22121,13 +22014,13 @@ public static func queueSizeV2( /// - Output output: `images` converted to HSV. @inlinable @inline(__always) public static func rGBToHSV( - images: Tensor + images: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RGBToHSV", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(images) - return op.execute(Int(1)) + let op = makeOp("RGBToHSV", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(images) + return op.execute(Int(1)) } /// Gather ragged slices from `params` axis `0` according to `indices`. @@ -22157,48 +22050,46 @@ public static func rGBToHSV( /// /// /// - Parameters: -/// - params_nested_splits: The `nested_row_splits` tensors that define the row-partitioning for the -/// `params` RaggedTensor input. -/// - params_dense_values: The `flat_values` for the `params` RaggedTensor. There was a terminology change -/// at the python level from dense_values to flat_values, so dense_values is the -/// deprecated name. -/// - indices: Indices in the outermost dimension of `params` of the values that should be -/// gathered. +/// - params_nested_splits: The `nested_row_splits` tensors that define the row-partitioning for the +/// `params` RaggedTensor input. +/// - params_dense_values: The `flat_values` for the `params` RaggedTensor. There was a terminology change +/// at the python level from dense_values to flat_values, so dense_values is the +/// deprecated name. +/// - indices: Indices in the outermost dimension of `params` of the values that should be +/// gathered. /// /// - Attrs: -/// - PARAMS_RAGGED_RANK: The ragged rank of the `params` RaggedTensor. `params_nested_splits` should -/// contain this number of `row_splits` tensors. This value should equal -/// `params.ragged_rank`. -/// - OUTPUT_RAGGED_RANK: The ragged rank of the output RaggedTensor. `output_nested_splits` will contain -/// this number of `row_splits` tensors. This value should equal -/// `indices.shape.ndims + params.ragged_rank - 1`. +/// - PARAMS_RAGGED_RANK: The ragged rank of the `params` RaggedTensor. `params_nested_splits` should +/// contain this number of `row_splits` tensors. This value should equal +/// `params.ragged_rank`. +/// - OUTPUT_RAGGED_RANK: The ragged rank of the output RaggedTensor. `output_nested_splits` will contain +/// this number of `row_splits` tensors. This value should equal +/// `indices.shape.ndims + params.ragged_rank - 1`. /// /// - Outputs: -/// - output_nested_splits: The `nested_row_splits` tensors that define the row-partitioning for the -/// returned RaggedTensor. -/// - output_dense_values: The `flat_values` for the returned RaggedTensor. +/// - output_nested_splits: The `nested_row_splits` tensors that define the row-partitioning for the +/// returned RaggedTensor. +/// - output_dense_values: The `flat_values` for the returned RaggedTensor. @inlinable @inline(__always) public static func raggedGather< Tvalues: TensorFlowScalar, - Tindices: BinaryInteger & TensorFlowScalar, - Tsplits: BinaryInteger & TensorFlowScalar + Tindices: BinaryInteger & TensorFlowScalar >( - paramsNestedSplits: [Tensor], - paramsDenseValues: Tensor, - indices: Tensor, - oUTPUTRAGGEDRANK: Int64 -) -> (outputNestedSplits: [Tensor], outputDenseValues: Tensor) { + paramsNestedSplits: [Tensor], + paramsDenseValues: Tensor, + indices: Tensor, + oUTPUTRAGGEDRANK: Int64 +) -> (outputNestedSplits: [Tensor], outputDenseValues: Tensor) { let nOutputs = Int(oUTPUTRAGGEDRANK) + Int(1) - let op = makeOp("RaggedGather", nOutputs) - op.updateAttribute("Tvalues", Tvalues.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) - op.updateAttribute("PARAMS_RAGGED_RANK", paramsNestedSplits.count) - op.updateAttribute("OUTPUT_RAGGED_RANK", oUTPUTRAGGEDRANK) - op.addInputList(paramsNestedSplits) - op.addInput(paramsDenseValues) - op.addInput(indices) - return op.execute(Int(oUTPUTRAGGEDRANK), Int(1)) + let op = makeOp("RaggedGather", nOutputs) + op.updateAttribute("Tvalues", Tvalues.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("PARAMS_RAGGED_RANK", paramsNestedSplits.count) + op.updateAttribute("OUTPUT_RAGGED_RANK", oUTPUTRAGGEDRANK) + op.addInputList(paramsNestedSplits) + op.addInput(paramsDenseValues) + op.addInput(indices) + return op.execute(Int(oUTPUTRAGGEDRANK), Int(1)) } /// Returns a `RaggedTensor` containing the specified sequences of numbers. @@ -22223,49 +22114,26 @@ public static func raggedGather< /// to match the size of the vector inputs. /// /// - Parameters: -/// - starts: The starts of each range. -/// - limits: The limits of each range. -/// - deltas: The deltas of each range. +/// - starts: The starts of each range. +/// - limits: The limits of each range. +/// - deltas: The deltas of each range. /// /// - Outputs: -/// - rt_nested_splits: The `row_splits` for the returned `RaggedTensor`. -/// - rt_dense_values: The `flat_values` for the returned `RaggedTensor`. -@inlinable @inline(__always) -public static func raggedRange< - T: Numeric & TensorFlowScalar, - Tsplits: BinaryInteger & TensorFlowScalar ->( - starts: Tensor, - limits: Tensor, - deltas: Tensor -) -> (rtNestedSplits: Tensor, rtDenseValues: Tensor) { +/// - rt_nested_splits: The `row_splits` for the returned `RaggedTensor`. +/// - rt_dense_values: The `flat_values` for the returned `RaggedTensor`. +@inlinable @inline(__always) +public static func raggedRange( + starts: Tensor, + limits: Tensor, + deltas: Tensor +) -> (rtNestedSplits: Tensor, rtDenseValues: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("RaggedRange", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) - op.addInput(starts) - op.addInput(limits) - op.addInput(deltas) - return op.execute(Int(1), Int(1)) -} - -@inlinable @inline(__always) -public static func raggedTensorFromVariant< - Tvalues: TensorFlowScalar, - Tsplits: BinaryInteger & TensorFlowScalar ->( - encodedRagged: VariantHandle, - inputRaggedRank: Int64, - outputRaggedRank: Int64 -) -> (outputNestedSplits: [Tensor], outputDenseValues: Tensor) { - let nOutputs = Int(outputRaggedRank) + Int(1) - let op = makeOp("RaggedTensorFromVariant", nOutputs) - op.updateAttribute("input_ragged_rank", inputRaggedRank) - op.updateAttribute("output_ragged_rank", outputRaggedRank) - op.updateAttribute("Tvalues", Tvalues.tensorFlowDataType) - op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) - op.addInput(encodedRagged) - return op.execute(Int(outputRaggedRank), Int(1)) + let op = makeOp("RaggedRange", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(starts) + op.addInput(limits) + op.addInput(deltas) + return op.execute(Int(1), Int(1)) } /// Converts a `RaggedTensor` into a `SparseTensor` with the same values. @@ -22275,53 +22143,29 @@ public static func raggedTensorFromVariant< /// dense_shape=sparse_dense_shape) /// /// - Parameters: -/// - rt_nested_splits: The `row_splits` for the `RaggedTensor`. -/// - rt_dense_values: The `flat_values` for the `RaggedTensor`. +/// - rt_nested_splits: The `row_splits` for the `RaggedTensor`. +/// - rt_dense_values: The `flat_values` for the `RaggedTensor`. /// /// - Attr RAGGED_RANK: The ragged rank of the input RaggedTensor. `rt_nested_splits` should contain -/// this number of ragged-splits tensors. This value should equal -/// `input.ragged_rank`. +/// this number of ragged-splits tensors. This value should equal +/// `input.ragged_rank`. /// /// - Outputs: -/// - sparse_indices: The indices for the `SparseTensor`. -/// - sparse_values: The values of the `SparseTensor`. -/// - sparse_dense_shape: `sparse_dense_shape` is a tight bounding box of the input `RaggedTensor`. +/// - sparse_indices: The indices for the `SparseTensor`. +/// - sparse_values: The values of the `SparseTensor`. +/// - sparse_dense_shape: `sparse_dense_shape` is a tight bounding box of the input `RaggedTensor`. @inlinable @inline(__always) -public static func raggedTensorToSparse< - T: TensorFlowScalar, - Tsplits: BinaryInteger & TensorFlowScalar ->( - rtNestedSplits: [Tensor], - rtDenseValues: Tensor +public static func raggedTensorToSparse( + rtNestedSplits: [Tensor], + rtDenseValues: Tensor ) -> (sparseIndices: Tensor, sparseValues: Tensor, sparseDenseShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("RaggedTensorToSparse", nOutputs) - op.updateAttribute("RAGGED_RANK", rtNestedSplits.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) - op.addInputList(rtNestedSplits) - op.addInput(rtDenseValues) - return op.execute(Int(1), Int(1), Int(1)) -} - -@inlinable @inline(__always) -public static func raggedTensorToVariant< - Tvalues: TensorFlowScalar, - Tsplits: BinaryInteger & TensorFlowScalar ->( - rtNestedSplits: [Tensor], - rtDenseValues: Tensor, - batchedInput: Bool -) -> VariantHandle { - let nOutputs = Int(1) - let op = makeOp("RaggedTensorToVariant", nOutputs) - op.updateAttribute("RAGGED_RANK", rtNestedSplits.count) - op.updateAttribute("Tvalues", Tvalues.tensorFlowDataType) - op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) - op.updateAttribute("batched_input", batchedInput) - op.addInputList(rtNestedSplits) - op.addInput(rtDenseValues) - return op.execute(Int(1)) + let op = makeOp("RaggedTensorToSparse", nOutputs) + op.updateAttribute("RAGGED_RANK", rtNestedSplits.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInputList(rtNestedSplits) + op.addInput(rtDenseValues) + return op.execute(Int(1), Int(1), Int(1)) } /// Randomly crop `image`. @@ -22334,31 +22178,31 @@ public static func raggedTensorToVariant< /// area will fit inside the original image. /// /// - Parameters: -/// - image: 3-D of shape `[height, width, channels]`. -/// - size: 1-D of length 2 containing: `crop_height`, `crop_width`.. +/// - image: 3-D of shape `[height, width, channels]`. +/// - size: 1-D of length 2 containing: `crop_height`, `crop_width`.. /// /// - Attrs: -/// - seed: If either seed or seed2 are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: An second seed to avoid seed collision. +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. /// /// - Output output: 3-D of shape `[crop_height, crop_width, channels].` @inlinable @inline(__always) public static func randomCrop( - image: Tensor, - size: Tensor, - seed: Int64 = 0, - seed2: Int64 = 0 + image: Tensor, + size: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RandomCrop", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.addInput(image) - op.addInput(size) - return op.execute(Int(1)) + let op = makeOp("RandomCrop", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(image) + op.addInput(size) + return op.execute(Int(1)) } /// Outputs random values from the Gamma distribution(s) described by alpha. @@ -22368,53 +22212,53 @@ public static func randomCrop( /// See http://dl.acm.org/citation.cfm?id=358414 /// /// - Parameters: -/// - shape: 1-D integer tensor. Shape of independent samples to draw from each -/// distribution described by the shape parameters given in alpha. -/// - alpha: A tensor in which each scalar is a "shape" parameter describing the -/// associated gamma distribution. +/// - shape: 1-D integer tensor. Shape of independent samples to draw from each +/// distribution described by the shape parameters given in alpha. +/// - alpha: A tensor in which each scalar is a "shape" parameter describing the +/// associated gamma distribution. /// /// - Attrs: -/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: A second seed to avoid seed collision. +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. /// /// - Output output: A tensor with shape `shape + shape(alpha)`. Each slice -/// `[:, ..., :, i0, i1, ...iN]` contains the samples drawn for -/// `alpha[i0, i1, ...iN]`. The dtype of the output matches the dtype of alpha. +/// `[:, ..., :, i0, i1, ...iN]` contains the samples drawn for +/// `alpha[i0, i1, ...iN]`. The dtype of the output matches the dtype of alpha. @inlinable @inline(__always) public static func randomGamma< S: BinaryInteger & TensorFlowScalar, T: FloatingPoint & TensorFlowScalar >( - shape: Tensor, - alpha: Tensor, - seed: Int64 = 0, - seed2: Int64 = 0 + shape: Tensor, + alpha: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RandomGamma", nOutputs) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("S", S.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(shape) - op.addInput(alpha) - return op.execute(Int(1)) + let op = makeOp("RandomGamma", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("S", S.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(shape) + op.addInput(alpha) + return op.execute(Int(1)) } /// Computes the derivative of a Gamma random sample w.r.t. `alpha`. @inlinable @inline(__always) public static func randomGammaGrad( - alpha: Tensor, - sample: Tensor + alpha: Tensor, + sample: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RandomGammaGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(alpha) - op.addInput(sample) - return op.execute(Int(1)) + let op = makeOp("RandomGammaGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(alpha) + op.addInput(sample) + return op.execute(Int(1)) } /// Use RandomPoissonV2 instead. @@ -22423,20 +22267,20 @@ public static func randomPoisson< S: BinaryInteger & TensorFlowScalar, Dtype: FloatingPoint & TensorFlowScalar >( - shape: Tensor, - rate: Tensor, - seed: Int64 = 0, - seed2: Int64 = 0 + shape: Tensor, + rate: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RandomPoisson", nOutputs) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("S", S.tensorFlowDataType) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(shape) - op.addInput(rate) - return op.execute(Int(1)) + let op = makeOp("RandomPoisson", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("S", S.tensorFlowDataType) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(shape) + op.addInput(rate) + return op.execute(Int(1)) } /// Outputs random values from the Poisson distribution(s) described by rate. @@ -22452,41 +22296,41 @@ public static func randomPoisson< /// Programming, Volume 2. Addison Wesley /// /// - Parameters: -/// - shape: 1-D integer tensor. Shape of independent samples to draw from each -/// distribution described by the shape parameters given in rate. -/// - rate: A tensor in which each scalar is a "rate" parameter describing the -/// associated poisson distribution. +/// - shape: 1-D integer tensor. Shape of independent samples to draw from each +/// distribution described by the shape parameters given in rate. +/// - rate: A tensor in which each scalar is a "rate" parameter describing the +/// associated poisson distribution. /// /// - Attrs: -/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: A second seed to avoid seed collision. +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. /// /// - Output output: A tensor with shape `shape + shape(rate)`. Each slice -/// `[:, ..., :, i0, i1, ...iN]` contains the samples drawn for -/// `rate[i0, i1, ...iN]`. +/// `[:, ..., :, i0, i1, ...iN]` contains the samples drawn for +/// `rate[i0, i1, ...iN]`. @inlinable @inline(__always) public static func randomPoissonV2< S: BinaryInteger & TensorFlowScalar, R: Numeric & TensorFlowScalar, Dtype: Numeric & TensorFlowScalar >( - shape: Tensor, - rate: Tensor, - seed: Int64 = 0, - seed2: Int64 = 0 + shape: Tensor, + rate: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RandomPoissonV2", nOutputs) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("S", S.tensorFlowDataType) - op.updateAttribute("R", R.tensorFlowDataType) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(shape) - op.addInput(rate) - return op.execute(Int(1)) + let op = makeOp("RandomPoissonV2", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("S", S.tensorFlowDataType) + op.updateAttribute("R", R.tensorFlowDataType) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(shape) + op.addInput(rate) + return op.execute(Int(1)) } /// Randomly shuffles a tensor along its first dimension. @@ -22504,72 +22348,72 @@ public static func randomPoissonV2< /// - Parameter value: The tensor to be shuffled. /// /// - Attrs: -/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: A second seed to avoid seed collision. +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. /// /// - Output output: A tensor of same shape and type as `value`, shuffled along its first -/// dimension. +/// dimension. @inlinable @inline(__always) public static func randomShuffle( - value: Tensor, - seed: Int64 = 0, - seed2: Int64 = 0 + value: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RandomShuffle", nOutputs) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(value) - return op.execute(Int(1)) + let op = makeOp("RandomShuffle", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(value) + return op.execute(Int(1)) } /// A queue that randomizes the order of elements. /// /// - Attrs: -/// - component_types: The type of each component in a value. -/// - shapes: The shape of each component in a value. The length of this attr must -/// be either 0 or the same as the length of component_types. If the length of -/// this attr is 0, the shapes of queue elements are not constrained, and -/// only one element may be dequeued at a time. -/// - capacity: The upper bound on the number of elements in this queue. -/// Negative numbers mean no limit. -/// - min_after_dequeue: Dequeue will block unless there would be this -/// many elements after the dequeue or the queue is closed. This -/// ensures a minimum level of mixing of elements. -/// - seed: If either seed or seed2 is set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, a random seed is used. -/// - seed2: A second seed to avoid seed collision. -/// - container: If non-empty, this queue is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this queue will be shared under the given name -/// across multiple sessions. +/// - component_types: The type of each component in a value. +/// - shapes: The shape of each component in a value. The length of this attr must +/// be either 0 or the same as the length of component_types. If the length of +/// this attr is 0, the shapes of queue elements are not constrained, and +/// only one element may be dequeued at a time. +/// - capacity: The upper bound on the number of elements in this queue. +/// Negative numbers mean no limit. +/// - min_after_dequeue: Dequeue will block unless there would be this +/// many elements after the dequeue or the queue is closed. This +/// ensures a minimum level of mixing of elements. +/// - seed: If either seed or seed2 is set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, a random seed is used. +/// - seed2: A second seed to avoid seed collision. +/// - container: If non-empty, this queue is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this queue will be shared under the given name +/// across multiple sessions. /// /// - Output handle: The handle to the queue. @inlinable @inline(__always) public static func randomShuffleQueueV2( - componentTypes: [TensorDataType], - shapes: [TensorShape?], - capacity: Int64 = -1, - minAfterDequeue: Int64 = 0, - seed: Int64 = 0, - seed2: Int64 = 0, - container: String, - sharedName: String + componentTypes: [TensorDataType], + shapes: [TensorShape?], + capacity: Int64 = -1, + minAfterDequeue: Int64 = 0, + seed: Int64 = 0, + seed2: Int64 = 0, + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("RandomShuffleQueueV2", nOutputs) - op.updateAttribute("component_types", componentTypes) - op.updateAttribute("shapes", shapes) - op.updateAttribute("capacity", capacity) - op.updateAttribute("min_after_dequeue", minAfterDequeue) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("RandomShuffleQueueV2", nOutputs) + op.updateAttribute("component_types", componentTypes) + op.updateAttribute("shapes", shapes) + op.updateAttribute("capacity", capacity) + op.updateAttribute("min_after_dequeue", minAfterDequeue) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Outputs random values from a normal distribution. @@ -22579,11 +22423,11 @@ public static func randomShuffleQueueV2( /// - Parameter shape: The shape of the output tensor. /// /// - Attrs: -/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: A second seed to avoid seed collision. -/// - dtype: The type of the output. +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. +/// - dtype: The type of the output. /// /// - Output output: A tensor of the specified shape filled with random normal values. @inlinable @inline(__always) @@ -22591,18 +22435,18 @@ public static func randomStandardNormal< Dtype: FloatingPoint & TensorFlowScalar, T: BinaryInteger & TensorFlowScalar >( - shape: Tensor, - seed: Int64 = 0, - seed2: Int64 = 0 + shape: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RandomStandardNormal", nOutputs) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(shape) - return op.execute(Int(1)) + let op = makeOp("RandomStandardNormal", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(shape) + return op.execute(Int(1)) } /// Outputs random values from a uniform distribution. @@ -22613,11 +22457,11 @@ public static func randomStandardNormal< /// - Parameter shape: The shape of the output tensor. /// /// - Attrs: -/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: A second seed to avoid seed collision. -/// - dtype: The type of the output. +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. +/// - dtype: The type of the output. /// /// - Output output: A tensor of the specified shape filled with uniform random values. @inlinable @inline(__always) @@ -22625,18 +22469,18 @@ public static func randomUniform< Dtype: FloatingPoint & TensorFlowScalar, T: BinaryInteger & TensorFlowScalar >( - shape: Tensor, - seed: Int64 = 0, - seed2: Int64 = 0 + shape: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RandomUniform", nOutputs) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(shape) - return op.execute(Int(1)) + let op = makeOp("RandomUniform", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(shape) + return op.execute(Int(1)) } /// Outputs random integers from a uniform distribution. @@ -22650,15 +22494,15 @@ public static func randomUniform< /// smaller than the range of the output (either `2^32` or `2^64`). /// /// - Parameters: -/// - shape: The shape of the output tensor. -/// - minval: 0-D. Inclusive lower bound on the generated integers. -/// - maxval: 0-D. Exclusive upper bound on the generated integers. +/// - shape: The shape of the output tensor. +/// - minval: 0-D. Inclusive lower bound on the generated integers. +/// - maxval: 0-D. Exclusive upper bound on the generated integers. /// /// - Attrs: -/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: A second seed to avoid seed collision. +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. /// /// - Output output: A tensor of the specified shape filled with uniform random integers. @inlinable @inline(__always) @@ -22666,22 +22510,22 @@ public static func randomUniformInt< Tout: BinaryInteger & TensorFlowScalar, T: BinaryInteger & TensorFlowScalar >( - shape: Tensor, - minval: Tensor, - maxval: Tensor, - seed: Int64 = 0, - seed2: Int64 = 0 + shape: Tensor, + minval: Tensor, + maxval: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RandomUniformInt", nOutputs) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("Tout", Tout.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(shape) - op.addInput(minval) - op.addInput(maxval) - return op.execute(Int(1)) + let op = makeOp("RandomUniformInt", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(shape) + op.addInput(minval) + op.addInput(maxval) + return op.execute(Int(1)) } /// Creates a sequence of numbers. @@ -22699,48 +22543,48 @@ public static func randomUniformInt< /// ``` /// /// - Parameters: -/// - start: 0-D (scalar). First entry in the sequence. -/// - limit: 0-D (scalar). Upper limit of sequence, exclusive. -/// - delta: 0-D (scalar). Optional. Default is 1. Number that increments `start`. +/// - start: 0-D (scalar). First entry in the sequence. +/// - limit: 0-D (scalar). Upper limit of sequence, exclusive. +/// - delta: 0-D (scalar). Optional. Default is 1. Number that increments `start`. /// /// - Output output: 1-D. @inlinable @inline(__always) public static func range( - start: Tensor, - limit: Tensor, - delta: Tensor + start: Tensor, + limit: Tensor, + delta: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Range", nOutputs) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(start) - op.addInput(limit) - op.addInput(delta) - return op.execute(Int(1)) + let op = makeOp("Range", nOutputs) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(start) + op.addInput(limit) + op.addInput(delta) + return op.execute(Int(1)) } /// Creates a dataset with a range of values. Corresponds to python's xrange. /// /// - Parameters: -/// - start: corresponds to start in python's xrange(). -/// - stop: corresponds to stop in python's xrange(). -/// - step: corresponds to step in python's xrange(). +/// - start: corresponds to start in python's xrange(). +/// - stop: corresponds to stop in python's xrange(). +/// - step: corresponds to step in python's xrange(). @inlinable @inline(__always) public static func rangeDataset( - start: Tensor, - stop: Tensor, - step: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + start: Tensor, + stop: Tensor, + step: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("RangeDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(start) - op.addInput(stop) - op.addInput(step) - return op.execute(Int(1)) + let op = makeOp("RangeDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(start) + op.addInput(stop) + op.addInput(step) + return op.execute(Int(1)) } /// Returns the rank of a tensor. @@ -22760,24 +22604,24 @@ public static func rangeDataset( /// of the tensor. Rank is also known as "order", "degree", or "ndims." @inlinable @inline(__always) public static func rank( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Rank", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Rank", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Reads and outputs the entire contents of the input filename. @inlinable @inline(__always) public static func readFile( - filename: StringTensor + filename: StringTensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("ReadFile", nOutputs) - op.addInput(filename) - return op.execute(Int(1)) + let op = makeOp("ReadFile", nOutputs) + op.addInput(filename) + return op.execute(Int(1)) } /// Reads the value of a variable. @@ -22794,13 +22638,13 @@ public static func readFile( /// - Attr dtype: the dtype of the value. @inlinable @inline(__always) public static func readVariableOp( - resource: ResourceHandle + resource: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ReadVariableOp", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(resource) - return op.execute(Int(1)) + let op = makeOp("ReadVariableOp", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(resource) + return op.execute(Int(1)) } /// Returns the number of records this Reader has produced. @@ -22811,12 +22655,12 @@ public static func readVariableOp( /// - Parameter reader_handle: Handle to a Reader. @inlinable @inline(__always) public static func readerNumRecordsProducedV2( - readerHandle: ResourceHandle + readerHandle: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ReaderNumRecordsProducedV2", nOutputs) - op.addInput(readerHandle) - return op.execute(Int(1)) + let op = makeOp("ReaderNumRecordsProducedV2", nOutputs) + op.addInput(readerHandle) + return op.execute(Int(1)) } /// Returns the number of work units this Reader has finished processing. @@ -22824,12 +22668,12 @@ public static func readerNumRecordsProducedV2( /// - Parameter reader_handle: Handle to a Reader. @inlinable @inline(__always) public static func readerNumWorkUnitsCompletedV2( - readerHandle: ResourceHandle + readerHandle: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ReaderNumWorkUnitsCompletedV2", nOutputs) - op.addInput(readerHandle) - return op.execute(Int(1)) + let op = makeOp("ReaderNumWorkUnitsCompletedV2", nOutputs) + op.addInput(readerHandle) + return op.execute(Int(1)) } /// Returns up to `num_records` (key, value) pairs produced by a Reader. @@ -22840,25 +22684,25 @@ public static func readerNumWorkUnitsCompletedV2( /// It may return less than `num_records` even before the last batch. /// /// - Parameters: -/// - reader_handle: Handle to a `Reader`. -/// - queue_handle: Handle to a `Queue`, with string work items. -/// - num_records: number of records to read from `Reader`. +/// - reader_handle: Handle to a `Reader`. +/// - queue_handle: Handle to a `Queue`, with string work items. +/// - num_records: number of records to read from `Reader`. /// /// - Outputs: -/// - keys: A 1-D tensor. -/// - values: A 1-D tensor. +/// - keys: A 1-D tensor. +/// - values: A 1-D tensor. @inlinable @inline(__always) public static func readerReadUpToV2( - readerHandle: ResourceHandle, - queueHandle: ResourceHandle, - numRecords: Tensor + readerHandle: ResourceHandle, + queueHandle: ResourceHandle, + numRecords: Tensor ) -> (keys: StringTensor, values: StringTensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("ReaderReadUpToV2", nOutputs) - op.addInput(readerHandle) - op.addInput(queueHandle) - op.addInput(numRecords) - return op.execute(Int(1), Int(1)) + let op = makeOp("ReaderReadUpToV2", nOutputs) + op.addInput(readerHandle) + op.addInput(queueHandle) + op.addInput(numRecords) + return op.execute(Int(1), Int(1)) } /// Returns the next record (key, value pair) produced by a Reader. @@ -22868,22 +22712,22 @@ public static func readerReadUpToV2( /// with the previous file). /// /// - Parameters: -/// - reader_handle: Handle to a Reader. -/// - queue_handle: Handle to a Queue, with string work items. +/// - reader_handle: Handle to a Reader. +/// - queue_handle: Handle to a Queue, with string work items. /// /// - Outputs: -/// - key: A scalar. -/// - value: A scalar. +/// - key: A scalar. +/// - value: A scalar. @inlinable @inline(__always) public static func readerReadV2( - readerHandle: ResourceHandle, - queueHandle: ResourceHandle + readerHandle: ResourceHandle, + queueHandle: ResourceHandle ) -> (key: StringTensor, value: StringTensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("ReaderReadV2", nOutputs) - op.addInput(readerHandle) - op.addInput(queueHandle) - return op.execute(Int(1), Int(1)) + let op = makeOp("ReaderReadV2", nOutputs) + op.addInput(readerHandle) + op.addInput(queueHandle) + return op.execute(Int(1), Int(1)) } /// Restore a Reader to its initial clean state. @@ -22891,12 +22735,12 @@ public static func readerReadV2( /// - Parameter reader_handle: Handle to a Reader. @inlinable @inline(__always) public static func readerResetV2( - readerHandle: ResourceHandle + readerHandle: ResourceHandle ) { let nOutputs = 0 - let op = makeOp("ReaderResetV2", nOutputs) - op.addInput(readerHandle) - op.execute() + let op = makeOp("ReaderResetV2", nOutputs) + op.addInput(readerHandle) + op.execute() } /// Restore a reader to a previously saved state. @@ -22905,19 +22749,19 @@ public static func readerResetV2( /// Unimplemented error. /// /// - Parameters: -/// - reader_handle: Handle to a Reader. -/// - state: Result of a ReaderSerializeState of a Reader with type -/// matching reader_handle. +/// - reader_handle: Handle to a Reader. +/// - state: Result of a ReaderSerializeState of a Reader with type +/// matching reader_handle. @inlinable @inline(__always) public static func readerRestoreStateV2( - readerHandle: ResourceHandle, - state: StringTensor + readerHandle: ResourceHandle, + state: StringTensor ) { let nOutputs = 0 - let op = makeOp("ReaderRestoreStateV2", nOutputs) - op.addInput(readerHandle) - op.addInput(state) - op.execute() + let op = makeOp("ReaderRestoreStateV2", nOutputs) + op.addInput(readerHandle) + op.addInput(state) + op.execute() } /// Produce a string tensor that encodes the state of a Reader. @@ -22928,12 +22772,12 @@ public static func readerRestoreStateV2( /// - Parameter reader_handle: Handle to a Reader. @inlinable @inline(__always) public static func readerSerializeStateV2( - readerHandle: ResourceHandle + readerHandle: ResourceHandle ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("ReaderSerializeStateV2", nOutputs) - op.addInput(readerHandle) - return op.execute(Int(1)) + let op = makeOp("ReaderSerializeStateV2", nOutputs) + op.addInput(readerHandle) + return op.execute(Int(1)) } /// Returns the real part of a complex number. @@ -22954,14 +22798,14 @@ public static func real< T: TensorFlowScalar, Tout: FloatingPoint & TensorFlowScalar >( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Real", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tout", Tout.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Real", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tout", Tout.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Returns x / y element-wise for real types. @@ -22972,15 +22816,15 @@ public static func real< /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func realDiv( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RealDiv", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("RealDiv", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Computes the reciprocal of x element-wise. @@ -22988,13 +22832,13 @@ public static func realDiv( /// I.e., \\(y = 1 / x\\). @inlinable @inline(__always) public static func reciprocal( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Reciprocal", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Reciprocal", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the gradient for the inverse of `x` wrt its input. @@ -23003,51 +22847,51 @@ public static func reciprocal( /// is the corresponding input gradient. @inlinable @inline(__always) public static func reciprocalGrad( - _ y: Tensor, - dy: Tensor + _ y: Tensor, + dy: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ReciprocalGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(y) - op.addInput(dy) - return op.execute(Int(1)) + let op = makeOp("ReciprocalGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(dy) + return op.execute(Int(1)) } /// Emits randomized records. /// /// - Attrs: -/// - file_pattern: Glob pattern for the data files. -/// - file_random_seed: Random seeds used to produce randomized records. -/// - file_shuffle_shift_ratio: Shifts the list of files after the list is randomly -/// shuffled. -/// - file_buffer_size: The randomization shuffling buffer. -/// - file_parallelism: How many sstables are opened and concurrently iterated over. -/// - batch_size: The batch size. -/// - compression_type: The type of compression for the file. Currently ZLIB and -/// GZIP are supported. Defaults to none. +/// - file_pattern: Glob pattern for the data files. +/// - file_random_seed: Random seeds used to produce randomized records. +/// - file_shuffle_shift_ratio: Shifts the list of files after the list is randomly +/// shuffled. +/// - file_buffer_size: The randomization shuffling buffer. +/// - file_parallelism: How many sstables are opened and concurrently iterated over. +/// - batch_size: The batch size. +/// - compression_type: The type of compression for the file. Currently ZLIB and +/// GZIP are supported. Defaults to none. /// /// - Output records: A tensor of shape [batch_size]. @inlinable @inline(__always) public static func recordInput( - filePattern: String, - fileRandomSeed: Int64 = 301, - fileShuffleShiftRatio: Double = 0, - fileBufferSize: Int64 = 10000, - fileParallelism: Int64 = 16, - batchSize: Int64 = 32, - compressionType: String + filePattern: String, + fileRandomSeed: Int64 = 301, + fileShuffleShiftRatio: Double = 0, + fileBufferSize: Int64 = 10000, + fileParallelism: Int64 = 16, + batchSize: Int64 = 32, + compressionType: String ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("RecordInput", nOutputs) - op.updateAttribute("file_pattern", filePattern) - op.updateAttribute("file_random_seed", fileRandomSeed) - op.updateAttribute("file_shuffle_shift_ratio", fileShuffleShiftRatio) - op.updateAttribute("file_buffer_size", fileBufferSize) - op.updateAttribute("file_parallelism", fileParallelism) - op.updateAttribute("batch_size", batchSize) - op.updateAttribute("compression_type", compressionType) - return op.execute(Int(1)) + let op = makeOp("RecordInput", nOutputs) + op.updateAttribute("file_pattern", filePattern) + op.updateAttribute("file_random_seed", fileRandomSeed) + op.updateAttribute("file_shuffle_shift_ratio", fileShuffleShiftRatio) + op.updateAttribute("file_buffer_size", fileBufferSize) + op.updateAttribute("file_parallelism", fileParallelism) + op.updateAttribute("batch_size", batchSize) + op.updateAttribute("compression_type", compressionType) + return op.execute(Int(1)) } /// An op that receives embedding activations on the TPU. @@ -23060,34 +22904,34 @@ public static func recordInput( /// most one RecvTPUEmbeddingActivations op in the TPU graph. /// /// - Attrs: -/// - num_outputs: The number of output activation tensors, equal to the number of -/// embedding tables in the model. -/// - config: Serialized TPUEmbeddingConfiguration proto. +/// - num_outputs: The number of output activation tensors, equal to the number of +/// embedding tables in the model. +/// - config: Serialized TPUEmbeddingConfiguration proto. /// /// - Output outputs: A TensorList of embedding activations containing one Tensor per -/// embedding table in the model. +/// embedding table in the model. @inlinable @inline(__always) public static func recvTPUEmbeddingActivations( - numOutputs: Int64, - config: String + numOutputs: Int64, + config: String ) -> [Tensor] { let nOutputs = Int(numOutputs) - let op = makeOp("RecvTPUEmbeddingActivations", nOutputs) - op.updateAttribute("num_outputs", numOutputs) - op.updateAttribute("config", config) - return op.execute(Int(numOutputs)) + let op = makeOp("RecvTPUEmbeddingActivations", nOutputs) + op.updateAttribute("num_outputs", numOutputs) + op.updateAttribute("config", config) + return op.execute(Int(numOutputs)) } /// Reduces the input dataset to a singleton using a reduce function. /// /// - Parameters: -/// - input_dataset: A variant tensor representing the input dataset. -/// - initial_state: A nested structure of tensors, representing the initial state of the -/// transformation. +/// - input_dataset: A variant tensor representing the input dataset. +/// - initial_state: A nested structure of tensors, representing the initial state of the +/// transformation. /// /// - Attr f: A function that maps `(old_state, input_element)` to `new_state`. It must take -/// two arguments and return a nested structures of tensors. The structure of -/// `new_state` must match the structure of `initial_state`. +/// two arguments and return a nested structures of tensors. The structure of +/// `new_state` must match the structure of `initial_state`. @inlinable @inline(__always) public static func reduceDataset< FIn: TensorGroup, @@ -23096,25 +22940,25 @@ public static func reduceDataset< Targuments: TensorArrayProtocol, OutputTypes: TensorGroup >( - inputDataset: VariantHandle, - initialState: Tstate, - otherArguments: Targuments, - f: (FIn) -> FOut, - outputShapes: [TensorShape?], - useInterOpParallelism: Bool = true + inputDataset: VariantHandle, + initialState: Tstate, + otherArguments: Targuments, + f: (FIn) -> FOut, + outputShapes: [TensorShape?], + useInterOpParallelism: Bool = true ) -> OutputTypes { let nOutputs = Int(OutputTypes._typeList.count) - let op = makeOp("ReduceDataset", nOutputs) - op.updateAttribute("f", f) - op.updateAttribute("Tstate", initialState._typeList) - op.updateAttribute("Targuments", otherArguments._typeList) - op.updateAttribute("output_types", OutputTypes._typeList) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("use_inter_op_parallelism", useInterOpParallelism) - op.addInput(inputDataset) - op.addInputList(initialState) - op.addInputList(otherArguments) - return op.execute(Int(OutputTypes._typeList.count)) + let op = makeOp("ReduceDataset", nOutputs) + op.updateAttribute("f", f) + op.updateAttribute("Tstate", initialState._typeList) + op.updateAttribute("Targuments", otherArguments._typeList) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("use_inter_op_parallelism", useInterOpParallelism) + op.addInput(inputDataset) + op.addInputList(initialState) + op.addInputList(otherArguments) + return op.execute(Int(OutputTypes._typeList.count)) } /// Joins a string Tensor across the given dimensions. @@ -23144,31 +22988,31 @@ public static func reduceDataset< /// ``` /// /// - Parameters: -/// - inputs: The input to be joined. All reduced indices must have non-zero size. -/// - reduction_indices: The dimensions to reduce over. Dimensions are reduced in the -/// order specified. Omitting `reduction_indices` is equivalent to passing -/// `[n-1, n-2, ..., 0]`. Negative indices from `-n` to `-1` are supported. +/// - inputs: The input to be joined. All reduced indices must have non-zero size. +/// - reduction_indices: The dimensions to reduce over. Dimensions are reduced in the +/// order specified. Omitting `reduction_indices` is equivalent to passing +/// `[n-1, n-2, ..., 0]`. Negative indices from `-n` to `-1` are supported. /// /// - Attrs: -/// - keep_dims: If `True`, retain reduced dimensions with length `1`. -/// - separator: The separator to use when joining. +/// - keep_dims: If `True`, retain reduced dimensions with length `1`. +/// - separator: The separator to use when joining. /// /// - Output output: Has shape equal to that of the input with reduced dimensions removed or -/// set to `1` depending on `keep_dims`. +/// set to `1` depending on `keep_dims`. @inlinable @inline(__always) public static func reduceJoin( - inputs: StringTensor, - reductionIndices: Tensor, - keepDims: Bool = false, - separator: String + inputs: StringTensor, + reductionIndices: Tensor, + keepDims: Bool = false, + separator: String ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("ReduceJoin", nOutputs) - op.updateAttribute("keep_dims", keepDims) - op.updateAttribute("separator", separator) - op.addInput(inputs) - op.addInput(reductionIndices) - return op.execute(Int(1)) + let op = makeOp("ReduceJoin", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("separator", separator) + op.addInput(inputs) + op.addInput(reductionIndices) + return op.execute(Int(1)) } /// Check if the input matches the regex pattern. @@ -23181,20 +23025,20 @@ public static func reduceJoin( /// The pattern follows the re2 syntax (https://github.com/google/re2/wiki/Syntax) /// /// - Parameters: -/// - input: A string tensor of the text to be processed. -/// - pattern: A scalar string tensor containing the regular expression to match the input. +/// - input: A string tensor of the text to be processed. +/// - pattern: A scalar string tensor containing the regular expression to match the input. /// /// - Output output: A bool tensor with the same shape as `input`. @inlinable @inline(__always) public static func regexFullMatch( - _ input: StringTensor, - pattern: StringTensor + _ input: StringTensor, + pattern: StringTensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RegexFullMatch", nOutputs) - op.addInput(input) - op.addInput(pattern) - return op.execute(Int(1)) + let op = makeOp("RegexFullMatch", nOutputs) + op.addInput(input) + op.addInput(pattern) + return op.execute(Int(1)) } /// Replaces matches of the `pattern` regular expression in `input` with the @@ -23203,109 +23047,109 @@ public static func regexFullMatch( /// It follows the re2 syntax (https://github.com/google/re2/wiki/Syntax) /// /// - Parameters: -/// - input: The text to be processed. -/// - pattern: The regular expression to be matched in the `input` strings. -/// - rewrite: The rewrite string to be substituted for the `pattern` expression where it is -/// matched in the `input` strings. +/// - input: The text to be processed. +/// - pattern: The regular expression to be matched in the `input` strings. +/// - rewrite: The rewrite string to be substituted for the `pattern` expression where it is +/// matched in the `input` strings. /// /// - Attr replace_global: If True, the replacement is global (that is, all matches of the `pattern` regular -/// expression in each input string are rewritten), otherwise the `rewrite` -/// substitution is only made for the first `pattern` match. +/// expression in each input string are rewritten), otherwise the `rewrite` +/// substitution is only made for the first `pattern` match. /// /// - Output output: The text after applying pattern match and rewrite substitution. @inlinable @inline(__always) public static func regexReplace( - _ input: StringTensor, - pattern: StringTensor, - rewrite: StringTensor, - replaceGlobal: Bool = true + _ input: StringTensor, + pattern: StringTensor, + rewrite: StringTensor, + replaceGlobal: Bool = true ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("RegexReplace", nOutputs) - op.updateAttribute("replace_global", replaceGlobal) - op.addInput(input) - op.addInput(pattern) - op.addInput(rewrite) - return op.execute(Int(1)) + let op = makeOp("RegexReplace", nOutputs) + op.updateAttribute("replace_global", replaceGlobal) + op.addInput(input) + op.addInput(pattern) + op.addInput(rewrite) + return op.execute(Int(1)) } /// Computes rectified linear: `max(features, 0)`. @inlinable @inline(__always) public static func relu( - features: Tensor + features: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Relu", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(features) - return op.execute(Int(1)) + let op = makeOp("Relu", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) } /// Computes rectified linear 6: `min(max(features, 0), 6)`. @inlinable @inline(__always) public static func relu6( - features: Tensor + features: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Relu6", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(features) - return op.execute(Int(1)) + let op = makeOp("Relu6", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) } /// Computes rectified linear 6 gradients for a Relu6 operation. /// /// - Parameters: -/// - gradients: The backpropagated gradients to the corresponding Relu6 operation. -/// - features: The features passed as input to the corresponding Relu6 operation, or -/// its output; using either one produces the same result. +/// - gradients: The backpropagated gradients to the corresponding Relu6 operation. +/// - features: The features passed as input to the corresponding Relu6 operation, or +/// its output; using either one produces the same result. /// /// - Output backprops: The gradients: -/// `gradients * (features > 0) * (features < 6)`. +/// `gradients * (features > 0) * (features < 6)`. @inlinable @inline(__always) public static func relu6Grad( - gradients: Tensor, - features: Tensor + gradients: Tensor, + features: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Relu6Grad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(gradients) - op.addInput(features) - return op.execute(Int(1)) + let op = makeOp("Relu6Grad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(features) + return op.execute(Int(1)) } /// Computes rectified linear gradients for a Relu operation. /// /// - Parameters: -/// - gradients: The backpropagated gradients to the corresponding Relu operation. -/// - features: The features passed as input to the corresponding Relu operation, OR -/// the outputs of that operation (both work equivalently). +/// - gradients: The backpropagated gradients to the corresponding Relu operation. +/// - features: The features passed as input to the corresponding Relu operation, OR +/// the outputs of that operation (both work equivalently). /// /// - Output backprops: `gradients * (features > 0)`. @inlinable @inline(__always) public static func reluGrad( - gradients: Tensor, - features: Tensor + gradients: Tensor, + features: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ReluGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(gradients) - op.addInput(features) - return op.execute(Int(1)) + let op = makeOp("ReluGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(features) + return op.execute(Int(1)) } /// Runs function `f` on a remote device indicated by `target`. /// /// - Parameters: -/// - target: A fully specified device name where we want to run the function. -/// - args: A list of arguments for the function. +/// - target: A fully specified device name where we want to run the function. +/// - args: A list of arguments for the function. /// /// - Attrs: -/// - Tin: The type list for the arguments. -/// - Tout: The type list for the return values. -/// - f: The function to run remotely. +/// - Tin: The type list for the arguments. +/// - Tout: The type list for the return values. +/// - f: The function to run remotely. /// /// - Output output: A list of return values. @inlinable @inline(__always) @@ -23315,18 +23159,18 @@ public static func remoteCall< FIn: TensorGroup, FOut: TensorGroup >( - target: StringTensor, - args: Tin, - f: (FIn) -> FOut + target: StringTensor, + args: Tin, + f: (FIn) -> FOut ) -> Tout { let nOutputs = Int(Tout._typeList.count) - let op = makeOp("RemoteCall", nOutputs) - op.updateAttribute("Tin", args._typeList) - op.updateAttribute("Tout", Tout._typeList) - op.updateAttribute("f", f) - op.addInput(target) - op.addInputList(args) - return op.execute(Int(Tout._typeList.count)) + let op = makeOp("RemoteCall", nOutputs) + op.updateAttribute("Tin", args._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("f", f) + op.addInput(target) + op.addInputList(args) + return op.execute(Int(Tout._typeList.count)) } /// Execute a sub graph on a remote processor. @@ -23342,7 +23186,7 @@ public static func remoteCall< /// - Parameter inputs: Arbitrary number of tensors with arbitrary data types /// /// - Attr serialized_remote_fused_graph_execute_info: Serialized protocol buffer -/// of RemoteFusedGraphExecuteInfo which contains graph specifications. +/// of RemoteFusedGraphExecuteInfo which contains graph specifications. /// /// - Output outputs: Arbitrary number of tensors with arbitrary data types @inlinable @inline(__always) @@ -23350,36 +23194,36 @@ public static func remoteFusedGraphExecute< Tinputs: TensorArrayProtocol, Toutputs: TensorGroup >( - inputs: Tinputs, - serializedRemoteFusedGraphExecuteInfo: String + inputs: Tinputs, + serializedRemoteFusedGraphExecuteInfo: String ) -> Toutputs { let nOutputs = Int(Toutputs._typeList.count) - let op = makeOp("RemoteFusedGraphExecute", nOutputs) - op.updateAttribute("Tinputs", inputs._typeList) - op.updateAttribute("Toutputs", Toutputs._typeList) - op.updateAttribute("serialized_remote_fused_graph_execute_info", serializedRemoteFusedGraphExecuteInfo) - op.addInputList(inputs) - return op.execute(Int(Toutputs._typeList.count)) + let op = makeOp("RemoteFusedGraphExecute", nOutputs) + op.updateAttribute("Tinputs", inputs._typeList) + op.updateAttribute("Toutputs", Toutputs._typeList) + op.updateAttribute("serialized_remote_fused_graph_execute_info", serializedRemoteFusedGraphExecuteInfo) + op.addInputList(inputs) + return op.execute(Int(Toutputs._typeList.count)) } /// Creates a dataset that emits the outputs of `input_dataset` `count` times. /// /// - Parameter count: A scalar representing the number of times that `input_dataset` should -/// be repeated. A value of `-1` indicates that it should be repeated infinitely. +/// be repeated. A value of `-1` indicates that it should be repeated infinitely. @inlinable @inline(__always) public static func repeatDataset( - inputDataset: VariantHandle, - count: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + count: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("RepeatDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(count) - return op.execute(Int(1)) + let op = makeOp("RepeatDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(count) + return op.execute(Int(1)) } /// Computes a range that covers the actual values present in a quantized tensor. @@ -23390,59 +23234,59 @@ public static func repeatDataset( /// `Requantize`. /// /// - Parameters: -/// - input_min: The float value that the minimum quantized input value represents. -/// - input_max: The float value that the maximum quantized input value represents. +/// - input_min: The float value that the minimum quantized input value represents. +/// - input_max: The float value that the maximum quantized input value represents. /// /// - Attr Tinput: The type of the input. /// /// - Outputs: -/// - output_min: The computed min output. -/// - output_max: the computed max output. +/// - output_min: The computed min output. +/// - output_max: the computed max output. @inlinable @inline(__always) public static func requantizationRange( - _ input: Tensor, - inputMin: Tensor, - inputMax: Tensor + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor ) -> (outputMin: Tensor, outputMax: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("RequantizationRange", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.addInput(input) - op.addInput(inputMin) - op.addInput(inputMax) - return op.execute(Int(1), Int(1)) + let op = makeOp("RequantizationRange", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + return op.execute(Int(1), Int(1)) } /// Computes requantization range per channel. /// /// - Parameters: -/// - input: The original input tensor. -/// - input_min: The minimum value of the input tensor -/// - input_max: The maximum value of the input tensor. +/// - input: The original input tensor. +/// - input_min: The minimum value of the input tensor +/// - input_max: The maximum value of the input tensor. /// /// - Attrs: -/// - T: The quantized type of input tensor that needs to be converted. -/// - clip_value_max: The maximum value of the output that needs to be clipped. -/// Example: set this to 6 for Relu6. +/// - T: The quantized type of input tensor that needs to be converted. +/// - clip_value_max: The maximum value of the output that needs to be clipped. +/// Example: set this to 6 for Relu6. /// /// - Outputs: -/// - output_min: The minimum value of the final output tensor -/// - output_max: The maximum value of the final output tensor. +/// - output_min: The minimum value of the final output tensor +/// - output_max: The maximum value of the final output tensor. @inlinable @inline(__always) public static func requantizationRangePerChannel( - _ input: Tensor, - inputMin: Tensor, - inputMax: Tensor, - clipValueMax: Double + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor, + clipValueMax: Double ) -> (outputMin: Tensor, outputMax: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("RequantizationRangePerChannel", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("clip_value_max", clipValueMax) - op.addInput(input) - op.addInput(inputMin) - op.addInput(inputMax) - return op.execute(Int(1), Int(1)) + let op = makeOp("RequantizationRangePerChannel", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("clip_value_max", clipValueMax) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + return op.execute(Int(1), Int(1)) } /// Converts the quantized `input` tensor into a lower-precision `output`. @@ -23456,108 +23300,108 @@ public static func requantizationRangePerChannel( /// value in the 16-bit data should be interpreted as -1.0f, and a 65535 means 1.0f. /// /// - Parameters: -/// - input_min: The float value that the minimum quantized input value represents. -/// - input_max: The float value that the maximum quantized input value represents. -/// - requested_output_min: The float value that the minimum quantized output value represents. -/// - requested_output_max: The float value that the maximum quantized output value represents. +/// - input_min: The float value that the minimum quantized input value represents. +/// - input_max: The float value that the maximum quantized input value represents. +/// - requested_output_min: The float value that the minimum quantized output value represents. +/// - requested_output_max: The float value that the maximum quantized output value represents. /// /// - Attrs: -/// - Tinput: The type of the input. -/// - out_type: The type of the output. Should be a lower bit depth than Tinput. +/// - Tinput: The type of the input. +/// - out_type: The type of the output. Should be a lower bit depth than Tinput. /// /// - Outputs: -/// - output_min: The requested_output_min value is copied into this output. -/// - output_max: The requested_output_max value is copied into this output. +/// - output_min: The requested_output_min value is copied into this output. +/// - output_max: The requested_output_max value is copied into this output. @inlinable @inline(__always) public static func requantize< Tinput: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - inputMin: Tensor, - inputMax: Tensor, - requestedOutputMin: Tensor, - requestedOutputMax: Tensor + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor, + requestedOutputMin: Tensor, + requestedOutputMax: Tensor ) -> (output: Tensor, outputMin: Tensor, outputMax: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("Requantize", nOutputs) - op.updateAttribute("Tinput", Tinput.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(input) - op.addInput(inputMin) - op.addInput(inputMax) - op.addInput(requestedOutputMin) - op.addInput(requestedOutputMax) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("Requantize", nOutputs) + op.updateAttribute("Tinput", Tinput.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + op.addInput(requestedOutputMin) + op.addInput(requestedOutputMax) + return op.execute(Int(1), Int(1), Int(1)) } /// Requantizes input with min and max values known per channel. /// /// - Parameters: -/// - input: The original input tensor. -/// - input_min: The minimum value of the input tensor -/// - input_max: The maximum value of the input tensor. -/// - requested_output_min: The minimum value of the output tensor requested. -/// - requested_output_max: The maximum value of the output tensor requested. +/// - input: The original input tensor. +/// - input_min: The minimum value of the input tensor +/// - input_max: The maximum value of the input tensor. +/// - requested_output_min: The minimum value of the output tensor requested. +/// - requested_output_max: The maximum value of the output tensor requested. /// /// - Attrs: -/// - T: The quantized type of input tensor that needs to be converted. -/// - out_type: The quantized type of output tensor that needs to be converted. +/// - T: The quantized type of input tensor that needs to be converted. +/// - out_type: The quantized type of output tensor that needs to be converted. /// /// - Outputs: -/// - output: Output tensor. -/// - output_min: The minimum value of the final output tensor -/// - output_max: The maximum value of the final output tensor. +/// - output: Output tensor. +/// - output_min: The minimum value of the final output tensor +/// - output_max: The maximum value of the final output tensor. @inlinable @inline(__always) public static func requantizePerChannel< T: TensorFlowScalar, OutType: TensorFlowScalar >( - _ input: Tensor, - inputMin: Tensor, - inputMax: Tensor, - requestedOutputMin: Tensor, - requestedOutputMax: Tensor + _ input: Tensor, + inputMin: Tensor, + inputMax: Tensor, + requestedOutputMin: Tensor, + requestedOutputMax: Tensor ) -> (output: Tensor, outputMin: Tensor, outputMax: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("RequantizePerChannel", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(input) - op.addInput(inputMin) - op.addInput(inputMax) - op.addInput(requestedOutputMin) - op.addInput(requestedOutputMax) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("RequantizePerChannel", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + op.addInput(inputMin) + op.addInput(inputMax) + op.addInput(requestedOutputMin) + op.addInput(requestedOutputMax) + return op.execute(Int(1), Int(1), Int(1)) } @inlinable @inline(__always) public static func requiresOlderGraphVersion( ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RequiresOlderGraphVersion", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("RequiresOlderGraphVersion", nOutputs) + + return op.execute(Int(1)) } @inlinable @inline(__always) public static func reservedAttr( - range: Int64 + range: Int64 ) { let nOutputs = 0 - let op = makeOp("ReservedAttr", nOutputs) - op.updateAttribute("range", range) - op.execute() + let op = makeOp("ReservedAttr", nOutputs) + op.updateAttribute("range", range) + op.execute() } @inlinable @inline(__always) public static func reservedInput( - _ input: Tensor + _ input: Tensor ) { let nOutputs = 0 - let op = makeOp("ReservedInput", nOutputs) - op.addInput(input) - op.execute() + let op = makeOp("ReservedInput", nOutputs) + op.addInput(input) + op.execute() } /// Reshapes a tensor. @@ -23625,16 +23469,16 @@ public static func reshape< T: TensorFlowScalar, Tshape: BinaryInteger & TensorFlowScalar >( - _ tensor: Tensor, - shape: Tensor + _ tensor: Tensor, + shape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Reshape", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tshape", Tshape.tensorFlowDataType) - op.addInput(tensor) - op.addInput(shape) - return op.execute(Int(1)) + let op = makeOp("Reshape", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tshape", Tshape.tensorFlowDataType) + op.addInput(tensor) + op.addInput(shape) + return op.execute(Int(1)) } /// Resize `images` to `size` using area interpolation. @@ -23652,28 +23496,28 @@ public static func reshape< /// area that intersects the footprint. This is the same as OpenCV's INTER_AREA. /// /// - Parameters: -/// - images: 4-D with shape `[batch, height, width, channels]`. -/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The -/// new size for the images. +/// - images: 4-D with shape `[batch, height, width, channels]`. +/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The +/// new size for the images. /// /// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and output tensors are -/// aligned, preserving the values at the corner pixels. Defaults to false. +/// aligned, preserving the values at the corner pixels. Defaults to false. /// /// - Output resized_images: 4-D with shape -/// `[batch, new_height, new_width, channels]`. +/// `[batch, new_height, new_width, channels]`. @inlinable @inline(__always) public static func resizeArea( - images: Tensor, - size: Tensor, - alignCorners: Bool = false + images: Tensor, + size: Tensor, + alignCorners: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ResizeArea", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("align_corners", alignCorners) - op.addInput(images) - op.addInput(size) - return op.execute(Int(1)) + let op = makeOp("ResizeArea", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.addInput(images) + op.addInput(size) + return op.execute(Int(1)) } /// Resize `images` to `size` using bicubic interpolation. @@ -23681,60 +23525,60 @@ public static func resizeArea( /// Input images can be of different types but output images are always float. /// /// - Parameters: -/// - images: 4-D with shape `[batch, height, width, channels]`. -/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The -/// new size for the images. +/// - images: 4-D with shape `[batch, height, width, channels]`. +/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The +/// new size for the images. /// /// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and output tensors are -/// aligned, preserving the values at the corner pixels. Defaults to false. +/// aligned, preserving the values at the corner pixels. Defaults to false. /// /// - Output resized_images: 4-D with shape -/// `[batch, new_height, new_width, channels]`. +/// `[batch, new_height, new_width, channels]`. @inlinable @inline(__always) public static func resizeBicubic( - images: Tensor, - size: Tensor, - alignCorners: Bool = false, - halfPixelCenters: Bool = false + images: Tensor, + size: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ResizeBicubic", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("align_corners", alignCorners) - op.updateAttribute("half_pixel_centers", halfPixelCenters) - op.addInput(images) - op.addInput(size) - return op.execute(Int(1)) + let op = makeOp("ResizeBicubic", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(images) + op.addInput(size) + return op.execute(Int(1)) } /// Computes the gradient of bicubic interpolation. /// /// - Parameters: -/// - grads: 4-D with shape `[batch, height, width, channels]`. -/// - original_image: 4-D with shape `[batch, orig_height, orig_width, channels]`, -/// The image tensor that was resized. +/// - grads: 4-D with shape `[batch, height, width, channels]`. +/// - original_image: 4-D with shape `[batch, orig_height, orig_width, channels]`, +/// The image tensor that was resized. /// /// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and grad tensors are -/// aligned. Defaults to false. +/// aligned. Defaults to false. /// /// - Output output: 4-D with shape `[batch, orig_height, orig_width, channels]`. -/// Gradients with respect to the input image. Input image must have been -/// float or double. +/// Gradients with respect to the input image. Input image must have been +/// float or double. @inlinable @inline(__always) public static func resizeBicubicGrad( - grads: Tensor, - originalImage: Tensor, - alignCorners: Bool = false, - halfPixelCenters: Bool = false + grads: Tensor, + originalImage: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ResizeBicubicGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("align_corners", alignCorners) - op.updateAttribute("half_pixel_centers", halfPixelCenters) - op.addInput(grads) - op.addInput(originalImage) - return op.execute(Int(1)) + let op = makeOp("ResizeBicubicGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(grads) + op.addInput(originalImage) + return op.execute(Int(1)) } /// Resize `images` to `size` using bilinear interpolation. @@ -23742,118 +23586,118 @@ public static func resizeBicubicGrad( /// Input images can be of different types but output images are always float. /// /// - Parameters: -/// - images: 4-D with shape `[batch, height, width, channels]`. -/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The -/// new size for the images. +/// - images: 4-D with shape `[batch, height, width, channels]`. +/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The +/// new size for the images. /// /// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and output tensors are -/// aligned, preserving the values at the corner pixels. Defaults to false. +/// aligned, preserving the values at the corner pixels. Defaults to false. /// /// - Output resized_images: 4-D with shape -/// `[batch, new_height, new_width, channels]`. +/// `[batch, new_height, new_width, channels]`. @inlinable @inline(__always) public static func resizeBilinear( - images: Tensor, - size: Tensor, - alignCorners: Bool = false, - halfPixelCenters: Bool = false + images: Tensor, + size: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ResizeBilinear", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("align_corners", alignCorners) - op.updateAttribute("half_pixel_centers", halfPixelCenters) - op.addInput(images) - op.addInput(size) - return op.execute(Int(1)) + let op = makeOp("ResizeBilinear", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(images) + op.addInput(size) + return op.execute(Int(1)) } /// Computes the gradient of bilinear interpolation. /// /// - Parameters: -/// - grads: 4-D with shape `[batch, height, width, channels]`. -/// - original_image: 4-D with shape `[batch, orig_height, orig_width, channels]`, -/// The image tensor that was resized. +/// - grads: 4-D with shape `[batch, height, width, channels]`. +/// - original_image: 4-D with shape `[batch, orig_height, orig_width, channels]`, +/// The image tensor that was resized. /// /// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and grad tensors are -/// aligned. Defaults to false. +/// aligned. Defaults to false. /// /// - Output output: 4-D with shape `[batch, orig_height, orig_width, channels]`. -/// Gradients with respect to the input image. Input image must have been -/// float or double. +/// Gradients with respect to the input image. Input image must have been +/// float or double. @inlinable @inline(__always) public static func resizeBilinearGrad( - grads: Tensor, - originalImage: Tensor, - alignCorners: Bool = false, - halfPixelCenters: Bool = false + grads: Tensor, + originalImage: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ResizeBilinearGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("align_corners", alignCorners) - op.updateAttribute("half_pixel_centers", halfPixelCenters) - op.addInput(grads) - op.addInput(originalImage) - return op.execute(Int(1)) + let op = makeOp("ResizeBilinearGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(grads) + op.addInput(originalImage) + return op.execute(Int(1)) } /// Resize `images` to `size` using nearest neighbor interpolation. /// /// - Parameters: -/// - images: 4-D with shape `[batch, height, width, channels]`. -/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The -/// new size for the images. +/// - images: 4-D with shape `[batch, height, width, channels]`. +/// - size: = A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The +/// new size for the images. /// /// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and output tensors are -/// aligned, preserving the values at the corner pixels. Defaults to false. +/// aligned, preserving the values at the corner pixels. Defaults to false. /// /// - Output resized_images: 4-D with shape -/// `[batch, new_height, new_width, channels]`. +/// `[batch, new_height, new_width, channels]`. @inlinable @inline(__always) public static func resizeNearestNeighbor( - images: Tensor, - size: Tensor, - alignCorners: Bool = false, - halfPixelCenters: Bool = false + images: Tensor, + size: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ResizeNearestNeighbor", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("align_corners", alignCorners) - op.updateAttribute("half_pixel_centers", halfPixelCenters) - op.addInput(images) - op.addInput(size) - return op.execute(Int(1)) + let op = makeOp("ResizeNearestNeighbor", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(images) + op.addInput(size) + return op.execute(Int(1)) } /// Computes the gradient of nearest neighbor interpolation. /// /// - Parameters: -/// - grads: 4-D with shape `[batch, height, width, channels]`. -/// - size: = A 1-D int32 Tensor of 2 elements: `orig_height, orig_width`. The -/// original input size. +/// - grads: 4-D with shape `[batch, height, width, channels]`. +/// - size: = A 1-D int32 Tensor of 2 elements: `orig_height, orig_width`. The +/// original input size. /// /// - Attr align_corners: If true, the centers of the 4 corner pixels of the input and grad tensors are -/// aligned. Defaults to false. +/// aligned. Defaults to false. /// /// - Output output: 4-D with shape `[batch, orig_height, orig_width, channels]`. Gradients -/// with respect to the input image. +/// with respect to the input image. @inlinable @inline(__always) public static func resizeNearestNeighborGrad( - grads: Tensor, - size: Tensor, - alignCorners: Bool = false, - halfPixelCenters: Bool = false + grads: Tensor, + size: Tensor, + alignCorners: Bool = false, + halfPixelCenters: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ResizeNearestNeighborGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("align_corners", alignCorners) - op.updateAttribute("half_pixel_centers", halfPixelCenters) - op.addInput(grads) - op.addInput(size) - return op.execute(Int(1)) + let op = makeOp("ResizeNearestNeighborGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("align_corners", alignCorners) + op.updateAttribute("half_pixel_centers", halfPixelCenters) + op.addInput(grads) + op.addInput(size) + return op.execute(Int(1)) } /// Update '*var' according to the AdaMax algorithm. @@ -23863,46 +23707,46 @@ public static func resizeNearestNeighborGrad( /// variable <- variable - learning_rate / (1 - beta1^t) * m_t / (v_t + epsilon) /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - m: Should be from a Variable(). -/// - v: Should be from a Variable(). -/// - beta1_power: Must be a scalar. -/// - lr: Scaling factor. Must be a scalar. -/// - beta1: Momentum factor. Must be a scalar. -/// - beta2: Momentum factor. Must be a scalar. -/// - epsilon: Ridge term. Must be a scalar. -/// - grad: The gradient. +/// - var: Should be from a Variable(). +/// - m: Should be from a Variable(). +/// - v: Should be from a Variable(). +/// - beta1_power: Must be a scalar. +/// - lr: Scaling factor. Must be a scalar. +/// - beta1: Momentum factor. Must be a scalar. +/// - beta2: Momentum factor. Must be a scalar. +/// - epsilon: Ridge term. Must be a scalar. +/// - grad: The gradient. /// /// - Attr use_locking: If `True`, updating of the var, m, and v tensors will be protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. @inlinable @inline(__always) public static func resourceApplyAdaMax( - var_: ResourceHandle, - m: ResourceHandle, - v: ResourceHandle, - beta1Power: Tensor, - lr: Tensor, - beta1: Tensor, - beta2: Tensor, - epsilon: Tensor, - grad: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + m: ResourceHandle, + v: ResourceHandle, + beta1Power: Tensor, + lr: Tensor, + beta1: Tensor, + beta2: Tensor, + epsilon: Tensor, + grad: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyAdaMax", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(m) - op.addInput(v) - op.addInput(beta1Power) - op.addInput(lr) - op.addInput(beta1) - op.addInput(beta2) - op.addInput(epsilon) - op.addInput(grad) - op.execute() + let op = makeOp("ResourceApplyAdaMax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(m) + op.addInput(v) + op.addInput(beta1Power) + op.addInput(lr) + op.addInput(beta1) + op.addInput(beta2) + op.addInput(epsilon) + op.addInput(grad) + op.execute() } /// Update '*var' according to the adadelta scheme. @@ -23913,39 +23757,39 @@ public static func resourceApplyAdaMax( /// var -= update; /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - accum: Should be from a Variable(). -/// - accum_update: Should be from a Variable(). -/// - lr: Scaling factor. Must be a scalar. -/// - rho: Decay factor. Must be a scalar. -/// - epsilon: Constant factor. Must be a scalar. -/// - grad: The gradient. +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - accum_update: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - rho: Decay factor. Must be a scalar. +/// - epsilon: Constant factor. Must be a scalar. +/// - grad: The gradient. /// /// - Attr use_locking: If True, updating of the var, accum and update_accum tensors will be protected by -/// a lock; otherwise the behavior is undefined, but may exhibit less contention. +/// a lock; otherwise the behavior is undefined, but may exhibit less contention. @inlinable @inline(__always) public static func resourceApplyAdadelta( - var_: ResourceHandle, - accum: ResourceHandle, - accumUpdate: ResourceHandle, - lr: Tensor, - rho: Tensor, - epsilon: Tensor, - grad: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + accum: ResourceHandle, + accumUpdate: ResourceHandle, + lr: Tensor, + rho: Tensor, + epsilon: Tensor, + grad: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyAdadelta", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(accum) - op.addInput(accumUpdate) - op.addInput(lr) - op.addInput(rho) - op.addInput(epsilon) - op.addInput(grad) - op.execute() + let op = makeOp("ResourceApplyAdadelta", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(accumUpdate) + op.addInput(lr) + op.addInput(rho) + op.addInput(epsilon) + op.addInput(grad) + op.execute() } /// Update '*var' according to the adagrad scheme. @@ -23954,74 +23798,74 @@ public static func resourceApplyAdadelta( /// var -= lr * grad * (1 / sqrt(accum)) /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - accum: Should be from a Variable(). -/// - lr: Scaling factor. Must be a scalar. -/// - grad: The gradient. +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - grad: The gradient. /// /// - Attr use_locking: If `True`, updating of the var and accum tensors will be protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. @inlinable @inline(__always) public static func resourceApplyAdagrad( - var_: ResourceHandle, - accum: ResourceHandle, - lr: Tensor, - grad: Tensor, - useLocking: Bool = false, - updateSlots: Bool = true + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + grad: Tensor, + useLocking: Bool = false, + updateSlots: Bool = true ) { let nOutputs = 0 - let op = makeOp("ResourceApplyAdagrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.updateAttribute("update_slots", updateSlots) - op.addInput(var_) - op.addInput(accum) - op.addInput(lr) - op.addInput(grad) - op.execute() + let op = makeOp("ResourceApplyAdagrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("update_slots", updateSlots) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(grad) + op.execute() } /// Update '*var' according to the proximal adagrad scheme. /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - gradient_accumulator: Should be from a Variable(). -/// - gradient_squared_accumulator: Should be from a Variable(). -/// - grad: The gradient. -/// - lr: Scaling factor. Must be a scalar. -/// - l1: L1 regularization. Must be a scalar. -/// - l2: L2 regularization. Must be a scalar. -/// - global_step: Training step number. Must be a scalar. +/// - var: Should be from a Variable(). +/// - gradient_accumulator: Should be from a Variable(). +/// - gradient_squared_accumulator: Should be from a Variable(). +/// - grad: The gradient. +/// - lr: Scaling factor. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - global_step: Training step number. Must be a scalar. /// /// - Attr use_locking: If True, updating of the var and accum tensors will be protected by -/// a lock; otherwise the behavior is undefined, but may exhibit less contention. +/// a lock; otherwise the behavior is undefined, but may exhibit less contention. @inlinable @inline(__always) public static func resourceApplyAdagradDA( - var_: ResourceHandle, - gradientAccumulator: ResourceHandle, - gradientSquaredAccumulator: ResourceHandle, - grad: Tensor, - lr: Tensor, - l1: Tensor, - l2: Tensor, - globalStep: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + gradientAccumulator: ResourceHandle, + gradientSquaredAccumulator: ResourceHandle, + grad: Tensor, + lr: Tensor, + l1: Tensor, + l2: Tensor, + globalStep: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyAdagradDA", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(gradientAccumulator) - op.addInput(gradientSquaredAccumulator) - op.addInput(grad) - op.addInput(lr) - op.addInput(l1) - op.addInput(l2) - op.addInput(globalStep) - op.execute() + let op = makeOp("ResourceApplyAdagradDA", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(gradientAccumulator) + op.addInput(gradientSquaredAccumulator) + op.addInput(grad) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(globalStep) + op.execute() } /// Update '*var' according to the Adam algorithm. @@ -24032,53 +23876,53 @@ public static func resourceApplyAdagradDA( /// $$variable := variable - lr_t * m_t / (\sqrt{v_t} + \epsilon)$$ /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - m: Should be from a Variable(). -/// - v: Should be from a Variable(). -/// - beta1_power: Must be a scalar. -/// - beta2_power: Must be a scalar. -/// - lr: Scaling factor. Must be a scalar. -/// - beta1: Momentum factor. Must be a scalar. -/// - beta2: Momentum factor. Must be a scalar. -/// - epsilon: Ridge term. Must be a scalar. -/// - grad: The gradient. +/// - var: Should be from a Variable(). +/// - m: Should be from a Variable(). +/// - v: Should be from a Variable(). +/// - beta1_power: Must be a scalar. +/// - beta2_power: Must be a scalar. +/// - lr: Scaling factor. Must be a scalar. +/// - beta1: Momentum factor. Must be a scalar. +/// - beta2: Momentum factor. Must be a scalar. +/// - epsilon: Ridge term. Must be a scalar. +/// - grad: The gradient. /// /// - Attrs: -/// - use_locking: If `True`, updating of the var, m, and v tensors will be protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. -/// - use_nesterov: If `True`, uses the nesterov update. +/// - use_locking: If `True`, updating of the var, m, and v tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +/// - use_nesterov: If `True`, uses the nesterov update. @inlinable @inline(__always) public static func resourceApplyAdam( - var_: ResourceHandle, - m: ResourceHandle, - v: ResourceHandle, - beta1Power: Tensor, - beta2Power: Tensor, - lr: Tensor, - beta1: Tensor, - beta2: Tensor, - epsilon: Tensor, - grad: Tensor, - useLocking: Bool = false, - useNesterov: Bool = false + var_: ResourceHandle, + m: ResourceHandle, + v: ResourceHandle, + beta1Power: Tensor, + beta2Power: Tensor, + lr: Tensor, + beta1: Tensor, + beta2: Tensor, + epsilon: Tensor, + grad: Tensor, + useLocking: Bool = false, + useNesterov: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyAdam", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.updateAttribute("use_nesterov", useNesterov) - op.addInput(var_) - op.addInput(m) - op.addInput(v) - op.addInput(beta1Power) - op.addInput(beta2Power) - op.addInput(lr) - op.addInput(beta1) - op.addInput(beta2) - op.addInput(epsilon) - op.addInput(grad) - op.execute() + let op = makeOp("ResourceApplyAdam", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("use_nesterov", useNesterov) + op.addInput(var_) + op.addInput(m) + op.addInput(v) + op.addInput(beta1Power) + op.addInput(beta2Power) + op.addInput(lr) + op.addInput(beta1) + op.addInput(beta2) + op.addInput(epsilon) + op.addInput(grad) + op.execute() } /// Update '*var' according to the Adam algorithm. @@ -24090,52 +23934,52 @@ public static func resourceApplyAdam( /// $$variable := variable - lr_t * m_t / (\sqrt{vhat_t} + \epsilon)$$ /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - m: Should be from a Variable(). -/// - v: Should be from a Variable(). -/// - vhat: Should be from a Variable(). -/// - beta1_power: Must be a scalar. -/// - beta2_power: Must be a scalar. -/// - lr: Scaling factor. Must be a scalar. -/// - beta1: Momentum factor. Must be a scalar. -/// - beta2: Momentum factor. Must be a scalar. -/// - epsilon: Ridge term. Must be a scalar. -/// - grad: The gradient. +/// - var: Should be from a Variable(). +/// - m: Should be from a Variable(). +/// - v: Should be from a Variable(). +/// - vhat: Should be from a Variable(). +/// - beta1_power: Must be a scalar. +/// - beta2_power: Must be a scalar. +/// - lr: Scaling factor. Must be a scalar. +/// - beta1: Momentum factor. Must be a scalar. +/// - beta2: Momentum factor. Must be a scalar. +/// - epsilon: Ridge term. Must be a scalar. +/// - grad: The gradient. /// /// - Attr use_locking: If `True`, updating of the var, m, and v tensors will be protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. @inlinable @inline(__always) public static func resourceApplyAdamWithAmsgrad( - var_: ResourceHandle, - m: ResourceHandle, - v: ResourceHandle, - vhat: ResourceHandle, - beta1Power: Tensor, - beta2Power: Tensor, - lr: Tensor, - beta1: Tensor, - beta2: Tensor, - epsilon: Tensor, - grad: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + m: ResourceHandle, + v: ResourceHandle, + vhat: ResourceHandle, + beta1Power: Tensor, + beta2Power: Tensor, + lr: Tensor, + beta1: Tensor, + beta2: Tensor, + epsilon: Tensor, + grad: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyAdamWithAmsgrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(m) - op.addInput(v) - op.addInput(vhat) - op.addInput(beta1Power) - op.addInput(beta2Power) - op.addInput(lr) - op.addInput(beta1) - op.addInput(beta2) - op.addInput(epsilon) - op.addInput(grad) - op.execute() + let op = makeOp("ResourceApplyAdamWithAmsgrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(m) + op.addInput(v) + op.addInput(vhat) + op.addInput(beta1Power) + op.addInput(beta2Power) + op.addInput(lr) + op.addInput(beta1) + op.addInput(beta2) + op.addInput(epsilon) + op.addInput(grad) + op.execute() } /// Update '*var' according to the AddSign update. @@ -24145,40 +23989,40 @@ public static func resourceApplyAdamWithAmsgrad( /// variable <- variable - lr_t * update /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - m: Should be from a Variable(). -/// - lr: Scaling factor. Must be a scalar. -/// - alpha: Must be a scalar. -/// - sign_decay: Must be a scalar. -/// - beta: Must be a scalar. -/// - grad: The gradient. +/// - var: Should be from a Variable(). +/// - m: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - alpha: Must be a scalar. +/// - sign_decay: Must be a scalar. +/// - beta: Must be a scalar. +/// - grad: The gradient. /// /// - Attr use_locking: If `True`, updating of the var and m tensors is -/// protected by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. +/// protected by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. @inlinable @inline(__always) public static func resourceApplyAddSign( - var_: ResourceHandle, - m: ResourceHandle, - lr: Tensor, - alpha: Tensor, - signDecay: Tensor, - beta: Tensor, - grad: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + m: ResourceHandle, + lr: Tensor, + alpha: Tensor, + signDecay: Tensor, + beta: Tensor, + grad: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyAddSign", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(m) - op.addInput(lr) - op.addInput(alpha) - op.addInput(signDecay) - op.addInput(beta) - op.addInput(grad) - op.execute() + let op = makeOp("ResourceApplyAddSign", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(m) + op.addInput(lr) + op.addInput(alpha) + op.addInput(signDecay) + op.addInput(beta) + op.addInput(grad) + op.execute() } /// Update '*var' according to the centered RMSProp algorithm. @@ -24203,45 +24047,45 @@ public static func resourceApplyAddSign( /// var <- var - mom /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - mg: Should be from a Variable(). -/// - ms: Should be from a Variable(). -/// - mom: Should be from a Variable(). -/// - lr: Scaling factor. Must be a scalar. -/// - rho: Decay rate. Must be a scalar. -/// - epsilon: Ridge term. Must be a scalar. -/// - grad: The gradient. +/// - var: Should be from a Variable(). +/// - mg: Should be from a Variable(). +/// - ms: Should be from a Variable(). +/// - mom: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - rho: Decay rate. Must be a scalar. +/// - epsilon: Ridge term. Must be a scalar. +/// - grad: The gradient. /// /// - Attr use_locking: If `True`, updating of the var, mg, ms, and mom tensors is -/// protected by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. +/// protected by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. @inlinable @inline(__always) public static func resourceApplyCenteredRMSProp( - var_: ResourceHandle, - mg: ResourceHandle, - ms: ResourceHandle, - mom: ResourceHandle, - lr: Tensor, - rho: Tensor, - momentum: Tensor, - epsilon: Tensor, - grad: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + mg: ResourceHandle, + ms: ResourceHandle, + mom: ResourceHandle, + lr: Tensor, + rho: Tensor, + momentum: Tensor, + epsilon: Tensor, + grad: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyCenteredRMSProp", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(mg) - op.addInput(ms) - op.addInput(mom) - op.addInput(lr) - op.addInput(rho) - op.addInput(momentum) - op.addInput(epsilon) - op.addInput(grad) - op.execute() + let op = makeOp("ResourceApplyCenteredRMSProp", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(mg) + op.addInput(ms) + op.addInput(mom) + op.addInput(lr) + op.addInput(rho) + op.addInput(momentum) + op.addInput(epsilon) + op.addInput(grad) + op.execute() } /// Update '*var' according to the Ftrl-proximal scheme. @@ -24253,43 +24097,43 @@ public static func resourceApplyCenteredRMSProp( /// accum = accum_new /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - accum: Should be from a Variable(). -/// - linear: Should be from a Variable(). -/// - grad: The gradient. -/// - lr: Scaling factor. Must be a scalar. -/// - l1: L1 regulariation. Must be a scalar. -/// - l2: L2 regulariation. Must be a scalar. -/// - lr_power: Scaling factor. Must be a scalar. +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - linear: Should be from a Variable(). +/// - grad: The gradient. +/// - lr: Scaling factor. Must be a scalar. +/// - l1: L1 regulariation. Must be a scalar. +/// - l2: L2 regulariation. Must be a scalar. +/// - lr_power: Scaling factor. Must be a scalar. /// /// - Attr use_locking: If `True`, updating of the var and accum tensors will be protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. @inlinable @inline(__always) public static func resourceApplyFtrl( - var_: ResourceHandle, - accum: ResourceHandle, - linear: ResourceHandle, - grad: Tensor, - lr: Tensor, - l1: Tensor, - l2: Tensor, - lrPower: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + accum: ResourceHandle, + linear: ResourceHandle, + grad: Tensor, + lr: Tensor, + l1: Tensor, + l2: Tensor, + lrPower: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyFtrl", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(accum) - op.addInput(linear) - op.addInput(grad) - op.addInput(lr) - op.addInput(l1) - op.addInput(l2) - op.addInput(lrPower) - op.execute() + let op = makeOp("ResourceApplyFtrl", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(linear) + op.addInput(grad) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(lrPower) + op.execute() } /// Update '*var' according to the Ftrl-proximal scheme. @@ -24303,71 +24147,71 @@ public static func resourceApplyFtrl( /// accum = accum_new /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - accum: Should be from a Variable(). -/// - linear: Should be from a Variable(). -/// - grad: The gradient. -/// - lr: Scaling factor. Must be a scalar. -/// - l1: L1 regulariation. Must be a scalar. -/// - l2: L2 shrinkage regulariation. Must be a scalar. -/// - lr_power: Scaling factor. Must be a scalar. +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - linear: Should be from a Variable(). +/// - grad: The gradient. +/// - lr: Scaling factor. Must be a scalar. +/// - l1: L1 regulariation. Must be a scalar. +/// - l2: L2 shrinkage regulariation. Must be a scalar. +/// - lr_power: Scaling factor. Must be a scalar. /// /// - Attr use_locking: If `True`, updating of the var and accum tensors will be protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. @inlinable @inline(__always) public static func resourceApplyFtrlV2( - var_: ResourceHandle, - accum: ResourceHandle, - linear: ResourceHandle, - grad: Tensor, - lr: Tensor, - l1: Tensor, - l2: Tensor, - l2Shrinkage: Tensor, - lrPower: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + accum: ResourceHandle, + linear: ResourceHandle, + grad: Tensor, + lr: Tensor, + l1: Tensor, + l2: Tensor, + l2Shrinkage: Tensor, + lrPower: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyFtrlV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(accum) - op.addInput(linear) - op.addInput(grad) - op.addInput(lr) - op.addInput(l1) - op.addInput(l2) - op.addInput(l2Shrinkage) - op.addInput(lrPower) - op.execute() + let op = makeOp("ResourceApplyFtrlV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(linear) + op.addInput(grad) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(l2Shrinkage) + op.addInput(lrPower) + op.execute() } /// Update '*var' by subtracting 'alpha' * 'delta' from it. /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - alpha: Scaling factor. Must be a scalar. -/// - delta: The change. +/// - var: Should be from a Variable(). +/// - alpha: Scaling factor. Must be a scalar. +/// - delta: The change. /// /// - Attr use_locking: If `True`, the subtraction will be protected by a lock; -/// otherwise the behavior is undefined, but may exhibit less contention. +/// otherwise the behavior is undefined, but may exhibit less contention. @inlinable @inline(__always) public static func resourceApplyGradientDescent( - var_: ResourceHandle, - alpha: Tensor, - delta: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + alpha: Tensor, + delta: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyGradientDescent", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(alpha) - op.addInput(delta) - op.execute() + let op = makeOp("ResourceApplyGradientDescent", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(alpha) + op.addInput(delta) + op.execute() } /// Update '*var' according to the momentum scheme. Set use_nesterov = True if you @@ -24378,40 +24222,40 @@ public static func resourceApplyGradientDescent( /// var += accum /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - accum: Should be from a Variable(). -/// - lr: Scaling factor. Must be a scalar. -/// - grad: The gradient. -/// - momentum: Momentum. Must be a scalar. +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - grad: The gradient. +/// - momentum: Momentum. Must be a scalar. /// /// - Attrs: -/// - use_locking: If `True`, updating of the var and accum tensors will be protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. -/// - use_nesterov: If `True`, the tensor passed to compute grad will be -/// var + momentum * accum, so in the end, the var you get is actually -/// var + momentum * accum. +/// - use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +/// - use_nesterov: If `True`, the tensor passed to compute grad will be +/// var + momentum * accum, so in the end, the var you get is actually +/// var + momentum * accum. @inlinable @inline(__always) public static func resourceApplyKerasMomentum( - var_: ResourceHandle, - accum: ResourceHandle, - lr: Tensor, - grad: Tensor, - momentum: Tensor, - useLocking: Bool = false, - useNesterov: Bool = false + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + grad: Tensor, + momentum: Tensor, + useLocking: Bool = false, + useNesterov: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyKerasMomentum", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.updateAttribute("use_nesterov", useNesterov) - op.addInput(var_) - op.addInput(accum) - op.addInput(lr) - op.addInput(grad) - op.addInput(momentum) - op.execute() + let op = makeOp("ResourceApplyKerasMomentum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("use_nesterov", useNesterov) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(grad) + op.addInput(momentum) + op.execute() } /// Update '*var' according to the momentum scheme. Set use_nesterov = True if you @@ -24422,40 +24266,40 @@ public static func resourceApplyKerasMomentum( /// var -= lr * accum /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - accum: Should be from a Variable(). -/// - lr: Scaling factor. Must be a scalar. -/// - grad: The gradient. -/// - momentum: Momentum. Must be a scalar. +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - grad: The gradient. +/// - momentum: Momentum. Must be a scalar. /// /// - Attrs: -/// - use_locking: If `True`, updating of the var and accum tensors will be protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. -/// - use_nesterov: If `True`, the tensor passed to compute grad will be -/// var - lr * momentum * accum, so in the end, the var you get is actually -/// var - lr * momentum * accum. +/// - use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +/// - use_nesterov: If `True`, the tensor passed to compute grad will be +/// var - lr * momentum * accum, so in the end, the var you get is actually +/// var - lr * momentum * accum. @inlinable @inline(__always) public static func resourceApplyMomentum( - var_: ResourceHandle, - accum: ResourceHandle, - lr: Tensor, - grad: Tensor, - momentum: Tensor, - useLocking: Bool = false, - useNesterov: Bool = false + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + grad: Tensor, + momentum: Tensor, + useLocking: Bool = false, + useNesterov: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyMomentum", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.updateAttribute("use_nesterov", useNesterov) - op.addInput(var_) - op.addInput(accum) - op.addInput(lr) - op.addInput(grad) - op.addInput(momentum) - op.execute() + let op = makeOp("ResourceApplyMomentum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("use_nesterov", useNesterov) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(grad) + op.addInput(momentum) + op.execute() } /// Update '*var' according to the AddSign update. @@ -24465,40 +24309,40 @@ public static func resourceApplyMomentum( /// variable <- variable - lr_t * update /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - m: Should be from a Variable(). -/// - lr: Scaling factor. Must be a scalar. -/// - logbase: Must be a scalar. -/// - sign_decay: Must be a scalar. -/// - beta: Must be a scalar. -/// - grad: The gradient. +/// - var: Should be from a Variable(). +/// - m: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - logbase: Must be a scalar. +/// - sign_decay: Must be a scalar. +/// - beta: Must be a scalar. +/// - grad: The gradient. /// /// - Attr use_locking: If `True`, updating of the var and m tensors is -/// protected by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. +/// protected by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. @inlinable @inline(__always) public static func resourceApplyPowerSign( - var_: ResourceHandle, - m: ResourceHandle, - lr: Tensor, - logbase: Tensor, - signDecay: Tensor, - beta: Tensor, - grad: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + m: ResourceHandle, + lr: Tensor, + logbase: Tensor, + signDecay: Tensor, + beta: Tensor, + grad: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyPowerSign", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(m) - op.addInput(lr) - op.addInput(logbase) - op.addInput(signDecay) - op.addInput(beta) - op.addInput(grad) - op.execute() + let op = makeOp("ResourceApplyPowerSign", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(m) + op.addInput(lr) + op.addInput(logbase) + op.addInput(signDecay) + op.addInput(beta) + op.addInput(grad) + op.execute() } /// Update '*var' and '*accum' according to FOBOS with Adagrad learning rate. @@ -24508,36 +24352,36 @@ public static func resourceApplyPowerSign( /// var = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0} /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - accum: Should be from a Variable(). -/// - lr: Scaling factor. Must be a scalar. -/// - l1: L1 regularization. Must be a scalar. -/// - l2: L2 regularization. Must be a scalar. -/// - grad: The gradient. +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - grad: The gradient. /// /// - Attr use_locking: If True, updating of the var and accum tensors will be protected by -/// a lock; otherwise the behavior is undefined, but may exhibit less contention. +/// a lock; otherwise the behavior is undefined, but may exhibit less contention. @inlinable @inline(__always) public static func resourceApplyProximalAdagrad( - var_: ResourceHandle, - accum: ResourceHandle, - lr: Tensor, - l1: Tensor, - l2: Tensor, - grad: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + l1: Tensor, + l2: Tensor, + grad: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyProximalAdagrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(accum) - op.addInput(lr) - op.addInput(l1) - op.addInput(l2) - op.addInput(grad) - op.execute() + let op = makeOp("ResourceApplyProximalAdagrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(grad) + op.execute() } /// Update '*var' as FOBOS algorithm with fixed learning rate. @@ -24546,33 +24390,33 @@ public static func resourceApplyProximalAdagrad( /// var = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0} /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - alpha: Scaling factor. Must be a scalar. -/// - l1: L1 regularization. Must be a scalar. -/// - l2: L2 regularization. Must be a scalar. -/// - delta: The change. +/// - var: Should be from a Variable(). +/// - alpha: Scaling factor. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - delta: The change. /// /// - Attr use_locking: If True, the subtraction will be protected by a lock; -/// otherwise the behavior is undefined, but may exhibit less contention. +/// otherwise the behavior is undefined, but may exhibit less contention. @inlinable @inline(__always) public static func resourceApplyProximalGradientDescent( - var_: ResourceHandle, - alpha: Tensor, - l1: Tensor, - l2: Tensor, - delta: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + alpha: Tensor, + l1: Tensor, + l2: Tensor, + delta: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyProximalGradientDescent", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(alpha) - op.addInput(l1) - op.addInput(l2) - op.addInput(delta) - op.execute() + let op = makeOp("ResourceApplyProximalGradientDescent", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(alpha) + op.addInput(l1) + op.addInput(l2) + op.addInput(delta) + op.execute() } /// Update '*var' according to the RMSProp algorithm. @@ -24589,42 +24433,42 @@ public static func resourceApplyProximalGradientDescent( - var_: ResourceHandle, - ms: ResourceHandle, - mom: ResourceHandle, - lr: Tensor, - rho: Tensor, - momentum: Tensor, - epsilon: Tensor, - grad: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + ms: ResourceHandle, + mom: ResourceHandle, + lr: Tensor, + rho: Tensor, + momentum: Tensor, + epsilon: Tensor, + grad: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceApplyRMSProp", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(ms) - op.addInput(mom) - op.addInput(lr) - op.addInput(rho) - op.addInput(momentum) - op.addInput(epsilon) - op.addInput(grad) - op.execute() + let op = makeOp("ResourceApplyRMSProp", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(ms) + op.addInput(mom) + op.addInput(lr) + op.addInput(rho) + op.addInput(momentum) + op.addInput(epsilon) + op.addInput(grad) + op.execute() } /// Increments variable pointed to by 'resource' until it reaches 'limit'. @@ -24632,31 +24476,31 @@ public static func resourceApplyRMSProp( /// - Parameter resource: Should be from a scalar `Variable` node. /// /// - Attr limit: If incrementing ref would bring it above limit, instead generates an -/// 'OutOfRange' error. +/// 'OutOfRange' error. /// /// - Output output: A copy of the input before increment. If nothing else modifies the -/// input, the values produced will all be distinct. +/// input, the values produced will all be distinct. @inlinable @inline(__always) public static func resourceCountUpTo( - resource: ResourceHandle, - limit: Int64 + resource: ResourceHandle, + limit: Int64 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ResourceCountUpTo", nOutputs) - op.updateAttribute("limit", limit) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(resource) - return op.execute(Int(1)) + let op = makeOp("ResourceCountUpTo", nOutputs) + op.updateAttribute("limit", limit) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(resource) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func resourceCreateOp( - resource: ResourceHandle + resource: ResourceHandle ) { let nOutputs = 0 - let op = makeOp("ResourceCreateOp", nOutputs) - op.addInput(resource) - op.execute() + let op = makeOp("ResourceCreateOp", nOutputs) + op.addInput(resource) + op.execute() } /// Gather slices from the variable pointed to by `resource` according to `indices`. @@ -24679,20 +24523,20 @@ public static func resourceGather< Dtype: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - resource: ResourceHandle, - indices: Tensor, - batchDims: Int64 = 0, - validateIndices: Bool = true + resource: ResourceHandle, + indices: Tensor, + batchDims: Int64 = 0, + validateIndices: Bool = true ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ResourceGather", nOutputs) - op.updateAttribute("batch_dims", batchDims) - op.updateAttribute("validate_indices", validateIndices) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(resource) - op.addInput(indices) - return op.execute(Int(1)) + let op = makeOp("ResourceGather", nOutputs) + op.updateAttribute("batch_dims", batchDims) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + return op.execute(Int(1)) } @inlinable @inline(__always) @@ -24700,26 +24544,26 @@ public static func resourceGatherNd< Dtype: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - resource: ResourceHandle, - indices: Tensor + resource: ResourceHandle, + indices: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ResourceGatherNd", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(resource) - op.addInput(indices) - return op.execute(Int(1)) + let op = makeOp("ResourceGatherNd", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func resourceInitializedOp( - resource: ResourceHandle + resource: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ResourceInitializedOp", nOutputs) - op.addInput(resource) - return op.execute(Int(1)) + let op = makeOp("ResourceInitializedOp", nOutputs) + op.addInput(resource) + return op.execute(Int(1)) } /// Adds sparse updates to the variable referenced by `resource`. @@ -24745,26 +24589,26 @@ public static func resourceInitializedOp( /// /// /// - Parameters: -/// - resource: Should be from a `Variable` node. -/// - indices: A tensor of indices into the first dimension of `ref`. -/// - updates: A tensor of updated values to add to `ref`. +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. @inlinable @inline(__always) public static func resourceScatterAdd< Dtype: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - resource: ResourceHandle, - indices: Tensor, - updates: Tensor + resource: ResourceHandle, + indices: Tensor, + updates: Tensor ) { let nOutputs = 0 - let op = makeOp("ResourceScatterAdd", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(resource) - op.addInput(indices) - op.addInput(updates) - op.execute() + let op = makeOp("ResourceScatterAdd", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() } /// Divides sparse updates into the variable referenced by `resource`. @@ -24790,26 +24634,26 @@ public static func resourceScatterAdd< /// /// /// - Parameters: -/// - resource: Should be from a `Variable` node. -/// - indices: A tensor of indices into the first dimension of `ref`. -/// - updates: A tensor of updated values to add to `ref`. +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. @inlinable @inline(__always) public static func resourceScatterDiv< Dtype: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - resource: ResourceHandle, - indices: Tensor, - updates: Tensor + resource: ResourceHandle, + indices: Tensor, + updates: Tensor ) { let nOutputs = 0 - let op = makeOp("ResourceScatterDiv", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(resource) - op.addInput(indices) - op.addInput(updates) - op.execute() + let op = makeOp("ResourceScatterDiv", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() } /// Reduces sparse updates into the variable referenced by `resource` using the `max` operation. @@ -24835,26 +24679,26 @@ public static func resourceScatterDiv< /// /// /// - Parameters: -/// - resource: Should be from a `Variable` node. -/// - indices: A tensor of indices into the first dimension of `ref`. -/// - updates: A tensor of updated values to add to `ref`. +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. @inlinable @inline(__always) public static func resourceScatterMax< Dtype: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - resource: ResourceHandle, - indices: Tensor, - updates: Tensor + resource: ResourceHandle, + indices: Tensor, + updates: Tensor ) { let nOutputs = 0 - let op = makeOp("ResourceScatterMax", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(resource) - op.addInput(indices) - op.addInput(updates) - op.execute() + let op = makeOp("ResourceScatterMax", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() } /// Reduces sparse updates into the variable referenced by `resource` using the `min` operation. @@ -24880,26 +24724,26 @@ public static func resourceScatterMax< /// /// /// - Parameters: -/// - resource: Should be from a `Variable` node. -/// - indices: A tensor of indices into the first dimension of `ref`. -/// - updates: A tensor of updated values to add to `ref`. +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. @inlinable @inline(__always) public static func resourceScatterMin< Dtype: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - resource: ResourceHandle, - indices: Tensor, - updates: Tensor + resource: ResourceHandle, + indices: Tensor, + updates: Tensor ) { let nOutputs = 0 - let op = makeOp("ResourceScatterMin", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(resource) - op.addInput(indices) - op.addInput(updates) - op.execute() + let op = makeOp("ResourceScatterMin", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() } /// Multiplies sparse updates into the variable referenced by `resource`. @@ -24925,26 +24769,26 @@ public static func resourceScatterMin< /// /// /// - Parameters: -/// - resource: Should be from a `Variable` node. -/// - indices: A tensor of indices into the first dimension of `ref`. -/// - updates: A tensor of updated values to add to `ref`. +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. @inlinable @inline(__always) public static func resourceScatterMul< Dtype: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - resource: ResourceHandle, - indices: Tensor, - updates: Tensor + resource: ResourceHandle, + indices: Tensor, + updates: Tensor ) { let nOutputs = 0 - let op = makeOp("ResourceScatterMul", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(resource) - op.addInput(indices) - op.addInput(updates) - op.execute() + let op = makeOp("ResourceScatterMul", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() } /// Applies sparse addition to individual values or slices in a Variable. @@ -24984,34 +24828,34 @@ public static func resourceScatterMul< /// slices. /// /// - Parameters: -/// - ref: A resource handle. Must be from a VarHandleOp. -/// - indices: A Tensor. Must be one of the following types: int32, int64. -/// A tensor of indices into ref. -/// - updates: A Tensor. Must have the same type as ref. A tensor of -/// values to add to ref. +/// - ref: A resource handle. Must be from a VarHandleOp. +/// - indices: A Tensor. Must be one of the following types: int32, int64. +/// A tensor of indices into ref. +/// - updates: A Tensor. Must have the same type as ref. A tensor of +/// values to add to ref. /// /// - Attr use_locking: An optional bool. Defaults to True. If True, the assignment will -/// be protected by a lock; otherwise the behavior is undefined, -/// but may exhibit less contention. +/// be protected by a lock; otherwise the behavior is undefined, +/// but may exhibit less contention. @inlinable @inline(__always) public static func resourceScatterNdAdd< T: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - ref: ResourceHandle, - indices: Tensor, - updates: Tensor, - useLocking: Bool = true + ref: ResourceHandle, + indices: Tensor, + updates: Tensor, + useLocking: Bool = true ) { let nOutputs = 0 - let op = makeOp("ResourceScatterNdAdd", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(ref) - op.addInput(indices) - op.addInput(updates) - op.execute() + let op = makeOp("ResourceScatterNdAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(ref) + op.addInput(indices) + op.addInput(updates) + op.execute() } /// Applies sparse subtraction to individual values or slices in a Variable. @@ -25051,34 +24895,34 @@ public static func resourceScatterNdAdd< /// slices. /// /// - Parameters: -/// - ref: A resource handle. Must be from a VarHandleOp. -/// - indices: A Tensor. Must be one of the following types: int32, int64. -/// A tensor of indices into ref. -/// - updates: A Tensor. Must have the same type as ref. A tensor of -/// values to add to ref. +/// - ref: A resource handle. Must be from a VarHandleOp. +/// - indices: A Tensor. Must be one of the following types: int32, int64. +/// A tensor of indices into ref. +/// - updates: A Tensor. Must have the same type as ref. A tensor of +/// values to add to ref. /// /// - Attr use_locking: An optional bool. Defaults to True. If True, the assignment will -/// be protected by a lock; otherwise the behavior is undefined, -/// but may exhibit less contention. +/// be protected by a lock; otherwise the behavior is undefined, +/// but may exhibit less contention. @inlinable @inline(__always) public static func resourceScatterNdSub< T: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - ref: ResourceHandle, - indices: Tensor, - updates: Tensor, - useLocking: Bool = true + ref: ResourceHandle, + indices: Tensor, + updates: Tensor, + useLocking: Bool = true ) { let nOutputs = 0 - let op = makeOp("ResourceScatterNdSub", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(ref) - op.addInput(indices) - op.addInput(updates) - op.execute() + let op = makeOp("ResourceScatterNdSub", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(ref) + op.addInput(indices) + op.addInput(updates) + op.execute() } /// Applies sparse `updates` to individual values or slices within a given @@ -25120,34 +24964,34 @@ public static func resourceScatterNdSub< /// slices. /// /// - Parameters: -/// - ref: A resource handle. Must be from a VarHandleOp. -/// - indices: A Tensor. Must be one of the following types: int32, int64. -/// A tensor of indices into ref. -/// - updates: A Tensor. Must have the same type as ref. A tensor of updated -/// values to add to ref. +/// - ref: A resource handle. Must be from a VarHandleOp. +/// - indices: A Tensor. Must be one of the following types: int32, int64. +/// A tensor of indices into ref. +/// - updates: A Tensor. Must have the same type as ref. A tensor of updated +/// values to add to ref. /// /// - Attr use_locking: An optional bool. Defaults to True. If True, the assignment will -/// be protected by a lock; otherwise the behavior is undefined, -/// but may exhibit less contention. +/// be protected by a lock; otherwise the behavior is undefined, +/// but may exhibit less contention. @inlinable @inline(__always) public static func resourceScatterNdUpdate< T: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - ref: ResourceHandle, - indices: Tensor, - updates: Tensor, - useLocking: Bool = true + ref: ResourceHandle, + indices: Tensor, + updates: Tensor, + useLocking: Bool = true ) { let nOutputs = 0 - let op = makeOp("ResourceScatterNdUpdate", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(ref) - op.addInput(indices) - op.addInput(updates) - op.execute() + let op = makeOp("ResourceScatterNdUpdate", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(ref) + op.addInput(indices) + op.addInput(updates) + op.execute() } /// Subtracts sparse updates from the variable referenced by `resource`. @@ -25173,26 +25017,26 @@ public static func resourceScatterNdUpdate< /// /// /// - Parameters: -/// - resource: Should be from a `Variable` node. -/// - indices: A tensor of indices into the first dimension of `ref`. -/// - updates: A tensor of updated values to add to `ref`. +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. @inlinable @inline(__always) public static func resourceScatterSub< Dtype: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - resource: ResourceHandle, - indices: Tensor, - updates: Tensor + resource: ResourceHandle, + indices: Tensor, + updates: Tensor ) { let nOutputs = 0 - let op = makeOp("ResourceScatterSub", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(resource) - op.addInput(indices) - op.addInput(updates) - op.execute() + let op = makeOp("ResourceScatterSub", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() } /// Assigns sparse updates to the variable referenced by `resource`. @@ -25209,70 +25053,70 @@ public static func resourceScatterSub< /// ref[indices[i, ..., j], ...] = updates[i, ..., j, ...] /// /// - Parameters: -/// - resource: Should be from a `Variable` node. -/// - indices: A tensor of indices into the first dimension of `ref`. -/// - updates: A tensor of updated values to add to `ref`. +/// - resource: Should be from a `Variable` node. +/// - indices: A tensor of indices into the first dimension of `ref`. +/// - updates: A tensor of updated values to add to `ref`. @inlinable @inline(__always) public static func resourceScatterUpdate< Dtype: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - resource: ResourceHandle, - indices: Tensor, - updates: Tensor + resource: ResourceHandle, + indices: Tensor, + updates: Tensor ) { let nOutputs = 0 - let op = makeOp("ResourceScatterUpdate", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(resource) - op.addInput(indices) - op.addInput(updates) - op.execute() + let op = makeOp("ResourceScatterUpdate", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(resource) + op.addInput(indices) + op.addInput(updates) + op.execute() } /// var: Should be from a Variable(). /// /// - Parameters: -/// - accum: Should be from a Variable(). -/// - accum_update: : Should be from a Variable(). -/// - lr: Learning rate. Must be a scalar. -/// - rho: Decay factor. Must be a scalar. -/// - epsilon: Constant factor. Must be a scalar. -/// - grad: The gradient. -/// - indices: A vector of indices into the first dimension of var and accum. +/// - accum: Should be from a Variable(). +/// - accum_update: : Should be from a Variable(). +/// - lr: Learning rate. Must be a scalar. +/// - rho: Decay factor. Must be a scalar. +/// - epsilon: Constant factor. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. /// /// - Attr use_locking: If True, updating of the var and accum tensors will be protected by -/// a lock; otherwise the behavior is undefined, but may exhibit less contention. +/// a lock; otherwise the behavior is undefined, but may exhibit less contention. @inlinable @inline(__always) public static func resourceSparseApplyAdadelta< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - var_: ResourceHandle, - accum: ResourceHandle, - accumUpdate: ResourceHandle, - lr: Tensor, - rho: Tensor, - epsilon: Tensor, - grad: Tensor, - indices: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + accum: ResourceHandle, + accumUpdate: ResourceHandle, + lr: Tensor, + rho: Tensor, + epsilon: Tensor, + grad: Tensor, + indices: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceSparseApplyAdadelta", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(accum) - op.addInput(accumUpdate) - op.addInput(lr) - op.addInput(rho) - op.addInput(epsilon) - op.addInput(grad) - op.addInput(indices) - op.execute() + let op = makeOp("ResourceSparseApplyAdadelta", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(accumUpdate) + op.addInput(lr) + op.addInput(rho) + op.addInput(epsilon) + op.addInput(grad) + op.addInput(indices) + op.execute() } /// Update relevant entries in '*var' and '*accum' according to the adagrad scheme. @@ -25282,88 +25126,88 @@ public static func resourceSparseApplyAdadelta< /// var -= lr * grad * (1 / sqrt(accum)) /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - accum: Should be from a Variable(). -/// - lr: Learning rate. Must be a scalar. -/// - grad: The gradient. -/// - indices: A vector of indices into the first dimension of var and accum. +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Learning rate. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. /// /// - Attr use_locking: If `True`, updating of the var and accum tensors will be protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. @inlinable @inline(__always) public static func resourceSparseApplyAdagrad< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - var_: ResourceHandle, - accum: ResourceHandle, - lr: Tensor, - grad: Tensor, - indices: Tensor, - useLocking: Bool = false, - updateSlots: Bool = true + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + grad: Tensor, + indices: Tensor, + useLocking: Bool = false, + updateSlots: Bool = true ) { let nOutputs = 0 - let op = makeOp("ResourceSparseApplyAdagrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.updateAttribute("update_slots", updateSlots) - op.addInput(var_) - op.addInput(accum) - op.addInput(lr) - op.addInput(grad) - op.addInput(indices) - op.execute() + let op = makeOp("ResourceSparseApplyAdagrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("update_slots", updateSlots) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(grad) + op.addInput(indices) + op.execute() } /// Update entries in '*var' and '*accum' according to the proximal adagrad scheme. /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - gradient_accumulator: Should be from a Variable(). -/// - gradient_squared_accumulator: Should be from a Variable(). -/// - grad: The gradient. -/// - indices: A vector of indices into the first dimension of var and accum. -/// - lr: Learning rate. Must be a scalar. -/// - l1: L1 regularization. Must be a scalar. -/// - l2: L2 regularization. Must be a scalar. -/// - global_step: Training step number. Must be a scalar. +/// - var: Should be from a Variable(). +/// - gradient_accumulator: Should be from a Variable(). +/// - gradient_squared_accumulator: Should be from a Variable(). +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// - lr: Learning rate. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - global_step: Training step number. Must be a scalar. /// /// - Attr use_locking: If True, updating of the var and accum tensors will be protected by -/// a lock; otherwise the behavior is undefined, but may exhibit less contention. +/// a lock; otherwise the behavior is undefined, but may exhibit less contention. @inlinable @inline(__always) public static func resourceSparseApplyAdagradDA< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - var_: ResourceHandle, - gradientAccumulator: ResourceHandle, - gradientSquaredAccumulator: ResourceHandle, - grad: Tensor, - indices: Tensor, - lr: Tensor, - l1: Tensor, - l2: Tensor, - globalStep: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + gradientAccumulator: ResourceHandle, + gradientSquaredAccumulator: ResourceHandle, + grad: Tensor, + indices: Tensor, + lr: Tensor, + l1: Tensor, + l2: Tensor, + globalStep: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceSparseApplyAdagradDA", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(gradientAccumulator) - op.addInput(gradientSquaredAccumulator) - op.addInput(grad) - op.addInput(indices) - op.addInput(lr) - op.addInput(l1) - op.addInput(l2) - op.addInput(globalStep) - op.execute() + let op = makeOp("ResourceSparseApplyAdagradDA", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(gradientAccumulator) + op.addInput(gradientSquaredAccumulator) + op.addInput(grad) + op.addInput(indices) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(globalStep) + op.execute() } /// Update '*var' according to the centered RMSProp algorithm. @@ -25386,52 +25230,52 @@ public static func resourceSparseApplyAdagradDA< /// var <- var - mom /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - mg: Should be from a Variable(). -/// - ms: Should be from a Variable(). -/// - mom: Should be from a Variable(). -/// - lr: Scaling factor. Must be a scalar. -/// - rho: Decay rate. Must be a scalar. -/// - epsilon: Ridge term. Must be a scalar. -/// - grad: The gradient. -/// - indices: A vector of indices into the first dimension of var, ms and mom. +/// - var: Should be from a Variable(). +/// - mg: Should be from a Variable(). +/// - ms: Should be from a Variable(). +/// - mom: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - rho: Decay rate. Must be a scalar. +/// - epsilon: Ridge term. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var, ms and mom. /// /// - Attr use_locking: If `True`, updating of the var, mg, ms, and mom tensors is -/// protected by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. +/// protected by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. @inlinable @inline(__always) public static func resourceSparseApplyCenteredRMSProp< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - var_: ResourceHandle, - mg: ResourceHandle, - ms: ResourceHandle, - mom: ResourceHandle, - lr: Tensor, - rho: Tensor, - momentum: Tensor, - epsilon: Tensor, - grad: Tensor, - indices: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + mg: ResourceHandle, + ms: ResourceHandle, + mom: ResourceHandle, + lr: Tensor, + rho: Tensor, + momentum: Tensor, + epsilon: Tensor, + grad: Tensor, + indices: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceSparseApplyCenteredRMSProp", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(mg) - op.addInput(ms) - op.addInput(mom) - op.addInput(lr) - op.addInput(rho) - op.addInput(momentum) - op.addInput(epsilon) - op.addInput(grad) - op.addInput(indices) - op.execute() + let op = makeOp("ResourceSparseApplyCenteredRMSProp", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(mg) + op.addInput(ms) + op.addInput(mom) + op.addInput(lr) + op.addInput(rho) + op.addInput(momentum) + op.addInput(epsilon) + op.addInput(grad) + op.addInput(indices) + op.execute() } /// Update relevant entries in '*var' according to the Ftrl-proximal scheme. @@ -25444,50 +25288,50 @@ public static func resourceSparseApplyCenteredRMSProp< /// accum = accum_new /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - accum: Should be from a Variable(). -/// - linear: Should be from a Variable(). -/// - grad: The gradient. -/// - indices: A vector of indices into the first dimension of var and accum. -/// - lr: Scaling factor. Must be a scalar. -/// - l1: L1 regularization. Must be a scalar. -/// - l2: L2 regularization. Must be a scalar. -/// - lr_power: Scaling factor. Must be a scalar. +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - linear: Should be from a Variable(). +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// - lr: Scaling factor. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - lr_power: Scaling factor. Must be a scalar. /// /// - Attr use_locking: If `True`, updating of the var and accum tensors will be protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. @inlinable @inline(__always) public static func resourceSparseApplyFtrl< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - var_: ResourceHandle, - accum: ResourceHandle, - linear: ResourceHandle, - grad: Tensor, - indices: Tensor, - lr: Tensor, - l1: Tensor, - l2: Tensor, - lrPower: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + accum: ResourceHandle, + linear: ResourceHandle, + grad: Tensor, + indices: Tensor, + lr: Tensor, + l1: Tensor, + l2: Tensor, + lrPower: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceSparseApplyFtrl", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(accum) - op.addInput(linear) - op.addInput(grad) - op.addInput(indices) - op.addInput(lr) - op.addInput(l1) - op.addInput(l2) - op.addInput(lrPower) - op.execute() + let op = makeOp("ResourceSparseApplyFtrl", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(linear) + op.addInput(grad) + op.addInput(indices) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(lrPower) + op.execute() } /// Update relevant entries in '*var' according to the Ftrl-proximal scheme. @@ -25502,52 +25346,52 @@ public static func resourceSparseApplyFtrl< /// accum = accum_new /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - accum: Should be from a Variable(). -/// - linear: Should be from a Variable(). -/// - grad: The gradient. -/// - indices: A vector of indices into the first dimension of var and accum. -/// - lr: Scaling factor. Must be a scalar. -/// - l1: L1 regularization. Must be a scalar. -/// - l2: L2 shrinkage regulariation. Must be a scalar. -/// - lr_power: Scaling factor. Must be a scalar. +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - linear: Should be from a Variable(). +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// - lr: Scaling factor. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 shrinkage regulariation. Must be a scalar. +/// - lr_power: Scaling factor. Must be a scalar. /// /// - Attr use_locking: If `True`, updating of the var and accum tensors will be protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. @inlinable @inline(__always) public static func resourceSparseApplyFtrlV2< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - var_: ResourceHandle, - accum: ResourceHandle, - linear: ResourceHandle, - grad: Tensor, - indices: Tensor, - lr: Tensor, - l1: Tensor, - l2: Tensor, - l2Shrinkage: Tensor, - lrPower: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + accum: ResourceHandle, + linear: ResourceHandle, + grad: Tensor, + indices: Tensor, + lr: Tensor, + l1: Tensor, + l2: Tensor, + l2Shrinkage: Tensor, + lrPower: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceSparseApplyFtrlV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(accum) - op.addInput(linear) - op.addInput(grad) - op.addInput(indices) - op.addInput(lr) - op.addInput(l1) - op.addInput(l2) - op.addInput(l2Shrinkage) - op.addInput(lrPower) - op.execute() + let op = makeOp("ResourceSparseApplyFtrlV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(linear) + op.addInput(grad) + op.addInput(indices) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(l2Shrinkage) + op.addInput(lrPower) + op.execute() } /// Update relevant entries in '*var' and '*accum' according to the momentum scheme. @@ -25560,47 +25404,47 @@ public static func resourceSparseApplyFtrlV2< /// var += accum /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - accum: Should be from a Variable(). -/// - lr: Learning rate. Must be a scalar. -/// - grad: The gradient. -/// - indices: A vector of indices into the first dimension of var and accum. -/// - momentum: Momentum. Must be a scalar. +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Learning rate. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// - momentum: Momentum. Must be a scalar. /// /// - Attrs: -/// - use_locking: If `True`, updating of the var and accum tensors will be protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. -/// - use_nesterov: If `True`, the tensor passed to compute grad will be -/// var + momentum * accum, so in the end, the var you get is actually -/// var + momentum * accum. +/// - use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +/// - use_nesterov: If `True`, the tensor passed to compute grad will be +/// var + momentum * accum, so in the end, the var you get is actually +/// var + momentum * accum. @inlinable @inline(__always) public static func resourceSparseApplyKerasMomentum< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - var_: ResourceHandle, - accum: ResourceHandle, - lr: Tensor, - grad: Tensor, - indices: Tensor, - momentum: Tensor, - useLocking: Bool = false, - useNesterov: Bool = false + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + grad: Tensor, + indices: Tensor, + momentum: Tensor, + useLocking: Bool = false, + useNesterov: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceSparseApplyKerasMomentum", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.updateAttribute("use_nesterov", useNesterov) - op.addInput(var_) - op.addInput(accum) - op.addInput(lr) - op.addInput(grad) - op.addInput(indices) - op.addInput(momentum) - op.execute() + let op = makeOp("ResourceSparseApplyKerasMomentum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("use_nesterov", useNesterov) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(grad) + op.addInput(indices) + op.addInput(momentum) + op.execute() } /// Update relevant entries in '*var' and '*accum' according to the momentum scheme. @@ -25613,47 +25457,47 @@ public static func resourceSparseApplyKerasMomentum< /// var -= lr * accum /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - accum: Should be from a Variable(). -/// - lr: Learning rate. Must be a scalar. -/// - grad: The gradient. -/// - indices: A vector of indices into the first dimension of var and accum. -/// - momentum: Momentum. Must be a scalar. +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Learning rate. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. +/// - momentum: Momentum. Must be a scalar. /// /// - Attrs: -/// - use_locking: If `True`, updating of the var and accum tensors will be protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. -/// - use_nesterov: If `True`, the tensor passed to compute grad will be -/// var - lr * momentum * accum, so in the end, the var you get is actually -/// var - lr * momentum * accum. +/// - use_locking: If `True`, updating of the var and accum tensors will be protected +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. +/// - use_nesterov: If `True`, the tensor passed to compute grad will be +/// var - lr * momentum * accum, so in the end, the var you get is actually +/// var - lr * momentum * accum. @inlinable @inline(__always) public static func resourceSparseApplyMomentum< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - var_: ResourceHandle, - accum: ResourceHandle, - lr: Tensor, - grad: Tensor, - indices: Tensor, - momentum: Tensor, - useLocking: Bool = false, - useNesterov: Bool = false + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + grad: Tensor, + indices: Tensor, + momentum: Tensor, + useLocking: Bool = false, + useNesterov: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceSparseApplyMomentum", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.updateAttribute("use_nesterov", useNesterov) - op.addInput(var_) - op.addInput(accum) - op.addInput(lr) - op.addInput(grad) - op.addInput(indices) - op.addInput(momentum) - op.execute() + let op = makeOp("ResourceSparseApplyMomentum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.updateAttribute("use_nesterov", useNesterov) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(grad) + op.addInput(indices) + op.addInput(momentum) + op.execute() } /// Sparse update entries in '*var' and '*accum' according to FOBOS algorithm. @@ -25665,43 +25509,43 @@ public static func resourceSparseApplyMomentum< /// var = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0} /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - accum: Should be from a Variable(). -/// - lr: Learning rate. Must be a scalar. -/// - l1: L1 regularization. Must be a scalar. -/// - l2: L2 regularization. Must be a scalar. -/// - grad: The gradient. -/// - indices: A vector of indices into the first dimension of var and accum. +/// - var: Should be from a Variable(). +/// - accum: Should be from a Variable(). +/// - lr: Learning rate. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. /// /// - Attr use_locking: If True, updating of the var and accum tensors will be protected by -/// a lock; otherwise the behavior is undefined, but may exhibit less contention. +/// a lock; otherwise the behavior is undefined, but may exhibit less contention. @inlinable @inline(__always) public static func resourceSparseApplyProximalAdagrad< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - var_: ResourceHandle, - accum: ResourceHandle, - lr: Tensor, - l1: Tensor, - l2: Tensor, - grad: Tensor, - indices: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + accum: ResourceHandle, + lr: Tensor, + l1: Tensor, + l2: Tensor, + grad: Tensor, + indices: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceSparseApplyProximalAdagrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(accum) - op.addInput(lr) - op.addInput(l1) - op.addInput(l2) - op.addInput(grad) - op.addInput(indices) - op.execute() + let op = makeOp("ResourceSparseApplyProximalAdagrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(accum) + op.addInput(lr) + op.addInput(l1) + op.addInput(l2) + op.addInput(grad) + op.addInput(indices) + op.execute() } /// Sparse update '*var' as FOBOS algorithm with fixed learning rate. @@ -25711,40 +25555,40 @@ public static func resourceSparseApplyProximalAdagrad< /// var = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0} /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - alpha: Scaling factor. Must be a scalar. -/// - l1: L1 regularization. Must be a scalar. -/// - l2: L2 regularization. Must be a scalar. -/// - grad: The gradient. -/// - indices: A vector of indices into the first dimension of var and accum. +/// - var: Should be from a Variable(). +/// - alpha: Scaling factor. Must be a scalar. +/// - l1: L1 regularization. Must be a scalar. +/// - l2: L2 regularization. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var and accum. /// /// - Attr use_locking: If True, the subtraction will be protected by a lock; -/// otherwise the behavior is undefined, but may exhibit less contention. +/// otherwise the behavior is undefined, but may exhibit less contention. @inlinable @inline(__always) public static func resourceSparseApplyProximalGradientDescent< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - var_: ResourceHandle, - alpha: Tensor, - l1: Tensor, - l2: Tensor, - grad: Tensor, - indices: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + alpha: Tensor, + l1: Tensor, + l2: Tensor, + grad: Tensor, + indices: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceSparseApplyProximalGradientDescent", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(alpha) - op.addInput(l1) - op.addInput(l2) - op.addInput(grad) - op.addInput(indices) - op.execute() + let op = makeOp("ResourceSparseApplyProximalGradientDescent", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(alpha) + op.addInput(l1) + op.addInput(l2) + op.addInput(grad) + op.addInput(indices) + op.execute() } /// Update '*var' according to the RMSProp algorithm. @@ -25761,49 +25605,49 @@ public static func resourceSparseApplyProximalGradientDescent< /// var <- var - mom /// /// - Parameters: -/// - var: Should be from a Variable(). -/// - ms: Should be from a Variable(). -/// - mom: Should be from a Variable(). -/// - lr: Scaling factor. Must be a scalar. -/// - rho: Decay rate. Must be a scalar. -/// - epsilon: Ridge term. Must be a scalar. -/// - grad: The gradient. -/// - indices: A vector of indices into the first dimension of var, ms and mom. +/// - var: Should be from a Variable(). +/// - ms: Should be from a Variable(). +/// - mom: Should be from a Variable(). +/// - lr: Scaling factor. Must be a scalar. +/// - rho: Decay rate. Must be a scalar. +/// - epsilon: Ridge term. Must be a scalar. +/// - grad: The gradient. +/// - indices: A vector of indices into the first dimension of var, ms and mom. /// /// - Attr use_locking: If `True`, updating of the var, ms, and mom tensors is protected -/// by a lock; otherwise the behavior is undefined, but may exhibit less -/// contention. +/// by a lock; otherwise the behavior is undefined, but may exhibit less +/// contention. @inlinable @inline(__always) public static func resourceSparseApplyRMSProp< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - var_: ResourceHandle, - ms: ResourceHandle, - mom: ResourceHandle, - lr: Tensor, - rho: Tensor, - momentum: Tensor, - epsilon: Tensor, - grad: Tensor, - indices: Tensor, - useLocking: Bool = false + var_: ResourceHandle, + ms: ResourceHandle, + mom: ResourceHandle, + lr: Tensor, + rho: Tensor, + momentum: Tensor, + epsilon: Tensor, + grad: Tensor, + indices: Tensor, + useLocking: Bool = false ) { let nOutputs = 0 - let op = makeOp("ResourceSparseApplyRMSProp", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("use_locking", useLocking) - op.addInput(var_) - op.addInput(ms) - op.addInput(mom) - op.addInput(lr) - op.addInput(rho) - op.addInput(momentum) - op.addInput(epsilon) - op.addInput(grad) - op.addInput(indices) - op.execute() + let op = makeOp("ResourceSparseApplyRMSProp", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("use_locking", useLocking) + op.addInput(var_) + op.addInput(ms) + op.addInput(mom) + op.addInput(lr) + op.addInput(rho) + op.addInput(momentum) + op.addInput(epsilon) + op.addInput(grad) + op.addInput(indices) + op.execute() } /// Assign `value` to the sliced l-value reference of `ref`. @@ -25819,42 +25663,42 @@ public static func resourceStridedSliceAssign< T: TensorFlowScalar, Index: BinaryInteger & TensorFlowScalar >( - ref: ResourceHandle, - begin: Tensor, - end: Tensor, - strides: Tensor, - value: Tensor, - beginMask: Int64 = 0, - endMask: Int64 = 0, - ellipsisMask: Int64 = 0, - newAxisMask: Int64 = 0, - shrinkAxisMask: Int64 = 0 + ref: ResourceHandle, + begin: Tensor, + end: Tensor, + strides: Tensor, + value: Tensor, + beginMask: Int64 = 0, + endMask: Int64 = 0, + ellipsisMask: Int64 = 0, + newAxisMask: Int64 = 0, + shrinkAxisMask: Int64 = 0 ) { let nOutputs = 0 - let op = makeOp("ResourceStridedSliceAssign", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Index", Index.tensorFlowDataType) - op.updateAttribute("begin_mask", beginMask) - op.updateAttribute("end_mask", endMask) - op.updateAttribute("ellipsis_mask", ellipsisMask) - op.updateAttribute("new_axis_mask", newAxisMask) - op.updateAttribute("shrink_axis_mask", shrinkAxisMask) - op.addInput(ref) - op.addInput(begin) - op.addInput(end) - op.addInput(strides) - op.addInput(value) - op.execute() + let op = makeOp("ResourceStridedSliceAssign", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Index", Index.tensorFlowDataType) + op.updateAttribute("begin_mask", beginMask) + op.updateAttribute("end_mask", endMask) + op.updateAttribute("ellipsis_mask", ellipsisMask) + op.updateAttribute("new_axis_mask", newAxisMask) + op.updateAttribute("shrink_axis_mask", shrinkAxisMask) + op.addInput(ref) + op.addInput(begin) + op.addInput(end) + op.addInput(strides) + op.addInput(value) + op.execute() } @inlinable @inline(__always) public static func resourceUsingOp( - resource: ResourceHandle + resource: ResourceHandle ) { let nOutputs = 0 - let op = makeOp("ResourceUsingOp", nOutputs) - op.addInput(resource) - op.execute() + let op = makeOp("ResourceUsingOp", nOutputs) + op.addInput(resource) + op.execute() } /// Restores a tensor from checkpoint files. @@ -25877,30 +25721,30 @@ public static func resourceUsingOp( /// See also `RestoreSlice`. /// /// - Parameters: -/// - file_pattern: Must have a single element. The pattern of the files from -/// which we read the tensor. -/// - tensor_name: Must have a single element. The name of the tensor to be -/// restored. +/// - file_pattern: Must have a single element. The pattern of the files from +/// which we read the tensor. +/// - tensor_name: Must have a single element. The name of the tensor to be +/// restored. /// /// - Attrs: -/// - dt: The type of the tensor to be restored. -/// - preferred_shard: Index of file to open first if multiple files match -/// `file_pattern`. +/// - dt: The type of the tensor to be restored. +/// - preferred_shard: Index of file to open first if multiple files match +/// `file_pattern`. /// /// - Output tensor: The restored tensor. @inlinable @inline(__always) public static func restore( - filePattern: StringTensor, - tensorName: StringTensor, - preferredShard: Int64 = -1 + filePattern: StringTensor, + tensorName: StringTensor, + preferredShard: Int64 = -1 ) -> Tensor
{ let nOutputs = Int(1) - let op = makeOp("Restore", nOutputs) - op.updateAttribute("dt", Dt.tensorFlowDataType) - op.updateAttribute("preferred_shard", preferredShard) - op.addInput(filePattern) - op.addInput(tensorName) - return op.execute(Int(1)) + let op = makeOp("Restore", nOutputs) + op.updateAttribute("dt", Dt.tensorFlowDataType) + op.updateAttribute("preferred_shard", preferredShard) + op.addInput(filePattern) + op.addInput(tensorName) + return op.execute(Int(1)) } /// Restores a tensor from checkpoint files. @@ -25913,34 +25757,34 @@ public static func restore( /// elements of the `shapes_and_slices` input of the `SaveSlices` op. /// /// - Parameters: -/// - file_pattern: Must have a single element. The pattern of the files from -/// which we read the tensor. -/// - tensor_name: Must have a single element. The name of the tensor to be -/// restored. -/// - shape_and_slice: Scalar. The shapes and slice specifications to use when -/// restoring a tensors. +/// - file_pattern: Must have a single element. The pattern of the files from +/// which we read the tensor. +/// - tensor_name: Must have a single element. The name of the tensor to be +/// restored. +/// - shape_and_slice: Scalar. The shapes and slice specifications to use when +/// restoring a tensors. /// /// - Attrs: -/// - dt: The type of the tensor to be restored. -/// - preferred_shard: Index of file to open first if multiple files match -/// `file_pattern`. See the documentation for `Restore`. +/// - dt: The type of the tensor to be restored. +/// - preferred_shard: Index of file to open first if multiple files match +/// `file_pattern`. See the documentation for `Restore`. /// /// - Output tensor: The restored tensor. @inlinable @inline(__always) public static func restoreSlice( - filePattern: StringTensor, - tensorName: StringTensor, - shapeAndSlice: StringTensor, - preferredShard: Int64 = -1 + filePattern: StringTensor, + tensorName: StringTensor, + shapeAndSlice: StringTensor, + preferredShard: Int64 = -1 ) -> Tensor
{ let nOutputs = Int(1) - let op = makeOp("RestoreSlice", nOutputs) - op.updateAttribute("dt", Dt.tensorFlowDataType) - op.updateAttribute("preferred_shard", preferredShard) - op.addInput(filePattern) - op.addInput(tensorName) - op.addInput(shapeAndSlice) - return op.execute(Int(1)) + let op = makeOp("RestoreSlice", nOutputs) + op.updateAttribute("dt", Dt.tensorFlowDataType) + op.updateAttribute("preferred_shard", preferredShard) + op.addInput(filePattern) + op.addInput(tensorName) + op.addInput(shapeAndSlice) + return op.execute(Int(1)) } /// Restores tensors from a V2 checkpoint. @@ -25960,51 +25804,51 @@ public static func restoreSlice( /// Callers must ensure all the named tensors are indeed stored in the checkpoint. /// /// - Parameters: -/// - prefix: Must have a single element. The prefix of a V2 checkpoint. -/// - tensor_names: shape {N}. The names of the tensors to be restored. -/// - shape_and_slices: shape {N}. The slice specs of the tensors to be restored. -/// Empty strings indicate that they are non-partitioned tensors. +/// - prefix: Must have a single element. The prefix of a V2 checkpoint. +/// - tensor_names: shape {N}. The names of the tensors to be restored. +/// - shape_and_slices: shape {N}. The slice specs of the tensors to be restored. +/// Empty strings indicate that they are non-partitioned tensors. /// /// - Attr dtypes: shape {N}. The list of expected dtype for the tensors. Must match -/// those stored in the checkpoint. +/// those stored in the checkpoint. /// /// - Output tensors: shape {N}. The restored tensors, whose shapes are read from the -/// checkpoint directly. +/// checkpoint directly. @inlinable @inline(__always) public static func restoreV2( - prefix: StringTensor, - tensorNames: StringTensor, - shapeAndSlices: StringTensor + prefix: StringTensor, + tensorNames: StringTensor, + shapeAndSlices: StringTensor ) -> Dtypes { let nOutputs = Int(Dtypes._typeList.count) - let op = makeOp("RestoreV2", nOutputs) - op.updateAttribute("dtypes", Dtypes._typeList) - op.addInput(prefix) - op.addInput(tensorNames) - op.addInput(shapeAndSlices) - return op.execute(Int(Dtypes._typeList.count)) + let op = makeOp("RestoreV2", nOutputs) + op.updateAttribute("dtypes", Dtypes._typeList) + op.addInput(prefix) + op.addInput(tensorNames) + op.addInput(shapeAndSlices) + return op.execute(Int(Dtypes._typeList.count)) } @inlinable @inline(__always) public static func restrict( - _ a: Tensor + _ a: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Restrict", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - return op.execute(Int(1)) + let op = makeOp("Restrict", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func restrict( - _ a: StringTensor + _ a: StringTensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("Restrict", nOutputs) - op.updateAttribute("T", TensorDataType(TF_STRING)) - op.addInput(a) - return op.execute(Int(1)) + let op = makeOp("Restrict", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(a) + return op.execute(Int(1)) } /// Retrieve ADAM embedding parameters. @@ -26015,23 +25859,23 @@ public static func restrict( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the ADAM optimization algorithm. -/// - momenta: Parameter momenta updated by the ADAM optimization algorithm. -/// - velocities: Parameter velocities updated by the ADAM optimization algorithm. +/// - parameters: Parameter parameters updated by the ADAM optimization algorithm. +/// - momenta: Parameter momenta updated by the ADAM optimization algorithm. +/// - velocities: Parameter velocities updated by the ADAM optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingADAMParameters( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, momenta: Tensor, velocities: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingADAMParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingADAMParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) } /// Retrieve ADAM embedding parameters with debug support. @@ -26042,24 +25886,24 @@ public static func retrieveTPUEmbeddingADAMParameters( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the ADAM optimization algorithm. -/// - momenta: Parameter momenta updated by the ADAM optimization algorithm. -/// - velocities: Parameter velocities updated by the ADAM optimization algorithm. -/// - gradient_accumulators: Parameter gradient_accumulators updated by the ADAM optimization algorithm. +/// - parameters: Parameter parameters updated by the ADAM optimization algorithm. +/// - momenta: Parameter momenta updated by the ADAM optimization algorithm. +/// - velocities: Parameter velocities updated by the ADAM optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the ADAM optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingADAMParametersGradAccumDebug( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, momenta: Tensor, velocities: Tensor, gradientAccumulators: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingADAMParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingADAMParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Retrieve Adadelta embedding parameters. @@ -26070,23 +25914,23 @@ public static func retrieveTPUEmbeddingADAMParametersGradAccumDebug( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the Adadelta optimization algorithm. -/// - accumulators: Parameter accumulators updated by the Adadelta optimization algorithm. -/// - updates: Parameter updates updated by the Adadelta optimization algorithm. +/// - parameters: Parameter parameters updated by the Adadelta optimization algorithm. +/// - accumulators: Parameter accumulators updated by the Adadelta optimization algorithm. +/// - updates: Parameter updates updated by the Adadelta optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingAdadeltaParameters( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, accumulators: Tensor, updates: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingAdadeltaParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingAdadeltaParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) } /// Retrieve Adadelta embedding parameters with debug support. @@ -26097,24 +25941,24 @@ public static func retrieveTPUEmbeddingAdadeltaParameters( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the Adadelta optimization algorithm. -/// - accumulators: Parameter accumulators updated by the Adadelta optimization algorithm. -/// - updates: Parameter updates updated by the Adadelta optimization algorithm. -/// - gradient_accumulators: Parameter gradient_accumulators updated by the Adadelta optimization algorithm. +/// - parameters: Parameter parameters updated by the Adadelta optimization algorithm. +/// - accumulators: Parameter accumulators updated by the Adadelta optimization algorithm. +/// - updates: Parameter updates updated by the Adadelta optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the Adadelta optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingAdadeltaParametersGradAccumDebug( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, accumulators: Tensor, updates: Tensor, gradientAccumulators: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingAdadeltaParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingAdadeltaParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Retrieve Adagrad embedding parameters. @@ -26125,22 +25969,22 @@ public static func retrieveTPUEmbeddingAdadeltaParametersGradAccumDebug( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the Adagrad optimization algorithm. -/// - accumulators: Parameter accumulators updated by the Adagrad optimization algorithm. +/// - parameters: Parameter parameters updated by the Adagrad optimization algorithm. +/// - accumulators: Parameter accumulators updated by the Adagrad optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingAdagradParameters( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, accumulators: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingAdagradParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingAdagradParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1)) } /// Retrieve Adagrad embedding parameters with debug support. @@ -26151,23 +25995,23 @@ public static func retrieveTPUEmbeddingAdagradParameters( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the Adagrad optimization algorithm. -/// - accumulators: Parameter accumulators updated by the Adagrad optimization algorithm. -/// - gradient_accumulators: Parameter gradient_accumulators updated by the Adagrad optimization algorithm. +/// - parameters: Parameter parameters updated by the Adagrad optimization algorithm. +/// - accumulators: Parameter accumulators updated by the Adagrad optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the Adagrad optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingAdagradParametersGradAccumDebug( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, accumulators: Tensor, gradientAccumulators: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingAdagradParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingAdagradParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) } /// Retrieve centered RMSProp embedding parameters. @@ -26178,24 +26022,24 @@ public static func retrieveTPUEmbeddingAdagradParametersGradAccumDebug( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the centered RMSProp optimization algorithm. -/// - ms: Parameter ms updated by the centered RMSProp optimization algorithm. -/// - mom: Parameter mom updated by the centered RMSProp optimization algorithm. -/// - mg: Parameter mg updated by the centered RMSProp optimization algorithm. +/// - parameters: Parameter parameters updated by the centered RMSProp optimization algorithm. +/// - ms: Parameter ms updated by the centered RMSProp optimization algorithm. +/// - mom: Parameter mom updated by the centered RMSProp optimization algorithm. +/// - mg: Parameter mg updated by the centered RMSProp optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingCenteredRMSPropParameters( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, ms: Tensor, mom: Tensor, mg: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingCenteredRMSPropParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingCenteredRMSPropParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Retrieve FTRL embedding parameters. @@ -26206,23 +26050,23 @@ public static func retrieveTPUEmbeddingCenteredRMSPropParameters( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the FTRL optimization algorithm. -/// - accumulators: Parameter accumulators updated by the FTRL optimization algorithm. -/// - linears: Parameter linears updated by the FTRL optimization algorithm. +/// - parameters: Parameter parameters updated by the FTRL optimization algorithm. +/// - accumulators: Parameter accumulators updated by the FTRL optimization algorithm. +/// - linears: Parameter linears updated by the FTRL optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingFTRLParameters( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, accumulators: Tensor, linears: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingFTRLParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingFTRLParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) } /// Retrieve FTRL embedding parameters with debug support. @@ -26233,24 +26077,24 @@ public static func retrieveTPUEmbeddingFTRLParameters( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the FTRL optimization algorithm. -/// - accumulators: Parameter accumulators updated by the FTRL optimization algorithm. -/// - linears: Parameter linears updated by the FTRL optimization algorithm. -/// - gradient_accumulators: Parameter gradient_accumulators updated by the FTRL optimization algorithm. +/// - parameters: Parameter parameters updated by the FTRL optimization algorithm. +/// - accumulators: Parameter accumulators updated by the FTRL optimization algorithm. +/// - linears: Parameter linears updated by the FTRL optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the FTRL optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingFTRLParametersGradAccumDebug( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, accumulators: Tensor, linears: Tensor, gradientAccumulators: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingFTRLParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingFTRLParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Retrieve MDL Adagrad Light embedding parameters. @@ -26261,24 +26105,24 @@ public static func retrieveTPUEmbeddingFTRLParametersGradAccumDebug( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the MDL Adagrad Light optimization algorithm. -/// - accumulators: Parameter accumulators updated by the MDL Adagrad Light optimization algorithm. -/// - weights: Parameter weights updated by the MDL Adagrad Light optimization algorithm. -/// - benefits: Parameter benefits updated by the MDL Adagrad Light optimization algorithm. +/// - parameters: Parameter parameters updated by the MDL Adagrad Light optimization algorithm. +/// - accumulators: Parameter accumulators updated by the MDL Adagrad Light optimization algorithm. +/// - weights: Parameter weights updated by the MDL Adagrad Light optimization algorithm. +/// - benefits: Parameter benefits updated by the MDL Adagrad Light optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingMDLAdagradLightParameters( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, accumulators: Tensor, weights: Tensor, benefits: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingMDLAdagradLightParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingMDLAdagradLightParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Retrieve Momentum embedding parameters. @@ -26289,22 +26133,22 @@ public static func retrieveTPUEmbeddingMDLAdagradLightParameters( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the Momentum optimization algorithm. -/// - momenta: Parameter momenta updated by the Momentum optimization algorithm. +/// - parameters: Parameter parameters updated by the Momentum optimization algorithm. +/// - momenta: Parameter momenta updated by the Momentum optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingMomentumParameters( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, momenta: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingMomentumParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingMomentumParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1)) } /// Retrieve Momentum embedding parameters with debug support. @@ -26315,23 +26159,23 @@ public static func retrieveTPUEmbeddingMomentumParameters( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the Momentum optimization algorithm. -/// - momenta: Parameter momenta updated by the Momentum optimization algorithm. -/// - gradient_accumulators: Parameter gradient_accumulators updated by the Momentum optimization algorithm. +/// - parameters: Parameter parameters updated by the Momentum optimization algorithm. +/// - momenta: Parameter momenta updated by the Momentum optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the Momentum optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingMomentumParametersGradAccumDebug( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, momenta: Tensor, gradientAccumulators: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingMomentumParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingMomentumParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) } /// Retrieve proximal Adagrad embedding parameters. @@ -26342,22 +26186,22 @@ public static func retrieveTPUEmbeddingMomentumParametersGradAccumDebug( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the proximal Adagrad optimization algorithm. -/// - accumulators: Parameter accumulators updated by the proximal Adagrad optimization algorithm. +/// - parameters: Parameter parameters updated by the proximal Adagrad optimization algorithm. +/// - accumulators: Parameter accumulators updated by the proximal Adagrad optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingProximalAdagradParameters( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, accumulators: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingProximalAdagradParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingProximalAdagradParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1)) } /// Retrieve proximal Adagrad embedding parameters with debug support. @@ -26368,23 +26212,23 @@ public static func retrieveTPUEmbeddingProximalAdagradParameters( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the proximal Adagrad optimization algorithm. -/// - accumulators: Parameter accumulators updated by the proximal Adagrad optimization algorithm. -/// - gradient_accumulators: Parameter gradient_accumulators updated by the proximal Adagrad optimization algorithm. +/// - parameters: Parameter parameters updated by the proximal Adagrad optimization algorithm. +/// - accumulators: Parameter accumulators updated by the proximal Adagrad optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the proximal Adagrad optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingProximalAdagradParametersGradAccumDebug( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, accumulators: Tensor, gradientAccumulators: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingProximalAdagradParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingProximalAdagradParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) } /// Retrieve RMSProp embedding parameters. @@ -26395,23 +26239,23 @@ public static func retrieveTPUEmbeddingProximalAdagradParametersGradAccumDebug( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the RMSProp optimization algorithm. -/// - ms: Parameter ms updated by the RMSProp optimization algorithm. -/// - mom: Parameter mom updated by the RMSProp optimization algorithm. +/// - parameters: Parameter parameters updated by the RMSProp optimization algorithm. +/// - ms: Parameter ms updated by the RMSProp optimization algorithm. +/// - mom: Parameter mom updated by the RMSProp optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingRMSPropParameters( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, ms: Tensor, mom: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingRMSPropParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingRMSPropParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1)) } /// Retrieve RMSProp embedding parameters with debug support. @@ -26422,24 +26266,24 @@ public static func retrieveTPUEmbeddingRMSPropParameters( /// used to retrieve updated parameters before saving a checkpoint. /// /// - Outputs: -/// - parameters: Parameter parameters updated by the RMSProp optimization algorithm. -/// - ms: Parameter ms updated by the RMSProp optimization algorithm. -/// - mom: Parameter mom updated by the RMSProp optimization algorithm. -/// - gradient_accumulators: Parameter gradient_accumulators updated by the RMSProp optimization algorithm. +/// - parameters: Parameter parameters updated by the RMSProp optimization algorithm. +/// - ms: Parameter ms updated by the RMSProp optimization algorithm. +/// - mom: Parameter mom updated by the RMSProp optimization algorithm. +/// - gradient_accumulators: Parameter gradient_accumulators updated by the RMSProp optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingRMSPropParametersGradAccumDebug( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> (parameters: Tensor, ms: Tensor, mom: Tensor, gradientAccumulators: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("RetrieveTPUEmbeddingRMSPropParametersGradAccumDebug", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("RetrieveTPUEmbeddingRMSPropParametersGradAccumDebug", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// Retrieve SGD embedding parameters. @@ -26452,18 +26296,18 @@ public static func retrieveTPUEmbeddingRMSPropParametersGradAccumDebug( /// - Output parameters: Parameter parameters updated by the stochastic gradient descent optimization algorithm. @inlinable @inline(__always) public static func retrieveTPUEmbeddingStochasticGradientDescentParameters( - tableId: Int64 = -1, - tableName: String, - numShards: Int64, - shardId: Int64 + tableId: Int64 = -1, + tableName: String, + numShards: Int64, + shardId: Int64 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RetrieveTPUEmbeddingStochasticGradientDescentParameters", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("table_name", tableName) - op.updateAttribute("num_shards", numShards) - op.updateAttribute("shard_id", shardId) - return op.execute(Int(1)) + let op = makeOp("RetrieveTPUEmbeddingStochasticGradientDescentParameters", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("table_name", tableName) + op.updateAttribute("num_shards", numShards) + op.updateAttribute("shard_id", shardId) + return op.execute(Int(1)) } /// Reverses specific dimensions of a tensor. @@ -26514,21 +26358,21 @@ public static func retrieveTPUEmbeddingStochasticGradientDescentParameters( /// ``` /// /// - Parameters: -/// - tensor: Up to 8-D. -/// - dims: 1-D. The dimensions to reverse. +/// - tensor: Up to 8-D. +/// - dims: 1-D. The dimensions to reverse. /// /// - Output output: The same shape as `tensor`. @inlinable @inline(__always) public static func reverse( - _ tensor: Tensor, - dims: Tensor + _ tensor: Tensor, + dims: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Reverse", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(tensor) - op.addInput(dims) - return op.execute(Int(1)) + let op = makeOp("Reverse", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(tensor) + op.addInput(dims) + return op.execute(Int(1)) } /// Reverses specific dimensions of a tensor. @@ -26579,21 +26423,21 @@ public static func reverse( /// ``` /// /// - Parameters: -/// - tensor: Up to 8-D. -/// - dims: 1-D. The dimensions to reverse. +/// - tensor: Up to 8-D. +/// - dims: 1-D. The dimensions to reverse. /// /// - Output output: The same shape as `tensor`. @inlinable @inline(__always) public static func reverse( - _ tensor: StringTensor, - dims: Tensor + _ tensor: StringTensor, + dims: Tensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("Reverse", nOutputs) - op.updateAttribute("T", TensorDataType(TF_STRING)) - op.addInput(tensor) - op.addInput(dims) - return op.execute(Int(1)) + let op = makeOp("Reverse", nOutputs) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(tensor) + op.addInput(dims) + return op.execute(Int(1)) } /// Reverses variable length slices. @@ -26654,13 +26498,13 @@ public static func reverse( /// ``` /// /// - Parameters: -/// - input: The input to reverse. -/// - seq_lengths: 1-D with length `input.dims(batch_dim)` and -/// `max(seq_lengths) <= input.dims(seq_dim)` +/// - input: The input to reverse. +/// - seq_lengths: 1-D with length `input.dims(batch_dim)` and +/// `max(seq_lengths) <= input.dims(seq_dim)` /// /// - Attrs: -/// - seq_dim: The dimension which is partially reversed. -/// - batch_dim: The dimension along which reversal is performed. +/// - seq_dim: The dimension which is partially reversed. +/// - batch_dim: The dimension along which reversal is performed. /// /// - Output output: The partially reversed input. It has the same shape as `input`. @inlinable @inline(__always) @@ -26668,20 +26512,20 @@ public static func reverseSequence< T: TensorFlowScalar, Tlen: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - seqLengths: Tensor, - seqDim: Int64, - batchDim: Int64 = 0 + _ input: Tensor, + seqLengths: Tensor, + seqDim: Int64, + batchDim: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ReverseSequence", nOutputs) - op.updateAttribute("seq_dim", seqDim) - op.updateAttribute("batch_dim", batchDim) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tlen", Tlen.tensorFlowDataType) - op.addInput(input) - op.addInput(seqLengths) - return op.execute(Int(1)) + let op = makeOp("ReverseSequence", nOutputs) + op.updateAttribute("seq_dim", seqDim) + op.updateAttribute("batch_dim", batchDim) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tlen", Tlen.tensorFlowDataType) + op.addInput(input) + op.addInput(seqLengths) + return op.execute(Int(1)) } /// Reverses specific dimensions of a tensor. @@ -26734,9 +26578,9 @@ public static func reverseSequence< /// ``` /// /// - Parameters: -/// - tensor: Up to 8-D. -/// - axis: 1-D. The indices of the dimensions to reverse. Must be in the range -/// `[-rank(tensor), rank(tensor))`. +/// - tensor: Up to 8-D. +/// - axis: 1-D. The indices of the dimensions to reverse. Must be in the range +/// `[-rank(tensor), rank(tensor))`. /// /// - Output output: The same shape as `tensor`. @inlinable @inline(__always) @@ -26744,16 +26588,16 @@ public static func reverseV2< Tidx: BinaryInteger & TensorFlowScalar, T: TensorFlowScalar >( - _ tensor: Tensor, - axis: Tensor + _ tensor: Tensor, + axis: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ReverseV2", nOutputs) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(tensor) - op.addInput(axis) - return op.execute(Int(1)) + let op = makeOp("ReverseV2", nOutputs) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(tensor) + op.addInput(axis) + return op.execute(Int(1)) } /// Reverses specific dimensions of a tensor. @@ -26806,23 +26650,23 @@ public static func reverseV2< /// ``` /// /// - Parameters: -/// - tensor: Up to 8-D. -/// - axis: 1-D. The indices of the dimensions to reverse. Must be in the range -/// `[-rank(tensor), rank(tensor))`. +/// - tensor: Up to 8-D. +/// - axis: 1-D. The indices of the dimensions to reverse. Must be in the range +/// `[-rank(tensor), rank(tensor))`. /// /// - Output output: The same shape as `tensor`. @inlinable @inline(__always) public static func reverseV2( - _ tensor: StringTensor, - axis: Tensor + _ tensor: StringTensor, + axis: Tensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("ReverseV2", nOutputs) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.updateAttribute("T", TensorDataType(TF_STRING)) - op.addInput(tensor) - op.addInput(axis) - return op.execute(Int(1)) + let op = makeOp("ReverseV2", nOutputs) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(tensor) + op.addInput(axis) + return op.execute(Int(1)) } /// Elementwise computes the bitwise right-shift of `x` and `y`. @@ -26834,15 +26678,15 @@ public static func reverseV2( /// the result is implementation defined. @inlinable @inline(__always) public static func rightShift( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RightShift", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("RightShift", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns element-wise integer closest to x. @@ -26858,27 +26702,13 @@ public static func rightShift( /// ``` @inlinable @inline(__always) public static func rint( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Rint", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) -} - -@inlinable @inline(__always) -public static func rngSkip( - resource: ResourceHandle, - algorithm: Tensor, - delta: Tensor -) { - let nOutputs = 0 - let op = makeOp("RngSkip", nOutputs) - op.addInput(resource) - op.addInput(algorithm) - op.addInput(delta) - op.execute() + let op = makeOp("Rint", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Rolls the elements of a tensor along an axis. @@ -26905,37 +26735,37 @@ public static func rngSkip( /// ``` /// /// - Parameters: -/// - shift: Dimension must be 0-D or 1-D. `shift[i]` specifies the number of places by which -/// elements are shifted positively (towards larger indices) along the dimension -/// specified by `axis[i]`. Negative shifts will roll the elements in the opposite -/// direction. -/// - axis: Dimension must be 0-D or 1-D. `axis[i]` specifies the dimension that the shift -/// `shift[i]` should occur. If the same axis is referenced more than once, the -/// total shift for that axis will be the sum of all the shifts that belong to that -/// axis. +/// - shift: Dimension must be 0-D or 1-D. `shift[i]` specifies the number of places by which +/// elements are shifted positively (towards larger indices) along the dimension +/// specified by `axis[i]`. Negative shifts will roll the elements in the opposite +/// direction. +/// - axis: Dimension must be 0-D or 1-D. `axis[i]` specifies the dimension that the shift +/// `shift[i]` should occur. If the same axis is referenced more than once, the +/// total shift for that axis will be the sum of all the shifts that belong to that +/// axis. /// /// - Output output: Has the same shape and size as the input. The elements are shifted -/// positively (towards larger indices) by the offsets of `shift` along the -/// dimensions of `axis`. +/// positively (towards larger indices) by the offsets of `shift` along the +/// dimensions of `axis`. @inlinable @inline(__always) public static func roll< T: TensorFlowScalar, Tshift: BinaryInteger & TensorFlowScalar, Taxis: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - shift: Tensor, - axis: Tensor + _ input: Tensor, + shift: Tensor, + axis: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Roll", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tshift", Tshift.tensorFlowDataType) - op.updateAttribute("Taxis", Taxis.tensorFlowDataType) - op.addInput(input) - op.addInput(shift) - op.addInput(axis) - return op.execute(Int(1)) + let op = makeOp("Roll", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tshift", Tshift.tensorFlowDataType) + op.updateAttribute("Taxis", Taxis.tensorFlowDataType) + op.addInput(input) + op.addInput(shift) + op.addInput(axis) + return op.execute(Int(1)) } /// Rounds the values of a tensor to the nearest integer, element-wise. @@ -26944,13 +26774,13 @@ public static func roll< /// according to the current system rounding mode use std::cint. @inlinable @inline(__always) public static func round( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Round", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Round", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Perform batches of RPC requests. @@ -27004,45 +26834,45 @@ public static func round( /// See the `TryRpc` op if you prefer to handle RPC failures manually in the graph. /// /// - Parameters: -/// - address: `0-D` or `1-D`. The address (i.e. host_name:port) of the RPC server. -/// If this tensor has more than 1 element, then multiple parallel rpc requests -/// are sent. This argument broadcasts with `method` and `request`. -/// - method: `0-D` or `1-D`. The method address on the RPC server. -/// If this tensor has more than 1 element, then multiple parallel rpc requests -/// are sent. This argument broadcasts with `address` and `request`. -/// - request: `0-D` or `1-D`. Serialized proto strings: the rpc request argument. -/// If this tensor has more than 1 element, then multiple parallel rpc requests -/// are sent. This argument broadcasts with `address` and `method`. +/// - address: `0-D` or `1-D`. The address (i.e. host_name:port) of the RPC server. +/// If this tensor has more than 1 element, then multiple parallel rpc requests +/// are sent. This argument broadcasts with `method` and `request`. +/// - method: `0-D` or `1-D`. The method address on the RPC server. +/// If this tensor has more than 1 element, then multiple parallel rpc requests +/// are sent. This argument broadcasts with `address` and `request`. +/// - request: `0-D` or `1-D`. Serialized proto strings: the rpc request argument. +/// If this tensor has more than 1 element, then multiple parallel rpc requests +/// are sent. This argument broadcasts with `address` and `method`. /// /// - Attrs: -/// - protocol: RPC protocol to use. Empty string means use the default protocol. -/// Options include 'grpc'. -/// - fail_fast: `boolean`. If `true` (default), then failures to connect -/// (i.e., the server does not immediately respond) cause an RPC failure. -/// - timeout_in_ms: `int`. If `0` (default), then the kernel will run the RPC -/// request and only time out if the RPC deadline passes or the session times out. -/// If this value is greater than `0`, then the op will raise an exception if -/// the RPC takes longer than `timeout_in_ms`. +/// - protocol: RPC protocol to use. Empty string means use the default protocol. +/// Options include 'grpc'. +/// - fail_fast: `boolean`. If `true` (default), then failures to connect +/// (i.e., the server does not immediately respond) cause an RPC failure. +/// - timeout_in_ms: `int`. If `0` (default), then the kernel will run the RPC +/// request and only time out if the RPC deadline passes or the session times out. +/// If this value is greater than `0`, then the op will raise an exception if +/// the RPC takes longer than `timeout_in_ms`. /// /// - Output response: Same shape as `request`. Serialized proto strings: the rpc responses. @inlinable @inline(__always) public static func rpc( - address: StringTensor, - method: StringTensor, - request: StringTensor, - protocol_: String, - failFast: Bool = true, - timeoutInMs: Int64 = 0 + address: StringTensor, + method: StringTensor, + request: StringTensor, + protocol_: String, + failFast: Bool = true, + timeoutInMs: Int64 = 0 ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("Rpc", nOutputs) - op.updateAttribute("protocol", protocol_) - op.updateAttribute("fail_fast", failFast) - op.updateAttribute("timeout_in_ms", timeoutInMs) - op.addInput(address) - op.addInput(method) - op.addInput(request) - return op.execute(Int(1)) + let op = makeOp("Rpc", nOutputs) + op.updateAttribute("protocol", protocol_) + op.updateAttribute("fail_fast", failFast) + op.updateAttribute("timeout_in_ms", timeoutInMs) + op.addInput(address) + op.addInput(method) + op.addInput(request) + return op.execute(Int(1)) } /// Computes reciprocal of square root of x element-wise. @@ -27050,13 +26880,13 @@ public static func rpc( /// I.e., \\(y = 1 / \sqrt{x}\\). @inlinable @inline(__always) public static func rsqrt( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Rsqrt", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Rsqrt", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the gradient for the rsqrt of `x` wrt its input. @@ -27065,15 +26895,15 @@ public static func rsqrt( /// is the corresponding input gradient. @inlinable @inline(__always) public static func rsqrtGrad( - _ y: Tensor, - dy: Tensor + _ y: Tensor, + dy: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("RsqrtGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(y) - op.addInput(dy) - return op.execute(Int(1)) + let op = makeOp("RsqrtGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(dy) + return op.execute(Int(1)) } /// Generate a single randomly distorted bounding box for an image. @@ -27118,62 +26948,62 @@ public static func rsqrtGrad( /// false and no bounding boxes are supplied, an error is raised. /// /// - Parameters: -/// - image_size: 1-D, containing `[height, width, channels]`. -/// - bounding_boxes: 3-D with shape `[batch, N, 4]` describing the N bounding boxes -/// associated with the image. +/// - image_size: 1-D, containing `[height, width, channels]`. +/// - bounding_boxes: 3-D with shape `[batch, N, 4]` describing the N bounding boxes +/// associated with the image. /// /// - Attrs: -/// - seed: If either `seed` or `seed2` are set to non-zero, the random number -/// generator is seeded by the given `seed`. Otherwise, it is seeded by a random -/// seed. -/// - seed2: A second seed to avoid seed collision. -/// - min_object_covered: The cropped area of the image must contain at least this -/// fraction of any bounding box supplied. The value of this parameter should be -/// non-negative. In the case of 0, the cropped area does not need to overlap -/// any of the bounding boxes supplied. -/// - aspect_ratio_range: The cropped area of the image must have an aspect ratio = -/// width / height within this range. -/// - area_range: The cropped area of the image must contain a fraction of the -/// supplied image within this range. -/// - max_attempts: Number of attempts at generating a cropped region of the image -/// of the specified constraints. After `max_attempts` failures, return the entire -/// image. -/// - use_image_if_no_bounding_boxes: Controls behavior if no bounding boxes supplied. -/// If true, assume an implicit bounding box covering the whole input. If false, -/// raise an error. +/// - seed: If either `seed` or `seed2` are set to non-zero, the random number +/// generator is seeded by the given `seed`. Otherwise, it is seeded by a random +/// seed. +/// - seed2: A second seed to avoid seed collision. +/// - min_object_covered: The cropped area of the image must contain at least this +/// fraction of any bounding box supplied. The value of this parameter should be +/// non-negative. In the case of 0, the cropped area does not need to overlap +/// any of the bounding boxes supplied. +/// - aspect_ratio_range: The cropped area of the image must have an aspect ratio = +/// width / height within this range. +/// - area_range: The cropped area of the image must contain a fraction of the +/// supplied image within this range. +/// - max_attempts: Number of attempts at generating a cropped region of the image +/// of the specified constraints. After `max_attempts` failures, return the entire +/// image. +/// - use_image_if_no_bounding_boxes: Controls behavior if no bounding boxes supplied. +/// If true, assume an implicit bounding box covering the whole input. If false, +/// raise an error. /// /// - Outputs: -/// - begin: 1-D, containing `[offset_height, offset_width, 0]`. Provide as input to -/// `tf.slice`. -/// - size: 1-D, containing `[target_height, target_width, -1]`. Provide as input to -/// `tf.slice`. -/// - bboxes: 3-D with shape `[1, 1, 4]` containing the distorted bounding box. -/// Provide as input to `tf.image.draw_bounding_boxes`. +/// - begin: 1-D, containing `[offset_height, offset_width, 0]`. Provide as input to +/// `tf.slice`. +/// - size: 1-D, containing `[target_height, target_width, -1]`. Provide as input to +/// `tf.slice`. +/// - bboxes: 3-D with shape `[1, 1, 4]` containing the distorted bounding box. +/// Provide as input to `tf.image.draw_bounding_boxes`. @inlinable @inline(__always) public static func sampleDistortedBoundingBox( - imageSize: Tensor, - boundingBoxes: Tensor, - seed: Int64 = 0, - seed2: Int64 = 0, - minObjectCovered: Double = 0.1, - aspectRatioRange: [Double] = [0.75, 1.33], - areaRange: [Double] = [0.05, 1], - maxAttempts: Int64 = 100, - useImageIfNoBoundingBoxes: Bool = false + imageSize: Tensor, + boundingBoxes: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0, + minObjectCovered: Double = 0.1, + aspectRatioRange: [Double] = [0.75, 1.33], + areaRange: [Double] = [0.05, 1], + maxAttempts: Int64 = 100, + useImageIfNoBoundingBoxes: Bool = false ) -> (begin: Tensor, size: Tensor, bboxes: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("SampleDistortedBoundingBox", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("min_object_covered", minObjectCovered) - op.updateAttribute("aspect_ratio_range", aspectRatioRange) - op.updateAttribute("area_range", areaRange) - op.updateAttribute("max_attempts", maxAttempts) - op.updateAttribute("use_image_if_no_bounding_boxes", useImageIfNoBoundingBoxes) - op.addInput(imageSize) - op.addInput(boundingBoxes) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("SampleDistortedBoundingBox", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("min_object_covered", minObjectCovered) + op.updateAttribute("aspect_ratio_range", aspectRatioRange) + op.updateAttribute("area_range", areaRange) + op.updateAttribute("max_attempts", maxAttempts) + op.updateAttribute("use_image_if_no_bounding_boxes", useImageIfNoBoundingBoxes) + op.addInput(imageSize) + op.addInput(boundingBoxes) + return op.execute(Int(1), Int(1), Int(1)) } /// Generate a single randomly distorted bounding box for an image. @@ -27218,89 +27048,89 @@ public static func sampleDistortedBoundingBox( - imageSize: Tensor, - boundingBoxes: Tensor, - minObjectCovered: Tensor, - seed: Int64 = 0, - seed2: Int64 = 0, - aspectRatioRange: [Double] = [0.75, 1.33], - areaRange: [Double] = [0.05, 1], - maxAttempts: Int64 = 100, - useImageIfNoBoundingBoxes: Bool = false + imageSize: Tensor, + boundingBoxes: Tensor, + minObjectCovered: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0, + aspectRatioRange: [Double] = [0.75, 1.33], + areaRange: [Double] = [0.05, 1], + maxAttempts: Int64 = 100, + useImageIfNoBoundingBoxes: Bool = false ) -> (begin: Tensor, size: Tensor, bboxes: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("SampleDistortedBoundingBoxV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("aspect_ratio_range", aspectRatioRange) - op.updateAttribute("area_range", areaRange) - op.updateAttribute("max_attempts", maxAttempts) - op.updateAttribute("use_image_if_no_bounding_boxes", useImageIfNoBoundingBoxes) - op.addInput(imageSize) - op.addInput(boundingBoxes) - op.addInput(minObjectCovered) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("SampleDistortedBoundingBoxV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("aspect_ratio_range", aspectRatioRange) + op.updateAttribute("area_range", areaRange) + op.updateAttribute("max_attempts", maxAttempts) + op.updateAttribute("use_image_if_no_bounding_boxes", useImageIfNoBoundingBoxes) + op.addInput(imageSize) + op.addInput(boundingBoxes) + op.addInput(minObjectCovered) + return op.execute(Int(1), Int(1), Int(1)) } /// Creates a dataset that contains `rate` elements from the `input_dataset`. /// /// - Parameters: -/// - rate: A scalar representing the sample rate of elements from the `input_dataset` -/// that should be taken. -/// - seed: A scalar representing seed of random number generator. -/// - seed2: A scalar representing seed2 of random number generator. +/// - rate: A scalar representing the sample rate of elements from the `input_dataset` +/// that should be taken. +/// - seed: A scalar representing seed of random number generator. +/// - seed2: A scalar representing seed2 of random number generator. @inlinable @inline(__always) public static func samplingDataset( - inputDataset: VariantHandle, - rate: Tensor, - seed: Tensor, - seed2: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + rate: Tensor, + seed: Tensor, + seed2: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("SamplingDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(rate) - op.addInput(seed) - op.addInput(seed2) - return op.execute(Int(1)) + let op = makeOp("SamplingDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(rate) + op.addInput(seed) + op.addInput(seed2) + return op.execute(Int(1)) } /// Saves the input tensors to disk. @@ -27311,23 +27141,23 @@ public static func samplingDataset( /// See also `SaveSlices`. /// /// - Parameters: -/// - filename: Must have a single element. The name of the file to which we write -/// the tensor. -/// - tensor_names: Shape `[N]`. The names of the tensors to be saved. -/// - data: `N` tensors to save. +/// - filename: Must have a single element. The name of the file to which we write +/// the tensor. +/// - tensor_names: Shape `[N]`. The names of the tensors to be saved. +/// - data: `N` tensors to save. @inlinable @inline(__always) public static func save( - filename: StringTensor, - tensorNames: StringTensor, - data: T + filename: StringTensor, + tensorNames: StringTensor, + data: T ) { let nOutputs = 0 - let op = makeOp("Save", nOutputs) - op.updateAttribute("T", data._typeList) - op.addInput(filename) - op.addInput(tensorNames) - op.addInputList(data) - op.execute() + let op = makeOp("Save", nOutputs) + op.updateAttribute("T", data._typeList) + op.addInput(filename) + op.addInput(tensorNames) + op.addInputList(data) + op.execute() } /// Saves input tensors slices to disk. @@ -27355,27 +27185,27 @@ public static func save( /// See also `Save`. /// /// - Parameters: -/// - filename: Must have a single element. The name of the file to which we write the -/// tensor. -/// - tensor_names: Shape `[N]`. The names of the tensors to be saved. -/// - shapes_and_slices: Shape `[N]`. The shapes and slice specifications to use when -/// saving the tensors. -/// - data: `N` tensors to save. +/// - filename: Must have a single element. The name of the file to which we write the +/// tensor. +/// - tensor_names: Shape `[N]`. The names of the tensors to be saved. +/// - shapes_and_slices: Shape `[N]`. The shapes and slice specifications to use when +/// saving the tensors. +/// - data: `N` tensors to save. @inlinable @inline(__always) public static func saveSlices( - filename: StringTensor, - tensorNames: StringTensor, - shapesAndSlices: StringTensor, - data: T + filename: StringTensor, + tensorNames: StringTensor, + shapesAndSlices: StringTensor, + data: T ) { let nOutputs = 0 - let op = makeOp("SaveSlices", nOutputs) - op.updateAttribute("T", data._typeList) - op.addInput(filename) - op.addInput(tensorNames) - op.addInput(shapesAndSlices) - op.addInputList(data) - op.execute() + let op = makeOp("SaveSlices", nOutputs) + op.updateAttribute("T", data._typeList) + op.addInput(filename) + op.addInput(tensorNames) + op.addInput(shapesAndSlices) + op.addInputList(data) + op.execute() } /// Saves tensors in V2 checkpoint format. @@ -27385,27 +27215,27 @@ public static func saveSlices( /// and correspondingly well-formed. /// /// - Parameters: -/// - prefix: Must have a single element. The prefix of the V2 checkpoint to which we -/// write the tensors. -/// - tensor_names: shape {N}. The names of the tensors to be saved. -/// - shape_and_slices: shape {N}. The slice specs of the tensors to be saved. -/// Empty strings indicate that they are non-partitioned tensors. -/// - tensors: `N` tensors to save. +/// - prefix: Must have a single element. The prefix of the V2 checkpoint to which we +/// write the tensors. +/// - tensor_names: shape {N}. The names of the tensors to be saved. +/// - shape_and_slices: shape {N}. The slice specs of the tensors to be saved. +/// Empty strings indicate that they are non-partitioned tensors. +/// - tensors: `N` tensors to save. @inlinable @inline(__always) public static func saveV2( - prefix: StringTensor, - tensorNames: StringTensor, - shapeAndSlices: StringTensor, - tensors: Dtypes + prefix: StringTensor, + tensorNames: StringTensor, + shapeAndSlices: StringTensor, + tensors: Dtypes ) { let nOutputs = 0 - let op = makeOp("SaveV2", nOutputs) - op.updateAttribute("dtypes", tensors._typeList) - op.addInput(prefix) - op.addInput(tensorNames) - op.addInput(shapeAndSlices) - op.addInputList(tensors) - op.execute() + let op = makeOp("SaveV2", nOutputs) + op.updateAttribute("dtypes", tensors._typeList) + op.addInput(prefix) + op.addInput(tensorNames) + op.addInput(shapeAndSlices) + op.addInputList(tensors) + op.execute() } /// Outputs a `Summary` protocol buffer with scalar values. @@ -27414,63 +27244,63 @@ public static func saveV2( /// has a summary value for each tag-value pair in `tags` and `values`. /// /// - Parameters: -/// - tags: Tags for the summary. -/// - values: Same shape as `tags. Values for the summary. +/// - tags: Tags for the summary. +/// - values: Same shape as `tags. Values for the summary. /// /// - Output summary: Scalar. Serialized `Summary` protocol buffer. @inlinable @inline(__always) public static func scalarSummary( - tags: StringTensor, - _ values: Tensor + tags: StringTensor, + _ values: Tensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("ScalarSummary", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(tags) - op.addInput(values) - return op.execute(Int(1)) + let op = makeOp("ScalarSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(tags) + op.addInput(values) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func scaleAndTranslate( - images: Tensor, - size: Tensor, - scale: Tensor, - translation: Tensor, - kernelType: String = "lanczos3", - antialias: Bool = true + images: Tensor, + size: Tensor, + scale: Tensor, + translation: Tensor, + kernelType: String = "lanczos3", + antialias: Bool = true ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ScaleAndTranslate", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("kernel_type", kernelType) - op.updateAttribute("antialias", antialias) - op.addInput(images) - op.addInput(size) - op.addInput(scale) - op.addInput(translation) - return op.execute(Int(1)) + let op = makeOp("ScaleAndTranslate", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("kernel_type", kernelType) + op.updateAttribute("antialias", antialias) + op.addInput(images) + op.addInput(size) + op.addInput(scale) + op.addInput(translation) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func scaleAndTranslateGrad( - grads: Tensor, - originalImage: Tensor, - scale: Tensor, - translation: Tensor, - kernelType: String = "lanczos3", - antialias: Bool = true + grads: Tensor, + originalImage: Tensor, + scale: Tensor, + translation: Tensor, + kernelType: String = "lanczos3", + antialias: Bool = true ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ScaleAndTranslateGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("kernel_type", kernelType) - op.updateAttribute("antialias", antialias) - op.addInput(grads) - op.addInput(originalImage) - op.addInput(scale) - op.addInput(translation) - return op.execute(Int(1)) + let op = makeOp("ScaleAndTranslateGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("kernel_type", kernelType) + op.updateAttribute("antialias", antialias) + op.addInput(grads) + op.addInput(originalImage) + op.addInput(scale) + op.addInput(translation) + return op.execute(Int(1)) } /// Scatter `updates` into a new tensor according to `indices`. @@ -27559,29 +27389,29 @@ public static func scaleAndTranslateGrad( /// On GPU, if an out of bound index is found, the index is ignored. /// /// - Parameters: -/// - indices: Index tensor. -/// - updates: Updates to scatter into output. -/// - shape: 1-D. The shape of the resulting tensor. +/// - indices: Index tensor. +/// - updates: Updates to scatter into output. +/// - shape: 1-D. The shape of the resulting tensor. /// /// - Output output: A new tensor with the given shape and updates applied according -/// to the indices. +/// to the indices. @inlinable @inline(__always) public static func scatterNd< T: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - indices: Tensor, - updates: Tensor, - shape: Tensor + indices: Tensor, + updates: Tensor, + shape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ScatterNd", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(indices) - op.addInput(updates) - op.addInput(shape) - return op.execute(Int(1)) + let op = makeOp("ScatterNd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(indices) + op.addInput(updates) + op.addInput(shape) + return op.execute(Int(1)) } /// Applies sparse addition to `input` using individual values or slices @@ -27621,31 +27451,31 @@ public static func scatterNd< /// See `tf.scatter_nd` for more details about how to make updates to slices. /// /// - Parameters: -/// - input: A Tensor. -/// - indices: A Tensor. Must be one of the following types: `int32`, `int64`. -/// A tensor of indices into `input`. -/// - updates: A Tensor. Must have the same type as ref. A tensor of updated values -/// to add to `input`. +/// - input: A Tensor. +/// - indices: A Tensor. Must be one of the following types: `int32`, `int64`. +/// A tensor of indices into `input`. +/// - updates: A Tensor. Must have the same type as ref. A tensor of updated values +/// to add to `input`. /// /// - Output output: A `Tensor` with the same shape as `input`, containing values of `input` -/// updated with `updates`. +/// updated with `updates`. @inlinable @inline(__always) public static func scatterNdNonAliasingAdd< T: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - indices: Tensor, - updates: Tensor + _ input: Tensor, + indices: Tensor, + updates: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ScatterNdNonAliasingAdd", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(input) - op.addInput(indices) - op.addInput(updates) - return op.execute(Int(1)) + let op = makeOp("ScatterNdNonAliasingAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(input) + op.addInput(indices) + op.addInput(updates) + return op.execute(Int(1)) } /// Computes fingerprints of the input strings. @@ -27653,15 +27483,15 @@ public static func scatterNdNonAliasingAdd< /// - Parameter input: vector of strings to compute fingerprints on. /// /// - Output output: a (N,2) shaped matrix where N is the number of elements in the input -/// vector. Each row contains the low and high parts of the fingerprint. +/// vector. Each row contains the low and high parts of the fingerprint. @inlinable @inline(__always) public static func sdcaFprint( - _ input: StringTensor + _ input: StringTensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SdcaFprint", nOutputs) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("SdcaFprint", nOutputs) + op.addInput(input) + return op.execute(Int(1)) } /// Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for @@ -27685,85 +27515,85 @@ public static func sdcaFprint( /// Dominik Csiba, Zheng Qu, Peter Richtarik. 2015 /// /// - Parameters: -/// - sparse_example_indices: a list of vectors which contain example indices. -/// - sparse_feature_indices: a list of vectors which contain feature indices. -/// - sparse_feature_values: a list of vectors which contains feature value -/// associated with each feature group. -/// - dense_features: a list of matrices which contains the dense feature values. -/// - example_weights: a vector which contains the weight associated with each -/// example. -/// - example_labels: a vector which contains the label/target associated with each -/// example. -/// - sparse_indices: a list of vectors where each value is the indices which has -/// corresponding weights in sparse_weights. This field maybe omitted for the -/// dense approach. -/// - sparse_weights: a list of vectors where each value is the weight associated with -/// a sparse feature group. -/// - dense_weights: a list of vectors where the values are the weights associated -/// with a dense feature group. -/// - example_state_data: a list of vectors containing the example state data. +/// - sparse_example_indices: a list of vectors which contain example indices. +/// - sparse_feature_indices: a list of vectors which contain feature indices. +/// - sparse_feature_values: a list of vectors which contains feature value +/// associated with each feature group. +/// - dense_features: a list of matrices which contains the dense feature values. +/// - example_weights: a vector which contains the weight associated with each +/// example. +/// - example_labels: a vector which contains the label/target associated with each +/// example. +/// - sparse_indices: a list of vectors where each value is the indices which has +/// corresponding weights in sparse_weights. This field maybe omitted for the +/// dense approach. +/// - sparse_weights: a list of vectors where each value is the weight associated with +/// a sparse feature group. +/// - dense_weights: a list of vectors where the values are the weights associated +/// with a dense feature group. +/// - example_state_data: a list of vectors containing the example state data. /// /// - Attrs: -/// - loss_type: Type of the primal loss. Currently SdcaSolver supports logistic, -/// squared and hinge losses. -/// - adaptative: Whether to use Adaptive SDCA for the inner loop. -/// - num_sparse_features: Number of sparse feature groups to train on. -/// - num_sparse_features_with_values: Number of sparse feature groups with values -/// associated with it, otherwise implicitly treats values as 1.0. -/// - num_dense_features: Number of dense feature groups to train on. -/// - l1: Symmetric l1 regularization strength. -/// - l2: Symmetric l2 regularization strength. -/// - num_loss_partitions: Number of partitions of the global loss function. -/// - num_inner_iterations: Number of iterations per mini-batch. +/// - loss_type: Type of the primal loss. Currently SdcaSolver supports logistic, +/// squared and hinge losses. +/// - adaptative: Whether to use Adaptive SDCA for the inner loop. +/// - num_sparse_features: Number of sparse feature groups to train on. +/// - num_sparse_features_with_values: Number of sparse feature groups with values +/// associated with it, otherwise implicitly treats values as 1.0. +/// - num_dense_features: Number of dense feature groups to train on. +/// - l1: Symmetric l1 regularization strength. +/// - l2: Symmetric l2 regularization strength. +/// - num_loss_partitions: Number of partitions of the global loss function. +/// - num_inner_iterations: Number of iterations per mini-batch. /// /// - Outputs: -/// - out_example_state_data: a list of vectors containing the updated example state -/// data. -/// - out_delta_sparse_weights: a list of vectors where each value is the delta -/// weights associated with a sparse feature group. -/// - out_delta_dense_weights: a list of vectors where the values are the delta -/// weights associated with a dense feature group. +/// - out_example_state_data: a list of vectors containing the updated example state +/// data. +/// - out_delta_sparse_weights: a list of vectors where each value is the delta +/// weights associated with a sparse feature group. +/// - out_delta_dense_weights: a list of vectors where the values are the delta +/// weights associated with a dense feature group. @inlinable @inline(__always) public static func sdcaOptimizer( - sparseExampleIndices: [Tensor], - sparseFeatureIndices: [Tensor], - sparseFeatureValues: [Tensor], - denseFeatures: [Tensor], - exampleWeights: Tensor, - exampleLabels: Tensor, - sparseIndices: [Tensor], - sparseWeights: [Tensor], - denseWeights: [Tensor], - exampleStateData: Tensor, - lossType: LossType, - adaptative: Bool = false, - l1: Double, - l2: Double, - numLossPartitions: Int64, - numInnerIterations: Int64 + sparseExampleIndices: [Tensor], + sparseFeatureIndices: [Tensor], + sparseFeatureValues: [Tensor], + denseFeatures: [Tensor], + exampleWeights: Tensor, + exampleLabels: Tensor, + sparseIndices: [Tensor], + sparseWeights: [Tensor], + denseWeights: [Tensor], + exampleStateData: Tensor, + lossType: LossType, + adaptative: Bool = false, + l1: Double, + l2: Double, + numLossPartitions: Int64, + numInnerIterations: Int64 ) -> (outExampleStateData: Tensor, outDeltaSparseWeights: [Tensor], outDeltaDenseWeights: [Tensor]) { let nOutputs = Int(1) + Int(sparseExampleIndices.count) + Int(denseFeatures.count) - let op = makeOp("SdcaOptimizer", nOutputs) - op.updateAttribute("loss_type", lossType.cName) - op.updateAttribute("adaptative", adaptative) - op.updateAttribute("num_sparse_features", sparseExampleIndices.count) - op.updateAttribute("num_sparse_features_with_values", sparseFeatureValues.count) - op.updateAttribute("num_dense_features", denseFeatures.count) - op.updateAttribute("l1", l1) - op.updateAttribute("l2", l2) - op.updateAttribute("num_loss_partitions", numLossPartitions) - op.updateAttribute("num_inner_iterations", numInnerIterations) - op.addInputList(sparseExampleIndices) - op.addInputList(sparseFeatureIndices) - op.addInputList(sparseFeatureValues) - op.addInputList(denseFeatures) - op.addInput(exampleWeights) - op.addInput(exampleLabels) - op.addInputList(sparseIndices) - op.addInputList(sparseWeights) - op.addInputList(denseWeights) - op.addInput(exampleStateData) - return op.execute(Int(1), Int(sparseExampleIndices.count), Int(denseFeatures.count)) + let op = makeOp("SdcaOptimizer", nOutputs) + op.updateAttribute("loss_type", lossType.cName) + op.updateAttribute("adaptative", adaptative) + op.updateAttribute("num_sparse_features", sparseExampleIndices.count) + op.updateAttribute("num_sparse_features_with_values", sparseFeatureValues.count) + op.updateAttribute("num_dense_features", denseFeatures.count) + op.updateAttribute("l1", l1) + op.updateAttribute("l2", l2) + op.updateAttribute("num_loss_partitions", numLossPartitions) + op.updateAttribute("num_inner_iterations", numInnerIterations) + op.addInputList(sparseExampleIndices) + op.addInputList(sparseFeatureIndices) + op.addInputList(sparseFeatureValues) + op.addInputList(denseFeatures) + op.addInput(exampleWeights) + op.addInput(exampleLabels) + op.addInputList(sparseIndices) + op.addInputList(sparseWeights) + op.addInputList(denseWeights) + op.addInput(exampleStateData) + return op.execute(Int(1), Int(sparseExampleIndices.count), Int(denseFeatures.count)) } /// Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for @@ -27787,85 +27617,85 @@ public static func sdcaOptimizer( /// Dominik Csiba, Zheng Qu, Peter Richtarik. 2015 /// /// - Parameters: -/// - sparse_example_indices: a list of vectors which contain example indices. -/// - sparse_feature_indices: a list of vectors which contain feature indices. -/// - sparse_feature_values: a list of vectors which contains feature value -/// associated with each feature group. -/// - dense_features: a list of matrices which contains the dense feature values. -/// - example_weights: a vector which contains the weight associated with each -/// example. -/// - example_labels: a vector which contains the label/target associated with each -/// example. -/// - sparse_indices: a list of vectors where each value is the indices which has -/// corresponding weights in sparse_weights. This field maybe omitted for the -/// dense approach. -/// - sparse_weights: a list of vectors where each value is the weight associated with -/// a sparse feature group. -/// - dense_weights: a list of vectors where the values are the weights associated -/// with a dense feature group. -/// - example_state_data: a list of vectors containing the example state data. +/// - sparse_example_indices: a list of vectors which contain example indices. +/// - sparse_feature_indices: a list of vectors which contain feature indices. +/// - sparse_feature_values: a list of vectors which contains feature value +/// associated with each feature group. +/// - dense_features: a list of matrices which contains the dense feature values. +/// - example_weights: a vector which contains the weight associated with each +/// example. +/// - example_labels: a vector which contains the label/target associated with each +/// example. +/// - sparse_indices: a list of vectors where each value is the indices which has +/// corresponding weights in sparse_weights. This field maybe omitted for the +/// dense approach. +/// - sparse_weights: a list of vectors where each value is the weight associated with +/// a sparse feature group. +/// - dense_weights: a list of vectors where the values are the weights associated +/// with a dense feature group. +/// - example_state_data: a list of vectors containing the example state data. /// /// - Attrs: -/// - loss_type: Type of the primal loss. Currently SdcaSolver supports logistic, -/// squared and hinge losses. -/// - adaptive: Whether to use Adaptive SDCA for the inner loop. -/// - num_sparse_features: Number of sparse feature groups to train on. -/// - num_sparse_features_with_values: Number of sparse feature groups with values -/// associated with it, otherwise implicitly treats values as 1.0. -/// - num_dense_features: Number of dense feature groups to train on. -/// - l1: Symmetric l1 regularization strength. -/// - l2: Symmetric l2 regularization strength. -/// - num_loss_partitions: Number of partitions of the global loss function. -/// - num_inner_iterations: Number of iterations per mini-batch. +/// - loss_type: Type of the primal loss. Currently SdcaSolver supports logistic, +/// squared and hinge losses. +/// - adaptive: Whether to use Adaptive SDCA for the inner loop. +/// - num_sparse_features: Number of sparse feature groups to train on. +/// - num_sparse_features_with_values: Number of sparse feature groups with values +/// associated with it, otherwise implicitly treats values as 1.0. +/// - num_dense_features: Number of dense feature groups to train on. +/// - l1: Symmetric l1 regularization strength. +/// - l2: Symmetric l2 regularization strength. +/// - num_loss_partitions: Number of partitions of the global loss function. +/// - num_inner_iterations: Number of iterations per mini-batch. /// /// - Outputs: -/// - out_example_state_data: a list of vectors containing the updated example state -/// data. -/// - out_delta_sparse_weights: a list of vectors where each value is the delta -/// weights associated with a sparse feature group. -/// - out_delta_dense_weights: a list of vectors where the values are the delta -/// weights associated with a dense feature group. +/// - out_example_state_data: a list of vectors containing the updated example state +/// data. +/// - out_delta_sparse_weights: a list of vectors where each value is the delta +/// weights associated with a sparse feature group. +/// - out_delta_dense_weights: a list of vectors where the values are the delta +/// weights associated with a dense feature group. @inlinable @inline(__always) public static func sdcaOptimizerV2( - sparseExampleIndices: [Tensor], - sparseFeatureIndices: [Tensor], - sparseFeatureValues: [Tensor], - denseFeatures: [Tensor], - exampleWeights: Tensor, - exampleLabels: Tensor, - sparseIndices: [Tensor], - sparseWeights: [Tensor], - denseWeights: [Tensor], - exampleStateData: Tensor, - lossType: LossType, - adaptive: Bool = false, - l1: Double, - l2: Double, - numLossPartitions: Int64, - numInnerIterations: Int64 + sparseExampleIndices: [Tensor], + sparseFeatureIndices: [Tensor], + sparseFeatureValues: [Tensor], + denseFeatures: [Tensor], + exampleWeights: Tensor, + exampleLabels: Tensor, + sparseIndices: [Tensor], + sparseWeights: [Tensor], + denseWeights: [Tensor], + exampleStateData: Tensor, + lossType: LossType, + adaptive: Bool = false, + l1: Double, + l2: Double, + numLossPartitions: Int64, + numInnerIterations: Int64 ) -> (outExampleStateData: Tensor, outDeltaSparseWeights: [Tensor], outDeltaDenseWeights: [Tensor]) { let nOutputs = Int(1) + Int(sparseExampleIndices.count) + Int(denseFeatures.count) - let op = makeOp("SdcaOptimizerV2", nOutputs) - op.updateAttribute("loss_type", lossType.cName) - op.updateAttribute("adaptive", adaptive) - op.updateAttribute("num_sparse_features", sparseExampleIndices.count) - op.updateAttribute("num_sparse_features_with_values", sparseFeatureValues.count) - op.updateAttribute("num_dense_features", denseFeatures.count) - op.updateAttribute("l1", l1) - op.updateAttribute("l2", l2) - op.updateAttribute("num_loss_partitions", numLossPartitions) - op.updateAttribute("num_inner_iterations", numInnerIterations) - op.addInputList(sparseExampleIndices) - op.addInputList(sparseFeatureIndices) - op.addInputList(sparseFeatureValues) - op.addInputList(denseFeatures) - op.addInput(exampleWeights) - op.addInput(exampleLabels) - op.addInputList(sparseIndices) - op.addInputList(sparseWeights) - op.addInputList(denseWeights) - op.addInput(exampleStateData) - return op.execute(Int(1), Int(sparseExampleIndices.count), Int(denseFeatures.count)) + let op = makeOp("SdcaOptimizerV2", nOutputs) + op.updateAttribute("loss_type", lossType.cName) + op.updateAttribute("adaptive", adaptive) + op.updateAttribute("num_sparse_features", sparseExampleIndices.count) + op.updateAttribute("num_sparse_features_with_values", sparseFeatureValues.count) + op.updateAttribute("num_dense_features", denseFeatures.count) + op.updateAttribute("l1", l1) + op.updateAttribute("l2", l2) + op.updateAttribute("num_loss_partitions", numLossPartitions) + op.updateAttribute("num_inner_iterations", numInnerIterations) + op.addInputList(sparseExampleIndices) + op.addInputList(sparseFeatureIndices) + op.addInputList(sparseFeatureValues) + op.addInputList(denseFeatures) + op.addInput(exampleWeights) + op.addInput(exampleLabels) + op.addInputList(sparseIndices) + op.addInputList(sparseWeights) + op.addInputList(denseWeights) + op.addInput(exampleStateData) + return op.execute(Int(1), Int(sparseExampleIndices.count), Int(denseFeatures.count)) } /// Computes the maximum along segments of a tensor. @@ -27895,25 +27725,25 @@ public static func sdcaOptimizerV2( /// /// /// - Parameter segment_ids: A 1-D tensor whose size is equal to the size of `data`'s -/// first dimension. Values should be sorted and can be repeated. +/// first dimension. Values should be sorted and can be repeated. /// /// - Output output: Has same shape as data, except for dimension 0 which -/// has size `k`, the number of segments. +/// has size `k`, the number of segments. @inlinable @inline(__always) public static func segmentMax< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - data: Tensor, - segmentIds: Tensor + data: Tensor, + segmentIds: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SegmentMax", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(data) - op.addInput(segmentIds) - return op.execute(Int(1)) + let op = makeOp("SegmentMax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + return op.execute(Int(1)) } /// Computes the mean along segments of a tensor. @@ -27944,25 +27774,25 @@ public static func segmentMax< /// /// /// - Parameter segment_ids: A 1-D tensor whose size is equal to the size of `data`'s -/// first dimension. Values should be sorted and can be repeated. +/// first dimension. Values should be sorted and can be repeated. /// /// - Output output: Has same shape as data, except for dimension 0 which -/// has size `k`, the number of segments. +/// has size `k`, the number of segments. @inlinable @inline(__always) public static func segmentMean< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - data: Tensor, - segmentIds: Tensor + data: Tensor, + segmentIds: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SegmentMean", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(data) - op.addInput(segmentIds) - return op.execute(Int(1)) + let op = makeOp("SegmentMean", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + return op.execute(Int(1)) } /// Computes the minimum along segments of a tensor. @@ -27991,25 +27821,25 @@ public static func segmentMean< /// ``` /// /// - Parameter segment_ids: A 1-D tensor whose size is equal to the size of `data`'s -/// first dimension. Values should be sorted and can be repeated. +/// first dimension. Values should be sorted and can be repeated. /// /// - Output output: Has same shape as data, except for dimension 0 which -/// has size `k`, the number of segments. +/// has size `k`, the number of segments. @inlinable @inline(__always) public static func segmentMin< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - data: Tensor, - segmentIds: Tensor + data: Tensor, + segmentIds: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SegmentMin", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(data) - op.addInput(segmentIds) - return op.execute(Int(1)) + let op = makeOp("SegmentMin", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + return op.execute(Int(1)) } /// Computes the product along segments of a tensor. @@ -28039,25 +27869,25 @@ public static func segmentMin< /// /// /// - Parameter segment_ids: A 1-D tensor whose size is equal to the size of `data`'s -/// first dimension. Values should be sorted and can be repeated. +/// first dimension. Values should be sorted and can be repeated. /// /// - Output output: Has same shape as data, except for dimension 0 which -/// has size `k`, the number of segments. +/// has size `k`, the number of segments. @inlinable @inline(__always) public static func segmentProd< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - data: Tensor, - segmentIds: Tensor + data: Tensor, + segmentIds: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SegmentProd", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(data) - op.addInput(segmentIds) - return op.execute(Int(1)) + let op = makeOp("SegmentProd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + return op.execute(Int(1)) } /// Computes the sum along segments of a tensor. @@ -28087,25 +27917,25 @@ public static func segmentProd< /// /// /// - Parameter segment_ids: A 1-D tensor whose size is equal to the size of `data`'s -/// first dimension. Values should be sorted and can be repeated. +/// first dimension. Values should be sorted and can be repeated. /// /// - Output output: Has same shape as data, except for dimension 0 which -/// has size `k`, the number of segments. +/// has size `k`, the number of segments. @inlinable @inline(__always) public static func segmentSum< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - data: Tensor, - segmentIds: Tensor + data: Tensor, + segmentIds: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SegmentSum", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(data) - op.addInput(segmentIds) - return op.execute(Int(1)) + let op = makeOp("SegmentSum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + return op.execute(Int(1)) } /// Selects elements from `x` or `y`, depending on `condition`. @@ -28150,25 +27980,25 @@ public static func segmentSum< /// ``` /// /// - Parameters: -/// - t: = A `Tensor` which may have the same shape as `condition`. -/// If `condition` is rank 1, `x` may have higher rank, -/// but its first dimension must match the size of `condition`. -/// - e: = A `Tensor` with the same type and shape as `x`. +/// - t: = A `Tensor` which may have the same shape as `condition`. +/// If `condition` is rank 1, `x` may have higher rank, +/// but its first dimension must match the size of `condition`. +/// - e: = A `Tensor` with the same type and shape as `x`. /// /// - Output output: = A `Tensor` with the same type and shape as `x` and `y`. @inlinable @inline(__always) public static func select( - condition: Tensor, - t: Tensor, - e: Tensor + condition: Tensor, + t: Tensor, + e: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Select", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(condition) - op.addInput(t) - op.addInput(e) - return op.execute(Int(1)) + let op = makeOp("Select", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(condition) + op.addInput(t) + op.addInput(e) + return op.execute(Int(1)) } /// Computes the Eigen Decomposition of a batch of square self-adjoint matrices. @@ -28186,13 +28016,13 @@ public static func select( /// - Output output: Shape is `[..., M+1, M]`. @inlinable @inline(__always) public static func selfAdjointEig( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SelfAdjointEig", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("SelfAdjointEig", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Computes the eigen decomposition of one or more square self-adjoint matrices. @@ -28212,22 +28042,22 @@ public static func selfAdjointEig( /// - Parameter input: `Tensor` input of shape `[N, N]`. /// /// - Attr compute_v: If `True` then eigenvectors will be computed and returned in `v`. -/// Otherwise, only the eigenvalues will be computed. +/// Otherwise, only the eigenvalues will be computed. /// /// - Outputs: -/// - e: Eigenvalues. Shape is `[N]`. -/// - v: Eigenvectors. Shape is `[N, N]`. +/// - e: Eigenvalues. Shape is `[N]`. +/// - v: Eigenvectors. Shape is `[N, N]`. @inlinable @inline(__always) public static func selfAdjointEigV2( - _ input: Tensor, - computeV: Bool = true + _ input: Tensor, + computeV: Bool = true ) -> (e: Tensor, v: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("SelfAdjointEigV2", nOutputs) - op.updateAttribute("compute_v", computeV) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1), Int(1)) + let op = makeOp("SelfAdjointEigV2", nOutputs) + op.updateAttribute("compute_v", computeV) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) } /// Computes scaled exponential linear: `scale * alpha * (exp(features) - 1)` @@ -28241,67 +28071,67 @@ public static func selfAdjointEigV2( /// See [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515) @inlinable @inline(__always) public static func selu( - features: Tensor + features: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Selu", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(features) - return op.execute(Int(1)) + let op = makeOp("Selu", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) } /// Computes gradients for the scaled exponential linear (Selu) operation. /// /// - Parameters: -/// - gradients: The backpropagated gradients to the corresponding Selu operation. -/// - outputs: The outputs of the corresponding Selu operation. +/// - gradients: The backpropagated gradients to the corresponding Selu operation. +/// - outputs: The outputs of the corresponding Selu operation. /// /// - Output backprops: The gradients: `gradients * (outputs + scale * alpha)` -/// if outputs < 0, `scale * gradients` otherwise. +/// if outputs < 0, `scale * gradients` otherwise. @inlinable @inline(__always) public static func seluGrad( - gradients: Tensor, - outputs: Tensor + gradients: Tensor, + outputs: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SeluGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(gradients) - op.addInput(outputs) - return op.execute(Int(1)) + let op = makeOp("SeluGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(outputs) + return op.execute(Int(1)) } /// Performs gradient updates of embedding tables. /// /// - Parameters: -/// - inputs: A TensorList of gradients with which to update embedding tables. -/// This argument has the same length and shapes as the return value of -/// RecvTPUEmbeddingActivations, but contains gradients of the model's loss -/// with respect to the embedding activations. The embedding tables are updated -/// from these gradients via the optimizer specified in the TPU embedding -/// configuration given to tpu.initialize_system. -/// - learning_rates: A TensorList of float32 scalars, one for each dynamic learning -/// rate tag: see the comments in -/// //third_party/tensorflow/core/protobuf/tpu/optimization_parameters.proto. -/// Multiple tables can share the same dynamic learning rate tag as specified -/// in the configuration. If the learning rates for all tables are constant, -/// this list should be empty. +/// - inputs: A TensorList of gradients with which to update embedding tables. +/// This argument has the same length and shapes as the return value of +/// RecvTPUEmbeddingActivations, but contains gradients of the model's loss +/// with respect to the embedding activations. The embedding tables are updated +/// from these gradients via the optimizer specified in the TPU embedding +/// configuration given to tpu.initialize_system. +/// - learning_rates: A TensorList of float32 scalars, one for each dynamic learning +/// rate tag: see the comments in +/// //third_party/tensorflow/core/protobuf/tpu/optimization_parameters.proto. +/// Multiple tables can share the same dynamic learning rate tag as specified +/// in the configuration. If the learning rates for all tables are constant, +/// this list should be empty. /// /// - Attr config: Serialized TPUEmbeddingConfiguration proto. @inlinable @inline(__always) public static func sendTPUEmbeddingGradients( - inputs: [Tensor], - learningRates: [Tensor], - config: String + inputs: [Tensor], + learningRates: [Tensor], + config: String ) { let nOutputs = 0 - let op = makeOp("SendTPUEmbeddingGradients", nOutputs) - op.updateAttribute("N", inputs.count) - op.updateAttribute("NN", learningRates.count) - op.updateAttribute("config", config) - op.addInputList(inputs) - op.addInputList(learningRates) - op.execute() + let op = makeOp("SendTPUEmbeddingGradients", nOutputs) + op.updateAttribute("N", inputs.count) + op.updateAttribute("NN", learningRates.count) + op.updateAttribute("config", config) + op.addInputList(inputs) + op.addInputList(learningRates) + op.execute() } /// Converts the given `resource_handle` representing an iterator to a variant tensor. @@ -28309,15 +28139,15 @@ public static func sendTPUEmbeddingGradients( /// - Parameter resource_handle: A handle to an iterator resource. /// /// - Output serialized: A variant tensor storing the state of the iterator contained in the -/// resource. +/// resource. @inlinable @inline(__always) public static func serializeIterator( - resourceHandle: ResourceHandle + resourceHandle: ResourceHandle ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("SerializeIterator", nOutputs) - op.addInput(resourceHandle) - return op.execute(Int(1)) + let op = makeOp("SerializeIterator", nOutputs) + op.addInput(resourceHandle) + return op.execute(Int(1)) } /// Serialize an `N`-minibatch `SparseTensor` into an `[N, 3]` `Tensor` object. @@ -28331,29 +28161,29 @@ public static func serializeIterator( /// The minibatch size `N` is extracted from `sparse_shape[0]`. /// /// - Parameters: -/// - sparse_indices: 2-D. The `indices` of the minibatch `SparseTensor`. -/// - sparse_values: 1-D. The `values` of the minibatch `SparseTensor`. -/// - sparse_shape: 1-D. The `shape` of the minibatch `SparseTensor`. +/// - sparse_indices: 2-D. The `indices` of the minibatch `SparseTensor`. +/// - sparse_values: 1-D. The `values` of the minibatch `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the minibatch `SparseTensor`. /// /// - Attr out_type: The `dtype` to use for serialization; the supported types are `string` -/// (default) and `variant`. +/// (default) and `variant`. @inlinable @inline(__always) public static func serializeManySparse< T: TensorFlowScalar, OutType: TensorFlowScalar >( - sparseIndices: Tensor, - sparseValues: Tensor, - sparseShape: Tensor + sparseIndices: Tensor, + sparseValues: Tensor, + sparseShape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SerializeManySparse", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(sparseIndices) - op.addInput(sparseValues) - op.addInput(sparseShape) - return op.execute(Int(1)) + let op = makeOp("SerializeManySparse", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(sparseIndices) + op.addInput(sparseValues) + op.addInput(sparseShape) + return op.execute(Int(1)) } /// Serialize an `N`-minibatch `SparseTensor` into an `[N, 3]` `Tensor` object. @@ -28367,79 +28197,79 @@ public static func serializeManySparse< /// The minibatch size `N` is extracted from `sparse_shape[0]`. /// /// - Parameters: -/// - sparse_indices: 2-D. The `indices` of the minibatch `SparseTensor`. -/// - sparse_values: 1-D. The `values` of the minibatch `SparseTensor`. -/// - sparse_shape: 1-D. The `shape` of the minibatch `SparseTensor`. +/// - sparse_indices: 2-D. The `indices` of the minibatch `SparseTensor`. +/// - sparse_values: 1-D. The `values` of the minibatch `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the minibatch `SparseTensor`. /// /// - Attr out_type: The `dtype` to use for serialization; the supported types are `string` -/// (default) and `variant`. +/// (default) and `variant`. @inlinable @inline(__always) public static func serializeManySparse( - sparseIndices: Tensor, - sparseValues: Tensor, - sparseShape: Tensor + sparseIndices: Tensor, + sparseValues: Tensor, + sparseShape: Tensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("SerializeManySparse", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("out_type", TensorDataType(TF_STRING)) - op.addInput(sparseIndices) - op.addInput(sparseValues) - op.addInput(sparseShape) - return op.execute(Int(1)) + let op = makeOp("SerializeManySparse", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", TensorDataType(TF_STRING)) + op.addInput(sparseIndices) + op.addInput(sparseValues) + op.addInput(sparseShape) + return op.execute(Int(1)) } /// Serialize a `SparseTensor` into a `[3]` `Tensor` object. /// /// - Parameters: -/// - sparse_indices: 2-D. The `indices` of the `SparseTensor`. -/// - sparse_values: 1-D. The `values` of the `SparseTensor`. -/// - sparse_shape: 1-D. The `shape` of the `SparseTensor`. +/// - sparse_indices: 2-D. The `indices` of the `SparseTensor`. +/// - sparse_values: 1-D. The `values` of the `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the `SparseTensor`. /// /// - Attr out_type: The `dtype` to use for serialization; the supported types are `string` -/// (default) and `variant`. +/// (default) and `variant`. @inlinable @inline(__always) public static func serializeSparse< T: TensorFlowScalar, OutType: TensorFlowScalar >( - sparseIndices: Tensor, - sparseValues: Tensor, - sparseShape: Tensor + sparseIndices: Tensor, + sparseValues: Tensor, + sparseShape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SerializeSparse", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(sparseIndices) - op.addInput(sparseValues) - op.addInput(sparseShape) - return op.execute(Int(1)) + let op = makeOp("SerializeSparse", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(sparseIndices) + op.addInput(sparseValues) + op.addInput(sparseShape) + return op.execute(Int(1)) } /// Serialize a `SparseTensor` into a `[3]` `Tensor` object. /// /// - Parameters: -/// - sparse_indices: 2-D. The `indices` of the `SparseTensor`. -/// - sparse_values: 1-D. The `values` of the `SparseTensor`. -/// - sparse_shape: 1-D. The `shape` of the `SparseTensor`. +/// - sparse_indices: 2-D. The `indices` of the `SparseTensor`. +/// - sparse_values: 1-D. The `values` of the `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the `SparseTensor`. /// /// - Attr out_type: The `dtype` to use for serialization; the supported types are `string` -/// (default) and `variant`. +/// (default) and `variant`. @inlinable @inline(__always) public static func serializeSparse( - sparseIndices: Tensor, - sparseValues: Tensor, - sparseShape: Tensor + sparseIndices: Tensor, + sparseValues: Tensor, + sparseShape: Tensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("SerializeSparse", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("out_type", TensorDataType(TF_STRING)) - op.addInput(sparseIndices) - op.addInput(sparseValues) - op.addInput(sparseShape) - return op.execute(Int(1)) + let op = makeOp("SerializeSparse", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", TensorDataType(TF_STRING)) + op.addInput(sparseIndices) + op.addInput(sparseValues) + op.addInput(sparseShape) + return op.execute(Int(1)) } /// Transforms a Tensor into a serialized TensorProto proto. @@ -28451,13 +28281,13 @@ public static func serializeSparse( /// - Output serialized: A serialized TensorProto proto of the input tensor. @inlinable @inline(__always) public static func serializeTensor( - _ tensor: Tensor + _ tensor: Tensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("SerializeTensor", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(tensor) - return op.execute(Int(1)) + let op = makeOp("SerializeTensor", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(tensor) + return op.execute(Int(1)) } /// Number of unique elements along last dimension of input `set`. @@ -28470,28 +28300,28 @@ public static func serializeTensor( /// indices. /// /// - Parameters: -/// - set_indices: 2D `Tensor`, indices of a `SparseTensor`. -/// - set_values: 1D `Tensor`, values of a `SparseTensor`. -/// - set_shape: 1D `Tensor`, shape of a `SparseTensor`. +/// - set_indices: 2D `Tensor`, indices of a `SparseTensor`. +/// - set_values: 1D `Tensor`, values of a `SparseTensor`. +/// - set_shape: 1D `Tensor`, shape of a `SparseTensor`. /// /// - Output size: For `set` ranked `n`, this is a `Tensor` with rank `n-1`, and the same 1st -/// `n-1` dimensions as `set`. Each value is the number of unique elements in -/// the corresponding `[0...n-1]` dimension of `set`. +/// `n-1` dimensions as `set`. Each value is the number of unique elements in +/// the corresponding `[0...n-1]` dimension of `set`. @inlinable @inline(__always) public static func setSize( - setIndices: Tensor, - setValues: Tensor, - setShape: Tensor, - validateIndices: Bool = true + setIndices: Tensor, + setValues: Tensor, + setShape: Tensor, + validateIndices: Bool = true ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SetSize", nOutputs) - op.updateAttribute("validate_indices", validateIndices) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(setIndices) - op.addInput(setValues) - op.addInput(setShape) - return op.execute(Int(1)) + let op = makeOp("SetSize", nOutputs) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(setIndices) + op.addInput(setValues) + op.addInput(setShape) + return op.execute(Int(1)) } /// Number of unique elements along last dimension of input `set`. @@ -28504,28 +28334,28 @@ public static func setSize( /// indices. /// /// - Parameters: -/// - set_indices: 2D `Tensor`, indices of a `SparseTensor`. -/// - set_values: 1D `Tensor`, values of a `SparseTensor`. -/// - set_shape: 1D `Tensor`, shape of a `SparseTensor`. +/// - set_indices: 2D `Tensor`, indices of a `SparseTensor`. +/// - set_values: 1D `Tensor`, values of a `SparseTensor`. +/// - set_shape: 1D `Tensor`, shape of a `SparseTensor`. /// /// - Output size: For `set` ranked `n`, this is a `Tensor` with rank `n-1`, and the same 1st -/// `n-1` dimensions as `set`. Each value is the number of unique elements in -/// the corresponding `[0...n-1]` dimension of `set`. +/// `n-1` dimensions as `set`. Each value is the number of unique elements in +/// the corresponding `[0...n-1]` dimension of `set`. @inlinable @inline(__always) public static func setSize( - setIndices: Tensor, - setValues: StringTensor, - setShape: Tensor, - validateIndices: Bool = true + setIndices: Tensor, + setValues: StringTensor, + setShape: Tensor, + validateIndices: Bool = true ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SetSize", nOutputs) - op.updateAttribute("validate_indices", validateIndices) - op.updateAttribute("T", TensorDataType(TF_STRING)) - op.addInput(setIndices) - op.addInput(setValues) - op.addInput(setShape) - return op.execute(Int(1)) + let op = makeOp("SetSize", nOutputs) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(setIndices) + op.addInput(setValues) + op.addInput(setShape) + return op.execute(Int(1)) } /// Returns the shape of a tensor. @@ -28543,14 +28373,14 @@ public static func shape< T: TensorFlowScalar, OutType: BinaryInteger & TensorFlowScalar >( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Shape", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Shape", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Returns shape of tensors. @@ -28561,40 +28391,38 @@ public static func shapeN< T: TensorFlowScalar, OutType: BinaryInteger & TensorFlowScalar >( - _ input: [Tensor] + _ input: [Tensor] ) -> [Tensor] { let nOutputs = Int(input.count) - let op = makeOp("ShapeN", nOutputs) - op.updateAttribute("N", input.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInputList(input) - return op.execute(Int(input.count)) + let op = makeOp("ShapeN", nOutputs) + op.updateAttribute("N", input.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInputList(input) + return op.execute(Int(input.count)) } /// Creates a `Dataset` that includes only 1/`num_shards` of this dataset. /// /// - Parameters: -/// - num_shards: An integer representing the number of shards operating in parallel. -/// - index: An integer representing the current worker index. +/// - num_shards: An integer representing the number of shards operating in parallel. +/// - index: An integer representing the current worker index. @inlinable @inline(__always) public static func shardDataset( - inputDataset: VariantHandle, - numShards: Tensor, - index: Tensor, - requireNonEmpty: Bool = false, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + numShards: Tensor, + index: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ShardDataset", nOutputs) - op.updateAttribute("require_non_empty", requireNonEmpty) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(numShards) - op.addInput(index) - return op.execute(Int(1)) + let op = makeOp("ShardDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(numShards) + op.addInput(index) + return op.execute(Int(1)) } /// Generate a sharded filename. The filename is printf formatted as @@ -28602,29 +28430,29 @@ public static func shardDataset( /// %s-%05d-of-%05d, basename, shard, num_shards. @inlinable @inline(__always) public static func shardedFilename( - basename: StringTensor, - shard: Tensor, - numShards: Tensor + basename: StringTensor, + shard: Tensor, + numShards: Tensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("ShardedFilename", nOutputs) - op.addInput(basename) - op.addInput(shard) - op.addInput(numShards) - return op.execute(Int(1)) + let op = makeOp("ShardedFilename", nOutputs) + op.addInput(basename) + op.addInput(shard) + op.addInput(numShards) + return op.execute(Int(1)) } /// Generate a glob pattern matching all sharded file names. @inlinable @inline(__always) public static func shardedFilespec( - basename: StringTensor, - numShards: Tensor + basename: StringTensor, + numShards: Tensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("ShardedFilespec", nOutputs) - op.addInput(basename) - op.addInput(numShards) - return op.execute(Int(1)) + let op = makeOp("ShardedFilespec", nOutputs) + op.addInput(basename) + op.addInput(numShards) + return op.execute(Int(1)) } /// Creates a dataset that shuffles and repeats elements from `input_dataset` @@ -28632,73 +28460,73 @@ public static func shardedFilespec( /// pseudorandomly. /// /// - Parameters: -/// - buffer_size: The number of output elements to buffer in an iterator over -/// this dataset. Compare with the `min_after_dequeue` attr when creating a -/// `RandomShuffleQueue`. -/// - seed: A scalar seed for the random number generator. If either `seed` or -/// `seed2` is set to be non-zero, the random number generator is seeded -/// by the given seed. Otherwise, a random seed is used. -/// - seed2: A second scalar seed to avoid seed collision. -/// - count: A scalar representing the number of times the underlying dataset -/// should be repeated. The default is `-1`, which results in infinite repetition. +/// - buffer_size: The number of output elements to buffer in an iterator over +/// this dataset. Compare with the `min_after_dequeue` attr when creating a +/// `RandomShuffleQueue`. +/// - seed: A scalar seed for the random number generator. If either `seed` or +/// `seed2` is set to be non-zero, the random number generator is seeded +/// by the given seed. Otherwise, a random seed is used. +/// - seed2: A second scalar seed to avoid seed collision. +/// - count: A scalar representing the number of times the underlying dataset +/// should be repeated. The default is `-1`, which results in infinite repetition. @inlinable @inline(__always) public static func shuffleAndRepeatDataset( - inputDataset: VariantHandle, - bufferSize: Tensor, - seed: Tensor, - seed2: Tensor, - count: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + bufferSize: Tensor, + seed: Tensor, + seed2: Tensor, + count: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ShuffleAndRepeatDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(bufferSize) - op.addInput(seed) - op.addInput(seed2) - op.addInput(count) - return op.execute(Int(1)) + let op = makeOp("ShuffleAndRepeatDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(bufferSize) + op.addInput(seed) + op.addInput(seed2) + op.addInput(count) + return op.execute(Int(1)) } /// Creates a dataset that shuffles elements from `input_dataset` pseudorandomly. /// /// - Parameters: -/// - buffer_size: The number of output elements to buffer in an iterator over -/// this dataset. Compare with the `min_after_dequeue` attr when creating a -/// `RandomShuffleQueue`. -/// - seed: A scalar seed for the random number generator. If either `seed` or -/// `seed2` is set to be non-zero, the random number generator is seeded -/// by the given seed. Otherwise, a random seed is used. -/// - seed2: A second scalar seed to avoid seed collision. +/// - buffer_size: The number of output elements to buffer in an iterator over +/// this dataset. Compare with the `min_after_dequeue` attr when creating a +/// `RandomShuffleQueue`. +/// - seed: A scalar seed for the random number generator. If either `seed` or +/// `seed2` is set to be non-zero, the random number generator is seeded +/// by the given seed. Otherwise, a random seed is used. +/// - seed2: A second scalar seed to avoid seed collision. /// /// - Attr reshuffle_each_iteration: If true, each iterator over this dataset will be given -/// a different pseudorandomly generated seed, based on a sequence seeded by the -/// `seed` and `seed2` inputs. If false, each iterator will be given the same -/// seed, and repeated iteration over this dataset will yield the exact same -/// sequence of results. +/// a different pseudorandomly generated seed, based on a sequence seeded by the +/// `seed` and `seed2` inputs. If false, each iterator will be given the same +/// seed, and repeated iteration over this dataset will yield the exact same +/// sequence of results. @inlinable @inline(__always) public static func shuffleDataset( - inputDataset: VariantHandle, - bufferSize: Tensor, - seed: Tensor, - seed2: Tensor, - reshuffleEachIteration: Bool = true, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + bufferSize: Tensor, + seed: Tensor, + seed2: Tensor, + reshuffleEachIteration: Bool = true, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ShuffleDataset", nOutputs) - op.updateAttribute("reshuffle_each_iteration", reshuffleEachIteration) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(bufferSize) - op.addInput(seed) - op.addInput(seed2) - return op.execute(Int(1)) + let op = makeOp("ShuffleDataset", nOutputs) + op.updateAttribute("reshuffle_each_iteration", reshuffleEachIteration) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(bufferSize) + op.addInput(seed) + op.addInput(seed2) + return op.execute(Int(1)) } /// Shuts down a running distributed TPU system. @@ -28708,9 +28536,9 @@ public static func shuffleDataset( public static func shutdownDistributedTPU( ) { let nOutputs = 0 - let op = makeOp("ShutdownDistributedTPU", nOutputs) - - op.execute() + let op = makeOp("ShutdownDistributedTPU", nOutputs) + + op.execute() } /// Computes sigmoid of `x` element-wise. @@ -28718,13 +28546,13 @@ public static func shutdownDistributedTPU( /// Specifically, `y = 1 / (1 + exp(-x))`. @inlinable @inline(__always) public static func sigmoid( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Sigmoid", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Sigmoid", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the gradient of the sigmoid of `x` wrt its input. @@ -28733,15 +28561,15 @@ public static func sigmoid( /// `dy` is the corresponding input gradient. @inlinable @inline(__always) public static func sigmoidGrad( - _ y: Tensor, - dy: Tensor + _ y: Tensor, + dy: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SigmoidGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(y) - op.addInput(dy) - return op.execute(Int(1)) + let op = makeOp("SigmoidGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(dy) + return op.execute(Int(1)) } /// Returns an element-wise indication of the sign of a number. @@ -28751,57 +28579,57 @@ public static func sigmoidGrad( /// For complex numbers, `y = sign(x) = x / |x|` if `x != 0`, otherwise `y = 0`. @inlinable @inline(__always) public static func sign( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Sign", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Sign", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func simple( - _ a: Tensor + _ a: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Simple", nOutputs) - op.addInput(a) - return op.execute(Int(1)) + let op = makeOp("Simple", nOutputs) + op.addInput(a) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func simpleStruct( - nA: Int64 + nA: Int64 ) -> [Tensor] { let nOutputs = Int(nA) - let op = makeOp("SimpleStruct", nOutputs) - op.updateAttribute("n_a", nA) - return op.execute(Int(nA)) + let op = makeOp("SimpleStruct", nOutputs) + op.updateAttribute("n_a", nA) + return op.execute(Int(nA)) } /// Computes sin of x element-wise. @inlinable @inline(__always) public static func sin( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Sin", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Sin", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes hyperbolic sine of x element-wise. @inlinable @inline(__always) public static func sinh( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Sinh", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Sinh", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Returns the size of a tensor. @@ -28820,71 +28648,71 @@ public static func size< T: TensorFlowScalar, OutType: BinaryInteger & TensorFlowScalar >( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Size", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Size", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Creates a dataset that skips `count` elements from the `input_dataset`. /// /// - Parameter count: A scalar representing the number of elements from the `input_dataset` -/// that should be skipped. If count is -1, skips everything. +/// that should be skipped. If count is -1, skips everything. @inlinable @inline(__always) public static func skipDataset( - inputDataset: VariantHandle, - count: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + count: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("SkipDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(count) - return op.execute(Int(1)) + let op = makeOp("SkipDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(count) + return op.execute(Int(1)) } /// Parses a text file and creates a batch of examples. /// /// - Attrs: -/// - filename: The corpus's text file name. -/// - batch_size: The size of produced batch. -/// - window_size: The number of words to predict to the left and right of the target. -/// - min_count: The minimum number of word occurrences for it to be included in the -/// vocabulary. -/// - subsample: Threshold for word occurrence. Words that appear with higher -/// frequency will be randomly down-sampled. Set to 0 to disable. +/// - filename: The corpus's text file name. +/// - batch_size: The size of produced batch. +/// - window_size: The number of words to predict to the left and right of the target. +/// - min_count: The minimum number of word occurrences for it to be included in the +/// vocabulary. +/// - subsample: Threshold for word occurrence. Words that appear with higher +/// frequency will be randomly down-sampled. Set to 0 to disable. /// /// - Outputs: -/// - vocab_word: A vector of words in the corpus. -/// - vocab_freq: Frequencies of words. Sorted in the non-ascending order. -/// - words_per_epoch: Number of words per epoch in the data file. -/// - current_epoch: The current epoch number. -/// - total_words_processed: The total number of words processed so far. -/// - examples: A vector of word ids. -/// - labels: A vector of word ids. +/// - vocab_word: A vector of words in the corpus. +/// - vocab_freq: Frequencies of words. Sorted in the non-ascending order. +/// - words_per_epoch: Number of words per epoch in the data file. +/// - current_epoch: The current epoch number. +/// - total_words_processed: The total number of words processed so far. +/// - examples: A vector of word ids. +/// - labels: A vector of word ids. @inlinable @inline(__always) public static func skipgram( - filename: String, - batchSize: Int64, - windowSize: Int64 = 5, - minCount: Int64 = 5, - subsample: Double = 0.001 + filename: String, + batchSize: Int64, + windowSize: Int64 = 5, + minCount: Int64 = 5, + subsample: Double = 0.001 ) -> (vocabWord: StringTensor, vocabFreq: Tensor, wordsPerEpoch: Tensor, currentEpoch: Tensor, totalWordsProcessed: Tensor, examples: Tensor, labels: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("Skipgram", nOutputs) - op.updateAttribute("filename", filename) - op.updateAttribute("batch_size", batchSize) - op.updateAttribute("window_size", windowSize) - op.updateAttribute("min_count", minCount) - op.updateAttribute("subsample", subsample) - return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("Skipgram", nOutputs) + op.updateAttribute("filename", filename) + op.updateAttribute("batch_size", batchSize) + op.updateAttribute("window_size", windowSize) + op.updateAttribute("min_count", minCount) + op.updateAttribute("subsample", subsample) + return op.execute(Int(1), Int(1), Int(1), Int(1), Int(1), Int(1), Int(1)) } /// Return a slice from 'input'. @@ -28897,57 +28725,41 @@ public static func skipgram( /// 0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n) /// /// - Parameters: -/// - begin: begin[i] specifies the offset into the 'i'th dimension of -/// 'input' to slice from. -/// - size: size[i] specifies the number of elements of the 'i'th dimension -/// of 'input' to slice. If size[i] is -1, all remaining elements in dimension -/// i are included in the slice (i.e. this is equivalent to setting -/// size[i] = input.dim_size(i) - begin[i]). +/// - begin: begin[i] specifies the offset into the 'i'th dimension of +/// 'input' to slice from. +/// - size: size[i] specifies the number of elements of the 'i'th dimension +/// of 'input' to slice. If size[i] is -1, all remaining elements in dimension +/// i are included in the slice (i.e. this is equivalent to setting +/// size[i] = input.dim_size(i) - begin[i]). @inlinable @inline(__always) public static func slice< T: TensorFlowScalar, Index: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - begin: Tensor, - size: Tensor + _ input: Tensor, + begin: Tensor, + size: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Slice", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Index", Index.tensorFlowDataType) - op.addInput(input) - op.addInput(begin) - op.addInput(size) - return op.execute(Int(1)) + let op = makeOp("Slice", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Index", Index.tensorFlowDataType) + op.addInput(input) + op.addInput(begin) + op.addInput(size) + return op.execute(Int(1)) } /// Returns a copy of the input tensor. @inlinable @inline(__always) public static func snapshot( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Snapshot", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) -} - -@inlinable @inline(__always) -public static func snapshotDataset( - inputDataset: VariantHandle, - path: StringTensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] -) -> VariantHandle { - let nOutputs = Int(1) - let op = makeOp("SnapshotDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(path) - return op.execute(Int(1)) + let op = makeOp("Snapshot", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Computes softmax activations. @@ -28961,13 +28773,13 @@ public static func snapshotDataset( /// - Output softmax: Same shape as `logits`. @inlinable @inline(__always) public static func softmax( - logits: Tensor + logits: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Softmax", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(logits) - return op.execute(Int(1)) + let op = makeOp("Softmax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(logits) + return op.execute(Int(1)) } /// Computes softmax cross entropy cost and gradients to backpropagate. @@ -28975,89 +28787,89 @@ public static func softmax( /// Inputs are the logits, not probabilities. /// /// - Parameters: -/// - features: batch_size x num_classes matrix -/// - labels: batch_size x num_classes matrix -/// The caller must ensure that each batch of labels represents a valid -/// probability distribution. +/// - features: batch_size x num_classes matrix +/// - labels: batch_size x num_classes matrix +/// The caller must ensure that each batch of labels represents a valid +/// probability distribution. /// /// - Outputs: -/// - loss: Per example loss (batch_size vector). -/// - backprop: backpropagated gradients (batch_size x num_classes matrix). +/// - loss: Per example loss (batch_size vector). +/// - backprop: backpropagated gradients (batch_size x num_classes matrix). @inlinable @inline(__always) public static func softmaxCrossEntropyWithLogits( - features: Tensor, - labels: Tensor + features: Tensor, + labels: Tensor ) -> (loss: Tensor, backprop: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("SoftmaxCrossEntropyWithLogits", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(features) - op.addInput(labels) - return op.execute(Int(1), Int(1)) + let op = makeOp("SoftmaxCrossEntropyWithLogits", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + op.addInput(labels) + return op.execute(Int(1), Int(1)) } /// Computes softplus: `log(exp(features) + 1)`. @inlinable @inline(__always) public static func softplus( - features: Tensor + features: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Softplus", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(features) - return op.execute(Int(1)) + let op = makeOp("Softplus", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) } /// Computes softplus gradients for a softplus operation. /// /// - Parameters: -/// - gradients: The backpropagated gradients to the corresponding softplus operation. -/// - features: The features passed as input to the corresponding softplus operation. +/// - gradients: The backpropagated gradients to the corresponding softplus operation. +/// - features: The features passed as input to the corresponding softplus operation. /// /// - Output backprops: The gradients: `gradients / (1 + exp(-features))`. @inlinable @inline(__always) public static func softplusGrad( - gradients: Tensor, - features: Tensor + gradients: Tensor, + features: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SoftplusGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(gradients) - op.addInput(features) - return op.execute(Int(1)) + let op = makeOp("SoftplusGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(features) + return op.execute(Int(1)) } /// Computes softsign: `features / (abs(features) + 1)`. @inlinable @inline(__always) public static func softsign( - features: Tensor + features: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Softsign", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(features) - return op.execute(Int(1)) + let op = makeOp("Softsign", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(features) + return op.execute(Int(1)) } /// Computes softsign gradients for a softsign operation. /// /// - Parameters: -/// - gradients: The backpropagated gradients to the corresponding softsign operation. -/// - features: The features passed as input to the corresponding softsign operation. +/// - gradients: The backpropagated gradients to the corresponding softsign operation. +/// - features: The features passed as input to the corresponding softsign operation. /// /// - Output backprops: The gradients: `gradients / (1 + abs(features)) ** 2`. @inlinable @inline(__always) public static func softsignGrad( - gradients: Tensor, - features: Tensor + gradients: Tensor, + features: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SoftsignGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(gradients) - op.addInput(features) - return op.execute(Int(1)) + let op = makeOp("SoftsignGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(gradients) + op.addInput(features) + return op.execute(Int(1)) } /// SpaceToBatch for 4-D tensors of type T. @@ -29071,109 +28883,109 @@ public static func softsignGrad( /// block size. /// /// - Parameters: -/// - input: 4-D with shape `[batch, height, width, depth]`. -/// - paddings: 2-D tensor of non-negative integers with shape `[2, 2]`. It specifies -/// the padding of the input with zeros across the spatial dimensions as follows: +/// - input: 4-D with shape `[batch, height, width, depth]`. +/// - paddings: 2-D tensor of non-negative integers with shape `[2, 2]`. It specifies +/// the padding of the input with zeros across the spatial dimensions as follows: /// -/// paddings = [[pad_top, pad_bottom], [pad_left, pad_right]] +/// paddings = [[pad_top, pad_bottom], [pad_left, pad_right]] /// -/// The effective spatial dimensions of the zero-padded input tensor will be: +/// The effective spatial dimensions of the zero-padded input tensor will be: /// -/// height_pad = pad_top + height + pad_bottom -/// width_pad = pad_left + width + pad_right +/// height_pad = pad_top + height + pad_bottom +/// width_pad = pad_left + width + pad_right /// -/// The attr `block_size` must be greater than one. It indicates the block size. +/// The attr `block_size` must be greater than one. It indicates the block size. /// -/// * Non-overlapping blocks of size `block_size x block size` in the height and -/// width dimensions are rearranged into the batch dimension at each location. -/// * The batch of the output tensor is `batch * block_size * block_size`. -/// * Both height_pad and width_pad must be divisible by block_size. +/// * Non-overlapping blocks of size `block_size x block size` in the height and +/// width dimensions are rearranged into the batch dimension at each location. +/// * The batch of the output tensor is `batch * block_size * block_size`. +/// * Both height_pad and width_pad must be divisible by block_size. /// -/// The shape of the output will be: +/// The shape of the output will be: /// -/// [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, -/// depth] +/// [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, +/// depth] /// -/// Some examples: +/// Some examples: /// -/// (1) For the following input of shape `[1, 2, 2, 1]` and block_size of 2: +/// (1) For the following input of shape `[1, 2, 2, 1]` and block_size of 2: /// -/// ``` -/// x = [[[[1], [2]], [[3], [4]]]] -/// ``` +/// ``` +/// x = [[[[1], [2]], [[3], [4]]]] +/// ``` /// -/// The output tensor has shape `[4, 1, 1, 1]` and value: +/// The output tensor has shape `[4, 1, 1, 1]` and value: /// -/// ``` -/// [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] -/// ``` +/// ``` +/// [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] +/// ``` /// -/// (2) For the following input of shape `[1, 2, 2, 3]` and block_size of 2: +/// (2) For the following input of shape `[1, 2, 2, 3]` and block_size of 2: /// -/// ``` -/// x = [[[[1, 2, 3], [4, 5, 6]], -/// [[7, 8, 9], [10, 11, 12]]]] -/// ``` +/// ``` +/// x = [[[[1, 2, 3], [4, 5, 6]], +/// [[7, 8, 9], [10, 11, 12]]]] +/// ``` /// -/// The output tensor has shape `[4, 1, 1, 3]` and value: +/// The output tensor has shape `[4, 1, 1, 3]` and value: /// -/// ``` -/// [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] -/// ``` +/// ``` +/// [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] +/// ``` /// -/// (3) For the following input of shape `[1, 4, 4, 1]` and block_size of 2: +/// (3) For the following input of shape `[1, 4, 4, 1]` and block_size of 2: /// -/// ``` -/// x = [[[[1], [2], [3], [4]], -/// [[5], [6], [7], [8]], -/// [[9], [10], [11], [12]], -/// [[13], [14], [15], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]], +/// [[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` /// -/// The output tensor has shape `[4, 2, 2, 1]` and value: +/// The output tensor has shape `[4, 2, 2, 1]` and value: /// -/// ``` -/// x = [[[[1], [3]], [[9], [11]]], -/// [[[2], [4]], [[10], [12]]], -/// [[[5], [7]], [[13], [15]]], -/// [[[6], [8]], [[14], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [3]], [[9], [11]]], +/// [[[2], [4]], [[10], [12]]], +/// [[[5], [7]], [[13], [15]]], +/// [[[6], [8]], [[14], [16]]]] +/// ``` /// -/// (4) For the following input of shape `[2, 2, 4, 1]` and block_size of 2: +/// (4) For the following input of shape `[2, 2, 4, 1]` and block_size of 2: /// -/// ``` -/// x = [[[[1], [2], [3], [4]], -/// [[5], [6], [7], [8]]], -/// [[[9], [10], [11], [12]], -/// [[13], [14], [15], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]]], +/// [[[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` /// -/// The output tensor has shape `[8, 1, 2, 1]` and value: +/// The output tensor has shape `[8, 1, 2, 1]` and value: /// -/// ``` -/// x = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]], -/// [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]], +/// [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]] +/// ``` /// -/// Among others, this operation is useful for reducing atrous convolution into -/// regular convolution. +/// Among others, this operation is useful for reducing atrous convolution into +/// regular convolution. @inlinable @inline(__always) public static func spaceToBatch< T: TensorFlowScalar, Tpaddings: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - paddings: Tensor, - blockSize: Int64 + _ input: Tensor, + paddings: Tensor, + blockSize: Int64 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SpaceToBatch", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) - op.updateAttribute("block_size", blockSize) - op.addInput(input) - op.addInput(paddings) - return op.execute(Int(1)) + let op = makeOp("SpaceToBatch", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) + op.updateAttribute("block_size", blockSize) + op.addInput(input) + op.addInput(paddings) + return op.execute(Int(1)) } /// SpaceToBatch for N-D tensors of type T. @@ -29188,136 +29000,136 @@ public static func spaceToBatch< /// precise description. /// /// - Parameters: -/// - input: N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`, -/// where spatial_shape has `M` dimensions. -/// - block_shape: 1-D with shape `[M]`, all values must be >= 1. -/// - paddings: 2-D with shape `[M, 2]`, all values must be >= 0. -/// `paddings[i] = [pad_start, pad_end]` specifies the padding for input dimension -/// `i + 1`, which corresponds to spatial dimension `i`. It is required that -/// `block_shape[i]` divides `input_shape[i + 1] + pad_start + pad_end`. +/// - input: N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`, +/// where spatial_shape has `M` dimensions. +/// - block_shape: 1-D with shape `[M]`, all values must be >= 1. +/// - paddings: 2-D with shape `[M, 2]`, all values must be >= 0. +/// `paddings[i] = [pad_start, pad_end]` specifies the padding for input dimension +/// `i + 1`, which corresponds to spatial dimension `i`. It is required that +/// `block_shape[i]` divides `input_shape[i + 1] + pad_start + pad_end`. /// -/// This operation is equivalent to the following steps: +/// This operation is equivalent to the following steps: /// -/// 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the -/// input according to `paddings` to produce `padded` of shape `padded_shape`. +/// 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the +/// input according to `paddings` to produce `padded` of shape `padded_shape`. /// -/// 2. Reshape `padded` to `reshaped_padded` of shape: +/// 2. Reshape `padded` to `reshaped_padded` of shape: /// -/// [batch] + -/// [padded_shape[1] / block_shape[0], -/// block_shape[0], -/// ..., -/// padded_shape[M] / block_shape[M-1], -/// block_shape[M-1]] + -/// remaining_shape +/// [batch] + +/// [padded_shape[1] / block_shape[0], +/// block_shape[0], +/// ..., +/// padded_shape[M] / block_shape[M-1], +/// block_shape[M-1]] + +/// remaining_shape /// -/// 3. Permute dimensions of `reshaped_padded` to produce -/// `permuted_reshaped_padded` of shape: +/// 3. Permute dimensions of `reshaped_padded` to produce +/// `permuted_reshaped_padded` of shape: /// -/// block_shape + -/// [batch] + -/// [padded_shape[1] / block_shape[0], -/// ..., -/// padded_shape[M] / block_shape[M-1]] + -/// remaining_shape +/// block_shape + +/// [batch] + +/// [padded_shape[1] / block_shape[0], +/// ..., +/// padded_shape[M] / block_shape[M-1]] + +/// remaining_shape /// -/// 4. Reshape `permuted_reshaped_padded` to flatten `block_shape` into the batch -/// dimension, producing an output tensor of shape: +/// 4. Reshape `permuted_reshaped_padded` to flatten `block_shape` into the batch +/// dimension, producing an output tensor of shape: /// -/// [batch * prod(block_shape)] + -/// [padded_shape[1] / block_shape[0], -/// ..., -/// padded_shape[M] / block_shape[M-1]] + -/// remaining_shape +/// [batch * prod(block_shape)] + +/// [padded_shape[1] / block_shape[0], +/// ..., +/// padded_shape[M] / block_shape[M-1]] + +/// remaining_shape /// -/// Some examples: +/// Some examples: /// -/// (1) For the following input of shape `[1, 2, 2, 1]`, `block_shape = [2, 2]`, and -/// `paddings = [[0, 0], [0, 0]]`: +/// (1) For the following input of shape `[1, 2, 2, 1]`, `block_shape = [2, 2]`, and +/// `paddings = [[0, 0], [0, 0]]`: /// -/// ``` -/// x = [[[[1], [2]], [[3], [4]]]] -/// ``` +/// ``` +/// x = [[[[1], [2]], [[3], [4]]]] +/// ``` /// -/// The output tensor has shape `[4, 1, 1, 1]` and value: +/// The output tensor has shape `[4, 1, 1, 1]` and value: /// -/// ``` -/// [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] -/// ``` +/// ``` +/// [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] +/// ``` /// -/// (2) For the following input of shape `[1, 2, 2, 3]`, `block_shape = [2, 2]`, and -/// `paddings = [[0, 0], [0, 0]]`: +/// (2) For the following input of shape `[1, 2, 2, 3]`, `block_shape = [2, 2]`, and +/// `paddings = [[0, 0], [0, 0]]`: /// -/// ``` -/// x = [[[[1, 2, 3], [4, 5, 6]], -/// [[7, 8, 9], [10, 11, 12]]]] -/// ``` +/// ``` +/// x = [[[[1, 2, 3], [4, 5, 6]], +/// [[7, 8, 9], [10, 11, 12]]]] +/// ``` /// -/// The output tensor has shape `[4, 1, 1, 3]` and value: +/// The output tensor has shape `[4, 1, 1, 3]` and value: /// -/// ``` -/// [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] -/// ``` +/// ``` +/// [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] +/// ``` /// -/// (3) For the following input of shape `[1, 4, 4, 1]`, `block_shape = [2, 2]`, and -/// `paddings = [[0, 0], [0, 0]]`: +/// (3) For the following input of shape `[1, 4, 4, 1]`, `block_shape = [2, 2]`, and +/// `paddings = [[0, 0], [0, 0]]`: /// -/// ``` -/// x = [[[[1], [2], [3], [4]], -/// [[5], [6], [7], [8]], -/// [[9], [10], [11], [12]], -/// [[13], [14], [15], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]], +/// [[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` /// -/// The output tensor has shape `[4, 2, 2, 1]` and value: +/// The output tensor has shape `[4, 2, 2, 1]` and value: /// -/// ``` -/// x = [[[[1], [3]], [[9], [11]]], -/// [[[2], [4]], [[10], [12]]], -/// [[[5], [7]], [[13], [15]]], -/// [[[6], [8]], [[14], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [3]], [[9], [11]]], +/// [[[2], [4]], [[10], [12]]], +/// [[[5], [7]], [[13], [15]]], +/// [[[6], [8]], [[14], [16]]]] +/// ``` /// -/// (4) For the following input of shape `[2, 2, 4, 1]`, block_shape = `[2, 2]`, and -/// paddings = `[[0, 0], [2, 0]]`: +/// (4) For the following input of shape `[2, 2, 4, 1]`, block_shape = `[2, 2]`, and +/// paddings = `[[0, 0], [2, 0]]`: /// -/// ``` -/// x = [[[[1], [2], [3], [4]], -/// [[5], [6], [7], [8]]], -/// [[[9], [10], [11], [12]], -/// [[13], [14], [15], [16]]]] -/// ``` +/// ``` +/// x = [[[[1], [2], [3], [4]], +/// [[5], [6], [7], [8]]], +/// [[[9], [10], [11], [12]], +/// [[13], [14], [15], [16]]]] +/// ``` /// -/// The output tensor has shape `[8, 1, 3, 1]` and value: +/// The output tensor has shape `[8, 1, 3, 1]` and value: /// -/// ``` -/// x = [[[[0], [1], [3]]], [[[0], [9], [11]]], -/// [[[0], [2], [4]]], [[[0], [10], [12]]], -/// [[[0], [5], [7]]], [[[0], [13], [15]]], -/// [[[0], [6], [8]]], [[[0], [14], [16]]]] -/// ``` +/// ``` +/// x = [[[[0], [1], [3]]], [[[0], [9], [11]]], +/// [[[0], [2], [4]]], [[[0], [10], [12]]], +/// [[[0], [5], [7]]], [[[0], [13], [15]]], +/// [[[0], [6], [8]]], [[[0], [14], [16]]]] +/// ``` /// -/// Among others, this operation is useful for reducing atrous convolution into -/// regular convolution. +/// Among others, this operation is useful for reducing atrous convolution into +/// regular convolution. @inlinable @inline(__always) public static func spaceToBatchND< T: TensorFlowScalar, TblockShape: BinaryInteger & TensorFlowScalar, Tpaddings: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - blockShape: Tensor, - paddings: Tensor + _ input: Tensor, + blockShape: Tensor, + paddings: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SpaceToBatchND", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tblock_shape", TblockShape.tensorFlowDataType) - op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) - op.addInput(input) - op.addInput(blockShape) - op.addInput(paddings) - return op.execute(Int(1)) + let op = makeOp("SpaceToBatchND", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tblock_shape", TblockShape.tensorFlowDataType) + op.updateAttribute("Tpaddings", Tpaddings.tensorFlowDataType) + op.addInput(input) + op.addInput(blockShape) + op.addInput(paddings) + return op.execute(Int(1)) } /// SpaceToDepth for tensors of type T. @@ -29409,17 +29221,17 @@ public static func spaceToBatchND< /// - Attr block_size: The size of the spatial block. @inlinable @inline(__always) public static func spaceToDepth( - _ input: Tensor, - blockSize: Int64, - dataFormat: DataFormat4 = .nhwc + _ input: Tensor, + blockSize: Int64, + dataFormat: DataFormat4 = .nhwc ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SpaceToDepth", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("block_size", blockSize) - op.updateAttribute("data_format", dataFormat.cName) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("SpaceToDepth", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("block_size", blockSize) + op.updateAttribute("data_format", dataFormat.cName) + op.addInput(input) + return op.execute(Int(1)) } /// Adds two `SparseTensor` objects to produce another `SparseTensor`. @@ -29439,39 +29251,39 @@ public static func spaceToDepth( /// In the following shapes, `nnz` is the count after taking `thresh` into account. /// /// - Parameters: -/// - a_indices: 2-D. The `indices` of the first `SparseTensor`, size `[nnz, ndims]` Matrix. -/// - a_values: 1-D. The `values` of the first `SparseTensor`, size `[nnz]` Vector. -/// - a_shape: 1-D. The `shape` of the first `SparseTensor`, size `[ndims]` Vector. -/// - b_indices: 2-D. The `indices` of the second `SparseTensor`, size `[nnz, ndims]` Matrix. -/// - b_values: 1-D. The `values` of the second `SparseTensor`, size `[nnz]` Vector. -/// - b_shape: 1-D. The `shape` of the second `SparseTensor`, size `[ndims]` Vector. -/// - thresh: 0-D. The magnitude threshold that determines if an output value/index -/// pair takes space. +/// - a_indices: 2-D. The `indices` of the first `SparseTensor`, size `[nnz, ndims]` Matrix. +/// - a_values: 1-D. The `values` of the first `SparseTensor`, size `[nnz]` Vector. +/// - a_shape: 1-D. The `shape` of the first `SparseTensor`, size `[ndims]` Vector. +/// - b_indices: 2-D. The `indices` of the second `SparseTensor`, size `[nnz, ndims]` Matrix. +/// - b_values: 1-D. The `values` of the second `SparseTensor`, size `[nnz]` Vector. +/// - b_shape: 1-D. The `shape` of the second `SparseTensor`, size `[ndims]` Vector. +/// - thresh: 0-D. The magnitude threshold that determines if an output value/index +/// pair takes space. @inlinable @inline(__always) public static func sparseAdd< T: Numeric & TensorFlowScalar, Treal: Numeric & TensorFlowScalar >( - aIndices: Tensor, - aValues: Tensor, - aShape: Tensor, - bIndices: Tensor, - bValues: Tensor, - bShape: Tensor, - thresh: Tensor + aIndices: Tensor, + aValues: Tensor, + aShape: Tensor, + bIndices: Tensor, + bValues: Tensor, + bShape: Tensor, + thresh: Tensor ) -> (sumIndices: Tensor, sumValues: Tensor, sumShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("SparseAdd", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Treal", Treal.tensorFlowDataType) - op.addInput(aIndices) - op.addInput(aValues) - op.addInput(aShape) - op.addInput(bIndices) - op.addInput(bValues) - op.addInput(bShape) - op.addInput(thresh) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("SparseAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Treal", Treal.tensorFlowDataType) + op.addInput(aIndices) + op.addInput(aValues) + op.addInput(aShape) + op.addInput(bIndices) + op.addInput(bValues) + op.addInput(bShape) + op.addInput(thresh) + return op.execute(Int(1), Int(1), Int(1)) } /// The gradient operator for the SparseAdd op. @@ -29482,33 +29294,33 @@ public static func sparseAdd< /// values of A and B. /// /// - Parameters: -/// - backprop_val_grad: 1-D with shape `[nnz(sum)]`. The gradient with respect to -/// the non-empty values of the sum. -/// - a_indices: 2-D. The `indices` of the `SparseTensor` A, size `[nnz(A), ndims]`. -/// - b_indices: 2-D. The `indices` of the `SparseTensor` B, size `[nnz(B), ndims]`. -/// - sum_indices: 2-D. The `indices` of the sum `SparseTensor`, size -/// `[nnz(sum), ndims]`. +/// - backprop_val_grad: 1-D with shape `[nnz(sum)]`. The gradient with respect to +/// the non-empty values of the sum. +/// - a_indices: 2-D. The `indices` of the `SparseTensor` A, size `[nnz(A), ndims]`. +/// - b_indices: 2-D. The `indices` of the `SparseTensor` B, size `[nnz(B), ndims]`. +/// - sum_indices: 2-D. The `indices` of the sum `SparseTensor`, size +/// `[nnz(sum), ndims]`. /// /// - Outputs: -/// - a_val_grad: 1-D with shape `[nnz(A)]`. The gradient with respect to the -/// non-empty values of A. -/// - b_val_grad: 1-D with shape `[nnz(B)]`. The gradient with respect to the -/// non-empty values of B. +/// - a_val_grad: 1-D with shape `[nnz(A)]`. The gradient with respect to the +/// non-empty values of A. +/// - b_val_grad: 1-D with shape `[nnz(B)]`. The gradient with respect to the +/// non-empty values of B. @inlinable @inline(__always) public static func sparseAddGrad( - backpropValGrad: Tensor, - aIndices: Tensor, - bIndices: Tensor, - sumIndices: Tensor + backpropValGrad: Tensor, + aIndices: Tensor, + bIndices: Tensor, + sumIndices: Tensor ) -> (aValGrad: Tensor, bValGrad: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("SparseAddGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(backpropValGrad) - op.addInput(aIndices) - op.addInput(bIndices) - op.addInput(sumIndices) - return op.execute(Int(1), Int(1)) + let op = makeOp("SparseAddGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(backpropValGrad) + op.addInput(aIndices) + op.addInput(bIndices) + op.addInput(sumIndices) + return op.execute(Int(1), Int(1)) } /// Concatenates a list of `SparseTensor` along the specified dimension. @@ -29556,33 +29368,33 @@ public static func sparseAddGrad( /// [b c ] [ ] [b c ] /// /// - Parameters: -/// - indices: 2-D. Indices of each input `SparseTensor`. -/// - values: 1-D. Non-empty values of each `SparseTensor`. -/// - shapes: 1-D. Shapes of each `SparseTensor`. +/// - indices: 2-D. Indices of each input `SparseTensor`. +/// - values: 1-D. Non-empty values of each `SparseTensor`. +/// - shapes: 1-D. Shapes of each `SparseTensor`. /// /// - Attr concat_dim: Dimension to concatenate along. Must be in range [-rank, rank), -/// where rank is the number of dimensions in each input `SparseTensor`. +/// where rank is the number of dimensions in each input `SparseTensor`. /// /// - Outputs: -/// - output_indices: 2-D. Indices of the concatenated `SparseTensor`. -/// - output_values: 1-D. Non-empty values of the concatenated `SparseTensor`. -/// - output_shape: 1-D. Shape of the concatenated `SparseTensor`. +/// - output_indices: 2-D. Indices of the concatenated `SparseTensor`. +/// - output_values: 1-D. Non-empty values of the concatenated `SparseTensor`. +/// - output_shape: 1-D. Shape of the concatenated `SparseTensor`. @inlinable @inline(__always) public static func sparseConcat( - indices: [Tensor], - _ values: [Tensor], - shapes: [Tensor], - concatDim: Int64 + indices: [Tensor], + _ values: [Tensor], + shapes: [Tensor], + concatDim: Int64 ) -> (outputIndices: Tensor, outputValues: Tensor, outputShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("SparseConcat", nOutputs) - op.updateAttribute("concat_dim", concatDim) - op.updateAttribute("N", indices.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInputList(indices) - op.addInputList(values) - op.addInputList(shapes) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("SparseConcat", nOutputs) + op.updateAttribute("concat_dim", concatDim) + op.updateAttribute("N", indices.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInputList(indices) + op.addInputList(values) + op.addInputList(shapes) + return op.execute(Int(1), Int(1), Int(1)) } /// Generates sparse cross from a list of sparse and dense tensors. @@ -29625,54 +29437,54 @@ public static func sparseConcat( /// Fingerprint64("e"), Fingerprint64("c"))) /// /// - Parameters: -/// - indices: 2-D. Indices of each input `SparseTensor`. -/// - values: 1-D. values of each `SparseTensor`. -/// - shapes: 1-D. Shapes of each `SparseTensor`. -/// - dense_inputs: 2-D. Columns represented by dense `Tensor`. +/// - indices: 2-D. Indices of each input `SparseTensor`. +/// - values: 1-D. values of each `SparseTensor`. +/// - shapes: 1-D. Shapes of each `SparseTensor`. +/// - dense_inputs: 2-D. Columns represented by dense `Tensor`. /// /// - Attrs: -/// - hashed_output: If true, returns the hash of the cross instead of the string. -/// This will allow us avoiding string manipulations. -/// - num_buckets: It is used if hashed_output is true. -/// output = hashed_value%num_buckets if num_buckets > 0 else hashed_value. -/// - hash_key: Specify the hash_key that will be used by the `FingerprintCat64` -/// function to combine the crosses fingerprints. +/// - hashed_output: If true, returns the hash of the cross instead of the string. +/// This will allow us avoiding string manipulations. +/// - num_buckets: It is used if hashed_output is true. +/// output = hashed_value%num_buckets if num_buckets > 0 else hashed_value. +/// - hash_key: Specify the hash_key that will be used by the `FingerprintCat64` +/// function to combine the crosses fingerprints. /// /// - Outputs: -/// - output_indices: 2-D. Indices of the concatenated `SparseTensor`. -/// - output_values: 1-D. Non-empty values of the concatenated or hashed -/// `SparseTensor`. -/// - output_shape: 1-D. Shape of the concatenated `SparseTensor`. +/// - output_indices: 2-D. Indices of the concatenated `SparseTensor`. +/// - output_values: 1-D. Non-empty values of the concatenated or hashed +/// `SparseTensor`. +/// - output_shape: 1-D. Shape of the concatenated `SparseTensor`. @inlinable @inline(__always) public static func sparseCross< SparseTypes: TensorArrayProtocol, DenseTypes: TensorArrayProtocol, OutType: BinaryInteger & TensorFlowScalar >( - indices: [Tensor], - _ values: SparseTypes, - shapes: [Tensor], - denseInputs: DenseTypes, - hashedOutput: Bool, - numBuckets: Int64, - hashKey: Int64, - internalType: TensorDataType + indices: [Tensor], + _ values: SparseTypes, + shapes: [Tensor], + denseInputs: DenseTypes, + hashedOutput: Bool, + numBuckets: Int64, + hashKey: Int64, + internalType: TensorDataType ) -> (outputIndices: Tensor, outputValues: Tensor, outputShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("SparseCross", nOutputs) - op.updateAttribute("N", indices.count) - op.updateAttribute("hashed_output", hashedOutput) - op.updateAttribute("num_buckets", numBuckets) - op.updateAttribute("hash_key", hashKey) - op.updateAttribute("sparse_types", values._typeList) - op.updateAttribute("dense_types", denseInputs._typeList) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.updateAttribute("internal_type", internalType) - op.addInputList(indices) - op.addInputList(values) - op.addInputList(shapes) - op.addInputList(denseInputs) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("SparseCross", nOutputs) + op.updateAttribute("N", indices.count) + op.updateAttribute("hashed_output", hashedOutput) + op.updateAttribute("num_buckets", numBuckets) + op.updateAttribute("hash_key", hashKey) + op.updateAttribute("sparse_types", values._typeList) + op.updateAttribute("dense_types", denseInputs._typeList) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.updateAttribute("internal_type", internalType) + op.addInputList(indices) + op.addInputList(values) + op.addInputList(shapes) + op.addInputList(denseInputs) + return op.execute(Int(1), Int(1), Int(1)) } /// Generates sparse cross from a list of sparse and dense tensors. @@ -29715,53 +29527,53 @@ public static func sparseCross< /// Fingerprint64("e"), Fingerprint64("c"))) /// /// - Parameters: -/// - indices: 2-D. Indices of each input `SparseTensor`. -/// - values: 1-D. values of each `SparseTensor`. -/// - shapes: 1-D. Shapes of each `SparseTensor`. -/// - dense_inputs: 2-D. Columns represented by dense `Tensor`. +/// - indices: 2-D. Indices of each input `SparseTensor`. +/// - values: 1-D. values of each `SparseTensor`. +/// - shapes: 1-D. Shapes of each `SparseTensor`. +/// - dense_inputs: 2-D. Columns represented by dense `Tensor`. /// /// - Attrs: -/// - hashed_output: If true, returns the hash of the cross instead of the string. -/// This will allow us avoiding string manipulations. -/// - num_buckets: It is used if hashed_output is true. -/// output = hashed_value%num_buckets if num_buckets > 0 else hashed_value. -/// - hash_key: Specify the hash_key that will be used by the `FingerprintCat64` -/// function to combine the crosses fingerprints. +/// - hashed_output: If true, returns the hash of the cross instead of the string. +/// This will allow us avoiding string manipulations. +/// - num_buckets: It is used if hashed_output is true. +/// output = hashed_value%num_buckets if num_buckets > 0 else hashed_value. +/// - hash_key: Specify the hash_key that will be used by the `FingerprintCat64` +/// function to combine the crosses fingerprints. /// /// - Outputs: -/// - output_indices: 2-D. Indices of the concatenated `SparseTensor`. -/// - output_values: 1-D. Non-empty values of the concatenated or hashed -/// `SparseTensor`. -/// - output_shape: 1-D. Shape of the concatenated `SparseTensor`. +/// - output_indices: 2-D. Indices of the concatenated `SparseTensor`. +/// - output_values: 1-D. Non-empty values of the concatenated or hashed +/// `SparseTensor`. +/// - output_shape: 1-D. Shape of the concatenated `SparseTensor`. @inlinable @inline(__always) public static func sparseCross< SparseTypes: TensorArrayProtocol, DenseTypes: TensorArrayProtocol >( - indices: [Tensor], - _ values: SparseTypes, - shapes: [Tensor], - denseInputs: DenseTypes, - hashedOutput: Bool, - numBuckets: Int64, - hashKey: Int64, - internalType: TensorDataType + indices: [Tensor], + _ values: SparseTypes, + shapes: [Tensor], + denseInputs: DenseTypes, + hashedOutput: Bool, + numBuckets: Int64, + hashKey: Int64, + internalType: TensorDataType ) -> (outputIndices: Tensor, outputValues: StringTensor, outputShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("SparseCross", nOutputs) - op.updateAttribute("N", indices.count) - op.updateAttribute("hashed_output", hashedOutput) - op.updateAttribute("num_buckets", numBuckets) - op.updateAttribute("hash_key", hashKey) - op.updateAttribute("sparse_types", values._typeList) - op.updateAttribute("dense_types", denseInputs._typeList) - op.updateAttribute("out_type", TensorDataType(TF_STRING)) - op.updateAttribute("internal_type", internalType) - op.addInputList(indices) - op.addInputList(values) - op.addInputList(shapes) - op.addInputList(denseInputs) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("SparseCross", nOutputs) + op.updateAttribute("N", indices.count) + op.updateAttribute("hashed_output", hashedOutput) + op.updateAttribute("num_buckets", numBuckets) + op.updateAttribute("hash_key", hashKey) + op.updateAttribute("sparse_types", values._typeList) + op.updateAttribute("dense_types", denseInputs._typeList) + op.updateAttribute("out_type", TensorDataType(TF_STRING)) + op.updateAttribute("internal_type", internalType) + op.addInputList(indices) + op.addInputList(values) + op.addInputList(shapes) + op.addInputList(denseInputs) + return op.execute(Int(1), Int(1), Int(1)) } /// Adds up a SparseTensor and a dense Tensor, using these special rules: @@ -29776,28 +29588,28 @@ public static func sparseCross< /// this Op is the resultant non-zero values. /// /// - Parameters: -/// - sp_indices: 2-D. `N x R` matrix with the indices of non-empty values in a -/// SparseTensor, possibly not in canonical ordering. -/// - sp_values: 1-D. `N` non-empty values corresponding to `sp_indices`. -/// - sp_shape: 1-D. Shape of the input SparseTensor. -/// - dense: `R`-D. The dense Tensor operand. +/// - sp_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - sp_values: 1-D. `N` non-empty values corresponding to `sp_indices`. +/// - sp_shape: 1-D. Shape of the input SparseTensor. +/// - dense: `R`-D. The dense Tensor operand. /// /// - Output output: 1-D. The `N` values that are operated on. @inlinable @inline(__always) public static func sparseDenseCwiseAdd( - spIndices: Tensor, - spValues: Tensor, - spShape: Tensor, - dense: Tensor + spIndices: Tensor, + spValues: Tensor, + spShape: Tensor, + dense: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseDenseCwiseAdd", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(spIndices) - op.addInput(spValues) - op.addInput(spShape) - op.addInput(dense) - return op.execute(Int(1)) + let op = makeOp("SparseDenseCwiseAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(spIndices) + op.addInput(spValues) + op.addInput(spShape) + op.addInput(dense) + return op.execute(Int(1)) } /// Component-wise divides a SparseTensor by a dense Tensor. @@ -29806,28 +29618,28 @@ public static func sparseDenseCwiseAdd( /// the other direction. /// /// - Parameters: -/// - sp_indices: 2-D. `N x R` matrix with the indices of non-empty values in a -/// SparseTensor, possibly not in canonical ordering. -/// - sp_values: 1-D. `N` non-empty values corresponding to `sp_indices`. -/// - sp_shape: 1-D. Shape of the input SparseTensor. -/// - dense: `R`-D. The dense Tensor operand. +/// - sp_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - sp_values: 1-D. `N` non-empty values corresponding to `sp_indices`. +/// - sp_shape: 1-D. Shape of the input SparseTensor. +/// - dense: `R`-D. The dense Tensor operand. /// /// - Output output: 1-D. The `N` values that are operated on. @inlinable @inline(__always) public static func sparseDenseCwiseDiv( - spIndices: Tensor, - spValues: Tensor, - spShape: Tensor, - dense: Tensor + spIndices: Tensor, + spValues: Tensor, + spShape: Tensor, + dense: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseDenseCwiseDiv", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(spIndices) - op.addInput(spValues) - op.addInput(spShape) - op.addInput(dense) - return op.execute(Int(1)) + let op = makeOp("SparseDenseCwiseDiv", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(spIndices) + op.addInput(spValues) + op.addInput(spShape) + op.addInput(dense) + return op.execute(Int(1)) } /// Component-wise multiplies a SparseTensor by a dense Tensor. @@ -29840,28 +29652,28 @@ public static func sparseDenseCwiseDiv( /// the other direction. /// /// - Parameters: -/// - sp_indices: 2-D. `N x R` matrix with the indices of non-empty values in a -/// SparseTensor, possibly not in canonical ordering. -/// - sp_values: 1-D. `N` non-empty values corresponding to `sp_indices`. -/// - sp_shape: 1-D. Shape of the input SparseTensor. -/// - dense: `R`-D. The dense Tensor operand. +/// - sp_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - sp_values: 1-D. `N` non-empty values corresponding to `sp_indices`. +/// - sp_shape: 1-D. Shape of the input SparseTensor. +/// - dense: `R`-D. The dense Tensor operand. /// /// - Output output: 1-D. The `N` values that are operated on. @inlinable @inline(__always) public static func sparseDenseCwiseMul( - spIndices: Tensor, - spValues: Tensor, - spShape: Tensor, - dense: Tensor + spIndices: Tensor, + spValues: Tensor, + spShape: Tensor, + dense: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseDenseCwiseMul", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(spIndices) - op.addInput(spValues) - op.addInput(spShape) - op.addInput(dense) - return op.execute(Int(1)) + let op = makeOp("SparseDenseCwiseMul", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(spIndices) + op.addInput(spValues) + op.addInput(spShape) + op.addInput(dense) + return op.execute(Int(1)) } /// Fills empty rows in the input 2-D `SparseTensor` with a default value. @@ -29904,33 +29716,33 @@ public static func sparseDenseCwiseMul( /// reverse_index_map[j] = out_j s.t. indices[j, :] == output_indices[out_j, :] /// /// - Parameters: -/// - indices: 2-D. the indices of the sparse tensor. -/// - values: 1-D. the values of the sparse tensor. -/// - dense_shape: 1-D. the shape of the sparse tensor. -/// - default_value: 0-D. default value to insert into location `[row, 0, ..., 0]` -/// for rows missing from the input sparse tensor. -/// output indices: 2-D. the indices of the filled sparse tensor. +/// - indices: 2-D. the indices of the sparse tensor. +/// - values: 1-D. the values of the sparse tensor. +/// - dense_shape: 1-D. the shape of the sparse tensor. +/// - default_value: 0-D. default value to insert into location `[row, 0, ..., 0]` +/// for rows missing from the input sparse tensor. +/// output indices: 2-D. the indices of the filled sparse tensor. /// /// - Outputs: -/// - output_values: 1-D. the values of the filled sparse tensor. -/// - empty_row_indicator: 1-D. whether the dense row was missing in the -/// input sparse tensor. -/// - reverse_index_map: 1-D. a map from the input indices to the output indices. +/// - output_values: 1-D. the values of the filled sparse tensor. +/// - empty_row_indicator: 1-D. whether the dense row was missing in the +/// input sparse tensor. +/// - reverse_index_map: 1-D. a map from the input indices to the output indices. @inlinable @inline(__always) public static func sparseFillEmptyRows( - indices: Tensor, - _ values: Tensor, - denseShape: Tensor, - defaultValue: Tensor + indices: Tensor, + _ values: Tensor, + denseShape: Tensor, + defaultValue: Tensor ) -> (outputIndices: Tensor, outputValues: Tensor, emptyRowIndicator: Tensor, reverseIndexMap: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) + Int(1) - let op = makeOp("SparseFillEmptyRows", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(indices) - op.addInput(values) - op.addInput(denseShape) - op.addInput(defaultValue) - return op.execute(Int(1), Int(1), Int(1), Int(1)) + let op = makeOp("SparseFillEmptyRows", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(indices) + op.addInput(values) + op.addInput(denseShape) + op.addInput(defaultValue) + return op.execute(Int(1), Int(1), Int(1), Int(1)) } /// The gradient of SparseFillEmptyRows. @@ -29945,23 +29757,23 @@ public static func sparseFillEmptyRows( /// grad_values[k] * 1{k not in reverse_index_map}) /// /// - Parameters: -/// - reverse_index_map: 1-D. The reverse index map from SparseFillEmptyRows. -/// - grad_values: 1-D. The gradients from backprop. +/// - reverse_index_map: 1-D. The reverse index map from SparseFillEmptyRows. +/// - grad_values: 1-D. The gradients from backprop. /// /// - Outputs: -/// - d_values: 1-D. The backprop into values. -/// - d_default_value: 0-D. The backprop into default_value. +/// - d_values: 1-D. The backprop into values. +/// - d_default_value: 0-D. The backprop into default_value. @inlinable @inline(__always) public static func sparseFillEmptyRowsGrad( - reverseIndexMap: Tensor, - gradValues: Tensor + reverseIndexMap: Tensor, + gradValues: Tensor ) -> (dValues: Tensor, dDefaultValue: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("SparseFillEmptyRowsGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(reverseIndexMap) - op.addInput(gradValues) - return op.execute(Int(1), Int(1)) + let op = makeOp("SparseFillEmptyRowsGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(reverseIndexMap) + op.addInput(gradValues) + return op.execute(Int(1), Int(1)) } /// Multiply matrix "a" by matrix "b". @@ -29980,24 +29792,24 @@ public static func sparseMatMul< Ta: FloatingPoint & TensorFlowScalar, Tb: FloatingPoint & TensorFlowScalar >( - _ a: Tensor, - _ b: Tensor, - transposeA: Bool = false, - transposeB: Bool = false, - aIsSparse: Bool = false, - bIsSparse: Bool = false + _ a: Tensor, + _ b: Tensor, + transposeA: Bool = false, + transposeB: Bool = false, + aIsSparse: Bool = false, + bIsSparse: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseMatMul", nOutputs) - op.updateAttribute("transpose_a", transposeA) - op.updateAttribute("transpose_b", transposeB) - op.updateAttribute("a_is_sparse", aIsSparse) - op.updateAttribute("b_is_sparse", bIsSparse) - op.updateAttribute("Ta", Ta.tensorFlowDataType) - op.updateAttribute("Tb", Tb.tensorFlowDataType) - op.addInput(a) - op.addInput(b) - return op.execute(Int(1)) + let op = makeOp("SparseMatMul", nOutputs) + op.updateAttribute("transpose_a", transposeA) + op.updateAttribute("transpose_b", transposeB) + op.updateAttribute("a_is_sparse", aIsSparse) + op.updateAttribute("b_is_sparse", bIsSparse) + op.updateAttribute("Ta", Ta.tensorFlowDataType) + op.updateAttribute("Tb", Tb.tensorFlowDataType) + op.addInput(a) + op.addInput(b) + return op.execute(Int(1)) } /// Computes the max of elements across dimensions of a SparseTensor. @@ -30016,32 +29828,32 @@ public static func sparseMatMul< /// which are interpreted according to the indexing rules in Python. /// /// - Parameters: -/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a -/// SparseTensor, possibly not in canonical ordering. -/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. -/// - input_shape: 1-D. Shape of the input SparseTensor. -/// - reduction_axes: 1-D. Length-`K` vector containing the reduction axes. +/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. +/// - input_shape: 1-D. Shape of the input SparseTensor. +/// - reduction_axes: 1-D. Length-`K` vector containing the reduction axes. /// /// - Attr keep_dims: If true, retain reduced dimensions with length 1. /// /// - Output output: `R-K`-D. The reduced Tensor. @inlinable @inline(__always) public static func sparseReduceMax( - inputIndices: Tensor, - inputValues: Tensor, - inputShape: Tensor, - reductionAxes: Tensor, - keepDims: Bool = false + inputIndices: Tensor, + inputValues: Tensor, + inputShape: Tensor, + reductionAxes: Tensor, + keepDims: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseReduceMax", nOutputs) - op.updateAttribute("keep_dims", keepDims) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(inputIndices) - op.addInput(inputValues) - op.addInput(inputShape) - op.addInput(reductionAxes) - return op.execute(Int(1)) + let op = makeOp("SparseReduceMax", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(inputIndices) + op.addInput(inputValues) + op.addInput(inputShape) + op.addInput(reductionAxes) + return op.execute(Int(1)) } /// Computes the max of elements across dimensions of a SparseTensor. @@ -30060,30 +29872,30 @@ public static func sparseReduceMax( /// which are interpreted according to the indexing rules in Python. /// /// - Parameters: -/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a -/// SparseTensor, possibly not in canonical ordering. -/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. -/// - input_shape: 1-D. Shape of the input SparseTensor. -/// - reduction_axes: 1-D. Length-`K` vector containing the reduction axes. +/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. +/// - input_shape: 1-D. Shape of the input SparseTensor. +/// - reduction_axes: 1-D. Length-`K` vector containing the reduction axes. /// /// - Attr keep_dims: If true, retain reduced dimensions with length 1. @inlinable @inline(__always) public static func sparseReduceMaxSparse( - inputIndices: Tensor, - inputValues: Tensor, - inputShape: Tensor, - reductionAxes: Tensor, - keepDims: Bool = false + inputIndices: Tensor, + inputValues: Tensor, + inputShape: Tensor, + reductionAxes: Tensor, + keepDims: Bool = false ) -> (outputIndices: Tensor, outputValues: Tensor, outputShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("SparseReduceMaxSparse", nOutputs) - op.updateAttribute("keep_dims", keepDims) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(inputIndices) - op.addInput(inputValues) - op.addInput(inputShape) - op.addInput(reductionAxes) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("SparseReduceMaxSparse", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(inputIndices) + op.addInput(inputValues) + op.addInput(inputShape) + op.addInput(reductionAxes) + return op.execute(Int(1), Int(1), Int(1)) } /// Computes the sum of elements across dimensions of a SparseTensor. @@ -30102,32 +29914,32 @@ public static func sparseReduceMaxSparse( /// which are interpreted according to the indexing rules in Python. /// /// - Parameters: -/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a -/// SparseTensor, possibly not in canonical ordering. -/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. -/// - input_shape: 1-D. Shape of the input SparseTensor. -/// - reduction_axes: 1-D. Length-`K` vector containing the reduction axes. +/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. +/// - input_shape: 1-D. Shape of the input SparseTensor. +/// - reduction_axes: 1-D. Length-`K` vector containing the reduction axes. /// /// - Attr keep_dims: If true, retain reduced dimensions with length 1. /// /// - Output output: `R-K`-D. The reduced Tensor. @inlinable @inline(__always) public static func sparseReduceSum( - inputIndices: Tensor, - inputValues: Tensor, - inputShape: Tensor, - reductionAxes: Tensor, - keepDims: Bool = false + inputIndices: Tensor, + inputValues: Tensor, + inputShape: Tensor, + reductionAxes: Tensor, + keepDims: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseReduceSum", nOutputs) - op.updateAttribute("keep_dims", keepDims) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(inputIndices) - op.addInput(inputValues) - op.addInput(inputShape) - op.addInput(reductionAxes) - return op.execute(Int(1)) + let op = makeOp("SparseReduceSum", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(inputIndices) + op.addInput(inputValues) + op.addInput(inputShape) + op.addInput(reductionAxes) + return op.execute(Int(1)) } /// Computes the sum of elements across dimensions of a SparseTensor. @@ -30146,30 +29958,30 @@ public static func sparseReduceSum( /// which are interpreted according to the indexing rules in Python. /// /// - Parameters: -/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a -/// SparseTensor, possibly not in canonical ordering. -/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. -/// - input_shape: 1-D. Shape of the input SparseTensor. -/// - reduction_axes: 1-D. Length-`K` vector containing the reduction axes. +/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. +/// - input_shape: 1-D. Shape of the input SparseTensor. +/// - reduction_axes: 1-D. Length-`K` vector containing the reduction axes. /// /// - Attr keep_dims: If true, retain reduced dimensions with length 1. @inlinable @inline(__always) public static func sparseReduceSumSparse( - inputIndices: Tensor, - inputValues: Tensor, - inputShape: Tensor, - reductionAxes: Tensor, - keepDims: Bool = false + inputIndices: Tensor, + inputValues: Tensor, + inputShape: Tensor, + reductionAxes: Tensor, + keepDims: Bool = false ) -> (outputIndices: Tensor, outputValues: Tensor, outputShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("SparseReduceSumSparse", nOutputs) - op.updateAttribute("keep_dims", keepDims) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(inputIndices) - op.addInput(inputValues) - op.addInput(inputShape) - op.addInput(reductionAxes) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("SparseReduceSumSparse", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(inputIndices) + op.addInput(inputValues) + op.addInput(inputShape) + op.addInput(reductionAxes) + return op.execute(Int(1), Int(1), Int(1)) } /// Reorders a SparseTensor into the canonical, row-major ordering. @@ -30184,28 +29996,28 @@ public static func sparseReduceSumSparse( /// shape `[N, R]`, input_values has length `N`, and input_shape has length `R`. /// /// - Parameters: -/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a -/// SparseTensor, possibly not in canonical ordering. -/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. -/// - input_shape: 1-D. Shape of the input SparseTensor. +/// - input_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, possibly not in canonical ordering. +/// - input_values: 1-D. `N` non-empty values corresponding to `input_indices`. +/// - input_shape: 1-D. Shape of the input SparseTensor. /// /// - Outputs: -/// - output_indices: 2-D. `N x R` matrix with the same indices as input_indices, but -/// in canonical row-major ordering. -/// - output_values: 1-D. `N` non-empty values corresponding to `output_indices`. +/// - output_indices: 2-D. `N x R` matrix with the same indices as input_indices, but +/// in canonical row-major ordering. +/// - output_values: 1-D. `N` non-empty values corresponding to `output_indices`. @inlinable @inline(__always) public static func sparseReorder( - inputIndices: Tensor, - inputValues: Tensor, - inputShape: Tensor + inputIndices: Tensor, + inputValues: Tensor, + inputShape: Tensor ) -> (outputIndices: Tensor, outputValues: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("SparseReorder", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(inputIndices) - op.addInput(inputValues) - op.addInput(inputShape) - return op.execute(Int(1), Int(1)) + let op = makeOp("SparseReorder", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(inputIndices) + op.addInput(inputValues) + op.addInput(inputShape) + return op.execute(Int(1), Int(1)) } /// Reshapes a SparseTensor to represent values in a new dense shape. @@ -30227,29 +30039,29 @@ public static func sparseReorder( /// `output_shape` has length `R_out`. /// /// - Parameters: -/// - input_indices: 2-D. `N x R_in` matrix with the indices of non-empty values in a -/// SparseTensor. -/// - input_shape: 1-D. `R_in` vector with the input SparseTensor's dense shape. -/// - new_shape: 1-D. `R_out` vector with the requested new dense shape. +/// - input_indices: 2-D. `N x R_in` matrix with the indices of non-empty values in a +/// SparseTensor. +/// - input_shape: 1-D. `R_in` vector with the input SparseTensor's dense shape. +/// - new_shape: 1-D. `R_out` vector with the requested new dense shape. /// /// - Outputs: -/// - output_indices: 2-D. `N x R_out` matrix with the updated indices of non-empty -/// values in the output SparseTensor. -/// - output_shape: 1-D. `R_out` vector with the full dense shape of the output -/// SparseTensor. This is the same as `new_shape` but with any -1 dimensions -/// filled in. +/// - output_indices: 2-D. `N x R_out` matrix with the updated indices of non-empty +/// values in the output SparseTensor. +/// - output_shape: 1-D. `R_out` vector with the full dense shape of the output +/// SparseTensor. This is the same as `new_shape` but with any -1 dimensions +/// filled in. @inlinable @inline(__always) public static func sparseReshape( - inputIndices: Tensor, - inputShape: Tensor, - newShape: Tensor + inputIndices: Tensor, + inputShape: Tensor, + newShape: Tensor ) -> (outputIndices: Tensor, outputShape: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("SparseReshape", nOutputs) - op.addInput(inputIndices) - op.addInput(inputShape) - op.addInput(newShape) - return op.execute(Int(1), Int(1)) + let op = makeOp("SparseReshape", nOutputs) + op.addInput(inputIndices) + op.addInput(inputShape) + op.addInput(newShape) + return op.execute(Int(1), Int(1)) } /// Computes the mean along sparse segments of a tensor. @@ -30260,28 +30072,28 @@ public static func sparseReshape( /// dimension, selecting a subset of dimension 0, specified by `indices`. /// /// - Parameters: -/// - indices: A 1-D tensor. Has same rank as `segment_ids`. -/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. +/// - indices: A 1-D tensor. Has same rank as `segment_ids`. +/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. /// /// - Output output: Has same shape as data, except for dimension 0 which -/// has size `k`, the number of segments. +/// has size `k`, the number of segments. @inlinable @inline(__always) public static func sparseSegmentMean< T: FloatingPoint & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - data: Tensor, - indices: Tensor, - segmentIds: Tensor + data: Tensor, + indices: Tensor, + segmentIds: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseSegmentMean", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(data) - op.addInput(indices) - op.addInput(segmentIds) - return op.execute(Int(1)) + let op = makeOp("SparseSegmentMean", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(data) + op.addInput(indices) + op.addInput(segmentIds) + return op.execute(Int(1)) } /// Computes gradients for SparseSegmentMean. @@ -30290,29 +30102,29 @@ public static func sparseSegmentMean< /// value is output_dim0. /// /// - Parameters: -/// - grad: gradient propagated to the SparseSegmentMean op. -/// - indices: indices passed to the corresponding SparseSegmentMean op. -/// - segment_ids: segment_ids passed to the corresponding SparseSegmentMean op. -/// - output_dim0: dimension 0 of "data" passed to SparseSegmentMean op. +/// - grad: gradient propagated to the SparseSegmentMean op. +/// - indices: indices passed to the corresponding SparseSegmentMean op. +/// - segment_ids: segment_ids passed to the corresponding SparseSegmentMean op. +/// - output_dim0: dimension 0 of "data" passed to SparseSegmentMean op. @inlinable @inline(__always) public static func sparseSegmentMeanGrad< T: FloatingPoint & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - grad: Tensor, - indices: Tensor, - segmentIds: Tensor, - outputDim0: Tensor + grad: Tensor, + indices: Tensor, + segmentIds: Tensor, + outputDim0: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseSegmentMeanGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(grad) - op.addInput(indices) - op.addInput(segmentIds) - op.addInput(outputDim0) - return op.execute(Int(1)) + let op = makeOp("SparseSegmentMeanGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(grad) + op.addInput(indices) + op.addInput(segmentIds) + op.addInput(outputDim0) + return op.execute(Int(1)) } /// Computes the mean along sparse segments of a tensor. @@ -30325,33 +30137,33 @@ public static func sparseSegmentMeanGrad< /// for an explanation of segments. /// /// - Parameters: -/// - indices: A 1-D tensor. Has same rank as `segment_ids`. -/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. -/// - num_segments: Should equal the number of distinct segment IDs. +/// - indices: A 1-D tensor. Has same rank as `segment_ids`. +/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. +/// - num_segments: Should equal the number of distinct segment IDs. /// /// - Output output: Has same shape as data, except for dimension 0 which has size -/// `num_segments`. +/// `num_segments`. @inlinable @inline(__always) public static func sparseSegmentMeanWithNumSegments< T: FloatingPoint & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar, Tnumsegments: BinaryInteger & TensorFlowScalar >( - data: Tensor, - indices: Tensor, - segmentIds: Tensor, - numSegments: Tensor + data: Tensor, + indices: Tensor, + segmentIds: Tensor, + numSegments: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseSegmentMeanWithNumSegments", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) - op.addInput(data) - op.addInput(indices) - op.addInput(segmentIds) - op.addInput(numSegments) - return op.execute(Int(1)) + let op = makeOp("SparseSegmentMeanWithNumSegments", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(indices) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) } /// Computes the sum along sparse segments of a tensor divided by the sqrt of N. @@ -30362,28 +30174,28 @@ public static func sparseSegmentMeanWithNumSegments< /// /// /// - Parameters: -/// - indices: A 1-D tensor. Has same rank as `segment_ids`. -/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. +/// - indices: A 1-D tensor. Has same rank as `segment_ids`. +/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. /// /// - Output output: Has same shape as data, except for dimension 0 which -/// has size `k`, the number of segments. +/// has size `k`, the number of segments. @inlinable @inline(__always) public static func sparseSegmentSqrtN< T: FloatingPoint & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - data: Tensor, - indices: Tensor, - segmentIds: Tensor + data: Tensor, + indices: Tensor, + segmentIds: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseSegmentSqrtN", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(data) - op.addInput(indices) - op.addInput(segmentIds) - return op.execute(Int(1)) + let op = makeOp("SparseSegmentSqrtN", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(data) + op.addInput(indices) + op.addInput(segmentIds) + return op.execute(Int(1)) } /// Computes gradients for SparseSegmentSqrtN. @@ -30392,29 +30204,29 @@ public static func sparseSegmentSqrtN< /// value is output_dim0. /// /// - Parameters: -/// - grad: gradient propagated to the SparseSegmentSqrtN op. -/// - indices: indices passed to the corresponding SparseSegmentSqrtN op. -/// - segment_ids: segment_ids passed to the corresponding SparseSegmentSqrtN op. -/// - output_dim0: dimension 0 of "data" passed to SparseSegmentSqrtN op. +/// - grad: gradient propagated to the SparseSegmentSqrtN op. +/// - indices: indices passed to the corresponding SparseSegmentSqrtN op. +/// - segment_ids: segment_ids passed to the corresponding SparseSegmentSqrtN op. +/// - output_dim0: dimension 0 of "data" passed to SparseSegmentSqrtN op. @inlinable @inline(__always) public static func sparseSegmentSqrtNGrad< T: FloatingPoint & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - grad: Tensor, - indices: Tensor, - segmentIds: Tensor, - outputDim0: Tensor + grad: Tensor, + indices: Tensor, + segmentIds: Tensor, + outputDim0: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseSegmentSqrtNGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(grad) - op.addInput(indices) - op.addInput(segmentIds) - op.addInput(outputDim0) - return op.execute(Int(1)) + let op = makeOp("SparseSegmentSqrtNGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(grad) + op.addInput(indices) + op.addInput(segmentIds) + op.addInput(outputDim0) + return op.execute(Int(1)) } /// Computes the sum along sparse segments of a tensor divided by the sqrt of N. @@ -30429,33 +30241,33 @@ public static func sparseSegmentSqrtNGrad< /// for an explanation of segments. /// /// - Parameters: -/// - indices: A 1-D tensor. Has same rank as `segment_ids`. -/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. -/// - num_segments: Should equal the number of distinct segment IDs. +/// - indices: A 1-D tensor. Has same rank as `segment_ids`. +/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. +/// - num_segments: Should equal the number of distinct segment IDs. /// /// - Output output: Has same shape as data, except for dimension 0 which -/// has size `k`, the number of segments. +/// has size `k`, the number of segments. @inlinable @inline(__always) public static func sparseSegmentSqrtNWithNumSegments< T: FloatingPoint & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar, Tnumsegments: BinaryInteger & TensorFlowScalar >( - data: Tensor, - indices: Tensor, - segmentIds: Tensor, - numSegments: Tensor + data: Tensor, + indices: Tensor, + segmentIds: Tensor, + numSegments: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseSegmentSqrtNWithNumSegments", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) - op.addInput(data) - op.addInput(indices) - op.addInput(segmentIds) - op.addInput(numSegments) - return op.execute(Int(1)) + let op = makeOp("SparseSegmentSqrtNWithNumSegments", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(indices) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) } /// Computes the sum along sparse segments of a tensor. @@ -30491,28 +30303,28 @@ public static func sparseSegmentSqrtNWithNumSegments< /// ``` /// /// - Parameters: -/// - indices: A 1-D tensor. Has same rank as `segment_ids`. -/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. +/// - indices: A 1-D tensor. Has same rank as `segment_ids`. +/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. /// /// - Output output: Has same shape as data, except for dimension 0 which -/// has size `k`, the number of segments. +/// has size `k`, the number of segments. @inlinable @inline(__always) public static func sparseSegmentSum< T: Numeric & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - data: Tensor, - indices: Tensor, - segmentIds: Tensor + data: Tensor, + indices: Tensor, + segmentIds: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseSegmentSum", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(data) - op.addInput(indices) - op.addInput(segmentIds) - return op.execute(Int(1)) + let op = makeOp("SparseSegmentSum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(data) + op.addInput(indices) + op.addInput(segmentIds) + return op.execute(Int(1)) } /// Computes the sum along sparse segments of a tensor. @@ -30546,33 +30358,33 @@ public static func sparseSegmentSum< /// ``` /// /// - Parameters: -/// - indices: A 1-D tensor. Has same rank as `segment_ids`. -/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. -/// - num_segments: Should equal the number of distinct segment IDs. +/// - indices: A 1-D tensor. Has same rank as `segment_ids`. +/// - segment_ids: A 1-D tensor. Values should be sorted and can be repeated. +/// - num_segments: Should equal the number of distinct segment IDs. /// /// - Output output: Has same shape as data, except for dimension 0 which -/// has size `num_segments`. +/// has size `num_segments`. @inlinable @inline(__always) public static func sparseSegmentSumWithNumSegments< T: Numeric & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar, Tnumsegments: BinaryInteger & TensorFlowScalar >( - data: Tensor, - indices: Tensor, - segmentIds: Tensor, - numSegments: Tensor + data: Tensor, + indices: Tensor, + segmentIds: Tensor, + numSegments: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseSegmentSumWithNumSegments", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) - op.addInput(data) - op.addInput(indices) - op.addInput(segmentIds) - op.addInput(numSegments) - return op.execute(Int(1)) + let op = makeOp("SparseSegmentSumWithNumSegments", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(indices) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) } /// Slice a `SparseTensor` based on the `start` and `size`. @@ -30594,36 +30406,36 @@ public static func sparseSegmentSumWithNumSegments< /// [ ] /// /// - Parameters: -/// - indices: 2-D tensor represents the indices of the sparse tensor. -/// - values: 1-D tensor represents the values of the sparse tensor. -/// - shape: 1-D. tensor represents the shape of the sparse tensor. -/// - start: 1-D. tensor represents the start of the slice. -/// - size: 1-D. tensor represents the size of the slice. -/// output indices: A list of 1-D tensors represents the indices of the output -/// sparse tensors. +/// - indices: 2-D tensor represents the indices of the sparse tensor. +/// - values: 1-D tensor represents the values of the sparse tensor. +/// - shape: 1-D. tensor represents the shape of the sparse tensor. +/// - start: 1-D. tensor represents the start of the slice. +/// - size: 1-D. tensor represents the size of the slice. +/// output indices: A list of 1-D tensors represents the indices of the output +/// sparse tensors. /// /// - Outputs: -/// - output_values: A list of 1-D tensors represents the values of the output sparse -/// tensors. -/// - output_shape: A list of 1-D tensors represents the shape of the output sparse -/// tensors. +/// - output_values: A list of 1-D tensors represents the values of the output sparse +/// tensors. +/// - output_shape: A list of 1-D tensors represents the shape of the output sparse +/// tensors. @inlinable @inline(__always) public static func sparseSlice( - indices: Tensor, - _ values: Tensor, - shape: Tensor, - start: Tensor, - size: Tensor + indices: Tensor, + _ values: Tensor, + shape: Tensor, + start: Tensor, + size: Tensor ) -> (outputIndices: Tensor, outputValues: Tensor, outputShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("SparseSlice", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(indices) - op.addInput(values) - op.addInput(shape) - op.addInput(start) - op.addInput(size) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("SparseSlice", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(indices) + op.addInput(values) + op.addInput(shape) + op.addInput(start) + op.addInput(size) + return op.execute(Int(1), Int(1), Int(1)) } /// The gradient operator for the SparseSlice op. @@ -30633,28 +30445,28 @@ public static func sparseSlice( /// the non-empty values of input `SparseTensor`. /// /// - Parameters: -/// - backprop_val_grad: 1-D. The gradient with respect to -/// the non-empty values of the sliced `SparseTensor`. -/// - input_indices: 2-D. The `indices` of the input `SparseTensor`. -/// - input_start: 1-D. tensor represents the start of the slice. -/// - output_indices: 2-D. The `indices` of the sliced `SparseTensor`. +/// - backprop_val_grad: 1-D. The gradient with respect to +/// the non-empty values of the sliced `SparseTensor`. +/// - input_indices: 2-D. The `indices` of the input `SparseTensor`. +/// - input_start: 1-D. tensor represents the start of the slice. +/// - output_indices: 2-D. The `indices` of the sliced `SparseTensor`. /// /// - Output val_grad: 1-D. The gradient with respect to the non-empty values of input `SparseTensor`. @inlinable @inline(__always) public static func sparseSliceGrad( - backpropValGrad: Tensor, - inputIndices: Tensor, - inputStart: Tensor, - outputIndices: Tensor + backpropValGrad: Tensor, + inputIndices: Tensor, + inputStart: Tensor, + outputIndices: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseSliceGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(backpropValGrad) - op.addInput(inputIndices) - op.addInput(inputStart) - op.addInput(outputIndices) - return op.execute(Int(1)) + let op = makeOp("SparseSliceGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(backpropValGrad) + op.addInput(inputIndices) + op.addInput(inputStart) + op.addInput(outputIndices) + return op.execute(Int(1)) } /// Applies softmax to a batched N-D `SparseTensor`. @@ -30676,25 +30488,25 @@ public static func sparseSliceGrad( /// shape. /// /// - Parameters: -/// - sp_indices: 2-D. `NNZ x R` matrix with the indices of non-empty values in a -/// SparseTensor, in canonical ordering. -/// - sp_values: 1-D. `NNZ` non-empty values corresponding to `sp_indices`. -/// - sp_shape: 1-D. Shape of the input SparseTensor. +/// - sp_indices: 2-D. `NNZ x R` matrix with the indices of non-empty values in a +/// SparseTensor, in canonical ordering. +/// - sp_values: 1-D. `NNZ` non-empty values corresponding to `sp_indices`. +/// - sp_shape: 1-D. Shape of the input SparseTensor. /// /// - Output output: 1-D. The `NNZ` values for the result `SparseTensor`. @inlinable @inline(__always) public static func sparseSoftmax( - spIndices: Tensor, - spValues: Tensor, - spShape: Tensor + spIndices: Tensor, + spValues: Tensor, + spShape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseSoftmax", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(spIndices) - op.addInput(spValues) - op.addInput(spShape) - return op.execute(Int(1)) + let op = makeOp("SparseSoftmax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(spIndices) + op.addInput(spValues) + op.addInput(spShape) + return op.execute(Int(1)) } /// Computes softmax cross entropy cost and gradients to backpropagate. @@ -30707,28 +30519,28 @@ public static func sparseSoftmax( /// Inputs are the logits, not probabilities. /// /// - Parameters: -/// - features: batch_size x num_classes matrix -/// - labels: batch_size vector with values in [0, num_classes). -/// This is the label for the given minibatch entry. +/// - features: batch_size x num_classes matrix +/// - labels: batch_size vector with values in [0, num_classes). +/// This is the label for the given minibatch entry. /// /// - Outputs: -/// - loss: Per example loss (batch_size vector). -/// - backprop: backpropagated gradients (batch_size x num_classes matrix). +/// - loss: Per example loss (batch_size vector). +/// - backprop: backpropagated gradients (batch_size x num_classes matrix). @inlinable @inline(__always) public static func sparseSoftmaxCrossEntropyWithLogits< T: FloatingPoint & TensorFlowScalar, Tlabels: BinaryInteger & TensorFlowScalar >( - features: Tensor, - labels: Tensor + features: Tensor, + labels: Tensor ) -> (loss: Tensor, backprop: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("SparseSoftmaxCrossEntropyWithLogits", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tlabels", Tlabels.tensorFlowDataType) - op.addInput(features) - op.addInput(labels) - return op.execute(Int(1), Int(1)) + let op = makeOp("SparseSoftmaxCrossEntropyWithLogits", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tlabels", Tlabels.tensorFlowDataType) + op.addInput(features) + op.addInput(labels) + return op.execute(Int(1), Int(1)) } /// Returns the element-wise max of two SparseTensors. @@ -30736,36 +30548,36 @@ public static func sparseSoftmaxCrossEntropyWithLogits< /// Assumes the two SparseTensors have the same shape, i.e., no broadcasting. /// /// - Parameters: -/// - a_indices: 2-D. `N x R` matrix with the indices of non-empty values in a -/// SparseTensor, in the canonical lexicographic ordering. -/// - a_values: 1-D. `N` non-empty values corresponding to `a_indices`. -/// - a_shape: 1-D. Shape of the input SparseTensor. -/// - b_indices: counterpart to `a_indices` for the other operand. -/// - b_values: counterpart to `a_values` for the other operand; must be of the same dtype. -/// - b_shape: counterpart to `a_shape` for the other operand; the two shapes must be equal. +/// - a_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, in the canonical lexicographic ordering. +/// - a_values: 1-D. `N` non-empty values corresponding to `a_indices`. +/// - a_shape: 1-D. Shape of the input SparseTensor. +/// - b_indices: counterpart to `a_indices` for the other operand. +/// - b_values: counterpart to `a_values` for the other operand; must be of the same dtype. +/// - b_shape: counterpart to `a_shape` for the other operand; the two shapes must be equal. /// /// - Outputs: -/// - output_indices: 2-D. The indices of the output SparseTensor. -/// - output_values: 1-D. The values of the output SparseTensor. +/// - output_indices: 2-D. The indices of the output SparseTensor. +/// - output_values: 1-D. The values of the output SparseTensor. @inlinable @inline(__always) public static func sparseSparseMaximum( - aIndices: Tensor, - aValues: Tensor, - aShape: Tensor, - bIndices: Tensor, - bValues: Tensor, - bShape: Tensor + aIndices: Tensor, + aValues: Tensor, + aShape: Tensor, + bIndices: Tensor, + bValues: Tensor, + bShape: Tensor ) -> (outputIndices: Tensor, outputValues: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("SparseSparseMaximum", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(aIndices) - op.addInput(aValues) - op.addInput(aShape) - op.addInput(bIndices) - op.addInput(bValues) - op.addInput(bShape) - return op.execute(Int(1), Int(1)) + let op = makeOp("SparseSparseMaximum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(aIndices) + op.addInput(aValues) + op.addInput(aShape) + op.addInput(bIndices) + op.addInput(bValues) + op.addInput(bShape) + return op.execute(Int(1), Int(1)) } /// Returns the element-wise min of two SparseTensors. @@ -30773,36 +30585,36 @@ public static func sparseSparseMaximum( /// Assumes the two SparseTensors have the same shape, i.e., no broadcasting. /// /// - Parameters: -/// - a_indices: 2-D. `N x R` matrix with the indices of non-empty values in a -/// SparseTensor, in the canonical lexicographic ordering. -/// - a_values: 1-D. `N` non-empty values corresponding to `a_indices`. -/// - a_shape: 1-D. Shape of the input SparseTensor. -/// - b_indices: counterpart to `a_indices` for the other operand. -/// - b_values: counterpart to `a_values` for the other operand; must be of the same dtype. -/// - b_shape: counterpart to `a_shape` for the other operand; the two shapes must be equal. +/// - a_indices: 2-D. `N x R` matrix with the indices of non-empty values in a +/// SparseTensor, in the canonical lexicographic ordering. +/// - a_values: 1-D. `N` non-empty values corresponding to `a_indices`. +/// - a_shape: 1-D. Shape of the input SparseTensor. +/// - b_indices: counterpart to `a_indices` for the other operand. +/// - b_values: counterpart to `a_values` for the other operand; must be of the same dtype. +/// - b_shape: counterpart to `a_shape` for the other operand; the two shapes must be equal. /// /// - Outputs: -/// - output_indices: 2-D. The indices of the output SparseTensor. -/// - output_values: 1-D. The values of the output SparseTensor. +/// - output_indices: 2-D. The indices of the output SparseTensor. +/// - output_values: 1-D. The values of the output SparseTensor. @inlinable @inline(__always) public static func sparseSparseMinimum( - aIndices: Tensor, - aValues: Tensor, - aShape: Tensor, - bIndices: Tensor, - bValues: Tensor, - bShape: Tensor + aIndices: Tensor, + aValues: Tensor, + aShape: Tensor, + bIndices: Tensor, + bValues: Tensor, + bShape: Tensor ) -> (outputIndices: Tensor, outputValues: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("SparseSparseMinimum", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(aIndices) - op.addInput(aValues) - op.addInput(aShape) - op.addInput(bIndices) - op.addInput(bValues) - op.addInput(bShape) - return op.execute(Int(1), Int(1)) + let op = makeOp("SparseSparseMinimum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(aIndices) + op.addInput(aValues) + op.addInput(aShape) + op.addInput(bIndices) + op.addInput(bValues) + op.addInput(bShape) + return op.execute(Int(1), Int(1)) } /// Split a `SparseTensor` into `num_split` tensors along one dimension. @@ -30826,38 +30638,38 @@ public static func sparseSparseMinimum( /// [ ] /// /// - Parameters: -/// - split_dim: 0-D. The dimension along which to split. Must be in the range -/// `[0, rank(shape))`. -/// - indices: 2-D tensor represents the indices of the sparse tensor. -/// - values: 1-D tensor represents the values of the sparse tensor. -/// - shape: 1-D. tensor represents the shape of the sparse tensor. -/// output indices: A list of 1-D tensors represents the indices of the output -/// sparse tensors. +/// - split_dim: 0-D. The dimension along which to split. Must be in the range +/// `[0, rank(shape))`. +/// - indices: 2-D tensor represents the indices of the sparse tensor. +/// - values: 1-D tensor represents the values of the sparse tensor. +/// - shape: 1-D. tensor represents the shape of the sparse tensor. +/// output indices: A list of 1-D tensors represents the indices of the output +/// sparse tensors. /// /// - Attr num_split: The number of ways to split. /// /// - Outputs: -/// - output_values: A list of 1-D tensors represents the values of the output sparse -/// tensors. -/// - output_shape: A list of 1-D tensors represents the shape of the output sparse -/// tensors. +/// - output_values: A list of 1-D tensors represents the values of the output sparse +/// tensors. +/// - output_shape: A list of 1-D tensors represents the shape of the output sparse +/// tensors. @inlinable @inline(__always) public static func sparseSplit( - splitDim: Tensor, - indices: Tensor, - _ values: Tensor, - shape: Tensor, - numSplit: Int64 + splitDim: Tensor, + indices: Tensor, + _ values: Tensor, + shape: Tensor, + numSplit: Int64 ) -> (outputIndices: [Tensor], outputValues: [Tensor], outputShape: [Tensor]) { let nOutputs = Int(numSplit) + Int(numSplit) + Int(numSplit) - let op = makeOp("SparseSplit", nOutputs) - op.updateAttribute("num_split", numSplit) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(splitDim) - op.addInput(indices) - op.addInput(values) - op.addInput(shape) - return op.execute(Int(numSplit), Int(numSplit), Int(numSplit)) + let op = makeOp("SparseSplit", nOutputs) + op.updateAttribute("num_split", numSplit) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(splitDim) + op.addInput(indices) + op.addInput(values) + op.addInput(shape) + return op.execute(Int(numSplit), Int(numSplit), Int(numSplit)) } /// Adds up a `SparseTensor` and a dense `Tensor`, producing a dense `Tensor`. @@ -30865,29 +30677,29 @@ public static func sparseSplit( /// This Op does not require `a_indices` be sorted in standard lexicographic order. /// /// - Parameters: -/// - a_indices: 2-D. The `indices` of the `SparseTensor`, with shape `[nnz, ndims]`. -/// - a_values: 1-D. The `values` of the `SparseTensor`, with shape `[nnz]`. -/// - a_shape: 1-D. The `shape` of the `SparseTensor`, with shape `[ndims]`. -/// - b: `ndims`-D Tensor. With shape `a_shape`. +/// - a_indices: 2-D. The `indices` of the `SparseTensor`, with shape `[nnz, ndims]`. +/// - a_values: 1-D. The `values` of the `SparseTensor`, with shape `[nnz]`. +/// - a_shape: 1-D. The `shape` of the `SparseTensor`, with shape `[ndims]`. +/// - b: `ndims`-D Tensor. With shape `a_shape`. @inlinable @inline(__always) public static func sparseTensorDenseAdd< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - aIndices: Tensor, - aValues: Tensor, - aShape: Tensor, - _ b: Tensor + aIndices: Tensor, + aValues: Tensor, + aShape: Tensor, + _ b: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseTensorDenseAdd", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(aIndices) - op.addInput(aValues) - op.addInput(aShape) - op.addInput(b) - return op.execute(Int(1)) + let op = makeOp("SparseTensorDenseAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(aIndices) + op.addInput(aValues) + op.addInput(aShape) + op.addInput(b) + return op.execute(Int(1)) } /// Multiply SparseTensor (of rank 2) "A" by dense matrix "B". @@ -30903,55 +30715,55 @@ public static func sparseTensorDenseAdd< /// order instead of "row major" order). /// /// - Parameters: -/// - a_indices: 2-D. The `indices` of the `SparseTensor`, size `[nnz, 2]` Matrix. -/// - a_values: 1-D. The `values` of the `SparseTensor`, size `[nnz]` Vector. -/// - a_shape: 1-D. The `shape` of the `SparseTensor`, size `[2]` Vector. -/// - b: 2-D. A dense Matrix. +/// - a_indices: 2-D. The `indices` of the `SparseTensor`, size `[nnz, 2]` Matrix. +/// - a_values: 1-D. The `values` of the `SparseTensor`, size `[nnz]` Vector. +/// - a_shape: 1-D. The `shape` of the `SparseTensor`, size `[2]` Vector. +/// - b: 2-D. A dense Matrix. /// /// - Attrs: -/// - adjoint_a: Use the adjoint of A in the matrix multiply. If A is complex, this -/// is transpose(conj(A)). Otherwise it's transpose(A). -/// - adjoint_b: Use the adjoint of B in the matrix multiply. If B is complex, this -/// is transpose(conj(B)). Otherwise it's transpose(B). +/// - adjoint_a: Use the adjoint of A in the matrix multiply. If A is complex, this +/// is transpose(conj(A)). Otherwise it's transpose(A). +/// - adjoint_b: Use the adjoint of B in the matrix multiply. If B is complex, this +/// is transpose(conj(B)). Otherwise it's transpose(B). @inlinable @inline(__always) public static func sparseTensorDenseMatMul< T: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - aIndices: Tensor, - aValues: Tensor, - aShape: Tensor, - _ b: Tensor, - adjointA: Bool = false, - adjointB: Bool = false -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("SparseTensorDenseMatMul", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("adjoint_a", adjointA) - op.updateAttribute("adjoint_b", adjointB) - op.addInput(aIndices) - op.addInput(aValues) - op.addInput(aShape) - op.addInput(b) - return op.execute(Int(1)) + aIndices: Tensor, + aValues: Tensor, + aShape: Tensor, + _ b: Tensor, + adjointA: Bool = false, + adjointB: Bool = false +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("SparseTensorDenseMatMul", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("adjoint_a", adjointA) + op.updateAttribute("adjoint_b", adjointB) + op.addInput(aIndices) + op.addInput(aValues) + op.addInput(aShape) + op.addInput(b) + return op.execute(Int(1)) } /// Creates a dataset that splits a SparseTensor into elements row-wise. @inlinable @inline(__always) public static func sparseTensorSliceDataset( - indices: Tensor, - _ values: Tensor, - denseShape: Tensor + indices: Tensor, + _ values: Tensor, + denseShape: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("SparseTensorSliceDataset", nOutputs) - op.updateAttribute("Tvalues", Tvalues.tensorFlowDataType) - op.addInput(indices) - op.addInput(values) - op.addInput(denseShape) - return op.execute(Int(1)) + let op = makeOp("SparseTensorSliceDataset", nOutputs) + op.updateAttribute("Tvalues", Tvalues.tensorFlowDataType) + op.addInput(indices) + op.addInput(values) + op.addInput(denseShape) + return op.execute(Int(1)) } /// Converts a sparse representation into a dense tensor. @@ -30977,16 +30789,16 @@ public static func sparseTensorSliceDataset( /// are checked during execution. /// /// - Parameters: -/// - sparse_indices: 0-D, 1-D, or 2-D. `sparse_indices[i]` contains the complete -/// index where `sparse_values[i]` will be placed. -/// - output_shape: 1-D. Shape of the dense output tensor. -/// - sparse_values: 1-D. Values corresponding to each row of `sparse_indices`, -/// or a scalar value to be used for all sparse indices. -/// - default_value: Scalar value to set for indices not specified in -/// `sparse_indices`. +/// - sparse_indices: 0-D, 1-D, or 2-D. `sparse_indices[i]` contains the complete +/// index where `sparse_values[i]` will be placed. +/// - output_shape: 1-D. Shape of the dense output tensor. +/// - sparse_values: 1-D. Values corresponding to each row of `sparse_indices`, +/// or a scalar value to be used for all sparse indices. +/// - default_value: Scalar value to set for indices not specified in +/// `sparse_indices`. /// /// - Attr validate_indices: If true, indices are checked to make sure they are sorted in -/// lexicographic order and that there are no repeats. +/// lexicographic order and that there are no repeats. /// /// - Output dense: Dense output tensor of shape `output_shape`. @inlinable @inline(__always) @@ -30994,22 +30806,22 @@ public static func sparseToDense< T: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - sparseIndices: Tensor, - outputShape: Tensor, - sparseValues: Tensor, - defaultValue: Tensor, - validateIndices: Bool = true + sparseIndices: Tensor, + outputShape: Tensor, + sparseValues: Tensor, + defaultValue: Tensor, + validateIndices: Bool = true ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SparseToDense", nOutputs) - op.updateAttribute("validate_indices", validateIndices) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(sparseIndices) - op.addInput(outputShape) - op.addInput(sparseValues) - op.addInput(defaultValue) - return op.execute(Int(1)) + let op = makeOp("SparseToDense", nOutputs) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(sparseIndices) + op.addInput(outputShape) + op.addInput(sparseValues) + op.addInput(defaultValue) + return op.execute(Int(1)) } /// Applies set operation along last dimension of 2 `SparseTensor` inputs. @@ -31039,50 +30851,50 @@ public static func sparseToDense< /// `[0...n-1]` dimension of `set`. /// /// - Parameters: -/// - set1_indices: 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major -/// order. -/// - set1_values: 1D `Tensor`, values of a `SparseTensor`. Must be in row-major -/// order. -/// - set1_shape: 1D `Tensor`, shape of a `SparseTensor`. `set1_shape[0...n-1]` must -/// be the same as `set2_shape[0...n-1]`, `set1_shape[n]` is the -/// max set size across `0...n-1` dimensions. -/// - set2_indices: 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major -/// order. -/// - set2_values: 1D `Tensor`, values of a `SparseTensor`. Must be in row-major -/// order. -/// - set2_shape: 1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must -/// be the same as `set1_shape[0...n-1]`, `set2_shape[n]` is the -/// max set size across `0...n-1` dimensions. +/// - set1_indices: 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major +/// order. +/// - set1_values: 1D `Tensor`, values of a `SparseTensor`. Must be in row-major +/// order. +/// - set1_shape: 1D `Tensor`, shape of a `SparseTensor`. `set1_shape[0...n-1]` must +/// be the same as `set2_shape[0...n-1]`, `set1_shape[n]` is the +/// max set size across `0...n-1` dimensions. +/// - set2_indices: 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major +/// order. +/// - set2_values: 1D `Tensor`, values of a `SparseTensor`. Must be in row-major +/// order. +/// - set2_shape: 1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must +/// be the same as `set1_shape[0...n-1]`, `set2_shape[n]` is the +/// max set size across `0...n-1` dimensions. /// /// - Outputs: -/// - result_indices: 2D indices of a `SparseTensor`. -/// - result_values: 1D values of a `SparseTensor`. -/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is -/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` -/// is the max result set size across all `0...n-1` dimensions. +/// - result_indices: 2D indices of a `SparseTensor`. +/// - result_values: 1D values of a `SparseTensor`. +/// - result_shape: 1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is +/// the same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]` +/// is the max result set size across all `0...n-1` dimensions. @inlinable @inline(__always) public static func sparseToSparseSetOperation( - set1Indices: Tensor, - set1Values: Tensor, - set1Shape: Tensor, - set2Indices: Tensor, - set2Values: Tensor, - set2Shape: Tensor, - setOperation: String, - validateIndices: Bool = true + set1Indices: Tensor, + set1Values: Tensor, + set1Shape: Tensor, + set2Indices: Tensor, + set2Values: Tensor, + set2Shape: Tensor, + setOperation: String, + validateIndices: Bool = true ) -> (resultIndices: Tensor, resultValues: Tensor, resultShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("SparseToSparseSetOperation", nOutputs) - op.updateAttribute("set_operation", setOperation) - op.updateAttribute("validate_indices", validateIndices) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(set1Indices) - op.addInput(set1Values) - op.addInput(set1Shape) - op.addInput(set2Indices) - op.addInput(set2Values) - op.addInput(set2Shape) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("SparseToSparseSetOperation", nOutputs) + op.updateAttribute("set_operation", setOperation) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(set1Indices) + op.addInput(set1Values) + op.addInput(set1Shape) + op.addInput(set2Indices) + op.addInput(set2Values) + op.addInput(set2Shape) + return op.execute(Int(1), Int(1), Int(1)) } /// Applies set operation along last dimension of 2 `SparseTensor` inputs. @@ -31112,112 +30924,112 @@ public static func sparseToSparseSetOperation, - set1Values: StringTensor, - set1Shape: Tensor, - set2Indices: Tensor, - set2Values: StringTensor, - set2Shape: Tensor, - setOperation: String, - validateIndices: Bool = true + set1Indices: Tensor, + set1Values: StringTensor, + set1Shape: Tensor, + set2Indices: Tensor, + set2Values: StringTensor, + set2Shape: Tensor, + setOperation: String, + validateIndices: Bool = true ) -> (resultIndices: Tensor, resultValues: StringTensor, resultShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("SparseToSparseSetOperation", nOutputs) - op.updateAttribute("set_operation", setOperation) - op.updateAttribute("validate_indices", validateIndices) - op.updateAttribute("T", TensorDataType(TF_STRING)) - op.addInput(set1Indices) - op.addInput(set1Values) - op.addInput(set1Shape) - op.addInput(set2Indices) - op.addInput(set2Values) - op.addInput(set2Shape) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("SparseToSparseSetOperation", nOutputs) + op.updateAttribute("set_operation", setOperation) + op.updateAttribute("validate_indices", validateIndices) + op.updateAttribute("T", TensorDataType(TF_STRING)) + op.addInput(set1Indices) + op.addInput(set1Values) + op.addInput(set1Shape) + op.addInput(set2Indices) + op.addInput(set2Values) + op.addInput(set2Shape) + return op.execute(Int(1), Int(1), Int(1)) } /// Splits a tensor into `num_split` tensors along one dimension. /// /// - Parameters: -/// - split_dim: 0-D. The dimension along which to split. Must be in the range -/// `[-rank(value), rank(value))`. -/// - value: The tensor to split. +/// - split_dim: 0-D. The dimension along which to split. Must be in the range +/// `[-rank(value), rank(value))`. +/// - value: The tensor to split. /// /// - Attr num_split: The number of ways to split. Must evenly divide -/// `value.shape[split_dim]`. +/// `value.shape[split_dim]`. /// /// - Output output: They are identically shaped tensors, whose shape matches that of `value` -/// except along `axis`, where their sizes are -/// `values.shape[split_dim] / num_split`. +/// except along `axis`, where their sizes are +/// `values.shape[split_dim] / num_split`. @inlinable @inline(__always) public static func split( - splitDim: Tensor, - value: Tensor, - numSplit: Int64 + splitDim: Tensor, + value: Tensor, + numSplit: Int64 ) -> [Tensor] { let nOutputs = Int(numSplit) - let op = makeOp("Split", nOutputs) - op.updateAttribute("num_split", numSplit) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(splitDim) - op.addInput(value) - return op.execute(Int(numSplit)) + let op = makeOp("Split", nOutputs) + op.updateAttribute("num_split", numSplit) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(splitDim) + op.addInput(value) + return op.execute(Int(numSplit)) } /// Splits a tensor into `num_split` tensors along one dimension. /// /// - Parameters: -/// - value: The tensor to split. -/// - size_splits: list containing the sizes of each output tensor along the split -/// dimension. Must sum to the dimension of value along split_dim. -/// Can contain one -1 indicating that dimension is to be inferred. -/// - split_dim: 0-D. The dimension along which to split. Must be in the range -/// `[-rank(value), rank(value))`. +/// - value: The tensor to split. +/// - size_splits: list containing the sizes of each output tensor along the split +/// dimension. Must sum to the dimension of value along split_dim. +/// Can contain one -1 indicating that dimension is to be inferred. +/// - split_dim: 0-D. The dimension along which to split. Must be in the range +/// `[-rank(value), rank(value))`. /// /// - Output output: Tensors whose shape matches that of `value` -/// except along `axis`, where their sizes are -/// `size_splits[i]`. +/// except along `axis`, where their sizes are +/// `size_splits[i]`. @inlinable @inline(__always) public static func splitV< T: TensorFlowScalar, Tlen: BinaryInteger & TensorFlowScalar >( - value: Tensor, - sizeSplits: Tensor, - splitDim: Tensor, - numSplit: Int64 + value: Tensor, + sizeSplits: Tensor, + splitDim: Tensor, + numSplit: Int64 ) -> [Tensor] { let nOutputs = Int(numSplit) - let op = makeOp("SplitV", nOutputs) - op.updateAttribute("num_split", numSplit) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tlen", Tlen.tensorFlowDataType) - op.addInput(value) - op.addInput(sizeSplits) - op.addInput(splitDim) - return op.execute(Int(numSplit)) + let op = makeOp("SplitV", nOutputs) + op.updateAttribute("num_split", numSplit) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tlen", Tlen.tensorFlowDataType) + op.addInput(value) + op.addInput(sizeSplits) + op.addInput(splitDim) + return op.execute(Int(numSplit)) } /// Computes square root of x element-wise. @@ -31225,13 +31037,13 @@ public static func splitV< /// I.e., \\(y = \sqrt{x} = x^{1/2}\\). @inlinable @inline(__always) public static func sqrt( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Sqrt", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Sqrt", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the gradient for the sqrt of `x` wrt its input. @@ -31240,15 +31052,15 @@ public static func sqrt( /// is the corresponding input gradient. @inlinable @inline(__always) public static func sqrtGrad( - _ y: Tensor, - dy: Tensor + _ y: Tensor, + dy: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SqrtGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(y) - op.addInput(dy) - return op.execute(Int(1)) + let op = makeOp("SqrtGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(dy) + return op.execute(Int(1)) } /// Computes square of x element-wise. @@ -31256,13 +31068,13 @@ public static func sqrtGrad( /// I.e., \\(y = x * x = x^2\\). @inlinable @inline(__always) public static func square( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Square", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Square", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Returns (x - y)(x - y) element-wise. @@ -31271,15 +31083,15 @@ public static func square( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func squaredDifference( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("SquaredDifference", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("SquaredDifference", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Removes dimensions of size 1 from the shape of a tensor. @@ -31306,22 +31118,22 @@ public static func squaredDifference( /// - Parameter input: The `input` to squeeze. /// /// - Attr squeeze_dims: If specified, only squeezes the dimensions listed. The dimension -/// index starts at 0. It is an error to squeeze a dimension that is not 1. Must -/// be in the range `[-rank(input), rank(input))`. +/// index starts at 0. It is an error to squeeze a dimension that is not 1. Must +/// be in the range `[-rank(input), rank(input))`. /// /// - Output output: Contains the same data as `input`, but has one or more dimensions of -/// size 1 removed. +/// size 1 removed. @inlinable @inline(__always) public static func squeeze( - _ input: Tensor, - squeezeDims: [Int32] + _ input: Tensor, + squeezeDims: [Int32] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Squeeze", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("squeeze_dims", squeezeDims) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Squeeze", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("squeeze_dims", squeezeDims) + op.addInput(input) + return op.execute(Int(1)) } /// Delete the stack from its resource container. @@ -31329,12 +31141,12 @@ public static func squeeze( /// - Parameter handle: The handle to a stack. @inlinable @inline(__always) public static func stackCloseV2( - handle: ResourceHandle + handle: ResourceHandle ) { let nOutputs = 0 - let op = makeOp("StackCloseV2", nOutputs) - op.addInput(handle) - op.execute() + let op = makeOp("StackCloseV2", nOutputs) + op.addInput(handle) + op.execute() } /// Pop the element at the top of the stack. @@ -31346,62 +31158,62 @@ public static func stackCloseV2( /// - Output elem: The tensor that is popped from the top of the stack. @inlinable @inline(__always) public static func stackPopV2( - handle: ResourceHandle + handle: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StackPopV2", nOutputs) - op.updateAttribute("elem_type", ElemType.tensorFlowDataType) - op.addInput(handle) - return op.execute(Int(1)) + let op = makeOp("StackPopV2", nOutputs) + op.updateAttribute("elem_type", ElemType.tensorFlowDataType) + op.addInput(handle) + return op.execute(Int(1)) } /// Push an element onto the stack. /// /// - Parameters: -/// - handle: The handle to a stack. -/// - elem: The tensor to be pushed onto the stack. +/// - handle: The handle to a stack. +/// - elem: The tensor to be pushed onto the stack. /// /// - Attr swap_memory: Swap `elem` to CPU. Default to false. /// /// - Output output: The same tensor as the input 'elem'. @inlinable @inline(__always) public static func stackPushV2( - handle: ResourceHandle, - elem: Tensor, - swapMemory: Bool = false + handle: ResourceHandle, + elem: Tensor, + swapMemory: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StackPushV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("swap_memory", swapMemory) - op.addInput(handle) - op.addInput(elem) - return op.execute(Int(1)) + let op = makeOp("StackPushV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("swap_memory", swapMemory) + op.addInput(handle) + op.addInput(elem) + return op.execute(Int(1)) } /// A stack that produces elements in first-in last-out order. /// /// - Parameter max_size: The maximum size of the stack if non-negative. If negative, the stack -/// size is unlimited. +/// size is unlimited. /// /// - Attrs: -/// - elem_type: The type of the elements on the stack. -/// - stack_name: Overrides the name used for the temporary stack resource. Default -/// value is the name of the 'Stack' op (which is guaranteed unique). +/// - elem_type: The type of the elements on the stack. +/// - stack_name: Overrides the name used for the temporary stack resource. Default +/// value is the name of the 'Stack' op (which is guaranteed unique). /// /// - Output handle: The handle to the stack. @inlinable @inline(__always) public static func stackV2( - maxSize: Tensor, - elemType: TensorDataType, - stackName: String + maxSize: Tensor, + elemType: TensorDataType, + stackName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("StackV2", nOutputs) - op.updateAttribute("elem_type", elemType) - op.updateAttribute("stack_name", stackName) - op.addInput(maxSize) - return op.execute(Int(1)) + let op = makeOp("StackV2", nOutputs) + op.updateAttribute("elem_type", elemType) + op.updateAttribute("stack_name", stackName) + op.addInput(maxSize) + return op.execute(Int(1)) } /// Stage values similar to a lightweight Enqueue. @@ -31410,52 +31222,52 @@ public static func stackV2( /// fewer capabilities and options. This Op is optimized for performance. /// /// - Parameter values: a list of tensors -/// dtypes A list of data types that inserted values should adhere to. +/// dtypes A list of data types that inserted values should adhere to. /// /// - Attrs: -/// - capacity: Maximum number of elements in the Staging Area. If > 0, inserts -/// on the container will block when the capacity is reached. -/// - memory_limit: The maximum number of bytes allowed for Tensors in the Staging Area. -/// If > 0, inserts will block until sufficient space is available. -/// - container: If non-empty, this queue is placed in the given container. Otherwise, -/// a default container is used. -/// - shared_name: It is necessary to match this name to the matching Unstage Op. +/// - capacity: Maximum number of elements in the Staging Area. If > 0, inserts +/// on the container will block when the capacity is reached. +/// - memory_limit: The maximum number of bytes allowed for Tensors in the Staging Area. +/// If > 0, inserts will block until sufficient space is available. +/// - container: If non-empty, this queue is placed in the given container. Otherwise, +/// a default container is used. +/// - shared_name: It is necessary to match this name to the matching Unstage Op. @inlinable @inline(__always) public static func stage( - _ values: Dtypes, - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - container: String, - sharedName: String + _ values: Dtypes, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String ) { let nOutputs = 0 - let op = makeOp("Stage", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", values._typeList) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.addInputList(values) - op.execute() + let op = makeOp("Stage", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", values._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInputList(values) + op.execute() } /// Op removes all elements in the underlying container. @inlinable @inline(__always) public static func stageClear( - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - dtypes: [TensorDataType], - container: String, - sharedName: String + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String ) { let nOutputs = 0 - let op = makeOp("StageClear", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", dtypes) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.execute() + let op = makeOp("StageClear", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.execute() } /// Op peeks at the values at the specified index. If the @@ -31465,40 +31277,40 @@ public static func stageClear( /// performance. @inlinable @inline(__always) public static func stagePeek( - index: Tensor, - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - container: String, - sharedName: String + index: Tensor, + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String ) -> Dtypes { let nOutputs = Int(Dtypes._typeList.count) - let op = makeOp("StagePeek", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", Dtypes._typeList) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.addInput(index) - return op.execute(Int(Dtypes._typeList.count)) + let op = makeOp("StagePeek", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(index) + return op.execute(Int(Dtypes._typeList.count)) } /// Op returns the number of elements in the underlying container. @inlinable @inline(__always) public static func stageSize( - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - dtypes: [TensorDataType], - container: String, - sharedName: String + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + dtypes: [TensorDataType], + container: String, + sharedName: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StageSize", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", dtypes) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("StageSize", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", dtypes) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// returns `f(inputs)`, where `f`'s body is placed and partitioned. @@ -31506,13 +31318,13 @@ public static func stageSize( /// - Parameter args: A list of input tensors. /// /// - Attrs: -/// - Tin: A list of input types. -/// - Tout: A list of output types. -/// - f: A function that takes 'args', a list of tensors, and returns 'output', -/// another list of tensors. Input and output types are specified by 'Tin' -/// and 'Tout'. The function body of f will be placed and partitioned across -/// devices, setting this op apart from the regular Call op. This op is -/// stateful. +/// - Tin: A list of input types. +/// - Tout: A list of output types. +/// - f: A function that takes 'args', a list of tensors, and returns 'output', +/// another list of tensors. Input and output types are specified by 'Tin' +/// and 'Tout'. The function body of f will be placed and partitioned across +/// devices, setting this op apart from the regular Call op. This op is +/// stateful. /// /// - Output output: A list of return values. @inlinable @inline(__always) @@ -31522,22 +31334,22 @@ public static func statefulPartitionedCall< FIn: TensorGroup, FOut: TensorGroup >( - args: Tin, - f: (FIn) -> FOut, - config: String, - configProto: String, - executorType: String + args: Tin, + f: (FIn) -> FOut, + config: String, + configProto: String, + executorType: String ) -> Tout { let nOutputs = Int(Tout._typeList.count) - let op = makeOp("StatefulPartitionedCall", nOutputs) - op.updateAttribute("Tin", args._typeList) - op.updateAttribute("Tout", Tout._typeList) - op.updateAttribute("f", f) - op.updateAttribute("config", config) - op.updateAttribute("config_proto", configProto) - op.updateAttribute("executor_type", executorType) - op.addInputList(args) - return op.execute(Int(Tout._typeList.count)) + let op = makeOp("StatefulPartitionedCall", nOutputs) + op.updateAttribute("Tin", args._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("f", f) + op.updateAttribute("config", config) + op.updateAttribute("config_proto", configProto) + op.updateAttribute("executor_type", executorType) + op.addInputList(args) + return op.execute(Int(Tout._typeList.count)) } @inlinable @inline(__always) @@ -31546,23 +31358,23 @@ public static func statefulRandomBinomial< T: Numeric & TensorFlowScalar, Dtype: Numeric & TensorFlowScalar >( - resource: ResourceHandle, - algorithm: Tensor, - shape: Tensor, - counts: Tensor, - probs: Tensor + resource: ResourceHandle, + algorithm: Tensor, + shape: Tensor, + counts: Tensor, + probs: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StatefulRandomBinomial", nOutputs) - op.updateAttribute("S", S.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(resource) - op.addInput(algorithm) - op.addInput(shape) - op.addInput(counts) - op.addInput(probs) - return op.execute(Int(1)) + let op = makeOp("StatefulRandomBinomial", nOutputs) + op.updateAttribute("S", S.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(algorithm) + op.addInput(shape) + op.addInput(counts) + op.addInput(probs) + return op.execute(Int(1)) } /// Outputs random values from a normal distribution. This op is deprecated in favor of op 'StatefulStandardNormalV2' @@ -31570,8 +31382,8 @@ public static func statefulRandomBinomial< /// The generated values will have mean 0 and standard deviation 1. /// /// - Parameters: -/// - resource: The handle of the resource variable that stores the state of the RNG. -/// - shape: The shape of the output tensor. +/// - resource: The handle of the resource variable that stores the state of the RNG. +/// - shape: The shape of the output tensor. /// /// - Attr dtype: The type of the output. /// @@ -31581,16 +31393,16 @@ public static func statefulStandardNormal< Dtype: TensorFlowScalar, ShapeDtype: TensorFlowScalar >( - resource: ResourceHandle, - shape: Tensor + resource: ResourceHandle, + shape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StatefulStandardNormal", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) - op.addInput(resource) - op.addInput(shape) - return op.execute(Int(1)) + let op = makeOp("StatefulStandardNormal", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(shape) + return op.execute(Int(1)) } /// Outputs random values from a normal distribution. @@ -31598,9 +31410,9 @@ public static func statefulStandardNormal< /// The generated values will have mean 0 and standard deviation 1. /// /// - Parameters: -/// - resource: The handle of the resource variable that stores the state of the RNG. -/// - algorithm: The RNG algorithm. -/// - shape: The shape of the output tensor. +/// - resource: The handle of the resource variable that stores the state of the RNG. +/// - algorithm: The RNG algorithm. +/// - shape: The shape of the output tensor. /// /// - Attr dtype: The type of the output. /// @@ -31610,18 +31422,18 @@ public static func statefulStandardNormalV2< Dtype: TensorFlowScalar, ShapeDtype: TensorFlowScalar >( - resource: ResourceHandle, - algorithm: Tensor, - shape: Tensor + resource: ResourceHandle, + algorithm: Tensor, + shape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StatefulStandardNormalV2", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) - op.addInput(resource) - op.addInput(algorithm) - op.addInput(shape) - return op.execute(Int(1)) + let op = makeOp("StatefulStandardNormalV2", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(algorithm) + op.addInput(shape) + return op.execute(Int(1)) } /// Outputs random values from a truncated normal distribution. @@ -31631,9 +31443,9 @@ public static func statefulStandardNormalV2< /// deviations from the mean are dropped and re-picked. /// /// - Parameters: -/// - resource: The handle of the resource variable that stores the state of the RNG. -/// - algorithm: The RNG algorithm. -/// - shape: The shape of the output tensor. +/// - resource: The handle of the resource variable that stores the state of the RNG. +/// - algorithm: The RNG algorithm. +/// - shape: The shape of the output tensor. /// /// - Attr dtype: The type of the output. /// @@ -31643,18 +31455,18 @@ public static func statefulTruncatedNormal< Dtype: TensorFlowScalar, ShapeDtype: TensorFlowScalar >( - resource: ResourceHandle, - algorithm: Tensor, - shape: Tensor + resource: ResourceHandle, + algorithm: Tensor, + shape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StatefulTruncatedNormal", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) - op.addInput(resource) - op.addInput(algorithm) - op.addInput(shape) - return op.execute(Int(1)) + let op = makeOp("StatefulTruncatedNormal", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(algorithm) + op.addInput(shape) + return op.execute(Int(1)) } /// Outputs random values from a uniform distribution. @@ -31663,9 +31475,9 @@ public static func statefulTruncatedNormal< /// lower bound 0 is included in the range, while the upper bound 1 is excluded. /// /// - Parameters: -/// - resource: The handle of the resource variable that stores the state of the RNG. -/// - algorithm: The RNG algorithm. -/// - shape: The shape of the output tensor. +/// - resource: The handle of the resource variable that stores the state of the RNG. +/// - algorithm: The RNG algorithm. +/// - shape: The shape of the output tensor. /// /// - Attr dtype: The type of the output. /// @@ -31675,18 +31487,18 @@ public static func statefulUniform< Dtype: TensorFlowScalar, ShapeDtype: TensorFlowScalar >( - resource: ResourceHandle, - algorithm: Tensor, - shape: Tensor + resource: ResourceHandle, + algorithm: Tensor, + shape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StatefulUniform", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) - op.addInput(resource) - op.addInput(algorithm) - op.addInput(shape) - return op.execute(Int(1)) + let op = makeOp("StatefulUniform", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(algorithm) + op.addInput(shape) + return op.execute(Int(1)) } /// Outputs random integers from a uniform distribution. @@ -31694,9 +31506,9 @@ public static func statefulUniform< /// The generated values are uniform integers covering the whole range of `dtype`. /// /// - Parameters: -/// - resource: The handle of the resource variable that stores the state of the RNG. -/// - algorithm: The RNG algorithm. -/// - shape: The shape of the output tensor. +/// - resource: The handle of the resource variable that stores the state of the RNG. +/// - algorithm: The RNG algorithm. +/// - shape: The shape of the output tensor. /// /// - Attr dtype: The type of the output. /// @@ -31706,18 +31518,18 @@ public static func statefulUniformFullInt< Dtype: TensorFlowScalar, ShapeDtype: TensorFlowScalar >( - resource: ResourceHandle, - algorithm: Tensor, - shape: Tensor + resource: ResourceHandle, + algorithm: Tensor, + shape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StatefulUniformFullInt", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) - op.addInput(resource) - op.addInput(algorithm) - op.addInput(shape) - return op.execute(Int(1)) + let op = makeOp("StatefulUniformFullInt", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(algorithm) + op.addInput(shape) + return op.execute(Int(1)) } /// Outputs random integers from a uniform distribution. @@ -31731,11 +31543,11 @@ public static func statefulUniformFullInt< /// smaller than the range of the output (either `2^32` or `2^64`). /// /// - Parameters: -/// - resource: The handle of the resource variable that stores the state of the RNG. -/// - algorithm: The RNG algorithm. -/// - shape: The shape of the output tensor. -/// - minval: Minimum value (inclusive, scalar). -/// - maxval: Maximum value (exclusive, scalar). +/// - resource: The handle of the resource variable that stores the state of the RNG. +/// - algorithm: The RNG algorithm. +/// - shape: The shape of the output tensor. +/// - minval: Minimum value (inclusive, scalar). +/// - maxval: Maximum value (exclusive, scalar). /// /// - Attr dtype: The type of the output. /// @@ -31745,45 +31557,45 @@ public static func statefulUniformInt< Dtype: TensorFlowScalar, ShapeDtype: TensorFlowScalar >( - resource: ResourceHandle, - algorithm: Tensor, - shape: Tensor, - minval: Tensor, - maxval: Tensor + resource: ResourceHandle, + algorithm: Tensor, + shape: Tensor, + minval: Tensor, + maxval: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StatefulUniformInt", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) - op.addInput(resource) - op.addInput(algorithm) - op.addInput(shape) - op.addInput(minval) - op.addInput(maxval) - return op.execute(Int(1)) + let op = makeOp("StatefulUniformInt", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("shape_dtype", ShapeDtype.tensorFlowDataType) + op.addInput(resource) + op.addInput(algorithm) + op.addInput(shape) + op.addInput(minval) + op.addInput(maxval) + return op.execute(Int(1)) } /// output = cond ? then_branch(input) : else_branch(input) /// /// - Parameters: -/// - cond: A Tensor. If the tensor is a scalar of non-boolean type, the -/// scalar is converted to a boolean according to the -/// following rule: if the scalar is a numerical value, non-zero means -/// `True` and zero means False; if the scalar is a string, non-empty -/// means `True` and empty means `False`. If the tensor is not a scalar, -/// being empty means False and being non-empty means True. +/// - cond: A Tensor. If the tensor is a scalar of non-boolean type, the +/// scalar is converted to a boolean according to the +/// following rule: if the scalar is a numerical value, non-zero means +/// `True` and zero means False; if the scalar is a string, non-empty +/// means `True` and empty means `False`. If the tensor is not a scalar, +/// being empty means False and being non-empty means True. /// -/// This should only be used when the if then/else body functions do not -/// have stateful ops. -/// - input: A list of input tensors. +/// This should only be used when the if then/else body functions do not +/// have stateful ops. +/// - input: A list of input tensors. /// /// - Attrs: -/// - Tin: A list of input types. -/// - Tout: A list of output types. -/// - then_branch: A function that takes 'inputs' and returns a list of tensors, whose -/// types are the same as what else_branch returns. -/// - else_branch: A function that takes 'inputs' and returns a list of tensors, whose -/// types are the same as what then_branch returns. +/// - Tin: A list of input types. +/// - Tout: A list of output types. +/// - then_branch: A function that takes 'inputs' and returns a list of tensors, whose +/// types are the same as what else_branch returns. +/// - else_branch: A function that takes 'inputs' and returns a list of tensors, whose +/// types are the same as what then_branch returns. /// /// - Output output: A list of return values. @inlinable @inline(__always) @@ -31796,52 +31608,52 @@ public static func statelessIf< ElsebranchIn: TensorGroup, ElsebranchOut: TensorGroup >( - cond: Tensor, - _ input: Tin, - thenBranch: (ThenbranchIn) -> ThenbranchOut, - elseBranch: (ElsebranchIn) -> ElsebranchOut + cond: Tensor, + _ input: Tin, + thenBranch: (ThenbranchIn) -> ThenbranchOut, + elseBranch: (ElsebranchIn) -> ElsebranchOut ) -> Tout { let nOutputs = Int(Tout._typeList.count) - let op = makeOp("StatelessIf", nOutputs) - op.updateAttribute("Tcond", Tcond.tensorFlowDataType) - op.updateAttribute("Tin", input._typeList) - op.updateAttribute("Tout", Tout._typeList) - op.updateAttribute("then_branch", thenBranch) - op.updateAttribute("else_branch", elseBranch) - op.addInput(cond) - op.addInputList(input) - return op.execute(Int(Tout._typeList.count)) + let op = makeOp("StatelessIf", nOutputs) + op.updateAttribute("Tcond", Tcond.tensorFlowDataType) + op.updateAttribute("Tin", input._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("then_branch", thenBranch) + op.updateAttribute("else_branch", elseBranch) + op.addInput(cond) + op.addInputList(input) + return op.execute(Int(Tout._typeList.count)) } /// Draws samples from a multinomial distribution. /// /// - Parameters: -/// - logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]` -/// represents the unnormalized log probabilities for all classes. -/// - num_samples: 0-D. Number of independent samples to draw for each row slice. -/// - seed: 2 seeds (shape [2]). +/// - logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]` +/// represents the unnormalized log probabilities for all classes. +/// - num_samples: 0-D. Number of independent samples to draw for each row slice. +/// - seed: 2 seeds (shape [2]). /// /// - Output output: 2-D Tensor with shape `[batch_size, num_samples]`. Each slice `[i, :]` -/// contains the drawn class labels with range `[0, num_classes)`. +/// contains the drawn class labels with range `[0, num_classes)`. @inlinable @inline(__always) public static func statelessMultinomial< T: Numeric & TensorFlowScalar, Tseed: BinaryInteger & TensorFlowScalar, OutputDtype: BinaryInteger & TensorFlowScalar >( - logits: Tensor, - numSamples: Tensor, - seed: Tensor + logits: Tensor, + numSamples: Tensor, + seed: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StatelessMultinomial", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tseed", Tseed.tensorFlowDataType) - op.updateAttribute("output_dtype", OutputDtype.tensorFlowDataType) - op.addInput(logits) - op.addInput(numSamples) - op.addInput(seed) - return op.execute(Int(1)) + let op = makeOp("StatelessMultinomial", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tseed", Tseed.tensorFlowDataType) + op.updateAttribute("output_dtype", OutputDtype.tensorFlowDataType) + op.addInput(logits) + op.addInput(numSamples) + op.addInput(seed) + return op.execute(Int(1)) } /// Outputs deterministic pseudorandom values from a normal distribution. @@ -31851,8 +31663,8 @@ public static func statelessMultinomial< /// The outputs are a deterministic function of `shape` and `seed`. /// /// - Parameters: -/// - shape: The shape of the output tensor. -/// - seed: 2 seeds (shape [2]). +/// - shape: The shape of the output tensor. +/// - seed: 2 seeds (shape [2]). /// /// - Attr dtype: The type of the output. /// @@ -31863,17 +31675,17 @@ public static func statelessRandomNormal< T: BinaryInteger & TensorFlowScalar, Tseed: BinaryInteger & TensorFlowScalar >( - shape: Tensor, - seed: Tensor + shape: Tensor, + seed: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StatelessRandomNormal", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tseed", Tseed.tensorFlowDataType) - op.addInput(shape) - op.addInput(seed) - return op.execute(Int(1)) + let op = makeOp("StatelessRandomNormal", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tseed", Tseed.tensorFlowDataType) + op.addInput(shape) + op.addInput(seed) + return op.execute(Int(1)) } /// Outputs deterministic pseudorandom random values from a uniform distribution. @@ -31884,8 +31696,8 @@ public static func statelessRandomNormal< /// The outputs are a deterministic function of `shape` and `seed`. /// /// - Parameters: -/// - shape: The shape of the output tensor. -/// - seed: 2 seeds (shape [2]). +/// - shape: The shape of the output tensor. +/// - seed: 2 seeds (shape [2]). /// /// - Attr dtype: The type of the output. /// @@ -31896,17 +31708,17 @@ public static func statelessRandomUniform< T: BinaryInteger & TensorFlowScalar, Tseed: BinaryInteger & TensorFlowScalar >( - shape: Tensor, - seed: Tensor + shape: Tensor, + seed: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StatelessRandomUniform", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tseed", Tseed.tensorFlowDataType) - op.addInput(shape) - op.addInput(seed) - return op.execute(Int(1)) + let op = makeOp("StatelessRandomUniform", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tseed", Tseed.tensorFlowDataType) + op.addInput(shape) + op.addInput(seed) + return op.execute(Int(1)) } /// Outputs deterministic pseudorandom random integers from a uniform distribution. @@ -31916,10 +31728,10 @@ public static func statelessRandomUniform< /// The outputs are a deterministic function of `shape`, `seed`, `minval`, and `maxval`. /// /// - Parameters: -/// - shape: The shape of the output tensor. -/// - seed: 2 seeds (shape [2]). -/// - minval: Minimum value (inclusive, scalar). -/// - maxval: Maximum value (exclusive, scalar). +/// - shape: The shape of the output tensor. +/// - seed: 2 seeds (shape [2]). +/// - minval: Minimum value (inclusive, scalar). +/// - maxval: Maximum value (exclusive, scalar). /// /// - Attr dtype: The type of the output. /// @@ -31930,21 +31742,21 @@ public static func statelessRandomUniformInt< T: BinaryInteger & TensorFlowScalar, Tseed: BinaryInteger & TensorFlowScalar >( - shape: Tensor, - seed: Tensor, - minval: Tensor, - maxval: Tensor + shape: Tensor, + seed: Tensor, + minval: Tensor, + maxval: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StatelessRandomUniformInt", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tseed", Tseed.tensorFlowDataType) - op.addInput(shape) - op.addInput(seed) - op.addInput(minval) - op.addInput(maxval) - return op.execute(Int(1)) + let op = makeOp("StatelessRandomUniformInt", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tseed", Tseed.tensorFlowDataType) + op.addInput(shape) + op.addInput(seed) + op.addInput(minval) + op.addInput(maxval) + return op.execute(Int(1)) } /// Outputs deterministic pseudorandom values from a truncated normal distribution. @@ -31956,8 +31768,8 @@ public static func statelessRandomUniformInt< /// The outputs are a deterministic function of `shape` and `seed`. /// /// - Parameters: -/// - shape: The shape of the output tensor. -/// - seed: 2 seeds (shape [2]). +/// - shape: The shape of the output tensor. +/// - seed: 2 seeds (shape [2]). /// /// - Attr dtype: The type of the output. /// @@ -31968,17 +31780,17 @@ public static func statelessTruncatedNormal< T: BinaryInteger & TensorFlowScalar, Tseed: BinaryInteger & TensorFlowScalar >( - shape: Tensor, - seed: Tensor + shape: Tensor, + seed: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StatelessTruncatedNormal", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tseed", Tseed.tensorFlowDataType) - op.addInput(shape) - op.addInput(seed) - return op.execute(Int(1)) + let op = makeOp("StatelessTruncatedNormal", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tseed", Tseed.tensorFlowDataType) + op.addInput(shape) + op.addInput(seed) + return op.execute(Int(1)) } /// output = input; While (Cond(output)) { output = Body(output) } @@ -31986,20 +31798,20 @@ public static func statelessTruncatedNormal< /// - Parameter input: A list of input tensors whose types are T. /// /// - Attrs: -/// - T: dtype in use. -/// - cond: A function takes 'input' and returns a tensor. If the tensor is -/// a scalar of non-boolean, the scalar is converted to a boolean -/// according to the following rule: if the scalar is a numerical -/// value, non-zero means True and zero means False; if the scalar is -/// a string, non-empty means True and empty means False. If the -/// tensor is not a scalar, non-emptiness means True and False -/// otherwise. -/// -/// This should only be used when the while condition and body functions -/// do not have stateful ops. -/// - body: A function that takes a list of tensors and returns another -/// list of tensors. Both lists have the same types as specified -/// by T. +/// - T: dtype in use. +/// - cond: A function takes 'input' and returns a tensor. If the tensor is +/// a scalar of non-boolean, the scalar is converted to a boolean +/// according to the following rule: if the scalar is a numerical +/// value, non-zero means True and zero means False; if the scalar is +/// a string, non-empty means True and empty means False. If the +/// tensor is not a scalar, non-emptiness means True and False +/// otherwise. +/// +/// This should only be used when the while condition and body functions +/// do not have stateful ops. +/// - body: A function that takes a list of tensors and returns another +/// list of tensors. Both lists have the same types as specified +/// by T. /// /// - Output output: A list of output tensors whose types are T. @inlinable @inline(__always) @@ -32010,17 +31822,17 @@ public static func statelessWhile< BodyIn: TensorGroup, BodyOut: TensorGroup >( - _ input: T, - cond: (CondIn) -> CondOut, - body: (BodyIn) -> BodyOut + _ input: T, + cond: (CondIn) -> CondOut, + body: (BodyIn) -> BodyOut ) -> T { let nOutputs = Int(input._typeList.count) - let op = makeOp("StatelessWhile", nOutputs) - op.updateAttribute("T", input._typeList) - op.updateAttribute("cond", cond) - op.updateAttribute("body", body) - op.addInputList(input) - return op.execute(Int(input._typeList.count)) + let op = makeOp("StatelessWhile", nOutputs) + op.updateAttribute("T", input._typeList) + op.updateAttribute("cond", cond) + op.updateAttribute("body", body) + op.addInputList(input) + return op.execute(Int(input._typeList.count)) } /// Check if the input matches the regex pattern. @@ -32039,14 +31851,14 @@ public static func statelessWhile< /// - Output output: A bool tensor with the same shape as `input`. @inlinable @inline(__always) public static func staticRegexFullMatch( - _ input: StringTensor, - pattern: String + _ input: StringTensor, + pattern: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StaticRegexFullMatch", nOutputs) - op.updateAttribute("pattern", pattern) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("StaticRegexFullMatch", nOutputs) + op.updateAttribute("pattern", pattern) + op.addInput(input) + return op.execute(Int(1)) } /// Replaces the match of pattern in input with rewrite. @@ -32056,51 +31868,51 @@ public static func staticRegexFullMatch( /// - Parameter input: The text to be processed. /// /// - Attrs: -/// - pattern: The regular expression to match the input. -/// - rewrite: The rewrite to be applied to the matched expression. -/// - replace_global: If True, the replacement is global, otherwise the replacement -/// is done only on the first match. +/// - pattern: The regular expression to match the input. +/// - rewrite: The rewrite to be applied to the matched expression. +/// - replace_global: If True, the replacement is global, otherwise the replacement +/// is done only on the first match. /// /// - Output output: The text after applying pattern and rewrite. @inlinable @inline(__always) public static func staticRegexReplace( - _ input: StringTensor, - pattern: String, - rewrite: String, - replaceGlobal: Bool = true + _ input: StringTensor, + pattern: String, + rewrite: String, + replaceGlobal: Bool = true ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("StaticRegexReplace", nOutputs) - op.updateAttribute("pattern", pattern) - op.updateAttribute("rewrite", rewrite) - op.updateAttribute("replace_global", replaceGlobal) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("StaticRegexReplace", nOutputs) + op.updateAttribute("pattern", pattern) + op.updateAttribute("rewrite", rewrite) + op.updateAttribute("replace_global", replaceGlobal) + op.addInput(input) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func statsAggregatorHandleV2( - container: String, - sharedName: String + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("StatsAggregatorHandleV2", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("StatsAggregatorHandleV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Set a summary_writer_interface to record statistics using given stats_aggregator. @inlinable @inline(__always) public static func statsAggregatorSetSummaryWriter( - statsAggregator: ResourceHandle, - summary: ResourceHandle + statsAggregator: ResourceHandle, + summary: ResourceHandle ) { let nOutputs = 0 - let op = makeOp("StatsAggregatorSetSummaryWriter", nOutputs) - op.addInput(statsAggregator) - op.addInput(summary) - op.execute() + let op = makeOp("StatsAggregatorSetSummaryWriter", nOutputs) + op.addInput(statsAggregator) + op.addInput(summary) + op.execute() } /// Stops gradient computation. @@ -32126,13 +31938,13 @@ public static func statsAggregatorSetSummaryWriter( /// example generation process. @inlinable @inline(__always) public static func stopGradient( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StopGradient", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("StopGradient", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Return a strided slice from `input`. @@ -32228,69 +32040,69 @@ public static func stopGradient( /// `ellipsis_mask must be a power of two (only one ellipsis)` /// /// - Parameters: -/// - begin: `begin[k]` specifies the offset into the `k`th range specification. -/// The exact dimension this corresponds to will be determined by context. -/// Out-of-bounds values will be silently clamped. If the `k`th bit of -/// `begin_mask` then `begin[k]` is ignored and the full range of the -/// appropriate dimension is used instead. Negative values causes indexing -/// to start from the highest element e.g. If `foo==[1,2,3]` then `foo[-1]==3`. -/// - end: `end[i]` is like `begin` with the exception that `end_mask` is -/// used to determine full ranges. -/// - strides: `strides[i]` specifies the increment in the `i`th specification -/// after extracting a given element. Negative indices will reverse -/// the original order. Out or range values are -/// clamped to `[0,dim[i]) if slice[i]>0` or `[-1,dim[i]-1] if slice[i] < 0` +/// - begin: `begin[k]` specifies the offset into the `k`th range specification. +/// The exact dimension this corresponds to will be determined by context. +/// Out-of-bounds values will be silently clamped. If the `k`th bit of +/// `begin_mask` then `begin[k]` is ignored and the full range of the +/// appropriate dimension is used instead. Negative values causes indexing +/// to start from the highest element e.g. If `foo==[1,2,3]` then `foo[-1]==3`. +/// - end: `end[i]` is like `begin` with the exception that `end_mask` is +/// used to determine full ranges. +/// - strides: `strides[i]` specifies the increment in the `i`th specification +/// after extracting a given element. Negative indices will reverse +/// the original order. Out or range values are +/// clamped to `[0,dim[i]) if slice[i]>0` or `[-1,dim[i]-1] if slice[i] < 0` /// /// - Attrs: -/// - begin_mask: a bitmask where a bit i being 1 means to ignore the begin -/// value and instead use the largest interval possible. At runtime -/// begin[i] will be replaced with `[0, n-1)` if `stride[i] > 0` or -/// `[-1, n-1]` if `stride[i] < 0` -/// - end_mask: analogous to `begin_mask` -/// - ellipsis_mask: a bitmask where bit `i` being 1 means the `i`th -/// position is actually an ellipsis. One bit at most can be 1. -/// If `ellipsis_mask == 0`, then an implicit ellipsis mask of `1 << (m+1)` -/// is provided. This means that `foo[3:5] == foo[3:5, ...]`. An ellipsis -/// implicitly creates as many range specifications as necessary to fully -/// specify the sliced range for every dimension. For example for a 4-dimensional -/// tensor `foo` the slice `foo[2, ..., 5:8]` implies `foo[2, :, :, 5:8]`. -/// - new_axis_mask: a bitmask where bit `i` being 1 means the `i`th -/// specification creates a new shape 1 dimension. For example -/// `foo[:4, tf.newaxis, :2]` would produce a shape `(4, 1, 2)` tensor. -/// - shrink_axis_mask: a bitmask where bit `i` implies that the `i`th -/// specification should shrink the dimensionality. begin and end -/// must imply a slice of size 1 in the dimension. For example in -/// python one might do `foo[:, 3, :]` which would result in -/// `shrink_axis_mask` being 2. +/// - begin_mask: a bitmask where a bit i being 1 means to ignore the begin +/// value and instead use the largest interval possible. At runtime +/// begin[i] will be replaced with `[0, n-1)` if `stride[i] > 0` or +/// `[-1, n-1]` if `stride[i] < 0` +/// - end_mask: analogous to `begin_mask` +/// - ellipsis_mask: a bitmask where bit `i` being 1 means the `i`th +/// position is actually an ellipsis. One bit at most can be 1. +/// If `ellipsis_mask == 0`, then an implicit ellipsis mask of `1 << (m+1)` +/// is provided. This means that `foo[3:5] == foo[3:5, ...]`. An ellipsis +/// implicitly creates as many range specifications as necessary to fully +/// specify the sliced range for every dimension. For example for a 4-dimensional +/// tensor `foo` the slice `foo[2, ..., 5:8]` implies `foo[2, :, :, 5:8]`. +/// - new_axis_mask: a bitmask where bit `i` being 1 means the `i`th +/// specification creates a new shape 1 dimension. For example +/// `foo[:4, tf.newaxis, :2]` would produce a shape `(4, 1, 2)` tensor. +/// - shrink_axis_mask: a bitmask where bit `i` implies that the `i`th +/// specification should shrink the dimensionality. begin and end +/// must imply a slice of size 1 in the dimension. For example in +/// python one might do `foo[:, 3, :]` which would result in +/// `shrink_axis_mask` being 2. @inlinable @inline(__always) public static func stridedSlice< T: TensorFlowScalar, Index: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - begin: Tensor, - end: Tensor, - strides: Tensor, - beginMask: Int64 = 0, - endMask: Int64 = 0, - ellipsisMask: Int64 = 0, - newAxisMask: Int64 = 0, - shrinkAxisMask: Int64 = 0 -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("StridedSlice", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Index", Index.tensorFlowDataType) - op.updateAttribute("begin_mask", beginMask) - op.updateAttribute("end_mask", endMask) - op.updateAttribute("ellipsis_mask", ellipsisMask) - op.updateAttribute("new_axis_mask", newAxisMask) - op.updateAttribute("shrink_axis_mask", shrinkAxisMask) - op.addInput(input) - op.addInput(begin) - op.addInput(end) - op.addInput(strides) - return op.execute(Int(1)) + _ input: Tensor, + begin: Tensor, + end: Tensor, + strides: Tensor, + beginMask: Int64 = 0, + endMask: Int64 = 0, + ellipsisMask: Int64 = 0, + newAxisMask: Int64 = 0, + shrinkAxisMask: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StridedSlice", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Index", Index.tensorFlowDataType) + op.updateAttribute("begin_mask", beginMask) + op.updateAttribute("end_mask", endMask) + op.updateAttribute("ellipsis_mask", ellipsisMask) + op.updateAttribute("new_axis_mask", newAxisMask) + op.updateAttribute("shrink_axis_mask", shrinkAxisMask) + op.addInput(input) + op.addInput(begin) + op.addInput(end) + op.addInput(strides) + return op.execute(Int(1)) } /// Returns the gradient of `StridedSlice`. @@ -32308,32 +32120,32 @@ public static func stridedSliceGrad< T: TensorFlowScalar, Index: BinaryInteger & TensorFlowScalar >( - shape: Tensor, - begin: Tensor, - end: Tensor, - strides: Tensor, - dy: Tensor, - beginMask: Int64 = 0, - endMask: Int64 = 0, - ellipsisMask: Int64 = 0, - newAxisMask: Int64 = 0, - shrinkAxisMask: Int64 = 0 -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("StridedSliceGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Index", Index.tensorFlowDataType) - op.updateAttribute("begin_mask", beginMask) - op.updateAttribute("end_mask", endMask) - op.updateAttribute("ellipsis_mask", ellipsisMask) - op.updateAttribute("new_axis_mask", newAxisMask) - op.updateAttribute("shrink_axis_mask", shrinkAxisMask) - op.addInput(shape) - op.addInput(begin) - op.addInput(end) - op.addInput(strides) - op.addInput(dy) - return op.execute(Int(1)) + shape: Tensor, + begin: Tensor, + end: Tensor, + strides: Tensor, + dy: Tensor, + beginMask: Int64 = 0, + endMask: Int64 = 0, + ellipsisMask: Int64 = 0, + newAxisMask: Int64 = 0, + shrinkAxisMask: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("StridedSliceGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Index", Index.tensorFlowDataType) + op.updateAttribute("begin_mask", beginMask) + op.updateAttribute("end_mask", endMask) + op.updateAttribute("ellipsis_mask", ellipsisMask) + op.updateAttribute("new_axis_mask", newAxisMask) + op.updateAttribute("shrink_axis_mask", shrinkAxisMask) + op.addInput(shape) + op.addInput(begin) + op.addInput(end) + op.addInput(strides) + op.addInput(dy) + return op.execute(Int(1)) } /// Formats a string template using a list of tensors. @@ -32343,26 +32155,26 @@ public static func stridedSliceGrad< /// - Parameter inputs: The list of tensors to format into the placeholder string. /// /// - Attrs: -/// - template: A string, the template to format tensor summaries into. -/// - placeholder: A string, at each placeholder in the template a subsequent tensor summary will be inserted. -/// - summarize: When formatting the tensor summaries print the first and last summarize entries of each tensor dimension. +/// - template: A string, the template to format tensor summaries into. +/// - placeholder: A string, at each placeholder in the template a subsequent tensor summary will be inserted. +/// - summarize: When formatting the tensor summaries print the first and last summarize entries of each tensor dimension. /// /// - Output output: = The resulting string scalar. @inlinable @inline(__always) public static func stringFormat( - inputs: T, - template: String = "%s", - placeholder: String = "%s", - summarize: Int64 = 3 + inputs: T, + template: String = "%s", + placeholder: String = "%s", + summarize: Int64 = 3 ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("StringFormat", nOutputs) - op.updateAttribute("T", inputs._typeList) - op.updateAttribute("template", template) - op.updateAttribute("placeholder", placeholder) - op.updateAttribute("summarize", summarize) - op.addInputList(inputs) - return op.execute(Int(1)) + let op = makeOp("StringFormat", nOutputs) + op.updateAttribute("T", inputs._typeList) + op.updateAttribute("template", template) + op.updateAttribute("placeholder", placeholder) + op.updateAttribute("summarize", summarize) + op.addInputList(inputs) + return op.execute(Int(1)) } /// Joins the strings in the given list of string tensors into one tensor; @@ -32370,21 +32182,21 @@ public static func stringFormat( /// with the given separator (default is an empty separator). /// /// - Parameter inputs: A list of string tensors. The tensors must all have the same shape, -/// or be scalars. Scalars may be mixed in; these will be broadcast to the shape -/// of non-scalar inputs. +/// or be scalars. Scalars may be mixed in; these will be broadcast to the shape +/// of non-scalar inputs. /// /// - Attr separator: string, an optional join separator. @inlinable @inline(__always) public static func stringJoin( - inputs: [StringTensor], - separator: String + inputs: [StringTensor], + separator: String ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("StringJoin", nOutputs) - op.updateAttribute("N", inputs.count) - op.updateAttribute("separator", separator) - op.addInputList(inputs) - return op.execute(Int(1)) + let op = makeOp("StringJoin", nOutputs) + op.updateAttribute("N", inputs.count) + op.updateAttribute("separator", separator) + op.addInputList(inputs) + return op.execute(Int(1)) } /// String lengths of `input`. @@ -32394,47 +32206,35 @@ public static func stringJoin( /// - Parameter input: The string for which to compute the length. /// /// - Attr unit: The unit that is counted to compute string length. One of: `"BYTE"` (for -/// the number of bytes in each string) or `"UTF8_CHAR"` (for the number of UTF-8 -/// encoded Unicode code points in each string). Results are undefined -/// if `unit=UTF8_CHAR` and the `input` strings do not contain structurally -/// valid UTF-8. +/// the number of bytes in each string) or `"UTF8_CHAR"` (for the number of UTF-8 +/// encoded Unicode code points in each string). Results are undefined +/// if `unit=UTF8_CHAR` and the `input` strings do not contain structurally +/// valid UTF-8. /// /// - Output output: Integer tensor that has the same shape as `input`. The output contains the -/// element-wise string lengths of `input`. +/// element-wise string lengths of `input`. @inlinable @inline(__always) public static func stringLength( - _ input: StringTensor, - unit: Unit = .byte + _ input: StringTensor, + unit: Unit = .byte ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StringLength", nOutputs) - op.updateAttribute("unit", unit.cName) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("StringLength", nOutputs) + op.updateAttribute("unit", unit.cName) + op.addInput(input) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func stringListAttr( - _ a: [String], - _ b: String + _ a: [String], + _ b: String ) { let nOutputs = 0 - let op = makeOp("StringListAttr", nOutputs) - op.updateAttribute("a", a) - op.updateAttribute("b", b) - op.execute() -} - -@inlinable @inline(__always) -public static func stringLower( - _ input: StringTensor, - encoding: String -) -> StringTensor { - let nOutputs = Int(1) - let op = makeOp("StringLower", nOutputs) - op.updateAttribute("encoding", encoding) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("StringListAttr", nOutputs) + op.updateAttribute("a", a) + op.updateAttribute("b", b) + op.execute() } /// Split elements of `input` based on `delimiter` into a `SparseTensor`. @@ -32461,29 +32261,29 @@ public static func stringLower( /// values = ['hello', 'world', 'a', 'b', 'c'] /// /// - Parameters: -/// - input: 1-D. Strings to split. -/// - delimiter: 0-D. Delimiter characters (bytes), or empty string. +/// - input: 1-D. Strings to split. +/// - delimiter: 0-D. Delimiter characters (bytes), or empty string. /// /// - Attr skip_empty: A `bool`. If `True`, skip the empty strings from the result. /// /// - Outputs: -/// - indices: A dense matrix of int64 representing the indices of the sparse tensor. -/// - values: A vector of strings corresponding to the splited values. -/// - shape: a length-2 vector of int64 representing the shape of the sparse -/// tensor, where the first value is N and the second value is the maximum number -/// of tokens in a single input entry. +/// - indices: A dense matrix of int64 representing the indices of the sparse tensor. +/// - values: A vector of strings corresponding to the splited values. +/// - shape: a length-2 vector of int64 representing the shape of the sparse +/// tensor, where the first value is N and the second value is the maximum number +/// of tokens in a single input entry. @inlinable @inline(__always) public static func stringSplit( - _ input: StringTensor, - delimiter: StringTensor, - skipEmpty: Bool = true + _ input: StringTensor, + delimiter: StringTensor, + skipEmpty: Bool = true ) -> (indices: Tensor, values: StringTensor, shape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("StringSplit", nOutputs) - op.updateAttribute("skip_empty", skipEmpty) - op.addInput(input) - op.addInput(delimiter) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("StringSplit", nOutputs) + op.updateAttribute("skip_empty", skipEmpty) + op.addInput(input) + op.addInput(delimiter) + return op.execute(Int(1), Int(1), Int(1)) } /// Split elements of `source` based on `sep` into a `SparseTensor`. @@ -32514,22 +32314,22 @@ public static func stringSplit( /// Note that the above mentioned behavior matches python's str.split. /// /// - Parameters: -/// - input: `1-D` string `Tensor`, the strings to split. -/// - sep: `0-D` string `Tensor`, the delimiter character. +/// - input: `1-D` string `Tensor`, the strings to split. +/// - sep: `0-D` string `Tensor`, the delimiter character. /// /// - Attr maxsplit: An `int`. If `maxsplit > 0`, limit of the split of the result. @inlinable @inline(__always) public static func stringSplitV2( - _ input: StringTensor, - sep: StringTensor, - maxsplit: Int64 = -1 + _ input: StringTensor, + sep: StringTensor, + maxsplit: Int64 = -1 ) -> (indices: Tensor, values: StringTensor, shape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("StringSplitV2", nOutputs) - op.updateAttribute("maxsplit", maxsplit) - op.addInput(input) - op.addInput(sep) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("StringSplitV2", nOutputs) + op.updateAttribute("maxsplit", maxsplit) + op.addInput(input) + op.addInput(sep) + return op.execute(Int(1), Int(1), Int(1)) } /// Strip leading and trailing whitespaces from the Tensor. @@ -32539,12 +32339,12 @@ public static func stringSplitV2( /// - Output output: A string `Tensor` of the same shape as the input. @inlinable @inline(__always) public static func stringStrip( - _ input: StringTensor + _ input: StringTensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("StringStrip", nOutputs) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("StringStrip", nOutputs) + op.addInput(input) + return op.execute(Int(1)) } /// Converts each string in the input Tensor to its hash mod by a number of buckets. @@ -32561,14 +32361,14 @@ public static func stringStrip( /// - Output output: A Tensor of the same shape as the input `string_tensor`. @inlinable @inline(__always) public static func stringToHashBucket( - stringTensor: StringTensor, - numBuckets: Int64 + stringTensor: StringTensor, + numBuckets: Int64 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StringToHashBucket", nOutputs) - op.updateAttribute("num_buckets", numBuckets) - op.addInput(stringTensor) - return op.execute(Int(1)) + let op = makeOp("StringToHashBucket", nOutputs) + op.updateAttribute("num_buckets", numBuckets) + op.addInput(stringTensor) + return op.execute(Int(1)) } /// Converts each string in the input Tensor to its hash mod by a number of buckets. @@ -32587,14 +32387,14 @@ public static func stringToHashBucket( /// - Output output: A Tensor of the same shape as the input `string_tensor`. @inlinable @inline(__always) public static func stringToHashBucketFast( - _ input: StringTensor, - numBuckets: Int64 + _ input: StringTensor, + numBuckets: Int64 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StringToHashBucketFast", nOutputs) - op.updateAttribute("num_buckets", numBuckets) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("StringToHashBucketFast", nOutputs) + op.updateAttribute("num_buckets", numBuckets) + op.addInput(input) + return op.execute(Int(1)) } /// Converts each string in the input Tensor to its hash mod by a number of buckets. @@ -32613,23 +32413,23 @@ public static func stringToHashBucketFast( /// - Parameter input: The strings to assign a hash bucket. /// /// - Attrs: -/// - num_buckets: The number of buckets. -/// - key: The key for the keyed hash function passed as a list of two uint64 -/// elements. +/// - num_buckets: The number of buckets. +/// - key: The key for the keyed hash function passed as a list of two uint64 +/// elements. /// /// - Output output: A Tensor of the same shape as the input `string_tensor`. @inlinable @inline(__always) public static func stringToHashBucketStrong( - _ input: StringTensor, - numBuckets: Int64, - key: [Int32] + _ input: StringTensor, + numBuckets: Int64, + key: [Int32] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StringToHashBucketStrong", nOutputs) - op.updateAttribute("num_buckets", numBuckets) - op.updateAttribute("key", key) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("StringToHashBucketStrong", nOutputs) + op.updateAttribute("num_buckets", numBuckets) + op.updateAttribute("key", key) + op.addInput(input) + return op.execute(Int(1)) } /// Converts each string in the input Tensor to the specified numeric type. @@ -32642,37 +32442,25 @@ public static func stringToHashBucketStrong( /// - Output output: A Tensor of the same shape as the input `string_tensor`. @inlinable @inline(__always) public static func stringToNumber( - stringTensor: StringTensor + stringTensor: StringTensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("StringToNumber", nOutputs) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(stringTensor) - return op.execute(Int(1)) -} - -@inlinable @inline(__always) -public static func stringUpper( - _ input: StringTensor, - encoding: String -) -> StringTensor { - let nOutputs = Int(1) - let op = makeOp("StringUpper", nOutputs) - op.updateAttribute("encoding", encoding) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("StringToNumber", nOutputs) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(stringTensor) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func stubResourceHandleOp( - container: String, - sharedName: String + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("StubResourceHandleOp", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("StubResourceHandleOp", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Returns x - y element-wise. @@ -32681,15 +32469,15 @@ public static func stubResourceHandleOp( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func sub( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Sub", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Sub", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Return substrings from `Tensor` of strings. @@ -32771,32 +32559,32 @@ public static func sub( /// ``` /// /// - Parameters: -/// - input: Tensor of strings -/// - pos: Scalar defining the position of first character in each substring -/// - len: Scalar defining the number of characters to include in each substring +/// - input: Tensor of strings +/// - pos: Scalar defining the position of first character in each substring +/// - len: Scalar defining the number of characters to include in each substring /// /// - Attr unit: The unit that is used to create the substring. One of: `"BYTE"` (for -/// defining position and length by bytes) or `"UTF8_CHAR"` (for the UTF-8 -/// encoded Unicode code points). The default is `"BYTE"`. Results are undefined if -/// `unit=UTF8_CHAR` and the `input` strings do not contain structurally valid -/// UTF-8. +/// defining position and length by bytes) or `"UTF8_CHAR"` (for the UTF-8 +/// encoded Unicode code points). The default is `"BYTE"`. Results are undefined if +/// `unit=UTF8_CHAR` and the `input` strings do not contain structurally valid +/// UTF-8. /// /// - Output output: Tensor of substrings @inlinable @inline(__always) public static func substr( - _ input: StringTensor, - pos: Tensor, - len: Tensor, - unit: Unit = .byte + _ input: StringTensor, + pos: Tensor, + len: Tensor, + unit: Unit = .byte ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("Substr", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("unit", unit.cName) - op.addInput(input) - op.addInput(pos) - op.addInput(len) - return op.execute(Int(1)) + let op = makeOp("Substr", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("unit", unit.cName) + op.addInput(input) + op.addInput(pos) + op.addInput(len) + return op.execute(Int(1)) } /// Computes the sum of elements across dimensions of a tensor. @@ -32807,9 +32595,9 @@ public static func substr( /// retained with length 1. /// /// - Parameters: -/// - input: The tensor to reduce. -/// - reduction_indices: The dimensions to reduce. Must be in the range -/// `[-rank(input), rank(input))`. +/// - input: The tensor to reduce. +/// - reduction_indices: The dimensions to reduce. Must be in the range +/// `[-rank(input), rank(input))`. /// /// - Attr keep_dims: If true, retain reduced dimensions with length 1. /// @@ -32819,30 +32607,30 @@ public static func sum< T: Numeric & TensorFlowScalar, Tidx: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - reductionIndices: Tensor, - keepDims: Bool = false + _ input: Tensor, + reductionIndices: Tensor, + keepDims: Bool = false ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Sum", nOutputs) - op.updateAttribute("keep_dims", keepDims) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(input) - op.addInput(reductionIndices) - return op.execute(Int(1)) + let op = makeOp("Sum", nOutputs) + op.updateAttribute("keep_dims", keepDims) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(input) + op.addInput(reductionIndices) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func summaryWriter( - sharedName: String, - container: String + sharedName: String, + container: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("SummaryWriter", nOutputs) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("container", container) - return op.execute(Int(1)) + let op = makeOp("SummaryWriter", nOutputs) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("container", container) + return op.execute(Int(1)) } /// Computes the singular value decompositions of one or more matrices. @@ -32860,37 +32648,37 @@ public static func summaryWriter( /// ``` /// /// - Parameter input: A tensor of shape `[..., M, N]` whose inner-most 2 dimensions -/// form matrices of size `[M, N]`. Let `P` be the minimum of `M` and `N`. +/// form matrices of size `[M, N]`. Let `P` be the minimum of `M` and `N`. /// /// - Attrs: -/// - compute_uv: If true, left and right singular vectors will be -/// computed and returned in `u` and `v`, respectively. -/// If false, `u` and `v` are not set and should never referenced. -/// - full_matrices: If true, compute full-sized `u` and `v`. If false -/// (the default), compute only the leading `P` singular vectors. -/// Ignored if `compute_uv` is `False`. +/// - compute_uv: If true, left and right singular vectors will be +/// computed and returned in `u` and `v`, respectively. +/// If false, `u` and `v` are not set and should never referenced. +/// - full_matrices: If true, compute full-sized `u` and `v`. If false +/// (the default), compute only the leading `P` singular vectors. +/// Ignored if `compute_uv` is `False`. /// /// - Outputs: -/// - s: Singular values. Shape is `[..., P]`. -/// - u: Left singular vectors. If `full_matrices` is `False` then shape is -/// `[..., M, P]`; if `full_matrices` is `True` then shape is -/// `[..., M, M]`. Undefined if `compute_uv` is `False`. -/// - v: Left singular vectors. If `full_matrices` is `False` then shape is -/// `[..., N, P]`. If `full_matrices` is `True` then shape is `[..., N, N]`. -/// Undefined if `compute_uv` is false. +/// - s: Singular values. Shape is `[..., P]`. +/// - u: Left singular vectors. If `full_matrices` is `False` then shape is +/// `[..., M, P]`; if `full_matrices` is `True` then shape is +/// `[..., M, M]`. Undefined if `compute_uv` is `False`. +/// - v: Left singular vectors. If `full_matrices` is `False` then shape is +/// `[..., N, P]`. If `full_matrices` is `True` then shape is `[..., N, N]`. +/// Undefined if `compute_uv` is false. @inlinable @inline(__always) public static func svd( - _ input: Tensor, - computeUv: Bool = true, - fullMatrices: Bool = false + _ input: Tensor, + computeUv: Bool = true, + fullMatrices: Bool = false ) -> (s: Tensor, u: Tensor, v: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("Svd", nOutputs) - op.updateAttribute("compute_uv", computeUv) - op.updateAttribute("full_matrices", fullMatrices) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("Svd", nOutputs) + op.updateAttribute("compute_uv", computeUv) + op.updateAttribute("full_matrices", fullMatrices) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1), Int(1)) } /// Forwards `data` to the output port determined by `pred`. @@ -32901,23 +32689,23 @@ public static func svd( /// See also `RefSwitch` and `Merge`. /// /// - Parameters: -/// - data: The tensor to be forwarded to the appropriate output. -/// - pred: A scalar that specifies which output port will receive data. +/// - data: The tensor to be forwarded to the appropriate output. +/// - pred: A scalar that specifies which output port will receive data. /// /// - Outputs: -/// - output_false: If `pred` is false, data will be forwarded to this output. -/// - output_true: If `pred` is true, data will be forwarded to this output. +/// - output_false: If `pred` is false, data will be forwarded to this output. +/// - output_true: If `pred` is true, data will be forwarded to this output. @inlinable @inline(__always) public static func switch_( - data: Tensor, - pred: Tensor + data: Tensor, + pred: Tensor ) -> (outputFalse: Tensor, outputTrue: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("Switch", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(data) - op.addInput(pred) - return op.execute(Int(1), Int(1)) + let op = makeOp("Switch", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(data) + op.addInput(pred) + return op.execute(Int(1), Int(1)) } /// Computes the gradient function for function f via backpropagation. @@ -32925,26 +32713,26 @@ public static func switch_( /// - Parameter input: a list of input tensors of size N + M; /// /// - Attrs: -/// - Tin: the type list for the input list. -/// - Tout: the type list for the input list. -/// - f: The function we want to compute the gradient for. +/// - Tin: the type list for the input list. +/// - Tout: the type list for the input list. +/// - f: The function we want to compute the gradient for. /// -/// The function 'f' must be a numerical function which takes N inputs and -/// produces M outputs. Its gradient function 'g', which is computed by -/// this SymbolicGradient op is a function taking N + M inputs and -/// produces N outputs. +/// The function 'f' must be a numerical function which takes N inputs and +/// produces M outputs. Its gradient function 'g', which is computed by +/// this SymbolicGradient op is a function taking N + M inputs and +/// produces N outputs. /// -/// I.e. if we have -/// (y1, y2, ..., y_M) = f(x1, x2, ..., x_N), -/// then, g is -/// (dL/dx1, dL/dx2, ..., dL/dx_N) = g(x1, x2, ..., x_N, -/// dL/dy1, dL/dy2, ..., dL/dy_M), +/// I.e. if we have +/// (y1, y2, ..., y_M) = f(x1, x2, ..., x_N), +/// then, g is +/// (dL/dx1, dL/dx2, ..., dL/dx_N) = g(x1, x2, ..., x_N, +/// dL/dy1, dL/dy2, ..., dL/dy_M), /// -/// where L is a scalar-value function of (x1, x2, ..., xN) (e.g., the -/// loss function). dL/dx_i is the partial derivative of L with respect -/// to x_i. +/// where L is a scalar-value function of (x1, x2, ..., xN) (e.g., the +/// loss function). dL/dx_i is the partial derivative of L with respect +/// to x_i. /// -/// (Needs some math expert to say the comment above better.) +/// (Needs some math expert to say the comment above better.) /// /// - Output output: a list of output tensors of size N; @inlinable @inline(__always) @@ -32954,62 +32742,62 @@ public static func symbolicGradient< FIn: TensorGroup, FOut: TensorGroup >( - _ input: Tin, - f: (FIn) -> FOut + _ input: Tin, + f: (FIn) -> FOut ) -> Tout { let nOutputs = Int(Tout._typeList.count) - let op = makeOp("SymbolicGradient", nOutputs) - op.updateAttribute("Tin", input._typeList) - op.updateAttribute("Tout", Tout._typeList) - op.updateAttribute("f", f) - op.addInputList(input) - return op.execute(Int(Tout._typeList.count)) + let op = makeOp("SymbolicGradient", nOutputs) + op.updateAttribute("Tin", input._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("f", f) + op.addInputList(input) + return op.execute(Int(Tout._typeList.count)) } /// Creates a dataset that emits the records from one or more TFRecord files. /// /// - Parameters: -/// - filenames: A scalar or vector containing the name(s) of the file(s) to be -/// read. -/// - compression_type: A scalar containing either (i) the empty string (no -/// compression), (ii) "ZLIB", or (iii) "GZIP". -/// - buffer_size: A scalar representing the number of bytes to buffer. A value of -/// 0 means no buffering will be performed. +/// - filenames: A scalar or vector containing the name(s) of the file(s) to be +/// read. +/// - compression_type: A scalar containing either (i) the empty string (no +/// compression), (ii) "ZLIB", or (iii) "GZIP". +/// - buffer_size: A scalar representing the number of bytes to buffer. A value of +/// 0 means no buffering will be performed. @inlinable @inline(__always) public static func tFRecordDataset( - filenames: StringTensor, - compressionType: StringTensor, - bufferSize: Tensor + filenames: StringTensor, + compressionType: StringTensor, + bufferSize: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TFRecordDataset", nOutputs) - op.addInput(filenames) - op.addInput(compressionType) - op.addInput(bufferSize) - return op.execute(Int(1)) + let op = makeOp("TFRecordDataset", nOutputs) + op.addInput(filenames) + op.addInput(compressionType) + op.addInput(bufferSize) + return op.execute(Int(1)) } /// A Reader that outputs the records from a TensorFlow Records file. /// /// - Attrs: -/// - container: If non-empty, this reader is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this reader is named in the given bucket -/// with this shared_name. Otherwise, the node name is used instead. +/// - container: If non-empty, this reader is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this reader is named in the given bucket +/// with this shared_name. Otherwise, the node name is used instead. /// /// - Output reader_handle: The handle to reference the Reader. @inlinable @inline(__always) public static func tFRecordReaderV2( - container: String, - sharedName: String, - compressionType: String + container: String, + sharedName: String, + compressionType: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("TFRecordReaderV2", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("compression_type", compressionType) - return op.execute(Int(1)) + let op = makeOp("TFRecordReaderV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("compression_type", compressionType) + return op.execute(Int(1)) } /// CompilationResultProto indicating the status of the TPU compilation. @@ -33017,9 +32805,9 @@ public static func tFRecordReaderV2( public static func tPUCompilationResult( ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("TPUCompilationResult", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("TPUCompilationResult", nOutputs) + + return op.execute(Int(1)) } /// An op enabling differentiation of TPU Embeddings. @@ -33031,28 +32819,28 @@ public static func tPUCompilationResult( /// libraries. /// /// - Parameters: -/// - embedding_variable: A trainable variable, enabling optimizers to find this op. -/// - sliced_activations: The embedding activations Tensor to return. +/// - embedding_variable: A trainable variable, enabling optimizers to find this op. +/// - sliced_activations: The embedding activations Tensor to return. /// /// - Attrs: -/// - table_id: The id of the table in the embedding layer configuration from which -/// these activations were computed. -/// - lookup_id: Identifier of the set of embedding indices which produced these -/// activations. +/// - table_id: The id of the table in the embedding layer configuration from which +/// these activations were computed. +/// - lookup_id: Identifier of the set of embedding indices which produced these +/// activations. @inlinable @inline(__always) public static func tPUEmbeddingActivations( - embeddingVariable: Tensor, - slicedActivations: Tensor, - tableId: Int64, - lookupId: Int64 + embeddingVariable: Tensor, + slicedActivations: Tensor, + tableId: Int64, + lookupId: Int64 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TPUEmbeddingActivations", nOutputs) - op.updateAttribute("table_id", tableId) - op.updateAttribute("lookup_id", lookupId) - op.addInput(embeddingVariable) - op.addInput(slicedActivations) - return op.execute(Int(1)) + let op = makeOp("TPUEmbeddingActivations", nOutputs) + op.updateAttribute("table_id", tableId) + op.updateAttribute("lookup_id", lookupId) + op.addInput(embeddingVariable) + op.addInput(slicedActivations) + return op.execute(Int(1)) } /// A TPU core selector Op. @@ -33066,21 +32854,21 @@ public static func tPUEmbeddingActivations( public static func tPUOrdinalSelector( ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TPUOrdinalSelector", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("TPUOrdinalSelector", nOutputs) + + return op.execute(Int(1)) } /// Calls a function placed on a specified TPU device. /// /// - Parameters: -/// - args: The arguments to the function. -/// - device_ordinal: The TPU device ordinal to run the function on. +/// - args: The arguments to the function. +/// - device_ordinal: The TPU device ordinal to run the function on. /// /// - Attrs: -/// - Tin: The types of the arguments to the function. -/// - Tout: The types of the outputs of the function. -/// - f: The function to call. +/// - Tin: The types of the arguments to the function. +/// - Tout: The types of the outputs of the function. +/// - f: The function to call. /// /// - Output output: The output of the function call. @inlinable @inline(__always) @@ -33090,49 +32878,49 @@ public static func tPUPartitionedCall< FIn: TensorGroup, FOut: TensorGroup >( - args: Tin, - deviceOrdinal: Tensor, - f: (FIn) -> FOut + args: Tin, + deviceOrdinal: Tensor, + f: (FIn) -> FOut ) -> Tout { let nOutputs = Int(Tout._typeList.count) - let op = makeOp("TPUPartitionedCall", nOutputs) - op.updateAttribute("Tin", args._typeList) - op.updateAttribute("Tout", Tout._typeList) - op.updateAttribute("f", f) - op.addInputList(args) - op.addInput(deviceOrdinal) - return op.execute(Int(Tout._typeList.count)) + let op = makeOp("TPUPartitionedCall", nOutputs) + op.updateAttribute("Tin", args._typeList) + op.updateAttribute("Tout", Tout._typeList) + op.updateAttribute("f", f) + op.addInputList(args) + op.addInput(deviceOrdinal) + return op.execute(Int(Tout._typeList.count)) } /// Runs replicated computations on a distributed TPU system. /// /// - Parameters: -/// - inputs: the inputs to 'computation', flattened, in replica-major order. -/// - broadcast_inputs: additional arguments to broadcast to all replicas. The -/// broadcast inputs are appended to the per-replica inputs when calling -/// computation. -/// - guaranteed_constants: arguments which have been guaranteed to not -/// change their values during the session lifetime. These contain tensors marked as -/// constant using the GuaranteeConstOp. +/// - inputs: the inputs to 'computation', flattened, in replica-major order. +/// - broadcast_inputs: additional arguments to broadcast to all replicas. The +/// broadcast inputs are appended to the per-replica inputs when calling +/// computation. +/// - guaranteed_constants: arguments which have been guaranteed to not +/// change their values during the session lifetime. These contain tensors marked as +/// constant using the GuaranteeConstOp. /// /// - Attrs: -/// - computation: a function containing the computation to run. -/// - num_replicas: the number of replicas of the computation to run. -/// - num_cores_per_replica: the number of logical cores in each replica. -/// - topology: A serialized tensorflow.tpu.TopologyProto that describes the TPU -/// topology. -/// - use_tpu: a bool indicating if this computation will run on TPU or CPU/GPU. -/// Currently, only supports a default placement (computation is placed on GPU -/// if one is available, and on CPU if not). -/// - device_assignment: a flattened array with shape -/// [replica, num_cores_per_replica, mesh_dimension] that maps the coordinates -/// of logical cores in each replica of a computation to physical coordinates in -/// the TPU topology. -/// - Tinputs: the types of the arguments to 'computation'. -/// - Tbroadcast_inputs: the types of the additional arguments to broadcast to all -/// replicas. -/// - Tguaranteed_constants: the types of the arguments to 'guaranteed_constants'. -/// - output_types: the types of the outputs of 'computation'. +/// - computation: a function containing the computation to run. +/// - num_replicas: the number of replicas of the computation to run. +/// - num_cores_per_replica: the number of logical cores in each replica. +/// - topology: A serialized tensorflow.tpu.TopologyProto that describes the TPU +/// topology. +/// - use_tpu: a bool indicating if this computation will run on TPU or CPU/GPU. +/// Currently, only supports a default placement (computation is placed on GPU +/// if one is available, and on CPU if not). +/// - device_assignment: a flattened array with shape +/// [replica, num_cores_per_replica, mesh_dimension] that maps the coordinates +/// of logical cores in each replica of a computation to physical coordinates in +/// the TPU topology. +/// - Tinputs: the types of the arguments to 'computation'. +/// - Tbroadcast_inputs: the types of the additional arguments to broadcast to all +/// replicas. +/// - Tguaranteed_constants: the types of the arguments to 'guaranteed_constants'. +/// - output_types: the types of the outputs of 'computation'. /// /// - Output outputs: the outputs of 'computation'. @inlinable @inline(__always) @@ -33144,124 +32932,124 @@ public static func tPUReplicate< TguaranteedConstants: TensorArrayProtocol, OutputTypes: TensorGroup >( - inputs: Tinputs, - broadcastInputs: TbroadcastInputs, - variables: [ResourceHandle], - guaranteedConstants: TguaranteedConstants, - computation: (ComputationIn) -> ComputationOut, - numReplicas: Int64, - numCoresPerReplica: Int64 = 1, - topology: String, - useTpu: Bool = true, - deviceAssignment: [Int32], - hostComputeCore: [String], - paddingMap: [String], - stepMarkerLocation: String = "STEP_MARK_AT_ENTRY" + inputs: Tinputs, + broadcastInputs: TbroadcastInputs, + variables: [ResourceHandle], + guaranteedConstants: TguaranteedConstants, + computation: (ComputationIn) -> ComputationOut, + numReplicas: Int64, + numCoresPerReplica: Int64 = 1, + topology: String, + useTpu: Bool = true, + deviceAssignment: [Int32], + hostComputeCore: [String], + paddingMap: [String], + stepMarkerLocation: String = "STEP_MARK_AT_ENTRY" ) -> OutputTypes { let nOutputs = Int(OutputTypes._typeList.count) - let op = makeOp("TPUReplicate", nOutputs) - op.updateAttribute("computation", computation) - op.updateAttribute("num_replicas", numReplicas) - op.updateAttribute("num_cores_per_replica", numCoresPerReplica) - op.updateAttribute("topology", topology) - op.updateAttribute("use_tpu", useTpu) - op.updateAttribute("device_assignment", deviceAssignment) - op.updateAttribute("host_compute_core", hostComputeCore) - op.updateAttribute("Tinputs", inputs._typeList) - op.updateAttribute("Tbroadcast_inputs", broadcastInputs._typeList) - op.updateAttribute("NumVariables", variables.count) - op.updateAttribute("Tguaranteed_constants", guaranteedConstants._typeList) - op.updateAttribute("output_types", OutputTypes._typeList) - op.updateAttribute("padding_map", paddingMap) - op.updateAttribute("step_marker_location", stepMarkerLocation) - op.addInputList(inputs) - op.addInputList(broadcastInputs) - op.addInputList(variables) - op.addInputList(guaranteedConstants) - return op.execute(Int(OutputTypes._typeList.count)) + let op = makeOp("TPUReplicate", nOutputs) + op.updateAttribute("computation", computation) + op.updateAttribute("num_replicas", numReplicas) + op.updateAttribute("num_cores_per_replica", numCoresPerReplica) + op.updateAttribute("topology", topology) + op.updateAttribute("use_tpu", useTpu) + op.updateAttribute("device_assignment", deviceAssignment) + op.updateAttribute("host_compute_core", hostComputeCore) + op.updateAttribute("Tinputs", inputs._typeList) + op.updateAttribute("Tbroadcast_inputs", broadcastInputs._typeList) + op.updateAttribute("NumVariables", variables.count) + op.updateAttribute("Tguaranteed_constants", guaranteedConstants._typeList) + op.updateAttribute("output_types", OutputTypes._typeList) + op.updateAttribute("padding_map", paddingMap) + op.updateAttribute("step_marker_location", stepMarkerLocation) + op.addInputList(inputs) + op.addInputList(broadcastInputs) + op.addInputList(variables) + op.addInputList(guaranteedConstants) + return op.execute(Int(OutputTypes._typeList.count)) } /// Metadata indicaitng how the TPU computation should be replicated. /// /// - Attrs: -/// - num_replicas: Number of replicas of the computation -/// - num_cores_per_replica: Number of cores per replica. Used for model parallelism. -/// - topology: TopologyProto indicating the topology of the TPU pod slice. -/// - use_tpu: Whether to place the computation on the TPU. -/// - device_assignment: The assignment of devices for the computation. -/// - computation_shape: DEPRECATED. Use num_cores_per_replica instead. +/// - num_replicas: Number of replicas of the computation +/// - num_cores_per_replica: Number of cores per replica. Used for model parallelism. +/// - topology: TopologyProto indicating the topology of the TPU pod slice. +/// - use_tpu: Whether to place the computation on the TPU. +/// - device_assignment: The assignment of devices for the computation. +/// - computation_shape: DEPRECATED. Use num_cores_per_replica instead. @inlinable @inline(__always) public static func tPUReplicateMetadata( - numReplicas: Int64, - numCoresPerReplica: Int64 = 1, - topology: String, - useTpu: Bool = true, - deviceAssignment: [Int32], - computationShape: [Int32], - hostComputeCore: [String], - paddingMap: [String], - stepMarkerLocation: String = "STEP_MARK_AT_ENTRY" + numReplicas: Int64, + numCoresPerReplica: Int64 = 1, + topology: String, + useTpu: Bool = true, + deviceAssignment: [Int32], + computationShape: [Int32], + hostComputeCore: [String], + paddingMap: [String], + stepMarkerLocation: String = "STEP_MARK_AT_ENTRY" ) { let nOutputs = 0 - let op = makeOp("TPUReplicateMetadata", nOutputs) - op.updateAttribute("num_replicas", numReplicas) - op.updateAttribute("num_cores_per_replica", numCoresPerReplica) - op.updateAttribute("topology", topology) - op.updateAttribute("use_tpu", useTpu) - op.updateAttribute("device_assignment", deviceAssignment) - op.updateAttribute("computation_shape", computationShape) - op.updateAttribute("host_compute_core", hostComputeCore) - op.updateAttribute("padding_map", paddingMap) - op.updateAttribute("step_marker_location", stepMarkerLocation) - op.execute() + let op = makeOp("TPUReplicateMetadata", nOutputs) + op.updateAttribute("num_replicas", numReplicas) + op.updateAttribute("num_cores_per_replica", numCoresPerReplica) + op.updateAttribute("topology", topology) + op.updateAttribute("use_tpu", useTpu) + op.updateAttribute("device_assignment", deviceAssignment) + op.updateAttribute("computation_shape", computationShape) + op.updateAttribute("host_compute_core", hostComputeCore) + op.updateAttribute("padding_map", paddingMap) + op.updateAttribute("step_marker_location", stepMarkerLocation) + op.execute() } /// Connects N inputs to an N-way replicated TPU computation. @inlinable @inline(__always) public static func tPUReplicatedInput( - inputs: [Tensor] + inputs: [Tensor] ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TPUReplicatedInput", nOutputs) - op.updateAttribute("N", inputs.count) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInputList(inputs) - return op.execute(Int(1)) + let op = makeOp("TPUReplicatedInput", nOutputs) + op.updateAttribute("N", inputs.count) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInputList(inputs) + return op.execute(Int(1)) } /// Connects outputs of an N-way replicated computation to N outputs. @inlinable @inline(__always) public static func tPUReplicatedOutput( - _ input: Tensor, - numReplicas: Int64 + _ input: Tensor, + numReplicas: Int64 ) -> [Tensor] { let nOutputs = Int(numReplicas) - let op = makeOp("TPUReplicatedOutput", nOutputs) - op.updateAttribute("num_replicas", numReplicas) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(numReplicas)) + let op = makeOp("TPUReplicatedOutput", nOutputs) + op.updateAttribute("num_replicas", numReplicas) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(numReplicas)) } /// Creates a dataset that contains `count` elements from the `input_dataset`. /// /// - Parameter count: A scalar representing the number of elements from the `input_dataset` -/// that should be taken. A value of `-1` indicates that all of `input_dataset` -/// is taken. +/// that should be taken. A value of `-1` indicates that all of `input_dataset` +/// is taken. @inlinable @inline(__always) public static func takeDataset( - inputDataset: VariantHandle, - count: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + count: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TakeDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(count) - return op.execute(Int(1)) + let op = makeOp("TakeDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(count) + return op.execute(Int(1)) } /// Read `SparseTensors` from a `SparseTensorsMap` and concatenate them. @@ -33316,57 +33104,57 @@ public static func takeDataset( /// ``` /// /// - Parameter sparse_handles: 1-D, The `N` serialized `SparseTensor` objects. -/// Shape: `[N]`. +/// Shape: `[N]`. /// /// - Attrs: -/// - dtype: The `dtype` of the `SparseTensor` objects stored in the -/// `SparseTensorsMap`. -/// - container: The container name for the `SparseTensorsMap` read by this op. -/// - shared_name: The shared name for the `SparseTensorsMap` read by this op. -/// It should not be blank; rather the `shared_name` or unique Operation name -/// of the Op that created the original `SparseTensorsMap` should be used. +/// - dtype: The `dtype` of the `SparseTensor` objects stored in the +/// `SparseTensorsMap`. +/// - container: The container name for the `SparseTensorsMap` read by this op. +/// - shared_name: The shared name for the `SparseTensorsMap` read by this op. +/// It should not be blank; rather the `shared_name` or unique Operation name +/// of the Op that created the original `SparseTensorsMap` should be used. /// /// - Outputs: -/// - sparse_indices: 2-D. The `indices` of the minibatch `SparseTensor`. -/// - sparse_values: 1-D. The `values` of the minibatch `SparseTensor`. -/// - sparse_shape: 1-D. The `shape` of the minibatch `SparseTensor`. +/// - sparse_indices: 2-D. The `indices` of the minibatch `SparseTensor`. +/// - sparse_values: 1-D. The `values` of the minibatch `SparseTensor`. +/// - sparse_shape: 1-D. The `shape` of the minibatch `SparseTensor`. @inlinable @inline(__always) public static func takeManySparseFromTensorsMap( - sparseHandles: Tensor, - container: String, - sharedName: String + sparseHandles: Tensor, + container: String, + sharedName: String ) -> (sparseIndices: Tensor, sparseValues: Tensor, sparseShape: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("TakeManySparseFromTensorsMap", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.addInput(sparseHandles) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("TakeManySparseFromTensorsMap", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.addInput(sparseHandles) + return op.execute(Int(1), Int(1), Int(1)) } /// Computes tan of x element-wise. @inlinable @inline(__always) public static func tan( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Tan", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Tan", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes hyperbolic tangent of `x` element-wise. @inlinable @inline(__always) public static func tanh( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Tanh", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("Tanh", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Computes the gradient for the tanh of `x` wrt its input. @@ -33375,26 +33163,26 @@ public static func tanh( /// is the corresponding input gradient. @inlinable @inline(__always) public static func tanhGrad( - _ y: Tensor, - dy: Tensor + _ y: Tensor, + dy: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TanhGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(y) - op.addInput(dy) - return op.execute(Int(1)) + let op = makeOp("TanhGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(y) + op.addInput(dy) + return op.execute(Int(1)) } /// Deprecated. Use TensorArrayCloseV3 @inlinable @inline(__always) public static func tensorArrayCloseV2( - handle: StringTensor + handle: StringTensor ) { let nOutputs = 0 - let op = makeOp("TensorArrayCloseV2", nOutputs) - op.addInput(handle) - op.execute() + let op = makeOp("TensorArrayCloseV2", nOutputs) + op.addInput(handle) + op.execute() } /// Delete the TensorArray from its resource container. @@ -33405,28 +33193,28 @@ public static func tensorArrayCloseV2( /// - Parameter handle: The handle to a TensorArray (output of TensorArray or TensorArrayGrad). @inlinable @inline(__always) public static func tensorArrayCloseV3( - handle: ResourceHandle + handle: ResourceHandle ) { let nOutputs = 0 - let op = makeOp("TensorArrayCloseV3", nOutputs) - op.addInput(handle) - op.execute() + let op = makeOp("TensorArrayCloseV3", nOutputs) + op.addInput(handle) + op.execute() } /// Deprecated. Use TensorArrayConcatV3 @inlinable @inline(__always) public static func tensorArrayConcatV2( - handle: StringTensor, - flowIn: Tensor, - elementShapeExcept0: TensorShape? + handle: StringTensor, + flowIn: Tensor, + elementShapeExcept0: TensorShape? ) -> (value: Tensor, lengths: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("TensorArrayConcatV2", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("element_shape_except0", elementShapeExcept0) - op.addInput(handle) - op.addInput(flowIn) - return op.execute(Int(1), Int(1)) + let op = makeOp("TensorArrayConcatV2", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("element_shape_except0", elementShapeExcept0) + op.addInput(handle) + op.addInput(flowIn) + return op.execute(Int(1), Int(1)) } /// Concat the elements from the TensorArray into value `value`. @@ -33444,53 +33232,53 @@ public static func tensorArrayConcatV2( /// All elements must have the same shape (excepting the first dimension). /// /// - Parameters: -/// - handle: The handle to a TensorArray. -/// - flow_in: A float scalar that enforces proper chaining of operations. +/// - handle: The handle to a TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. /// /// - Attrs: -/// - dtype: The type of the elem that is returned. -/// - element_shape_except0: The expected shape of an element, if known, -/// excluding the first dimension. Used to validate the shapes of -/// TensorArray elements. If this shape is not fully specified, concatenating -/// zero-size TensorArrays is an error. +/// - dtype: The type of the elem that is returned. +/// - element_shape_except0: The expected shape of an element, if known, +/// excluding the first dimension. Used to validate the shapes of +/// TensorArray elements. If this shape is not fully specified, concatenating +/// zero-size TensorArrays is an error. /// /// - Outputs: -/// - value: All of the elements in the TensorArray, concatenated along the first -/// axis. -/// - lengths: A vector of the row sizes of the original T elements in the -/// value output. In the example above, this would be the values: -/// `(n1, n2, ..., n(T-1))`. +/// - value: All of the elements in the TensorArray, concatenated along the first +/// axis. +/// - lengths: A vector of the row sizes of the original T elements in the +/// value output. In the example above, this would be the values: +/// `(n1, n2, ..., n(T-1))`. @inlinable @inline(__always) public static func tensorArrayConcatV3( - handle: ResourceHandle, - flowIn: Tensor, - elementShapeExcept0: TensorShape? + handle: ResourceHandle, + flowIn: Tensor, + elementShapeExcept0: TensorShape? ) -> (value: Tensor, lengths: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("TensorArrayConcatV3", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("element_shape_except0", elementShapeExcept0) - op.addInput(handle) - op.addInput(flowIn) - return op.execute(Int(1), Int(1)) + let op = makeOp("TensorArrayConcatV3", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("element_shape_except0", elementShapeExcept0) + op.addInput(handle) + op.addInput(flowIn) + return op.execute(Int(1), Int(1)) } /// Deprecated. Use TensorArrayGatherV3 @inlinable @inline(__always) public static func tensorArrayGatherV2( - handle: StringTensor, - indices: Tensor, - flowIn: Tensor, - elementShape: TensorShape? + handle: StringTensor, + indices: Tensor, + flowIn: Tensor, + elementShape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorArrayGatherV2", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("element_shape", elementShape) - op.addInput(handle) - op.addInput(indices) - op.addInput(flowIn) - return op.execute(Int(1)) + let op = makeOp("TensorArrayGatherV2", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("element_shape", elementShape) + op.addInput(handle) + op.addInput(indices) + op.addInput(flowIn) + return op.execute(Int(1)) } /// Gather specific elements from the TensorArray into output `value`. @@ -33498,48 +33286,48 @@ public static func tensorArrayGatherV2( /// All elements selected by `indices` must have the same shape. /// /// - Parameters: -/// - handle: The handle to a TensorArray. -/// - indices: The locations in the TensorArray from which to read tensor elements. -/// - flow_in: A float scalar that enforces proper chaining of operations. +/// - handle: The handle to a TensorArray. +/// - indices: The locations in the TensorArray from which to read tensor elements. +/// - flow_in: A float scalar that enforces proper chaining of operations. /// /// - Attrs: -/// - dtype: The type of the elem that is returned. -/// - element_shape: The expected shape of an element, if known. Used to -/// validate the shapes of TensorArray elements. If this shape is not -/// fully specified, gathering zero-size TensorArrays is an error. +/// - dtype: The type of the elem that is returned. +/// - element_shape: The expected shape of an element, if known. Used to +/// validate the shapes of TensorArray elements. If this shape is not +/// fully specified, gathering zero-size TensorArrays is an error. /// /// - Output value: All of the elements in the TensorArray, concatenated along a new -/// axis (the new dimension 0). +/// axis (the new dimension 0). @inlinable @inline(__always) public static func tensorArrayGatherV3( - handle: ResourceHandle, - indices: Tensor, - flowIn: Tensor, - elementShape: TensorShape? + handle: ResourceHandle, + indices: Tensor, + flowIn: Tensor, + elementShape: TensorShape? ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorArrayGatherV3", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("element_shape", elementShape) - op.addInput(handle) - op.addInput(indices) - op.addInput(flowIn) - return op.execute(Int(1)) + let op = makeOp("TensorArrayGatherV3", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("element_shape", elementShape) + op.addInput(handle) + op.addInput(indices) + op.addInput(flowIn) + return op.execute(Int(1)) } /// Deprecated. Use TensorArrayGradV3 @inlinable @inline(__always) public static func tensorArrayGradV2( - handle: StringTensor, - flowIn: Tensor, - source: String + handle: StringTensor, + flowIn: Tensor, + source: String ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("TensorArrayGradV2", nOutputs) - op.updateAttribute("source", source) - op.addInput(handle) - op.addInput(flowIn) - return op.execute(Int(1)) + let op = makeOp("TensorArrayGradV2", nOutputs) + op.updateAttribute("source", source) + op.addInput(handle) + op.addInput(flowIn) + return op.execute(Int(1)) } /// Creates a TensorArray for storing the gradients of values in the given handle. @@ -33582,23 +33370,23 @@ public static func tensorArrayGradV2( /// calculation gets its own TensorArray accumulator. /// /// - Parameters: -/// - handle: The handle to the forward TensorArray. -/// - flow_in: A float scalar that enforces proper chaining of operations. +/// - handle: The handle to the forward TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. /// /// - Attr source: The gradient source string, used to decide which gradient TensorArray -/// to return. +/// to return. @inlinable @inline(__always) public static func tensorArrayGradV3( - handle: ResourceHandle, - flowIn: Tensor, - source: String + handle: ResourceHandle, + flowIn: Tensor, + source: String ) -> (gradHandle: ResourceHandle, flowOut: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("TensorArrayGradV3", nOutputs) - op.updateAttribute("source", source) - op.addInput(handle) - op.addInput(flowIn) - return op.execute(Int(1), Int(1)) + let op = makeOp("TensorArrayGradV3", nOutputs) + op.updateAttribute("source", source) + op.addInput(handle) + op.addInput(flowIn) + return op.execute(Int(1), Int(1)) } /// Creates a TensorArray for storing multiple gradients of values in the given handle. @@ -33609,86 +33397,86 @@ public static func tensorArrayGradV3( /// calculated using the same accumulator. /// /// - Parameters: -/// - handle: The handle to the forward TensorArray. -/// - flow_in: A float scalar that enforces proper chaining of operations. -/// - shape_to_prepend: An int32 vector representing a shape. Elements in the gradient accumulator will -/// have shape which is this shape_to_prepend value concatenated with shape of the -/// elements in the TensorArray corresponding to the input handle. +/// - handle: The handle to the forward TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. +/// - shape_to_prepend: An int32 vector representing a shape. Elements in the gradient accumulator will +/// have shape which is this shape_to_prepend value concatenated with shape of the +/// elements in the TensorArray corresponding to the input handle. /// /// - Attr source: The gradient source string, used to decide which gradient TensorArray -/// to return. +/// to return. @inlinable @inline(__always) public static func tensorArrayGradWithShape( - handle: ResourceHandle, - flowIn: Tensor, - shapeToPrepend: Tensor, - source: String + handle: ResourceHandle, + flowIn: Tensor, + shapeToPrepend: Tensor, + source: String ) -> (gradHandle: ResourceHandle, flowOut: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("TensorArrayGradWithShape", nOutputs) - op.updateAttribute("source", source) - op.addInput(handle) - op.addInput(flowIn) - op.addInput(shapeToPrepend) - return op.execute(Int(1), Int(1)) + let op = makeOp("TensorArrayGradWithShape", nOutputs) + op.updateAttribute("source", source) + op.addInput(handle) + op.addInput(flowIn) + op.addInput(shapeToPrepend) + return op.execute(Int(1), Int(1)) } /// Deprecated. Use TensorArrayReadV3 @inlinable @inline(__always) public static func tensorArrayReadV2( - handle: StringTensor, - index: Tensor, - flowIn: Tensor + handle: StringTensor, + index: Tensor, + flowIn: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorArrayReadV2", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(handle) - op.addInput(index) - op.addInput(flowIn) - return op.execute(Int(1)) + let op = makeOp("TensorArrayReadV2", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(handle) + op.addInput(index) + op.addInput(flowIn) + return op.execute(Int(1)) } /// Read an element from the TensorArray into output `value`. /// /// - Parameters: -/// - handle: The handle to a TensorArray. -/// - flow_in: A float scalar that enforces proper chaining of operations. +/// - handle: The handle to a TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. /// /// - Attr dtype: The type of the elem that is returned. /// /// - Output value: The tensor that is read from the TensorArray. @inlinable @inline(__always) public static func tensorArrayReadV3( - handle: ResourceHandle, - index: Tensor, - flowIn: Tensor + handle: ResourceHandle, + index: Tensor, + flowIn: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorArrayReadV3", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.addInput(handle) - op.addInput(index) - op.addInput(flowIn) - return op.execute(Int(1)) + let op = makeOp("TensorArrayReadV3", nOutputs) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.addInput(handle) + op.addInput(index) + op.addInput(flowIn) + return op.execute(Int(1)) } /// Deprecated. Use TensorArrayScatterV3 @inlinable @inline(__always) public static func tensorArrayScatterV2( - handle: StringTensor, - indices: Tensor, - value: Tensor, - flowIn: Tensor + handle: StringTensor, + indices: Tensor, + value: Tensor, + flowIn: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorArrayScatterV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(handle) - op.addInput(indices) - op.addInput(value) - op.addInput(flowIn) - return op.execute(Int(1)) + let op = makeOp("TensorArrayScatterV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(handle) + op.addInput(indices) + op.addInput(value) + op.addInput(flowIn) + return op.execute(Int(1)) } /// Scatter the data from the input value into specific TensorArray elements. @@ -33696,77 +33484,77 @@ public static func tensorArrayScatterV2( /// `indices` must be a vector, its length must match the first dim of `value`. /// /// - Parameters: -/// - handle: The handle to a TensorArray. -/// - indices: The locations at which to write the tensor elements. -/// - value: The concatenated tensor to write to the TensorArray. -/// - flow_in: A float scalar that enforces proper chaining of operations. +/// - handle: The handle to a TensorArray. +/// - indices: The locations at which to write the tensor elements. +/// - value: The concatenated tensor to write to the TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. /// /// - Output flow_out: A float scalar that enforces proper chaining of operations. @inlinable @inline(__always) public static func tensorArrayScatterV3( - handle: ResourceHandle, - indices: Tensor, - value: Tensor, - flowIn: Tensor + handle: ResourceHandle, + indices: Tensor, + value: Tensor, + flowIn: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorArrayScatterV3", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(handle) - op.addInput(indices) - op.addInput(value) - op.addInput(flowIn) - return op.execute(Int(1)) + let op = makeOp("TensorArrayScatterV3", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(handle) + op.addInput(indices) + op.addInput(value) + op.addInput(flowIn) + return op.execute(Int(1)) } /// Deprecated. Use TensorArraySizeV3 @inlinable @inline(__always) public static func tensorArraySizeV2( - handle: StringTensor, - flowIn: Tensor + handle: StringTensor, + flowIn: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorArraySizeV2", nOutputs) - op.addInput(handle) - op.addInput(flowIn) - return op.execute(Int(1)) + let op = makeOp("TensorArraySizeV2", nOutputs) + op.addInput(handle) + op.addInput(flowIn) + return op.execute(Int(1)) } /// Get the current size of the TensorArray. /// /// - Parameters: -/// - handle: The handle to a TensorArray (output of TensorArray or TensorArrayGrad). -/// - flow_in: A float scalar that enforces proper chaining of operations. +/// - handle: The handle to a TensorArray (output of TensorArray or TensorArrayGrad). +/// - flow_in: A float scalar that enforces proper chaining of operations. /// /// - Output size: The current size of the TensorArray. @inlinable @inline(__always) public static func tensorArraySizeV3( - handle: ResourceHandle, - flowIn: Tensor + handle: ResourceHandle, + flowIn: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorArraySizeV3", nOutputs) - op.addInput(handle) - op.addInput(flowIn) - return op.execute(Int(1)) + let op = makeOp("TensorArraySizeV3", nOutputs) + op.addInput(handle) + op.addInput(flowIn) + return op.execute(Int(1)) } /// Deprecated. Use TensorArraySplitV3 @inlinable @inline(__always) public static func tensorArraySplitV2( - handle: StringTensor, - value: Tensor, - lengths: Tensor, - flowIn: Tensor + handle: StringTensor, + value: Tensor, + lengths: Tensor, + flowIn: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorArraySplitV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(handle) - op.addInput(value) - op.addInput(lengths) - op.addInput(flowIn) - return op.execute(Int(1)) + let op = makeOp("TensorArraySplitV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(handle) + op.addInput(value) + op.addInput(lengths) + op.addInput(flowIn) + return op.execute(Int(1)) } /// Split the data from the input value into TensorArray elements. @@ -33790,49 +33578,49 @@ public static func tensorArraySplitV2( /// ```nt x d0 x d1 x ...``` /// /// - Parameters: -/// - handle: The handle to a TensorArray. -/// - value: The concatenated tensor to write to the TensorArray. -/// - lengths: The vector of lengths, how to split the rows of value into the -/// TensorArray. -/// - flow_in: A float scalar that enforces proper chaining of operations. +/// - handle: The handle to a TensorArray. +/// - value: The concatenated tensor to write to the TensorArray. +/// - lengths: The vector of lengths, how to split the rows of value into the +/// TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. /// /// - Output flow_out: A float scalar that enforces proper chaining of operations. @inlinable @inline(__always) public static func tensorArraySplitV3( - handle: ResourceHandle, - value: Tensor, - lengths: Tensor, - flowIn: Tensor + handle: ResourceHandle, + value: Tensor, + lengths: Tensor, + flowIn: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorArraySplitV3", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(handle) - op.addInput(value) - op.addInput(lengths) - op.addInput(flowIn) - return op.execute(Int(1)) + let op = makeOp("TensorArraySplitV3", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(handle) + op.addInput(value) + op.addInput(lengths) + op.addInput(flowIn) + return op.execute(Int(1)) } /// Deprecated. Use TensorArrayV3 @inlinable @inline(__always) public static func tensorArrayV2( - size: Tensor, - dtype: TensorDataType, - elementShape: TensorShape?, - dynamicSize: Bool = false, - clearAfterRead: Bool = true, - tensorArrayName: String + size: Tensor, + dtype: TensorDataType, + elementShape: TensorShape?, + dynamicSize: Bool = false, + clearAfterRead: Bool = true, + tensorArrayName: String ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("TensorArrayV2", nOutputs) - op.updateAttribute("dtype", dtype) - op.updateAttribute("element_shape", elementShape) - op.updateAttribute("dynamic_size", dynamicSize) - op.updateAttribute("clear_after_read", clearAfterRead) - op.updateAttribute("tensor_array_name", tensorArrayName) - op.addInput(size) - return op.execute(Int(1)) + let op = makeOp("TensorArrayV2", nOutputs) + op.updateAttribute("dtype", dtype) + op.updateAttribute("element_shape", elementShape) + op.updateAttribute("dynamic_size", dynamicSize) + op.updateAttribute("clear_after_read", clearAfterRead) + op.updateAttribute("tensor_array_name", tensorArrayName) + op.addInput(size) + return op.execute(Int(1)) } /// An array of Tensors of given size. @@ -33842,140 +33630,140 @@ public static func tensorArrayV2( /// - Parameter size: The size of the array. /// /// - Attrs: -/// - dtype: The type of the elements on the tensor_array. -/// - element_shape: The expected shape of an element, if known. Used to -/// validate the shapes of TensorArray elements. If this shape is not -/// fully specified, gathering zero-size TensorArrays is an error. -/// - dynamic_size: A boolean that determines whether writes to the TensorArray -/// are allowed to grow the size. By default, this is not allowed. -/// - clear_after_read: If true (default), Tensors in the TensorArray are cleared -/// after being read. This disables multiple read semantics but allows early -/// release of memory. -/// - identical_element_shapes: If true (default is false), then all -/// elements in the TensorArray will be expected to have have identical shapes. -/// This allows certain behaviors, like dynamically checking for -/// consistent shapes on write, and being able to fill in properly -/// shaped zero tensors on stack -- even if the element_shape attribute -/// is not fully defined. -/// - tensor_array_name: Overrides the name used for the temporary tensor_array -/// resource. Default value is the name of the 'TensorArray' op (which -/// is guaranteed unique). +/// - dtype: The type of the elements on the tensor_array. +/// - element_shape: The expected shape of an element, if known. Used to +/// validate the shapes of TensorArray elements. If this shape is not +/// fully specified, gathering zero-size TensorArrays is an error. +/// - dynamic_size: A boolean that determines whether writes to the TensorArray +/// are allowed to grow the size. By default, this is not allowed. +/// - clear_after_read: If true (default), Tensors in the TensorArray are cleared +/// after being read. This disables multiple read semantics but allows early +/// release of memory. +/// - identical_element_shapes: If true (default is false), then all +/// elements in the TensorArray will be expected to have have identical shapes. +/// This allows certain behaviors, like dynamically checking for +/// consistent shapes on write, and being able to fill in properly +/// shaped zero tensors on stack -- even if the element_shape attribute +/// is not fully defined. +/// - tensor_array_name: Overrides the name used for the temporary tensor_array +/// resource. Default value is the name of the 'TensorArray' op (which +/// is guaranteed unique). /// /// - Outputs: -/// - handle: The handle to the TensorArray. -/// - flow: A scalar used to control gradient flow. +/// - handle: The handle to the TensorArray. +/// - flow: A scalar used to control gradient flow. @inlinable @inline(__always) public static func tensorArrayV3( - size: Tensor, - dtype: TensorDataType, - elementShape: TensorShape?, - dynamicSize: Bool = false, - clearAfterRead: Bool = true, - identicalElementShapes: Bool = false, - tensorArrayName: String + size: Tensor, + dtype: TensorDataType, + elementShape: TensorShape?, + dynamicSize: Bool = false, + clearAfterRead: Bool = true, + identicalElementShapes: Bool = false, + tensorArrayName: String ) -> (handle: ResourceHandle, flow: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("TensorArrayV3", nOutputs) - op.updateAttribute("dtype", dtype) - op.updateAttribute("element_shape", elementShape) - op.updateAttribute("dynamic_size", dynamicSize) - op.updateAttribute("clear_after_read", clearAfterRead) - op.updateAttribute("identical_element_shapes", identicalElementShapes) - op.updateAttribute("tensor_array_name", tensorArrayName) - op.addInput(size) - return op.execute(Int(1), Int(1)) + let op = makeOp("TensorArrayV3", nOutputs) + op.updateAttribute("dtype", dtype) + op.updateAttribute("element_shape", elementShape) + op.updateAttribute("dynamic_size", dynamicSize) + op.updateAttribute("clear_after_read", clearAfterRead) + op.updateAttribute("identical_element_shapes", identicalElementShapes) + op.updateAttribute("tensor_array_name", tensorArrayName) + op.addInput(size) + return op.execute(Int(1), Int(1)) } /// Deprecated. Use TensorArrayGradV3 @inlinable @inline(__always) public static func tensorArrayWriteV2( - handle: StringTensor, - index: Tensor, - value: Tensor, - flowIn: Tensor + handle: StringTensor, + index: Tensor, + value: Tensor, + flowIn: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorArrayWriteV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(handle) - op.addInput(index) - op.addInput(value) - op.addInput(flowIn) - return op.execute(Int(1)) + let op = makeOp("TensorArrayWriteV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(handle) + op.addInput(index) + op.addInput(value) + op.addInput(flowIn) + return op.execute(Int(1)) } /// Push an element onto the tensor_array. /// /// - Parameters: -/// - handle: The handle to a TensorArray. -/// - index: The position to write to inside the TensorArray. -/// - value: The tensor to write to the TensorArray. -/// - flow_in: A float scalar that enforces proper chaining of operations. +/// - handle: The handle to a TensorArray. +/// - index: The position to write to inside the TensorArray. +/// - value: The tensor to write to the TensorArray. +/// - flow_in: A float scalar that enforces proper chaining of operations. /// /// - Output flow_out: A float scalar that enforces proper chaining of operations. @inlinable @inline(__always) public static func tensorArrayWriteV3( - handle: ResourceHandle, - index: Tensor, - value: Tensor, - flowIn: Tensor + handle: ResourceHandle, + index: Tensor, + value: Tensor, + flowIn: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorArrayWriteV3", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(handle) - op.addInput(index) - op.addInput(value) - op.addInput(flowIn) - return op.execute(Int(1)) + let op = makeOp("TensorArrayWriteV3", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(handle) + op.addInput(index) + op.addInput(value) + op.addInput(flowIn) + return op.execute(Int(1)) } /// Creates a dataset that emits `components` as a tuple of tensors once. @inlinable @inline(__always) public static func tensorDataset( - components: ToutputTypes, - outputShapes: [TensorShape?] + components: ToutputTypes, + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TensorDataset", nOutputs) - op.updateAttribute("Toutput_types", components._typeList) - op.updateAttribute("output_shapes", outputShapes) - op.addInputList(components) - return op.execute(Int(1)) + let op = makeOp("TensorDataset", nOutputs) + op.updateAttribute("Toutput_types", components._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInputList(components) + return op.execute(Int(1)) } /// Creates a tree resource and returns a handle to it. /// /// - Parameters: -/// - tree_handle: Handle to the tree resource to be created. -/// - tree_config: Serialized proto string of the boosted_trees.Tree. +/// - tree_handle: Handle to the tree resource to be created. +/// - tree_config: Serialized proto string of the boosted_trees.Tree. @inlinable @inline(__always) public static func tensorForestCreateTreeVariable( - treeHandle: ResourceHandle, - treeConfig: StringTensor + treeHandle: ResourceHandle, + treeConfig: StringTensor ) { let nOutputs = 0 - let op = makeOp("TensorForestCreateTreeVariable", nOutputs) - op.addInput(treeHandle) - op.addInput(treeConfig) - op.execute() + let op = makeOp("TensorForestCreateTreeVariable", nOutputs) + op.addInput(treeHandle) + op.addInput(treeConfig) + op.execute() } /// Deserializes a proto into the tree handle /// /// - Parameters: -/// - tree_handle: Handle to the tree resource to be restored. -/// - tree_config: Serialied proto string of the boosted_trees.Tree proto. +/// - tree_handle: Handle to the tree resource to be restored. +/// - tree_config: Serialied proto string of the boosted_trees.Tree proto. @inlinable @inline(__always) public static func tensorForestTreeDeserialize( - treeHandle: ResourceHandle, - treeConfig: StringTensor + treeHandle: ResourceHandle, + treeConfig: StringTensor ) { let nOutputs = 0 - let op = makeOp("TensorForestTreeDeserialize", nOutputs) - op.addInput(treeHandle) - op.addInput(treeConfig) - op.execute() + let op = makeOp("TensorForestTreeDeserialize", nOutputs) + op.addInput(treeHandle) + op.addInput(treeConfig) + op.execute() } /// Checks whether a tree has been initialized. @@ -33985,48 +33773,48 @@ public static func tensorForestTreeDeserialize( /// - Output is_initialized: Whether the tree is initialized. @inlinable @inline(__always) public static func tensorForestTreeIsInitializedOp( - treeHandle: ResourceHandle + treeHandle: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorForestTreeIsInitializedOp", nOutputs) - op.addInput(treeHandle) - return op.execute(Int(1)) + let op = makeOp("TensorForestTreeIsInitializedOp", nOutputs) + op.addInput(treeHandle) + return op.execute(Int(1)) } /// Output the logits for the given input data /// /// - Parameters: -/// - tree_handle: Handle to the tree resource. -/// - dense_features: Rank 2 dense features tensor. +/// - tree_handle: Handle to the tree resource. +/// - dense_features: Rank 2 dense features tensor. /// /// - Attr logits_dimension: Scalar, dimension of the logits. /// /// - Output logits: The logits predictions from the tree for each instance in the batch. @inlinable @inline(__always) public static func tensorForestTreePredict( - treeHandle: ResourceHandle, - denseFeatures: Tensor, - logitsDimension: Int64 + treeHandle: ResourceHandle, + denseFeatures: Tensor, + logitsDimension: Int64 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorForestTreePredict", nOutputs) - op.updateAttribute("logits_dimension", logitsDimension) - op.addInput(treeHandle) - op.addInput(denseFeatures) - return op.execute(Int(1)) + let op = makeOp("TensorForestTreePredict", nOutputs) + op.updateAttribute("logits_dimension", logitsDimension) + op.addInput(treeHandle) + op.addInput(denseFeatures) + return op.execute(Int(1)) } /// Creates a handle to a TensorForestTreeResource @inlinable @inline(__always) public static func tensorForestTreeResourceHandleOp( - container: String, - sharedName: String + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("TensorForestTreeResourceHandleOp", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("TensorForestTreeResourceHandleOp", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Serializes the tree handle to a proto @@ -34036,12 +33824,12 @@ public static func tensorForestTreeResourceHandleOp( /// - Output tree_config: Serialied proto string of the tree resource. @inlinable @inline(__always) public static func tensorForestTreeSerialize( - treeHandle: ResourceHandle + treeHandle: ResourceHandle ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("TensorForestTreeSerialize", nOutputs) - op.addInput(treeHandle) - return op.execute(Int(1)) + let op = makeOp("TensorForestTreeSerialize", nOutputs) + op.addInput(treeHandle) + return op.execute(Int(1)) } /// Get the number of nodes in a tree @@ -34051,12 +33839,12 @@ public static func tensorForestTreeSerialize( /// - Output tree_size: The size of the tree. @inlinable @inline(__always) public static func tensorForestTreeSize( - treeHandle: ResourceHandle + treeHandle: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorForestTreeSize", nOutputs) - op.addInput(treeHandle) - return op.execute(Int(1)) + let op = makeOp("TensorForestTreeSize", nOutputs) + op.addInput(treeHandle) + return op.execute(Int(1)) } /// Concats all tensors in the list along the 0th dimension. @@ -34069,29 +33857,29 @@ public static func tensorForestTreeSize( /// @inlinable @inline(__always) public static func tensorListConcat( - inputHandle: VariantHandle, - elementShape: TensorShape? + inputHandle: VariantHandle, + elementShape: TensorShape? ) -> (tensor: Tensor, lengths: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("TensorListConcat", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.updateAttribute("element_shape", elementShape) - op.addInput(inputHandle) - return op.execute(Int(1), Int(1)) + let op = makeOp("TensorListConcat", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("element_shape", elementShape) + op.addInput(inputHandle) + return op.execute(Int(1), Int(1)) } @inlinable @inline(__always) public static func tensorListConcatLists( - inputA: VariantHandle, - inputB: VariantHandle, - elementDtype: TensorDataType + inputA: VariantHandle, + inputB: VariantHandle, + elementDtype: TensorDataType ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TensorListConcatLists", nOutputs) - op.updateAttribute("element_dtype", elementDtype) - op.addInput(inputA) - op.addInput(inputB) - return op.execute(Int(1)) + let op = makeOp("TensorListConcatLists", nOutputs) + op.updateAttribute("element_dtype", elementDtype) + op.addInput(inputA) + op.addInput(inputB) + return op.execute(Int(1)) } /// Concats all tensors in the list along the 0th dimension. @@ -34113,18 +33901,18 @@ public static func tensorListConcatV2< ElementDtype: TensorFlowScalar, ShapeType: BinaryInteger & TensorFlowScalar >( - inputHandle: VariantHandle, - elementShape: Tensor, - leadingDims: Tensor + inputHandle: VariantHandle, + elementShape: Tensor, + leadingDims: Tensor ) -> (tensor: Tensor, lengths: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("TensorListConcatV2", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) - op.addInput(inputHandle) - op.addInput(elementShape) - op.addInput(leadingDims) - return op.execute(Int(1), Int(1)) + let op = makeOp("TensorListConcatV2", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(elementShape) + op.addInput(leadingDims) + return op.execute(Int(1), Int(1)) } /// The shape of the elements of the given list, as a tensor. @@ -34133,13 +33921,13 @@ public static func tensorListConcatV2< /// element_shape: the shape of elements of the list @inlinable @inline(__always) public static func tensorListElementShape( - inputHandle: VariantHandle + inputHandle: VariantHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorListElementShape", nOutputs) - op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) - op.addInput(inputHandle) - return op.execute(Int(1)) + let op = makeOp("TensorListElementShape", nOutputs) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(inputHandle) + return op.execute(Int(1)) } /// Creates a TensorList which, when stacked, has the value of `tensor`. @@ -34153,16 +33941,16 @@ public static func tensorListFromTensor< ElementDtype: TensorFlowScalar, ShapeType: BinaryInteger & TensorFlowScalar >( - _ tensor: Tensor, - elementShape: Tensor + _ tensor: Tensor, + elementShape: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TensorListFromTensor", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) - op.addInput(tensor) - op.addInput(elementShape) - return op.execute(Int(1)) + let op = makeOp("TensorListFromTensor", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(tensor) + op.addInput(elementShape) + return op.execute(Int(1)) } /// Creates a Tensor by indexing into the TensorList. @@ -34175,32 +33963,32 @@ public static func tensorListFromTensor< /// values: The tensor. @inlinable @inline(__always) public static func tensorListGather( - inputHandle: VariantHandle, - indices: Tensor, - elementShape: Tensor + inputHandle: VariantHandle, + indices: Tensor, + elementShape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorListGather", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.addInput(inputHandle) - op.addInput(indices) - op.addInput(elementShape) - return op.execute(Int(1)) + let op = makeOp("TensorListGather", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(indices) + op.addInput(elementShape) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func tensorListGetItem( - inputHandle: VariantHandle, - index: Tensor, - elementShape: Tensor + inputHandle: VariantHandle, + index: Tensor, + elementShape: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorListGetItem", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.addInput(inputHandle) - op.addInput(index) - op.addInput(elementShape) - return op.execute(Int(1)) + let op = makeOp("TensorListGetItem", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(index) + op.addInput(elementShape) + return op.execute(Int(1)) } /// Returns the number of tensors in the input tensor list. @@ -34209,12 +33997,12 @@ public static func tensorListGetItem( /// length: the number of tensors in the list @inlinable @inline(__always) public static func tensorListLength( - inputHandle: VariantHandle + inputHandle: VariantHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorListLength", nOutputs) - op.addInput(inputHandle) - return op.execute(Int(1)) + let op = makeOp("TensorListLength", nOutputs) + op.addInput(inputHandle) + return op.execute(Int(1)) } /// Returns the last element of the input list as well as a list with all but that element. @@ -34227,15 +34015,15 @@ public static func tensorListLength( /// element_shape: the shape of the output tensor @inlinable @inline(__always) public static func tensorListPopBack( - inputHandle: VariantHandle, - elementShape: Tensor + inputHandle: VariantHandle, + elementShape: Tensor ) -> (outputHandle: VariantHandle, tensor: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("TensorListPopBack", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.addInput(inputHandle) - op.addInput(elementShape) - return op.execute(Int(1), Int(1)) + let op = makeOp("TensorListPopBack", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(elementShape) + return op.execute(Int(1), Int(1)) } /// Returns a list list which has the passed-in `Tensor` as last element and the other elements of the given list in `input_handle`. @@ -34247,28 +34035,28 @@ public static func tensorListPopBack( /// element_shape: a shape compatible with that of elements in the list. @inlinable @inline(__always) public static func tensorListPushBack( - inputHandle: VariantHandle, - _ tensor: Tensor + inputHandle: VariantHandle, + _ tensor: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TensorListPushBack", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.addInput(inputHandle) - op.addInput(tensor) - return op.execute(Int(1)) + let op = makeOp("TensorListPushBack", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(tensor) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func tensorListPushBackBatch( - inputHandles: VariantHandle, - _ tensor: Tensor + inputHandles: VariantHandle, + _ tensor: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TensorListPushBackBatch", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.addInput(inputHandles) - op.addInput(tensor) - return op.execute(Int(1)) + let op = makeOp("TensorListPushBackBatch", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandles) + op.addInput(tensor) + return op.execute(Int(1)) } /// List of the given size with empty elements. @@ -34279,17 +34067,17 @@ public static func tensorListPushBackBatch( /// element_dtype: the desired type of elements in the list. @inlinable @inline(__always) public static func tensorListReserve( - elementShape: Tensor, - numElements: Tensor, - elementDtype: TensorDataType + elementShape: Tensor, + numElements: Tensor, + elementDtype: TensorDataType ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TensorListReserve", nOutputs) - op.updateAttribute("element_dtype", elementDtype) - op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) - op.addInput(elementShape) - op.addInput(numElements) - return op.execute(Int(1)) + let op = makeOp("TensorListReserve", nOutputs) + op.updateAttribute("element_dtype", elementDtype) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(elementShape) + op.addInput(numElements) + return op.execute(Int(1)) } /// Resizes the list. @@ -34300,14 +34088,14 @@ public static func tensorListReserve + inputHandle: VariantHandle, + size: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TensorListResize", nOutputs) - op.addInput(inputHandle) - op.addInput(size) - return op.execute(Int(1)) + let op = makeOp("TensorListResize", nOutputs) + op.addInput(inputHandle) + op.addInput(size) + return op.execute(Int(1)) } /// Creates a TensorList by indexing into a Tensor. @@ -34325,18 +34113,18 @@ public static func tensorListScatter< ElementDtype: TensorFlowScalar, ShapeType: BinaryInteger & TensorFlowScalar >( - _ tensor: Tensor, - indices: Tensor, - elementShape: Tensor + _ tensor: Tensor, + indices: Tensor, + elementShape: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TensorListScatter", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) - op.addInput(tensor) - op.addInput(indices) - op.addInput(elementShape) - return op.execute(Int(1)) + let op = makeOp("TensorListScatter", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(tensor) + op.addInput(indices) + op.addInput(elementShape) + return op.execute(Int(1)) } /// Scatters tensor at indices in an input list. @@ -34350,17 +34138,17 @@ public static func tensorListScatter< /// output_handle: The TensorList. @inlinable @inline(__always) public static func tensorListScatterIntoExistingList( - inputHandle: VariantHandle, - _ tensor: Tensor, - indices: Tensor + inputHandle: VariantHandle, + _ tensor: Tensor, + indices: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TensorListScatterIntoExistingList", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.addInput(inputHandle) - op.addInput(tensor) - op.addInput(indices) - return op.execute(Int(1)) + let op = makeOp("TensorListScatterIntoExistingList", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(tensor) + op.addInput(indices) + return op.execute(Int(1)) } /// Creates a TensorList by indexing into a Tensor. @@ -34381,35 +34169,35 @@ public static func tensorListScatterV2< ElementDtype: TensorFlowScalar, ShapeType: BinaryInteger & TensorFlowScalar >( - _ tensor: Tensor, - indices: Tensor, - elementShape: Tensor, - numElements: Tensor + _ tensor: Tensor, + indices: Tensor, + elementShape: Tensor, + numElements: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TensorListScatterV2", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) - op.addInput(tensor) - op.addInput(indices) - op.addInput(elementShape) - op.addInput(numElements) - return op.execute(Int(1)) + let op = makeOp("TensorListScatterV2", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(tensor) + op.addInput(indices) + op.addInput(elementShape) + op.addInput(numElements) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func tensorListSetItem( - inputHandle: VariantHandle, - index: Tensor, - item: Tensor + inputHandle: VariantHandle, + index: Tensor, + item: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TensorListSetItem", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.addInput(inputHandle) - op.addInput(index) - op.addInput(item) - return op.execute(Int(1)) + let op = makeOp("TensorListSetItem", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.addInput(inputHandle) + op.addInput(index) + op.addInput(item) + return op.execute(Int(1)) } /// Splits a tensor into a list. @@ -34426,18 +34214,18 @@ public static func tensorListSplit< ElementDtype: TensorFlowScalar, ShapeType: BinaryInteger & TensorFlowScalar >( - _ tensor: Tensor, - elementShape: Tensor, - lengths: Tensor + _ tensor: Tensor, + elementShape: Tensor, + lengths: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TensorListSplit", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) - op.addInput(tensor) - op.addInput(elementShape) - op.addInput(lengths) - return op.execute(Int(1)) + let op = makeOp("TensorListSplit", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("shape_type", ShapeType.tensorFlowDataType) + op.addInput(tensor) + op.addInput(elementShape) + op.addInput(lengths) + return op.execute(Int(1)) } /// Stacks all tensors in the list. @@ -34450,17 +34238,17 @@ public static func tensorListSplit< /// @inlinable @inline(__always) public static func tensorListStack( - inputHandle: VariantHandle, - elementShape: Tensor, - numElements: Int64 = -1 + inputHandle: VariantHandle, + elementShape: Tensor, + numElements: Int64 = -1 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorListStack", nOutputs) - op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) - op.updateAttribute("num_elements", numElements) - op.addInput(inputHandle) - op.addInput(elementShape) - return op.execute(Int(1)) + let op = makeOp("TensorListStack", nOutputs) + op.updateAttribute("element_dtype", ElementDtype.tensorFlowDataType) + op.updateAttribute("num_elements", numElements) + op.addInput(inputHandle) + op.addInput(elementShape) + return op.execute(Int(1)) } /// Adds sparse `updates` to an existing tensor according to `indices`. @@ -34531,9 +34319,9 @@ public static func tensorListStack( /// On GPU, if an out of bound index is found, the index is ignored. /// /// - Parameters: -/// - tensor: Tensor to copy/update. -/// - indices: Index tensor. -/// - updates: Updates to scatter into output. +/// - tensor: Tensor to copy/update. +/// - indices: Index tensor. +/// - updates: Updates to scatter into output. /// /// - Output output: A new tensor copied from tensor and updates added according to the indices. @inlinable @inline(__always) @@ -34541,18 +34329,18 @@ public static func tensorScatterAdd< T: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - _ tensor: Tensor, - indices: Tensor, - updates: Tensor + _ tensor: Tensor, + indices: Tensor, + updates: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorScatterAdd", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(tensor) - op.addInput(indices) - op.addInput(updates) - return op.execute(Int(1)) + let op = makeOp("TensorScatterAdd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(tensor) + op.addInput(indices) + op.addInput(updates) + return op.execute(Int(1)) } /// Subtracts sparse `updates` from an existing tensor according to `indices`. @@ -34623,9 +34411,9 @@ public static func tensorScatterAdd< /// On GPU, if an out of bound index is found, the index is ignored. /// /// - Parameters: -/// - tensor: Tensor to copy/update. -/// - indices: Index tensor. -/// - updates: Updates to scatter into output. +/// - tensor: Tensor to copy/update. +/// - indices: Index tensor. +/// - updates: Updates to scatter into output. /// /// - Output output: A new tensor copied from tensor and updates subtracted according to the indices. @inlinable @inline(__always) @@ -34633,18 +34421,18 @@ public static func tensorScatterSub< T: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - _ tensor: Tensor, - indices: Tensor, - updates: Tensor + _ tensor: Tensor, + indices: Tensor, + updates: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorScatterSub", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(tensor) - op.addInput(indices) - op.addInput(updates) - return op.execute(Int(1)) + let op = makeOp("TensorScatterSub", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(tensor) + op.addInput(indices) + op.addInput(updates) + return op.execute(Int(1)) } /// Scatter `updates` into an existing tensor according to `indices`. @@ -34726,43 +34514,43 @@ public static func tensorScatterSub< /// On GPU, if an out of bound index is found, the index is ignored. /// /// - Parameters: -/// - tensor: Tensor to copy/update. -/// - indices: Index tensor. -/// - updates: Updates to scatter into output. +/// - tensor: Tensor to copy/update. +/// - indices: Index tensor. +/// - updates: Updates to scatter into output. /// /// - Output output: A new tensor with the given shape and updates applied according -/// to the indices. +/// to the indices. @inlinable @inline(__always) public static func tensorScatterUpdate< T: TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar >( - _ tensor: Tensor, - indices: Tensor, - updates: Tensor + _ tensor: Tensor, + indices: Tensor, + updates: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TensorScatterUpdate", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(tensor) - op.addInput(indices) - op.addInput(updates) - return op.execute(Int(1)) + let op = makeOp("TensorScatterUpdate", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.addInput(tensor) + op.addInput(indices) + op.addInput(updates) + return op.execute(Int(1)) } /// Creates a dataset that emits each dim-0 slice of `components` once. @inlinable @inline(__always) public static func tensorSliceDataset( - components: ToutputTypes, - outputShapes: [TensorShape?] + components: ToutputTypes, + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TensorSliceDataset", nOutputs) - op.updateAttribute("Toutput_types", components._typeList) - op.updateAttribute("output_shapes", outputShapes) - op.addInputList(components) - return op.execute(Int(1)) + let op = makeOp("TensorSliceDataset", nOutputs) + op.updateAttribute("Toutput_types", components._typeList) + op.updateAttribute("output_shapes", outputShapes) + op.addInputList(components) + return op.execute(Int(1)) } /// Assign `value` to the sliced l-value reference of `input`. @@ -34778,32 +34566,32 @@ public static func tensorStridedSliceUpdate< T: TensorFlowScalar, Index: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - begin: Tensor, - end: Tensor, - strides: Tensor, - value: Tensor, - beginMask: Int64 = 0, - endMask: Int64 = 0, - ellipsisMask: Int64 = 0, - newAxisMask: Int64 = 0, - shrinkAxisMask: Int64 = 0 -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("TensorStridedSliceUpdate", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Index", Index.tensorFlowDataType) - op.updateAttribute("begin_mask", beginMask) - op.updateAttribute("end_mask", endMask) - op.updateAttribute("ellipsis_mask", ellipsisMask) - op.updateAttribute("new_axis_mask", newAxisMask) - op.updateAttribute("shrink_axis_mask", shrinkAxisMask) - op.addInput(input) - op.addInput(begin) - op.addInput(end) - op.addInput(strides) - op.addInput(value) - return op.execute(Int(1)) + _ input: Tensor, + begin: Tensor, + end: Tensor, + strides: Tensor, + value: Tensor, + beginMask: Int64 = 0, + endMask: Int64 = 0, + ellipsisMask: Int64 = 0, + newAxisMask: Int64 = 0, + shrinkAxisMask: Int64 = 0 +) -> Tensor { + let nOutputs = Int(1) + let op = makeOp("TensorStridedSliceUpdate", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Index", Index.tensorFlowDataType) + op.updateAttribute("begin_mask", beginMask) + op.updateAttribute("end_mask", endMask) + op.updateAttribute("ellipsis_mask", ellipsisMask) + op.updateAttribute("new_axis_mask", newAxisMask) + op.updateAttribute("shrink_axis_mask", shrinkAxisMask) + op.addInput(input) + op.addInput(begin) + op.addInput(end) + op.addInput(strides) + op.addInput(value) + return op.execute(Int(1)) } /// Outputs a `Summary` protocol buffer with a tensor. @@ -34815,111 +34603,111 @@ public static func tensorStridedSliceUpdate< /// - Parameter tensor: A tensor to serialize. /// /// - Attrs: -/// - description: A json-encoded SummaryDescription proto. -/// - labels: An unused list of strings. -/// - display_name: An unused string. +/// - description: A json-encoded SummaryDescription proto. +/// - labels: An unused list of strings. +/// - display_name: An unused string. @inlinable @inline(__always) public static func tensorSummary( - _ tensor: Tensor, - description: String, - labels: [String], - displayName: String + _ tensor: Tensor, + description: String, + labels: [String], + displayName: String ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("TensorSummary", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("description", description) - op.updateAttribute("labels", labels) - op.updateAttribute("display_name", displayName) - op.addInput(tensor) - return op.execute(Int(1)) + let op = makeOp("TensorSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("description", description) + op.updateAttribute("labels", labels) + op.updateAttribute("display_name", displayName) + op.addInput(tensor) + return op.execute(Int(1)) } /// Outputs a `Summary` protocol buffer with a tensor and per-plugin data. /// /// - Parameters: -/// - tag: A string attached to this summary. Used for organization in TensorBoard. -/// - tensor: A tensor to serialize. -/// - serialized_summary_metadata: A serialized SummaryMetadata proto. Contains plugin -/// data. +/// - tag: A string attached to this summary. Used for organization in TensorBoard. +/// - tensor: A tensor to serialize. +/// - serialized_summary_metadata: A serialized SummaryMetadata proto. Contains plugin +/// data. @inlinable @inline(__always) public static func tensorSummaryV2( - tag: StringTensor, - _ tensor: Tensor, - serializedSummaryMetadata: StringTensor + tag: StringTensor, + _ tensor: Tensor, + serializedSummaryMetadata: StringTensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("TensorSummaryV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(tag) - op.addInput(tensor) - op.addInput(serializedSummaryMetadata) - return op.execute(Int(1)) + let op = makeOp("TensorSummaryV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(tag) + op.addInput(tensor) + op.addInput(serializedSummaryMetadata) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func testAttr( ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TestAttr", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - return op.execute(Int(1)) + let op = makeOp("TestAttr", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func testStringOutput( - _ input: Tensor + _ input: Tensor ) -> (output1: Tensor, output2: StringTensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("TestStringOutput", nOutputs) - op.addInput(input) - return op.execute(Int(1), Int(1)) + let op = makeOp("TestStringOutput", nOutputs) + op.addInput(input) + return op.execute(Int(1), Int(1)) } /// Creates a dataset that emits the lines of one or more text files. /// /// - Parameters: -/// - filenames: A scalar or a vector containing the name(s) of the file(s) to be -/// read. -/// - compression_type: A scalar containing either (i) the empty string (no -/// compression), (ii) "ZLIB", or (iii) "GZIP". -/// - buffer_size: A scalar containing the number of bytes to buffer. +/// - filenames: A scalar or a vector containing the name(s) of the file(s) to be +/// read. +/// - compression_type: A scalar containing either (i) the empty string (no +/// compression), (ii) "ZLIB", or (iii) "GZIP". +/// - buffer_size: A scalar containing the number of bytes to buffer. @inlinable @inline(__always) public static func textLineDataset( - filenames: StringTensor, - compressionType: StringTensor, - bufferSize: Tensor + filenames: StringTensor, + compressionType: StringTensor, + bufferSize: Tensor ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("TextLineDataset", nOutputs) - op.addInput(filenames) - op.addInput(compressionType) - op.addInput(bufferSize) - return op.execute(Int(1)) + let op = makeOp("TextLineDataset", nOutputs) + op.addInput(filenames) + op.addInput(compressionType) + op.addInput(bufferSize) + return op.execute(Int(1)) } /// A Reader that outputs the lines of a file delimited by '\n'. /// /// - Attrs: -/// - skip_header_lines: Number of lines to skip from the beginning of every file. -/// - container: If non-empty, this reader is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this reader is named in the given bucket -/// with this shared_name. Otherwise, the node name is used instead. +/// - skip_header_lines: Number of lines to skip from the beginning of every file. +/// - container: If non-empty, this reader is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this reader is named in the given bucket +/// with this shared_name. Otherwise, the node name is used instead. /// /// - Output reader_handle: The handle to reference the Reader. @inlinable @inline(__always) public static func textLineReaderV2( - skipHeaderLines: Int64 = 0, - container: String, - sharedName: String + skipHeaderLines: Int64 = 0, + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("TextLineReaderV2", nOutputs) - op.updateAttribute("skip_header_lines", skipHeaderLines) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("TextLineReaderV2", nOutputs) + op.updateAttribute("skip_header_lines", skipHeaderLines) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// Generates labels for candidate sampling with a learned unigram distribution. @@ -34935,50 +34723,50 @@ public static func textLineReaderV2( /// true labels. /// /// - Parameter true_classes: A batch_size * num_true matrix, in which each row contains the -/// IDs of the num_true target_classes in the corresponding original label. +/// IDs of the num_true target_classes in the corresponding original label. /// /// - Attrs: -/// - num_true: Number of true labels per context. -/// - num_sampled: Number of candidates to randomly sample. -/// - unique: If unique is true, we sample with rejection, so that all sampled -/// candidates in a batch are unique. This requires some approximation to -/// estimate the post-rejection sampling probabilities. -/// - range_max: The sampler will sample integers from the interval [0, range_max). -/// - seed: If either seed or seed2 are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: An second seed to avoid seed collision. +/// - num_true: Number of true labels per context. +/// - num_sampled: Number of candidates to randomly sample. +/// - unique: If unique is true, we sample with rejection, so that all sampled +/// candidates in a batch are unique. This requires some approximation to +/// estimate the post-rejection sampling probabilities. +/// - range_max: The sampler will sample integers from the interval [0, range_max). +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. /// /// - Outputs: -/// - sampled_candidates: A vector of length num_sampled, in which each element is -/// the ID of a sampled candidate. -/// - true_expected_count: A batch_size * num_true matrix, representing -/// the number of times each candidate is expected to occur in a batch -/// of sampled candidates. If unique=true, then this is a probability. -/// - sampled_expected_count: A vector of length num_sampled, for each sampled -/// candidate representing the number of times the candidate is expected -/// to occur in a batch of sampled candidates. If unique=true, then this is a -/// probability. +/// - sampled_candidates: A vector of length num_sampled, in which each element is +/// the ID of a sampled candidate. +/// - true_expected_count: A batch_size * num_true matrix, representing +/// the number of times each candidate is expected to occur in a batch +/// of sampled candidates. If unique=true, then this is a probability. +/// - sampled_expected_count: A vector of length num_sampled, for each sampled +/// candidate representing the number of times the candidate is expected +/// to occur in a batch of sampled candidates. If unique=true, then this is a +/// probability. @inlinable @inline(__always) public static func threadUnsafeUnigramCandidateSampler( - trueClasses: Tensor, - numTrue: Int64, - numSampled: Int64, - unique: Bool, - rangeMax: Int64, - seed: Int64 = 0, - seed2: Int64 = 0 + trueClasses: Tensor, + numTrue: Int64, + numSampled: Int64, + unique: Bool, + rangeMax: Int64, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> (sampledCandidates: Tensor, trueExpectedCount: Tensor, sampledExpectedCount: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("ThreadUnsafeUnigramCandidateSampler", nOutputs) - op.updateAttribute("num_true", numTrue) - op.updateAttribute("num_sampled", numSampled) - op.updateAttribute("unique", unique) - op.updateAttribute("range_max", rangeMax) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.addInput(trueClasses) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("ThreadUnsafeUnigramCandidateSampler", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("num_sampled", numSampled) + op.updateAttribute("unique", unique) + op.updateAttribute("range_max", rangeMax) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + return op.execute(Int(1), Int(1), Int(1)) } /// Constructs a tensor by tiling a given tensor. @@ -34990,23 +34778,23 @@ public static func threadUnsafeUnigramCandidateSampler( /// `[a b c d a b c d]`. /// /// - Parameters: -/// - input: 1-D or higher. -/// - multiples: 1-D. Length must be the same as the number of dimensions in `input` +/// - input: 1-D or higher. +/// - multiples: 1-D. Length must be the same as the number of dimensions in `input` @inlinable @inline(__always) public static func tile< T: TensorFlowScalar, Tmultiples: BinaryInteger & TensorFlowScalar >( - _ input: Tensor, - multiples: Tensor + _ input: Tensor, + multiples: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Tile", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tmultiples", Tmultiples.tensorFlowDataType) - op.addInput(input) - op.addInput(multiples) - return op.execute(Int(1)) + let op = makeOp("Tile", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tmultiples", Tmultiples.tensorFlowDataType) + op.addInput(input) + op.addInput(multiples) + return op.execute(Int(1)) } /// Returns the gradient of `Tile`. @@ -35016,15 +34804,15 @@ public static func tile< /// each repeated tile of `input` into `output`. @inlinable @inline(__always) public static func tileGrad( - _ input: Tensor, - multiples: Tensor + _ input: Tensor, + multiples: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TileGrad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - op.addInput(multiples) - return op.execute(Int(1)) + let op = makeOp("TileGrad", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(multiples) + return op.execute(Int(1)) } /// Provides the time since epoch in seconds. @@ -35037,9 +34825,9 @@ public static func tileGrad( public static func timestamp( ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Timestamp", nOutputs) - - return op.execute(Int(1)) + let op = makeOp("Timestamp", nOutputs) + + return op.execute(Int(1)) } /// Finds values and indices of the `k` largest elements for the last dimension. @@ -35060,27 +34848,27 @@ public static func timestamp( /// - Parameter input: 1-D or higher with last dimension at least `k`. /// /// - Attrs: -/// - k: Number of top elements to look for along the last dimension (along each -/// row for matrices). -/// - sorted: If true the resulting `k` elements will be sorted by the values in -/// descending order. +/// - k: Number of top elements to look for along the last dimension (along each +/// row for matrices). +/// - sorted: If true the resulting `k` elements will be sorted by the values in +/// descending order. /// /// - Outputs: -/// - values: The `k` largest elements along each last dimensional slice. -/// - indices: The indices of `values` within the last dimension of `input`. +/// - values: The `k` largest elements along each last dimensional slice. +/// - indices: The indices of `values` within the last dimension of `input`. @inlinable @inline(__always) public static func topK( - _ input: Tensor, - k: Int64, - sorted: Bool = true + _ input: Tensor, + k: Int64, + sorted: Bool = true ) -> (values: Tensor, indices: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("TopK", nOutputs) - op.updateAttribute("k", k) - op.updateAttribute("sorted", sorted) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1), Int(1)) + let op = makeOp("TopK", nOutputs) + op.updateAttribute("k", k) + op.updateAttribute("sorted", sorted) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1), Int(1)) } /// Finds values and indices of the `k` largest elements for the last dimension. @@ -35097,29 +34885,29 @@ public static func topK( /// If two elements are equal, the lower-index element appears first. /// /// - Parameters: -/// - input: 1-D or higher with last dimension at least `k`. -/// - k: 0-D. Number of top elements to look for along the last dimension (along each -/// row for matrices). +/// - input: 1-D or higher with last dimension at least `k`. +/// - k: 0-D. Number of top elements to look for along the last dimension (along each +/// row for matrices). /// /// - Attr sorted: If true the resulting `k` elements will be sorted by the values in -/// descending order. +/// descending order. /// /// - Outputs: -/// - values: The `k` largest elements along each last dimensional slice. -/// - indices: The indices of `values` within the last dimension of `input`. +/// - values: The `k` largest elements along each last dimensional slice. +/// - indices: The indices of `values` within the last dimension of `input`. @inlinable @inline(__always) public static func topKV2( - _ input: Tensor, - k: Tensor, - sorted: Bool = true + _ input: Tensor, + k: Tensor, + sorted: Bool = true ) -> (values: Tensor, indices: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("TopKV2", nOutputs) - op.updateAttribute("sorted", sorted) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - op.addInput(k) - return op.execute(Int(1), Int(1)) + let op = makeOp("TopKV2", nOutputs) + op.updateAttribute("sorted", sorted) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + op.addInput(k) + return op.execute(Int(1), Int(1)) } /// Shuffle dimensions of x according to a permutation. @@ -35131,33 +34919,16 @@ public static func transpose< T: TensorFlowScalar, Tperm: BinaryInteger & TensorFlowScalar >( - _ x: Tensor, - perm: Tensor + _ x: Tensor, + perm: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Transpose", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tperm", Tperm.tensorFlowDataType) - op.addInput(x) - op.addInput(perm) - return op.execute(Int(1)) -} - -@inlinable @inline(__always) -public static func tridiagonalMatMul( - superdiag: Tensor, - maindiag: Tensor, - subdiag: Tensor, - rhs: Tensor -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("TridiagonalMatMul", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(superdiag) - op.addInput(maindiag) - op.addInput(subdiag) - op.addInput(rhs) - return op.execute(Int(1)) + let op = makeOp("Transpose", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tperm", Tperm.tensorFlowDataType) + op.addInput(x) + op.addInput(perm) + return op.execute(Int(1)) } /// Solves tridiagonal systems of equations. @@ -35171,23 +34942,21 @@ public static func tridiagonalMatMul( /// The output is a tensor of shape `[..., M, K]` containing the solutions. /// /// - Parameters: -/// - diagonals: Shape is `[..., 3, M]`. -/// - rhs: Shape is `[..., M, K]`. +/// - diagonals: Shape is `[..., 3, M]`. +/// - rhs: Shape is `[..., M, K]`. /// /// - Output output: Shape is `[..., M, K]`. @inlinable @inline(__always) public static func tridiagonalSolve( - diagonals: Tensor, - rhs: Tensor, - partialPivoting: Bool = true + diagonals: Tensor, + rhs: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TridiagonalSolve", nOutputs) - op.updateAttribute("partial_pivoting", partialPivoting) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(diagonals) - op.addInput(rhs) - return op.execute(Int(1)) + let op = makeOp("TridiagonalSolve", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(diagonals) + op.addInput(rhs) + return op.execute(Int(1)) } /// Returns x / y element-wise for integer types. @@ -35201,15 +34970,15 @@ public static func tridiagonalSolve( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func truncateDiv( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TruncateDiv", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("TruncateDiv", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns element-wise remainder of division. This emulates C semantics in that @@ -35221,15 +34990,15 @@ public static func truncateDiv( /// [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) @inlinable @inline(__always) public static func truncateMod( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TruncateMod", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("TruncateMod", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Outputs random values from a truncated normal distribution. @@ -35241,31 +35010,31 @@ public static func truncateMod( /// - Parameter shape: The shape of the output tensor. /// /// - Attrs: -/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: A second seed to avoid seed collision. -/// - dtype: The type of the output. +/// - seed: If either `seed` or `seed2` are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: A second seed to avoid seed collision. +/// - dtype: The type of the output. /// /// - Output output: A tensor of the specified shape filled with random truncated normal -/// values. +/// values. @inlinable @inline(__always) public static func truncatedNormal< Dtype: FloatingPoint & TensorFlowScalar, T: BinaryInteger & TensorFlowScalar >( - shape: Tensor, - seed: Int64 = 0, - seed2: Int64 = 0 + shape: Tensor, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TruncatedNormal", nOutputs) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(shape) - return op.execute(Int(1)) + let op = makeOp("TruncatedNormal", nOutputs) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.updateAttribute("dtype", Dtype.tensorFlowDataType) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(shape) + return op.execute(Int(1)) } /// Perform batches of RPC requests. @@ -35321,161 +35090,161 @@ public static func truncatedNormal< /// not fail; the rest of the entries will have empty strings. /// /// - Parameters: -/// - address: `0-D` or `1-D`. The address (i.e. host_name:port) of the RPC server. -/// If this tensor has more than 1 element, then multiple parallel rpc requests -/// are sent. This argument broadcasts with `method` and `request`. -/// - method: `0-D` or `1-D`. The method address on the RPC server. -/// If this tensor has more than 1 element, then multiple parallel rpc requests -/// are sent. This argument broadcasts with `address` and `request`. -/// - request: `0-D` or `1-D`. Serialized proto strings: the rpc request argument. -/// If this tensor has more than 1 element, then multiple parallel rpc requests -/// are sent. This argument broadcasts with `address` and `method`. +/// - address: `0-D` or `1-D`. The address (i.e. host_name:port) of the RPC server. +/// If this tensor has more than 1 element, then multiple parallel rpc requests +/// are sent. This argument broadcasts with `method` and `request`. +/// - method: `0-D` or `1-D`. The method address on the RPC server. +/// If this tensor has more than 1 element, then multiple parallel rpc requests +/// are sent. This argument broadcasts with `address` and `request`. +/// - request: `0-D` or `1-D`. Serialized proto strings: the rpc request argument. +/// If this tensor has more than 1 element, then multiple parallel rpc requests +/// are sent. This argument broadcasts with `address` and `method`. /// /// - Attrs: -/// - protocol: RPC protocol to use. Empty string means use the default protocol. -/// Options include 'grpc'. -/// - fail_fast: `boolean`. If `true` (default), then failures to connect -/// (i.e., the server does not immediately respond) cause an RPC failure. -/// - timeout_in_ms: `int`. If `0` (default), then the kernel will run the RPC -/// request and only time out if the RPC deadline passes or the session times out. -/// If this value is greater than `0`, then the op will raise an exception if -/// the RPC takes longer than `timeout_in_ms`. +/// - protocol: RPC protocol to use. Empty string means use the default protocol. +/// Options include 'grpc'. +/// - fail_fast: `boolean`. If `true` (default), then failures to connect +/// (i.e., the server does not immediately respond) cause an RPC failure. +/// - timeout_in_ms: `int`. If `0` (default), then the kernel will run the RPC +/// request and only time out if the RPC deadline passes or the session times out. +/// If this value is greater than `0`, then the op will raise an exception if +/// the RPC takes longer than `timeout_in_ms`. /// /// - Outputs: -/// - response: Same shape as `request`. Serialized proto strings: the rpc responses. -/// - status_code: Same shape as `request`. Values correspond to tensorflow Status enum codes. -/// - status_message: Same shape as `request`. Values correspond to Status messages -/// returned from the RPC calls. +/// - response: Same shape as `request`. Serialized proto strings: the rpc responses. +/// - status_code: Same shape as `request`. Values correspond to tensorflow Status enum codes. +/// - status_message: Same shape as `request`. Values correspond to Status messages +/// returned from the RPC calls. @inlinable @inline(__always) public static func tryRpc( - address: StringTensor, - method: StringTensor, - request: StringTensor, - protocol_: String, - failFast: Bool = true, - timeoutInMs: Int64 = 0 + address: StringTensor, + method: StringTensor, + request: StringTensor, + protocol_: String, + failFast: Bool = true, + timeoutInMs: Int64 = 0 ) -> (response: StringTensor, statusCode: Tensor, statusMessage: StringTensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("TryRpc", nOutputs) - op.updateAttribute("protocol", protocol_) - op.updateAttribute("fail_fast", failFast) - op.updateAttribute("timeout_in_ms", timeoutInMs) - op.addInput(address) - op.addInput(method) - op.addInput(request) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("TryRpc", nOutputs) + op.updateAttribute("protocol", protocol_) + op.updateAttribute("fail_fast", failFast) + op.updateAttribute("timeout_in_ms", timeoutInMs) + op.addInput(address) + op.addInput(method) + op.addInput(request) + return op.execute(Int(1), Int(1), Int(1)) } @inlinable @inline(__always) public static func twoFloatInputs( - _ a: Tensor, - _ b: Tensor + _ a: Tensor, + _ b: Tensor ) { let nOutputs = 0 - let op = makeOp("TwoFloatInputs", nOutputs) - op.addInput(a) - op.addInput(b) - op.execute() + let op = makeOp("TwoFloatInputs", nOutputs) + op.addInput(a) + op.addInput(b) + op.execute() } @inlinable @inline(__always) public static func twoFloatInputsFloatOutput( - _ a: Tensor, - _ b: Tensor + _ a: Tensor, + _ b: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TwoFloatInputsFloatOutput", nOutputs) - op.addInput(a) - op.addInput(b) - return op.execute(Int(1)) + let op = makeOp("TwoFloatInputsFloatOutput", nOutputs) + op.addInput(a) + op.addInput(b) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func twoFloatInputsIntOutput( - _ a: Tensor, - _ b: Tensor + _ a: Tensor, + _ b: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("TwoFloatInputsIntOutput", nOutputs) - op.addInput(a) - op.addInput(b) - return op.execute(Int(1)) + let op = makeOp("TwoFloatInputsIntOutput", nOutputs) + op.addInput(a) + op.addInput(b) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func twoFloatOutputs( ) -> (a: Tensor, b: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("TwoFloatOutputs", nOutputs) - - return op.execute(Int(1), Int(1)) + let op = makeOp("TwoFloatOutputs", nOutputs) + + return op.execute(Int(1), Int(1)) } @inlinable @inline(__always) public static func twoIntInputs( - _ a: Tensor, - _ b: Tensor + _ a: Tensor, + _ b: Tensor ) { let nOutputs = 0 - let op = makeOp("TwoIntInputs", nOutputs) - op.addInput(a) - op.addInput(b) - op.execute() + let op = makeOp("TwoIntInputs", nOutputs) + op.addInput(a) + op.addInput(b) + op.execute() } @inlinable @inline(__always) public static func twoIntOutputs( ) -> (a: Tensor, b: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("TwoIntOutputs", nOutputs) - - return op.execute(Int(1), Int(1)) + let op = makeOp("TwoIntOutputs", nOutputs) + + return op.execute(Int(1), Int(1)) } @inlinable @inline(__always) public static func typeList( - _ a: T + _ a: T ) { let nOutputs = 0 - let op = makeOp("TypeList", nOutputs) - op.updateAttribute("T", a._typeList) - op.addInputList(a) - op.execute() + let op = makeOp("TypeList", nOutputs) + op.updateAttribute("T", a._typeList) + op.addInputList(a) + op.execute() } @inlinable @inline(__always) public static func typeListRestrict( - _ a: T + _ a: T ) { let nOutputs = 0 - let op = makeOp("TypeListRestrict", nOutputs) - op.updateAttribute("T", a._typeList) - op.addInputList(a) - op.execute() + let op = makeOp("TypeListRestrict", nOutputs) + op.updateAttribute("T", a._typeList) + op.addInputList(a) + op.execute() } @inlinable @inline(__always) public static func typeListTwice( - _ a: T, - _ b: T + _ a: T, + _ b: T ) { let nOutputs = 0 - let op = makeOp("TypeListTwice", nOutputs) - op.updateAttribute("T", a._typeList) - op.addInputList(a) - op.addInputList(b) - op.execute() + let op = makeOp("TypeListTwice", nOutputs) + op.updateAttribute("T", a._typeList) + op.addInputList(a) + op.addInputList(b) + op.execute() } @inlinable @inline(__always) public static func unary( - _ a: Tensor + _ a: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Unary", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - return op.execute(Int(1)) + let op = makeOp("Unary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(a) + return op.execute(Int(1)) } /// Reverses the operation of Batch for a single output Tensor. @@ -35500,23 +35269,23 @@ public static func unary( /// be used as the shared name. @inlinable @inline(__always) public static func unbatch( - batchedTensor: Tensor, - batchIndex: Tensor, - id: Tensor, - timeoutMicros: Int64, - container: String, - sharedName: String + batchedTensor: Tensor, + batchIndex: Tensor, + id: Tensor, + timeoutMicros: Int64, + container: String, + sharedName: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Unbatch", nOutputs) - op.updateAttribute("timeout_micros", timeoutMicros) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(batchedTensor) - op.addInput(batchIndex) - op.addInput(id) - return op.execute(Int(1)) + let op = makeOp("Unbatch", nOutputs) + op.updateAttribute("timeout_micros", timeoutMicros) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(batchedTensor) + op.addInput(batchIndex) + op.addInput(id) + return op.execute(Int(1)) } /// Gradient of Unbatch. @@ -35537,23 +35306,23 @@ public static func unbatch( /// will be used as the shared name. @inlinable @inline(__always) public static func unbatchGrad( - originalInput: Tensor, - batchIndex: Tensor, - grad: Tensor, - id: Tensor, - container: String, - sharedName: String + originalInput: Tensor, + batchIndex: Tensor, + grad: Tensor, + id: Tensor, + container: String, + sharedName: String ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("UnbatchGrad", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(originalInput) - op.addInput(batchIndex) - op.addInput(grad) - op.addInput(id) - return op.execute(Int(1)) + let op = makeOp("UnbatchGrad", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(originalInput) + op.addInput(batchIndex) + op.addInput(grad) + op.addInput(id) + return op.execute(Int(1)) } /// Decodes each string in `input` into a sequence of Unicode code points. @@ -35573,45 +35342,44 @@ public static func unbatchGrad( /// string (in row-major order). /// /// - Parameter input: The text to be decoded. Can have any shape. Note that the output is flattened -/// to a vector of char values. +/// to a vector of char values. /// /// - Attrs: -/// - input_encoding: Text encoding of the input strings. This is any of the encodings supported -/// by ICU ucnv algorithmic converters. Examples: `"UTF-16", "US ASCII", "UTF-8"`. -/// - errors: Error handling policy when there is invalid formatting found in the input. -/// The value of 'strict' will cause the operation to produce a InvalidArgument -/// error on any invalid input formatting. A value of 'replace' (the default) will -/// cause the operation to replace any invalid formatting in the input with the -/// `replacement_char` codepoint. A value of 'ignore' will cause the operation to -/// skip any invalid formatting in the input and produce no corresponding output -/// character. -/// - replacement_char: The replacement character codepoint to be used in place of any invalid -/// formatting in the input when `errors='replace'`. Any valid unicode codepoint may -/// be used. The default value is the default unicode replacement character is -/// 0xFFFD or U+65533.) -/// - replace_control_characters: Whether to replace the C0 control characters (00-1F) with the -/// `replacement_char`. Default is false. +/// - input_encoding: Text encoding of the input strings. This is any of the encodings supported +/// by ICU ucnv algorithmic converters. Examples: `"UTF-16", "US ASCII", "UTF-8"`. +/// - errors: Error handling policy when there is invalid formatting found in the input. +/// The value of 'strict' will cause the operation to produce a InvalidArgument +/// error on any invalid input formatting. A value of 'replace' (the default) will +/// cause the operation to replace any invalid formatting in the input with the +/// `replacement_char` codepoint. A value of 'ignore' will cause the operation to +/// skip any invalid formatting in the input and produce no corresponding output +/// character. +/// - replacement_char: The replacement character codepoint to be used in place of any invalid +/// formatting in the input when `errors='replace'`. Any valid unicode codepoint may +/// be used. The default value is the default unicode replacement character is +/// 0xFFFD or U+65533.) +/// - replace_control_characters: Whether to replace the C0 control characters (00-1F) with the +/// `replacement_char`. Default is false. /// /// - Outputs: -/// - row_splits: A 1D int32 tensor containing the row splits. -/// - char_values: A 1D int32 Tensor containing the decoded codepoints. -@inlinable @inline(__always) -public static func unicodeDecode( - _ input: StringTensor, - inputEncoding: String, - errors: Errors = .replace, - replacementChar: Int64 = 65533, - replaceControlCharacters: Bool = false -) -> (rowSplits: Tensor, charValues: Tensor) { +/// - row_splits: A 1D int32 tensor containing the row splits. +/// - char_values: A 1D int32 Tensor containing the decoded codepoints. +@inlinable @inline(__always) +public static func unicodeDecode( + _ input: StringTensor, + inputEncoding: String, + errors: Errors = .replace, + replacementChar: Int64 = 65533, + replaceControlCharacters: Bool = false +) -> (rowSplits: Tensor, charValues: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("UnicodeDecode", nOutputs) - op.updateAttribute("input_encoding", inputEncoding) - op.updateAttribute("errors", errors.cName) - op.updateAttribute("replacement_char", replacementChar) - op.updateAttribute("replace_control_characters", replaceControlCharacters) - op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1), Int(1)) + let op = makeOp("UnicodeDecode", nOutputs) + op.updateAttribute("input_encoding", inputEncoding) + op.updateAttribute("errors", errors.cName) + op.updateAttribute("replacement_char", replacementChar) + op.updateAttribute("replace_control_characters", replaceControlCharacters) + op.addInput(input) + return op.execute(Int(1), Int(1)) } /// Decodes each string in `input` into a sequence of Unicode code points. @@ -35635,47 +35403,46 @@ public static func unicodeDecode( /// string (in row-major order). /// /// - Parameter input: The text to be decoded. Can have any shape. Note that the output is flattened -/// to a vector of char values. +/// to a vector of char values. /// /// - Attrs: -/// - input_encoding: Text encoding of the input strings. This is any of the encodings supported -/// by ICU ucnv algorithmic converters. Examples: `"UTF-16", "US ASCII", "UTF-8"`. -/// - errors: Error handling policy when there is invalid formatting found in the input. -/// The value of 'strict' will cause the operation to produce a InvalidArgument -/// error on any invalid input formatting. A value of 'replace' (the default) will -/// cause the operation to replace any invalid formatting in the input with the -/// `replacement_char` codepoint. A value of 'ignore' will cause the operation to -/// skip any invalid formatting in the input and produce no corresponding output -/// character. -/// - replacement_char: The replacement character codepoint to be used in place of any invalid -/// formatting in the input when `errors='replace'`. Any valid unicode codepoint may -/// be used. The default value is the default unicode replacement character is -/// 0xFFFD or U+65533.) -/// - replace_control_characters: Whether to replace the C0 control characters (00-1F) with the -/// `replacement_char`. Default is false. +/// - input_encoding: Text encoding of the input strings. This is any of the encodings supported +/// by ICU ucnv algorithmic converters. Examples: `"UTF-16", "US ASCII", "UTF-8"`. +/// - errors: Error handling policy when there is invalid formatting found in the input. +/// The value of 'strict' will cause the operation to produce a InvalidArgument +/// error on any invalid input formatting. A value of 'replace' (the default) will +/// cause the operation to replace any invalid formatting in the input with the +/// `replacement_char` codepoint. A value of 'ignore' will cause the operation to +/// skip any invalid formatting in the input and produce no corresponding output +/// character. +/// - replacement_char: The replacement character codepoint to be used in place of any invalid +/// formatting in the input when `errors='replace'`. Any valid unicode codepoint may +/// be used. The default value is the default unicode replacement character is +/// 0xFFFD or U+65533.) +/// - replace_control_characters: Whether to replace the C0 control characters (00-1F) with the +/// `replacement_char`. Default is false. /// /// - Outputs: -/// - row_splits: A 1D int32 tensor containing the row splits. -/// - char_values: A 1D int32 Tensor containing the decoded codepoints. -/// - char_to_byte_starts: A 1D int32 Tensor containing the byte index in the input string where each -/// character in `char_values` starts. -@inlinable @inline(__always) -public static func unicodeDecodeWithOffsets( - _ input: StringTensor, - inputEncoding: String, - errors: Errors = .replace, - replacementChar: Int64 = 65533, - replaceControlCharacters: Bool = false -) -> (rowSplits: Tensor, charValues: Tensor, charToByteStarts: Tensor) { +/// - row_splits: A 1D int32 tensor containing the row splits. +/// - char_values: A 1D int32 Tensor containing the decoded codepoints. +/// - char_to_byte_starts: A 1D int32 Tensor containing the byte index in the input string where each +/// character in `char_values` starts. +@inlinable @inline(__always) +public static func unicodeDecodeWithOffsets( + _ input: StringTensor, + inputEncoding: String, + errors: Errors = .replace, + replacementChar: Int64 = 65533, + replaceControlCharacters: Bool = false +) -> (rowSplits: Tensor, charValues: Tensor, charToByteStarts: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("UnicodeDecodeWithOffsets", nOutputs) - op.updateAttribute("input_encoding", inputEncoding) - op.updateAttribute("errors", errors.cName) - op.updateAttribute("replacement_char", replacementChar) - op.updateAttribute("replace_control_characters", replaceControlCharacters) - op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("UnicodeDecodeWithOffsets", nOutputs) + op.updateAttribute("input_encoding", inputEncoding) + op.updateAttribute("errors", errors.cName) + op.updateAttribute("replacement_char", replacementChar) + op.updateAttribute("replace_control_characters", replaceControlCharacters) + op.addInput(input) + return op.execute(Int(1), Int(1), Int(1)) } /// Encode a tensor of ints into unicode strings. @@ -35697,44 +35464,43 @@ public static func unicodeDecodeWithOffsets( - inputValues: Tensor, - inputSplits: Tensor, - errors: Errors = .replace, - outputEncoding: OutputEncoding, - replacementChar: Int64 = 65533 +public static func unicodeEncode( + inputValues: Tensor, + inputSplits: Tensor, + errors: Errors = .replace, + outputEncoding: OutputEncoding, + replacementChar: Int64 = 65533 ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("UnicodeEncode", nOutputs) - op.updateAttribute("errors", errors.cName) - op.updateAttribute("output_encoding", outputEncoding.cName) - op.updateAttribute("replacement_char", replacementChar) - op.updateAttribute("Tsplits", Tsplits.tensorFlowDataType) - op.addInput(inputValues) - op.addInput(inputSplits) - return op.execute(Int(1)) + let op = makeOp("UnicodeEncode", nOutputs) + op.updateAttribute("errors", errors.cName) + op.updateAttribute("output_encoding", outputEncoding.cName) + op.updateAttribute("replacement_char", replacementChar) + op.addInput(inputValues) + op.addInput(inputSplits) + return op.execute(Int(1)) } /// Determine the script codes of a given tensor of Unicode integer code points. @@ -35750,12 +35516,12 @@ public static func unicodeEncode( /// - Output output: A Tensor of int32 script codes corresponding to each input code point. @inlinable @inline(__always) public static func unicodeScript( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("UnicodeScript", nOutputs) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("UnicodeScript", nOutputs) + op.addInput(input) + return op.execute(Int(1)) } /// Transcode the input text from a source encoding to a destination encoding. @@ -35788,48 +35554,48 @@ public static func unicodeScript( /// - Parameter input: The text to be processed. Can have any shape. /// /// - Attrs: -/// - input_encoding: Text encoding of the input strings. This is any of the encodings supported -/// by ICU ucnv algorithmic converters. Examples: `"UTF-16", "US ASCII", "UTF-8"`. -/// - output_encoding: The unicode encoding to use in the output. Must be one of -/// `"UTF-8", "UTF-16-BE", "UTF-32-BE"`. Multi-byte encodings will be big-endian. -/// - errors: Error handling policy when there is invalid formatting found in the input. -/// The value of 'strict' will cause the operation to produce a InvalidArgument -/// error on any invalid input formatting. A value of 'replace' (the default) will -/// cause the operation to replace any invalid formatting in the input with the -/// `replacement_char` codepoint. A value of 'ignore' will cause the operation to -/// skip any invalid formatting in the input and produce no corresponding output -/// character. -/// - replacement_char: The replacement character codepoint to be used in place of any invalid -/// formatting in the input when `errors='replace'`. Any valid unicode codepoint may -/// be used. The default value is the default unicode replacement character is -/// 0xFFFD or U+65533.) -/// -/// Note that for UTF-8, passing a replacement character expressible in 1 byte, such -/// as ' ', will preserve string alignment to the source since invalid bytes will be -/// replaced with a 1-byte replacement. For UTF-16-BE and UTF-16-LE, any 1 or 2 byte -/// replacement character will preserve byte alignment to the source. -/// - replace_control_characters: Whether to replace the C0 control characters (00-1F) with the -/// `replacement_char`. Default is false. +/// - input_encoding: Text encoding of the input strings. This is any of the encodings supported +/// by ICU ucnv algorithmic converters. Examples: `"UTF-16", "US ASCII", "UTF-8"`. +/// - output_encoding: The unicode encoding to use in the output. Must be one of +/// `"UTF-8", "UTF-16-BE", "UTF-32-BE"`. Multi-byte encodings will be big-endian. +/// - errors: Error handling policy when there is invalid formatting found in the input. +/// The value of 'strict' will cause the operation to produce a InvalidArgument +/// error on any invalid input formatting. A value of 'replace' (the default) will +/// cause the operation to replace any invalid formatting in the input with the +/// `replacement_char` codepoint. A value of 'ignore' will cause the operation to +/// skip any invalid formatting in the input and produce no corresponding output +/// character. +/// - replacement_char: The replacement character codepoint to be used in place of any invalid +/// formatting in the input when `errors='replace'`. Any valid unicode codepoint may +/// be used. The default value is the default unicode replacement character is +/// 0xFFFD or U+65533.) +/// +/// Note that for UTF-8, passing a replacement character expressible in 1 byte, such +/// as ' ', will preserve string alignment to the source since invalid bytes will be +/// replaced with a 1-byte replacement. For UTF-16-BE and UTF-16-LE, any 1 or 2 byte +/// replacement character will preserve byte alignment to the source. +/// - replace_control_characters: Whether to replace the C0 control characters (00-1F) with the +/// `replacement_char`. Default is false. /// /// - Output output: A string tensor containing unicode text encoded using `output_encoding`. @inlinable @inline(__always) public static func unicodeTranscode( - _ input: StringTensor, - inputEncoding: String, - outputEncoding: OutputEncoding, - errors: Errors = .replace, - replacementChar: Int64 = 65533, - replaceControlCharacters: Bool = false + _ input: StringTensor, + inputEncoding: String, + outputEncoding: OutputEncoding, + errors: Errors = .replace, + replacementChar: Int64 = 65533, + replaceControlCharacters: Bool = false ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("UnicodeTranscode", nOutputs) - op.updateAttribute("input_encoding", inputEncoding) - op.updateAttribute("output_encoding", outputEncoding.cName) - op.updateAttribute("errors", errors.cName) - op.updateAttribute("replacement_char", replacementChar) - op.updateAttribute("replace_control_characters", replaceControlCharacters) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("UnicodeTranscode", nOutputs) + op.updateAttribute("input_encoding", inputEncoding) + op.updateAttribute("output_encoding", outputEncoding.cName) + op.updateAttribute("errors", errors.cName) + op.updateAttribute("replacement_char", replacementChar) + op.updateAttribute("replace_control_characters", replaceControlCharacters) + op.addInput(input) + return op.execute(Int(1)) } /// Generates labels for candidate sampling with a uniform distribution. @@ -35845,50 +35611,50 @@ public static func unicodeTranscode( /// true labels. /// /// - Parameter true_classes: A batch_size * num_true matrix, in which each row contains the -/// IDs of the num_true target_classes in the corresponding original label. +/// IDs of the num_true target_classes in the corresponding original label. /// /// - Attrs: -/// - num_true: Number of true labels per context. -/// - num_sampled: Number of candidates to randomly sample. -/// - unique: If unique is true, we sample with rejection, so that all sampled -/// candidates in a batch are unique. This requires some approximation to -/// estimate the post-rejection sampling probabilities. -/// - range_max: The sampler will sample integers from the interval [0, range_max). -/// - seed: If either seed or seed2 are set to be non-zero, the random number -/// generator is seeded by the given seed. Otherwise, it is seeded by a -/// random seed. -/// - seed2: An second seed to avoid seed collision. +/// - num_true: Number of true labels per context. +/// - num_sampled: Number of candidates to randomly sample. +/// - unique: If unique is true, we sample with rejection, so that all sampled +/// candidates in a batch are unique. This requires some approximation to +/// estimate the post-rejection sampling probabilities. +/// - range_max: The sampler will sample integers from the interval [0, range_max). +/// - seed: If either seed or seed2 are set to be non-zero, the random number +/// generator is seeded by the given seed. Otherwise, it is seeded by a +/// random seed. +/// - seed2: An second seed to avoid seed collision. /// /// - Outputs: -/// - sampled_candidates: A vector of length num_sampled, in which each element is -/// the ID of a sampled candidate. -/// - true_expected_count: A batch_size * num_true matrix, representing -/// the number of times each candidate is expected to occur in a batch -/// of sampled candidates. If unique=true, then this is a probability. -/// - sampled_expected_count: A vector of length num_sampled, for each sampled -/// candidate representing the number of times the candidate is expected -/// to occur in a batch of sampled candidates. If unique=true, then this is a -/// probability. +/// - sampled_candidates: A vector of length num_sampled, in which each element is +/// the ID of a sampled candidate. +/// - true_expected_count: A batch_size * num_true matrix, representing +/// the number of times each candidate is expected to occur in a batch +/// of sampled candidates. If unique=true, then this is a probability. +/// - sampled_expected_count: A vector of length num_sampled, for each sampled +/// candidate representing the number of times the candidate is expected +/// to occur in a batch of sampled candidates. If unique=true, then this is a +/// probability. @inlinable @inline(__always) public static func uniformCandidateSampler( - trueClasses: Tensor, - numTrue: Int64, - numSampled: Int64, - unique: Bool, - rangeMax: Int64, - seed: Int64 = 0, - seed2: Int64 = 0 + trueClasses: Tensor, + numTrue: Int64, + numSampled: Int64, + unique: Bool, + rangeMax: Int64, + seed: Int64 = 0, + seed2: Int64 = 0 ) -> (sampledCandidates: Tensor, trueExpectedCount: Tensor, sampledExpectedCount: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("UniformCandidateSampler", nOutputs) - op.updateAttribute("num_true", numTrue) - op.updateAttribute("num_sampled", numSampled) - op.updateAttribute("unique", unique) - op.updateAttribute("range_max", rangeMax) - op.updateAttribute("seed", seed) - op.updateAttribute("seed2", seed2) - op.addInput(trueClasses) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("UniformCandidateSampler", nOutputs) + op.updateAttribute("num_true", numTrue) + op.updateAttribute("num_sampled", numSampled) + op.updateAttribute("unique", unique) + op.updateAttribute("range_max", rangeMax) + op.updateAttribute("seed", seed) + op.updateAttribute("seed2", seed2) + op.addInput(trueClasses) + return op.execute(Int(1), Int(1), Int(1)) } /// Finds unique elements in a 1-D tensor. @@ -35912,21 +35678,21 @@ public static func uniformCandidateSampler( /// - Parameter x: 1-D. /// /// - Outputs: -/// - y: 1-D. -/// - idx: 1-D. +/// - y: 1-D. +/// - idx: 1-D. @inlinable @inline(__always) public static func unique< T: TensorFlowScalar, OutIdx: BinaryInteger & TensorFlowScalar >( - _ x: Tensor + _ x: Tensor ) -> (y: Tensor, idx: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("Unique", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1), Int(1)) + let op = makeOp("Unique", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1), Int(1)) } /// Finds unique elements along an axis of a tensor. @@ -35976,31 +35742,31 @@ public static func unique< /// ``` /// /// - Parameters: -/// - x: A `Tensor`. -/// - axis: A `Tensor` of type `int32` (default: None). The axis of the Tensor to -/// find the unique elements. +/// - x: A `Tensor`. +/// - axis: A `Tensor` of type `int32` (default: None). The axis of the Tensor to +/// find the unique elements. /// /// - Outputs: -/// - y: A `Tensor`. Unique elements along the `axis` of `Tensor` x. -/// - idx: A 1-D Tensor. Has the same type as x that contains the index of each -/// value of x in the output y. +/// - y: A `Tensor`. Unique elements along the `axis` of `Tensor` x. +/// - idx: A 1-D Tensor. Has the same type as x that contains the index of each +/// value of x in the output y. @inlinable @inline(__always) public static func uniqueV2< T: TensorFlowScalar, Taxis: BinaryInteger & TensorFlowScalar, OutIdx: BinaryInteger & TensorFlowScalar >( - _ x: Tensor, - axis: Tensor + _ x: Tensor, + axis: Tensor ) -> (y: Tensor, idx: Tensor) { let nOutputs = Int(1) + Int(1) - let op = makeOp("UniqueV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Taxis", Taxis.tensorFlowDataType) - op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) - op.addInput(x) - op.addInput(axis) - return op.execute(Int(1), Int(1)) + let op = makeOp("UniqueV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Taxis", Taxis.tensorFlowDataType) + op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) + op.addInput(x) + op.addInput(axis) + return op.execute(Int(1), Int(1)) } /// Finds unique elements in a 1-D tensor. @@ -36026,22 +35792,22 @@ public static func uniqueV2< /// - Parameter x: 1-D. /// /// - Outputs: -/// - y: 1-D. -/// - idx: 1-D. -/// - count: 1-D. +/// - y: 1-D. +/// - idx: 1-D. +/// - count: 1-D. @inlinable @inline(__always) public static func uniqueWithCounts< T: TensorFlowScalar, OutIdx: BinaryInteger & TensorFlowScalar >( - _ x: Tensor + _ x: Tensor ) -> (y: Tensor, idx: Tensor, count: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("UniqueWithCounts", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("UniqueWithCounts", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1), Int(1), Int(1)) } /// Finds unique elements along an axis of a tensor. @@ -36095,32 +35861,32 @@ public static func uniqueWithCounts< /// ``` /// /// - Parameters: -/// - x: A `Tensor`. -/// - axis: A `Tensor` of type `int32` (default: None). The axis of the Tensor to -/// find the unique elements. +/// - x: A `Tensor`. +/// - axis: A `Tensor` of type `int32` (default: None). The axis of the Tensor to +/// find the unique elements. /// /// - Outputs: -/// - y: A `Tensor`. Unique elements along the `axis` of `Tensor` x. -/// - idx: A 1-D Tensor. Has the same type as x that contains the index of each -/// value of x in the output y. -/// - count: A 1-D Tensor. The count of each value of x in the output y. +/// - y: A `Tensor`. Unique elements along the `axis` of `Tensor` x. +/// - idx: A 1-D Tensor. Has the same type as x that contains the index of each +/// value of x in the output y. +/// - count: A 1-D Tensor. The count of each value of x in the output y. @inlinable @inline(__always) public static func uniqueWithCountsV2< T: TensorFlowScalar, Taxis: BinaryInteger & TensorFlowScalar, OutIdx: BinaryInteger & TensorFlowScalar >( - _ x: Tensor, - axis: Tensor + _ x: Tensor, + axis: Tensor ) -> (y: Tensor, idx: Tensor, count: Tensor) { let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("UniqueWithCountsV2", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Taxis", Taxis.tensorFlowDataType) - op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) - op.addInput(x) - op.addInput(axis) - return op.execute(Int(1), Int(1), Int(1)) + let op = makeOp("UniqueWithCountsV2", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Taxis", Taxis.tensorFlowDataType) + op.updateAttribute("out_idx", OutIdx.tensorFlowDataType) + op.addInput(x) + op.addInput(axis) + return op.execute(Int(1), Int(1), Int(1)) } /// Unpacks a given dimension of a rank-`R` tensor into `num` rank-`(R-1)` tensors. @@ -36141,22 +35907,22 @@ public static func uniqueWithCountsV2< /// - Parameter value: 1-D or higher, with `axis` dimension size equal to `num`. /// /// - Attr axis: Dimension along which to unpack. Negative values wrap around, so the -/// valid range is `[-R, R)`. +/// valid range is `[-R, R)`. /// /// - Output output: The list of tensors unpacked from `value`. @inlinable @inline(__always) public static func unpack( - value: Tensor, - num: Int64, - axis: Int64 = 0 + value: Tensor, + num: Int64, + axis: Int64 = 0 ) -> [Tensor] { let nOutputs = Int(num) - let op = makeOp("Unpack", nOutputs) - op.updateAttribute("num", num) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("axis", axis) - op.addInput(value) - return op.execute(Int(num)) + let op = makeOp("Unpack", nOutputs) + op.updateAttribute("num", num) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("axis", axis) + op.addInput(value) + return op.execute(Int(num)) } /// Converts a flat index or array of flat indices into a tuple of @@ -36168,24 +35934,24 @@ public static func unpack( /// @end_compatibility /// /// - Parameters: -/// - indices: An 0-D or 1-D `int` Tensor whose elements are indices into the -/// flattened version of an array of dimensions dims. -/// - dims: An 1-D `int` Tensor. The shape of the array to use for unraveling -/// indices. +/// - indices: An 0-D or 1-D `int` Tensor whose elements are indices into the +/// flattened version of an array of dimensions dims. +/// - dims: An 1-D `int` Tensor. The shape of the array to use for unraveling +/// indices. /// /// - Output output: An 2-D (or 1-D if indices is 0-D) tensor where each row has the -/// same shape as the indices array. +/// same shape as the indices array. @inlinable @inline(__always) public static func unravelIndex( - indices: Tensor, - dims: Tensor + indices: Tensor, + dims: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("UnravelIndex", nOutputs) - op.updateAttribute("Tidx", Tidx.tensorFlowDataType) - op.addInput(indices) - op.addInput(dims) - return op.execute(Int(1)) + let op = makeOp("UnravelIndex", nOutputs) + op.updateAttribute("Tidx", Tidx.tensorFlowDataType) + op.addInput(indices) + op.addInput(dims) + return op.execute(Int(1)) } /// Computes the maximum along segments of a tensor. @@ -36225,27 +35991,27 @@ public static func unravelIndex( /// - Parameter segment_ids: A tensor whose shape is a prefix of `data.shape`. /// /// - Output output: Has same shape as data, except for the first `segment_ids.rank` -/// dimensions, which are replaced with a single dimension which has size -/// `num_segments`. +/// dimensions, which are replaced with a single dimension which has size +/// `num_segments`. @inlinable @inline(__always) public static func unsortedSegmentMax< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar, Tnumsegments: BinaryInteger & TensorFlowScalar >( - data: Tensor, - segmentIds: Tensor, - numSegments: Tensor + data: Tensor, + segmentIds: Tensor, + numSegments: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("UnsortedSegmentMax", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) - op.addInput(data) - op.addInput(segmentIds) - op.addInput(numSegments) - return op.execute(Int(1)) + let op = makeOp("UnsortedSegmentMax", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) } /// Computes the minimum along segments of a tensor. @@ -36280,27 +36046,27 @@ public static func unsortedSegmentMax< /// - Parameter segment_ids: A tensor whose shape is a prefix of `data.shape`. /// /// - Output output: Has same shape as data, except for the first `segment_ids.rank` -/// dimensions, which are replaced with a single dimension which has size -/// `num_segments`. +/// dimensions, which are replaced with a single dimension which has size +/// `num_segments`. @inlinable @inline(__always) public static func unsortedSegmentMin< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar, Tnumsegments: BinaryInteger & TensorFlowScalar >( - data: Tensor, - segmentIds: Tensor, - numSegments: Tensor + data: Tensor, + segmentIds: Tensor, + numSegments: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("UnsortedSegmentMin", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) - op.addInput(data) - op.addInput(segmentIds) - op.addInput(numSegments) - return op.execute(Int(1)) + let op = makeOp("UnsortedSegmentMin", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) } /// Computes the product along segments of a tensor. @@ -36334,27 +36100,27 @@ public static func unsortedSegmentMin< /// - Parameter segment_ids: A tensor whose shape is a prefix of `data.shape`. /// /// - Output output: Has same shape as data, except for the first `segment_ids.rank` -/// dimensions, which are replaced with a single dimension which has size -/// `num_segments`. +/// dimensions, which are replaced with a single dimension which has size +/// `num_segments`. @inlinable @inline(__always) public static func unsortedSegmentProd< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar, Tnumsegments: BinaryInteger & TensorFlowScalar >( - data: Tensor, - segmentIds: Tensor, - numSegments: Tensor + data: Tensor, + segmentIds: Tensor, + numSegments: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("UnsortedSegmentProd", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) - op.addInput(data) - op.addInput(segmentIds) - op.addInput(numSegments) - return op.execute(Int(1)) + let op = makeOp("UnsortedSegmentProd", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) } /// Computes the sum along segments of a tensor. @@ -36390,27 +36156,27 @@ public static func unsortedSegmentProd< /// - Parameter segment_ids: A tensor whose shape is a prefix of `data.shape`. /// /// - Output output: Has same shape as data, except for the first `segment_ids.rank` -/// dimensions, which are replaced with a single dimension which has size -/// `num_segments`. +/// dimensions, which are replaced with a single dimension which has size +/// `num_segments`. @inlinable @inline(__always) public static func unsortedSegmentSum< T: Numeric & TensorFlowScalar, Tindices: BinaryInteger & TensorFlowScalar, Tnumsegments: BinaryInteger & TensorFlowScalar >( - data: Tensor, - segmentIds: Tensor, - numSegments: Tensor + data: Tensor, + segmentIds: Tensor, + numSegments: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("UnsortedSegmentSum", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) - op.addInput(data) - op.addInput(segmentIds) - op.addInput(numSegments) - return op.execute(Int(1)) + let op = makeOp("UnsortedSegmentSum", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("Tindices", Tindices.tensorFlowDataType) + op.updateAttribute("Tnumsegments", Tnumsegments.tensorFlowDataType) + op.addInput(data) + op.addInput(segmentIds) + op.addInput(numSegments) + return op.execute(Int(1)) } /// Op is similar to a lightweight Dequeue. @@ -36419,29 +36185,29 @@ public static func unsortedSegmentSum< /// capabilities and options. This Op is optimized for performance. @inlinable @inline(__always) public static func unstage( - capacity: Int64 = 0, - memoryLimit: Int64 = 0, - container: String, - sharedName: String + capacity: Int64 = 0, + memoryLimit: Int64 = 0, + container: String, + sharedName: String ) -> Dtypes { let nOutputs = Int(Dtypes._typeList.count) - let op = makeOp("Unstage", nOutputs) - op.updateAttribute("capacity", capacity) - op.updateAttribute("memory_limit", memoryLimit) - op.updateAttribute("dtypes", Dtypes._typeList) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(Dtypes._typeList.count)) + let op = makeOp("Unstage", nOutputs) + op.updateAttribute("capacity", capacity) + op.updateAttribute("memory_limit", memoryLimit) + op.updateAttribute("dtypes", Dtypes._typeList) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(Dtypes._typeList.count)) } @inlinable @inline(__always) public static func unwrapDatasetVariant( - inputHandle: VariantHandle + inputHandle: VariantHandle ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("UnwrapDatasetVariant", nOutputs) - op.addInput(inputHandle) - return op.execute(Int(1)) + let op = makeOp("UnwrapDatasetVariant", nOutputs) + op.addInput(inputHandle) + return op.execute(Int(1)) } /// Applies upper_bound(sorted_search_values, values) along each row. @@ -36465,52 +36231,52 @@ public static func unwrapDatasetVariant( /// [0, 2, 5]] /// /// - Parameters: -/// - sorted_inputs: 2-D Tensor where each row is ordered. -/// - values: 2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains -/// the values that will be searched for in `sorted_search_values`. +/// - sorted_inputs: 2-D Tensor where each row is ordered. +/// - values: 2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains +/// the values that will be searched for in `sorted_search_values`. /// /// - Output output: A `Tensor` with the same shape as `values`. It contains the last scalar index -/// into the last dimension where values can be inserted without changing the -/// ordered property. +/// into the last dimension where values can be inserted without changing the +/// ordered property. @inlinable @inline(__always) public static func upperBound< T: TensorFlowScalar, OutType: BinaryInteger & TensorFlowScalar >( - sortedInputs: Tensor, - _ values: Tensor + sortedInputs: Tensor, + _ values: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("UpperBound", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(sortedInputs) - op.addInput(values) - return op.execute(Int(1)) + let op = makeOp("UpperBound", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(sortedInputs) + op.addInput(values) + return op.execute(Int(1)) } /// Creates a handle to a Variable resource. /// /// - Attrs: -/// - container: the container this variable is placed in. -/// - shared_name: the name by which this variable is referred to. -/// - dtype: the type of this variable. Must agree with the dtypes -/// of all ops using this variable. -/// - shape: The (possibly partially specified) shape of this variable. +/// - container: the container this variable is placed in. +/// - shared_name: the name by which this variable is referred to. +/// - dtype: the type of this variable. Must agree with the dtypes +/// of all ops using this variable. +/// - shape: The (possibly partially specified) shape of this variable. @inlinable @inline(__always) public static func varHandleOp( - container: String, - sharedName: String, - dtype: TensorDataType, - shape: TensorShape? + container: String, + sharedName: String, + dtype: TensorDataType, + shape: TensorShape? ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("VarHandleOp", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - op.updateAttribute("dtype", dtype) - op.updateAttribute("shape", shape) - return op.execute(Int(1)) + let op = makeOp("VarHandleOp", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + op.updateAttribute("dtype", dtype) + op.updateAttribute("shape", shape) + return op.execute(Int(1)) } /// Checks whether a resource handle-based variable has been initialized. @@ -36518,15 +36284,15 @@ public static func varHandleOp( /// - Parameter resource: the input resource handle. /// /// - Output is_initialized: a scalar boolean which is true if the variable has been -/// initialized. +/// initialized. @inlinable @inline(__always) public static func varIsInitializedOp( - resource: ResourceHandle + resource: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("VarIsInitializedOp", nOutputs) - op.addInput(resource) - return op.execute(Int(1)) + let op = makeOp("VarIsInitializedOp", nOutputs) + op.addInput(resource) + return op.execute(Int(1)) } /// Returns the shape of the variable pointed to by `resource`. @@ -36541,13 +36307,13 @@ public static func varIsInitializedOp( /// ``` @inlinable @inline(__always) public static func variableShape( - _ input: ResourceHandle + _ input: ResourceHandle ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("VariableShape", nOutputs) - op.updateAttribute("out_type", OutType.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("VariableShape", nOutputs) + op.updateAttribute("out_type", OutType.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// Returns locations of nonzero / true values in a tensor. @@ -36613,13 +36379,13 @@ public static func variableShape( /// ``` @inlinable @inline(__always) public static func where_( - _ input: Tensor + _ input: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Where", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) + let op = makeOp("Where", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(input) + return op.execute(Int(1)) } /// output = input; While (Cond(output)) { output = Body(output) } @@ -36627,17 +36393,17 @@ public static func where_( /// - Parameter input: A list of input tensors whose types are T. /// /// - Attrs: -/// - T: dtype in use. -/// - cond: A function takes 'input' and returns a tensor. If the tensor is -/// a scalar of non-boolean, the scalar is converted to a boolean -/// according to the following rule: if the scalar is a numerical -/// value, non-zero means True and zero means False; if the scalar is -/// a string, non-empty means True and empty means False. If the -/// tensor is not a scalar, non-emptiness means True and False -/// otherwise. -/// - body: A function that takes a list of tensors and returns another -/// list of tensors. Both lists have the same types as specified -/// by T. +/// - T: dtype in use. +/// - cond: A function takes 'input' and returns a tensor. If the tensor is +/// a scalar of non-boolean, the scalar is converted to a boolean +/// according to the following rule: if the scalar is a numerical +/// value, non-zero means True and zero means False; if the scalar is +/// a string, non-empty means True and empty means False. If the +/// tensor is not a scalar, non-emptiness means True and False +/// otherwise. +/// - body: A function that takes a list of tensors and returns another +/// list of tensors. Both lists have the same types as specified +/// by T. /// /// - Output output: A list of output tensors whose types are T. @inlinable @inline(__always) @@ -36648,21 +36414,21 @@ public static func while_< BodyIn: TensorGroup, BodyOut: TensorGroup >( - _ input: T, - cond: (CondIn) -> CondOut, - body: (BodyIn) -> BodyOut, - outputShapes: [TensorShape?], - parallelIterations: Int64 = 10 + _ input: T, + cond: (CondIn) -> CondOut, + body: (BodyIn) -> BodyOut, + outputShapes: [TensorShape?], + parallelIterations: Int64 = 10 ) -> T { let nOutputs = Int(input._typeList.count) - let op = makeOp("While", nOutputs) - op.updateAttribute("T", input._typeList) - op.updateAttribute("cond", cond) - op.updateAttribute("body", body) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("parallel_iterations", parallelIterations) - op.addInputList(input) - return op.execute(Int(input._typeList.count)) + let op = makeOp("While", nOutputs) + op.updateAttribute("T", input._typeList) + op.updateAttribute("cond", cond) + op.updateAttribute("body", body) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("parallel_iterations", parallelIterations) + op.addInputList(input) + return op.execute(Int(input._typeList.count)) } /// A Reader that outputs the entire contents of a file as a value. @@ -36671,54 +36437,54 @@ public static func while_< /// be a filename (key) and the contents of that file (value). /// /// - Attrs: -/// - container: If non-empty, this reader is placed in the given container. -/// Otherwise, a default container is used. -/// - shared_name: If non-empty, this reader is named in the given bucket -/// with this shared_name. Otherwise, the node name is used instead. +/// - container: If non-empty, this reader is placed in the given container. +/// Otherwise, a default container is used. +/// - shared_name: If non-empty, this reader is named in the given bucket +/// with this shared_name. Otherwise, the node name is used instead. /// /// - Output reader_handle: The handle to reference the Reader. @inlinable @inline(__always) public static func wholeFileReaderV2( - container: String, - sharedName: String + container: String, + sharedName: String ) -> ResourceHandle { let nOutputs = Int(1) - let op = makeOp("WholeFileReaderV2", nOutputs) - op.updateAttribute("container", container) - op.updateAttribute("shared_name", sharedName) - return op.execute(Int(1)) + let op = makeOp("WholeFileReaderV2", nOutputs) + op.updateAttribute("container", container) + op.updateAttribute("shared_name", sharedName) + return op.execute(Int(1)) } /// A dataset that creates window datasets from the input dataset. /// /// - Parameters: -/// - size: A scalar representing the number of elements to accumulate in a window. -/// - shift: A scalar representing the steps moving the sliding window forward in one -/// iteration. It must be positive. -/// - stride: A scalar representing the stride of the input elements of the sliding window. -/// It must be positive. -/// - drop_remainder: A scalar representing whether a window should be dropped in case its size is -/// smaller than desired. +/// - size: A scalar representing the number of elements to accumulate in a window. +/// - shift: A scalar representing the steps moving the sliding window forward in one +/// iteration. It must be positive. +/// - stride: A scalar representing the stride of the input elements of the sliding window. +/// It must be positive. +/// - drop_remainder: A scalar representing whether a window should be dropped in case its size is +/// smaller than desired. @inlinable @inline(__always) public static func windowDataset( - inputDataset: VariantHandle, - size: Tensor, - shift: Tensor, - stride: Tensor, - dropRemainder: Tensor, - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDataset: VariantHandle, + size: Tensor, + shift: Tensor, + stride: Tensor, + dropRemainder: Tensor, + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("WindowDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.addInput(inputDataset) - op.addInput(size) - op.addInput(shift) - op.addInput(stride) - op.addInput(dropRemainder) - return op.execute(Int(1)) + let op = makeOp("WindowDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.addInput(inputDataset) + op.addInput(size) + op.addInput(shift) + op.addInput(stride) + op.addInput(dropRemainder) + return op.execute(Int(1)) } /// Worker heartbeat op. @@ -36731,42 +36497,42 @@ public static func windowDataset( /// - Output response: A string tensor containing a serialized WorkerHeartbeatResponse @inlinable @inline(__always) public static func workerHeartbeat( - request: StringTensor + request: StringTensor ) -> StringTensor { let nOutputs = Int(1) - let op = makeOp("WorkerHeartbeat", nOutputs) - op.addInput(request) - return op.execute(Int(1)) + let op = makeOp("WorkerHeartbeat", nOutputs) + op.addInput(request) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func wrapDatasetVariant( - inputHandle: VariantHandle + inputHandle: VariantHandle ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("WrapDatasetVariant", nOutputs) - op.addInput(inputHandle) - return op.execute(Int(1)) + let op = makeOp("WrapDatasetVariant", nOutputs) + op.addInput(inputHandle) + return op.execute(Int(1)) } @inlinable @inline(__always) public static func writeAudioSummary( - writer: ResourceHandle, - step: Tensor, - tag: StringTensor, - _ tensor: Tensor, - sampleRate: Tensor, - maxOutputs: Int64 = 3 + writer: ResourceHandle, + step: Tensor, + tag: StringTensor, + _ tensor: Tensor, + sampleRate: Tensor, + maxOutputs: Int64 = 3 ) { let nOutputs = 0 - let op = makeOp("WriteAudioSummary", nOutputs) - op.updateAttribute("max_outputs", maxOutputs) - op.addInput(writer) - op.addInput(step) - op.addInput(tag) - op.addInput(tensor) - op.addInput(sampleRate) - op.execute() + let op = makeOp("WriteAudioSummary", nOutputs) + op.updateAttribute("max_outputs", maxOutputs) + op.addInput(writer) + op.addInput(step) + op.addInput(tag) + op.addInput(tensor) + op.addInput(sampleRate) + op.execute() } /// Writes contents to the file at input filename. Creates file and recursively @@ -36774,816 +36540,148 @@ public static func writeAudioSummary( /// creates directory if not existing. /// /// - Parameters: -/// - filename: scalar. The name of the file to which we write the contents. -/// - contents: scalar. The content to be written to the output file. +/// - filename: scalar. The name of the file to which we write the contents. +/// - contents: scalar. The content to be written to the output file. @inlinable @inline(__always) public static func writeFile( - filename: StringTensor, - contents: StringTensor + filename: StringTensor, + contents: StringTensor ) { let nOutputs = 0 - let op = makeOp("WriteFile", nOutputs) - op.addInput(filename) - op.addInput(contents) - op.execute() + let op = makeOp("WriteFile", nOutputs) + op.addInput(filename) + op.addInput(contents) + op.execute() } @inlinable @inline(__always) public static func writeGraphSummary( - writer: ResourceHandle, - step: Tensor, - _ tensor: StringTensor + writer: ResourceHandle, + step: Tensor, + _ tensor: StringTensor ) { let nOutputs = 0 - let op = makeOp("WriteGraphSummary", nOutputs) - op.addInput(writer) - op.addInput(step) - op.addInput(tensor) - op.execute() + let op = makeOp("WriteGraphSummary", nOutputs) + op.addInput(writer) + op.addInput(step) + op.addInput(tensor) + op.execute() } @inlinable @inline(__always) public static func writeHistogramSummary( - writer: ResourceHandle, - step: Tensor, - tag: StringTensor, - _ values: Tensor + writer: ResourceHandle, + step: Tensor, + tag: StringTensor, + _ values: Tensor ) { let nOutputs = 0 - let op = makeOp("WriteHistogramSummary", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(writer) - op.addInput(step) - op.addInput(tag) - op.addInput(values) - op.execute() + let op = makeOp("WriteHistogramSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(writer) + op.addInput(step) + op.addInput(tag) + op.addInput(values) + op.execute() } @inlinable @inline(__always) public static func writeImageSummary( - writer: ResourceHandle, - step: Tensor, - tag: StringTensor, - _ tensor: Tensor, - badColor: Tensor, - maxImages: Int64 = 3 + writer: ResourceHandle, + step: Tensor, + tag: StringTensor, + _ tensor: Tensor, + badColor: Tensor, + maxImages: Int64 = 3 ) { let nOutputs = 0 - let op = makeOp("WriteImageSummary", nOutputs) - op.updateAttribute("max_images", maxImages) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(writer) - op.addInput(step) - op.addInput(tag) - op.addInput(tensor) - op.addInput(badColor) - op.execute() + let op = makeOp("WriteImageSummary", nOutputs) + op.updateAttribute("max_images", maxImages) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(writer) + op.addInput(step) + op.addInput(tag) + op.addInput(tensor) + op.addInput(badColor) + op.execute() } @inlinable @inline(__always) public static func writeRawProtoSummary( - writer: ResourceHandle, - step: Tensor, - _ tensor: StringTensor + writer: ResourceHandle, + step: Tensor, + _ tensor: StringTensor ) { let nOutputs = 0 - let op = makeOp("WriteRawProtoSummary", nOutputs) - op.addInput(writer) - op.addInput(step) - op.addInput(tensor) - op.execute() + let op = makeOp("WriteRawProtoSummary", nOutputs) + op.addInput(writer) + op.addInput(step) + op.addInput(tensor) + op.execute() } @inlinable @inline(__always) public static func writeScalarSummary( - writer: ResourceHandle, - step: Tensor, - tag: StringTensor, - value: Tensor + writer: ResourceHandle, + step: Tensor, + tag: StringTensor, + value: Tensor ) { let nOutputs = 0 - let op = makeOp("WriteScalarSummary", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(writer) - op.addInput(step) - op.addInput(tag) - op.addInput(value) - op.execute() + let op = makeOp("WriteScalarSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(writer) + op.addInput(step) + op.addInput(tag) + op.addInput(value) + op.execute() } @inlinable @inline(__always) public static func writeSummary( - writer: ResourceHandle, - step: Tensor, - _ tensor: Tensor, - tag: StringTensor, - summaryMetadata: StringTensor + writer: ResourceHandle, + step: Tensor, + _ tensor: Tensor, + tag: StringTensor, + summaryMetadata: StringTensor ) { let nOutputs = 0 - let op = makeOp("WriteSummary", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(writer) - op.addInput(step) - op.addInput(tensor) - op.addInput(tag) - op.addInput(summaryMetadata) - op.execute() + let op = makeOp("WriteSummary", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(writer) + op.addInput(step) + op.addInput(tensor) + op.addInput(tag) + op.addInput(summaryMetadata) + op.execute() } /// Returns 0 if x == 0, and x / y otherwise, elementwise. @inlinable @inline(__always) public static func xdivy( - _ x: Tensor, - _ y: Tensor -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("Xdivy", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) -} - -/// Helper operator for performing XLA-style broadcasts -/// -/// Broadcasts `lhs` and `rhs` to the same rank, by adding size 1 dimensions to -/// whichever of `lhs` and `rhs` has the lower rank, using XLA's broadcasting rules -/// for binary operators. -/// -/// - Parameters: -/// - lhs: the LHS input tensor -/// - rhs: the RHS input tensor -/// - broadcast_dims: an XLA-style broadcast dimension specification -/// -/// - Outputs: -/// - lhs_output: the broadcasted LHS tensor -/// - rhs_output: the broadcasted RHS tensor -@inlinable @inline(__always) -public static func xlaBroadcastHelper< - T: Numeric & TensorFlowScalar, - Tindices: BinaryInteger & TensorFlowScalar ->( - lhs: Tensor, - rhs: Tensor, - broadcastDims: Tensor -) -> (lhsOutput: Tensor, rhsOutput: Tensor) { - let nOutputs = Int(1) + Int(1) - let op = makeOp("XlaBroadcastHelper", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(lhs) - op.addInput(rhs) - op.addInput(broadcastDims) - return op.execute(Int(1), Int(1)) -} - -/// Operator that connects the output of an XLA computation to other consumer graph nodes. -@inlinable @inline(__always) -public static func xlaClusterOutput( - _ input: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("XlaClusterOutput", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) -} - -/// Wraps the XLA ConvGeneralDilated operator, documented at -/// -/// https://www.tensorflow.org/performance/xla/operation_semantics#conv_convolution -/// . -/// -/// - Parameters: -/// - lhs: the input tensor -/// - rhs: the kernel tensor -/// - window_strides: the inter-window strides -/// - padding: the padding to apply at the start and end of each input dimensions -/// - lhs_dilation: dilation to apply between input elements -/// - rhs_dilation: dilation to apply between kernel elements -/// - feature_group_count: number of feature groups for grouped convolution. -/// -/// - Attrs: -/// - dimension_numbers: a serialized xla::ConvolutionDimensionNumbers proto. -/// - precision_config: a serialized xla::PrecisionConfig proto. -@inlinable @inline(__always) -public static func xlaConv< - T: Numeric & TensorFlowScalar, - Tindices: BinaryInteger & TensorFlowScalar ->( - lhs: Tensor, - rhs: Tensor, - windowStrides: Tensor, - padding: Tensor, - lhsDilation: Tensor, - rhsDilation: Tensor, - featureGroupCount: Tensor, - dimensionNumbers: String, - precisionConfig: String -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("XlaConv", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("dimension_numbers", dimensionNumbers) - op.updateAttribute("precision_config", precisionConfig) - op.addInput(lhs) - op.addInput(rhs) - op.addInput(windowStrides) - op.addInput(padding) - op.addInput(lhsDilation) - op.addInput(rhsDilation) - op.addInput(featureGroupCount) - return op.execute(Int(1)) -} - -/// Wraps the XLA ConvGeneralDilated operator, documented at -/// -/// https://www.tensorflow.org/performance/xla/operation_semantics#dotgeneral -/// . -/// -/// - Parameters: -/// - lhs: the LHS tensor -/// - rhs: the RHS tensor -/// -/// - Attrs: -/// - dimension_numbers: a serialized xla::DotDimensionNumbers proto. -/// - precision_config: a serialized xla::PrecisionConfig proto. -@inlinable @inline(__always) -public static func xlaDot( - lhs: Tensor, - rhs: Tensor, - dimensionNumbers: String, - precisionConfig: String -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("XlaDot", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("dimension_numbers", dimensionNumbers) - op.updateAttribute("precision_config", precisionConfig) - op.addInput(lhs) - op.addInput(rhs) - return op.execute(Int(1)) -} - -/// Wraps the XLA DynamicSlice operator, documented at -/// -/// https://www.tensorflow.org/performance/xla/operation_semantics#dynamicslice -/// . -/// -/// DynamicSlice extracts a sub-array from the input array at dynamic -/// start_indices. The size of the slice in each dimension is passed in -/// size_indices, which specify the end point of exclusive slice intervals in each -/// dimension -- [start, start + size). The shape of start_indices must have rank 1, -/// with dimension size equal to the rank of operand. -/// -/// - Parameters: -/// - input: A `Tensor` of type T. -/// - start_indices: List of N integers containing the slice size for each -/// dimension. Each value must be strictly greater than zero, and start + size -/// must be less than or equal to the size of the dimension to avoid -/// implementation defined behavior. -@inlinable @inline(__always) -public static func xlaDynamicSlice< - T: TensorFlowScalar, - Tindices: BinaryInteger & TensorFlowScalar ->( - _ input: Tensor, - startIndices: Tensor, - sizeIndices: Tensor -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("XlaDynamicSlice", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(input) - op.addInput(startIndices) - op.addInput(sizeIndices) - return op.execute(Int(1)) -} - -/// Wraps the XLA DynamicUpdateSlice operator, documented at -/// -/// https://www.tensorflow.org/performance/xla/operation_semantics#dynamicupdateslice -/// . -/// -/// XlaDynamicUpdateSlice generates a result which is the value of the `input` -/// operand, with a slice update overwritten at `indices`. The shape of `update` -/// determines the shape of the sub-array of the result which is updated. The shape -/// of indices must be rank == 1, with dimension size equal to the rank of `input`. -/// -/// Handling of out-of-bounds slice indices is implementation-defined. -/// -/// - Parameters: -/// - input: A `Tensor` of type T. -/// - update: A `Tensor` of type T. Same rank as `input`. -/// - indices: A vector of indices into `input`. Must have length equal to the rank of -/// `input`. -/// -/// - Output output: A `Tensor` of type T. -@inlinable @inline(__always) -public static func xlaDynamicUpdateSlice< - T: TensorFlowScalar, - Tindices: BinaryInteger & TensorFlowScalar ->( - _ input: Tensor, - update: Tensor, - indices: Tensor -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("XlaDynamicUpdateSlice", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(input) - op.addInput(update) - op.addInput(indices) - return op.execute(Int(1)) -} - -/// An op which supports basic einsum op with 2 inputs and 1 output. -/// -/// This op has better TPU performnce since it doesn't have explicitly reshape and -/// transpose operations as tf.einsum does. -@inlinable @inline(__always) -public static func xlaEinsum( - _ a: Tensor, - _ b: Tensor, - equation: String -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("XlaEinsum", nOutputs) - op.updateAttribute("equation", equation) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - op.addInput(b) - return op.execute(Int(1)) -} - -/// output = cond ? then_branch(inputs) : else_branch(inputs). -/// -/// - Parameters: -/// - cond: A boolean scalar. -/// - inputs: A list of input tensors. -/// -/// - Attrs: -/// - then_branch: A function takes 'inputs' and returns a list of tensors, -/// whose types are the same as what else_branch returns. -/// - else_branch: A function takes 'inputs' and returns a list of tensors. -/// whose types are the same as what then_branch returns. -/// -/// - Output output: A list of tensors returned by either then_branch(inputs) or -/// else_branch(inputs). The input shapes of the then_branch and -/// else_branch must match. -@inlinable @inline(__always) -public static func xlaIf< - Tcond: TensorFlowScalar, - ThenbranchIn: TensorGroup, - ThenbranchOut: TensorGroup, - ElsebranchIn: TensorGroup, - ElsebranchOut: TensorGroup, - Tin: TensorArrayProtocol, - Tout: TensorGroup ->( - cond: Tensor, - inputs: Tin, - thenBranch: (ThenbranchIn) -> ThenbranchOut, - elseBranch: (ElsebranchIn) -> ElsebranchOut -) -> Tout { - let nOutputs = Int(Tout._typeList.count) - let op = makeOp("XlaIf", nOutputs) - op.updateAttribute("Tcond", Tcond.tensorFlowDataType) - op.updateAttribute("then_branch", thenBranch) - op.updateAttribute("else_branch", elseBranch) - op.updateAttribute("Tin", inputs._typeList) - op.updateAttribute("Tout", Tout._typeList) - op.addInput(cond) - op.addInputList(inputs) - return op.execute(Int(Tout._typeList.count)) -} - -/// Wraps the XLA Sort operator, documented at -/// -/// https://www.tensorflow.org/performance/xla/operation_semantics#sort -/// . -/// -/// Sorts a tensor. Currently only sorts in ascending order are supported. -/// -/// - Parameters: -/// - keys: A `Tensor` of type K. -/// - values: A `Tensor` of type V. -/// -/// - Outputs: -/// - sorted_keys: A `Tensor` of type K. -/// - sorted_values: A `Tensor` of type V. -@inlinable @inline(__always) -public static func xlaKeyValueSort< - K: Numeric & TensorFlowScalar, - V: TensorFlowScalar ->( - keys: Tensor, - _ values: Tensor -) -> (sortedKeys: Tensor, sortedValues: Tensor) { - let nOutputs = Int(1) + Int(1) - let op = makeOp("XlaKeyValueSort", nOutputs) - op.updateAttribute("K", K.tensorFlowDataType) - op.updateAttribute("V", V.tensorFlowDataType) - op.addInput(keys) - op.addInput(values) - return op.execute(Int(1), Int(1)) -} - -/// XLA Launch Op. For use by the XLA JIT only. -@inlinable @inline(__always) -public static func xlaLaunch< - Tconstants: TensorArrayProtocol, - Targs: TensorArrayProtocol, - Tresults: TensorGroup, - FunctionIn: TensorGroup, - FunctionOut: TensorGroup ->( - constants: Tconstants, - args: Targs, - resources: [ResourceHandle], - function: (FunctionIn) -> FunctionOut -) -> Tresults { - let nOutputs = Int(Tresults._typeList.count) - let op = makeOp("XlaLaunch", nOutputs) - op.updateAttribute("Tconstants", constants._typeList) - op.updateAttribute("Targs", args._typeList) - op.updateAttribute("Nresources", resources.count) - op.updateAttribute("Tresults", Tresults._typeList) - op.updateAttribute("function", function) - op.addInputList(constants) - op.addInputList(args) - op.addInputList(resources) - return op.execute(Int(Tresults._typeList.count)) -} - -/// Wraps the XLA Pad operator, documented at -/// -/// https://www.tensorflow.org/performance/xla/operation_semantics#pad -/// . -/// -/// - Parameters: -/// - input: A `Tensor` of type T. -/// - padding_value: A scalar `Tensor` of type T. -/// - padding_low: the padding to apply at the start of each input dimensions -/// - padding_high: the padding to apply at the end of each input dimension. -/// - padding_interior: the padding to apply between each input element. -/// -/// - Output output: A `Tensor` of type T. -@inlinable @inline(__always) -public static func xlaPad< - T: TensorFlowScalar, - Tindices: BinaryInteger & TensorFlowScalar ->( - _ input: Tensor, - paddingValue: Tensor, - paddingLow: Tensor, - paddingHigh: Tensor, - paddingInterior: Tensor -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("XlaPad", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.addInput(input) - op.addInput(paddingValue) - op.addInput(paddingLow) - op.addInput(paddingHigh) - op.addInput(paddingInterior) - return op.execute(Int(1)) -} - -/// Receives the named tensor from another XLA computation. Wraps the XLA Recv -/// -/// operator documented at -/// https://www.tensorflow.org/performance/xla/operation_semantics#recv . -/// -/// - Attrs: -/// - dtype: The type of the tensor. -/// - tensor_name: A string key that identifies the channel. -/// - shape: The shape of the tensor. -/// -/// - Output tensor: The tensor to receive. -@inlinable @inline(__always) -public static func xlaRecv( - tensorName: String, - shape: TensorShape? -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("XlaRecv", nOutputs) - op.updateAttribute("dtype", Dtype.tensorFlowDataType) - op.updateAttribute("tensor_name", tensorName) - op.updateAttribute("shape", shape) - return op.execute(Int(1)) -} - -/// Wraps the XLA Reduce operator, documented at -/// -/// https://www.tensorflow.org/performance/xla/operation_semantics#reduce . -/// -/// - Parameters: -/// - input: the input tensor -/// - init_value: a scalar representing the initial value for the reduction -/// -/// - Attrs: -/// - dimensions_to_reduce: dimension numbers over which to reduce -/// - reducer: a reducer function to apply -@inlinable @inline(__always) -public static func xlaReduce< - T: Numeric & TensorFlowScalar, - ReducerIn: TensorGroup, - ReducerOut: TensorGroup ->( - _ input: Tensor, - initValue: Tensor, - dimensionsToReduce: [Int32], - reducer: (ReducerIn) -> ReducerOut -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("XlaReduce", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("dimensions_to_reduce", dimensionsToReduce) - op.updateAttribute("reducer", reducer) - op.addInput(input) - op.addInput(initValue) - return op.execute(Int(1)) -} - -/// Wraps the XLA ReduceWindow operator, documented at -/// -/// https://www.tensorflow.org/performance/xla/operation_semantics#reducewindow . -/// -/// - Parameters: -/// - input: the input tensor -/// - init_value: a scalar representing the initial value for the reduction -/// - window_dimensions: the shape of the window -/// - window_strides: the inter-window strides -/// - padding: the padding to apply at the start and end of each input dimensions -/// -/// - Attr computation: a reducer function to apply -@inlinable @inline(__always) -public static func xlaReduceWindow< - T: Numeric & TensorFlowScalar, - Tindices: BinaryInteger & TensorFlowScalar, - ComputationIn: TensorGroup, - ComputationOut: TensorGroup ->( - _ input: Tensor, - initValue: Tensor, - windowDimensions: Tensor, - windowStrides: Tensor, - baseDilations: Tensor, - windowDilations: Tensor, - padding: Tensor, - computation: (ComputationIn) -> ComputationOut -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("XlaReduceWindow", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("computation", computation) - op.addInput(input) - op.addInput(initValue) - op.addInput(windowDimensions) - op.addInput(windowStrides) - op.addInput(baseDilations) - op.addInput(windowDilations) - op.addInput(padding) - return op.execute(Int(1)) -} - -/// Replica ID. -@inlinable @inline(__always) -public static func xlaReplicaId( -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("XlaReplicaId", nOutputs) - - return op.execute(Int(1)) -} - -/// Wraps the XLA SelectAndScatter operator, documented at -/// -/// https://www.tensorflow.org/performance/xla/operation_semantics#selectandscatter -/// . -/// -/// - Parameters: -/// - operand: the input tensor -/// - window_dimensions: the shape of the window -/// - window_strides: the inter-window strides -/// - padding: the padding to apply at the start and end of each input dimensions -/// - source: a tensor of values to scatter -/// - init_value: a scalar representing the initial value for the output tensor -/// -/// - Attrs: -/// - select: a selection function to apply -/// - scatter: a scatter function to apply -@inlinable @inline(__always) -public static func xlaSelectAndScatter< - T: Numeric & TensorFlowScalar, - Tindices: BinaryInteger & TensorFlowScalar, - SelectIn: TensorGroup, - SelectOut: TensorGroup, - ScatterIn: TensorGroup, - ScatterOut: TensorGroup ->( - operand: Tensor, - windowDimensions: Tensor, - windowStrides: Tensor, - padding: Tensor, - source: Tensor, - initValue: Tensor, - select: (SelectIn) -> SelectOut, - scatter: (ScatterIn) -> ScatterOut -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("XlaSelectAndScatter", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("Tindices", Tindices.tensorFlowDataType) - op.updateAttribute("select", select) - op.updateAttribute("scatter", scatter) - op.addInput(operand) - op.addInput(windowDimensions) - op.addInput(windowStrides) - op.addInput(padding) - op.addInput(source) - op.addInput(initValue) - return op.execute(Int(1)) -} - -/// Computes the eigen decomposition of a batch of self-adjoint matrices -/// -/// (Note: Only real inputs are supported). -/// -/// Computes the eigenvalues and eigenvectors of the innermost N-by-N matrices in -/// tensor such that tensor[...,:,:] * v[..., :,i] = e[..., i] * v[...,:,i], for -/// i=0...N-1. -/// -/// - Parameter a: the input tensor. -/// -/// - Attrs: -/// - lower: a boolean specifies whether the calculation is done with the lower -/// triangular part or the upper triangular part. -/// - max_iter: maximum number of sweep update, i.e., the whole lower triangular -/// part or upper triangular part based on parameter lower. Heuristically, it has -/// been argued that approximatly logN sweeps are needed in practice (Ref: Golub & -/// van Loan "Matrix Computation"). -/// - epsilon: the tolerance ratio. -/// -/// - Outputs: -/// - w: The eigenvalues in ascending order, each repeated according to its -/// multiplicity. -/// - v: The column v[..., :, i] is the normalized eigenvector corresponding to the -/// eigenvalue w[..., i]. -@inlinable @inline(__always) -public static func xlaSelfAdjointEig( - _ a: Tensor, - lower: Bool, - maxIter: Int64, - epsilon: Double -) -> (w: Tensor, v: Tensor) { - let nOutputs = Int(1) + Int(1) - let op = makeOp("XlaSelfAdjointEig", nOutputs) - op.updateAttribute("lower", lower) - op.updateAttribute("max_iter", maxIter) - op.updateAttribute("epsilon", epsilon) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - return op.execute(Int(1), Int(1)) -} - -/// Sends the named tensor to another XLA computation. Wraps the XLA Send operator -/// -/// documented at -/// https://www.tensorflow.org/performance/xla/operation_semantics#send . -/// -/// - Parameter tensor: The tensor to send. -/// -/// - Attr tensor_name: A string key that identifies the channel. -@inlinable @inline(__always) -public static func xlaSend( - _ tensor: Tensor, - tensorName: String -) { - let nOutputs = 0 - let op = makeOp("XlaSend", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.updateAttribute("tensor_name", tensorName) - op.addInput(tensor) - op.execute() -} - -/// Wraps the XLA Sort operator, documented at -/// -/// https://www.tensorflow.org/performance/xla/operation_semantics#sort -/// . -/// -/// Sorts a tensor. Currently only sorts in ascending order are supported. -/// -/// - Parameter input: A `Tensor` of type T. -/// -/// - Output output: A `Tensor` of type T. -@inlinable @inline(__always) -public static func xlaSort( - _ input: Tensor -) -> Tensor { - let nOutputs = Int(1) - let op = makeOp("XlaSort", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(input) - return op.execute(Int(1)) -} - -/// Computes the eigen decomposition of a batch of self-adjoint matrices -/// -/// (Note: Only real inputs are supported). -/// -/// Computes the eigenvalues and eigenvectors of the innermost M-by-N matrices in -/// tensor such that tensor[...,:,:] = u[..., :, :] * Diag(s[..., :]) * Transpose(v[...,:,:]). -/// -/// - Parameter a: the input tensor. -/// -/// - Attrs: -/// - max_iter: maximum number of sweep update, i.e., the whole lower triangular -/// part or upper triangular part based on parameter lower. Heuristically, it has -/// been argued that approximatly log(min (M, N)) sweeps are needed in practice -/// (Ref: Golub & van Loan "Matrix Computation"). -/// - epsilon: the tolerance ratio. -/// - precision_config: a serialized xla::PrecisionConfig proto. -/// -/// - Outputs: -/// - s: Singular values. The values are sorted in reverse order of magnitude, so -/// s[..., 0] is the largest value, s[..., 1] is the second largest, etc. -/// - u: Left singular vectors. -/// - v: Right singular vectors. -@inlinable @inline(__always) -public static func xlaSvd( - _ a: Tensor, - maxIter: Int64, - epsilon: Double, - precisionConfig: String -) -> (s: Tensor, u: Tensor, v: Tensor) { - let nOutputs = Int(1) + Int(1) + Int(1) - let op = makeOp("XlaSvd", nOutputs) - op.updateAttribute("max_iter", maxIter) - op.updateAttribute("epsilon", epsilon) - op.updateAttribute("precision_config", precisionConfig) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(a) - return op.execute(Int(1), Int(1), Int(1)) -} - -/// output = input; While (Cond(output)) { output = Body(output) } -/// -/// - Parameter input: A list of input tensors whose types are T. -/// -/// - Attrs: -/// - cond: A function takes 'input' and returns a tensor. If the tensor is -/// a scalar of non-boolean, the scalar is converted to a boolean -/// according to the following rule: if the scalar is a numerical -/// value, non-zero means True and zero means False; if the scalar is -/// a string, non-empty means True and empty means False. If the -/// tensor is not a scalar, non-emptiness means True and False -/// otherwise. -/// - body: A function that takes a list of tensors and returns another -/// list of tensors. Both lists have the same types as specified by T. -/// -/// - Output output: A list of output tensors whose types are T. -@inlinable @inline(__always) -public static func xlaWhile< - T: TensorArrayProtocol, - CondIn: TensorGroup, - CondOut: TensorGroup, - BodyIn: TensorGroup, - BodyOut: TensorGroup ->( - _ input: T, - cond: (CondIn) -> CondOut, - body: (BodyIn) -> BodyOut -) -> T { - let nOutputs = Int(input._typeList.count) - let op = makeOp("XlaWhile", nOutputs) - op.updateAttribute("T", input._typeList) - op.updateAttribute("cond", cond) - op.updateAttribute("body", body) - op.addInputList(input) - return op.execute(Int(input._typeList.count)) + let op = makeOp("Xdivy", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns 0 if x == 0, and x * log(y) otherwise, elementwise. @inlinable @inline(__always) public static func xlogy( - _ x: Tensor, - _ y: Tensor + _ x: Tensor, + _ y: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Xlogy", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(y) - return op.execute(Int(1)) + let op = makeOp("Xlogy", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(y) + return op.execute(Int(1)) } /// Returns a tensor of zeros with the same shape and type as x. @@ -37593,13 +36691,13 @@ public static func xlogy( /// - Output y: a tensor of the same shape and type as x but filled with zeros. @inlinable @inline(__always) public static func zerosLike( - _ x: Tensor + _ x: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("ZerosLike", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - return op.execute(Int(1)) + let op = makeOp("ZerosLike", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + return op.execute(Int(1)) } /// Compute the Hurwitz zeta function \\(\zeta(x, q)\\). @@ -37610,31 +36708,31 @@ public static func zerosLike( /// \\(\zeta(x, q) = \sum_{n=0}^{\infty} (q + n)^{-x}\\) @inlinable @inline(__always) public static func zeta( - _ x: Tensor, - q: Tensor + _ x: Tensor, + q: Tensor ) -> Tensor { let nOutputs = Int(1) - let op = makeOp("Zeta", nOutputs) - op.updateAttribute("T", T.tensorFlowDataType) - op.addInput(x) - op.addInput(q) - return op.execute(Int(1)) + let op = makeOp("Zeta", nOutputs) + op.updateAttribute("T", T.tensorFlowDataType) + op.addInput(x) + op.addInput(q) + return op.execute(Int(1)) } /// Creates a dataset that zips together `input_datasets`. @inlinable @inline(__always) public static func zipDataset( - inputDatasets: [VariantHandle], - outputTypes: [TensorDataType], - outputShapes: [TensorShape?] + inputDatasets: [VariantHandle], + outputTypes: [TensorDataType], + outputShapes: [TensorShape?] ) -> VariantHandle { let nOutputs = Int(1) - let op = makeOp("ZipDataset", nOutputs) - op.updateAttribute("output_types", outputTypes) - op.updateAttribute("output_shapes", outputShapes) - op.updateAttribute("N", inputDatasets.count) - op.addInputList(inputDatasets) - return op.execute(Int(1)) + let op = makeOp("ZipDataset", nOutputs) + op.updateAttribute("output_types", outputTypes) + op.updateAttribute("output_shapes", outputShapes) + op.updateAttribute("N", inputDatasets.count) + op.addInputList(inputDatasets) + return op.execute(Int(1)) } } diff --git a/Sources/DeepLearning/Bindings/TFTensorOperation.swift b/Sources/DeepLearning/Bindings/TFTensorOperation.swift index acd8cc18b..f137a3cfc 100644 --- a/Sources/DeepLearning/Bindings/TFTensorOperation.swift +++ b/Sources/DeepLearning/Bindings/TFTensorOperation.swift @@ -14,137 +14,136 @@ // A protocol for a tensor operation. public protocol TensorOperation { - // We use functions instead of fields to give freedom in the - // representation for the conforming types. - init(_ name: String, _ outputCount: Int) + // We use functions instead of fields to give freedom in the representation for the conforming + // types. + init(_ name: String, _ outputCount: Int) - func updateAttribute(_ name: String, _ value: Bool) - func updateAttribute(_ name: String, _ value: Int) - func updateAttribute(_ name: String, _ value: Int32) - func updateAttribute(_ name: String, _ value: Int64) - func updateAttribute(_ name: String, _ value: Float) - func updateAttribute(_ name: String, _ value: Double) - func updateAttribute(_ name: String, _ value: String) - func updateAttribute(_ name: String, _ value: [Bool]) - func updateAttribute(_ name: String, _ value: [Int]) - func updateAttribute(_ name: String, _ value: [Int32]) - func updateAttribute(_ name: String, _ value: [Int64]) - func updateAttribute(_ name: String, _ value: [Float]) - func updateAttribute(_ name: String, _ value: [Double]) - func updateAttribute(_ name: String, _ value: [String]) + func updateAttribute(_ name: String, _ value: Bool) + func updateAttribute(_ name: String, _ value: Int) + func updateAttribute(_ name: String, _ value: Int32) + func updateAttribute(_ name: String, _ value: Int64) + func updateAttribute(_ name: String, _ value: Float) + func updateAttribute(_ name: String, _ value: Double) + func updateAttribute(_ name: String, _ value: String) + func updateAttribute(_ name: String, _ value: [Bool]) + func updateAttribute(_ name: String, _ value: [Int]) + func updateAttribute(_ name: String, _ value: [Int32]) + func updateAttribute(_ name: String, _ value: [Int64]) + func updateAttribute(_ name: String, _ value: [Float]) + func updateAttribute(_ name: String, _ value: [Double]) + func updateAttribute(_ name: String, _ value: [String]) - // TODO(https://bugs.swift.org/browse/TF-522): When we are able to - // use opaque return types everywhere, we should add an - // associatedtype requirement and add the following methods so that - // we can work with non-tensorflow backends if neeeded. - // - // associatedtype TensorValueHandle - // - // func addInput(_ input : TensorValueHandle) - // func evaluate() -> ([TensorValueHandle]) + // TODO(https://bugs.swift.org/browse/TF-522): When we are able to + // use opaque return types everywhere, we should add an + // associatedtype requirement and add the following methods so that + // we can work with non-tensorflow backends if neeeded. + // + // associatedtype TensorValueHandle + // + // func addInput(_ input: TensorValueHandle) + // func evaluate() -> ([TensorValueHandle]) } // A protocol for a tensor operation in TensorFlow library. -public protocol TFTensorOperation : TensorOperation { - func addInput(_ input: Tensor) - func addInput(_ input: StringTensor) - func addInput(_ input: VariantHandle) - func addInput(_ input: ResourceHandle) - func addInputList(_ input: T) +public protocol TFTensorOperation: TensorOperation { + func addInput(_ input: Tensor) + func addInput(_ input: StringTensor) + func addInput(_ input: VariantHandle) + func addInput(_ input: ResourceHandle) + func addInputList(_ input: T) - func updateAttribute(_ name: String, _ value: TensorDataType) - func updateAttribute(_ name: String, _ value: TensorShape) - func updateAttribute(_ name: String, _ value: TensorShape?) - func updateAttribute(_ name: String, _ value: [TensorDataType]) - func updateAttribute(_ name: String, _ value: [TensorShape]) - func updateAttribute(_ name: String, _ value: [TensorShape?]) - func updateAttribute( - _ name: String, _ value: (In) -> Out) + func updateAttribute(_ name: String, _ value: TensorDataType) + func updateAttribute(_ name: String, _ value: TensorShape) + func updateAttribute(_ name: String, _ value: TensorShape?) + func updateAttribute(_ name: String, _ value: [TensorDataType]) + func updateAttribute(_ name: String, _ value: [TensorShape]) + func updateAttribute(_ name: String, _ value: [TensorShape?]) + func updateAttribute(_ name: String, _ value: (In) -> Out) - func execute() + func execute() - func execute( - _ count0: Int - ) -> (T0) + func execute( + _ count0: Int + ) -> (T0) - func execute( - _ count0: Int, - _ count1: Int - ) -> (T0, T1) + func execute( + _ count0: Int, + _ count1: Int + ) -> (T0, T1) - func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int - ) -> (T0, T1, T2) + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int + ) -> (T0, T1, T2) - func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int - ) -> (T0, T1, T2, T3) + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int + ) -> (T0, T1, T2, T3) - func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int, - _ count4: Int - ) -> (T0, T1, T2, T3, T4) + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int + ) -> (T0, T1, T2, T3, T4) - func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int, - _ count4: Int, - _ count5: Int - ) -> (T0, T1, T2, T3, T4, T5) + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int + ) -> (T0, T1, T2, T3, T4, T5) - func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int, - _ count4: Int, - _ count5: Int, - _ count6: Int - ) -> (T0, T1, T2, T3, T4, T5, T6) - - func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int, - _ count4: Int, - _ count5: Int, - _ count6: Int, - _ count7: Int - ) -> (T0, T1, T2, T3, T4, T5, T6, T7) + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int + ) -> (T0, T1, T2, T3, T4, T5, T6) + + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int, + _ count7: Int + ) -> (T0, T1, T2, T3, T4, T5, T6, T7) - func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int, - _ count4: Int, - _ count5: Int, - _ count6: Int, - _ count7: Int, - _ count8: Int - ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8) - - func execute( - _ count0: Int, - _ count1: Int, - _ count2: Int, - _ count3: Int, - _ count4: Int, - _ count5: Int, - _ count6: Int, - _ count7: Int, - _ count8: Int, - _ count9: Int - ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9) + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int, + _ count7: Int, + _ count8: Int + ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8) + + func execute( + _ count0: Int, + _ count1: Int, + _ count2: Int, + _ count3: Int, + _ count4: Int, + _ count5: Int, + _ count6: Int, + _ count7: Int, + _ count8: Int, + _ count9: Int + ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9) } diff --git a/Sources/DeepLearning/Bindings/generate_wrappers.py b/Sources/DeepLearning/Bindings/generate_wrappers.py index c1e276254..915ab8e3b 100644 --- a/Sources/DeepLearning/Bindings/generate_wrappers.py +++ b/Sources/DeepLearning/Bindings/generate_wrappers.py @@ -189,8 +189,8 @@ def indent(line_index): if indent_level == 0: return '' if line_index: - return ' ' * indent_level - return ' ' * (indent_level - 1) + '- ' + return ' ' * indent_level + return ' ' * (indent_level - 1) + '- ' return ''.join([ (_START_COMMENT + ' ' + indent(line_index) + line + '\n' @@ -243,10 +243,10 @@ def _swift_generics(self): def _swift_input_args(self): args = '' for arg in self.input_args: - args += '\n %s: %s,' % (arg.swift_arg_name, str(arg.swift_type(self.string_valued))) + args += '\n %s: %s,' % (arg.swift_arg_name, str(arg.swift_type(self.string_valued))) for attr in self.attrs: if not attr.is_inferred_type_attr and not attr.is_inferred_number_attr: - args += '\n %s: %s%s,' % (attr.swift_arg_name, attr.swift_type, attr.swift_default) + args += '\n %s: %s%s,' % (attr.swift_arg_name, attr.swift_type, attr.swift_default) if args != '': args = args[:-1] return args @@ -273,11 +273,11 @@ def _swift_body(self): body = 'let nOutputs = 0' else: body = 'let nOutputs = {}'.format(' + '.join(counts)) - body += '\n let op = makeOp("{}", nOutputs)\n '.format(self.op_def.name) - body += '\n '.join(setters) + body += '\n let op = makeOp("{}", nOutputs)\n '.format(self.op_def.name) + body += '\n '.join(setters) if len(self.output_args) == 0: - return body + '\n op.execute()' - body += '\n return op.execute({})'.format(', '.join(counts)) + return body + '\n op.execute()' + body += '\n return op.execute({})'.format(', '.join(counts)) return body @@ -611,22 +611,22 @@ def enum_codes(self): # '@_frozen\n' + '// @_frozen // SR-9739\n' + 'public enum {} {{\n'.format(type_name) + - '\n'.join([' case {}'.format( + '\n'.join([' case {}'.format( swift_compatible_identifier(a.lower())) for a in allowed_values]) + '\n\n' + - ' @inlinable\n' + - ' var cName: String {\n' + - ' @inline(__always)\n' + - ' get {\n' + - ' switch self {\n' + - '\n'.join([' case .{}: return "{}"'.format( + ' @inlinable\n' + + ' var cName: String {\n' + + ' @inline(__always)\n' + + ' get {\n' + + ' switch self {\n' + + '\n'.join([' case .{}: return "{}"'.format( swift_compatible_identifier(a.lower()), a) for a in allowed_values]) + '\n' + - ' }\n' + + ' }\n' + + ' }\n' + ' }\n' + - ' }\n' + '}') return codes @@ -698,9 +698,8 @@ def main(argv): _HEADER + 'import CTensorFlow\n\n' + '@inlinable @inline(__always)\n' + - 'func makeOp(_ name: String, _ nOutputs: Int)'+ - ' -> TFTensorOperation {\n' + - ' _ExecutionContext.makeOp(name, nOutputs)\n' + + 'func makeOp(_ name: String, _ nOutputs: Int) -> TFTensorOperation {\n' + + ' _ExecutionContext.makeOp(name, nOutputs)\n' + '}\n'+ '\npublic enum Raw {\n\n' + '\n'.join(version_codes) + From 261a424f9433730c3df4bb4138902d29f4b59446 Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 18:28:00 -0400 Subject: [PATCH 06/14] Added the runtime helpers. --- Sources/DeepLearning/Core/Runtime.swift | 1287 +++++++++++++++++++++ Sources/DeepLearning/Core/Utilities.swift | 169 +++ 2 files changed, 1456 insertions(+) create mode 100644 Sources/DeepLearning/Core/Runtime.swift create mode 100644 Sources/DeepLearning/Core/Utilities.swift diff --git a/Sources/DeepLearning/Core/Runtime.swift b/Sources/DeepLearning/Core/Runtime.swift new file mode 100644 index 000000000..b80ae90e8 --- /dev/null +++ b/Sources/DeepLearning/Core/Runtime.swift @@ -0,0 +1,1287 @@ +// Copyright 2018 The TensorFlow Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This file defines the Swift runtime support for TensorFlow computation. +// +// This file should only contain internal details: runtime-related public APIs +// should be defined in `Execution.swift`. +// +// Design notes on TF eager based runtime: +// +// A global context (`_ExecutionContext.global`) is used to manage all tensor +// computation and transfers. +// +// Potential TODOs: +// - Support async on platforms other than Linux and FreeBSD. +// - Revisit the concurrency model and see if Dispatch can be built without +// Foundation. +// +//===----------------------------------------------------------------------===// + +#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +import Darwin +#else +import Glibc +#endif +import CTensorFlow + +/// TraceContext contains the state needed to build a trace graph function (TF_Function). As eager +/// ops are executed in tracing mode, their corresponding nodes are added to the trace graph (via +/// `addEagerOpToGraph()`). When the trace is finalized (via `finalize()`), the trace graph function +/// can then be executed (via `execute()`) by the eager runtime. +@usableFromInline +internal class TraceContext { + let status: CTFStatus = TF_NewStatus() + + /// The trace graph, which will be converted to a trace graph function upon finalizing. + let graph = TF_NewGraph() + + /// The list of inputs to the trace graph function. It starts with the inputs to the function + /// that we trace (referred to as the "tracee function" or "tracee"), followed by possible + /// additional inputs that correspond to concrete tensors produced within the trace function. + /// + /// For example, if the tracee is: + /// + /// struct TensorPair: TensorGroup { + /// public var first: T + /// public var second: U + /// } + /// + /// func foo(x: TensorPair) -> Tensor { + /// let y = Tensor(1.0) + /// return x.first + x.second + y + /// } + /// + /// Then the generated trace graph function has 3 input tensors: x.first, x.second, and y. + /// + /// These symbolic tensors corresond to PlaceHolder nodes in the trace graph, and will be filled + /// in when we execute the trace graph function. + // + // TODO: If some tensors in `x` are not used within `foo()`, they can be pruned away in the + // inputs to the trace graph function. + var symbolicInputs: [TF_Output] = [] + + /// The outputs obtained by executing the `tracee` for computing the trace. + var tracedOutputs: [CTensorHandle] = [] + + /// The trace context object used in TF C API calls that convert eager ops to (trace) graph + /// nodes. + let cTraceContext: CTFETraceContext + + /// The trace graph function created by `finalize()`. + var traceGraphFn: CTFFunction? + + /// The number of additional input tensors to the trace graph function, created from concrete + /// intermediate tensors in the tracee, such as `y` in the code snippet above. + var additionalInputTensorCount: Int32 = -1 + + /// `dtypes` is the (flattened) list of TF_DataType of input tensors to the trace function. + init(dtypes: [TF_DataType]) { + debugLog("Instiantiating TraceContext with \(dtypes.count) input tensors.") + for (i, dtype) in dtypes.enumerated() { + let desc = TF_NewOperation(graph, "Placeholder", "input_\(i)") + TF_SetAttrType(desc, "dtype", dtype) + let result = TF_FinishOperation(desc, status) + checkOk(status) + symbolicInputs.append(TF_Output(oper: result, index: 0)) + } + cTraceContext = TFE_NewTraceContext(graph) + } + + deinit { + TFE_DeleteTraceContext(cTraceContext) + TF_DeleteGraph(graph) + TF_DeleteStatus(status) + } + + @usableFromInline + func addEagerOpToGraph( + _ op: CTFEOp, + _ retvals: UnsafeMutablePointer, + _ retvalCount: UnsafeMutablePointer, + _ status: CTFStatus + ) { + TFE_AddEagerOpToGraph(op, cTraceContext, retvals, retvalCount, status) + checkOk(status) + } + + /// Finalize the trace graph function. + func finalize(traceeBasicName: String) { + internalConsistencyCheck(traceGraphFn == nil) + var symbolicOutputs: [TF_Output] = [] + // Only add symbolic output tensors as the outputs of the trace graph function. + // For example, let the tracee be: + // func foo(x: Tensor) -> (Tensor, Tensor) { + // let y = Tensor(1.0) + // return (x + x, y) + // } + // + // Here foo() returns 2 tensors, but only the first one (as computed by x + x) is symbolic. + // The second one for y is concrete, and is computed at trace creation time, not trace + // execution time. Also see the comment block above finalizeAndExecuteTraceFn(). + for (i, tracedOutput) in tracedOutputs.enumerated() + where TFE_TensorHandleIsConcrete(tracedOutput) == 0 { + debugLog("Adding symbolic tracedOutput \(i) as a trace graph func output.") + symbolicOutputs.append(TFE_GetTFOutputFromTensorHandle(tracedOutput ,status)) + checkOk(status) + } + + let traceeInputCount = symbolicInputs.count + // Append concrete tensors created within the tracee as symbolic inputs to the generated + // trace graph function. + additionalInputTensorCount = TFE_FinalizeInputTensorsFromTraceContext(cTraceContext) + for i in 0.. [CTensorHandle] { + // We must be in the `notTracing` enum mode. + internalConsistencyCheck(_RuntimeConfig.traceState.context == nil) + internalConsistencyCheck(traceGraphFn != nil) + + let tracedFunctionName = TF_FunctionName(traceGraphFn) + internalConsistencyCheck(tracedFunctionName != nil) + let eagerContext = _TFCGetGlobalEagerContext() + let op: CTFEOp! = TFE_NewOp(eagerContext, tracedFunctionName, status) + defer { TFE_DeleteOp(op) } + checkOk(status) + + let deviceName = _ExecutionContext.global.currentDeviceName + if let deviceName = deviceName { + debugLog("Placing the trace func on device \(deviceName).") + TFE_OpSetDevice(op, deviceName, status) + checkOk(status) + } + + if useXLA { + debugLog("Enabling XLA compilation") + TFE_OpSetAttrBool(op, "_XlaCompile", 1) + } + + debugLog("Adding \(traceeInputs.count) tracee input tensors.") + internalConsistencyCheck( + symbolicInputs.count == traceeInputs.count + Int(additionalInputTensorCount)) + for input in traceeInputs { + _TFCOpAddInputFromTensorHandle(op, input, status) + checkOk(status) + } + + debugLog("Adding \(additionalInputTensorCount) additional input tensors.") + for i in 0.. String { + let specializedGraph = TF_NewGraph()! + + TF_GraphCopyFunction(specializedGraph, traceGraphFn, /*gradient*/ nil, status) + checkOk(status) + + let tracedFunctionName = TF_FunctionName(traceGraphFn) + internalConsistencyCheck(tracedFunctionName != nil) + let tracedOpDesc = TF_NewOperation(specializedGraph, tracedFunctionName, "tracedFn") + + // Create and append the inputs to the graph function. + let traceeInputs = symbolicInputs.dropLast( + dataTensors.count + Int(additionalInputTensorCount)) + var inputs: [TF_Output] = [] + for (i, traceeInput) in traceeInputs.enumerated() { + let desc = TF_NewOperation(specializedGraph, "Placeholder", "input_\(i)") + TF_SetAttrType(desc, "dtype", TF_OperationOutputType(traceeInput)) + let result = TF_FinishOperation(desc, status) + checkOk(status) + let input = TF_Output(oper: result, index: 0) + TF_AddInput(tracedOpDesc, input) + inputs.append(input) + } + + // Wire the data to the corresponding inputs of the tracedOp. + for (i, cTensorHandle) in dataTensors.enumerated() { + let cTensor = TFE_TensorHandleResolve(cTensorHandle, status) + checkOk(status) + let desc = TF_NewOperation(specializedGraph, "Const", "input_const_\(i)") + TF_SetAttrType(desc, "dtype", TFE_TensorHandleDataType(cTensorHandle)) + TF_SetAttrTensor(desc, "value", cTensor, status) + checkOk(status) + let result = TF_FinishOperation(desc, status) + checkOk(status) + TF_AddInput(tracedOpDesc, TF_Output(oper: result, index: 0)) + } + + var nextConst = dataTensors.count + debugLog("Adding \(additionalInputTensorCount) additional input tensors.") + for i in 0..= 0 && newValue <= 4 else { + fatalError("Invalid tensorflowVerboseLogLevel value \(newValue)") + } + } + } +} + +private func configureRuntimeFromEnvironment() { + if let value = getenv("SWIFT_TENSORFLOW_ENABLE_DEBUG_LOGGING"), + String(cString: value).lowercased() == "true" { + _RuntimeConfig.printsDebugLog = true + debugLog("Turning on debug logging from env.") + } + + if let value = getenv("SWIFT_TENSORFLOW_VERBOSE_LOG_LEVEL") { + guard var verboseLevel = Int32(String(cString: value)) else { + fatalError("SWIFT_TENSORFLOW_VERBOSE_LOG_LEVEL must take an int value.") + } + if verboseLevel > 4 { + verboseLevel = 4 + } + _RuntimeConfig.tensorflowVerboseLogLevel = verboseLevel + debugLog("Setting TF logging verbose level to \(verboseLevel) from env.") + } + + if let value = getenv("SWIFT_TENSORFLOW_SERVER_ADDRESS") { + let address = String(cString: value) + debugLog("Env var SWIFT_TENSORFLOW_SERVER_ADDRESS has value \(address).") + if address == "local" { + _RuntimeConfig.session = .local + debugLog("Using local TF session.") + } else { + guard let idx = address.firstIndex(of: ":"), + let endIdx = address.index(idx, offsetBy: 3, limitedBy: address.endIndex), + address[idx.. + + /// The TFE_Context object. + @usableFromInline + internal let eagerContext: CTFEContext + + /// The status for checking TensorFlow errors. + private let status: CTFStatus = TF_NewStatus() + + /// The mutex for preventing potential concurrent access. + private var mutex: pthread_mutex_t = pthread_mutex_t() + + /// Initializes a new execution context by initializing available devices. + @usableFromInline + init() { + configureRuntimeFromEnvironment() + + // Suppress TensorFlow logging, unless the user specified a log level. + setenv("TF_CPP_MIN_LOG_LEVEL", "3", /*override*/ 0) + + debugLog("Initializing global context.") + + // Initialize the TF runtime exactly once. Only affects local execution + // (when _RuntimeConfig.tensorFlowServer is set to ""). + if !_RuntimeConfig.tensorFlowRuntimeInitialized { + var args = ["dummyProgramName"] + if _RuntimeConfig.printsDebugLog { + args.append("--alsologtostderr") + } + if _RuntimeConfig.tensorflowVerboseLogLevel > 0 { + args.append("--v=\(_RuntimeConfig.tensorflowVerboseLogLevel)") + } + // Collect all the strings' utf8 bytes into a single array so that we can + // address all the strings with a single `flattenedStringBytes.withUnsafeBufferPointer`. + var flattenedStringBytes: [Int8] = [] + var lengths: [Int] = [] + for arg in args { + let bytes = arg.utf8CString + flattenedStringBytes.append(contentsOf: bytes) + lengths.append(bytes.count) + } + + // Calculate the addresses of all the strings within our single buffer, and then call + // TF_InitMain. + flattenedStringBytes.withUnsafeMutableBufferPointer { flattenedStringBytesBuffer in + var stringAddrs: [UnsafeMutablePointer?] = [] + var currentStringAddr = flattenedStringBytesBuffer.baseAddress + .map(UnsafeMutablePointer.init) + for length in lengths { + stringAddrs.append(currentStringAddr) + currentStringAddr = currentStringAddr?.advanced(by: length) + } + + stringAddrs.withUnsafeMutableBufferPointer { stringAddrsBuffer in + var cArgs = [stringAddrsBuffer.baseAddress.map(UnsafeMutablePointer.init)] + var cArgsCount = [Int32(args.count)] + + cArgs.withUnsafeMutableBufferPointer { cArgsBuffer in + cArgsCount.withUnsafeMutableBufferPointer { cArgsCountBuffer in + TF_InitMain(nil, cArgsCountBuffer.baseAddress, cArgsBuffer.baseAddress) + } + } + } + } + _RuntimeConfig.tensorFlowRuntimeInitialized = true + } + + guard let opts = TFE_NewContextOptions() else { + fatalError("ContextOptions object can never be nil.") + } + + // Create TF config object. + if _RuntimeConfig.gpuMemoryAllowGrowth { + debugLog("Allowing growth for GPU memory allocator.") + } + self.tensorFlowConfig = TF_CreateConfig( + /* enable_xla_compilation */ 0, + _RuntimeConfig.gpuMemoryAllowGrowth ? 1 : 0, + _RuntimeConfig.cpuDeviceCount) + TFE_ContextOptionsSetConfig(opts, + tensorFlowConfig.pointee.data, + tensorFlowConfig.pointee.length, + status) + checkOk(status) + + let ctx = TFE_NewContext(opts, status) + checkOk(status) + self.eagerContext = ctx! + TFE_DeleteContextOptions(opts) + checkOk(status) + + if case .remote(let serverDef) = _RuntimeConfig.session { + debugLog("Setting up the server def to \(serverDef)...") + let serverDef: UnsafeMutablePointer! = TFE_GetServerDef(serverDef, status) + checkOk(status) + TFE_ContextSetServerDef( + eagerContext, /*keep_alive_secs*/0, serverDef.pointee.data, + serverDef.pointee.length, status) + checkOk(status) + TF_DeleteBuffer(serverDef) + } + + let devices = TFE_ContextListDevices(eagerContext, status) + checkOk(status) + defer { TF_DeleteDeviceList(devices!) } + + let deviceCount = TF_DeviceListCount(devices!) + debugLog("There are \(deviceCount) devices.") + for deviceId in 0.. TFTensorOperation { + return TFE_Op(name, nOutputs) + } +} + +// Elements in `outputs` can come from two sources: +// a) Symbolic tensors produced by tensor ops, and added as trace graph nodes. +// b) Concrete tensors produced by host code (e.g. Tensor(1.0)). +fileprivate func finalizeTraceFunction(_ name: String) -> TraceContext { + guard let traceContext = _RuntimeConfig.traceState.context else { + fatalError("Not in tracing mode!.") + } + _RuntimeConfig.traceState = .notTracing + traceContext.finalize(traceeBasicName: name) + return traceContext +} + +private extension TensorArrayProtocol { + // The returned handles are owned by the caller. + var cTensorHandles: [CTensorHandle] { + debugLog("Getting \(self._tensorHandleCount) C handles.") + let buffer = UnsafeMutablePointer.allocate( + capacity: Int(self._tensorHandleCount)) + debugLog("Unpacking handles into buffer.") + _unpackTensorHandles(into: buffer) + let status = TF_NewStatus() + debugLog("Copying buffer content to output handles.") + var output: [CTensorHandle] = [] + for i in 0..(_copying input: C) where C.Element == CTensorHandle { + assert(Self._tensorHandleCount == input.count) + let buffer = UnsafeMutablePointer.allocate(capacity: input.count) + let status = TF_NewStatus() + // copy input to buffer + for (i, inputTensorHandle) in input.enumerated() { + let address = buffer.advanced(by: i) + // Each tensor can be symbolic (e.g. when using this API to create a symbolic input + // instance to tracee) or concrete (e.g. when creating the final output of the tracee). + let newHandle = TFE_TensorHandleCopySharingTensor(inputTensorHandle, status) + checkOk(status) + address.initialize(to: newHandle!) + } + TF_DeleteStatus(status) + self.init(_owning: buffer) + } + + init(_owning input: C) where C.Element == CTensorHandle { + assert(Self._tensorHandleCount == input.count) + let buffer = UnsafeMutablePointer.allocate(capacity: input.count) + let status = TF_NewStatus() + // copy input to buffer + for (i, inputTensorHandle) in input.enumerated() { + let address = buffer.advanced(by: i) + address.initialize(to: inputTensorHandle) + } + TF_DeleteStatus(status) + self.init(_owning: buffer) + } +} + +// TODO: Fold this protocol into TensorArrayProtocol. +// This requires that we move concrete implementation such as Tensor._makeInstance() to +// TensorGroup.swift. +public protocol _TensorArrayProtocolEnhanced: TensorArrayProtocol { + // Create an instance based on `inputs`, which can be symbolic (e.g., when creating a symbolic + // input to tracee) or concrete (e.., when creating a final output of executing the tracee). + func _makeInstance(owning inputs: C) -> Self where C.Element == CTensorHandle +} + +extension _TensorArrayProtocolEnhanced { + var _dtypes: [TF_DataType] { + let count = Int(_tensorHandleCount) + let buffer = UnsafeMutableBufferPointer.allocate(capacity: count) + defer { buffer.deallocate() } + _unpackTensorHandles(into: buffer.baseAddress) + return buffer.map { TFE_TensorHandleDataType($0) } + } +} + +/// Trace `fn` with newly created tensor handles and return a trace context. +private func _trace( + with dtypes: [TF_DataType], + in fn: ([CTensorHandle]) -> [CTensorHandle] +) -> TraceContext { + debugLog(""" + Tracing over a function with \(dtypes.count) inputs. + """) + + // Verify that we are not already tracing. + internalConsistencyCheck(_RuntimeConfig.traceState.context == nil, + "Should not be in tracing mode already!") + + // Switch to tracing mode. + let traceCtx = TraceContext(dtypes: dtypes) + _RuntimeConfig.traceState = .tracing(traceCtx) + + // Handle inputs. + let inputSymbolicTensors = traceCtx.symbolicInputs.map { + TFE_NewTensorHandleFromTFOutput($0, TF_OperationOutputType($0))! + } + internalConsistencyCheck(inputSymbolicTensors.count == dtypes.count) + + // Run tracee to build the trace, adding ops to the trace graph function. The tracee output can + // contain a mixture of symbolic and concrete tensors (see the comment block within + // TraceContext.finalize()). + debugLog("Running tracee in tracing mode.") + traceCtx.tracedOutputs = fn(inputSymbolicTensors) + + debugLog("Finalizing trace graph function.") + // TAP means tensor array protocol. + let opType = "MyTraceFn_TAP" + return finalizeTraceFunction(opType) +} + +private func _graphInternal( + with state: State, + in fn: (State, Data) -> (State, Result?) +) -> (State, Data) -> (State, Result?) { + let traceContext: TraceContext = withoutActuallyEscaping(fn) { escapableFn in + let wrappedFn = { (inputs: [CTensorHandle]) -> [CTensorHandle] in + let symbolicState = state._makeInstance(owning: inputs.dropLast(Data._typeList.count)) + let symbolicData = Data(_copying: inputs.dropFirst(Int(state._tensorHandleCount))) + let (outputState, outputResult) = escapableFn(symbolicState, symbolicData) + + debugLog("Assembling output tensor handles.") + let outputs = + outputResult != nil + ? (outputState.cTensorHandles + outputResult!.cTensorHandles) + : outputState.cTensorHandles + return outputs + } + let dtypes = state._dtypes + Data._typeList.map { $0._cDataType } + return _trace(with: dtypes, in: wrappedFn) + } + // The result is a closure that captures and executes the trace graph function in the trace + // context. + return { (oldState: State, data: Data) -> (State, Result?) in + debugLog("Running trace function over state \(oldState) and data \(data).") + + debugLog("Getting input state tensor handles.") + let inputStateTensorHandles = oldState.cTensorHandles + var inputTensors = inputStateTensorHandles.map { + TFETensorHandle(_owning: $0) + } + debugLog("Getting input data tensor handles.") + let inputDataTensorHandles = data.cTensorHandles + inputTensors.append(contentsOf: inputDataTensorHandles.map { + TFETensorHandle(_owning: $0) + }) + + debugLog("Executing trace graph function.") + let returnValues = traceContext.execute(traceeInputs: inputTensors) + + debugLog("Creating output model instance.") + let newState = state._makeInstance( + owning: returnValues.prefix(Int(state._tensorHandleCount))) + let resultValues = returnValues.dropFirst(Int(state._tensorHandleCount)) + let result: Result? = resultValues.isEmpty ? nil : Result(_owning: resultValues) + return (newState, result) + } +} + +// TODO: rename this to `graph` when it's ready for end users. +public func _graph( + with state: State, + in fn: (State, Data) -> (State, Result) +) -> (State, Data) -> (State, Result) { + let graphFunction = _graphInternal(with: state, in: fn) + return { (state: State, data: Data) in + let result = graphFunction(state, data) + internalConsistencyCheck(result.1 != nil) + return (result.0, result.1!) + } +} + +// TODO: rename this to `graph` when it's ready for end users. +public func _graph( + with state: State, + in fn: (State, Data) -> State +) -> (State, Data) -> State { + let graphFunction: (State, Data) -> (State, TensorHandle?) = + withoutActuallyEscaping(fn) { escapableFn in + let wrappedFn = { + // The result argument needs to a type that conforms to TensorGroup. + // We are arbitrarily picking TensorHandle here. + (s: State, d: Data) -> (State, TensorHandle?) in + (escapableFn(s, d), nil) + } + return _graphInternal(with: state, in: wrappedFn) + } + return { (state: State, data: Data) in graphFunction(state, data).0 } +} + +/// Trace the given function `fn` and return a closure that can be used to create a +/// `TF_Function(State)` specialized for `data`. +public func _tffunc( + with state: State, + in fn: (State, Data) -> State +) -> (Data) -> (String) { + let traceContext: TraceContext = withoutActuallyEscaping(fn) { escapableFn in + let wrappedFn = { (inputs: [CTensorHandle]) -> [CTensorHandle] in + let symbolicState = state._makeInstance(owning: inputs.dropLast(Data._typeList.count)) + let symbolicData = Data(_copying: inputs.dropFirst(Int(state._tensorHandleCount))) + let outputState = escapableFn(symbolicState, symbolicData) + return outputState.cTensorHandles + } + let dtypes = state._dtypes + Data._typeList.map { $0._cDataType } + return _trace(with: dtypes, in: wrappedFn) + } + return { + data in traceContext.specializeTFFunction(with: data.cTensorHandles) + } +} + +// Trace the given function to generate a TF graph and return a closure that can be used to launch +// the graph. +public func _graph( + _ fn: (In) -> Out, + useXLA: Bool = false +) -> (In) -> Out { + let traceContext: TraceContext = withoutActuallyEscaping(fn) { escapableFn in + let wrappedFn = { (inputs: [CTensorHandle]) -> [CTensorHandle] in + let buffer = UnsafeMutablePointer.allocate(capacity: Int(inputs.count)) + var ptr = buffer + for input in inputs { + ptr.initialize(to: input) + ptr = ptr.advanced(by: 1) + } + let symbolicIn = In(_owning: buffer) + let symbolicOut = escapableFn(symbolicIn) + return symbolicOut.cTensorHandles + } + let dtypes = In._typeList.map { $0._cDataType } + return _trace(with: dtypes, in: wrappedFn) + } + // The result is a closure that captures and executes the trace graph function in the trace + // context. + return { (input: In) -> (Out) in + debugLog("Running trace function over input \(input).") + + debugLog("Getting input state tensor handles.") + let inputStateTensorHandles = input.cTensorHandles + let inputTensors = inputStateTensorHandles.map { + TFETensorHandle(_owning: $0) + } + debugLog("Executing trace graph function.") + let returnValues = traceContext.execute(traceeInputs: inputTensors, useXLA: useXLA) + + debugLog("Creating output model instance.") + return Out(_owning: returnValues) + } +} + +/// Trace the given function and return the name of the corresponding `TF_Function: In -> Out` that +/// was created. +public func _tffunc(_ fn: (In) -> Out) -> String { + let traceContext: TraceContext = withoutActuallyEscaping(fn) { escapableFn in + let wrappedFn = { (inputs: [CTensorHandle]) -> [CTensorHandle] in + let buffer = UnsafeMutablePointer.allocate(capacity: Int(inputs.count)) + var ptr = buffer + for input in inputs { + ptr.initialize(to: input) + ptr = ptr.advanced(by: 1) + } + let symbolicIn = In(_owning: buffer) + let symbolicOut = escapableFn(symbolicIn) + return symbolicOut.cTensorHandles + } + + let dtypes = In._typeList.map { $0._cDataType } + return _trace(with: dtypes, in: wrappedFn) + } + return traceContext.specializeTFFunction(with: []) +} + +internal extension _ExecutionContext { + /// Returns a valid TensorFlow device name, which corresponds to the closest enclosing call to + /// one of the overloads of withDevice. A return value of `nil` indicates the absence of a + /// withDevice call on the call stack or the presence of an immediately enclosing + /// `withDefaultDevice(perform)` call. + var currentDeviceName: String? { + return _ThreadLocalState.local._currentDevice + } + + /// See documentation for the top-level `withDevice(_:_:perform)`. + func withDevice( + _ kind: DeviceKind, + _ index: UInt = 0, + perform body: () throws -> R + ) rethrows -> R { + let name: String + switch kind { + case .cpu: + name = "/job:localhost/replica:0/task:0/device:CPU:\(index)" + case .gpu: + name = "/job:localhost/replica:0/task:0/device:GPU:\(index)" + case .tpu: + // According to server def generated when you set + // SWIFT_TENSORFLOW_SERVER_ADDRESS, the TPUs will all be on task 1. + name = "/job:localhost/replica:0/task:1/device:TPU:\(index)" + } + return try withDevice(named: name, perform: body) + } + + /// See documentation for the top-level `withDevice(named:perform)`. + func withDevice(named name: String, perform body: () throws -> R) rethrows -> R { + guard deviceNames.contains(name) else { + fatalError("Device \(name) not found") + } + _ThreadLocalState.local.pushDevice(name) + let result = try body() + _ThreadLocalState.local.popDevice() + return result + } + + /// See documentation for the top-level `withDefaultDevice(perform)`. + func withDefaultDevice(perform body: () throws -> R) rethrows -> R { + _ThreadLocalState.local.pushDevice(nil) + let result = try body() + _ThreadLocalState.local.popDevice() + return result + } +} + +internal extension _ExecutionContext { + /// Synchronously execute the body, preventing asynchronous computation from corrupting the + /// context data. + private func sync(execute body: () throws -> Result) rethrows -> Result { + let lockStatus = pthread_mutex_lock(&mutex) + internalConsistencyCheck(lockStatus == 0) + defer { + let unlockStatus = pthread_mutex_unlock(&mutex) + internalConsistencyCheck(unlockStatus == 0) + // Create a cancellation point. + pthread_testcancel() + } + return try body() + } +} + +@usableFromInline +internal func dumpTensorContent( + _ inputTensor: CTensorHandle, + _: Scalar.Type +) { + assert(TFE_TensorHandleIsConcrete(inputTensor) != 0) + + let array = ShapedArray(cTensorHandle: inputTensor) + debugLog("Rank is \(array.rank), shape is \(array.shape).") + debugLog(""" + The content of the \(array.scalars.count) scalars are: \ + \(array.scalars). + """) +} + +@usableFromInline +internal func dumpCTensorHandleContent(_ idx: Int, _ inputTensorHandle: CTensorHandle) { + if TFE_TensorHandleIsConcrete(inputTensorHandle) == 0 { + debugLog("Skip dumpping a symbolic tensor handle.") + return + } + + let dType: TF_DataType = TFE_TensorHandleDataType(inputTensorHandle) + debugLog("Tensor \(idx) has TF data type \(dType).") + switch dType { + case TF_UINT8: dumpTensorContent(inputTensorHandle, UInt8.self) + case TF_INT8: dumpTensorContent(inputTensorHandle, Int8.self) + case TF_UINT16: dumpTensorContent(inputTensorHandle, UInt16.self) + case TF_INT16: dumpTensorContent(inputTensorHandle, Int16.self) + case TF_UINT32: dumpTensorContent(inputTensorHandle, UInt32.self) + case TF_INT32: dumpTensorContent(inputTensorHandle, Int32.self) + case TF_UINT64: dumpTensorContent(inputTensorHandle, UInt64.self) + case TF_INT64: dumpTensorContent(inputTensorHandle, Int64.self) + case TF_FLOAT: dumpTensorContent(inputTensorHandle, Float.self) + case TF_DOUBLE: dumpTensorContent(inputTensorHandle, Double.self) + case TF_BOOL: dumpTensorContent(inputTensorHandle, Bool.self) + // TODO: Handle `TF_BFloat16`? BFloat16 does not have a host-side + // representation and cannot be printed directly. Consider calling into TF + // runtime. + default: fatalError("Unsupported dtype \(dType)") + } +} + +@inlinable +@_cdecl("_swift_tfc_EagerExecute") +internal func _TFCEagerExecute( + _ op: CTFEOp, + _ retvals: UnsafeMutablePointer, + _ retvalCount: UnsafeMutablePointer, + _ status: CTFStatus +) { + if _RuntimeConfig.printsDebugLog { + debugLog("Calling _TFCEagerExecute() over: ") + if let value = getenv("TF_CPP_MIN_LOG_LEVEL"), + String(cString: value) == "0" { + TFE_OpPrintDebugString(op) + } else { + debugLog("[Run with TF_CPP_MIN_LOG_LEVEL=0 to have TFEOps printed out]") + } + } + if let traceContext = _RuntimeConfig.traceState.context { + // convert this eager op into a trace graph node + debugLog("Adding eager op \(op) to trace graph.") + traceContext.addEagerOpToGraph(op, retvals, retvalCount, status) + checkOk(status) + } else { + debugLog("Executing eager op \(op).") + TFE_Execute(op, retvals, retvalCount, status) + checkOk(status) + } +} + +//===----------------------------------------------------------------------===// +// - MARK: Dynamic compilation (per-op dispatch) entrypoints +//===----------------------------------------------------------------------===// + +@usableFromInline +@_cdecl("_swift_tfc_GetGlobalEagerContext") +func _TFCGetGlobalEagerContext() -> CTFEContext { + debugLog("Calling _GetGlobalEagerContext()") + return _ExecutionContext.global.eagerContext +} + +// Some of the functions are marked with @silgen_name instead of @_cdecl, because their input/output +// data types are not C-compatible (e.g., AnyTensorHandle). + +/// Adds `handle` as an input to `op`. +@usableFromInline +@_silgen_name("_swift_tfc_OpAddInputFromTensorHandle") +func _TFCOpAddInputFromTensorHandle(_ op: CTFEOp, _ handle: _AnyTensorHandle, _ status: CTFStatus) { + TFE_OpAddInput(op, handle._cTensorHandle, status) +} + +/// Adds `t` as an input or inputs to `op`. Returns the number of inputs added. +@usableFromInline +@_silgen_name("_swift_tfc_OpAddInputFromTensorGroup") +func _TFCOpAddInputFromTensorGroup( + _ op: CTFEOp, + _ t: T, + _ status: CTFStatus +) -> Int32 { + let count = t._tensorHandleCount + let buffer = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) + defer { buffer.deallocate() } + t._unpackTensorHandles(into: buffer.baseAddress) + for handle in buffer { + TFE_OpAddInput(op, handle, status) + guard TF_GetCode(status) == TF_OK else { + return 0 + } + } + return count +} + +/// Special protocol for calling tensorflow operations that take heterogeneous arrays as input. +public protocol AnyTensor { + var _rawTensorHandle: CTensorHandle { get } + var _tensorFlowDataType: TensorDataType { get } +} + +@usableFromInline +func _TFCOpAddInputFromAnyTensors(_ op: CTFEOp, _ tensors: [AnyTensor], _ status: CTFStatus) { + for tensor in tensors { + let handle = tensor._rawTensorHandle + TFE_OpAddInput(op, handle, status) + checkOk(status) + } +} + +// _TFCOpSetAttr*Array functions are wrappers around TFE_OpSetAttr*List functions. The wrappers +// handle converting the Swift Stdlib Array values into buffers that TFE_OpSetAttr*List functions +// can read. + +@usableFromInline +@_silgen_name("_swift_tfc_OpSetAttrTypeArray") +func _TFCOpSetAttrTypeArray( + _ op: CTFEOp, + _ attrName: UnsafePointer, + _ value: Array +) { + value.withUnsafeBufferPointer { buffer in + buffer.withMemoryRebound(to: TF_DataType.self) { reboundBuffer in + TFE_OpSetAttrTypeList( + op, attrName, reboundBuffer.baseAddress, Int32(reboundBuffer.count)) + } + } +} + +/// Given dimensions and ranks in the form described below, makes the appropriate call to +/// `TFE_OpSetAttrShapeList(op, attrName, ..., status)`. +/// +/// - Parameters +/// - flattenedDims: all the shapes' dimensions concatenated together in order. +/// - ranks: all the shapes' ranks (-1 denotes unknown rank). +fileprivate func setAttrShapeList( + op: CTFEOp, + attrName: UnsafePointer, + flattenedDims: Array, + ranks: Array, + status: CTFStatus +) { + flattenedDims.withUnsafeBufferPointer { flattenedDimsBuffer in + var dimsPtr: UnsafePointer? = flattenedDimsBuffer.baseAddress + var dims: [UnsafePointer?] = [] + for rank in ranks { + dims.append(dimsPtr) + if rank >= 0 { + dimsPtr = dimsPtr.map { $0.advanced(by: Int(rank)) } + } + } + dims.withUnsafeMutableBufferPointer { dimsBuffer in + ranks.withUnsafeBufferPointer { ranksBuffer in + TFE_OpSetAttrShapeList( + op, attrName, dimsBuffer.baseAddress, ranksBuffer.baseAddress, + Int32(ranksBuffer.count), status) + } + } + } +} + +/// Stack of devices that models nested calls to withDevice/withDefaultDevice. Devices are +/// represented by their names in TensorFlow notation. See documentation for +/// `withDevice(named:perform:)` to learn about device names. +/// +/// All TensorFlow operations will be put on the topmost device on the stack. When the stack is +/// empty or the topmost device is `nil`, that allows TensorFlow to place operations on any device +/// that it sees fit. +@usableFromInline +class _ThreadLocalState { + var deviceScopes: [String?] = [] + + private static let key: pthread_key_t = { + var key = pthread_key_t() + pthread_key_create(&key) { +#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) + let _: AnyObject = Unmanaged.fromOpaque($0).takeRetainedValue() +#else + let _: AnyObject = Unmanaged.fromOpaque($0!).takeRetainedValue() +#endif + } + return key + }() + + var _currentDevice: String? { + return deviceScopes.last ?? nil + } + + @usableFromInline + func pushDevice(_ device: String?) { + deviceScopes.append(device) + } + + @usableFromInline + func popDevice() { + internalConsistencyCheck(deviceScopes.popLast() != nil) + } + + @usableFromInline + static var local: _ThreadLocalState { + if let state = pthread_getspecific(key) { + return Unmanaged.fromOpaque(state).takeUnretainedValue() + } + let state = _ThreadLocalState() + pthread_setspecific(key, Unmanaged.passRetained(state).toOpaque()) + return state + } +} + +@usableFromInline +@_cdecl("_swift_tfc_OpSetDeviceFromScope") +func _TFCOpSetDeviceFromScope(_ op: CTFEOp, _ status: CTFStatus) { + if let deviceName = _ExecutionContext.global.currentDeviceName { + TFE_OpSetDevice(op, deviceName, status) + } +} diff --git a/Sources/DeepLearning/Core/Utilities.swift b/Sources/DeepLearning/Core/Utilities.swift new file mode 100644 index 000000000..e9fa78fb0 --- /dev/null +++ b/Sources/DeepLearning/Core/Utilities.swift @@ -0,0 +1,169 @@ +// Copyright 2018 The TensorFlow Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +import Darwin +#else +import Glibc +#endif + +import CTensorFlow + +//===------------------------------------------------------------------------------------------===// +// Runtime Checkers +//===------------------------------------------------------------------------------------------===// + +/// These checks run in both debug and release modes (while assert() only runs in debug mode), to +/// help shake out more bugs and facilitate debugging in the early project phases. It can be +/// replaced with plain assert() later, when we have a more mature code base. +@usableFromInline +internal func internalConsistencyCheck( + _ predicate: Bool, + _ errMessage: String = "TF runtime assertion failure", + file: StaticString = #file, + line: UInt = #line +) { + guard predicate else { + fatalError(errMessage, file: file, line: line) + } +} + +@usableFromInline +internal func checkOk( + _ s: CTFStatus?, + file: StaticString = #file, + line: UInt = #line +) { + internalConsistencyCheck( + TF_GetCode(s) == TF_OK, + String(cString: TF_Message(s)), + file: file, + line: line) +} + +//===------------------------------------------------------------------------------------------===// +// Type Aliases +//===------------------------------------------------------------------------------------------===// + +// Before assigning a C pointer to one of the pointer type aliases below, caller should check that +// the pointer is not NULL. + +/// The `TF_Session *` type. +@usableFromInline +internal typealias CTFSession = OpaquePointer + +/// The `TF_Status *` type. +@usableFromInline +internal typealias CTFStatus = OpaquePointer + +/// The `TF_Graph*` type. +@usableFromInline +internal typealias CTFGraph = OpaquePointer + +/// The `TF_Function*` type. +@usableFromInline +internal typealias CTFFunction = OpaquePointer + +/// The `TF_Tensor *` type. +@usableFromInline +internal typealias CTensor = OpaquePointer + +/// The `TF_TensorHandle *` type. +/// +/// - Note: This is public so that compiler generated code can read/write tensor handles when +/// calling runtime APIs. +public typealias CTensorHandle = OpaquePointer + +/// The `TFE_Context *` type. +@usableFromInline +internal typealias CTFEContext = OpaquePointer + +/// The `TFE_Op *` type. +@usableFromInline +internal typealias CTFEOp = OpaquePointer + +/// The `TF_OperationDescription *` type. +@usableFromInline +internal typealias CTFOperationDescription = OpaquePointer + +/// The `TFE_TraceContext *` type. +@usableFromInline +internal typealias CTFETraceContext = OpaquePointer + +//===------------------------------------------------------------------------------------------===// +// Logging +//===------------------------------------------------------------------------------------------===// + +#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +@usableFromInline internal let stderr = __stderrp +@usableFromInline internal let stdout = __stdoutp +#endif + +/// Log to standard error. +@usableFromInline +internal func logToStderr(_ message: StaticString) { + message.utf8Start.withMemoryRebound(to: Int8.self, capacity: message.utf8CodeUnitCount) { + _ = fputs($0, stderr) + } +} + +/// Log to standard error. +@usableFromInline +internal func logToStderr(_ message: String) { + _ = fputs(message, stderr) +} + +@usableFromInline +internal func debugLog( + _ message: @autoclosure () -> String, + file: StaticString = #file, + line: UInt = #line +) { + if _RuntimeConfig.printsDebugLog { + print("[\(file):\(line)] \(message())") + // This helps dump more log before a crash. + fflush(stdout) + } +} + +//===------------------------------------------------------------------------------------------===// +// File Writing +//===------------------------------------------------------------------------------------------===// + +/// Given the address of a `TF_Buffer` and a file path, write the buffer's contents to the file. +@usableFromInline +internal func writeContents(of buffer: UnsafePointer, toFile path: String) { + let fp = fopen(path, "w+") + fwrite(buffer.pointee.data, /*size*/ 1, /*count*/ buffer.pointee.length, fp) + fclose(fp) +} + +//===------------------------------------------------------------------------------------------===// +// Unit Test Utilities +//===------------------------------------------------------------------------------------------===// + +// TODO: Consider revising the call sites where this is necessary to only need UnsafeMutablePointer +// to optional when it is the actual c-api call site. +extension UnsafeMutablePointer where Pointee == CTensorHandle? { + @usableFromInline + init(_ other: UnsafeMutablePointer) { + self.init(other._rawValue) + } + + @usableFromInline + init?(_ other: UnsafeMutablePointer?) { + guard let unwrapped = other else { return nil } + self.init(unwrapped) + } +} From 457ce1af0c54098193cb17604360d8778eaec83f Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 18:35:14 -0400 Subject: [PATCH 07/14] Minor edit. --- Sources/DeepLearning/Core/Runtime.swift | 84 ++++++++++++------------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/Sources/DeepLearning/Core/Runtime.swift b/Sources/DeepLearning/Core/Runtime.swift index b80ae90e8..f6f8d70f2 100644 --- a/Sources/DeepLearning/Core/Runtime.swift +++ b/Sources/DeepLearning/Core/Runtime.swift @@ -1050,48 +1050,48 @@ internal extension _ExecutionContext { } } -@usableFromInline -internal func dumpTensorContent( - _ inputTensor: CTensorHandle, - _: Scalar.Type -) { - assert(TFE_TensorHandleIsConcrete(inputTensor) != 0) - - let array = ShapedArray(cTensorHandle: inputTensor) - debugLog("Rank is \(array.rank), shape is \(array.shape).") - debugLog(""" - The content of the \(array.scalars.count) scalars are: \ - \(array.scalars). - """) -} - -@usableFromInline -internal func dumpCTensorHandleContent(_ idx: Int, _ inputTensorHandle: CTensorHandle) { - if TFE_TensorHandleIsConcrete(inputTensorHandle) == 0 { - debugLog("Skip dumpping a symbolic tensor handle.") - return - } - - let dType: TF_DataType = TFE_TensorHandleDataType(inputTensorHandle) - debugLog("Tensor \(idx) has TF data type \(dType).") - switch dType { - case TF_UINT8: dumpTensorContent(inputTensorHandle, UInt8.self) - case TF_INT8: dumpTensorContent(inputTensorHandle, Int8.self) - case TF_UINT16: dumpTensorContent(inputTensorHandle, UInt16.self) - case TF_INT16: dumpTensorContent(inputTensorHandle, Int16.self) - case TF_UINT32: dumpTensorContent(inputTensorHandle, UInt32.self) - case TF_INT32: dumpTensorContent(inputTensorHandle, Int32.self) - case TF_UINT64: dumpTensorContent(inputTensorHandle, UInt64.self) - case TF_INT64: dumpTensorContent(inputTensorHandle, Int64.self) - case TF_FLOAT: dumpTensorContent(inputTensorHandle, Float.self) - case TF_DOUBLE: dumpTensorContent(inputTensorHandle, Double.self) - case TF_BOOL: dumpTensorContent(inputTensorHandle, Bool.self) - // TODO: Handle `TF_BFloat16`? BFloat16 does not have a host-side - // representation and cannot be printed directly. Consider calling into TF - // runtime. - default: fatalError("Unsupported dtype \(dType)") - } -} +// @usableFromInline +// internal func dumpTensorContent( +// _ inputTensor: CTensorHandle, +// _: Scalar.Type +// ) { +// assert(TFE_TensorHandleIsConcrete(inputTensor) != 0) + +// let array = ShapedArray(cTensorHandle: inputTensor) +// debugLog("Rank is \(array.rank), shape is \(array.shape).") +// debugLog(""" +// The content of the \(array.scalars.count) scalars are: \ +// \(array.scalars). +// """) +// } + +// @usableFromInline +// internal func dumpCTensorHandleContent(_ idx: Int, _ inputTensorHandle: CTensorHandle) { +// if TFE_TensorHandleIsConcrete(inputTensorHandle) == 0 { +// debugLog("Skip dumpping a symbolic tensor handle.") +// return +// } + +// let dType: TF_DataType = TFE_TensorHandleDataType(inputTensorHandle) +// debugLog("Tensor \(idx) has TF data type \(dType).") +// switch dType { +// case TF_UINT8: dumpTensorContent(inputTensorHandle, UInt8.self) +// case TF_INT8: dumpTensorContent(inputTensorHandle, Int8.self) +// case TF_UINT16: dumpTensorContent(inputTensorHandle, UInt16.self) +// case TF_INT16: dumpTensorContent(inputTensorHandle, Int16.self) +// case TF_UINT32: dumpTensorContent(inputTensorHandle, UInt32.self) +// case TF_INT32: dumpTensorContent(inputTensorHandle, Int32.self) +// case TF_UINT64: dumpTensorContent(inputTensorHandle, UInt64.self) +// case TF_INT64: dumpTensorContent(inputTensorHandle, Int64.self) +// case TF_FLOAT: dumpTensorContent(inputTensorHandle, Float.self) +// case TF_DOUBLE: dumpTensorContent(inputTensorHandle, Double.self) +// case TF_BOOL: dumpTensorContent(inputTensorHandle, Bool.self) +// // TODO: Handle `TF_BFloat16`? BFloat16 does not have a host-side +// // representation and cannot be printed directly. Consider calling into TF +// // runtime. +// default: fatalError("Unsupported dtype \(dType)") +// } +// } @inlinable @_cdecl("_swift_tfc_EagerExecute") From 38b25fed8189b8ab1b8e51b71b58b8dede754752 Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 19:35:36 -0400 Subject: [PATCH 08/14] Added back some commented out code. --- Sources/DeepLearning/Core/Runtime.swift | 84 ++++++++++++------------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/Sources/DeepLearning/Core/Runtime.swift b/Sources/DeepLearning/Core/Runtime.swift index f6f8d70f2..b80ae90e8 100644 --- a/Sources/DeepLearning/Core/Runtime.swift +++ b/Sources/DeepLearning/Core/Runtime.swift @@ -1050,48 +1050,48 @@ internal extension _ExecutionContext { } } -// @usableFromInline -// internal func dumpTensorContent( -// _ inputTensor: CTensorHandle, -// _: Scalar.Type -// ) { -// assert(TFE_TensorHandleIsConcrete(inputTensor) != 0) - -// let array = ShapedArray(cTensorHandle: inputTensor) -// debugLog("Rank is \(array.rank), shape is \(array.shape).") -// debugLog(""" -// The content of the \(array.scalars.count) scalars are: \ -// \(array.scalars). -// """) -// } - -// @usableFromInline -// internal func dumpCTensorHandleContent(_ idx: Int, _ inputTensorHandle: CTensorHandle) { -// if TFE_TensorHandleIsConcrete(inputTensorHandle) == 0 { -// debugLog("Skip dumpping a symbolic tensor handle.") -// return -// } - -// let dType: TF_DataType = TFE_TensorHandleDataType(inputTensorHandle) -// debugLog("Tensor \(idx) has TF data type \(dType).") -// switch dType { -// case TF_UINT8: dumpTensorContent(inputTensorHandle, UInt8.self) -// case TF_INT8: dumpTensorContent(inputTensorHandle, Int8.self) -// case TF_UINT16: dumpTensorContent(inputTensorHandle, UInt16.self) -// case TF_INT16: dumpTensorContent(inputTensorHandle, Int16.self) -// case TF_UINT32: dumpTensorContent(inputTensorHandle, UInt32.self) -// case TF_INT32: dumpTensorContent(inputTensorHandle, Int32.self) -// case TF_UINT64: dumpTensorContent(inputTensorHandle, UInt64.self) -// case TF_INT64: dumpTensorContent(inputTensorHandle, Int64.self) -// case TF_FLOAT: dumpTensorContent(inputTensorHandle, Float.self) -// case TF_DOUBLE: dumpTensorContent(inputTensorHandle, Double.self) -// case TF_BOOL: dumpTensorContent(inputTensorHandle, Bool.self) -// // TODO: Handle `TF_BFloat16`? BFloat16 does not have a host-side -// // representation and cannot be printed directly. Consider calling into TF -// // runtime. -// default: fatalError("Unsupported dtype \(dType)") -// } -// } +@usableFromInline +internal func dumpTensorContent( + _ inputTensor: CTensorHandle, + _: Scalar.Type +) { + assert(TFE_TensorHandleIsConcrete(inputTensor) != 0) + + let array = ShapedArray(cTensorHandle: inputTensor) + debugLog("Rank is \(array.rank), shape is \(array.shape).") + debugLog(""" + The content of the \(array.scalars.count) scalars are: \ + \(array.scalars). + """) +} + +@usableFromInline +internal func dumpCTensorHandleContent(_ idx: Int, _ inputTensorHandle: CTensorHandle) { + if TFE_TensorHandleIsConcrete(inputTensorHandle) == 0 { + debugLog("Skip dumpping a symbolic tensor handle.") + return + } + + let dType: TF_DataType = TFE_TensorHandleDataType(inputTensorHandle) + debugLog("Tensor \(idx) has TF data type \(dType).") + switch dType { + case TF_UINT8: dumpTensorContent(inputTensorHandle, UInt8.self) + case TF_INT8: dumpTensorContent(inputTensorHandle, Int8.self) + case TF_UINT16: dumpTensorContent(inputTensorHandle, UInt16.self) + case TF_INT16: dumpTensorContent(inputTensorHandle, Int16.self) + case TF_UINT32: dumpTensorContent(inputTensorHandle, UInt32.self) + case TF_INT32: dumpTensorContent(inputTensorHandle, Int32.self) + case TF_UINT64: dumpTensorContent(inputTensorHandle, UInt64.self) + case TF_INT64: dumpTensorContent(inputTensorHandle, Int64.self) + case TF_FLOAT: dumpTensorContent(inputTensorHandle, Float.self) + case TF_DOUBLE: dumpTensorContent(inputTensorHandle, Double.self) + case TF_BOOL: dumpTensorContent(inputTensorHandle, Bool.self) + // TODO: Handle `TF_BFloat16`? BFloat16 does not have a host-side + // representation and cannot be printed directly. Consider calling into TF + // runtime. + default: fatalError("Unsupported dtype \(dType)") + } +} @inlinable @_cdecl("_swift_tfc_EagerExecute") From e976be78d319406a70a91fb46e230223692ddf17 Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 19:46:01 -0400 Subject: [PATCH 09/14] Fixed some typos. --- .../OperatorTests/BasicTests.swift | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Tests/DeepLearningTests/OperatorTests/BasicTests.swift b/Tests/DeepLearningTests/OperatorTests/BasicTests.swift index 9b17c9ac4..860d87386 100644 --- a/Tests/DeepLearningTests/OperatorTests/BasicTests.swift +++ b/Tests/DeepLearningTests/OperatorTests/BasicTests.swift @@ -419,17 +419,17 @@ final class BasicOperatorTests: XCTestCase { XCTAssertEqual([1, 3, 1, 2, 1], result.shape) } - func testUnbroadcasted1() { + func testUnbroadcast1() { let x = Tensor(repeating: 1, shape: [2, 3, 4, 5]) let y = Tensor(repeating: 1, shape: [4, 5]) - let z = x.unbroadcasted(like: y) + let z = x.unbroadcast(like: y) XCTAssertEqual(ShapedArray(repeating: 6, shape: [4, 5]), z.array) } - func testUnbroadcasted2() { + func testUnbroadcast2() { let x = Tensor(repeating: 1, shape: [2, 3, 4, 5]) let y = Tensor(repeating: 1, shape: [3, 1, 5]) - let z = x.unbroadcasted(like: y) + let z = x.unbroadcast(like: y) XCTAssertEqual(ShapedArray(repeating: 8, shape: [3, 1, 5]), z.array) } @@ -453,7 +453,7 @@ final class BasicOperatorTests: XCTestCase { // 1 -> 2 x 3 x 4 let one = Tensor(1) var target = Tensor(repeating: 0.0, shape: [2, 3, 4]) - let broadcasted = one.broadcasted(like: target) + let broadcasted = one.broadcast(like: target) XCTAssertEqual(Tensor(repeating: 1, shape: [2, 3, 4]), broadcasted) target .= Tensor(repeating: 1, shape: [1, 3, 1]) XCTAssertEqual(Tensor(repeating: 1, shape: [2, 3, 4]), target) @@ -480,8 +480,8 @@ final class BasicOperatorTests: XCTestCase { ("testFlatten0D", testFlatten0D), ("testReshapeToScalar", testReshapeToScalar), ("testReshapeTensor", testReshapeTensor), - ("testUnbroadcasted1", testUnbroadcasted1), - ("testUnbroadcasted2", testUnbroadcasted2), + ("testUnbroadcast1", testUnbroadcast1), + ("testUnbroadcast2", testUnbroadcast2), ("testSliceUpdate", testSliceUpdate), ("testBroadcastTensor", testBroadcastTensor) ] From 3d59b74a2a710e008d2340d2178c9bbb6c5ea466 Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 21:30:36 -0400 Subject: [PATCH 10/14] Fixed a couple of tests. --- Tests/DeepLearningTests/OperatorTests/MathTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/DeepLearningTests/OperatorTests/MathTests.swift b/Tests/DeepLearningTests/OperatorTests/MathTests.swift index 0db5406ed..166a78ed5 100644 --- a/Tests/DeepLearningTests/OperatorTests/MathTests.swift +++ b/Tests/DeepLearningTests/OperatorTests/MathTests.swift @@ -88,8 +88,8 @@ final class MathOperatorTests: XCTestCase { let y = tanh(x) let array = y.array XCTAssertEqual([2], array.shape) - XCTAssertEqual(0.833655, Double(array.scalars[0])) - XCTAssertEqual(0.833655, Double(array.scalars[1])) + XCTAssertEqual(0.833655, Double(array.scalars[0]), accuracy: 0.0001) + XCTAssertEqual(0.833655, Double(array.scalars[1]), accuracy: 0.0001) } func testStandardDeviation() { From d63f5c583a5694e0c1085547ff1b10a3419215d4 Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 23:21:26 -0400 Subject: [PATCH 11/14] Minor edits. --- Sources/DeepLearning/Core/Runtime.swift | 43 +++++++++++++------------ 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/Sources/DeepLearning/Core/Runtime.swift b/Sources/DeepLearning/Core/Runtime.swift index b80ae90e8..e0e0f469d 100644 --- a/Sources/DeepLearning/Core/Runtime.swift +++ b/Sources/DeepLearning/Core/Runtime.swift @@ -138,7 +138,7 @@ internal class TraceContext { } let traceeInputCount = symbolicInputs.count - // Append concrete tensors created within the tracee as symbolic inputs to the generated + // Append concrete tensors created within the tracee as symbolic inputs to the generated // trace graph function. additionalInputTensorCount = TFE_FinalizeInputTensorsFromTraceContext(cTraceContext) for i in 0.. [CTensorHandle] { + func execute(traceeInputs: [_AnyTensorHandle], useXLA: Bool = false) -> [CTensorHandle] { // We must be in the `notTracing` enum mode. internalConsistencyCheck(_RuntimeConfig.traceState.context == nil) internalConsistencyCheck(traceGraphFn != nil) @@ -551,8 +548,7 @@ public final class _ExecutionContext { public let tensorFlowConfig: UnsafeMutablePointer /// The TFE_Context object. - @usableFromInline - internal let eagerContext: CTFEContext + @usableFromInline let eagerContext: CTFEContext /// The status for checking TensorFlow errors. private let status: CTFStatus = TF_NewStatus() @@ -791,8 +787,8 @@ private func _trace( in fn: ([CTensorHandle]) -> [CTensorHandle] ) -> TraceContext { debugLog(""" - Tracing over a function with \(dtypes.count) inputs. - """) + Tracing over a function with \(dtypes.count) inputs. + """) // Verify that we are not already tracing. internalConsistencyCheck(_RuntimeConfig.traceState.context == nil, @@ -820,9 +816,11 @@ private func _trace( return finalizeTraceFunction(opType) } -private func _graphInternal( +private func _graphInternal< + State: _TensorArrayProtocolEnhanced, + Data: TensorGroup, + Result: TensorGroup +>( with state: State, in fn: (State, Data) -> (State, Result?) ) -> (State, Data) -> (State, Result?) { @@ -871,9 +869,7 @@ private func _graphInternal( +public func _graph( with state: State, in fn: (State, Data) -> (State, Result) ) -> (State, Data) -> (State, Result) { @@ -886,16 +882,16 @@ public func _graph( +public func _graph( with state: State, in fn: (State, Data) -> State ) -> (State, Data) -> State { - let graphFunction: (State, Data) -> (State, TensorHandle?) = + let graphFunction: (State, Data) -> (State, Tensor?) = withoutActuallyEscaping(fn) { escapableFn in let wrappedFn = { // The result argument needs to a type that conforms to TensorGroup. - // We are arbitrarily picking TensorHandle here. - (s: State, d: Data) -> (State, TensorHandle?) in + // We are arbitrarily picking Tensor here. + (s: State, d: Data) -> (State, Tensor?) in (escapableFn(s, d), nil) } return _graphInternal(with: state, in: wrappedFn) @@ -1095,7 +1091,7 @@ internal func dumpCTensorHandleContent(_ idx: Int, _ inputTensorHandle: CTensorH @inlinable @_cdecl("_swift_tfc_EagerExecute") -internal func _TFCEagerExecute( +func _TFCEagerExecute( _ op: CTFEOp, _ retvals: UnsafeMutablePointer, _ retvalCount: UnsafeMutablePointer, @@ -1170,6 +1166,11 @@ public protocol AnyTensor { var _tensorFlowDataType: TensorDataType { get } } +extension Tensor: AnyTensor { + public var _rawTensorHandle: CTensorHandle { return handle._cTensorHandle } + public var _tensorFlowDataType: TensorDataType { return Scalar.tensorFlowDataType } +} + @usableFromInline func _TFCOpAddInputFromAnyTensors(_ op: CTFEOp, _ tensors: [AnyTensor], _ status: CTFStatus) { for tensor in tensors { From 6cc2301b6b5e6868c3112d79d77fd764925575dd Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 23:22:20 -0400 Subject: [PATCH 12/14] Minor edit. --- Sources/DeepLearning/Core/Runtime.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Sources/DeepLearning/Core/Runtime.swift b/Sources/DeepLearning/Core/Runtime.swift index e0e0f469d..75351df6d 100644 --- a/Sources/DeepLearning/Core/Runtime.swift +++ b/Sources/DeepLearning/Core/Runtime.swift @@ -1114,7 +1114,6 @@ func _TFCEagerExecute( } else { debugLog("Executing eager op \(op).") TFE_Execute(op, retvals, retvalCount, status) - checkOk(status) } } From 0628d783b14b9484786b01c831e8dd67a99896e4 Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 23:44:59 -0400 Subject: [PATCH 13/14] Commented out a couple of the dataset tests. --- .../OperatorTests/DatasetTests.swift | 43 ++++++++++--------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/Tests/DeepLearningTests/OperatorTests/DatasetTests.swift b/Tests/DeepLearningTests/OperatorTests/DatasetTests.swift index 54f413e50..10c67b75b 100644 --- a/Tests/DeepLearningTests/OperatorTests/DatasetTests.swift +++ b/Tests/DeepLearningTests/OperatorTests/DatasetTests.swift @@ -83,27 +83,28 @@ final class DatasetTests: XCTestCase { XCTAssertEqual([0, 4, 1, 3, 2], shuffled.map { $0.scalar! }) } - func testSingleValueHOFs() { - let scalars = Tensor(rangeFrom: 0, to: 5, stride: 1) - let dataset = Dataset(elements: scalars) - let addedOne: Dataset = dataset.map { $0 + 1 } - XCTAssertEqual([1, 2, 3, 4, 5], addedOne.flatMap { $0.scalars }) - // Use '.==' in the following closure to avoid any conversions to - // host data types, which is not handled correctly in tracing. - let evens: Dataset = dataset.filter { Tensor($0 % 2) .== Tensor(0) } - XCTAssertEqual([0, 2, 4], evens.flatMap { $0.scalars }) - } - - func testParallelMap() { - let scalars = Tensor(rangeFrom: 0, to: 5, stride: 1) - let dataset = Dataset(elements: scalars) - let addedOne: Dataset = dataset.map(parallelCallCount: 5) { $0 + 1 } - XCTAssertEqual([1, 2, 3, 4, 5], addedOne.flatMap { $0.scalars }) - // Use '.==' in the following closure to avoid any conversions to - // host data types, which is not handled correctly in tracing. - let evens: Dataset = dataset.filter { Tensor($0 % 2) .== Tensor(0) } - XCTAssertEqual([0, 2, 4], evens.flatMap { $0.scalars }) - } + // TODO: Uncomment these two tests. + // func testSingleValueHOFs() { + // let scalars = Tensor(rangeFrom: 0, to: 5, stride: 1) + // let dataset = Dataset(elements: scalars) + // let addedOne: Dataset = dataset.map { $0 + 1 } + // XCTAssertEqual([1, 2, 3, 4, 5], addedOne.flatMap { $0.scalars }) + // // Use '.==' in the following closure to avoid any conversions to + // // host data types, which is not handled correctly in tracing. + // let evens: Dataset = dataset.filter { Tensor($0 % 2) .== Tensor(0) } + // XCTAssertEqual([0, 2, 4], evens.flatMap { $0.scalars }) + // } + // + // func testParallelMap() { + // let scalars = Tensor(rangeFrom: 0, to: 5, stride: 1) + // let dataset = Dataset(elements: scalars) + // let addedOne: Dataset = dataset.map(parallelCallCount: 5) { $0 + 1 } + // XCTAssertEqual([1, 2, 3, 4, 5], addedOne.flatMap { $0.scalars }) + // // Use '.==' in the following closure to avoid any conversions to + // // host data types, which is not handled correctly in tracing. + // let evens: Dataset = dataset.filter { Tensor($0 % 2) .== Tensor(0) } + // XCTAssertEqual([0, 2, 4], evens.flatMap { $0.scalars }) + // } func testMapToDifferentType() { let scalars = Tensor(rangeFrom: 0, to: 5, stride: 1) From 65bbc83b3ba534c7c6f3fddf56afdebabe4960fd Mon Sep 17 00:00:00 2001 From: Anthony Platanios Date: Tue, 28 May 2019 23:55:19 -0400 Subject: [PATCH 14/14] Uncommented out some of the dataset tests. --- .../OperatorTests/DatasetTests.swift | 43 +++++++++---------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/Tests/DeepLearningTests/OperatorTests/DatasetTests.swift b/Tests/DeepLearningTests/OperatorTests/DatasetTests.swift index 10c67b75b..54f413e50 100644 --- a/Tests/DeepLearningTests/OperatorTests/DatasetTests.swift +++ b/Tests/DeepLearningTests/OperatorTests/DatasetTests.swift @@ -83,28 +83,27 @@ final class DatasetTests: XCTestCase { XCTAssertEqual([0, 4, 1, 3, 2], shuffled.map { $0.scalar! }) } - // TODO: Uncomment these two tests. - // func testSingleValueHOFs() { - // let scalars = Tensor(rangeFrom: 0, to: 5, stride: 1) - // let dataset = Dataset(elements: scalars) - // let addedOne: Dataset = dataset.map { $0 + 1 } - // XCTAssertEqual([1, 2, 3, 4, 5], addedOne.flatMap { $0.scalars }) - // // Use '.==' in the following closure to avoid any conversions to - // // host data types, which is not handled correctly in tracing. - // let evens: Dataset = dataset.filter { Tensor($0 % 2) .== Tensor(0) } - // XCTAssertEqual([0, 2, 4], evens.flatMap { $0.scalars }) - // } - // - // func testParallelMap() { - // let scalars = Tensor(rangeFrom: 0, to: 5, stride: 1) - // let dataset = Dataset(elements: scalars) - // let addedOne: Dataset = dataset.map(parallelCallCount: 5) { $0 + 1 } - // XCTAssertEqual([1, 2, 3, 4, 5], addedOne.flatMap { $0.scalars }) - // // Use '.==' in the following closure to avoid any conversions to - // // host data types, which is not handled correctly in tracing. - // let evens: Dataset = dataset.filter { Tensor($0 % 2) .== Tensor(0) } - // XCTAssertEqual([0, 2, 4], evens.flatMap { $0.scalars }) - // } + func testSingleValueHOFs() { + let scalars = Tensor(rangeFrom: 0, to: 5, stride: 1) + let dataset = Dataset(elements: scalars) + let addedOne: Dataset = dataset.map { $0 + 1 } + XCTAssertEqual([1, 2, 3, 4, 5], addedOne.flatMap { $0.scalars }) + // Use '.==' in the following closure to avoid any conversions to + // host data types, which is not handled correctly in tracing. + let evens: Dataset = dataset.filter { Tensor($0 % 2) .== Tensor(0) } + XCTAssertEqual([0, 2, 4], evens.flatMap { $0.scalars }) + } + + func testParallelMap() { + let scalars = Tensor(rangeFrom: 0, to: 5, stride: 1) + let dataset = Dataset(elements: scalars) + let addedOne: Dataset = dataset.map(parallelCallCount: 5) { $0 + 1 } + XCTAssertEqual([1, 2, 3, 4, 5], addedOne.flatMap { $0.scalars }) + // Use '.==' in the following closure to avoid any conversions to + // host data types, which is not handled correctly in tracing. + let evens: Dataset = dataset.filter { Tensor($0 % 2) .== Tensor(0) } + XCTAssertEqual([0, 2, 4], evens.flatMap { $0.scalars }) + } func testMapToDifferentType() { let scalars = Tensor(rangeFrom: 0, to: 5, stride: 1)