Takzen commited on
Commit
c38466b
·
verified ·
1 Parent(s): e49a9dd

Add starling.py (whole flow with package gate); fix procurement example; note part-number aliases

Browse files
Files changed (2) hide show
  1. README.md +61 -5
  2. starling.py +204 -0
README.md CHANGED
@@ -88,8 +88,8 @@ Two rules hold throughout:
88
  VAT matrix and the PO are part of the state or the options. A new account or a new rate
89
  therefore needs no retraining.
90
  - **Code compares numbers and applies policy.** Ordinary code checks amounts, prices, quantities
91
- and the company's rules. The model only judges what is fuzzy, such as whether "Toner HP 59A" and
92
- "Kaseta z tonerem CF259A" are the same item.
93
 
94
  ### Why finance asks five questions
95
 
@@ -308,11 +308,13 @@ def decide(adapter: str, state: str, question: str, options: dict[str, str],
308
 
309
 
310
  # procurement: is the invoice line the PO item?
311
- print(decide("procurement", "Zamówienie (PO): Toner HP 59A czarny\nFaktura: Kaseta z tonerem CF259A, czarna",
312
- "Czy pozycja z faktury to ten sam towar co pozycja z zamówienia? Ilości i ceny pomiń.",
 
 
313
  {"true": "tak, ta sama pozycja", "false": "nie, inny towar lub inny wariant"},
314
  kind="noul", temperature=CAL["procurement"]["po_match"]["temperature"]))
315
- # {'true': 0.889, 'false': 0.111}: the same toner, 89% sure
316
 
317
 
318
  # finance: five questions about the e-mail text, the company's rule in code
@@ -357,6 +359,57 @@ else:
357
  - Questions can also be asked with an English frame (`State`, `Question`, `Options`). Every
358
  decision was trained with several Polish phrasings and one English one.
359
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
  ## Training
361
 
362
  - **Recipe:** QLoRA, as in Bullfinch.
@@ -412,6 +465,9 @@ else:
412
  - **Finance flags e-mails for verification; it does not prove fraud.** A held payment should be
413
  checked by a person through a known channel. It asks five questions per e-mail, which makes it
414
  five times slower than a single question.
 
 
 
415
  - **Department adapters are weaker at general questions than Bullfinch 4B.** Route those to
416
  Bullfinch.
417
  - **Decisions with legal or financial consequences should be reviewed by a person.**
 
88
  VAT matrix and the PO are part of the state or the options. A new account or a new rate
89
  therefore needs no retraining.
90
  - **Code compares numbers and applies policy.** Ordinary code checks amounts, prices, quantities
91
+ and the company's rules. The model only judges what is fuzzy, such as whether "Papier ksero A4
92
+ 80 g/m², ryza" and "Papier do drukarek A4 80 g, karton 5 ryz" are the same item.
93
 
94
  ### Why finance asks five questions
95
 
 
308
 
309
 
310
  # procurement: is the invoice line the PO item?
311
+ print(decide("procurement",
312
+ "Pozycja w zamówieniu (PO): Długopisy żelowe Pentel EnerGel 0,7 mm, niebieskie\n"
313
+ "Pozycja na fakturze: Długopis żelowy Pentel EnerGel BL77, niebieski, 0,7 mm",
314
+ "Czy pozycja z faktury to ten sam towar lub usługa co pozycja z zamówienia (PO)? Ilości i ceny pomiń.",
315
  {"true": "tak, ta sama pozycja", "false": "nie, inny towar lub inny wariant"},
316
  kind="noul", temperature=CAL["procurement"]["po_match"]["temperature"]))
317
+ # {'true': 0.962, 'false': 0.038}: the same pen, 96% sure
318
 
319
 
320
  # finance: five questions about the e-mail text, the company's rule in code
 
359
  - Questions can also be asked with an English frame (`State`, `Question`, `Options`). Every
360
  decision was trained with several Polish phrasings and one English one.
361
 
362
+ ### Run the whole flow
363
+
364
+ [`starling.py`](starling.py) in this repo puts the pieces together in one file:
365
+
366
+ - **Step 0, files of unknown type:** `classify()` asks Bullfinch 4B whether a file is a contract
367
+ or an invoice. Below its threshold, the file goes to a person. E-mails are known by their
368
+ channel. Bullfinch tends to call an e-mail that sends an invoice an invoice.
369
+ - **Routing:** code sends each question to the adapter of the department that owns it.
370
+ - **Decisions:** each one is calibrated and checked against its threshold from `CALIBRATION.json`.
371
+ - **Payment rule:** it runs in code.
372
+ - **Gate:** it decides the whole package as BLOCK, TO PERSON or AUTO.
373
+
374
+ The document's content comes from your systems: invoice lines, the purchase order, facts about the
375
+ sender. A KSeF invoice and your ERP are typical sources. The model does not extract data. It only
376
+ decides.
377
+
378
+ ```bash
379
+ pip install torch transformers peft bitsandbytes huggingface_hub
380
+ python starling.py
381
+ ```
382
+
383
+ It runs one package twice. The package has a contract clause, an invoice with three lines and an
384
+ e-mail. The first run uses a genuine e-mail, the second a fake one asking for a new bank account.
385
+
386
+ ```text
387
+ == package with the genuine e-mail ==
388
+ document contract 99.2% threshold 90.0% sure
389
+ document invoice 98.2% threshold 90.0% sure
390
+ contract_risk true 97.5% threshold 87.5% sure
391
+ gl_account 401-01 99.0% threshold 52.7% sure
392
+ vat_rate 23 100.0% threshold 55.1% sure
393
+ po_match true 94.1% threshold 59.5% sure
394
+ gl_account 401-01 98.7% threshold 52.7% sure
395
+ vat_rate 23 100.0% threshold 55.1% sure
396
+ po_match true 96.2% threshold 59.5% sure
397
+ gl_account 402-01 99.8% threshold 52.7% sure
398
+ vat_rate 23 100.0% threshold 55.1% sure
399
+ po_match true 92.1% threshold 59.5% sure
400
+ payment_fraud pay 99.9% threshold 52.8% sure
401
+ gate: AUTO
402
+
403
+ == package with the fraud e-mail ==
404
+ ... (the same 12 decisions) ...
405
+ payment_fraud hold 100.0% threshold 52.8% sure
406
+ gate: BLOCK
407
+ ```
408
+
409
+ AUTO means every decision is sure. It does not mean "approve". Here the contract does renew
410
+ automatically (`contract_risk true`). Your code decides what follows, such as flagging the clause
411
+ for the legal team.
412
+
413
  ## Training
414
 
415
  - **Recipe:** QLoRA, as in Bullfinch.
 
465
  - **Finance flags e-mails for verification; it does not prove fraud.** A held payment should be
466
  checked by a person through a known channel. It asks five questions per e-mail, which makes it
467
  five times slower than a single question.
468
+ - **Procurement does not know part-number aliases.** It treats a different product code as a
469
+ different variant. For example, it says that "HP 59A" and "CF259A" are different toners, though
470
+ they are the same. Keep an alias table in code, or put both codes in the description.
471
  - **Department adapters are weaker at general questions than Bullfinch 4B.** Route those to
472
  Bullfinch.
473
  - **Decisions with legal or financial consequences should be reviewed by a person.**
starling.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Starling 4B: the whole decision flow in one file.
3
+
4
+ pip install torch transformers peft bitsandbytes huggingface_hub
5
+ python starling.py
6
+
7
+ Tested with transformers 5.20, peft 0.21, bitsandbytes 0.50, torch 2.11, on one NVIDIA GPU with
8
+ 8 GB (about 4 GB used).
9
+
10
+ What it does:
11
+ 1. Loads Qwen3.5-4B in 4-bit once, Bullfinch 4B and the four Starling adapters on top of it.
12
+ 2. Step 0, for a file of unknown type: classify() asks Bullfinch 4B whether it is a contract or an
13
+ invoice. Usually the channel already tells you: KSeF gives the invoice, the inbox the e-mail.
14
+ Then code routes each question to the adapter of the department that owns it (ROUTE).
15
+ 3. Each adapter answers with one forward pass and a calibrated probability per option.
16
+ 4. A gate in code decides the whole package:
17
+ * BLOCK: the finance rule holds the payment and is sure. Verify through a known channel.
18
+ * TO PERSON: at least one decision is below its threshold. A person or a large model decides.
19
+ * AUTO: every decision is at or above its threshold.
20
+
21
+ The content comes from your systems: invoice lines, purchase order, facts about the sender (for
22
+ example KSeF and the ERP). The model does not extract data; it only decides.
23
+
24
+ Thresholds come from <adapter>/CALIBRATION.json. They were fitted on our calibration split for at
25
+ most 5% error ("0.05") or 1% error ("0.01"). Before automating anything, refit them on a few hundred
26
+ rows of your own.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import json
32
+ import math
33
+ from dataclasses import dataclass
34
+
35
+ import torch
36
+ from huggingface_hub import hf_hub_download
37
+ from peft import PeftModel
38
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
39
+
40
+ BASE, REVISION = "Qwen/Qwen3.5-4B", "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a"
41
+ REPO = "Takzen/starling-4b"
42
+ GENERAL = "Takzen/bullfinch-4b"
43
+ ADAPTERS = ("legal", "accounting", "procurement", "finance")
44
+ # question family -> the department adapter that answers it
45
+ ROUTE = {"contract_nli": "legal", "contract_risk": "legal", "gl_account": "accounting",
46
+ "vat_rate": "accounting", "po_match": "procurement", "payment_fraud": "finance"}
47
+ PREFILL = '{"answer": "'
48
+ FRAME = ("Stan", "Pytanie", "Opcje", 'Odpowiedz wyłącznie w formacie JSON: {"answer": "<litera opcji>"}.')
49
+ LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
50
+ # Step 0 is for files of unknown type (an upload, a scan). E-mails are known by their channel, the
51
+ # inbox. Bullfinch tends to call an e-mail that sends an invoice an invoice, so e-mails skip step 0.
52
+ DOC_TYPES = {"contract": "fragment umowy (zapisy, strony, warunki)",
53
+ "invoice": "faktura VAT (sprzedawca, pozycje, kwoty)",
54
+ "other": "inny dokument"}
55
+
56
+
57
+ @dataclass
58
+ class Decision:
59
+ family: str
60
+ answer: str
61
+ confidence: float
62
+ threshold: float
63
+ probs: dict[str, float]
64
+
65
+ @property
66
+ def sure(self) -> bool:
67
+ return self.confidence >= self.threshold
68
+
69
+
70
+ class Starling:
71
+ def __init__(self, error: str = "0.05", device: int = 0):
72
+ self.error, self.device = error, device
73
+ self.tok = AutoTokenizer.from_pretrained(BASE, revision=REVISION)
74
+ base = AutoModelForCausalLM.from_pretrained(
75
+ BASE, revision=REVISION, device_map={"": device}, dtype=torch.bfloat16,
76
+ quantization_config=BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
77
+ bnb_4bit_compute_dtype=torch.bfloat16,
78
+ bnb_4bit_use_double_quant=True))
79
+ self.model = PeftModel.from_pretrained(base, GENERAL, adapter_name="general")
80
+ for name in ADAPTERS:
81
+ self.model.load_adapter(REPO, adapter_name=name, subfolder=name)
82
+ self.model.eval()
83
+ self.cal: dict[str, dict] = {}
84
+ for name in ADAPTERS:
85
+ with open(hf_hub_download(REPO, f"{name}/CALIBRATION.json"), encoding="utf-8") as f:
86
+ self.cal.update(json.load(f)["families"])
87
+ with open(hf_hub_download(REPO, "finance/SIGNALS.json"), encoding="utf-8") as f:
88
+ self.signals = json.load(f)["signals"]
89
+ self.prefix = len(self.tok.encode(PREFILL, add_special_tokens=False))
90
+
91
+ def probs(self, adapter: str, state: str, question: str, options: dict[str, str],
92
+ kind: str = "choice", temperature: float = 1.0) -> dict[str, float]:
93
+ """Probability of each option key. `kind` is "choice" or "noul" (yes/no: keys true/false)."""
94
+ self.model.set_adapter(adapter)
95
+ s, q, o, reply = FRAME
96
+ codes = dict(zip(LETTERS, options))
97
+ lines = "\n".join(f"{c}) {k}: {options[k]}" if kind == "choice" else f"{c}) {options[k]}"
98
+ for c, k in codes.items())
99
+ content = f"{s}:\n{state}\n\n{q}: {question}\n\n{o}:\n{lines}\n\n{reply}"
100
+ text = self.tok.apply_chat_template([{"role": "user", "content": content}], tokenize=False,
101
+ add_generation_prompt=True, enable_thinking=False)
102
+ ids = self.tok(text + PREFILL, return_tensors="pt", add_special_tokens=False).input_ids
103
+ with torch.inference_mode():
104
+ logits = self.model(input_ids=ids.to(self.device), logits_to_keep=1).logits[0, -1].float()
105
+ letters = [self.tok.encode(PREFILL + c, add_special_tokens=False)[self.prefix] for c in codes]
106
+ p = torch.softmax(logits[letters] / temperature, dim=0)
107
+ return dict(zip(codes.values(), p.tolist()))
108
+
109
+ def ask(self, family: str, state: str, question: str, options: dict[str, str]) -> Decision:
110
+ """One department decision, calibrated and checked against its threshold."""
111
+ c = self.cal[family]
112
+ p = self.probs(ROUTE[family], state, question, options, c["type"], c["temperature"])
113
+ answer = max(p, key=p.get)
114
+ return Decision(family, answer, p[answer], c["thresholds"][self.error], p)
115
+
116
+ def payment(self, mail: str, sender_in_supplier_master: bool, has_purchase_order: bool) -> Decision:
117
+ """Five questions about the e-mail text, then the company's rule in code."""
118
+ p = {name: self.probs("finance", mail, s["question"], s["criteria"], "noul")["true"]
119
+ for name, s in self.signals.items()}
120
+ facts = not sender_in_supplier_master and not has_purchase_order
121
+ conds = [p["pay"] if facts else 0.0, p["account"], p["skip"], p["login"],
122
+ p["pay"] * (1 - p["order"]) ** 2]
123
+ hold = 1 - math.prod(1 - c for c in conds)
124
+ answer = "hold" if hold >= 0.5 else "pay"
125
+ return Decision("payment_fraud", answer, max(hold, 1 - hold),
126
+ self.cal["payment_fraud"]["thresholds"][self.error], {"hold": hold, "pay": 1 - hold})
127
+
128
+ def general(self, state: str, question: str, options: dict[str, str], kind: str = "choice") -> dict[str, float]:
129
+ """Questions outside the four departments go to Bullfinch 4B (uncalibrated here)."""
130
+ return self.probs("general", state, question, options, kind)
131
+
132
+ def classify(self, text: str, threshold: float = 0.9) -> Decision:
133
+ """Step 0 for a document of unknown type, answered by Bullfinch 4B.
134
+ This threshold is not fitted: refit it on a few hundred of your own documents."""
135
+ p = self.general(text, "Jaki to dokument?", DOC_TYPES)
136
+ answer = max(p, key=p.get)
137
+ return Decision("document", answer, p[answer], threshold, p)
138
+
139
+
140
+ def gate(decisions: list[Decision]) -> str:
141
+ if any(d.family == "payment_fraud" and d.answer == "hold" and d.sure for d in decisions):
142
+ return "BLOCK"
143
+ return "AUTO" if all(d.sure for d in decisions) else "TO PERSON"
144
+
145
+
146
+ # ---- example: one package = a contract, an invoice with three lines, an e-mail ----
147
+
148
+ CHART = {"401-01": "401-01 Materiały biurowe (papier, tonery, artykuły piśmiennicze)",
149
+ "401-03": "401-03 Energia elektryczna, gaz i woda",
150
+ "402-01": "402-01 Usługi telekomunikacyjne (telefony, internet)",
151
+ "402-04": "402-04 Najem i dzierżawa (biura, magazynu, sprzętu)",
152
+ "402-07": "402-07 Reklama i marketing",
153
+ "409-02": "409-02 Reprezentacja (catering i upominki dla kontrahentów)"}
154
+ VAT = {"23": "23% — pozostałe towary i usługi, niewymienione niżej",
155
+ "8": "8% — usługi noclegowe, przewóz osób, produkty lecznicze (leki)",
156
+ "5": "5% — podstawowa żywność i pieczywo (chleb, nabiał, świeże mięso, świeże owoce i warzywa), "
157
+ "książki drukowane",
158
+ "zw": "zw — usługi ubezpieczeniowe, usługi medyczne, usługi finansowe (odsetki, prowizje i opłaty bankowe)"}
159
+ SELLER = "Sprzedawca: Biuro-Serwis Sp. z o.o."
160
+ # (invoice line, purchase-order line)
161
+ LINES = [("Papier do drukarek A4 80 g, karton 5 ryz", "Papier ksero A4 80 g/m², ryza 500 arkuszy"),
162
+ ("Długopis żelowy Pentel EnerGel BL77, niebieski, 0,7 mm", "Długopisy żelowe Pentel EnerGel 0,7 mm, niebieskie"),
163
+ ("Abonament internet światłowodowy 1 Gb/s, listopad 2026", "Internet światłowodowy 1 Gb/s, abonament miesięczny")]
164
+ CLAUSE = ("This Agreement shall commence on the Effective Date and continue for one (1) year. Thereafter it "
165
+ "shall automatically renew for successive one-year terms unless either party gives written notice "
166
+ "of non-renewal at least ninety (90) days before the end of the then-current term.")
167
+ MAILS = {
168
+ "genuine": ("Od: Anna Kowalska <a.kowalska@biuro-serwis.pl>\nTemat: Faktura FV/11/2026/118\n\n"
169
+ "Dzień dobry, w załączniku przesyłam fakturę za dostawę z zamówienia PO-2026-0457. "
170
+ "Termin płatności 14 dni, rachunek bez zmian. Pozdrawiam, Anna Kowalska"),
171
+ "fraud": ("Od: Anna Kowalska <a.kowalska@biuro-serwis-pl.com>\nTemat: PILNE: zmiana rachunku\n\n"
172
+ "Dzień dobry, w związku ze zmianą banku prosimy, aby płatność za fakturę FV/11/2026/118 "
173
+ "przelać na nowy rachunek podany w załączniku. Prosimy o realizację jeszcze dziś."),
174
+ }
175
+
176
+
177
+ def package(st: Starling, mail: str) -> list[Decision]:
178
+ invoice = f"{SELLER}\nFaktura FV/11/2026/118\n" + "\n".join(f"{i}. {line}" for i, (line, _) in enumerate(LINES, 1))
179
+ # step 0: two files of unknown type (the e-mail came through the inbox). In real code, route by the answer.
180
+ d = [st.classify(doc) for doc in (CLAUSE, invoice)]
181
+ d.append(st.ask("contract_risk", CLAUSE,
182
+ "Sprawdź fragment umowy handlowej. Czy zawiera on automatyczne lub jednostronne przedłużenie "
183
+ "umowy na kolejny okres?", {"true": "tak, zawiera", "false": "nie, nie zawiera"}))
184
+ for line, po in LINES:
185
+ state = f"{SELLER}\nPozycja faktury: {line}"
186
+ d.append(st.ask("gl_account", state, "Na które konto kosztowe zaksięgować tę pozycję faktury?", CHART))
187
+ d.append(st.ask("vat_rate", state,
188
+ "Jaką stawkę VAT powinna mieć ta pozycja faktury według matrycy stawek firmy?", VAT))
189
+ d.append(st.ask("po_match", f"Pozycja w zamówieniu (PO): {po}\nPozycja na fakturze: {line}",
190
+ "Czy pozycja z faktury to ten sam towar lub usługa co pozycja z zamówienia (PO)? "
191
+ "Ilości i ceny pomiń.", {"true": "tak, ta sama pozycja", "false": "nie, inny towar lub inny wariant"}))
192
+ d.append(st.payment(mail, sender_in_supplier_master=True, has_purchase_order=True))
193
+ return d
194
+
195
+
196
+ if __name__ == "__main__":
197
+ st = Starling(error="0.05")
198
+ for name, mail in MAILS.items():
199
+ decisions = package(st, mail)
200
+ print(f"\n== package with the {name} e-mail ==")
201
+ for d in decisions:
202
+ print(f"{d.family:14} {d.answer:8} {d.confidence:6.1%} threshold {d.threshold:6.1%} "
203
+ f"{'sure' if d.sure else 'NOT SURE'}")
204
+ print("gate:", gate(decisions))