HrushikeshGangane commited on
Commit
c800ccd
·
verified ·
1 Parent(s): d068f7b

Publish decision_maker inference bundle

Browse files
README.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - text-classification
4
+ - multiple-choice
5
+ - calibrated-classification
6
+ ---
7
+
8
+ # decision_maker
9
+
10
+ `decision_maker` is a BERT-Large decision encoder. It accepts a state, a
11
+ question, and a variable list of options, then returns a calibrated probability
12
+ distribution over those options in one encoder pass.
13
+
14
+ ## Quick start
15
+
16
+ ```bash
17
+ pip install -r requirements.txt
18
+ python run.py
19
+ ```
20
+
21
+ Edit `STATE`, `QUESTION`, and `OPTIONS` at the top of `run.py`.
22
+
23
+ ## Architecture
24
+
25
+ - `bert-large-uncased` bidirectional base encoder
26
+ - four-layer decision Transformer
27
+ - `[DECIDE]` query and `[OPTION]` key dot-product scoring
28
+ - global post-training temperature scaling
29
+
30
+ ## Evaluation
31
+
32
+ On the held-out development split used for this release, raw vs calibrated:
33
+
34
+ | Metric | Raw | Calibrated |
35
+ |---|---:|---:|
36
+ | Accuracy | 0.699 | 0.699 |
37
+ | NLL | 0.772 | 0.625 |
38
+ | Brier | 0.386 | 0.359 |
39
+ | ECE | 0.121 | 0.045 |
40
+
41
+ ## Limitations
42
+
43
+ This model has a 256-token structured input limit. Inputs that exceed that
44
+ limit are not supported by the reference runner. Calibration is measured on
45
+ the release validation distribution and may not transfer to every domain.
46
+ Do not use it as the sole basis for high-stakes decisions.
__pycache__/run.cpython-312.pyc ADDED
Binary file (3.65 kB). View file
 
data_utils.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """JSONL dataset, marker-aware encoding, and batch collation."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import torch
9
+ from torch.utils.data import Dataset
10
+
11
+ from decision_model import SPECIAL_TOKENS
12
+
13
+
14
+ class DecisionDataset(Dataset):
15
+ def __init__(self, path: str | Path, tokenizer=None, max_length: int | None = None):
16
+ with open(path, encoding="utf-8") as f:
17
+ self.rows = [json.loads(line) for line in f if line.strip()]
18
+ for row in self.rows:
19
+ if not row.get("options") or not 0 <= row.get("label", -1) < len(row["options"]):
20
+ raise ValueError(f"Bad decision example: {row.get('id', row)}")
21
+ self.total_rows = len(self.rows)
22
+ self.skipped_oversize = 0
23
+ if tokenizer is not None and max_length is not None:
24
+ kept = []
25
+ for row in self.rows:
26
+ if len(encode_row(tokenizer, row)["input_ids"]) <= max_length:
27
+ kept.append(row)
28
+ else:
29
+ self.skipped_oversize += 1
30
+ self.rows = kept
31
+ if not self.rows:
32
+ raise ValueError(f"Every example in {path} exceeds max_length={max_length}")
33
+
34
+ def __len__(self):
35
+ return len(self.rows)
36
+
37
+ def __getitem__(self, index: int) -> dict[str, Any]:
38
+ return self.rows[index]
39
+
40
+
41
+ def encode_row(tokenizer, row: dict[str, Any]) -> dict[str, Any]:
42
+ """Tokenize one row without padding, retaining structural marker positions."""
43
+ marker_ids = {token: tokenizer.convert_tokens_to_ids(token) for token in SPECIAL_TOKENS}
44
+ ids = [tokenizer.cls_token_id]
45
+ ids += [marker_ids["[STATE]"]] + tokenizer.encode(row.get("state", ""), add_special_tokens=False)
46
+ ids += [marker_ids["[QUESTION]"]] + tokenizer.encode(row["question"], add_special_tokens=False)
47
+ options = []
48
+ for option in row["options"]:
49
+ options.append(len(ids))
50
+ ids += [marker_ids["[OPTION]"]] + tokenizer.encode(str(option), add_special_tokens=False)
51
+ decide = len(ids)
52
+ ids += [marker_ids["[DECIDE]"], tokenizer.sep_token_id]
53
+ return {"input_ids": ids, "decide_position": decide, "option_positions": options}
54
+
55
+
56
+ def make_collate(tokenizer, max_length: int):
57
+
58
+ def collate(rows: list[dict[str, Any]]) -> dict[str, Any]:
59
+ # Tokenize fields separately so marker locations stay exact even under truncation.
60
+ sequences, decide_positions, option_positions = [], [], []
61
+ for row in rows:
62
+ encoded = encode_row(tokenizer, row)
63
+ ids, decide, opts = encoded["input_ids"], encoded["decide_position"], encoded["option_positions"]
64
+ if len(ids) > max_length:
65
+ raise ValueError(f"Oversize example reached collate: {row.get('id', '<unknown>')} exceeds max_length={max_length}. Construct DecisionDataset with tokenizer/max_length to filter it.")
66
+ sequences.append(ids)
67
+ decide_positions.append(decide)
68
+ option_positions.append(opts)
69
+ padded = tokenizer.pad({"input_ids": sequences}, padding=True, return_tensors="pt")
70
+ max_options = max(len(p) for p in option_positions)
71
+ pos = torch.full((len(rows), max_options), -1, dtype=torch.long)
72
+ mask = torch.zeros((len(rows), max_options), dtype=torch.bool)
73
+ for i, positions in enumerate(option_positions):
74
+ pos[i, : len(positions)] = torch.tensor(positions)
75
+ mask[i, : len(positions)] = True
76
+ return {
77
+ **padded,
78
+ "decide_positions": torch.tensor(decide_positions, dtype=torch.long),
79
+ "option_positions": pos,
80
+ "option_mask": mask,
81
+ "labels": torch.tensor([row["label"] for row in rows], dtype=torch.long),
82
+ "rows": rows,
83
+ }
84
+
85
+ return collate
decision_model.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bidirectional decision encoder with query/key option scoring."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import asdict, dataclass
5
+ from typing import Any
6
+
7
+ import torch
8
+ from torch import Tensor, nn
9
+ from transformers import AutoModel, AutoTokenizer
10
+
11
+ SPECIAL_TOKENS = ["[STATE]", "[QUESTION]", "[OPTION]", "[DECIDE]"]
12
+
13
+
14
+ @dataclass
15
+ class ModelConfig:
16
+ encoder_name: str = "bert-base-uncased"
17
+ decision_layers: int = 4
18
+ decision_heads: int = 16
19
+ decision_ffn_dim: int = 4096
20
+ dropout: float = 0.1
21
+ score_dim: int = 256
22
+
23
+ def to_dict(self) -> dict[str, Any]:
24
+ return asdict(self)
25
+
26
+
27
+ def build_tokenizer(encoder_name: str):
28
+ tokenizer = AutoTokenizer.from_pretrained(encoder_name, use_fast=True)
29
+ tokenizer.add_special_tokens({"additional_special_tokens": SPECIAL_TOKENS})
30
+ return tokenizer
31
+
32
+
33
+ class DecisionModel(nn.Module):
34
+ def __init__(self, config: ModelConfig):
35
+ super().__init__()
36
+ self.config = config
37
+ self.encoder = AutoModel.from_pretrained(config.encoder_name)
38
+ hidden = self.encoder.config.hidden_size
39
+ if hidden % config.decision_heads:
40
+ raise ValueError(f"hidden_size={hidden} is not divisible by decision_heads={config.decision_heads}")
41
+ layer = nn.TransformerEncoderLayer(
42
+ d_model=hidden,
43
+ nhead=config.decision_heads,
44
+ dim_feedforward=config.decision_ffn_dim,
45
+ dropout=config.dropout,
46
+ activation="gelu",
47
+ batch_first=True,
48
+ norm_first=True,
49
+ )
50
+ self.decision_transformer = nn.TransformerEncoder(
51
+ layer, num_layers=config.decision_layers, enable_nested_tensor=False
52
+ )
53
+ self.final_norm = nn.LayerNorm(hidden)
54
+ self.query = nn.Linear(hidden, config.score_dim, bias=False)
55
+ self.key = nn.Linear(hidden, config.score_dim, bias=False)
56
+ self.scale = config.score_dim ** -0.5
57
+
58
+ def resize_token_embeddings(self, vocab_size: int) -> None:
59
+ self.encoder.resize_token_embeddings(vocab_size)
60
+
61
+ def forward(
62
+ self,
63
+ input_ids: Tensor,
64
+ attention_mask: Tensor,
65
+ decide_positions: Tensor,
66
+ option_positions: Tensor,
67
+ option_mask: Tensor,
68
+ ) -> Tensor:
69
+ """Return one unnormalized logit per real option, padded slots = -inf."""
70
+ base = self.encoder(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
71
+ # Transformer expects True where tokens should be ignored.
72
+ contextual = self.decision_transformer(base, src_key_padding_mask=~attention_mask.bool())
73
+ contextual = self.final_norm(contextual)
74
+ batch = torch.arange(input_ids.size(0), device=input_ids.device)
75
+ decision_vec = contextual[batch, decide_positions] # [B, H]
76
+ safe_option_positions = option_positions.clamp_min(0)
77
+ option_vecs = contextual[batch[:, None], safe_option_positions] # [B, N, H]
78
+ q = self.query(decision_vec).unsqueeze(1)
79
+ k = self.key(option_vecs)
80
+ logits = (q * k).sum(-1) * self.scale
81
+ return logits.masked_fill(~option_mask, torch.finfo(logits.dtype).min)
82
+
manifest.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checkpoint_sha256": "9a73b349a8f9c6946fcaa07849e089d605f0dc721bfbf5a2a8cde97e16f80a7f",
3
+ "weights_sha256": "9a7a39f70c32810111eec32888558ebc454cfe8be9ab882e748ecd3bb151b851",
4
+ "temperature_sha256": "943213b58249b46f3ca554b6a8e8f917afb3da3e990023122528c78a69ddc631",
5
+ "files": [
6
+ "README.md",
7
+ "data_utils.py",
8
+ "decision_model.py",
9
+ "model.safetensors",
10
+ "model_config.json",
11
+ "requirements.txt",
12
+ "run.py",
13
+ "temperature.json",
14
+ "tokenizer"
15
+ ]
16
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a7a39f70c32810111eec32888558ebc454cfe8be9ab882e748ecd3bb151b851
3
+ size 1544283016
model_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format": "decision_maker.v1",
3
+ "model_config": {
4
+ "encoder_name": "bert-large-uncased",
5
+ "decision_layers": 4,
6
+ "decision_heads": 16,
7
+ "decision_ffn_dim": 4096,
8
+ "dropout": 0.1,
9
+ "score_dim": 256
10
+ },
11
+ "max_length": 256,
12
+ "temperature": 2.01273250579834,
13
+ "weights": "model.safetensors"
14
+ }
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch>=2.2
2
+ transformers>=4.40
3
+ safetensors>=0.4
run.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Edit STATE, QUESTION, and OPTIONS, then run: python run.py."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+
7
+ import torch
8
+ from safetensors.torch import load_file
9
+ from transformers import AutoTokenizer
10
+
11
+ from data_utils import make_collate
12
+ from decision_model import DecisionModel, ModelConfig
13
+
14
+ # ----- Edit only these values -------------------------------------------------
15
+ STATE = "I was charged twice for the same purchase."
16
+ QUESTION = "Which issue is this?"
17
+ OPTIONS = ["delivery problem", "duplicate charge", "wrong item"]
18
+ # -----------------------------------------------------------------------------
19
+
20
+
21
+ def load_decision_maker(model_dir: str | Path):
22
+ model_dir = Path(model_dir)
23
+ config = json.loads((model_dir / "model_config.json").read_text(encoding="utf-8"))
24
+ tokenizer = AutoTokenizer.from_pretrained(model_dir / "tokenizer")
25
+ model = DecisionModel(ModelConfig(**config["model_config"]))
26
+ model.resize_token_embeddings(len(tokenizer))
27
+ model.load_state_dict(load_file(model_dir / "model.safetensors"))
28
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
29
+ return model.to(device).eval(), tokenizer, config, device
30
+
31
+
32
+ def decide(model, tokenizer, config, device, state: str, question: str, options: list[str]):
33
+ row = {"id": "request", "state": state, "question": question, "options": options, "label": 0}
34
+ batch = make_collate(tokenizer, config["max_length"])([row])
35
+ tensors = {key: value.to(device) for key, value in batch.items() if isinstance(value, torch.Tensor) and key != "labels"}
36
+ temperature = float(config.get("temperature", 1.0))
37
+ with torch.no_grad():
38
+ probabilities = (model(**tensors)[0] / temperature).softmax(-1).cpu()
39
+ distribution = {option: round(probabilities[index].item(), 6) for index, option in enumerate(options)}
40
+ return {"choice": options[int(probabilities.argmax())], "temperature": temperature, "probabilities": distribution}
41
+
42
+
43
+ if __name__ == "__main__":
44
+ root = Path(__file__).parent
45
+ model, tokenizer, config, device = load_decision_maker(root)
46
+ print(json.dumps(decide(model, tokenizer, config, device, STATE, QUESTION, OPTIONS), indent=2))
temperature.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "method": "global_temperature_scaling",
3
+ "temperature": 2.01273250579834,
4
+ "checkpoint": "/runs/kev-v8-h100/best.pt",
5
+ "calibration_file": "/data/kev-v8/calibration.jsonl",
6
+ "calibration_sha256": "9a13d1a9ef55407d698168650c5bd5262cb3a18e5ed7c41f2a2411a48816954b",
7
+ "max_length": 256,
8
+ "calibration_raw": {
9
+ "accuracy": 0.6754717230796814,
10
+ "nll": 0.7315163450421027,
11
+ "brier": 0.4151699372057645,
12
+ "ece": 0.08237492353076448
13
+ },
14
+ "calibration_calibrated": {
15
+ "accuracy": 0.6754717230796814,
16
+ "nll": 0.6432405147912368,
17
+ "brier": 0.39327908461948613,
18
+ "ece": 0.03798134288385491
19
+ },
20
+ "development_file": "/data/kev-v8/development.jsonl",
21
+ "development_raw": {
22
+ "accuracy": 0.6987281441688538,
23
+ "nll": 0.7721685559647261,
24
+ "brier": 0.38594967761744753,
25
+ "ece": 0.12070055375777305
26
+ },
27
+ "development_calibrated": {
28
+ "accuracy": 0.6987281441688538,
29
+ "nll": 0.6249599214199048,
30
+ "brier": 0.3587786533495201,
31
+ "ece": 0.04545749252473659
32
+ }
33
+ }
tokenizer/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer/tokenizer_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "cls_token": "[CLS]",
4
+ "do_lower_case": true,
5
+ "extra_special_tokens": [
6
+ "[STATE]",
7
+ "[QUESTION]",
8
+ "[OPTION]",
9
+ "[DECIDE]"
10
+ ],
11
+ "is_local": false,
12
+ "local_files_only": false,
13
+ "mask_token": "[MASK]",
14
+ "model_max_length": 512,
15
+ "pad_token": "[PAD]",
16
+ "sep_token": "[SEP]",
17
+ "strip_accents": null,
18
+ "tokenize_chinese_chars": true,
19
+ "tokenizer_class": "BertTokenizer",
20
+ "unk_token": "[UNK]"
21
+ }