quyet 1.0.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.
- quyet/__init__.py +6 -0
- quyet/__main__.py +5 -0
- quyet/answers.py +31 -0
- quyet/base.py +47 -0
- quyet/calibration.py +19 -0
- quyet/cli.py +39 -0
- quyet/encoder/__init__.py +0 -0
- quyet/encoder/inputs.py +114 -0
- quyet/encoder/modeling.py +123 -0
- quyet/encoder/runtime.py +75 -0
- quyet/errors.py +2 -0
- quyet/hub.py +49 -0
- quyet/llm/__init__.py +0 -0
- quyet/llm/prompt.py +83 -0
- quyet/llm/runtime.py +110 -0
- quyet/questions.py +80 -0
- quyet-1.0.0.dist-info/METADATA +120 -0
- quyet-1.0.0.dist-info/RECORD +22 -0
- quyet-1.0.0.dist-info/WHEEL +4 -0
- quyet-1.0.0.dist-info/entry_points.txt +2 -0
- quyet-1.0.0.dist-info/licenses/LICENSE +202 -0
- quyet-1.0.0.dist-info/licenses/NOTICE +29 -0
quyet/__init__.py
ADDED
quyet/__main__.py
ADDED
quyet/answers.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Probabilities -> Jev-format answers (the shape of TypeSafe's /v1/systemone)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def _r(x):
|
|
6
|
+
return round(float(x), 4)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def format_answer(d, probs, truncated=False):
|
|
10
|
+
"""probs: floats aligned with d.labels, summing to 1."""
|
|
11
|
+
if d.type == "choice":
|
|
12
|
+
i = max(range(len(probs)), key=probs.__getitem__)
|
|
13
|
+
a = {"type": "choice", "choice": d.labels[i], "confidence": _r(probs[i]),
|
|
14
|
+
"probabilities": {k: _r(p) for k, p in zip(d.labels, probs)}}
|
|
15
|
+
elif d.type == "score":
|
|
16
|
+
a = {"type": "score", "score": _r(sum(i * p for i, p in enumerate(probs))), "confidence": _r(max(probs)),
|
|
17
|
+
"legend": {k: (t if t is not None else k) for k, t in zip(d.labels, d.texts)},
|
|
18
|
+
"probabilities": {k: _r(p) for k, p in zip(d.labels, probs)}}
|
|
19
|
+
else:
|
|
20
|
+
a = {"type": "noul", "noul": _r(probs[0]), "confidence": _r(max(probs[0], 1 - probs[0]))}
|
|
21
|
+
if truncated:
|
|
22
|
+
a["truncated"] = True
|
|
23
|
+
return a
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build_response(model_name, decisions, probs, truncated, input_tokens, warnings):
|
|
27
|
+
"""decisions / probs / truncated: dicts keyed by question id, in request order."""
|
|
28
|
+
return {"model": model_name,
|
|
29
|
+
"answers": {qid: format_answer(d, probs[qid], truncated[qid]) for qid, d in decisions.items()},
|
|
30
|
+
"usage": {"input_tokens": int(input_tokens), "output_tokens": 0},
|
|
31
|
+
"warnings": list(warnings)}
|
quyet/base.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Shared model interface: predict / predict_many / raw_probabilities over Jev-format requests."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
|
|
6
|
+
from .answers import build_response
|
|
7
|
+
from .errors import QuestionError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class Result:
|
|
12
|
+
decisions: dict # qid -> Decision
|
|
13
|
+
probs: dict # qid -> list[float] aligned with Decision.labels
|
|
14
|
+
truncated: dict # qid -> bool
|
|
15
|
+
input_tokens: int
|
|
16
|
+
warnings: list = field(default_factory=list)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def check_state(state):
|
|
20
|
+
if not isinstance(state, (str, dict, list)):
|
|
21
|
+
raise QuestionError(f"state must be a string, object or list, got {type(state).__name__}")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def truncation_warning(state, total, kept):
|
|
25
|
+
return {"code": "state_truncated", "state_tokens": int(total), "kept_tokens": int(kept),
|
|
26
|
+
"kept": "tail" if isinstance(state, list) else "head"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class QuyetModel:
|
|
30
|
+
name = "quyet"
|
|
31
|
+
kind = ""
|
|
32
|
+
|
|
33
|
+
def _run(self, requests, strict):
|
|
34
|
+
raise NotImplementedError
|
|
35
|
+
|
|
36
|
+
def predict(self, state, questions, *, strict=False):
|
|
37
|
+
"""One request -> {"model", "answers", "usage", "warnings"}. strict=True raises instead of truncating."""
|
|
38
|
+
return self.predict_many([{"state": state, "questions": questions}], strict=strict)[0]
|
|
39
|
+
|
|
40
|
+
def predict_many(self, requests, *, strict=False):
|
|
41
|
+
"""Several requests batched together; any invalid request raises QuestionError for the whole call."""
|
|
42
|
+
return [build_response(self.name, r.decisions, r.probs, r.truncated, r.input_tokens, r.warnings)
|
|
43
|
+
for r in self._run(list(requests), strict)]
|
|
44
|
+
|
|
45
|
+
def raw_probabilities(self, requests, *, strict=False):
|
|
46
|
+
"""Unrounded probabilities per question id, aligned with the answer labels."""
|
|
47
|
+
return [r.probs for r in self._run(list(requests), strict)]
|
quyet/calibration.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Per-bucket temperature scaling. Encoder temperatures are keyed "<type>:<size>" (e.g. "choice:3-5"); LLM
|
|
2
|
+
temperatures are keyed by type. A missing key means 1.0 (uncalibrated)."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def size_bucket(k):
|
|
9
|
+
return "2" if k <= 2 else "3-5" if k <= 5 else "6-10" if k <= 10 else "11+"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def temperature(temps, qtype, k):
|
|
13
|
+
return float(temps.get(f"{qtype}:{size_bucket(k)}", temps.get(qtype, 1.0)))
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def softmax_t(logits, t):
|
|
17
|
+
z = np.asarray(logits, np.float64) / t
|
|
18
|
+
p = np.exp(z - z.max())
|
|
19
|
+
return (p / p.sum()).tolist()
|
quyet/cli.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""quyet predict MODEL: JSON lines {"state", "questions"} in, one JSON response (or {"error"}) per line out."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from .errors import QuestionError
|
|
9
|
+
from .hub import load
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main(argv=None):
|
|
13
|
+
ap = argparse.ArgumentParser(prog="quyet", description="Run a Quyet decision model.")
|
|
14
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
15
|
+
p = sub.add_parser("predict", help="answer JSON-lines requests {state, questions}")
|
|
16
|
+
p.add_argument("model", help="Hugging Face repo id (e.g. chinhnc/Quyet-1.0-Small) or local directory")
|
|
17
|
+
p.add_argument("--input", help="JSON-lines file (default: stdin)")
|
|
18
|
+
p.add_argument("--device", help="cpu, cuda, cuda:1, ... (default: cuda if available)")
|
|
19
|
+
p.add_argument("--strict", action="store_true", help="fail instead of truncating a long state")
|
|
20
|
+
a = ap.parse_args(argv)
|
|
21
|
+
model = load(a.model, device=a.device)
|
|
22
|
+
failed = False
|
|
23
|
+
src = open(a.input, encoding="utf8") if a.input else sys.stdin
|
|
24
|
+
with src:
|
|
25
|
+
for line in src:
|
|
26
|
+
if not line.strip():
|
|
27
|
+
continue
|
|
28
|
+
try:
|
|
29
|
+
req = json.loads(line)
|
|
30
|
+
out = model.predict(req["state"], req["questions"], strict=a.strict)
|
|
31
|
+
except (QuestionError, KeyError, TypeError, json.JSONDecodeError) as e:
|
|
32
|
+
failed = True
|
|
33
|
+
out = {"error": f"{type(e).__name__}: {e}"}
|
|
34
|
+
print(json.dumps(out, ensure_ascii=False), flush=True)
|
|
35
|
+
return 1 if failed else 0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
if __name__ == "__main__":
|
|
39
|
+
sys.exit(main())
|
|
File without changes
|
quyet/encoder/inputs.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Decision -> encoder input sequence: the exact layout the Quyet encoders were trained on.
|
|
2
|
+
|
|
3
|
+
CLS "<type> question: <instructions>" SEP {MASK " <label>[:]" [" <text>"]}* SEP state SEP
|
|
4
|
+
|
|
5
|
+
Each option is a MASK marker, its label, then its description as a separate text span (empty when there is no
|
|
6
|
+
description, in which case the label has no colon). Only the state is truncated: list (conversation) states keep
|
|
7
|
+
their end, all others keep their beginning. Option rendering follows Convai Innovations' Laya (Apache-2.0).
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from ..errors import QuestionError
|
|
16
|
+
|
|
17
|
+
QTYPES = {"choice": 0, "score": 1, "noul": 2}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def serialize_state(state):
|
|
21
|
+
return state if isinstance(state, str) else json.dumps(state, ensure_ascii=False)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def canonical(d):
|
|
25
|
+
"""(option (label, text) parts in the model's order, map from that order to the index in d.labels)."""
|
|
26
|
+
if d.type == "choice":
|
|
27
|
+
return list(zip(d.labels, d.texts)), list(range(len(d.labels)))
|
|
28
|
+
if d.type == "score":
|
|
29
|
+
return ([("level %d" % i, t if t is not None else "level %d" % i) for i, t in enumerate(d.texts)],
|
|
30
|
+
list(range(len(d.labels))))
|
|
31
|
+
t_true, t_false = d.texts
|
|
32
|
+
return ([("false", t_false if t_false is not None else "no, the statement does not hold"),
|
|
33
|
+
("true", t_true if t_true is not None else "yes, the statement holds")], [1, 0])
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Tokens:
|
|
37
|
+
"""Plain-text tokenization: literal special-token strings in user text stay text."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, tok):
|
|
40
|
+
self.tok = tok
|
|
41
|
+
self.special = frozenset(tok.all_special_ids)
|
|
42
|
+
|
|
43
|
+
def encode(self, text):
|
|
44
|
+
ids = self.tok(text, add_special_tokens=False, split_special_tokens=True)["input_ids"]
|
|
45
|
+
if any(i in self.special for i in ids):
|
|
46
|
+
raise QuestionError(f"text produced a special token: {text[:80]!r}")
|
|
47
|
+
return ids
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_item(tokens, d, state_ids, keep_end, max_len):
|
|
51
|
+
tok = tokens.tok
|
|
52
|
+
parts, to_label = canonical(d)
|
|
53
|
+
head = [tok.cls_token_id] + tokens.encode("%s question: %s" % (d.type, d.instructions))
|
|
54
|
+
q_end = len(head)
|
|
55
|
+
head.append(tok.sep_token_id)
|
|
56
|
+
markers, spans = [], []
|
|
57
|
+
for label, text in parts:
|
|
58
|
+
markers.append(len(head))
|
|
59
|
+
head += [tok.mask_token_id] + tokens.encode(" " + label + (":" if text is not None else ""))
|
|
60
|
+
s = len(head)
|
|
61
|
+
if text is not None:
|
|
62
|
+
head += tokens.encode(" " + text)
|
|
63
|
+
spans.append((s, len(head)))
|
|
64
|
+
head.append(tok.sep_token_id)
|
|
65
|
+
room = max_len - len(head) - 1
|
|
66
|
+
if room < 0:
|
|
67
|
+
raise QuestionError(f"question and options need {len(head) + 1} tokens, over the {max_len}-token window")
|
|
68
|
+
n = len(state_ids)
|
|
69
|
+
kept = list(state_ids[max(0, n - room):] if keep_end else state_ids[:room])
|
|
70
|
+
st_start = len(head)
|
|
71
|
+
return dict(ids=head + kept + [tok.sep_token_id], markers=markers, spans=spans, q_end=q_end, st_start=st_start,
|
|
72
|
+
st_end=st_start + len(kept), qtype=QTYPES[d.type], to_label=to_label, state_tokens=n,
|
|
73
|
+
kept_state_tokens=len(kept))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def collate(items, pad_id):
|
|
77
|
+
n, L = len(items), max(len(it["ids"]) for it in items)
|
|
78
|
+
k = max(len(it["markers"]) for it in items)
|
|
79
|
+
ids = np.full((n, L), pad_id, np.int64)
|
|
80
|
+
att = np.zeros((n, L), np.int64)
|
|
81
|
+
evid = np.zeros((n, L), bool)
|
|
82
|
+
mpos = np.zeros((n, k), np.int64)
|
|
83
|
+
mmask = np.zeros((n, k), bool)
|
|
84
|
+
s0 = np.zeros((n, k), np.int64)
|
|
85
|
+
s1 = np.zeros((n, k), np.int64)
|
|
86
|
+
for i, it in enumerate(items):
|
|
87
|
+
t, m = it["ids"], it["markers"]
|
|
88
|
+
ids[i, :len(t)] = t
|
|
89
|
+
att[i, :len(t)] = 1
|
|
90
|
+
evid[i, 0] = True # CLS
|
|
91
|
+
evid[i, 1:it["q_end"]] = True # question tokens
|
|
92
|
+
evid[i, it["st_start"]:it["st_end"]] = True # (possibly truncated) state tokens
|
|
93
|
+
mpos[i, :len(m)] = m
|
|
94
|
+
mmask[i, :len(m)] = True
|
|
95
|
+
s0[i, :len(m)] = [s for s, _ in it["spans"]]
|
|
96
|
+
s1[i, :len(m)] = [e for _, e in it["spans"]]
|
|
97
|
+
return dict(input_ids=ids, attention_mask=att, evidence_mask=evid, marker_pos=mpos, marker_mask=mmask,
|
|
98
|
+
span_start=s0, span_end=s1, qtype=np.asarray([it["qtype"] for it in items], np.int64))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def length_batches(lengths, max_tokens, max_rows):
|
|
102
|
+
"""Sort by length (stable); cut when padded tokens or rows would overflow. A long item may stand alone."""
|
|
103
|
+
order = np.argsort(np.asarray(lengths), kind="stable")
|
|
104
|
+
batches, cur, cur_max = [], [], 0
|
|
105
|
+
for i in order.tolist():
|
|
106
|
+
L = int(lengths[i])
|
|
107
|
+
if cur and (max(cur_max, L) * (len(cur) + 1) > max_tokens or len(cur) >= max_rows):
|
|
108
|
+
batches.append(np.asarray(cur, dtype=np.int64))
|
|
109
|
+
cur, cur_max = [], 0
|
|
110
|
+
cur.append(i)
|
|
111
|
+
cur_max = max(cur_max, L)
|
|
112
|
+
if cur:
|
|
113
|
+
batches.append(np.asarray(cur, dtype=np.int64))
|
|
114
|
+
return batches
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Encoder decision models: a ModernBERT-family encoder plus one option-scoring head (inference only).
|
|
2
|
+
|
|
3
|
+
Every head jointly reads question + options + state once, conditions on the question type and scores each option
|
|
4
|
+
with a shared scalar scorer; padded option slots are masked before the softmax.
|
|
5
|
+
option_query_v1 encoder states -> Linear(d, 384) + type embedding; option query = GELU(Linear(2h, h)[marker;
|
|
6
|
+
mean(option text)]); one cross-attention block into CLS + question + state; one self-attention block
|
|
7
|
+
over the option queries; LayerNorm -> Linear -> GELU -> Linear.
|
|
8
|
+
option_query_wide the same with h = 1024, 16 heads and two (cross-attention, self-attention) pairs.
|
|
9
|
+
refine_pool_v1 encoder states + type embedding -> two full-sequence pre-norm Transformer layers -> marker + mean
|
|
10
|
+
option text -> GELU(Linear(2d, d)) -> LayerNorm -> Linear -> GELU -> Linear. This head follows the
|
|
11
|
+
decision head of Convai Innovations' Laya (Apache-2.0).
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import torch
|
|
16
|
+
import torch.nn as nn
|
|
17
|
+
|
|
18
|
+
HEADS = ("option_query_v1", "refine_pool_v1", "option_query_wide")
|
|
19
|
+
MASKED_LOGIT = -1e4
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def span_pool(x, marker_vec, span_start, span_end):
|
|
23
|
+
"""Mean of x over each option's text span [start, end); empty spans fall back to the option's marker vector."""
|
|
24
|
+
pos = torch.arange(x.size(1), device=x.device)[None, None, :]
|
|
25
|
+
inside = (pos >= span_start[:, :, None]) & (pos < span_end[:, :, None])
|
|
26
|
+
n = inside.sum(-1, keepdim=True)
|
|
27
|
+
w = inside.to(x.dtype) / n.clamp(min=1).to(x.dtype)
|
|
28
|
+
return torch.where(n > 0, torch.bmm(w, x), marker_vec)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def gather_positions(x, pos):
|
|
32
|
+
return torch.gather(x, 1, pos.clamp(min=0)[:, :, None].expand(-1, -1, x.size(-1)))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class CrossBlock(nn.Module):
|
|
36
|
+
def __init__(self, h, heads, dropout):
|
|
37
|
+
super().__init__()
|
|
38
|
+
self.ln_q, self.ln_m, self.ln_f = nn.LayerNorm(h), nn.LayerNorm(h), nn.LayerNorm(h)
|
|
39
|
+
self.attn = nn.MultiheadAttention(h, heads, dropout=dropout, batch_first=True)
|
|
40
|
+
self.drop1, self.drop2 = nn.Dropout(dropout), nn.Dropout(dropout)
|
|
41
|
+
self.ffn = nn.Sequential(nn.Linear(h, 4 * h), nn.GELU(), nn.Dropout(dropout), nn.Linear(4 * h, h))
|
|
42
|
+
|
|
43
|
+
def forward(self, q, mem, mem_valid):
|
|
44
|
+
m = self.ln_m(mem)
|
|
45
|
+
a = self.attn(self.ln_q(q), m, m, key_padding_mask=~mem_valid, need_weights=False)[0]
|
|
46
|
+
q = q + self.drop1(a)
|
|
47
|
+
return q + self.drop2(self.ffn(self.ln_f(q)))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class OptionQueryHead(nn.Module):
|
|
51
|
+
def __init__(self, d, h=384, heads=6, dropout=0.0, blocks=1):
|
|
52
|
+
super().__init__()
|
|
53
|
+
self.proj = nn.Linear(d, h)
|
|
54
|
+
self.type_emb = nn.Embedding(3, h)
|
|
55
|
+
self.query = nn.Sequential(nn.Linear(2 * h, h), nn.GELU())
|
|
56
|
+
self.cross = CrossBlock(h, heads, dropout)
|
|
57
|
+
self.refine = nn.TransformerEncoderLayer(h, heads, 4 * h, dropout, activation="gelu", batch_first=True,
|
|
58
|
+
norm_first=True)
|
|
59
|
+
self.extra = nn.ModuleList(nn.ModuleList([
|
|
60
|
+
CrossBlock(h, heads, dropout),
|
|
61
|
+
nn.TransformerEncoderLayer(h, heads, 4 * h, dropout, activation="gelu", batch_first=True, norm_first=True)])
|
|
62
|
+
for _ in range(blocks - 1)) if blocks > 1 else None
|
|
63
|
+
self.scorer = nn.Sequential(nn.LayerNorm(h), nn.Linear(h, h), nn.GELU(), nn.Linear(h, 1))
|
|
64
|
+
|
|
65
|
+
def forward(self, hs, b):
|
|
66
|
+
x = self.proj(hs) + self.type_emb(b["qtype"])[:, None, :]
|
|
67
|
+
mk = gather_positions(x, b["marker_pos"])
|
|
68
|
+
q = self.query(torch.cat([mk, span_pool(x, mk, b["span_start"], b["span_end"])], -1))
|
|
69
|
+
pairs = [(self.cross, self.refine)] + ([tuple(p) for p in self.extra] if self.extra is not None else [])
|
|
70
|
+
for cross, refine in pairs:
|
|
71
|
+
q = cross(q, x, b["evidence_mask"])
|
|
72
|
+
q = refine(q, src_key_padding_mask=~b["marker_mask"])
|
|
73
|
+
return self.scorer(q).squeeze(-1)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class RefinePoolHead(nn.Module):
|
|
77
|
+
def __init__(self, d, layers=2, dropout=0.0):
|
|
78
|
+
super().__init__()
|
|
79
|
+
self.type_emb = nn.Embedding(3, d)
|
|
80
|
+
self.layers = nn.ModuleList(
|
|
81
|
+
nn.TransformerEncoderLayer(d, d // 64, 4 * d, dropout, activation="gelu", batch_first=True, norm_first=True)
|
|
82
|
+
for _ in range(layers))
|
|
83
|
+
self.fuse = nn.Sequential(nn.Linear(2 * d, d), nn.GELU())
|
|
84
|
+
self.scorer = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, d), nn.GELU(), nn.Linear(d, 1))
|
|
85
|
+
|
|
86
|
+
def forward(self, hs, b):
|
|
87
|
+
x = hs + self.type_emb(b["qtype"])[:, None, :]
|
|
88
|
+
pad = ~b["attention_mask"].bool()
|
|
89
|
+
for layer in self.layers:
|
|
90
|
+
x = layer(x, src_key_padding_mask=pad)
|
|
91
|
+
mk = gather_positions(x, b["marker_pos"])
|
|
92
|
+
return self.scorer(self.fuse(torch.cat([mk, span_pool(x, mk, b["span_start"], b["span_end"])], -1))).squeeze(-1)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def make_head(kind, d, dropout=0.0):
|
|
96
|
+
if kind == "option_query_v1":
|
|
97
|
+
return OptionQueryHead(d, 384, 6, dropout)
|
|
98
|
+
if kind == "option_query_wide":
|
|
99
|
+
return OptionQueryHead(d, 1024, 16, dropout, blocks=2)
|
|
100
|
+
if kind == "refine_pool_v1":
|
|
101
|
+
if d % 64:
|
|
102
|
+
raise ValueError(f"refine_pool_v1 needs a width divisible by 64, got {d}")
|
|
103
|
+
return RefinePoolHead(d, 2, dropout)
|
|
104
|
+
raise ValueError(f"unknown head {kind!r}; expected one of {list(HEADS)}")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class DecisionModel(nn.Module):
|
|
108
|
+
def __init__(self, encoder, head_kind, dropout=0.0):
|
|
109
|
+
super().__init__()
|
|
110
|
+
self.encoder = encoder
|
|
111
|
+
self.head_kind = head_kind
|
|
112
|
+
self.head = make_head(head_kind, encoder.config.hidden_size, dropout)
|
|
113
|
+
|
|
114
|
+
def forward(self, b):
|
|
115
|
+
hs = self.encoder(input_ids=b["input_ids"], attention_mask=b["attention_mask"]).last_hidden_state
|
|
116
|
+
return self.head(hs, b).float().masked_fill(~b["marker_mask"], MASKED_LOGIT)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def build_model(config):
|
|
120
|
+
"""Skeleton from quyet_config.json (random weights until a state dict is loaded)."""
|
|
121
|
+
from transformers import AutoConfig, AutoModel
|
|
122
|
+
enc = AutoModel.from_config(AutoConfig.for_model(**config["encoder_config"]), attn_implementation="sdpa")
|
|
123
|
+
return DecisionModel(enc, config["head"])
|
quyet/encoder/runtime.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""EncoderModel: quyet_config.json + model.safetensors + tokenizer files -> Jev-format answers.
|
|
2
|
+
CUDA runs under bfloat16 autocast (as evaluated); CPU runs in float32."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from ..base import QuyetModel, Result, check_state, truncation_warning
|
|
8
|
+
from ..calibration import softmax_t, temperature
|
|
9
|
+
from ..errors import QuestionError
|
|
10
|
+
from ..questions import parse_questions
|
|
11
|
+
from . import inputs as I
|
|
12
|
+
from .modeling import build_model
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class EncoderModel(QuyetModel):
|
|
16
|
+
kind = "encoder"
|
|
17
|
+
|
|
18
|
+
def __init__(self, path, config, device):
|
|
19
|
+
from safetensors.torch import load_file
|
|
20
|
+
from transformers import AutoTokenizer
|
|
21
|
+
self.path, self.config, self.device = Path(path), config, str(device)
|
|
22
|
+
self.name = config["name"]
|
|
23
|
+
self.max_len = int(config["max_len"])
|
|
24
|
+
self.temps = dict(config.get("temperatures") or {})
|
|
25
|
+
self.max_batch_tokens, self.max_batch_rows = 32768, 256
|
|
26
|
+
model = build_model(config)
|
|
27
|
+
model.load_state_dict(load_file(str(self.path / "model.safetensors")), strict=True)
|
|
28
|
+
self.model = model.to(self.device).eval()
|
|
29
|
+
self.tokens = I.Tokens(AutoTokenizer.from_pretrained(str(self.path)))
|
|
30
|
+
self.pad_id = self.tokens.tok.pad_token_id
|
|
31
|
+
|
|
32
|
+
def _logits(self, items):
|
|
33
|
+
import torch
|
|
34
|
+
out = [None] * len(items)
|
|
35
|
+
cuda = self.device.startswith("cuda")
|
|
36
|
+
for bi in I.length_batches([len(it["ids"]) for it in items], self.max_batch_tokens, self.max_batch_rows):
|
|
37
|
+
arrays = I.collate([items[i] for i in bi], self.pad_id)
|
|
38
|
+
b = {k: torch.from_numpy(v).to(self.device) for k, v in arrays.items()}
|
|
39
|
+
with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=cuda):
|
|
40
|
+
lg = self.model(b).float().cpu().numpy()
|
|
41
|
+
for j, i in enumerate(bi):
|
|
42
|
+
out[i] = lg[j, :len(items[i]["markers"])]
|
|
43
|
+
return out
|
|
44
|
+
|
|
45
|
+
def _run(self, requests, strict):
|
|
46
|
+
prepared = []
|
|
47
|
+
for r in requests:
|
|
48
|
+
state = r["state"]
|
|
49
|
+
check_state(state)
|
|
50
|
+
decisions = parse_questions(r["questions"])
|
|
51
|
+
state_ids = self.tokens.encode(I.serialize_state(state))
|
|
52
|
+
items = {qid: I.build_item(self.tokens, d, state_ids, isinstance(state, list), self.max_len)
|
|
53
|
+
for qid, d in decisions.items()}
|
|
54
|
+
truncated = {qid: it["kept_state_tokens"] < it["state_tokens"] for qid, it in items.items()}
|
|
55
|
+
warnings = []
|
|
56
|
+
if any(truncated.values()):
|
|
57
|
+
if strict:
|
|
58
|
+
raise QuestionError(f"state has {len(state_ids)} tokens and does not fit the {self.max_len}-token "
|
|
59
|
+
f"window (strict)")
|
|
60
|
+
warnings.append(truncation_warning(state, len(state_ids),
|
|
61
|
+
min(it["kept_state_tokens"] for it in items.values())))
|
|
62
|
+
prepared.append((decisions, items, truncated, warnings))
|
|
63
|
+
logits = iter(self._logits([it for _, items, _, _ in prepared for it in items.values()]))
|
|
64
|
+
results = []
|
|
65
|
+
for decisions, items, truncated, warnings in prepared:
|
|
66
|
+
probs = {}
|
|
67
|
+
for qid, d in decisions.items():
|
|
68
|
+
lg = next(logits)
|
|
69
|
+
canon = softmax_t(lg, temperature(self.temps, d.type, len(lg)))
|
|
70
|
+
p = [0.0] * len(canon)
|
|
71
|
+
for c, x in enumerate(canon):
|
|
72
|
+
p[items[qid]["to_label"][c]] = x
|
|
73
|
+
probs[qid] = p
|
|
74
|
+
results.append(Result(decisions, probs, truncated, sum(len(it["ids"]) for it in items.values()), warnings))
|
|
75
|
+
return results
|
quyet/errors.py
ADDED
quyet/hub.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Find a Quyet model (local directory or Hugging Face repo id) and load it."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
FORMAT = 1
|
|
8
|
+
KINDS = ("encoder", "llm")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def resolve(name_or_path, revision=None):
|
|
12
|
+
p = Path(str(name_or_path)).expanduser()
|
|
13
|
+
if p.is_dir():
|
|
14
|
+
return p
|
|
15
|
+
from huggingface_hub import snapshot_download
|
|
16
|
+
return Path(snapshot_download(str(name_or_path), revision=revision))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def read_config(path):
|
|
20
|
+
f = Path(path) / "quyet_config.json"
|
|
21
|
+
if not f.is_file():
|
|
22
|
+
raise ValueError(f"{path} is not a Quyet model: quyet_config.json is missing")
|
|
23
|
+
cfg = json.loads(f.read_text(encoding="utf8"))
|
|
24
|
+
if cfg.get("quyet_format") != FORMAT:
|
|
25
|
+
raise ValueError(f"quyet_format {cfg.get('quyet_format')!r} is not supported by this version of the package "
|
|
26
|
+
f"(reads format {FORMAT}); upgrade quyet")
|
|
27
|
+
if cfg.get("kind") not in KINDS:
|
|
28
|
+
raise ValueError(f"unknown model kind {cfg.get('kind')!r}; expected one of {list(KINDS)}")
|
|
29
|
+
return cfg
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def load(name_or_path, *, device=None, revision=None, dtype=None, device_map=None):
|
|
33
|
+
"""Load a Quyet model. device: "cuda" when available, else "cpu". dtype (default bfloat16) and device_map
|
|
34
|
+
(e.g. "auto" to spread Quyet-1.0-Large over several GPUs; needs `pip install quyet[multi-gpu]`) apply to LLMs only."""
|
|
35
|
+
path = resolve(name_or_path, revision)
|
|
36
|
+
cfg = read_config(path)
|
|
37
|
+
if cfg["kind"] == "encoder":
|
|
38
|
+
if device_map is not None:
|
|
39
|
+
raise ValueError("device_map applies to LLM models only; use device= for encoders")
|
|
40
|
+
if device is None:
|
|
41
|
+
import torch
|
|
42
|
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
43
|
+
from .encoder.runtime import EncoderModel
|
|
44
|
+
return EncoderModel(path, cfg, device)
|
|
45
|
+
if device is None and device_map is None:
|
|
46
|
+
import torch
|
|
47
|
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
48
|
+
from .llm.runtime import LLMModel
|
|
49
|
+
return LLMModel(path, cfg, device, dtype=dtype, device_map=device_map)
|
quyet/llm/__init__.py
ADDED
|
File without changes
|
quyet/llm/prompt.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Prompt for the LLM letter readout, exactly as the Quyet LLMs were trained and evaluated.
|
|
2
|
+
|
|
3
|
+
The prompt holds the state, the question and the options lettered A..J. Two prompt versions (quyet_config.json
|
|
4
|
+
"prompt_version"): 1 = the training prompt (Quyet-1.0-Medium); 2 = the "diet" prompt for Quyet-1.0-Large: no system
|
|
5
|
+
message, no closing line, compact JSON states, the trained per-type instructions kept. Version 2 cuts ~68 input tokens
|
|
6
|
+
per decision; on held-out data its accuracy is about 0.3 pt below version 1. Its temperatures were refit for it. The next-token distribution over those
|
|
7
|
+
letters (renormalised, temperature-scaled) is the decision distribution. Nothing is generated.
|
|
8
|
+
choice: options in the given order; score: levels 0..k-1 in order; noul: A = true description, B = false description.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
|
|
14
|
+
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
15
|
+
MAX_LETTERS = 10
|
|
16
|
+
SYSTEM = ("You are a decision model. Read the state and the question, then choose exactly one option. "
|
|
17
|
+
"Base the decision only on the state and the option descriptions. Reply with the option letter only.")
|
|
18
|
+
KIND = {"choice": "Choose the option that fits best.",
|
|
19
|
+
"score": "Choose the level that fits best (levels are ordered from lowest to highest).",
|
|
20
|
+
"noul": "Choose A if the statement is true for this state, B if it is not."}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def option_texts(d):
|
|
24
|
+
"""Option texts in letter order, with the fallbacks the models were trained with."""
|
|
25
|
+
if d.type == "noul":
|
|
26
|
+
return [d.texts[0] or "true", d.texts[1] or "false"]
|
|
27
|
+
if d.type == "score":
|
|
28
|
+
return [t if t is not None else str(i) for i, t in enumerate(d.texts)]
|
|
29
|
+
return [t if t is not None else k for k, t in zip(d.labels, d.texts)]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
PROMPT_VERSIONS = (1, 2)
|
|
33
|
+
CLOSING = "Answer with one letter."
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def check_version(version):
|
|
37
|
+
if version not in PROMPT_VERSIONS:
|
|
38
|
+
raise ValueError(f"unknown prompt_version {version!r}; this package knows {list(PROMPT_VERSIONS)}")
|
|
39
|
+
return version
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def serialize_state(state, compact=False):
|
|
43
|
+
if isinstance(state, str):
|
|
44
|
+
return state
|
|
45
|
+
if compact:
|
|
46
|
+
return json.dumps(state, ensure_ascii=False, separators=(",", ":"))
|
|
47
|
+
return json.dumps(state, ensure_ascii=False, indent=1)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def truncate_state(tok, state, max_tokens, compact=False):
|
|
51
|
+
"""(state text for the prompt, state tokens before truncation, truncated?). Lists keep the tail, others the head.
|
|
52
|
+
compact: JSON without indentation (prompt version 2)."""
|
|
53
|
+
s = serialize_state(state, compact)
|
|
54
|
+
ids = tok(s, add_special_tokens=False)["input_ids"]
|
|
55
|
+
if len(ids) <= max_tokens:
|
|
56
|
+
return s, len(ids), False
|
|
57
|
+
is_list = isinstance(state, list)
|
|
58
|
+
keep = ids[-max_tokens:] if is_list else ids[:max_tokens]
|
|
59
|
+
return ("… " if is_list else "") + tok.decode(keep) + ("" if is_list else " …"), len(ids), True
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def build_prompt(tok, state_text, d, version=1):
|
|
63
|
+
check_version(version)
|
|
64
|
+
opts = "\n".join(f"{LETTERS[i]}. {t}" for i, t in enumerate(option_texts(d)))
|
|
65
|
+
user = f"State:\n{state_text}\n\nQuestion: {d.instructions}\n{KIND[d.type]}\n\nOptions:\n{opts}"
|
|
66
|
+
if version == 1:
|
|
67
|
+
msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": f"{user}\n\n{CLOSING}"}]
|
|
68
|
+
else:
|
|
69
|
+
msgs = [{"role": "user", "content": user}]
|
|
70
|
+
try:
|
|
71
|
+
return tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False)
|
|
72
|
+
except TypeError:
|
|
73
|
+
return tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def letter_ids(tok, n=MAX_LETTERS):
|
|
77
|
+
ids = []
|
|
78
|
+
for letter in LETTERS[:n]:
|
|
79
|
+
enc = tok.encode(letter, add_special_tokens=False)
|
|
80
|
+
if len(enc) != 1:
|
|
81
|
+
raise ValueError(f"letter {letter} is not a single token: {enc}")
|
|
82
|
+
ids.append(enc[0])
|
|
83
|
+
return ids
|
quyet/llm/runtime.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""LLMModel: a merged causal LM + quyet_config.json -> Jev-format answers via one forward pass per question."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from ..base import QuyetModel, Result, check_state, truncation_warning
|
|
7
|
+
from ..calibration import softmax_t, temperature
|
|
8
|
+
from ..errors import QuestionError
|
|
9
|
+
from ..questions import parse_questions
|
|
10
|
+
from . import prompt as P
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class LLMModel(QuyetModel):
|
|
14
|
+
kind = "llm"
|
|
15
|
+
|
|
16
|
+
def __init__(self, path, config, device, dtype=None, device_map=None):
|
|
17
|
+
import torch
|
|
18
|
+
from transformers import AutoModelForCausalLM, AutoModelForImageTextToText, AutoTokenizer
|
|
19
|
+
self.path, self.config = Path(path), config
|
|
20
|
+
self.name = config["name"]
|
|
21
|
+
self.tok = AutoTokenizer.from_pretrained(str(self.path))
|
|
22
|
+
dtype = dtype or torch.bfloat16
|
|
23
|
+
kw = dict(dtype=dtype) if device_map is None else dict(dtype=dtype, device_map=device_map)
|
|
24
|
+
try:
|
|
25
|
+
model = AutoModelForCausalLM.from_pretrained(str(self.path), **kw)
|
|
26
|
+
except (ValueError, KeyError):
|
|
27
|
+
model = AutoModelForImageTextToText.from_pretrained(str(self.path), **kw)
|
|
28
|
+
if device_map is None:
|
|
29
|
+
model = model.to(device)
|
|
30
|
+
self.model = model.eval()
|
|
31
|
+
self.device = str(self.model.get_input_embeddings().weight.device)
|
|
32
|
+
self.letter_ids = P.letter_ids(self.tok)
|
|
33
|
+
self.temps = dict(config.get("temperatures") or {})
|
|
34
|
+
self.prompt_version = P.check_version(int(config.get("prompt_version", 1)))
|
|
35
|
+
lim = config["limits"]
|
|
36
|
+
self.max_state_tokens = int(lim["max_state_tokens"])
|
|
37
|
+
self.max_prompt_tokens = int(lim["max_prompt_tokens"])
|
|
38
|
+
self.min_state_tokens = int(lim["min_state_tokens"])
|
|
39
|
+
self.max_batch_tokens = 8000
|
|
40
|
+
self.pad_id = self.tok.pad_token_id if self.tok.pad_token_id is not None else self.tok.eos_token_id
|
|
41
|
+
|
|
42
|
+
def _prompt_ids(self, state, decisions, strict):
|
|
43
|
+
"""Token ids per question; the state budget shrinks until the longest prompt fits max_prompt_tokens."""
|
|
44
|
+
cap = self.max_state_tokens
|
|
45
|
+
for _ in range(4):
|
|
46
|
+
state_text, n_state, truncated = P.truncate_state(self.tok, state, cap, compact=self.prompt_version == 2)
|
|
47
|
+
ids = [self.tok(P.build_prompt(self.tok, state_text, d, self.prompt_version), add_special_tokens=False)["input_ids"]
|
|
48
|
+
for d in decisions.values()]
|
|
49
|
+
over = max(len(x) for x in ids) - self.max_prompt_tokens
|
|
50
|
+
if over <= 0:
|
|
51
|
+
break
|
|
52
|
+
cap = min(cap, n_state) - over - 16
|
|
53
|
+
if cap < self.min_state_tokens:
|
|
54
|
+
raise QuestionError(f"question and option text leave no room for the state: a prompt would exceed "
|
|
55
|
+
f"{self.max_prompt_tokens} tokens")
|
|
56
|
+
else:
|
|
57
|
+
raise QuestionError(f"prompt exceeds {self.max_prompt_tokens} tokens")
|
|
58
|
+
warnings = []
|
|
59
|
+
if truncated:
|
|
60
|
+
if strict:
|
|
61
|
+
raise QuestionError(f"state has {n_state} tokens, over the limit of {cap} (strict)")
|
|
62
|
+
warnings.append(truncation_warning(state, n_state, cap))
|
|
63
|
+
return ids, truncated, warnings
|
|
64
|
+
|
|
65
|
+
def _letter_logits(self, seqs):
|
|
66
|
+
"""seqs: [(ids, k)] -> letter logits over the first k letters; left-padded length-sorted batches."""
|
|
67
|
+
import torch
|
|
68
|
+
order = sorted(range(len(seqs)), key=lambda i: len(seqs[i][0]))
|
|
69
|
+
out = [None] * len(seqs)
|
|
70
|
+
lid = torch.tensor(self.letter_ids, device=self.device)
|
|
71
|
+
i = 0
|
|
72
|
+
while i < len(order):
|
|
73
|
+
j, longest = i, 0
|
|
74
|
+
while j < len(order) and max(longest, len(seqs[order[j]][0])) * (j - i + 1) <= self.max_batch_tokens:
|
|
75
|
+
longest = max(longest, len(seqs[order[j]][0]))
|
|
76
|
+
j += 1
|
|
77
|
+
j = max(j, i + 1)
|
|
78
|
+
batch = order[i:j]
|
|
79
|
+
L = max(len(seqs[b][0]) for b in batch)
|
|
80
|
+
ids = torch.full((len(batch), L), self.pad_id, dtype=torch.long)
|
|
81
|
+
att = torch.zeros((len(batch), L), dtype=torch.long)
|
|
82
|
+
for r, b in enumerate(batch):
|
|
83
|
+
s = seqs[b][0]
|
|
84
|
+
ids[r, L - len(s):] = torch.tensor(s)
|
|
85
|
+
att[r, L - len(s):] = 1
|
|
86
|
+
with torch.no_grad():
|
|
87
|
+
logits = self.model(input_ids=ids.to(self.device), attention_mask=att.to(self.device),
|
|
88
|
+
logits_to_keep=1).logits[:, -1, :]
|
|
89
|
+
sel = logits.float()[:, lid]
|
|
90
|
+
for r, b in enumerate(batch):
|
|
91
|
+
out[b] = sel[r, :seqs[b][1]].cpu().numpy()
|
|
92
|
+
i = j
|
|
93
|
+
return out
|
|
94
|
+
|
|
95
|
+
def _run(self, requests, strict):
|
|
96
|
+
prepared = []
|
|
97
|
+
for r in requests:
|
|
98
|
+
check_state(r["state"])
|
|
99
|
+
decisions = parse_questions(r["questions"])
|
|
100
|
+
ids, truncated, warnings = self._prompt_ids(r["state"], decisions, strict)
|
|
101
|
+
prepared.append((decisions, ids, truncated, warnings))
|
|
102
|
+
seqs = [(x, len(d.labels)) for decisions, ids, _, _ in prepared for d, x in zip(decisions.values(), ids)]
|
|
103
|
+
logits = iter(self._letter_logits(seqs))
|
|
104
|
+
results = []
|
|
105
|
+
for decisions, ids, truncated, warnings in prepared:
|
|
106
|
+
probs = {qid: softmax_t(next(logits), temperature(self.temps, d.type, len(d.labels)))
|
|
107
|
+
for qid, d in decisions.items()}
|
|
108
|
+
results.append(Result(decisions, probs, {qid: truncated for qid in decisions}, sum(len(x) for x in ids),
|
|
109
|
+
warnings))
|
|
110
|
+
return results
|
quyet/questions.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Jev /v1/systemone questions -> validated Decision objects shared by both runtimes.
|
|
2
|
+
|
|
3
|
+
A question is {"type": "choice" | "score" | "noul", "instructions": str, "criteria": ...}:
|
|
4
|
+
choice criteria {label: description} (or a list of labels) -> answer keys = the labels, in the given order
|
|
5
|
+
score criteria [level description, ...] lowest first -> answer keys "0".."K-1"
|
|
6
|
+
noul criteria {"true": description, "false": description} -> answer keys ("true", "false"); both optional
|
|
7
|
+
Descriptions keep None where none was given; each runtime applies the fallback text it was trained with.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
|
|
14
|
+
from .errors import QuestionError
|
|
15
|
+
|
|
16
|
+
TYPES = ("choice", "score", "noul")
|
|
17
|
+
MAX_OPTIONS = 10
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Decision:
|
|
22
|
+
type: str
|
|
23
|
+
instructions: str
|
|
24
|
+
labels: tuple
|
|
25
|
+
texts: tuple
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def describe(value):
|
|
29
|
+
"""Option description as text: strings as-is, other JSON values as compact JSON. Falsy values (None, "", 0,
|
|
30
|
+
False, {}, []) mean "no description", as in the evaluated encoder path (`text or None`)."""
|
|
31
|
+
if not value:
|
|
32
|
+
return None
|
|
33
|
+
if isinstance(value, str):
|
|
34
|
+
return value
|
|
35
|
+
return json.dumps(value, ensure_ascii=False, separators=(", ", ": "), default=str)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def parse_question(q) -> Decision:
|
|
39
|
+
if not isinstance(q, dict):
|
|
40
|
+
raise QuestionError("a question must be an object with type, instructions and criteria")
|
|
41
|
+
t, instr, crit = q.get("type"), q.get("instructions"), q.get("criteria")
|
|
42
|
+
if t not in TYPES:
|
|
43
|
+
raise QuestionError(f"unknown question type {t!r}; expected one of {list(TYPES)}")
|
|
44
|
+
if not isinstance(instr, str) or not instr.strip():
|
|
45
|
+
raise QuestionError("instructions must be a non-empty string")
|
|
46
|
+
if t == "choice":
|
|
47
|
+
if isinstance(crit, dict):
|
|
48
|
+
pairs = [(str(k), describe(v)) for k, v in crit.items()]
|
|
49
|
+
elif isinstance(crit, list):
|
|
50
|
+
pairs = [(str(k), None) for k in crit]
|
|
51
|
+
else:
|
|
52
|
+
raise QuestionError("choice criteria must be an object {label: description} or a list of labels")
|
|
53
|
+
if len({k for k, _ in pairs}) != len(pairs):
|
|
54
|
+
raise QuestionError("choice labels must be unique")
|
|
55
|
+
elif t == "score":
|
|
56
|
+
if not isinstance(crit, list):
|
|
57
|
+
raise QuestionError("score criteria must be a list of level descriptions, lowest first")
|
|
58
|
+
pairs = [(str(i), describe(c)) for i, c in enumerate(crit)]
|
|
59
|
+
else:
|
|
60
|
+
crit = {} if crit is None else crit
|
|
61
|
+
if not isinstance(crit, dict):
|
|
62
|
+
raise QuestionError("noul criteria must be an object with optional keys true and false")
|
|
63
|
+
pairs = [("true", describe(crit.get("true"))), ("false", describe(crit.get("false")))]
|
|
64
|
+
if len(pairs) < 2:
|
|
65
|
+
raise QuestionError(f"{t} needs at least 2 options")
|
|
66
|
+
if len(pairs) > MAX_OPTIONS:
|
|
67
|
+
raise QuestionError(f"{t} supports at most {MAX_OPTIONS} options, got {len(pairs)}")
|
|
68
|
+
return Decision(t, instr, tuple(k for k, _ in pairs), tuple(v for _, v in pairs))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def parse_questions(questions) -> dict:
|
|
72
|
+
if not isinstance(questions, dict) or not questions:
|
|
73
|
+
raise QuestionError("questions must be a non-empty object {question_id: question}")
|
|
74
|
+
out = {}
|
|
75
|
+
for qid, q in questions.items():
|
|
76
|
+
try:
|
|
77
|
+
out[str(qid)] = parse_question(q)
|
|
78
|
+
except QuestionError as e:
|
|
79
|
+
raise QuestionError(f"question {qid!r}: {e}") from None
|
|
80
|
+
return out
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: quyet
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Quyet decision models: pick one option for a state and a question, with calibrated probabilities.
|
|
5
|
+
Project-URL: Homepage, https://huggingface.co/chinhnc
|
|
6
|
+
Project-URL: Source, https://github.com/ncchinh/quyet
|
|
7
|
+
Project-URL: Issues, https://github.com/ncchinh/quyet/issues
|
|
8
|
+
Author: Chinh Nguyen
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
License-File: NOTICE
|
|
12
|
+
Keywords: calibration,classification,decision model,encoder,llm
|
|
13
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
14
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Requires-Dist: huggingface-hub>=0.34
|
|
22
|
+
Requires-Dist: numpy>=1.26
|
|
23
|
+
Requires-Dist: safetensors>=0.4
|
|
24
|
+
Requires-Dist: torch>=2.4
|
|
25
|
+
Requires-Dist: transformers>=5.17
|
|
26
|
+
Provides-Extra: multi-gpu
|
|
27
|
+
Requires-Dist: accelerate>=1.0; extra == 'multi-gpu'
|
|
28
|
+
Provides-Extra: test
|
|
29
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# Quyet
|
|
33
|
+
|
|
34
|
+
Quyet is a family of **decision models**. Give it a state (any text, JSON or conversation) and
|
|
35
|
+
one or more typed questions; it picks one option per question and returns calibrated probabilities. Nothing is
|
|
36
|
+
generated: every answer is a probability distribution over the options you supplied.
|
|
37
|
+
|
|
38
|
+
This package is the runtime for all Quyet 1.0 models. The weights are on Hugging Face.
|
|
39
|
+
|
|
40
|
+
The models are built for English and also tuned for Vietnamese; other languages work, with lower accuracy. Small-EN is
|
|
41
|
+
trained on English only.
|
|
42
|
+
|
|
43
|
+
| model | kind | parameters |
|
|
44
|
+
|---|---|---|
|
|
45
|
+
| [Quyet-1.0-Large](https://huggingface.co/chinhnc/Quyet-1.0-Large) | LLM (GPU) | 31.3B (30.7B text) |
|
|
46
|
+
| [Quyet-1.0-Medium](https://huggingface.co/chinhnc/Quyet-1.0-Medium) | LLM (GPU) | 4.66B (4.21B text) |
|
|
47
|
+
| [Quyet-1.0-Small](https://huggingface.co/chinhnc/Quyet-1.0-Small) | encoder (CPU or GPU) | 328M |
|
|
48
|
+
| [Quyet-1.0-Small-EN](https://huggingface.co/chinhnc/Quyet-1.0-Small-EN) | encoder (CPU or GPU) | 153M |
|
|
49
|
+
| [Quyet-1.0-Tiny](https://huggingface.co/chinhnc/Quyet-1.0-Tiny) | encoder (CPU or GPU) | 183M |
|
|
50
|
+
|
|
51
|
+
## Install
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
pip install quyet # CPU or single GPU
|
|
55
|
+
pip install "quyet[multi-gpu]" # spread Quyet-1.0-Large over several GPUs (device_map="auto")
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Python 3.10 or newer. The first `quyet.load` downloads the weights from Hugging Face.
|
|
59
|
+
|
|
60
|
+
## Use
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
import quyet
|
|
64
|
+
|
|
65
|
+
m = quyet.load("chinhnc/Quyet-1.0-Small")
|
|
66
|
+
r = m.predict(
|
|
67
|
+
{"message": "Please close my card, I lost it yesterday."},
|
|
68
|
+
{"intent": {"type": "choice", "instructions": "What does the customer want?",
|
|
69
|
+
"criteria": {"cancel": "close the card", "limit": "change the limit", "other": None}},
|
|
70
|
+
"urgent": {"type": "noul", "instructions": "The request is urgent."},
|
|
71
|
+
"mood": {"type": "score", "instructions": "How upset is the customer?", "criteria": ["calm", "annoyed", "angry"]}},
|
|
72
|
+
)
|
|
73
|
+
print(r["answers"])
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`quyet.load(name_or_path, device=None, revision=None, dtype=None, device_map=None)` accepts a Hugging Face repo id or a
|
|
77
|
+
local directory. `predict_many` answers a list of requests; `raw_probabilities` returns the uncalibrated distributions.
|
|
78
|
+
|
|
79
|
+
### Question types and answers
|
|
80
|
+
|
|
81
|
+
Answers follow the TypeSafe `/v1/systemone` shape:
|
|
82
|
+
|
|
83
|
+
- `choice`: pick one label from `criteria` (a dict of label to description, or a list of labels). Answer: `choice`,
|
|
84
|
+
`confidence`, `probabilities`.
|
|
85
|
+
- `score`: an ordered scale given as a list of levels. Answer: expected level `score`, `probabilities`, `legend`.
|
|
86
|
+
- `noul`: a statement that is true or false. Answer: `noul` = P(true).
|
|
87
|
+
|
|
88
|
+
Probabilities are temperature-calibrated per question type and option count.
|
|
89
|
+
|
|
90
|
+
### Command line
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
quyet predict chinhnc/Quyet-1.0-Small < requests.jsonl > answers.jsonl
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Each input line is `{"state": ..., "questions": {...}}`; each output line is the response or `{"error": ...}`.
|
|
97
|
+
Options: `--input FILE`, `--device cpu|cuda|cuda:1`, `--strict` (fail instead of truncating a long state).
|
|
98
|
+
|
|
99
|
+
## Limits
|
|
100
|
+
|
|
101
|
+
- At most 10 options per question; more are rejected, not truncated.
|
|
102
|
+
- Only the state is ever truncated: conversation lists keep their most recent turns, other states keep their
|
|
103
|
+
beginning. Encoders read 8,192 tokens; the LLMs keep up to 6,000 state tokens.
|
|
104
|
+
- Not evaluated for safety, bias or adversarial robustness; do not use as the only control for high-stakes decisions.
|
|
105
|
+
|
|
106
|
+
## Licence and credit
|
|
107
|
+
|
|
108
|
+
Apache-2.0 for the code and the weights. Keep the [NOTICE](NOTICE) file, which starts with "Quyet by Chinh Nguyen",
|
|
109
|
+
when you redistribute this package, a model, or anything derived from them.
|
|
110
|
+
|
|
111
|
+
```bibtex
|
|
112
|
+
@misc{quyet2026,
|
|
113
|
+
title = {Quyet 1.0: calibrated decision models},
|
|
114
|
+
author = {Chinh Nguyen},
|
|
115
|
+
year = {2026},
|
|
116
|
+
url = {https://github.com/ncchinh/quyet}
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Questions and issues: [GitHub issues](https://github.com/ncchinh/quyet/issues) or email@chinh.com.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
quyet/__init__.py,sha256=KaJj9EvBaULIUBSoRI0D45qHG8SRbb10PXGk5utBSCw,226
|
|
2
|
+
quyet/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
|
|
3
|
+
quyet/answers.py,sha256=TzOeYsYZkyeO7WUyoPBu4YqI3g_fwmsyqeDmof7WO50,1423
|
|
4
|
+
quyet/base.py,sha256=vlyMCRjBaYH0paiyu1p8Rk1JoUkq4IW-PV_-IU2_dM0,1835
|
|
5
|
+
quyet/calibration.py,sha256=URLY5wQF6sijNxi0zCBCxHnHARgAb97sIj5bKv5Xhoc,588
|
|
6
|
+
quyet/cli.py,sha256=x0OTiaZt0InPnDUwrrFzpXSPwl5rWm3rhtRoz9in7iM,1585
|
|
7
|
+
quyet/errors.py,sha256=M5ynywlNueLuW8BlYu8HSeZCGmWF9JUIG67a3JCqxXE,146
|
|
8
|
+
quyet/hub.py,sha256=WGpE0BtUDUzYBTcXl3WwjX_p8OX79tGW9PWSZMXC2Rk,2062
|
|
9
|
+
quyet/questions.py,sha256=3RBBjGuqr0ErtjyoWIh3Xi2FGNgqeeVdvEaEWIMOgd8,3466
|
|
10
|
+
quyet/encoder/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
quyet/encoder/inputs.py,sha256=8ASgIDJi1ERiGDuCYhji1A8cnDQDbA5RAWESqUmBB5E,4875
|
|
12
|
+
quyet/encoder/modeling.py,sha256=x27IwXSOVS_HC-vb6wNWO_RaF8pGTPg0uGesM1-sq4o,6104
|
|
13
|
+
quyet/encoder/runtime.py,sha256=hE3ktMAYDFZSC7PgvXpyTWvA7eb-W0vH7cwbHreP0TU,3677
|
|
14
|
+
quyet/llm/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
15
|
+
quyet/llm/prompt.py,sha256=tQ9hFqZVBWkl8MlPG6g0A1J3enFNumkSpz-Ooq9R8_w,3828
|
|
16
|
+
quyet/llm/runtime.py,sha256=1Yvnxl3fYNhUrDhnuAIvKDnmdNYvwuiNBqf_V-n7RQg,5506
|
|
17
|
+
quyet-1.0.0.dist-info/METADATA,sha256=7HqLPrWJ7eJ6YYsQf9IgiwCYbn98SlJ0gf3Uzwjg9Gw,5094
|
|
18
|
+
quyet-1.0.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
19
|
+
quyet-1.0.0.dist-info/entry_points.txt,sha256=JwEdea4XOwToIUT9zQ0qLjggNEROI1GH03mUvpfJPPo,41
|
|
20
|
+
quyet-1.0.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
21
|
+
quyet-1.0.0.dist-info/licenses/NOTICE,sha256=id3Fm2bYkU2WIvNlq1hUwvplDUJRoyP1cPe5LF7hylg,3293
|
|
22
|
+
quyet-1.0.0.dist-info/RECORD,,
|
|
@@ -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,29 @@
|
|
|
1
|
+
Quyet by Chinh Nguyen
|
|
2
|
+
Copyright 2026 Chinh Nguyen
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (see LICENSE). Redistributions of this work or of derivative works must keep this NOTICE, including the credit line above.
|
|
5
|
+
|
|
6
|
+
This work includes or derives from:
|
|
7
|
+
- Gemma 4 by Google (Apache-2.0): https://huggingface.co/google/gemma-4-31B-it (revision 842da3794eaa)
|
|
8
|
+
- Qwen3.5 by Alibaba Cloud (Apache-2.0): https://huggingface.co/Qwen/Qwen3.5-4B (revision 851bf6e806ef)
|
|
9
|
+
- SEA-LION-ModernBERT-300M by AI Singapore (MIT; Copyright 2023 AI Singapore): https://huggingface.co/aisingapore/SEA-LION-ModernBERT-300M (revision e3d70b810769)
|
|
10
|
+
|
|
11
|
+
MIT License text for aisingapore/SEA-LION-ModernBERT-300M:
|
|
12
|
+
|
|
13
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
14
|
+
|
|
15
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
18
|
+
- ModernBERT-base by Answer.AI and LightOn (Apache-2.0): https://huggingface.co/answerdotai/ModernBERT-base (revision 8949b909ec90)
|
|
19
|
+
- mmBERT-small by the mmBERT authors, JHU CLSP (MIT); first 16 of its 22 layers: https://huggingface.co/jhu-clsp/mmBERT-small (revision abc32620dd4f)
|
|
20
|
+
|
|
21
|
+
MIT License text for jhu-clsp/mmBERT-small:
|
|
22
|
+
|
|
23
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
24
|
+
|
|
25
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
26
|
+
|
|
27
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
28
|
+
|
|
29
|
+
The encoder models' option rendering and the refinement head of Quyet-1.0-Small follow Laya by Convai Innovations (https://huggingface.co/convaiinnovations/laya, Apache-2.0); this code was modified. No Laya weights are used.
|