PEFT
Safetensors
Polish
English
typed-decisions
decision-model
classification
polish
lora
qlora
multi-adapter
business
contracts
invoices
payment-fraud
Run this model with HF Jobs
Run Takzen/starling-4b on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Takzen/starling-4b. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Takzen/starling-4b on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Takzen/starling-4b with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use Takzen/starling-4b with PEFT:
Task type is invalid.
- Notebooks
- Google Colab
- Kaggle
Add starling.py (whole flow with package gate); fix procurement example; note part-number aliases
Browse filesFiles changed (2)
- README.md+61-5
- starling.pyAdded+204
87 unmodified lines8889909192939495212 unmodified lines30830931031131231331431531631731838 unmodified lines35735835936036136249 unmodified lines41241341441541641787 unmodified linesVAT matrix and the PO are part of the state or the options. A new account or a new ratetherefore needs no retraining.- **Code compares numbers and applies policy.** Ordinary code checks amounts, prices, quantitiesand the company's rules. The model only judges what is fuzzy, such as whether "Toner HP 59A" and"Kaseta z tonerem CF259A" are the same item.### Why finance asks five questions212 unmodified lines# procurement: is the invoice line the PO item?print(decide("procurement", "Zamówienie (PO): Toner HP 59A czarny\nFaktura: Kaseta z tonerem CF259A, czarna","Czy pozycja z faktury to ten sam towar co pozycja z zamówienia? Ilości i ceny pomiń.",{"true": "tak, ta sama pozycja", "false": "nie, inny towar lub inny wariant"},kind="noul", temperature=CAL["procurement"]["po_match"]["temperature"]))# {'true': 0.889, 'false': 0.111}: the same toner, 89% sure# finance: five questions about the e-mail text, the company's rule in code38 unmodified lines- Questions can also be asked with an English frame (`State`, `Question`, `Options`). Everydecision was trained with several Polish phrasings and one English one.## Training- **Recipe:** QLoRA, as in Bullfinch.49 unmodified lines- **Finance flags e-mails for verification; it does not prove fraud.** A held payment should bechecked by a person through a known channel. It asks five questions per e-mail, which makes itfive times slower than a single question.- **Department adapters are weaker at general questions than Bullfinch 4B.** Route those toBullfinch.- **Decisions with legal or financial consequences should be reviewed by a person.**87 unmodified lines8889909192939495212 unmodified lines30830931031131231331431531631731831932038 unmodified lines35936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441549 unmodified lines46546646746846947047147247387 unmodified linesVAT matrix and the PO are part of the state or the options. A new account or a new ratetherefore needs no retraining.- **Code compares numbers and applies policy.** Ordinary code checks amounts, prices, quantitiesand the company's rules. The model only judges what is fuzzy, such as whether "Papier ksero A480 g/m², ryza" and "Papier do drukarek A4 80 g, karton 5 ryz" are the same item.### Why finance asks five questions212 unmodified lines# procurement: is the invoice line the PO item?print(decide("procurement","Pozycja w zamówieniu (PO): Długopisy żelowe Pentel EnerGel 0,7 mm, niebieskie\n""Pozycja na fakturze: Długopis żelowy Pentel EnerGel BL77, niebieski, 0,7 mm","Czy pozycja z faktury to ten sam towar lub usługa co pozycja z zamówienia (PO)? Ilości i ceny pomiń.",{"true": "tak, ta sama pozycja", "false": "nie, inny towar lub inny wariant"},kind="noul", temperature=CAL["procurement"]["po_match"]["temperature"]))# {'true': 0.962, 'false': 0.038}: the same pen, 96% sure# finance: five questions about the e-mail text, the company's rule in code38 unmodified lines- Questions can also be asked with an English frame (`State`, `Question`, `Options`). Everydecision was trained with several Polish phrasings and one English one.### Run the whole flow[`starling.py`](starling.py) in this repo puts the pieces together in one file:- **Step 0, files of unknown type:** `classify()` asks Bullfinch 4B whether a file is a contractor an invoice. Below its threshold, the file goes to a person. E-mails are known by theirchannel. Bullfinch tends to call an e-mail that sends an invoice an invoice.- **Routing:** code sends each question to the adapter of the department that owns it.- **Decisions:** each one is calibrated and checked against its threshold from `CALIBRATION.json`.- **Payment rule:** it runs in code.- **Gate:** it decides the whole package as BLOCK, TO PERSON or AUTO.The document's content comes from your systems: invoice lines, the purchase order, facts about thesender. A KSeF invoice and your ERP are typical sources. The model does not extract data. It onlydecides.```bashpip install torch transformers peft bitsandbytes huggingface_hubpython starling.py```It runs one package twice. The package has a contract clause, an invoice with three lines and ane-mail. The first run uses a genuine e-mail, the second a fake one asking for a new bank account.```text== package with the genuine e-mail ==document contract 99.2% threshold 90.0% suredocument invoice 98.2% threshold 90.0% surecontract_risk true 97.5% threshold 87.5% suregl_account 401-01 99.0% threshold 52.7% surevat_rate 23 100.0% threshold 55.1% surepo_match true 94.1% threshold 59.5% suregl_account 401-01 98.7% threshold 52.7% surevat_rate 23 100.0% threshold 55.1% surepo_match true 96.2% threshold 59.5% suregl_account 402-01 99.8% threshold 52.7% surevat_rate 23 100.0% threshold 55.1% surepo_match true 92.1% threshold 59.5% surepayment_fraud pay 99.9% threshold 52.8% suregate: AUTO== package with the fraud e-mail ==... (the same 12 decisions) ...payment_fraud hold 100.0% threshold 52.8% suregate: BLOCK```AUTO means every decision is sure. It does not mean "approve". Here the contract does renewautomatically (`contract_risk true`). Your code decides what follows, such as flagging the clausefor the legal team.## Training- **Recipe:** QLoRA, as in Bullfinch.49 unmodified lines- **Finance flags e-mails for verification; it does not prove fraud.** A held payment should bechecked by a person through a known channel. It asks five questions per e-mail, which makes itfive times slower than a single question.- **Procurement does not know part-number aliases.** It treats a different product code as adifferent variant. For example, it says that "HP 59A" and "CF259A" are different toners, thoughthey are the same. Keep an alias table in code, or put both codes in the description.- **Department adapters are weaker at general questions than Bullfinch 4B.** Route those toBullfinch.- **Decisions with legal or financial consequences should be reviewed by a person.**
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204#!/usr/bin/env python3"""Starling 4B: the whole decision flow in one file.
pip install torch transformers peft bitsandbytes huggingface_hub python starling.py
Tested with transformers 5.20, peft 0.21, bitsandbytes 0.50, torch 2.11, on one NVIDIA GPU with8 GB (about 4 GB used).
What it does:1. Loads Qwen3.5-4B in 4-bit once, Bullfinch 4B and the four Starling adapters on top of it.2. Step 0, for a file of unknown type: classify() asks Bullfinch 4B whether it is a contract or an invoice. Usually the channel already tells you: KSeF gives the invoice, the inbox the e-mail. Then code routes each question to the adapter of the department that owns it (ROUTE).3. Each adapter answers with one forward pass and a calibrated probability per option.4. A gate in code decides the whole package: * BLOCK: the finance rule holds the payment and is sure. Verify through a known channel. * TO PERSON: at least one decision is below its threshold. A person or a large model decides. * AUTO: every decision is at or above its threshold.
The content comes from your systems: invoice lines, purchase order, facts about the sender (forexample KSeF and the ERP). The model does not extract data; it only decides.
Thresholds come from <adapter>/CALIBRATION.json. They were fitted on our calibration split for atmost 5% error ("0.05") or 1% error ("0.01"). Before automating anything, refit them on a few hundredrows of your own."""
from __future__ import annotations
import jsonimport mathfrom dataclasses import dataclass
import torchfrom huggingface_hub import hf_hub_downloadfrom peft import PeftModelfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
BASE, REVISION = "Qwen/Qwen3.5-4B", "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a"REPO = "Takzen/starling-4b"GENERAL = "Takzen/bullfinch-4b"ADAPTERS = ("legal", "accounting", "procurement", "finance")# question family -> the department adapter that answers itROUTE = {"contract_nli": "legal", "contract_risk": "legal", "gl_account": "accounting", "vat_rate": "accounting", "po_match": "procurement", "payment_fraud": "finance"}PREFILL = '{"answer": "'FRAME = ("Stan", "Pytanie", "Opcje", 'Odpowiedz wyłącznie w formacie JSON: {"answer": "<litera opcji>"}.')LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"# Step 0 is for files of unknown type (an upload, a scan). E-mails are known by their channel, the# inbox. Bullfinch tends to call an e-mail that sends an invoice an invoice, so e-mails skip step 0.DOC_TYPES = {"contract": "fragment umowy (zapisy, strony, warunki)", "invoice": "faktura VAT (sprzedawca, pozycje, kwoty)", "other": "inny dokument"}
@dataclassclass Decision: family: str answer: str confidence: float threshold: float probs: dict[str, float]
@property def sure(self) -> bool: return self.confidence >= self.threshold
class Starling: def __init__(self, error: str = "0.05", device: int = 0): self.error, self.device = error, device self.tok = AutoTokenizer.from_pretrained(BASE, revision=REVISION) base = AutoModelForCausalLM.from_pretrained( BASE, revision=REVISION, device_map={"": device}, dtype=torch.bfloat16, quantization_config=BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True)) self.model = PeftModel.from_pretrained(base, GENERAL, adapter_name="general") for name in ADAPTERS: self.model.load_adapter(REPO, adapter_name=name, subfolder=name) self.model.eval() self.cal: dict[str, dict] = {} for name in ADAPTERS: with open(hf_hub_download(REPO, f"{name}/CALIBRATION.json"), encoding="utf-8") as f: self.cal.update(json.load(f)["families"]) with open(hf_hub_download(REPO, "finance/SIGNALS.json"), encoding="utf-8") as f: self.signals = json.load(f)["signals"] self.prefix = len(self.tok.encode(PREFILL, add_special_tokens=False))
def probs(self, adapter: str, state: str, question: str, options: dict[str, str], kind: str = "choice", temperature: float = 1.0) -> dict[str, float]: """Probability of each option key. `kind` is "choice" or "noul" (yes/no: keys true/false).""" self.model.set_adapter(adapter) s, q, o, reply = FRAME codes = dict(zip(LETTERS, options)) lines = "\n".join(f"{c}) {k}: {options[k]}" if kind == "choice" else f"{c}) {options[k]}" for c, k in codes.items()) content = f"{s}:\n{state}\n\n{q}: {question}\n\n{o}:\n{lines}\n\n{reply}" text = self.tok.apply_chat_template([{"role": "user", "content": content}], tokenize=False, add_generation_prompt=True, enable_thinking=False) ids = self.tok(text + PREFILL, return_tensors="pt", add_special_tokens=False).input_ids with torch.inference_mode(): logits = self.model(input_ids=ids.to(self.device), logits_to_keep=1).logits[0, -1].float() letters = [self.tok.encode(PREFILL + c, add_special_tokens=False)[self.prefix] for c in codes] p = torch.softmax(logits[letters] / temperature, dim=0) return dict(zip(codes.values(), p.tolist()))
def ask(self, family: str, state: str, question: str, options: dict[str, str]) -> Decision: """One department decision, calibrated and checked against its threshold.""" c = self.cal[family] p = self.probs(ROUTE[family], state, question, options, c["type"], c["temperature"]) answer = max(p, key=p.get) return Decision(family, answer, p[answer], c["thresholds"][self.error], p)
def payment(self, mail: str, sender_in_supplier_master: bool, has_purchase_order: bool) -> Decision: """Five questions about the e-mail text, then the company's rule in code.""" p = {name: self.probs("finance", mail, s["question"], s["criteria"], "noul")["true"] for name, s in self.signals.items()} facts = not sender_in_supplier_master and not has_purchase_order conds = [p["pay"] if facts else 0.0, p["account"], p["skip"], p["login"], p["pay"] * (1 - p["order"]) ** 2] hold = 1 - math.prod(1 - c for c in conds) answer = "hold" if hold >= 0.5 else "pay" return Decision("payment_fraud", answer, max(hold, 1 - hold), self.cal["payment_fraud"]["thresholds"][self.error], {"hold": hold, "pay": 1 - hold})
def general(self, state: str, question: str, options: dict[str, str], kind: str = "choice") -> dict[str, float]: """Questions outside the four departments go to Bullfinch 4B (uncalibrated here).""" return self.probs("general", state, question, options, kind)
def classify(self, text: str, threshold: float = 0.9) -> Decision: """Step 0 for a document of unknown type, answered by Bullfinch 4B. This threshold is not fitted: refit it on a few hundred of your own documents.""" p = self.general(text, "Jaki to dokument?", DOC_TYPES) answer = max(p, key=p.get) return Decision("document", answer, p[answer], threshold, p)
def gate(decisions: list[Decision]) -> str: if any(d.family == "payment_fraud" and d.answer == "hold" and d.sure for d in decisions): return "BLOCK" return "AUTO" if all(d.sure for d in decisions) else "TO PERSON"
# ---- example: one package = a contract, an invoice with three lines, an e-mail ----
CHART = {"401-01": "401-01 Materiały biurowe (papier, tonery, artykuły piśmiennicze)", "401-03": "401-03 Energia elektryczna, gaz i woda", "402-01": "402-01 Usługi telekomunikacyjne (telefony, internet)", "402-04": "402-04 Najem i dzierżawa (biura, magazynu, sprzętu)", "402-07": "402-07 Reklama i marketing", "409-02": "409-02 Reprezentacja (catering i upominki dla kontrahentów)"}VAT = {"23": "23% — pozostałe towary i usługi, niewymienione niżej", "8": "8% — usługi noclegowe, przewóz osób, produkty lecznicze (leki)", "5": "5% — podstawowa żywność i pieczywo (chleb, nabiał, świeże mięso, świeże owoce i warzywa), " "książki drukowane", "zw": "zw — usługi ubezpieczeniowe, usługi medyczne, usługi finansowe (odsetki, prowizje i opłaty bankowe)"}SELLER = "Sprzedawca: Biuro-Serwis Sp. z o.o."# (invoice line, purchase-order line)LINES = [("Papier do drukarek A4 80 g, karton 5 ryz", "Papier ksero A4 80 g/m², ryza 500 arkuszy"), ("Długopis żelowy Pentel EnerGel BL77, niebieski, 0,7 mm", "Długopisy żelowe Pentel EnerGel 0,7 mm, niebieskie"), ("Abonament internet światłowodowy 1 Gb/s, listopad 2026", "Internet światłowodowy 1 Gb/s, abonament miesięczny")]CLAUSE = ("This Agreement shall commence on the Effective Date and continue for one (1) year. Thereafter it " "shall automatically renew for successive one-year terms unless either party gives written notice " "of non-renewal at least ninety (90) days before the end of the then-current term.")MAILS = { "genuine": ("Od: Anna Kowalska <a.kowalska@biuro-serwis.pl>\nTemat: Faktura FV/11/2026/118\n\n" "Dzień dobry, w załączniku przesyłam fakturę za dostawę z zamówienia PO-2026-0457. " "Termin płatności 14 dni, rachunek bez zmian. Pozdrawiam, Anna Kowalska"), "fraud": ("Od: Anna Kowalska <a.kowalska@biuro-serwis-pl.com>\nTemat: PILNE: zmiana rachunku\n\n" "Dzień dobry, w związku ze zmianą banku prosimy, aby płatność za fakturę FV/11/2026/118 " "przelać na nowy rachunek podany w załączniku. Prosimy o realizację jeszcze dziś."),}
def package(st: Starling, mail: str) -> list[Decision]: invoice = f"{SELLER}\nFaktura FV/11/2026/118\n" + "\n".join(f"{i}. {line}" for i, (line, _) in enumerate(LINES, 1)) # step 0: two files of unknown type (the e-mail came through the inbox). In real code, route by the answer. d = [st.classify(doc) for doc in (CLAUSE, invoice)] d.append(st.ask("contract_risk", CLAUSE, "Sprawdź fragment umowy handlowej. Czy zawiera on automatyczne lub jednostronne przedłużenie " "umowy na kolejny okres?", {"true": "tak, zawiera", "false": "nie, nie zawiera"})) for line, po in LINES: state = f"{SELLER}\nPozycja faktury: {line}" d.append(st.ask("gl_account", state, "Na które konto kosztowe zaksięgować tę pozycję faktury?", CHART)) d.append(st.ask("vat_rate", state, "Jaką stawkę VAT powinna mieć ta pozycja faktury według matrycy stawek firmy?", VAT)) d.append(st.ask("po_match", f"Pozycja w zamówieniu (PO): {po}\nPozycja na fakturze: {line}", "Czy pozycja z faktury to ten sam towar lub usługa co pozycja z zamówienia (PO)? " "Ilości i ceny pomiń.", {"true": "tak, ta sama pozycja", "false": "nie, inny towar lub inny wariant"})) d.append(st.payment(mail, sender_in_supplier_master=True, has_purchase_order=True)) return d
if __name__ == "__main__": st = Starling(error="0.05") for name, mail in MAILS.items(): decisions = package(st, mail) print(f"\n== package with the {name} e-mail ==") for d in decisions: print(f"{d.family:14} {d.answer:8} {d.confidence:6.1%} threshold {d.threshold:6.1%} " f"{'sure' if d.sure else 'NOT SURE'}") print("gate:", gate(decisions))README.md+61-5
starling.pyAdded+204