Проблемы с компиляцией файла tenorflow lite для работы на коралловом процессоре - PullRequest
1 голос
/ 29 мая 2019

Я пытаюсь получить повторяющуюся простую модель для компиляции, чтобы она работала на коралловом процессоре. До сих пор я замораживал и преобразовывал файл в файл tflite, однако, когда я запускаю файл через Edge TPU Model Compiler , он выдает мне относительно бесполезное сообщение об ошибке.

COMPILING FAILED
Something went wrong. Couldn't compile model.
Please make sure your model meets the requirements.
See the log below for more compilation details.
If you believe your model meets the requirements but you still receive this error,
email support at coral‑support@google.com.

Я написал им по электронной почте, и они сказали использовать / tenorflow / lite / tools: визуализировать, чтобы увидеть, что не так с моделью. (У меня проблемы с тем, чтобы это сработало, но мне кажется, что я должен задать отдельный вопрос, чтобы получить помощь по поводу базеля)

Я обучил модель обучению с учетом квантования после этого сайта , и я запустил файл tflite со случайными входами, и, похоже, он работает. Я волновался, что часть проблемы с компилятором модели TPU заключалась в том, что я был за прокси, поэтому я пропустил через него чужой файл, и он успешно скомпилировался.)

Вот график оценки:

import pandas as pd
import sys
import tensorflow as tf
import numpy as np
from tensorflow.python.tools import inspect_checkpoint as chkp
from sklearn.model_selection import train_test_split


#test data
seed = np.random.seed(141)

features = pd.read_csv(sys.argv[1], sep=',', index_col=0)
labels = pd.read_csv(sys.argv[2], sep=',', index_col=0)
train_input, test_input, train_labels, test_labels = train_test_split(features, labels, test_size=0.2, random_state=seed)

def neuron_layer(X, n_neurons, name, activation=None):
    with tf.name_scope(name):
        n_inputs = int(X.get_shape()[1])
        W = tf.Variable(tf.zeros([n_inputs, n_neurons]), name="kernal")
        b = tf.Variable(tf.zeros([n_neurons]), name="bias")
        Z = tf.matmul(X, W) + b
        if activation is not None:
            return activation(Z)
        else:
            return Z

X = tf.placeholder(tf.float32, (1, 701), name="X")
n_outputs = 2
n_hidden1 = 700
n_hidden2 = 701
with tf.name_scope("dnn"):
    hidden1 = neuron_layer(X, n_hidden1, name="hidden1", activation=tf.nn.relu)
    # hidden2 = neuron_layer(hidden1, n_hidden2, name="hidden2", activation=tf.nn.relu)
    # trying only one layer
    logits = neuron_layer(hidden1, n_outputs, name="outputs")

with tf.name_scope("final_eval"):
    output = tf.argmax(logits, axis=1, name="output")


# Call the eval rewrite which rewrites the graph in-place with
# FakeQuantization nodes and fold batchnorm for eval.
g = tf.get_default_graph()
tf.contrib.quantize.create_eval_graph(input_graph=g)

# Add ops to save and restore all the variables.
saver = tf.train.Saver()
eval_graph_file = "eval_graph.pb"

#handles different tensorboard runs
from datetime import datetime
now = datetime.utcnow().strftime("%Y%m%d%H%M%S")
root_logdir = "tf_logs"
logdir = "eval/{}/run-{}".format(root_logdir, now)

file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph())
with tf.Session() as sess:
    saver.restore(sess, "./nbtf/nothing_but_tf_model.ckpt")

    # Save the checkpoint and eval graph proto to disk for freezing
    # and providing to TFLite.
    with open(eval_graph_file, 'w+') as f:
        f.write(str(g.as_graph_def()))
    saver.save(sess, "./nbtf/eval/eval.ckpt")
    pred = output.eval(feed_dict={X: [test_input.values[45]]})
    print(pred, test_labels.values[45])

Тогда я замираю с этим:

 freeze_graph --input_graph=eval_graph.pb --input_checkpoint=nbtf\eval\eval.ckpt --output_graph=frozen_eval_graph.pb --output_node_names=final_eval/output

Затем преобразуйте с помощью этого:

toco --graph_def_file=frozen_eval_graph.pb --output_file=tflite_model.tflite --input_format=TENSORFLOW_GRAPHDEF --output_format=TFLITE --inference_type=QUANTIZED_UINT8 --input_array=X --output_array=final_eval/output --std_dev_value=127 --mean_value=127

изображение тензорной доски

Я просто хочу, чтобы этот файл компилировался, он не должен быть идеальным или что-то в этом роде.

Спасибо за помощь.

Edit:

Я попробовал две вещи, во-первых, я распечатал тензоры из файла tflite (я пытался использовать инструмент visualize.py, но у меня был прокси-сервер и у меня были большие проблемы с его работой. ) Я получил это:

{'name': 'X', 'index': 0, 'shape': array([  1, 701]), 'dtype': <class 'numpy.uint8'>, 'quantization': (0.007874015718698502, 127)}
{'name': 'dnn/fully_connected/MatMul_bias', 'index': 1, 'shape': array([702]), 'dtype': <class 'numpy.int32'>, 'quantization': (3.750092218979262e-05, 0)}
{'name': 'dnn/fully_connected/Relu', 'index': 2, 'shape': array([  1, 702]), 'dtype': <class 'numpy.uint8'>, 'quantization': (0.035464514046907425, 0)}
{'name': 'dnn/fully_connected/weights_quant/FakeQuantWithMinMaxVars/transpose', 'index': 3, 'shape': array([702, 701]), 'dtype': <class 'numpy.uint8'>, 'quantization': (0.004762616939842701, 121)}
{'name': 'dnn/fully_connected_1/MatMul_bias', 'index': 4, 'shape': array([703]), 'dtype': <class 'numpy.int32'>, 'quantization': (0.0001283923047594726, 0)}
{'name': 'dnn/fully_connected_1/Relu', 'index': 5, 'shape': array([  1, 703]), 'dtype': <class 'numpy.uint8'>, 'quantization': (0.019155390560626984, 0)}
{'name': 'dnn/fully_connected_1/weights_quant/FakeQuantWithMinMaxVars/transpose', 'index': 6, 'shape': array([703, 702]), 'dtype': <class 'numpy.uint8'>, 'quantization': (0.0036203034687787294, 120)}
{'name': 'dnn/outputs/MatMul_bias', 'index': 7, 'shape': array([2]), 'dtype': <class 'numpy.int32'>, 'quantization': (3.3737978810677305e-05, 0)}
{'name': 'dnn/outputs/add', 'index': 8, 'shape': array([1, 2]), 'dtype': <class 'numpy.uint8'>, 'quantization': (0.055008530616760254, 131)}
{'name': 'dnn/outputs/weights_quant/FakeQuantWithMinMaxVars/transpose', 'index': 9, 'shape': array([  2, 703]), 'dtype': <class 'numpy.uint8'>, 'quantization': (0.0017612784868106246, 110)}
{'name': 'final_eval/output', 'index': 10, 'shape': array([1, 1]), 'dtype': <class 'numpy.int64'>, 'quantization': (0.0, 0)}
{'name': 'final_eval/output/dimension', 'index': 11, 'shape': array([], dtype=int32), 'dtype': <class 'numpy.int32'>, 'quantization': (0.0, 0)}

Думаю, проблема в том, что тензоры MatMul_bias не конвертируются в uint8 (что требуется для кораллового процессора).

Я не уверен, как это исправить.

Другое изменение, которое я попробовал, - это использовать tenorflow slim.fully_connected, а не мою собственную полностью подключенную нейронную сеть. (У них та же проблема.)

1 Ответ

0 голосов
/ 19 июня 2019

Хорошо, я смог скомпилировать файл без проблем. Мне просто нужно было использовать автономный компилятор . Казалось бы, исправить это полностью.

...