theclassifier 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ """The Classifier: local inference and LoRA fine-tuning."""
2
+ __version__ = "0.1.0"
3
+
4
+
5
+ def __getattr__(name):
6
+ if name == "Classifier":
7
+ from .model import Classifier
8
+ return Classifier
9
+ if name == "finetune":
10
+ from .training import finetune
11
+ return finetune
12
+ raise AttributeError(name)
@@ -0,0 +1,2 @@
1
+ from .cli import main
2
+ main()
@@ -0,0 +1,40 @@
1
+ """Cache-first checkpoint resolution. No model weights are bundled in the wheel."""
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ from huggingface_hub import snapshot_download
6
+ from huggingface_hub.errors import LocalEntryNotFoundError
7
+
8
+ VERSIONS = ("general", "intent", "sentiment", "triage", "cause", "codify", "complaints", "stars")
9
+
10
+
11
+ def validate_checkpoint(path):
12
+ path = Path(path)
13
+ required = [path / "adapter/adapter_config.json", path / "tokenizer/tokenizer_config.json"]
14
+ weights = any((path / "adapter" / name).is_file() for name in ("adapter_model.safetensors", "adapter_model.bin"))
15
+ if not weights or not all(p.is_file() for p in required) or not any((path / name).is_file() for name in ("head.safetensors", "head.pt")):
16
+ raise ValueError(f"Incomplete checkpoint at {path}: expected adapter/, tokenizer/ and head.safetensors or head.pt")
17
+ return path
18
+
19
+
20
+ def resolve_checkpoint(version="general", *, checkpoint=None, model_repo=None, cache_dir=None, revision="main", offline=False):
21
+ if checkpoint is not None:
22
+ return validate_checkpoint(Path(checkpoint).expanduser())
23
+ if version not in VERSIONS:
24
+ raise ValueError(f"Unknown version {version!r}; choose {', '.join(VERSIONS)} or supply checkpoint=...")
25
+ repo = model_repo or os.environ.get("THECLASSIFIER_MODEL_REPO") or "TrueState/theclassifier"
26
+ options = dict(repo_id=repo, revision=revision, cache_dir=cache_dir,
27
+ allow_patterns=[f"{version}/adapter/*", f"{version}/tokenizer/*", f"{version}/head.*", f"{version}/classifier.json"])
28
+ try:
29
+ root = snapshot_download(**options, local_files_only=True)
30
+ return validate_checkpoint(Path(root) / version)
31
+ except (LocalEntryNotFoundError, ValueError):
32
+ if offline:
33
+ raise FileNotFoundError(f"Version {version!r} is not fully cached; download it once before offline use") from None
34
+ root = snapshot_download(**options)
35
+ return validate_checkpoint(Path(root) / version)
36
+
37
+
38
+ def checkpoint_model(path):
39
+ config = json.loads((Path(path) / "adapter/adapter_config.json").read_text())
40
+ return config["base_model_name_or_path"]
theclassifier/cli.py ADDED
@@ -0,0 +1,63 @@
1
+ import argparse
2
+ import json
3
+ import os
4
+
5
+
6
+ def main(argv=None):
7
+ parser = argparse.ArgumentParser(prog="theclassifier")
8
+ sub = parser.add_subparsers(dest="command", required=True)
9
+ for command in ("serve", "classify", "download", "finetune"):
10
+ p = sub.add_parser(command)
11
+ p.add_argument("--version", default="general" if command != "finetune" else None)
12
+ p.add_argument("--checkpoint")
13
+ p.add_argument("--model-repo", default=os.getenv("THECLASSIFIER_MODEL_REPO"))
14
+ p.add_argument("--cache-dir")
15
+ p.add_argument("--revision", default="main")
16
+ p.add_argument("--offline", action="store_true")
17
+ if command != "download":
18
+ p.add_argument("--device", default="auto")
19
+ p.add_argument("--max-length", type=int, default=2048)
20
+ if command == "serve":
21
+ p.add_argument("--host", default="127.0.0.1")
22
+ p.add_argument("--port", type=int, default=8090)
23
+ elif command == "classify":
24
+ p.add_argument("--text", required=True)
25
+ p.add_argument("--choices", nargs="+", required=True)
26
+ p.add_argument("--question", default="Which label fits?")
27
+ elif command == "finetune":
28
+ p.add_argument("--data", required=True)
29
+ p.add_argument("--output", required=True)
30
+ p.add_argument("--base-model", default="Qwen/Qwen3-1.7B-Base")
31
+ p.add_argument("--epochs", type=int, default=1)
32
+ p.add_argument("--rank", type=int, default=16)
33
+ p.add_argument("--alpha", type=int, default=16)
34
+ p.add_argument("--learning-rate", type=float, default=2e-4)
35
+ p.add_argument("--grad-accum", type=int, default=16)
36
+ p.add_argument("--max-steps", type=int)
37
+ args = vars(parser.parse_args(argv))
38
+ command = args.pop("command")
39
+ try:
40
+ if command == "download":
41
+ from .checkpoints import resolve_checkpoint
42
+ print(resolve_checkpoint(**args))
43
+ elif command == "finetune":
44
+ from .training import finetune
45
+ args["output_dir"] = args.pop("output")
46
+ print(json.dumps(finetune(**args), indent=2, default=str))
47
+ else:
48
+ from .model import Classifier
49
+ if command == "classify":
50
+ text, choices, question = args.pop("text"), args.pop("choices"), args.pop("question")
51
+ print(json.dumps(Classifier(**args).classify(text, choices=choices, question=question), indent=2))
52
+ else:
53
+ host, port = args.pop("host"), args.pop("port")
54
+ key = os.getenv("API_KEY")
55
+ if host not in {"localhost", "127.0.0.1", "::1"} and not key:
56
+ parser.error("Set API_KEY before exposing the server outside localhost")
57
+ import uvicorn
58
+ from .server import create_app
59
+ uvicorn.run(create_app(Classifier(**args), api_key=key), host=host, port=port)
60
+ except (ValueError, FileNotFoundError) as exc:
61
+ parser.error(str(exc))
62
+ except ImportError as exc:
63
+ parser.error(f"Missing dependency: {exc}. For serving, install theclassifier[serve].")
theclassifier/model.py ADDED
@@ -0,0 +1,142 @@
1
+ import json
2
+ import threading
3
+ import time
4
+ from pathlib import Path
5
+ import torch
6
+ from torch import nn
7
+ from transformers import AutoModel, AutoTokenizer
8
+ from peft import PeftModel
9
+ from safetensors.torch import load_file
10
+ from .checkpoints import resolve_checkpoint, checkpoint_model
11
+ from .prompt import pack_example
12
+ from .schema import normalize
13
+
14
+
15
+ def select_device(device="auto"):
16
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu") if device == "auto" else torch.device(device)
17
+ if device.type not in {"cpu", "cuda"}:
18
+ raise ValueError("Supported devices: auto, cpu, cuda, cuda:N")
19
+ if device.type == "cuda" and not torch.cuda.is_available():
20
+ raise ValueError("CUDA was requested but is unavailable. Install a CUDA-enabled PyTorch build or use device='cpu'.")
21
+ return device
22
+
23
+
24
+ def select_dtype(device):
25
+ if device.type == "cuda":
26
+ with torch.cuda.device(device):
27
+ return torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float32
28
+ return torch.float32
29
+
30
+
31
+ class Scorer(nn.Module):
32
+ def __init__(self, encoder):
33
+ super().__init__()
34
+ self.encoder = encoder
35
+ self.head = nn.Linear(encoder.config.hidden_size, 1)
36
+
37
+ def forward(self, input_ids, attention_mask):
38
+ hidden = self.encoder(input_ids=input_ids, attention_mask=attention_mask, use_cache=False).last_hidden_state
39
+ last = attention_mask.sum(dim=1) - 1
40
+ return self.head(hidden[torch.arange(len(hidden), device=hidden.device), last].float()).squeeze(-1)
41
+
42
+
43
+ def load_head(path):
44
+ path = Path(path)
45
+ if (path / "head.safetensors").is_file():
46
+ return load_file(str(path / "head.safetensors"))
47
+ return torch.load(path / "head.pt", map_location="cpu", weights_only=True)
48
+
49
+
50
+ class Classifier:
51
+ def __init__(self, version="general", *, checkpoint=None, model_repo=None, cache_dir=None,
52
+ revision="main", offline=False, device="auto", max_length=2048, batch_size=8,
53
+ base_model=None, attention="sdpa"):
54
+ if max_length < 2 or batch_size < 1:
55
+ raise ValueError("max_length must be >=2 and batch_size >=1")
56
+ if attention not in {"sdpa", "eager"}:
57
+ raise ValueError("attention must be sdpa or eager")
58
+ self.device = select_device(device)
59
+ self.options = dict(model_repo=model_repo, cache_dir=cache_dir, revision=revision, offline=offline)
60
+ path = resolve_checkpoint(version, checkpoint=checkpoint, **self.options)
61
+ self.base_model = base_model or checkpoint_model(path)
62
+ self.max_length, self.batch_size = max_length, batch_size
63
+ self.default_version = version
64
+ self.lock = threading.RLock()
65
+ self.tokenizers = {}
66
+ self.heads = {}
67
+ encoder = AutoModel.from_pretrained(self.base_model, dtype=select_dtype(self.device), attn_implementation=attention,
68
+ cache_dir=cache_dir, local_files_only=offline, trust_remote_code=False)
69
+ encoder = PeftModel.from_pretrained(encoder, path / "adapter", adapter_name=version, local_files_only=True)
70
+ self.model = Scorer(encoder).to(self.device)
71
+ self._store(version, path)
72
+ self.active = None
73
+ self.model.eval()
74
+
75
+ def _store(self, version, path):
76
+ head = load_head(path)
77
+ # Validate shape before a checkpoint is made available.
78
+ probe = nn.Linear(self.model.head.in_features, 1)
79
+ probe.load_state_dict(head)
80
+ tokenizer = AutoTokenizer.from_pretrained(path / "tokenizer", local_files_only=True, trust_remote_code=False)
81
+ if tokenizer.pad_token_id is None:
82
+ if tokenizer.eos_token_id is None:
83
+ raise ValueError("Checkpoint tokenizer requires a pad or EOS token")
84
+ tokenizer.pad_token = tokenizer.eos_token
85
+ tokenizer.padding_side = "right"
86
+ self.heads[version], self.tokenizers[version] = head, tokenizer
87
+
88
+ def load_adapter(self, version, checkpoint=None):
89
+ with self.lock:
90
+ if version in self.heads:
91
+ return self
92
+ path = resolve_checkpoint(version, checkpoint=checkpoint, **self.options)
93
+ expected = checkpoint_model(path)
94
+ first = self.model.encoder.peft_config[self.default_version].base_model_name_or_path
95
+ if expected != first:
96
+ raise ValueError("Adapter base model does not match the loaded backbone")
97
+ self._store(version, path)
98
+ try:
99
+ self.model.encoder.load_adapter(path / "adapter", adapter_name=version, is_trainable=False, local_files_only=True)
100
+ except Exception:
101
+ self.heads.pop(version, None); self.tokenizers.pop(version, None)
102
+ raise
103
+ self.active = None
104
+ self.model.eval()
105
+ return self
106
+
107
+ def _tokens(self, rows, tokenizer):
108
+ sequences = []
109
+ for text in rows:
110
+ ids = tokenizer.encode(text, add_special_tokens=True)
111
+ # Preserve the original checkpoint's first-token-plus-tail convention.
112
+ if len(ids) > self.max_length:
113
+ ids = ids[:1] + ids[-(self.max_length - 1):]
114
+ sequences.append({"input_ids": ids, "attention_mask": [1] * len(ids)})
115
+ return tokenizer.pad(sequences, padding=True, return_tensors="pt").to(self.device)
116
+
117
+ def classify(self, state, questions=None, *, choices=None, question="Which label fits?", version=None):
118
+ if questions is not None and choices is not None:
119
+ raise ValueError("Pass questions or choices, not both")
120
+ questions = normalize(state, questions if questions is not None else [{"question": question, "choices": choices}])
121
+ version = version or self.default_version
122
+ start = time.perf_counter()
123
+ with self.lock, torch.inference_mode():
124
+ self.load_adapter(version)
125
+ if self.active != version:
126
+ self.model.encoder.set_adapter(version)
127
+ self.model.head.load_state_dict(self.heads[version])
128
+ self.active = version
129
+ self.model.eval()
130
+ tokenizer = self.tokenizers[version]
131
+ results, tokens = [], 0
132
+ for item in questions:
133
+ rows = [pack_example(state, item["question"], c["choice"], item["guidance"], c["criteria"], item["choices"]) for c in item["choices"]]
134
+ chunks = []
135
+ for offset in range(0, len(rows), self.batch_size):
136
+ batch = self._tokens(rows[offset:offset+self.batch_size], tokenizer)
137
+ tokens += int(batch["attention_mask"].sum())
138
+ chunks.append(self.model(batch["input_ids"], batch["attention_mask"]))
139
+ probabilities = torch.cat(chunks).float().softmax(dim=0).cpu().tolist()
140
+ detailed = sorted([{"choice": c["choice"], "score": round(p, 4)} for c,p in zip(item["choices"], probabilities)], key=lambda row: row["score"], reverse=True)
141
+ results.append({"question": item["question"], "selected": detailed[0], "detailed_results": detailed})
142
+ return {"results": results, "version": version, "input_tokens": tokens, "latency_ms": round((time.perf_counter()-start)*1000, 3)}
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ def pack_example(
5
+ state: str,
6
+ question: str,
7
+ choice: str,
8
+ guidance: str | None = None,
9
+ criteria: str | None = None,
10
+ choices: list[dict] | None = None,
11
+ ) -> str:
12
+ if not state.strip():
13
+ raise ValueError("state must not be empty")
14
+ if not question.strip():
15
+ raise ValueError("question must not be empty")
16
+ if not choice.strip():
17
+ raise ValueError("choice must not be empty")
18
+
19
+ menu = choices or [{"choice": choice, "criteria": criteria}]
20
+ parts = [f"<state>\n{state.strip()}", f"<question>\n{question.strip()}"]
21
+ if guidance and guidance.strip():
22
+ parts.append(f"<guidance>\n{guidance.strip()}")
23
+ parts.append(_choices_block(menu))
24
+ parts.append(f"<choice>\n{choice.strip()}")
25
+ return "\n".join(parts)
26
+
27
+
28
+ def _choices_block(choices: list[dict]) -> str:
29
+ lines = ["<choices>"]
30
+ for item in choices:
31
+ name = str(item.get("choice") or "").strip()
32
+ if not name:
33
+ continue
34
+ criterion = item.get("criteria")
35
+ if criterion is not None and str(criterion).strip():
36
+ lines.append(f"- {name}: {str(criterion).strip()}")
37
+ else:
38
+ lines.append(f"- {name}")
39
+ if len(lines) == 1:
40
+ raise ValueError("choices must include at least one choice")
41
+ return "\n".join(lines)
42
+
43
+
44
+ def humanize_label(label: str) -> str:
45
+ return label.replace("_", " ").replace("?", "").strip()
@@ -0,0 +1,30 @@
1
+ """Input validation shared by inference, serving and training."""
2
+ def normalize(state, questions):
3
+ if not isinstance(state, str) or not state.strip():
4
+ raise ValueError("state must be a non-empty string")
5
+ if not isinstance(questions, list) or not questions:
6
+ raise ValueError("questions must be a non-empty list")
7
+ normalized = []
8
+ for question in questions:
9
+ if not isinstance(question, dict) or not isinstance(question.get("question"), str) or not question["question"].strip():
10
+ raise ValueError("each question needs a non-empty question string")
11
+ raw = question.get("choices")
12
+ if not isinstance(raw, list) or not raw:
13
+ raise ValueError("each question needs at least one choice")
14
+ choices = []
15
+ for choice in raw:
16
+ if isinstance(choice, str):
17
+ choice = {"choice": choice}
18
+ if not isinstance(choice, dict) or not isinstance(choice.get("choice"), str) or not choice["choice"].strip():
19
+ raise ValueError("choices must be non-empty strings or objects with a choice string")
20
+ criteria = choice.get("criteria")
21
+ if criteria is not None and not isinstance(criteria, str):
22
+ raise ValueError("criteria must be a string")
23
+ choices.append({"choice": choice["choice"].strip(), "criteria": criteria})
24
+ if len({c["choice"] for c in choices}) != len(choices):
25
+ raise ValueError("choice names must be unique within each question")
26
+ guidance = question.get("guidance")
27
+ if guidance is not None and not isinstance(guidance, str):
28
+ raise ValueError("guidance must be a string")
29
+ normalized.append({"question": question["question"].strip(), "choices": choices, "guidance": guidance})
30
+ return normalized
@@ -0,0 +1,33 @@
1
+ """Standalone inference server; deliberately separate from hosted billing."""
2
+ import hmac
3
+ from typing import Any
4
+ from fastapi import FastAPI, Header, HTTPException
5
+ from pydantic import BaseModel, Field, ConfigDict
6
+
7
+
8
+ class ClassifyRequest(BaseModel):
9
+ model_config = ConfigDict(extra="forbid")
10
+ state: str
11
+ questions: list[dict[str, Any]] = Field(min_length=1)
12
+ version: str | None = None
13
+
14
+
15
+ def create_app(classifier, *, api_key=None):
16
+ app = FastAPI(title="The Classifier", version="0.1.0")
17
+
18
+ @app.get("/health")
19
+ def health():
20
+ return {"status": "ok"}
21
+
22
+ @app.post("/v1/classify")
23
+ def classify(body: ClassifyRequest, authorization: str | None = Header(default=None)):
24
+ if api_key and not hmac.compare_digest(authorization or "", f"Bearer {api_key}"):
25
+ raise HTTPException(status_code=401, detail="Invalid API key")
26
+ try:
27
+ return classifier.classify(body.state, body.questions, version=body.version)
28
+ except ValueError as exc:
29
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
30
+ except (FileNotFoundError, OSError) as exc:
31
+ raise HTTPException(status_code=503, detail="Requested checkpoint is unavailable") from exc
32
+
33
+ return app
@@ -0,0 +1,120 @@
1
+ """Fine-tune LoRA adapters and a scalar head using menu cross-entropy."""
2
+ import json
3
+ import random
4
+ from pathlib import Path
5
+ import torch
6
+ from transformers import AutoModel, AutoTokenizer
7
+ from peft import LoraConfig, TaskType, get_peft_model, PeftModel
8
+ from safetensors.torch import save_file
9
+ from .model import Scorer, select_device, select_dtype, load_head
10
+ from .checkpoints import resolve_checkpoint, checkpoint_model
11
+ from .schema import normalize
12
+ from .prompt import pack_example
13
+
14
+
15
+ def read_examples(source):
16
+ if isinstance(source, (str, Path)):
17
+ with Path(source).open() as handle:
18
+ source = [json.loads(line) for line in handle if line.strip()]
19
+ examples = []
20
+ for index, row in enumerate(source):
21
+ if not isinstance(row, dict):
22
+ raise ValueError(f"Example {index}: expected an object")
23
+ state = row.get("state")
24
+ item = normalize(state, [{"question": row.get("question"), "choices": row.get("choices"), "guidance": row.get("guidance")}])[0]
25
+ answer = row.get("answer")
26
+ names = [c["choice"] for c in item["choices"]]
27
+ if len(names) < 2 or answer not in names:
28
+ raise ValueError(f"Example {index}: at least two choices and an answer matching one choice are required")
29
+ examples.append((state, item, names.index(answer)))
30
+ if not examples:
31
+ raise ValueError("Training data is empty")
32
+ return examples
33
+
34
+
35
+ def finetune(data, output_dir, *, checkpoint=None, version=None, model_repo=None, cache_dir=None,
36
+ revision="main", offline=False, base_model="Qwen/Qwen3-1.7B-Base", device="auto",
37
+ epochs=1, learning_rate=2e-4, rank=16, alpha=16, dropout=0.05,
38
+ max_length=2048, grad_accum=16, seed=7, max_steps=None):
39
+ """Start fresh from a base model, or continue an adapter with checkpoint/version.
40
+
41
+ Data is JSONL or an iterable of {state, question, choices, answer} records.
42
+ Continuation starts a new optimizer; this is not exact optimizer-state resume.
43
+ """
44
+ if epochs < 1 or grad_accum < 1 or rank < 1 or alpha < 1 or learning_rate <= 0 or not 0 <= dropout < 1 or max_length < 2 or (max_steps is not None and max_steps < 1):
45
+ raise ValueError("Invalid training hyperparameters")
46
+ examples = read_examples(data)
47
+ output = Path(output_dir)
48
+ if output.exists() and any(output.iterdir()):
49
+ raise ValueError("output_dir must be empty; existing checkpoints are never overwritten")
50
+ torch.manual_seed(seed)
51
+ rng = random.Random(seed)
52
+ device = select_device(device)
53
+ initial = None
54
+ if checkpoint is not None or version is not None:
55
+ initial = resolve_checkpoint(version or "general", checkpoint=checkpoint, model_repo=model_repo,
56
+ cache_dir=cache_dir, revision=revision, offline=offline)
57
+ base_model = checkpoint_model(initial)
58
+ tokenizer = AutoTokenizer.from_pretrained(initial / "tokenizer" if initial else base_model, cache_dir=cache_dir, local_files_only=offline, trust_remote_code=False)
59
+ if tokenizer.pad_token_id is None:
60
+ if tokenizer.eos_token_id is None:
61
+ raise ValueError("Tokenizer needs an EOS or pad token")
62
+ tokenizer.pad_token = tokenizer.eos_token
63
+ tokenizer.padding_side = "right"
64
+ encoder = AutoModel.from_pretrained(base_model, dtype=select_dtype(device), attn_implementation="sdpa", cache_dir=cache_dir, local_files_only=offline, trust_remote_code=False)
65
+ if initial:
66
+ encoder = PeftModel.from_pretrained(encoder, initial / "adapter", is_trainable=True, local_files_only=True)
67
+ else:
68
+ config = LoraConfig(task_type=TaskType.FEATURE_EXTRACTION, r=rank, lora_alpha=alpha,
69
+ lora_dropout=dropout, bias="none", target_modules=["q_proj", "v_proj"])
70
+ encoder = get_peft_model(encoder, config)
71
+ encoder.config.use_cache = False
72
+ encoder.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
73
+ model = Scorer(encoder).to(device)
74
+ if initial:
75
+ model.head.load_state_dict(load_head(initial))
76
+ model.train()
77
+ parameters = [p for p in model.parameters() if p.requires_grad]
78
+ optimizer = torch.optim.AdamW(parameters, lr=learning_rate)
79
+ optimizer.zero_grad(set_to_none=True)
80
+ step, losses = 0, []
81
+ for epoch in range(epochs):
82
+ rng.shuffle(examples)
83
+ for offset in range(0, len(examples), grad_accum):
84
+ window = examples[offset:offset+grad_accum]
85
+ window_loss = 0.0
86
+ for state, item, target in window:
87
+ # Evaluate a whole choice menu together, preserving relative scores.
88
+ rows = []
89
+ for choice in item["choices"]:
90
+ text = pack_example(state, item["question"], choice["choice"], item["guidance"], choice["criteria"], item["choices"])
91
+ ids = tokenizer.encode(text, add_special_tokens=True)
92
+ if len(ids) > max_length:
93
+ ids = ids[:1] + ids[-(max_length-1):]
94
+ rows.append({"input_ids": ids, "attention_mask": [1]*len(ids)})
95
+ batch = tokenizer.pad(rows, padding=True, return_tensors="pt").to(device)
96
+ logits = model(batch["input_ids"], batch["attention_mask"])
97
+ loss = torch.nn.functional.cross_entropy(logits.unsqueeze(0), torch.tensor([target], device=device))
98
+ (loss / len(window)).backward()
99
+ window_loss += float(loss.detach()) / len(window)
100
+ torch.nn.utils.clip_grad_norm_(parameters, 1.0)
101
+ optimizer.step()
102
+ optimizer.zero_grad(set_to_none=True)
103
+ step += 1
104
+ losses.append(window_loss)
105
+ if max_steps is not None and step >= max_steps:
106
+ break
107
+ if max_steps is not None and step >= max_steps:
108
+ break
109
+ output.mkdir(parents=True, exist_ok=True)
110
+ model.encoder.save_pretrained(output / "adapter", safe_serialization=True, save_embedding_layers=False)
111
+ tokenizer.save_pretrained(output / "tokenizer")
112
+ save_file({k:v.detach().cpu().contiguous() for k,v in model.head.state_dict().items()}, str(output / "head.safetensors"))
113
+ report = dict(base_model=base_model, steps=step, examples=len(examples), losses=losses, device=str(device),
114
+ seed=seed, epochs=epochs, max_length=max_length, learning_rate=learning_rate,
115
+ grad_accum=grad_accum, trainable_parameters=sum(p.numel() for p in parameters),
116
+ initial_checkpoint=str(initial) if initial else None, objective="menu_cross_entropy",
117
+ optimizer="AdamW", scheduler="constant", lora=model.encoder.peft_config["default"].to_dict())
118
+ (output / "training.json").write_text(json.dumps(report, indent=2, default=str)+"\n")
119
+ (output / "classifier.json").write_text(json.dumps({"max_length": max_length, "base_model": base_model})+"\n")
120
+ return report
@@ -0,0 +1,215 @@
1
+ Metadata-Version: 2.4
2
+ Name: theclassifier
3
+ Version: 0.1.0
4
+ Summary: Natural language classification on CPU and GPU, with domain adapters and LoRA fine-tuning
5
+ Author: TrueState
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://theclassifier.ai
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: torch<3,>=2.6
12
+ Requires-Dist: transformers<6,>=4.56
13
+ Requires-Dist: peft<1,>=0.17
14
+ Requires-Dist: accelerate<2,>=1
15
+ Requires-Dist: huggingface-hub<2,>=0.34
16
+ Requires-Dist: safetensors>=0.5
17
+ Provides-Extra: serve
18
+ Requires-Dist: fastapi<1,>=0.115; extra == "serve"
19
+ Requires-Dist: uvicorn<1,>=0.30; extra == "serve"
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=8; extra == "dev"
22
+ Requires-Dist: httpx; extra == "dev"
23
+ Requires-Dist: build; extra == "dev"
24
+ Requires-Dist: twine; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # The Classifier
28
+
29
+ A general-purpose natural language classifier with domain-specific LoRA adapters.
30
+ Run locally on CPU or NVIDIA GPU, serve the same `/v1/classify` request format as
31
+ the hosted service, or fine-tune an adapter on your own labelled examples.
32
+
33
+ ## Release status
34
+
35
+ This is the initial 0.1.0 package. The configured model repository is
36
+ `TrueState/theclassifier`. The checkpoints are staged privately; authenticate with
37
+ Hugging Face and obtain repository access before using named-version downloads.
38
+ A local checkpoint also works.
39
+ Model weights are not included in the Python package. This code is Apache-2.0;
40
+ checkpoint and dataset licences are separate.
41
+
42
+ ## Install
43
+
44
+ From this checkout, until the PyPI release is published:
45
+
46
+ ```sh
47
+ pip install './python[serve]'
48
+ ```
49
+
50
+ After release:
51
+
52
+ ```sh
53
+ pip install 'theclassifier[serve]'
54
+ ```
55
+
56
+ Python 3.10+ is required. Install a PyTorch build suitable for your platform first
57
+ if needed; CUDA support depends on that build and your NVIDIA driver. CPU uses
58
+ float32; CUDA uses bfloat16 when supported, otherwise float32. No FlashAttention
59
+ extension is required. `auto` selects CUDA when available and CPU otherwise.
60
+ Apple MPS is not currently supported.
61
+
62
+ ## Classify locally
63
+
64
+ ```python
65
+ from theclassifier import Classifier
66
+
67
+ classifier = Classifier() # general; downloads once, then uses the local cache
68
+ result = classifier.classify(
69
+ 'Please close my account.',
70
+ choices=['billing', 'cancellation', 'none'],
71
+ question='What is the customer asking for?',
72
+ )
73
+ print(result['results'][0]['selected'])
74
+ ```
75
+
76
+ Use `Classifier(checkpoint='./checkpoints/general', device='cpu')` to load an
77
+ existing local checkpoint. A checkpoint contains `adapter/`, `tokenizer/` and
78
+ `head.safetensors` (or the existing `head.pt` format). The pretrained backbone is
79
+ resolved from the adapter configuration. A local adapter can still require a
80
+ backbone download if the backbone is not already cached.
81
+
82
+ The full question format supports multiple decisions and optional criteria:
83
+
84
+ ```python
85
+ result = classifier.classify(
86
+ 'Please close my account.',
87
+ questions=[{
88
+ 'question': 'What is the customer asking for?',
89
+ 'choices': [
90
+ {'choice': 'cancellation', 'criteria': 'Requests to close an account.'},
91
+ {'choice': 'none', 'criteria': 'None of the other choices apply.'},
92
+ ],
93
+ }],
94
+ version='intent',
95
+ )
96
+ ```
97
+
98
+ Versions: `general`, `intent`, `sentiment`, `triage`, `cause`, `codify`,
99
+ `complaints`, `stars`. Selecting a new version checks the Hugging Face cache,
100
+ downloads missing files, then loads the adapter and its scoring head onto the
101
+ shared backbone. Selection and inference are serialized to keep the adapter and
102
+ head paired. A failed download raises an error; it never silently falls back to
103
+ another model.
104
+
105
+ ```python
106
+ classifier.load_adapter('custom', checkpoint='./checkpoints/my-adapter')
107
+ result = classifier.classify('example', choices=['yes', 'no'], version='custom')
108
+ ```
109
+
110
+ Use `model_repo=`, `revision=` and `cache_dir=` or the
111
+ `THECLASSIFIER_MODEL_REPO` environment variable to override download settings.
112
+ Pin `revision` to a commit for reproducibility. `offline=True` disables network
113
+ loading, including the base model. Pre-download adapters with:
114
+
115
+ ```sh
116
+ theclassifier download --version general
117
+ theclassifier download --version intent
118
+ ```
119
+
120
+ These commands download adapters and tokenizers; initialize the classifier once
121
+ online to cache the backbone as well. The repository layout is
122
+ `<version>/adapter/`, `<version>/tokenizer/`, `<version>/head.safetensors`.
123
+
124
+ Default maximum input length is 2,048 tokens per candidate; longer inputs retain
125
+ the first token and tail, matching the existing prompt format. Set `max_length`
126
+ explicitly for longer records. `batch_size` controls inference candidate chunks.
127
+ This initial portable runtime uses direct candidate scoring, not shared-prefix
128
+ KV caching. It has not been benchmarked against the optimized production server.
129
+
130
+ ## Serve on CPU or GPU
131
+
132
+ ```sh
133
+ theclassifier serve --checkpoint ./checkpoints/general --device cpu
134
+ # On a CUDA machine:
135
+ API_KEY=your-serving-key theclassifier serve --device cuda --host 0.0.0.0
136
+ ```
137
+
138
+ Default binding is `127.0.0.1:8090`. Binding outside localhost requires `API_KEY`.
139
+ Use one process per GPU; run behind a TLS proxy for remote clients. This standalone
140
+ server provides inference and authentication, not the hosted service's billing,
141
+ quotas or rate limiting. Set resource limits in your deployment.
142
+
143
+ ```sh
144
+ curl http://127.0.0.1:8090/v1/classify \
145
+ -H 'Content-Type: application/json' \
146
+ -d '{"state":"Close my account","questions":[{"question":"Intent?","choices":[{"choice":"cancel"},{"choice":"none"}]}]}'
147
+ ```
148
+
149
+ Include `Authorization: Bearer YOUR_KEY` when `API_KEY` is configured.
150
+ Responses contain `results` (with `question`, `selected`, `detailed_results`),
151
+ `version`, `input_tokens` and `latency_ms`.
152
+
153
+ ## Fine-tune with LoRA
154
+
155
+ Each JSONL line is one complete choice menu, with an exact matching answer label:
156
+
157
+ ```json
158
+ {"state":"Close my account","question":"Intent?","choices":[{"choice":"cancel","criteria":"Requests to close an account"},{"choice":"none"}],"answer":"cancel"}
159
+ ```
160
+
161
+ ```sh
162
+ # Continue the general checkpoint to create a specialist:
163
+ theclassifier finetune --version general --data train.jsonl \
164
+ --output checkpoints/my-adapter --device cuda
165
+
166
+ # Train an adapter and scoring head from the base model:
167
+ theclassifier finetune --base-model Qwen/Qwen3-1.7B-Base \
168
+ --data train.jsonl --output checkpoints/from-base --rank 16 --alpha 16
169
+ ```
170
+
171
+ Or in Python:
172
+
173
+ ```python
174
+ from theclassifier import finetune
175
+
176
+ report = finetune(
177
+ 'train.jsonl', 'checkpoints/my-adapter',
178
+ checkpoint='checkpoints/general', device='auto', epochs=1,
179
+ learning_rate=2e-4, grad_accum=16,
180
+ )
181
+ ```
182
+
183
+ Training freezes the backbone, learns LoRA updates to `q_proj` and `v_proj`, and
184
+ trains a float32 scalar head using cross-entropy across each menu. Whole menus
185
+ are processed together, gradients accumulate between menus, and gradient
186
+ checkpointing reduces activation memory. Large choice menus may still require
187
+ smaller input lengths or more memory. CPU training is supported but slow.
188
+
189
+ New adapters default to rank 16, alpha 16 and dropout 0.05. Continuing an existing
190
+ adapter preserves its LoRA configuration. A new AdamW optimizer is created with
191
+ a constant learning rate; this is fine-tuning, not exact training-state resume.
192
+ The optimizer configuration differs from the original research runs. Output
193
+ folders must be empty. Saved files include the adapter, head, tokenizer,
194
+ `classifier.json` and `training.json`. Keep evaluation data separate and evaluate
195
+ before using a new checkpoint; the training loss is not a quality benchmark.
196
+
197
+ ## Development and release
198
+
199
+ ```sh
200
+ cd python
201
+ pip install -e '.[serve,dev]'
202
+ pytest
203
+ python -m build
204
+ python -m twine check dist/*
205
+ # With PyPI credentials configured locally:
206
+ python -m twine upload dist/*
207
+ ```
208
+
209
+ The tests build a tiny random Qwen model locally: no production weights, private
210
+ data or external inference service is needed. All six tests passed on the NVIDIA
211
+ workstation, including CUDA inference. Real v1.1 checkpoints were also smoke-tested
212
+ on CUDA, and the general model was checked on CPU against the original scoring
213
+ implementation. These checks establish execution compatibility, not accuracy.
214
+ Publishing the package does not upload model weights. See `RELEASE.md` for the
215
+ checkpoint and publication steps.
@@ -0,0 +1,15 @@
1
+ theclassifier/__init__.py,sha256=nRwlemZCjFjR0x9pMzmQP4CmSPRLHht1E8W5kTan9uM,321
2
+ theclassifier/__main__.py,sha256=z3OQolCKD8rUd3pKYp_FISq2VctFhFl1mV-DVnaoNOM,29
3
+ theclassifier/checkpoints.py,sha256=_1YCCfFTdKYKcY_nDvCKjLZdBO4TdxDQnhii4WSwInk,2144
4
+ theclassifier/cli.py,sha256=k2Ok6joUDaw_EQAvMziJhv2g9GO97IY5GEBNBuEMn2w,3173
5
+ theclassifier/model.py,sha256=-P73wjtcSz6j7CW5MOOR2rj1J0JPdJxREluBzyWqlpE,7240
6
+ theclassifier/prompt.py,sha256=NDgd55hHrVLtA7l-tOZIdd9P43xSfb-1Z4KiDa05UMQ,1452
7
+ theclassifier/schema.py,sha256=pFXfyLJnE2KnQwG62fcVjCEp94JzmAt77xAFxHoa-zs,1824
8
+ theclassifier/server.py,sha256=I5WXANV9Mr7TTzj6eK_zmt_Jf2y2u6-0H7yLox6XRuw,1251
9
+ theclassifier/training.py,sha256=naoG47rohHnExTKh-2Xix1pVni-cUYX0Ssfvv3d6Jeg,6950
10
+ theclassifier-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
11
+ theclassifier-0.1.0.dist-info/METADATA,sha256=cJjIf8B1L35k7bQgWQt50yffIyEg6w7h1379Yo8aaYw,8270
12
+ theclassifier-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
13
+ theclassifier-0.1.0.dist-info/entry_points.txt,sha256=DgP8Qe9vZ3ThSk2GZKG8rn_QClpkZtxUZvVDk_3rwTc,57
14
+ theclassifier-0.1.0.dist-info/top_level.txt,sha256=3Gs26yaCztM7QB4sT0A_4INgG9njDqnsjl9sHDHSXCw,14
15
+ theclassifier-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ theclassifier = theclassifier.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ theclassifier