basal-engine 3.0.3__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.
- basal/__init__.py +7 -0
- basal/adapter.py +420 -0
- basal/adapters.py +8 -0
- basal/agree.py +393 -0
- basal/attach.py +160 -0
- basal/attn512.py +132 -0
- basal/auth.py +194 -0
- basal/bench.py +367 -0
- basal/blockquant.py +227 -0
- basal/calibrate.py +2198 -0
- basal/chat.py +175 -0
- basal/cli.py +70 -0
- basal/client.py +8 -0
- basal/decision_log.py +189 -0
- basal/decision_rules.py +569 -0
- basal/decisions.py +158 -0
- basal/derive.py +98 -0
- basal/disconnect.py +85 -0
- basal/engine.py +6023 -0
- basal/evidence.py +133 -0
- basal/examples/choice.jsonl +8 -0
- basal/examples/complex.jsonl +5 -0
- basal/examples/labelled_tickets.jsonl +500 -0
- basal/examples/local_backend.py +34 -0
- basal/examples/noul.jsonl +8 -0
- basal/examples/questions.jsonl +20 -0
- basal/examples/score.jsonl +8 -0
- basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
- basal/examples/selfcheck_basal-omni-pico.json +1 -0
- basal/examples/types_demo.py +74 -0
- basal/facts.py +497 -0
- basal/feedback.py +234 -0
- basal/file_identity.py +39 -0
- basal/finetune.py +321 -0
- basal/fit_decisions.py +944 -0
- basal/fla_configs.json +1822 -0
- basal/fold.py +206 -0
- basal/fonts/OFL-DMSans.txt +93 -0
- basal/fonts/OFL-SpaceGrotesk.txt +93 -0
- basal/fonts/dm-sans-latin-ext.woff2 +0 -0
- basal/fonts/dm-sans-latin.woff2 +0 -0
- basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
- basal/fonts/space-grotesk-latin.woff2 +0 -0
- basal/fp8block.py +100 -0
- basal/gdn_graph.py +1792 -0
- basal/gemma4.py +726 -0
- basal/gemma4_graph.py +931 -0
- basal/gguf_export.py +497 -0
- basal/identity.py +217 -0
- basal/int8block.py +50 -0
- basal/interpolate.py +330 -0
- basal/jsonl.py +172 -0
- basal/lean.py +204 -0
- basal/llama_attn.py +252 -0
- basal/llama_attn_kernels.py +266 -0
- basal/llama_graph.py +587 -0
- basal/llama_kernels.py +593 -0
- basal/loadtest.py +189 -0
- basal/mcp_server.py +432 -0
- basal/media.py +138 -0
- basal/metrics.py +16 -0
- basal/mlx_attn_kernels.py +1057 -0
- basal/mlx_forward.py +326 -0
- basal/mlx_kernels.py +543 -0
- basal/mlx_metal.py +510 -0
- basal/navcut.py +283 -0
- basal/navigate.py +646 -0
- basal/navtree.py +397 -0
- basal/nvfp4.py +245 -0
- basal/ordercheck.py +165 -0
- basal/pdf.py +183 -0
- basal/prepared.py +355 -0
- basal/presets.py +8 -0
- basal/prompt.py +462 -0
- basal/rank.py +373 -0
- basal/readout.py +121 -0
- basal/request.py +327 -0
- basal/response_cache.py +105 -0
- basal/router.py +1551 -0
- basal/router_ui.html +902 -0
- basal/router_ui.py +277 -0
- basal/run.py +376 -0
- basal/selfcheck.py +215 -0
- basal/server.py +5279 -0
- basal/sets.py +214 -0
- basal/signals.py +28 -0
- basal/state_disk.py +942 -0
- basal/strix.py +505 -0
- basal/synth.py +92 -0
- basal/tasks.py +848 -0
- basal/textio.py +21 -0
- basal/think.py +390 -0
- basal/tools.py +171 -0
- basal/tpu.py +336 -0
- basal/tpu_kernels.py +129 -0
- basal/trace.py +125 -0
- basal/ui.html +861 -0
- basal/ui.py +526 -0
- basal/varloop.py +813 -0
- basal/varloop_graph.py +1377 -0
- basal/varloop_kernels.py +907 -0
- basal/viz.html +660 -0
- basal/viz.py +375 -0
- basal/vllm_unified.py +100 -0
- basal_engine-3.0.3.dist-info/METADATA +416 -0
- basal_engine-3.0.3.dist-info/RECORD +111 -0
- basal_engine-3.0.3.dist-info/WHEEL +5 -0
- basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
- basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
- basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
- basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/strix.py
ADDED
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
"""`--mode strix`: a basal-1.5 / basal-2.0 forward written for AMD Strix Halo (Radeon 8060S, gfx1151, ROCm), with
|
|
2
|
+
Triton kernels where the stock ones fall short on this GPU (docs/benchmarks/STRIX_HALO.md, "--mode strix"). Speeds at
|
|
3
|
+
~6k tokens:
|
|
4
|
+
|
|
5
|
+
attention flash attention over the packed prefix trie, GQA-packed (the query heads of a kv head share each key /
|
|
6
|
+
value tile). GraphBackend's block mask becomes an interval per key: depth-first packing puts every
|
|
7
|
+
block's subtree in one contiguous range, so key k is visible to query q iff k <= q < sub_end[k]. Key
|
|
8
|
+
blocks no query of a block can see are skipped, blocks every query sees run without a mask, so a packed
|
|
9
|
+
row costs what a causal row of the same length costs. ~20 TFLOPS; AOTriton's flash attention ~10.
|
|
10
|
+
FFN input gate and up projections, their biases and SwiGLU in one kernel (two accumulators per output tile, one
|
|
11
|
+
load of the activations for both): half the output bytes, no activation pass. ~32 TFLOPS; F.linear +
|
|
12
|
+
silu * up ~17.
|
|
13
|
+
qkv, o, matmuls with the bias, and for o / down the residual add, in the epilogue; tile configs per row count.
|
|
14
|
+
down Faster than F.linear + add on every shape measured (o at 6k tokens 2.4 vs 3.7 ms per layer).
|
|
15
|
+
RMSNorm, small kernels; rotary writes q / k / v head-major for the attention kernel.
|
|
16
|
+
rotary
|
|
17
|
+
|
|
18
|
+
The last layer runs attention, o and the FFN for the readout rows only. q, k and v are one projection (weights
|
|
19
|
+
concatenated at start-up; the Hugging Face modules keep views of them, so the evidence head still runs the stock
|
|
20
|
+
model). Rounding follows the Hugging Face bf16 forward step by step (RMSNorm in fp32 then the weight in bf16, rotary as
|
|
21
|
+
round(q cos) + round(rot(q) sin), silu(gate) and its product with up rounded to bf16, bias then residual each rounded),
|
|
22
|
+
so answers match the other bf16 engines. Every packed row of a chunk is one sequence (no padding, no shapes, no
|
|
23
|
+
graphs): rows of different requests are separate trees of the same interval mask."""
|
|
24
|
+
import math
|
|
25
|
+
import time
|
|
26
|
+
|
|
27
|
+
import torch
|
|
28
|
+
import torch.nn.functional as F
|
|
29
|
+
import triton
|
|
30
|
+
import triton.language as tl
|
|
31
|
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
32
|
+
|
|
33
|
+
from . import adapter as adapter_module
|
|
34
|
+
from .engine import GraphBackend, modelopt_refused
|
|
35
|
+
from .prompt import PREFILL
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# -- kernels -------------------------------------------------------------------------------------------------------
|
|
39
|
+
@triton.jit
|
|
40
|
+
def _attn_fwd(Q, K, V, O, SUB, KMIN, KMAX, TOK, L, NQ, som, scale,
|
|
41
|
+
HPG: tl.constexpr, D: tl.constexpr, BT: tl.constexpr, BN: tl.constexpr, GATHER: tl.constexpr):
|
|
42
|
+
"""One program = BT query tokens x the HPG query heads of one kv head (GQA packed: each key / value tile is
|
|
43
|
+
loaded once for the whole group). Q [H, L, D], K / V [KV, L, D] head-major; O [NQ, H * D]. GATHER: the query
|
|
44
|
+
tokens are TOK[0:NQ] (ascending), else 0..L-1."""
|
|
45
|
+
pid_t = tl.program_id(0)
|
|
46
|
+
kvh = tl.program_id(1)
|
|
47
|
+
R: tl.constexpr = BT * HPG
|
|
48
|
+
r = tl.arange(0, R)
|
|
49
|
+
head = kvh * HPG + r // BT
|
|
50
|
+
qi = pid_t * BT + r % BT # query index (row of O)
|
|
51
|
+
live = qi < NQ
|
|
52
|
+
if GATHER:
|
|
53
|
+
tok = tl.load(TOK + qi, mask=live, other=0)
|
|
54
|
+
q0 = tl.load(TOK + pid_t * BT)
|
|
55
|
+
q_last = tl.load(TOK + tl.minimum(pid_t * BT + BT, NQ) - 1)
|
|
56
|
+
else:
|
|
57
|
+
tok = qi
|
|
58
|
+
q0 = pid_t * BT
|
|
59
|
+
q_last = tl.minimum(q0 + BT, L) - 1
|
|
60
|
+
rd = tl.arange(0, D)
|
|
61
|
+
q = tl.load(Q + (head[:, None] * L + tok[:, None]) * D + rd[None, :], mask=live[:, None], other=0.0)
|
|
62
|
+
m_i = tl.full((R,), float("-inf"), tl.float32)
|
|
63
|
+
l_i = tl.zeros((R,), tl.float32)
|
|
64
|
+
acc = tl.zeros((R, D), tl.float32)
|
|
65
|
+
qs = scale * 1.4426950408889634 # exp2 below
|
|
66
|
+
for k0 in range(0, q_last + 1, BN): # causal: no key after the block's last query
|
|
67
|
+
kb = k0 // BN
|
|
68
|
+
if tl.load(KMAX + kb) > q0: # some key of the block is still visible to some query of this block
|
|
69
|
+
rn = k0 + tl.arange(0, BN)
|
|
70
|
+
k = tl.load(K + (kvh * L + rn[None, :]) * D + rd[:, None], mask=rn[None, :] < L, other=0.0)
|
|
71
|
+
s = tl.dot(q, k) * qs
|
|
72
|
+
if ((k0 + BN - 1) > q0) | (tl.load(KMIN + kb) <= q_last) | GATHER: # not all keys visible to all
|
|
73
|
+
se = tl.load(SUB + rn, mask=rn < L, other=0)
|
|
74
|
+
vis = (rn[None, :] <= tok[:, None]) & (tok[:, None] < se[None, :])
|
|
75
|
+
s = tl.where(vis, s, float("-inf"))
|
|
76
|
+
m_new = tl.maximum(m_i, tl.max(s, 1))
|
|
77
|
+
# a row that has seen no visible key yet (rows of a later tree in the sequence) keeps -inf: subtract 0
|
|
78
|
+
# instead, so its p and alpha are 0 rather than nan
|
|
79
|
+
m_use = tl.where(m_new == float("-inf"), 0.0, m_new)
|
|
80
|
+
p = tl.exp2(s - m_use[:, None])
|
|
81
|
+
alpha = tl.exp2(m_i - m_use)
|
|
82
|
+
l_i = l_i * alpha + tl.sum(p, 1)
|
|
83
|
+
acc = acc * alpha[:, None]
|
|
84
|
+
v = tl.load(V + (kvh * L + rn[:, None]) * D + rd[None, :], mask=rn[:, None] < L, other=0.0)
|
|
85
|
+
acc += tl.dot(p.to(v.dtype), v)
|
|
86
|
+
m_i = m_new
|
|
87
|
+
acc = acc / l_i[:, None]
|
|
88
|
+
tl.store(O + qi[:, None] * som + head[:, None] * D + rd[None, :], acc.to(O.dtype.element_ty), mask=live[:, None])
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@triton.jit
|
|
92
|
+
def _swiglu_mm(x_ptr, wg_ptr, wu_ptr, bg_ptr, bu_ptr, o_ptr, M, N, K, sxm, swn, som,
|
|
93
|
+
BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, GM: tl.constexpr):
|
|
94
|
+
pid = tl.program_id(0)
|
|
95
|
+
npm, npn = tl.cdiv(M, BM), tl.cdiv(N, BN)
|
|
96
|
+
group = GM * npn
|
|
97
|
+
first = (pid // group) * GM
|
|
98
|
+
gsz = min(npm - first, GM)
|
|
99
|
+
pm = first + ((pid % group) % gsz)
|
|
100
|
+
pn = (pid % group) // gsz
|
|
101
|
+
rm = pm * BM + tl.arange(0, BM)
|
|
102
|
+
rn = pn * BN + tl.arange(0, BN)
|
|
103
|
+
rk = tl.arange(0, BK)
|
|
104
|
+
xp = x_ptr + rm[:, None] * sxm + rk[None, :]
|
|
105
|
+
gp = wg_ptr + rn[None, :] * swn + rk[:, None]
|
|
106
|
+
up = wu_ptr + rn[None, :] * swn + rk[:, None]
|
|
107
|
+
ag = tl.zeros((BM, BN), dtype=tl.float32)
|
|
108
|
+
au = tl.zeros((BM, BN), dtype=tl.float32)
|
|
109
|
+
for _ in range(0, K, BK):
|
|
110
|
+
xv = tl.load(xp, mask=rm[:, None] < M, other=0.0)
|
|
111
|
+
ag += tl.dot(xv, tl.load(gp))
|
|
112
|
+
au += tl.dot(xv, tl.load(up))
|
|
113
|
+
xp += BK
|
|
114
|
+
gp += BK
|
|
115
|
+
up += BK
|
|
116
|
+
g = (ag + tl.load(bg_ptr + rn).to(tl.float32)[None, :]).to(tl.bfloat16).to(tl.float32)
|
|
117
|
+
u = (au + tl.load(bu_ptr + rn).to(tl.float32)[None, :]).to(tl.bfloat16).to(tl.float32)
|
|
118
|
+
s = (g / (1.0 + tl.exp(-g))).to(tl.bfloat16).to(tl.float32)
|
|
119
|
+
tl.store(o_ptr + rm[:, None] * som + rn[None, :], (s * u).to(tl.bfloat16), mask=rm[:, None] < M)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@triton.jit
|
|
123
|
+
def _linear(x_ptr, w_ptr, b_ptr, r_ptr, o_ptr, M, N, K, sxm, swn, som,
|
|
124
|
+
BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, GM: tl.constexpr, RES: tl.constexpr):
|
|
125
|
+
"""o = x @ w^T + b, rounded to bf16 as F.linear; RES: then + r in bf16 (the residual add; o may alias r)."""
|
|
126
|
+
pid = tl.program_id(0)
|
|
127
|
+
npm, npn = tl.cdiv(M, BM), tl.cdiv(N, BN)
|
|
128
|
+
group = GM * npn
|
|
129
|
+
first = (pid // group) * GM
|
|
130
|
+
gsz = min(npm - first, GM)
|
|
131
|
+
pm = first + ((pid % group) % gsz)
|
|
132
|
+
pn = (pid % group) // gsz
|
|
133
|
+
rm = pm * BM + tl.arange(0, BM)
|
|
134
|
+
rn = pn * BN + tl.arange(0, BN)
|
|
135
|
+
rk = tl.arange(0, BK)
|
|
136
|
+
xp = x_ptr + rm[:, None] * sxm + rk[None, :]
|
|
137
|
+
wp = w_ptr + rn[None, :] * swn + rk[:, None]
|
|
138
|
+
acc = tl.zeros((BM, BN), dtype=tl.float32)
|
|
139
|
+
for _ in range(0, K, BK):
|
|
140
|
+
acc += tl.dot(tl.load(xp, mask=rm[:, None] < M, other=0.0), tl.load(wp))
|
|
141
|
+
xp += BK
|
|
142
|
+
wp += BK
|
|
143
|
+
o = (acc + tl.load(b_ptr + rn).to(tl.float32)[None, :]).to(tl.bfloat16)
|
|
144
|
+
if RES:
|
|
145
|
+
r = tl.load(r_ptr + rm[:, None] * som + rn[None, :], mask=rm[:, None] < M, other=0.0)
|
|
146
|
+
o = (o.to(tl.float32) + r.to(tl.float32)).to(tl.bfloat16)
|
|
147
|
+
tl.store(o_ptr + rm[:, None] * som + rn[None, :], o, mask=rm[:, None] < M)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@triton.jit
|
|
151
|
+
def _rmsnorm(h_ptr, w_ptr, xo_ptr, eps, N: tl.constexpr):
|
|
152
|
+
"""xo = w * rmsnorm(h), as the stock LlamaRMSNorm: fp32 statistics, normalised value cast to bf16, then the
|
|
153
|
+
weight multiplied in bf16."""
|
|
154
|
+
row = tl.program_id(0)
|
|
155
|
+
offs = tl.arange(0, N)
|
|
156
|
+
hf = tl.load(h_ptr + row * N + offs).to(tl.float32)
|
|
157
|
+
y = (hf * tl.rsqrt(tl.sum(hf * hf, 0) / N + eps)).to(tl.bfloat16)
|
|
158
|
+
tl.store(xo_ptr + row * N + offs, (tl.load(w_ptr + offs).to(tl.float32) * y.to(tl.float32)).to(tl.bfloat16))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@triton.jit
|
|
162
|
+
def _rope(x_ptr, pos_ptr, cos_ptr, sin_ptr, q_ptr, k_ptr, v_ptr, L, sxm, H: tl.constexpr, KV: tl.constexpr,
|
|
163
|
+
HALF: tl.constexpr):
|
|
164
|
+
"""Row `row` of the qkv projection -> q [H, L, D], k / v [KV, L, D] (head-major, contiguous: what the attention
|
|
165
|
+
kernel reads fastest), rotary applied to q and k."""
|
|
166
|
+
row = tl.program_id(0)
|
|
167
|
+
head = tl.program_id(1) # q heads, k heads, v heads: consecutive 2 * HALF blocks of the qkv row
|
|
168
|
+
offs = tl.arange(0, HALF)
|
|
169
|
+
base = x_ptr + row * sxm + head * 2 * HALF
|
|
170
|
+
x1 = tl.load(base + offs)
|
|
171
|
+
x2 = tl.load(base + HALF + offs)
|
|
172
|
+
if head < H + KV:
|
|
173
|
+
p = tl.load(pos_ptr + row)
|
|
174
|
+
c = tl.load(cos_ptr + p * HALF + offs).to(tl.float32)
|
|
175
|
+
s = tl.load(sin_ptr + p * HALF + offs).to(tl.float32)
|
|
176
|
+
f1, f2 = x1.to(tl.float32), x2.to(tl.float32)
|
|
177
|
+
bf = tl.bfloat16
|
|
178
|
+
x1 = ((f1 * c).to(bf).to(tl.float32) + (-f2 * s).to(bf).to(tl.float32)).to(bf)
|
|
179
|
+
x2 = ((f2 * c).to(bf).to(tl.float32) + (f1 * s).to(bf).to(tl.float32)).to(bf)
|
|
180
|
+
if head < H:
|
|
181
|
+
dst = q_ptr + (head * L + row) * 2 * HALF
|
|
182
|
+
elif head < H + KV:
|
|
183
|
+
dst = k_ptr + ((head - H) * L + row) * 2 * HALF
|
|
184
|
+
else:
|
|
185
|
+
dst = v_ptr + ((head - H - KV) * L + row) * 2 * HALF
|
|
186
|
+
tl.store(dst + offs, x1)
|
|
187
|
+
tl.store(dst + HALF + offs, x2)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
# -- backend -------------------------------------------------------------------------------------------------------
|
|
191
|
+
class StrixHaloFastBackend(GraphBackend):
|
|
192
|
+
"""`--mode strix` (see the module docstring). Rows of one chunk are concatenated into a single sequence of at
|
|
193
|
+
most TOKEN_BUDGET tokens; a packed row longer than that is bisected like in GraphBackend (exact). A single prompt
|
|
194
|
+
longer than that runs alone in one forward, as GraphBackend runs one past its largest graph (the server keeps
|
|
195
|
+
prompts within the model's context; activations grow linearly, attention memory does not grow with length)."""
|
|
196
|
+
|
|
197
|
+
KIND = "strix" # one call at a time, no early readouts (engine.KIND_CAPS)
|
|
198
|
+
TOKEN_BUDGET = 16384 # tokens per forward (the GGUF context): ~0.4 GB of FFN activations
|
|
199
|
+
# tile configs measured on the 8060S (Triton 3.7, ROCm 7.2), inside the full forward where it mattered
|
|
200
|
+
ATTN = dict(BT=8, BN=32, num_warps=8, num_stages=1) # ~20 TFLOPS at 6k tokens
|
|
201
|
+
# FFN input (gate / up / SwiGLU): (largest row count, config), first match wins; ~32 TFLOPS at 6k tokens
|
|
202
|
+
FFN = ((512, dict(BM=128, BN=32, BK=64, GM=8, num_warps=4, num_stages=1, waves_per_eu=2)),
|
|
203
|
+
(None, dict(BM=128, BN=64, BK=64, GM=16, num_warps=8, num_stages=1, waves_per_eu=1)))
|
|
204
|
+
# projections: (largest row count, config) per shape, first match wins; round-robin sweeps on the 8060S
|
|
205
|
+
LINEAR = {
|
|
206
|
+
"qkv": ((512, dict(BM=64, BN=64, BK=64, GM=8, num_warps=8, num_stages=2)),
|
|
207
|
+
(1536, dict(BM=128, BN=64, BK=64, GM=8, num_warps=8, num_stages=2)),
|
|
208
|
+
(None, dict(BM=64, BN=128, BK=64, GM=8, num_warps=8, num_stages=2))),
|
|
209
|
+
"o": ((512, dict(BM=128, BN=64, BK=64, GM=8, num_warps=4, num_stages=2)),
|
|
210
|
+
(None, dict(BM=128, BN=64, BK=64, GM=4, num_warps=8, num_stages=2))),
|
|
211
|
+
"down": ((512, dict(BM=64, BN=64, BK=32, GM=8, num_warps=4, num_stages=1)),
|
|
212
|
+
(None, dict(BM=128, BN=128, BK=64, GM=8, num_warps=4, num_stages=2)))}
|
|
213
|
+
LINEAR_ROWS = 2304 # qkv and o run in row chunks of at most this many (they slow down past ~3k rows)
|
|
214
|
+
|
|
215
|
+
@classmethod
|
|
216
|
+
def unsupported(cls, cfg):
|
|
217
|
+
"""What in a model config the kernels cannot run (empty: supported). Every tile config must divide its
|
|
218
|
+
projection (the matmuls have no column or depth masks), tl.arange needs power-of-two extents (head size, query
|
|
219
|
+
heads per kv head, hidden size), and the rotary tables are computed once at start-up. The forward is Llama's
|
|
220
|
+
(basal-1.5, basal-2.0): other architectures (basal-omni is Gemma 4) are refused before their shapes are read."""
|
|
221
|
+
if getattr(cfg, "model_type", None) != "llama":
|
|
222
|
+
return [f"model type {getattr(cfg, 'model_type', None)} (Llama only: basal-1.5, basal-2.0)"]
|
|
223
|
+
H, KV = cfg.num_attention_heads, cfg.num_key_value_heads
|
|
224
|
+
D = getattr(cfg, "head_dim", None) or cfg.hidden_size // H
|
|
225
|
+
hidden, inter = cfg.hidden_size, cfg.intermediate_size
|
|
226
|
+
pow2 = lambda n: n > 0 and n & (n - 1) == 0 # noqa: E731
|
|
227
|
+
rope = getattr(cfg, "rope_parameters", None) or getattr(cfg, "rope_scaling", None) or {}
|
|
228
|
+
rope = rope.get("rope_type", "default")
|
|
229
|
+
out = []
|
|
230
|
+
if cfg.hidden_act != "silu":
|
|
231
|
+
out.append(f"activation {cfg.hidden_act} (silu only)")
|
|
232
|
+
if not pow2(hidden):
|
|
233
|
+
out.append(f"hidden size {hidden} (a power of two)")
|
|
234
|
+
if not pow2(D) or D < 16:
|
|
235
|
+
out.append(f"head size {D} (a power of two, at least 16)")
|
|
236
|
+
if H % KV or not pow2(H // KV):
|
|
237
|
+
out.append(f"{H} query heads over {KV} kv heads (a power-of-two ratio)")
|
|
238
|
+
if "dynamic" in rope or rope == "longrope":
|
|
239
|
+
out.append(f"RoPE type {rope} (its frequencies depend on the sequence length)")
|
|
240
|
+
for name, n, k, cfgs in (("qkv", (H + 2 * KV) * D, hidden, cls.LINEAR["qkv"]),
|
|
241
|
+
("o", hidden, H * D, cls.LINEAR["o"]), ("down", hidden, inter, cls.LINEAR["down"]),
|
|
242
|
+
("gate / up", inter, hidden, cls.FFN)):
|
|
243
|
+
bn, bk = max(c["BN"] for _, c in cfgs), max(c["BK"] for _, c in cfgs)
|
|
244
|
+
if n % bn or k % bk:
|
|
245
|
+
out.append(f"{name} projection {k} -> {n} (multiples of {bk} -> {bn})")
|
|
246
|
+
return out
|
|
247
|
+
|
|
248
|
+
def __init__(self, model_dir, dtype="bfloat16", warm=True, adapter=None):
|
|
249
|
+
if dtype != "bfloat16":
|
|
250
|
+
raise ValueError("--mode strix runs bf16 only")
|
|
251
|
+
if not torch.version.hip:
|
|
252
|
+
raise ValueError("--mode strix needs PyTorch built for ROCm (its kernels and tile configs are for AMD "
|
|
253
|
+
"Strix Halo)")
|
|
254
|
+
why = modelopt_refused(model_dir, "strix") # (transformers' loader: no ModelOpt scales)
|
|
255
|
+
if why:
|
|
256
|
+
raise ValueError(f"{model_dir}: {why}")
|
|
257
|
+
self.tok = AutoTokenizer.from_pretrained(model_dir)
|
|
258
|
+
self.tok.pad_token = self.tok.pad_token or self.tok.eos_token
|
|
259
|
+
self.model = AutoModelForCausalLM.from_pretrained(model_dir, dtype=torch.bfloat16)
|
|
260
|
+
self.adapter_modules = adapter_module.merge_torch(self.model, adapter) if adapter else 0 # on the CPU
|
|
261
|
+
self.model = self.model.cuda().eval()
|
|
262
|
+
self._init_packing(next(self.model.parameters()).device)
|
|
263
|
+
self.prefill = PREFILL
|
|
264
|
+
cfg = self.model.config
|
|
265
|
+
if problems := self.unsupported(cfg):
|
|
266
|
+
raise ValueError("--mode strix cannot run this model: " + "; ".join(problems))
|
|
267
|
+
self.H, self.KV = cfg.num_attention_heads, cfg.num_key_value_heads
|
|
268
|
+
self.D = getattr(cfg, "head_dim", None) or cfg.hidden_size // self.H
|
|
269
|
+
self.hidden, self.eps = cfg.hidden_size, cfg.rms_norm_eps
|
|
270
|
+
m = self.model.model
|
|
271
|
+
self.layers = []
|
|
272
|
+
for layer in m.layers:
|
|
273
|
+
a, f = layer.self_attn, layer.mlp
|
|
274
|
+
w = torch.cat([a.q_proj.weight, a.k_proj.weight, a.v_proj.weight]).contiguous()
|
|
275
|
+
b = torch.cat([a.q_proj.bias, a.k_proj.bias, a.v_proj.bias]).contiguous() \
|
|
276
|
+
if a.q_proj.bias is not None else None
|
|
277
|
+
nq, nk = a.q_proj.weight.shape[0], a.k_proj.weight.shape[0]
|
|
278
|
+
for mod, lo, hi in ((a.q_proj, 0, nq), (a.k_proj, nq, nq + nk), (a.v_proj, nq + nk, w.shape[0])):
|
|
279
|
+
mod.weight.data = w[lo:hi] # views: the stock modules (evidence head) share the fused weights
|
|
280
|
+
if b is not None:
|
|
281
|
+
mod.bias.data = b[lo:hi]
|
|
282
|
+
zeros = lambda n: torch.zeros(n, device=self.dev, dtype=torch.bfloat16) # noqa: E731 (no bias)
|
|
283
|
+
bias = lambda mod: mod.bias if mod.bias is not None else zeros(mod.weight.shape[0]) # noqa: E731
|
|
284
|
+
self.layers.append((layer.input_layernorm.weight, w, b if b is not None else zeros(w.shape[0]),
|
|
285
|
+
a.o_proj.weight, bias(a.o_proj), layer.post_attention_layernorm.weight,
|
|
286
|
+
f.gate_proj.weight.contiguous(), bias(f.gate_proj), f.up_proj.weight.contiguous(),
|
|
287
|
+
bias(f.up_proj), f.down_proj.weight.contiguous(), bias(f.down_proj)))
|
|
288
|
+
torch.cuda.empty_cache()
|
|
289
|
+
self.embed, self.final_norm = m.embed_tokens.weight, m.norm.weight
|
|
290
|
+
# rotary tables as the stock model computes them: fp32 angles, cos / sin scaled, then cast to bf16
|
|
291
|
+
rot = m.rotary_emb
|
|
292
|
+
pos = torch.arange(cfg.max_position_embeddings, device=self.dev, dtype=torch.float32)
|
|
293
|
+
ang = pos[:, None] * rot.inv_freq.float()[None, :]
|
|
294
|
+
self.cos = (ang.cos() * rot.attention_scaling).to(torch.bfloat16).contiguous()
|
|
295
|
+
self.sin = (ang.sin() * rot.attention_scaling).to(torch.bfloat16).contiguous()
|
|
296
|
+
if warm: # compile every kernel once (Triton JIT), short and multi-block rows; within vocabulary and context
|
|
297
|
+
V = self.embed.shape[0]
|
|
298
|
+
for n in (min(300, self.cos.shape[0] - 1), min(1100, self.cos.shape[0] - 1)):
|
|
299
|
+
toks = [[1] + list(range(1000, 1000 + n)), [1] + list(range(1000, 1000 + n // 2)) + [7, 8]]
|
|
300
|
+
self.run_shared([([[t % V for t in x] for x in toks], [[30 % V, 31 % V]] * 2)])
|
|
301
|
+
self._warm_shapes()
|
|
302
|
+
|
|
303
|
+
# Start-up forwards for attention and rotary (one tile config each): sequence lengths other and a multiple of 16,
|
|
304
|
+
# each against readout rows 1, other and a multiple of 16 (the last layer's attention takes both counts), and a
|
|
305
|
+
# sequence of one token (a request that packs to one). They run the first layer and the last only: every layer
|
|
306
|
+
# between needs the copies the first one compiles.
|
|
307
|
+
WARM_FORWARDS = ((1, 1), (17, 1), (32, 1), (17, 3), (32, 3), (17, 16), (32, 16))
|
|
308
|
+
|
|
309
|
+
@staticmethod
|
|
310
|
+
def warm_rows(cfgs):
|
|
311
|
+
"""Row counts that cover a (largest row count, config) list: 1 (the last row chunk of qkv / o, one readout
|
|
312
|
+
row), then in every range one count that is not a multiple of 16 and one that is."""
|
|
313
|
+
rows, lo = [1], 0
|
|
314
|
+
for lim, _ in cfgs:
|
|
315
|
+
rows += [lo + 17 + ((lo + 17) % 16 == 0), (lo // 16 + 2) * 16]
|
|
316
|
+
lo = lim
|
|
317
|
+
return rows
|
|
318
|
+
|
|
319
|
+
def _warm_row(self, L, nq):
|
|
320
|
+
"""Inputs of `forward` for one packed row of L tokens and its last nq tokens read out: causal sequences of
|
|
321
|
+
at most the context each (positions within the rotary tables), token ids within the vocabulary."""
|
|
322
|
+
i = torch.arange(L, device=self.dev)
|
|
323
|
+
P = self.cos.shape[0]
|
|
324
|
+
ends = torch.clamp((i // P + 1) * P, max=L)
|
|
325
|
+
return (i + 1000) % self.embed.shape[0], (i % P).to(torch.int32), ends.to(torch.int32), i[L - nq:]
|
|
326
|
+
|
|
327
|
+
@torch.no_grad()
|
|
328
|
+
def _warm_shapes(self):
|
|
329
|
+
"""Compile every kernel copy a request can need. Triton compiles a kernel once per tile config and per class of
|
|
330
|
+
each integer argument: 1, a multiple of 16, other. The row count picks both (the config by its range in FFN /
|
|
331
|
+
LINEAR, the class by its value), and a request that needs a copy not compiled yet waits for it: ~0.2-0.3 s per
|
|
332
|
+
copy on the 8060S, ~1 ms when Triton's disk cache holds it (in the request matrix, the first timed pass of S
|
|
333
|
+
with 1 question and of M with 2 did). The projections run on zero rows of warm_rows, as the forward calls them
|
|
334
|
+
(same strides, residual for o / down); attention and rotary in the short WARM_FORWARDS, over the first and the
|
|
335
|
+
last layer (all 60 layers of basal-2.0 took ~0.7 s per start)."""
|
|
336
|
+
z = lambda m, n: torch.zeros(m, n, device=self.dev, dtype=torch.bfloat16) # noqa: E731
|
|
337
|
+
_, wqkv, bqkv, wo, bo, _, wg, bg, wu, bu, wd, bd = self.layers[0]
|
|
338
|
+
for m in self.warm_rows(self.LINEAR["qkv"]):
|
|
339
|
+
self._linear("qkv", z(m, self.hidden), wqkv, bqkv)
|
|
340
|
+
for m in self.warm_rows(self.LINEAR["o"]):
|
|
341
|
+
self._linear("o", z(m, wo.shape[1]), wo, bo, z(m, self.hidden))
|
|
342
|
+
for m in self.warm_rows(self.LINEAR["down"]):
|
|
343
|
+
self._linear("down", z(m, wd.shape[1]), wd, bd, z(m, self.hidden))
|
|
344
|
+
for m in self.warm_rows(self.FFN):
|
|
345
|
+
self._ffn_in(z(m, self.hidden), wg, bg, wu, bu)
|
|
346
|
+
layers = self.layers
|
|
347
|
+
self.layers = layers[:1] + layers[-1:] if len(layers) > 1 else layers
|
|
348
|
+
try:
|
|
349
|
+
for L, nq in self.WARM_FORWARDS:
|
|
350
|
+
self.forward(*self._warm_row(L, nq))
|
|
351
|
+
self._wait()
|
|
352
|
+
finally:
|
|
353
|
+
self.layers = layers
|
|
354
|
+
|
|
355
|
+
def _oversize(self, pack, n):
|
|
356
|
+
return len(pack[0]) > self.TOKEN_BUDGET
|
|
357
|
+
|
|
358
|
+
def _chunks_tok(self, units):
|
|
359
|
+
"""Units sorted by length, cut into chunks of at most TOKEN_BUDGET tokens."""
|
|
360
|
+
out, cur, n = [], [], 0
|
|
361
|
+
for k in sorted(range(len(units)), key=lambda k: len(units[k][0][0])):
|
|
362
|
+
t = len(units[k][0][0])
|
|
363
|
+
if cur and n + t > self.TOKEN_BUDGET:
|
|
364
|
+
out.append(cur); cur, n = [], 0
|
|
365
|
+
cur.append(k); n += t
|
|
366
|
+
return out + ([cur] if cur else [])
|
|
367
|
+
|
|
368
|
+
@staticmethod
|
|
369
|
+
def _sub_end(pack, off):
|
|
370
|
+
"""Per token of a packed row: the end of its block's subtree (global index, row starting at off)."""
|
|
371
|
+
t, pos, seg, last, parent = pack
|
|
372
|
+
own_end = [0] * len(parent)
|
|
373
|
+
for i, s in enumerate(seg):
|
|
374
|
+
own_end[s] = i + 1
|
|
375
|
+
sub = own_end[:]
|
|
376
|
+
for b in range(len(parent) - 1, -1, -1): # children follow their parent (depth-first order)
|
|
377
|
+
if parent[b] >= 0:
|
|
378
|
+
sub[parent[b]] = max(sub[parent[b]], sub[b])
|
|
379
|
+
return [off + sub[s] for s in seg]
|
|
380
|
+
|
|
381
|
+
def _qkv_heads(self, qkv, pos):
|
|
382
|
+
"""qkv projection -> rotary q, k and v, head-major [heads, L, D]."""
|
|
383
|
+
L = qkv.shape[0]
|
|
384
|
+
H, KV, D = self.H, self.KV, self.D
|
|
385
|
+
q = torch.empty(H, L, D, device=qkv.device, dtype=qkv.dtype)
|
|
386
|
+
k = torch.empty(KV, L, D, device=qkv.device, dtype=qkv.dtype)
|
|
387
|
+
v = torch.empty(KV, L, D, device=qkv.device, dtype=qkv.dtype)
|
|
388
|
+
_rope[(L, H + 2 * KV)](qkv, pos, self.cos, self.sin, q, k, v, L, qkv.stride(0), H=H, KV=KV, HALF=D // 2,
|
|
389
|
+
num_warps=1)
|
|
390
|
+
return q, k, v
|
|
391
|
+
|
|
392
|
+
def _key_bounds(self, sub):
|
|
393
|
+
"""Smallest and largest sub_end of every key block of the attention kernel: blocks no query of a query block
|
|
394
|
+
can see are skipped, blocks every query sees run without a mask."""
|
|
395
|
+
BN = self.ATTN["BN"]
|
|
396
|
+
nb = triton.cdiv(sub.shape[0], BN)
|
|
397
|
+
pad = nb * BN - sub.shape[0]
|
|
398
|
+
kmin = F.pad(sub, (0, pad), value=2 ** 30).view(nb, BN).amin(1).contiguous()
|
|
399
|
+
kmax = F.pad(sub, (0, pad), value=0).view(nb, BN).amax(1).contiguous()
|
|
400
|
+
return kmin, kmax
|
|
401
|
+
|
|
402
|
+
def _attention(self, q, k, v, sub, kmin, kmax, tok=None):
|
|
403
|
+
"""Attention of every token (tok None) or of the query tokens tok (ascending) -> [n, H * D]."""
|
|
404
|
+
H, L, D = q.shape
|
|
405
|
+
n = L if tok is None else tok.shape[0]
|
|
406
|
+
o = torch.empty(n, H * D, device=q.device, dtype=q.dtype)
|
|
407
|
+
c = self.ATTN
|
|
408
|
+
_attn_fwd[(triton.cdiv(n, c["BT"]), self.KV)](q, k, v, o, sub, kmin, kmax, tok if tok is not None else sub,
|
|
409
|
+
L, n, o.stride(0), 1.0 / math.sqrt(D), HPG=H // self.KV, D=D,
|
|
410
|
+
BT=c["BT"], BN=c["BN"], GATHER=tok is not None,
|
|
411
|
+
num_warps=c["num_warps"], num_stages=c["num_stages"])
|
|
412
|
+
return o
|
|
413
|
+
|
|
414
|
+
def _ffn_in(self, x, wg, bg, wu, bu):
|
|
415
|
+
M, K = x.shape
|
|
416
|
+
N = wg.shape[0]
|
|
417
|
+
o = torch.empty(M, N, device=x.device, dtype=x.dtype)
|
|
418
|
+
c = next(c for lim, c in self.FFN if lim is None or M <= lim)
|
|
419
|
+
grid = (triton.cdiv(M, c["BM"]) * (N // c["BN"]),)
|
|
420
|
+
_swiglu_mm[grid](x, wg, wu, bg, bu, o, M, N, K, x.stride(0), wg.stride(0), o.stride(0), **c)
|
|
421
|
+
return o
|
|
422
|
+
|
|
423
|
+
def _linear(self, kind, x, w, b, r=None):
|
|
424
|
+
"""x @ w^T + b (+ r, written into r)."""
|
|
425
|
+
M, K = x.shape
|
|
426
|
+
N = w.shape[0]
|
|
427
|
+
o = r if r is not None else torch.empty(M, N, device=x.device, dtype=x.dtype)
|
|
428
|
+
step = M if kind == "down" else self.LINEAR_ROWS
|
|
429
|
+
for a in range(0, M, step):
|
|
430
|
+
xa, oa = x[a: a + step], o[a: a + step]
|
|
431
|
+
m = xa.shape[0]
|
|
432
|
+
c = next(c for lim, c in self.LINEAR[kind] if lim is None or m <= lim)
|
|
433
|
+
_linear[(triton.cdiv(m, c["BM"]) * (N // c["BN"]),)](xa, w, b, oa, oa, m, N, K, xa.stride(0), w.stride(0),
|
|
434
|
+
oa.stride(0), RES=r is not None, **c)
|
|
435
|
+
return o
|
|
436
|
+
|
|
437
|
+
def _norm(self, h, w):
|
|
438
|
+
x = torch.empty_like(h)
|
|
439
|
+
_rmsnorm[(h.shape[0],)](h, w, x, self.eps, N=self.hidden, num_warps=4)
|
|
440
|
+
return x
|
|
441
|
+
|
|
442
|
+
@torch.no_grad()
|
|
443
|
+
def forward(self, ids, pos, sub, reads):
|
|
444
|
+
"""One sequence of packed rows -> final-normalised hidden states at the readout rows. The last layer runs
|
|
445
|
+
attention, o and the FFN for the readout rows only (nothing else reads its output)."""
|
|
446
|
+
kmin, kmax = self._key_bounds(sub)
|
|
447
|
+
h = F.embedding(ids, self.embed)
|
|
448
|
+
x = self._norm(h, self.layers[0][0])
|
|
449
|
+
n = len(self.layers)
|
|
450
|
+
for i, (_, wqkv, bqkv, wo, bo, ln2, wg, bg, wu, bu, wd, bd) in enumerate(self.layers):
|
|
451
|
+
q, k, v = self._qkv_heads(self._linear("qkv", x, wqkv, bqkv), pos)
|
|
452
|
+
if i + 1 < n:
|
|
453
|
+
a = self._attention(q, k, v, sub, kmin, kmax)
|
|
454
|
+
else: # last layer: readout rows only (sorted for the attention kernel)
|
|
455
|
+
rs, order = torch.sort(reads)
|
|
456
|
+
a = self._attention(q, k, v, sub, kmin, kmax, tok=rs.to(torch.int32))
|
|
457
|
+
h = h[rs]
|
|
458
|
+
x = self._norm(self._linear("o", a, wo, bo, h), ln2) # h += o_proj(a)
|
|
459
|
+
g = self._ffn_in(x, wg, bg, wu, bu)
|
|
460
|
+
x = self._norm(self._linear("down", g, wd, bd, h), # h += down_proj(g)
|
|
461
|
+
self.layers[i + 1][0] if i + 1 < n else self.final_norm)
|
|
462
|
+
return x[torch.argsort(order)]
|
|
463
|
+
|
|
464
|
+
SPIN_S = 0.3 # seconds of a forward waited for by spinning before polling (_wait)
|
|
465
|
+
|
|
466
|
+
@classmethod
|
|
467
|
+
def _wait(cls):
|
|
468
|
+
"""Wait for the GPU: query an event in a loop for the first SPIN_S seconds, then poll it with 0.5 ms sleeps.
|
|
469
|
+
ROCm's synchronize spins a CPU core at 100% for the whole forward (seconds on long rows). Polling from the start
|
|
470
|
+
let short forwards run up to 3x slower on a Radeon 8060S in an HP Z2 Mini, as the GPU clocked down while the CPU
|
|
471
|
+
slept (one 200-token question 230-510 ms instead of 155-162 ms), while forwards of 0.7 s and more ran as fast
|
|
472
|
+
polled as spun. So a short forward is waited for spinning, and a long one costs at most SPIN_S of a core."""
|
|
473
|
+
ev = torch.cuda.Event()
|
|
474
|
+
ev.record()
|
|
475
|
+
end = time.perf_counter() + cls.SPIN_S
|
|
476
|
+
while not ev.query():
|
|
477
|
+
if time.perf_counter() > end:
|
|
478
|
+
time.sleep(0.0005)
|
|
479
|
+
|
|
480
|
+
@torch.no_grad()
|
|
481
|
+
def run(self, prompts, ids_list):
|
|
482
|
+
return [r[0] for r in self.run_shared([([p], [x]) for p, x in zip(prompts, ids_list)])]
|
|
483
|
+
|
|
484
|
+
@torch.no_grad()
|
|
485
|
+
def run_shared(self, groups, policy=None):
|
|
486
|
+
units = self._units(groups)
|
|
487
|
+
probs = [None] * len(units)
|
|
488
|
+
for idx in self._chunks_tok(units):
|
|
489
|
+
ids, pos, sub, reads, off = [], [], [], [], 0
|
|
490
|
+
for k in idx:
|
|
491
|
+
t, pp, sg, last, par = pk = units[k][0]
|
|
492
|
+
ids += t; pos += pp; sub += self._sub_end(pk, off); reads += [off + i for i in last]
|
|
493
|
+
off += len(t)
|
|
494
|
+
if max(pos) >= self.cos.shape[0]:
|
|
495
|
+
raise ValueError(f"prompt too long for --mode strix: position {max(pos)}, the model has "
|
|
496
|
+
f"{self.cos.shape[0]}")
|
|
497
|
+
dev = self.dev
|
|
498
|
+
h = self.forward(torch.tensor(ids, device=dev), torch.tensor(pos, device=dev, dtype=torch.int32),
|
|
499
|
+
torch.tensor(sub, device=dev, dtype=torch.int32), torch.tensor(reads, device=dev))
|
|
500
|
+
self._wait()
|
|
501
|
+
pr = self._readout(h, [x for k in idx for x in units[k][1]])
|
|
502
|
+
j = 0
|
|
503
|
+
for k in idx:
|
|
504
|
+
n = len(units[k][1]); probs[k] = pr[j: j + n]; j += n
|
|
505
|
+
return self._assemble(groups, units, probs)
|
basal/synth.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Synthetic decision items with long states, for speed and identity measurements (no real data).
|
|
2
|
+
|
|
3
|
+
A state is a generated case log (Polish or English) of about `tokens` tokens, the question asks which unit should
|
|
4
|
+
handle the latest entry, and the options are 2..k department names (or `options` of them, for many-option tests).
|
|
5
|
+
The texts are meaningless as decisions; only their shape (length, language, option count) matters.
|
|
6
|
+
|
|
7
|
+
python -m basal.synth --n 500 --tokens 1500 --out synth.jsonl
|
|
8
|
+
"""
|
|
9
|
+
import argparse
|
|
10
|
+
import random
|
|
11
|
+
|
|
12
|
+
from .jsonl import write
|
|
13
|
+
|
|
14
|
+
CHARS_PER_TOKEN = {"pl": 2.1, "en": 1.85} # Bielik v3 tokenizers on these logs (dates and amounts; measured)
|
|
15
|
+
|
|
16
|
+
WORDS = {
|
|
17
|
+
"pl": dict(
|
|
18
|
+
names=["Anna Nowak", "Piotr Wiśniewski", "Katarzyna Wójcik", "Tomasz Kamiński", "Magdalena Lewandowska",
|
|
19
|
+
"Michał Zieliński", "Agnieszka Szymańska", "Paweł Woźniak", "Ewa Dąbrowska", "Krzysztof Kozłowski"],
|
|
20
|
+
issues=["uszkodzona przesyłka", "brak zwrotu pieniędzy", "błędna faktura", "opóźniona dostawa",
|
|
21
|
+
"nie działa logowanie", "podwójne obciążenie karty", "zmiana adresu dostawy", "reklamacja towaru",
|
|
22
|
+
"pytanie o gwarancję", "wymiana na inny rozmiar"],
|
|
23
|
+
status=["przyjęte", "w toku", "czeka na klienta", "przekazane", "zamknięte"],
|
|
24
|
+
line="[{d:02d}.{mo:02d}.2026 {h:02d}:{mi:02d}] Zgłoszenie {id}: {name} — {issue}; kwota {amt},{gr:02d} zł, "
|
|
25
|
+
"status: {st}.",
|
|
26
|
+
head="Historia zgłoszeń klienta (system obsługi, eksport automatyczny):",
|
|
27
|
+
question="Który dział powinien obsłużyć ostatnie zgłoszenie?",
|
|
28
|
+
units=["Reklamacje", "Płatności", "Logistyka", "Obsługa techniczna", "Faktury", "Sprzedaż", "Dział prawny",
|
|
29
|
+
"Kadry", "Magazyn", "Zwroty"],
|
|
30
|
+
unit="Dział {k}"),
|
|
31
|
+
"en": dict(
|
|
32
|
+
names=["Alice Moore", "John Carter", "Emily Brooks", "David Turner", "Sarah Hughes", "Mark Bennett",
|
|
33
|
+
"Laura Price", "James Foster", "Olivia Reed", "Daniel Ward"],
|
|
34
|
+
issues=["damaged parcel", "refund not received", "wrong invoice", "late delivery", "cannot log in",
|
|
35
|
+
"card charged twice", "change of delivery address", "product complaint", "warranty question",
|
|
36
|
+
"exchange for another size"],
|
|
37
|
+
status=["received", "in progress", "waiting for customer", "forwarded", "closed"],
|
|
38
|
+
line="[{d:02d}/{mo:02d}/2026 {h:02d}:{mi:02d}] Ticket {id}: {name} - {issue}; amount {amt}.{gr:02d} EUR, "
|
|
39
|
+
"status: {st}.",
|
|
40
|
+
head="Customer ticket history (support system, automatic export):",
|
|
41
|
+
question="Which department should handle the latest ticket?",
|
|
42
|
+
units=["Complaints", "Payments", "Logistics", "Technical support", "Invoicing", "Sales", "Legal", "HR",
|
|
43
|
+
"Warehouse", "Returns"],
|
|
44
|
+
unit="Department {k}"),
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def state(rnd, lang, tokens):
|
|
49
|
+
w = WORDS[lang]
|
|
50
|
+
lines, n = [w["head"]], len(w["head"])
|
|
51
|
+
while n < tokens * CHARS_PER_TOKEN[lang]:
|
|
52
|
+
x = w["line"].format(d=rnd.randint(1, 28), mo=rnd.randint(1, 12), h=rnd.randint(7, 20), mi=rnd.randint(0, 59),
|
|
53
|
+
id=rnd.randint(10000, 99999), name=rnd.choice(w["names"]), issue=rnd.choice(w["issues"]),
|
|
54
|
+
amt=rnd.randint(10, 9999), gr=rnd.randint(0, 99), st=rnd.choice(w["status"]))
|
|
55
|
+
lines.append(x); n += len(x) + 1
|
|
56
|
+
return "\n".join(lines)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def items(n, tokens=1500, seed=0, options=None, spread=0.33, langs=("pl", "en"), long_frac=0.0, long_tokens=(3000, 10000)):
|
|
60
|
+
"""n items; state lengths uniform in tokens * (1 +- spread), except a share long_frac of long states (uniform in
|
|
61
|
+
long_tokens; a long-document tail); options: fixed count, else 2..6 at random."""
|
|
62
|
+
rnd = random.Random(seed)
|
|
63
|
+
out = []
|
|
64
|
+
for i in range(n):
|
|
65
|
+
lang = langs[i % len(langs)]
|
|
66
|
+
w = WORDS[lang]
|
|
67
|
+
k = options or rnd.randint(2, 6)
|
|
68
|
+
units = w["units"][:] if k <= len(w["units"]) else w["units"] + [w["unit"].format(k=j) for j in range(11, k + 1)]
|
|
69
|
+
units = units[:k]
|
|
70
|
+
rnd.shuffle(units)
|
|
71
|
+
t = int(tokens * (1 + rnd.uniform(-spread, spread)))
|
|
72
|
+
if long_frac and rnd.random() < long_frac:
|
|
73
|
+
t = rnd.randint(*long_tokens)
|
|
74
|
+
out.append(dict(id=f"synth-{seed}-{i}", state=state(rnd, lang, t), question=w["question"], options=units))
|
|
75
|
+
return out
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def main():
|
|
79
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
80
|
+
ap.add_argument("--n", type=int, default=500)
|
|
81
|
+
ap.add_argument("--tokens", type=int, default=1500, help="mean state length in tokens")
|
|
82
|
+
ap.add_argument("--options", type=int, default=None, help="options per item (default: 2..6 at random)")
|
|
83
|
+
ap.add_argument("--seed", type=int, default=0)
|
|
84
|
+
ap.add_argument("--long-frac", dest="long_frac", type=float, default=0.0, help="share of long states (e.g. 0.1)")
|
|
85
|
+
ap.add_argument("--long-tokens", dest="long_tokens", type=int, nargs=2, default=(3000, 10000))
|
|
86
|
+
ap.add_argument("--out", required=True)
|
|
87
|
+
a = ap.parse_args()
|
|
88
|
+
write(a.out, items(a.n, a.tokens, a.seed, a.options, long_frac=a.long_frac, long_tokens=tuple(a.long_tokens)))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if __name__ == "__main__":
|
|
92
|
+
main()
|