← 文章 / AI技术
HuggingFace博客 23天前 · 2026-11-11 02:03:54 · 33 阅读

Hugging Face 中的决策模型:让 LLM 直接输出概率而非文本

大语言模型(LLM)在生成文本方面极其出色。我们用它来回答问题、编写代码、推理问题等等。但并不是每个问题都需要生成文本。

假设客服系统收到这样一条消息:

“我的订阅被扣了两次款,我今天就需要退款。”

系统需要判断这个请求应该由哪个团队处理、紧急程度如何,以及客户是否在申请退款。

我们可以让 LLM 返回一个包含这些答案的 JSON 对象。

llama cli -hf ggml-org/gemma-4-e4b-it-GGUF:Q4_0

> We have the following customer support ticket, "I was charged twice for my subscription. I need a refund today.", which team should handle the request, how urgent it is, and whether the customer is requesting a refund. Give the answers in JSON.

[Start thinking]
...
[end thinking]
```json
{
  "team_to_handle": "Billing",
  "urgency": "High",
  "request_refund": true
}

但如果模型能够直接对各个候选选项进行评估,并返回它们之上的概率分布,完全不生成任何文本呢?

from transformers import pipeline

decide = pipeline("decision", model="autotrust/GEV-26B-Decide")
decision = decide(
    {
        "state": "I was charged twice for my order and want a refund.",
        "questions": {
            "department": {
                "type": "choice",
                "instructions": "Which team should handle this?",
                "criteria": {
                    "billing": "Payments and refunds",
                    "technical": "Bugs and technical issues",
                    "sales": "Pricing and subscriptions"
                }
            },
        }
    }
)

# {
#   'department': {
#       'type': 'choice',
#       'choice': 'billing',
#       'confidence': 0.9974000453948975,
#       'probabilities': {
#         'billing': 0.9982666969299316,
#         'technical': 0.0010246571619063616,
#         'sales': 0.0007087149424478412
#       }
#     }
# }

这正是决策模型背后的核心思想。

什么是决策模型?

决策模型接收输入的上下文(state),针对一个问题在预定义的可选答案(primitives)中做出评估,最终返回一个结构化的决策及其对应的概率。我们不是让模型逐个 token 地生成答案,而是让它为应用已经理解好的候选答案赋予概率。

决策模型的 state 和 primitives

TypeSafe AI 发布了 Jev,并将其称为一种System One 模型。这个名字的灵感来自《思考,快与慢》中的概念:快速直觉的系统 1 思维,与更慢、更审慎的系统 2 思维。

社区最终统一使用了decision model(决策模型)这个术语,因为它描述的是模型的计算角色,而不涉及某种具体的认知理论。在本文接下来的部分,我们将使用"决策模型"而不是"System One 模型"来称呼这类模型。(参见Twitter 上关于如何命名这类模型的投票)

决策模型的基本接口是:

State + Questions + Allowed Answers → Decisions + Probabilities

为什么不全部用 LLM?

我们当然可以直接让 LLM 返回一个包含决策结果的 JSON 对象。事实上,很多应用目前就是这样用语言模型做分类、路由和其他结构化任务的。

但这种做法存在一些问题。

  • LLM 不保证遵循指定的 schema:即使给出了明确的指令,模型仍可能生成无效的 JSON、引入意料之外的键,或者返回不在允许范围内的答案。
  • 约束解码能有所帮助,但无法消除额外的计算开销:像 Outlines 和 XGrammar 这样的库可以通过限制模型每一步可生成的 token,来强制输出符合语法规则或 JSON schema。这能保证输出遵循结构约束,但也带来了额外的工作量。
  • 为什么要生成完整回复:LLM 本是为开放式生成而设计的,但如果应用只需要在预设答案中做选择,自回归解码就可能是多余的工作。

决策模型与分类模型有何不同?

在了解决策模型的接口之前,有必要先回顾两种密切相关的方法:传统分类和零样本分类。

传统分类

假设我们训练一个分类器,把客户支持请求路由到三个部门:

  • 账单
  • 技术支持
  • 销售

传统分类模型学习的是从输入到一组预定义标签的映射。训练时,模型通过样本学会预测这些标签。分类头通常为每个类别输出一个 logit,再由 softmax 把这些 logit 转换为概率分布。

它的局限在于 输出类别是固定写在模型分类头里的。

如果我们新增第四个部门(比如法务),现有分类器并不会自动获得对应的输出类别。我们可能需要修改分类头、收集训练数据,然后重新训练或调整模型。

零样本分类

零样本分类部分解决了这个局限。它不需要为每个输出类别专门训练分类器,而是在推理时直接提供候选标签。

例如:

from transformers import pipeline

classifier = pipeline(
    "zero-shot-classification",
    model="facebook/bart-large-mnli",
)

classifier(
    "My payment was deducted twice.",
    candidate_labels=["billing", "technical support", "sales"],
)

# {'sequence': 'My payment was deducted twice.',
#  'labels': ['billing', 'sales', 'technical support'],
#  'scores': [0.8466812372207642, 0.0962134450674057, 0.05710534751415253]}

与传统的固定标签分类器不同,这里的类别可以随每次请求动态变化。比如新增一个“Legal”(法务)部门,再看看模型的输出。

from transformers import pipeline

classifier = pipeline(
    "zero-shot-classification",
    model="facebook/bart-large-mnli",
)

classifier(
    "My payment was deducted twice.",
    candidate_labels=["billing", "technical support", "sales", "legal"],
)

# {'sequence': 'My payment was deducted twice.',
#  'labels': ['billing', 'sales', 'technical support', 'legal'],
#  'scores': [0.8185835480690002, 0.09302053600549698, 0.05521026626229286, 0.03318570926785469]}

一种常见实现方式是使用在自然语言推理(NLI)任务上训练的模型。每个候选标签会被转换成一个假设,模型再衡量输入在多大程度上蕴含该假设。

这听起来已经很像决策模型了——从很多角度看,它确实就是。

决策模型的不同之处

决策模型的概念不止于把输入归入某个类别。它可以针对同一个状态接收多个命名问题,且各问题的答案类型可以不同:可以是多项选择(choice)、有序量表打分(score),也可以是估计某陈述为真的概率(noul)。

更重要的是,它的接口是围绕可能决策的概率分布设计的。

对比以下三种方式:

特性 分类 零样本分类 决策模型
输出选项的概率分布 是 是 是
推理时定义标签 否 是 是
多个带类型的问题 否 否 是
有序打分与是非决策 取决于具体任务 需改造后可行 原生原语

决策模型的优势并不在于发明了运行时定义的标签或概率分类,而在于把这些能力整合成一个一致的接口,底层还可能采用专为决策优化的架构和训练流程。

决策模型接口

一次决策模型请求由以下两个部分组成:

  1. state(状态)
  2. questions(问题)

State(状态)

state 是模型需要评估的信息,可以是字符串、结构化的 JSON 对象,对于支持的全模态模型也可以是其他形式的数据。

例如:

{
  "customer_message": "I was charged twice. Please refund me today.",
  "subscription": "pro",
  "previous_tickets": 2
}

Questions(问题)及其原语

questions 描述我们想从 state 中了解什么。在决策模型接口中,有三种基础原语,对应不同形式的决策:

  1. Choice: 从多个候选答案中选出一个。
  2. Score: 在有序量表上对某事物打分。
  3. Noul: 以概率形式回答一个是非问题。

下面逐一介绍。

Choice:选项上的概率分布

Choice 是最直观的原语,也最接近传统的分类任务。

假设我们提出问题:

这条客户请求应该由哪个部门处理?

可选的部门包括 Billing(账务)、Technical support(技术支持)和 Sales(销售)。

from transformers import pipeline

decide = pipeline("decision", model="autotrust/GEV-26B-Decide")
decision = decide(
    {
        "state": "I was charged twice for my order and want a refund.",
        "questions": {
            "department": {
                "type": "choice",
                "instructions": "Which team should handle this?",
                "criteria": {
                    "billing": "Payments and refunds",
                    "technical": "Bugs and technical issues",
                    "sales": "Pricing and subscriptions"
                }
            },
        }
    }
)

# {
#   'department': {
#     'type': 'choice',
#     'choice': 'billing',
#     'confidence': 0.9974000453948975,
#     'probabilities': {
#       'billing': 0.9982666969299316,
#       'technical': 0.0010246571619063616,
#       'sales': 0.0007087149424478412
#     }
#   }
# }

模型会给每个选项分配一个 logit。对于 logits($z_1,\ldots,z_K$)(共 K 个类别),可以用 softmax 计算概率:

$p_i=\frac{\exp(z_i/T)}{\sum_{j=1}^{K}\exp(z_j)}$

这里 K 是选项数量。

以下面这个示例分布为例:

选项 概率
Billing(计费) 0.998
Technical support(技术支持) 0.001
Sales(销售) 0.001

所有概率之和为 1:

$\sum_{i=1}^{K}p_i=1$

模型会选择概率最大的选项:

$\hat y=\arg\max_i p_i$

在这个例子中,模型选择了 Billing,概率为 0.998。但其余的概率同样有价值——它们展示了模型在其他选项上的置信度分布。

Score:有序分布的期望值

Choice 适用于在多个离散选项中做选择。但如果我们要在有序尺度上进行度量呢?

比如这个问题:

这个客户请求有多紧急?

我们定义三个等级:

  • 0:低紧急
  • 1:中等紧急
  • 2:高紧急
from transformers import pipeline

decide = pipeline("decision", model="autotrust/GEV-26B-Decide")
decision = decide(
    {
        "state": "I was charged twice for my order and want a refund.",
        "questions": {
            "urgency": {
                "type": "score",
                "instructions": "How urgent is the request?",
                "criteria": ["low", "medium", "high"]
            },
        }
    }
)

# {
#   'urgency': {
#     'type': 'score',
#     'score': 1.7053890228271484,
#     'legend': {
#       '0': 'low',
#       '1': 'medium',
#       '2': 'high'
#     },
#     'confidence': 0.5580834252759814,
#     'probabilities': {
#       '0': 0.014908230863511562,
#       '1': 0.26479458808898926,
#       '2': 0.7202972173690796
#     }
#   }
# }

模型同样会输出一个概率分布:

等级 概率
0 — 低 0.10
1 — 中 0.26
2 — 高 0.72

Score 原语并不只是返回可能性最大的那个等级,而是计算等级索引的期望值。

设 (X) 为表示等级的随机变量,其期望为:

E[X]=∑i=0K−1ipi \mathbb{E}[X]=\sum_{i=0}^{K-1}ip_i E[X]=i=0∑K−1​ipi​

代入本例:

E[X]=0(0.10)+1(0.26)+2(0.72)=1.7 \mathbb{E}[X] = 0(0.10)+1(0.26)+2(0.72)=1.7 E[X]=0(0.10)+1(0.26)+2(0.72)=1.7

因此最终得分是 1.7。

这并不意味着模型选中了一个介于“中”和“高”之间的虚构等级,而是说它的概率分布期望值为 1.7。

Noul:伯努利决策

第三个原语是 Noul,用于表示二元问题。

例如:

客户是否要求退款?

from transformers import pipeline

decide = pipeline("decision", model="autotrust/GEV-26B-Decide")
decision = decide(
    {
        "state": "I was charged twice for my order and want a refund.",
        "questions": {
            "refund": {
                "type": "noul",
                "instructions": "Is the customer requesting a refund?"
            }
        }
    }
)

# {
#   'refund': {
#     'type': 'noul',
#     'noul': 0.9947046637535095
#   }
# }

我们不定义一个选项列表,而是让模型返回答案为真的概率。可以用 Bernoulli 分布来理解这一点(noul 得名于 Bernoulli)。

设 (Y) 表示一个二元结果:

Y∼Bernoulli⁡(p) Y\sim\operatorname{Bernoulli}(p) Y∼Bernoulli(p)

其中

P(Y=1)=p,P(Y=0)=1−p. P(Y=1)=p,\qquad P(Y=0)=1-p. P(Y=1)=p,P(Y=0)=1−p.

如果模型返回:

{"type": "noul", "noul": 0.92}

那么它给 Yes 分配了 0.92 的概率,给 No 分配了 0.08 的概率。

模型并不是随机采样一个二元答案,而是直接返回概率参数本身,至于如何基于这个概率采取行动,则交给应用程序来决定。

置信度:模型有多确定?

到目前为止,我们已经从模型那里获得了概率分布。但决策模型接口还会为 Choice 和 Score 返回一个名为 confidence 的字段。

完整的分布可能包含多个可能的答案,此时把模型信念的集中程度做一个汇总会很有用。confidence 正是为此而设。

对于一个有 (K) 个选项的 Choice,置信度为:

pmax⁡−1K1−1K \frac{p_{\max}-\frac{1}{K}}{1-\frac{1}{K}} 1−K1​pmax​−K1​​

其中 ($p_{\max}$) 是最大的预测概率。

直观理解是:

  • 均匀分布的置信度为 0($p_{\max} = \frac{1}{K}$),即模型认为所有选项的可能性相同。
  • 完全集中于某一个选项的分布置信度为 1($p_{\max} = 1$)。
  • 胜出概率相对均匀分布越大,置信度越高。

在前面的三选一例子里,Billing 的概率是 0.80:

C=3(0.99)−12=0.98 C=\frac{3(0.99)-1}{2}=0.98 C=23(0.99)−1​=0.98

注意,胜出概率是 0.99,但报告的置信度是 0.98。置信度是根据可用选项数对最大概率做归一化后的结果。相比之下,前面那个有序 Score 例子的置信度只有 0.558。

Hugging Face 生态中的决策模型

决策模型是一个年轻且快速演进的领域。每款模型内部的决策机制各不相同(有的用联合对整个 schema 打分的 head,有的在 LLM backbone 上加独立的 readout,还有 edge 端和多模态变体等)。这种多样性是好事,但也有代价:如果每个模型都暴露自己的接口,周边工具就得为每个模型做适配。

我们在 Hugging Face 的目标是就统一的接口达成共识,而不强求统一的实现。决策模型内部想怎么工作都可以,只要接受相同的状态和问题输入,返回相同类型化的决策结果即可。一旦这个契约确立,整个生态只需围绕它构建一次:

  • llama.cpp 等推理引擎可以通过同一套 API 服务任何决策模型
  • Hub 可以一致地打包和呈现这些模型
  • 训练工具可以面向共享的原语,而不是针对各个架构单独开发

本节接下来的内容会逐一介绍这些部分。

  1. 用 Transformers 部署

Transformers 现已支持 DecisionPipeline、AutoModelForDecision 和 DecisionConfig 类。它们沿用了 transformers 中 pipeline 和模型类的整体结构,但专门为决策模型定制。

from transformers import pipeline

decide = pipeline("decision", model="autotrust/GEV-26B-Decide")
print(decide)

# DecisionPipeline: {'model': 'JevForDecision', 'dtype': 'bfloat16', 'device': 'cuda', 'input_modalities': 'text'}

也可以这样查看配置和模型:

from transformers import AutoModelForDecision, DecisionConfig

model_id = "autotrust/GEV-26B-Decide"
config = DecisionConfig.from_pretrained(model_id)
model = AutoModelForDecision.from_pretrained(model_id)

Transformers 还支持 /v1/systemone 端点。

安装 serving 相关依赖后,我们可以启动一个本地服务器:

pip install "transformers[serving]"
transformers serve

使用兼容版本的 Transformers,就可以发送决策请求了:

curl http://localhost:8000/v1/systemone \
  -H "Content-Type: application/json" \
  -d '{
    "model": "autotrust/GEV-26B-Decide",
    "state": "I was charged twice. Please refund me today.",
    "questions": {
      "department": {
        "type": "choice",
        "instructions": "Which team should handle this?",
        "criteria": {
          "billing": "Payments and refunds",
          "technical": "Bugs and technical issues",
          "sales": "Pricing and subscriptions"
        }
      },
      "urgency": {
        "type": "score",
        "instructions": "How urgent is the request?",
        "criteria": ["low", "medium", "high"]
      },
      "refund": {
        "type": "noul",
        "instructions": "Is the customer requesting a refund?"
      }
    }
  }'

返回结果包含三个具名答案,各自带有对应类型的结果和概率。

{
  "model":"autotrust/GEV-26B-Decide",
  "answers":{
    "department":{
      "type":"choice",
      "choice":"billing",
      "confidence":0.9974000453948975,
      "probabilities":{
        "billing":0.9982666969299316,
        "technical":0.0010246571619063616,
        "sales":0.0007087149424478412
        }
    },
    "urgency":{
      "type":"score",
      "score":1.7525686174631119,
      "legend":{"0":"low","1":"medium","2":"high"},
      "confidence":0.6288529792800546,
      "probabilities":{
        "0":0.014000383205711842,
        "1":0.2194305807352066,
        "2":0.7665690183639526
      }
    },
    "refund":{
      "type":"noul",
      "noul":0.9953224062919617
    }
  },
  "usage":{"input_tokens":148,"output_tokens":0}
}

有个有趣的细节:上面这些 API 同样适用于兼容的自回归语言模型。Transformers 会构建决策 prompt,在批量前向传播中评估答案标签的 logits,并应用 softmax,全程无需生成回复文本。这意味着我们可以先不训练新模型,就直接试验这套决策接口。

  1. 用 llama.cpp 部署

llama.cpp 也支持决策模型,使用相同的 /v1/systemone API。

比如,我们可以从 Hub 启动一个 GGUF 决策模型:

llama serve -hf ggml-org/Kev-4B-GGUF

默认服务器运行在 9931 端口。

接下来可以用 http://localhost:9931/v1/systemone 发送一个包含相同 state 和 questions 的请求。由于模型已由服务器选定,请求中可以省略 model 字段。

最有价值的一点是接口兼容性。

curl http://localhost:9931/v1/systemone \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ggml-org/Kev-4B-GGUF",
    "state": "I was charged twice. Please refund me today.",
    "questions": {
      "department": {
        "type": "choice",
        "instructions": "Which team should handle this?",
        "criteria": {
          "billing": "Payments and refunds",
          "technical": "Bugs and technical issues",
          "sales": "Pricing and subscriptions"
        }
      },
      "urgency": {
        "type": "score",
        "instructions": "How urgent is the request?",
        "criteria": ["low", "medium", "high"]
      },
      "refund": {
        "type": "noul",
        "instructions": "Is the customer requesting a refund?"
      }
    }
  }'

  1. 在 Hugging Face Hub 上发现模型

Hugging Face 专门提供了 decision-model 标签,方便查找兼容的模型。这很有必要,因为 decision model 并不要求共享同一种骨干网络或架构。

比如,这个生态中既有基于 ModernBERT 等 encoder 架构的模型,也有从更大的生成式语言模型骨干衍生出来的模型。

  1. 用 Hugging Face 工具训练 decision model

了解了推理之后,下一个问题是我们能否对 decision model 进行定制。由于 decision model 已集成到 transformers 中,我们可以用 Trainer API 来微调它们。

下面是一个微调 JEV-9B 来路由客服请求的示例。例子刻意保持简单,但涵盖了关键部分:

  • 每条样本是一个 decision 请求(一个 state 加上 questions),并配有标准答案。
  • model.decision_config.prepare_inputs 会把请求转换成模型输入,与推理时的处理方式一致。
  • 模型为每个选项输出一个 logit,因此 choice 类型的问题直接用标准的交叉熵损失在选项上训练。
import os; os.environ["CUDA_VISIBLE_DEVICES"]="2"
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForDecision, Trainer, TrainingArguments

checkpoint = "autotrust/JEV-9B"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForDecision.from_pretrained(checkpoint)

examples = [
    ("I was charged twice. Please refund me.", "refund"),
    ("My package has not arrived.", "shipping"),
    ("The application crashes when I open it.", "technical"),
    ("I want my money back.", "refund"),
    ("Where is my delivery?", "shipping"),
    ("I cannot log into my account.", "technical"),
]

options = {
    "refund": "Billing issues and refunds",
    "shipping": "Orders and deliveries",
    "technical": "Software and account issues",
}

def preprocess(text, label):
    request = {
        "state": text,
        "questions": {
            "category": {
                "type": "choice",
                "instructions": "Classify the support request.",
                "criteria": options,
            }
        },
    }
    (inputs, questions), = model.decision_config.prepare_inputs(
        request, tokenizer
    )
    inputs["marks"] = inputs["marks"].unsqueeze(0)
    inputs["num_options"] = torch.tensor([[len(questions[0].options)]])
    inputs["question_type_ids"] = torch.tensor([[1]])  # choice
    inputs["labels"] = torch.tensor(
        [questions[0].options.index(label)]
    )
    return inputs

dataset = [preprocess(text, label) for text, label in examples]

class DecisionTrainer(Trainer):
    def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
        inputs = inputs.copy()
        labels = inputs.pop("labels")
        logits = model(**inputs)

        logits = logits.unsqueeze(0)  # [3] -> [1, 3]
        loss = F.cross_entropy(logits.float(), labels)

        return (loss, logits) if return_outputs else loss

trainer = DecisionTrainer(
    model=model,
    args=TrainingArguments(
        output_dir="./decision-toy",
        max_steps=30,
        per_device_train_batch_size=1,
        learning_rate=1e-3,
        logging_steps=5,
        save_strategy="no",
        report_to="none",
        remove_unused_columns=False,
    ),
    train_dataset=dataset,
    data_collator=lambda batch: batch[0],
)

trainer.train()


TRL 也将为一等公民级别的决策模型训练提供支持(huggingface/trl#8040),届时我们就不用再手写这些底层代码了。截至撰写本文,该 PR 仍处于开放状态。

如果想更进一步,把生成式 LLM 改造成决策模型,Unsloth 提供了一套方案,用 LoRA 和决策评分头对 Qwen 等模型进行微调。

结语

决策模型的价值不在于分类本身有多新颖,而在于它让决策和概率成为软件的一等输出。

传统分类器早已能输出概率,zero-shot 分类器也早已支持运行时定义类别。决策模型则把这些理念整合进了类型化接口:提供多种问题原语、非生成式打分,还能通过专门训练实现可靠且校准良好的决策。

原始来源: HuggingFace博客

评论 (0)