Articles

How to Train a Decision Model: Data, Fine-Tuning, and Evaluation

Train a decision model for agent triage on an 8 GB Mac: map Banking77 to five queues, fine-tune with LoRA, score held-out accuracy, calibration and baselines.

· 19 min read
decision-model-training lora-fine-tuning mlx llm-evaluation model-calibration data-annotation agent-triage
Banner with the post title on the left and, on the right, a prompt that asks for one letter above five keycaps A to E, each a single token for one support queue, feeding a softmax that gives one probability per queue.
Table of Contents

Take a hypothetical bank support agent that needs a decision model: read a customer message, return one of five queues with a probability for each. In our run on public Banking77 data, the Qwen3.5-0.8B-4bit model, asked zero-shot, sent 124 of 126 held-out security and fraud reports elsewhere. A decision tree, which splits tabular features, is a different tool.

One option is to train a decision model for exactly these five answers. The same zero-shot model got 576 of 1,311 held-out test messages right, so labelled data has room to help. The open question is whether fine-tuning is the cheapest way to close that gap.

You get the data, LoRA fine-tuning on one 8 GB laptop and a held-out evaluation against zero-shot and classical baselines, plus every script needed to rerun it. On this split a cheap TF-IDF classifier beat the fine-tuned adapter on accuracy, and that result shapes the advice.

TL;DR

  • To train a decision model for agent triage, fix the option list first, map every raw label to one option, and split with a fixed seed before any training.
  • Single-token letters A to E give one probability per queue from five log-probabilities, as long as the Qwen3.5 prompt closes its thinking block.
  • LoRA at rank 8 on 8 of 24 layers trained about one epoch over 10,461 Banking77 messages on an 8 GB M1 in about 3 hours 36 minutes.
  • On 1,311 held-out test rows the adapter reached 0.9352 accuracy and 0.0189 ECE, up from 0.4394 zero-shot, and a validation-fixed threshold sent 89 rows to people.
  • A TF-IDF plus logistic regression baseline reached 0.9672 on the same rows, so fit it first, and keep the hashes, config and split so anyone can rerun the comparison.

When to train a decision model instead of calling a hosted one

Train your own model when the option list is fixed, the message volume is high, the data cannot leave your network, or a hosted call misses your latency budget. If none of those holds, a hosted model or a cheap classifier is less work, and our run shows the classifier deserves the first try.

A fixed option list matters because a trained model answers only with the letters it learned. Volume, residency and latency favour your own hardware: no per-call price, no messages leaving your network and no round trip to an external service on every request.

For hosted candidates and the wider concept, start with our guide to AI decision models.

Build the triage dataset from labels you can trust

A training set you can trust needs a fixed option list, a written mapping from raw labels to options, a split stratified on the finest label, and a check that no test message reappears in training. Our run pooled 13,083 Banking77 messages, mapped 77 intents to five queues, and split them 80/10/10 with seed 7.

Each step guards against a different failure. The mapping is a product decision, so write it where reviewers can argue with it. Stratifying on the finest label keeps rare intents in every split, and the leakage check keeps the test honest, since a test message seen in training inflates every score.

Five queues and where the labels come from

The options are A card services, B payments and transfers, C fees and refunds, D account and identity, and E security and fraud. In production, reviewers in a review queue pick one option per message, and two reviewers per item give you agreement. For tooling, see LLM annotation tools.

This run maps public data. The Banking77 dataset card lists 13,083 customer service queries in 77 intents (train 10,003, test 3,080), labelled by its authors and licensed CC BY 4.0. We mapped the intents to five options and re-split the pooled rows.

Attribution: Casanueva, Temcinas, Gerz, Henderson and Vulic, Efficient Intent Detection with Dual Sentence Encoders, NLP for ConvAI workshop at ACL 2020.

Mapping 77 Banking77 intents to five options

The table gives every intent’s option: 22 go to A, 24 to B, 15 to C, 9 to D and 7 to E, with none dropped. prepare.py asserts that the mapping covers all 77 label ids, so a missing row stops the run before any split is written.

OptionIntentsEvery intent mappedPooled rowsShare
A card services22activate_my_card, apple_pay_or_google_pay, atm_support, card_about_to_expire, card_acceptance, card_arrival, card_delivery_estimate, card_linking, card_not_working, card_swallowed, change_pin, contactless_not_working, disposable_card_limits, get_disposable_virtual_card, get_physical_card, getting_spare_card, getting_virtual_card, order_physical_card, pin_blocked, supported_cards_and_currencies, virtual_card_not_working, visa_or_mastercard3,2650.250
B payments and transfers24automatic_top_up, balance_not_updated_after_bank_transfer, balance_not_updated_after_cheque_or_cash_deposit, beneficiary_not_allowed, cancel_transfer, declined_card_payment, declined_cash_withdrawal, declined_transfer, failed_transfer, pending_card_payment, pending_cash_withdrawal, pending_top_up, pending_transfer, receiving_money, reverted_card_payment?, top_up_by_cash_or_cheque, top_up_failed, top_up_limits, top_up_reverted, topping_up_by_card, transfer_into_account, transfer_not_received_by_recipient, transfer_timing, verify_top_up4,3460.332
C fees and refunds15card_payment_fee_charged, card_payment_wrong_exchange_rate, cash_withdrawal_charge, exchange_charge, exchange_rate, exchange_via_app, extra_charge_on_statement, fiat_currency_support, Refund_not_showing_up, request_refund, top_up_by_bank_transfer_charge, top_up_by_card_charge, transaction_charged_twice, transfer_fee_charged, wrong_exchange_rate_for_cash_withdrawal2,8400.217
D account and identity9age_limit, country_support, edit_personal_details, passcode_forgotten, terminate_account, unable_to_verify_identity, verify_my_identity, verify_source_of_funds, why_verify_identity1,3730.105
E security and fraud7card_payment_not_recognised, cash_withdrawal_not_recognised, compromised_card, direct_debit_payment_not_recognised, lost_or_stolen_card, lost_or_stolen_phone, wrong_amount_of_cash_received1,2590.096

Label 51 keeps the card’s capital R in Refund_not_showing_up, and label 53 keeps the question mark in reverted_card_payment?. Some rows are our calls, such as wrong_amount_of_cash_received in E and country_support in D. mapping.csv is committed and hashed, so you can change one row and rerun.

Class balance and a stratified split with seed 7

Classes are uneven: A has 3,265 of the 13,083 pooled rows (0.250), B 4,346 (0.332), C 2,840 (0.217), D 1,373 (0.105) and E 1,259 (0.096), with 75 to 227 rows per intent. E is the smallest class and the costliest to get wrong.

class balance (rows per option, all pooled rows and per split)
option  name                         total  train  valid   test  share
A       card services                 3265   2607    329    329  0.250
B       payments and transfers        4346   3476    435    435  0.332
C       fees and refunds              2840   2270    285    285  0.217
D       account and identity          1373   1101    136    136  0.105
E       security and fraud            1259   1007    126    126  0.096
rows per intent: min 75, max 227; every intent present in every split: True
    # stratified 80/10/10 split on the 77 intents
    rng = random.Random(SEED)
    by = collections.defaultdict(list)
    for r in rows:
        by[r["label"]].append(r["id"])
    split = {}
    for lab in sorted(by):
        ids = by[lab][:]; rng.shuffle(ids)
        nv = nt = round(0.1 * len(ids))
        for k, i in enumerate(ids):
            split[i] = "valid" if k < nv else "test" if k < nv + nt else "train"
    for r in rows:
        r["split"] = split[r["id"]]
    S = {s: [r["id"] for r in rows if r["split"] == s] for s in ("train", "valid", "test")}
    print("split sizes", {s: len(v) for s, v in S.items()})

The split pools the official train and test files and stratifies 80/10/10 on the 77 intents with Python’s random seed 7: 10,461 train, 1,311 validation and 1,311 test rows, every intent in every split. Scores on our test split do not compare with results on the official test file.

pooled rows 13083 (official train 10003, official test 3080), intents 77, options 5
split sizes {'train': 10461, 'valid': 1311, 'test': 1311}

Leakage checks for duplicates across splits

prepare.py checks normalised exact matches and near duplicates at word unigram plus bigram Jaccard of 0.8 or more, hashed to 16,384 buckets. Validation against train had 7 exact and 57 near duplicates, test against train 10 and 72, test against validation 1 and 9; no pair crossed options.

leakage check: normalised exact match and word uni+bigram Jaccard >= 0.8 (hashed to 16384 buckets)
  valid vs train: rows 1311, exact duplicates 7, near duplicates (Jaccard >= 0.8) 57, of those with a different option 0, max Jaccard 1.000
  test vs train: rows 1311, exact duplicates 10, near duplicates (Jaccard >= 0.8) 72, of those with a different option 0, max Jaccard 1.000
  test vs valid: rows 1311, exact duplicates 1, near duplicates (Jaccard >= 0.8) 9, of those with a different option 0, max Jaccard 1.000

The flagged rows stay in the test set, and evaluation also scores the 1,239 test rows with no near duplicate in train: adapter 0.9330, baseline 0.9653, zero-shot 0.4391, each within 0.003 of its full-test score. The general gate is covered in data quality gates before fine-tuning.

Single-token option labels that turn into probabilities

Give each option a letter that the tokenizer encodes as a single token, then read the model’s log-probabilities for those five letters at the answer position. A softmax over the five values gives the probability for each queue, so every answer comes back as one of the five letters, already scored, from a single forward pass.

That gives constrained decoding without a decoding library: only five letters can come back, so nothing free-form needs validating and no retry follows an invented sixth option. The prompt below, from common.py, is shared by the training data, validation and evaluation.

def user_prompt(text):
    lines = "\n".join(f"{k}) {OPTIONS[k]}" for k in LETTERS)
    return (
        "You triage customer messages for a bank's support team. "
        "Pick the queue that should own the message.\n"
        f"{lines}\n"
        "Answer with one letter.\n"
        f"Message: {text}"
    )


def messages(text, letter=None):
    m = [{"role": "user", "content": user_prompt(text)}]
    if letter is not None:
        m.append({"role": "assistant", "content": letter})
    return m


def generation_text(tok, text):
    """The evaluation prompt. enable_thinking=False is REQUIRED: without it mlx-lm's wrapper turns
    thinking on, the prompt opens a <think> block and the first generated token is not an option letter."""
    return tok.apply_chat_template(
        messages(text), add_generation_prompt=True, enable_thinking=False, tokenize=False
    )
option letters A-E token ids [32, 33, 34, 35, 36] (each a single token)
generation prompt ends with 'tant\n<think>\n\n</think>\n\n'

Reading the five letter log-probabilities

Letters A to E are token ids 32 to 36 here, each a single token. evaluate.py takes the last-position logits, keeps the five letter values and renormalises them with logsumexp. A printed self-check matched the full forward pass with a maximum difference of 0.0000 and the same argmax.

def score(model, tok, rows, tag):
    """Returns (n,5) option log-probs renormalised over the five letters, and (n,) probability mass the model put on them."""
    CACHE.mkdir(exist_ok=True)
    f = CACHE / f"{tag}.npz"
    if f.exists():
        z = np.load(f); return z["lp"], z["mass"]
    lid = [tok.encode(l, add_special_tokens=False) for l in LETTERS]
    assert all(len(x) == 1 for x in lid), "option letters must be single tokens"
    lid = mx.array([x[0] for x in lid])
    lp, mass, t0 = [], [], time.time()
    for k, r in enumerate(rows):
        ids = mx.array([tok.encode(generation_text(tok, r["text"]), add_special_tokens=False)])
        lg = head_logits(model, ids)
        five = lg[lid]
        lp.append(five - mx.logsumexp(five)); mass.append(mx.exp(mx.logsumexp(five) - mx.logsumexp(lg)))
        mx.eval(lp[-1], mass[-1])  # evaluate every row: a lazy graph over 1,311 rows will not fit in 8 GB
        if k % 100 == 99:
            mx.clear_cache()
            print(f"    {tag}: {k+1}/{len(rows)} rows, {time.time()-t0:.0f}s", flush=True)
    lp = np.array(mx.stack(lp)); mass = np.array(mx.stack(mass))
    np.savez(f, lp=lp, mass=mass)
    return lp, mass

Before renormalising, the five letters held a mean probability mass of 0.9875 for the zero-shot model and 0.9994 for the adapter on test. Geuter, Cheng and Alvarez-Melis describe reading answers from letter logits at the last token position (arXiv, 2026-10-12). Some stacks train a separate scoring head; letter logits add no layer.

Why the empty thinking block matters for Qwen3.5

The upstream Qwen3.5-0.8B card says the model runs in non-thinking mode by default, but mlx-lm 0.32.2’s tokenizer wrapper sets enable_thinking to the tokenizer’s has_thinking flag when the caller omits it (tokenizer_utils.py lines 391 to 395). In our 2026-11-19 check without the flag, the top first token was “Thinking”, not a letter.

With enable_thinking=False the prompt ends in an empty think block, as printed above, and the Qwen3.5-0.8B-4bit model card template writes the same block in the final assistant turn. With mask_prompt on, the supervised span also covers the closing think tokens (mlx-lm issue 2062, open on 2026-11-20).

Train a decision model with LoRA on an 8 GB Mac

LoRA trains small low-rank matrices next to frozen weights, which is why a 0.8B model stored in 4 bits fits on an 8 GB Apple Silicon laptop. Our run trained rank 8 adapters on the last 8 of 24 layers for about one epoch over 10,461 messages, which took 3 hours 36 minutes on an M1.

The stack is mlx 0.32.4 and mlx-lm 0.32.2 from PyPI with mlx-community/Qwen3.5-0.8B-4bit, a 652,029,391-byte download that run.sh calls 622 MB in binary units. LoRA comes from the LoRA paper, and mlx-lm trains a quantized model through its QLoRA path.

That Qwen3.5 checkpoint, model type qwen3_5, loads through Qwen3.5 support in mlx-lm 0.32.2.

Every hyperparameter in one committed config

config.yaml holds every setting, and python -m mlx_lm lora -c config.yaml is the one training command. Rank 8, scale 20.0 and dropout 0.0 sit under lora_parameters because mlx-lm 0.32.2 has no command-line flag for them; the mlx-lm LoRA guide lists the rest.

# mlx_lm.lora config. Train split 10,461 rows, about one epoch: 5,231 steps of 2; mlx-lm 0.32.2 builds 5,230 length-sorted batches per pass and leaves the same row, last in the length sort (a longest row), out of every pass (prepare.py writes min(train rows, iters x batch)).
# batch_size 2, num_layers 8 and grad_checkpoint true (recomputes activations, same gradients) are what fit in 8 GB on this M1.
model: mlx-community/Qwen3.5-0.8B-4bit
train: true
fine_tune_type: lora
optimizer: adamw
data: data
adapter_path: adapters
seed: 7
num_layers: 8
batch_size: 2
iters: 5231
learning_rate: 1.0e-4
max_seq_length: 256
mask_prompt: true
grad_checkpoint: true
steps_per_report: 10
steps_per_eval: 500
val_batches: 50
save_every: 100
lr_schedule:
  name: cosine_decay
  arguments: [1.0e-4, 5231, 1.0e-6]
  warmup: 50
lora_parameters:
  rank: 8
  scale: 20.0
  dropout: 0.0
echo "== 2 train (LoRA, mlx_lm.lora, config.yaml)"; date -u +"start %FT%TZ"; $RUN python -m mlx_lm lora -c config.yaml 2>&1 | tr '\r' '\n' | sed 's/\x1b\[[0-9;]*[A-Za-z]//g' | grep -v '^\s*$' | grep -v '^train *[█░]' ; date -u +"end %FT%TZ"
Trainable parameters: 0.240% (1.804M/752.392M)

The run trained 0.240% of the parameters. It counts as about one epoch because mlx-lm 0.32.2 builds 5,230 length-sorted batches of 2 from the 10,461 train rows, so the same longest row sits out every pass, and step 5,231 starts a second shuffled pass.

The training curve from validation loss

Validation loss, computed on 50 validation batches rather than the full split, fell from 3.483 at iteration 1 to 0.231 at 500 and 0.061 at 2,000, then moved between 0.029 and 0.065 before ending at 0.040 at 5,231. Every printed point is in the chart below.

Line chart of validation loss at twelve evaluation points, falling from 3.483 at iteration 1 to 0.040 at iteration 5,231

Training loss, printed every 10 steps, is noisy: it spiked to 0.980 and 1.000 at steps 570 and 580. The printed loss also counts one padding position per sequence (mlx-lm issue 2029, open on 2026-11-20), so every quality claim rests on the held-out evaluation.

How to train a decision model when memory is tight

Four settings kept the run inside 8 GB: batch size 2, LoRA on 8 of 24 layers, gradient checkpointing (recomputed activations, same gradients), and max_seq_length 256 against a longest training example of 170 tokens (mean 87.5, none truncated). The LoRA guide’s memory tips name the same levers.

Step time on this model family grows with the number of trained layers (mlx-lm issue 1956, open on 2026-11-20). run.sh printed a start of 18:45:24 UTC and an end of 22:21:54 UTC on 2026-11-19, or 3 h 36 min 30 s, for a final adapter file of 7,230,451 bytes.

Held-out results against zero-shot and classical baselines

Score every model on the same 1,311 held-out Banking77 test rows with the same prompt, and fix every choice on validation first. The Qwen3.5-0.8B-4bit LoRA adapter reached 0.9352 accuracy against 0.4394 zero-shot, while TF-IDF plus logistic regression reached 0.9672, so the cheap classifier won on accuracy.

MeasureZero-shot baseLoRA adapterTF-IDF plus logistic regression
Accuracy0.43940.93520.9672
Macro-F10.25930.93140.9666
Security and fraud recall0.0160.8410.937
ECE, 10 equal-width bins0.15640.01890.0405
Temperature fitted on validation0.990.970.69
ECE after temperature0.15470.01620.0047
Threshold chosen on validationNone met the rule0.6250.3 (grid floor)
Auto-handled on testNo threshold met the rule1,222 at 0.95831,311 at 0.9672
Escalated to people on testNo threshold met the rule890
Security rows auto-sent to another queueNot applicable11 of 1268 of 126
At the adapter’s test coverage, 1,222 rows (matched, not a threshold)Not applicable0.9583 accuracy, 11 of 126 security rows0.9869 accuracy, 4 of 126 security rows
Accuracy on 1,239 rows with no near duplicate0.43910.93300.9653

The protocol: metrics come from the test split only, temperature and threshold are fitted on validation and applied to test once, and all three models read the same rows through the same report() code. Our guide to evaluating LLM classifiers defines each metric.

Accuracy, macro-F1 and per-class recall on 1,311 test rows

The adapter scored 0.9352 accuracy and 0.9314 macro-F1. Precision and recall ran A 0.928 and 0.939, B 0.926 and 0.952, C 0.950 and 0.933, D 0.949 and 0.963, E 0.938 and 0.841, so security and fraud has the lowest recall: 106 of 126 reached E.

accuracy 0.9352   macro-F1 0.9314   ECE (10 equal-width bins) 0.0189   mean probability mass on the 5 letters 0.9994
per-class (option, precision, recall, F1, support)
  A card services          0.928  0.939  0.934  329
  B payments and transfers 0.926  0.952  0.939  435
  C fees and refunds       0.950  0.933  0.942  285
  D account and identity   0.949  0.963  0.956  136
  E security and fraud     0.938  0.841  0.887  126

Zero-shot macro-F1 was 0.2593 because the base model labelled most messages A (recall 0.967, precision 0.372) and almost never chose C, D or E, with recall 0.021, 0.074 and 0.016. Its accuracy comes mostly from the two largest queues, A and B.

Where the adapter confuses queues

Rows are the true queue and columns the predicted one. The costly cell is the E row: 20 of 126 security and fraud messages went elsewhere, 7 to A, 7 to B, 5 to C and 1 to D, each a security or fraud report waiting in the wrong team’s queue.

confusion matrix (rows true A-E, columns predicted A-E)
  A   309   12    3    5    0
  B    10  414    6    1    4
  C     5   11  266    0    3
  D     2    3    0  131    0
  E     7    7    5    1  106

The weakest intents point at boundaries you may redraw: supported_cards_and_currencies 0.53 (n=17), top_up_by_bank_transfer_charge 0.60 (n=15) and card_payment_not_recognised 0.62 (n=21). The last is a security intent, so its misses land in the E row above.

Calibration error in ten equal-width bins

ECE bins predictions by top-option probability, takes the gap between mean confidence and accuracy in each bin, and weights it by bin size, as defined in On Calibration of Modern Neural Networks by Guo, Pleiss, Sun and Weinberger (2017), building on Naeini et al. (2015).

We use 10 equal-width bins on the top-option probability; the paper’s tables use 15, so values do not compare directly. Adapter test ECE was 0.0189 (validation 0.0121), and 1,037 of 1,311 test rows sit in the 0.9 to 1.0 bin at confidence 0.981 and accuracy 0.986.

def ece_table(conf, correct):
    idx = np.clip(np.ceil(conf * NBINS).astype(int) - 1, 0, NBINS - 1)
    rows, ece = [], 0.0
    for b in range(NBINS):
        m = idx == b
        n = int(m.sum())
        c = float(conf[m].mean()) if n else None
        a = float(correct[m].mean()) if n else None
        if n:
            ece += n / len(conf) * abs(a - c)
        rows.append({"bin": f"({b/NBINS:.1f},{(b+1)/NBINS:.1f}]", "n": n, "mean_confidence": c, "accuracy": a,
                     "gap": None if n == 0 else abs(a - c)})
    return float(ece), rows
reliability table (test)
  bin          n   mean_conf  accuracy  gap
  (0.0,0.1]      0   -          -         -
  (0.1,0.2]      0   -          -         -
  (0.2,0.3]      0   -          -         -
  (0.3,0.4]      2   0.370      0.500     0.130
  (0.4,0.5]     22   0.477      0.364     0.114
  (0.5,0.6]     51   0.549      0.706     0.157
  (0.6,0.7]     43   0.646      0.581     0.064
  (0.7,0.8]     54   0.754      0.796     0.042
  (0.8,0.9]    102   0.854      0.892     0.038
  (0.9,1.0]   1037   0.981      0.986     0.005

Bar chart of mean confidence and accuracy in each of seven occupied probability bins for the LoRA adapter on 1,311 test rows

The largest gap is the 0.5 to 0.6 bin: 51 rows at 0.549 confidence and 0.706 accuracy, so it is under-confident. The 0.4 to 0.5 bin is over-confident. A validation-fitted temperature of 0.97 moves test ECE to 0.0162. Zero-shot ECE was 0.1564, then 0.1547 at its fitted 0.99.

The escalation threshold fixed on validation

A message is auto-handled when its top probability reaches the threshold: the smallest value on a grid from 0.300 to 0.999, in steps of 0.005, whose auto-handled validation accuracy is at least 0.95 while auto-handling at least 5% of validation rows. The zero-shot model never met it.

def choose_threshold(conf, correct):
    for t in GRID:
        m = conf >= t
        if m.mean() >= MIN_COVER and correct[m].mean() >= TARGET_ACC:
            return t
    return None

The adapter’s threshold is 0.625. On validation it auto-handled 1,244 of 1,311 rows at 0.9502; on test, 1,222 at 0.9583, sending 89 to people, against 0.9352 if every row were answered. That leaves 11 of the 126 true security rows auto-sent to another queue.

The TF-IDF baseline scored higher on this split

Settings were fixed before the first run and never tuned: scikit-learn 1.9.1’s TfidfVectorizer on word 1 and 2 grams with sublinear tf, then logistic regression with C=10 and seed 7, fit on the same 10,461 train rows.

    vec = TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True, min_df=1)
    X = vec.fit_transform([r["text"] for r in train])
    clf = LogisticRegression(C=10.0, max_iter=2000, random_state=7).fit(X, [LETTERS.index(r["option"]) for r in train])

It reached 0.9672 accuracy, 0.9666 macro-F1 and 0.937 security recall, with raw ECE 0.0405 falling to 0.0047 at its fitted 0.69. Its validation rule stopped at the grid floor of 0.3, so it escalated 0 test rows and auto-sent 8 of 126 security rows elsewhere.

At the adapter’s coverage, its 1,222 most confident test rows were auto-handled at 0.9869 against 0.9583, with 4 security rows auto-sent elsewhere against 11. The baseline led on accuracy, macro-F1, ECE after scaling and matched-coverage triage, trailing only on raw ECE. The run isolates no cause, so the adapter’s claim is its gain over zero-shot.

at the adapter's test coverage (1222 most confident test rows auto-handled, 89 escalated, lowest auto-handled confidence 0.709): auto-handled accuracy 0.9869, true security rows auto-sent to another queue 4

Reproducible artifacts and a one-command re-run

This guide publishes the dataset revision, mapping, config, scripts, all three printed eval reports, file hashes, pinned package versions and a one-script rerun of all four steps. The data split can be rebuilt exactly. The published artifacts do not pin the base model and tokenizer revision, so a rerun against the current checkpoint may produce different model scores.

Each artifact closes one gap: the dataset revision and parquet hashes catch a changed source, split.csv and mapping.csv fix rows and labels, config.yaml and the adapter’s SHA-256 identify the training setup and adapter, but not the base model revision, and the printed reports hold every score in the tables above.

What the folder records and hashes

prepare.py pins dataset revision 1846984189f2bc0ac51c6fc3a600fa9e1714e0c6, and hashes.json records SHA-256 for the parquets, pooled data, mapping, split, config, training files, code, near duplicates, adapter (prefix fb386122), eval and baseline JSON and both outputs. The trained config hashed to 6591f0ad; the published 110d0abb changes only comment line 1.

  "banking77_train.parquet": "8dc89b87a188509c42cce5a086e8f7c1ff4a225bdd9ae3f23e6cdfa5806e363a",
  "banking77_test.parquet": "1f40f777c33f0edfa6c530ff84fe2878db6490838c12d22d036f626948905341",
  "pooled_data_sha256": "84999d823077703e42b851e452b6748d4d19812650c28b31269a31edd27f2bb4",
  "mapping.csv_sha256": "93722d03bcab55ff391e102d6ddcdadddcddd4b97dee5a9c5f7d19043a158865",
  "split.csv_sha256": "d8d60cfb5159d5d4290990d6173be3f115b2f1c0248a65babc7d1217f3804f99",
  "config.yaml_sha256": "110d0abb7ee1725a0d948baeb6f2ecf33546513bd97d8f97f9f87a8d87c6444a",
  "adapters/adapters.safetensors_sha256": "fb38612252c9fe077e9df66619c277a1126733538a7b365d6f222600c66480fa",

requirements.txt pins the eight direct dependencies whose versions the run printed below, and run.sh adds scikit-learn 1.9.1 for the baseline step. Transitive packages resolve at run time (the run printed “Installed 39 packages”), so the printed version lines record what ran.

mlx 0.32.4
mlx-lm 0.32.2
pyarrow 26.0.1
numpy 2.5.5
transformers 5.23.0
huggingface_hub 2.4.0
safetensors 0.8.0
pyyaml 6.0.3

Re-running the whole pipeline

With uv on an Apple Silicon Mac with 8 GB or more, bash run.sh 2>&1 | tee run_output_$(date +%F).txt runs every step and downloads the model plus parquets of 293,553 and 92,409 bytes. Delete cache/ to rescore; scoring printed 147 to 158 seconds per 1,300 rows.

The four Python scripts and run.sh below were tested end to end on an 8 GB M1 and are embedded in full, plus three run-output blocks. A re-run rewrites hashes.json with data hashes only. The adapter file is not distributed; its SHA-256 identifies the scored weights, so a retrained adapter compares by printed metrics.

common.py: the shared prompt, used by training data, validation and evaluation
"""Shared prompt template for training data, validation and evaluation (one source of truth)."""
import csv
from pathlib import Path

HERE = Path(__file__).parent
MODEL = "mlx-community/Qwen3.5-0.8B-4bit"


def load_mapping():
    with open(HERE / "mapping.csv", newline="") as f:
        return list(csv.DictReader(f))


MAPPING = load_mapping()
OPTIONS = {}
for _r in MAPPING:
    OPTIONS.setdefault(_r["option_letter"], _r["option_name"])
LETTERS = sorted(OPTIONS)  # A..E, each a single token in the Qwen3.5 tokenizer


def user_prompt(text):
    lines = "\n".join(f"{k}) {OPTIONS[k]}" for k in LETTERS)
    return (
        "You triage customer messages for a bank's support team. "
        "Pick the queue that should own the message.\n"
        f"{lines}\n"
        "Answer with one letter.\n"
        f"Message: {text}"
    )


def messages(text, letter=None):
    m = [{"role": "user", "content": user_prompt(text)}]
    if letter is not None:
        m.append({"role": "assistant", "content": letter})
    return m


def generation_text(tok, text):
    """The evaluation prompt. enable_thinking=False is REQUIRED: without it mlx-lm's wrapper turns
    thinking on, the prompt opens a <think> block and the first generated token is not an option letter."""
    return tok.apply_chat_template(
        messages(text), add_generation_prompt=True, enable_thinking=False, tokenize=False
    )
prepare.py: download, map, split, leakage check and data hashes
"""Download Banking77, map 77 intents to 5 triage options, split, check leakage, hash.

Dataset: PolyAI/banking77, CC-BY-4.0. Casanueva, Temcinas, Gerz, Henderson, Vulic,
"Efficient Intent Detection with Dual Sentence Encoders", 2020, https://arxiv.org/abs/2003.04807
Pooled official train + test (13,083 rows), stratified 80/10/10 on the 77 intents, seed 7.
"""
import collections, csv, hashlib, json, os, random, re, sys, urllib.request, zlib
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
import yaml

from common import HERE, MAPPING, MODEL, generation_text, messages

SEED = 7
REV = "1846984189f2bc0ac51c6fc3a600fa9e1714e0c6"  # dataset card revision read 2026-11-19
URL = f"https://huggingface.co/datasets/PolyAI/banking77/resolve/{REV}/data/"
RAW, DATA = HERE / "raw", HERE / "data"
JACCARD = 0.8   # near-duplicate threshold on word unigram + bigram sets
BUCKETS = 16384  # hashed feature space for the near-duplicate index


def sha(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def norm(t):
    return " ".join(re.sub(r"[^a-z0-9]+", " ", t.lower()).split())


def feats(t):
    w = norm(t).split()
    return sorted({zlib.crc32(x.encode()) % BUCKETS for x in w + [a + " " + b for a, b in zip(w, w[1:])]})


def near_dups(query_ids, ref_ids, F):
    """For each query id, best Jaccard against any ref id (inverted index + bincount)."""
    post = collections.defaultdict(list)
    for j, r in enumerate(ref_ids):
        for b in F[r]:
            post[b].append(j)
    post = {b: np.array(v) for b, v in post.items()}
    size = np.array([len(F[r]) for r in ref_ids])
    out = {}
    for q in query_ids:
        hit = [post[b] for b in F[q] if b in post]
        if not hit:
            out[q] = (0.0, None); continue
        inter = np.bincount(np.concatenate(hit), minlength=len(ref_ids))
        jac = inter / (len(F[q]) + size - inter)
        j = int(jac.argmax())
        out[q] = (float(jac[j]), ref_ids[j])
    return out


def main():
    cfg = yaml.safe_load(open(HERE / "config.yaml"))
    RAW.mkdir(exist_ok=True); DATA.mkdir(exist_ok=True)
    hashes = {}
    rows = []  # pooled: official train first, then official test
    for src in ("train", "test"):
        p = RAW / f"{src}.parquet"
        if not p.exists():
            urllib.request.urlretrieve(URL + f"{src}-00000-of-00001.parquet", p)
        hashes[f"banking77_{src}.parquet"] = sha(p)
        for r in pq.read_table(p).to_pylist():
            rows.append({"source": src, "label": r["label"], "text": r["text"]})
    for i, r in enumerate(rows):
        r["id"] = i
    letter = {int(m["label_id"]): m["option_letter"] for m in MAPPING}
    assert sorted(letter) == list(range(77)), "mapping must cover all 77 intents"
    assert {r["label"] for r in rows} == set(range(77))
    print(f"pooled rows {len(rows)} (official train {sum(r['source']=='train' for r in rows)}, "
          f"official test {sum(r['source']=='test' for r in rows)}), intents 77, options 5")

    # stratified 80/10/10 split on the 77 intents
    rng = random.Random(SEED)
    by = collections.defaultdict(list)
    for r in rows:
        by[r["label"]].append(r["id"])
    split = {}
    for lab in sorted(by):
        ids = by[lab][:]; rng.shuffle(ids)
        nv = nt = round(0.1 * len(ids))
        for k, i in enumerate(ids):
            split[i] = "valid" if k < nv else "test" if k < nv + nt else "train"
    for r in rows:
        r["split"] = split[r["id"]]
    S = {s: [r["id"] for r in rows if r["split"] == s] for s in ("train", "valid", "test")}
    print("split sizes", {s: len(v) for s, v in S.items()})

    # training rows: min(train rows, iters * batch_size), proportional per intent (largest remainder). With the committed
    # config (5231 x 2 = 10,462 >= 10,461) this is the whole train split, so in_train_subsample is 1 for every train row.
    n_train = min(len(S["train"]), cfg["iters"] * cfg["batch_size"])
    tby = collections.defaultdict(list)
    for i in S["train"]:
        tby[rows[i]["label"]].append(i)
    quota = {l: n_train * len(v) / len(S["train"]) for l, v in tby.items()}
    take = {l: int(q) for l, q in quota.items()}
    for l in sorted(quota, key=lambda l: quota[l] - take[l], reverse=True)[: n_train - sum(take.values())]:
        take[l] += 1
    sub = set()
    for l, v in tby.items():
        v = v[:]; random.Random(SEED + l).shuffle(v); sub.update(v[: take[l]])
    for r in rows:
        r["in_train_subsample"] = int(r["id"] in sub)
    print(f"training subsample {len(sub)} of {len(S['train'])} train rows "
          f"(iters {cfg['iters']} x batch {cfg['batch_size']} = about one epoch: mlx-lm 0.32.2 builds 5,230 length-sorted batches of 2 per pass "
          f"and leaves the same row, last in the length sort (a longest row), out of every pass)")

    # class balance
    print("\nclass balance (rows per option, all pooled rows and per split)")
    print("option  name                         total  train  valid   test  share")
    names = {m["option_letter"]: m["option_name"] for m in MAPPING}
    for L in sorted(names):
        c = {s: sum(letter[rows[i]["label"]] == L for i in S[s]) for s in S}
        tot = sum(c.values())
        print(f"{L}       {names[L]:<28} {tot:>5} {c['train']:>6} {c['valid']:>6} {c['test']:>6}  {tot/len(rows):.3f}")
    cnt = collections.Counter(r["label"] for r in rows)
    print(f"rows per intent: min {min(cnt.values())}, max {max(cnt.values())}; every intent present in every split: "
          f"{all(any(rows[i]['label']==l for i in S[s]) for l in range(77) for s in S)}")

    # leakage: exact (normalised) and near duplicates across splits
    F = {r["id"]: feats(r["text"]) for r in rows}
    print(f"\nleakage check: normalised exact match and word uni+bigram Jaccard >= {JACCARD} "
          f"(hashed to {BUCKETS} buckets)")
    tr_norm = collections.defaultdict(set)
    for i in S["train"]:
        tr_norm[norm(rows[i]["text"])].add(rows[i]["label"])
    flagged = []
    for s, ref in (("valid", "train"), ("test", "train"), ("test", "valid")):
        nd = near_dups(S[s], S[ref], F)
        ref_norm = {norm(rows[j]["text"]) for j in S[ref]}
        ex = sum(norm(rows[i]["text"]) in ref_norm for i in S[s])
        nd_n = [i for i, (j, _) in nd.items() if j >= JACCARD]
        conflict = sum(1 for i in nd_n if letter[rows[nd[i][1]]["label"]] != letter[rows[i]["label"]]) if nd_n else 0
        print(f"  {s} vs {ref}: rows {len(S[s])}, exact duplicates {ex}, near duplicates (Jaccard >= {JACCARD}) {len(nd_n)}, "
              f"of those with a different option {conflict}, max Jaccard {max(j for j, _ in nd.values()):.3f}")
        if ref == "train":
            flagged += [(s, i, nd[i][1], round(nd[i][0], 3)) for i in nd_n]
    with open(HERE / "near_duplicates.csv", "w", newline="") as f:
        w = csv.writer(f); w.writerow(["split", "id", "nearest_train_id", "jaccard"]); w.writerows(flagged)

    # write artifacts
    with open(HERE / "split.csv", "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["id", "source", "label", "option", "split", "in_train_subsample", "text"])
        for r in rows:
            w.writerow([r["id"], r["source"], r["label"], letter[r["label"]], r["split"], r["in_train_subsample"], r["text"]])
    pooled = "\n".join(f"{r['id']}\t{r['source']}\t{r['label']}\t{r['text']}" for r in rows)
    hashes["pooled_data_sha256"] = hashlib.sha256(pooled.encode()).hexdigest()

    def dump(name, ids, subsample=False):
        with open(DATA / name, "w") as f:
            for i in ids:
                if subsample and not rows[i]["in_train_subsample"]:
                    continue
                f.write(json.dumps({"messages": messages(rows[i]["text"], letter[rows[i]["label"]])}) + "\n")
    dump("train.jsonl", S["train"], subsample=True); dump("valid.jsonl", S["valid"])

    # token lengths under the exact training render
    from mlx_lm.utils import _download, load_tokenizer
    tok = load_tokenizer(_download(MODEL))
    L = [len(tok.encode(tok.apply_chat_template(messages(rows[i]["text"], letter[rows[i]["label"]]), tokenize=False)))
         for i in sorted(sub)]
    print(f"\ntraining sequence length in tokens: max {max(L)}, mean {sum(L)/len(L):.1f}, "
          f"rows over max_seq_length {cfg['max_seq_length']}: {sum(x > cfg['max_seq_length'] for x in L)}")
    ids_ = [tok.encode(l, add_special_tokens=False) for l in "ABCDE"]
    assert all(len(x) == 1 for x in ids_), ids_
    print("option letters A-E token ids", [x[0] for x in ids_], "(each a single token)")
    ex = generation_text(tok, "example message")
    assert ex.rstrip("\n").endswith("</think>"), repr(ex[-40:])
    print("generation prompt ends with", repr(ex[-24:]))

    for name in ("mapping.csv", "split.csv", "config.yaml", "data/train.jsonl", "data/valid.jsonl"):
        hashes[name + "_sha256"] = sha(HERE / name)
    json.dump(hashes, open(HERE / "hashes.json", "w"), indent=2)
    print("\nhashes"); [print(f"  {k}: {v}") for k, v in hashes.items()]


if __name__ == "__main__":
    main()
evaluate.py: letter readout, metrics, calibration and the escalation rule
"""Zero-shot base model vs LoRA adapter on the SAME validation and test splits.

Probability of each option = softmax over the log-probabilities of the five option-letter tokens at the
last position of the generation prompt (enable_thinking=False). Everything reported on the test split uses
only choices fixed on validation: the temperature and the escalation threshold.
"""
import argparse, csv, hashlib, json, sys, time
from pathlib import Path

import numpy as np
import mlx.core as mx
from mlx_lm import load

from common import HERE, LETTERS, MAPPING, MODEL, generation_text

NBINS = 10          # ECE: 10 equal-width bins on the top-option probability, (0,0.1], (0.1,0.2], ... (0.9,1.0]
TARGET_ACC = 0.95   # escalation rule: smallest threshold whose auto-handled validation accuracy >= this
MIN_COVER = 0.05    # ... and that auto-handles at least this share of validation rows
GRID = [round(x, 3) for x in np.arange(0.30, 0.9995, 0.005)] + [0.999]
CACHE = HERE / "cache"


def read_split():
    out = {"valid": [], "test": []}
    with open(HERE / "split.csv", newline="") as f:
        for r in csv.DictReader(f):
            if r["split"] in out:
                out[r["split"]].append({"id": int(r["id"]), "label": int(r["label"]), "y": LETTERS.index(r["option"]), "text": r["text"]})
    return out


def head_logits(model, ids):
    """Logits at the last position only (skips the 248k-wide LM head for every other position)."""
    lm = model.language_model
    h = lm.model(ids)[:, -1:, :]
    out = lm.model.embed_tokens.as_linear(h) if lm.args.tie_word_embeddings else lm.lm_head(h)
    return out[0, 0].astype(mx.float32)


def score(model, tok, rows, tag):
    """Returns (n,5) option log-probs renormalised over the five letters, and (n,) probability mass the model put on them."""
    CACHE.mkdir(exist_ok=True)
    f = CACHE / f"{tag}.npz"
    if f.exists():
        z = np.load(f); return z["lp"], z["mass"]
    lid = [tok.encode(l, add_special_tokens=False) for l in LETTERS]
    assert all(len(x) == 1 for x in lid), "option letters must be single tokens"
    lid = mx.array([x[0] for x in lid])
    lp, mass, t0 = [], [], time.time()
    for k, r in enumerate(rows):
        ids = mx.array([tok.encode(generation_text(tok, r["text"]), add_special_tokens=False)])
        lg = head_logits(model, ids)
        five = lg[lid]
        lp.append(five - mx.logsumexp(five)); mass.append(mx.exp(mx.logsumexp(five) - mx.logsumexp(lg)))
        mx.eval(lp[-1], mass[-1])  # evaluate every row: a lazy graph over 1,311 rows will not fit in 8 GB
        if k % 100 == 99:
            mx.clear_cache()
            print(f"    {tag}: {k+1}/{len(rows)} rows, {time.time()-t0:.0f}s", flush=True)
    lp = np.array(mx.stack(lp)); mass = np.array(mx.stack(mass))
    np.savez(f, lp=lp, mass=mass)
    return lp, mass


def softmax(lp, T=1.0):
    z = lp / T; z = z - z.max(1, keepdims=True); e = np.exp(z)
    return e / e.sum(1, keepdims=True)


def prf(y, p, k=5):
    cm = np.zeros((k, k), int)
    for a, b in zip(y, p):
        cm[a, b] += 1
    tp = np.diag(cm); prec = tp / np.maximum(cm.sum(0), 1); rec = tp / np.maximum(cm.sum(1), 1)
    f1 = np.where(prec + rec > 0, 2 * prec * rec / np.maximum(prec + rec, 1e-12), 0.0)
    return cm, prec, rec, f1


def ece_table(conf, correct):
    idx = np.clip(np.ceil(conf * NBINS).astype(int) - 1, 0, NBINS - 1)
    rows, ece = [], 0.0
    for b in range(NBINS):
        m = idx == b
        n = int(m.sum())
        c = float(conf[m].mean()) if n else None
        a = float(correct[m].mean()) if n else None
        if n:
            ece += n / len(conf) * abs(a - c)
        rows.append({"bin": f"({b/NBINS:.1f},{(b+1)/NBINS:.1f}]", "n": n, "mean_confidence": c, "accuracy": a,
                     "gap": None if n == 0 else abs(a - c)})
    return float(ece), rows


def fit_temperature(lp, y):
    best = min(np.arange(0.2, 5.001, 0.01), key=lambda T: -np.log(softmax(lp, T)[np.arange(len(y)), y] + 1e-12).mean())
    return float(round(best, 2))


def choose_threshold(conf, correct):
    for t in GRID:
        m = conf >= t
        if m.mean() >= MIN_COVER and correct[m].mean() >= TARGET_ACC:
            return t
    return None


def triage(conf, pred, y, t, e_idx):
    if t is None:
        return {"threshold": None, "note": f"no threshold on the grid reached {TARGET_ACC} auto-handled accuracy with {MIN_COVER:.0%} coverage on validation"}
    m = conf >= t
    n_auto = int(m.sum())
    e = y == e_idx
    return {"threshold": t, "n": len(y), "auto_handled": n_auto, "coverage": n_auto / len(y),
            "auto_accuracy": float((pred[m] == y[m]).mean()) if n_auto else None,
            "escalated_to_human": int((~m).sum()),
            "accuracy_if_all_answered": float((pred == y).mean()),
            "true_security_rows": int(e.sum()),
            "true_security_auto_sent_to_another_queue": int((m & e & (pred != y)).sum())}


def report(name, lp_val, y_val, lp_test, y_test, rows_test, clean_mask, mass_test, names):
    e_idx = LETTERS.index("E")
    P = softmax(lp_test); pred = P.argmax(1); conf = P.max(1); correct = pred == y_test
    cm, prec, rec, f1 = prf(y_test, pred)
    ece, rel = ece_table(conf, correct)
    Pv = softmax(lp_val); cv = Pv.max(1); okv = Pv.argmax(1) == y_val
    thr = choose_threshold(cv, okv)
    T = fit_temperature(lp_val, y_val)
    Pt = softmax(lp_test, T); ece_t, _ = ece_table(Pt.max(1), Pt.argmax(1) == y_test)
    _, _, _, f1c = prf(y_test[clean_mask], pred[clean_mask])
    lab = np.array([r["label"] for r in rows_test])
    per_intent = sorted(((names[l], float(correct[lab == l].mean()), int((lab == l).sum())) for l in sorted(set(lab))), key=lambda x: x[1])
    res = {
        "model": name, "test_n": len(y_test), "accuracy": float(correct.mean()), "macro_f1": float(f1.mean()),
        "per_class": {LETTERS[i]: {"option": names_opt[LETTERS[i]], "precision": float(prec[i]), "recall": float(rec[i]),
                                    "f1": float(f1[i]), "support": int(cm[i].sum())} for i in range(5)},
        "confusion_matrix_rows_true_cols_pred": cm.tolist(),
        "ece_10_equal_width_bins": ece, "reliability_table": rel,
        "mean_letter_probability_mass_test": float(mass_test.mean()),
        "validation": {"accuracy": float(okv.mean()), "ece_10_bins": ece_table(cv, okv)[0]},
        "temperature_fit_on_validation": T, "test_ece_after_temperature_scaling": ece_t,
        "escalation_rule": f"auto-handle when top option probability >= threshold; threshold = smallest grid value whose validation auto-handled accuracy >= {TARGET_ACC} while auto-handling at least {MIN_COVER:.0%} of validation rows",
        "escalation_on_validation": triage(cv, Pv.argmax(1), y_val, thr, e_idx),
        "escalation_on_test": triage(conf, pred, y_test, thr, e_idx),
        "test_without_near_duplicates_of_train": {"n": int(clean_mask.sum()), "accuracy": float(correct[clean_mask].mean()),
                                                  "macro_f1": float(f1c.mean())},
        "lowest_accuracy_intents_on_test": per_intent[:8],
    }
    return res


def show(r):
    print(f"\n=== {r['model']} (test n={r['test_n']})")
    print(f"accuracy {r['accuracy']:.4f}   macro-F1 {r['macro_f1']:.4f}   ECE (10 equal-width bins) {r['ece_10_equal_width_bins']:.4f}   "
          f"mean probability mass on the 5 letters {r['mean_letter_probability_mass_test']:.4f}")
    print("per-class (option, precision, recall, F1, support)")
    for k, v in r["per_class"].items():
        print(f"  {k} {v['option']:<22} {v['precision']:.3f}  {v['recall']:.3f}  {v['f1']:.3f}  {v['support']}")
    print("confusion matrix (rows true A-E, columns predicted A-E)")
    for k, row in zip(LETTERS, r["confusion_matrix_rows_true_cols_pred"]):
        print(f"  {k}  " + " ".join(f"{x:>4}" for x in row))
    print("reliability table (test)")
    print("  bin          n   mean_conf  accuracy  gap")
    for b in r["reliability_table"]:
        if b["n"]:
            print(f"  {b['bin']:<11}{b['n']:>5}   {b['mean_confidence']:.3f}      {b['accuracy']:.3f}     {b['gap']:.3f}")
        else:
            print(f"  {b['bin']:<11}{0:>5}   -          -         -")
    print(f"validation accuracy {r['validation']['accuracy']:.4f}, validation ECE {r['validation']['ece_10_bins']:.4f}")
    print(f"temperature fit on validation {r['temperature_fit_on_validation']}; test ECE after scaling {r['test_ece_after_temperature_scaling']:.4f}")
    print(f"escalation: {r['escalation_rule']}")
    print("  validation:", json.dumps(r["escalation_on_validation"]))
    print("  test:      ", json.dumps(r["escalation_on_test"]))
    c = r["test_without_near_duplicates_of_train"]
    print(f"test rows with no near duplicate in train: n={c['n']} accuracy {c['accuracy']:.4f} macro-F1 {c['macro_f1']:.4f}")
    print("lowest-accuracy intents on test:", "; ".join(f"{n} {a:.2f} (n={c})" for n, a, c in r["lowest_accuracy_intents_on_test"]))


names_opt = {}
for _m in MAPPING:
    names_opt.setdefault(_m["option_letter"], _m["option_name"])


def main():
    ap = argparse.ArgumentParser(); ap.add_argument("--adapter", default=str(HERE / "adapters")); ap.add_argument("--out", required=True)
    a = ap.parse_args()
    sp = read_split()
    y = {s: np.array([r["y"] for r in sp[s]]) for s in sp}
    intent = {int(m["label_id"]): m["intent"] for m in MAPPING}
    flagged = {int(r["id"]) for r in csv.DictReader(open(HERE / "near_duplicates.csv")) if r["split"] == "test"}
    clean = np.array([r["id"] not in flagged for r in sp["test"]])
    print(f"validation rows {len(y['valid'])}, test rows {len(y['test'])}, test rows with a near duplicate in train {int((~clean).sum())}")
    results, scores = {}, {}
    for name, adapter in (("zero-shot base", None), ("LoRA adapter", a.adapter)):
        model, tok = load(MODEL, adapter_path=adapter)
        tag = "base" if adapter is None else "adapter_" + hashlib.sha256((Path(adapter) / "adapters.safetensors").read_bytes()).hexdigest()[:10]
        if adapter is None:  # one-off check that the last-position shortcut equals the full forward pass
            ids = mx.array([tok.encode(generation_text(tok, sp["test"][0]["text"]), add_special_tokens=False)])
            lid = mx.array([tok.encode(l, add_special_tokens=False)[0] for l in LETTERS])
            full = model(ids)[0, -1].astype(mx.float32)[lid]; short = head_logits(model, ids)[lid]
            d = mx.abs((full - mx.logsumexp(full)) - (short - mx.logsumexp(short))).max()
            print(f"self-check: max abs difference in the five option log-probs, full forward vs last-position head: {float(d):.4f} (same argmax: {int(full.argmax()) == int(short.argmax())})")
        lp = {s: score(model, tok, sp[s], f"{tag}_{s}") for s in ("valid", "test")}
        results[name] = report(name, lp["valid"][0], y["valid"], lp["test"][0], y["test"], sp["test"], clean, lp["test"][1], intent)
        scores[name] = {s: {"option_logprobs": np.round(lp[s][0], 5).tolist()} for s in lp}
        show(results[name])
        del model; mx.clear_cache()
    b, t = results["zero-shot base"], results["LoRA adapter"]
    print(f"\nSUMMARY (same {t['test_n']} test rows, same prompt template): base accuracy {b['accuracy']:.4f} macro-F1 {b['macro_f1']:.4f} ECE {b['ece_10_equal_width_bins']:.4f}"
          f"  |  adapter accuracy {t['accuracy']:.4f} macro-F1 {t['macro_f1']:.4f} ECE {t['ece_10_equal_width_bins']:.4f}")
    json.dump({"results": results, "split_ids": {s: [r["id"] for r in sp[s]] for s in sp}, "scores": scores}, open(a.out, "w"))
    print("wrote", a.out)


if __name__ == "__main__":
    main()
baseline.py: TF-IDF plus logistic regression, scored by the same report code
"""Classical baseline: TF-IDF + logistic regression on the SAME split, scored with evaluate.py's report().

Fit once on the full train split (the same 10,461 train rows the adapter's run drew from).
Settings (word 1-2 grams, sublinear tf, C=10, seed 7) were fixed before the first run and not tuned.
Validation fixes the temperature and the escalation threshold; test is reported once, exactly as for the adapter.
It also reports the baseline at the adapter's test coverage (same number of auto-handled rows), so the triage rows compare like for like.
"""
import csv, json

import numpy as np
import sklearn
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression

from common import HERE, LETTERS, MAPPING
from evaluate import read_split, report, show


def main():
    print("scikit-learn", sklearn.__version__)
    sp = read_split()
    train = [r for r in csv.DictReader(open(HERE / "split.csv", newline="")) if r["split"] == "train"]
    y = {s: np.array([r["y"] for r in sp[s]]) for s in sp}
    intent = {int(m["label_id"]): m["intent"] for m in MAPPING}
    flagged = {int(r["id"]) for r in csv.DictReader(open(HERE / "near_duplicates.csv")) if r["split"] == "test"}
    clean = np.array([r["id"] not in flagged for r in sp["test"]])
    name = "TF-IDF + logistic regression, full train split"
    vec = TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True, min_df=1)
    X = vec.fit_transform([r["text"] for r in train])
    clf = LogisticRegression(C=10.0, max_iter=2000, random_state=7).fit(X, [LETTERS.index(r["option"]) for r in train])
    lp = {s: np.log(np.clip(clf.predict_proba(vec.transform([r["text"] for r in sp[s]])), 1e-12, 1)) for s in sp}
    print(f"\n{name}: fit on {len(train)} rows")
    out = {name: report(name, lp["valid"], y["valid"], lp["test"], y["test"], sp["test"], clean, np.ones(len(y["test"])), intent)}
    show(out[name])
    # Like-for-like triage: auto-handle as many test rows as the adapter did (its validation-fixed threshold), taking the
    # baseline's most confident ones. This is a comparison at matched coverage, not a threshold: k comes from the test run.
    k = json.load(open(sorted(HERE.glob("eval_*.json"))[-1]))["results"]["LoRA adapter"]["escalation_on_test"]["auto_handled"]
    P = np.exp(lp["test"]); pred = P.argmax(1); conf = P.max(1)
    top = np.argsort(-conf, kind="stable")[:k]
    e = y["test"][top] == LETTERS.index("E")
    out[name]["test_at_adapter_coverage"] = m = {
        "auto_handled": int(k), "escalated_to_human": int(len(conf) - k), "lowest_auto_handled_confidence": float(conf[top].min()),
        "auto_accuracy": float((pred[top] == y["test"][top]).mean()),
        "true_security_auto_sent_to_another_queue": int((e & (pred[top] != y["test"][top])).sum())}
    print(f"at the adapter's test coverage ({k} most confident test rows auto-handled, {m['escalated_to_human']} escalated, "
          f"lowest auto-handled confidence {m['lowest_auto_handled_confidence']:.3f}): auto-handled accuracy {m['auto_accuracy']:.4f}, "
          f"true security rows auto-sent to another queue {m['true_security_auto_sent_to_another_queue']}")
    json.dump(out, open(HERE / "baseline_2026-11-20.json", "w"))
    print("wrote baseline_2026-11-20.json")


if __name__ == "__main__":
    main()
mapping.csv: every Banking77 intent and its option letter
label_id,intent,option_letter,option_name
0,activate_my_card,A,card services
1,age_limit,D,account and identity
2,apple_pay_or_google_pay,A,card services
3,atm_support,A,card services
4,automatic_top_up,B,payments and transfers
5,balance_not_updated_after_bank_transfer,B,payments and transfers
6,balance_not_updated_after_cheque_or_cash_deposit,B,payments and transfers
7,beneficiary_not_allowed,B,payments and transfers
8,cancel_transfer,B,payments and transfers
9,card_about_to_expire,A,card services
10,card_acceptance,A,card services
11,card_arrival,A,card services
12,card_delivery_estimate,A,card services
13,card_linking,A,card services
14,card_not_working,A,card services
15,card_payment_fee_charged,C,fees and refunds
16,card_payment_not_recognised,E,security and fraud
17,card_payment_wrong_exchange_rate,C,fees and refunds
18,card_swallowed,A,card services
19,cash_withdrawal_charge,C,fees and refunds
20,cash_withdrawal_not_recognised,E,security and fraud
21,change_pin,A,card services
22,compromised_card,E,security and fraud
23,contactless_not_working,A,card services
24,country_support,D,account and identity
25,declined_card_payment,B,payments and transfers
26,declined_cash_withdrawal,B,payments and transfers
27,declined_transfer,B,payments and transfers
28,direct_debit_payment_not_recognised,E,security and fraud
29,disposable_card_limits,A,card services
30,edit_personal_details,D,account and identity
31,exchange_charge,C,fees and refunds
32,exchange_rate,C,fees and refunds
33,exchange_via_app,C,fees and refunds
34,extra_charge_on_statement,C,fees and refunds
35,failed_transfer,B,payments and transfers
36,fiat_currency_support,C,fees and refunds
37,get_disposable_virtual_card,A,card services
38,get_physical_card,A,card services
39,getting_spare_card,A,card services
40,getting_virtual_card,A,card services
41,lost_or_stolen_card,E,security and fraud
42,lost_or_stolen_phone,E,security and fraud
43,order_physical_card,A,card services
44,passcode_forgotten,D,account and identity
45,pending_card_payment,B,payments and transfers
46,pending_cash_withdrawal,B,payments and transfers
47,pending_top_up,B,payments and transfers
48,pending_transfer,B,payments and transfers
49,pin_blocked,A,card services
50,receiving_money,B,payments and transfers
51,Refund_not_showing_up,C,fees and refunds
52,request_refund,C,fees and refunds
53,reverted_card_payment?,B,payments and transfers
54,supported_cards_and_currencies,A,card services
55,terminate_account,D,account and identity
56,top_up_by_bank_transfer_charge,C,fees and refunds
57,top_up_by_card_charge,C,fees and refunds
58,top_up_by_cash_or_cheque,B,payments and transfers
59,top_up_failed,B,payments and transfers
60,top_up_limits,B,payments and transfers
61,top_up_reverted,B,payments and transfers
62,topping_up_by_card,B,payments and transfers
63,transaction_charged_twice,C,fees and refunds
64,transfer_fee_charged,C,fees and refunds
65,transfer_into_account,B,payments and transfers
66,transfer_not_received_by_recipient,B,payments and transfers
67,transfer_timing,B,payments and transfers
68,unable_to_verify_identity,D,account and identity
69,verify_my_identity,D,account and identity
70,verify_source_of_funds,D,account and identity
71,verify_top_up,B,payments and transfers
72,virtual_card_not_working,A,card services
73,visa_or_mastercard,A,card services
74,why_verify_identity,D,account and identity
75,wrong_amount_of_cash_received,E,security and fraud
76,wrong_exchange_rate_for_cash_withdrawal,C,fees and refunds
config.yaml: every training setting passed to mlx_lm lora
# mlx_lm.lora config. Train split 10,461 rows, about one epoch: 5,231 steps of 2; mlx-lm 0.32.2 builds 5,230 length-sorted batches per pass and leaves the same row, last in the length sort (a longest row), out of every pass (prepare.py writes min(train rows, iters x batch)).
# batch_size 2, num_layers 8 and grad_checkpoint true (recomputes activations, same gradients) are what fit in 8 GB on this M1.
model: mlx-community/Qwen3.5-0.8B-4bit
train: true
fine_tune_type: lora
optimizer: adamw
data: data
adapter_path: adapters
seed: 7
num_layers: 8
batch_size: 2
iters: 5231
learning_rate: 1.0e-4
max_seq_length: 256
mask_prompt: true
grad_checkpoint: true
steps_per_report: 10
steps_per_eval: 500
val_batches: 50
save_every: 100
lr_schedule:
  name: cosine_decay
  arguments: [1.0e-4, 5231, 1.0e-6]
  warmup: 50
lora_parameters:
  rank: 8
  scale: 20.0
  dropout: 0.0
requirements.txt: the eight pinned direct dependencies
mlx==0.32.4
mlx-lm==0.32.2
pyarrow==26.0.1
numpy==2.5.5
transformers==5.23.0
huggingface_hub==2.4.0
safetensors==0.8.0
pyyaml==6.0.3
run.sh: versions, prepare, train, evaluate and baseline in one script
#!/bin/bash
# Re-run everything: bash run.sh 2>&1 | tee run_output_$(date +%F).txt
# Needs uv (https://docs.astral.sh/uv/) and an Apple Silicon Mac. First run downloads the model (622 MB in the Hugging Face cache).
set -euo pipefail
cd "$(dirname "$0")"
export HF_HOME="${HF_HOME:-$PWD/.hf}"
RUN="uv run --no-project --with-requirements requirements.txt"
echo "== versions"; $RUN python -c "import importlib.metadata as m; [print(p, m.version(p)) for p in ('mlx','mlx-lm','pyarrow','numpy','transformers','huggingface_hub','safetensors','pyyaml')]"
echo "== 1 prepare (download, map, split, leakage check, hash)"; $RUN python prepare.py
echo "== 2 train (LoRA, mlx_lm.lora, config.yaml)"; date -u +"start %FT%TZ"; $RUN python -m mlx_lm lora -c config.yaml 2>&1 | tr '\r' '\n' | sed 's/\x1b\[[0-9;]*[A-Za-z]//g' | grep -v '^\s*$' | grep -v '^train *[█░]' ; date -u +"end %FT%TZ"
echo "== 3 evaluate (zero-shot base and adapter, same validation and test rows)"; $RUN python evaluate.py --out eval_$(date +%F).json
echo "== 4 classical baseline (TF-IDF + logistic regression, same split, same report)"; uv run --no-project --with-requirements requirements.txt --with scikit-learn==1.9.1 python baseline.py
Run output: step 3 reports for the zero-shot base and adapter, progress bars at their final frame (run_output_2026-11-20.txt lines 669 to 796)
== 3 evaluate (zero-shot base and adapter, same validation and test rows)
validation rows 1311, test rows 1311, test rows with a near duplicate in train 72
Fetching 10 files: 100%|██████████| 10/10 [00:00<00:00, 3402.53it/s]
self-check: max abs difference in the five option log-probs, full forward vs last-position head: 0.0000 (same argmax: True)
    base_valid: 100/1311 rows, 11s
    base_valid: 200/1311 rows, 22s
    base_valid: 300/1311 rows, 34s
    base_valid: 400/1311 rows, 45s
    base_valid: 500/1311 rows, 56s
    base_valid: 600/1311 rows, 68s
    base_valid: 700/1311 rows, 79s
    base_valid: 800/1311 rows, 91s
    base_valid: 900/1311 rows, 102s
    base_valid: 1000/1311 rows, 113s
    base_valid: 1100/1311 rows, 125s
    base_valid: 1200/1311 rows, 136s
    base_valid: 1300/1311 rows, 147s
    base_test: 100/1311 rows, 11s
    base_test: 200/1311 rows, 23s
    base_test: 300/1311 rows, 34s
    base_test: 400/1311 rows, 46s
    base_test: 500/1311 rows, 57s
    base_test: 600/1311 rows, 69s
    base_test: 700/1311 rows, 80s
    base_test: 800/1311 rows, 92s
    base_test: 900/1311 rows, 103s
    base_test: 1000/1311 rows, 115s
    base_test: 1100/1311 rows, 126s
    base_test: 1200/1311 rows, 137s
    base_test: 1300/1311 rows, 148s

=== zero-shot base (test n=1311)
accuracy 0.4394   macro-F1 0.2593   ECE (10 equal-width bins) 0.1564   mean probability mass on the 5 letters 0.9875
per-class (option, precision, recall, F1, support)
  A card services          0.372  0.967  0.538  329
  B payments and transfers 0.547  0.552  0.549  435
  C fees and refunds       1.000  0.021  0.041  285
  D account and identity   1.000  0.074  0.137  136
  E security and fraud     1.000  0.016  0.031  126
confusion matrix (rows true A-E, columns predicted A-E)
  A   318   11    0    0    0
  B   195  240    0    0    0
  C   145  134    6    0    0
  D   121    5    0   10    0
  E    75   49    0    0    2
reliability table (test)
  bin          n   mean_conf  accuracy  gap
  (0.0,0.1]      0   -          -         -
  (0.1,0.2]      0   -          -         -
  (0.2,0.3]     49   0.277      0.102     0.175
  (0.3,0.4]    588   0.361      0.216     0.145
  (0.4,0.5]    414   0.442      0.580     0.138
  (0.5,0.6]    174   0.541      0.782     0.240
  (0.6,0.7]     65   0.636      0.815     0.179
  (0.7,0.8]     21   0.741      0.714     0.027
  (0.8,0.9]      0   -          -         -
  (0.9,1.0]      0   -          -         -
validation accuracy 0.4401, validation ECE 0.1556
temperature fit on validation 0.99; test ECE after scaling 0.1547
escalation: auto-handle when top option probability >= threshold; threshold = smallest grid value whose validation auto-handled accuracy >= 0.95 while auto-handling at least 5% of validation rows
  validation: {"threshold": null, "note": "no threshold on the grid reached 0.95 auto-handled accuracy with 5% coverage on validation"}
  test:       {"threshold": null, "note": "no threshold on the grid reached 0.95 auto-handled accuracy with 5% coverage on validation"}
test rows with no near duplicate in train: n=1239 accuracy 0.4391 macro-F1 0.2601
lowest-accuracy intents on test: age_limit 0.00 (n=15); card_payment_fee_charged 0.00 (n=23); card_payment_not_recognised 0.00 (n=21); card_payment_wrong_exchange_rate 0.00 (n=21); cash_withdrawal_charge 0.00 (n=22); cash_withdrawal_not_recognised 0.00 (n=20); country_support 0.00 (n=17); edit_personal_details 0.00 (n=16)
Fetching 10 files: 100%|██████████| 10/10 [00:00<00:00, 2844.37it/s]
    adapter_fb38612252_valid: 100/1311 rows, 12s
    adapter_fb38612252_valid: 200/1311 rows, 24s
    adapter_fb38612252_valid: 300/1311 rows, 36s
    adapter_fb38612252_valid: 400/1311 rows, 48s
    adapter_fb38612252_valid: 500/1311 rows, 60s
    adapter_fb38612252_valid: 600/1311 rows, 73s
    adapter_fb38612252_valid: 700/1311 rows, 85s
    adapter_fb38612252_valid: 800/1311 rows, 97s
    adapter_fb38612252_valid: 900/1311 rows, 109s
    adapter_fb38612252_valid: 1000/1311 rows, 121s
    adapter_fb38612252_valid: 1100/1311 rows, 133s
    adapter_fb38612252_valid: 1200/1311 rows, 145s
    adapter_fb38612252_valid: 1300/1311 rows, 157s
    adapter_fb38612252_test: 100/1311 rows, 12s
    adapter_fb38612252_test: 200/1311 rows, 24s
    adapter_fb38612252_test: 300/1311 rows, 37s
    adapter_fb38612252_test: 400/1311 rows, 49s
    adapter_fb38612252_test: 500/1311 rows, 61s
    adapter_fb38612252_test: 600/1311 rows, 73s
    adapter_fb38612252_test: 700/1311 rows, 86s
    adapter_fb38612252_test: 800/1311 rows, 98s
    adapter_fb38612252_test: 900/1311 rows, 110s
    adapter_fb38612252_test: 1000/1311 rows, 122s
    adapter_fb38612252_test: 1100/1311 rows, 134s
    adapter_fb38612252_test: 1200/1311 rows, 146s
    adapter_fb38612252_test: 1300/1311 rows, 158s

=== LoRA adapter (test n=1311)
accuracy 0.9352   macro-F1 0.9314   ECE (10 equal-width bins) 0.0189   mean probability mass on the 5 letters 0.9994
per-class (option, precision, recall, F1, support)
  A card services          0.928  0.939  0.934  329
  B payments and transfers 0.926  0.952  0.939  435
  C fees and refunds       0.950  0.933  0.942  285
  D account and identity   0.949  0.963  0.956  136
  E security and fraud     0.938  0.841  0.887  126
confusion matrix (rows true A-E, columns predicted A-E)
  A   309   12    3    5    0
  B    10  414    6    1    4
  C     5   11  266    0    3
  D     2    3    0  131    0
  E     7    7    5    1  106
reliability table (test)
  bin          n   mean_conf  accuracy  gap
  (0.0,0.1]      0   -          -         -
  (0.1,0.2]      0   -          -         -
  (0.2,0.3]      0   -          -         -
  (0.3,0.4]      2   0.370      0.500     0.130
  (0.4,0.5]     22   0.477      0.364     0.114
  (0.5,0.6]     51   0.549      0.706     0.157
  (0.6,0.7]     43   0.646      0.581     0.064
  (0.7,0.8]     54   0.754      0.796     0.042
  (0.8,0.9]    102   0.854      0.892     0.038
  (0.9,1.0]   1037   0.981      0.986     0.005
validation accuracy 0.9306, validation ECE 0.0121
temperature fit on validation 0.97; test ECE after scaling 0.0162
escalation: auto-handle when top option probability >= threshold; threshold = smallest grid value whose validation auto-handled accuracy >= 0.95 while auto-handling at least 5% of validation rows
  validation: {"threshold": 0.625, "n": 1311, "auto_handled": 1244, "coverage": 0.9488939740655988, "auto_accuracy": 0.9501607717041801, "escalated_to_human": 67, "accuracy_if_all_answered": 0.9305873379099924, "true_security_rows": 126, "true_security_auto_sent_to_another_queue": 11}
  test:       {"threshold": 0.625, "n": 1311, "auto_handled": 1222, "coverage": 0.9321128909229596, "auto_accuracy": 0.9582651391162029, "escalated_to_human": 89, "accuracy_if_all_answered": 0.935163996948894, "true_security_rows": 126, "true_security_auto_sent_to_another_queue": 11}
test rows with no near duplicate in train: n=1239 accuracy 0.9330 macro-F1 0.9293
lowest-accuracy intents on test: supported_cards_and_currencies 0.53 (n=17); top_up_by_bank_transfer_charge 0.60 (n=15); card_payment_not_recognised 0.62 (n=21); lost_or_stolen_phone 0.75 (n=16); virtual_card_not_working 0.75 (n=8); receiving_money 0.79 (n=14); card_not_working 0.80 (n=15); verify_source_of_funds 0.80 (n=15)

SUMMARY (same 1311 test rows, same prompt template): base accuracy 0.4394 macro-F1 0.2593 ECE 0.1564  |  adapter accuracy 0.9352 macro-F1 0.9314 ECE 0.0189
wrote eval_2026-11-20.json
Run output: the baseline report as printed (baseline_run_2026-11-20.txt in full)
scikit-learn 1.9.1

TF-IDF + logistic regression, full train split: fit on 10461 rows

=== TF-IDF + logistic regression, full train split (test n=1311)
accuracy 0.9672   macro-F1 0.9666   ECE (10 equal-width bins) 0.0405   mean probability mass on the 5 letters 1.0000
per-class (option, precision, recall, F1, support)
  A card services          0.961  0.967  0.964  329
  B payments and transfers 0.957  0.979  0.968  435
  C fees and refunds       0.975  0.968  0.972  285
  D account and identity   0.985  0.956  0.970  136
  E security and fraud     0.983  0.937  0.959  126
confusion matrix (rows true A-E, columns predicted A-E)
  A   318    7    3    1    0
  B     4  426    3    0    2
  C     2    6  276    1    0
  D     5    1    0  130    0
  E     2    5    1    0  118
reliability table (test)
  bin          n   mean_conf  accuracy  gap
  (0.0,0.1]      0   -          -         -
  (0.1,0.2]      0   -          -         -
  (0.2,0.3]      0   -          -         -
  (0.3,0.4]      2   0.335      0.000     0.335
  (0.4,0.5]     15   0.459      0.467     0.008
  (0.5,0.6]     33   0.542      0.758     0.216
  (0.6,0.7]     33   0.651      0.788     0.137
  (0.7,0.8]     69   0.753      0.884     0.131
  (0.8,0.9]    135   0.855      0.956     0.100
  (0.9,1.0]   1024   0.978      0.996     0.018
validation accuracy 0.9565, validation ECE 0.0334
temperature fit on validation 0.69; test ECE after scaling 0.0047
escalation: auto-handle when top option probability >= threshold; threshold = smallest grid value whose validation auto-handled accuracy >= 0.95 while auto-handling at least 5% of validation rows
  validation: {"threshold": 0.3, "n": 1311, "auto_handled": 1310, "coverage": 0.9992372234935164, "auto_accuracy": 0.9572519083969465, "escalated_to_human": 1, "accuracy_if_all_answered": 0.9565217391304348, "true_security_rows": 126, "true_security_auto_sent_to_another_queue": 14}
  test:       {"threshold": 0.3, "n": 1311, "auto_handled": 1311, "coverage": 1.0, "auto_accuracy": 0.9672006102212052, "escalated_to_human": 0, "accuracy_if_all_answered": 0.9672006102212052, "true_security_rows": 126, "true_security_auto_sent_to_another_queue": 8}
test rows with no near duplicate in train: n=1239 accuracy 0.9653 macro-F1 0.9649
lowest-accuracy intents on test: supported_cards_and_currencies 0.71 (n=17); card_not_working 0.80 (n=15); country_support 0.82 (n=17); lost_or_stolen_card 0.83 (n=12); wrong_amount_of_cash_received 0.86 (n=22); verify_source_of_funds 0.87 (n=15); fiat_currency_support 0.88 (n=17); pending_card_payment 0.90 (n=20)
at the adapter's test coverage (1222 most confident test rows auto-handled, 89 escalated, lowest auto-handled confidence 0.709): auto-handled accuracy 0.9869, true security rows auto-sent to another queue 4
wrote baseline_2026-11-20.json
Run output: hashes.json in full, the SHA-256 of every file the run used or produced
{
  "banking77_train.parquet": "8dc89b87a188509c42cce5a086e8f7c1ff4a225bdd9ae3f23e6cdfa5806e363a",
  "banking77_test.parquet": "1f40f777c33f0edfa6c530ff84fe2878db6490838c12d22d036f626948905341",
  "pooled_data_sha256": "84999d823077703e42b851e452b6748d4d19812650c28b31269a31edd27f2bb4",
  "mapping.csv_sha256": "93722d03bcab55ff391e102d6ddcdadddcddd4b97dee5a9c5f7d19043a158865",
  "split.csv_sha256": "d8d60cfb5159d5d4290990d6173be3f115b2f1c0248a65babc7d1217f3804f99",
  "config.yaml_sha256": "110d0abb7ee1725a0d948baeb6f2ecf33546513bd97d8f97f9f87a8d87c6444a",
  "data/train.jsonl_sha256": "dd749bf91dd2037da27e9b71cfd02142187f68d12a017590afbfa7bfd2eef70e",
  "data/valid.jsonl_sha256": "d6e90f90fa1db2cf550a1684b5c2fb52225874288bf9103a30f073059b2ccc7f",
  "README.md_sha256": "b75307c7bc770a5a63a7b32b4f384de57b4dd628815abb647e95cd64cdab4f11",
  "run.sh_sha256": "5529ea9425e8cc65f64ed8b1c7e0bd07fb7c3d72049d79119af92bababbe4a6f",
  "requirements.txt_sha256": "aed861e39e782f6aa81afb0974de1cbd0509df4347d5db5fbfc9164e17bbcd4d",
  "common.py_sha256": "2a9decfe4ebf68b19d7899a2672ec16bf65f940cdf0f5756e58455daa20a21b4",
  "prepare.py_sha256": "060dcae8c8a57ef17e6e59c5976aaa6efcc6d1c019b3c03d88f388dbfe797110",
  "evaluate.py_sha256": "d537314abcbdf64a2193b7810f4b160525537d61fdb56ede351cab35c37c1d7a",
  "baseline.py_sha256": "80c2868991c6b9299ba26ca4d553b3801ff6889c8b435e9a4221323c35f937f1",
  "near_duplicates.csv_sha256": "827e549be4bed0c1e04b5290d9939aa3cc74573dce7a3ccae4bb503803f182f3",
  "adapters/adapters.safetensors_sha256": "fb38612252c9fe077e9df66619c277a1126733538a7b365d6f222600c66480fa",
  "adapters/adapter_config.json_sha256": "b47625af1cabe1be33fe72bd1b85ed08663bb524e69e3a7891c6d6a54110cf1a",
  "eval_2026-11-20.json_sha256": "351861cf457548885a046be343318391abc0164c5c00884ed734da2cb07b8984",
  "baseline_2026-11-20.json_sha256": "07b8d15aa0adab0b7717761dd8ce8c1618a38ea692abe37595d32803ac792edf",
  "run_output_2026-11-20.txt_sha256": "dbbb7ee0e610b6060cbe17329097b3fa0cf8e4d4f0ed5cee996d2ebd13d3c335",
  "baseline_run_2026-11-20.txt_sha256": "b46a3206f3439e7e86c9ee4733fdeed2f8ce1760bede3d681ce4ae1e60138290"
}

What to watch after the triage model ships

Three things drift after launch: the share of messages per queue, the match between stated confidence and real accuracy, and the option list itself. Re-check each on a fresh labelled sample on a fixed schedule, and retrain when a new queue appears, since the adapter can only answer with the five letters it learned.

For class mix, compare the weekly share of predicted letters with the pooled shares printed earlier: A 0.250, B 0.332, C 0.217, D 0.105 and E 0.096. One odd week means little; a sustained shift means the customers or the model moved, so check it against a fixed test file.

For calibration, rebuild the 10-bin reliability table on a newly labelled sample and check that the 0.625 threshold still gives at least 0.95 auto-handled accuracy, refitting it on fresh validation data if not. A sixth queue needs a new letter, an updated mapping, fresh labels and a retrain; until then the threshold sends unsure messages to people.

Future AGI for labelling and scoring the triage model

Future AGI annotation queues collect the human labels a triage set needs, show how often annotators agree, and export completed items to a dataset. That covers the labelling half of decision model training, and a custom eval saved once can then score the held-out set on that dataset by its name.

For your own data the flow runs from a review queue to a labelled dataset to held-out scoring. The Banking77 run above used the dataset authors’ labels, so none of its numbers came from a queue or a platform eval. Browse the source at Future AGI on GitHub.

Annotation queues for the triage labels

A queue carries a status, its labels, the people and their roles, submissions per item and whether review is required; items move through pending, in progress, completed or skipped. A categorical label holds the five options. The docs cover annotation queues and items.

The Agreement tab reports overall, per-label and annotator-pair agreement as raw percentages, plus Cohen’s Kappa, the only chance-corrected agreement statistic it computes, once two annotators score an item. The docs gate it behind the Agreement Metrics entitlement (progress and agreement).

Export to Dataset takes completed items by default, has no item cap and lets you rename, add or drop columns, while Download tops out at 1,000 items by default. The docs list fine-tuning data among its uses (export annotations to a dataset).

Custom evals on the held-out set

A custom eval is a template defined once as an Agent Evaluator, an LLM-as-Judge or a Code Eval, the type the docs pair with a deterministic rule. An exact match between predicted letter and label is that kind of rule, so a Code Eval fits.

Once saved it works like a built-in, on a dataset, a trace, a simulation or from the SDK by its name. Add it to the exported held-out dataset and Future AGI scores every row against the rule you wrote once, as the docs describe for any custom eval.

The five support queues after training

Back to the five queues: in our run the zero-shot model routed 2 of 126 security reports correctly. The adapter routed 106 of them to security and auto-handles 1,222 of 1,311 messages at 0.9583 accuracy and escalates 89. Fit the cheap baseline on your own labels first, and train the adapter when it misses your bar.

That comes down to four moves: copy mapping.csv and redraw any boundary your team disputes, swap in labels from your own review queue, run the four steps, and read the security row of the confusion matrix before trusting any threshold. If the baseline clears your bar, ship it; if not, train the adapter we ran.

Frequently Asked Questions

How to train a decision model in machine learning

To train a decision model, define a fixed option list, label examples, split them with a fixed seed, fine-tune an instruct model with LoRA, and score a held-out test set. Our run mapped Banking77 to five queues, trained about one epoch on an 8 GB Mac and reported accuracy, calibration and baselines on 1,311 test rows.

What is temperature scaling in machine learning?

Temperature scaling is a calibration step that divides a model's logits by one number fitted on validation data, softening or sharpening confidence without changing the top answer. Fit it on validation and report test once. In our run the adapter's fitted value was 0.97, and test ECE moved from 0.0189 to 0.0162.

Is fine-tuning an LLM worth it?

Fine-tuning your own LLM is worth it when the option list is fixed, message volume is high, data cannot leave your network, or a hosted call misses your latency budget. Otherwise a hosted model is less work. In our Banking77 run a TF-IDF classifier beat the LoRA adapter on accuracy, so fit that baseline before you commit to either route.

Should you start with logistic regression before fine-tuning a language model?

Yes, fit a cheap classifier on the same split first, because it sets the bar any fine-tuned model has to clear. On our five Banking77 queues, TF-IDF plus logistic regression reached 0.9672 test accuracy against 0.9352 for the LoRA adapter, so the baseline won on this data.

How should you split data to train a decision model?

Stratify by the finest label you have, use a fixed seed, and keep validation and test apart from training and from each other. Our run split 13,083 Banking77 messages 80/10/10 across 77 intents with seed 7, then flagged 72 test rows that nearly duplicate a training row.
Related Articles
View all