-
Notifications
You must be signed in to change notification settings - Fork 2k
[core]Modularize addN. #3002
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
[core]Modularize addN. #3002
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a24796a
[core]Modularize addN.
lina128 a179acc
Separate out gradient.
lina128 b30595a
.
lina128 cf42795
Add a boolean flag to gradConfig to save all inputs to handle inputs …
lina128 f5db7da
Add tests.
lina128 8f612bc
Add more restriction to the flag.
lina128 d4fd3c9
.
lina128 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| /** | ||
| * @license | ||
| * Copyright 2020 Google Inc. 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 {AddN} from '../kernel_names'; | ||
| import {GradConfig} from '../kernel_registry'; | ||
| import {Tensor} from '../tensor'; | ||
|
|
||
| export const addNGradConfig: GradConfig = { | ||
| kernelName: AddN, | ||
| saveAllInputs: true, | ||
| gradFunc: (dy: Tensor, saved: Tensor[]) => { | ||
| const ders: {[key: string]: () => Tensor} = {}; | ||
| saved.forEach((_, i) => { | ||
| ders[i] = () => dy.clone(); | ||
| }); | ||
| return ders; | ||
| } | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| /** | ||
| * @license | ||
| * Copyright 2020 Google Inc. 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 {ENGINE, ForwardFunc} from '../engine'; | ||
| import {AddNInputs} from '../kernel_names'; | ||
| import {Tensor} from '../tensor'; | ||
| import {NamedTensorMap} from '../tensor_types'; | ||
| import {convertToTensor} from '../tensor_util_env'; | ||
| import {TensorLike} from '../types'; | ||
| import * as util from '../util'; | ||
|
|
||
| import {op} from './operation'; | ||
|
|
||
| /** | ||
| * Adds a list of `tf.Tensor`s element-wise, each with the same shape and dtype. | ||
| * | ||
| * ```js | ||
| * const a = tf.tensor1d([1, 2]); | ||
| * const b = tf.tensor1d([3, 4]); | ||
| * const c = tf.tensor1d([5, 6]); | ||
| * | ||
| * tf.addN([a, b, c]).print(); | ||
| * ``` | ||
| * @param tensors A list of tensors with the same shape and dtype. | ||
| */ | ||
| /** @doc {heading: 'Operations', subheading: 'Arithmetic'} */ | ||
| function addN_<T extends Tensor>(tensors: Array<T|TensorLike>): T { | ||
| util.assert( | ||
| Array.isArray(tensors), | ||
| () => 'The argument passed to tf.addN() must be a list of tensors'); | ||
| util.assert( | ||
| tensors.length >= 1, | ||
| () => `Must pass at least one tensor to tf.addN(), but got ` + | ||
| `${tensors.length}`); | ||
|
|
||
| const $tensors = | ||
| tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'addN')); | ||
|
|
||
| const firstTensor = $tensors[0]; | ||
| $tensors.forEach(t => { | ||
| if (t.dtype !== firstTensor.dtype) { | ||
| throw new Error( | ||
| 'All tensors passed to tf.addN() must have the same dtype'); | ||
| } | ||
| }); | ||
|
|
||
| $tensors.forEach(t => { | ||
| if (!util.arraysEqual(t.shape, firstTensor.shape)) { | ||
| throw new Error( | ||
| 'All tensors passed to tf.addN() must have the same shape'); | ||
| } | ||
| }); | ||
|
|
||
| const forward: ForwardFunc<Tensor> = (backend, save) => | ||
| backend.addN($tensors); | ||
|
|
||
| const inputs: AddNInputs = $tensors; | ||
|
|
||
| return ENGINE.runKernelFunc( | ||
| forward, inputs as {} as NamedTensorMap, null /* grad */, | ||
| 'AddN') as T; | ||
| } | ||
|
|
||
| export const addN = op({addN_}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| /** | ||
| * @license | ||
| * Copyright 2020 Google Inc. 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 * as tf from '../index'; | ||
| import {ALL_ENVS, describeWithFlags} from '../jasmine_util'; | ||
| import {expectArraysClose} from '../test_util'; | ||
|
|
||
| describeWithFlags('addN', ALL_ENVS, () => { | ||
| it('a single tensor', async () => { | ||
| const res = tf.addN([tf.tensor1d([1, 2, 3])]); | ||
| expectArraysClose(await res.data(), [1, 2, 3]); | ||
| }); | ||
|
|
||
| it('two tensors, int32', async () => { | ||
| const res = tf.addN([ | ||
| tf.tensor1d([1, 2, -1], 'int32'), | ||
| tf.tensor1d([5, 3, 2], 'int32'), | ||
| ]); | ||
| expectArraysClose(await res.data(), [6, 5, 1]); | ||
| expect(res.dtype).toBe('int32'); | ||
| expect(res.shape).toEqual([3]); | ||
| }); | ||
|
|
||
| it('three tensors', async () => { | ||
| const res = tf.addN([ | ||
| tf.tensor1d([1, 2]), | ||
| tf.tensor1d([5, 3]), | ||
| tf.tensor1d([-5, -2]), | ||
| ]); | ||
| expectArraysClose(await res.data(), [1, 3]); | ||
| expect(res.dtype).toBe('float32'); | ||
| expect(res.shape).toEqual([2]); | ||
| }); | ||
|
|
||
| it('accepts a tensor-like object', async () => { | ||
| const res = tf.addN([[1, 2], [3, 4]]); | ||
| expectArraysClose(await res.data(), [4, 6]); | ||
| expect(res.dtype).toBe('float32'); | ||
| expect(res.shape).toEqual([2]); | ||
| }); | ||
|
|
||
| it('list of numbers gets treated as a list of scalars', async () => { | ||
| const res = tf.addN([1, 2, 3, 4]); | ||
| expectArraysClose(await res.data(), [10]); | ||
| expect(res.dtype).toBe('float32'); | ||
| expect(res.shape).toEqual([]); | ||
| }); | ||
|
|
||
| it('errors if list is empty', () => { | ||
| expect(() => tf.addN([])) | ||
| .toThrowError( | ||
| /Must pass at least one tensor to tf.addN\(\), but got 0/); | ||
| }); | ||
|
|
||
| it('errors if argument is not an array', () => { | ||
| // tslint:disable-next-line:no-any | ||
| expect(() => tf.addN(tf.scalar(3) as any)) | ||
| .toThrowError( | ||
| /The argument passed to tf.addN\(\) must be a list of tensors/); | ||
| }); | ||
|
|
||
| it('errors if arguments not of same dtype', () => { | ||
| expect(() => tf.addN([tf.scalar(1, 'int32'), tf.scalar(2, 'float32')])) | ||
| .toThrowError( | ||
| /All tensors passed to tf.addN\(\) must have the same dtype/); | ||
| }); | ||
|
|
||
| it('errors if arguments not of same shape', () => { | ||
| expect(() => tf.addN([tf.scalar(1), tf.tensor1d([2])])) | ||
| .toThrowError( | ||
| /All tensors passed to tf.addN\(\) must have the same shape/); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We need to have an exception here, AddNInputs is an array of Tensors. We don't have a fixed number of Tensors, so we cannot use NamedTensorInfoMap. Cast this input as NamedTensorMap and use it later is fine, because array is basically an object with index as key, this array can use all the Object apis.