Text Classification
Transformers
Safetensors
English
qwen3_5_text
text-generation
Rodinia
finance
financial-ai
decision-intelligence
typed-decisions
financial-classification
calibrated-probabilities
probability-calibration
risk-assessment
sentiment-analysis
portfolio-analysis
0.8b
sociodynamics-ai
Instructions to use NeoSapian/Rodinia with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use NeoSapian/Rodinia with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="NeoSapian/Rodinia")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("NeoSapian/Rodinia") model = AutoModelForCausalLM.from_pretrained("NeoSapian/Rodinia", device_map="auto") - Notebooks
- Google Colab
- Kaggle
File size: 8,932 Bytes
c379be3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | """jev_common.py - shared code for a Jev-style (System One) typed decision model.
Idea: one forward pass over <state> + <question> + <options> and read the next-token
logits ONLY over option-letter tokens (" A", " B", ...). Softmax over those letters is the
probability distribution over the typed answer. No text is ever generated.
"""
import json
import os
import random
import torch
import torch.nn as nn
LETTERS = [chr(65 + i) for i in range(26)]
MAX_OPTS = 26
TEMPLATE_VERSION = "v1"
# ----------------------------------------------------------------------------- prompt
def build_prompt(state, question, options, qtype):
opts = "\n".join(f"{LETTERS[i]}. {o}" for i, o in enumerate(options))
return (
f"<state>\n{state}\n</state>\n"
f"<question type=\"{qtype}\">\n{question}\n</question>\n"
f"<options>\n{opts}\n</options>\nAnswer:"
)
def prepare(rec, rng=None, shuffle=True):
"""Shuffle option order for choice/noul (kills position bias). Score levels keep low->high order."""
opts = list(rec["options"])
lab = rec.get("label", 0)
if shuffle and rng is not None and rec["qtype"] != "score":
perm = list(range(len(opts)))
rng.shuffle(perm)
opts = [opts[p] for p in perm]
lab = perm.index(lab)
return opts, lab
def encode_prompt(tok, state, question, options, qtype, max_len, state_chars=1600):
st = state if len(state) <= state_chars else state[:state_chars] + " ..."
while True:
ids = tok(build_prompt(st, question, options, qtype), add_special_tokens=False)["input_ids"]
if len(ids) <= max_len or len(st) < 50:
return ids[-max_len:] # keep the tail (question + options + "Answer:")
st = st[: len(st) // 2]
def letter_token_ids(tok):
ids = []
for L in LETTERS:
t = tok.encode(" " + L, add_special_tokens=False)
assert len(t) == 1, f"' {L}' is not a single token for this tokenizer: {t}"
ids.append(t[0])
return ids
def collate(items, pad_id):
"""items: list of (ids, n_opts, label). Right padding (safe for linear-attention layers too)."""
L = max(len(i[0]) for i in items)
ids = torch.full((len(items), L), pad_id, dtype=torch.long)
mask = torch.zeros((len(items), L), dtype=torch.long)
for j, (x, _, _) in enumerate(items):
ids[j, : len(x)] = torch.tensor(x)
mask[j, : len(x)] = 1
n_opts = torch.tensor([i[1] for i in items], dtype=torch.long)
labels = torch.tensor([i[2] for i in items], dtype=torch.long)
return {"input_ids": ids, "attention_mask": mask, "n_opts": n_opts, "labels": labels}
def mask_logits(logits, n_opts):
cols = torch.arange(logits.size(1), device=logits.device)[None, :]
return logits.masked_fill(cols >= n_opts.to(logits.device)[:, None], -1e4)
# ----------------------------------------------------------------------------- model
def load_lm(path, dtype=torch.float32, **kw):
from transformers import AutoModelForCausalLM
try:
return AutoModelForCausalLM.from_pretrained(path, dtype=dtype, **kw)
except TypeError: # older transformers
return AutoModelForCausalLM.from_pretrained(path, torch_dtype=dtype, **kw)
class JevModel(nn.Module):
"""Backbone + restricted read-out. Never materialises the 248k-vocab logits (huge memory saver)."""
def __init__(self, lm, letter_ids):
super().__init__()
self.lm = lm
self.register_buffer("letter_ids", torch.tensor(letter_ids, dtype=torch.long), persistent=False)
def forward(self, input_ids, attention_mask):
out = self.lm.model(input_ids=input_ids, attention_mask=attention_mask)
h = out.last_hidden_state
last = attention_mask.sum(1) - 1
h = h[torch.arange(h.size(0), device=h.device), last]
W = self.lm.get_output_embeddings().weight[self.letter_ids] # (26, hidden)
return (h @ W.t()).float() # (B, 26) unmasked
@torch.no_grad()
def predict_logits(model, tok, recs, device, bs=32, max_len=640, shuffle_seed=1234):
"""Returns list of (logits[n_opts] cpu float, label) with deterministic option shuffling."""
model.eval()
pad = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id
order = sorted(range(len(recs)), key=lambda i: len(recs[i]["state"]))
out = [None] * len(recs)
for s in range(0, len(order), bs):
idx = order[s : s + bs]
items = []
for i in idx:
r = recs[i]
opts, lab = prepare(r, random.Random(shuffle_seed + i), True)
items.append((encode_prompt(tok, r["state"], r["question"], opts, r["qtype"], max_len), len(opts), lab))
b = collate(items, pad)
with torch.autocast("cuda", dtype=torch.float16, enabled=str(device).startswith("cuda")):
lg = model(b["input_ids"].to(device), b["attention_mask"].to(device))
for j, i in enumerate(idx):
n = items[j][1]
out[i] = (lg[j, :n].float().cpu(), items[j][2])
return out
# ----------------------------------------------------------------------------- inference API
class JevClassifier:
"""Jev-API-like interface: decide(state, {key: {type, instructions, criteria|levels}})"""
def __init__(self, path, device=None, dtype=torch.float16):
from transformers import AutoTokenizer
if not os.path.isdir(path):
from huggingface_hub import snapshot_download
path = snapshot_download(path)
self.cfg = json.load(open(os.path.join(path, "jev_config.json")))
self.tok = AutoTokenizer.from_pretrained(path)
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
lm = load_lm(path, dtype=dtype if self.device != "cpu" else torch.float32).to(self.device)
self.model = JevModel(lm, letter_token_ids(self.tok)).eval()
self.max_len = self.cfg.get("max_len", 640)
self.pad = self.tok.pad_token_id if self.tok.pad_token_id is not None else self.tok.eos_token_id
def _temp(self, qtype):
t = self.cfg.get("temperature", {})
return float(t.get(qtype, t.get("default", 1.0)))
@torch.no_grad()
def decide(self, state, questions, debias=True):
if not isinstance(state, str):
state = json.dumps(state, ensure_ascii=False)
specs, jobs = {}, []
for key, q in questions.items():
t = q["type"].lower()
instr = q.get("instructions", "")
if t == "noul":
base, text = ["No", "Yes"], instr
elif t == "choice":
crit = q["criteria"]
base = list(crit)
text = instr + "\n" + "\n".join(f"- {k}: {v}" for k, v in crit.items())
elif t == "score":
lv = q["levels"]
base = list(lv)
text = instr
if isinstance(lv, dict):
text += "\n" + "\n".join(f"- {k}: {v}" for k, v in lv.items())
else:
raise ValueError(f"unknown question type {t}")
specs[key] = (t, base)
orders = [base] + ([base[::-1]] if debias and t != "score" else [])
for o in orders:
jobs.append((key, o, encode_prompt(self.tok, state, text, o, t, self.max_len)))
acc = {k: torch.zeros(len(v[1])) for k, v in specs.items()}
cnt = {k: 0 for k in specs}
for s in range(0, len(jobs), 32):
chunk = jobs[s : s + 32]
b = collate([(ids, len(o), 0) for _, o, ids in chunk], self.pad)
with torch.autocast("cuda", dtype=torch.float16, enabled=self.device.startswith("cuda")):
lg = self.model(b["input_ids"].to(self.device), b["attention_mask"].to(self.device)).cpu()
for j, (key, o, _) in enumerate(chunk):
t, base = specs[key]
p = torch.softmax(lg[j, : len(o)] / self._temp(t), dim=-1)
for pos, name in enumerate(o):
acc[key][base.index(name)] += p[pos]
cnt[key] += 1
res = {}
for key, (t, base) in specs.items():
p = acc[key] / cnt[key]
probs = {n: round(float(p[i]), 4) for i, n in enumerate(base)}
best = int(p.argmax())
if t == "noul":
res[key] = {"type": "noul", "noul": probs["Yes"]}
elif t == "choice":
res[key] = {"type": "choice", "choice": base[best], "probabilities": probs,
"confidence": round(float(p.max()), 4)}
else:
k = len(base)
expected = float(sum(p[i] * (i / (k - 1)) for i in range(k))) if k > 1 else 0.0
res[key] = {"type": "score", "level": base[best], "score": round(expected, 4),
"probabilities": probs, "confidence": round(float(p.max()), 4)}
return res
|