tetu-AI commited on
Commit
2309cb1
·
verified ·
1 Parent(s): fa18b24

Initial release

Browse files
README.md ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ - fr
6
+ - code
7
+ pipeline_tag: text-generation
8
+ tags:
9
+ - code
10
+ - coding-agent
11
+ - small-language-model
12
+ - trained-from-scratch
13
+ - custom-architecture
14
+ - tool-use
15
+ - opencode
16
+ model-index:
17
+ - name: Tetu-Code-2
18
+ results:
19
+ - task:
20
+ type: text-generation
21
+ dataset:
22
+ name: HumanEval+
23
+ type: evalplus/humanevalplus
24
+ metrics:
25
+ - type: pass@1
26
+ name: pass@1 (greedy, chat prompt)
27
+ value: 15.9
28
+ - task:
29
+ type: text-generation
30
+ dataset:
31
+ name: MBPP+
32
+ type: evalplus/mbppplus
33
+ metrics:
34
+ - type: pass@1
35
+ name: pass@1 (greedy, chat prompt)
36
+ value: 30.7
37
+ ---
38
+
39
+ # Têtu Code 2
40
+
41
+ **A small coding agent trained from scratch, built to work in the terminal through [OpenCode](https://opencode.ai).**
42
+
43
+ Têtu Code 2 is an independent research model with its own architecture. No weights from any other model went into
44
+ it. A larger open model (Qwen3.6-35B-A3B, Apache 2.0) was used only as a *teacher*: it wrote demonstrations, and a
45
+ program checked each one before training. The whole project ran on one consumer GPU (RTX 5070, 12 GB) plus about
46
+ 30 hours of rented cloud GPU.
47
+
48
+ ## Model summary
49
+
50
+ | | |
51
+ |---|---|
52
+ | **Developed by** | tetu-AI (independent project) |
53
+ | **Model type** | Decoder-only language model, custom architecture |
54
+ | **Parameters** | 1.15B in total, of which **475M do the computation** for each token. The rest is a large memory that the model reads at almost no cost. |
55
+ | **Context length** | 65,536 tokens |
56
+ | **Languages** | Python first (plus HTML, CSS, JavaScript and others); instructions in English and French |
57
+ | **Vocabulary** | 32,768 tokens, trained on code |
58
+ | **Precision** | bfloat16 (`model.safetensors`) |
59
+ | **License** | Apache 2.0 |
60
+
61
+ What it does:
62
+ - **Works as an agent.** It reads files, writes and edits them, and runs commands through OpenCode's tools.
63
+ - **Thinks before acting.** It writes a short reasoning between `<|think|>` and `<|/think|>` before each action.
64
+ - **Knows when it may be wrong.** A small head estimates, for every token, the probability that it is wrong.
65
+ - **Comes with a server.** It ships with an OpenAI-compatible server for OpenCode (1.x and 2.x tool formats). The
66
+ server keeps the cache between turns and stops repeated identical calls.
67
+
68
+ ## Training
69
+
70
+ | Stage | What |
71
+ |---|---|
72
+ | Pre-training | 7.08B tokens: mostly code (Python, then web and other languages), plus code-related web pages, French and English web text and math |
73
+ | End of pre-training | The last quarter mixes in teacher projects, coding exercises whose solutions pass their tests, agent trajectories and commits |
74
+ | Agent fine-tuning | 2,093 runs on real multi-file projects (command-line tools, games, sites, APIs, bug fixes, tests…). The teacher played them and a program checked them. Plus DAgger states: the model plays, and the teacher gives the right action. |
75
+
76
+ ## Evaluation
77
+
78
+ All results come from measurements we had already made. Nothing was re-run for this page.
79
+
80
+ ### Code generation (EvalPlus)
81
+
82
+ | Model | Size | Training tokens | HumanEval+ | MBPP+ |
83
+ |---|---|---|---|---|
84
+ | DeepSeek-Coder-1.3B-instruct | 1.3B | 2T | 60.4 | 54.8 |
85
+ | DeepSeek-Coder-1.3B-base | 1.3B | 2T | 25.6 | 47.9 |
86
+ | Qwen2.5-Coder-0.5B (base) | 0.5B | 5.5T | 23.8 | 47.1 |
87
+ | Têtu Code 1 (our previous model) | 193M compute | 7B | 18.3 | 27.5 |
88
+ | **Têtu Code 2** | **475M compute** | **7.08B** | **15.9** | **30.7** |
89
+ | SantaCoder-1.1B | 1.1B | 236B | 14.0 | – |
90
+ | StarCoderBase-1B | 1B | 1T | 12.2 | – |
91
+ | InCoder-1.3B | 1.3B | ~60B | 11.0 | – |
92
+ | CodeGen2-1B | 1B | ~400B | 9.1 | – |
93
+
94
+ - **Têtu Code:** EvalPlus 0.3.1, greedy decoding, one sample per problem, chat prompt. A second run with the same
95
+ setup gave HumanEval+ 14.6 and MBPP+ 30.7, so allow for about ±1.5 points of noise.
96
+ - **Other models:** official EvalPlus leaderboard, read on 23 Oct. 2026; Qwen2.5-Coder numbers come from its authors.
97
+ - **Reading the table:** Têtu Code 2 beats the 1B code models of 2023 (SantaCoder, StarCoderBase-1B) after seeing 30
98
+ to 140 times fewer tokens. It is behind DeepSeek-Coder-1.3B and Qwen2.5-Coder-0.5B, which saw 280 to 780 times
99
+ more tokens.
100
+
101
+ ### As an agent
102
+
103
+ | | Têtu Code 1 | **Têtu Code 2** | Teacher (Qwen3.6-35B-A3B) |
104
+ |---|---|---|---|
105
+ | 40 held-out real projects in OpenCode 2.1.4 (hidden tests) | 0/40 | **8/40** | 29/40 |
106
+ | Older single-function agent benchmark (OpenCode 1.19.4) | 46.5 % | 28.5 % | 85.5 % |
107
+ | Validation loss on Python (pre-training) | 0.821 | **0.777** | – |
108
+
109
+ **Speed** on an RTX 5070: about 143 tokens/s at 2k context and 71 tokens/s at 16k.
110
+
111
+ ## Limitations
112
+
113
+ - **It is a small model.** It often gets the logic wrong from the start, or invents variables.
114
+ - **It does not repair its own failing tests.** When its tests fail, it tends to re-run commands instead of fixing
115
+ the code.
116
+ - **It follows multi-turn conversations poorly.** It can miss a correction or a second request given later in the
117
+ same conversation.
118
+ - **It is an agent, not a chatbot.** In the plain terminal chat (`chat.py`), it often still tries to call a tool.
119
+ Ask for it through OpenCode.
120
+ - **It sometimes writes files in the wrong folder.** The bundled server moves such paths back into the project.
121
+ - **Do not let it run unattended on code that matters.** Use a sandbox or a throwaway directory.
122
+
123
+ ## Usage
124
+
125
+ The architecture is custom, so it does not load with `transformers`. Use the bundled inference code.
126
+
127
+ ```bash
128
+ git clone https://huggingface.co/tetu-AI/Tetu-Code-2 && cd Tetu-Code-2
129
+ pip install -r requirements.txt
130
+ python chat.py # terminal chat, no tools (--cpu without a GPU)
131
+ python -m tetu_code.serve --model . --port 8070 # OpenAI-compatible server for OpenCode
132
+ ```
133
+
134
+ `opencode.json`:
135
+
136
+ ```json
137
+ "provider": {"tetu": {"npm": "@ai-sdk/openai-compatible", "name": "Têtu Code",
138
+ "options": {"baseURL": "http://127.0.0.1:8070/v1", "apiKey": "x"},
139
+ "models": {"tetu-code": {"name": "Têtu Code", "tool_call": true,
140
+ "limit": {"context": 65536, "output": 4096}}}}}
141
+ ```
142
+
143
+ From Python:
144
+
145
+ ```python
146
+ import torch
147
+ from tetu_code.generate import Decoder, load
148
+ model, tok = load(".", device="cuda") # or device="cpu", dtype=torch.float32
149
+ dec = Decoder(model, tok, max_len=16384)
150
+ ```
151
+
152
+ ## License
153
+
154
+ **Apache 2.0.**
155
+
156
+ Teachers, both Apache 2.0:
157
+ - Qwen3.6-35B-A3B, for the agent runs;
158
+ - Qwen2.5-7B-Instruct, for everyday conversations.
159
+
160
+ Training data:
161
+ - github-code-clean (permissively licensed files only);
162
+ - FineWeb-Edu, FineWeb2-HQ and FineMath (ODC-By);
163
+ - OpenCodeInstruct;
164
+ - Nemotron-SWE trajectories;
165
+ - CommitPackFT.
166
+
167
+ Check each dataset's own terms before commercial use.
168
+
169
+ ## Citation
170
+
171
+ ```bibtex
172
+ @misc{tetucode2026,
173
+ title = {Têtu Code 2: a small coding agent trained from scratch},
174
+ author = {tetu-AI},
175
+ year = {2026},
176
+ url = {https://huggingface.co/tetu-AI/Tetu-Code-2}
177
+ }
178
+ ```
chat.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chat with Têtu Code 2 in the terminal (no tools). For the agent in OpenCode: python -m tetu_code.serve
2
+
3
+ python chat.py (GPU) python chat.py --cpu
4
+ """
5
+ import argparse
6
+ from pathlib import Path
7
+ import re
8
+
9
+ import torch
10
+
11
+ from tetu_code import fmt
12
+ from tetu_code.generate import Decoder, load
13
+
14
+ ROOT = Path(__file__).resolve().parent
15
+
16
+
17
+ def main():
18
+ p = argparse.ArgumentParser()
19
+ p.add_argument("--cpu", action="store_true")
20
+ p.add_argument("--temp", type=float, default=0.2)
21
+ p.add_argument("--max_new", type=int, default=1024)
22
+ a = p.parse_args()
23
+ dev = "cpu" if a.cpu or not torch.cuda.is_available() else "cuda"
24
+ model, tok = load(str(ROOT), device=dev, dtype=torch.float32 if dev == "cpu" else torch.bfloat16)
25
+ dec = Decoder(model, tok, max_len=16384, graph=dev == "cuda")
26
+ stop = {tok.token_to_id(t) for t in ("<|end|>", "<|eos|>", "<|user|>", "<|/call|>")}
27
+ text = f"<|system|>{fmt.system_text()}"
28
+ print("Têtu Code 2 — /reset to clear, Ctrl+C to quit")
29
+ while True:
30
+ q = input("\n> ").strip()
31
+ if q == "/reset":
32
+ text = f"<|system|>{fmt.system_text()}"
33
+ continue
34
+ text += f"<|user|>{q}<|assistant|>"
35
+ ids = tok.encode(text, add_special_tokens=False).ids
36
+ out = []
37
+ for t in dec.generate(ids, max_new=a.max_new, temp=a.temp, stop=stop):
38
+ if t in stop:
39
+ break
40
+ out.append(t)
41
+ print(tok.decode([t], skip_special_tokens=False), end="", flush=True)
42
+ reply = tok.decode(out, skip_special_tokens=False)
43
+ text += reply + "<|end|>"
44
+ print()
45
+
46
+
47
+ if __name__ == "__main__":
48
+ main()
config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "Têtu Code 2",
3
+ "step": 910,
4
+ "tokens": null,
5
+ "config": {
6
+ "vocab_size": 32768,
7
+ "d_model": 1152,
8
+ "n_layers": 28,
9
+ "n_heads": 18,
10
+ "n_kv_heads": 6,
11
+ "mlp_mult": 4,
12
+ "max_seq_len": 65536,
13
+ "window": 2048,
14
+ "global_every": 4,
15
+ "rope_local": 10000.0,
16
+ "rope_global": 500000.0,
17
+ "log_base": 4096,
18
+ "engram": [
19
+ [
20
+ 1,
21
+ [
22
+ 2,
23
+ 3
24
+ ]
25
+ ],
26
+ [
27
+ 9,
28
+ [
29
+ 3,
30
+ 4
31
+ ]
32
+ ],
33
+ [
34
+ 17,
35
+ [
36
+ 4,
37
+ 6
38
+ ]
39
+ ]
40
+ ],
41
+ "engram_heads": 2,
42
+ "engram_slots": 393209,
43
+ "engram_dim": 128,
44
+ "n_value_embeds": 3,
45
+ "struct_sizes": [
46
+ 16,
47
+ 16,
48
+ 4,
49
+ 2
50
+ ],
51
+ "softcap": 30.0,
52
+ "doubt_weight": 0.1,
53
+ "eos_id": 1
54
+ }
55
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2b4f3bf2409b9eb976db7767db901bd529fe08817fa4aca9755dab4bc5d599f
3
+ size 2309279312
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torch>=2.5
2
+ tokenizers
3
+ safetensors
4
+ numpy
tetu_code/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Têtu Code 2 — inference code (tetu-AI). License: Apache 2.0, see README.md.
2
+ pass
tetu_code/fmt.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Têtu Code 2 — inference code (tetu-AI). License: Apache 2.0, see README.md.
2
+ import json
3
+ import re
4
+ SYSTEM = "Tu es Têtu Code, un agent de programmation qui travaille dans le terminal de l'utilisateur. Sers-toi des outils pour lire, chercher, modifier et tester le code, un appel à la fois. Lis un fichier avant de le modifier ; après une modification, vérifie (tests, exécution) quand c'est possible. Réponds dans la langue de l'utilisateur, brièvement et précisément."
5
+ ENV_KEYS = ('Working directory', 'Is directory a git repo', 'Platform', "Today's date")
6
+ TOOL_DESC = {'bash': 'run a shell command', 'read': 'read a file or list a directory', 'edit': 'replace an exact passage of a file (oldString must match exactly once, or set replaceAll)', 'write': 'write a whole file', 'glob': 'find files by name pattern', 'grep': 'search file contents with a regex', 'todowrite': 'update the task list', 'webfetch': 'fetch a web page'}
7
+ DROP = {'task', 'skill', 'question', 'todowrite', 'webfetch', 'subagent', 'websearch', 'execute'}
8
+ TOOL_ALIASES = {'shell': 'bash'}
9
+ ARG_ALIASES = {'read': {'path': 'filePath'}, 'write': {'path': 'filePath'}, 'edit': {'path': 'filePath'}}
10
+ OPENCODE_TOOLS = [('bash', [('command', 'string', True), ('timeout', 'integer', False), ('workdir', 'string', False)]), ('edit', [('filePath', 'string', True), ('oldString', 'string', True), ('newString', 'string', True), ('replaceAll', 'boolean', False)]), ('glob', [('pattern', 'string', True), ('path', 'string', False)]), ('grep', [('pattern', 'string', True), ('path', 'string', False), ('include', 'string', False)]), ('read', [('filePath', 'string', True), ('offset', 'integer', False), ('limit', 'integer', False)]), ('todowrite', [('todos', 'array', True)]), ('webfetch', [('url', 'string', True), ('format', 'string', False), ('timeout', 'number', False)]), ('write', [('content', 'string', True), ('filePath', 'string', True)])]
11
+ MAX_RESULT = 12000
12
+
13
+ def opencode_tools():
14
+ out = []
15
+ for name, params in OPENCODE_TOOLS:
16
+ props = {p: {'type': t} for p, t, _ in params}
17
+ out.append({'type': 'function', 'function': {'name': name, 'description': TOOL_DESC[name], 'parameters': {'type': 'object', 'properties': props, 'required': [p for p, _, r in params if r]}}})
18
+ return out
19
+
20
+ def keep_tools(tools):
21
+ return [t for t in tools or [] if t.get('function', {}).get('name') not in DROP]
22
+
23
+ def dialect(tools):
24
+ out, back = ([], {})
25
+ for t in tools or []:
26
+ f = t.get('function', {})
27
+ cname = f.get('name')
28
+ name = TOOL_ALIASES.get(cname, cname)
29
+ ps = f.get('parameters') or {}
30
+ props = ps.get('properties') or {}
31
+ ren = {p: m for p, m in ARG_ALIASES.get(name, {}).items() if p in props and m not in props}
32
+ if name != cname or ren:
33
+ ps = dict(ps, properties={ren.get(p, p): s for p, s in props.items()}, required=[ren.get(p, p) for p in ps.get('required', [])])
34
+ t = dict(t, function=dict(f, name=name, parameters=ps))
35
+ back[name] = (cname, {m: p for p, m in ren.items()})
36
+ out.append(t)
37
+ order = [n for n, _ in OPENCODE_TOOLS]
38
+ out.sort(key=lambda t: order.index(t['function']['name']) if t['function']['name'] in order else len(order))
39
+ return (out, back)
40
+
41
+ def to_model(messages, back):
42
+ fwd = {cname: (name, {c: m for m, c in args.items()}) for name, (cname, args) in back.items()}
43
+ out = []
44
+ for m in messages:
45
+ if m.get('role') == 'assistant' and m.get('tool_calls'):
46
+ calls = []
47
+ for c in m['tool_calls']:
48
+ f = c.get('function', {})
49
+ name, ren = fwd.get(f.get('name'), (f.get('name'), {}))
50
+ f = dict(f, name=name)
51
+ if ren:
52
+ try:
53
+ a = json.loads(f.get('arguments') or '{}')
54
+ except ValueError:
55
+ a = None
56
+ if isinstance(a, dict):
57
+ f['arguments'] = json.dumps({ren.get(k, k): v for k, v in a.items()}, ensure_ascii=False)
58
+ calls.append(dict(c, function=f))
59
+ m = dict(m, tool_calls=calls)
60
+ out.append(m)
61
+ return out
62
+
63
+ def to_client(call, back):
64
+ if call is None:
65
+ return None
66
+ name, args = call
67
+ cname, ren = back.get(name, (name, {}))
68
+ return (cname, {ren.get(k, k): v for k, v in args.items()})
69
+
70
+ def tools_text(tools):
71
+ lines = []
72
+ for t in keep_tools(tools):
73
+ f = t['function']
74
+ ps = f.get('parameters', {}) or {}
75
+ req = set(ps.get('required', []))
76
+ args = ', '.join((p + ('' if p in req else '?') for p in ps.get('properties') or {}))
77
+ desc = TOOL_DESC.get(f['name']) or re.split('(?<=[.!?])\\s|\\n', (f.get('description') or '').strip())[0][:120]
78
+ lines.append(f"{f['name']}({args}) — {desc}")
79
+ return '\n'.join(lines)
80
+
81
+ def env_from_system(text):
82
+ m = re.search('<env>(.*?)</env>', text or '', re.S)
83
+ env = {}
84
+ for line in (m.group(1) if m else '').splitlines():
85
+ k, _, v = line.strip().partition(':')
86
+ if k in ENV_KEYS:
87
+ env[k] = v.strip()
88
+ return env
89
+
90
+ def system_text(env=None):
91
+ env = env or {}
92
+ lines = [f'{k}: {env[k]}' for k in ENV_KEYS if env.get(k)]
93
+ return SYSTEM + ('\n<env>\n' + '\n'.join(lines) + '\n</env>' if lines else '')
94
+
95
+ def arg_text(v):
96
+ if isinstance(v, str):
97
+ return v
98
+ if isinstance(v, bool):
99
+ return 'true' if v else 'false'
100
+ if isinstance(v, (int, float)):
101
+ return str(int(v)) if float(v).is_integer() else str(v)
102
+ return json.dumps(v, ensure_ascii=False)
103
+
104
+ def call_text(name, args):
105
+ return f'<|call|>{name}\n' + ''.join((f'<|arg|>{k}\n{arg_text(v)}\n' for k, v in args.items())) + '<|/call|>'
106
+
107
+ def parse_call(text, tools=None):
108
+ name, _, rest = text.partition('<|arg|>')
109
+ name, args = (name.strip(), {})
110
+ for part in ('<|arg|>' + rest).split('<|arg|>')[1:]:
111
+ k, _, v = part.partition('\n')
112
+ args[k.strip()] = v[:-1] if v.endswith('\n') else v
113
+ types = {}
114
+ for t in tools or []:
115
+ if t['function']['name'] == name:
116
+ types = {p: s.get('type') for p, s in (t['function'].get('parameters', {}).get('properties') or {}).items()}
117
+ for k, v in list(args.items()):
118
+ ty = types.get(k)
119
+ try:
120
+ if ty in ('number', 'integer'):
121
+ args[k] = int(v) if re.fullmatch('\\s*-?\\d+\\s*', v) else float(v)
122
+ elif ty == 'boolean':
123
+ args[k] = v.strip().lower() == 'true'
124
+ elif ty in ('array', 'object'):
125
+ args[k] = json.loads(v)
126
+ except ValueError:
127
+ pass
128
+ return (name, args)
129
+
130
+ def clip(text, limit=MAX_RESULT):
131
+ if len(text) <= limit:
132
+ return text
133
+ head, tail = (text[:limit * 2 // 3], text[-limit // 3:])
134
+ head, tail = (head[:head.rfind('\n') + 1] or head, tail[tail.find('\n') + 1:] or tail)
135
+ cut = text.count('\n', len(head), len(text) - len(tail))
136
+ return f'{head}… ({cut} lines cut) …\n{tail}'
137
+
138
+ def compact_read(text):
139
+ m = re.match('\\s*<path>(.*?)</path>\\s*<type>(.*?)</type>\\s*<content>\\n?(.*?)\\n?</content>\\s*$', text, re.S)
140
+ if not m:
141
+ return compact_read2(text)
142
+ path, kind, body = m.groups()
143
+ note = ''
144
+ n = re.search('\\n*\\((End of file - total (\\d+) lines|[^()\\n]*(?:offset|lines)[^()\\n]*)\\)\\s*$', body)
145
+ if n:
146
+ body, note = (body[:n.start()], n.group(1))
147
+ lines = body.split('\n')
148
+ nums = [re.match('(\\d+): ?', l) for l in lines]
149
+ if kind.strip() == 'file' and lines and all(nums):
150
+ first, last = (int(nums[0].group(1)), int(nums[-1].group(1)))
151
+ body = '\n'.join((l[k.end():] for l, k in zip(lines, nums)))
152
+ total = n.group(2) if n and n.group(2) else (re.search('of (\\d+)', note) or [None, None])[1]
153
+ if n and n.group(2) and (first == 1):
154
+ head = f'{path} (end of file, {total} lines)'
155
+ else:
156
+ head = f'{path} (lines {first}-{last}' + (f' of {total}' if total else '') + ')'
157
+ return head + '\n' + clip(body)
158
+ return f'{path} ({kind.strip()})\n' + clip(body) + (f'\n({note})' if note else '')
159
+
160
+ def compact_read2(text):
161
+ m = re.match('Read (file|directory) (.+?), (?:lines|entries) (\\d+)-(\\d+)(?: of (\\d+))?\\r?\\n?(.*)\\Z', text, re.S)
162
+ if not m:
163
+ return text
164
+ kind, path, first, last, total, body = m.groups()
165
+ lines = body.replace('\r\n', '\n').rstrip('\r').split('\n')
166
+ if kind == 'directory':
167
+ entries = [l[:-1] + '/' if l.endswith('\\') else l for l in lines if l]
168
+ return f'{path} (directory)\n' + clip('\n'.join(entries)) + f'\n({len(entries)} entries)'
169
+ nums = [re.match('(\\d+): ?', l) for l in lines]
170
+ if not all(nums):
171
+ return text
172
+ body = '\n'.join((l[k.end():] for l, k in zip(lines, nums)))
173
+ first, last = (int(first), int(last))
174
+ if first == 1 and (total is None and last - first + 1 < 2000 or (total and last >= int(total))):
175
+ return f'{path} (end of file, {last} lines)\n' + clip(body)
176
+ return f'{path} (lines {first}-{last}' + (f' of {total}' if total else '') + ')\n' + clip(body)
177
+
178
+ def read_result(path, content, first=1, total=None):
179
+ n = content.count('\n') + 1 if content else 0
180
+ if first == 1 and (total is None or n >= total):
181
+ return f'{path} (end of file, {n} lines)\n' + clip(content)
182
+ return f'{path} (lines {first}-{first + n - 1}' + (f' of {total}' if total else '') + ')\n' + clip(content)
183
+
184
+ def compact_result(name, text):
185
+ text = text if isinstance(text, str) else json.dumps(text, ensure_ascii=False)
186
+ if text.startswith('{"error"'):
187
+ try:
188
+ text = 'Error: ' + json.loads(text)['error']['message']
189
+ except (ValueError, KeyError, TypeError):
190
+ pass
191
+ return compact_read(text) if name == 'read' else clip(text)
192
+
193
+ def content_text(c):
194
+ if isinstance(c, list):
195
+ return ''.join((x.get('text', '') for x in c if isinstance(x, dict)))
196
+ return c or ''
197
+
198
+ def think_text(m):
199
+ t = (m.get('reasoning') or m.get('reasoning_content') or '').strip()
200
+ return f'<|think|>{t}<|/think|>' if t else ''
201
+
202
+ def render(messages, tools=None, env=None, system=None):
203
+ out = [(f'<|system|>{(system if system is not None else system_text(env))}', False)]
204
+ if tools:
205
+ out.append((f'<|tools|>{tools_text(tools)}', False))
206
+ results = {m.get('tool_call_id'): m for m in messages if m['role'] == 'tool'}
207
+ for m in messages:
208
+ role = m['role']
209
+ if role == 'system':
210
+ continue
211
+ if role == 'user':
212
+ out.append((f"<|user|>{content_text(m.get('content'))}", False))
213
+ elif role == 'assistant':
214
+ text, calls = (content_text(m.get('content')).strip(), m.get('tool_calls') or [])
215
+ th = think_text(m)
216
+ learn = m.get('learn', True)
217
+ if not calls:
218
+ out += [('<|assistant|>', False), (f'{th}{text}<|end|>', learn)]
219
+ continue
220
+ for j, c in enumerate(calls):
221
+ f = c['function']
222
+ args = f.get('arguments') or '{}'
223
+ args = json.loads(args) if isinstance(args, str) else args
224
+ out += [('<|assistant|>', False), ((th + text + ('\n' if text else '') if j == 0 else '') + call_text(f['name'], args), learn)]
225
+ r = results.get(c.get('id'))
226
+ out.append((f"<|tool|>{compact_result(f['name'], content_text(r.get('content')) if r else '(no result)')}", False))
227
+ return out
228
+
229
+ def text_of(segments):
230
+ return ''.join((t for t, _ in segments))
tetu_code/generate.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Têtu Code 2 — inference code (tetu-AI). License: Apache 2.0, see README.md.
2
+ from pathlib import Path
3
+ import math
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch.nn.attention import SDPBackend, sdpa_kernel
8
+ from tokenizers import Tokenizer
9
+ from tetu_code.model import TetuCode, TetuCodeConfig, apply_rope, rms, rope_table, unpack_struct
10
+ from tetu_code.structure import Tables, features
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+
13
+ def attend(q, k, v, mask):
14
+ B, H, T, hd = q.shape
15
+ G = H // k.size(1)
16
+ if T == 1:
17
+ with sdpa_kernel(SDPBackend.MATH):
18
+ y = F.scaled_dot_product_attention(q.reshape(B, H // G, G, hd), k, v, attn_mask=mask)
19
+ return y.reshape(B, H, 1, hd)
20
+ return F.scaled_dot_product_attention(q, k.repeat_interleave(G, 1), v.repeat_interleave(G, 1), attn_mask=mask)
21
+
22
+ def load(path, device='cuda', dtype=torch.bfloat16, tokenizer=None):
23
+ if Path(path).is_dir():
24
+ import json
25
+ from safetensors.torch import load_file
26
+ meta = json.loads((Path(path) / 'config.json').read_text(encoding='utf-8'))
27
+ ck = dict(meta, model=load_file(str(Path(path) / 'model.safetensors')))
28
+ else:
29
+ ck = torch.load(path, map_location='cpu', weights_only=False)
30
+ cfg = TetuCodeConfig(**ck['config'])
31
+ with torch.device(device):
32
+ model = TetuCode(cfg)
33
+ model.to(device)
34
+ model.load_state_dict(ck['model'])
35
+ if torch.device(device).type != 'cpu':
36
+ with torch.device('cpu'):
37
+ for name, theta in (('loc', cfg.rope_local), ('glo', cfg.rope_global)):
38
+ cosine, sine = rope_table(cfg.max_seq_len, cfg.d_model // cfg.n_heads, theta)
39
+ setattr(model, f'cos_{name}', cosine.to(device))
40
+ setattr(model, f'sin_{name}', sine.to(device))
41
+ for name, p in model.named_parameters():
42
+ if not name.startswith('doubt_head'):
43
+ p.data = p.data.to(dtype)
44
+ model.to(device).eval()
45
+ model.meta = {k: ck.get(k) for k in ('step', 'tokens', 'val')}
46
+ return (model, Tokenizer.from_file(str(tokenizer or ROOT / 'tokenizer.json')))
47
+
48
+ class Decoder:
49
+
50
+ def __init__(self, model, tok, max_len=32768, ring=4096, chunk=2048, graph=True, compile=False, memo=None):
51
+ self.memo = memo
52
+ cfg = model.cfg
53
+ self.model, self.tok, self.cfg = (model, tok, cfg)
54
+ self.dev = next(model.parameters()).device
55
+ dt = model.tok_emb.weight.dtype
56
+ hd = cfg.d_model // cfg.n_heads
57
+ self.max_len, self.ring, self.chunk, self.sw = (max_len, ring, chunk, cfg.window // 128)
58
+ assert ring >= chunk + cfg.window, 'anneau trop petit pour le pré-remplissage par morceaux'
59
+ self.S = [max_len if b.attn.is_global else ring for b in model.blocks]
60
+ self.K = [torch.zeros(1, cfg.n_kv_heads, s, hd, device=self.dev, dtype=dt) for s in self.S]
61
+ self.V = [torch.zeros_like(k) for k in self.K]
62
+ self.ring_pos = torch.full((ring,), -(1 << 40), dtype=torch.long, device=self.dev)
63
+ self.tok_ring = torch.full((ring,), cfg.vocab_size, dtype=torch.long, device=self.dev)
64
+ self.eng = [i for i, b in enumerate(model.blocks) if b.engram is not None]
65
+ self.order = max((max(o) for _, o in cfg.engram))
66
+ self.s_ring = {i: torch.zeros(1, ring, cfg.d_model, device=self.dev, dtype=dt) for i in self.eng}
67
+ self.gidx = torch.arange(max_len, device=self.dev)
68
+ self.tab = Tables(tok).arrays
69
+ self.flag = self.tab[2]
70
+ self.ids, self.st, self.reset_at = ([], [], 0)
71
+ self.t_in = torch.zeros(1, 1, dtype=torch.long, device=self.dev)
72
+ self.s_in = torch.zeros(1, 1, dtype=torch.int16, device=self.dev)
73
+ self.p_in = torch.zeros(1, dtype=torch.long, device=self.dev)
74
+ self.temp_t = torch.zeros((), device=self.dev)
75
+ self.top_p_t = torch.full((), 0.95, device=self.dev)
76
+ self.noise = torch.ones(50, device=self.dev)
77
+ self.nxt = torch.zeros((), dtype=torch.long, device=self.dev)
78
+ self._doubt = None
79
+ self.graphs = {}
80
+ if graph and self.dev.type == 'cuda':
81
+ step = self._step
82
+ if compile:
83
+ import torch._dynamo as dynamo
84
+ dynamo.config.cache_size_limit = max(dynamo.config.cache_size_limit, 16)
85
+ step = torch.compile(self._step, dynamic=False)
86
+ for n in sorted({min(4096 << i, max_len) for i in range(8) if (4096 << i) // 2 < max_len}):
87
+ s = torch.cuda.Stream()
88
+ s.wait_stream(torch.cuda.current_stream())
89
+ with torch.cuda.stream(s):
90
+ for _ in range(3):
91
+ self.noise.exponential_()
92
+ step(n)
93
+ torch.cuda.current_stream().wait_stream(s)
94
+ g = torch.cuda.CUDAGraph()
95
+ with torch.cuda.graph(g):
96
+ self.noise.exponential_()
97
+ self.graphs[n] = (g, step(n))
98
+ self.reset()
99
+
100
+ @property
101
+ def last_doubt(self):
102
+ return float(self._doubt[0, -1]) if self._doubt is not None else 0.0
103
+
104
+ def reset(self):
105
+ self.ring_pos.fill_(-(1 << 40))
106
+ self.tok_ring.fill_(self.cfg.vocab_size)
107
+ for r in self.s_ring.values():
108
+ r.zero_()
109
+ self.ids, self.st, self.reset_at = ([], [], 0)
110
+
111
+ def _struct(self, new):
112
+ s0 = self.reset_at
113
+ st = features(np.asarray(self.ids[s0:] + list(new), dtype=np.int64), *self.tab)
114
+ return [int(v) for v in st[len(self.ids) - s0:]]
115
+
116
+ def _append(self, toks, st):
117
+ for t in toks:
118
+ if self.flag[t] == 1:
119
+ self.reset_at = len(self.ids)
120
+ self.ids.append(t)
121
+ self.st += st
122
+
123
+ def rollback(self, n):
124
+ if n <= 0:
125
+ return True
126
+ if n > self.ring - self.cfg.window - 128:
127
+ return False
128
+ p = len(self.ids) - n
129
+ self.ring_pos.masked_fill_(self.ring_pos >= p, -(1 << 40))
130
+ del self.ids[p:], self.st[p:]
131
+ r = np.flatnonzero(self.flag[np.asarray(self.ids, dtype=np.int64)] == 1) if self.ids else []
132
+ self.reset_at = int(r[-1]) if len(r) else 0
133
+ return True
134
+
135
+ def sync(self, ids):
136
+ ids = list(ids)
137
+ k = 0
138
+ n = min(len(ids), len(self.ids))
139
+ while k < n and ids[k] == self.ids[k]:
140
+ k += 1
141
+ if k == len(ids) and k > 0:
142
+ k -= 1
143
+ if not self.rollback(len(self.ids) - k):
144
+ self.reset()
145
+ k = 0
146
+ return self.feed(ids[k:])
147
+
148
+ @torch.no_grad()
149
+ def feed(self, new):
150
+ assert len(self.ids) + len(new) < self.max_len, 'contexte trop long'
151
+ out = None
152
+ for a in range(0, len(new), self.chunk):
153
+ part = new[a:a + self.chunk]
154
+ if len(part) == 1 and self.graphs:
155
+ out = self.step(part[0])
156
+ else:
157
+ out = self._prefill(part)
158
+ return out
159
+
160
+ def step(self, t):
161
+ if not self.graphs:
162
+ return self._prefill([t])
163
+ st = self._struct([t])[0]
164
+ n = len(self.ids)
165
+ g, out = next((v for k, v in self.graphs.items() if k > n))
166
+ self.t_in.fill_(t)
167
+ self.s_in.fill_(st)
168
+ self.p_in.fill_(n)
169
+ g.replay()
170
+ self._append([t], [st])
171
+ return out
172
+
173
+ def _rope(self, pos):
174
+ m = self.model
175
+ qs = (torch.log(pos.float() + 1) / math.log(self.cfg.log_base)).clamp_min(1.0)
176
+ return ((m.cos_loc[pos], m.sin_loc[pos]), (m.cos_glo[pos], m.sin_glo[pos]), qs)
177
+
178
+ def _embed(self, idx, st):
179
+ m = self.model
180
+ x = m.tok_emb(idx)
181
+ for e, f in zip(m.struct_emb, unpack_struct(st)):
182
+ x = x + e(f)
183
+ return rms(x)
184
+
185
+ def _layers(self, x, idx, pos, single):
186
+ m, cfg = (self.model, self.cfg)
187
+ T = idx.size(1)
188
+ loc, glo, qs = self._rope(pos)
189
+ L, skips = (cfg.n_layers, [])
190
+ slot = pos % self.ring
191
+ self.tok_ring.index_copy_(0, slot, idx[0])
192
+ self.ring_pos.index_copy_(0, slot, pos)
193
+ for i, blk in enumerate(m.blocks):
194
+ if i >= L - L // 2:
195
+ x = x + m.skip_w[L - 1 - i] * skips.pop()
196
+ if blk.engram is not None:
197
+ eng, xe = (blk.engram, rms(x))
198
+ back = pos[None, :] - torch.arange(self.order - 1, -1, -1, device=self.dev)[:, None]
199
+ ctx = torch.where(back >= 0, self.tok_ring[back % self.ring], torch.full_like(back, cfg.eos_id))
200
+ e = eng.table(eng.slots(ctx.t().contiguous())[:, -1]).reshape(1, T, -1).to(x.dtype)
201
+ k, v = (eng.wk(e), eng.wv(e))
202
+ alpha = torch.sigmoid((rms(xe) * rms(k)).sum(-1, keepdim=True) / math.sqrt(cfg.d_model))
203
+ s = alpha * v
204
+ self.s_ring[i][0].index_copy_(0, slot, s[0])
205
+ prev = pos[None, :] - torch.arange(3, 0, -1, device=self.dev)[:, None]
206
+ ps = torch.where((prev >= 0)[..., None], self.s_ring[i][0][prev % self.ring], torch.zeros_like(s[0]))
207
+ win = torch.cat([ps, s], dim=0).permute(1, 2, 0)
208
+ c = (win * eng.conv.weight[:, 0, :]).sum(-1)
209
+ x = x + s + F.silu(c[None])
210
+ att, xa = (blk.attn, rms(x))
211
+ q = att.wq(xa).view(1, T, att.H, att.hd).transpose(1, 2)
212
+ k = att.wk(xa).view(1, T, att.Hk, att.hd).transpose(1, 2)
213
+ v = att.wv(xa).view(1, T, att.Hk, att.hd).transpose(1, 2)
214
+ j = m.ve_layer.get(i)
215
+ if j is not None:
216
+ v = v + m.ve_lambda[i] * m.value_embeds[j](idx).to(v.dtype).view(1, T, att.Hk, att.hd).transpose(1, 2)
217
+ c_, s_ = glo if att.is_global else loc
218
+ q, k = (apply_rope(rms(q), c_, s_), apply_rope(rms(k), c_, s_))
219
+ if att.is_global:
220
+ q = q * qs.to(q.dtype)[:, None]
221
+ self.K[i].index_copy_(2, pos, k)
222
+ self.V[i].index_copy_(2, pos, v)
223
+ if single:
224
+ Kc, Vc = (self.K[i][:, :, :single], self.V[i][:, :, :single])
225
+ mask = (self.gidx[:single] <= pos[0])[None, None, None]
226
+ else:
227
+ end = int(pos[-1]) + 1
228
+ Kc, Vc = (self.K[i][:, :, :end], self.V[i][:, :, :end])
229
+ kp = self.gidx[:end]
230
+ mask = (kp[None] <= pos[:, None])[None, None]
231
+ else:
232
+ self.K[i].index_copy_(2, slot, k)
233
+ self.V[i].index_copy_(2, slot, v)
234
+ if single:
235
+ rp = self.ring_pos
236
+ Kc, Vc = (self.K[i], self.V[i])
237
+ mask = ((rp <= pos[0]) & (rp // 128 > pos[0] // 128 - self.sw))[None, None, None]
238
+ else:
239
+ k0 = max(0, (int(pos[0]) // 128 - self.sw + 1) * 128)
240
+ kp = torch.arange(k0, int(pos[-1]) + 1, device=self.dev)
241
+ Kc, Vc = (self.K[i][:, :, kp % self.ring], self.V[i][:, :, kp % self.ring])
242
+ mask = ((kp[None] <= pos[:, None]) & (pos[:, None] // 128 - kp[None] // 128 < self.sw))[None, None]
243
+ y = attend(q, Kc, Vc, mask)
244
+ x = x + att.wo(y.transpose(1, 2).reshape(1, T, -1) * torch.sigmoid(att.wg(xa)))
245
+ x = x + blk.mlp(rms(x))
246
+ if self.memo is not None and i == self.memo.L:
247
+ if getattr(self.memo, 'exact', False):
248
+ back = pos[None, :] - torch.arange(self.memo.K - 1, -1, -1, device=self.dev)[:, None]
249
+ ctx = torch.where(back >= 0, self.tok_ring[back % self.ring], torch.full_like(back, -1))
250
+ x = self.memo(x, ctx.t()[None])
251
+ else:
252
+ x = self.memo(x)
253
+ if i < L // 2:
254
+ skips.append(x)
255
+ return rms(x)
256
+
257
+ @torch.no_grad()
258
+ def _step(self, n):
259
+ h = self._layers(self._embed(self.t_in, self.s_in), self.t_in, self.p_in, n)
260
+ logits = self.model.logits(h)
261
+ z = logits[0, -1].float()
262
+ v, i = torch.topk(z / self.temp_t.clamp_min(1e-06), 50)
263
+ p = torch.softmax(v, -1)
264
+ p = torch.where(torch.cumsum(p, -1) - p < self.top_p_t, p, torch.zeros_like(p))
265
+ pick = i.gather(0, torch.argmax(p / self.noise).view(1))[0]
266
+ self.nxt.copy_(torch.where(self.temp_t > 0, pick, z.argmax()))
267
+ return (logits, torch.sigmoid(self.model.doubt_head(h, logits)))
268
+
269
+ @torch.no_grad()
270
+ def _prefill(self, part):
271
+ st = self._struct(part)
272
+ idx = torch.tensor([part], device=self.dev)
273
+ sx = torch.tensor([st], device=self.dev, dtype=torch.int16)
274
+ pos = torch.arange(len(self.ids), len(self.ids) + len(part), device=self.dev)
275
+ h = self._layers(self._embed(idx, sx), idx, pos, 0)[:, -1:]
276
+ self._append(list(part), st)
277
+ logits = self.model.logits(h)
278
+ return (logits, torch.sigmoid(self.model.doubt_head(h, logits)))
279
+
280
+ @torch.no_grad()
281
+ def generate(self, ids, max_new=512, temp=0.0, top_p=0.95, top_k=50, stop=(), seed=0):
282
+ g = torch.Generator(device=self.dev).manual_seed(seed)
283
+ self.temp_t.fill_(max(temp, 0.0))
284
+ self.top_p_t.fill_(top_p)
285
+ in_graph = bool(self.graphs) and top_k == 50
286
+ logits, doubt = self.sync(ids)
287
+ stop = set(stop)
288
+ t = None
289
+ for _ in range(max_new):
290
+ if t is None:
291
+ z = logits[0, -1].float()
292
+ if temp <= 0:
293
+ t = int(z.argmax())
294
+ else:
295
+ v, i = torch.topk(z / temp, top_k)
296
+ p = torch.softmax(v, -1)
297
+ keep = torch.cumsum(p, -1) - p < top_p
298
+ p = torch.where(keep, p, torch.zeros_like(p))
299
+ t = int(i[torch.multinomial(p / p.sum(), 1, generator=g)])
300
+ self._doubt = doubt
301
+ yield t
302
+ if t in stop:
303
+ return
304
+ logits, doubt = self.step(t)
305
+ t = int(self.nxt) if in_graph else None
tetu_code/model.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Têtu Code 2 — inference code (tetu-AI). License: Apache 2.0, see README.md.
2
+ from dataclasses import asdict, dataclass, field
3
+ import math
4
+ from typing import Optional
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ try:
9
+ from torch.nn.attention.flex_attention import BlockMask, flex_attention
10
+ except ImportError:
11
+ BlockMask = flex_attention = None
12
+
13
+ @dataclass
14
+ class TetuCodeConfig:
15
+ vocab_size: int = 32768
16
+ d_model: int = 768
17
+ n_layers: int = 24
18
+ n_heads: int = 12
19
+ n_kv_heads: int = 4
20
+ mlp_mult: int = 4
21
+ max_seq_len: int = 65536
22
+ window: int = 2048
23
+ global_every: int = 4
24
+ rope_local: float = 10000.0
25
+ rope_global: float = 500000.0
26
+ log_base: int = 4096
27
+ engram: tuple = ((1, (2, 3)), (8, (3, 4)), (15, (4, 6)))
28
+ engram_heads: int = 2
29
+ engram_slots: int = 393209
30
+ engram_dim: int = 128
31
+ n_value_embeds: int = 3
32
+ struct_sizes: tuple = (16, 16, 4, 2)
33
+ softcap: float = 30.0
34
+ doubt_weight: float = 0.1
35
+ eos_id: int = 1
36
+
37
+ def __post_init__(self):
38
+ self.engram = tuple(((int(l), tuple(o)) for l, o in self.engram))
39
+ self.struct_sizes = tuple(self.struct_sizes)
40
+
41
+ def is_global(self, i):
42
+ return (i + 1) % self.global_every == 0
43
+
44
+ def to_dict(self):
45
+ return asdict(self)
46
+
47
+ def rms(x):
48
+ return F.rms_norm(x, (x.size(-1),))
49
+
50
+ def rope_table(n, hd, theta):
51
+ inv = 1.0 / theta ** (torch.arange(0, hd, 2, dtype=torch.float32) / hd)
52
+ f = torch.outer(torch.arange(n, dtype=torch.float32), inv)
53
+ return (f.cos(), f.sin())
54
+
55
+ def apply_rope(x, cos, sin):
56
+ x1, x2 = x.chunk(2, dim=-1)
57
+ return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1).type_as(x)
58
+
59
+ def _ordered(m):
60
+ num = m.sum(dim=-1, dtype=torch.int32)
61
+ idx = m.to(torch.int32).argsort(dim=-1, descending=False, stable=True).flip(-1).to(torch.int32)
62
+ return (num[None, None].contiguous(), idx[None, None].contiguous())
63
+
64
+ def doc_block_masks(doc, window, block=128):
65
+ n, sw = (doc.size(0) // block, window // block)
66
+
67
+ def doc_causal(b, h, q, kv):
68
+ return (q >= kv) & (doc[q] == doc[kv])
69
+
70
+ def doc_local(b, h, q, kv):
71
+ return doc_causal(b, h, q, kv) & (q // block - kv // block < sw)
72
+ i = torch.arange(n, device=doc.device)
73
+ lo, hi = (doc.view(n, block)[:, 0], doc.view(n, block)[:, -1])
74
+ some = (i[:, None] >= i[None]) & (lo[:, None] <= hi[None]) & (lo[None] <= hi[:, None])
75
+ full = (i[:, None] > i[None]) & (lo[:, None] == hi[None]) & (lo[None] == hi[:, None])
76
+ kn, ki = _ordered(some & ~full)
77
+ fn, fi = _ordered(full)
78
+ mk = lambda a, b, f: BlockMask.from_kv_blocks(a, ki, b, fi, BLOCK_SIZE=block, mask_mod=f)
79
+ return (mk(kn, fn, doc_causal), mk(torch.clamp_max(kn, torch.clamp_min(sw - fn, 1)), torch.clamp_max(fn, sw - 1), doc_local))
80
+
81
+ def dense_masks(doc, window, block=128):
82
+ i = torch.arange(doc.size(0), device=doc.device)
83
+ g = (i[:, None] >= i[None]) & (doc[:, None] == doc[None])
84
+ return (g, g & (i[:, None] // block - i[None] // block < window // block))
85
+
86
+ class Linear(nn.Linear):
87
+
88
+ def __init__(self, i, o, zero=False):
89
+ super().__init__(i, o, bias=False)
90
+ with torch.no_grad():
91
+ if zero:
92
+ self.weight.zero_()
93
+ else:
94
+ b = math.sqrt(3) * 0.5 / math.sqrt(i)
95
+ self.weight.uniform_(-b, b)
96
+
97
+ class Engram(nn.Module):
98
+ P = 2147483647
99
+
100
+ def __init__(self, cfg: TetuCodeConfig, orders, seed):
101
+ super().__init__()
102
+ self.orders, self.K, self.S, self.dm = (tuple(orders), cfg.engram_heads, cfg.engram_slots, cfg.engram_dim)
103
+ self.n_tab = len(self.orders) * self.K
104
+ self.pad_id = cfg.vocab_size
105
+ self.table = nn.Embedding(self.n_tab * self.S, self.dm)
106
+ nn.init.normal_(self.table.weight, std=1.0)
107
+ g = torch.Generator().manual_seed(seed)
108
+ mult = torch.randint(1 << 20, 1 << 30, (self.n_tab, max(self.orders)), generator=g, device=g.device) | 1
109
+ self.register_buffer('mult', mult, persistent=False)
110
+ self.register_buffer('offset', torch.arange(self.n_tab) * self.S, persistent=False)
111
+ d, de = (cfg.d_model, self.n_tab * self.dm)
112
+ self.wk = Linear(de, d)
113
+ self.wv = Linear(de, d, zero=True)
114
+ self.conv = nn.Conv1d(d, d, 4, groups=d, bias=False)
115
+ nn.init.zeros_(self.conv.weight)
116
+
117
+ def slots(self, idx):
118
+ T = idx.size(1)
119
+ grams = [idx] + [F.pad(idx, (j, 0), value=self.pad_id)[:, :T] for j in range(1, max(self.orders))]
120
+ out, t = ([], 0)
121
+ for o in self.orders:
122
+ for _ in range(self.K):
123
+ h = torch.zeros_like(idx)
124
+ for j in range(o):
125
+ h = (h * 1000003 + (grams[j] + 1) * self.mult[t, j]) % self.P
126
+ out.append(h % self.S + self.offset[t])
127
+ t += 1
128
+ return torch.stack(out, dim=-1)
129
+
130
+ def read(self, x, e):
131
+ k, v = (self.wk(e), self.wv(e))
132
+ alpha = torch.sigmoid((rms(x) * rms(k)).sum(-1, keepdim=True) / math.sqrt(x.size(-1)))
133
+ return (alpha * v, alpha)
134
+
135
+ def forward(self, x, idx):
136
+ B, T, d = x.shape
137
+ e = self.table(self.slots(idx)).reshape(B, T, -1).to(x.dtype)
138
+ s, alpha = self.read(x, e)
139
+ c = self.conv(F.pad(s.transpose(1, 2), (3, 0))).transpose(1, 2)
140
+ if not torch.compiler.is_compiling():
141
+ self.last_gate = alpha.detach().float().mean()
142
+ return s + F.silu(c)
143
+
144
+ class Attention(nn.Module):
145
+
146
+ def __init__(self, cfg: TetuCodeConfig, is_global: bool):
147
+ super().__init__()
148
+ self.H, self.Hk = (cfg.n_heads, cfg.n_kv_heads)
149
+ self.hd = cfg.d_model // cfg.n_heads
150
+ d = cfg.d_model
151
+ self.wq = Linear(d, self.H * self.hd)
152
+ self.wk = Linear(d, self.Hk * self.hd)
153
+ self.wv = Linear(d, self.Hk * self.hd)
154
+ self.wg = Linear(d, self.H * self.hd)
155
+ self.wo = Linear(self.H * self.hd, d, zero=True)
156
+ self.is_global, self.window = (is_global, cfg.window)
157
+
158
+ def qkv(self, x, cos, sin, qs=None, ve=None, lam=None):
159
+ B, T, _ = x.shape
160
+ q = self.wq(x).view(B, T, self.H, self.hd).transpose(1, 2)
161
+ k = self.wk(x).view(B, T, self.Hk, self.hd).transpose(1, 2)
162
+ v = self.wv(x).view(B, T, self.Hk, self.hd).transpose(1, 2)
163
+ if ve is not None:
164
+ v = v + lam * ve.to(v.dtype).view(B, T, self.Hk, self.hd).transpose(1, 2)
165
+ q, k = (apply_rope(rms(q), cos, sin), apply_rope(rms(k), cos, sin))
166
+ if qs is not None:
167
+ q = q * qs.to(q.dtype)[:, None]
168
+ return (q, k, v)
169
+
170
+ def forward(self, x, cos, sin, mask, qs=None, ve=None, lam=None):
171
+ B, T, _ = x.shape
172
+ q, k, v = self.qkv(x, cos, sin, qs, ve, lam)
173
+ if mask is not None and (not isinstance(mask, torch.Tensor)):
174
+ y = flex_attention(q, k, v, block_mask=mask, enable_gqa=True)
175
+ else:
176
+ r = self.H // self.Hk
177
+ k, v = (k.repeat_interleave(r, dim=1), v.repeat_interleave(r, dim=1))
178
+ if mask is not None:
179
+ y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
180
+ elif self.is_global or T <= self.window - 127:
181
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
182
+ else:
183
+ i = torch.arange(T, device=x.device)
184
+ m = (i[:, None] >= i[None]) & (i[:, None] // 128 - i[None] // 128 < self.window // 128)
185
+ y = F.scaled_dot_product_attention(q, k, v, attn_mask=m)
186
+ y = y.transpose(1, 2).reshape(B, T, -1) * torch.sigmoid(self.wg(x))
187
+ return self.wo(y)
188
+
189
+ class MLP(nn.Module):
190
+
191
+ def __init__(self, d, h):
192
+ super().__init__()
193
+ self.w1, self.w2 = (Linear(d, h), Linear(h, d, zero=True))
194
+
195
+ def forward(self, x):
196
+ return self.w2(F.relu(self.w1(x)).square())
197
+
198
+ class Block(nn.Module):
199
+
200
+ def __init__(self, cfg: TetuCodeConfig, i: int, engram_orders=None):
201
+ super().__init__()
202
+ self.attn = Attention(cfg, cfg.is_global(i))
203
+ self.mlp = MLP(cfg.d_model, cfg.mlp_mult * cfg.d_model)
204
+ self.engram = Engram(cfg, engram_orders, seed=1234 + i) if engram_orders else None
205
+
206
+ def forward(self, x, idx, cos, sin, mask, qs, ve, lam):
207
+ if self.engram is not None:
208
+ x = x + self.engram(rms(x), idx)
209
+ x = x + self.attn(rms(x), cos, sin, mask, qs, ve, lam)
210
+ return x + self.mlp(rms(x))
211
+
212
+ class DoubtHead(nn.Module):
213
+
214
+ def __init__(self, d):
215
+ super().__init__()
216
+ self.net = nn.Sequential(nn.Linear(d + 2, 128), nn.ReLU(), nn.Linear(128, 1))
217
+
218
+ def forward(self, h, logits):
219
+ with torch.no_grad():
220
+ lp = F.log_softmax(logits.float(), dim=-1)
221
+ conf = torch.stack([lp.max(-1).values, -(lp.exp() * lp).sum(-1)], dim=-1) / 4
222
+ return self.net(torch.cat([rms(h.detach()).float(), conf], dim=-1)).squeeze(-1)
223
+
224
+ @dataclass
225
+ class Output:
226
+ logits: torch.Tensor
227
+ loss: Optional[torch.Tensor] = None
228
+ lm_loss: Optional[torch.Tensor] = None
229
+ doubt_loss: Optional[torch.Tensor] = None
230
+ doubt: Optional[torch.Tensor] = None
231
+ unlike_loss: Optional[torch.Tensor] = None
232
+
233
+ def unpack_struct(s):
234
+ s = s.long()
235
+ return (s & 15, s >> 4 & 15, s >> 8 & 3, s >> 10 & 1)
236
+
237
+ class TetuCode(nn.Module):
238
+
239
+ def __init__(self, cfg: TetuCodeConfig):
240
+ super().__init__()
241
+ self.unlike_weight = 1.0
242
+ self.ckpt_blocks = False
243
+ self.head_chunk = 8192
244
+ self.cfg = cfg
245
+ d, L = (cfg.d_model, cfg.n_layers)
246
+ kv = cfg.n_kv_heads * (d // cfg.n_heads)
247
+ self.tok_emb = nn.Embedding(cfg.vocab_size, d)
248
+ nn.init.normal_(self.tok_emb.weight, std=1.0)
249
+ self.struct_emb = nn.ModuleList((nn.Embedding(n, d) for n in cfg.struct_sizes))
250
+ for e in self.struct_emb:
251
+ nn.init.normal_(e.weight, std=0.3)
252
+ self.value_embeds = nn.ModuleList((nn.Embedding(cfg.vocab_size, kv) for _ in range(cfg.n_value_embeds)))
253
+ for e in self.value_embeds:
254
+ nn.init.normal_(e.weight, std=1.0)
255
+ n = cfg.n_value_embeds
256
+ self.ve_layer = {i: i for i in range(n)} | {L - n + i: i for i in range(n)}
257
+ self.ve_lambda = nn.Parameter(torch.full((L,), 0.5))
258
+ eng = dict(cfg.engram)
259
+ self.blocks = nn.ModuleList((Block(cfg, i, eng.get(i)) for i in range(L)))
260
+ self.skip_w = nn.Parameter(torch.ones(L // 2))
261
+ self.lm_head = Linear(d, cfg.vocab_size, zero=True)
262
+ self.doubt_head = DoubtHead(d)
263
+ hd = d // cfg.n_heads
264
+ for name, theta in (('loc', cfg.rope_local), ('glo', cfg.rope_global)):
265
+ c, s = rope_table(cfg.max_seq_len, hd, theta)
266
+ self.register_buffer(f'cos_{name}', c, persistent=False)
267
+ self.register_buffer(f'sin_{name}', s, persistent=False)
268
+
269
+ def num_params(self):
270
+ return sum((p.numel() for p in self.parameters()))
271
+
272
+ def compute_params(self):
273
+ lookup = self.tok_emb.weight.numel() + sum((e.weight.numel() for e in self.value_embeds))
274
+ lookup += sum((e.weight.numel() for e in self.struct_emb))
275
+ lookup += sum((b.engram.table.weight.numel() for b in self.blocks if b.engram is not None))
276
+ return self.num_params() - lookup
277
+
278
+ def param_groups(self):
279
+ tables, engram, head, scal, muon = ([], [], [], [], [])
280
+ for n, p in self.named_parameters():
281
+ if n.endswith('engram.table.weight'):
282
+ engram.append(p)
283
+ elif n.startswith(('tok_emb', 'value_embeds', 'struct_emb')):
284
+ tables.append(p)
285
+ elif n.startswith('lm_head'):
286
+ head.append(p)
287
+ elif p.dim() == 2 and (not n.startswith('doubt_head')):
288
+ muon.append(p)
289
+ else:
290
+ scal.append(p)
291
+ return {'tables': tables, 'engram': engram, 'head': head, 'scalars': scal, 'muon': muon}
292
+
293
+ def rope(self, T, pos=None):
294
+ p = torch.arange(T, device=self.cos_loc.device) if pos is None else pos
295
+ qs = (torch.log(p.float() + 1) / math.log(self.cfg.log_base)).clamp_min(1.0)
296
+ return ((self.cos_loc[p], self.sin_loc[p]), (self.cos_glo[p], self.sin_glo[p]), qs)
297
+
298
+ def embed(self, idx, struct=None):
299
+ x = self.tok_emb(idx)
300
+ if struct is not None:
301
+ for e, f in zip(self.struct_emb, unpack_struct(struct)):
302
+ x = x + e(f)
303
+ return rms(x)
304
+
305
+ def hidden(self, idx, struct=None, doc=None, pos=None):
306
+ B, T = idx.shape
307
+ loc, glo, qs = self.rope(T, pos)
308
+ x = self.embed(idx, struct)
309
+ L, skips = (self.cfg.n_layers, [])
310
+ mg = ml = None
311
+ if doc is not None:
312
+ mg, ml = (doc_block_masks if idx.is_cuda else dense_masks)(doc, self.cfg.window)
313
+ for i, blk in enumerate(self.blocks):
314
+ if i >= L - L // 2:
315
+ x = x + self.skip_w[L - 1 - i] * skips.pop()
316
+ j = self.ve_layer.get(i)
317
+ ve = self.value_embeds[j](idx) if j is not None else None
318
+ g = blk.attn.is_global
319
+ c, s = glo if g else loc
320
+ args = (x, idx, c, s, mg if g else ml, qs if g else None, ve, self.ve_lambda[i])
321
+ if self.ckpt_blocks and torch.is_grad_enabled():
322
+ x = torch.utils.checkpoint.checkpoint(blk, *args, use_reentrant=False)
323
+ else:
324
+ x = blk(*args)
325
+ if i < L // 2:
326
+ skips.append(x)
327
+ return rms(x)
328
+
329
+ def logits(self, h):
330
+ z = self.lm_head(h).float()
331
+ return self.cfg.softcap * torch.tanh(z / self.cfg.softcap)
332
+
333
+ def _head_chunk(self, h, t):
334
+ z = self.logits(h)
335
+ lse = torch.logsumexp(z, -1)
336
+ good, bad = (t >= 0, t <= -200)
337
+ zt = z.gather(-1, torch.where(good, t, (-t - 200).clamp(0, z.size(-1) - 1))[:, None])[:, 0]
338
+ loss = ((lse - zt) * good).sum()
339
+ p_bad = torch.exp(zt - lse).clamp(max=1 - 1e-06)
340
+ unlike = (-torch.log1p(-p_bad) * bad).sum()
341
+ with torch.no_grad():
342
+ lp = F.log_softmax(z, dim=-1)
343
+ conf = torch.stack([lp.max(-1).values, -(lp.exp() * lp).sum(-1)], dim=-1) / 4
344
+ wrong = (z.argmax(-1) != t).float()
345
+ return (loss, conf, wrong, unlike)
346
+
347
+ def forward(self, idx, targets=None, struct=None, doc=None, pos=None, chunk=None):
348
+ chunk = chunk or self.head_chunk
349
+ h = self.hidden(idx, struct, doc, pos)
350
+ if targets is None:
351
+ logits = self.logits(h)
352
+ return Output(logits=logits, doubt=torch.sigmoid(self.doubt_head(h, logits)))
353
+ hf, tf = (h.flatten(0, 1), targets.flatten())
354
+ parts = [torch.utils.checkpoint.checkpoint(self._head_chunk, hf[i:i + chunk], tf[i:i + chunk], use_reentrant=False) for i in range(0, hf.size(0), chunk)]
355
+ mask = tf >= 0
356
+ n = mask.sum().clamp_min(1)
357
+ conf = torch.cat([p[1] for p in parts])
358
+ wrong = torch.cat([p[2] for p in parts])
359
+ doubt_logit = self.doubt_head.net(torch.cat([rms(hf.detach()).float(), conf], dim=-1)).squeeze(-1)
360
+ bce = F.binary_cross_entropy_with_logits(doubt_logit, wrong, reduction='none')
361
+ out = Output(logits=None, doubt=None)
362
+ out.lm_loss = sum((p[0] for p in parts)) / n
363
+ out.doubt_loss = (bce * mask).sum() / n
364
+ out.unlike_loss = sum((p[3] for p in parts)) / n
365
+ out.loss = out.lm_loss + self.cfg.doubt_weight * out.doubt_loss + self.unlike_weight * out.unlike_loss
366
+ return out
367
+
368
+ def engram_gates(self):
369
+ return [b.engram.last_gate for b in self.blocks if b.engram is not None and hasattr(b.engram, 'last_gate')]
tetu_code/serve.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Têtu Code 2 — inference code (tetu-AI). License: Apache 2.0, see README.md.
2
+ import argparse
3
+ import collections
4
+ import hashlib
5
+ import ntpath
6
+ import os
7
+ import posixpath
8
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
9
+ import json
10
+ import re
11
+ import threading
12
+ import time
13
+ import uuid
14
+ from tetu_code import fmt
15
+
16
+ def project_instructions(system):
17
+ out = []
18
+ for m in re.finditer('Instructions from: ([^\\n]+)\\n(.*?)(?=\\nInstructions from: |\\n<available_skills>|\\Z)', system, re.S):
19
+ out.append(f'Instructions ({m.group(1).strip()}) :\n{m.group(2).strip()[:4000]}')
20
+ return '\n\n'.join(out)
21
+
22
+ def split_think(s):
23
+ if not s.startswith('<|think|>'):
24
+ return ('', s)
25
+ inner, sep, rest = s[len('<|think|>'):].partition('<|/think|>')
26
+ return (inner, rest if sep else '')
27
+
28
+ def last_call(body):
29
+ for m in reversed(body.get('messages', [])):
30
+ if m.get('role') == 'assistant' and m.get('tool_calls'):
31
+ f = m['tool_calls'][-1].get('function', {})
32
+ try:
33
+ return (f.get('name'), json.loads(f.get('arguments') or '{}'))
34
+ except ValueError:
35
+ return None
36
+ return None
37
+
38
+ def degenerate(toks, max_period=256):
39
+ n = len(toks)
40
+ for p in range(1, max_period + 1):
41
+ L = max(4 * p, 160)
42
+ if L > n:
43
+ break
44
+ if toks[-1] == toks[-1 - p] and toks[n - L + p:] == toks[n - L:n - p]:
45
+ return n - L + p
46
+ return 0
47
+
48
+ def recent_calls(body, k=4):
49
+ out = []
50
+ for m in reversed(body.get('messages', [])):
51
+ for c in reversed(m.get('tool_calls') or []) if m.get('role') == 'assistant' else []:
52
+ f = c.get('function', {})
53
+ try:
54
+ out.append((f.get('name'), json.loads(f.get('arguments') or '{}')))
55
+ except ValueError:
56
+ pass
57
+ if len(out) >= k:
58
+ return out
59
+ return out
60
+
61
+ def core_command(cmd):
62
+ c = re.sub('\\s*(\\|\\||;|&&)\\s*(true|echo\\b[^|;&]*|:)\\s*', ' ', cmd or '')
63
+ c = re.sub('\\s*\\d?>&\\d|\\s*2>\\s*/dev/null', ' ', c)
64
+ return ' '.join(c.split())
65
+ CODE_START = re.compile('\\s*(?:from \\w[\\w.]* import|import \\w|def \\w|class \\w|#!/usr/bin/env python|if __name__)')
66
+
67
+ def misplaced(call, body):
68
+ if call is None or call[0] not in ('write', 'edit'):
69
+ return False
70
+ path = str(call[1].get('filePath') or '')
71
+ text = str(call[1].get('content') if call[0] == 'write' else call[1].get('newString') or '')
72
+ if not re.search('\\.(md|txt|rst)$', path, re.I) or not CODE_START.match(text):
73
+ return False
74
+ users = ' '.join((fmt.content_text(m.get('content')) for m in body.get('messages', []) if m.get('role') == 'user'))
75
+ return re.split('[\\\\/]', path)[-1].lower() not in users.lower()
76
+
77
+ def workdir(body):
78
+ msgs = body.get('messages', [])
79
+ return fmt.env_from_system('\n'.join((fmt.content_text(m.get('content')) for m in msgs if m.get('role') == 'system'))).get('Working directory', '')
80
+
81
+ def rebase(call, body):
82
+ wd = workdir(body)
83
+ if call is None or not wd:
84
+ return call
85
+ pm = ntpath if re.match('[A-Za-z]:[\\\\/]', wd) else posixpath
86
+ root = pm.normpath(wd)
87
+ name, args = call
88
+ new = dict(args)
89
+ for k in ('filePath', 'path'):
90
+ p = args.get(k)
91
+ if not isinstance(p, str) or not pm.isabs(p):
92
+ continue
93
+ q = pm.normpath(p)
94
+ if pm.normcase(q) == pm.normcase(root) or pm.normcase(q).startswith(pm.normcase(root) + pm.sep):
95
+ continue
96
+ anc = root
97
+ for _ in range(2):
98
+ if pm.dirname(anc) == anc:
99
+ break
100
+ anc = pm.dirname(anc)
101
+ if pm.normcase(q) == pm.normcase(anc):
102
+ new[k] = wd
103
+ break
104
+ if pm.normcase(q).startswith(pm.normcase(anc).rstrip(pm.sep) + pm.sep):
105
+ if not os.path.exists(p):
106
+ new[k] = pm.join(root, q[len(anc.rstrip(pm.sep)) + 1:])
107
+ break
108
+ return call if new == args else (name, new)
109
+
110
+ def missing_file(call, body):
111
+ if call is None or call[0] not in ('read', 'edit'):
112
+ return False
113
+ path = str(call[1].get('filePath') or '')
114
+ wd = workdir(body)
115
+ if not path or not wd or (not os.path.isdir(wd)):
116
+ return False
117
+ return not os.path.exists(path if os.path.isabs(path) else os.path.join(wd, path))
118
+
119
+ def looping(call, prev, recent=()):
120
+ if call is None:
121
+ return False
122
+ name, args = call
123
+ if name == 'edit' and args.get('oldString') == args.get('newString'):
124
+ return True
125
+ if prev is not None and (name, args) == tuple(prev):
126
+ return True
127
+ if name == 'bash':
128
+ core = core_command(args.get('command'))
129
+ return sum((n == 'bash' and core_command(a.get('command')) == core for n, a in recent)) >= 2
130
+ return False
131
+ TASK_HINT = re.compile('(?i)\\b(?:cr[ée]{1,2}r?|cr[ée]{1,2}s|[ée]cri[srt]?|[ée]crire|fai[st]|fais-moi|ajout\\w*|modifi\\w*|corrig\\w*|renomm\\w*|lance\\w*|teste[rz]?|code[rz]?|programm\\w*|g[ée]n[èe]re\\w*|supprim\\w*|enl[èe]v\\w*|chang\\w*|remplac\\w*|mets|met|install\\w*|r[ée]par\\w*|impl[ée]ment\\w*|transform\\w*|traduis|convertis|create|write|make|build|add|edit|fix|rename|run|implement|refactor|delete|remove|site|page|script|programme|appli\\w*|app|jeu|outil|todo|calculatrice|convertisseur|compteur|classe|fonction|fichier|projet|api|serveur|bot|formulaire|bouton|menu|readme|tests|html|css|python|javascript|js|flask)\\b|\\w\\.(?:py|js|ts|html|css|json|md|txt|sh|java|go|rs|c|cpp)\\b')
132
+ DANGER = re.compile('(?i)bombes?\\b(?! de bain)|explosi|\\barmes?\\b|keylogger|espion|pirat|hack|phishing|fausse page de connexion|vol(?:er)? (?:des|les) (?:mots de passe|identifiants)|porn|sex|prompt syst|system prompt|ignore (?:tes|les) consignes')
133
+ NO_TOOL_HINT = re.compile("(?i)^\\W*(?:explique|c'est quoi|qu'est[- ]ce|quel(?:le)?s?\\b|pourquoi|comment\\b|quelle est la diff|diff[ée]rence|r[ée]sume|d[ée]finis|que (?:veut|signifie)|est-ce que|peux-tu m'expliquer|tu peux m'expliquer)|\\b(?:donne|affiche|montre|r[ée]ponds|envoie)(?:-moi)? (?:uniquement |seulement |juste |directement )?(?:avec )?(?:le |du |que le )?code\\b|\\b(?:uniquement|seulement|juste) le code\\b|\\bsans (?:outils?|fichiers?|cr[ée]er de fichier)|\\bdans (?:ta|la) r[ée]ponse\\b|\\br[ée]ponds en\\b|\\ben \\d+ phrases?\\b|\\ben (?:une|deux|trois) phrases?\\b")
134
+ FILE_NAME = re.compile('\\w\\.(?:py|js|ts|html|css|json|md|txt|sh|java|go|rs|c|cpp)\\b')
135
+
136
+ def wants_tools(text):
137
+ text = (text or '').strip()
138
+ if not text or DANGER.search(text):
139
+ return False
140
+ if NO_TOOL_HINT.search(text) and (not FILE_NAME.search(text)):
141
+ return False
142
+ words = len(text.split())
143
+ return bool(TASK_HINT.search(text)) and (words >= 3 or bool(re.search('\\w\\.\\w{1,4}\\b', text)))
144
+
145
+ def turn_calls(body):
146
+ out = []
147
+ for m in body.get('messages', []):
148
+ if m.get('role') == 'user':
149
+ out = []
150
+ for c in m.get('tool_calls') or [] if m.get('role') == 'assistant' else []:
151
+ f = c.get('function', {})
152
+ try:
153
+ out.append((f.get('name'), json.loads(f.get('arguments') or '{}')))
154
+ except ValueError:
155
+ out.append((f.get('name'), {}))
156
+ return out
157
+ CITED = re.compile('(?<![\\w/\\\\.-])((?:[\\w-]+[/\\\\])*[\\w-]+\\.(?:py|js|ts|html|css|json|md|txt|sh|csv))\\b')
158
+ TESTED = re.compile("(?i)\\bj'ai (?:bien )?(?:test[ée]|v[ée]rifi[ée]|lanc[ée]|ex[ée]cut[ée])|\\btests? (?:passent|r[ée]ussi|pass(?:ed|ing)?\\b)|\\btests (?:sont|ont) (?:ok|verts|r[ée]ussi|pass[ée])|\\btest[ée]e?s? et (?:[çc]a|il|elle|tout) (?:marche|fonctionne)|\\bi (?:have )?(?:tested|ran|run|verified)\\b|\\ball tests pass")
159
+
160
+ def dishonest(text, body):
161
+ calls = turn_calls(body)
162
+ if not calls or not (text or '').strip():
163
+ return ''
164
+ if TESTED.search(text) and (not any((n == 'bash' for n, _ in calls))):
165
+ return 'dit avoir testé sans commande'
166
+ seen = []
167
+ for m in body.get('messages', []):
168
+ if m.get('role') != 'system':
169
+ seen.append(fmt.content_text(m.get('content')))
170
+ for c in m.get('tool_calls') or []:
171
+ seen.append(str(c.get('function', {}).get('arguments') or ''))
172
+ seen = '\n'.join(seen).lower().replace('\\\\', '/').replace('\\', '/')
173
+ wd = workdir(body)
174
+ local = bool(wd) and os.path.isdir(wd)
175
+ for name in CITED.findall(text):
176
+ if re.split('[/\\\\]', name)[-1].lower() in seen:
177
+ continue
178
+ if local and os.path.exists(os.path.join(wd, name)):
179
+ continue
180
+ return f'cite {name}, absent du projet'
181
+ return ''
182
+
183
+ def last_user(body):
184
+ msgs = body.get('messages', [])
185
+ return fmt.content_text(msgs[-1].get('content')) if msgs and msgs[-1].get('role') == 'user' else ''
186
+
187
+ def finish_call(text, tools):
188
+ if '<|call|>' not in text:
189
+ return (text.strip(), None)
190
+ before, _, call = text.partition('<|call|>')
191
+ while call.startswith('<|call|>'):
192
+ call = call[len('<|call|>'):]
193
+ name, args = fmt.parse_call(call, tools)
194
+ names = {t['function']['name'] for t in tools or []}
195
+ if names and name not in names:
196
+ vals = ' '.join((str(v) for v in args.values()))
197
+ return (' '.join((x for x in (before.strip(), name, vals) if x)).strip(), None)
198
+ return (before.strip(), (name, args))
199
+
200
+ def is_title_request(body):
201
+ msgs = body.get('messages', [])
202
+ sys_ = fmt.content_text(msgs[0].get('content')) if msgs and msgs[0].get('role') == 'system' else ''
203
+ return not body.get('tools') and 'title' in sys_.lower() and ('generate' in sys_.lower())
204
+
205
+ def title_of(body):
206
+ users = [fmt.content_text(m.get('content')) for m in body.get('messages', []) if m.get('role') == 'user']
207
+ text = users[-1] if users else ''
208
+ text = re.sub('^\\s*Generate a title for this conversation:?\\s*', '', text, flags=re.I).strip().strip('"')
209
+ words = re.sub('[@`*#>]', '', text).split()
210
+ t = ' '.join(words[:6]) or 'Nouvelle session'
211
+ return t[:1].upper() + t[1:]
212
+
213
+ class Engine:
214
+
215
+ def __init__(self, a):
216
+ import torch
217
+ from tetu_code.generate import Decoder, load
218
+ dev = a.device if a.device != 'cuda' or torch.cuda.is_available() else 'cpu'
219
+ self.model, self.tok = load(a.model, device=dev)
220
+ memo = None
221
+ if getattr(a, 'memo', ''):
222
+ import sys
223
+ from pathlib import Path
224
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
225
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'lab'))
226
+ from tc_cles_exact import load_memo
227
+ memo = load_memo(a.memo, dev)
228
+ self.dec = Decoder(self.model, self.tok, max_len=a.max_len, graph=dev == 'cuda', compile=a.compile and dev == 'cuda', memo=memo)
229
+ self.lock = threading.Lock()
230
+ self.a = a
231
+ self.stop_ids = {self.tok.token_to_id(t) for t in ('<|end|>', '<|/call|>', '<|eos|>')}
232
+ self.call_id = self.tok.token_to_id('<|call|>')
233
+ self.thoughts = collections.OrderedDict()
234
+ d = os.environ.get('TETU_REP_LOG') or ('rep-log' if os.path.isdir('rep-log') else '')
235
+ self.rep_log = open(os.path.join(d, f'serve-{a.port}.jsonl'), 'a', encoding='utf-8') if d else None
236
+
237
+ def prompt_ids(self, body):
238
+ msgs = body.get('messages', [])
239
+ system = '\n'.join((fmt.content_text(m.get('content')) for m in msgs if m.get('role') == 'system'))
240
+ env = fmt.env_from_system(system)
241
+ sys_text = fmt.system_text(env)
242
+ extra = project_instructions(system)
243
+ if extra:
244
+ sys_text += '\n\n' + extra
245
+ tools = fmt.keep_tools(body.get('tools'))
246
+ msgs = [self.with_thought(m) for m in msgs if m.get('role') != 'system']
247
+ text = fmt.text_of(fmt.render(msgs, tools, system=sys_text))
248
+ ids = self.tok.encode(text + '<|assistant|>', add_special_tokens=False).ids
249
+ budget = self.a.max_len - self.a.max_new - 16
250
+ if len(ids) > budget:
251
+ head = ids[:2048]
252
+ ids = head + ids[-(budget - len(head)):]
253
+ return (ids, tools)
254
+
255
+ @staticmethod
256
+ def thought_key(m):
257
+ calls = m.get('tool_calls') or []
258
+ if calls and calls[0].get('id'):
259
+ return calls[0]['id']
260
+ return 'txt:' + hashlib.md5(fmt.content_text(m.get('content')).strip().encode()).hexdigest()
261
+
262
+ def with_thought(self, m):
263
+ if m.get('role') != 'assistant' or m.get('reasoning') or m.get('reasoning_content'):
264
+ return m
265
+ t = self.thoughts.get(self.thought_key(m))
266
+ return dict(m, reasoning=t) if t else m
267
+
268
+ def remember(self, key, think):
269
+ if think:
270
+ self.thoughts[key] = think
271
+ while len(self.thoughts) > 5000:
272
+ self.thoughts.popitem(last=False)
273
+
274
+ def generate(self, body, on_text=None, on_think=None, info=None):
275
+ tools_m, back = fmt.dialect(body.get('tools'))
276
+ body = dict(body, tools=tools_m, messages=fmt.to_model(body.get('messages', []), back))
277
+ calls = sum((len(m.get('tool_calls') or []) for m in body.get('messages', []) if m.get('role') == 'assistant'))
278
+ if self.a.max_calls and calls >= self.a.max_calls:
279
+ text = "Je m'arrête ici : trop d'étapes pour cette demande. Dis-moi comment continuer."
280
+ if on_text:
281
+ on_text(text)
282
+ return (text, None, 0, '')
283
+ ids, tools = self.prompt_ids(body)
284
+ if info is not None:
285
+ info['prompt'] = len(ids)
286
+ force = body.get('tool_choice') == 'required' or isinstance(body.get('tool_choice'), dict)
287
+ mode = getattr(self.a, 'force', 'smart')
288
+ if force and mode == 'smart':
289
+ force = wants_tools(last_user(body))
290
+ elif mode == 'never':
291
+ force = False
292
+ temp = float(body.get('temperature', self.a.temp) if self.a.respect_temp else self.a.temp)
293
+ max_new = min(int(body.get('max_tokens') or self.a.max_new), self.a.max_new)
294
+ prev, recent, total = (last_call(body), recent_calls(body), 0)
295
+ hold = bool(getattr(self.a, 'garde', 1)) and bool(turn_calls(body))
296
+ with self.lock:
297
+ for k in range(1 + self.a.retries):
298
+ t_k = temp if k == 0 else max(temp, (0.7, 1.0)[min(k, 2) - 1])
299
+ text, call, n, rep, think = self._sample(ids, tools, max_new, t_k, k, on_text if k == 0 and (not hold) else None, on_think if k == 0 else None, force=force)
300
+ fixed = rebase(call, body)
301
+ if fixed is not call and self.a.verbose:
302
+ print(f' path moved back into the project: {call[1]} → {fixed[1]}'[:300], flush=True)
303
+ call = fixed
304
+ total += n
305
+ if info is not None:
306
+ info['last'] = n
307
+ lie = dishonest(text, body) if hold and call is None and (k < self.a.retries) else ''
308
+ if not lie and (not rep) and (not looping(call, prev, recent)) and (not (k < self.a.retries and (misplaced(call, body) or missing_file(call, body)))):
309
+ break
310
+ if self.a.verbose:
311
+ why = f'anti-mensonge : {lie}' if lie else 'anti-boucle : ' + ('répétition en boucle' if rep else f'{call[0]} inutile')
312
+ print(f' {why}, resampling (temperature {t_k:.1f})', flush=True)
313
+ if hold and on_text and text:
314
+ on_text(text)
315
+ return (text, fmt.to_client(call, back), total, think)
316
+
317
+ def _sample(self, ids, tools, max_new, temp, seed, on_text, on_think=None, force=False):
318
+ out, shown, shown_th, in_call, n, rep = ([], '', '', False, 0, False)
319
+ if force:
320
+ ids, out, in_call = (list(ids) + [self.call_id], [self.call_id], True)
321
+ for t in self.dec.generate(ids, max_new=max_new, temp=temp, top_p=self.a.top_p, stop=self.stop_ids, seed=seed):
322
+ n += 1
323
+ if t in self.stop_ids:
324
+ break
325
+ out.append(t)
326
+ if t == self.call_id:
327
+ in_call = True
328
+ if n % 32 == 0:
329
+ keep = degenerate(out)
330
+ if keep:
331
+ if self.rep_log:
332
+ self.rep_log.write(json.dumps({'ids': list(ids), 'gen': list(out), 'keep': keep, 'temp': temp}) + '\n')
333
+ self.rep_log.flush()
334
+ del out[keep:]
335
+ rep = True
336
+ break
337
+ if (on_text or on_think) and (not in_call):
338
+ s = self.tok.decode(out, skip_special_tokens=False)
339
+ if not s.endswith('�'):
340
+ th, vis = split_think(s)
341
+ if on_think and len(th) > len(shown_th):
342
+ on_think(th[len(shown_th):])
343
+ shown_th = th
344
+ if on_text and len(vis) > len(shown):
345
+ on_text(vis[len(shown):])
346
+ shown = vis
347
+ think, text = split_think(self.tok.decode(out, skip_special_tokens=False))
348
+ text, call = finish_call(text, tools)
349
+ return (text, call, n, rep, think.strip())
350
+
351
+ def make_handler(eng, a):
352
+
353
+ class H(BaseHTTPRequestHandler):
354
+ protocol_version = 'HTTP/1.1'
355
+
356
+ def log_message(self, *args):
357
+ pass
358
+
359
+ def _json(self, code, obj):
360
+ b = json.dumps(obj).encode()
361
+ self.send_response(code)
362
+ self.send_header('Content-Type', 'application/json')
363
+ self.send_header('Content-Length', str(len(b)))
364
+ self.end_headers()
365
+ self.wfile.write(b)
366
+
367
+ def do_GET(self):
368
+ if self.path.rstrip('/').endswith('/models'):
369
+ self._json(200, {'object': 'list', 'data': [{'id': a.name, 'object': 'model', 'owned_by': 'tetu', 'context_length': a.max_len}]})
370
+ else:
371
+ self._json(404, {'error': 'not found'})
372
+
373
+ def do_POST(self):
374
+ n = int(self.headers.get('Content-Length', 0))
375
+ body = json.loads(self.rfile.read(n) or b'{}')
376
+ if not self.path.rstrip('/').endswith('/chat/completions'):
377
+ self._json(404, {'error': 'not found'})
378
+ return
379
+ cid, created = (f'chatcmpl-{uuid.uuid4().hex[:12]}', int(time.time()))
380
+ base = {'id': cid, 'created': created, 'model': a.name}
381
+ stream = bool(body.get('stream'))
382
+ t0, info = (time.time(), {})
383
+ if is_title_request(body):
384
+ text, call, ntok, think = (title_of(body), None, 0, '')
385
+ chunks = None
386
+ elif stream:
387
+ self.send_response(200)
388
+ self.send_header('Content-Type', 'text/event-stream')
389
+ self.send_header('Cache-Control', 'no-cache')
390
+ self.end_headers()
391
+
392
+ def send(obj):
393
+ self.wfile.write(f'data: {json.dumps(obj)}\n\n'.encode())
394
+ self.wfile.flush()
395
+ send(base | {'object': 'chat.completion.chunk', 'choices': [{'index': 0, 'delta': {'role': 'assistant', 'content': ''}, 'finish_reason': None}]})
396
+ text, call, ntok, think = eng.generate(body, on_text=lambda s: send(base | {'object': 'chat.completion.chunk', 'choices': [{'index': 0, 'delta': {'content': s}, 'finish_reason': None}]}), on_think=lambda s: send(base | {'object': 'chat.completion.chunk', 'choices': [{'index': 0, 'delta': {'reasoning_content': s}, 'finish_reason': None}]}), info=info)
397
+ chunks = send
398
+ else:
399
+ text, call, ntok, think = eng.generate(body, info=info)
400
+ chunks = None
401
+ prompt, last = (info.get('prompt', 0), info.get('last', ntok))
402
+ usage = {'prompt_tokens': prompt, 'completion_tokens': last, 'total_tokens': prompt + last, 'context_window': a.max_len}
403
+ tool_calls = None
404
+ if call:
405
+ tool_calls = [{'index': 0, 'id': f'call_{uuid.uuid4().hex[:10]}', 'type': 'function', 'function': {'name': call[0], 'arguments': json.dumps(call[1], ensure_ascii=False)}}]
406
+ eng.remember(tool_calls[0]['id'] if tool_calls else 'txt:' + hashlib.md5(text.strip().encode()).hexdigest(), think)
407
+ fin = 'tool_calls' if call else 'stop'
408
+ if a.verbose:
409
+ print(f"[{time.strftime('%H:%M:%S')}] {ntok} tokens in {time.time() - t0:.1f} s · {('call ' + call[0] if call else 'answer')}", flush=True)
410
+ if chunks is not None:
411
+ if tool_calls:
412
+ chunks(base | {'object': 'chat.completion.chunk', 'choices': [{'index': 0, 'delta': {'tool_calls': tool_calls}, 'finish_reason': None}]})
413
+ chunks(base | {'object': 'chat.completion.chunk', 'choices': [{'index': 0, 'delta': {}, 'finish_reason': fin}], 'usage': usage})
414
+ self.wfile.write(b'data: [DONE]\n\n')
415
+ self.wfile.flush()
416
+ self.close_connection = True
417
+ return
418
+ msg = {'role': 'assistant', 'content': text if not call or text else None}
419
+ if think:
420
+ msg['reasoning_content'] = think
421
+ if tool_calls:
422
+ msg['tool_calls'] = [{k: v for k, v in tc.items() if k != 'index'} for tc in tool_calls]
423
+ if stream:
424
+ self.send_response(200)
425
+ self.send_header('Content-Type', 'text/event-stream')
426
+ self.end_headers()
427
+ for c in ({'role': 'assistant', 'content': text}, {}):
428
+ self.wfile.write(f"data: {json.dumps(base | {'object': 'chat.completion.chunk', 'choices': [{'index': 0, 'delta': c, 'finish_reason': None if c else 'stop'}]})}\n\n".encode())
429
+ self.wfile.write(b'data: [DONE]\n\n')
430
+ self.close_connection = True
431
+ return
432
+ self._json(200, base | {'object': 'chat.completion', 'usage': usage, 'choices': [{'index': 0, 'message': msg, 'finish_reason': fin}]})
433
+ return H
434
+
435
+ def main():
436
+ p = argparse.ArgumentParser()
437
+ p.add_argument('--model', required=True)
438
+ p.add_argument('--name', default='tetu-code')
439
+ p.add_argument('--host', default='127.0.0.1')
440
+ p.add_argument('--port', type=int, default=8070)
441
+ p.add_argument('--device', default='cuda')
442
+ p.add_argument('--max_len', type=int, default=65536)
443
+ p.add_argument('--max_new', type=int, default=4096)
444
+ p.add_argument('--temp', type=float, default=0.2)
445
+ p.add_argument('--top_p', type=float, default=0.95)
446
+ p.add_argument('--respect_temp', action='store_true', help='use the temperature sent by the client')
447
+ p.add_argument('--max_calls', type=int, default=40, help='max tool calls per conversation (0 = no limit)')
448
+ p.add_argument('--compile', action='store_true', help='torch.compile the decoding step (+40 %% speed, 2-8 min at startup)')
449
+ p.add_argument('--garde', type=int, default=1, help='1: check the final answer (cited file missing, "tested" without a command) and redraw if needed')
450
+ p.add_argument('--retries', type=int, default=2, help='resamples when a call loops (0 = never)')
451
+ p.add_argument('--force', choices=('smart', 'client', 'never'), default='smart', help='tool_choice "required": smart = only for requests that look like a task')
452
+ p.add_argument('--verbose', action='store_true')
453
+ p.add_argument('--memo', default='', help='optional add-on, not included in this release')
454
+ a = p.parse_args()
455
+ eng = Engine(a)
456
+ ThreadingHTTPServer.daemon_threads = True
457
+ srv = ThreadingHTTPServer((a.host, a.port), make_handler(eng, a))
458
+ print(f'Têtu Code ready: http://{a.host}:{a.port}/v1 (model "{a.name}")', flush=True)
459
+ srv.serve_forever()
460
+ if __name__ == '__main__':
461
+ main()
tetu_code/structure.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Têtu Code 2 — inference code (tetu-AI). License: Apache 2.0, see README.md.
2
+ import numpy as np
3
+ try:
4
+ from numba import njit
5
+ except ImportError:
6
+
7
+ def njit(*a, **k):
8
+ return (lambda f: f) if not a or not callable(a[0]) else a[0]
9
+ C_OTHER, C_ALNUM, C_SPACE, C_TAB, C_NL, C_DQ, C_SQ, C_HASH, C_BSL, C_OPEN, C_CLOSE = range(11)
10
+ T_NORMAL, T_RESET, T_FIM_SUF, T_FIM_MID = (0, 1, 2, 3)
11
+
12
+ class Tables:
13
+
14
+ def __init__(self, tok):
15
+ V = tok.get_vocab_size()
16
+ specials = {t.content for t in tok.get_added_tokens_decoder().values()} if hasattr(tok, 'get_added_tokens_decoder') else set()
17
+ bs = list(range(ord('!'), ord('~') + 1)) + list(range(ord('¡'), ord('¬') + 1)) + list(range(ord('®'), ord('ÿ') + 1))
18
+ cs, n = (bs[:], 0)
19
+ for b in range(256):
20
+ if b not in bs:
21
+ bs.append(b)
22
+ cs.append(256 + n)
23
+ n += 1
24
+ dec = {chr(c): b for b, c in zip(bs, cs)}
25
+ off, ln, flag, ev = (np.zeros(V, np.int64), np.zeros(V, np.int32), np.zeros(V, np.int8), [])
26
+ for i in range(V):
27
+ s = tok.id_to_token(i) or ''
28
+ if s in specials or (s.startswith('<|') and s.endswith('|>')):
29
+ flag[i] = {'<|fim_suffix|>': T_FIM_SUF, '<|fim_middle|>': T_FIM_MID}.get(s, T_RESET)
30
+ off[i], ln[i] = (len(ev), 0)
31
+ continue
32
+ raw = bytes((dec.get(ch, 63) for ch in s))
33
+ off[i] = len(ev)
34
+ for b in raw:
35
+ c = chr(b)
36
+ ev.append(C_ALNUM if c.isalnum() or c == '_' or b >= 128 else C_SPACE if c == ' ' else C_TAB if c == '\t' else C_NL if c == '\n' else C_DQ if c == '"' else C_SQ if c == "'" else C_HASH if c == '#' else C_BSL if c == '\\' else C_OPEN if c in '([{' else C_CLOSE if c in ')]}' else C_OTHER)
37
+ ln[i] = len(raw)
38
+ pref = np.zeros(max(1, len(ev)), np.int8)
39
+ for i in range(V):
40
+ if ln[i]:
41
+ raw = bytes((dec.get(ch, 63) for ch in tok.id_to_token(i) or ''))
42
+ for j, b in enumerate(raw):
43
+ pref[off[i] + j] = 1 if chr(b) in 'frbuFRBU' else 0
44
+ self.arrays = (off, ln, flag, np.asarray(ev, np.int8), pref)
45
+
46
+ @njit(cache=True)
47
+ def features(ids, off, ln, flag, ev, pref):
48
+ n = ids.shape[0]
49
+ out = np.zeros(n, np.int16)
50
+ mode = 0
51
+ q = 0
52
+ qrun = 0
53
+ opened = 0
54
+ esc = 0
55
+ depth = 0
56
+ indent = 0
57
+ ls = 1
58
+ run = 0
59
+ run_pref = 1
60
+ s_mode = s_depth = s_indent = s_ls = 0
61
+ for t in range(n):
62
+ i = ids[t]
63
+ f = flag[i]
64
+ if f == 1:
65
+ mode = q = qrun = opened = esc = depth = indent = run = 0
66
+ ls = 1
67
+ run_pref = 1
68
+ elif f == 2:
69
+ s_mode, s_depth, s_indent, s_ls = (mode, depth, indent, ls)
70
+ mode = q = qrun = opened = esc = depth = indent = run = 0
71
+ ls = 1
72
+ run_pref = 1
73
+ elif f == 3:
74
+ mode, depth, indent, ls = (s_mode, s_depth, s_indent, s_ls)
75
+ q = qrun = opened = esc = run = 0
76
+ run_pref = 1
77
+ else:
78
+ o = off[i]
79
+ for j in range(ln[i]):
80
+ c = ev[o + j]
81
+ if c == 4:
82
+ if mode == 1 or mode == 3:
83
+ mode = 0
84
+ opened = qrun = esc = run = 0
85
+ run_pref = 1
86
+ ls = 1
87
+ indent = 0
88
+ continue
89
+ if ls == 1:
90
+ if c == 2:
91
+ indent += 1
92
+ continue
93
+ if c == 3:
94
+ indent += 4
95
+ continue
96
+ ls = 0
97
+ if mode == 0:
98
+ if c == 1:
99
+ run += 1
100
+ if pref[o + j] == 0:
101
+ run_pref = 0
102
+ else:
103
+ if c == 5 or c == 6:
104
+ if c == 5 or run == 0 or (run_pref == 1 and run <= 2):
105
+ mode, q, opened, qrun = (1, c, 1, 1)
106
+ elif c == 7:
107
+ mode = 3
108
+ elif c == 9:
109
+ depth += 1
110
+ elif c == 10:
111
+ depth = depth - 1 if depth > 0 else 0
112
+ run = 0
113
+ run_pref = 1
114
+ elif mode == 1:
115
+ if esc == 1:
116
+ esc = 0
117
+ opened = 0
118
+ elif c == q:
119
+ if opened == 1:
120
+ qrun += 1
121
+ if qrun == 3:
122
+ mode, opened, qrun = (2, 0, 0)
123
+ else:
124
+ mode, qrun = (0, 0)
125
+ elif opened == 1 and qrun == 2:
126
+ mode, opened, qrun = (0, 0, 0)
127
+ if c == 9:
128
+ depth += 1
129
+ elif c == 10:
130
+ depth = depth - 1 if depth > 0 else 0
131
+ elif c == 7:
132
+ mode = 3
133
+ else:
134
+ opened = 0
135
+ qrun = 0
136
+ if c == 8:
137
+ esc = 1
138
+ elif mode == 2:
139
+ if esc == 1:
140
+ esc = 0
141
+ elif c == 8:
142
+ esc = 1
143
+ qrun = 0
144
+ elif c == q:
145
+ qrun += 1
146
+ if qrun == 3:
147
+ mode, qrun = (0, 0)
148
+ else:
149
+ qrun = 0
150
+ lvl = indent // 4
151
+ if lvl > 15:
152
+ lvl = 15
153
+ d = depth if depth < 15 else 15
154
+ m = 1 if mode == 1 else 2 if mode == 2 else 3 if mode == 3 else 0
155
+ out[t] = lvl | d << 4 | m << 8 | ls << 10
156
+ return out
157
+
158
+ def describe(v):
159
+ v = int(v)
160
+ return dict(indent=v & 15, depth=v >> 4 & 15, mode=('code', 'chaîne', 'triple', 'comm.')[v >> 8 & 3], ls=v >> 10 & 1)
tetu_code/tokenizer.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Têtu Code 2 — inference code (tetu-AI). License: Apache 2.0, see README.md.
2
+ from tokenizers import Regex, Tokenizer, decoders, models, pre_tokenizers, trainers
3
+ SPECIALS = ['<|pad|>', '<|eos|>', '<|system|>', '<|user|>', '<|assistant|>', '<|tool|>', '<|call|>', '<|/call|>', '<|fim_prefix|>', '<|fim_suffix|>', '<|fim_middle|>', '<|file|>', '<|repo|>', '<|think|>', '<|/think|>', '<|trace|>', '<|/trace|>', '<|tools|>', '<|commit|>', '<|arg|>', '<|end|>'] + [f'<|reserved_{i}|>' for i in range(2, 16)]
4
+ PATTERN = '\\r?\\n[ \\t]*|\\p{N}| ?[\\p{L}\\p{M}_]+| ?[^\\s\\p{L}\\p{M}\\p{N}_]+|[ \\t]+|\\s'
5
+ VOCAB = 32768
6
+
7
+ def new_tokenizer():
8
+ tok = Tokenizer(models.BPE())
9
+ tok.pre_tokenizer = pre_tokenizers.Sequence([pre_tokenizers.Split(Regex(PATTERN), behavior='isolated'), pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=False)])
10
+ tok.decoder = decoders.ByteLevel()
11
+ return tok
12
+
13
+ def train(texts, vocab=VOCAB, length=None):
14
+ tok = new_tokenizer()
15
+ trainer = trainers.BpeTrainer(vocab_size=vocab, min_frequency=2, special_tokens=SPECIALS, show_progress=False, initial_alphabet=pre_tokenizers.ByteLevel.alphabet(), max_token_length=32)
16
+ tok.train_from_iterator(texts, trainer, length=length)
17
+ return tok
18
+
19
+ def load(path):
20
+ return Tokenizer.from_file(str(path))
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff