This repository has been archived by the owner on Aug 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 950
Add basic types and helper methods for model exporting #990
Merged
Merged
Changes from 4 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
a3fba36
Add basic types and helper methods for model exporting
caisq d1a03ab
WIP1
caisq 711365f
WIP2
caisq fae4217
Merge branch 'master' into save-model-2
caisq 52a7e4c
Merge branch 'master' into save-model-2
caisq 4172414
Respond to review comments
caisq 748daa6
Export SaveConfig for layer use
caisq a70d3a0
Respond to further review comments.
caisq 012c7fc
Merge branch 'master' of github.com:caisq/deeplearnjs into save-model-2
caisq b2cd37b
Add not-implemented Error for quantization in decodeWeights
caisq f9f28a1
Add missing bool field to DTYPE_VALUE_SIZE_MAP
caisq eeae1db
Move serialization related types and functions to tf.io.*
caisq ac3eb47
Respond to Daniel's comment
caisq 0ea20f0
Delete unintended file
caisq 4b8d53d
fix typo
caisq 8fa5841
Merge branch 'master' into save-model-2
caisq 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 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 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,136 @@ | ||
/** | ||
* @license | ||
* Copyright 2018 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 {tensor} from '../index'; | ||
import {Tensor} from '../tensor'; | ||
import {NamedTensorMap} from '../types'; | ||
import {WeightsManifestEntry} from './types'; | ||
|
||
/** | ||
* Encode a map from names to Tensors as an ArrayBuffer. | ||
* | ||
* @param tensors A map ("dict") from names to tensors. | ||
* @returns A `Promise` of | ||
* - A flat `ArrayBuffer` with all the binary values of the `Tensor`s | ||
* concatenated. | ||
* - An `Array` of `WeightManifestEntry`s, carrying information including | ||
* tensor names, `dtype`s and shapes. | ||
* @throws Error: on unsupported tensor `dtype`. | ||
*/ | ||
export async function encodeTensors(tensors: NamedTensorMap): | ||
Promise<[ArrayBuffer, WeightsManifestEntry[]]> { | ||
const specs: WeightsManifestEntry[] = []; | ||
const dataPromises: Array<Promise<Float32Array|Int32Array|Uint8Array>> = []; | ||
for (const name in tensors) { | ||
const tensor = tensors[name]; | ||
|
||
if (tensor.dtype !== 'float32' && tensor.dtype !== 'int32' && | ||
tensor.dtype !== 'bool') { | ||
throw new Error(`Unsupported dtype: ${tensor.dtype}`); | ||
} | ||
specs.push({name, shape: tensor.shape, dtype: tensor.dtype}); | ||
dataPromises.push(tensor.data()); | ||
} | ||
const tensorValues = await Promise.all(dataPromises); | ||
return [concatenateTypedArrays(tensorValues), specs]; | ||
} | ||
|
||
/** | ||
* Decode flat ArrayBuffer as named Tensors. | ||
* | ||
* @param buffer A flat ArrayBuffer carrying the binary values of the tensors | ||
* concatenated in the order specified in `specs`. | ||
* @param specs Specifications of the names, dtypes and shapes of the tensors | ||
* whose value are encoded by `buffer`. | ||
* @return A map from tensor name to tensor value, with the names corresponding | ||
* to names in `specs`. | ||
* @throws Error, if any of the tensors has unsupported dtype. | ||
*/ | ||
export function decodeTensors( | ||
buffer: ArrayBuffer, specs: WeightsManifestEntry[]): NamedTensorMap { | ||
const out: NamedTensorMap = {}; | ||
let offset = 0; | ||
for (const spec of specs) { | ||
const name = spec.name; | ||
const dtype = spec.dtype; | ||
const shape = spec.shape; | ||
|
||
let numel = 1; | ||
for (const dim of shape) { | ||
numel *= dim; | ||
} | ||
let bytes: number; | ||
let value: Tensor; | ||
if (dtype === 'float32') { | ||
bytes = numel * 4; | ||
value = tensor(new Float32Array(buffer, offset, numel), shape, 'float32'); | ||
} else if (dtype === 'int32') { | ||
bytes = numel * 4; | ||
value = tensor(new Int32Array(buffer, offset, numel), shape, 'int32'); | ||
} else if (dtype === 'bool') { | ||
bytes = numel; | ||
value = tensor(new Uint8Array(buffer, offset, numel), shape, 'bool'); | ||
} else { | ||
throw new Error(`Unsupported dtype: ${dtype}`); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As above, please include the name fields as well. |
||
} | ||
out[name] = value; | ||
offset += bytes; | ||
} | ||
return out; | ||
} | ||
|
||
/** | ||
* Concatenate TypedArrays into an ArrayBuffer. | ||
*/ | ||
export function concatenateTypedArrays( | ||
xs: Array<Float32Array|Int32Array|Uint8Array>): ArrayBuffer { | ||
if (xs === null) { | ||
return null; | ||
} | ||
if (xs === undefined) { | ||
return undefined; | ||
} | ||
if (xs.length === 0) { | ||
return new ArrayBuffer(0); | ||
} | ||
|
||
let totalByteLength = 0; | ||
for (const x of xs) { | ||
// tslint:disable-next-line:no-any | ||
if (x as any instanceof Float32Array || x instanceof Int32Array) { | ||
totalByteLength += x.length * 4; | ||
// tslint:disable-next-line:no-any | ||
} else if (x as any instanceof Uint8Array) { | ||
totalByteLength += x.length; | ||
} else { | ||
throw new Error(`Unsupported TypedArray subtype: ${x.constructor.name}`); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Are there minification concerns here with constructor.name? |
||
} | ||
} | ||
|
||
const y = new Uint8Array(totalByteLength); | ||
let offset = 0; | ||
for (const x of xs) { | ||
y.set(new Uint8Array(x.buffer), offset); | ||
if (x instanceof Float32Array || x instanceof Int32Array) { | ||
offset += x.length * 4; | ||
} else { | ||
offset += x.length; | ||
} | ||
} | ||
|
||
return y.buffer; | ||
} |
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.
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.
Can we include the name of the tensor here as well.