jev-sindhi 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.
- jev_sindhi/__init__.py +23 -0
- jev_sindhi/_checkpoint.py +469 -0
- jev_sindhi/api.py +123 -0
- jev_sindhi/runtime.py +221 -0
- jev_sindhi-0.1.0.dist-info/METADATA +79 -0
- jev_sindhi-0.1.0.dist-info/RECORD +10 -0
- jev_sindhi-0.1.0.dist-info/WHEEL +5 -0
- jev_sindhi-0.1.0.dist-info/licenses/LICENSE +176 -0
- jev_sindhi-0.1.0.dist-info/licenses/NOTICE +19 -0
- jev_sindhi-0.1.0.dist-info/top_level.txt +1 -0
jev_sindhi/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Sindhi decision models. Importing the package does not download a model.
|
|
2
|
+
|
|
3
|
+
Modified from the jev-urdu library by Danish Mahdi; see NOTICE.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from .api import (
|
|
7
|
+
DEFAULT_MODEL, JevSindhi, choice, yes_no,
|
|
8
|
+
PRESETS, SINDHI_PRESETS,
|
|
9
|
+
SINDHI_TOPICS, SINDHI_SENTIMENTS, SINDHI_PRIORITIES, SINDHI_ISSUES, SINDHI_RELATIONS,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
13
|
+
__all__ = [
|
|
14
|
+
"DEFAULT_MODEL", "JevSindhi", "choice", "yes_no", "load",
|
|
15
|
+
"PRESETS", "SINDHI_PRESETS",
|
|
16
|
+
"SINDHI_TOPICS", "SINDHI_SENTIMENTS", "SINDHI_PRIORITIES", "SINDHI_ISSUES", "SINDHI_RELATIONS",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
def load(model=DEFAULT_MODEL, *, device=None, token=None, revision=None,
|
|
20
|
+
local_files_only=False):
|
|
21
|
+
"""Load a model from Hugging Face or a local checkpoint directory."""
|
|
22
|
+
return JevSindhi(model, device=device, token=token, revision=revision,
|
|
23
|
+
local_files_only=local_files_only)
|
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
"""Checkpoint inference primitives adapted from Laya 0.3.22 (Apache-2.0).
|
|
2
|
+
|
|
3
|
+
See LICENSE and NOTICE. The inference-only subset and per-call token encoding
|
|
4
|
+
were adapted by the jev-urdu authors from Laya. Modified for jev-sindhi by
|
|
5
|
+
Danish Mahdi; the upstream question-cache machinery is not included.
|
|
6
|
+
"""
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
import os
|
|
10
|
+
import threading
|
|
11
|
+
from contextlib import nullcontext
|
|
12
|
+
from typing import Any, Dict, List, Optional, Union
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import torch
|
|
16
|
+
import torch.nn as nn
|
|
17
|
+
import torch.nn.functional as F
|
|
18
|
+
from torch.utils.checkpoint import checkpoint
|
|
19
|
+
|
|
20
|
+
QTYPES = {"choice": 0, "score": 1, "noul": 2}
|
|
21
|
+
QTYPE_NAMES = {value: key for key, value in QTYPES.items()}
|
|
22
|
+
_DEFAULT_NOUL_LABELS = {"false": "false", "true": "true"}
|
|
23
|
+
_TOKENIZE_LOCK = threading.RLock()
|
|
24
|
+
TEMP_MIN = 0.5
|
|
25
|
+
TEMP_MAX = 5.0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def encode_text(tok, text, **kwargs):
|
|
29
|
+
"""Tokenize `text` while holding the lock a shared fast tokenizer needs."""
|
|
30
|
+
with _TOKENIZE_LOCK:
|
|
31
|
+
return tok(text, **kwargs)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _encode_question_text(tok, text, **kwargs):
|
|
35
|
+
return encode_text(tok, text, **kwargs)["input_ids"]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def serialize_state(state: Union[str, dict, list]) -> str:
|
|
39
|
+
if isinstance(state, str):
|
|
40
|
+
return state
|
|
41
|
+
return json.dumps(state, ensure_ascii=False)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def render_criterion(value) -> str:
|
|
45
|
+
"""Render one criterion value as text.
|
|
46
|
+
|
|
47
|
+
Strings pass through; anything structured (dict, list, number) becomes compact JSON, so a
|
|
48
|
+
rubric reads as JSON rather than a Python repr. Without this a dict-valued criterion
|
|
49
|
+
crashed `noul` outright and leaked `{'desc': ...}` into `choice` and `score` prompts.
|
|
50
|
+
"""
|
|
51
|
+
if isinstance(value, str):
|
|
52
|
+
return value
|
|
53
|
+
return json.dumps(value, ensure_ascii=False, separators=(", ", ": "), default=str)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _resolve_noul_labels(labels=None):
|
|
57
|
+
if labels is None:
|
|
58
|
+
labels = _DEFAULT_NOUL_LABELS
|
|
59
|
+
if not isinstance(labels, dict) or set(labels) != {"false", "true"}:
|
|
60
|
+
raise ValueError("noul labels must map exactly 'false' and 'true' to distinct non-empty strings")
|
|
61
|
+
false_label, true_label = labels["false"], labels["true"]
|
|
62
|
+
if not isinstance(false_label, str) or not isinstance(true_label, str):
|
|
63
|
+
raise ValueError("noul labels must map exactly 'false' and 'true' to distinct non-empty strings")
|
|
64
|
+
false_label, true_label = false_label.strip(), true_label.strip()
|
|
65
|
+
if not false_label or not true_label or false_label == true_label:
|
|
66
|
+
raise ValueError("noul labels must map exactly 'false' and 'true' to distinct non-empty strings")
|
|
67
|
+
return false_label, true_label
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def render_options(q: Dict) -> List[str]:
|
|
71
|
+
"""Render option texts in label-index order. Noul semantic order is always [false, true]."""
|
|
72
|
+
t, crit = q["t"], q.get("crit")
|
|
73
|
+
if t != "noul" and "labels" in q:
|
|
74
|
+
raise ValueError("labels is only supported for noul questions")
|
|
75
|
+
if t == "choice":
|
|
76
|
+
# only None/"" mean "no description"; 0 and False are legitimate criterion values.
|
|
77
|
+
# `str(k)` unconditionally: a label with no description is rendered as itself, so an int
|
|
78
|
+
# label used to come back as an int from a function annotated `-> List[str]` and then
|
|
79
|
+
# reached `build_sequence`, which calls `.replace` on it and raised an AttributeError
|
|
80
|
+
# naming neither the question nor the label. With a description the same label already
|
|
81
|
+
# went through `"%s: %s" %` and was a str, which is why only the undescribed form broke.
|
|
82
|
+
# `structured._enum_field` stringifies labels the same way; the returned answer still
|
|
83
|
+
# carries the caller's original label, which is unchanged.
|
|
84
|
+
return [str(k) if v is None or v == "" else "%s: %s" % (k, render_criterion(v))
|
|
85
|
+
for k, v in crit.items()]
|
|
86
|
+
if t == "score":
|
|
87
|
+
return ["level %d: %s" % (i, render_criterion(c)) for i, c in enumerate(crit)]
|
|
88
|
+
crit = crit or {}
|
|
89
|
+
false_label, true_label = _resolve_noul_labels(q.get("labels"))
|
|
90
|
+
false_crit, true_crit = crit.get("false"), crit.get("true")
|
|
91
|
+
return [
|
|
92
|
+
false_label + ": "
|
|
93
|
+
+ (render_criterion(false_crit) if false_crit not in (None, "") else "no, the statement does not hold"),
|
|
94
|
+
true_label + ": "
|
|
95
|
+
+ (render_criterion(true_crit) if true_crit not in (None, "") else "yes, the statement holds"),
|
|
96
|
+
]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def build_sequence(
|
|
100
|
+
tok,
|
|
101
|
+
state: Union[str, dict, list],
|
|
102
|
+
q: Dict,
|
|
103
|
+
max_len: int = 512,
|
|
104
|
+
head_max_len: int = 192,
|
|
105
|
+
option_order: Optional[List[int]] = None,
|
|
106
|
+
truncate_left: bool = False,
|
|
107
|
+
state_ids: Optional[List[int]] = None,
|
|
108
|
+
return_stats: bool = False,
|
|
109
|
+
return_truncation_stats: bool = False,
|
|
110
|
+
):
|
|
111
|
+
"""Format: [CLS] <type> instructions [SEP] [MASK] opt0 [MASK] opt1 ... [SEP] state [SEP].
|
|
112
|
+
|
|
113
|
+
`state_ids` lets a caller tokenize the shared state once and reuse it across every question,
|
|
114
|
+
instead of re-serializing and re-tokenizing the same document per question.
|
|
115
|
+
|
|
116
|
+
`return_stats` adds a third return value describing what the head budget did to the options:
|
|
117
|
+
`options` (how many the question defines), `options_distinct` (how many still have a token
|
|
118
|
+
span of their own) and `tokens_per_option` (the cap applied to each, or None when none was).
|
|
119
|
+
|
|
120
|
+
The state is clamped to whatever room is left after the head, so a long state loses tokens
|
|
121
|
+
here silently. `return_truncation_stats=True` adds one more return value, after the option
|
|
122
|
+
stats when both are asked for, reporting that clamp:
|
|
123
|
+
|
|
124
|
+
{"state_tokens": int, "state_tokens_used": int, "state_tokens_dropped": int,
|
|
125
|
+
"truncated": bool}
|
|
126
|
+
|
|
127
|
+
Callers cannot reconstruct this from the outside. The budget is in tokens, not characters,
|
|
128
|
+
and the room left for the state depends on `max_len`, `head_max_len`, the instruction and
|
|
129
|
+
the rendered options - so it moves per checkpoint and per question. A caller guessing with a
|
|
130
|
+
fixed character threshold is wrong in both directions: it reports truncation that did not
|
|
131
|
+
happen, and stays silent while evidence is being dropped (issue #174).
|
|
132
|
+
"""
|
|
133
|
+
mask_tok = tok.mask_token
|
|
134
|
+
opts = render_options(q)
|
|
135
|
+
order = option_order if option_order is not None else list(range(len(opts)))
|
|
136
|
+
ins = str(q["ins"]).replace(mask_tok, " ")
|
|
137
|
+
head_ids = _encode_question_text(tok, "%s question: %s" % (q["t"], ins), add_special_tokens=False)
|
|
138
|
+
opt_ids = []
|
|
139
|
+
for i in order:
|
|
140
|
+
# Cap at the tokenizer, not after the fact: `[:48]` still makes the tokenizer process the
|
|
141
|
+
# whole (possibly long) description. truncation=True, max_length=48 keeps the first 48
|
|
142
|
+
# tokens, which is exactly what the previous slice produced.
|
|
143
|
+
opt_tokens = _encode_question_text(
|
|
144
|
+
tok,
|
|
145
|
+
" " + opts[i].replace(mask_tok, " "),
|
|
146
|
+
add_special_tokens=False,
|
|
147
|
+
truncation=True,
|
|
148
|
+
max_length=48,
|
|
149
|
+
)
|
|
150
|
+
opt_ids.append([tok.mask_token_id] + opt_tokens)
|
|
151
|
+
opt_budget = head_max_len - sum(len(o) for o in opt_ids)
|
|
152
|
+
per_option = None
|
|
153
|
+
if opt_budget < 16:
|
|
154
|
+
per = max(4, (head_max_len - 16) // max(1, len(opt_ids)))
|
|
155
|
+
per_option = per
|
|
156
|
+
opt_ids = [o[:per] for o in opt_ids]
|
|
157
|
+
opt_budget = head_max_len - sum(len(o) for o in opt_ids)
|
|
158
|
+
head_ids = head_ids[: max(8, opt_budget)]
|
|
159
|
+
ids = [tok.cls_token_id] + head_ids + [tok.sep_token_id]
|
|
160
|
+
markers = []
|
|
161
|
+
for o in opt_ids:
|
|
162
|
+
markers.append(len(ids))
|
|
163
|
+
ids.extend(o)
|
|
164
|
+
ids.append(tok.sep_token_id)
|
|
165
|
+
room = max(0, max_len - len(ids) - 1)
|
|
166
|
+
if state_ids is None:
|
|
167
|
+
state_ids = encode_text(tok, serialize_state(state).replace(mask_tok, " "),
|
|
168
|
+
add_special_tokens=False)["input_ids"]
|
|
169
|
+
# not state_ids[-room:]: with no room left, state_ids[-0:] is the whole state rather than none of it
|
|
170
|
+
st = state_ids[max(0, len(state_ids) - room):] if truncate_left else state_ids[:room]
|
|
171
|
+
ids = ids + st + [tok.sep_token_id]
|
|
172
|
+
ids, markers = ids[:max_len], [m for m in markers if m < max_len]
|
|
173
|
+
extra = ()
|
|
174
|
+
if return_truncation_stats:
|
|
175
|
+
# `room` leaves space for the closing [SEP], so every token in `st` survives the [:max_len] clamp
|
|
176
|
+
extra = ({
|
|
177
|
+
"state_tokens": len(state_ids),
|
|
178
|
+
"state_tokens_used": len(st),
|
|
179
|
+
"state_tokens_dropped": len(state_ids) - len(st),
|
|
180
|
+
"truncated": len(st) < len(state_ids),
|
|
181
|
+
},)
|
|
182
|
+
if not return_stats:
|
|
183
|
+
return (ids, markers) + extra
|
|
184
|
+
# Two options that share a prefix can come out of the cut as the same token span: the marker
|
|
185
|
+
# count still matches the option count, so the guard in `Agent._encode_state` passes and
|
|
186
|
+
# nothing downstream can tell that the question lost the ability to name them apart. Counted
|
|
187
|
+
# on the capped option ids, before assembly: re-slicing the finished sequence cannot close
|
|
188
|
+
# the last option's span -- it runs on into the serialized state, which differs per request,
|
|
189
|
+
# so the last option always looks distinguishable however it collided (#538).
|
|
190
|
+
return (ids, markers, {
|
|
191
|
+
"options": len(opt_ids),
|
|
192
|
+
"options_distinct": len({tuple(o) for o in opt_ids}),
|
|
193
|
+
"tokens_per_option": per_option,
|
|
194
|
+
}) + extra
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class _DynamicMultiheadAttention(nn.MultiheadAttention):
|
|
198
|
+
"""`nn.MultiheadAttention` that keeps the shapes it traces.
|
|
199
|
+
|
|
200
|
+
The stock module reshapes the packed projection with sizes captured while tracing, so under
|
|
201
|
+
the legacy ONNX exporter the traced sequence length becomes a constant and a model exported
|
|
202
|
+
from a short dummy input only runs at that length. The parameters and the maths are the same
|
|
203
|
+
here; the reshape uses only constant shape arguments (`chunk` / `unflatten` / `flatten`) and
|
|
204
|
+
`scaled_dot_product_attention`, the kernel the stock path already uses when weights are not
|
|
205
|
+
requested.
|
|
206
|
+
"""
|
|
207
|
+
|
|
208
|
+
def forward(self, query, key, value, key_padding_mask=None, need_weights=True,
|
|
209
|
+
attn_mask=None, average_attn_weights=True, is_causal=False):
|
|
210
|
+
if (need_weights or self.in_proj_weight is None or self.bias_k is not None
|
|
211
|
+
or self.bias_v is not None
|
|
212
|
+
or (attn_mask is not None and attn_mask.dtype != torch.bool)):
|
|
213
|
+
# Weight averaging, additive masks and the optional k/v bias are not on the traced
|
|
214
|
+
# path; the stock implementation keeps them correct.
|
|
215
|
+
return super().forward(query, key, value, key_padding_mask=key_padding_mask,
|
|
216
|
+
need_weights=need_weights, attn_mask=attn_mask,
|
|
217
|
+
average_attn_weights=average_attn_weights, is_causal=is_causal)
|
|
218
|
+
if self.batch_first:
|
|
219
|
+
query, key, value = query.transpose(0, 1), key.transpose(0, 1), value.transpose(0, 1)
|
|
220
|
+
# (T, B, E) from here, matching the stock module's internals; attention runs on (B, H, T, D).
|
|
221
|
+
if query is key is value:
|
|
222
|
+
q, k, v = (part.unflatten(-1, (self.num_heads, self.head_dim)).permute(1, 2, 0, 3)
|
|
223
|
+
for part in F.linear(query, self.in_proj_weight, self.in_proj_bias).chunk(3, dim=-1))
|
|
224
|
+
else:
|
|
225
|
+
embed_dim = query.shape[-1]
|
|
226
|
+
wq, wk, wv = self.in_proj_weight.split(embed_dim, dim=0)
|
|
227
|
+
bq, bk, bv = ((None, None, None) if self.in_proj_bias is None
|
|
228
|
+
else self.in_proj_bias.split(embed_dim, dim=0))
|
|
229
|
+
q, k, v = (
|
|
230
|
+
F.linear(t, w, b).unflatten(-1, (self.num_heads, self.head_dim)).permute(1, 2, 0, 3)
|
|
231
|
+
for t, w, b in ((query, wq, bq), (key, wk, bk), (value, wv, bv))
|
|
232
|
+
)
|
|
233
|
+
mask = None
|
|
234
|
+
if attn_mask is not None:
|
|
235
|
+
mask = ~attn_mask
|
|
236
|
+
if key_padding_mask is not None:
|
|
237
|
+
# `== 0` keeps this correct for a bool mask and for the 0 / -inf float mask the encoder
|
|
238
|
+
# layer hands over (`F._canonical_mask`), where `~` would not be defined.
|
|
239
|
+
keep = key_padding_mask[:, None, None, :] == 0
|
|
240
|
+
mask = keep if mask is None else mask & keep
|
|
241
|
+
attn = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, is_causal=is_causal and mask is None,
|
|
242
|
+
dropout_p=self.dropout if self.training else 0.0)
|
|
243
|
+
attn = attn.permute(2, 0, 1, 3).flatten(-2)
|
|
244
|
+
if self.batch_first:
|
|
245
|
+
attn = attn.transpose(0, 1)
|
|
246
|
+
return self.out_proj(attn), None
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def unpermute_probs(p: np.ndarray, option_order: Optional[List[int]]) -> np.ndarray:
|
|
250
|
+
"""Put a slot-ordered probability row back into the caller's option order.
|
|
251
|
+
|
|
252
|
+
`build_sequence` puts option `option_order[s]` in slot `s`, so a model row comes back
|
|
253
|
+
indexed by slot. Everything downstream indexes by option -- `zip(keys, p)` for a choice,
|
|
254
|
+
`arange(k) * p` for a score level, `p[1]` for noul-true -- so the row has to be inverted
|
|
255
|
+
first or the probabilities end up attached to the wrong options, which is silent.
|
|
256
|
+
|
|
257
|
+
A missing or mismatched order returns `p` untouched, so the canonical path is unaffected.
|
|
258
|
+
"""
|
|
259
|
+
if option_order is None or len(option_order) != len(p):
|
|
260
|
+
return p
|
|
261
|
+
canonical = np.empty_like(p)
|
|
262
|
+
canonical[np.asarray(option_order, dtype=int)] = p
|
|
263
|
+
return canonical
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
class DecisionModel(nn.Module):
|
|
267
|
+
"""Bidirectional transformer encoder backbone + typed decision head."""
|
|
268
|
+
|
|
269
|
+
def __init__(self, encoder: nn.Module, head_layers: int = 2, n_act: int = 2, dropout: float = 0.1,
|
|
270
|
+
no_init: bool = False):
|
|
271
|
+
super().__init__()
|
|
272
|
+
self.encoder = encoder
|
|
273
|
+
d = encoder.config.hidden_size
|
|
274
|
+
# `no_init` means the caller is about to load every parameter from a checkpoint, so the
|
|
275
|
+
# head's initial values are pure overhead -- and not just time. transformers'
|
|
276
|
+
# `no_init_weights()` patches the torch.nn.init functions, but something inside
|
|
277
|
+
# nn.TransformerEncoderLayer draws from the RNG outside them, so building it still
|
|
278
|
+
# advanced the global generator and made `load()` a visible side effect. On the meta
|
|
279
|
+
# device no initialisation kernel runs at all; the layers are materialised empty and the
|
|
280
|
+
# load fills them.
|
|
281
|
+
with torch.device("meta") if no_init else nullcontext():
|
|
282
|
+
nhead = max(1, d // 64)
|
|
283
|
+
layer = nn.TransformerEncoderLayer(d, nhead, 4 * d, dropout, batch_first=True, norm_first=True)
|
|
284
|
+
# The stock attention bakes the traced length into an exported graph; see
|
|
285
|
+
# _DynamicMultiheadAttention. Same parameters, same maths, traceable shapes.
|
|
286
|
+
layer.self_attn = _DynamicMultiheadAttention(d, nhead, dropout=dropout, batch_first=True)
|
|
287
|
+
self.head = nn.TransformerEncoder(layer, head_layers, enable_nested_tensor=False) if head_layers > 0 else None
|
|
288
|
+
self.type_emb = nn.Embedding(3, d)
|
|
289
|
+
self.scorer = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, d), nn.GELU(), nn.Linear(d, 1))
|
|
290
|
+
self.act_head = nn.Sequential(nn.Linear(d + 4, 256), nn.GELU(), nn.Linear(256, n_act))
|
|
291
|
+
self.register_buffer("temperature", torch.ones(3))
|
|
292
|
+
if no_init:
|
|
293
|
+
# Only the modules created above are on the meta device; the encoder is already real
|
|
294
|
+
# and may hold non-persistent buffers (RoPE frequencies) that to_empty would wipe.
|
|
295
|
+
for module in (self.head, self.type_emb, self.scorer, self.act_head):
|
|
296
|
+
if module is not None:
|
|
297
|
+
module.to_empty(device="cpu")
|
|
298
|
+
self.temperature = torch.empty_like(self.temperature, device="cpu")
|
|
299
|
+
self.head_checkpointing = False
|
|
300
|
+
|
|
301
|
+
def forward(self, input_ids, attention_mask, marker_pos, marker_mask, qtype, detach_encoder: bool = False):
|
|
302
|
+
h = self.encoder(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
|
|
303
|
+
if detach_encoder:
|
|
304
|
+
h = h.detach()
|
|
305
|
+
h = h + self.type_emb(qtype)[:, None, :]
|
|
306
|
+
if self.head is not None:
|
|
307
|
+
pad = ~attention_mask.bool()
|
|
308
|
+
for layer in self.head.layers:
|
|
309
|
+
if self.head_checkpointing and self.training and torch.is_grad_enabled():
|
|
310
|
+
# Non-reentrant checkpointing also trains the head when its input
|
|
311
|
+
# is frozen. Default RNG preservation keeps dropout consistent.
|
|
312
|
+
h = checkpoint(layer, h, src_key_padding_mask=pad, use_reentrant=False)
|
|
313
|
+
else:
|
|
314
|
+
h = layer(h, src_key_padding_mask=pad)
|
|
315
|
+
idx = marker_pos.clamp(min=0)[:, :, None].expand(-1, -1, h.size(-1))
|
|
316
|
+
m = torch.gather(h, 1, idx)
|
|
317
|
+
logits = self.scorer(m).squeeze(-1).float()
|
|
318
|
+
logits = logits.masked_fill(~marker_mask, -1e4)
|
|
319
|
+
|
|
320
|
+
p = torch.softmax(logits.detach(), -1)
|
|
321
|
+
k = marker_mask.sum(-1).clamp(min=2).float()
|
|
322
|
+
ent = -(p * torch.log(p.clamp_min(1e-9))).sum(-1) / torch.log(k)
|
|
323
|
+
if p.size(-1) >= 2:
|
|
324
|
+
top2 = p.topk(2, -1).values
|
|
325
|
+
else:
|
|
326
|
+
# A single-option question has exactly one marker, so p.topk(2, ...)
|
|
327
|
+
# has nothing to select for the second slot and raises. The answer
|
|
328
|
+
# is still well-defined: softmax over one logit is 1.0 regardless of
|
|
329
|
+
# its value, so pad the missing second entry with 0.0 - that gives
|
|
330
|
+
# the act head top1 - top2 == 1.0, the same "fully decided" signal
|
|
331
|
+
# it would see for any other unambiguous top-1-vs-rest gap.
|
|
332
|
+
top1 = p.topk(1, -1).values
|
|
333
|
+
top2 = torch.cat([top1, torch.zeros_like(top1)], dim=-1)
|
|
334
|
+
feats = torch.stack([top2[:, 0], top2[:, 0] - top2[:, 1], ent, k / 255.0], -1)
|
|
335
|
+
pooled = h[:, 0].float()
|
|
336
|
+
act_logits = self.act_head(torch.cat([pooled, feats], -1))
|
|
337
|
+
return logits, act_logits
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _apply_rope_config(ecfg) -> None:
|
|
341
|
+
"""Carry transformers>=5 per-layer RoPE settings over to the attributes 4.x reads.
|
|
342
|
+
|
|
343
|
+
A checkpoint re-saved by transformers 5 stores RoPE as
|
|
344
|
+
`rope_parameters = {"full_attention": {"rope_theta": ...}, "sliding_attention": {...}}`.
|
|
345
|
+
transformers 4.x does not know that key, so it keeps its own defaults (global 160000,
|
|
346
|
+
local 10000) and any checkpoint whose sliding-attention theta differs silently runs the
|
|
347
|
+
wrong RoPE base -- mmBERT is exactly that case, both of its thetas are 160000. Map the
|
|
348
|
+
values onto `global_rope_theta` / `local_rope_theta`, which 4.x does read. On
|
|
349
|
+
transformers 5 this is a no-op beyond re-setting the same numbers.
|
|
350
|
+
"""
|
|
351
|
+
rope = getattr(ecfg, "rope_parameters", None)
|
|
352
|
+
if not isinstance(rope, dict):
|
|
353
|
+
return
|
|
354
|
+
flat = rope.get("rope_theta")
|
|
355
|
+
for layer_type, attr in (("full_attention", "global_rope_theta"),
|
|
356
|
+
("sliding_attention", "local_rope_theta")):
|
|
357
|
+
params = rope.get(layer_type)
|
|
358
|
+
theta = params.get("rope_theta") if isinstance(params, dict) else flat
|
|
359
|
+
if theta is not None and hasattr(ecfg, attr):
|
|
360
|
+
setattr(ecfg, attr, float(theta))
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _no_init_weights():
|
|
364
|
+
"""`no_init_weights` lives in different modules across transformers versions."""
|
|
365
|
+
try:
|
|
366
|
+
from transformers.initialization import no_init_weights
|
|
367
|
+
except ImportError: # transformers 4.x
|
|
368
|
+
from transformers.modeling_utils import no_init_weights
|
|
369
|
+
return no_init_weights()
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def build_model(cfg: Dict, encoder_dir: Optional[str] = None, pretrained: bool = True,
|
|
373
|
+
revision: Optional[str] = None) -> DecisionModel:
|
|
374
|
+
"""Build the decision model described by `cfg`.
|
|
375
|
+
|
|
376
|
+
With `pretrained=False`, or when `encoder_dir` holds a saved encoder config, nothing is
|
|
377
|
+
downloaded and **no parameter is initialised**: the caller is expected to load a checkpoint
|
|
378
|
+
into the result with `load_state_dict(..., strict=True)` immediately. Skipping initialisation
|
|
379
|
+
keeps `load()` from spending time on, or consuming RNG for, weights it is about to overwrite.
|
|
380
|
+
"""
|
|
381
|
+
from transformers import AutoConfig, AutoModel
|
|
382
|
+
|
|
383
|
+
head_layers, n_act = cfg.get("head_layers", 2), len(cfg.get("act_costs", {})) + 1
|
|
384
|
+
if not pretrained or (encoder_dir and os.path.exists(encoder_dir)):
|
|
385
|
+
ecfg = AutoConfig.from_pretrained(encoder_dir or cfg["encoder"])
|
|
386
|
+
_apply_rope_config(ecfg)
|
|
387
|
+
with _no_init_weights():
|
|
388
|
+
enc = AutoModel.from_config(ecfg, attn_implementation="sdpa")
|
|
389
|
+
return DecisionModel(enc, head_layers, n_act, no_init=True)
|
|
390
|
+
# Training-time Hub load of the base encoder; allow pinning it like the checkpoints.
|
|
391
|
+
kw = {"attn_implementation": "sdpa"}
|
|
392
|
+
if revision:
|
|
393
|
+
kw["revision"] = revision
|
|
394
|
+
enc = AutoModel.from_pretrained(cfg["encoder"], **kw)
|
|
395
|
+
return DecisionModel(enc, head_layers, n_act)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def confidence_from_probs(p: np.ndarray, k: int) -> float:
|
|
399
|
+
"""Normalized Shannon entropy confidence: 1 - H(p) / log(k).
|
|
400
|
+
|
|
401
|
+
How concentrated the whole distribution is. Useful, but not calibrated: it is not what
|
|
402
|
+
temperature scaling fits and not what the reported ECE measures. See `answer_confidence`.
|
|
403
|
+
"""
|
|
404
|
+
if k < 2:
|
|
405
|
+
return 1.0
|
|
406
|
+
p = p[:k]
|
|
407
|
+
ent = -(p * np.log(np.clip(p, 1e-12, 1.0))).sum()
|
|
408
|
+
return float(np.clip(1.0 - ent / math.log(k), 0.0, 1.0))
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def temp_bucket(qtype: int, k: int) -> str:
|
|
412
|
+
size = "2" if k <= 2 else "3-5" if k <= 5 else "6-10" if k <= 10 else "11+"
|
|
413
|
+
return "%s:%s" % (QTYPE_NAMES[int(qtype)], size)
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def clamp_temperature(t, lo: float = TEMP_MIN, hi: float = TEMP_MAX) -> float:
|
|
417
|
+
"""A usable temperature: `t` confined to [lo, hi], falling back to 1.0 if it is not a number."""
|
|
418
|
+
try:
|
|
419
|
+
t = float(t)
|
|
420
|
+
except (TypeError, ValueError):
|
|
421
|
+
return 1.0
|
|
422
|
+
if t != t or t in (float("inf"), float("-inf")): # NaN / inf
|
|
423
|
+
return 1.0
|
|
424
|
+
return min(hi, max(lo, t))
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def collate_items(batch, pad_id: int):
|
|
428
|
+
items = [it for group in batch for it in group]
|
|
429
|
+
if not items:
|
|
430
|
+
return None
|
|
431
|
+
n, L = len(items), max(len(it["ids"]) for it in items)
|
|
432
|
+
kmax = max(len(it["markers"]) for it in items)
|
|
433
|
+
ids = torch.full((n, L), pad_id, dtype=torch.long)
|
|
434
|
+
att = torch.zeros((n, L), dtype=torch.long)
|
|
435
|
+
mpos = torch.zeros((n, kmax), dtype=torch.long)
|
|
436
|
+
mmask = torch.zeros((n, kmax), dtype=torch.bool)
|
|
437
|
+
has_target = any("target" in it for it in items)
|
|
438
|
+
target = torch.zeros((n, kmax), dtype=torch.float32) if has_target else None
|
|
439
|
+
|
|
440
|
+
for i, it in enumerate(items):
|
|
441
|
+
ids[i, : len(it["ids"])] = torch.tensor(it["ids"])
|
|
442
|
+
att[i, : len(it["ids"])] = 1
|
|
443
|
+
k = len(it["markers"])
|
|
444
|
+
mpos[i, :k] = torch.tensor(it["markers"])
|
|
445
|
+
mmask[i, :k] = True
|
|
446
|
+
if has_target and "target" in it:
|
|
447
|
+
if len(it["target"]) > k:
|
|
448
|
+
# Otherwise this lands as "The expanded size of the tensor (k) must match the
|
|
449
|
+
# existing size (kmax)" from inside the assignment, which says nothing about the
|
|
450
|
+
# actual mistake: a target with more entries than the item has options. The limit
|
|
451
|
+
# is this item's own marker count, not the batch-wide kmax: in a mixed-width
|
|
452
|
+
# batch a longer sibling row must not legitimise extra entries (#311).
|
|
453
|
+
raise ValueError(
|
|
454
|
+
"collate_items: item %d has %d target entries but only %d marker positions; "
|
|
455
|
+
"a target needs one entry per option" % (i, len(it["target"]), k))
|
|
456
|
+
target[i, : len(it["target"])] = torch.tensor(it["target"], dtype=torch.float32)
|
|
457
|
+
|
|
458
|
+
res = {
|
|
459
|
+
"input_ids": ids,
|
|
460
|
+
"attention_mask": att,
|
|
461
|
+
"marker_pos": mpos,
|
|
462
|
+
"marker_mask": mmask,
|
|
463
|
+
"qtype": torch.tensor([it["qtype"] for it in items]),
|
|
464
|
+
"label": torch.tensor([it.get("label", -1) for it in items]),
|
|
465
|
+
"meta": [{k: it[k] for k in it if k not in ("ids", "markers", "target")} for it in items],
|
|
466
|
+
}
|
|
467
|
+
if target is not None:
|
|
468
|
+
res["target"] = target
|
|
469
|
+
return res
|
jev_sindhi/api.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Sindhi and Urdu decision tasks exposed by the jev-sindhi API.
|
|
2
|
+
|
|
3
|
+
Modified from the jev-urdu library by Danish Mahdi; see NOTICE.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
|
|
8
|
+
DEFAULT_MODEL = "DanishMahdi/snd-jev"
|
|
9
|
+
|
|
10
|
+
# Urdu presets constants
|
|
11
|
+
ISSUES = ["ریفنڈ", "ڈیلیوری", "لاگ اِن", "ادائیگی", "تکنیکی مسئلہ", "اکاؤنٹ", "منسوخی", "پروڈکٹ"]
|
|
12
|
+
PRIORITIES = ["فوری", "جلد", "معمول"]
|
|
13
|
+
SENTIMENTS = ["مثبت", "منفی", "غیر جانبدار"]
|
|
14
|
+
RELATIONS = ["ثابت ہوتا ہے", "متضاد ہے", "معلومات ناکافی ہیں"]
|
|
15
|
+
CONSENT_STATES = ["واضح اجازت", "واضح انکار", "غیر واضح", "محدود اجازت"]
|
|
16
|
+
TEXT_KINDS = ["صرف حوالہ/اقتباس", "ہدایات بدلنے کی کوشش"]
|
|
17
|
+
|
|
18
|
+
# Sindhi presets constants
|
|
19
|
+
SINDHI_ISSUES = ["ريفنڊ", "ترسيل", "لاگ ان", "ادائيگي", "ٽيڪنيڪل مسئلو", "اڪائونٽ", "منسوخي", "پراڊڪٽ"]
|
|
20
|
+
SINDHI_PRIORITIES = ["فوري", "جلد", "معمول"]
|
|
21
|
+
SINDHI_SENTIMENTS = ["مثبت", "منفي", "غير جانبدار"]
|
|
22
|
+
SINDHI_RELATIONS = ["ثابت ٿئي ٿو", "متضاد آهي", "معلومات ناڪافي آهن"]
|
|
23
|
+
SINDHI_TOPICS = ["تعليم", "ٽيڪنالاجي", "زراعت", "صحت", "ٻيو"]
|
|
24
|
+
|
|
25
|
+
def choice(question, options):
|
|
26
|
+
"""A choice question; options may be labels or a mapping to descriptions."""
|
|
27
|
+
if isinstance(options, (str, bytes)):
|
|
28
|
+
raise TypeError("options must be a collection of labels or a mapping.")
|
|
29
|
+
criteria = dict(options) if isinstance(options, Mapping) else list(options)
|
|
30
|
+
return {"type": "choice", "instructions": question, "criteria": criteria}
|
|
31
|
+
|
|
32
|
+
def yes_no(question):
|
|
33
|
+
# A question answered with the probability that the answer is yes.
|
|
34
|
+
return {"type": "noul", "instructions": question}
|
|
35
|
+
|
|
36
|
+
# The Urdu question sets are retained for callers using lang="ur".
|
|
37
|
+
PRESETS = {
|
|
38
|
+
"triage": {"issue": choice("بنیادی مسئلہ کیا ہے؟", ISSUES),
|
|
39
|
+
"wants_human": yes_no("کیا انسانی نمائندے کی واضح درخواست ہے؟"),
|
|
40
|
+
"priority": choice("ترجیح کیا ہونی چاہیے؟", PRIORITIES)},
|
|
41
|
+
"sentiment": {"sentiment": choice("جذباتی رجحان کیا ہے؟", SENTIMENTS),
|
|
42
|
+
"dissatisfied": yes_no("کیا واضح عدم اطمینان ہے؟")},
|
|
43
|
+
"claim": {"relation": choice("دعویٰ اور سیاق کا تعلق؟", RELATIONS),
|
|
44
|
+
"supported": yes_no("کیا دعویٰ براہِ راست ثابت ہوتا ہے؟")},
|
|
45
|
+
"consent": {"status": choice("اجازت کی حالت کیا ہے؟", CONSENT_STATES),
|
|
46
|
+
"full_permission": yes_no("کیا مکمل کارروائی کی واضح اجازت ہے؟")},
|
|
47
|
+
"injection": {"kind": choice("متن کس قسم کا ہے؟", TEXT_KINDS),
|
|
48
|
+
"is_injection": yes_no("کیا یہ سابقہ ہدایات نظر انداز کرانے کی کوشش ہے؟")},
|
|
49
|
+
"tool_check": {"succeeded": yes_no("کیا اصل کارروائی کامیاب ہوئی؟"),
|
|
50
|
+
"claim_matches": yes_no("کیا اسسٹنٹ کا دعویٰ رسید سے مطابقت رکھتا ہے؟")},
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
# Native Sindhi presets using natural phrasing and orthography
|
|
54
|
+
SINDHI_PRESETS = {
|
|
55
|
+
"triage": {"issue": choice("بنيادي مسئلو ڇا آهي؟", SINDHI_ISSUES),
|
|
56
|
+
"wants_human": yes_no("ڇا انساني نمائندي جي واضح درخواست آهي؟"),
|
|
57
|
+
"priority": choice("ترجيح ڇا هئڻ گهرجي؟", SINDHI_PRIORITIES)},
|
|
58
|
+
"sentiment": {"sentiment": choice("جذباتي رجحان ڇا آهي؟", SINDHI_SENTIMENTS),
|
|
59
|
+
"dissatisfied": yes_no("ڇا واضح عدم اطمينان آهي؟")},
|
|
60
|
+
"claim": {"relation": choice("دعويٰ ۽ معلومات جو تعلق ڇا آهي؟", SINDHI_RELATIONS),
|
|
61
|
+
"supported": yes_no("ڇا دعويٰ سڌي ريت ثابت ٿئي ٿي؟")},
|
|
62
|
+
"topic": {"topic": choice("هي پيغام ڪهڙي موضوع سان لاڳاپيل آهي؟", SINDHI_TOPICS)},
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
def _simplify(answer):
|
|
66
|
+
if answer["type"] == "noul":
|
|
67
|
+
return {"answer": answer["noul"] >= 0.5, "probability": answer["noul"]}
|
|
68
|
+
if answer["type"] == "score":
|
|
69
|
+
return {"answer": answer["score"], "probability": answer["answer_confidence"],
|
|
70
|
+
"probabilities": answer["probabilities"]}
|
|
71
|
+
return {"answer": answer["choice"], "probability": answer["probabilities"][answer["choice"]],
|
|
72
|
+
"probabilities": answer["probabilities"]}
|
|
73
|
+
|
|
74
|
+
class JevSindhi:
|
|
75
|
+
def __init__(self, model=DEFAULT_MODEL, device=None, token=None, *, revision=None,
|
|
76
|
+
local_files_only=False):
|
|
77
|
+
from .runtime import Agent
|
|
78
|
+
|
|
79
|
+
self.agent = Agent(model, device=device, token=token, revision=revision,
|
|
80
|
+
local_files_only=local_files_only)
|
|
81
|
+
|
|
82
|
+
def predict(self, state, questions, **kwargs):
|
|
83
|
+
"""Return typed predictions, including whether input text was truncated."""
|
|
84
|
+
return self.agent.predict(state, questions, **kwargs)
|
|
85
|
+
|
|
86
|
+
def predict_batch(self, states, questions, **kwargs):
|
|
87
|
+
"""Return typed predictions for several states in input order."""
|
|
88
|
+
return self.agent.predict_batch(states, questions, **kwargs)
|
|
89
|
+
|
|
90
|
+
def ask(self, text, questions, **kwargs):
|
|
91
|
+
answers = self.agent.predict(text, questions, **kwargs)["answers"]
|
|
92
|
+
return {name: _simplify(a) for name, a in answers.items()}
|
|
93
|
+
|
|
94
|
+
def ask_many(self, texts, questions, batch_size=8, **kwargs):
|
|
95
|
+
results = self.agent.predict_batch(list(texts), questions, batch_size=batch_size, **kwargs)
|
|
96
|
+
return [{name: _simplify(a) for name, a in r["answers"].items()} for r in results]
|
|
97
|
+
|
|
98
|
+
def triage(self, text, *, lang="sd"):
|
|
99
|
+
presets = SINDHI_PRESETS if lang == "sd" else PRESETS
|
|
100
|
+
return self.ask(text, presets["triage"])
|
|
101
|
+
|
|
102
|
+
def sentiment(self, text, *, lang="sd"):
|
|
103
|
+
presets = SINDHI_PRESETS if lang == "sd" else PRESETS
|
|
104
|
+
return self.ask(text, presets["sentiment"])
|
|
105
|
+
|
|
106
|
+
def check_claim(self, context, claim, *, lang="sd"):
|
|
107
|
+
presets = SINDHI_PRESETS if lang == "sd" else PRESETS
|
|
108
|
+
return self.ask("Context: %s\nClaim: %s" % (context, claim), presets["claim"])
|
|
109
|
+
|
|
110
|
+
def topic(self, text, *, lang="sd"):
|
|
111
|
+
presets = SINDHI_PRESETS if lang == "sd" else PRESETS
|
|
112
|
+
if "topic" not in presets:
|
|
113
|
+
raise ValueError(f"No built-in topic preset for language {lang!r}.")
|
|
114
|
+
return self.ask(text, presets["topic"])
|
|
115
|
+
|
|
116
|
+
def consent(self, text):
|
|
117
|
+
return self.ask(text, PRESETS["consent"])
|
|
118
|
+
|
|
119
|
+
def detect_injection(self, text):
|
|
120
|
+
return self.ask(text, PRESETS["injection"])
|
|
121
|
+
|
|
122
|
+
def verify_tool_result(self, receipt):
|
|
123
|
+
return self.ask(receipt, PRESETS["tool_check"])
|
jev_sindhi/runtime.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Standalone inference for Jev decision checkpoints.
|
|
2
|
+
|
|
3
|
+
Modified from the jev-urdu library by Danish Mahdi; see NOTICE.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import threading
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from contextlib import nullcontext
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import torch
|
|
16
|
+
from huggingface_hub import snapshot_download
|
|
17
|
+
from safetensors.torch import load_file
|
|
18
|
+
from transformers import AutoTokenizer
|
|
19
|
+
|
|
20
|
+
from ._checkpoint import (
|
|
21
|
+
QTYPES, build_model, build_sequence, clamp_temperature, collate_items,
|
|
22
|
+
confidence_from_probs, encode_text, render_options, serialize_state,
|
|
23
|
+
temp_bucket, unpermute_probs,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _question(qid, definition):
|
|
28
|
+
if not isinstance(definition, Mapping):
|
|
29
|
+
raise ValueError(f"Question {qid!r} must be a mapping.")
|
|
30
|
+
kind = definition.get("type")
|
|
31
|
+
if not isinstance(kind, str) or kind not in QTYPES:
|
|
32
|
+
raise ValueError(f"Question {qid!r}: type must be choice, score, or noul.")
|
|
33
|
+
instructions = definition.get("instructions")
|
|
34
|
+
if not isinstance(instructions, str) or not instructions.strip():
|
|
35
|
+
raise ValueError(f"Question {qid!r} needs non-empty string instructions.")
|
|
36
|
+
criteria = definition.get("criteria")
|
|
37
|
+
if kind == "choice":
|
|
38
|
+
if isinstance(criteria, list):
|
|
39
|
+
if not all(isinstance(label, str) and label.strip() for label in criteria):
|
|
40
|
+
raise ValueError(f"Question {qid!r}: choice labels must be non-empty strings.")
|
|
41
|
+
if len(set(criteria)) != len(criteria):
|
|
42
|
+
raise ValueError(f"Question {qid!r}: choice labels must be unique.")
|
|
43
|
+
criteria = dict.fromkeys(criteria)
|
|
44
|
+
if not isinstance(criteria, Mapping) or not criteria:
|
|
45
|
+
raise ValueError(f"Question {qid!r}: choice needs at least one option.")
|
|
46
|
+
if not all(isinstance(label, str) and label.strip() for label in criteria):
|
|
47
|
+
raise ValueError(f"Question {qid!r}: choice labels must be non-empty strings.")
|
|
48
|
+
criteria = dict(criteria)
|
|
49
|
+
elif kind == "score":
|
|
50
|
+
if not isinstance(criteria, list) or len(criteria) < 2:
|
|
51
|
+
raise ValueError(f"Question {qid!r}: score needs at least two ordered levels.")
|
|
52
|
+
elif criteria is not None:
|
|
53
|
+
if not isinstance(criteria, Mapping):
|
|
54
|
+
raise ValueError(f"Question {qid!r}: noul criteria must map false and true.")
|
|
55
|
+
criteria = {str(key).lower(): value for key, value in criteria.items()}
|
|
56
|
+
if set(criteria) - {"false", "true"}:
|
|
57
|
+
raise ValueError(f"Question {qid!r}: noul criteria accept only false and true.")
|
|
58
|
+
internal = {"t": kind, "ins": instructions, "crit": criteria}
|
|
59
|
+
if "labels" in definition:
|
|
60
|
+
internal["labels"] = definition["labels"]
|
|
61
|
+
count = len(render_options(internal))
|
|
62
|
+
if "option_order" in definition:
|
|
63
|
+
order = definition["option_order"]
|
|
64
|
+
if not isinstance(order, list) or any(type(i) is not int for i in order):
|
|
65
|
+
raise ValueError(f"Question {qid!r}: option_order must contain integer indices.")
|
|
66
|
+
if sorted(order) != list(range(count)):
|
|
67
|
+
raise ValueError(f"Question {qid!r}: option_order must be a permutation of all options.")
|
|
68
|
+
internal["option_order"] = order
|
|
69
|
+
return internal
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Agent:
|
|
73
|
+
"""Typed decision inference with strict checkpoint loading and bounded batching."""
|
|
74
|
+
|
|
75
|
+
def __init__(self, model, *, device=None, token=None, revision=None,
|
|
76
|
+
local_files_only=False):
|
|
77
|
+
source = os.fspath(model)
|
|
78
|
+
directory = Path(source).expanduser()
|
|
79
|
+
if not directory.is_dir():
|
|
80
|
+
if directory.exists() or isinstance(model, Path) or directory.is_absolute() or source.startswith(("./", "../", ".\\", "..\\")):
|
|
81
|
+
raise FileNotFoundError(f"Local checkpoint directory not found: {source}")
|
|
82
|
+
directory = Path(snapshot_download(
|
|
83
|
+
repo_id=source, token=token, revision=revision,
|
|
84
|
+
local_files_only=local_files_only,
|
|
85
|
+
allow_patterns=["rl_agent_config.json", "model.safetensors", "encoder/*", "tokenizer/*"],
|
|
86
|
+
))
|
|
87
|
+
required = ["rl_agent_config.json", "model.safetensors", "encoder/config.json", "tokenizer/tokenizer.json"]
|
|
88
|
+
for filename in required:
|
|
89
|
+
if not (directory / filename).is_file():
|
|
90
|
+
raise FileNotFoundError(f"Checkpoint {source!r} is missing {filename!r}.")
|
|
91
|
+
self.cfg = json.loads((directory / "rl_agent_config.json").read_text(encoding="utf-8"))
|
|
92
|
+
raw_temperature = self.cfg.get("temperature", [1.0, 1.0, 1.0])
|
|
93
|
+
if not isinstance(raw_temperature, list) or len(raw_temperature) != 3:
|
|
94
|
+
raise ValueError("Checkpoint temperature must contain three values.")
|
|
95
|
+
if any(not isinstance(t, (int, float)) or not math.isfinite(t) or t <= 0 for t in raw_temperature):
|
|
96
|
+
raise ValueError("Checkpoint temperatures must be finite positive numbers.")
|
|
97
|
+
self.temperature = [clamp_temperature(t) for t in raw_temperature]
|
|
98
|
+
overrides = self.cfg.get("temperature_by_options", {})
|
|
99
|
+
if not isinstance(overrides, dict):
|
|
100
|
+
raise ValueError("Checkpoint temperature_by_options must be a mapping.")
|
|
101
|
+
if any(not isinstance(t, (int, float)) or not math.isfinite(t) or t <= 0 for t in overrides.values()):
|
|
102
|
+
raise ValueError("Option temperatures must be finite positive numbers.")
|
|
103
|
+
self.temperature_by_options = {k: clamp_temperature(t) for k, t in overrides.items()}
|
|
104
|
+
self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else
|
|
105
|
+
"mps" if torch.backends.mps.is_available() else "cpu"))
|
|
106
|
+
if self.device.type == "cuda" and not torch.cuda.is_available():
|
|
107
|
+
raise ValueError("CUDA is unavailable. Use device='cpu' or install a CUDA-enabled PyTorch build.")
|
|
108
|
+
self.tok = AutoTokenizer.from_pretrained(directory / "tokenizer", local_files_only=True,
|
|
109
|
+
trust_remote_code=False)
|
|
110
|
+
if any(getattr(self.tok, name) is None for name in ("mask_token", "mask_token_id", "cls_token_id", "sep_token_id", "pad_token_id")):
|
|
111
|
+
raise ValueError("Checkpoint tokenizer needs mask, CLS, SEP, and padding tokens.")
|
|
112
|
+
self.model = build_model(self.cfg, encoder_dir=str(directory / "encoder"), pretrained=False)
|
|
113
|
+
self.model.encoder.config.reference_compile = False
|
|
114
|
+
weights = load_file(str(directory / "model.safetensors"), device="cpu")
|
|
115
|
+
self.model.load_state_dict(weights, strict=True)
|
|
116
|
+
del weights
|
|
117
|
+
self.model.to(self.device).eval()
|
|
118
|
+
self.model_id = source
|
|
119
|
+
self.revision = directory.name if directory.parent.name == "snapshots" else revision
|
|
120
|
+
self._lock = threading.RLock()
|
|
121
|
+
|
|
122
|
+
def _items(self, state, questions, max_len, head_max_len):
|
|
123
|
+
if not isinstance(state, (str, dict, list)):
|
|
124
|
+
raise TypeError("State must be text, a dictionary, or a list.")
|
|
125
|
+
state_ids = encode_text(self.tok, serialize_state(state).replace(self.tok.mask_token, " "),
|
|
126
|
+
add_special_tokens=False)["input_ids"]
|
|
127
|
+
items = []
|
|
128
|
+
for qid, question in questions.items():
|
|
129
|
+
ids, markers, stats, truncation = build_sequence(
|
|
130
|
+
self.tok, state, question, max_len=max_len, head_max_len=head_max_len,
|
|
131
|
+
state_ids=state_ids, truncate_left=isinstance(state, list),
|
|
132
|
+
option_order=question.get("option_order"),
|
|
133
|
+
return_stats=True, return_truncation_stats=True,
|
|
134
|
+
)
|
|
135
|
+
if len(markers) != stats["options"]:
|
|
136
|
+
raise ValueError(f"Question {qid!r}: options do not fit in max_len={max_len}.")
|
|
137
|
+
if stats["options_distinct"] != stats["options"]:
|
|
138
|
+
raise ValueError(f"Question {qid!r}: option text becomes identical after token truncation.")
|
|
139
|
+
items.append({"ids": ids, "markers": markers, "qtype": QTYPES[question["t"]],
|
|
140
|
+
"state_stats": truncation})
|
|
141
|
+
return items
|
|
142
|
+
|
|
143
|
+
def _decode(self, logits, act, items, questions):
|
|
144
|
+
answers = {}
|
|
145
|
+
for row, (qid, question) in enumerate(questions.items()):
|
|
146
|
+
count = len(items[row]["markers"])
|
|
147
|
+
qt = QTYPES[question["t"]]
|
|
148
|
+
scale = self.temperature_by_options.get(temp_bucket(qt, count), self.temperature[qt])
|
|
149
|
+
values = logits[row][:count] / scale
|
|
150
|
+
probabilities = np.exp(values - values.max())
|
|
151
|
+
probabilities /= probabilities.sum()
|
|
152
|
+
probabilities = unpermute_probs(probabilities, question.get("option_order"))
|
|
153
|
+
common = {
|
|
154
|
+
"type": question["t"],
|
|
155
|
+
"answer_confidence": round(float(probabilities.max()), 4),
|
|
156
|
+
"action": {"act_probability": round(float(act[row][0]), 4)},
|
|
157
|
+
}
|
|
158
|
+
if question["t"] == "choice":
|
|
159
|
+
labels = list(question["crit"])
|
|
160
|
+
common.update(choice=labels[int(probabilities.argmax())],
|
|
161
|
+
probabilities={label: round(float(p), 4) for label, p in zip(labels, probabilities)},
|
|
162
|
+
confidence=round(confidence_from_probs(probabilities, count), 4))
|
|
163
|
+
elif question["t"] == "noul":
|
|
164
|
+
common.update(noul=round(float(probabilities[1]), 4),
|
|
165
|
+
confidence=common["answer_confidence"])
|
|
166
|
+
else:
|
|
167
|
+
common.update(score=round(float(np.arange(count) @ probabilities), 4),
|
|
168
|
+
probabilities={str(i): round(float(p), 4) for i, p in enumerate(probabilities)},
|
|
169
|
+
confidence=round(confidence_from_probs(probabilities, count), 4))
|
|
170
|
+
answers[qid] = common
|
|
171
|
+
return {"answers": answers, "truncated": any(item["state_stats"]["truncated"] for item in items)}
|
|
172
|
+
|
|
173
|
+
def predict(self, state, questions, *, max_len=None, head_max_len=None):
|
|
174
|
+
return self.predict_batch([state], questions, batch_size=1,
|
|
175
|
+
max_len=max_len, head_max_len=head_max_len)[0]
|
|
176
|
+
|
|
177
|
+
def predict_batch(self, states, questions, *, batch_size=8, max_len=None, head_max_len=None):
|
|
178
|
+
if type(batch_size) is not int or batch_size < 1:
|
|
179
|
+
raise ValueError("batch_size must be a positive integer.")
|
|
180
|
+
if not isinstance(states, (list, tuple)):
|
|
181
|
+
raise TypeError("states must be a list or tuple of states.")
|
|
182
|
+
if not isinstance(questions, Mapping) or not questions:
|
|
183
|
+
raise ValueError("questions must be a non-empty mapping.")
|
|
184
|
+
if not all(isinstance(qid, str) and qid for qid in questions):
|
|
185
|
+
raise ValueError("Question IDs must be non-empty strings.")
|
|
186
|
+
internal = {qid: _question(qid, definition) for qid, definition in questions.items()}
|
|
187
|
+
limit = self.cfg.get("max_len", 1024) if max_len is None else max_len
|
|
188
|
+
head_limit = self.cfg.get("head_max_len", 256) if head_max_len is None else head_max_len
|
|
189
|
+
capacity = self.model.encoder.config.max_position_embeddings
|
|
190
|
+
if type(limit) is not int or not 8 <= limit <= capacity:
|
|
191
|
+
raise ValueError(f"max_len must be an integer between 8 and {capacity}.")
|
|
192
|
+
if type(head_limit) is not int or not 16 <= head_limit <= limit:
|
|
193
|
+
raise ValueError("head_max_len must be an integer between 16 and max_len.")
|
|
194
|
+
results = []
|
|
195
|
+
dtype = torch.bfloat16 if self.device.type == "cuda" and torch.cuda.is_bf16_supported() else torch.float16
|
|
196
|
+
with self._lock, torch.inference_mode():
|
|
197
|
+
for start in range(0, len(states), batch_size):
|
|
198
|
+
groups = [self._items(state, internal, limit, head_limit)
|
|
199
|
+
for state in states[start:start + batch_size]]
|
|
200
|
+
flattened = [item for group in groups for item in group]
|
|
201
|
+
# Bound forward-pass rows even when a request contains many questions.
|
|
202
|
+
logit_rows, act_rows = [], []
|
|
203
|
+
for row_start in range(0, len(flattened), batch_size):
|
|
204
|
+
rows = flattened[row_start:row_start + batch_size]
|
|
205
|
+
batch = collate_items([rows], self.tok.pad_token_id)
|
|
206
|
+
tensors = {name: batch[name].to(self.device) for name in
|
|
207
|
+
("input_ids", "attention_mask", "marker_pos", "marker_mask", "qtype")}
|
|
208
|
+
amp = torch.autocast("cuda", dtype=dtype) if self.device.type == "cuda" else nullcontext()
|
|
209
|
+
with amp:
|
|
210
|
+
logits, act_logits = self.model(**tensors)
|
|
211
|
+
acts = act_logits.float().softmax(-1).cpu().numpy()
|
|
212
|
+
logits = logits.float().cpu().numpy()
|
|
213
|
+
for row, item in enumerate(rows):
|
|
214
|
+
logit_rows.append(logits[row, :len(item["markers"])])
|
|
215
|
+
act_rows.append(acts[row])
|
|
216
|
+
width = len(internal)
|
|
217
|
+
for index, items in enumerate(groups):
|
|
218
|
+
offset = index * width
|
|
219
|
+
results.append(self._decode(logit_rows[offset:offset + width],
|
|
220
|
+
act_rows[offset:offset + width], items, internal))
|
|
221
|
+
return results
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jev-sindhi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Sindhi decision-model inference for Jev
|
|
5
|
+
Author: Muhammad Noman, LughaatNLP, Danish Mahdi
|
|
6
|
+
Maintainer: Danish Mahdi
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Project-URL: Model, https://huggingface.co/DanishMahdi/snd-jev
|
|
9
|
+
Project-URL: Source, https://huggingface.co/DanishMahdi/snd-jev/tree/main/library
|
|
10
|
+
Project-URL: Documentation, https://huggingface.co/DanishMahdi/snd-jev/blob/main/library/README.md
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
License-File: NOTICE
|
|
19
|
+
Requires-Dist: torch<3,>=2.2
|
|
20
|
+
Requires-Dist: transformers<6,>=4.48
|
|
21
|
+
Requires-Dist: safetensors<1,>=0.4
|
|
22
|
+
Requires-Dist: huggingface-hub<2,>=0.24
|
|
23
|
+
Requires-Dist: numpy<3,>=1.24
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# jev-sindhi
|
|
27
|
+
|
|
28
|
+
Python inference library for [DanishMahdi/snd-jev](https://huggingface.co/DanishMahdi/snd-jev).
|
|
29
|
+
It provides structured choice decisions for Sindhi and Roman Sindhi; it does not generate text.
|
|
30
|
+
|
|
31
|
+
This package is a Sindhi-focused fork of the Apache-2.0 `jev-urdu` inference library. Original
|
|
32
|
+
copyright and Laya attribution are retained in [NOTICE](./NOTICE).
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
Install the published package from PyPI:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
python -m pip install jev-sindhi
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
In Google Colab, run this in a notebook cell:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
%pip install jev-sindhi
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Python 3.10+ is supported. PyTorch, Transformers, Safetensors, and Hugging Face Hub are installed
|
|
49
|
+
as package dependencies. The checkpoint is downloaded and cached when `load()` is called.
|
|
50
|
+
|
|
51
|
+
## Use
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import jev_sindhi
|
|
55
|
+
|
|
56
|
+
model = jev_sindhi.load() # defaults to DanishMahdi/snd-jev
|
|
57
|
+
|
|
58
|
+
print(model.sentiment("هي خدمت تمام سٺي آهي."))
|
|
59
|
+
print(model.topic("مريض کي بخار آهي."))
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Select a device or model revision explicitly if needed:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
model = jev_sindhi.load(device="cpu", revision="<Hugging Face commit SHA>")
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
For custom decision questions, use `choice()` and `yes_no()` and pass the resulting definitions to
|
|
69
|
+
`model.ask(text, questions)`. `model.predict()` exposes the lower-level typed predictions.
|
|
70
|
+
|
|
71
|
+
## Evaluation and limitations
|
|
72
|
+
|
|
73
|
+
The model card's evaluation uses a 300-item synthetic, unreviewed benchmark. Its reported scores
|
|
74
|
+
are exploratory only and do not establish accuracy on natural Sindhi. See the model card and
|
|
75
|
+
[evaluation report](../evaluation_report.md) before using the model. Do not use the model for
|
|
76
|
+
consequential decisions without independent, native-speaker evaluation.
|
|
77
|
+
|
|
78
|
+
The inference library is licensed under Apache-2.0; see [LICENSE](./LICENSE) and [NOTICE](./NOTICE).
|
|
79
|
+
The model weights and encoder retain their respective licenses and attributions.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
jev_sindhi/__init__.py,sha256=BzdxXI51IFvGeH39P_HjMUxKMDa-X0pIZpecSp8AWQg,877
|
|
2
|
+
jev_sindhi/_checkpoint.py,sha256=kuKOXsC5He41noW38LtczMj9QGQgkjFrN4K9t2Bhfhk,23683
|
|
3
|
+
jev_sindhi/api.py,sha256=ZnUYpWh0Z2y_EfLIAMCyVRflV3vqz-AjNmlKGEPF1E8,6813
|
|
4
|
+
jev_sindhi/runtime.py,sha256=KSvuQsBn6DsYVq3WPn0Pq_8SJw9kHXIwdD1BRiNsWzU,13174
|
|
5
|
+
jev_sindhi-0.1.0.dist-info/licenses/LICENSE,sha256=psuoW8kuDP96RQsdhzwOqi6fyWv0ct8CR6Jr7He_P_k,10173
|
|
6
|
+
jev_sindhi-0.1.0.dist-info/licenses/NOTICE,sha256=NSREkvcMMsY1gf90RZbxvqNWwW2Jwfxosg6OlbzEG54,956
|
|
7
|
+
jev_sindhi-0.1.0.dist-info/METADATA,sha256=L3qd-PXtLRvcAlAWCDEGrzeez1XbHqHdw5tifjC4NkU,2850
|
|
8
|
+
jev_sindhi-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
jev_sindhi-0.1.0.dist-info/top_level.txt,sha256=Pk5rEdfu99BlCCwCLrdml2_7UFBaYX_EzemFDD7i09A,11
|
|
10
|
+
jev_sindhi-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
jev-sindhi
|
|
2
|
+
Copyright 2026 LughaatNLP
|
|
3
|
+
|
|
4
|
+
The checkpoint architecture and token-packing implementation in
|
|
5
|
+
src/jev_sindhi/_checkpoint.py are adapted from Laya 0.3.22, distributed under
|
|
6
|
+
the Apache License, Version 2.0 by Convai Innovations.
|
|
7
|
+
Upstream: https://github.com/NandhaKishorM/laya
|
|
8
|
+
|
|
9
|
+
Modifications: retained the checkpoint-compatible inference primitives in a
|
|
10
|
+
standalone module; added the jev-urdu loader, question validation, and Urdu API,
|
|
11
|
+
packaging, documentation, and tests. The Laya Python package is not required.
|
|
12
|
+
|
|
13
|
+
The jev-sindhi package was derived from the above work by Danish Mahdi under
|
|
14
|
+
the Apache License, Version 2.0. Changes include the jev_sindhi import package,
|
|
15
|
+
Sindhi default model and convenience APIs, and package metadata/documentation.
|
|
16
|
+
|
|
17
|
+
The pretrained Jev model is downloaded separately from Hugging Face.
|
|
18
|
+
Its mmBERT-base encoder has its own upstream MIT license. Package licensing
|
|
19
|
+
does not replace model licensing or upstream notices.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
jev_sindhi
|