某岛

… : "…アッカリ~ン . .. . " .. .
April 23, 2023

gradio_client 介绍

随着最近 HuggingGPT 和 AutoGPT 的火爆,让 LLM 作为 Control 调用各种各样的 Domain Expert Models 也成为了一个常见的需求了。
连 Gradio 也在上周推出了 gradio_client 功能。

顺带一提。。前几天 OpenAI 三巨头之一的 GDB 在 Ted 给了一个 talk,也再次向公众秀了一把 ChatGPT Plugin…
可惜 量子位的这篇报道 明显是混淆了 AutoGPT 和 ChatGPT Plugin…
调模型可以算做使用工具的一环,但 AutoGPT 核心的 feature 是 Auto 啊。

总之,先让我们看看 gradio_client 具体都能做些什么吧~!

背景

在具体讨论 gradio_client 之前,我们不妨稍微回顾一下当前开发者的现状,随着 ChatGPT 的火爆和其极其廉价的,近乎于倾销的定价模式,使得 OpenAI API 已经几乎成为所有开发者的标配,甚至许多开发者都将开源 LLM 封装成类似 OpenAI API 的调用格式。实际上,利用 HuggingFace Inference Endpoints,也可以做到和 OpenAI API 类似的功能,而 gradio_client 则可以让一个 Gradio 程序即使脱离 HuggingFace 平台,也依然保持通信。

这乍看起来像是某种 反射魔法。。。直接就构造一个类然后 import 进来它的 predict 函数了?
。。不过那安全性怎么处理?。。所以应该还是工程层面的东西吧。。

例子

The Gradio client works with any hosted Gradio app, whether it be an image generator, a text summarizer, a stateful chatbot, a tax calculator, or anything else! The Gradio Client is mostly used with apps hosted on Hugging Face Spaces, but your app can be hosted anywhere, such as your own server.

ChatGPT

首先我们先使用 ChatGPT 熟悉一下基础的 Gradio 程序。
HuggingFace 上 ChatGPT instance 不要太多。。。让我们随机看几个例子。。

loveleaves2012/ChatGPT

ysharma/ChatGPTwithAPI

anzorq/chatgpt-demo

这个版本目前我觉得最棒。。。因为它还代一个类似 stable diffusion 安装插件的功能。。从 gist 里同步 prompt 模板。。。
我们复刻的版本在 这里

ChatGLM

当然上面的例子里虽然是 Gradio,但实际最后都是用 OpenAI 的服务,并没能展现 gradio_client 的优越性。。。
所以我们换一个 LLM 的例子。上面是三段 ChatGLM 的代码,都是用 Gradio 实现。
首先是紅葉大大的版本,这个版本的控件最丰富,但是是完全本地版,需要用户将模型下载到本地方可运行。
并不兼容 huggingface。

第二个是 HF 的高产 stuff,multimodalart 的版本,利用了 HF 的基础设施,但是需要用户花钱 host model 方可运行。

def predict(input, history=None):
    if history is None:
        history = []
    response, history = model.chat(tokenizer, input, history)
    return history, history

第三个版本是我从第二个版本魔改而来的,核心是只需要修改 predict 函数,跳过模型调用的过程,而直接从远端进行呼叫。

def predict(input, history=None):
    if history is None:
        history = []

    client = Client('https://multimodalart-chatglm-6b.hf.space/')
    with open(client.predict(input, fn_index=0)) as f: 
        text = process_text(f.read())
        output = json.loads(text)[0]
        history += [output]
        return history, history

这个例子目前跑在这儿:https://testing.agentswap.net/models/19/remi-test-app

Stable Diffusion 2.1

这个例子更复杂一些,首先,虽然 host 在 huggingface 上,但它并不是一个传统的 huggingface service,而是更类似之前的 ChatGPT 里的例子,是一个由 Google 和 StabilityAI 共同维护的一个 public good。。

但是我们依然和上例一样。。。可以通过 gradio_client 获得 predict 方法。。。

可以在 这里 看到实际运行的结果。

Further Discussion

gradio_client 看起来符合了我对开源软件的完美预期,人人为我,我为人人,甚至说我可以本地 self host,然后 share=true,
然后利用 gradio_client 再打包成外部服务(比如 telegram bot)。。。想象空间很大。。。

但是仔细想想,这里也有一些问题,最大的受害者可能是部署模型的那个孩子,相当于花钱给大家做 public good。
而且如果一份模型非常火爆,现有的架构的可扩展性相交于 Cloud Model 也会很快显示出不足。
当然现在因为资料太少,我依然没搞懂它是怎么实现的,以及 export 出的 function 满足什么样的规则,有没有安全性风险等等。。

最后 这里 似乎有更多的例子。
甚至还有依赖 gradio_client 构建的 gradio_tools。。。。太快了吧。。