如何编写包含持久C++对象的TysFraseOutlook OP?

2024-10-04 03:18:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个Tensorflow序列模型,它通过OpenFST解码图(从二进制文件加载)在Tensorflow序列模型的logits输出上进行波束搜索。在

我已经编写了一个自定义操作,它允许我在logit上执行解码,但是每次,在执行解码之前,我都会调用fst::Read(二进制_文件)。只要它保持较小就可以了,但是我希望避免I/O开销。在

我已经通读了Tensorflow定制操作,并试图找到类似的例子,但我还是迷路了。基本上,我想在图表中做的是:

FstDecodingOp.Initialize('BINARY_FILE.bin') #loads the BINARY_FILE.bin into memory
...
for o in output:
    FstDecodingOp.decode(o) # uses BINARY_FILE.bin to decode

当然,在Python中,这在tensorflow图之外是很简单的,但我最终需要将其移动到一个普通的TF服务环境中,因此需要将其冻结到导出图中。以前有人遇到过类似的问题吗?在

解决方案:

没有意识到可以使用“OpKernel(context)”设置私有属性。刚刚用那个函数初始化了它。在

编辑:关于我是怎么做到的。尚未尝试上菜。

^{pr2}$

在python中:


sess = tf.Session()
mat = tf.placeholder(tf.float32, shape=test_npy.shape)
res_ = decoder_op.fst_decoder(beam=30, fst_decoder_path="decoder_path.fst", log_likelihoods=mat)
res = sess.run(res_, {mat : test_npy} )


Tags: 文件模型bintftensorflow二进制res序列
1条回答
网友
1楼 · 发布于 2024-10-04 03:18:32

解决方案:

没有意识到可以使用“OpKernel(context)”设置私有属性。刚刚用那个函数初始化了它。在

编辑:关于我是怎么做到的。尚未尝试上菜。

REGISTER_OP("FstDecoder")
    .Input("log_likelihoods: float")
    .Attr("fst_decoder_path: string")
    ....

...

template <typename Device, typename T>
class FstDecoderOp : public OpKernel {

private:
   fst::Fst<fst::StdArc>* fst_;
   float beam_;

public:
  explicit FstDecoderOp(OpKernelConstruction* context) : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("beam", &beam_));

    std::string fst_path;
    OP_REQUIRES_OK(context, context->GetAttr("fst_decoder_path", &fst_path));

    fst_ = fst::Fst<fst::StdArc>::Read(fst_path);
  }

  void Compute(OpKernelContext* context) override {
    // do some compute 
    const Tensor* log_likelihoods;

    OP_REQUIRES_OK(context, context->input("log_likelihoods", 
     &log_likelihoods));

    // simplified 
    compute_op(_fst, log_likelihoods);

  }
};

在python中:

^{pr2}$

相关问题 更多 >