Upload folder using huggingface_hub
Browse files- benchmark.md +46 -0
- chat_template.jinja +1 -0
- check_hf.py +141 -0
- config.json +31 -0
- merges.txt +0 -0
- model.fir +224 -0
- model.safetensors +3 -0
- probe.bybylang +72 -0
- test_model.bybylang +342 -0
- tokenizer.json +0 -0
- vocab.json +0 -0
benchmark.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GPT-2 125M through FIR: inference benchmark
|
| 2 |
+
|
| 3 |
+
The model runs from `model.fir` only (`runtime graph`): one GPU session per token, KV cache
|
| 4 |
+
resident on the GPU. Q4 is the default (resident Q4 linears); `--fir-f32` keeps the linears
|
| 5 |
+
in fp32 as the correctness reference.
|
| 6 |
+
|
| 7 |
+
## English
|
| 8 |
+
|
| 9 |
+
### Intel Iris Plus Graphics 640
|
| 10 |
+
|
| 11 |
+
Measured in chat mode (`-cnv`, temperature 0.8, chat template from `chat_template.jinja`).
|
| 12 |
+
|
| 13 |
+
| Backend | Weights | Prompt tokens | Prompt eval | Generated tokens | Decode |
|
| 14 |
+
|---|---|---:|---:|---:|---:|
|
| 15 |
+
| Metal | Q4 | 13 | 0.583 s, 22.31 tok/s | 168 | 19.596 s, 8.57 tok/s |
|
| 16 |
+
| Vulkan | Q4 | 15 | 1.048 s, 14.31 tok/s | 35 | 3.071 s, 11.40 tok/s |
|
| 17 |
+
| Metal | fp32 | 10 | 0.732 s, 13.67 tok/s | 21 | 1.948 s, 10.78 tok/s |
|
| 18 |
+
| Vulkan | fp32 | 11 | 0.955 s, 11.52 tok/s | 51 | 5.974 s, 8.54 tok/s |
|
| 19 |
+
|
| 20 |
+
```sh
|
| 21 |
+
other/formers.n/formers-cli --models models/gpt2-125m -cnv --temp 0.8 --backend metal
|
| 22 |
+
other/formers.n/formers-cli --models models/gpt2-125m -cnv --temp 0.8 --backend vulkan
|
| 23 |
+
other/formers.n/formers-cli --models models/gpt2-125m -cnv --fir-f32 --temp 0.8 --backend metal
|
| 24 |
+
other/formers.n/formers-cli --models models/gpt2-125m -cnv --fir-f32 --temp 0.8 --backend vulkan
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
## Tiếng Việt
|
| 28 |
+
|
| 29 |
+
### Intel Iris Plus Graphics 640
|
| 30 |
+
|
| 31 |
+
Đo ở chế độ chat (`-cnv`, temperature 0.8, template từ `chat_template.jinja`). GPT-2 125M
|
| 32 |
+
|
| 33 |
+
| Backend | Weight | Token prompt | Prompt eval | Token sinh ra | Decode |
|
| 34 |
+
|---|---|---:|---:|---:|---:|
|
| 35 |
+
| Metal | Q4 | 13 | 0,583 s, 22,31 tok/s | 168 | 19,596 s, 8,57 tok/s |
|
| 36 |
+
| Vulkan | Q4 | 15 | 1,048 s, 14,31 tok/s | 35 | 3,071 s, 11,40 tok/s |
|
| 37 |
+
| Metal | fp32 | 10 | 0,732 s, 13,67 tok/s | 21 | 1,948 s, 10,78 tok/s |
|
| 38 |
+
| Vulkan | fp32 | 11 | 0,955 s, 11,52 tok/s | 51 | 5,974 s, 8,54 tok/s |
|
| 39 |
+
|
| 40 |
+
```sh
|
| 41 |
+
other/formers.n/formers-cli --models models/gpt2-125m -cnv --temp 0.8 --backend metal
|
| 42 |
+
other/formers.n/formers-cli --models models/gpt2-125m -cnv --temp 0.8 --backend vulkan
|
| 43 |
+
other/formers.n/formers-cli --models models/gpt2-125m -cnv --fir-f32 --temp 0.8 --backend metal
|
| 44 |
+
other/formers.n/formers-cli --models models/gpt2-125m -cnv --fir-f32 --temp 0.8 --backend vulkan
|
| 45 |
+
```
|
| 46 |
+
|
chat_template.jinja
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{% for message in messages %}{% if message['role'] == 'system' %}{{ message['content'] + '\n' }}{% elif message['role'] == 'user' %}{{ 'User: ' + message['content'] + '\n' }}{% else %}{{ 'Assistant:' + message['content'] + '\n' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ 'Assistant:' }}{% endif %}
|
check_hf.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Offline GPT-2 fp32 regression and resident Q4 quality/throughput report.
|
| 3 |
+
|
| 4 |
+
Default: require the original fp32 32/32 HF fixture. --quality: report Q4
|
| 5 |
+
matching prefixes and Q4/fp32 logit error/top-1 at identical HF prefixes.
|
| 6 |
+
No files or downloads are created.
|
| 7 |
+
|
| 8 |
+
Run from the repo root after make formers-cli. Requires installed torch,
|
| 9 |
+
transformers, safetensors and tokenizers, and the existing local GPT-2 assets.
|
| 10 |
+
"""
|
| 11 |
+
import argparse
|
| 12 |
+
import gc
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import subprocess
|
| 17 |
+
import time
|
| 18 |
+
|
| 19 |
+
os.environ["HF_HUB_OFFLINE"] = "1"
|
| 20 |
+
os.environ["TRANSFORMERS_OFFLINE"] = "1"
|
| 21 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 22 |
+
|
| 23 |
+
PROMPT = "Hello, my name is"
|
| 24 |
+
QUALITY_PROMPTS = [PROMPT, "The capital of France is", "def fibonacci(n):"]
|
| 25 |
+
# Locally obtained from HF GPT2LMHeadModel in eval mode, greedy FP32 on CPU.
|
| 26 |
+
KNOWN_IDS = [1757, 13, 314, 1101, 257, 6260, 11, 290, 314, 1101, 257, 6260,
|
| 27 |
+
13, 314, 1101, 257, 6260, 13, 314, 1101, 257, 6260, 13, 314,
|
| 28 |
+
1101, 257, 6260, 13, 314, 1101, 257, 6260]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def prefix_length(actual, expected):
|
| 32 |
+
return next((i for i, (a, b) in enumerate(zip(actual, expected)) if a != b),
|
| 33 |
+
min(len(actual), len(expected)))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def quality_check(args, root, model_dir, tokenizer, model, torch):
|
| 37 |
+
import numpy as np
|
| 38 |
+
|
| 39 |
+
requests, hf_logits, expected = [], [], []
|
| 40 |
+
for text in args.prompt or QUALITY_PROMPTS:
|
| 41 |
+
ids = tokenizer(text, return_tensors="pt").input_ids
|
| 42 |
+
with torch.no_grad():
|
| 43 |
+
sequence = model.generate(ids, max_new_tokens=args.tokens, do_sample=False,
|
| 44 |
+
pad_token_id=tokenizer.eos_token_id)[0]
|
| 45 |
+
continuation = sequence[ids.shape[1]:].tolist()
|
| 46 |
+
steps = min(args.logit_steps, len(continuation))
|
| 47 |
+
# Teacher-forced logits at exactly the same prefixes in every run.
|
| 48 |
+
logits = model(sequence[:ids.shape[1]+steps-1].unsqueeze(0)).logits[0]
|
| 49 |
+
expected.append(continuation)
|
| 50 |
+
hf_logits.append(logits[ids.shape[1]-1:ids.shape[1]+steps-1].numpy())
|
| 51 |
+
requests.append(dict(prompt=ids[0].tolist(), teacher=continuation[:steps],
|
| 52 |
+
count=len(continuation)))
|
| 53 |
+
del model
|
| 54 |
+
gc.collect()
|
| 55 |
+
probe = root / "other/formers.n/build/fir_probe"
|
| 56 |
+
if not probe.is_file():
|
| 57 |
+
raise SystemExit("Build the offline probe: make -C other/formers.n fir-probe")
|
| 58 |
+
runs = {}
|
| 59 |
+
for precision in ("fp32", "q4"):
|
| 60 |
+
print(f"Running resident {precision} on {args.backend} ({len(requests)} prompts)...", flush=True)
|
| 61 |
+
completed = subprocess.run([str(probe), str(model_dir), args.backend, precision],
|
| 62 |
+
input="".join(json.dumps(r)+"\n" for r in requests),
|
| 63 |
+
cwd=root, text=True, capture_output=True)
|
| 64 |
+
if completed.returncode:
|
| 65 |
+
raise SystemExit(f"FAIL {precision} probe: {completed.stderr} {completed.stdout[:2000]}")
|
| 66 |
+
runs[precision] = [json.loads(line) for line in completed.stdout.splitlines()]
|
| 67 |
+
assert len(runs[precision]) == len(requests)
|
| 68 |
+
texts = args.prompt or QUALITY_PROMPTS
|
| 69 |
+
for i, (text, reference) in enumerate(zip(texts, expected)):
|
| 70 |
+
fp, q4 = runs["fp32"][i], runs["q4"][i]
|
| 71 |
+
f = np.asarray(fp["logits"], dtype=np.float32)
|
| 72 |
+
q = np.asarray(q4["logits"], dtype=np.float32)
|
| 73 |
+
h = hf_logits[i]
|
| 74 |
+
assert f.shape == q.shape == h.shape and np.isfinite(f).all() and np.isfinite(q).all()
|
| 75 |
+
assert fp["generated"] == reference, f"fp32 vs HF greedy mismatch for {text!r}"
|
| 76 |
+
print(f"{text!r}: Q4/HF matching prefix {prefix_length(q4['generated'], reference)}/{len(reference)}; "
|
| 77 |
+
f"Q4/fp32 max logit error={np.max(np.abs(q-f)):.6f}, "
|
| 78 |
+
f"top-1 agreement={np.mean(q.argmax(-1)==f.argmax(-1)):.1%} ({len(f)} HF prefixes); "
|
| 79 |
+
f"fp32/HF max error={np.max(np.abs(f-h)):.6f}")
|
| 80 |
+
for precision, run in (("fp32", fp), ("q4", q4)):
|
| 81 |
+
steps = len(requests[i]["prompt"])+len(reference)-1
|
| 82 |
+
assert run["sessions"] == run["logits_reads"] == steps
|
| 83 |
+
prefill = run["prefill_tokens"]/run["prefill_seconds"]
|
| 84 |
+
decode = run["decode_steps"]/run["decode_seconds"] if run["decode_steps"] else 0
|
| 85 |
+
print(f" {precision}: sequential prefill {run['prefill_tokens']} tokens / "
|
| 86 |
+
f"{run['prefill_seconds']:.3f}s = {prefill:.3f} tok/s; "
|
| 87 |
+
f"decode {run['decode_steps']} steps / {run['decode_seconds']:.3f}s = {decode:.3f} tok/s; "
|
| 88 |
+
f"{steps} sessions, {steps} logits reads")
|
| 89 |
+
print("PASS fp32 greedy vs offline HF; Q4 quality reported without a greedy-match threshold. "
|
| 90 |
+
"Timings exclude load/JIT preparation; first-use backend costs may remain.")
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def main():
|
| 94 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 95 |
+
parser.add_argument("--backend", choices=["cpu", "metal", "vulkan"], default="cpu")
|
| 96 |
+
parser.add_argument("--quality", action="store_true", help="compare resident Q4/fp32 logits and greedy prefixes on several prompts")
|
| 97 |
+
parser.add_argument("--tokens", type=int, default=32, help="quality-mode greedy continuation length")
|
| 98 |
+
parser.add_argument("--logit-steps", type=int, default=8, help="quality-mode HF prefixes for logit comparisons")
|
| 99 |
+
parser.add_argument("--prompt", action="append", help="override quality prompts; may be repeated")
|
| 100 |
+
args = parser.parse_args()
|
| 101 |
+
if args.tokens < 1 or args.logit_steps < 1:
|
| 102 |
+
parser.error("--tokens and --logit-steps must be positive")
|
| 103 |
+
import torch
|
| 104 |
+
from transformers import GPT2LMHeadModel, GPT2TokenizerFast
|
| 105 |
+
|
| 106 |
+
torch.set_num_threads(1)
|
| 107 |
+
root = Path(__file__).resolve().parents[2]
|
| 108 |
+
model_dir = root / "models/gpt2-125m"
|
| 109 |
+
tokenizer = GPT2TokenizerFast.from_pretrained(model_dir, local_files_only=True)
|
| 110 |
+
model = GPT2LMHeadModel.from_pretrained(model_dir, local_files_only=True).cpu().eval()
|
| 111 |
+
if args.quality:
|
| 112 |
+
quality_check(args, root, model_dir, tokenizer, model, torch)
|
| 113 |
+
return
|
| 114 |
+
prompt = tokenizer(PROMPT, return_tensors="pt")
|
| 115 |
+
assert prompt.input_ids[0].tolist() == [15496, 11, 616, 1438, 318]
|
| 116 |
+
with torch.no_grad():
|
| 117 |
+
output = model.generate(**prompt, max_new_tokens=32, do_sample=False,
|
| 118 |
+
pad_token_id=tokenizer.eos_token_id)
|
| 119 |
+
expected_ids = output[0, prompt.input_ids.shape[1]:].tolist()
|
| 120 |
+
assert expected_ids == KNOWN_IDS, f"HF baseline changed: {expected_ids}"
|
| 121 |
+
expected = tokenizer.decode(expected_ids)
|
| 122 |
+
del model, output
|
| 123 |
+
gc.collect()
|
| 124 |
+
command = [str(root / "other/formers.n/formers-cli"), "--models", str(model_dir),
|
| 125 |
+
"--fir", str(model_dir / "model.fir"), "--fir-f32", "--raw", "-p", PROMPT,
|
| 126 |
+
"-n", "32", "--temp", "0", "--backend", args.backend]
|
| 127 |
+
started = time.monotonic()
|
| 128 |
+
completed = subprocess.run(command, cwd=root, text=True, capture_output=True)
|
| 129 |
+
print(completed.stderr, end="")
|
| 130 |
+
if completed.returncode:
|
| 131 |
+
raise SystemExit(f"FAIL CLI exited {completed.returncode}: {completed.stdout}")
|
| 132 |
+
actual = completed.stdout.removesuffix("\n")
|
| 133 |
+
assert actual == expected, f"greedy mismatch\nactual: {actual!r}\nHF: {expected!r}"
|
| 134 |
+
assert tokenizer.encode(actual, add_special_tokens=False) == expected_ids
|
| 135 |
+
print(f"PASS GPT-2 {args.backend}: 32/32 greedy token IDs match offline HF "
|
| 136 |
+
f"and known fixture ({time.monotonic()-started:.2f} s)")
|
| 137 |
+
print(repr(actual))
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
main()
|
config.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"activation_function": "gelu_new",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"GPT2LMHeadModel"
|
| 5 |
+
],
|
| 6 |
+
"attn_pdrop": 0.1,
|
| 7 |
+
"bos_token_id": 50256,
|
| 8 |
+
"embd_pdrop": 0.1,
|
| 9 |
+
"eos_token_id": 50256,
|
| 10 |
+
"initializer_range": 0.02,
|
| 11 |
+
"layer_norm_epsilon": 1e-05,
|
| 12 |
+
"model_type": "gpt2",
|
| 13 |
+
"n_ctx": 1024,
|
| 14 |
+
"n_embd": 768,
|
| 15 |
+
"n_head": 12,
|
| 16 |
+
"n_layer": 12,
|
| 17 |
+
"n_positions": 1024,
|
| 18 |
+
"resid_pdrop": 0.1,
|
| 19 |
+
"summary_activation": null,
|
| 20 |
+
"summary_first_dropout": 0.1,
|
| 21 |
+
"summary_proj_to_labels": true,
|
| 22 |
+
"summary_type": "cls_index",
|
| 23 |
+
"summary_use_proj": true,
|
| 24 |
+
"task_specific_params": {
|
| 25 |
+
"text-generation": {
|
| 26 |
+
"do_sample": true,
|
| 27 |
+
"max_length": 50
|
| 28 |
+
}
|
| 29 |
+
},
|
| 30 |
+
"vocab_size": 50257
|
| 31 |
+
}
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model.fir
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Resident GPT-2 decode. Q4 source shapes follow HF Conv1D [input,output];
|
| 2 |
+
# the loader transposes to [output,input] before grouped asymmetric int4 quantization.
|
| 3 |
+
# wte/lm_head stays tied fp32; --fir-f32 restores all fp32 linears.
|
| 4 |
+
fir 1
|
| 5 |
+
model gpt2
|
| 6 |
+
config config.json
|
| 7 |
+
runtime graph
|
| 8 |
+
epsilon layer_norm_epsilon
|
| 9 |
+
prefix transformer.
|
| 10 |
+
|
| 11 |
+
# Config checks owned by this model file (a key that is absent passes).
|
| 12 |
+
require config model_type gpt2
|
| 13 |
+
require config activation_function gelu_new
|
| 14 |
+
require config scale_attn_weights true
|
| 15 |
+
require config scale_attn_by_inverse_layer_idx false
|
| 16 |
+
require config reorder_and_upcast_attn false
|
| 17 |
+
require config add_cross_attention false
|
| 18 |
+
|
| 19 |
+
# Every integer key of config.json is already a symbol (n_embd, n_head, ...).
|
| 20 |
+
# The graph runtime needs these names:
|
| 21 |
+
sym layers = n_layer
|
| 22 |
+
sym positions = n_positions
|
| 23 |
+
sym vocab = vocab_size
|
| 24 |
+
sym hidden = n_embd
|
| 25 |
+
sym nheads = n_head
|
| 26 |
+
sym headdim = hidden/nheads
|
| 27 |
+
sym mlp = 4*hidden
|
| 28 |
+
require sym hidden = nheads*headdim
|
| 29 |
+
buf token_id f32 1 input:token
|
| 30 |
+
buf position f32 1 input:position
|
| 31 |
+
buf x f32 n_embd
|
| 32 |
+
buf pos_embed f32 n_embd
|
| 33 |
+
buf norm f32 n_embd
|
| 34 |
+
buf qkv f32 3*n_embd
|
| 35 |
+
buf attn f32 n_embd
|
| 36 |
+
buf mix f32 n_embd
|
| 37 |
+
buf fc f32 mlp
|
| 38 |
+
buf activated f32 mlp
|
| 39 |
+
buf scores f32 n_head*n_positions
|
| 40 |
+
buf key_cache f32 n_positions*n_embd per_layer
|
| 41 |
+
buf value_cache f32 n_positions*n_embd per_layer
|
| 42 |
+
buf logits f32 vocab output:logits
|
| 43 |
+
weight wte f32 wte.weight tensor [vocab_size,n_embd]
|
| 44 |
+
weight wpe f32 wpe.weight tensor [n_positions,n_embd]
|
| 45 |
+
weight ln1w f32 h.{i}.ln_1.weight tensor [n_embd]
|
| 46 |
+
weight ln1b f32 h.{i}.ln_1.bias tensor [n_embd]
|
| 47 |
+
weight qkvw q4 h.{i}.attn.c_attn.weight tensor [n_embd,3*n_embd]
|
| 48 |
+
weight qkvb f32 h.{i}.attn.c_attn.bias tensor [3*n_embd]
|
| 49 |
+
weight attnw q4 h.{i}.attn.c_proj.weight tensor [n_embd,n_embd]
|
| 50 |
+
weight attnb f32 h.{i}.attn.c_proj.bias tensor [n_embd]
|
| 51 |
+
weight ln2w f32 h.{i}.ln_2.weight tensor [n_embd]
|
| 52 |
+
weight ln2b f32 h.{i}.ln_2.bias tensor [n_embd]
|
| 53 |
+
weight fcw q4 h.{i}.mlp.c_fc.weight tensor [n_embd,mlp]
|
| 54 |
+
weight fcb f32 h.{i}.mlp.c_fc.bias tensor [mlp]
|
| 55 |
+
weight projw q4 h.{i}.mlp.c_proj.weight tensor [mlp,n_embd]
|
| 56 |
+
weight projb f32 h.{i}.mlp.c_proj.bias tensor [n_embd]
|
| 57 |
+
weight lnfw f32 ln_f.weight tensor [n_embd]
|
| 58 |
+
weight lnfb f32 ln_f.bias tensor [n_embd]
|
| 59 |
+
# ---- Micro-kernels defined by this model --------------------------------------
|
| 60 |
+
# One line = one session_vm emit* call (mnemonic = emit name, lower case, no "emit").
|
| 61 |
+
# Registers r are 0..31; @inN / @outN / @buffer are element addresses in the arena.
|
| 62 |
+
# R0 holds the lane id on entry (rtou 0 0 copies it to U0).
|
| 63 |
+
|
| 64 |
+
kernel g2.add in=2 out=1 size=in0,in1,out0 threads=out0.size tg=1 tgbytes=16
|
| 65 |
+
rtou 0 0
|
| 66 |
+
uloadf32 1 0 @in0
|
| 67 |
+
uloadf32 2 0 @in1
|
| 68 |
+
add 1 1 2
|
| 69 |
+
ustoref32 1 0 @out0
|
| 70 |
+
endkernel
|
| 71 |
+
|
| 72 |
+
# gelu_new(x) = x * sigmoid(2*sqrt(2/pi) * (x + 0.044715*x^3))
|
| 73 |
+
kernel g2.gelu_new in=1 out=1 size=in0,out0 threads=out0.size tg=1 tgbytes=16
|
| 74 |
+
rtou 0 0
|
| 75 |
+
uloadf32 1 0 @in0
|
| 76 |
+
mul 2 1 1
|
| 77 |
+
mul 2 2 1
|
| 78 |
+
mulconst 2 2 0.044715
|
| 79 |
+
add 2 2 1
|
| 80 |
+
mulconst 2 2 2*sqrt(2/pi)
|
| 81 |
+
sigmoid 2 2
|
| 82 |
+
mul 1 1 2
|
| 83 |
+
ustoref32 1 0 @out0
|
| 84 |
+
endkernel
|
| 85 |
+
|
| 86 |
+
# LayerNorm over one row: mean (R1), variance (R3), then (x-mean)*rsqrt(var+eps)*gamma+beta.
|
| 87 |
+
kernel g2.layernorm in=3 out=1 size=in0,in1,in2,out0 threads=1 tg=1 tgbytes=16
|
| 88 |
+
loadconstf32 15 in0.size
|
| 89 |
+
uconst 0 0
|
| 90 |
+
loadconstf32 1 0
|
| 91 |
+
forbegin 15
|
| 92 |
+
uloadf32 2 0 @in0
|
| 93 |
+
add 1 1 2
|
| 94 |
+
uaddk 0 0 1
|
| 95 |
+
forend
|
| 96 |
+
mulconst 1 1 1/in0.size
|
| 97 |
+
uconst 0 0
|
| 98 |
+
loadconstf32 3 0
|
| 99 |
+
forbegin 15
|
| 100 |
+
uloadf32 2 0 @in0
|
| 101 |
+
sub 2 2 1
|
| 102 |
+
mul 2 2 2
|
| 103 |
+
add 3 3 2
|
| 104 |
+
uaddk 0 0 1
|
| 105 |
+
forend
|
| 106 |
+
mulconst 3 3 1/in0.size
|
| 107 |
+
addconst 3 3 eps
|
| 108 |
+
rsqrt 3 3
|
| 109 |
+
uconst 0 0
|
| 110 |
+
forbegin 15
|
| 111 |
+
uloadf32 2 0 @in0
|
| 112 |
+
uloadf32 4 0 @in1
|
| 113 |
+
uloadf32 5 0 @in2
|
| 114 |
+
sub 2 2 1
|
| 115 |
+
mul 2 2 3
|
| 116 |
+
mul 2 2 4
|
| 117 |
+
add 2 2 5
|
| 118 |
+
ustoref32 2 0 @out0
|
| 119 |
+
uaddk 0 0 1
|
| 120 |
+
forend
|
| 121 |
+
endkernel
|
| 122 |
+
|
| 123 |
+
# One lane per head: write this token's K/V into the cache, then causal softmax
|
| 124 |
+
# attention over positions 0..position (nothing after the current token is read).
|
| 125 |
+
# ins: qkv position key_cache value_cache scores; outs: attn key_cache value_cache scores.
|
| 126 |
+
kernel g2.attn_decode in=5 out=4 threads=nheads tg=1 tgbytes=16 expect=in0:3*hidden,in1:1,in2:positions*hidden,in3:positions*hidden,in4:nheads*positions,out0:hidden
|
| 127 |
+
rtou 0 0
|
| 128 |
+
umulk 1 0 headdim
|
| 129 |
+
umulk 2 0 positions
|
| 130 |
+
uconst 3 0
|
| 131 |
+
uloadf32 14 3 @in1
|
| 132 |
+
rtou 4 14
|
| 133 |
+
umulk 4 4 hidden
|
| 134 |
+
uadd 4 4 1
|
| 135 |
+
addconst 14 14 1
|
| 136 |
+
loadconstf32 15 headdim
|
| 137 |
+
uaddk 5 1 0
|
| 138 |
+
forbegin 15
|
| 139 |
+
uloadf32 1 5 @in0+hidden
|
| 140 |
+
uloadf32 2 5 @in0+2*hidden
|
| 141 |
+
ustoref32 1 4 @in2
|
| 142 |
+
ustoref32 2 4 @in3
|
| 143 |
+
uaddk 4 4 1
|
| 144 |
+
uaddk 5 5 1
|
| 145 |
+
forend
|
| 146 |
+
uaddk 4 1 0
|
| 147 |
+
uaddk 6 2 0
|
| 148 |
+
loadconstf32 10 -3e38
|
| 149 |
+
forbegin 14
|
| 150 |
+
uaddk 5 1 0
|
| 151 |
+
loadconstf32 3 0
|
| 152 |
+
forbegin 15
|
| 153 |
+
uloadf32 1 5 @in0
|
| 154 |
+
uloadf32 2 4 @in2
|
| 155 |
+
mul 2 1 2
|
| 156 |
+
add 3 3 2
|
| 157 |
+
uaddk 4 4 1
|
| 158 |
+
uaddk 5 5 1
|
| 159 |
+
forend
|
| 160 |
+
mulconst 3 3 1/sqrt(headdim)
|
| 161 |
+
ustoref32 3 6 @in4
|
| 162 |
+
cmplt 4 10 3
|
| 163 |
+
ifbegin 4
|
| 164 |
+
mulconst 10 3 1
|
| 165 |
+
ifend
|
| 166 |
+
uaddk 4 4 hidden-headdim
|
| 167 |
+
uaddk 6 6 1
|
| 168 |
+
forend
|
| 169 |
+
uaddk 6 2 0
|
| 170 |
+
loadconstf32 11 0
|
| 171 |
+
forbegin 14
|
| 172 |
+
uloadf32 3 6 @in4
|
| 173 |
+
sub 3 3 10
|
| 174 |
+
exp 3 3
|
| 175 |
+
ustoref32 3 6 @in4
|
| 176 |
+
add 11 11 3
|
| 177 |
+
uaddk 6 6 1
|
| 178 |
+
forend
|
| 179 |
+
uaddk 6 2 0
|
| 180 |
+
forbegin 14
|
| 181 |
+
uloadf32 3 6 @in4
|
| 182 |
+
div 3 3 11
|
| 183 |
+
ustoref32 3 6 @in4
|
| 184 |
+
uaddk 6 6 1
|
| 185 |
+
forend
|
| 186 |
+
uaddk 5 1 0
|
| 187 |
+
forbegin 15
|
| 188 |
+
uaddk 4 5 0
|
| 189 |
+
uaddk 6 2 0
|
| 190 |
+
loadconstf32 12 0
|
| 191 |
+
forbegin 14
|
| 192 |
+
uloadf32 1 6 @in4
|
| 193 |
+
uloadf32 2 4 @in3
|
| 194 |
+
mul 2 1 2
|
| 195 |
+
add 12 12 2
|
| 196 |
+
uaddk 4 4 hidden
|
| 197 |
+
uaddk 6 6 1
|
| 198 |
+
forend
|
| 199 |
+
ustoref32 12 5 @out0
|
| 200 |
+
uaddk 5 5 1
|
| 201 |
+
forend
|
| 202 |
+
endkernel
|
| 203 |
+
|
| 204 |
+
node token ext fir.embedding token_id wte -> x
|
| 205 |
+
node positional ext fir.embedding position wpe -> pos_embed
|
| 206 |
+
node embeddings micro g2.add x pos_embed -> x
|
| 207 |
+
repeat layers
|
| 208 |
+
node ln1 micro g2.layernorm x ln1w ln1b -> norm
|
| 209 |
+
node qkv_linear ext fir.linear norm qkvw -> qkv
|
| 210 |
+
node qkv_bias micro g2.add qkv qkvb -> qkv
|
| 211 |
+
node attention micro g2.attn_decode qkv position key_cache value_cache scores -> attn key_cache value_cache scores
|
| 212 |
+
node attention_linear ext fir.linear attn attnw -> mix
|
| 213 |
+
node attention_bias micro g2.add mix attnb -> mix
|
| 214 |
+
node attention_residual micro g2.add x mix -> x
|
| 215 |
+
node ln2 micro g2.layernorm x ln2w ln2b -> norm
|
| 216 |
+
node fc_linear ext fir.linear norm fcw -> fc
|
| 217 |
+
node fc_bias micro g2.add fc fcb -> fc
|
| 218 |
+
node gelu micro g2.gelu_new fc -> activated
|
| 219 |
+
node proj_linear ext fir.linear activated projw -> mix
|
| 220 |
+
node proj_bias micro g2.add mix projb -> mix
|
| 221 |
+
node mlp_residual micro g2.add x mix -> x
|
| 222 |
+
endrepeat
|
| 223 |
+
node final_norm micro g2.layernorm x lnfw lnfb -> norm
|
| 224 |
+
node head ext fir.linear_t norm wte -> logits
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:248dfc3911869ec493c76e65bf2fcf7f615828b0254c12b473182f0f81d3a707
|
| 3 |
+
size 548105171
|
probe.bybylang
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Offline diagnostic protocol for check_hf.py. Requests/responses stay on
|
| 2 |
+
# stdin/stdout; no checkpoint conversion, downloads or log files are created.
|
| 3 |
+
import nim "std/[os, json, times, tables]"
|
| 4 |
+
import nim "backend"
|
| 5 |
+
import "../../other/formers.n/src/formers/ir/fir_parse.bybylang"
|
| 6 |
+
import "../../other/formers.n/src/formers/ir/fir_graph.bybylang"
|
| 7 |
+
import "../../other/formers.n/src/formers/runtime/console.bybylang"
|
| 8 |
+
|
| 9 |
+
function probeTop(logits: seq[float32]): int
|
| 10 |
+
for i in 1 ..< logits.len:
|
| 11 |
+
if logits[i] > logits[result]:
|
| 12 |
+
result = i
|
| 13 |
+
|
| 14 |
+
function probe(model: var FirGraph, request: JsonNode): JsonNode
|
| 15 |
+
var prompt: seq[int]
|
| 16 |
+
var teacher: seq[int]
|
| 17 |
+
for id in request["prompt"]:
|
| 18 |
+
prompt.add(id.getInt())
|
| 19 |
+
for id in request["teacher"]:
|
| 20 |
+
teacher.add(id.getInt())
|
| 21 |
+
let count = request["count"].getInt()
|
| 22 |
+
if prompt.len == 0 or count < 1 or teacher.len < 1:
|
| 23 |
+
raise newException(ValueError, "probe needs prompt, teacher continuation and positive count")
|
| 24 |
+
firGraphReset(model)
|
| 25 |
+
let sessionStart = model.sessions
|
| 26 |
+
let readStart = model.logitsReads
|
| 27 |
+
var logits: seq[float32]
|
| 28 |
+
let prefillStart = epochTime()
|
| 29 |
+
for id in prompt:
|
| 30 |
+
logits = firGraphStep(model, id)
|
| 31 |
+
let prefillSeconds = epochTime()-prefillStart
|
| 32 |
+
var generated: seq[int]
|
| 33 |
+
var decodeSeconds = 0.0
|
| 34 |
+
var samples = newJArray()
|
| 35 |
+
# Greedy timing uses count-1 actual forward steps after the prompt.
|
| 36 |
+
for i in 0 ..< count:
|
| 37 |
+
let id = probeTop(logits)
|
| 38 |
+
generated.add(id)
|
| 39 |
+
if i+1 < count:
|
| 40 |
+
let start = epochTime()
|
| 41 |
+
logits = firGraphStep(model, id)
|
| 42 |
+
decodeSeconds += epochTime()-start
|
| 43 |
+
let greedySessions = model.sessions-sessionStart
|
| 44 |
+
let greedyReads = model.logitsReads-readStart
|
| 45 |
+
firGraphReset(model)
|
| 46 |
+
for id in prompt:
|
| 47 |
+
logits = firGraphStep(model, id)
|
| 48 |
+
# Every precision/backend sees identical HF prefixes when comparing logits.
|
| 49 |
+
for i, id in teacher:
|
| 50 |
+
samples.add(%logits)
|
| 51 |
+
if i+1 < teacher.len:
|
| 52 |
+
logits = firGraphStep(model, id)
|
| 53 |
+
result = %*{"generated": generated, "logits": samples, "prefill_tokens": prompt.len, "prefill_seconds": prefillSeconds, "decode_steps": count-1, "decode_seconds": decodeSeconds, "sessions": greedySessions, "logits_reads": greedyReads}
|
| 54 |
+
|
| 55 |
+
fmConsoleInit(false)
|
| 56 |
+
try:
|
| 57 |
+
let args = commandLineParams()
|
| 58 |
+
if args.len != 3 or args[2] notin ["q4", "fp32"]:
|
| 59 |
+
raise newException(ValueError, "usage: fir_probe MODEL_DIR cpu|metal|vulkan q4|fp32")
|
| 60 |
+
var graph = firParse(args[0] / "model.fir")
|
| 61 |
+
if args[2] == "fp32":
|
| 62 |
+
graph = firF32Weights(graph)
|
| 63 |
+
backend.setForbidCpuFallback(true)
|
| 64 |
+
var model = firLoadGraph(graph, args[0] / "model.safetensors", newBackend(args[1]))
|
| 65 |
+
defer: firFreeGraph(model)
|
| 66 |
+
var line: string
|
| 67 |
+
while stdin.readLine(line):
|
| 68 |
+
fmOut().writeLine($probe(model, parseJson(line)))
|
| 69 |
+
fmOut().flushFile()
|
| 70 |
+
except Exception as e:
|
| 71 |
+
fmSay("GPT-2 probe failed: " & e.msg)
|
| 72 |
+
quit(1)
|
test_model.bybylang
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Independent float references; runGrid tests never use the production CPU VM.
|
| 2 |
+
import nim "std/[os, tables, json, math, random, strutils]"
|
| 3 |
+
import nim "vm_interp"
|
| 4 |
+
import nim "backend"
|
| 5 |
+
import nim "quant"
|
| 6 |
+
import "../../other/formers.n/src/formers/ir/fir_parse.bybylang"
|
| 7 |
+
import "../../other/formers.n/src/formers/ir/fir_exec.bybylang"
|
| 8 |
+
import "../../other/formers.n/src/formers/ir/fir_graph.bybylang"
|
| 9 |
+
import "../../other/formers.n/src/formers/ir/fir_graph_kernels.bybylang"
|
| 10 |
+
import "../../other/formers.n/src/formers/io/safetensors.bybylang"
|
| 11 |
+
import "../../other/formers.n/src/formers/arch/detect.bybylang"
|
| 12 |
+
|
| 13 |
+
function fgClose(actual, expected: openArray[float32], label: string)
|
| 14 |
+
doAssert actual.len == expected.len, label & " length"
|
| 15 |
+
for i in 0 ..< actual.len:
|
| 16 |
+
if classify(actual[i]) in {fcNan, fcInf, fcNegInf} or abs(actual[i]-expected[i]) > 1e-4'f32:
|
| 17 |
+
raise newException(ValueError, label & " index=" & $i & ": " & $actual[i] & " != " & $expected[i])
|
| 18 |
+
|
| 19 |
+
function fgRandom(rng: var Rand, count: int, scale: float32 = 0.3'f32): seq[float32]
|
| 20 |
+
result = newSeq[float32](count)
|
| 21 |
+
for value in result.mitems:
|
| 22 |
+
value = (rng.rand(2.0'f32)-1)*scale
|
| 23 |
+
|
| 24 |
+
function refNorm(x, gamma, beta: seq[float32], eps: float32): seq[float32]
|
| 25 |
+
var mean = 0'f32
|
| 26 |
+
for value in x:
|
| 27 |
+
mean += value
|
| 28 |
+
mean /= float32(x.len)
|
| 29 |
+
var variance = 0'f32
|
| 30 |
+
for value in x:
|
| 31 |
+
variance += (value-mean)*(value-mean)
|
| 32 |
+
let inverse = 1'f32/sqrt(variance/float32(x.len)+eps)
|
| 33 |
+
for i, value in x:
|
| 34 |
+
result.add((value-mean)*inverse*gamma[i]+beta[i])
|
| 35 |
+
|
| 36 |
+
function refAdd(a, b: seq[float32]): seq[float32]
|
| 37 |
+
for i in 0 ..< a.len:
|
| 38 |
+
result.add(a[i]+b[i])
|
| 39 |
+
|
| 40 |
+
function refGelu(x: seq[float32]): seq[float32]
|
| 41 |
+
# Independent tanh form of gelu_new (equivalent to the sigmoid builder).
|
| 42 |
+
for value in x:
|
| 43 |
+
result.add(0.5'f32*value*(1'f32+tanh(sqrt(2'f32/PI.float32)*(value+0.044715'f32*value*value*value))))
|
| 44 |
+
|
| 45 |
+
function refLinear(x, w, bias: seq[float32]): seq[float32]
|
| 46 |
+
result = bias
|
| 47 |
+
for j in 0 ..< bias.len:
|
| 48 |
+
for i in 0 ..< x.len:
|
| 49 |
+
result[j] += x[i]*w[i*bias.len+j]
|
| 50 |
+
|
| 51 |
+
function refAttention(qkv: seq[float32], keys, values: var seq[float32], position, hidden, heads: int): seq[float32]
|
| 52 |
+
for i in 0 ..< hidden:
|
| 53 |
+
keys[position*hidden+i] = qkv[hidden+i]
|
| 54 |
+
values[position*hidden+i] = qkv[2*hidden+i]
|
| 55 |
+
let width = hidden div heads
|
| 56 |
+
result = newSeq[float32](hidden)
|
| 57 |
+
for head in 0 ..< heads:
|
| 58 |
+
var scores = newSeq[float32](position+1)
|
| 59 |
+
for t in 0 .. position:
|
| 60 |
+
for d in 0 ..< width:
|
| 61 |
+
scores[t] += qkv[head*width+d]*keys[t*hidden+head*width+d]
|
| 62 |
+
scores[t] /= sqrt(float32(width))
|
| 63 |
+
var peak = scores[0]
|
| 64 |
+
for score in scores:
|
| 65 |
+
peak = max(peak, score)
|
| 66 |
+
var total = 0'f32
|
| 67 |
+
for score in scores.mitems:
|
| 68 |
+
score = exp(score-peak)
|
| 69 |
+
total += score
|
| 70 |
+
for t in 0 .. position:
|
| 71 |
+
for d in 0 ..< width:
|
| 72 |
+
result[head*width+d] += scores[t]/total*values[t*hidden+head*width+d]
|
| 73 |
+
|
| 74 |
+
function checkMicro(graph: FirProgram)
|
| 75 |
+
let registry = firDefaultRegistry()
|
| 76 |
+
let bindings = firGraphBindings(graph)
|
| 77 |
+
firValidate(graph, registry, bindings)
|
| 78 |
+
var rng = initRand(7293)
|
| 79 |
+
for node in graph.nodes:
|
| 80 |
+
if node.kind != "micro":
|
| 81 |
+
continue
|
| 82 |
+
let ins = node.inputs.splitWhitespace()
|
| 83 |
+
let output = node.outputs.splitWhitespace()[0]
|
| 84 |
+
var memory = fgRandom(rng, bindings.memoryFloats, 4'f32)
|
| 85 |
+
var expected: seq[float32]
|
| 86 |
+
if node.op == "g2.attn_decode":
|
| 87 |
+
var keys = fgRandom(rng, graph.buffers["key_cache"].elements)
|
| 88 |
+
var values = fgRandom(rng, keys.len)
|
| 89 |
+
for position in 0 ..< graph.symbols["positions"]:
|
| 90 |
+
let qkv = fgRandom(rng, graph.buffers["qkv"].elements, 3'f32)
|
| 91 |
+
for i, value in qkv:
|
| 92 |
+
memory[bindings.memory["qkv"]+i] = value
|
| 93 |
+
memory[bindings.memory["position"]] = float32(position)
|
| 94 |
+
# Future cache entries are poison; causal decode must not read them.
|
| 95 |
+
for i in position*graph.symbols["hidden"] ..< keys.len:
|
| 96 |
+
memory[bindings.memory["key_cache"]+i] = 999'f32
|
| 97 |
+
memory[bindings.memory["value_cache"]+i] = -999'f32
|
| 98 |
+
expected = refAttention(qkv, keys, values, position, graph.symbols["hidden"], graph.symbols["nheads"])
|
| 99 |
+
let kernel = firMicroKernel(node, graph, registry, bindings)
|
| 100 |
+
runGrid(kernel.program, memory, kernel.threads, kernel.tgSize)
|
| 101 |
+
let offset = bindings.memory["attn"]
|
| 102 |
+
fgClose(memory[offset ..< offset+expected.len], expected, "attention")
|
| 103 |
+
let count = (position+1)*graph.symbols["hidden"]
|
| 104 |
+
for cache in ["key_cache", "value_cache"]:
|
| 105 |
+
let base = bindings.memory[cache]
|
| 106 |
+
let reference = if cache == "key_cache": keys else: values
|
| 107 |
+
fgClose(memory[base ..< base+count], reference[0 ..< count], cache)
|
| 108 |
+
for head in 0 ..< graph.symbols["nheads"]:
|
| 109 |
+
var total = 0'f32
|
| 110 |
+
for t in 0 .. position:
|
| 111 |
+
total += memory[bindings.memory["scores"]+head*graph.symbols["positions"]+t]
|
| 112 |
+
fgClose(@[total], @[1'f32], "softmax sum")
|
| 113 |
+
continue
|
| 114 |
+
let xoff = bindings.memory[ins[0]]
|
| 115 |
+
let count = graph.buffers[ins[0]].elements
|
| 116 |
+
let x = memory[xoff ..< xoff+count]
|
| 117 |
+
if node.op == "g2.layernorm":
|
| 118 |
+
let goff = bindings.memory[ins[1]]
|
| 119 |
+
let boff = bindings.memory[ins[2]]
|
| 120 |
+
expected = refNorm(x, memory[goff ..< goff+count], memory[boff ..< boff+count], graph.epsilon)
|
| 121 |
+
elif node.op == "g2.gelu_new":
|
| 122 |
+
expected = refGelu(x)
|
| 123 |
+
else:
|
| 124 |
+
let boff = bindings.memory[ins[1]]
|
| 125 |
+
expected = refAdd(x, memory[boff ..< boff+count])
|
| 126 |
+
let kernel = firMicroKernel(node, graph, registry, bindings)
|
| 127 |
+
runGrid(kernel.program, memory, kernel.threads, kernel.tgSize)
|
| 128 |
+
let offset = bindings.memory[output]
|
| 129 |
+
fgClose(memory[offset ..< offset+expected.len], expected, node.name)
|
| 130 |
+
echo "PASS GPT-2 all micro nodes through runGrid: layernorm, gelu_new, bias/residual, causal attention/softmax and KV (tol 1e-4)"
|
| 131 |
+
|
| 132 |
+
function refForward(graph: FirProgram, weights: Table[string, seq[float32]], tokens: seq[int]): seq[float32]
|
| 133 |
+
let hidden = graph.symbols["hidden"]
|
| 134 |
+
let capacity = graph.symbols["positions"]
|
| 135 |
+
let heads = graph.symbols["nheads"]
|
| 136 |
+
var keys = newSeq[seq[float32]](graph.symbols["layers"])
|
| 137 |
+
var values = newSeq[seq[float32]](keys.len)
|
| 138 |
+
for i in 0 ..< keys.len:
|
| 139 |
+
keys[i] = newSeq[float32](capacity*hidden)
|
| 140 |
+
values[i] = newSeq[float32](capacity*hidden)
|
| 141 |
+
for position, token in tokens:
|
| 142 |
+
let wte = weights["wte.weight"]
|
| 143 |
+
let wpe = weights["wpe.weight"]
|
| 144 |
+
var x = refAdd(wte[token*hidden ..< (token+1)*hidden], wpe[position*hidden ..< (position+1)*hidden])
|
| 145 |
+
for layer in 0 ..< keys.len:
|
| 146 |
+
let p = "h." & $layer & "."
|
| 147 |
+
let norm1 = refNorm(x, weights[p & "ln_1.weight"], weights[p & "ln_1.bias"], graph.epsilon)
|
| 148 |
+
let qkv = refLinear(norm1, weights[p & "attn.c_attn.weight"], weights[p & "attn.c_attn.bias"])
|
| 149 |
+
let attn = refAttention(qkv, keys[layer], values[layer], position, hidden, heads)
|
| 150 |
+
x = refAdd(x, refLinear(attn, weights[p & "attn.c_proj.weight"], weights[p & "attn.c_proj.bias"]))
|
| 151 |
+
let norm2 = refNorm(x, weights[p & "ln_2.weight"], weights[p & "ln_2.bias"], graph.epsilon)
|
| 152 |
+
let fc = refLinear(norm2, weights[p & "mlp.c_fc.weight"], weights[p & "mlp.c_fc.bias"])
|
| 153 |
+
x = refAdd(x, refLinear(refGelu(fc), weights[p & "mlp.c_proj.weight"], weights[p & "mlp.c_proj.bias"]))
|
| 154 |
+
x = refNorm(x, weights["ln_f.weight"], weights["ln_f.bias"], graph.epsilon)
|
| 155 |
+
result = newSeq[float32](graph.symbols["vocab"])
|
| 156 |
+
for token in 0 ..< result.len:
|
| 157 |
+
for i in 0 ..< hidden:
|
| 158 |
+
result[token] += x[i]*wte[token*hidden+i]
|
| 159 |
+
|
| 160 |
+
function writeSafe(path: string, weights: Table[string, seq[float32]], shapes: Table[string, seq[int]])
|
| 161 |
+
var header = newJObject()
|
| 162 |
+
var offset = 0
|
| 163 |
+
var names: seq[string]
|
| 164 |
+
for name, data in weights:
|
| 165 |
+
names.add(name)
|
| 166 |
+
header[name] = %*{"dtype": "F32", "shape": shapes[name], "data_offsets": [offset, offset+data.len*4]}
|
| 167 |
+
offset += data.len*4
|
| 168 |
+
var text = $header
|
| 169 |
+
while text.len mod 8 != 0:
|
| 170 |
+
text.add(' ')
|
| 171 |
+
var f = open(path, fmWrite)
|
| 172 |
+
defer: f.close()
|
| 173 |
+
var length = uint64(text.len)
|
| 174 |
+
discard f.writeBuffer(addr length, 8)
|
| 175 |
+
f.write(text)
|
| 176 |
+
for name in names:
|
| 177 |
+
let data = weights[name]
|
| 178 |
+
discard f.writeBuffer(unsafeAddr data[0], data.len*4)
|
| 179 |
+
|
| 180 |
+
function checkFull(graph: FirProgram, root: string)
|
| 181 |
+
var weights = initTable[string, seq[float32]]()
|
| 182 |
+
var shapes = initTable[string, seq[int]]()
|
| 183 |
+
var rng = initRand(8343)
|
| 184 |
+
for name, buffer in graph.buffers:
|
| 185 |
+
if buffer.kind != "weight":
|
| 186 |
+
continue
|
| 187 |
+
for layer in 0 ..< (if buffer.tensorName.contains("{i}"): graph.symbols["layers"] else: 1):
|
| 188 |
+
let tensor = buffer.tensorName.replace("{i}", $layer)
|
| 189 |
+
weights[tensor] = fgRandom(rng, buffer.elements)
|
| 190 |
+
shapes[tensor] = buffer.dims
|
| 191 |
+
let safePath = root / "model.safetensors"
|
| 192 |
+
writeSafe(safePath, weights, shapes)
|
| 193 |
+
var model = firLoadGraph(firF32Weights(graph), safePath, newBackend("cpu"))
|
| 194 |
+
defer: firFreeGraph(model)
|
| 195 |
+
var tokens: seq[int]
|
| 196 |
+
for i in 0 ..< graph.symbols["positions"]:
|
| 197 |
+
let token = rng.rand(graph.symbols["vocab"]-1)
|
| 198 |
+
tokens.add(token)
|
| 199 |
+
let actual = firGraphStep(model, token)
|
| 200 |
+
let expected = refForward(graph, weights, tokens)
|
| 201 |
+
fgClose(actual, expected, "full graph at position " & $i)
|
| 202 |
+
doAssert model.dispatched > 0
|
| 203 |
+
doAssert model.sessions == tokens.len and model.logitsReads == tokens.len
|
| 204 |
+
firGraphReset(model)
|
| 205 |
+
fgClose(firGraphStep(model, tokens[0]), refForward(graph, weights, @[tokens[0]]), "fp32 reset")
|
| 206 |
+
# Independently dequantize the framework's packed Q4, transpose back to HF
|
| 207 |
+
# layout and compare the whole resident graph with scalar float formulas.
|
| 208 |
+
var rounded = weights
|
| 209 |
+
for name, buffer in graph.buffers:
|
| 210 |
+
if buffer.dtype != "q4":
|
| 211 |
+
continue
|
| 212 |
+
let k = buffer.dims[0]
|
| 213 |
+
let n = buffer.dims[1]
|
| 214 |
+
for layer in 0 ..< graph.symbols["layers"]:
|
| 215 |
+
let tensor = buffer.tensorName.replace("{i}", $layer)
|
| 216 |
+
var transposed = newSeq[float32](buffer.elements)
|
| 217 |
+
for j in 0 ..< n:
|
| 218 |
+
for i in 0 ..< k:
|
| 219 |
+
transposed[j*k+i] = weights[tensor][i*n+j]
|
| 220 |
+
let packed = quantizeInt4AsymmetricGrouped(transposed, @[n, k])
|
| 221 |
+
doAssert packed.kind == qkInt4Asymmetric and packed.groupSize == 32
|
| 222 |
+
let restored = dequantizeTensor(packed)
|
| 223 |
+
var hf = newSeq[float32](buffer.elements)
|
| 224 |
+
for j in 0 ..< n:
|
| 225 |
+
for i in 0 ..< k:
|
| 226 |
+
hf[i*n+j] = restored[j*k+i]
|
| 227 |
+
rounded[tensor] = hf
|
| 228 |
+
var resident = firNewGraph(graph, weights, newBackend("cpu"), firDefaultRegistry())
|
| 229 |
+
defer: firFreeGraph(resident)
|
| 230 |
+
doAssert resident.q4.len == 4*graph.symbols["layers"]
|
| 231 |
+
doAssert resident.fp32.len == 2, "tied head must reuse wte"
|
| 232 |
+
var prefix: seq[int]
|
| 233 |
+
for token in tokens:
|
| 234 |
+
prefix.add(token)
|
| 235 |
+
fgClose(firGraphStep(resident, token), refForward(graph, rounded, prefix), "Q4 resident graph")
|
| 236 |
+
doAssert resident.sessions == tokens.len and resident.logitsReads == tokens.len
|
| 237 |
+
firGraphReset(resident)
|
| 238 |
+
fgClose(firGraphStep(resident, tokens[0]), refForward(graph, rounded, @[tokens[0]]), "Q4 reset")
|
| 239 |
+
echo "PASS resident Q4 full graph vs independently dequantized scalar reference; transpose, tied head, one session/read per token, reset (tol 1e-4)"
|
| 240 |
+
for i in 1 ..< tokens.len:
|
| 241 |
+
discard firGraphStep(model, tokens[i])
|
| 242 |
+
var rejected = false
|
| 243 |
+
try:
|
| 244 |
+
discard firGraphStep(model, 0)
|
| 245 |
+
except ValueError:
|
| 246 |
+
rejected = true
|
| 247 |
+
doAssert rejected, "context overflow accepted"
|
| 248 |
+
# Header-only routing, then malformed shape and truncated payload rejection.
|
| 249 |
+
writeFile(root / "model.fir", readFile(graph.sourcePath))
|
| 250 |
+
writeFile(root / "tokenizer.json", "{}")
|
| 251 |
+
var opts = fmDefaultOptions()
|
| 252 |
+
opts.modelsDir = root
|
| 253 |
+
opts.backend = "cpu"
|
| 254 |
+
let detected = fmDetect(opts)
|
| 255 |
+
doAssert detected.supported and detected.route == frFir, detected.errors.join("; ")
|
| 256 |
+
let header = fmReadSafeHeader(safePath)
|
| 257 |
+
rejected = false
|
| 258 |
+
try:
|
| 259 |
+
discard fmLoadSafeF32(safePath, header, "wte.weight", @[1, 1])
|
| 260 |
+
except ValueError:
|
| 261 |
+
rejected = true
|
| 262 |
+
doAssert rejected, "wrong safetensors shape accepted"
|
| 263 |
+
let valid = readFile(safePath)
|
| 264 |
+
writeFile(safePath, valid[0 ..< valid.len-4])
|
| 265 |
+
rejected = false
|
| 266 |
+
try:
|
| 267 |
+
discard fmReadSafeHeader(safePath)
|
| 268 |
+
except ValueError:
|
| 269 |
+
rejected = true
|
| 270 |
+
doAssert rejected, "truncated safetensors accepted"
|
| 271 |
+
echo "PASS GPT-2 tiny full graph through production CPU VM/backend vs independent reference, all positions (tol 1e-4); safetensors, detection, context guards"
|
| 272 |
+
|
| 273 |
+
function checkQuant()
|
| 274 |
+
var rng = initRand(425)
|
| 275 |
+
let rows = 3
|
| 276 |
+
let cols = 35 # Odd row width and a partial second group.
|
| 277 |
+
var input = fgRandom(rng, rows*cols, 5'f32)
|
| 278 |
+
for c in 0 ..< cols:
|
| 279 |
+
input[c] = 2.5'f32 # Constant groups must retain their nonzero value.
|
| 280 |
+
let packed = quantizeInt4AsymmetricGrouped(input, @[rows, cols])
|
| 281 |
+
doAssert packed.data.len == rows*((cols+1) div 2)
|
| 282 |
+
doAssert packed.scale.len == rows*2 and packed.zero_point.len == rows*2
|
| 283 |
+
let restored = dequantizeTensor(packed)
|
| 284 |
+
for r in 0 ..< rows:
|
| 285 |
+
for c in 0 ..< cols:
|
| 286 |
+
let sc = packed.scale[r*2+c div 32]
|
| 287 |
+
doAssert abs(restored[r*cols+c]-input[r*cols+c]) <= sc*0.501'f32+1e-6'f32
|
| 288 |
+
fgClose(restored[0 ..< cols], input[0 ..< cols], "constant Q4 groups")
|
| 289 |
+
let ctx = newBackend("cpu")
|
| 290 |
+
var w = beResidentUploadQ4(ctx, packed.data, packed.scale, packed.zero_point, cols, rows, 32, 2)
|
| 291 |
+
defer: beResidentFreeQ4(w)
|
| 292 |
+
let x = fgRandom(rng, cols)
|
| 293 |
+
var expected = newSeq[float32](rows)
|
| 294 |
+
for r in 0 ..< rows:
|
| 295 |
+
for c in 0 ..< cols:
|
| 296 |
+
expected[r] += x[c]*restored[r*cols+c]
|
| 297 |
+
fgClose(beResidentLinearQ4(ctx, x, w, 1), expected, "odd grouped resident GEMV")
|
| 298 |
+
echo "PASS grouped asymmetric Q4: odd row padding, partial groups, nonzero constants and resident GEMV (tol 1e-4)"
|
| 299 |
+
|
| 300 |
+
function checkBadKernels(root: string)
|
| 301 |
+
# Kernel blocks in a model file must fail loudly: no silent wrong programs.
|
| 302 |
+
let source = readFile("models/gpt2-125m/model.fir")
|
| 303 |
+
var cases: seq[(string, string, string)]
|
| 304 |
+
cases.add(("unknown mnemonic", " mulconst 1 1 1/in0.size", " bogus 1 1"))
|
| 305 |
+
cases.add(("register out of range", " add 1 1 2\n ustoref32 1 0 @out0", " add 1 1 40\n ustoref32 1 0 @out0"))
|
| 306 |
+
cases.add(("unclosed loop", " forend\n mulconst 1 1 1/in0.size", " mulconst 1 1 1/in0.size"))
|
| 307 |
+
cases.add(("unknown name", "mulconst 2 2 0.044715", "mulconst 2 2 not_a_symbol"))
|
| 308 |
+
cases.add(("wrong buffer size", "in1:1,", "in1:2,"))
|
| 309 |
+
cases.add(("wrong arity", "kernel g2.add in=2 out=1", "kernel g2.add in=3 out=1"))
|
| 310 |
+
cases.add(("wrong argument count", " mul 2 1 1\n mul 2 2 1", " mul 2 1\n mul 2 2 1"))
|
| 311 |
+
for (label, find, replacement) in cases:
|
| 312 |
+
if not source.contains(find):
|
| 313 |
+
raise newException(ValueError, "bad-kernel fixture does not match model.fir: " & label)
|
| 314 |
+
let bad = root / "bad.fir"
|
| 315 |
+
writeFile(bad, source.replace(find, replacement))
|
| 316 |
+
var rejected = false
|
| 317 |
+
try:
|
| 318 |
+
let graph = firParse(bad)
|
| 319 |
+
firValidate(graph, firDefaultRegistry(), firGraphBindings(graph))
|
| 320 |
+
except ValueError:
|
| 321 |
+
rejected = true
|
| 322 |
+
if not rejected:
|
| 323 |
+
raise newException(ValueError, "bad kernel accepted: " & label)
|
| 324 |
+
echo "PASS FIR kernel blocks reject unknown mnemonics, bad registers, unbalanced loops, unknown names, wrong sizes and arities"
|
| 325 |
+
|
| 326 |
+
checkQuant()
|
| 327 |
+
let root = getTempDir() / ("fir_graph_" & $getCurrentProcessId())
|
| 328 |
+
createDir(root)
|
| 329 |
+
try:
|
| 330 |
+
let path = root / "config.json"
|
| 331 |
+
for (hidden, heads) in [(8, 2), (15, 3)]:
|
| 332 |
+
let cfg = %*{"model_type": "gpt2", "n_embd": hidden, "n_head": heads, "n_layer": 2, "n_positions": 5, "vocab_size": 19, "layer_norm_epsilon": 0.0003, "activation_function": "gelu_new"}
|
| 333 |
+
writeFile(path, $cfg)
|
| 334 |
+
let graph = firParse("models/gpt2-125m/model.fir", path)
|
| 335 |
+
checkMicro(graph)
|
| 336 |
+
checkFull(graph, root)
|
| 337 |
+
let large = firParse("models/gpt2-125m/model.fir")
|
| 338 |
+
firValidate(large, firDefaultRegistry(), firGraphBindings(large))
|
| 339 |
+
echo "PASS GPT-2 real config FIR validation, every micro program built without weights"
|
| 340 |
+
checkBadKernels(root)
|
| 341 |
+
finally:
|
| 342 |
+
removeDir(root)
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|