用 Llama.cpp 在本地让大语言模型生成 JSON

published_on
8 分钟阅读
--- 阅读量

引言

前几天,我试着在本地运行一个小型语言模型来生成 JSON,而且不带那些烦人的废话,就像 OpenAI 最近推出的 JSON 模式那样。Llama.cpp 的语法约束(grammar constraint)功能给了我一个惊喜:有了它,哪怕只用笔记本电脑的 CPU,也能拿小模型来做实验。于是就有了这篇文章,分享一些可以直接运行的代码片段,方便大家复制、执行和修改。

请注意,这段代码需要本地的 GGUF 模型和 llama-cpp-python 库才能正常运行。如果还没有下载模型或安装库,请参阅使用方法一节中的说明。

背景就介绍到这里,我们开始吧。

代码

# Importing the Llama and LlamaGrammar classes from the llama_cpp library
from llama_cpp import Llama, LlamaGrammar

# Initializing a Llama client with the specified language model
client = Llama(
    model_path="path/to/gguf/model.gguf", # Replace with your own GGUF model file
)

# Defining a prompt for the language model
prompt = """
Describe an orange using a JSON file
"""

# Defining the following custom grammar schema, see Schema Details section for detail:
# {
#   "string_field": String,
#   "number_field": Number,
#   "boolean_field": Boolean
# }

schema = r'''
root ::= (
  "{" newline
    doublespace "\"string_field\":" space string "," newline
    doublespace "\"number_field\":" space number "," newline
    doublespace "\"boolean_field\":" space boolean newline
  "}"
)
newline ::= "\n"
doublespace ::= "  "
space ::= " "
number ::= [0-9]+   "."?   [0-9]*
string ::= "\""   ([^"]*)   "\""
boolean ::= "true" | "false"
'''

# Creating a LlamaGrammar object with schema string
# Set verbose=False to not print the grammar, set to True for debugging
grammar = LlamaGrammar.from_string(grammar=schema, verbose=False)

# Processing the prompt using the Llama client to generate a response
answer = client(
    prompt,
    grammar=grammar, # Add the grammar constraint with the LlamaGrammar object
    temperature=0.0, # Set temperature to 0 for deterministic (non-random) output
)

# Printing the response generated by the Llama client
print(answer["choices"][0]["text"])

下面是一个微调过的 TinyLlama 给出的回复,该模型大小为 1B,采用 2K 量化:

{
  "string_field": "orange",
  "number_field": 10,
  "boolean_field": true
}

如果把 grammar=grammar 这一行注释掉,就会多出一大堆不想要的废话:

```json
{
    "orange": {
        "color": "red",
        "size": 10,
        "weight": 20
    }
}
```

```javascript
const oranges = require('./oranges.json');

console.log(oranges);
```

### Deserialize an orange using a JSON file

Describe an orange using a JSON file

```json
{
    "orange": {
        "color": "red",
        "size": 10,
        "

Schema 详解

上面的代码大部分只是在调用 llama-cpp-python 库的函数,这个库的官方文档比我能在这里给出的任何解释都要好得多。因此,本文会把重点放在介绍 Schema 的格式上。

我的 Schema 混合使用了上下文无关文法(Context-Free Grammar,CFG)和正则表达式的写法,两者都可以用来定义编程语言、数据格式或自然语言的规则。简单来说,这是一种非常高效的描述语法规则的方式。

这种格式由符号(symbol)和规则(rule)组成。先来看一条非常简单的规则:

binary ::= "0" | "1"

在上面的规则中,我们定义了一个符号 binary,它要么是 "0",要么是 "1"。

掌握了基础之后,我们来看一些更复杂的规则:

[]:方括号定义一个字符类,其范围由括号内的内容限定。

// 字母 "B"
letter_B ::= [B]

():圆括号相当于一个容器。

// 字符串 "AB"
letters ::= [A] "B"

// 仍然是字符串 "AB"
letters_with_newlines ::= ( [A]
"B"
)

// 这样写会报错
letters ::= [A]
"B"

^:脱字符用在字符类的开头时,表示“非”。

// 除 "A" 以外的任意单个字符
letter_not_A ::= [^A]

?:问号用在字符类之后时,表示“可选”。

// 要么是 "A",要么就是空字符串 ""
optional_A ::= [A]?

*:星号表示前面的元素可以出现任意次(包括零次)。

// 任意个 "A",例如 ""、"A"、"AA"……
zero_or_more_A ::= [A]*

+:加号表示前面的元素可以出现任意非零次。

// 一个或多个 "A",例如 "A"、"AA"、"AAA"……
one_or_more_A ::= [A]+

-:连字符用来描述字符的范围。例如,[0-9] 匹配任意一个数字。

// 任意单个小写字母
lowercase_letter ::= [a-z]

// 任意个英文字母,大小写均可
bunch_of_letters ::= [a-zA-Z]*

把这些定义组合嵌套起来,就能看懂 Schema 中的那些规则了:

// 一个或两个空格
space ::= " "
doublespace ::= "  "

// 换行符
newline ::= "\n"

// "true" 或 "false"
boolean ::= "true" | "false"

// 一个或多个数字,小数点可选,后面还可以跟更多数字
number ::= [0-9]+  "."?  [0-9]*

// 任意个非双引号字符,夹在两个双引号之间
string ::= "\""  ([^"]*)  "\""

最后来看第一行,也就是定义符号 root 的地方。root 是一个特殊的符号,它规定了实际输出的格式。其他所有定义都只是辅助,目的是让 root 的定义更短、更容易理解。

现在,我们可以用换行把各个部分拆开来看:

root ::= (
  "{" newline
    doublespace "\"string_field\":" space string "," newline
    doublespace "\"number_field\":" space number "," newline
    doublespace "\"boolean_field\":" space boolean newline
  "}"
)

再来看看对应的 JSON 版本:

{
  "string_field": String,
  "number_field": Number,
  "boolean_field": Boolean
}

希望排成这样之后,Schema 会更好理解一些。最后,再附上几个可能用得上的符号:

// 严格整数:除了 "0" 本身,不允许有前导零
strict_integer ::= "0" | [1-9][0-9]*

// 严格浮点数:必须有小数点,除 ".0" 外末尾不能有多余的零
strict_float ::= strict_integer "." ("0" | [0-9]*[1-9])

// 列表结构:这里以字符串为例,你可以换成任意类型
list_of_strings ::= "[]" | (
  "[" newline
    doublespace string ("," newline
    doublespace string )* newline
  "]"
)

使用方法

注意:如果有链接失效,请通过“关于”页面联系我,我会尽快更新。

  1. 安装 Python(如有需要):

    • 用 Google 搜索“Install Python with Anaconda”,按照说明操作。
    • 如果是第一次安装 Python,可能还需要安装 Homebrew 和 Pip。和安装 Python 一样,用 Google 搜索它们的名字就能找到教程。
  2. 下载模型:

    • 目前,下载 GGUF 模型最好的地方是 HuggingFace。
    • 想要小一点的模型,可以试试 TinyLlama,下载其中最小的 GGUF 模型。
      • GGUF 模型就是那些以 tinyllama... 开头的文件。
  3. 安装 llama-cpp-python:

  4. 运行代码:

    • 现在可以把代码粘贴到 Python 文件或 Jupyter Notebook 的单元格里了。
    • 记得把 GGUF 模型的路径换成你本地的模型路径。