跳到正文
Hugging Face Blog·· 10 天前精選AI 評分64

Hugging Face 生態系如何支援決策模型

Decision Models in Hugging Face

AI 導讀

Hugging Face 將決策模型支援整合至 Transformers,並以共通介面讓模型根據狀態、問題及允許答案輸出結構化決策和機率。

推薦理由

文章比較決策模型與傳統分類、零樣本分類的定位差異,並展示 Transformers 與 llama.cpp 如何透過共通介面處理選項、序位評分及是非判斷。

正文 · 繁體中文

大型語言模型(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
#       }
#     }
# }

這就是決策模型背後的核心概念。

甚麼是決策模型?

決策模型會接收一些輸入情境(狀態),根據一組預先定義的可能答案(基本項)評估問題,並連同機率傳回結構化決策。我們不再要求模型逐個 token 生成答案,而是要求它為應用程式本身已能理解的答案分配機率。

state and primitives for the decision models

TypeSafe AI 介紹了 Jev,並將它描述為一種System One 模型。這個名稱的靈感來自快速、直覺式思考(System 1)與較慢、審慎思考(System 2)之間的區別。

社羣逐漸統一採用決策模型一詞,因為這個詞描述的是模型在計算上的作用,而非援引某種特定的認知理論。在本文其餘部分,我們會稱這些模型為「決策模型」,而非「System One 模型」。(Twitter 上一項探討這類模型應如何稱呼的投票)

決策模型的基本介面如下:

State + Questions + Allowed Answers → Decisions + Probabilities

為甚麼不把 LLM 用於所有事情?

我們可以直接提示 LLM,要求它傳回一個包含所需決策的 JSON 物件。事實上,許多應用程式目前已透過這種方式,使用語言模型進行分類、路由及其他結構化任務。

不過,這種做法有幾個問題。

  • LLM 不一定會遵循指定的結構描述:即使有明確指示,模型仍可能生成無效的 JSON、加入意料之外的鍵,或傳回不在允許選項範圍內的答案。
  • 受限解碼有幫助,但無法消除計算開銷:Outlines 和 XGrammar 等程式庫可以透過限制模型每一步可生成的 token,強制遵循文法或 JSON 結構描述。這能確保輸出符合支援的結構限制,但也會帶來額外的計算工作。
  • 為甚麼要生成完整回應:LLM 的設計目標是開放式生成,但如果應用程式只需在預先定義的答案中作出選擇,自回歸解碼便可能是多餘的工作。

決策模型與分類模型有甚麼不同?

在瞭解決策模型的介面之前,不妨先回顧兩種密切相關的方法:傳統分類和零樣本分類。

傳統分類

假設我們訓練一個分類器,把客戶支援請求分流至以下三個部門:

  • 帳務
  • 技術支援
  • 銷售

傳統分類模型會學習將輸入映射至一組預先定義的標籤。訓練期間,模型會從範例中學習預測這些標籤。分類頭通常會為每個類別產生一個 logit,而 softmax 會將這些 logits 轉換成機率分佈。

這裏的限制是,輸出類別已固定在模型的分類頭中。

如果我們加入第四個部門,例如法務部,現有的分類器不會自動新增相應的輸出類別。我們可能需要修改分類頭、收集訓練數據,並重新訓練或調整模型。

零樣本分類

零樣本分類處理了這項限制的一個重要部分。我們無須要求分類器針對每個輸出類別進行專門訓練,只需在推理時提供候選標籤。

例如:

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]}

與傳統的固定標籤分類器不同,類別可以因應不同請求而改變。讓我們加入另一個部門,例如「法務部」,看看模型的輸出。

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. 狀態
  2. 問題

狀態

狀態是模型應評估的資訊。它可以是字串、結構化 JSON 物件,或是支援全模態模型可處理的其他模態。

例如:

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

問題及其基元

問題描述我們想從狀態中瞭解甚麼。在決策模型介面中,三種基本基元代表不同形式的決策:

  1. Choice:從多個可能答案中選擇一個。
  2. Score:按有序刻度評估某項事物。
  3. Noul:以機率方式回答是/否問題。

讓我們逐一看看。

Choice:選項的機率分佈

Choice 是最直觀的基元,也最接近傳統分類。

假設我們問:

哪個部門應處理這項客戶請求?

可用選項包括帳單、技術支援和銷售。

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 計算機率:

pi=exp⁡(zi/T)∑j=1Kexp⁡(zj) p_i=\frac{\exp(z_i/T)}{\sum_{j=1}^{K}\exp(z_j)}

這裏,(K) 是選項數目。

考慮以下示例分佈:

選項 機率
帳單 0.998
技術支援 0.001
銷售 0.001

機率總和為一:

∑i=1Kpi=1. \sum_{i=1}^{K}p_i=1.

模型會選擇機率最大的選項:

y^=arg⁡max⁡ipi \hat y=\arg\max_i p_i

在這個例子中,模型選擇了帳單,其機率為 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 primitive 不會只回傳最有可能的級別,而是計算級別索引的期望值。

對於代表級別的隨機變數 (X),其期望值為:

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

以這個例子來説:

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

因此,回報的分數為 1.7。

這並不代表模型選擇了一個虛構的級別,介乎中和高之間。這表示其機率分佈的期望值為 1.7。

Noul:Bernoulli 決策

第三個 primitive 是 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)

其中

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

如果模型回傳:

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

它會為「是」分配 0.92 的機率,為「否」分配 0.08 的機率。

模型在這裏不會隨機抽取一個二元答案,而是直接回傳機率參數,讓應用程式決定如何處理。

信心度:模型有多確定?

到目前為止,我們已從模型取得機率分佈。不過,決策模型介面亦會為 Choice 和 Score 回傳一個名為 confidence 的欄位。

完整分佈可能包含多個答案,而概括模型判斷的集中程度會很有用。透過 confidence,我們正好可以做到這一點。

對於有 (K) 個選項的 Choice,信心度為:

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

其中 ($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

請注意,勝出機率為 0.99,但報告的信心度是 0.98。信心度會根據可用選項的數量,將最高機率標準化。相較之下,有序 Score 範例的信心度只有 0.558。

Hugging Face 生態系統中的決策模型

決策模型仍是新興且發展迅速的領域。每個模型在底層作出決策的方式各有不同(例如,對整個結構描述共同評分的輸出頭、建基於 LLM 主幹模型的獨立讀出層、適用於邊緣裝置的模型,以及多模態模型等)。這種多樣性有益,但也帶來代價。如果每個模型都採用自己的介面,周邊的每種工具便都需要針對個別模型作出調整。

Hugging Face 的目標是在不強制採用相同實作方式的前提下,建立共通的介面。決策模型應可自由選擇內部運作方式,只要接受相同的狀態和問題,並傳回相同類型的決策即可。這項協定一旦確立,生態系統的其他部分便可據此一次過建構:

  • llama.cpp 等推理引擎可透過同一 API 提供任何決策模型
  • Hub 可用一致的方式封裝及展示這些模型
  • 而訓練工具可針對共用的基本元件,而非個別架構

本節其餘部分會逐一介紹這些元件。

1. 使用 Transformers 提供服務

Transformers 現在支援 DecisionPipeline、AutoModelForDecision 和 DecisionConfig 類別。這些類別沿用 transformers 中 pipeline 和 model 類別的整體結構,但專為決策模型設計。

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 endpoint。

我們可以使用提供服務所需的依賴項,啟動本機伺服器:

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 會建立決策提示詞,在批次前向傳播中評估答案標籤的 logits,並套用 softmax,而不生成回應文字。這表示我們可以試用決策介面,而不一定要訓練新模型。

2. 使用 llama.cpp 提供服務

llama.cpp 亦支援決策模型,並使用相同的 /v1/systemone API。

例如,我們可以從 Hub 啟動 GGUF 決策模型:

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

預設伺服器會在連接埠 9931 執行。

接着,我們可以使用 http://localhost:9931/v1/systemone 傳送包含相同狀態和問題的請求。由伺服器選擇模型後,請求中便可省略 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?"
      }
    }
  }'

3. 在 Hugging Face Hub 上尋找模型

Hugging Face 為尋找相容模型推出專用的 decision-model 標籤。這項功能很實用,因為決策模型不必採用相同的主幹模型或架構。

例如,生態系統中既有以 ModernBERT 等編碼器架構為基礎的模型,也有源自較大型生成式語言模型主幹的模型。

4. 使用 Hugging Face 工具訓練決策模型

瞭解推理後,下一個問題是我們能否調整決策模型。由於決策模型已整合在 transformers 中,我們可以使用 Trainer API 對它們進行微調。

以下是一個簡單示例,透過微調 JEV-9B 來分流支援請求。示例刻意保持精簡,但展示了重要部分:

  • 每個示例都是一項決策請求(由 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 等模型。

最後想法

決策模型之所以值得關注,並非因為分類是新事物,而是因為它們讓決策和概率成為軟件的一級輸出。

傳統分類器已能產生概率,零樣本分類器亦已支援在執行時定義類別。決策模型則把這些概念帶到具型別的介面中,並提供多種問題基本構件、非生成式評分,以及透過專門訓練實現可靠且經校準決策的可能性。

來源:Hugging Face Blog · huggingface.co