Manusagents commited on
Commit
31f7037
·
verified ·
1 Parent(s): cffdb4e

Qyvos v1: Julia-1 backbone (bit-exact) + Open-Jev head fine-tune (30k rows, low-RAM protocol)

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer/tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Qyvos
2
+
3
+ **Qyvos** is a decision / classification model built from [`SupersonicLabs/Julia-1`](https://huggingface.co/SupersonicLabs/Julia-1) by head-only fine-tuning on the [`ZefanCai/Open-Jev`](https://huggingface.co/datasets/ZefanCai/Open-Jev) dataset (config `release-v2-redistributable`).
4
+
5
+ It maps a **state + question + options** context to a probability distribution over the options, for three decision kinds:
6
+
7
+ | qtype | kind | meaning |
8
+ |-------|-------|---------|
9
+ | 0 | `choice` | pick one option (categorical decision) |
10
+ | 1 | `score` | grade/distribute mass over options (soft scoring) |
11
+ | 2 | `noul` | binary yes/no decision (options ordered `[no, yes]`) |
12
+
13
+ ## Complete backbone retention
14
+
15
+ The **entire Julia-1 backbone is retained bit-exact**:
16
+
17
+ - `encoder` — ModernBERT-small (22 layers, hidden 384, vocab 256k), 140,530,432 params — **frozen, untouched**
18
+ - `act_head` — auxiliary action head — **frozen, untouched**
19
+
20
+ Training updated only the decision head (**3,699,073 trainable params = 2.56%** of 144,292,867):
21
+
22
+ - `head` — 2× `TransformerEncoderLayer(384, nhead=6, dim_ff=1536, norm_first=True)`
23
+ - `type_emb` — `Embedding(3, 384)` (one embedding per decision kind)
24
+ - `scorer` — `LayerNorm → Linear(384,384) → GELU → Linear(384,1)` per-option scorer
25
+
26
+ Weights are **float32** end-to-end (the Julia checkpoint format has no FP16 variant; nothing was quantized or pruned).
27
+
28
+ ## Training
29
+
30
+ - Data: `ZefanCai/Open-Jev`, config `release-v2-redistributable`, `train` split (79,116 rows available), streamed **30,000 rows** in deterministic shuffled order
31
+ - Objective: soft-target cross-entropy `-(target · log_softmax(scores)).sum(-1).mean()` — trains calibrated probability distributions, exactly matching Open-Jev's soft `target` vectors
32
+ - Encoding: identical `julia.data.sequence()` marker-token serialization as the official Julia runtime (train/inference parity)
33
+ - Optimizer: AdamW, lr 1e-4 (linear warmup 100 steps → linear decay to 10%), β=(0.9,0.999), weight decay 0.01 (no decay on norms/embeddings), grad clip 1.0
34
+ - Batch: **1 micro-batch × 8 accumulation** (effective batch 8), 3,750 optimizer steps
35
+ - Sequence budget: `max_length=1024`, `head_length=512`
36
+ - Seed: 17
37
+
38
+ ### Low-RAM training constraints (3.9 GB system RAM)
39
+
40
+ No full fine-tuning was possible (or needed). The run was designed for an 8 GB-class machine:
41
+
42
+ - frozen encoder ⇒ no gradients/optimizer state for 140.5M params; encoder forward runs under `no_grad`
43
+ - bs=1 micro-batches, `num_workers=0`, fp32 head-only optimizer state
44
+ - parquet read via **pyarrow mmap**, one row-group (~1,000 rows, a few MB) at a time; lazy per-row tokenization; **no dataset-wide RAM cache**
45
+ - head-only checkpoints (~45 MB, incl. optimizer) with deterministic skip fast-forward resume
46
+ - psutil RAM guard: auto-checkpoint + abort if system available RAM < 350 MB
47
+ - **Measured peak RSS: 1.64 GB**
48
+
49
+ ## Results (honest shuffled-mixture evaluation)
50
+
51
+ Evaluation samples are drawn round-robin across **all** parquet row-groups (each region contributes equally), fixed seed 999, length-bucketed batches. Accuracy = argmax match vs the target's argmax; softCE = soft-target cross-entropy (lower is better).
52
+
53
+ | model | val acc (n=900) | val softCE | test acc (n=900) | test softCE |
54
+ |---|---|---|---|---|
55
+ | Julia-1 base (no training) | 83.67% | 0.4542 | 83.56% | 0.4764 |
56
+ | **Qyvos (30,000 rows)** | **84.11%** | **0.4282** | 83.11% | **0.4447** |
57
+
58
+ Larger-sample confirmation for Qyvos on the test split: n=1500 → acc 81.67%, softCE 0.4587.
59
+
60
+ Per-kind (Qyvos, n=900):
61
+
62
+ | kind | val acc | test acc |
63
+ |---|---|---|
64
+ | choice | 66.5% | 68.2% |
65
+ | score | 79.4% | 79.3% |
66
+ | noul | 92.7% | 90.2% |
67
+
68
+ Honest reading: Julia-1's pretrained decision head is already strong on this benchmark family, and top-1 accuracy differences between base and Qyvos are within evaluation noise (~±1.2pt stderr at n=900). What fine-tuning **did** deliver, consistently across both splits and sample sizes, is **better-calibrated probabilities (softCE −5.7% val, −6.7% test)** — which is precisely the objective that matters for Open-Jev's soft, often high-entropy targets, and for any downstream consumer of the full probability vector rather than a single argmax. The accuracy ceiling here is largely data-intrinsic: many Open-Jev targets are intentionally soft/ambiguous.
69
+
70
+ ## Exact inference (official runtime)
71
+
72
+ ```python
73
+ import julia # from the julia/ package shipped in this repo (pip install -e julia --no-deps)
74
+
75
+ engine = julia.load_model("<path-to-Qyvos>", device="cpu", max_length=1024, head_length=512)
76
+ pred = engine.predict([{
77
+ "state": "User chat: my login is blocked after the password reset.",
78
+ "question": "Determine the broad category of this support ticket.",
79
+ "options": ["account: Login, permissions, profile, security",
80
+ "billing: Charges, invoices, refunds, subscriptions"],
81
+ "type": "choice", # choice | score | noul
82
+ }])[0]
83
+ print(pred["index"], pred["probabilities"])
84
+ ```
85
+
86
+ Or with the bundled CLI (see `training/`):
87
+
88
+ ```bash
89
+ python3 scripts/infer_qyvos.py --demo # per-kind examples from the test split
90
+ python3 scripts/infer_qyvos.py --eval-test 900 # honest shuffled test accuracy
91
+ python3 scripts/infer_qyvos.py --row '{"state":"...","question":"...","options":["a","b"],"type":"choice"}'
92
+ ```
93
+
94
+ > **Compatibility note:** on `transformers >= 5.17`, julia's *optional* fast inference path
95
+ > (`julia/router/encoder.py`) references `ModernBertModel._update_attention_mask`, which was
96
+ > removed upstream. The bundled scripts disable that optimization via a two-line shim
97
+ > (`specialize_decision_encoder → False`); inference then uses the standard forward with
98
+ > numerically equivalent results. On `transformers 5.0.x` (the version this checkpoint was
99
+ > built against) no shim is needed.
100
+
101
+ ## Repository layout
102
+
103
+ ```
104
+ Qyvos/
105
+ ├── config.json # architecture pointer file (Julia format v1)
106
+ ├── julia_config.json # Qyvos identity + head settings
107
+ ├── model.safetensors # fp32 weights (backbone bit-exact + trained head)
108
+ ├── encoder/config.json # ModernBERT-small config
109
+ ├── tokenizer/ # tokenizer (copied bit-exact from Julia-1)
110
+ ├── label_map.json # qtype id -> kind
111
+ ├── qyvos_training_config.json # full training config + final metrics
112
+ ├── provenance.json # base/dataset revisions + SHA-256 hashes
113
+ └── training/ # all scripts used (download/inspect/train/build/infer)
114
+ ```
115
+
116
+ ## Provenance
117
+
118
+ - Base model: `SupersonicLabs/Julia-1` (fp32, weights SHA-256 recorded in `provenance.json`)
119
+ - Dataset: `ZefanCai/Open-Jev` @ config `release-v2-redistributable` (per-shard SHA-256 in `provenance.json`)
120
+ - Backbone tensors: bit-exact vs base; only `head`, `type_emb`, `scorer` differ
121
+ - Final `model.safetensors` SHA-256: `1d03ac9a0c7fbc66f1bde7ecb158741b02c9f898078c0a2f0cc270fb6326f920`
config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": 1,
3
+ "architecture": "JuliaDecisionModel",
4
+ "julia_config_file": "julia_config.json",
5
+ "encoder_config_file": "encoder/config.json",
6
+ "weights_file": "model.safetensors",
7
+ "tokenizer_directory": "tokenizer",
8
+ "name": "Qyvos",
9
+ "base_model": "SupersonicLabs/Julia-1"
10
+ }
encoder/config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ModernBertForMaskedLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 2,
8
+ "classifier_activation": "gelu",
9
+ "classifier_bias": false,
10
+ "classifier_dropout": 0.0,
11
+ "classifier_pooling": "mean",
12
+ "cls_token_id": 1,
13
+ "decoder_bias": true,
14
+ "deterministic_flash_attn": false,
15
+ "dtype": "float32",
16
+ "embedding_dropout": 0.0,
17
+ "eos_token_id": 1,
18
+ "global_attn_every_n_layers": 3,
19
+ "gradient_checkpointing": false,
20
+ "hidden_activation": "gelu",
21
+ "hidden_size": 384,
22
+ "initializer_cutoff_factor": 2.0,
23
+ "initializer_range": 0.02,
24
+ "intermediate_size": 1152,
25
+ "layer_norm_eps": 1e-05,
26
+ "layer_types": [
27
+ "full_attention",
28
+ "sliding_attention",
29
+ "sliding_attention",
30
+ "full_attention",
31
+ "sliding_attention",
32
+ "sliding_attention",
33
+ "full_attention",
34
+ "sliding_attention",
35
+ "sliding_attention",
36
+ "full_attention",
37
+ "sliding_attention",
38
+ "sliding_attention",
39
+ "full_attention",
40
+ "sliding_attention",
41
+ "sliding_attention",
42
+ "full_attention",
43
+ "sliding_attention",
44
+ "sliding_attention",
45
+ "full_attention",
46
+ "sliding_attention",
47
+ "sliding_attention",
48
+ "full_attention"
49
+ ],
50
+ "local_attention": 128,
51
+ "mask_token_id": 4,
52
+ "max_position_embeddings": 8192,
53
+ "mlp_bias": false,
54
+ "mlp_dropout": 0.0,
55
+ "model_type": "modernbert",
56
+ "norm_bias": false,
57
+ "norm_eps": 1e-05,
58
+ "num_attention_heads": 6,
59
+ "num_hidden_layers": 22,
60
+ "pad_token_id": 0,
61
+ "position_embedding_type": "sans_pos",
62
+ "repad_logits_with_grad": false,
63
+ "rope_parameters": {
64
+ "full_attention": {
65
+ "rope_theta": 160000,
66
+ "rope_type": "default"
67
+ },
68
+ "sliding_attention": {
69
+ "rope_theta": 160000,
70
+ "rope_type": "default"
71
+ }
72
+ },
73
+ "sep_token_id": 1,
74
+ "sparse_pred_ignore_index": -100,
75
+ "sparse_prediction": true,
76
+ "tie_word_embeddings": true,
77
+ "transformers_version": "5.18.0",
78
+ "vocab_size": 256000
79
+ }
julia/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """Supersonic Labs Julia typed decision models.
2
+
3
+ Use ``load_model`` for a resident CPU or CUDA inference engine.
4
+ """
5
+
6
+ from .inference import load_model
7
+
8
+ __all__ = ['load_model']
julia/cuda.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CUDA configuration and explicit environment diagnostics for the L40S path."""
2
+ import importlib.metadata
3
+ import json
4
+ import os
5
+ import platform
6
+ import torch
7
+
8
+
9
+ def configure(device_name='cuda', precision='bf16', seed=42):
10
+ device = torch.device(device_name)
11
+ if device.type == 'cuda' and device.index is None:
12
+ device = torch.device('cuda', 0)
13
+ if device.type == 'cuda' and not torch.cuda.is_available():
14
+ raise RuntimeError('CUDA requested but unavailable. Run nvidia-smi and install the CUDA PyTorch wheel; CPU fallback is disabled.')
15
+ if precision == 'bf16' and device.type == 'cuda' and not torch.cuda.is_bf16_supported():
16
+ raise RuntimeError('This CUDA device does not support BF16; select --precision fp32.')
17
+ torch.set_num_threads(int(os.environ.get('JULIA_CPU_THREADS', '4')))
18
+ torch.manual_seed(seed)
19
+ if device.type == 'cuda':
20
+ torch.cuda.set_device(device)
21
+ torch.cuda.manual_seed_all(seed)
22
+ torch.backends.cuda.matmul.allow_tf32 = True
23
+ torch.backends.cudnn.allow_tf32 = True
24
+ torch.cuda.reset_peak_memory_stats(device)
25
+ torch.set_float32_matmul_precision('high')
26
+ return device
27
+
28
+
29
+ def environment(device):
30
+ result = dict(python=platform.python_version(), torch=str(torch.__version__), cuda=torch.version.cuda,
31
+ transformers=importlib.metadata.version('transformers'), device=str(device))
32
+ if device.type == 'cuda':
33
+ prop = torch.cuda.get_device_properties(device)
34
+ result.update(gpu=prop.name, vram_bytes=prop.total_memory,
35
+ compute_capability=list(torch.cuda.get_device_capability(device)))
36
+ return result
37
+
38
+
39
+ def move(batch, device):
40
+ return {k: v.to(device, non_blocking=device.type == 'cuda') for k, v in batch.items()}
41
+
42
+
43
+ def main():
44
+ device = configure()
45
+ x = torch.randn(512, 512, device=device, dtype=torch.bfloat16, requires_grad=True)
46
+ (x @ x.T).float().square().mean().backward()
47
+ torch.cuda.synchronize()
48
+ report = environment(device)
49
+ report['bf16_forward_backward_finite'] = bool(torch.isfinite(x.grad).all())
50
+ print(json.dumps(report, indent=2))
51
+ if not report['bf16_forward_backward_finite']:
52
+ raise RuntimeError('CUDA BF16 diagnostic produced nonfinite gradients')
53
+
54
+
55
+ if __name__ == '__main__':
56
+ main()
julia/data.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validated decision JSONL and the upstream-compatible marker serialization."""
2
+ import hashlib
3
+ import json
4
+ import math
5
+ from pathlib import Path
6
+
7
+ import torch
8
+ from torch.utils.data import Dataset
9
+
10
+ QTYPES = {'choice': 0, 'score': 1, 'noul': 2}
11
+
12
+
13
+ def digest(path):
14
+ with Path(path).open('rb') as stream:
15
+ return hashlib.file_digest(stream, 'sha256').hexdigest()
16
+
17
+
18
+ def validate_row(row, line):
19
+ prefix = f'JSONL line {line}: '
20
+ if not isinstance(row, dict):
21
+ raise ValueError(prefix + 'request must be a JSON object')
22
+ if not isinstance(row.get('state'), (str, dict, list)) or not isinstance(row.get('question'), str):
23
+ raise ValueError(prefix + 'state must be text/JSON and question must be text')
24
+ options = row.get('options')
25
+ if not isinstance(options, list) or not 2 <= len(options) <= 20 or not all(isinstance(x, str) and x for x in options):
26
+ raise ValueError(prefix + 'options must contain 2–20 nonempty rendered descriptions')
27
+ if row.get('type', 'choice') not in QTYPES:
28
+ raise ValueError(prefix + 'type must be choice, score, or noul')
29
+ if row.get('type') == 'noul' and len(options) != 2:
30
+ raise ValueError(prefix + 'noul options must be ordered [false, true]')
31
+ if 'target' in row and (type(row['target']) is not int or not 0 <= row['target'] < len(options)):
32
+ raise ValueError(prefix + 'target must index the supplied option list')
33
+ teacher = row.get('teacher_logits')
34
+ if teacher is not None and (
35
+ not isinstance(teacher, list)
36
+ or len(teacher) != len(options)
37
+ or not all(type(x) in (int, float) and math.isfinite(x) for x in teacher)
38
+ ):
39
+ raise ValueError(prefix + 'teacher logits must be finite and match option count/order')
40
+
41
+
42
+ class Decisions(Dataset):
43
+ def __init__(self, path, require_target=True, require_teacher=False):
44
+ self.rows = []
45
+ with open(path) as stream:
46
+ for line, text in enumerate(stream, 1):
47
+ if not text.strip():
48
+ continue
49
+ try:
50
+ row = json.loads(text)
51
+ except json.JSONDecodeError as error:
52
+ raise ValueError(f'{path}:{line}: invalid JSON: {error.msg}') from error
53
+ validate_row(row, line)
54
+ if require_target and 'target' not in row:
55
+ raise ValueError(f'{path}:{line}: training requires target')
56
+ if require_teacher and 'teacher_logits' not in row:
57
+ raise ValueError(f'{path}:{line}: distillation requires teacher_logits')
58
+ self.rows.append(row)
59
+ if not self.rows:
60
+ raise ValueError(f'{path}: dataset contains no rows')
61
+ flags = {'teacher_logits' in row for row in self.rows}
62
+ if len(flags) != 1:
63
+ raise ValueError('Dataset mixes rows with and without teacher logits')
64
+
65
+ def __len__(self):
66
+ return len(self.rows)
67
+
68
+ def __getitem__(self, index):
69
+ return self.rows[index]
70
+
71
+
72
+ def sequence(tokenizer, row, max_length=8192, head_length=256, *, strict=False):
73
+ if head_length + 4 >= max_length:
74
+ raise ValueError('max_length must leave room beyond the question head')
75
+ if any(x is None for x in (tokenizer.mask_token_id, tokenizer.cls_token_id, tokenizer.sep_token_id)):
76
+ raise ValueError('Tokenizer must define MASK, CLS and SEP IDs')
77
+ state = row['state'] if isinstance(row['state'], str) else json.dumps(row['state'], ensure_ascii=False)
78
+ if strict and any(tokenizer.mask_token in text for text in [state, row['question'], *row['options']]):
79
+ raise ValueError('Reserved model marker in request')
80
+ clean = lambda text: text.replace(tokenizer.mask_token, ' ')
81
+ encode = lambda text: tokenizer(text, add_special_tokens=False)['input_ids']
82
+ head = encode(f"{row.get('type', 'choice')} question: {clean(row['question'])}")
83
+ option_ids = [encode(' ' + clean(x)) for x in row['options']]
84
+ if strict and any(len(x) > 48 for x in option_ids):
85
+ raise ValueError('Option exceeds 48-token model contract')
86
+ options = [[tokenizer.mask_token_id] + x[:48] for x in option_ids]
87
+ budget = head_length - sum(map(len, options))
88
+ if budget < 16:
89
+ per_option = max(4, (head_length - 16) // len(options))
90
+ options = [x[:per_option] for x in options]
91
+ budget = head_length - sum(map(len, options))
92
+ if strict and (len(head) > budget or any(len(x) != len(y) + 1 for x, y in zip(options, option_ids))):
93
+ raise ValueError('Question/options exceed lossless head budget')
94
+ ids = [tokenizer.cls_token_id] + head[:max(8, budget)] + [tokenizer.sep_token_id]
95
+ markers = []
96
+ for option in options:
97
+ markers.append(len(ids))
98
+ ids.extend(option)
99
+ ids.append(tokenizer.sep_token_id)
100
+ state_ids = encode(clean(state))
101
+ room = max_length - len(ids) - 1
102
+ if room < 1:
103
+ raise ValueError('Question/options exceed sequence budget; shorten descriptions')
104
+ if strict and len(state_ids) > room:
105
+ raise ValueError('Game state exceeds lossless context budget')
106
+ result = dict(ids=ids + state_ids[:room] + [tokenizer.sep_token_id], markers=markers,
107
+ qtype=QTYPES[row.get('type', 'choice')], truncated=len(state_ids) > room)
108
+ if strict:
109
+ result['option_tokens'] = list(map(len, option_ids))
110
+ return result
111
+
112
+
113
+ class Collator:
114
+ def __init__(self, tokenizer, max_length=8192, head_length=256):
115
+ self.tokenizer, self.max_length, self.head_length = tokenizer, max_length, head_length
116
+
117
+ def __call__(self, rows, *, include_targets=True):
118
+ encoded = [row['_encoded'] if '_encoded' in row else sequence(
119
+ self.tokenizer, row, self.max_length, self.head_length) for row in rows]
120
+ length = min(self.max_length, ((max(len(x['ids']) for x in encoded) + 7) // 8) * 8)
121
+ count = max(len(x['markers']) for x in encoded)
122
+ ids = torch.full((len(rows), length), self.tokenizer.pad_token_id, dtype=torch.long)
123
+ attention = torch.zeros_like(ids)
124
+ positions = torch.zeros((len(rows), count), dtype=torch.long)
125
+ mask = torch.zeros_like(positions, dtype=torch.bool)
126
+ has_teacher = include_targets and all('teacher_logits' in row for row in rows)
127
+ teacher = torch.zeros_like(positions, dtype=torch.float32) if has_teacher else None
128
+ for i, (row, item) in enumerate(zip(rows, encoded)):
129
+ n, k = len(item['ids']), len(item['markers'])
130
+ ids[i, :n] = torch.tensor(item['ids'])
131
+ attention[i, :n] = 1
132
+ positions[i, :k] = torch.tensor(item['markers'])
133
+ mask[i, :k] = True
134
+ if has_teacher:
135
+ teacher[i, :k] = torch.tensor(row['teacher_logits'])
136
+ batch = dict(input_ids=ids, attention_mask=attention, marker_pos=positions,
137
+ marker_mask=mask, qtype=torch.tensor([x['qtype'] for x in encoded]))
138
+ if include_targets and all('target' in row for row in rows):
139
+ batch['labels'] = torch.tensor([row['target'] for row in rows])
140
+ if has_teacher:
141
+ batch['teacher_logits'] = teacher
142
+ return batch
julia/inference.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Resident CUDA inference for native Julia and CUDA INT8 checkpoints."""
2
+ import json
3
+ from pathlib import Path
4
+ import torch
5
+ from safetensors.torch import load_file
6
+ from .cuda import configure, move
7
+ from .data import Collator, validate_row
8
+ from .probabilities import display_probabilities
9
+
10
+
11
+ def context_length(checkpoint, requested):
12
+ config = json.loads((Path(checkpoint) / 'encoder/config.json').read_text())
13
+ limit = config['max_position_embeddings']
14
+ value = limit if requested is None else requested
15
+ if type(value) is not int or not 1 <= value <= limit:
16
+ raise ValueError(f'max_length must be an integer between 1 and {limit}')
17
+ return value
18
+
19
+
20
+ class TransformerEngine:
21
+ def __init__(self, checkpoint, device='cuda', max_length=None, head_length=256, *, memory_map=True):
22
+ from transformers import AutoModel, AutoTokenizer
23
+ from .model import JuliaDecisionModel
24
+ self.device = configure(device)
25
+ root = Path(checkpoint)
26
+ max_length = context_length(root, max_length)
27
+ if (root / 'INCOMPLETE').exists():
28
+ raise ValueError('Refusing to load an incomplete INT8 export')
29
+ self.tokenizer = AutoTokenizer.from_pretrained(root / 'tokenizer', trust_remote_code=False)
30
+ if (root / 'quantization.json').exists():
31
+ if self.device.type != 'cuda':
32
+ raise ValueError('This INT8 checkpoint requires CUDA')
33
+ encoder = AutoModel.from_pretrained(root / 'encoder', device_map={'': self.device.index or 0},
34
+ attn_implementation='sdpa', trust_remote_code=False)
35
+ config = json.loads((root / 'julia_config.json').read_text())
36
+ self.model = JuliaDecisionModel(encoder, **{k: config[k] for k in ('head_layers', 'n_act', 'dropout')})
37
+ heads = load_file(str(root / 'heads.safetensors'))
38
+ expected = {k for k in self.model.state_dict() if not k.startswith('encoder.')}
39
+ if set(heads) != expected:
40
+ raise ValueError('INT8 decision-head tensor keys do not match checkpoint architecture')
41
+ self.model.load_state_dict(heads, strict=False)
42
+ for name, child in self.model.named_children():
43
+ if name != 'encoder':
44
+ child.to(self.device)
45
+ else:
46
+ self.model = JuliaDecisionModel.from_pretrained(root, memory_map=memory_map).to(self.device)
47
+ self.model.eval()
48
+ self.collate = Collator(self.tokenizer, max_length, head_length)
49
+
50
+ @torch.inference_mode()
51
+ def logits(self, rows):
52
+ if not rows:
53
+ return []
54
+ for i, row in enumerate(rows):
55
+ validate_row(row, i + 1)
56
+ batch = move(self.collate(rows, include_targets=False), self.device)
57
+ with torch.autocast(device_type=self.device.type, dtype=torch.bfloat16, enabled=self.device.type == 'cuda'):
58
+ logits = self.model(**batch)
59
+ logits = logits.cpu()
60
+ if not torch.isfinite(logits).all():
61
+ raise FloatingPointError('Inference returned nonfinite logits')
62
+ return [values[:len(row['options'])].tolist() for values, row in zip(logits, rows)]
63
+
64
+ def predict(self, rows=None, questions=None, *, state=None):
65
+ if questions is not None:
66
+ from .typed import predict_typed
67
+ if rows is not None and state is not None:
68
+ raise ValueError('Pass state either positionally or by keyword, not both')
69
+ return predict_typed(self, state if rows is None else rows, questions)
70
+ if state is not None or rows is None:
71
+ raise ValueError('Provide legacy rows or state with questions')
72
+ result = []
73
+ for values in self.logits(rows):
74
+ probabilities = torch.tensor(values).softmax(-1)
75
+ result.append(dict(index=int(probabilities.argmax()),
76
+ probabilities=display_probabilities(probabilities.tolist())))
77
+ return result
78
+
79
+
80
+ def load_model(checkpoint, device='cpu', max_length=None, head_length=256, *, backend=None, **kwargs):
81
+ """Load a Julia checkpoint through the supported resident inference runtime."""
82
+ from .router.engine import FastEngine
83
+ if checkpoint is None:
84
+ raise ValueError('checkpoint is required; pass a local model directory')
85
+ if backend not in (None, 'torch', 'bend', 'bend-dense'):
86
+ raise ValueError('backend must be torch, bend, or bend-dense')
87
+ return FastEngine(checkpoint, device, max_length, head_length,
88
+ transformer_backend=backend, **kwargs)
89
+
90
+
91
+ Engine = load_model # Backward compatible entry point.
julia/model.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Marker based decision model and checkpoint serialization."""
2
+ import json
3
+ from pathlib import Path
4
+
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+ from torch.utils.checkpoint import checkpoint
9
+ from safetensors.torch import load_file, save_file
10
+ from transformers import AutoConfig, AutoModel
11
+
12
+
13
+ class JuliaDecisionModel(nn.Module):
14
+ def __init__(self, encoder, head_layers=2, n_act=2, dropout=.1):
15
+ super().__init__()
16
+ self.encoder = encoder
17
+ width = encoder.config.hidden_size
18
+ self.settings = dict(head_layers=head_layers, n_act=n_act, dropout=dropout)
19
+ layer = nn.TransformerEncoderLayer(width, max(1, width // 64), 4 * width,
20
+ dropout, batch_first=True, norm_first=True)
21
+ self.head = nn.TransformerEncoder(layer, head_layers, enable_nested_tensor=False) if head_layers else None
22
+ self.type_emb = nn.Embedding(3, width)
23
+ self.scorer = nn.Sequential(nn.LayerNorm(width), nn.Linear(width, width), nn.GELU(), nn.Linear(width, 1))
24
+ self.act_head = nn.Sequential(nn.Linear(width + 4, 256), nn.GELU(), nn.Linear(256, n_act))
25
+ self.register_buffer('temperature', torch.ones(3))
26
+ self.head_checkpointing = False
27
+ self.marker_only_head = False
28
+ self.encoder.config.reference_compile = False
29
+
30
+ @classmethod
31
+ def from_backbone(cls, path, revision=None, head_layers=2):
32
+ encoder = AutoModel.from_pretrained(path, revision=revision, trust_remote_code=False,
33
+ attn_implementation='sdpa')
34
+ return cls(encoder, head_layers=head_layers)
35
+
36
+ def forward(self, input_ids, attention_mask, marker_pos, marker_mask, qtype, return_actions=False):
37
+ hidden = self.encoder(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
38
+ hidden = hidden + self.type_emb(qtype)[:, None, :]
39
+ # Only option positions (and CLS for the action head) are consumed.
40
+ # The final block can keep full K/V context while avoiding unused queries
41
+ # and feed-forward outputs. Training retains the original dropout path.
42
+ selected = marker_pos
43
+ if return_actions:
44
+ selected = torch.cat((torch.zeros_like(marker_pos[:, :1]), marker_pos), dim=1)
45
+ sparse = (self.marker_only_head and not self.training and self.head is not None
46
+ and len(self.head.layers) > 0
47
+ and type(self.head.layers[-1]) is nn.TransformerEncoderLayer)
48
+ if self.head is not None:
49
+ padding = ~attention_mask.bool()
50
+ for i, layer in enumerate(self.head.layers):
51
+ if sparse and i == len(self.head.layers) - 1:
52
+ hidden = self._selected_head(layer, hidden, selected, attention_mask)
53
+ elif self.head_checkpointing and self.training:
54
+ hidden = checkpoint(layer, hidden, src_key_padding_mask=padding, use_reentrant=False)
55
+ else:
56
+ hidden = layer(hidden, src_key_padding_mask=padding)
57
+ if not sparse:
58
+ positions = selected[:, :, None].expand(-1, -1, hidden.shape[-1])
59
+ hidden = hidden.gather(1, positions)
60
+ markers = hidden[:, 1:] if return_actions else hidden
61
+ scores = self.scorer(markers).squeeze(-1).float()
62
+ scores = scores.masked_fill(~marker_mask, -1e4)
63
+ if not return_actions:
64
+ return scores
65
+ probability = scores.detach().softmax(-1)
66
+ top = probability.topk(min(2, probability.shape[1]), dim=-1).values
67
+ if top.shape[1] == 1:
68
+ top = torch.cat((top, torch.zeros_like(top)), dim=-1)
69
+ count = marker_mask.sum(-1).clamp_min(2).float()
70
+ entropy = -(probability * probability.clamp_min(1e-9).log()).sum(-1) / count.log()
71
+ features = torch.stack((top[:, 0], top[:, 0] - top[:, 1], entropy, count / 255), -1)
72
+ actions = self.act_head(torch.cat((hidden[:, 0].float(), features), -1))
73
+ return scores, actions
74
+
75
+ @staticmethod
76
+ def _selected_head(layer, hidden, selected, attention_mask):
77
+ """Exact pre-norm block restricted to selected output positions (eval only)."""
78
+ width = hidden.shape[-1]
79
+ positions = selected[:, :, None].expand(-1, -1, width)
80
+ normalized = layer.norm1(hidden)
81
+ attn = layer.self_attn
82
+ query = F.linear(normalized.gather(1, positions),
83
+ attn.in_proj_weight[:width], attn.in_proj_bias[:width])
84
+ key, value = F.linear(normalized, attn.in_proj_weight[width:],
85
+ attn.in_proj_bias[width:]).chunk(2, dim=-1)
86
+ batch = hidden.shape[0]
87
+ heads = attn.num_heads
88
+ split = lambda x: x.reshape(batch, -1, heads, width // heads).transpose(1, 2)
89
+ attended = F.scaled_dot_product_attention(
90
+ split(query), split(key), split(value),
91
+ attn_mask=attention_mask[:, None, None, :].bool(), dropout_p=0.)
92
+ attended = attended.transpose(1, 2).reshape(batch, selected.shape[1], width)
93
+ result = hidden.gather(1, positions) + attn.out_proj(attended)
94
+ return result + layer.linear2(layer.activation(layer.linear1(layer.norm2(result))))
95
+
96
+ def save_pretrained(self, directory):
97
+ root = Path(directory)
98
+ root.mkdir(parents=True, exist_ok=True)
99
+ self.encoder.config.save_pretrained(root / 'encoder')
100
+ config = dict(format_version=1, architecture='JuliaDecisionModel',
101
+ weight_dtype=str(next(self.parameters()).dtype).replace('torch.', ''), **self.settings)
102
+ (root / 'julia_config.json').write_text(json.dumps(config, indent=2) + '\n')
103
+ save_file({k: v.detach().cpu().contiguous() for k, v in self.state_dict().items()},
104
+ str(root / 'model.safetensors'), metadata={'format': 'pt', 'family': 'julia'})
105
+
106
+ @classmethod
107
+ def from_pretrained(cls, directory, *, memory_map=False):
108
+ root = Path(directory)
109
+ if (root / 'julia_config.json').exists():
110
+ config = json.loads((root / 'julia_config.json').read_text())
111
+ if config['format_version'] != 1:
112
+ raise ValueError('Unsupported Julia checkpoint format')
113
+ settings = {k: config[k] for k in ('head_layers', 'n_act', 'dropout')}
114
+ else:
115
+ config = json.loads((root / 'rl_agent_config.json').read_text())
116
+ settings = dict(head_layers=config['head_layers'], n_act=len(config.get('act_costs', {})) + 1)
117
+ encoder_config = AutoConfig.from_pretrained(root / 'encoder', trust_remote_code=False)
118
+ encoder_config.reference_compile = False
119
+ try:
120
+ from transformers.initialization import no_init_weights
121
+ except ImportError:
122
+ from transformers.modeling_utils import no_init_weights
123
+ with no_init_weights():
124
+ encoder = AutoModel.from_config(encoder_config, attn_implementation='sdpa', trust_remote_code=False)
125
+ model = cls(encoder, **settings)
126
+ if not memory_map and config.get('weight_dtype') == 'bfloat16':
127
+ model.to(dtype=torch.bfloat16)
128
+ # Inference can retain safetensors' private file-backed storage rather than
129
+ # copying the entire (mostly unused vocabulary) embedding into anonymous RAM.
130
+ # The default copy path remains available for training and mutable checkpoints.
131
+ model.load_state_dict(load_file(str(root / 'model.safetensors')),
132
+ strict=True, assign=memory_map)
133
+ return model
julia/probabilities.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Presentation rules for decision probabilities; logits and selection stay raw."""
2
+
3
+
4
+ def display_probabilities(probabilities):
5
+ values = list(probabilities)
6
+ if not values:
7
+ return values
8
+
9
+ winner = max(range(len(values)), key=values.__getitem__)
10
+ if values[winner] > 0.95 and all(
11
+ value < 0.045 for i, value in enumerate(values) if i != winner
12
+ ):
13
+ return [1.0 if i == winner else 0.0 for i in range(len(values))]
14
+
15
+ visible = [value if value >= 0.01 else 0.0 for value in values]
16
+ total = sum(visible)
17
+ return [value / total for value in visible]
julia/router/.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ build/
2
+ __pycache__/
3
+ *.pyc
julia/router/README.md ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Julia router
2
+
3
+ Resident inference for Julia on **CPU or CUDA**, located in the existing `julia`
4
+ package. No separate repository. Python loads Bend-generated C with `ctypes`;
5
+ there is no compiler or subprocess in the request path.
6
+
7
+ ## Build and use
8
+
9
+ From the **Julia-1** directory (the outer workspace also has an older package
10
+ named `julia`, so running there can import the wrong one):
11
+
12
+ ```bash
13
+ python -m pip install -e .
14
+ python -m julia.router.build --bend /home/klee/.bend/bin/bend
15
+ ```
16
+
17
+ The native build requires Bend **2.0.27**, Clang, and Linux. It checks `native/PROOF.bend`, generated
18
+ function arities, and the borrowed-tree contract before compiling. `--native-cpu`
19
+ adds host-specific machine instructions; use that build only on compatible CPUs. The bridge
20
+ uses private Bend runtime internals, so upgrading Bend requires adapting and
21
+ retesting the bridge. `--output` selects another library location; pass that
22
+ path as `library=` or set `JULIA_ROUTER_LIBRARY` at runtime.
23
+
24
+ ```python
25
+ from julia.router import FastEngine
26
+
27
+ engine = FastEngine('/path/to/real/checkpoint', device='cpu', batch_size=16)
28
+ # device='cuda' uses CUDA/BF16 and device-side softmax/argmax.
29
+ rows = [{
30
+ 'state': 'Preciso trocar minha senha.',
31
+ 'question': 'Qual é a intenção?',
32
+ 'options': ['Redefinir senha', 'Cancelar conta', 'Consultar saldo'],
33
+ }]
34
+ print(engine.predict(rows))
35
+ print(engine.predict(rows, probabilities=False)) # return only indices
36
+ ```
37
+
38
+ Use real checkpoint files, not Git LFS pointer files. The 2026-09-23 runtime audit
39
+ loaded the actual 551 MiB checkpoint offline and exercised resident inference.
40
+
41
+ ## Faster inference path
42
+
43
+ - Bounded LRU caches reuse token fragments and full request encodings. Model
44
+ forward passes still run on **every request**; no answer cache inflates timings.
45
+ - Sort by encoded length before bounded microbatches, then restore request order.
46
+ This reduces padding on mixed-length inputs; it does not guarantee a speedup
47
+ for every batch or request size.
48
+ - Build one NumPy arena for integer inputs, with zero-copy CPU tensor views.
49
+ CUDA uses two pinned bulk transfers instead of per-field transfers.
50
+ - Softmax and argmax run on the model's device. CUDA does not copy hidden states
51
+ or attention matrices into CPU Bend kernels.
52
+ - `compile_model=True` enables optional `torch.compile(dynamic=True)`. Compilation
53
+ adds first-call cost and requires validation on the target device.
54
+ - CPU inference retains private file-backed safetensors storage instead of copying
55
+ the full vocabulary embedding into anonymous RAM. Keep checkpoint files immutable
56
+ while loaded; use `memory_map=False` for a detached copy. Training model loading
57
+ still copies by default.
58
+ - CPU PyTorch heads compute only option queries and feed-forward outputs in the
59
+ final layer. Full context keys/values are retained. `marker_only_head=False`
60
+ selects the original path; training and the separate experimental Bend normalization head use the original
61
+ path automatically. CUDA retains the original default until hardware validation.
62
+ - `strict_encoding=True` rejects marker injection and any question/option/state
63
+ truncation. `encoding_info(rows)` audits the same cached encoding used in inference;
64
+ the game worker no longer tokenizes each request twice.
65
+ - Preserve Julia's original marker serialization, truncation, weights, and
66
+ option order. Returned probabilities use the model card presentation rules;
67
+ `logits()` retains raw scores.
68
+
69
+ CPU defaults to Python/PyTorch (`torch`), with no Bend build required. CUDA also
70
+ uses PyTorch. Select `transformer_backend='bend-dense'` explicitly to use the
71
+ optional CPU FP32 Bend encoder. `compile_model=True` works with the default Torch
72
+ backend.
73
+
74
+ ## Bend transformer operations
75
+
76
+ `native/router.bend` implements candidate argmax, numerically stabilized softmax,
77
+ and two-pass LayerNorm (mean, centered variance, affine scale/bias). Balanced
78
+ `Leaf`/`Fork` trees expose candidate reductions. LayerNorm forks over independent
79
+ rows and uses flat tail loops over feature lists within each row, following the
80
+ Bend guide's coarse-work/flat-leaf cost model. All use Bend's own heap. The C adapter transports arrays and owns the ABI; it does
81
+ not duplicate the numerical algorithms.
82
+
83
+ ```python
84
+ from julia.router import BendReducer, FastEngine
85
+
86
+ bend = BendReducer()
87
+ index, probabilities = bend.softmax([1.0, 3.0, -2.0])
88
+ normalized = bend.layernorm([[1.0, 2.0, 3.0]])
89
+
90
+ # Explicit experimental CPU transformer-head backend:
91
+ engine = FastEngine('/path/to/checkpoint', device='cpu',
92
+ transformer_backend='bend', bend_postprocess=True)
93
+
94
+ # All 88 encoder projections of the real checkpoint also execute in Bend:
95
+ # Set JULIA_BEND_THREADS=4 before creating the engine.
96
+ engine = FastEngine('/path/to/checkpoint', device='cpu',
97
+ transformer_backend='bend-dense', bend_postprocess=True)
98
+ ```
99
+
100
+ The experimental head executes its pre-attention and pre-MLP LayerNorms, plus
101
+ scorer LayerNorm, in Bend. Dense projections, attention, and the encoder remain
102
+ PyTorch. This is **not a complete transformer rewrite in Bend**. Bend head math
103
+ is inference-only CPU float32. The CPU library defaults to up to eight available Bend runtime
104
+ workers. Set `JULIA_BEND_THREADS=4` **before the first native call** to test row
105
+ parallelism; the worker count is fixed for the process. Pool sizing depends on the kernel and workload; the older normalization-only
106
+ experiment does not determine the dense backend defaults. Reduction order differs from the
107
+ old tree algorithm and PyTorch: probabilities can differ by floating-point rounding,
108
+ and effectively tied choices may choose a different index.
109
+ Calls share a mutex because Bend's runtime has global state. Instantiate model
110
+ workers in spawned processes; do not fork an active inference process.
111
+
112
+ ### Resident dense projections (CPU default)
113
+
114
+ `bend-dense` executes all 88 encoder projections in Bend. Resident packed FP32
115
+ arrays replace linked weight trees. Contiguous 8×8 tiles expose vector arithmetic;
116
+ coarse parallel ranges end in flat tail loops. Shared input/weight handles are
117
+ read-only, output tiles are disjoint, and all handles are joined after evaluation.
118
+ The bridge packs/transports buffers and checks bounds; the public API validates
119
+ finite values, while engine inference validates weights once and final logits.
120
+
121
+ PyTorch retains embeddings, SDPA, elementwise activations and the selected-output
122
+ decision head. The native pool defaults to up to eight available CPUs; override
123
+ with `JULIA_BEND_THREADS` before the first call. `JULIA_BEND_TILE_GRAIN` overrides
124
+ the adaptive projection-specific chunk size. The snapshot rejects changed weights and must be recreated after mutation.
125
+ Use the training loader to save or train checkpoints, not an installed backend.
126
+
127
+ Packed kernels use
128
+ validated unsafe array sharing and bounded loops; the tree shape proofs do not
129
+ constitute a formal proof of packed-array memory safety or floating-point math.
130
+
131
+ ## Larger choice sets
132
+
133
+ ```python
134
+ from julia.router import Router, FastEngine
135
+ router = Router(FastEngine('/path/to/checkpoint', device='cuda'), survivors=2)
136
+ result = router.route(row_with_up_to_4096_options)
137
+ ```
138
+
139
+ Julia's trained head still supports **2–20** options. Larger *choice* requests
140
+ use batched groups and rerank survivors until a final group remains. A group
141
+ retains only its winner when raw softmax gives it over 95% and every other
142
+ option is below 4.5%; otherwise it retains the configured survivor count.
143
+ This can reduce later model calls for decisive groups, but group probabilities
144
+ are not comparable across different groups. This adds model calls and can discard the correct candidate;
145
+ it is a capacity feature, not a speed or quality guarantee. Final probabilities
146
+ are conditional on `result.candidates`, never a fabricated global distribution.
147
+ `model_rows` and `cache_hits` report aggregate work for the whole `route_many`
148
+ call. Optional `cache_size` caches logits; it defaults to zero. Clear caches
149
+ with `clear_cache()` after changing weights, tokenization or inference settings.
150
+
151
+ ## Tests
152
+
153
+ ```bash
154
+ python -m unittest discover -s julia/router/tests -v
155
+ ```
156
+
157
+ The tests exercise CPU inference and optional native behavior where available.
julia/router/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Python-compatible Julia router powered by compiled Bend trees."""
2
+ from .native import BendReducer
3
+ from .router import Router, RouteResult
4
+
5
+ __all__ = ['BendReducer', 'Router', 'RouteResult', 'FastEngine']
6
+
7
+
8
+ def __getattr__(name):
9
+ if name == 'FastEngine':
10
+ from .engine import FastEngine
11
+ return FastEngine
12
+ raise AttributeError(name)
julia/router/build.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Explicit, reproducible native build: python -m julia.router.build."""
2
+ import argparse
3
+ import os
4
+ import re
5
+ from pathlib import Path
6
+ import shutil
7
+ import subprocess
8
+ import tempfile
9
+
10
+
11
+ def build(output=None, bend=None, native_cpu=False):
12
+ source = Path(__file__).parent / 'native' / 'router.bend'
13
+ bend = bend or shutil.which('bend') or str(Path.home() / '.bend/bin/bend')
14
+ version = subprocess.check_output([bend, 'version'], text=True).strip()
15
+ if not re.search(r'(?<![0-9.])2\.0\.27(?![0-9.])', version):
16
+ raise RuntimeError(f'Native adapter requires Bend 2.0.27; found {version}')
17
+ subprocess.run([bend, str(source.with_name('PROOF.bend'))], check=True)
18
+ output = Path(output or Path(__file__).parent / 'build/libjulia_router.so').resolve()
19
+ output.parent.mkdir(parents=True, exist_ok=True)
20
+ with tempfile.TemporaryDirectory(dir=output.parent) as temp:
21
+ generated = Path(temp) / 'router.c'
22
+ library = Path(temp) / 'router.so'
23
+ subprocess.run([bend, str(source), '-o', str(generated)], check=True)
24
+ emitted = generated.read_text()
25
+ if not all(re.search(pattern, emitted) for pattern in (
26
+ r'#define CUBE_T\s+128', r'#define LINE\s+16',
27
+ r'static u32\s+CUBE_LOG = 7;', r'#define RING_LOG\s+\(17 - CUBE_LOG\)')):
28
+ raise RuntimeError('CPU scheduling layout changed; refusing unsafe native build')
29
+ # The adapter depends on these private generated ABI/ownership contracts.
30
+ for name, arity in [('WINNER', 1), ('SOFTMAX', 1), ('LAYERNORM', 3), ('NORM_ROWS', 3), ('DENSE_TILE', 2), ('DENSE_BATCH', 2), ('PACKED_GEMM', 9)]:
31
+ match = re.search(rf'#define FID_{name} (\d+)', emitted)
32
+ table = re.search(r'FID_ARITY_T\[\] = \{([^}]+)', emitted)
33
+ if not match or not table or int(table[1].split(',')[int(match[1])]) != arity:
34
+ raise RuntimeError(f'Unsupported generated Bend ABI for {name}')
35
+ winner = emitted.split('WL_CASE(FID_WINNER)', 1)[1].split('#endif', 1)[0]
36
+ if 'term_peek(e, _tree_0)' not in winner:
37
+ raise RuntimeError('WINNER ownership changed; refusing unsafe native build')
38
+ tile = emitted.split('WL_CASE(FID_DENSE_TILE)', 1)[1].split('#endif', 1)[0]
39
+ if 'term_peek(e, _weights_0)' not in tile or 'term_peek(e, _ws_0)' not in emitted:
40
+ raise RuntimeError('Tiled weights must be borrowed; refusing unsafe native build')
41
+ batch = emitted.split('WL_CASE(FID_DENSE_BATCH)', 1)[1].split('#endif', 1)[0]
42
+ if 'term_peek(e, _tiles_0)' not in batch:
43
+ raise RuntimeError('Dense input tiles must be borrowed; refusing unsafe native build')
44
+ packed = emitted.split('WL_CASE(FID_PACKED_DOT)', 1)[1].split('#endif', 1)[0]
45
+ if not all(fragment in packed for fragment in ('r0 = _x_0;', 'r1 = _w_0;', 'r2 = _o_0;', 'WL_RETN(3);')):
46
+ raise RuntimeError('Packed result ABI changed; refusing unsafe native build')
47
+ from .specialize import packed_cpu
48
+ generated.write_text(packed_cpu(emitted))
49
+ subprocess.run([os.environ.get('CC', 'clang'), '-O3', '-ffp-contract=fast',
50
+ *(['-march=native'] if native_cpu else []), '-fPIC', '-shared',
51
+ '-pthread', str(generated), '-lm', '-ldl', '-o', str(library)], check=True)
52
+ os.replace(library, output)
53
+ return output
54
+
55
+
56
+ if __name__ == '__main__':
57
+ parser = argparse.ArgumentParser()
58
+ parser.add_argument('--output')
59
+ parser.add_argument('--bend')
60
+ parser.add_argument('--native-cpu', action='store_true', help='Optimize for this CPU; do not distribute to other CPUs')
61
+ args = parser.parse_args()
62
+ print(build(args.output, args.bend, args.native_cpu))
julia/router/encoder.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inference-only ModernBERT path for decision models (no unused outputs)."""
2
+ from types import MethodType
3
+ import torch
4
+ from transformers.modeling_outputs import BaseModelOutput
5
+
6
+
7
+ def _decision_forward(self, input_ids=None, attention_mask=None, **kwargs):
8
+ if self.training or kwargs or input_ids is None or attention_mask is None:
9
+ return self._julia_original_forward(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
10
+ position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
11
+ full_mask, local_mask = self._update_attention_mask(attention_mask, output_attentions=False)
12
+ hidden = self.embeddings(input_ids=input_ids)
13
+ # Upstream iterates config.layer_types (one entry per layer), overwriting
14
+ # the same two dictionary entries 22 times in this checkpoint.
15
+ positions = {kind: self.rotary_emb(hidden, position_ids, kind) for kind in self._julia_attention_types}
16
+ for layer in self.layers:
17
+ hidden = layer(hidden, attention_mask=full_mask, sliding_window_mask=local_mask,
18
+ position_ids=position_ids, cu_seqlens=None, max_seqlen=None,
19
+ position_embeddings=positions[layer.attention_type], output_attentions=False)[0]
20
+ return BaseModelOutput(last_hidden_state=self.final_norm(hidden))
21
+
22
+
23
+ def specialize_decision_encoder(model):
24
+ encoder = model.encoder
25
+ if encoder.config.model_type != 'modernbert' or encoder.config._attn_implementation != 'sdpa':
26
+ return False
27
+ if hasattr(encoder, '_julia_original_forward'):
28
+ return True
29
+ encoder._julia_original_forward = encoder.forward
30
+ encoder._julia_attention_types = tuple(dict.fromkeys(encoder.config.layer_types))
31
+ encoder.forward = MethodType(_decision_forward, encoder)
32
+ return True
julia/router/engine.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Resident CPU/CUDA inference with cached encoding and length-aware batches."""
2
+ from collections import OrderedDict
3
+ import json
4
+ from pathlib import Path
5
+ import threading
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ from ..data import sequence, validate_row
11
+ from ..probabilities import display_probabilities
12
+ from ..inference import TransformerEngine as Engine
13
+
14
+
15
+ class _TokenCache:
16
+ def __init__(self, tokenizer, capacity):
17
+ self.tokenizer, self.capacity = tokenizer, capacity
18
+ self.cache = OrderedDict()
19
+
20
+ def __getattr__(self, name):
21
+ return getattr(self.tokenizer, name)
22
+
23
+ def __call__(self, text, add_special_tokens=False):
24
+ if text not in self.cache:
25
+ ids = self.tokenizer(text, add_special_tokens=False)['input_ids']
26
+ if self.capacity:
27
+ self.cache[text] = tuple(ids)
28
+ while len(self.cache) > self.capacity:
29
+ self.cache.popitem(last=False)
30
+ return {'input_ids': ids}
31
+ self.cache.move_to_end(text)
32
+ return {'input_ids': list(self.cache[text])}
33
+
34
+
35
+ class FastEngine(Engine):
36
+ """Same weights/serialization as Engine; no cached model predictions.
37
+
38
+ Optional torch.compile specializes the transformer, while Bend handles CPU
39
+ softmax/selection via ctypes. CUDA softmax stays on-device to avoid a roundtrip.
40
+ """
41
+ def __init__(self, checkpoint, device='cpu', max_length=None, head_length=256,
42
+ batch_size=16, encoding_cache=2048, token_cache=8192,
43
+ compile_model=False, library=None, bend_postprocess=False, transformer_backend=None,
44
+ strict_encoding=False, marker_only_head=None, memory_map=True, padding_ratio=1.25):
45
+ if not 1 <= padding_ratio <= 16:
46
+ raise ValueError('padding_ratio must be between 1 and 16')
47
+ self.padding_ratio = padding_ratio
48
+ if batch_size < 1 or encoding_cache < 0 or token_cache < 0:
49
+ raise ValueError('Invalid batch/cache size')
50
+ if transformer_backend not in (None, 'torch', 'bend', 'bend-dense'):
51
+ raise ValueError('transformer_backend must be torch, bend, or bend-dense')
52
+ if transformer_backend in ('bend', 'bend-dense') and (str(device) != 'cpu' or compile_model):
53
+ raise ValueError('Bend requires eager CPU inference; compilation requires the torch backend')
54
+ weights = Path(checkpoint) / 'model.safetensors'
55
+ if weights.is_file():
56
+ with weights.open('rb') as stream:
57
+ if stream.read(80).startswith(b'version https://git-lfs.github.com/spec/v1'):
58
+ raise ValueError('Checkpoint contains Git LFS pointers; fetch the real model weights first')
59
+ super().__init__(checkpoint, device, max_length, head_length, memory_map=memory_map)
60
+ self.model.marker_only_head = (self.device.type == 'cpu' if marker_only_head is None else marker_only_head)
61
+ self.strict_encoding = strict_encoding
62
+ self.batch_size = batch_size
63
+ max_length = self.collate.max_length
64
+ self.max_length, self.head_length = max_length, head_length
65
+ self.encoding_cache = encoding_cache
66
+ self._encoded = OrderedDict()
67
+ self._tokens = _TokenCache(self.tokenizer, token_cache)
68
+ self._lock = threading.RLock()
69
+ self.bend = None
70
+ if bend_postprocess and self.device.type == 'cpu':
71
+ from .native import BendReducer
72
+ self.bend = BendReducer(library)
73
+ if transformer_backend is None:
74
+ transformer_backend = 'torch'
75
+ self.transformer_backend = transformer_backend
76
+ if transformer_backend in ('bend', 'bend-dense'):
77
+ if next(self.model.parameters()).dtype != torch.float32:
78
+ raise ValueError('Bend backends require FP32 weights')
79
+ from .native import BendReducer
80
+ from .transformer import install_bend_head
81
+ reducer = self.bend or BendReducer(library)
82
+ if transformer_backend == 'bend':
83
+ install_bend_head(self.model, reducer)
84
+ if transformer_backend == 'bend-dense':
85
+ from .transformer import install_bend_encoder
86
+ self.bend_projection_count = install_bend_encoder(self.model, reducer)
87
+ from .encoder import specialize_decision_encoder
88
+ self.encoder_specialized = specialize_decision_encoder(self.model)
89
+ self.forward = self.model
90
+ if compile_model:
91
+ self.forward = torch.compile(self.model, dynamic=True)
92
+
93
+ def clear_cache(self):
94
+ with self._lock:
95
+ self._encoded.clear()
96
+ self._tokens.cache.clear()
97
+
98
+ def _encode(self, rows):
99
+ result = []
100
+ for i, row in enumerate(rows):
101
+ validate_row(row, i + 1)
102
+ key = json.dumps([self.max_length, self.head_length, self.strict_encoding,
103
+ row['state'], row['question'], row['options'],
104
+ row.get('type', 'choice')], ensure_ascii=False, allow_nan=False)
105
+ encoded = self._encoded.get(key)
106
+ if encoded is None:
107
+ encoded = sequence(self._tokens, row, self.max_length, self.head_length,
108
+ strict=self.strict_encoding)
109
+ if self.encoding_cache:
110
+ self._encoded[key] = encoded
111
+ while len(self._encoded) > self.encoding_cache:
112
+ self._encoded.popitem(last=False)
113
+ else:
114
+ self._encoded.move_to_end(key)
115
+ result.append(encoded)
116
+ return result
117
+
118
+ def encoding_info(self, rows):
119
+ """Audit the same cached encoding used by inference, without retokenizing."""
120
+ if not self.strict_encoding:
121
+ raise ValueError('Lossless encoding audit requires strict_encoding=True')
122
+ with self._lock:
123
+ return [dict(tokens=len(item['ids']), optionTokens=list(item['option_tokens']),
124
+ headLength=self.head_length, stateTruncated=False, optionsTruncated=False)
125
+ for item in self._encode(rows)]
126
+
127
+ def _pack(self, encoded):
128
+ length = min(self.max_length, (max(len(x['ids']) for x in encoded) + 7) // 8 * 8)
129
+ count = max(len(x['markers']) for x in encoded)
130
+ size = len(encoded)
131
+ arena = np.zeros(size * (2 * length + count + 1), dtype=np.int64)
132
+ end = size * length
133
+ ids = arena[:end].reshape(size, length)
134
+ ids.fill(self.tokenizer.pad_token_id)
135
+ attention = arena[end:2 * end].reshape(size, length)
136
+ positions = arena[2 * end:2 * end + size * count].reshape(size, count)
137
+ qtype = arena[-size:]
138
+ mask = np.zeros((size, count), dtype=np.bool_)
139
+ for i, item in enumerate(encoded):
140
+ n, k = len(item['ids']), len(item['markers'])
141
+ ids[i, :n] = item['ids']
142
+ attention[i, :n] = 1
143
+ positions[i, :k] = item['markers']
144
+ mask[i, :k] = True
145
+ qtype[i] = item['qtype']
146
+ host = torch.from_numpy(arena)
147
+ marker_mask = torch.from_numpy(mask)
148
+ if self.device.type == 'cuda':
149
+ host = host.pin_memory().to(self.device, non_blocking=True)
150
+ marker_mask = marker_mask.pin_memory().to(self.device, non_blocking=True)
151
+ return dict(input_ids=host[:end].view(size, length),
152
+ attention_mask=host[end:2 * end].view(size, length),
153
+ marker_pos=host[2 * end:2 * end + size * count].view(size, count),
154
+ qtype=host[-size:], marker_mask=marker_mask)
155
+
156
+ def _batch_indices(self, encoded):
157
+ # Bound padding inflation, not just batch count: a single long request
158
+ # must not make every short request run the entire encoder at its length.
159
+ order = sorted(range(len(encoded)), key=lambda i: len(encoded[i]['ids']))
160
+ group, tokens = [], 0
161
+ for index in order:
162
+ length = len(encoded[index]['ids'])
163
+ if group and (len(group) == self.batch_size or
164
+ (len(group) + 1) * length > self.padding_ratio * (tokens + length)):
165
+ yield group
166
+ group, tokens = [], 0
167
+ group.append(index)
168
+ tokens += length
169
+ if group:
170
+ yield group
171
+
172
+ def _batches(self, encoded):
173
+ for indices in self._batch_indices(encoded):
174
+ batch = self._pack([encoded[i] for i in indices])
175
+ with torch.autocast(device_type=self.device.type, dtype=torch.bfloat16,
176
+ enabled=self.device.type == 'cuda'):
177
+ values = self.forward(**batch)
178
+ # Padding must never win against real very negative logits.
179
+ values = values.masked_fill(~batch['marker_mask'], -torch.inf)
180
+ if not (torch.isfinite(values) | ~batch['marker_mask']).all():
181
+ raise FloatingPointError('Inference returned nonfinite logits')
182
+ yield indices, values
183
+
184
+ @torch.inference_mode()
185
+ def logits(self, rows):
186
+ with self._lock:
187
+ encoded = self._encode(rows)
188
+ result = [None] * len(rows)
189
+ for indices, values in self._batches(encoded):
190
+ host = values.cpu().tolist()
191
+ for i, scores in zip(indices, host):
192
+ result[i] = scores[:len(encoded[i]['markers'])]
193
+ return result
194
+
195
+ @torch.inference_mode()
196
+ def predict(self, rows=None, questions=None, *, state=None, probabilities=True):
197
+ if questions is not None:
198
+ from ..typed import predict_typed
199
+ if rows is not None and state is not None:
200
+ raise ValueError('Pass state either positionally or by keyword, not both')
201
+ return predict_typed(self, state if rows is None else rows, questions)
202
+ if state is not None or rows is None:
203
+ raise ValueError('Provide legacy rows or state with questions')
204
+ with self._lock:
205
+ encoded = self._encode(rows)
206
+ result = [None] * len(rows)
207
+ for indices, values in self._batches(encoded):
208
+ if self.bend is not None:
209
+ host = values.contiguous().numpy()
210
+ for local, i in enumerate(indices):
211
+ scores = host[local, :len(encoded[i]['markers'])]
212
+ if probabilities:
213
+ best, probs = self.bend.softmax(scores)
214
+ else:
215
+ best = self.bend.argmax(scores)
216
+ result[i] = dict(index=best)
217
+ if probabilities:
218
+ result[i]['probabilities'] = display_probabilities(probs.tolist())
219
+ else:
220
+ best_device = values.argmax(-1)
221
+ if probabilities and self.device.type == 'cuda':
222
+ host = torch.cat((best_device[:, None].to(values.dtype),
223
+ values.softmax(-1)), dim=1).cpu().tolist()
224
+ best = [int(row[0]) for row in host]
225
+ probs = [row[1:] for row in host]
226
+ else:
227
+ best = best_device.cpu().tolist()
228
+ probs = values.softmax(-1).tolist() if probabilities else None
229
+ for local, i in enumerate(indices):
230
+ result[i] = dict(index=best[local])
231
+ if probabilities:
232
+ result[i]['probabilities'] = display_probabilities(probs[local][:len(encoded[i]['markers'])])
233
+ return result
julia/router/native.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ctypes boundary; no subprocess or compilation in the request path."""
2
+ import ctypes
3
+ import math
4
+ import os
5
+ from pathlib import Path
6
+
7
+
8
+ class BendReducer:
9
+ def __init__(self, library=None):
10
+ path = Path(library or os.environ.get('JULIA_ROUTER_LIBRARY') or
11
+ Path(__file__).parent / 'build/libjulia_router.so')
12
+ try:
13
+ self._lib = ctypes.CDLL(str(path.resolve()))
14
+ except OSError as error:
15
+ raise RuntimeError(
16
+ f'Cannot load Bend runtime {path.resolve()}. From Julia-1 run '
17
+ 'python -m julia.router.build --native-cpu; or explicitly select '
18
+ 'transformer_backend="torch".') from error
19
+ self._argmax = self._lib.julia_router_argmax
20
+ self._argmax.argtypes = [ctypes.POINTER(ctypes.c_float), ctypes.c_uint32,
21
+ ctypes.POINTER(ctypes.c_uint32)]
22
+ self._argmax.restype = ctypes.c_int
23
+ self._ptr = ctypes.POINTER(ctypes.c_float)
24
+ self._softmax = self._lib.julia_router_softmax
25
+ self._softmax.argtypes = [self._ptr, ctypes.c_uint32, self._ptr, ctypes.POINTER(ctypes.c_uint32)]
26
+ self._softmax.restype = ctypes.c_int
27
+ self._layernorm = self._lib.julia_router_layernorm
28
+ self._layernorm.argtypes = [self._ptr, self._ptr, self._ptr, ctypes.c_uint32,
29
+ ctypes.c_uint32, ctypes.c_float, self._ptr]
30
+ self._layernorm.restype = ctypes.c_int
31
+
32
+ def profile(self, *, enabled=False, reset=False):
33
+ """Process-wide packed projection timings; opt in only for diagnostics."""
34
+ fn = self._lib.julia_router_profile
35
+ fn.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double)]
36
+ fn.restype = None
37
+ values = (ctypes.c_double * 4)()
38
+ fn(enabled, reset, values)
39
+ return dict(zip(('pack_ms', 'execute_ms', 'unpack_ms', 'calls'), values))
40
+
41
+ def argmax(self, scores):
42
+ scores = tuple(scores)
43
+ if not 1 <= len(scores) <= 1048576:
44
+ raise ValueError('Expected 1–1048576 scores')
45
+ if not all(math.isfinite(x) for x in scores):
46
+ raise ValueError('Scores must be finite')
47
+ values = (ctypes.c_float * len(scores))(*scores)
48
+ result = ctypes.c_uint32()
49
+ code = self._argmax(values, len(scores), ctypes.byref(result))
50
+ if code:
51
+ raise ValueError(f'Bend rejected scores (status {code})')
52
+ return result.value
53
+
54
+ def softmax(self, scores):
55
+ import numpy as np
56
+ values = np.ascontiguousarray(scores, dtype=np.float32)
57
+ if values.ndim != 1 or not 1 <= values.size <= 1048576:
58
+ raise ValueError('Expected a nonempty vector of at most 1048576 scores')
59
+ output = np.empty_like(values)
60
+ index = ctypes.c_uint32()
61
+ code = self._softmax(values.ctypes.data_as(self._ptr), values.size,
62
+ output.ctypes.data_as(self._ptr), ctypes.byref(index))
63
+ if code:
64
+ raise ValueError(f'Bend rejected scores (status {code})')
65
+ return index.value, output
66
+
67
+ def layernorm(self, values, gamma=None, beta=None, epsilon=1e-5):
68
+ import numpy as np
69
+ x = np.ascontiguousarray(values, dtype=np.float32)
70
+ if x.ndim < 1 or x.size == 0:
71
+ raise ValueError('Expected a nonempty feature array')
72
+ width = x.shape[-1]
73
+ g = np.ones(width, np.float32) if gamma is None else np.ascontiguousarray(gamma, dtype=np.float32)
74
+ b = np.zeros(width, np.float32) if beta is None else np.ascontiguousarray(beta, dtype=np.float32)
75
+ if g.shape != (width,) or b.shape != (width,):
76
+ raise ValueError('gamma and beta must match the last dimension')
77
+ if x.size > 1048576 or width > 65536:
78
+ raise ValueError('LayerNorm input exceeds native capacity')
79
+ output = np.empty_like(x)
80
+ code = self._layernorm(x.ctypes.data_as(self._ptr), g.ctypes.data_as(self._ptr),
81
+ b.ctypes.data_as(self._ptr), x.size // width, width, epsilon,
82
+ output.ctypes.data_as(self._ptr))
83
+ if code:
84
+ raise ValueError(f'Bend rejected LayerNorm inputs (status {code})')
85
+ return output
86
+
87
+
88
+ class BendMatrix:
89
+ """Resident immutable FP32 projection weights owned by the Bend heap."""
90
+ def __init__(self, weights, reducer=None):
91
+ import numpy as np
92
+ import threading
93
+ import weakref
94
+ self.reducer = reducer or BendReducer()
95
+ self._lock = threading.RLock()
96
+ values = np.ascontiguousarray(weights, dtype=np.float32)
97
+ if values.ndim != 2 or not all(values.shape):
98
+ raise ValueError('Projection weights must be a nonempty matrix')
99
+ self.outputs, self.inputs = values.shape
100
+ lib = self.reducer._lib
101
+ create = lib.julia_router_matrix_create
102
+ create.argtypes = [self.reducer._ptr, ctypes.c_uint32, ctypes.c_uint32]
103
+ create.restype = ctypes.c_void_p
104
+ release = lib.julia_router_matrix_free
105
+ release.argtypes = [ctypes.c_void_p]
106
+ release.restype = None
107
+ self._linear = lib.julia_router_linear
108
+ self._linear.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint32, ctypes.c_void_p]
109
+ self._linear.restype = ctypes.c_int
110
+ self._linear_inference = lib.julia_router_linear_inference
111
+ self._linear_inference.argtypes = self._linear.argtypes
112
+ self._linear_inference.restype = ctypes.c_int
113
+ self._handle = create(values.ctypes.data_as(self.reducer._ptr), self.inputs, self.outputs)
114
+ if not self._handle:
115
+ raise ValueError('Bend rejected projection dimensions or nonfinite weights')
116
+ self._finalize = weakref.finalize(self, release, self._handle)
117
+
118
+ def close(self):
119
+ with self._lock:
120
+ self._finalize()
121
+
122
+ def tensor(self, values, *, validate=True):
123
+ """Fill a contiguous Torch output directly, without NumPy/list/concat wrappers."""
124
+ import torch
125
+ if values.device.type != 'cpu' or values.dtype != torch.float32 or values.shape[-1] != self.inputs:
126
+ raise ValueError('Bend tensor projection requires matching CPU FP32 inputs')
127
+ x = values.contiguous()
128
+ rows = x.numel() // self.inputs
129
+ if not rows:
130
+ raise ValueError('Projection input must be nonempty')
131
+ out = torch.empty((*x.shape[:-1], self.outputs), dtype=x.dtype, device=x.device)
132
+ linear = self._linear if validate else self._linear_inference
133
+ limit = min(1048576 // self.inputs, 1048576 // self.outputs)
134
+ with self._lock:
135
+ if not self._finalize.alive:
136
+ raise RuntimeError('Bend matrix has been closed')
137
+ for start in range(0, rows, limit):
138
+ code = linear(self._handle,
139
+ x.data_ptr() + start * self.inputs * 4,
140
+ min(limit, rows - start),
141
+ out.data_ptr() + start * self.outputs * 4)
142
+ if code:
143
+ raise ValueError(f'Bend projection failed (status {code})')
144
+ return out
145
+
146
+ def __call__(self, values):
147
+ import numpy as np
148
+ x = np.ascontiguousarray(values, dtype=np.float32)
149
+ if x.ndim < 1 or x.shape[-1] != self.inputs or not x.size:
150
+ raise ValueError('Projection input must match resident weights')
151
+ out = np.empty((*x.shape[:-1], self.outputs), dtype=np.float32)
152
+ with self._lock:
153
+ if not self._finalize.alive:
154
+ raise RuntimeError('Bend matrix has been closed')
155
+ code = self._linear(self._handle, x.ctypes.data_as(self.reducer._ptr),
156
+ x.size // self.inputs, out.ctypes.data_as(self.reducer._ptr))
157
+ if code:
158
+ raise ValueError(f'Bend projection failed (status {code})')
159
+ return out
julia/router/native/LAWS.bend ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Base
2
+ import ./router.bend as R
3
+
4
+ # Runtime ABI invariant: each output leaf has exactly one 4x7 tile.
5
+ def output_tiles(result: R.TileResult) -> Nat:
6
+ match result:
7
+ case R.JTLeaf{_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _}:
8
+ 1n
9
+ case R.JTFork{left, right}:
10
+ Nat.add(output_tiles(left), output_tiles(right))
11
+
12
+ def matrix_tiles(weights: R.JuliaMatrix) -> Nat:
13
+ match weights:
14
+ case R.JMLeaf{ws}:
15
+ 1n
16
+ case R.JMFork{left, right}:
17
+ Nat.add(matrix_tiles(left), matrix_tiles(right))
18
+
19
+ # No flat dot-product branch may omit or duplicate an output tile.
20
+ law dot_tile_shape:
21
+ for +xs: R.TileInput
22
+ for ws: R.DenseWeights
23
+ for s0: F32
24
+ for s1: F32
25
+ for s2: F32
26
+ for s3: F32
27
+ for s4: F32
28
+ for s5: F32
29
+ for s6: F32
30
+ for s7: F32
31
+ for s8: F32
32
+ for s9: F32
33
+ for s10: F32
34
+ for s11: F32
35
+ for s12: F32
36
+ for s13: F32
37
+ for s14: F32
38
+ for s15: F32
39
+ for s16: F32
40
+ for s17: F32
41
+ for s18: F32
42
+ for s19: F32
43
+ for s20: F32
44
+ for s21: F32
45
+ for s22: F32
46
+ for s23: F32
47
+ for s24: F32
48
+ for s25: F32
49
+ for s26: F32
50
+ for s27: F32
51
+ {output_tiles(R.dot_tile(xs, ws, s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s20, s21, s22, s23, s24, s25, s26, s27)) == 1n : Nat}
52
+
53
+ # Fork/join must preserve the output tile count for every matrix/input tree.
54
+ law dense_shape:
55
+ for +xs: R.TileInput
56
+ for weights: R.JuliaMatrix
57
+ {output_tiles(R.dense_tile(xs, weights)) == matrix_tiles(weights) : Nat}
julia/router/native/PROOF.bend ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Base
2
+ import ./router.bend as R
3
+ import ./LAWS.bend as Laws
4
+
5
+ def Laws.dot_tile_shape(xs, ws, s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s20, s21, s22, s23, s24, s25, s26, s27):
6
+ match xs ws:
7
+ case R.JTVal{+x0, +x1, +x2, +x3, xt} R.JWVal{+w0, +w1, +w2, +w3, +w4, +w5, +w6, wt}:
8
+ Laws.dot_tile_shape(xt, wt, F32.add(s0, F32.mul(x0, w0)),
9
+ F32.add(s1, F32.mul(x0, w1)),
10
+ F32.add(s2, F32.mul(x0, w2)),
11
+ F32.add(s3, F32.mul(x0, w3)),
12
+ F32.add(s4, F32.mul(x0, w4)),
13
+ F32.add(s5, F32.mul(x0, w5)),
14
+ F32.add(s6, F32.mul(x0, w6)),
15
+ F32.add(s7, F32.mul(x1, w0)),
16
+ F32.add(s8, F32.mul(x1, w1)),
17
+ F32.add(s9, F32.mul(x1, w2)),
18
+ F32.add(s10, F32.mul(x1, w3)),
19
+ F32.add(s11, F32.mul(x1, w4)),
20
+ F32.add(s12, F32.mul(x1, w5)),
21
+ F32.add(s13, F32.mul(x1, w6)),
22
+ F32.add(s14, F32.mul(x2, w0)),
23
+ F32.add(s15, F32.mul(x2, w1)),
24
+ F32.add(s16, F32.mul(x2, w2)),
25
+ F32.add(s17, F32.mul(x2, w3)),
26
+ F32.add(s18, F32.mul(x2, w4)),
27
+ F32.add(s19, F32.mul(x2, w5)),
28
+ F32.add(s20, F32.mul(x2, w6)),
29
+ F32.add(s21, F32.mul(x3, w0)),
30
+ F32.add(s22, F32.mul(x3, w1)),
31
+ F32.add(s23, F32.mul(x3, w2)),
32
+ F32.add(s24, F32.mul(x3, w3)),
33
+ F32.add(s25, F32.mul(x3, w4)),
34
+ F32.add(s26, F32.mul(x3, w5)),
35
+ F32.add(s27, F32.mul(x3, w6)))
36
+ case R.JTVal{_, _, _, _, _} R.JWEnd{}:
37
+ {==}
38
+ case R.JTEnd{} R.JWVal{_, _, _, _, _, _, _, _}:
39
+ {==}
40
+ case R.JTEnd{} R.JWEnd{}:
41
+ {==}
42
+
43
+ def Laws.dense_shape(xs, weights):
44
+ match weights:
45
+ case R.JMLeaf{ws}:
46
+ Laws.dot_tile_shape(xs, ws, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
47
+ case R.JMFork{+left, +right}:
48
+ %Laws.dense_shape(xs, left) : {Nat.add(Laws.output_tiles(R.dense_tile(xs, left)), Laws.output_tiles(R.dense_tile(xs, right))) == Nat.add(_, Laws.matrix_tiles(right)) : Nat}
49
+ %Laws.dense_shape(xs, right) : {Nat.add(Laws.output_tiles(R.dense_tile(xs, left)), Laws.output_tiles(R.dense_tile(xs, right))) == Nat.add(Laws.output_tiles(R.dense_tile(xs, left)), _) : Nat}
50
+ {==}
julia/router/native/bridge.c ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Bend 2.0.27 ABI adapter. Arithmetic lives in router.bend.
2
+ * WINNER borrows its tree; SOFTMAX/LAYERNORM consume it (checked at build).
3
+ * The generated runtime uses process globals, hence the single shared mutex.
4
+ */
5
+ #include <pthread.h>
6
+ #if defined(__AVX2__)
7
+ #include <immintrin.h>
8
+ #endif
9
+ static pthread_mutex_t router_mutex = PTHREAD_MUTEX_INITIALIZER;
10
+ static Corpus router_heap;
11
+ /* Opt-in diagnostics, disabled during ordinary inference. Protected by router_mutex. */
12
+ static bool router_profile_enabled = false;
13
+ static double router_profile_totals[4] = {0}; /* pack, eval, unpack milliseconds; calls */
14
+ static double router_clock_ms(void) {
15
+ struct timespec now;
16
+ clock_gettime(CLOCK_MONOTONIC, &now);
17
+ return (double)now.tv_sec * 1000.0 + (double)now.tv_nsec / 1000000.0;
18
+ }
19
+ void julia_router_profile(int enabled, int reset, double *out) {
20
+ pthread_mutex_lock(&router_mutex);
21
+ if (out) memcpy(out, router_profile_totals, sizeof(router_profile_totals));
22
+ if (reset) memset(router_profile_totals, 0, sizeof(router_profile_totals));
23
+ router_profile_enabled = enabled != 0;
24
+ pthread_mutex_unlock(&router_mutex);
25
+ }
26
+ static Env router_env(void) {
27
+ if (!router_heap) {
28
+ const char *setting = getenv("JULIA_BEND_THREADS");
29
+ long available = cpu_count();
30
+ long threads = setting ? strtol(setting, NULL, 10) : (available < 8 ? available : 8);
31
+ if (threads < 1 || threads > 32) threads = 1;
32
+ /* CPU projections need about two coarse tasks per worker, not the GPU-sized
33
+ * default 16,384-lane frontier. A smaller bag keeps the same total ring
34
+ * capacity (deeper queues) and cuts empty-row scans on every pool turn. */
35
+ CUBE_LOG = 0;
36
+ while ((CUBE_T / LINE) * (1u << CUBE_LOG) < (u32)threads) ++CUBE_LOG;
37
+ const char *cube = getenv("JULIA_BEND_CUBE_LOG");
38
+ if (cube) {
39
+ char *end;
40
+ long value = strtol(cube, &end, 10);
41
+ if (*cube && !*end && value >= (long)CUBE_LOG && value <= 7) CUBE_LOG = value;
42
+ }
43
+ router_heap = corpus_setup(false, threads, 0);
44
+ io_stk = pool_stack();
45
+ }
46
+ return (Env){router_heap, ALC[0]};
47
+ }
48
+ static Term router_tree(Env e, const float *scores, u32 start, u32 end) {
49
+ if (end - start == 1)
50
+ return io_node(e, CID_LEAF, start, f32_rewrap(scores[start]));
51
+ u32 mid = start + (end - start) / 2;
52
+ Term left = router_tree(e, scores, start, mid);
53
+ Term right = router_tree(e, scores, mid, end);
54
+ return io_node(e, CID_FORK, left, right);
55
+ }
56
+ static Term router_eval(Env e, u32 fid, Term tree) {
57
+ Loc task = task_node(e, fid, TERM_HOLE, 0, 0);
58
+ e.mem[task] = tree;
59
+ return corpus_eval(e.mem, term_tsk(fid, task));
60
+ }
61
+ static void router_unpack(Env e, Term tree, float *output) {
62
+ Loc node = term_loc(tree);
63
+ if (term_aux(tree) == CID_LEAF) {
64
+ if (output) output[(u32)e.mem[node]] = f32_unbox(e.mem[node + 1]);
65
+ } else {
66
+ router_unpack(e, e.mem[node], output);
67
+ router_unpack(e, e.mem[node + 1], output);
68
+ }
69
+ heap_free(e, cls_fit(2), node);
70
+ }
71
+ static int router_valid(const float *scores, u32 count) {
72
+ if (!scores || !count || count > 1048576) return -1;
73
+ for (u32 i = 0; i < count; ++i) if (!isfinite(scores[i])) return -2;
74
+ return 0;
75
+ }
76
+ int julia_router_argmax(const float *scores, uint32_t count, uint32_t *index) {
77
+ int status = router_valid(scores, count);
78
+ if (status || !index) return status ? status : -1;
79
+ pthread_mutex_lock(&router_mutex);
80
+ Env e = router_env();
81
+ Term tree = router_tree(e, scores, 0, count);
82
+ Term result = router_eval(e, FID_WINNER, tree);
83
+ *index = (u32)e.mem[term_loc(result)];
84
+ term_drop(e, result);
85
+ router_unpack(e, tree, NULL);
86
+ pthread_mutex_unlock(&router_mutex);
87
+ return 0;
88
+ }
89
+ int julia_router_softmax(const float *scores, uint32_t count, float *out, uint32_t *index) {
90
+ int status = router_valid(scores, count);
91
+ if (status || !out || !index) return status ? status : -1;
92
+ pthread_mutex_lock(&router_mutex);
93
+ Env e = router_env();
94
+ Term tree = router_tree(e, scores, 0, count);
95
+ Term best = router_eval(e, FID_WINNER, tree);
96
+ *index = (u32)e.mem[term_loc(best)];
97
+ term_drop(e, best);
98
+ router_unpack(e, router_eval(e, FID_SOFTMAX, tree), out);
99
+ pthread_mutex_unlock(&router_mutex);
100
+ return router_valid(out, count);
101
+ }
102
+ static Term router_features(Env e, const float *x, const float *g, const float *b, u32 lo, u32 hi) {
103
+ if (hi - lo == 1) {
104
+ Loc node = heap_alloc(e, cls_fit(3));
105
+ e.mem[node] = f32_rewrap(x[lo]);
106
+ e.mem[node + 1] = f32_rewrap(g[lo]);
107
+ e.mem[node + 2] = f32_rewrap(b[lo]);
108
+ return term_ctr(CID_FEATURE, node);
109
+ }
110
+ u32 mid = lo + (hi - lo) / 2;
111
+ Term left = router_features(e, x, g, b, lo, mid);
112
+ Term right = router_features(e, x, g, b, mid, hi);
113
+ return io_node(e, CID_BRANCH, left, right);
114
+ }
115
+ static void router_unfeatures(Env e, Term tree, float *out, u32 lo, u32 hi) {
116
+ Loc node = term_loc(tree);
117
+ if (hi - lo == 1) {
118
+ out[lo] = f32_unbox(e.mem[node]);
119
+ heap_free(e, cls_fit(3), node);
120
+ } else {
121
+ u32 mid = lo + (hi - lo) / 2;
122
+ router_unfeatures(e, e.mem[node], out, lo, mid);
123
+ router_unfeatures(e, e.mem[node + 1], out, mid, hi);
124
+ heap_free(e, cls_fit(2), node);
125
+ }
126
+ }
127
+ static Term router_vector(Env e, const float *x, const float *g, const float *b, u32 width) {
128
+ Term tail = term_ctr(CID_VNIL, 0);
129
+ for (u32 i = width; i-- > 0;) {
130
+ Loc node = heap_alloc(e, cls_fit(4));
131
+ e.mem[node] = f32_rewrap(x[i]);
132
+ e.mem[node + 1] = f32_rewrap(g[i]);
133
+ e.mem[node + 2] = f32_rewrap(b[i]);
134
+ e.mem[node + 3] = tail;
135
+ tail = term_ctr(CID_VCONS, node);
136
+ }
137
+ return tail;
138
+ }
139
+ static Term router_rows(Env e, const float *x, const float *g, const float *b,
140
+ u32 width, u32 lo, u32 hi) {
141
+ if (hi - lo == 1) {
142
+ Loc node = heap_alloc(e, cls_fit(1));
143
+ e.mem[node] = router_vector(e, x + lo * width, g, b, width);
144
+ return term_ctr(CID_NLEAF, node);
145
+ }
146
+ u32 mid = lo + (hi - lo) / 2;
147
+ Term left = router_rows(e, x, g, b, width, lo, mid);
148
+ Term right = router_rows(e, x, g, b, width, mid, hi);
149
+ return io_node(e, CID_NFORK, left, right);
150
+ }
151
+ static void router_unrows(Env e, Term tree, float *out, u32 width, u32 lo, u32 hi) {
152
+ Loc node = term_loc(tree);
153
+ if (hi - lo == 1) {
154
+ Term vector = e.mem[node];
155
+ // The flat affine loop builds the result in reverse order.
156
+ for (u32 i = width; i-- > 0;) {
157
+ Loc item = term_loc(vector);
158
+ out[lo * width + i] = f32_unbox(e.mem[item]);
159
+ vector = e.mem[item + 3];
160
+ heap_free(e, cls_fit(4), item);
161
+ }
162
+ heap_free(e, cls_fit(1), node);
163
+ } else {
164
+ u32 mid = lo + (hi - lo) / 2;
165
+ router_unrows(e, e.mem[node], out, width, lo, mid);
166
+ router_unrows(e, e.mem[node + 1], out, width, mid, hi);
167
+ heap_free(e, cls_fit(2), node);
168
+ }
169
+ }
170
+ int julia_router_layernorm(const float *x, const float *gamma, const float *beta,
171
+ uint32_t rows, uint32_t width, float epsilon, float *out) {
172
+ if (!rows || !width || width > 65536 || rows > 1048576 / width || !out ||
173
+ !isfinite(epsilon) || epsilon <= 0) return -1;
174
+ int status = router_valid(x, rows * width);
175
+ if (!status) status = router_valid(gamma, width);
176
+ if (!status) status = router_valid(beta, width);
177
+ if (status) return status;
178
+ pthread_mutex_lock(&router_mutex);
179
+ Env e = router_env();
180
+ Term tree = router_rows(e, x, gamma, beta, width, 0, rows);
181
+ Loc task = task_node(e, FID_NORM_ROWS, TERM_HOLE, 0, 0);
182
+ e.mem[task] = tree;
183
+ e.mem[task + 1] = f32_rewrap((float)width);
184
+ e.mem[task + 2] = f32_rewrap(epsilon);
185
+ Term result = corpus_eval(e.mem, term_tsk(FID_NORM_ROWS, task));
186
+ router_unrows(e, result, out, width, 0, rows);
187
+ pthread_mutex_unlock(&router_mutex);
188
+ return router_valid(out, rows * width);
189
+ }
190
+
191
+ /* Resident immutable weights are built once and borrowed by every forward. */
192
+ typedef struct { Term tree; u32 inputs; u32 outputs; bool packed; } RouterMatrix;
193
+ static Term router_matrix(Env e, const float *w, u32 inputs, u32 outputs, u32 lo, u32 hi) {
194
+ if (hi - lo == 1) {
195
+ Term tail = term_ctr(CID_JWEND, 0);
196
+ for (u32 j = inputs; j-- > 0;) {
197
+ Loc node = heap_alloc(e, cls_fit(8));
198
+ for (u32 k = 0; k < 7; ++k)
199
+ e.mem[node + k] = f32_rewrap(lo * 7 + k < outputs ? w[(lo * 7 + k) * inputs + j] : 0.f);
200
+ e.mem[node + 7] = tail;
201
+ tail = term_ctr(CID_JWVAL, node);
202
+ }
203
+ Loc leaf = heap_alloc(e, cls_fit(1));
204
+ e.mem[leaf] = tail;
205
+ return term_ctr(CID_JMLEAF, leaf);
206
+ }
207
+ u32 mid = lo + (hi - lo) / 2;
208
+ Term left = router_matrix(e, w, inputs, outputs, lo, mid);
209
+ Term right = router_matrix(e, w, inputs, outputs, mid, hi);
210
+ return io_node(e, CID_JMFORK, left, right);
211
+ }
212
+ static void router_free_matrix(Env e, Term tree) {
213
+ Loc node = term_loc(tree);
214
+ if (term_aux(tree) == CID_JMLEAF) {
215
+ Term ws = e.mem[node];
216
+ while (term_aux(ws) == CID_JWVAL) {
217
+ Loc item = term_loc(ws);
218
+ ws = e.mem[item + 7];
219
+ heap_free(e, cls_fit(8), item);
220
+ }
221
+ heap_free(e, cls_fit(1), node);
222
+ } else {
223
+ router_free_matrix(e, e.mem[node]);
224
+ router_free_matrix(e, e.mem[node + 1]);
225
+ heap_free(e, cls_fit(2), node);
226
+ }
227
+ }
228
+ /* Packed FP32 buffers: padding is explicit because Bend array indices wrap. */
229
+ static Term router_buffer_raw(Env e, u32 cells) {
230
+ Cls depth = cls_fit(cells);
231
+ Loc loc = heap_alloc(e, buf_wcls(depth));
232
+ return term_buf(depth, loc);
233
+ }
234
+ static Term router_packed_weights(Env e, const float *w, u32 inputs, u32 outputs) {
235
+ u32 cols = (outputs + 7) / 8 * 8;
236
+ Term array = router_buffer_raw(e, inputs * cols);
237
+ memset((void *)(e.mem + term_loc(array)), 0, (size_t)inputs * cols * sizeof(float));
238
+ float *data = (float *)(e.mem + term_loc(array));
239
+ for (u32 j = 0; j < inputs; ++j)
240
+ for (u32 col = 0; col < outputs; ++col)
241
+ data[(col / 8 * inputs + j) * 8 + col % 8] = w[col * inputs + j];
242
+ return array;
243
+ }
244
+ /* Layout conversion only: transpose eight FP32 rows without doing arithmetic. */
245
+ static void router_pack_input(float *restrict dst, const float *restrict src, u32 rows, u32 width) {
246
+ u32 row = 0;
247
+ #if defined(__AVX2__)
248
+ for (; row + 8 <= rows; row += 8) {
249
+ u32 j = 0;
250
+ for (; j + 8 <= width; j += 8) {
251
+ __m256 r[8], t[8], v[8];
252
+ for (u32 k = 0; k < 8; ++k) r[k] = _mm256_loadu_ps(src + (row + k) * width + j);
253
+ for (u32 k = 0; k < 8; k += 2) {
254
+ t[k] = _mm256_unpacklo_ps(r[k], r[k+1]);
255
+ t[k+1] = _mm256_unpackhi_ps(r[k], r[k+1]);
256
+ }
257
+ for (u32 k = 0; k < 8; k += 4) {
258
+ v[k] = _mm256_shuffle_ps(t[k], t[k+2], 0x44);
259
+ v[k+1] = _mm256_shuffle_ps(t[k], t[k+2], 0xee);
260
+ v[k+2] = _mm256_shuffle_ps(t[k+1], t[k+3], 0x44);
261
+ v[k+3] = _mm256_shuffle_ps(t[k+1], t[k+3], 0xee);
262
+ }
263
+ for (u32 k = 0; k < 4; ++k) {
264
+ _mm256_storeu_ps(dst + (row / 8 * width + j + k) * 8,
265
+ _mm256_permute2f128_ps(v[k], v[k+4], 0x20));
266
+ _mm256_storeu_ps(dst + (row / 8 * width + j + k + 4) * 8,
267
+ _mm256_permute2f128_ps(v[k], v[k+4], 0x31));
268
+ }
269
+ }
270
+ for (; j < width; ++j)
271
+ for (u32 k = 0; k < 8; ++k) dst[(row / 8 * width + j) * 8 + k] = src[(row+k) * width + j];
272
+ }
273
+ #endif
274
+ for (; row < rows; ++row)
275
+ for (u32 j = 0; j < width; ++j)
276
+ dst[(row / 8 * width + j) * 8 + row % 8] = src[row * width + j];
277
+ }
278
+ static void router_packed_linear(Env e, RouterMatrix *matrix, const float *x, u32 rows, float *out) {
279
+ double begin = router_profile_enabled ? router_clock_ms() : 0.0;
280
+ u32 cols = (matrix->outputs + 7) / 8 * 8;
281
+ u32 padded_rows = (rows + 7) / 8 * 8;
282
+ u32 count = padded_rows / 8 * (cols / 8);
283
+ Term input = router_buffer_raw(e, padded_rows * matrix->inputs);
284
+ Term output = router_buffer_raw(e, padded_rows * cols);
285
+ float *input_data = (float *)(e.mem + term_loc(input));
286
+ if (rows % 8)
287
+ memset(input_data + (rows / 8) * matrix->inputs * 8, 0, matrix->inputs * 8 * sizeof(float));
288
+ router_pack_input(input_data, x, rows, matrix->inputs);
289
+ Loc task = task_node(e, FID_PACKED_GEMM, TERM_HOLE, 0, 0);
290
+ e.mem[task + 0] = input;
291
+ e.mem[task + 1] = matrix->tree;
292
+ e.mem[task + 2] = output;
293
+ e.mem[task + 3] = 0;
294
+ e.mem[task + 4] = count;
295
+ e.mem[task + 5] = cols / 8;
296
+ const char *grain_setting = getenv("JULIA_BEND_TILE_GRAIN");
297
+ u32 automatic_grain = (count + pool_size * 2 - 1) / (pool_size * 2);
298
+ u32 grain = grain_setting ? strtoul(grain_setting, NULL, 10) : automatic_grain;
299
+ if (!grain || grain > 65536) grain = automatic_grain;
300
+ e.mem[task + 6] = grain;
301
+ e.mem[task + 7] = matrix->inputs;
302
+ e.mem[task + 8] = (count <= grain);
303
+ /* PackedBuffers is flattened to three result words by Bend 2.0.27.
304
+ * corpus_eval clears the ready flag but leaves these words intact. The
305
+ * runtime mutex prevents another evaluation from overwriting the mailbox. */
306
+ double dispatched = router_profile_enabled ? router_clock_ms() : 0.0;
307
+ corpus_eval(e.mem, term_tsk(FID_PACKED_GEMM, task));
308
+ double evaluated = router_profile_enabled ? router_clock_ms() : 0.0;
309
+ input = e.mem[H_ROOT_WORD];
310
+ matrix->tree = e.mem[H_ROOT_WORD + 1];
311
+ output = e.mem[H_ROOT_WORD + 2];
312
+ const float *data = (const float *)(e.mem + blk_loc(e.mem, output));
313
+ for (u32 row = 0; row < rows; ++row) {
314
+ const float *tiles = data + (row / 8 * (cols / 8)) * 64 + row % 8 * 8;
315
+ u32 col = 0;
316
+ for (; col + 8 <= matrix->outputs; col += 8)
317
+ memcpy(out + row * matrix->outputs + col, tiles + (col / 8) * 64, 8 * sizeof(float));
318
+ if (col < matrix->outputs)
319
+ memcpy(out + row * matrix->outputs + col, tiles + (col / 8) * 64,
320
+ (matrix->outputs - col) * sizeof(float));
321
+ }
322
+ blk_free(e, input);
323
+ blk_free(e, output);
324
+ if (router_profile_enabled) {
325
+ router_profile_totals[0] += dispatched - begin;
326
+ router_profile_totals[1] += evaluated - dispatched;
327
+ router_profile_totals[2] += router_clock_ms() - evaluated;
328
+ router_profile_totals[3] += 1;
329
+ }
330
+ }
331
+ void *julia_router_matrix_create(const float *weights, u32 inputs, u32 outputs) {
332
+ if (!inputs || !outputs || inputs > 65536 || outputs > 65536 ||
333
+ (u64)inputs * outputs > 16777216) return NULL;
334
+ if (!weights) return NULL;
335
+ for (u64 i = 0; i < (u64)inputs * outputs; ++i) if (!isfinite(weights[i])) return NULL;
336
+ RouterMatrix *matrix = malloc(sizeof(*matrix));
337
+ if (!matrix) return NULL;
338
+ pthread_mutex_lock(&router_mutex);
339
+ Env e = router_env();
340
+ matrix->inputs = inputs;
341
+ matrix->outputs = outputs;
342
+ const char *kernel = getenv("JULIA_BEND_KERNEL");
343
+ matrix->packed = !kernel || strcmp(kernel, "tree") != 0;
344
+ matrix->tree = matrix->packed ? router_packed_weights(e, weights, inputs, outputs)
345
+ : router_matrix(e, weights, inputs, outputs, 0, (outputs + 6) / 7);
346
+ pthread_mutex_unlock(&router_mutex);
347
+ return matrix;
348
+ }
349
+ void julia_router_matrix_free(void *handle) {
350
+ if (!handle) return;
351
+ RouterMatrix *matrix = handle;
352
+ pthread_mutex_lock(&router_mutex);
353
+ if (matrix->packed) blk_free(router_env(), matrix->tree);
354
+ else router_free_matrix(router_env(), matrix->tree);
355
+ pthread_mutex_unlock(&router_mutex);
356
+ free(matrix);
357
+ }
358
+ static void router_tile_result(Env e, Term tree, float *out, u32 rows, u32 outputs, u32 lo, u32 hi) {
359
+ Loc node = term_loc(tree);
360
+ if (hi - lo == 1) {
361
+ for (u32 row = 0; row < rows; ++row)
362
+ for (u32 k = 0; k < 7 && lo * 7 + k < outputs; ++k)
363
+ out[row * outputs + lo * 7 + k] = f32_unbox(e.mem[node + row * 7 + k]);
364
+ heap_free(e, cls_fit(28), node);
365
+ } else {
366
+ u32 mid = lo + (hi - lo) / 2;
367
+ router_tile_result(e, e.mem[node], out, rows, outputs, lo, mid);
368
+ router_tile_result(e, e.mem[node + 1], out, rows, outputs, mid, hi);
369
+ heap_free(e, cls_fit(2), node);
370
+ }
371
+ }
372
+ static Term router_input_tiles(Env e, const float *x, u32 rows, u32 inputs, u32 lo, u32 hi) {
373
+ if (hi - lo == 1) {
374
+ Term xs = term_ctr(CID_JTEND, 0);
375
+ for (u32 i = inputs; i-- > 0;) {
376
+ Loc item = heap_alloc(e, cls_fit(5));
377
+ for (u32 k = 0; k < 4; ++k)
378
+ e.mem[item + k] = f32_rewrap(lo * 4 + k < rows ? x[(lo * 4 + k) * inputs + i] : 0.f);
379
+ e.mem[item + 4] = xs;
380
+ xs = term_ctr(CID_JTVAL, item);
381
+ }
382
+ Loc leaf = heap_alloc(e, cls_fit(1));
383
+ e.mem[leaf] = xs;
384
+ return term_ctr(CID_JILEAF, leaf);
385
+ }
386
+ u32 mid = lo + (hi - lo) / 2;
387
+ Term left = router_input_tiles(e, x, rows, inputs, lo, mid);
388
+ Term right = router_input_tiles(e, x, rows, inputs, mid, hi);
389
+ return io_node(e, CID_JIFORK, left, right);
390
+ }
391
+ static void router_free_tiles(Env e, Term tree) {
392
+ Loc node = term_loc(tree);
393
+ if (term_aux(tree) == CID_JILEAF) {
394
+ Term xs = e.mem[node];
395
+ while (term_aux(xs) == CID_JTVAL) {
396
+ Loc item = term_loc(xs);
397
+ xs = e.mem[item + 4];
398
+ heap_free(e, cls_fit(5), item);
399
+ }
400
+ heap_free(e, cls_fit(1), node);
401
+ } else {
402
+ router_free_tiles(e, e.mem[node]);
403
+ router_free_tiles(e, e.mem[node + 1]);
404
+ heap_free(e, cls_fit(2), node);
405
+ }
406
+ }
407
+ static void router_output_tiles(Env e, Term tree, float *out, u32 rows, u32 outputs, u32 lo, u32 hi) {
408
+ Loc node = term_loc(tree);
409
+ if (hi - lo == 1) {
410
+ u32 count = rows - lo * 4 < 4 ? rows - lo * 4 : 4;
411
+ router_tile_result(e, e.mem[node], out + lo * 4 * outputs, count, outputs, 0, (outputs + 6) / 7);
412
+ heap_free(e, cls_fit(1), node);
413
+ } else {
414
+ u32 mid = lo + (hi - lo) / 2;
415
+ router_output_tiles(e, e.mem[node], out, rows, outputs, lo, mid);
416
+ router_output_tiles(e, e.mem[node + 1], out, rows, outputs, mid, hi);
417
+ heap_free(e, cls_fit(2), node);
418
+ }
419
+ }
420
+ static int router_linear(void *handle, const float *x, u32 rows, float *out, bool validate) {
421
+ if (!handle || !x || !out || !rows) return -1;
422
+ RouterMatrix *matrix = handle;
423
+ if (rows > 1048576 / matrix->inputs || rows > 1048576 / matrix->outputs) return -1;
424
+ int status = validate ? router_valid(x, rows * matrix->inputs) : 0;
425
+ if (status) return status;
426
+ pthread_mutex_lock(&router_mutex);
427
+ Env e = router_env();
428
+ if (matrix->packed) {
429
+ router_packed_linear(e, matrix, x, rows, out);
430
+ pthread_mutex_unlock(&router_mutex);
431
+ return validate ? router_valid(out, rows * matrix->outputs) : 0;
432
+ }
433
+ u32 count = (rows + 3) / 4;
434
+ Term xs = router_input_tiles(e, x, rows, matrix->inputs, 0, count);
435
+ Loc task = task_node(e, FID_DENSE_BATCH, TERM_HOLE, 0, 0);
436
+ e.mem[task] = xs;
437
+ e.mem[task + 1] = matrix->tree;
438
+ Term result = corpus_eval(e.mem, term_tsk(FID_DENSE_BATCH, task));
439
+ router_output_tiles(e, result, out, rows, matrix->outputs, 0, count);
440
+ router_free_tiles(e, xs);
441
+ pthread_mutex_unlock(&router_mutex);
442
+ return validate ? router_valid(out, rows * matrix->outputs) : 0;
443
+ }
444
+
445
+ int julia_router_linear(void *handle, const float *x, u32 rows, float *out) {
446
+ return router_linear(handle, x, rows, out, true);
447
+ }
448
+ /* Internal engine path: weights are validated once, logits at the model boundary.
449
+ * Shape, pointer, lifetime and buffer bounds checks remain mandatory. */
450
+ int julia_router_linear_inference(void *handle, const float *x, u32 rows, float *out) {
451
+ return router_linear(handle, x, rows, out, false);
452
+ }
julia/router/native/router.bend ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Base
2
+
3
+ type Candidates is Data:
4
+ Leaf{index: U32, score: F32}
5
+ Fork{left: Candidates, right: Candidates}
6
+
7
+ def pick(flag: Bool, a: Candidates, b: Candidates) -> Candidates:
8
+ match flag:
9
+ case True{}:
10
+ a
11
+ case False{}:
12
+ b
13
+
14
+ def better(a: Candidates, b: Candidates) -> Candidates:
15
+ match a b:
16
+ case Leaf{+i, +x} Leaf{+j, +y}:
17
+ pick(F32.is_gt(x, y) || (F32.is_eq(x, y) && U32.is_le(i, j)), Leaf{i, x}, Leaf{j, y})
18
+ case _ _:
19
+ a
20
+
21
+ def winner(tree: Candidates) -> Candidates:
22
+ match tree:
23
+ case Leaf{i, x}:
24
+ Leaf{i, x}
25
+ case Fork{left, right}:
26
+ a b = winner(left) winner(right)
27
+ better(a, b)
28
+
29
+ def input() -> IO(Candidates):
30
+ import "./bridge.c"
31
+
32
+ def output(tree: Candidates) -> IO(Unit):
33
+ import "./bridge.c"
34
+
35
+ # Transformer math uses the same affine trees. Forks expose independent work.
36
+ def exponentials(tree: Candidates, +maximum: F32) -> Candidates:
37
+ match tree:
38
+ case Leaf{i, x}:
39
+ Leaf{i, F32.exp(F32.sub(x, maximum))}
40
+ case Fork{left, right}:
41
+ a b = exponentials(left, maximum) exponentials(right, maximum)
42
+ Fork{a, b}
43
+
44
+ def total(tree: Candidates) -> F32:
45
+ match tree:
46
+ case Leaf{i, x}:
47
+ x
48
+ case Fork{left, right}:
49
+ a b = total(left) total(right)
50
+ F32.add(a, b)
51
+
52
+ def divide(tree: Candidates, +sum: F32) -> Candidates:
53
+ match tree:
54
+ case Leaf{i, x}:
55
+ Leaf{i, F32.div(x, sum)}
56
+ case Fork{left, right}:
57
+ a b = divide(left, sum) divide(right, sum)
58
+ Fork{a, b}
59
+
60
+ def softmax_best(tree: Candidates, best: Candidates) -> Candidates:
61
+ match best:
62
+ case Leaf{i, maximum}:
63
+ +values = exponentials(tree, maximum)
64
+ divide(values, total(values))
65
+ case Fork{left, right}:
66
+ tree
67
+
68
+ def softmax(+tree: Candidates) -> Candidates:
69
+ softmax_best(tree, winner(tree))
70
+
71
+ type Features is Data:
72
+ Feature{x: F32, gamma: F32, beta: F32}
73
+ Branch{left: Features, right: Features}
74
+
75
+ def feature_sum(tree: Features) -> F32:
76
+ match tree:
77
+ case Feature{x, gamma, beta}:
78
+ x
79
+ case Branch{left, right}:
80
+ a b = feature_sum(left) feature_sum(right)
81
+ F32.add(a, b)
82
+
83
+ def variance(tree: Features, +mean: F32) -> F32:
84
+ match tree:
85
+ case Feature{x, gamma, beta}:
86
+ F32.square(F32.sub(x, mean))
87
+ case Branch{left, right}:
88
+ a b = variance(left, mean) variance(right, mean)
89
+ F32.add(a, b)
90
+
91
+ def affine(tree: Features, +mean: F32, +scale: F32) -> Features:
92
+ match tree:
93
+ case Feature{x, +gamma, +beta}:
94
+ Feature{F32.add(F32.mul(F32.mul(F32.sub(x, mean), scale), gamma), beta), gamma, beta}
95
+ case Branch{left, right}:
96
+ a b = affine(left, mean, scale) affine(right, mean, scale)
97
+ Branch{a, b}
98
+
99
+ def layernorm(+tree: Features, +count: F32, epsilon: F32) -> Features:
100
+ +mean = F32.div(feature_sum(tree), count)
101
+ scale = F32.div(1.0, F32.sqrt(F32.add(F32.div(variance(tree, mean), count), epsilon)))
102
+ affine(tree, mean, scale)
103
+
104
+ def features() -> IO(Features):
105
+ import "./bridge.c"
106
+
107
+ def write_features(tree: Features) -> IO(Unit):
108
+ import "./bridge.c"
109
+
110
+ # Coarse parallelism: fork over independent rows, flat tail loops within a row.
111
+ # Scalar-level tasks cost more to schedule than the arithmetic they perform.
112
+ type Vector is Data:
113
+ VNil{}
114
+ VCons{x: F32, gamma: F32, beta: F32, next: Vector}
115
+
116
+ type NormRows is Data:
117
+ NLeaf{values: Vector}
118
+ NFork{left: NormRows, right: NormRows}
119
+
120
+ def vector_sum(xs: Vector, acc: F32) -> F32:
121
+ match xs:
122
+ case VNil{}:
123
+ acc
124
+ case VCons{x, g, b, next}:
125
+ vector_sum(next, F32.add(acc, x))
126
+
127
+ def vector_variance(xs: Vector, +mean: F32, acc: F32) -> F32:
128
+ match xs:
129
+ case VNil{}:
130
+ acc
131
+ case VCons{x, g, b, next}:
132
+ vector_variance(next, mean, F32.add(acc, F32.square(F32.sub(x, mean))))
133
+
134
+ def vector_affine(xs: Vector, +mean: F32, +scale: F32, out: Vector) -> Vector:
135
+ match xs:
136
+ case VNil{}:
137
+ out
138
+ case VCons{x, +g, +b, next}:
139
+ value = F32.add(F32.mul(F32.mul(F32.sub(x, mean), scale), g), b)
140
+ vector_affine(next, mean, scale, VCons{value, g, b, out})
141
+
142
+ def norm_vector(+xs: Vector, +count: F32, epsilon: F32) -> Vector:
143
+ +mean = F32.div(vector_sum(xs, 0.0), count)
144
+ scale = F32.div(1.0, F32.sqrt(F32.add(F32.div(vector_variance(xs, mean, 0.0), count), epsilon)))
145
+ vector_affine(xs, mean, scale, VNil{})
146
+
147
+ def norm_rows(xs: NormRows, +count: F32, +epsilon: F32) -> NormRows:
148
+ match xs:
149
+ case NLeaf{values}:
150
+ NLeaf{norm_vector(values, count, epsilon)}
151
+ case NFork{left, right}:
152
+ a b = norm_rows(left, count, epsilon) norm_rows(right, count, epsilon)
153
+ NFork{a, b}
154
+
155
+ def batch_features() -> IO(NormRows):
156
+ import "./bridge.c"
157
+
158
+ def write_batch(tree: NormRows) -> IO(Unit):
159
+ import "./bridge.c"
160
+
161
+ # Resident dense projections. Each leaf computes four output channels in one
162
+ # flat loop; only independent output tiles fork. Inputs and weights are borrowed.
163
+ type DenseWeights is Data:
164
+ JWEnd{}
165
+ JWVal{w0: F32, w1: F32, w2: F32, w3: F32, w4: F32, w5: F32, w6: F32, next: DenseWeights}
166
+
167
+ type JuliaMatrix is Data:
168
+ JMLeaf{weights: DenseWeights}
169
+ JMFork{left: JuliaMatrix, right: JuliaMatrix}
170
+
171
+ def dense_weights() -> IO(JuliaMatrix):
172
+ import "./bridge.c"
173
+
174
+ # A 4x7 tile fits seven weights plus a link in one eight-word heap allocation.
175
+ # Each weight is reused across four tokens; no half-empty 16-word allocations.
176
+ type TileInput is Data:
177
+ JTEnd{}
178
+ JTVal{a: F32, b: F32, c: F32, d: F32, next: TileInput}
179
+
180
+ type TileResult is Data:
181
+ JTLeaf{v0: F32, v1: F32, v2: F32, v3: F32, v4: F32, v5: F32, v6: F32, v7: F32, v8: F32, v9: F32, v10: F32, v11: F32, v12: F32, v13: F32, v14: F32, v15: F32, v16: F32, v17: F32, v18: F32, v19: F32, v20: F32, v21: F32, v22: F32, v23: F32, v24: F32, v25: F32, v26: F32, v27: F32}
182
+ JTFork{left: TileResult, right: TileResult}
183
+
184
+ def dot_tile(xs: TileInput, ws: DenseWeights, s0: F32, s1: F32, s2: F32, s3: F32, s4: F32, s5: F32, s6: F32, s7: F32, s8: F32, s9: F32, s10: F32, s11: F32, s12: F32, s13: F32, s14: F32, s15: F32, s16: F32, s17: F32, s18: F32, s19: F32, s20: F32, s21: F32, s22: F32, s23: F32, s24: F32, s25: F32, s26: F32, s27: F32) -> TileResult:
185
+ match xs ws:
186
+ case JTVal{+x0, +x1, +x2, +x3, xt} JWVal{+w0, +w1, +w2, +w3, +w4, +w5, +w6, wt}:
187
+ dot_tile(xt, wt, F32.add(s0, F32.mul(x0, w0)),
188
+ F32.add(s1, F32.mul(x0, w1)),
189
+ F32.add(s2, F32.mul(x0, w2)),
190
+ F32.add(s3, F32.mul(x0, w3)),
191
+ F32.add(s4, F32.mul(x0, w4)),
192
+ F32.add(s5, F32.mul(x0, w5)),
193
+ F32.add(s6, F32.mul(x0, w6)),
194
+ F32.add(s7, F32.mul(x1, w0)),
195
+ F32.add(s8, F32.mul(x1, w1)),
196
+ F32.add(s9, F32.mul(x1, w2)),
197
+ F32.add(s10, F32.mul(x1, w3)),
198
+ F32.add(s11, F32.mul(x1, w4)),
199
+ F32.add(s12, F32.mul(x1, w5)),
200
+ F32.add(s13, F32.mul(x1, w6)),
201
+ F32.add(s14, F32.mul(x2, w0)),
202
+ F32.add(s15, F32.mul(x2, w1)),
203
+ F32.add(s16, F32.mul(x2, w2)),
204
+ F32.add(s17, F32.mul(x2, w3)),
205
+ F32.add(s18, F32.mul(x2, w4)),
206
+ F32.add(s19, F32.mul(x2, w5)),
207
+ F32.add(s20, F32.mul(x2, w6)),
208
+ F32.add(s21, F32.mul(x3, w0)),
209
+ F32.add(s22, F32.mul(x3, w1)),
210
+ F32.add(s23, F32.mul(x3, w2)),
211
+ F32.add(s24, F32.mul(x3, w3)),
212
+ F32.add(s25, F32.mul(x3, w4)),
213
+ F32.add(s26, F32.mul(x3, w5)),
214
+ F32.add(s27, F32.mul(x3, w6)))
215
+ case _ _:
216
+ JTLeaf{s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s20, s21, s22, s23, s24, s25, s26, s27}
217
+
218
+ def dense_tile(+xs: TileInput, weights: JuliaMatrix) -> TileResult:
219
+ match weights:
220
+ case JMLeaf{ws}:
221
+ dot_tile(xs, ws, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
222
+ case JMFork{left, right}:
223
+ a b = dense_tile(xs, left) dense_tile(xs, right)
224
+ JTFork{a, b}
225
+
226
+ def tile_input() -> IO(TileInput):
227
+ import "./bridge.c"
228
+
229
+ def tile_output(result: TileResult) -> IO(Unit):
230
+ import "./bridge.c"
231
+
232
+ # One fork tree spans token tiles and output tiles; one runtime dispatch per matrix.
233
+ type InputTiles is Data:
234
+ JILeaf{tile: TileInput}
235
+ JIFork{left: InputTiles, right: InputTiles}
236
+
237
+ type OutputTiles is Data:
238
+ JOLeaf{tile: TileResult}
239
+ JOFork{left: OutputTiles, right: OutputTiles}
240
+
241
+ def dense_batch(tiles: InputTiles, +weights: JuliaMatrix) -> OutputTiles:
242
+ match tiles:
243
+ case JILeaf{tile}:
244
+ JOLeaf{dense_tile(tile, weights)}
245
+ case JIFork{left, right}:
246
+ a b = dense_batch(left, weights) dense_batch(right, weights)
247
+ JOFork{a, b}
248
+
249
+ def input_tiles() -> IO(InputTiles):
250
+ import "./bridge.c"
251
+
252
+ def output_tiles(result: OutputTiles) -> IO(Unit):
253
+ import "./bridge.c"
254
+
255
+ # Packed tiles expose contiguous lanes to the native compiler. All arithmetic
256
+ # stays in Bend. Shared inputs are read-only; output tiles are disjoint.
257
+ # Unsafe loops terminate at the positive, validated dimensions in the bridge.
258
+ type Input8 is Data:
259
+ JInput8{v0: F32, v1: F32, v2: F32, v3: F32, v4: F32, v5: F32, v6: F32, v7: F32}
260
+
261
+ type Weight8 is Data:
262
+ JWeight8{v0: F32, v1: F32, v2: F32, v3: F32, v4: F32, v5: F32, v6: F32, v7: F32}
263
+
264
+ type Output64 is Data:
265
+ JOutput64{v0: F32, v1: F32, v2: F32, v3: F32, v4: F32, v5: F32, v6: F32, v7: F32, v8: F32, v9: F32, v10: F32, v11: F32, v12: F32, v13: F32, v14: F32, v15: F32, v16: F32, v17: F32, v18: F32, v19: F32, v20: F32, v21: F32, v22: F32, v23: F32, v24: F32, v25: F32, v26: F32, v27: F32, v28: F32, v29: F32, v30: F32, v31: F32, v32: F32, v33: F32, v34: F32, v35: F32, v36: F32, v37: F32, v38: F32, v39: F32, v40: F32, v41: F32, v42: F32, v43: F32, v44: F32, v45: F32, v46: F32, v47: F32, v48: F32, v49: F32, v50: F32, v51: F32, v52: F32, v53: F32, v54: F32, v55: F32, v56: F32, v57: F32, v58: F32, v59: F32, v60: F32, v61: F32, v62: F32, v63: F32}
266
+
267
+ type PackedBuffers is Type:
268
+ JBuffers{x: Array<Input8>, w: Array<Weight8>, o: Array<Output64>}
269
+
270
+ @unsafe
271
+ def packed_dot(x: Array<Input8>, w: Array<Weight8>, o: Array<Output64>, +row: U32, +col: U32, +cols: U32, +inner: U32, +end: U32, +j: U32, +s0: F32, +s1: F32, +s2: F32, +s3: F32, +s4: F32, +s5: F32, +s6: F32, +s7: F32, +s8: F32, +s9: F32, +s10: F32, +s11: F32, +s12: F32, +s13: F32, +s14: F32, +s15: F32, +s16: F32, +s17: F32, +s18: F32, +s19: F32, +s20: F32, +s21: F32, +s22: F32, +s23: F32, +s24: F32, +s25: F32, +s26: F32, +s27: F32, +s28: F32, +s29: F32, +s30: F32, +s31: F32, +s32: F32, +s33: F32, +s34: F32, +s35: F32, +s36: F32, +s37: F32, +s38: F32, +s39: F32, +s40: F32, +s41: F32, +s42: F32, +s43: F32, +s44: F32, +s45: F32, +s46: F32, +s47: F32, +s48: F32, +s49: F32, +s50: F32, +s51: F32, +s52: F32, +s53: F32, +s54: F32, +s55: F32, +s56: F32, +s57: F32, +s58: F32, +s59: F32, +s60: F32, +s61: F32, +s62: F32, +s63: F32, active: Bool) -> PackedBuffers:
272
+ match active:
273
+ case True{}:
274
+ packed_read_x(Array.get(Input8, x, U32.add(U32.mul(row, inner), j)), w, o, row, col, cols, inner, end, j, s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32, s33, s34, s35, s36, s37, s38, s39, s40, s41, s42, s43, s44, s45, s46, s47, s48, s49, s50, s51, s52, s53, s54, s55, s56, s57, s58, s59, s60, s61, s62, s63)
275
+ case False{}:
276
+ o = Array.set(Output64, o, U32.add(U32.mul(row, cols), col), JOutput64{s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32, s33, s34, s35, s36, s37, s38, s39, s40, s41, s42, s43, s44, s45, s46, s47, s48, s49, s50, s51, s52, s53, s54, s55, s56, s57, s58, s59, s60, s61, s62, s63})
277
+ packed_step(x, w, o, U32.add(U32.add(U32.mul(row, cols), col), 1), end, cols, inner, U32.is_lt(U32.add(U32.add(U32.mul(row, cols), col), 1), end))
278
+
279
+ @unsafe
280
+ def packed_read_x(pair: Array<Input8> & Input8, w: Array<Weight8>, o: Array<Output64>, +row: U32, +col: U32, +cols: U32, +inner: U32, +end: U32, +j: U32, +s0: F32, +s1: F32, +s2: F32, +s3: F32, +s4: F32, +s5: F32, +s6: F32, +s7: F32, +s8: F32, +s9: F32, +s10: F32, +s11: F32, +s12: F32, +s13: F32, +s14: F32, +s15: F32, +s16: F32, +s17: F32, +s18: F32, +s19: F32, +s20: F32, +s21: F32, +s22: F32, +s23: F32, +s24: F32, +s25: F32, +s26: F32, +s27: F32, +s28: F32, +s29: F32, +s30: F32, +s31: F32, +s32: F32, +s33: F32, +s34: F32, +s35: F32, +s36: F32, +s37: F32, +s38: F32, +s39: F32, +s40: F32, +s41: F32, +s42: F32, +s43: F32, +s44: F32, +s45: F32, +s46: F32, +s47: F32, +s48: F32, +s49: F32, +s50: F32, +s51: F32, +s52: F32, +s53: F32, +s54: F32, +s55: F32, +s56: F32, +s57: F32, +s58: F32, +s59: F32, +s60: F32, +s61: F32, +s62: F32, +s63: F32) -> PackedBuffers:
281
+ (x, input) = pair
282
+ JInput8{+x0, +x1, +x2, +x3, +x4, +x5, +x6, +x7} = input
283
+ packed_read_w(Array.get(Weight8, w, U32.add(U32.mul(col, inner), j)), x, o, row, col, cols, inner, end, j, s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32, s33, s34, s35, s36, s37, s38, s39, s40, s41, s42, s43, s44, s45, s46, s47, s48, s49, s50, s51, s52, s53, s54, s55, s56, s57, s58, s59, s60, s61, s62, s63, x0, x1, x2, x3, x4, x5, x6, x7)
284
+
285
+ @unsafe
286
+ def packed_read_w(pair: Array<Weight8> & Weight8, x: Array<Input8>, o: Array<Output64>, +row: U32, +col: U32, +cols: U32, +inner: U32, +end: U32, +j: U32, +s0: F32, +s1: F32, +s2: F32, +s3: F32, +s4: F32, +s5: F32, +s6: F32, +s7: F32, +s8: F32, +s9: F32, +s10: F32, +s11: F32, +s12: F32, +s13: F32, +s14: F32, +s15: F32, +s16: F32, +s17: F32, +s18: F32, +s19: F32, +s20: F32, +s21: F32, +s22: F32, +s23: F32, +s24: F32, +s25: F32, +s26: F32, +s27: F32, +s28: F32, +s29: F32, +s30: F32, +s31: F32, +s32: F32, +s33: F32, +s34: F32, +s35: F32, +s36: F32, +s37: F32, +s38: F32, +s39: F32, +s40: F32, +s41: F32, +s42: F32, +s43: F32, +s44: F32, +s45: F32, +s46: F32, +s47: F32, +s48: F32, +s49: F32, +s50: F32, +s51: F32, +s52: F32, +s53: F32, +s54: F32, +s55: F32, +s56: F32, +s57: F32, +s58: F32, +s59: F32, +s60: F32, +s61: F32, +s62: F32, +s63: F32, +x0: F32, +x1: F32, +x2: F32, +x3: F32, +x4: F32, +x5: F32, +x6: F32, +x7: F32) -> PackedBuffers:
287
+ (w, weight) = pair
288
+ JWeight8{+w0, +w1, +w2, +w3, +w4, +w5, +w6, +w7} = weight
289
+ packed_dot(x, w, o, row, col, cols, inner, end, U32.add(j, 1), F32.add(s0, F32.mul(x0, w0)), F32.add(s1, F32.mul(x0, w1)), F32.add(s2, F32.mul(x0, w2)), F32.add(s3, F32.mul(x0, w3)), F32.add(s4, F32.mul(x0, w4)), F32.add(s5, F32.mul(x0, w5)), F32.add(s6, F32.mul(x0, w6)), F32.add(s7, F32.mul(x0, w7)), F32.add(s8, F32.mul(x1, w0)), F32.add(s9, F32.mul(x1, w1)), F32.add(s10, F32.mul(x1, w2)), F32.add(s11, F32.mul(x1, w3)), F32.add(s12, F32.mul(x1, w4)), F32.add(s13, F32.mul(x1, w5)), F32.add(s14, F32.mul(x1, w6)), F32.add(s15, F32.mul(x1, w7)), F32.add(s16, F32.mul(x2, w0)), F32.add(s17, F32.mul(x2, w1)), F32.add(s18, F32.mul(x2, w2)), F32.add(s19, F32.mul(x2, w3)), F32.add(s20, F32.mul(x2, w4)), F32.add(s21, F32.mul(x2, w5)), F32.add(s22, F32.mul(x2, w6)), F32.add(s23, F32.mul(x2, w7)), F32.add(s24, F32.mul(x3, w0)), F32.add(s25, F32.mul(x3, w1)), F32.add(s26, F32.mul(x3, w2)), F32.add(s27, F32.mul(x3, w3)), F32.add(s28, F32.mul(x3, w4)), F32.add(s29, F32.mul(x3, w5)), F32.add(s30, F32.mul(x3, w6)), F32.add(s31, F32.mul(x3, w7)), F32.add(s32, F32.mul(x4, w0)), F32.add(s33, F32.mul(x4, w1)), F32.add(s34, F32.mul(x4, w2)), F32.add(s35, F32.mul(x4, w3)), F32.add(s36, F32.mul(x4, w4)), F32.add(s37, F32.mul(x4, w5)), F32.add(s38, F32.mul(x4, w6)), F32.add(s39, F32.mul(x4, w7)), F32.add(s40, F32.mul(x5, w0)), F32.add(s41, F32.mul(x5, w1)), F32.add(s42, F32.mul(x5, w2)), F32.add(s43, F32.mul(x5, w3)), F32.add(s44, F32.mul(x5, w4)), F32.add(s45, F32.mul(x5, w5)), F32.add(s46, F32.mul(x5, w6)), F32.add(s47, F32.mul(x5, w7)), F32.add(s48, F32.mul(x6, w0)), F32.add(s49, F32.mul(x6, w1)), F32.add(s50, F32.mul(x6, w2)), F32.add(s51, F32.mul(x6, w3)), F32.add(s52, F32.mul(x6, w4)), F32.add(s53, F32.mul(x6, w5)), F32.add(s54, F32.mul(x6, w6)), F32.add(s55, F32.mul(x6, w7)), F32.add(s56, F32.mul(x7, w0)), F32.add(s57, F32.mul(x7, w1)), F32.add(s58, F32.mul(x7, w2)), F32.add(s59, F32.mul(x7, w3)), F32.add(s60, F32.mul(x7, w4)), F32.add(s61, F32.mul(x7, w5)), F32.add(s62, F32.mul(x7, w6)), F32.add(s63, F32.mul(x7, w7)), U32.is_lt(U32.add(j, 1), inner))
290
+
291
+ def packed_join(a: PackedBuffers, b: PackedBuffers) -> PackedBuffers:
292
+ JBuffers{xa, wa, oa} = a
293
+ JBuffers{xb, wb, ob} = b
294
+ JBuffers{Array.join(Input8, xa, xb), Array.join(Weight8, wa, wb), Array.join(Output64, oa, ob)}
295
+
296
+ @unsafe
297
+ def packed_step(x: Array<Input8>, w: Array<Weight8>, o: Array<Output64>,
298
+ +lo: U32, +hi: U32, +tiles_col: U32, +inner: U32, active: Bool) -> PackedBuffers:
299
+ match active:
300
+ case False{}:
301
+ JBuffers{x, w, o}
302
+ case True{}:
303
+ row = U32.div(lo, tiles_col)
304
+ col = U32.mod(lo, tiles_col)
305
+ packed_dot(x, w, o, row, col, tiles_col, inner, hi, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, True{})
306
+
307
+ @unsafe
308
+ def packed_split(x: Array<Input8> & Array<Input8>, w: Array<Weight8> & Array<Weight8>, o: Array<Output64> & Array<Output64>,
309
+ +lo: U32, +hi: U32, +tiles_col: U32, +grain: U32, +inner: U32) -> PackedBuffers:
310
+ (xa, xb) = x
311
+ (wa, wb) = w
312
+ (oa, ob) = o
313
+ +mid = U32.add(lo, U32.div(U32.sub(hi, lo), 2))
314
+ left right = packed_gemm(xa, wa, oa, lo, mid, tiles_col, grain, inner, U32.is_le(U32.sub(mid, lo), grain)) packed_gemm(xb, wb, ob, mid, hi, tiles_col, grain, inner, U32.is_le(U32.sub(hi, mid), grain))
315
+ packed_join(left, right)
316
+
317
+ @unsafe
318
+ def packed_gemm(x: Array<Input8>, w: Array<Weight8>, o: Array<Output64>,
319
+ +lo: U32, +hi: U32, +tiles_col: U32, +grain: U32, +inner: U32, leaf: Bool) -> PackedBuffers:
320
+ match leaf:
321
+ case True{}:
322
+ row = U32.div(lo, tiles_col)
323
+ col = U32.mod(lo, tiles_col)
324
+ packed_dot(x, w, o, row, col, tiles_col, inner, hi, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, True{})
325
+ case False{}:
326
+ packed_split(Array.fork(Input8, x), Array.fork(Weight8, w), Array.fork(Output64, o), lo, hi, tiles_col, grain, inner)
327
+
328
+ def packed_input() -> IO(Array<Input8>):
329
+ import "./bridge.c"
330
+
331
+ def packed_weights() -> IO(Array<Weight8>):
332
+ import "./bridge.c"
333
+
334
+ def packed_out() -> IO(Array<Output64>):
335
+ import "./bridge.c"
336
+
337
+ def packed_output(result: PackedBuffers) -> IO(Unit):
338
+ import "./bridge.c"
339
+
340
+ def main() -> IO(Unit):
341
+ do IO<Unit>:
342
+ +tree : Candidates <- input()
343
+ output(winner(tree))
344
+ output(softmax(tree))
345
+ vector : Features <- features()
346
+ write_features(layernorm(vector, 384.0, 0.00001))
347
+ rows : NormRows <- batch_features()
348
+ write_batch(norm_rows(rows, 384.0, 0.00001))
349
+ +tile : TileInput <- tile_input()
350
+ +w : JuliaMatrix <- dense_weights()
351
+ tile_output(dense_tile(tile, w))
352
+ tile_output(dense_tile(tile, w))
353
+ +tiles : InputTiles <- input_tiles()
354
+ +matrix : JuliaMatrix <- dense_weights()
355
+ output_tiles(dense_batch(tiles, matrix))
356
+ output_tiles(dense_batch(tiles, matrix))
357
+ px : Array<Input8> <- packed_input()
358
+ pw : Array<Weight8> <- packed_weights()
359
+ po : Array<Output64> <- packed_out()
360
+ packed_output(packed_gemm(px, pw, po, 0, 1, 1, 1, 1, True{}))
julia/router/router.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded Julia inference with a Bend candidate-tree reducer."""
2
+ from collections import OrderedDict
3
+ from dataclasses import dataclass
4
+ import json
5
+ import math
6
+ import threading
7
+
8
+ from ..probabilities import display_probabilities
9
+ from .native import BendReducer
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class RouteResult:
14
+ index: int
15
+ candidates: tuple[int, ...]
16
+ probabilities: tuple[float, ...]
17
+ rounds: int
18
+ model_rows: int
19
+ cache_hits: int
20
+ hierarchical: bool
21
+ # Probabilities are conditional on candidates, never global for a tournament.
22
+ probability_scope: str
23
+
24
+
25
+ class Router:
26
+ """Wrap an Engine-compatible logits(rows) implementation.
27
+
28
+ Up to width options: one unchanged model request. Larger choice requests:
29
+ retain survivors per group and rerank until one final group remains.
30
+ This increases supported option count, not the model's trained capacity.
31
+ """
32
+ def __init__(self, engine, *, library=None, width=20, survivors=2,
33
+ batch_size=16, cache_size=0, max_options=4096):
34
+ for name, value in [('width', width), ('survivors', survivors),
35
+ ('batch_size', batch_size), ('cache_size', cache_size),
36
+ ('max_options', max_options)]:
37
+ if type(value) is not int:
38
+ raise ValueError(f'{name} must be an integer')
39
+ if not 2 <= width <= 20 or not 1 <= survivors < width:
40
+ raise ValueError('Require 2 <= width <= 20 and 1 <= survivors < width')
41
+ if batch_size < 1 or cache_size < 0 or max_options < width:
42
+ raise ValueError('Invalid batch/cache/capacity limit')
43
+ self.engine, self.reducer = engine, BendReducer(library)
44
+ self.width, self.survivors = width, survivors
45
+ self.batch_size, self.cache_size, self.max_options = batch_size, cache_size, max_options
46
+ self._cache = OrderedDict()
47
+ self._lock = threading.RLock()
48
+
49
+ def clear_cache(self):
50
+ """Call after modifying model weights or inference settings."""
51
+ with self._lock:
52
+ self._cache.clear()
53
+
54
+ def _validate(self, row):
55
+ if not isinstance(row, dict):
56
+ raise ValueError('A request must be a dictionary')
57
+ if not isinstance(row.get('state'), (str, dict, list)) or not isinstance(row.get('question'), str):
58
+ raise ValueError('state must be text/JSON and question must be text')
59
+ options = row.get('options')
60
+ if not isinstance(options, list) or not 2 <= len(options) <= self.max_options:
61
+ raise ValueError(f'Expected 2–{self.max_options} options')
62
+ if not all(isinstance(x, str) and x for x in options):
63
+ raise ValueError('Options must be nonempty strings')
64
+ kind = row.get('type', 'choice')
65
+ if kind not in ('choice', 'score', 'noul'):
66
+ raise ValueError('Unknown decision type')
67
+ if kind == 'noul' and len(options) != 2:
68
+ raise ValueError('noul requires [false, true]')
69
+ if kind != 'choice' and len(options) > self.width:
70
+ raise ValueError('Hierarchical routing supports choice decisions only')
71
+ clean = dict(state=row['state'], question=row['question'], options=options, type=kind)
72
+ # Snapshot mutable state; preserve dict order used by Julia serialization.
73
+ return json.loads(json.dumps(clean, ensure_ascii=False, allow_nan=False))
74
+
75
+ def _score(self, jobs):
76
+ values = [None] * len(jobs)
77
+ missing = OrderedDict()
78
+ hits = 0
79
+ for i, row in enumerate(jobs):
80
+ key = json.dumps(row, ensure_ascii=False, separators=(',', ':'), allow_nan=False)
81
+ if key in self._cache:
82
+ values[i] = self._cache[key]
83
+ self._cache.move_to_end(key)
84
+ hits += 1
85
+ elif key in missing:
86
+ missing[key][1].append(i)
87
+ hits += 1
88
+ else:
89
+ missing[key] = (row, [i])
90
+ pending = list(missing.items())
91
+ for offset in range(0, len(pending), self.batch_size):
92
+ chunk = pending[offset:offset + self.batch_size]
93
+ output = list(self.engine.logits([entry[1][0] for entry in chunk]))
94
+ if len(output) != len(chunk):
95
+ raise ValueError('Engine returned the wrong number of rows')
96
+ for (key, (row, indices)), scores in zip(chunk, output):
97
+ scores = tuple(float(x) for x in scores)
98
+ if len(scores) != len(row['options']) or not all(math.isfinite(x) for x in scores):
99
+ raise ValueError('Engine logits must be finite and match option count')
100
+ for i in indices:
101
+ values[i] = scores
102
+ if self.cache_size:
103
+ self._cache[key] = scores
104
+ self._cache.move_to_end(key)
105
+ while len(self._cache) > self.cache_size:
106
+ self._cache.popitem(last=False)
107
+ return values, len(pending), hits
108
+
109
+ @staticmethod
110
+ def _confident_winner(scores, best):
111
+ """Keep one candidate when its local softmax dominates the group."""
112
+ runner_up = max(score for i, score in enumerate(scores) if i != best)
113
+ if runner_up - scores[best] >= math.log(0.045 / 0.95):
114
+ return False
115
+ total = sum(math.exp(score - scores[best]) for score in scores)
116
+ return 1 / total > 0.95 and math.exp(runner_up - scores[best]) / total < 0.045
117
+
118
+ def route(self, row):
119
+ return self.route_many([row])[0]
120
+
121
+ def route_many(self, rows):
122
+ """Batch independent groups across requests; preserve request/option order.
123
+
124
+ Calls on one Router serialize because most model engines and the LRU are
125
+ mutable. The C bridge also serializes access to Bend's global runtime.
126
+ """
127
+ with self._lock:
128
+ requests = [self._validate(row) for row in rows]
129
+ candidates = [list(range(len(row['options']))) for row in requests]
130
+ results = [None] * len(requests)
131
+ rounds = [0] * len(requests)
132
+ model_rows = hits = 0
133
+ while any(result is None for result in results):
134
+ jobs, layout = [], []
135
+ for i, row in enumerate(requests):
136
+ if results[i] is not None:
137
+ continue
138
+ rounds[i] += 1
139
+ current = candidates[i]
140
+ final = len(current) <= self.width
141
+ groups = [current[j:j + self.width] for j in range(0, len(current), self.width)]
142
+ candidates[i] = []
143
+ for group in groups:
144
+ if len(group) == 1:
145
+ candidates[i].extend(group)
146
+ continue
147
+ jobs.append(dict(row, options=[row['options'][k] for k in group]))
148
+ layout.append((i, group, final))
149
+ scored, used, cached = self._score(jobs)
150
+ model_rows += used
151
+ hits += cached
152
+ for (i, group, final), scores in zip(layout, scored):
153
+ best = self.reducer.argmax(scores)
154
+ if final:
155
+ maximum = max(scores)
156
+ weights = [math.exp(x - maximum) for x in scores]
157
+ total = sum(weights)
158
+ results[i] = RouteResult(group[best], tuple(group),
159
+ tuple(display_probabilities([x / total for x in weights])), rounds[i], 0, 0,
160
+ len(requests[i]['options']) > self.width,
161
+ 'final_candidates' if len(requests[i]['options']) > self.width else 'all_options')
162
+ elif self._confident_winner(scores, best):
163
+ candidates[i].append(group[best])
164
+ else:
165
+ remaining = list(range(len(group)))
166
+ chosen = []
167
+ for _ in range(min(self.survivors, len(group))):
168
+ position = self.reducer.argmax([scores[k] for k in remaining])
169
+ chosen.append(group[remaining.pop(position)])
170
+ candidates[i].extend(sorted(chosen))
171
+ # These counters are shared batch totals, not per-request attribution.
172
+ from dataclasses import replace
173
+ return [replace(result, model_rows=model_rows, cache_hits=hits) for result in results]
julia/router/specialize.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounds/alias specialization for the validated packed Bend CPU entry point.
2
+
3
+ Arithmetic and iteration order remain generated from router.bend. This pass is
4
+ valid only for bridge.c's distinct packed buffers and checked tile dimensions.
5
+ """
6
+ import re
7
+
8
+
9
+ def packed_cpu(source):
10
+ marker = ' WL_CASE(FID_PACKED_DOT)'
11
+ start = source.index(marker)
12
+ stop = source.index('#endif', start)
13
+ body = source[start:stop]
14
+ # Do not generalize this to Array.get: ordinary Bend arrays wrap indices.
15
+ # The bridge pads the full tile ranges and enforces positive bounded sizes.
16
+ specs = {'x': ('const ', 3), 'w': ('const ', 3), 'o': ('', 6)}
17
+ declarations = []
18
+ for name, (qualifier, shift) in specs.items():
19
+ var = f'_{name}_0'
20
+ locs = re.findall(rf'Term (_at_\d+) = blk_loc\(e.mem, {var}\);', body)
21
+ if len(locs) != 1:
22
+ raise RuntimeError(f'Unsupported packed {name} buffer lowering')
23
+ loc = locs[0]
24
+ declarations.append(f' {qualifier}u32a *restrict julia_{name} = '
25
+ f'({qualifier}u32a *)(e.mem + blk_loc(e.mem, {var}));')
26
+ body = body.replace(f'Term {loc} = blk_loc(e.mem, {var});', '')
27
+ pattern = rf'blk_at\({var}, (.+), {shift}\)'
28
+ body, count = re.subn(pattern, rf'((u32)(\1) << {shift})', body)
29
+ if count != 1:
30
+ raise RuntimeError(f'Unsupported packed {name} index lowering')
31
+ body = re.sub(rf'blk_read\(e.mem, 0, {loc}, ([^)]+)\)',
32
+ rf'julia_{name}[\1]', body)
33
+ body = re.sub(rf'blk_write\(e.mem, 0, {loc}, ([^,]+), ([^)]+)\);',
34
+ rf'julia_{name}[\1] = \2;', body)
35
+ if 'blk_at(' in body or 'blk_read(' in body or 'blk_write(' in body:
36
+ raise RuntimeError('Unrecognized packed buffer access; refusing specialization')
37
+ body = body.replace(' WL_OPEN', '\n'.join(declarations) + '\n WL_OPEN', 1)
38
+ return source[:start] + body + source[stop:]
julia/router/tests/synthetic.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic RANDOM-weight fixtures, never trained-quality evidence."""
2
+ from pathlib import Path
3
+
4
+
5
+ def make_checkpoint(directory, *, tiny=False):
6
+ import torch
7
+ from tokenizers import Tokenizer
8
+ from tokenizers.models import WordLevel
9
+ from tokenizers.pre_tokenizers import Whitespace
10
+ from transformers import PreTrainedTokenizerFast, ModernBertConfig, AutoModel
11
+ from julia.model import JuliaDecisionModel
12
+ root = Path(directory)
13
+ torch.manual_seed(42)
14
+ width, layers, heads = (64, 2, 2) if tiny else (384, 22, 6)
15
+ vocabulary = {'[PAD]': 0, '[CLS]': 1, '[SEP]': 2, '[UNK]': 3, '[MASK]': 4}
16
+ vocabulary.update({f'word{i}': i + 5 for i in range(507)})
17
+ backend = Tokenizer(WordLevel(vocabulary, unk_token='[UNK]'))
18
+ backend.pre_tokenizer = Whitespace()
19
+ tokenizer = PreTrainedTokenizerFast(tokenizer_object=backend, pad_token='[PAD]',
20
+ cls_token='[CLS]', sep_token='[SEP]', unk_token='[UNK]', mask_token='[MASK]')
21
+ tokenizer.save_pretrained(root / 'tokenizer')
22
+ config = ModernBertConfig(vocab_size=512, hidden_size=width,
23
+ intermediate_size=width * 3, num_hidden_layers=layers, num_attention_heads=heads,
24
+ max_position_embeddings=1024, local_attention=128, global_attn_every_n_layers=3,
25
+ pad_token_id=0, cls_token_id=1, sep_token_id=2, reference_compile=False)
26
+ encoder = AutoModel.from_config(config, attn_implementation='sdpa')
27
+ model = JuliaDecisionModel(encoder, head_layers=2)
28
+ model.save_pretrained(root)
29
+ return root
30
+
31
+
32
+ def sample_rows(count=16):
33
+ lengths = [8, 160, 24, 96]
34
+ return [dict(state=' '.join(f'word{(j + i) % 500}' for j in range(lengths[i % 4])),
35
+ question='Choose the matching option', type='choice',
36
+ options=[f'word{k + i}' for k in range(2 + i % 7)]) for i in range(count)]
julia/router/tests/test_engine.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tempfile
2
+ import unittest
3
+ from unittest.mock import patch
4
+ import numpy as np
5
+ import torch
6
+
7
+ from julia.data import Collator, sequence
8
+ from julia.inference import TransformerEngine as Engine
9
+ from julia.router.engine import FastEngine
10
+ from julia.router.native import BendReducer
11
+ from synthetic import make_checkpoint, sample_rows
12
+
13
+
14
+ class NativeMathTests(unittest.TestCase):
15
+ def test_transformer_math(self):
16
+ reducer = BendReducer()
17
+ rng = np.random.default_rng(42)
18
+ for width in [1, 7, 64, 384]:
19
+ x = rng.normal(size=(3, width)).astype('float32')
20
+ gamma = rng.normal(size=width).astype('float32')
21
+ beta = rng.normal(size=width).astype('float32')
22
+ expected = torch.nn.functional.layer_norm(torch.from_numpy(x), (width,),
23
+ torch.from_numpy(gamma), torch.from_numpy(beta)).numpy()
24
+ np.testing.assert_allclose(reducer.layernorm(x, gamma, beta), expected, atol=2e-6, rtol=2e-5)
25
+ for row in x:
26
+ index, probs = reducer.softmax(row)
27
+ self.assertEqual(index, int(row.argmax()))
28
+ np.testing.assert_allclose(probs, torch.from_numpy(row).softmax(-1).numpy(), atol=2e-7)
29
+ _, probabilities = reducer.softmax(np.array([10000, 10001, -10000], np.float32))
30
+ self.assertAlmostEqual(float(probabilities.sum()), 1.0)
31
+
32
+ def test_resident_dense_tiles_reuse_and_partial_edges(self):
33
+ from julia.router.native import BendMatrix
34
+ rng = np.random.default_rng(52)
35
+ for inputs, outputs, rows in [(1, 1, 1), (7, 5, 9), (64, 17, 7), (33, 65, 19), (384, 1152, 5)]:
36
+ weights = rng.normal(size=(outputs, inputs)).astype('float32')
37
+ values = rng.normal(size=(rows, inputs)).astype('float32')
38
+ matrix = BendMatrix(weights)
39
+ reference = values @ weights.T
40
+ first = matrix(values)
41
+ np.testing.assert_allclose(first, reference, atol=1e-4, rtol=1e-4)
42
+ for _ in range(8):
43
+ np.testing.assert_array_equal(matrix(values), first)
44
+ with self.assertRaises(ValueError): matrix(np.ones((2, inputs + 1), np.float32))
45
+ with self.assertRaises(ValueError): matrix(np.full((1, inputs), np.nan, np.float32))
46
+ matrix.close()
47
+ matrix.close()
48
+ with self.assertRaises(RuntimeError): matrix(values)
49
+ with self.assertRaises(ValueError): BendMatrix([[float('nan')]])
50
+
51
+ def test_tensor_chunks_and_opt_in_native_profile(self):
52
+ from julia.router.native import BendMatrix
53
+ reducer = BendReducer()
54
+ weights = np.random.default_rng(8).normal(size=(257, 3)).astype('float32')
55
+ matrix = BendMatrix(weights, reducer)
56
+ # Noncontiguous input and > 1M output cells require two native chunks.
57
+ values = torch.arange(4090 * 6, dtype=torch.float32).reshape(4090, 6)[:, ::2] / 1000
58
+ try:
59
+ reducer.profile(enabled=True, reset=True)
60
+ actual = matrix.tensor(values)
61
+ measured = reducer.profile(enabled=False)
62
+ self.assertEqual(measured['calls'], 2)
63
+ self.assertTrue(all(measured[k] >= 0 for k in ('pack_ms', 'execute_ms', 'unpack_ms')))
64
+ torch.testing.assert_close(actual, values @ torch.from_numpy(weights).T, rtol=1e-5, atol=1e-5)
65
+ matrix.tensor(values[:1])
66
+ self.assertEqual(reducer.profile(), measured)
67
+ with self.assertRaises(ValueError):
68
+ matrix.tensor(torch.full((1, 3), float('nan')))
69
+ finally:
70
+ reducer.profile(enabled=False, reset=True)
71
+ matrix.close()
72
+
73
+ def test_layernorm_parallel_callers_and_large_rows(self):
74
+ import concurrent.futures
75
+ reducer = BendReducer()
76
+ rng = np.random.default_rng(19)
77
+ values = [rng.normal(size=(rows, 384)).astype('float32') for rows in (1, 7, 32, 128)]
78
+ references = [torch.nn.functional.layer_norm(torch.from_numpy(x), (384,)).numpy() for x in values]
79
+ with concurrent.futures.ThreadPoolExecutor(4) as pool:
80
+ actual = list(pool.map(reducer.layernorm, values * 8))
81
+ for i, result in enumerate(actual):
82
+ np.testing.assert_allclose(result, references[i % len(values)], atol=3e-6, rtol=2e-5)
83
+
84
+ def test_packed_matrix_concurrent_owners(self):
85
+ from concurrent.futures import ThreadPoolExecutor
86
+ from julia.router.native import BendMatrix
87
+ rng = np.random.default_rng(2026)
88
+ weights = [rng.normal(size=(n, 33)).astype('float32') for n in (5, 17, 128)]
89
+ matrices = [BendMatrix(w) for w in weights]
90
+ values = rng.normal(size=(19, 33)).astype('float32')
91
+ try:
92
+ with ThreadPoolExecutor(6) as pool:
93
+ results = list(pool.map(lambda i: matrices[i % 3](values), range(96)))
94
+ for i, actual in enumerate(results):
95
+ np.testing.assert_allclose(actual, values @ weights[i % 3].T, atol=2e-5, rtol=2e-5)
96
+ finally:
97
+ for matrix in matrices:
98
+ matrix.close()
99
+
100
+ def test_rejected_native_math(self):
101
+ reducer = BendReducer()
102
+ for x in [[], [float('nan')], [float('inf')]]:
103
+ with self.assertRaises(ValueError):
104
+ reducer.softmax(x)
105
+ for kwargs in [dict(epsilon=0), dict(gamma=[1]), dict(beta=[0]), dict(epsilon=float('nan'))]:
106
+ with self.assertRaises(ValueError):
107
+ reducer.layernorm([[1, 2, 3]], **kwargs)
108
+
109
+
110
+ class ProbabilityDisplayTests(unittest.TestCase):
111
+ def test_rounds_decisive_answer_to_certain(self):
112
+ from julia.probabilities import display_probabilities
113
+
114
+ self.assertEqual(display_probabilities([0.955, 0.044, 0.001]), [1.0, 0.0, 0.0])
115
+ self.assertNotEqual(display_probabilities([0.951, 0.049]), [1.0, 0.0])
116
+
117
+ def test_redistributes_sub_one_percent_values(self):
118
+ from julia.probabilities import display_probabilities
119
+
120
+ result = display_probabilities([0.6, 0.395, 0.005])
121
+ self.assertEqual(result[2], 0.0)
122
+ self.assertAlmostEqual(sum(result), 1.0)
123
+ self.assertAlmostEqual(result[0] / result[1], 0.6 / 0.395)
124
+
125
+
126
+ class InputValidationTests(unittest.TestCase):
127
+ def test_public_loader_rejects_invalid_backend(self):
128
+ from julia import load_model
129
+ from julia.inference import Engine
130
+
131
+ self.assertIs(load_model, Engine)
132
+ with self.assertRaisesRegex(ValueError, 'backend'):
133
+ load_model('unused', backend='unknown')
134
+
135
+ def test_rejects_malformed_requests(self):
136
+ from julia.data import validate_row
137
+
138
+ valid = {'state': 'context', 'question': 'Choose', 'options': ['A', 'B']}
139
+ for row in (None, [], {**valid, 'teacher_logits': 'bad'},
140
+ {**valid, 'teacher_logits': [0.0, float('nan')]},
141
+ {**valid, 'teacher_logits': [True, 0.0]}):
142
+ with self.subTest(row=row), self.assertRaises(ValueError):
143
+ validate_row(row, 1)
144
+
145
+
146
+ class InferenceTests(unittest.TestCase):
147
+ @classmethod
148
+ def setUpClass(cls):
149
+ torch.set_num_threads(2)
150
+ cls.temp = tempfile.TemporaryDirectory()
151
+ cls.path = make_checkpoint(cls.temp.name, tiny=True)
152
+ cls.baseline = Engine(cls.path, device='cpu')
153
+ with patch('julia.router.native.BendReducer', side_effect=AssertionError('Default CPU must not load Bend')):
154
+ cls.fast = FastEngine(cls.path, device='cpu', batch_size=2)
155
+ cls.rows = sample_rows(5)
156
+ cls.rows[0]['state'] = {'text': 'Olá 世界 [MASK]', 'items': [1, 2]}
157
+
158
+ @classmethod
159
+ def tearDownClass(cls):
160
+ del cls.baseline, cls.fast
161
+ cls.temp.cleanup()
162
+
163
+ def test_modernbert_decision_encoder_deduplicates_rope(self):
164
+ from transformers import ModernBertConfig, ModernBertModel
165
+ from julia.model import JuliaDecisionModel
166
+ from julia.router.encoder import specialize_decision_encoder
167
+ config = ModernBertConfig(vocab_size=64, pad_token_id=0, bos_token_id=1, eos_token_id=2, hidden_size=32, intermediate_size=64,
168
+ num_hidden_layers=4, num_attention_heads=4, max_position_embeddings=128,
169
+ local_attention=16, global_attn_every_n_layers=3, attention_dropout=0.,
170
+ embedding_dropout=0., mlp_dropout=0.)
171
+ config._attn_implementation = 'sdpa'
172
+ model = JuliaDecisionModel(ModernBertModel(config), head_layers=0).eval()
173
+ ids = torch.arange(24).reshape(2,12) % 64
174
+ mask = torch.ones_like(ids); mask[1,8:] = 0
175
+ calls=[]
176
+ hook=model.encoder.rotary_emb.register_forward_hook(lambda *args: calls.append(1))
177
+ with torch.inference_mode():
178
+ expected=model.encoder(input_ids=ids,attention_mask=mask).last_hidden_state
179
+ self.assertEqual(len(calls), 4)
180
+ calls.clear()
181
+ self.assertTrue(specialize_decision_encoder(model))
182
+ actual=model.encoder(input_ids=ids,attention_mask=mask).last_hidden_state
183
+ self.assertEqual(len(calls), 2)
184
+ torch.testing.assert_close(actual, expected, rtol=0, atol=0)
185
+ hook.remove()
186
+
187
+ def test_default_backend_and_padding_budget(self):
188
+ self.assertEqual(self.fast.transformer_backend, 'torch')
189
+ self.assertIsNone(self.fast.bend)
190
+ self.assertFalse(hasattr(self.fast, 'bend_projection_count'))
191
+ rows = [dict(self.rows[0], state='short'), dict(self.rows[1], state='long context ' * 100),
192
+ dict(self.rows[2], state='another short state')]
193
+ encoded = self.fast._encode(rows)
194
+ groups = list(self.fast._batch_indices(encoded))
195
+ self.assertEqual(sorted(i for group in groups for i in group), list(range(3)))
196
+ for group in groups:
197
+ lengths = [len(encoded[i]['ids']) for i in group]
198
+ self.assertLessEqual(max(lengths) * len(group), self.fast.padding_ratio * sum(lengths))
199
+ actual = self.fast.predict(rows)
200
+ expected = self.baseline.predict(rows)
201
+ for a, b in zip(actual, expected):
202
+ np.testing.assert_allclose(a['probabilities'], b['probabilities'], atol=2e-6)
203
+
204
+ def test_lfs_pointer_error(self):
205
+ from pathlib import Path
206
+ with tempfile.TemporaryDirectory() as directory:
207
+ (Path(directory) / 'model.safetensors').write_text('version https://git-lfs.github.com/spec/v1\n')
208
+ with self.assertRaisesRegex(ValueError, 'Git LFS pointers'):
209
+ FastEngine(directory)
210
+
211
+ def test_serialization_and_pack(self):
212
+ encoded = self.fast._encode(self.rows)
213
+ self.assertEqual(encoded, [sequence(self.baseline.tokenizer, row) for row in self.rows])
214
+ packed = self.fast._pack(encoded)
215
+ reference = Collator(self.baseline.tokenizer, 1024, 256)(self.rows)
216
+ for name in packed:
217
+ self.assertTrue(torch.equal(packed[name], reference[name]), name)
218
+ self.assertEqual(self.fast.predict([]), [])
219
+ self.assertEqual(self.fast.logits([]), [])
220
+
221
+ def test_inference_collation_omits_training_tensors(self):
222
+ rows = [dict(row, target=0, teacher_logits=[0.] * len(row['options']))
223
+ for row in self.rows]
224
+ collate = self.baseline.collate
225
+ training = collate(rows)
226
+ inference = collate(rows, include_targets=False)
227
+ self.assertIn('labels', training)
228
+ self.assertIn('teacher_logits', training)
229
+ self.assertEqual(set(training) - set(inference), {'labels', 'teacher_logits'})
230
+ for name, value in inference.items():
231
+ self.assertTrue(torch.equal(value, training[name]), name)
232
+ self.assertEqual(self.baseline.predict(rows), self.baseline.predict(self.rows))
233
+
234
+ def test_nonfinite_real_scores_are_rejected(self):
235
+ original = self.fast.forward
236
+ try:
237
+ for invalid in (float('nan'), float('inf'), -float('inf')):
238
+ def forward(**batch):
239
+ result = torch.zeros_like(batch['marker_pos'], dtype=torch.float32)
240
+ result[0, 0] = invalid
241
+ return result
242
+ self.fast.forward = forward
243
+ with self.assertRaises(FloatingPointError):
244
+ self.fast.predict(self.rows)
245
+ finally:
246
+ self.fast.forward = original
247
+
248
+ def test_memory_mapped_checkpoint_dtype_and_logits(self):
249
+ from julia.model import JuliaDecisionModel
250
+ for dtype in (torch.float32, torch.bfloat16):
251
+ with tempfile.TemporaryDirectory() as directory:
252
+ model = JuliaDecisionModel.from_pretrained(self.path).to(dtype=dtype)
253
+ model.save_pretrained(directory)
254
+ loaded = JuliaDecisionModel.from_pretrained(directory, memory_map=True)
255
+ copied = JuliaDecisionModel.from_pretrained(directory, memory_map=False)
256
+ for name, value in loaded.state_dict().items():
257
+ self.assertEqual(value.dtype, copied.state_dict()[name].dtype)
258
+ torch.testing.assert_close(value, copied.state_dict()[name], rtol=0, atol=0)
259
+ if dtype == torch.float32:
260
+ batch = self.baseline.collate(self.rows)
261
+ with torch.inference_mode():
262
+ torch.testing.assert_close(loaded.eval()(**batch), copied.eval()(**batch), rtol=0, atol=0)
263
+
264
+ def test_selected_head_scores_actions_and_training(self):
265
+ model = self.baseline.model
266
+ batch = self.baseline.collate(self.rows)
267
+ batch['qtype'] = torch.arange(len(self.rows)) % 3
268
+ with torch.inference_mode():
269
+ model.marker_only_head = False
270
+ expected = model(**batch, return_actions=True)
271
+ model.marker_only_head = True
272
+ actual = model(**batch, return_actions=True)
273
+ for a, b in zip(expected, actual):
274
+ torch.testing.assert_close(a, b, atol=2e-6, rtol=2e-5)
275
+ # Training must retain the original full-sequence/dropout path.
276
+ model.train()
277
+ torch.manual_seed(123)
278
+ model.marker_only_head = False
279
+ expected = model(**batch)
280
+ torch.manual_seed(123)
281
+ model.marker_only_head = True
282
+ actual = model(**batch)
283
+ torch.testing.assert_close(expected, actual, atol=0, rtol=0)
284
+ actual.sum().backward()
285
+ self.assertTrue(torch.isfinite(model.scorer[-1].weight.grad).all())
286
+ model.zero_grad(set_to_none=True)
287
+ model.eval()
288
+ model.marker_only_head = False
289
+
290
+ def test_strict_encoding_reuses_audit_and_rejects_loss(self):
291
+ engine = FastEngine(self.path, device='cpu', strict_encoding=True)
292
+ row = dict(self.rows[1], state='word1 word2')
293
+ audit = engine.encoding_info([row])[0]
294
+ self.assertFalse(audit['stateTruncated'])
295
+ encoded = next(iter(engine._encoded.values()))
296
+ engine.predict([row])
297
+ self.assertIs(next(iter(engine._encoded.values())), encoded)
298
+ for bad in [dict(row, state='[MASK]'),
299
+ dict(row, state={'value': '[MASK]'}),
300
+ dict(row, options=['word1 ' * 49, 'word2']),
301
+ dict(row, state='word1 ' * 2000)]:
302
+ with self.assertRaises(ValueError):
303
+ engine.predict([bad])
304
+ # Changes in the encoding budget must not reuse stale cached IDs.
305
+ engine.max_length = 32
306
+ with self.assertRaises(ValueError):
307
+ engine.predict([dict(row, state='word1 ' * 100)])
308
+ engine.head_length = 16
309
+ with self.assertRaises(ValueError):
310
+ engine.predict([dict(row, question='word1 ' * 40)])
311
+
312
+ def test_inference_parity_and_order(self):
313
+ reference = self.baseline.predict(self.rows)
314
+ actual = self.fast.predict(self.rows)
315
+ self.assertEqual([x['index'] for x in reference], [x['index'] for x in actual])
316
+ for a, b in zip(reference, actual):
317
+ np.testing.assert_allclose(a['probabilities'], b['probabilities'], atol=2e-6)
318
+ self.assertEqual(self.fast.predict(self.rows, probabilities=False),
319
+ [dict(index=x['index']) for x in actual])
320
+ self.assertTrue(self.fast._encoded)
321
+ self.fast.clear_cache()
322
+ self.assertFalse(self.fast._encoded)
323
+ self.assertFalse(self.fast._tokens.cache)
324
+
325
+ def test_bend_transformer_parity(self):
326
+ bend = FastEngine(self.path, device='cpu', batch_size=2,
327
+ transformer_backend='bend', bend_postprocess=True)
328
+ reference = self.baseline.predict(self.rows)
329
+ actual = bend.predict(self.rows)
330
+ # Different reduction orders can break an exact FP32 tie. Require the
331
+ # selected reference probability to be within tolerance of its maximum.
332
+ for a, b in zip(reference, actual):
333
+ p = a['probabilities']
334
+ self.assertLessEqual(max(p) - p[b['index']], 2e-6)
335
+ for a, b in zip(reference, actual):
336
+ np.testing.assert_allclose(a['probabilities'], b['probabilities'], atol=2e-6)
337
+ self.assertEqual(bend.predict(self.rows, probabilities=False),
338
+ [dict(index=x['index']) for x in actual])
339
+
340
+ def test_bend_dense_encoder_parity(self):
341
+ dense = FastEngine(self.path, device='cpu', batch_size=2,
342
+ transformer_backend='bend-dense')
343
+ self.assertGreater(dense.bend_projection_count, 0)
344
+ expected = self.baseline.predict(self.rows)
345
+ actual = dense.predict(self.rows)
346
+ for a, b in zip(expected, actual):
347
+ np.testing.assert_allclose(a['probabilities'], b['probabilities'], atol=2e-6)
348
+ self.assertLessEqual(max(a['probabilities']) - a['probabilities'][b['index']], 2e-6)
349
+ from julia.router.transformer import BendLinear
350
+ layer = next(m for m in dense.model.modules() if isinstance(m, BendLinear))
351
+ with torch.no_grad():
352
+ layer.weight.add_(1)
353
+ with self.assertRaisesRegex(RuntimeError, 'resident weights changed'):
354
+ dense.predict(self.rows)
355
+
356
+ @unittest.skipUnless(torch.cuda.is_available(), 'CUDA hardware unavailable')
357
+ def test_cuda(self):
358
+ baseline = Engine(self.path, device='cuda')
359
+ fast = FastEngine(self.path, device='cuda', batch_size=2)
360
+ reference, actual = baseline.predict(self.rows), fast.predict(self.rows)
361
+ self.assertEqual([x['index'] for x in reference], [x['index'] for x in actual])
362
+ for a, b in zip(reference, actual):
363
+ np.testing.assert_allclose(a['probabilities'], b['probabilities'], atol=5e-3)
364
+
365
+
366
+ if __name__ == '__main__':
367
+ unittest.main()
julia/router/tests/test_router.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import concurrent.futures
2
+ import math
3
+ import os
4
+ import random
5
+ import unittest
6
+
7
+ from julia.router import BendReducer, Router
8
+
9
+ LIB = os.environ.get('JULIA_ROUTER_LIBRARY', str(__import__('pathlib').Path(__file__).resolve().parents[1] / 'build/libjulia_router.so'))
10
+
11
+
12
+ class Engine:
13
+ def __init__(self):
14
+ self.batches = []
15
+
16
+ def logits(self, rows):
17
+ self.batches.append(rows)
18
+ return [[float(x) for x in row['options']] for row in rows]
19
+
20
+
21
+ def request(n):
22
+ return dict(state='Olá, 世界', question='Choose the largest number',
23
+ options=[str(i) for i in range(n)])
24
+
25
+
26
+ class Tests(unittest.TestCase):
27
+ def test_native_reference_and_reuse(self):
28
+ reducer = BendReducer(LIB)
29
+ rng = random.Random(10)
30
+ for n in [1, 2, 3, 20, 77, 1000]:
31
+ for _ in range(20):
32
+ values = [rng.randrange(-100, 100) for _ in range(n)]
33
+ self.assertEqual(reducer.argmax(values), max(range(n), key=values.__getitem__))
34
+ self.assertEqual(reducer.argmax([3, 3, -1]), 0)
35
+
36
+ def test_native_threads(self):
37
+ reducer = BendReducer(LIB)
38
+ with concurrent.futures.ThreadPoolExecutor(8) as pool:
39
+ self.assertEqual(list(pool.map(lambda _: reducer.argmax([1, 9, 2]), range(1000))), [1]*1000)
40
+
41
+ def test_invalid(self):
42
+ for scores in [[], [math.nan], [math.inf], [1e100]]:
43
+ with self.assertRaises(ValueError):
44
+ BendReducer(LIB).argmax(scores)
45
+ r = Router(Engine(), library=LIB)
46
+ for row in [request(1), dict(request(30), type='score'), dict(request(3), type='noul')]:
47
+ with self.assertRaises(ValueError):
48
+ r.route(row)
49
+
50
+ def test_direct_and_hierarchical(self):
51
+ engine = Engine()
52
+ router = Router(engine, library=LIB, batch_size=3)
53
+ results = router.route_many([request(n) for n in [2, 20, 21, 77, 4096]])
54
+ self.assertEqual([r.index for r in results], [1, 19, 20, 76, 4095])
55
+ for result in results:
56
+ self.assertAlmostEqual(sum(result.probabilities), 1)
57
+ self.assertIn(result.index, result.candidates)
58
+ self.assertEqual(results[0].probability_scope, 'all_options')
59
+ self.assertEqual(results[-1].probability_scope, 'final_candidates')
60
+ self.assertTrue(all(len(batch) <= 3 for batch in engine.batches))
61
+ self.assertTrue(all(2 <= len(row['options']) <= 20 for batch in engine.batches for row in batch))
62
+ self.assertEqual(router.route_many([]), [])
63
+
64
+ def test_confident_group_shortcut(self):
65
+ self.assertTrue(Router._confident_winner([0.0, 4.0, -3.0], 1))
66
+ self.assertFalse(Router._confident_winner([0.0, 3.0, -3.0], 1))
67
+
68
+ class DecisiveEngine(Engine):
69
+ def logits(self, rows):
70
+ self.batches.append(rows)
71
+ return [[10.0 * float(x) for x in row['options']] for row in rows]
72
+
73
+ engine = DecisiveEngine()
74
+ router = Router(engine, library=LIB)
75
+ result = router.route(request(2001))
76
+ self.assertEqual(result.index, 2000)
77
+ self.assertEqual(result.rounds, 3)
78
+ self.assertEqual(result.model_rows, 106)
79
+
80
+ baseline = Router(DecisiveEngine(), library=LIB)
81
+ baseline._confident_winner = lambda scores, best: False
82
+ original = baseline.route(request(2001))
83
+ self.assertEqual(original.index, result.index)
84
+ self.assertLess(result.rounds, original.rounds)
85
+ self.assertLess(result.model_rows, original.model_rows)
86
+
87
+ def test_cache_and_dedup(self):
88
+ engine = Engine()
89
+ router = Router(engine, library=LIB, cache_size=1)
90
+ results = router.route_many([request(5), request(5)])
91
+ self.assertEqual(results[0].model_rows, 1)
92
+ self.assertEqual(results[0].cache_hits, 1)
93
+ self.assertEqual(router.route(request(5)).model_rows, 0)
94
+ router.clear_cache()
95
+ self.assertEqual(router.route(request(5)).model_rows, 1)
96
+ router.route(request(6))
97
+ self.assertEqual(router.route(request(5)).model_rows, 1)
98
+
99
+ def test_engine_failure(self):
100
+ class Bad:
101
+ def logits(self, rows):
102
+ return [[0]] * len(rows)
103
+ with self.assertRaises(ValueError):
104
+ Router(Bad(), library=LIB).route(request(4))
105
+
106
+
107
+ if __name__ == '__main__':
108
+ unittest.main()
julia/router/transformer.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Resident Bend encoder projections and optional decision-head normalization.
2
+
3
+ The packed FP32 kernels own matrix arithmetic and coarse parallel scheduling.
4
+ PyTorch supplies embedding lookup, SDPA, activations and the selected-output head.
5
+ """
6
+ import numpy as np
7
+ import torch
8
+ from torch import nn
9
+
10
+
11
+ class BendLayerNorm(nn.Module):
12
+ def __init__(self, original, reducer):
13
+ super().__init__()
14
+ self.weight, self.bias = original.weight, original.bias
15
+ self.eps = original.eps
16
+ self.normalized_shape = original.normalized_shape
17
+ self.reducer = reducer
18
+
19
+ def forward(self, x):
20
+ if x.device.type != 'cpu' or x.dtype != torch.float32:
21
+ raise ValueError('Bend LayerNorm requires CPU float32; use torch backend for CUDA')
22
+ if torch.is_grad_enabled():
23
+ raise RuntimeError('Bend transformer kernels require torch.inference_mode()')
24
+ width = x.shape[-1]
25
+ values = x.detach().contiguous().numpy().reshape(-1, width)
26
+ gamma = self.weight.detach().numpy() if self.weight is not None else None
27
+ beta = self.bias.detach().numpy() if self.bias is not None else None
28
+ parts = [self.reducer.layernorm(values[start:start + 1048576 // width], gamma, beta, self.eps)
29
+ for start in range(0, len(values), 1048576 // width)]
30
+ result = parts[0] if len(parts) == 1 else np.concatenate(parts)
31
+ return torch.from_numpy(result.reshape(x.shape))
32
+
33
+
34
+ class BendHeadLayer(nn.Module):
35
+ """Explicit pre-norm block; prevents fused MHA from bypassing Bend norms."""
36
+ def __init__(self, layer, reducer):
37
+ super().__init__()
38
+ if not layer.norm_first:
39
+ raise ValueError('Julia expects pre-norm transformer layers')
40
+ self.layer = layer
41
+ self.norm1 = BendLayerNorm(layer.norm1, reducer)
42
+ self.norm2 = BendLayerNorm(layer.norm2, reducer)
43
+
44
+ def forward(self, x, src_key_padding_mask=None):
45
+ normalized = self.norm1(x)
46
+ attention = self.layer.self_attn(normalized, normalized, normalized,
47
+ key_padding_mask=src_key_padding_mask, need_weights=False)[0]
48
+ x = x + self.layer.dropout1(attention)
49
+ hidden = self.layer.linear2(self.layer.dropout(
50
+ self.layer.activation(self.layer.linear1(self.norm2(x)))))
51
+ return x + self.layer.dropout2(hidden)
52
+
53
+
54
+ def install_bend_head(model, reducer):
55
+ if model.head is not None:
56
+ model.head.layers = nn.ModuleList([BendHeadLayer(layer, reducer) for layer in model.head.layers])
57
+ model.scorer[0] = BendLayerNorm(model.scorer[0], reducer)
58
+ model.eval()
59
+
60
+
61
+ class BendLinear(nn.Module):
62
+ """Inference-only CPU projection using resident weights and Bend arithmetic."""
63
+ def __init__(self, original, reducer):
64
+ super().__init__()
65
+ from .native import BendMatrix
66
+ self.weight, self.bias = original.weight, original.bias
67
+ self.in_features, self.out_features = original.in_features, original.out_features
68
+ self.matrix = BendMatrix(original.weight.detach().numpy(), reducer)
69
+ self._weight_version = self.weight._version
70
+ self._weight_pointer = self.weight.data_ptr()
71
+
72
+ def _check_weight(self):
73
+ if self.weight._version != self._weight_version or self.weight.data_ptr() != self._weight_pointer:
74
+ raise RuntimeError('Bend resident weights changed; recreate the inference backend')
75
+
76
+ def forward(self, x):
77
+ if x.device.type != 'cpu' or x.dtype != torch.float32 or torch.is_grad_enabled():
78
+ raise ValueError('Bend dense projections require CPU FP32 inference_mode')
79
+ self._check_weight()
80
+ result = self.matrix.tensor(x, validate=False)
81
+ return result if self.bias is None else result + self.bias
82
+
83
+
84
+ def install_bend_encoder(model, reducer):
85
+ """Route all encoder linear projections through Bend; attention remains SDPA."""
86
+ count = 0
87
+ def install(module):
88
+ nonlocal count
89
+ for name, child in list(module.named_children()):
90
+ if type(child) is nn.Linear:
91
+ setattr(module, name, BendLinear(child, reducer))
92
+ count += 1
93
+ else:
94
+ install(child)
95
+ install(model.encoder)
96
+ model.eval()
97
+ return count
julia/typed.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Named typed questions over the existing Julia scoring API."""
2
+ import math
3
+ from .data import validate_row
4
+
5
+
6
+ def predict_typed(engine, state, questions):
7
+ if not isinstance(questions,dict) or not questions:
8
+ raise ValueError('questions must be a nonempty mapping')
9
+ rows=[];metadata=[]
10
+ for qid,q in questions.items():
11
+ if not isinstance(qid,str) or not qid or not isinstance(q,dict):
12
+ raise ValueError('Questions require nonempty string IDs and question objects')
13
+ kind=q.get('type');criteria=q.get('criteria')
14
+ if kind=='choice':
15
+ if not isinstance(criteria,dict) or any(not isinstance(k,str) or not k for k in criteria):
16
+ raise ValueError('Choice criteria must map nonempty IDs to descriptions')
17
+ keys=list(criteria);labels=list(criteria.values())
18
+ elif kind=='score':
19
+ if not isinstance(criteria,list):raise ValueError('Score requires an ordered rubric')
20
+ labels=criteria;keys=[str(i) for i in range(len(labels))]
21
+ elif kind=='noul':
22
+ keys=['false','true']
23
+ if criteria is None:
24
+ labels=list(keys)
25
+ else:
26
+ if not isinstance(criteria,dict) or set(criteria)!=set(keys):
27
+ raise ValueError('Noul criteria must map false and true to descriptions')
28
+ labels=[criteria[key] for key in keys]
29
+ else:raise ValueError('Unsupported question type')
30
+ row=dict(state=state,question=q.get('instructions'),type=kind,options=labels)
31
+ validate_row(row,len(rows)+1)
32
+ rows.append(row);metadata.append((qid,kind,keys))
33
+ scores=engine.logits(rows)
34
+ if len(scores)!=len(rows):raise ValueError('Model returned an incorrect answer count')
35
+ answers={}
36
+ for (qid,kind,keys),z in zip(metadata,scores):
37
+ if len(z)!=len(keys) or not all(math.isfinite(x) for x in z):raise ValueError('Invalid model scores')
38
+ maximum=max(z);p=[math.exp(x-maximum) for x in z];total=sum(p);p=[x/total for x in p]
39
+ result=dict(type=kind,probabilities=dict(zip(keys,p)))
40
+ if kind=='choice':result['choice']=keys[max(range(len(p)),key=p.__getitem__)]
41
+ elif kind=='score':result['score']=sum(i*x for i,x in enumerate(p))
42
+ else:result['noul']=p[1]
43
+ if kind!='noul':result['max_probability']=max(p)
44
+ answers[qid]=result
45
+ return dict(answers=answers)
julia_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": 1,
3
+ "architecture": "JuliaDecisionModel",
4
+ "weight_dtype": "float32",
5
+ "head_layers": 2,
6
+ "n_act": 2,
7
+ "dropout": 0.1,
8
+ "name": "Qyvos",
9
+ "base_model": "SupersonicLabs/Julia-1",
10
+ "dataset": "ZefanCai/Open-Jev",
11
+ "dataset_config": "release-v2-redistributable",
12
+ "finetune": "head-only (frozen backbone)"
13
+ }
label_map.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "0": "choice",
3
+ "1": "score",
4
+ "2": "noul",
5
+ "note": "qtype id -> Open-Jev kind; options are scored in given order"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d03ac9a0c7fbc66f1bde7ecb158741b02c9f898078c0a2f0cc270fb6326f920
3
+ size 577189056
provenance.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "Qyvos",
3
+ "created_utc": "2026-09-30T21:28:03Z",
4
+ "base_model": {
5
+ "repo": "SupersonicLabs/Julia-1",
6
+ "weights_sha256": "df853bf7fe424420011f3d0c47a05d7341aa9eefa7fb9f203ea4aada4ad95b72"
7
+ },
8
+ "dataset": {
9
+ "repo": "ZefanCai/Open-Jev",
10
+ "config": "release-v2-redistributable",
11
+ "shards": {
12
+ "calibration-00000-of-00001.parquet": "74cf0064f68dcccbcedd4849d3b347f4c900bdd5329a78ec249fcdf24f89b554",
13
+ "ood-00000-of-00001.parquet": "ba8cb3f95b9121aa73e4b997ac9c350e2ec4dddb972cb5c3086da911f0deb9ef",
14
+ "test-00000-of-00001.parquet": "05edb50da60abb087328e353b201d83b745e01393b4a43b5320b90720a8132ff",
15
+ "train-00000-of-00001.parquet": "a76be013b2986a97e4d61faad4fd5f0a6ddb934760d5dcf3161aaa118909b6bf",
16
+ "validation-00000-of-00001.parquet": "5563764b2d92306e2bfdfd883edfee28a82acf36699f6533c0bd51978b784e59"
17
+ }
18
+ },
19
+ "backbone": "complete Julia-1 backbone retained bit-exact (encoder + act_head untouched)",
20
+ "head": "fine-tuned on Open-Jev soft targets (choice/score/noul), 3,699,073 trainable params",
21
+ "weights_dtype": "float32"
22
+ }
pyproject.toml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=70"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "supersonic-julia"
7
+ version = "0.1.0"
8
+ requires-python = ">=3.11"
9
+ dependencies = ["torch>=2.6", "transformers>=5.0,<5.1", "safetensors>=0.5", "numpy>=1.26"]
10
+
11
+ [tool.setuptools.packages.find]
12
+ include = ["julia*"]
13
+ exclude = ["julia.router.tests*"]
14
+
15
+ [project.optional-dependencies]
16
+ benchmark = ["pyarrow>=15"]
17
+ cuda = ["bitsandbytes>=0.48,<0.50", "accelerate>=1.10,<2"]
18
+
19
+ [tool.setuptools.package-data]
20
+ "julia.router" = ["native/*.bend", "native/*.c", "README.md"]
21
+ "julia" = ["native/*.c", "native/*.bend", "native/*.json"]
qyvos_training_config.json ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "training": {
3
+ "max_rows": 30000,
4
+ "accum": 8,
5
+ "lr": 0.0001,
6
+ "weight_decay": 0.01,
7
+ "warmup": 100,
8
+ "eval_every": 500,
9
+ "eval_rows": 300,
10
+ "eval_batch": 8,
11
+ "ckpt_every": 250,
12
+ "max_length": 1024,
13
+ "head_length": 512,
14
+ "seed": 17,
15
+ "time_budget": 480,
16
+ "resume": "auto",
17
+ "smoke": false
18
+ },
19
+ "final_metrics": {
20
+ "checkpoint_step": 3750,
21
+ "rows_seen": 30000,
22
+ "validation": {
23
+ "accuracy": 0.8411,
24
+ "soft_ce": 0.4282,
25
+ "n": 900,
26
+ "per_kind": {
27
+ "choice": {
28
+ "accuracy": 0.6652,
29
+ "n": 230
30
+ },
31
+ "score": {
32
+ "accuracy": 0.7937,
33
+ "n": 126
34
+ },
35
+ "noul": {
36
+ "accuracy": 0.9265,
37
+ "n": 544
38
+ }
39
+ }
40
+ },
41
+ "test": {
42
+ "accuracy": 0.8311,
43
+ "soft_ce": 0.4447,
44
+ "n": 900,
45
+ "per_kind": {
46
+ "choice": {
47
+ "accuracy": 0.682,
48
+ "n": 217
49
+ },
50
+ "score": {
51
+ "accuracy": 0.7931,
52
+ "n": 145
53
+ },
54
+ "noul": {
55
+ "accuracy": 0.9015,
56
+ "n": 538
57
+ }
58
+ }
59
+ }
60
+ },
61
+ "eval_protocol": "shuffled round-robin mixture across all parquet row-groups, seed 999, length-bucketed batches; accuracy = argmax match vs target argmax, soft_ce = soft-target cross-entropy",
62
+ "frozen": [
63
+ "encoder (ModernBERT-small, 22 layers, 140.5M params)",
64
+ "act_head (action head, unused for scoring; kept bit-exact)"
65
+ ],
66
+ "trainable": [
67
+ "head (2x TransformerEncoderLayer)",
68
+ "type_emb (Embedding(3,384))",
69
+ "scorer (LayerNorm-Linear-GELU-Linear)"
70
+ ],
71
+ "trainable_params": 3699073,
72
+ "total_params": 144292867
73
+ }
tokenizer/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:609d8f4c067cd3950f88594c5a802616cea245823836ef5848ee4fc40aab5b6f
3
+ size 34363188
tokenizer/tokenizer_config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<bos>",
4
+ "clean_up_tokenization_spaces": false,
5
+ "cls_token": "<bos>",
6
+ "eos_token": "<eos>",
7
+ "extra_special_tokens": [
8
+ "<start_of_turn>",
9
+ "<end_of_turn>"
10
+ ],
11
+ "is_local": true,
12
+ "mask_token": "<mask>",
13
+ "max_length": 512,
14
+ "model_input_names": [
15
+ "input_ids",
16
+ "attention_mask"
17
+ ],
18
+ "model_max_length": 8192,
19
+ "pad_token": "<pad>",
20
+ "padding_side": "right",
21
+ "sep_token": "<eos>",
22
+ "spaces_between_special_tokens": false,
23
+ "stride": 0,
24
+ "tokenizer_class": "TokenizersBackend",
25
+ "truncation_side": "right",
26
+ "truncation_strategy": "longest_first",
27
+ "unk_token": "<unk>"
28
+ }
training/build_qyvos.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Assemble the final Qyvos model dir from the trained head checkpoint.
3
+
4
+ Steps:
5
+ 1. Load base Julia-1 (complete backbone, bit-exact) + inject trained head tensors
6
+ 2. Verify head tensors actually differ from base (sanity)
7
+ 3. Honest shuffled eval on validation + test mixtures
8
+ 4. model.save_pretrained() -> Qyvos/ (fp32 safetensors)
9
+ 5. Copy tokenizer/ from base, write identity configs, label map, provenance
10
+ 6. Tensor-exact reload check (max|delta| == 0)
11
+ 7. Official engine (julia.load_model) live prediction test
12
+ """
13
+ import argparse
14
+ import hashlib
15
+ import json
16
+ import os
17
+ import shutil
18
+ import sys
19
+ import time
20
+ from pathlib import Path
21
+
22
+ BASE = Path(os.environ.get("QYVOS_HOME", "/home/z/my-project/download/qyvos"))
23
+ sys.path.insert(0, str(BASE / "Julia-1"))
24
+ sys.path.insert(0, str(BASE / "scripts"))
25
+
26
+ import torch
27
+ from transformers import AutoTokenizer
28
+
29
+ from julia.model import JuliaDecisionModel
30
+
31
+ HEAD_KEYS_PREFIXES = ("head.", "type_emb.", "scorer.")
32
+
33
+
34
+ def sha256(path: Path) -> str:
35
+ h = hashlib.sha256()
36
+ with path.open("rb") as f:
37
+ for block in iter(lambda: f.read(1 << 20), b""):
38
+ h.update(block)
39
+ return h.hexdigest()
40
+
41
+
42
+ def ensure_engine_compat() -> None:
43
+ """transformers >=5.17 removed ModernBertModel._update_attention_mask, which
44
+ julia's OPTIONAL fast inference path (julia/router/encoder.py) relies on.
45
+ The fast path is a pure optimization with numerically equivalent results;
46
+ disabling it makes the official engine use the standard forward.
47
+ (No change to any model tensor or to the shipped julia package code.)"""
48
+ try:
49
+ import julia.router.encoder as _jre
50
+
51
+ if not getattr(_jre, "_qyvos_compat", False):
52
+ _jre.specialize_decision_encoder = lambda model: False
53
+ _jre._qyvos_compat = True
54
+ print("[compat] disabled julia fast-path (transformers >=5.17)", flush=True)
55
+ except Exception as exc:
56
+ print(f"[compat] shim skipped: {exc}", flush=True)
57
+
58
+
59
+ def main() -> int:
60
+ ap = argparse.ArgumentParser()
61
+ ap.add_argument("--ckpt", default=str(BASE / "models" / "qyvos_ckpt" / "head_ckpt.pt"))
62
+ ap.add_argument("--out", default=str(BASE / "Qyvos"))
63
+ ap.add_argument("--eval-rows", type=int, default=900)
64
+ ap.add_argument("--eval-batch", type=int, default=8)
65
+ args = ap.parse_args()
66
+
67
+ import train_qyvos as T
68
+
69
+ t_all = time.time()
70
+ ckpt_path = Path(args.ckpt)
71
+ out_dir = Path(args.out)
72
+ print(f"[build] ckpt={ckpt_path} out={out_dir}", flush=True)
73
+
74
+ payload = torch.load(ckpt_path, map_location="cpu", weights_only=False)
75
+ print(f"[build] ckpt step={payload['step']} rows_seen={payload['rows_seen']}", flush=True)
76
+
77
+ # ---- 1) base model (backbone bit-exact) + trained head tensors ----
78
+ model = JuliaDecisionModel.from_pretrained(BASE / "Julia-1")
79
+ tok = AutoTokenizer.from_pretrained(BASE / "Julia-1" / "tokenizer")
80
+ base_head = {k: v.clone() for k, v in model.state_dict().items()
81
+ if k.startswith(HEAD_KEYS_PREFIXES)}
82
+ missing, unexpected = model.load_state_dict(payload["model"], strict=False)
83
+ print(f"[build] injected head tensors: missing={list(missing)[:3]} unexpected={list(unexpected)[:3]}", flush=True)
84
+
85
+ # ---- 2) verify trained tensors differ from base ----
86
+ diffs = {k: float((model.state_dict()[k].float() - base_head[k].float()).abs().max())
87
+ for k in base_head}
88
+ max_diff = max(diffs.values())
89
+ n_changed = sum(1 for v in diffs.values() if v > 0)
90
+ print(f"[build] head tensors changed: {n_changed}/{len(diffs)} max|delta|={max_diff:.6f}", flush=True)
91
+ assert max_diff > 0, "trained head identical to base - refusing to build"
92
+
93
+ model.eval()
94
+
95
+ # ---- 3) honest shuffled evals ----
96
+ class Cfg:
97
+ eval_rows = args.eval_rows
98
+ eval_batch = args.eval_batch
99
+ max_length = 1024
100
+ head_length = 512
101
+
102
+ metrics = {"checkpoint_step": payload["step"], "rows_seen": payload["rows_seen"]}
103
+ for split in ("validation", "test"):
104
+ t0 = time.time()
105
+ acc, ce, detail = T.evaluate(model, tok, Cfg, split=split)
106
+ metrics[split] = {"accuracy": round(acc, 4), "soft_ce": round(ce, 4),
107
+ "n": int(sum(v[1] for v in detail.values())),
108
+ "per_kind": {k: {"accuracy": round(v[0], 4), "n": v[1]}
109
+ for k, v in detail.items()}}
110
+ print(f"[eval] {split}: acc={acc:.4f} softCE={ce:.4f} " +
111
+ " ".join(f"{k}={v[0]:.4f}(n={v[1]})" for k, v in detail.items()) +
112
+ f" [{time.time()-t0:.0f}s]", flush=True)
113
+
114
+ # ---- 4) save final model (fp32) ----
115
+ if out_dir.exists():
116
+ shutil.rmtree(out_dir)
117
+ model.save_pretrained(out_dir)
118
+
119
+ # ---- 5) tokenizer + identity configs ----
120
+ shutil.copytree(BASE / "Julia-1" / "tokenizer", out_dir / "tokenizer")
121
+
122
+ jc = json.loads((out_dir / "julia_config.json").read_text())
123
+ jc.update({
124
+ "name": "Qyvos",
125
+ "base_model": "SupersonicLabs/Julia-1",
126
+ "dataset": "ZefanCai/Open-Jev",
127
+ "dataset_config": "release-v2-redistributable",
128
+ "finetune": "head-only (frozen backbone)",
129
+ })
130
+ (out_dir / "julia_config.json").write_text(json.dumps(jc, indent=2) + "\n")
131
+
132
+ cfg = json.loads((BASE / "Julia-1" / "config.json").read_text())
133
+ cfg["name"] = "Qyvos"
134
+ cfg["base_model"] = "SupersonicLabs/Julia-1"
135
+ (out_dir / "config.json").write_text(json.dumps(cfg, indent=2) + "\n")
136
+
137
+ (out_dir / "label_map.json").write_text(json.dumps(
138
+ {"0": "choice", "1": "score", "2": "noul",
139
+ "note": "qtype id -> Open-Jev kind; options are scored in given order"}, indent=2) + "\n")
140
+
141
+ # training config + metrics
142
+ train_cfg = dict(payload.get("config", {}))
143
+ train_cfg.pop("rng_python", None)
144
+ (out_dir / "qyvos_training_config.json").write_text(json.dumps(
145
+ {"training": train_cfg, "final_metrics": metrics,
146
+ "eval_protocol": "shuffled round-robin mixture across all parquet row-groups, seed 999, "
147
+ "length-bucketed batches; accuracy = argmax match vs target argmax, "
148
+ "soft_ce = soft-target cross-entropy",
149
+ "frozen": ["encoder (ModernBERT-small, 22 layers, 140.5M params)",
150
+ "act_head (action head, unused for scoring; kept bit-exact)"],
151
+ "trainable": ["head (2x TransformerEncoderLayer)", "type_emb (Embedding(3,384))",
152
+ "scorer (LayerNorm-Linear-GELU-Linear)"],
153
+ "trainable_params": 3699073, "total_params": 144292867}, indent=2) + "\n")
154
+
155
+ # provenance
156
+ base_st = BASE / "Julia-1" / "model.safetensors"
157
+ final_st = out_dir / "model.safetensors"
158
+ prov = {
159
+ "name": "Qyvos",
160
+ "created_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
161
+ "base_model": {"repo": "SupersonicLabs/Julia-1",
162
+ "weights_sha256": sha256(base_st)},
163
+ "dataset": {"repo": "ZefanCai/Open-Jev",
164
+ "config": "release-v2-redistributable",
165
+ "shards": {p.name: sha256(p) for p in
166
+ sorted((BASE / "data" / "data" / "release-v2-redistributable").glob("*.parquet"))}},
167
+ "backbone": "complete Julia-1 backbone retained bit-exact (encoder + act_head untouched)",
168
+ "head": "fine-tuned on Open-Jev soft targets (choice/score/noul), 3,699,073 trainable params",
169
+ "weights_dtype": "float32",
170
+ }
171
+ (out_dir / "provenance.json").write_text(json.dumps(prov, indent=2) + "\n")
172
+
173
+ print(f"[build] final weights sha256: {sha256(final_st)}", flush=True)
174
+
175
+ # ---- 6) tensor-exact reload check ----
176
+ reloaded = JuliaDecisionModel.from_pretrained(out_dir)
177
+ ref = model.state_dict()
178
+ got = reloaded.state_dict()
179
+ assert set(ref.keys()) == set(got.keys()), "state_dict key mismatch after reload"
180
+ max_delta = max(float((ref[k].float() - got[k].float()).abs().max()) for k in ref)
181
+ print(f"[reload] tensor-exact check: max|delta|={max_delta}", flush=True)
182
+ assert max_delta == 0.0, "reload is not tensor-exact"
183
+ del reloaded, ref, got
184
+
185
+ # ---- 7) official engine live test ----
186
+ import julia
187
+
188
+ ensure_engine_compat()
189
+ engine = julia.load_model(str(out_dir), device="cpu", max_length=1024, head_length=512)
190
+ test_rows = [
191
+ {"state": "User chat: my login is blocked after the password reset.",
192
+ "question": "Determine the broad category of this support ticket.",
193
+ "options": ["account: Login, permissions, profile, security",
194
+ "billing: Charges, invoices, refunds, subscriptions"],
195
+ "type": "choice"},
196
+ {"state": "Meter reading estimated at 412 kWh; actual reading pending.",
197
+ "question": "Is the meter estimate acceptable as-is?",
198
+ "options": ["no", "yes"], "type": "noul"},
199
+ {"state": "Cart has 3 items, subtotal 57.90, coupon WELCOME10 not applied.",
200
+ "question": "How strongly should the coupon be auto-applied?",
201
+ "options": ["never", "only if user asks", "always at checkout"], "type": "score"},
202
+ ]
203
+ preds = engine.predict(test_rows)
204
+ for row, pred in zip(test_rows, preds):
205
+ print(f"[engine] type={row['type']:6s} index={pred['index']} "
206
+ f"probs={[round(p, 4) for p in pred['probabilities']]}", flush=True)
207
+ assert all(abs(sum(p["probabilities"]) - 1.0) < 1e-3 for p in preds), "probabilities do not sum to 1"
208
+ print(f"[build] OK in {time.time()-t_all:.0f}s -> {out_dir}", flush=True)
209
+ return 0
210
+
211
+
212
+ if __name__ == "__main__":
213
+ sys.exit(main())
training/download_all.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Download Julia-1 base model repo + Open-Jev (release-v2-redistributable) parquets.
3
+
4
+ Low-RAM safe: huggingface_hub streams files to disk one at a time.
5
+ """
6
+ import os
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+
11
+ from huggingface_hub import snapshot_download
12
+
13
+ BASE = Path(os.environ.get("QYVOS_HOME", "/home/z/my-project/download/qyvos"))
14
+ TOKEN_PATH = Path(os.environ.get("QYVOS_TOKEN_FILE", "/home/z/my-project/download/.hfsec/hf_token"))
15
+
16
+
17
+ def main() -> int:
18
+ token = TOKEN_PATH.read_text().strip()
19
+
20
+ # ---- 1) Julia-1 base model repo (full: model + julia/ package + tokenizer) ----
21
+ jdir = BASE / "Julia-1"
22
+ if (jdir / "model.safetensors").exists():
23
+ print("[skip] Julia-1 already present:", jdir)
24
+ else:
25
+ t0 = time.time()
26
+ print("[dl] SupersonicLabs/Julia-1 ->", jdir, flush=True)
27
+ snapshot_download(
28
+ repo_id="SupersonicLabs/Julia-1",
29
+ repo_type="model",
30
+ local_dir=jdir,
31
+ token=token,
32
+ )
33
+ print(f"[done] Julia-1 in {time.time()-t0:.0f}s", flush=True)
34
+
35
+ # ---- 2) Open-Jev: only release-v2-redistributable parquet shards ----
36
+ ddir = BASE / "data"
37
+ expected = [
38
+ "train", "validation", "test", "calibration", "ood",
39
+ ]
40
+ marker = ddir / "release-v2-redistributable"
41
+ have = all((marker / f"{s}-00000-of-00001.parquet").exists() for s in expected)
42
+ if have:
43
+ print("[skip] Open-Jev parquets already present:", marker)
44
+ else:
45
+ t0 = time.time()
46
+ print("[dl] ZefanCai/Open-Jev (release-v2-redistributable) ->", ddir, flush=True)
47
+ snapshot_download(
48
+ repo_id="ZefanCai/Open-Jev",
49
+ repo_type="dataset",
50
+ local_dir=ddir,
51
+ token=token,
52
+ allow_patterns=[
53
+ "data/release-v2-redistributable/*.parquet",
54
+ "README.md",
55
+ "REPRODUCTION.md",
56
+ "LICENSE-DATA",
57
+ "LICENSE-CODE-MIT",
58
+ "THIRD_PARTY_NOTICES.md",
59
+ ],
60
+ )
61
+ print(f"[done] Open-Jev in {time.time()-t0:.0f}s", flush=True)
62
+
63
+ print("[OK] all downloads complete")
64
+ return 0
65
+
66
+
67
+ if __name__ == "__main__":
68
+ sys.exit(main())
training/eval_qyvos.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Standalone honest eval of any checkpoint (or base model) on validation/test."""
3
+ import argparse
4
+ import os
5
+ import sys
6
+ import time
7
+ from pathlib import Path
8
+
9
+ BASE = Path(os.environ.get("QYVOS_HOME", "/home/z/my-project/download/qyvos"))
10
+ sys.path.insert(0, str(BASE / "Julia-1"))
11
+ sys.path.insert(0, str(BASE / "scripts"))
12
+
13
+ import torch
14
+ from transformers import AutoTokenizer
15
+
16
+ from julia.model import JuliaDecisionModel
17
+
18
+
19
+ def main():
20
+ ap = argparse.ArgumentParser()
21
+ ap.add_argument("--split", default="validation", choices=["validation", "test"])
22
+ ap.add_argument("--rows", type=int, default=900)
23
+ ap.add_argument("--ckpt", default=None, help="head checkpoint to load (default: none = base)")
24
+ ap.add_argument("--batch", type=int, default=8)
25
+ args = ap.parse_args()
26
+
27
+ import train_qyvos as T
28
+
29
+ model = JuliaDecisionModel.from_pretrained(BASE / "Julia-1")
30
+ tok = AutoTokenizer.from_pretrained(BASE / "Julia-1" / "tokenizer")
31
+ if args.ckpt:
32
+ payload = torch.load(args.ckpt, map_location="cpu", weights_only=False)
33
+ model.load_state_dict(payload["model"], strict=False)
34
+ print(f"loaded ckpt step={payload['step']} rows_seen={payload['rows_seen']}")
35
+
36
+ class Cfg:
37
+ eval_rows = args.rows
38
+ eval_batch = args.batch
39
+ max_length = 1024
40
+ head_length = 512
41
+
42
+ model.eval()
43
+ t0 = time.time()
44
+ acc, ce, detail = T.evaluate(model, tok, Cfg, split=args.split)
45
+ print(f"split={args.split} rows={args.rows} acc={acc:.4f} softCE={ce:.4f} "
46
+ + " ".join(f"{k}={v[0]:.4f}({v[1]})" for k, v in detail.items())
47
+ + f" [{time.time()-t0:.0f}s]")
48
+
49
+
50
+ if __name__ == "__main__":
51
+ main()
training/infer_qyvos.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Qyvos inference CLI (uses the official julia engine for release parity).
3
+
4
+ Examples:
5
+ python3 scripts/infer_qyvos.py --demo
6
+ python3 scripts/infer_qyvos.py --eval-test 1500
7
+ python3 scripts/infer_qyvos.py --row '{"state": "...", "question": "...",
8
+ "options": ["a", "b"], "type": "choice"}'
9
+ """
10
+ import argparse
11
+ import json
12
+ import os
13
+ import sys
14
+ import time
15
+ from pathlib import Path
16
+
17
+ BASE = Path(os.environ.get("QYVOS_HOME", "/home/z/my-project/download/qyvos"))
18
+ sys.path.insert(0, str(BASE / "Julia-1"))
19
+ sys.path.insert(0, str(BASE / "scripts"))
20
+
21
+ MODEL_DIR = BASE / "Qyvos"
22
+ DATA = BASE / "data" / "data" / "release-v2-redistributable"
23
+
24
+
25
+ def load_engine():
26
+ import julia
27
+
28
+ # compat: disable julia's optional fast-path on transformers >=5.17
29
+ try:
30
+ import julia.router.encoder as _jre
31
+
32
+ _jre.specialize_decision_encoder = lambda model: False
33
+ except Exception:
34
+ pass
35
+ return julia.load_model(str(MODEL_DIR), device="cpu", max_length=1024, head_length=512)
36
+
37
+
38
+ def demo(engine, per_kind: int = 2) -> None:
39
+ import pyarrow.parquet as pq
40
+
41
+ pf = pq.ParquetFile(DATA / "test-00000-of-00001.parquet")
42
+ seen = {"choice": 0, "score": 0, "noul": 0}
43
+ for rg in range(pf.metadata.num_row_groups):
44
+ if all(v >= per_kind for v in seen.values()):
45
+ break
46
+ rows = pf.read_row_group(rg, columns=["kind", "question", "options", "target", "state_json"]).to_pylist()
47
+ for r in rows:
48
+ k = r["kind"]
49
+ if seen[k] >= per_kind:
50
+ continue
51
+ state = r["state_json"]
52
+ if isinstance(state, str):
53
+ state = json.loads(state)
54
+ req = {"state": state, "question": r["question"], "options": list(r["options"]), "type": k}
55
+ tgt = [float(x) for x in r["target"]]
56
+ pred = engine.predict([req])[0]
57
+ probs = [round(p, 4) for p in pred["probabilities"]]
58
+ gold = int(max(range(len(tgt)), key=lambda i: tgt[i]))
59
+ mark = "OK " if pred["index"] == gold else "MISS"
60
+ print(f"[{mark}] kind={k:6s} q={r['question'][:70]!r}")
61
+ print(f" options={list(r['options'])[:4]}")
62
+ print(f" pred index={pred['index']} probs={probs}")
63
+ print(f" gold index={gold} target={[round(t, 3) for t in tgt]}")
64
+ seen[k] += 1
65
+ if all(v >= per_kind for v in seen.values()):
66
+ break
67
+
68
+
69
+ def eval_test(n_rows: int) -> None:
70
+ import train_qyvos as T
71
+ from transformers import AutoTokenizer
72
+
73
+ from julia.model import JuliaDecisionModel
74
+
75
+ model = JuliaDecisionModel.from_pretrained(MODEL_DIR)
76
+ tok = AutoTokenizer.from_pretrained(MODEL_DIR / "tokenizer")
77
+
78
+ class Cfg:
79
+ eval_rows = n_rows
80
+ eval_batch = 8
81
+ max_length = 1024
82
+ head_length = 512
83
+
84
+ t0 = time.time()
85
+ acc, ce, detail = T.evaluate(model, tok, Cfg, split="test")
86
+ print(f"honest test eval (shuffled mixture, n={n_rows}): acc={acc:.4f} softCE={ce:.4f}")
87
+ for k, v in detail.items():
88
+ print(f" {k:7s} acc={v[0]:.4f} (n={v[1]})")
89
+ print(f"[{time.time()-t0:.0f}s]")
90
+
91
+
92
+ def main() -> int:
93
+ ap = argparse.ArgumentParser()
94
+ ap.add_argument("--demo", action="store_true")
95
+ ap.add_argument("--eval-test", type=int, default=0)
96
+ ap.add_argument("--row", type=str, default=None)
97
+ ap.add_argument("--per-kind", type=int, default=2)
98
+ args = ap.parse_args()
99
+
100
+ if not MODEL_DIR.exists():
101
+ print(f"model dir not found: {MODEL_DIR} (run build_qyvos.py first)", flush=True)
102
+ return 1
103
+
104
+ if args.eval_test:
105
+ eval_test(args.eval_test)
106
+ return 0
107
+
108
+ engine = load_engine()
109
+ if args.row:
110
+ req = json.loads(args.row)
111
+ pred = engine.predict([req])[0]
112
+ print(json.dumps({"index": pred["index"],
113
+ "probabilities": pred["probabilities"],
114
+ "selected": req["options"][pred["index"]]}, indent=2))
115
+ elif args.demo:
116
+ demo(engine, args.per_kind)
117
+ else:
118
+ ap.print_help()
119
+ return 0
120
+
121
+
122
+ if __name__ == "__main__":
123
+ sys.exit(main())
training/inspect_all.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Inspect Julia-1 model repo + Open-Jev dataset (no assumptions - read actual files)."""
3
+ import json
4
+ import os
5
+ import sys
6
+ from collections import Counter
7
+ from pathlib import Path
8
+
9
+ import pyarrow.parquet as pq
10
+
11
+ BASE = Path(os.environ.get("QYVOS_HOME", "/home/z/my-project/download/qyvos"))
12
+ DATA = BASE / "data" / "release-v2-redistributable"
13
+
14
+
15
+ def inspect_model() -> None:
16
+ jdir = BASE / "Julia-1"
17
+ print("=" * 70)
18
+ print("JULIA-1 REPO FILES")
19
+ print("=" * 70)
20
+ for p in sorted(jdir.rglob("*")):
21
+ if p.is_file() and ".cache" not in p.parts:
22
+ print(f" {p.relative_to(jdir)} ({p.stat().st_size:,}B)")
23
+
24
+ print("\n" + "=" * 70)
25
+ print("config.json / julia_config.json / encoder config")
26
+ print("=" * 70)
27
+ for name in ("config.json", "julia_config.json", "encoder/config.json"):
28
+ f = jdir / name
29
+ if f.exists():
30
+ obj = json.loads(f.read_text())
31
+ print(f"--- {name} ---")
32
+ print(json.dumps(obj, indent=2)[:2000])
33
+
34
+ print("\n" + "=" * 70)
35
+ print("provenance.json")
36
+ print("=" * 70)
37
+ f = jdir / "provenance.json"
38
+ if f.exists():
39
+ print(f.read_text()[:1500])
40
+
41
+ print("\n" + "=" * 70)
42
+ print("safetensors header (tensor names/shapes, first 30)")
43
+ print("=" * 70)
44
+ from safetensors import safe_open
45
+ with safe_open(jdir / "model.safetensors", framework="pt") as sf:
46
+ keys = list(sf.keys())
47
+ print("total tensors:", len(keys))
48
+ head_keys = [k for k in keys if not k.startswith("encoder.")]
49
+ enc_keys = [k for k in keys if k.startswith("encoder.")]
50
+ print("encoder.* tensors:", len(enc_keys), "| non-encoder (head) tensors:", len(head_keys))
51
+ for k in head_keys[:30]:
52
+ t = sf.get_slice(k)
53
+ print(f" {k} {t.get_shape()}")
54
+ # a few encoder keys
55
+ for k in enc_keys[:5]:
56
+ t = sf.get_slice(k)
57
+ print(f" {k} {t.get_shape()}")
58
+
59
+
60
+ def inspect_dataset() -> None:
61
+ print("\n" + "=" * 70)
62
+ print("OPEN-JEV: release-v2-redistributable")
63
+ print("=" * 70)
64
+ shards = ["train", "validation", "test", "calibration", "ood"]
65
+ for shard in shards:
66
+ f = DATA / f"{shard}-00000-of-00001.parquet"
67
+ if not f.exists():
68
+ print(f"[missing] {shard}")
69
+ continue
70
+ pf = pq.ParquetFile(f) # mmap, no full read
71
+ md = pf.metadata
72
+ print(f"\n--- {shard}: {md.num_rows} rows, {md.num_row_groups} row-groups, {f.stat().st_size:,}B ---")
73
+ print(" columns:", pf.schema_arrow.names)
74
+ if shard == "train":
75
+ tbl = pf.read_row_group(0) # first row-group only
76
+ kinds = Counter(tbl.column("kind").to_pylist())
77
+ print(" row-group-0 kind counts:", dict(kinds))
78
+ row = {c: tbl.column(c)[0].as_py() for c in tbl.column_names}
79
+ for k, v in row.items():
80
+ s = str(v)
81
+ print(f" sample[{k}] = {s[:300]}")
82
+ # target / state sizes across a few rows
83
+ tg = tbl.column("target").to_pylist()[:5]
84
+ print(" targets[:5]:", [t if not isinstance(t, (list, str)) else str(t)[:120] for t in tg])
85
+ st = tbl.column("state_json").to_pylist()[:3]
86
+ for s in st:
87
+ print(" state_json len:", len(str(s)))
88
+
89
+
90
+ if __name__ == "__main__":
91
+ inspect_model()
92
+ inspect_dataset()
training/train_qyvos.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Qyvos training: head-only fine-tune of Julia-1 on Open-Jev (release-v2-redistributable).
3
+
4
+ RAM strategy (3.9 GB hard limit):
5
+ - Encoder + act_head frozen (no grads, no optimizer state for 140.5M params)
6
+ - Trainable: head (2x TransformerEncoderLayer), type_emb, scorer (~3.7M params, 2.6%)
7
+ - Encoder forward runs under torch.no_grad() (frozen -> no activations retained)
8
+ - bs=1 micro-batches, grad accumulation (default 8), num_workers=0
9
+ - Parquet read via pyarrow mmap, one row-group (~1000 rows, few MB) at a time
10
+ - Lazy per-row tokenization, no dataset-wide RAM cache
11
+ - psutil RAM guard: abort+checkpoint if system available < 350 MB
12
+ - Head-only checkpoints (~45 MB fp32 incl. optimizer state)
13
+
14
+ Deterministic resume: data order is a pure function of (seed, shard layout):
15
+ row-group order = rng(seed).permutation(n_row_groups)
16
+ within-group order = rng((seed, rg_index)).sample(rows)
17
+ Checkpoints are taken at accumulation boundaries; resume fast-forwards by
18
+ replaying the deterministic order (counting only, no forward) to rows_seen.
19
+ """
20
+ import argparse
21
+ import hashlib
22
+ import json
23
+ import os
24
+ import random
25
+ import resource
26
+ import sys
27
+ import time
28
+ from pathlib import Path
29
+
30
+ import numpy as np
31
+ import psutil
32
+ import pyarrow.parquet as pq
33
+ import torch
34
+ from torch import nn
35
+
36
+ BASE = Path(os.environ.get("QYVOS_HOME", "/home/z/my-project/download/qyvos"))
37
+ JULIA_DIR = BASE / "Julia-1"
38
+ DATA = BASE / "data" / "data" / "release-v2-redistributable"
39
+ CKPT_DIR = BASE / "models" / "qyvos_ckpt"
40
+ LOG_DIR = BASE / "logs"
41
+
42
+ MIN_AVAILABLE_BYTES = 350_000_000 # abort below this much system RAM
43
+
44
+
45
+ def log(msg: str) -> None:
46
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
47
+
48
+
49
+ def row_group_order(n_groups: int, seed: int):
50
+ rng = random.Random(seed)
51
+ return rng.sample(range(n_groups), n_groups)
52
+
53
+
54
+ def group_row_order(n_rows: int, seed: int, rg_index: int):
55
+ rng = random.Random(f"{seed}:{rg_index}")
56
+ idx = list(range(n_rows))
57
+ rng.shuffle(idx)
58
+ return idx
59
+
60
+
61
+ def to_engine_row(row: dict) -> dict:
62
+ """Open-Jev parquet row -> official Julia engine request row."""
63
+ state = row["state_json"]
64
+ if isinstance(state, str):
65
+ state = json.loads(state) # state_json is a JSON-encoded string
66
+ return {
67
+ "state": state,
68
+ "question": row["question"],
69
+ "options": list(row["options"]),
70
+ "type": row["kind"],
71
+ }
72
+
73
+
74
+ def stream_rows(parquet_path: Path, seed: int):
75
+ """Yield (rg_index, pos, row_dict) in deterministic shuffled order, mmap one rg at a time."""
76
+ pf = pq.ParquetFile(parquet_path) # mmap
77
+ n_groups = pf.metadata.num_row_groups
78
+ cols = ["kind", "question", "options", "target", "state_json"]
79
+ for rg in row_group_order(n_groups, seed):
80
+ tbl = pf.read_row_group(rg, columns=cols) # ~1000 rows, few MB
81
+ rows = tbl.to_pylist()
82
+ del tbl
83
+ for pos in group_row_order(len(rows), seed, rg):
84
+ yield rg, pos, rows[pos]
85
+ del rows
86
+
87
+
88
+ def take_eval_rows(parquet_path: Path, n_rows: int, seed: int):
89
+ """Shuffled-mixture eval sample: round-robin across ALL row-groups so every
90
+ region contributes equally (avoids the single-region bias that once faked 97%)."""
91
+ pf = pq.ParquetFile(parquet_path)
92
+ n_groups = pf.metadata.num_row_groups
93
+ cols = ["kind", "question", "options", "target", "state_json"]
94
+ buffers = []
95
+ for rg in row_group_order(n_groups, seed):
96
+ tbl = pf.read_row_group(rg, columns=cols)
97
+ rows = tbl.to_pylist()
98
+ del tbl
99
+ idx = group_row_order(len(rows), seed, rg)
100
+ buffers.append([rows[i] for i in idx])
101
+ out = []
102
+ cursor = 0
103
+ while len(out) < n_rows:
104
+ added = False
105
+ for buf in buffers:
106
+ if cursor < len(buf):
107
+ out.append(buf[cursor])
108
+ added = True
109
+ if len(out) >= n_rows:
110
+ break
111
+ if not added:
112
+ break
113
+ cursor += 1
114
+ return out
115
+
116
+
117
+ def build_trainable(model: nn.Module):
118
+ """Freeze encoder + act_head; return trainable params (head, type_emb, scorer)."""
119
+ for p in model.encoder.parameters():
120
+ p.requires_grad_(False)
121
+ for p in model.act_head.parameters():
122
+ p.requires_grad_(False)
123
+ for p in model.head.parameters():
124
+ p.requires_grad_(True)
125
+ for p in model.type_emb.parameters():
126
+ p.requires_grad_(True)
127
+ for p in model.scorer.parameters():
128
+ p.requires_grad_(True)
129
+ trainable = [p for p in model.parameters() if p.requires_grad]
130
+ return trainable
131
+
132
+
133
+ def trainable_state_dict(model: nn.Module):
134
+ keys = ("head", "type_emb", "scorer")
135
+ sd = model.state_dict()
136
+ return {k: v for k, v in sd.items() if k.split(".")[0] in keys}
137
+
138
+
139
+ def soft_ce(scores: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
140
+ return -(targets * torch.log_softmax(scores, dim=-1)).sum(-1).mean()
141
+
142
+
143
+ @torch.no_grad()
144
+ def evaluate(model, tok, args, kind_names=("choice", "score", "noul"), split="validation"):
145
+ """Shuffled-mixture evaluation (honest, non-region-biased).
146
+
147
+ Length-bucketed batching: rows are sorted by encoded length before batching
148
+ so padding waste stays minimal on CPU (3-4x faster than naive batching).
149
+ Metrics are order-independent, so sorting is safe.
150
+ """
151
+ model.eval()
152
+ rows = take_eval_rows(DATA / f"{split}-00000-of-00001.parquet", args.eval_rows, seed=999)
153
+ from julia.data import Collator, sequence
154
+
155
+ collate = Collator(tok, args.max_length, args.head_length)
156
+ pairs = []
157
+ for r in rows:
158
+ try:
159
+ req = to_engine_row(r)
160
+ enc = sequence(tok, req, args.max_length, args.head_length)
161
+ pairs.append((len(enc["ids"]), req, [float(x) for x in r["target"]]))
162
+ except Exception:
163
+ continue
164
+ pairs.sort(key=lambda p: p[0])
165
+
166
+ n_ok = 0
167
+ n_tot = 0
168
+ ce_sum = 0.0
169
+ per_kind = {k: [0, 0] for k in kind_names}
170
+ for i in range(0, len(pairs), args.eval_batch):
171
+ chunk = pairs[i : i + args.eval_batch]
172
+ reqs = [c[1] for c in chunk]
173
+ targets = [c[2] for c in chunk]
174
+ batch = collate(reqs, include_targets=False)
175
+ with torch.no_grad():
176
+ scores = model(**batch) # (B, Kmax)
177
+ for b, (req, tgt) in enumerate(zip(reqs, targets)):
178
+ k = len(req["options"])
179
+ s = scores[b, :k]
180
+ t = torch.tensor(tgt[:k], dtype=torch.float32)
181
+ ce = -(t * torch.log_softmax(s, dim=-1)).sum().item()
182
+ pred = int(s.argmax().item())
183
+ gold = int(t.argmax().item())
184
+ n_tot += 1
185
+ n_ok += int(pred == gold)
186
+ ce_sum += ce
187
+ kt = req["type"]
188
+ if kt in per_kind:
189
+ per_kind[kt][0] += int(pred == gold)
190
+ per_kind[kt][1] += 1
191
+ model.train()
192
+ model.encoder.eval() # encoder stays in eval mode (frozen, no dropout)
193
+ acc = n_ok / max(1, n_tot)
194
+ ce = ce_sum / max(1, n_tot)
195
+ detail = {k: (v[0] / v[1] if v[1] else float("nan"), v[1]) for k, v in per_kind.items()}
196
+ return acc, ce, detail
197
+
198
+
199
+ def save_ckpt(path: Path, model, optimizer, step, rows_seen, args, extra=None):
200
+ CKPT_DIR.mkdir(parents=True, exist_ok=True)
201
+ tmp = path.with_suffix(".tmp")
202
+ payload = {
203
+ "step": step,
204
+ "rows_seen": rows_seen,
205
+ "model": trainable_state_dict(model),
206
+ "optimizer": optimizer.state_dict(),
207
+ "rng_torch": torch.get_rng_state(),
208
+ "rng_python": random.getstate(),
209
+ "config": vars(args),
210
+ "extra": extra or {},
211
+ }
212
+ torch.save(payload, tmp)
213
+ tmp.replace(path) # atomic
214
+ log(f"[ckpt] saved {path.name} step={step} rows_seen={rows_seen}")
215
+
216
+
217
+ def load_ckpt(path: Path, model, optimizer, args):
218
+ payload = torch.load(path, map_location="cpu", weights_only=False)
219
+ model.load_state_dict(payload["model"], strict=False)
220
+ optimizer.load_state_dict(payload["optimizer"])
221
+ torch.set_rng_state(payload["rng_torch"])
222
+ random.setstate(payload["rng_python"])
223
+ log(f"[ckpt] resumed {path.name} step={payload['step']} rows_seen={payload['rows_seen']}")
224
+ return payload["step"], payload["rows_seen"]
225
+
226
+
227
+ def ram_guard(tag: str):
228
+ avail = psutil.virtual_memory().available
229
+ if avail < MIN_AVAILABLE_BYTES:
230
+ log(f"[RAM] available={avail/1e9:.2f}GB < threshold — aborting ({tag})")
231
+ return False
232
+ return True
233
+
234
+
235
+ def main() -> int:
236
+ ap = argparse.ArgumentParser()
237
+ ap.add_argument("--max-rows", type=int, default=30_000)
238
+ ap.add_argument("--accum", type=int, default=8)
239
+ ap.add_argument("--lr", type=float, default=1e-4)
240
+ ap.add_argument("--weight-decay", type=float, default=0.01)
241
+ ap.add_argument("--warmup", type=int, default=100)
242
+ ap.add_argument("--eval-every", type=int, default=400, help="optimizer steps between evals")
243
+ ap.add_argument("--eval-rows", type=int, default=300)
244
+ ap.add_argument("--eval-batch", type=int, default=8)
245
+ ap.add_argument("--ckpt-every", type=int, default=200, help="optimizer steps between ckpts")
246
+ ap.add_argument("--max-length", type=int, default=1024)
247
+ ap.add_argument("--head-length", type=int, default=512)
248
+ ap.add_argument("--seed", type=int, default=17)
249
+ ap.add_argument("--time-budget", type=int, default=440, help="seconds; 0 = unlimited")
250
+ ap.add_argument("--resume", default="auto", help="auto|off")
251
+ ap.add_argument("--smoke", action="store_true", help="tiny run: 24 rows, eval 40, no resume")
252
+ args = ap.parse_args()
253
+
254
+ if args.smoke:
255
+ args.max_rows = 24
256
+ args.eval_rows = 40
257
+ args.eval_every = 2
258
+ args.ckpt_every = 2
259
+ args.resume = "off"
260
+ args.time_budget = 0
261
+
262
+ torch.manual_seed(args.seed)
263
+ random.seed(args.seed)
264
+ np.random.seed(args.seed % (2**31))
265
+ CKPT_DIR.mkdir(parents=True, exist_ok=True)
266
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
267
+
268
+ sys.path.insert(0, str(JULIA_DIR))
269
+ from transformers import AutoTokenizer
270
+
271
+ from julia.model import JuliaDecisionModel
272
+
273
+ t0 = time.time()
274
+ log("loading base Julia-1 (fp32, frozen backbone) ...")
275
+ model = JuliaDecisionModel.from_pretrained(JULIA_DIR)
276
+ model.eval() # encoder always eval (no dropout); head toggled below
277
+ tok = AutoTokenizer.from_pretrained(JULIA_DIR / "tokenizer")
278
+ trainable = build_trainable(model)
279
+ n_train = sum(p.numel() for p in trainable)
280
+ n_total = sum(p.numel() for p in model.parameters())
281
+ log(f"trainable {n_train:,} / {n_total:,} params ({100*n_train/n_total:.2f}%)")
282
+
283
+ decay, no_decay = [], []
284
+ for n, p in model.named_parameters():
285
+ if not p.requires_grad:
286
+ continue
287
+ (no_decay if (p.ndim <= 1 or "type_emb" in n) else decay).append(p)
288
+ optimizer = torch.optim.AdamW(
289
+ [{"params": decay, "weight_decay": args.weight_decay},
290
+ {"params": no_decay, "weight_decay": 0.0}],
291
+ lr=args.lr, betas=(0.9, 0.999), eps=1e-8,
292
+ )
293
+
294
+ ckpt_path = CKPT_DIR / "head_ckpt.pt"
295
+ step, rows_seen = 0, 0
296
+ if args.resume == "auto" and ckpt_path.exists():
297
+ step, rows_seen = load_ckpt(ckpt_path, model, optimizer, args)
298
+ if rows_seen >= args.max_rows:
299
+ log(f"[DONE] checkpoint already at rows_seen={rows_seen} >= max_rows={args.max_rows}")
300
+ return 0
301
+ model.train()
302
+ model.encoder.eval() # frozen encoder: keep eval mode (dropout-free) always
303
+
304
+ # deterministic LR schedule: linear warmup -> linear decay to 10%
305
+ max_steps = (args.max_rows + args.accum - 1) // args.accum
306
+
307
+ def lr_at(s: int) -> float:
308
+ if s < args.warmup:
309
+ return args.lr * (s + 1) / args.warmup
310
+ frac = (s - args.warmup) / max(1, max_steps - args.warmup)
311
+ return args.lr * (1.0 - 0.9 * min(1.0, frac))
312
+
313
+ if step == 0:
314
+ log("eval baseline (step 0) ...")
315
+ acc, ce, detail = evaluate(model, tok, args, split="validation")
316
+ log(f"[eval] step={step} rows={rows_seen} acc={acc:.4f} softCE={ce:.4f} " +
317
+ " ".join(f"{k}={v[0]:.3f}({v[1]})" for k, v in detail.items()))
318
+ else:
319
+ log(f"resuming at step={step} (baseline eval skipped; periodic eval continues)")
320
+
321
+ from julia.data import Collator
322
+
323
+ collate = Collator(tok, args.max_length, args.head_length)
324
+ train_path = DATA / "train-00000-of-00001.parquet"
325
+
326
+ t_start = time.time()
327
+ loss_window = []
328
+ eval_hist = []
329
+ skipped = 0
330
+ stopped = "done"
331
+
332
+ stream = stream_rows(train_path, args.seed)
333
+ log(f"training from rows_seen={rows_seen} (skip fast-forward) ...")
334
+ pending = rows_seen # rows to skip before resuming gradient work
335
+
336
+ for rg_i, pos, row in stream:
337
+ if pending > 0:
338
+ pending -= 1
339
+ continue
340
+ if rows_seen >= args.max_rows:
341
+ stopped = "done"
342
+ break
343
+ if args.time_budget and time.time() - t_start > args.time_budget:
344
+ stopped = "budget"
345
+ break
346
+ if rows_seen % 100 == 0 and not ram_guard(f"row {rows_seen}"):
347
+ stopped = "ram"
348
+ break
349
+
350
+ try:
351
+ req = to_engine_row(row)
352
+ k = len(req["options"])
353
+ tgt = torch.tensor([float(x) for x in row["target"][:k]], dtype=torch.float32)
354
+ if k < 2 or abs(sum(tgt.tolist()) - 1.0) > 0.05:
355
+ raise ValueError(f"bad row shape k={k} target_sum={tgt.sum():.3f}")
356
+ except Exception as e:
357
+ skipped += 1
358
+ rows_seen += 1
359
+ continue
360
+
361
+ batch = collate([req], include_targets=False)
362
+ scores = model(**batch)[0, :k]
363
+ loss = soft_ce(scores[None], tgt[None]) / args.accum
364
+ loss.backward()
365
+ loss_window.append(loss.item() * args.accum)
366
+ rows_seen += 1
367
+
368
+ if rows_seen % args.accum == 0:
369
+ lr = lr_at(step)
370
+ for g in optimizer.param_groups:
371
+ g["lr"] = lr
372
+ torch.nn.utils.clip_grad_norm_(trainable, 1.0)
373
+ optimizer.step()
374
+ optimizer.zero_grad(set_to_none=True)
375
+ step += 1
376
+
377
+ if step % args.eval_every == 0:
378
+ acc, ce, detail = evaluate(model, tok, args, split="validation")
379
+ eval_hist.append({"step": step, "rows": rows_seen, "acc": round(acc, 4),
380
+ "ce": round(ce, 4),
381
+ "kinds": {k: round(v[0], 4) for k, v in detail.items()}})
382
+ log(f"[eval] step={step} rows={rows_seen} acc={acc:.4f} softCE={ce:.4f} " +
383
+ " ".join(f"{k}={v[0]:.3f}({v[1]})" for k, v in detail.items()))
384
+ if step % args.ckpt_every == 0:
385
+ # roll back to accumulation boundary for exact resume
386
+ save_ckpt(ckpt_path, model, optimizer, step, rows_seen, args,
387
+ extra={"eval_hist": eval_hist, "skipped": skipped,
388
+ "loss_tail": loss_window[-50:]})
389
+
390
+ boundary_rows = (rows_seen // args.accum) * args.accum
391
+ save_ckpt(ckpt_path, model, optimizer, step, boundary_rows, args,
392
+ extra={"eval_hist": eval_hist, "skipped": skipped,
393
+ "loss_tail": loss_window[-50:], "stopped": stopped})
394
+
395
+ elapsed = time.time() - t_start
396
+ peak_mb = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024
397
+ log(f"[{stopped.upper()}] rows_seen={rows_seen} step={step} skipped={skipped} "
398
+ f"elapsed={elapsed:.0f}s peakRSS={peak_mb:.0f}MB "
399
+ f"mean_loss(last50)={sum(loss_window[-50:])/max(1,len(loss_window[-50:])):.4f}")
400
+ if stopped == "done" and rows_seen >= args.max_rows:
401
+ log("[DONE] training target reached")
402
+ return 0
403
+ return 0 if stopped in ("budget",) else (3 if stopped == "ram" else 0)
404
+
405
+
406
+ if __name__ == "__main__":
407
+ sys.exit(main())