Please initialize `Prune` with a supported layer. Layers should either be a `PrunableLayer` instance, or should be supported by the PruneRegistry. You passed: <class 'tensorflow.python.keras.layers.wrappers.Bidirectional'>
Describe the bug A clear and concise description of what the bug is. I want to prune a bi-LSTM layer , but get a error message that Bidirectional maybe not support System information centos 6.3 cuda 10.1 cudnn 7.6
TensorFlow installed from (source or binary):
TensorFlow version: tensorflow 2.1.0 (cuda 10.1 cudnn 7.6) TensorFlow Model Optimization version: 0.22 Python version: 3.6.10 Describe the expected behavior
Describe the current behavior
Traceback (most recent call last):
File "/home/users/yinchao/soft/python3_tf2/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"main", mod_spec)
File "/home/users/yinchao/soft/python3_tf2/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/users/yinchao/nn_tasks/satisfy_model_prune/experiments/demo_session_lstm_satisfy_predict.py", line 198, in Prune with a supported layer. Layers should either be a PrunableLayer instance, or should be supported by the PruneRegistry. You passed: <class 'tensorflow.python.keras.layers.wrappers.Bidirectional'>
Code to reproduce the issue Provide a reproducible code that is the bare minimum necessary to generate the problem. ` import os import sys import logging import pathlib import json import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import backend as K import pandas as pd import pickle import math import random from tensorflow_model_optimization.python.core.sparsity.keras import prune from tensorflow_model_optimization.python.core.sparsity.keras import pruning_callbacks from tensorflow_model_optimization.python.core.sparsity.keras import pruning_schedule
from models.base_experiment import BaseExperiment from utils.data_processor import handle_fn_dicts from dataset.token_dicts import TokenDicts from dataset.session_dataset_hdfs import SessionDatasetGenerator from dataset.session_dataset_hdfs import DataField from dataset.session_dataset_hdfs import test_dataset from utils.plot import plot_fit_history from utils.settings import set_single_free_memory_gpu from utils.data_filters import * from utils.param import * from utils.model_convert import convert_CuDNN2cpu from typing import Dict from typing import Any from typing import List from typing import Union from typing import Tuple
ConstantSparsity = pruning_schedule.ConstantSparsity
def create_model(hyper_parameters):
max_session_len = hyper_parameters['inputs'].get('max_session_len') + 1
max_query_len = hyper_parameters['inputs']['query_words'].get('max_len')
nlu_class_len = hyper_parameters['inputs']['nlu_class'].get('max_len')
query_vocab_size = hyper_parameters['inputs']['query_words'].get('vocab') + 1
ner_flags_vocab_size = hyper_parameters['inputs']['ner_flags'].get('vocab') + 1
nlu_class_vocab_size = hyper_parameters['inputs']['nlu_class'].get('vocab') + 1
#model params
query_emb_size = hyper_parameters['model'].get('query_emb_size')
ner_flags_emb_size = hyper_parameters['model'].get('ner_flags_emb_size')
nlu_class_emb_size = hyper_parameters['model'].get('nlu_class_emb_size')
rnn_units = hyper_parameters['model'].get('rnn_units')
staytime_emb_size = hyper_parameters['model'].get('staytime_emb_size')
staytime_size = hyper_parameters['model'].get('staytime_size')
"""build_model_structure"""
# 继承之类去实现model的构建,包括tf的model或者tf.keras的model
if tf.version.startswith('1.'):
lstm = keras.layers.CuDNNLSTM
else:
lstm = tf.compat.v1.keras.layers.CuDNNLSTM
#lstm = keras.layers.LSTM
#lstm = keras.layers.CuDNNGRU
#lstm = keras.layers.CuDNNGRU
#lstm = keras.layers.LSTM
query_input = keras.Input(shape=(max_session_len, max_query_len, ), name='query_input')
ner_flags_input = keras.Input(shape=(max_session_len, max_query_len, ), name='ner_input')
nlu_class_input = keras.Input(shape=(max_session_len, nlu_class_len, ), name='nlu_class_input')
#staytime_input = keras.Input(shape=(max_session_len, ), name='staytime_input')
query_emb = keras.layers.Embedding(query_vocab_size, query_emb_size, name='q_emb')(query_input)
ner_flags_emb = keras.layers.Embedding(ner_flags_vocab_size,
ner_flags_emb_size, name='ner_emb')(ner_flags_input)
nlu_class_emb = keras.layers.Embedding(nlu_class_vocab_size,
nlu_class_emb_size, name='class_emb')(nlu_class_input)
nlu_class_emb = keras.layers.Lambda(lambda x:
K.reshape(x, [-1, max_session_len, nlu_class_emb_size * nlu_class_len])
)(nlu_class_emb)
#staytime_input = keras.layers.Reshape([-1, max_session_len])(staytime_input)
#staytime_emb = keras.layers.Embedding(staytime_size, staytime_emb_size,
# name='staytime_emb')(staytime_input)
emb = keras.layers.concatenate([query_emb, ner_flags_emb], axis=-1, name='query_ner_cat')
emb = keras.layers.Lambda(lambda x:
K.reshape(x, [-1, max_query_len, query_emb_size + ner_flags_emb_size])
)(emb)
#emb = keras.layers.Reshape([-1, max_session_len, query_emb_size+ner_flags_emb_size])(emb)
q_seq = keras.layers.Bidirectional(lstm(units=rnn_units,
return_sequences=False,
#activation='relu',
), name='q_seq_out')(emb)
q_seq = keras.layers.Lambda(lambda x:
K.reshape(x, [-1, max_session_len, rnn_units * 2])
)(q_seq)
session_emb = keras.layers.concatenate([q_seq, nlu_class_emb], axis=-1, name='session_cat')
out = keras.layers.Bidirectional(lstm(units=rnn_units,
return_sequences=False,
#activation='relu',
), name='session_out')(session_emb)
out = keras.layers.Dense(64, activation='relu', name='mid_out')(out)
out = keras.layers.Dropout(0.5)(out)
prob = keras.layers.Dense(1, activation='sigmoid', name="prob")(out)
model = keras.models.Model([query_input, ner_flags_input, nlu_class_input], prob)
print('model', model)
return model
if name == "main": experiment_name = sys.argv[1] print('experiment_name', experiment_name) hdfs_dataset_path = sys.argv[2] print('hdfs_dataset_path', hdfs_dataset_path) try: testset_suffix = sys.argv[3] except: testset_suffix = None model_name = experiment_name + ".h5"
set_single_free_memory_gpu()
if tf.__version__.startswith('1.'):
tf.enable_eager_execution()
#init params
#=====================================PARAM=====================================#
token_dicts = TokenDicts({"query_words": "dict/query_words.vocab", "nlu_class": "dict/nlu_class.vocab", \
"slots": "dict/slots.vocab", "ner_flags": "dict/ner_flags.vocab"}, \
{"query_words": 20, "nlu_class": 10, "slots": 2, "ner_flags": 20})
hyper_parameters = {
'inputs': {'max_session_len': 5},
'train': {'max_file_num': 0},
'model': {'rnn_units': 100, 'query_emb_size': 128, 'ner_flags_emb_size': 8, \
'nlu_class_emb_size': 32, 'staytime_size': 2, 'staytime_emb_size': 16}
}
#=====================================PARAM=====================================#
max_session_len = hyper_parameters['inputs']['max_session_len']
#下面是dataset重要的数据schema定义,需要和hdfs_dataset_path上面的数据一一对应上
#如果某一列不用,handle_fn填None就行[即DataField的第二个参数]
#=====================================DATASET SCHEMA=====================================#
data_field_list = []
if max_session_len == 0:
data_field_list.append(DataField('query', None, tf.int32, 'int32', (32), 32, 'query_words'))
data_field_list.append(DataField('query_words', 'to_id_padding_zero', tf.int32, 'int32', \
(32), 32, 'query_words'))
data_field_list.append(DataField('ner_flags', 'to_id_padding_zero', tf.int32, 'int32', \
(32), 32, 'ner_flags'))
data_field_list.append(DataField('nlu_class', 'to_id_padding_zero', tf.int32, 'int32', \
(4), 4, 'nlu_class'))
data_field_list.append(DataField('slots', None, tf.int32, 'int32', (12), 12, 'slots'))
data_field_list.append(DataField('staytime', None, tf.int32, 'int32', (1), 1, None, mask_current=True))
data_field_list.append(DataField('pv', None, tf.int32, 'int32', (1), 1, None))
data_field_list.append(DataField('avg_score', None, tf.int32, 'int32', (1), 12, None))
data_field_list.append(DataField('slot_prob', None, tf.int32, 'int32', (1), 12, None))
data_field_list.append(DataField('org_query', None, tf.int32, 'int32', (1), 12, None))
data_field_list.append(DataField('asr_nbest', None, tf.int32, 'int32', (1), 12, None))
else:
data_field_list.append(DataField('query', None, tf.int32, 'int32', (max_session_len + 1, 20), 20, 'query_words'))
data_field_list.append(DataField('query_words', 'to_id_padding_zero', tf.int32, 'int32', \
(max_session_len + 1, 32), 32, 'query_words'))
data_field_list.append(DataField('ner_flags', 'to_id_padding_zero', tf.int32, 'int32', \
(max_session_len + 1, 32), 32, 'ner_flags'))
data_field_list.append(DataField('nlu_class', 'to_id_padding_zero', tf.int32, 'int32', \
(max_session_len + 1, 4), 4, 'nlu_class'))
data_field_list.append(DataField('slots', None, tf.int32, 'int32', (max_session_len + 1, 12), 12, 'slots'))
data_field_list.append(DataField('staytime', None, tf.int32, 'int32', (max_session_len + 1), 0, None, mask_current=True))
data_field_list.append(DataField('pv', None, tf.int32, 'int32', (max_session_len + 1), 1, None))
data_field_list.append(DataField('avg_score', None, tf.int32, 'int32', (max_session_len + 1), 1, None))
data_field_list.append(DataField('slot_prob', None, tf.int32, 'int32', (1), 12, None))
data_field_list.append(DataField('org_query', None, tf.int32, 'int32', (1), 12, None))
data_field_list.append(DataField('asr_nbest', None, tf.int32, 'int32', (1), 12, None))
label_field = DataField('label', 'to_np', tf.float32, 'float32', (1), 1, None)
add_inputs_to_hyperparams(data_field_list, token_dicts, hyper_parameters)
print(json.dumps(hyper_parameters, indent=4))
#build model and run experiment
model = create_model(hyper_parameters)
pruning_params = {
'pruning_schedule': ConstantSparsity(0.75, begin_step=2000, frequency=100)
}
model = prune.prune_low_magnitude(model, **pruning_params)
` Screenshots If applicable, add screenshots to help explain your problem.
Additional context Add any other context about the problem here.
I remove Bidirectional layer , no error exist, and can run. what should I can do to fix Bidirectional to run? can I define a new bi-LSTM layer to solve this problem?
@nutsiepully Can you help take a look at this issue?
Hi @yinochaos,
Bidirectional is a Keras wrapper we haven't added explicit support for yet. In the short-term, you can fix your issue by subclassing Bidirectional and implementing PrunableLayer.
It shouldn't be that hard. In the get_prunable_weights method, you can include the weights you want to prune. And that should take care of it.
But we'll keep this issue open, and can investigate adding library support for it.
Hi @yinochaos,
Bidirectional is a Keras wrapper we haven't added explicit support for yet. In the short-term, you can fix your issue by subclassing
Bidirectionaland implementingPrunableLayer.It shouldn't be that hard. In the
get_prunable_weightsmethod, you can include the weights you want to prune. And that should take care of it.But we'll keep this issue open, and can investigate adding library support for it.
@nutsiepully thanks, can you give me some example that can help me subclassing Bidirectional and implementing PrunableLayer, thanks : )
Hi @yinochaos,
Try taking a look at this test. This is a simple example of how to make a layer prunable.
You can apply the same approach to Bidirectional. Just add the get_prunable_weights method and in that you can choose which tensors you want to prune.
Hi @yinochaos,
Try taking a look at this test. This is a simple example of how to make a layer prunable.
You can apply the same approach to
Bidirectional. Just add theget_prunable_weightsmethod and in that you can choose which tensors you want to prune.
thanks for your help. I fix this problem. that is very simple.
class PruneBidirectional(keras.layers.Bidirectional, prunable_layer.PrunableLayer):
def get_prunable_weights(self):
return self.forward_layer._trainable_weights + self.backward_layer._trainable_weights
Hi @yinochaos, Try taking a look at this test. This is a simple example of how to make a layer prunable. You can apply the same approach to
Bidirectional. Just add theget_prunable_weightsmethod and in that you can choose which tensors you want to prune.thanks for your help. I fix this problem. that is very simple.
class PruneBidirectional(keras.layers.Bidirectional, prunable_layer.PrunableLayer): def get_prunable_weights(self): return self.forward_layer._trainable_weights + self.backward_layer._trainable_weights
I tried this but getting the error 'go_backwards' could please elaborate on how to further use this for pruning