Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[wasm] Add Diag kernel #7277

Merged
merged 3 commits into from
Jan 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions tfjs-backend-wasm/src/cc/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,15 @@ tfjs_unit_test(
],
)

tfjs_cc_library(
name = "Diag",
srcs = ["kernels/Diag.cc"],
deps = [
":backend",
":util",
],
)

tfjs_cc_library(
name = "RealDiv",
srcs = ["kernels/RealDiv.cc"],
Expand Down
71 changes: 71 additions & 0 deletions tfjs-backend-wasm/src/cc/kernels/Diag.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* @license
* Copyright 2023 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
*
* 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.
* =============================================================================
*/

#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif

#include <algorithm>
#include <cmath>

#include "tfjs-backend-wasm/src/cc/backend.h"
#include "tfjs-backend-wasm/src/cc/util.h"

namespace tfjs {
namespace wasm {

namespace {

template <typename T>
inline void DiagImpl(const T* x_buf, int32_t x_size, T* out_buf) {
std::fill(out_buf, out_buf + x_size * x_size, 0);
for (int32_t i = 0; i < x_size; ++i) {
out_buf[x_size * i + i] = x_buf[i];
}
}
Comment on lines +34 to +39
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a really nice implementation. For a while, I thought you'd have to do a lot of index calculations to account for diagonals of different dimensions, but that's not the case.

For some k dimensional tensor,

output[i1,..., ik, i1,..., ik] = diagonal[i1, ..., ik]

But the index in the tensor's data array that i1,..., ik corresponds to is some unique number d. Then, we just have

output[d, d] = diagonal[d]

for all d in the input, and this is just

out_buf[x_size * d + d] = x_buf[d]


} // namespace

// We use C-style API to interface with Javascript.
extern "C" {

#ifdef __EMSCRIPTEN__
EMSCRIPTEN_KEEPALIVE
#endif
void Diag(const int32_t x_id, const DType dtype, const int32_t x_size,
const int32_t out_id) {
const TensorInfo& x_info = backend::get_tensor_info(x_id);
TensorInfo& out_info = backend::get_tensor_info_out(out_id);
switch (dtype) {
case DType::float32:
DiagImpl(x_info.f32(), x_size, out_info.f32_write());
break;
case DType::int32:
DiagImpl(x_info.i32(), x_size, out_info.i32_write());
break;
case DType::boolean:
DiagImpl(x_info.b(), x_size, out_info.b_write());
break;
default:
util::warn("Diag for tensor id %d failed. Unsupported dtype %d", x_id,
dtype);
}
}

} // extern "C"
} // namespace wasm
} // namespace tfjs
55 changes: 55 additions & 0 deletions tfjs-backend-wasm/src/kernels/Diag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* @license
* Copyright 2023 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
*
* 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 {Diag, DiagInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';

import {BackendWasm} from '../backend_wasm';

import {CppDType} from './types';

let wasmDiag: (xId: number, xDType: CppDType, xSize: number, outId: number) =>
void;

function setup(backend: BackendWasm) {
wasmDiag = backend.wasm.cwrap('Diag', null, [
'number', // xId
'number', // xDType,
'number', // xSize,
'number', // outId
]);
}

export function diag(args: {inputs: DiagInputs, backend: BackendWasm}):
TensorInfo {
const {inputs, backend} = args;
const {x} = inputs;

const xSize = util.sizeFromShape(x.shape);
const out = backend.makeOutput([...x.shape, ...x.shape], x.dtype);

wasmDiag(
backend.dataIdMap.get(x.dataId).id, CppDType[x.dtype], xSize,
backend.dataIdMap.get(out.dataId).id);
return out;
}

export const diagConfig: KernelConfig = {
kernelName: Diag,
backendName: 'wasm',
setupFunc: setup,
kernelFunc: diag as unknown as KernelFunc
};
2 changes: 2 additions & 0 deletions tfjs-backend-wasm/src/register_all_kernels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {cumprodConfig} from './kernels/Cumprod';
import {cumsumConfig} from './kernels/Cumsum';
import {depthToSpaceConfig} from './kernels/DepthToSpace';
import {depthwiseConv2dNativeConfig} from './kernels/DepthwiseConv2dNative';
import {diagConfig} from './kernels/Diag';
import {eluConfig} from './kernels/Elu';
import {equalConfig} from './kernels/Equal';
import {expConfig} from './kernels/Exp';
Expand Down Expand Up @@ -166,6 +167,7 @@ const kernelConfigs: KernelConfig[] = [
cumsumConfig,
depthToSpaceConfig,
depthwiseConv2dNativeConfig,
diagConfig,
eluConfig,
equalConfig,
expConfig,
Expand Down
1 change: 1 addition & 0 deletions tfjs-backend-wasm/src/setup_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,7 @@ const TEST_FILTERS: TestFilter[] = [
{include: 'acosh '},
{include: 'asin '},
{include: 'asinh '},
{include: 'diag '},
];

const customInclude = (testName: string) => {
Expand Down