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

Update weights loading #7872

Merged
merged 9 commits into from
Aug 4, 2023
Merged
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
30 changes: 30 additions & 0 deletions tfjs-layers/src/engine/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,9 @@ export abstract class Container extends Layer {
// e.g. dense/0
const key = Object.keys(weights)[0].split('/');
const isKerasSavedModelFormat = !isNaN(parseInt(key[key.length - 1], 10));
if (isKerasSavedModelFormat) {
this.parseWeights(weights);
}
// Check if weights from keras v3.
for (const layer of this.layers) {
for (const [index, weight] of layer.weights.entries()) {
Expand Down Expand Up @@ -652,6 +655,33 @@ export abstract class Container extends Layer {
batchSetValue(weightValueTuples);
}

protected parseWeights(weights: NamedTensorMap) {
for (const key in Object.keys(weights)) {
const listParts = key.split('/');
const list = ['vars', 'layer_checkpoint_dependencies'];
// For keras v3, the weights name are saved based on the folder structure.
// e.g. _backbone/_layer_checkpoint_dependencies/transformer/_self../
// _output_dense/vars/0
// Therefore we discard the `vars` and `layer_checkpoint_depencies` within
// the saved name and only keeps the layer name and weights.
// This can help to mapping the actual name of the layers and load each
// weight accordingly.
const newKey = listParts
.map(str => {
if (str.startsWith('_')) {
return str.slice(1);
}
return str;
})
.filter(str => !list.includes(str))
.join('/');
fengwuyao marked this conversation as resolved.
Show resolved Hide resolved
if (newKey !== key) {
weights[newKey] = weights[key];
delete weights[key];
}
}
}

/**
* Util shared between different serialization methods.
* @returns LayersModel config with Keras version information added.
Expand Down