GithubHelp home page GithubHelp logo

cdial-gpt-tf's People

Contributors

bojone avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

cdial-gpt-tf's Issues

model.save()保存 savedmodel,做tfserving 时报错tensor shape 错误。

设置了环境变量 TF_KERAS=1
代码如下:

#! -*- coding: utf-8 -*-
# bert4keras加载CDial-GPT
# https://github.com/bojone/CDial-GPT-tf

import numpy as np
from bert4keras.models import build_transformer_model
from bert4keras.tokenizers import Tokenizer
from bert4keras.snippets import AutoRegressiveDecoder
from bert4keras.snippets import uniout
from tensorflow import keras
import json
import requests


config_path = './GPT_LCCC-large-tf/config.json'
checkpoint_path = './GPT_LCCC-large-tf/gpt_model.ckpt'
dict_path = './GPT_LCCC-large-tf/vocab.txt'

tokenizer = Tokenizer(dict_path, do_lower_case=True)  # 建立分词器
speakers = [
    tokenizer.token_to_id('[speaker1]'),
    tokenizer.token_to_id('[speaker2]')
]

model = build_transformer_model(
    config_path=config_path,
    checkpoint_path=checkpoint_path,
    model='gpt_openai'
)  # 建立模型,加载权重


print(type(model))
model.summary(line_length=150)
# model.save('./b4k_model')
# k_model = keras.models.load_model('./b4k_model')

mls_uri = 'http://cdial-gpt.t9k-sample.n.ksvc.tensorstack.net/v1/models/cdial-gpt:predict'

class ChatBot(AutoRegressiveDecoder):
    """基于随机采样对话机器人
    """
    @AutoRegressiveDecoder.wraps(default_rtype='probas')
    def predict(self, inputs, output_ids, states):
        token_ids, segment_ids = inputs
        curr_segment_ids = np.zeros_like(output_ids) + token_ids[0, -1]
        token_ids = np.concatenate([token_ids, output_ids], 1)
        segment_ids = np.concatenate([segment_ids, curr_segment_ids], 1)
        
        serving_url = mls_uri
        instances = [{'Input-Segment': segment_ids.tolist(), 'Input-Token': token_ids.tolist()}]
        data = {'signature_name': 'serving_default', 'instances': instances}
        data = json.dumps(data)
        headers = {"content-type": "application/json"}

        json_response = requests.post(serving_url, data=data, headers=headers)
        try:
            pred_res = json.loads(json_response.text)
        except json.decoder.JSONDecodeError:
            raise Exception("Invalid response: {}".format(json_response))
        print(type(pred_res))
        print(pred_res)
        pred = pred_res['predictions']
        return pred[:, -1]

    def response(self, texts, topk=5):
        token_ids = [tokenizer._token_start_id, speakers[0]]
        segment_ids = [tokenizer._token_start_id, speakers[0]]
        for i, text in enumerate(texts):
            ids = tokenizer.encode(text)[0][1:-1] + [speakers[(i + 1) % 2]]
            token_ids.extend(ids)
            segment_ids.extend([speakers[i % 2]] * len(ids))
            segment_ids[-1] = speakers[(i + 1) % 2]
        results = self.random_sample([token_ids, segment_ids], 1, topk)
        return tokenizer.decode(results[0])


chatbot = ChatBot(start_id=None, end_id=tokenizer._token_end_id, maxlen=32)
while True:
    raw_text = input(">>> ")
    print(chatbot.response([raw_text]))
"""
回复是随机的,例如:你还有我 | 那就不要爱我 | 你是不是傻 | 等等。
"""

报错:

{'error': 'Input to reshape is a tensor with 3840 values, but the requested shape has 5\n\t [[{{node model/Transformer-0-MultiHeadSelfAttention/dense/Tensordot/Reshape}}]]'}

在tf2.0.0 和2.3.0 下均报该错误

本TF版本的输入 `token_ids, segment_ids` 和原版的模型输入 `input_ids, token_type_ids` 是否一样?

本TF版predict 输入为 https://github.com/bojone/CDial-GPT-tf/blob/master/example.py#L37

return model.predict([token_ids, segment_ids])[:, -1]

原版模型输入为 https://github.com/thu-coai/CDial-GPT/blob/master/interact.py#L81

logits, *_ = model(input_ids, token_type_ids=token_type_ids)

我使用 pytorch 版的输入 input_ids, token_type_ids 作为 TF版的输入 token_ids, segment_ids,但两个模型的输出结果虽然shape相同,但数值差别很大。

请问什么原因呢?感谢!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.