|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2021 Google LLC. All Rights Reserved. |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + * ============================================================================= |
| 16 | + */ |
| 17 | + |
| 18 | +import {KernelConfig, KernelFunc, TensorInfo, Unpack, UnpackAttrs, UnpackInputs} from '@tensorflow/tfjs-core'; |
| 19 | + |
| 20 | +import {WebGPUBackend} from '../backend_webgpu'; |
| 21 | + |
| 22 | +import {reshape} from './Reshape'; |
| 23 | +import {slice} from './Slice'; |
| 24 | + |
| 25 | +export function unpack( |
| 26 | + args: |
| 27 | + {inputs: UnpackInputs, backend: WebGPUBackend, attrs: UnpackAttrs}): |
| 28 | + TensorInfo[] { |
| 29 | + const {inputs, backend, attrs} = args; |
| 30 | + const {value} = inputs; |
| 31 | + let {axis} = attrs; |
| 32 | + |
| 33 | + if (axis < 0) { |
| 34 | + axis += value.shape.length; |
| 35 | + } |
| 36 | + |
| 37 | + const x = value; |
| 38 | + const xRank = x.shape.length; |
| 39 | + |
| 40 | + const num = value.shape[axis]; |
| 41 | + const outShape: number[] = new Array(xRank - 1); |
| 42 | + let outIndex = 0; |
| 43 | + for (let i = 0; i < xRank; i++) { |
| 44 | + if (i !== axis) { |
| 45 | + outShape[outIndex++] = x.shape[i]; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + const toDispose = []; |
| 50 | + |
| 51 | + const begin = new Array(xRank).fill(0); |
| 52 | + const size = x.shape.slice(); |
| 53 | + size[axis] = 1; |
| 54 | + const res: TensorInfo[] = new Array(num); |
| 55 | + for (let i = 0; i < res.length; i++) { |
| 56 | + begin[axis] = i; |
| 57 | + const sliced = slice({inputs: {x}, backend, attrs: {begin, size}}); |
| 58 | + const reshaped = |
| 59 | + reshape({inputs: {x: sliced}, backend, attrs: {shape: outShape}}); |
| 60 | + res[i] = reshaped; |
| 61 | + |
| 62 | + toDispose.push(sliced); |
| 63 | + } |
| 64 | + |
| 65 | + toDispose.forEach(t => backend.disposeData(t.dataId)); |
| 66 | + return res; |
| 67 | +} |
| 68 | + |
| 69 | +export const unpackConfig: KernelConfig = { |
| 70 | + kernelName: Unpack, |
| 71 | + backendName: 'webgpu', |
| 72 | + kernelFunc: unpack as {} as KernelFunc |
| 73 | +}; |
0 commit comments